_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 |
|---|---|---|---|---|---|---|---|---|
0983edd35977b73f9741bcba5d65f97624be1eb67ff3910059ef24a70350e2fe | sdiehl/elliptic-curve | BrainpoolP256T1.hs | module Data.Curve.Weierstrass.BrainpoolP256T1
( module Data.Curve.Weierstrass
, Point(..)
* BrainpoolP256T1 curve
, module Data.Curve.Weierstrass.BrainpoolP256T1
) where
import Protolude
import Data.Field.Galois
import GHC.Natural (Natural)
import Data.Curve.Weierstrass
-------------------------------------------------------------------------------
-- Types
-------------------------------------------------------------------------------
| BrainpoolP256T1 curve .
data BrainpoolP256T1
| Field of points of BrainpoolP256T1 curve .
type Fq = Prime Q
type Q = 0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377
| Field of coefficients of BrainpoolP256T1 curve .
type Fr = Prime R
type R = 0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7
BrainpoolP256T1 curve is a Weierstrass curve .
instance Curve 'Weierstrass c BrainpoolP256T1 Fq Fr => WCurve c BrainpoolP256T1 Fq Fr where
a_ = const _a
{-# INLINABLE a_ #-}
b_ = const _b
# INLINABLE b _ #
h_ = const _h
{-# INLINABLE h_ #-}
q_ = const _q
# INLINABLE q _ #
r_ = const _r
# INLINABLE r _ #
| Affine BrainpoolP256T1 curve point .
type PA = WAPoint BrainpoolP256T1 Fq Fr
Affine BrainpoolP256T1 curve is a Weierstrass affine curve .
instance WACurve BrainpoolP256T1 Fq Fr where
gA_ = gA
# INLINABLE gA _ #
| Jacobian BrainpoolP256T1 point .
type PJ = WJPoint BrainpoolP256T1 Fq Fr
Jacobian BrainpoolP256T1 curve is a Weierstrass Jacobian curve .
instance WJCurve BrainpoolP256T1 Fq Fr where
gJ_ = gJ
# INLINABLE gJ _ #
-- | Projective BrainpoolP256T1 point.
type PP = WPPoint BrainpoolP256T1 Fq Fr
Projective BrainpoolP256T1 curve is a Weierstrass projective curve .
instance WPCurve BrainpoolP256T1 Fq Fr where
gP_ = gP
# INLINABLE gP _ #
-------------------------------------------------------------------------------
-- Parameters
-------------------------------------------------------------------------------
| Coefficient @A@ of BrainpoolP256T1 curve .
_a :: Fq
_a = 0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5374
# INLINABLE _ a #
| Coefficient @B@ of BrainpoolP256T1 curve .
_b :: Fq
_b = 0x662c61c430d84ea4fe66a7733d0b76b7bf93ebc4af2f49256ae58101fee92b04
{-# INLINABLE _b #-}
| Cofactor of BrainpoolP256T1 curve .
_h :: Natural
_h = 0x1
# INLINABLE _ h #
| Characteristic of BrainpoolP256T1 curve .
_q :: Natural
_q = 0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377
{-# INLINABLE _q #-}
| Order of BrainpoolP256T1 curve .
_r :: Natural
_r = 0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7
{-# INLINABLE _r #-}
| Coordinate @X@ of BrainpoolP256T1 curve .
_x :: Fq
_x = 0xa3e8eb3cc1cfe7b7732213b23a656149afa142c47aafbc2b79a191562e1305f4
{-# INLINABLE _x #-}
| Coordinate @Y@ of BrainpoolP256T1 curve .
_y :: Fq
_y = 0x2d996c823439c56d7f7b22e14644417e69bcb6de39d027001dabe8f35b25c9be
{-# INLINABLE _y #-}
| Generator of affine BrainpoolP256T1 curve .
gA :: PA
gA = A _x _y
# INLINABLE gA #
| Generator of Jacobian BrainpoolP256T1 curve .
gJ :: PJ
gJ = J _x _y 1
# INLINABLE gJ #
| Generator of projective BrainpoolP256T1 curve .
gP :: PP
gP = P _x _y 1
# INLINABLE gP #
| null | https://raw.githubusercontent.com/sdiehl/elliptic-curve/445e196a550e36e0f25bd4d9d6a38676b4cf2be8/src/Data/Curve/Weierstrass/BrainpoolP256T1.hs | haskell | -----------------------------------------------------------------------------
Types
-----------------------------------------------------------------------------
# INLINABLE a_ #
# INLINABLE h_ #
| Projective BrainpoolP256T1 point.
-----------------------------------------------------------------------------
Parameters
-----------------------------------------------------------------------------
# INLINABLE _b #
# INLINABLE _q #
# INLINABLE _r #
# INLINABLE _x #
# INLINABLE _y # | module Data.Curve.Weierstrass.BrainpoolP256T1
( module Data.Curve.Weierstrass
, Point(..)
* BrainpoolP256T1 curve
, module Data.Curve.Weierstrass.BrainpoolP256T1
) where
import Protolude
import Data.Field.Galois
import GHC.Natural (Natural)
import Data.Curve.Weierstrass
| BrainpoolP256T1 curve .
data BrainpoolP256T1
| Field of points of BrainpoolP256T1 curve .
type Fq = Prime Q
type Q = 0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377
| Field of coefficients of BrainpoolP256T1 curve .
type Fr = Prime R
type R = 0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7
BrainpoolP256T1 curve is a Weierstrass curve .
instance Curve 'Weierstrass c BrainpoolP256T1 Fq Fr => WCurve c BrainpoolP256T1 Fq Fr where
a_ = const _a
b_ = const _b
# INLINABLE b _ #
h_ = const _h
q_ = const _q
# INLINABLE q _ #
r_ = const _r
# INLINABLE r _ #
| Affine BrainpoolP256T1 curve point .
type PA = WAPoint BrainpoolP256T1 Fq Fr
Affine BrainpoolP256T1 curve is a Weierstrass affine curve .
instance WACurve BrainpoolP256T1 Fq Fr where
gA_ = gA
# INLINABLE gA _ #
| Jacobian BrainpoolP256T1 point .
type PJ = WJPoint BrainpoolP256T1 Fq Fr
Jacobian BrainpoolP256T1 curve is a Weierstrass Jacobian curve .
instance WJCurve BrainpoolP256T1 Fq Fr where
gJ_ = gJ
# INLINABLE gJ _ #
type PP = WPPoint BrainpoolP256T1 Fq Fr
Projective BrainpoolP256T1 curve is a Weierstrass projective curve .
instance WPCurve BrainpoolP256T1 Fq Fr where
gP_ = gP
# INLINABLE gP _ #
| Coefficient @A@ of BrainpoolP256T1 curve .
_a :: Fq
_a = 0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5374
# INLINABLE _ a #
| Coefficient @B@ of BrainpoolP256T1 curve .
_b :: Fq
_b = 0x662c61c430d84ea4fe66a7733d0b76b7bf93ebc4af2f49256ae58101fee92b04
| Cofactor of BrainpoolP256T1 curve .
_h :: Natural
_h = 0x1
# INLINABLE _ h #
| Characteristic of BrainpoolP256T1 curve .
_q :: Natural
_q = 0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377
| Order of BrainpoolP256T1 curve .
_r :: Natural
_r = 0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7
| Coordinate @X@ of BrainpoolP256T1 curve .
_x :: Fq
_x = 0xa3e8eb3cc1cfe7b7732213b23a656149afa142c47aafbc2b79a191562e1305f4
| Coordinate @Y@ of BrainpoolP256T1 curve .
_y :: Fq
_y = 0x2d996c823439c56d7f7b22e14644417e69bcb6de39d027001dabe8f35b25c9be
| Generator of affine BrainpoolP256T1 curve .
gA :: PA
gA = A _x _y
# INLINABLE gA #
| Generator of Jacobian BrainpoolP256T1 curve .
gJ :: PJ
gJ = J _x _y 1
# INLINABLE gJ #
| Generator of projective BrainpoolP256T1 curve .
gP :: PP
gP = P _x _y 1
# INLINABLE gP #
|
f1bf48920142da853500aa1d9ee2cb0a1172cc0d2410379c874d91cb0a0b41df | mhuebert/chia | build.cljs | ;; EXPERIMENTAL
(ns chia.material-ui.build
(:require ["fs" :as fs]
["typescript" :as ts]
["ts-morph" :as tsm]
[clojure.string :as str]
[applied-science.js-interop :as j]))
(defn walk-dir
[path]
(let [{files false
dirs true} (->> (fs/readdirSync path)
(map #(str path "/" %))
(group-by #(some-> ^js (fs/statSync %)
(.isDirectory))))]
(into files
(mapcat walk-dir dirs))))
(defn all-components []
(->> (walk-dir "node_modules/@material-ui/core")
(filter #(and (str/ends-with? % ".d.ts")
(not (re-find #"/index\.|test" %))))
(keep (fn [path]
(when-let [Name (second (re-find #"([A-Z][^/]+)/\1\.d\.ts$" path))]
{:Name Name
:full-path path
:path (second (re-find (re-pattern (str ".*(@material-ui.*)/" Name ".d.ts")) path))})))))
(def syntax-kind (.-SyntaxKind ts))
(defn kind-name [kind]
(keyword (j/get syntax-kind (str kind))))
(defn kind [node]
(kind-name (.-kind node)))
(def primitives #{:AnyKeyword
:BooleanKeyword
:NumberKeyword
:StringKeyword})
(deftype Node [name type])
(defn add-child! [node name type]
(let [child (Node. name type)]
(j/update! node .-children (fnil j/push! #js[]) child)
child))
(defn to-obj [node]
(j/obj (.-name node)
(if-some [children (.-children node)]
(->> (mapv to-obj children)
(reduce (fn [pv child]
(reduce (fn [pv k]
(if (j/contains? pv k)
(j/extend! pv child)
(j/assoc! pv k (j/get child k)))
pv) pv (js-keys child))) #js{}))
(.-type node))))
(defn resolve-array-type [node]
(loop [adeep 0
node node]
(if (= (kind node) :ArrayType)
(recur (inc adeep) (.-elementType node))
[node adeep])))
(defn id-name [node-name]
(case (kind node-name)
:IdentifierName (.text node-name)
:QualifiedName (str (.-left node-name) "." (.-right node-name))
(kind node-name)))
(defn visit [^js parent-node]
(fn [^js node]
(case (kind node)
:ModuleDeclaration
(ts/forEachChild node (visit (add-child! parent-node (.. node -name -text) nil)))
:ModuleBlock
(ts/forEachChild node (visit parent-node))
:InterfaceDeclaration
(let [i-name (.. node -name -text)]
(j/assoc! parent-node i-name #js{})
(ts/forEachChild
node (visit
(add-child! parent-node i-name nil))))
:PropertySignature
(let [prop-name (cond (string? node) node
(j/contains? node :name) (.-name node)
:else node)
[prop-type a-deep] (resolve-array-type node)
prop-kind (kind prop-type)]
(if (= prop-kind :TypeReference)
(let [real-type (.-typeName prop-type)]
(prn :R prop-name :T prop-name)
(add-child! parent-node prop-name
(str (.repeat "Array<" a-deep)
(if (= :QualifiedName (kind real-type))
(.getText real-type)
(j/get real-type :text real-type))
(.repeat ">" a-deep))))
(if (primitives prop-kind)
(add-child! parent-node prop-name prop-kind)
(do
(when (not= (.-text (.-name prop-type)) prop-name)
#_(prn node (kind node) :not= prop-name (.-text (.-name prop-type)) #_(js-keys prop-type)))
))
))
:ClassDeclaration nil #_(prn :ClassDeclaration (.. node -name -text) (js-keys node))
:TypeAliasDeclaration nil
:ExportDeclaration (prn :Export (js-keys node))
(if-let [name (j/get-in node [.-name .-text])]
(do :ignore name (kind node))
(prn :unknown (kind node))))))
(defn parse [filenames]
(let [program (ts/createProgram (to-array filenames) #js{})
node (Node. "root" nil)]
(doseq [file (.getSourceFiles program)]
(ts/forEachChild file (#'visit node)))
(j/get (to-obj node) :root)))
(let [components (all-components)
tree (parse ["node_modules/@material-ui/core/index.d.ts"])]
(js-keys tree)
(j/select-keys tree (mapv :Name components))
(js-keys tree)
nil
#_(mapv :Name components)
#_(for [file files
:when (.isDeclarationFile file)
:let [interfaces (.getInterfaces file)
i (first interfaces)]
:when (and i (.getExtends i))]
{:s (.getStructure i)
:extends (mapv (comp #(.getText %) #(.getExpression %)) (.getExtends i))
:members (mapv #(.getName %) (.getMembers i))
:t (.getText i)}
#_{#_#_:t (.getText i)
:members (mapv #(.getName %) (.getMembers i))
:ext (mapv #(.-kind %) (.getExtends i))
:meth (.getMethods i)
:base-d (.getBaseDeclarations i)
:base-t (.getBaseTypes i)}))
(defn camel-dash [s]
(-> s
(str/replace #"^[A-Z]" str/lower-case)
(str/replace-all #"[A-Z]" #(str "-" (str/lower-case %)))))
(defn generate []
(doseq [{:keys [Name path]} (all-components)
:let [name (camel-dash Name)]]
(fs/writeFileSync
(str "src/chia/material_ui/" (munge name) ".cljs")
(str "(ns chia.material-ui." name "
(:require [\"" path "\" :as " Name "]))
(def " name " " Name "/default)"))))
| null | https://raw.githubusercontent.com/mhuebert/chia/74ee3ee9f86efbdf81d8829ab4f0a44d619c73d3/material-ui/build/chia/material_ui/build.cljs | clojure | EXPERIMENTAL |
(ns chia.material-ui.build
(:require ["fs" :as fs]
["typescript" :as ts]
["ts-morph" :as tsm]
[clojure.string :as str]
[applied-science.js-interop :as j]))
(defn walk-dir
[path]
(let [{files false
dirs true} (->> (fs/readdirSync path)
(map #(str path "/" %))
(group-by #(some-> ^js (fs/statSync %)
(.isDirectory))))]
(into files
(mapcat walk-dir dirs))))
(defn all-components []
(->> (walk-dir "node_modules/@material-ui/core")
(filter #(and (str/ends-with? % ".d.ts")
(not (re-find #"/index\.|test" %))))
(keep (fn [path]
(when-let [Name (second (re-find #"([A-Z][^/]+)/\1\.d\.ts$" path))]
{:Name Name
:full-path path
:path (second (re-find (re-pattern (str ".*(@material-ui.*)/" Name ".d.ts")) path))})))))
(def syntax-kind (.-SyntaxKind ts))
(defn kind-name [kind]
(keyword (j/get syntax-kind (str kind))))
(defn kind [node]
(kind-name (.-kind node)))
(def primitives #{:AnyKeyword
:BooleanKeyword
:NumberKeyword
:StringKeyword})
(deftype Node [name type])
(defn add-child! [node name type]
(let [child (Node. name type)]
(j/update! node .-children (fnil j/push! #js[]) child)
child))
(defn to-obj [node]
(j/obj (.-name node)
(if-some [children (.-children node)]
(->> (mapv to-obj children)
(reduce (fn [pv child]
(reduce (fn [pv k]
(if (j/contains? pv k)
(j/extend! pv child)
(j/assoc! pv k (j/get child k)))
pv) pv (js-keys child))) #js{}))
(.-type node))))
(defn resolve-array-type [node]
(loop [adeep 0
node node]
(if (= (kind node) :ArrayType)
(recur (inc adeep) (.-elementType node))
[node adeep])))
(defn id-name [node-name]
(case (kind node-name)
:IdentifierName (.text node-name)
:QualifiedName (str (.-left node-name) "." (.-right node-name))
(kind node-name)))
(defn visit [^js parent-node]
(fn [^js node]
(case (kind node)
:ModuleDeclaration
(ts/forEachChild node (visit (add-child! parent-node (.. node -name -text) nil)))
:ModuleBlock
(ts/forEachChild node (visit parent-node))
:InterfaceDeclaration
(let [i-name (.. node -name -text)]
(j/assoc! parent-node i-name #js{})
(ts/forEachChild
node (visit
(add-child! parent-node i-name nil))))
:PropertySignature
(let [prop-name (cond (string? node) node
(j/contains? node :name) (.-name node)
:else node)
[prop-type a-deep] (resolve-array-type node)
prop-kind (kind prop-type)]
(if (= prop-kind :TypeReference)
(let [real-type (.-typeName prop-type)]
(prn :R prop-name :T prop-name)
(add-child! parent-node prop-name
(str (.repeat "Array<" a-deep)
(if (= :QualifiedName (kind real-type))
(.getText real-type)
(j/get real-type :text real-type))
(.repeat ">" a-deep))))
(if (primitives prop-kind)
(add-child! parent-node prop-name prop-kind)
(do
(when (not= (.-text (.-name prop-type)) prop-name)
#_(prn node (kind node) :not= prop-name (.-text (.-name prop-type)) #_(js-keys prop-type)))
))
))
:ClassDeclaration nil #_(prn :ClassDeclaration (.. node -name -text) (js-keys node))
:TypeAliasDeclaration nil
:ExportDeclaration (prn :Export (js-keys node))
(if-let [name (j/get-in node [.-name .-text])]
(do :ignore name (kind node))
(prn :unknown (kind node))))))
(defn parse [filenames]
(let [program (ts/createProgram (to-array filenames) #js{})
node (Node. "root" nil)]
(doseq [file (.getSourceFiles program)]
(ts/forEachChild file (#'visit node)))
(j/get (to-obj node) :root)))
(let [components (all-components)
tree (parse ["node_modules/@material-ui/core/index.d.ts"])]
(js-keys tree)
(j/select-keys tree (mapv :Name components))
(js-keys tree)
nil
#_(mapv :Name components)
#_(for [file files
:when (.isDeclarationFile file)
:let [interfaces (.getInterfaces file)
i (first interfaces)]
:when (and i (.getExtends i))]
{:s (.getStructure i)
:extends (mapv (comp #(.getText %) #(.getExpression %)) (.getExtends i))
:members (mapv #(.getName %) (.getMembers i))
:t (.getText i)}
#_{#_#_:t (.getText i)
:members (mapv #(.getName %) (.getMembers i))
:ext (mapv #(.-kind %) (.getExtends i))
:meth (.getMethods i)
:base-d (.getBaseDeclarations i)
:base-t (.getBaseTypes i)}))
(defn camel-dash [s]
(-> s
(str/replace #"^[A-Z]" str/lower-case)
(str/replace-all #"[A-Z]" #(str "-" (str/lower-case %)))))
(defn generate []
(doseq [{:keys [Name path]} (all-components)
:let [name (camel-dash Name)]]
(fs/writeFileSync
(str "src/chia/material_ui/" (munge name) ".cljs")
(str "(ns chia.material-ui." name "
(:require [\"" path "\" :as " Name "]))
(def " name " " Name "/default)"))))
|
8ff2f3c88dddf848f9c098287058b7ac3b94865f7497fb9e66956259d3f1c011 | Javran/advent-of-code | Day1.hs | module Javran.AdventOfCode.Y2021.Day1 (
) where
import Data.List.Split
import Javran.AdventOfCode.Prelude
data Day1 deriving (Generic)
countIncr :: [Int] -> Int
countIncr xs = countLength id $ zipWith (<) xs (tail xs)
instance Solution Day1 where
solutionRun _ SolutionContext {getInputS, answerShow} = do
xs <- fmap (read @Int) . lines <$> getInputS
answerShow $ countIncr xs
let xs' = fmap sum $ divvy 3 1 xs
answerShow $ countIncr xs'
| null | https://raw.githubusercontent.com/Javran/advent-of-code/676ef13c2f9d341cf7de0f383335a1cf577bd73d/src/Javran/AdventOfCode/Y2021/Day1.hs | haskell | module Javran.AdventOfCode.Y2021.Day1 (
) where
import Data.List.Split
import Javran.AdventOfCode.Prelude
data Day1 deriving (Generic)
countIncr :: [Int] -> Int
countIncr xs = countLength id $ zipWith (<) xs (tail xs)
instance Solution Day1 where
solutionRun _ SolutionContext {getInputS, answerShow} = do
xs <- fmap (read @Int) . lines <$> getInputS
answerShow $ countIncr xs
let xs' = fmap sum $ divvy 3 1 xs
answerShow $ countIncr xs'
| |
6b725189aea0d7f80bd198e9f0466dc9014340806a4c68fc1c53d797e54ac523 | hellonico/origami-fun | drawsegments.clj | (ns opencv4.drawsegments
(:require
[opencv4.utils :as u]
[opencv4.colors.rgb :as color]
[opencv4.core :refer :all]))
;
; find liines in a picture using draw segment
;
;
(def parking2 (imread "resources/images/lines/parking.png" CV_8UC1))
(def det (create-line-segment-detector))
(def lines (new-mat))
(def result (clone parking2))
(.detect det parking2 lines)
(.drawSegments det result lines)
(def output (new-mat))
(vconcat [(cvt-color! parking2 COLOR_GRAY2BGR) result] output)
(imwrite output "output/hough2.png")
| null | https://raw.githubusercontent.com/hellonico/origami-fun/80117788530d942eaa9a80e2995b37409fa24889/test/opencv4/drawsegments.clj | clojure |
find liines in a picture using draw segment
| (ns opencv4.drawsegments
(:require
[opencv4.utils :as u]
[opencv4.colors.rgb :as color]
[opencv4.core :refer :all]))
(def parking2 (imread "resources/images/lines/parking.png" CV_8UC1))
(def det (create-line-segment-detector))
(def lines (new-mat))
(def result (clone parking2))
(.detect det parking2 lines)
(.drawSegments det result lines)
(def output (new-mat))
(vconcat [(cvt-color! parking2 COLOR_GRAY2BGR) result] output)
(imwrite output "output/hough2.png")
|
e58fad31cf1ffb989dbb9de421f298694359234c1231171370ffb093b198ab91 | alexandergunnarson/quantum | refs.cljc | (ns quantum.untyped.core.refs
(:require
[quantum.untyped.core.core :as ucore])
#?(:clj (:import [clojure.lang IDeref IAtom])))
(ucore/log-this-ns)
(defn atom? [x] (#?(:clj instance? :cljs satisfies?) IAtom x))
(defn derefable? [x] (#?(:clj instance? :cljs satisfies?) IDeref x))
(defn ?deref [x] (if (derefable? x) @x x))
| null | https://raw.githubusercontent.com/alexandergunnarson/quantum/0c655af439734709566110949f9f2f482e468509/src-untyped/quantum/untyped/core/refs.cljc | clojure | (ns quantum.untyped.core.refs
(:require
[quantum.untyped.core.core :as ucore])
#?(:clj (:import [clojure.lang IDeref IAtom])))
(ucore/log-this-ns)
(defn atom? [x] (#?(:clj instance? :cljs satisfies?) IAtom x))
(defn derefable? [x] (#?(:clj instance? :cljs satisfies?) IDeref x))
(defn ?deref [x] (if (derefable? x) @x x))
| |
2567f7180636d40f5ead7efefc6d497c9676aafbd2e60da99407022c65887d44 | zkincaid/duet | cache.ml | type cache_params = {
max_size : int;
hard_limit : int;
keys_hit_rate : float;
min_hits : float;
aging_factor : float;
}
let default_params = {
max_size = 1000;
hard_limit = 0;
keys_hit_rate = 0.9;
min_hits = 0.9;
aging_factor = 0.95;
}
module type S = sig
type ('a, 'b) t
val create : ?random:bool -> ?params:cache_params -> int -> ('a, 'b) t
val get_params : ('a, 'b) t -> cache_params
val set_params : ('a, 'b) t -> cache_params -> unit
val clear : ('a, 'b) t -> unit
val reset : ('a, 'b) t -> unit
val copy : ('a, 'b) t -> ('a, 'b) t
val add : ('a, 'b) t -> 'a -> 'b -> unit
val find : ('a, 'b) t -> 'a -> 'b
val find_opt : ('a, 'b) t -> 'a -> 'b option
val mem : ('a, 'b) t -> 'a -> bool
val remove : ('a, 'b) t -> 'a -> unit
val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
val filter_map_inplace : ('a -> 'b -> 'b option) -> ('a, 'b) t -> unit
val fold : ('a -> 'b -> 'c -> 'c) -> ('a, 'b) t -> 'c -> 'c
val length : ('a, 'b) t -> int
end
module type HashS = sig
type key
type 'a t
val create : ?params:cache_params -> int -> 'a t
val get_params : 'a t -> cache_params
val set_params : 'a t -> cache_params -> unit
val clear : 'a t -> unit
val reset : 'a t -> unit
val copy : 'a t -> 'a t
val add : 'a t -> key -> 'a -> unit
val find : 'a t -> key -> 'a
val find_opt : 'a t -> key -> 'a option
val mem : 'a t -> key -> bool
val remove : 'a t -> key -> unit
val iter : (key -> 'a -> unit) -> 'a t -> unit
val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit
val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
val length : 'a t -> int
end
module DList = struct
type 'a node = {
data : 'a;
mutable prev : 'a node option;
mutable next : 'a node option;
}
type 'a t = {
mutable head : 'a node option;
mutable tail : 'a node option;
}
let create _ =
{ head = None; tail = None }
let clear dl =
dl.head <- None; dl.tail <- None
let copy dl =
let rec go n cprev =
match n with
| None -> (Some cprev)
| Some n ->
let cn = { data = n.data; prev = (Some cprev); next = None } in
go n.next cn
in
match (dl.head, dl.tail) with
| None, None -> { head = None; tail = None }
| Some hd, Some _ ->
let chd = { data = hd.data; prev = None; next = None } in
{ head = Some chd; tail = (go hd.next chd) }
| _ -> assert false
let move_front dl n =
match n.prev with
| None -> ()
| Some prev ->
prev.next <- n.next;
(match n.next with
| None -> dl.tail <- Some prev
| Some next -> next.prev <- Some prev);
n.prev <- None;
n.next <- dl.head;
dl.head <- (Some n)
let add_front dl datum =
let n = {data = datum; prev = None; next = None } in
(match (dl.head, dl.tail) with
| None, None -> dl.head <- Some n; dl.tail <- Some n
| Some hd, Some _ -> hd.prev <- Some n; n.next <- dl.head; dl.head <- Some n
| _ -> assert false);
n
let remove dl n =
(match n.prev with
| None -> dl.head <- n.next
| Some prev -> prev.next <- n.next);
(match n.next with
| None -> dl.tail <- n.prev
| Some next -> next.prev <- n.prev);
n.prev <- None; n.next <- None
end
module LRU = struct
type ('a, 'b) data = {
key : 'a;
mutable value : 'b;
mutable hits : float;
}
let new_data k v = { key = k; value = v; hits = 0.0 }
type ('a, 'b) node = ('a, 'b) data DList.node
type ('a, 'b) dlist = ('a, 'b) data DList.t
type ('a, 'b) t = {
updates : ('a, 'b) dlist; (* head is most recently updated, tail is least recently updated *)
table : ('a, ('a, 'b) node) Hashtbl.t;
mutable num_hit_rate : int; (* number of keys that surpass min_hit threshold *)
mutable params : cache_params;
init_params : cache_params;
}
let validate_params p =
0 < p.max_size &&
(p.hard_limit = 0 || p.max_size <= p.hard_limit) &&
0.0 <= p.keys_hit_rate && p.keys_hit_rate <= 1.0 &&
0.0 <= p.min_hits &&
0.0 <= p.aging_factor && p.aging_factor <= 1.0
let create ?(random = false) ?(params = default_params) init_sz =
if not (validate_params params) then invalid_arg "Cache params not valid" else
{ updates = DList.create ();
table = Hashtbl.create ~random init_sz;
num_hit_rate = 0;
params;
init_params = params;
}
let get_params c = c.params
let clear c =
DList.clear c.updates;
c.num_hit_rate <- 0;
Hashtbl.clear c.table
let reset c =
DList.clear c.updates;
c.num_hit_rate <- 0;
Hashtbl.reset c.table;
c.params <- c.init_params
let copy c =
{ c with updates = DList.copy c.updates; table = Hashtbl.copy c.table }
let remove c k =
match Hashtbl.find_opt c.table k with
| None -> ()
| Some n ->
DList.remove c.updates n;
Hashtbl.remove c.table k;
if c.params.min_hits <= n.data.hits then
c.num_hit_rate <- c.num_hit_rate - 1
let evict c =
let k =
match c.updates.tail with
| None -> assert false
| Some tl -> tl.data.key
in remove c k
let resize c =
let next_sz sz limit = min (2 * sz) limit in
let limit = if c.params.hard_limit = 0 then Sys.max_array_length else c.params.hard_limit in
let nsize = next_sz (Hashtbl.length c.table) limit in
c.params <- { c.params with max_size = nsize };
Hashtbl.iter (fun _ (n : ('a, 'b) node) ->
n.data.hits <- c.params.aging_factor *. n.data.hits
) c.table
let evict_or_resize c =
assert (Hashtbl.length c.table = c.params.max_size);
if (c.params.hard_limit <> 0 && c.params.max_size = c.params.hard_limit) ||
(float c.num_hit_rate) /. (float (Hashtbl.length c.table)) < c.params.keys_hit_rate then
evict c
else
resize c
let set_params c p =
if not (validate_params p) then invalid_arg "Cache params not valid";
c.params <- p;
c.num_hit_rate <- 0;
Hashtbl.iter (fun _ (n : ('a, 'b) node) ->
if p.min_hits <= n.data.hits then
c.num_hit_rate <- c.num_hit_rate + 1
) c.table;
while c.params.max_size < Hashtbl.length c.table do
evict_or_resize c
done
let add_hit c (n : ('a, 'b) node) =
let b4 = n.data.hits in
n.data.hits <- n.data.hits +. 1.0;
let after = n.data.hits in
if b4 < c.params.min_hits && c.params.min_hits <= after then
c.num_hit_rate <- c.num_hit_rate + 1
let add c k v =
match Hashtbl.find_opt c.table k with
| Some n ->
n.data.value <- v;
add_hit c n;
DList.move_front c.updates n
| None ->
Cache is full
evict_or_resize c;
let n = DList.add_front c.updates (new_data k v) in
Hashtbl.add c.table k n
let find c k =
match Hashtbl.find_opt c.table k with
| None -> raise Not_found
| Some n -> add_hit c n; DList.move_front c.updates n; n.data.value
let find_opt c k =
match Hashtbl.find_opt c.table k with
| None -> None
| Some n -> add_hit c n; DList.move_front c.updates n; Some n.data.value
let mem c k =
match Hashtbl.find_opt c.table k with
| None -> false
| Some n -> add_hit c n; DList.move_front c.updates n; true
let iter f c =
Hashtbl.iter (fun k n ->
add_hit c n; f k n.data.value
) c.table
let filter_map_inplace f c =
Hashtbl.filter_map_inplace (fun k (n : ('a, 'b) node) ->
match f k n.data.value with
| Some v -> add_hit c n; n.data.value <- v; Some n
| None ->
DList.remove c.updates n;
if c.params.min_hits <= n.data.hits then
c.num_hit_rate <- c.num_hit_rate - 1;
None
) c.table
let fold f c init =
Hashtbl.fold (fun k n acc ->
add_hit c n; f k n.data.value acc
) c.table init
let length c = Hashtbl.length c.table
module Make(K : Hashtbl.HashedType) = struct
type key = K.t
module HT = Hashtbl.Make(K)
type 'a t = {
updates : (key, 'a) dlist; (* head is most recently updated, tail is least recently updated *)
table : (key, 'a) node HT.t;
mutable num_hit_rate : int; (* number of keys that surpass min_hit threshold *)
mutable params : cache_params;
init_params : cache_params;
}
let create ?(params = default_params) init_sz =
if not (validate_params params) then invalid_arg "Cache params not valid" else
{ updates = DList.create ();
table = HT.create init_sz;
num_hit_rate = 0;
params;
init_params = params;
}
let get_params c = c.params
let clear c =
DList.clear c.updates;
c.num_hit_rate <- 0;
HT.clear c.table
let reset c =
DList.clear c.updates;
c.num_hit_rate <- 0;
HT.reset c.table;
c.params <- c.init_params
let copy c =
{ c with updates = DList.copy c.updates; table = HT.copy c.table }
let remove c k =
match HT.find_opt c.table k with
| None -> ()
| Some n ->
DList.remove c.updates n;
HT.remove c.table k;
if c.params.min_hits <= n.data.hits then
c.num_hit_rate <- c.num_hit_rate - 1
let evict c =
let k =
match c.updates.tail with
| None -> assert false
| Some tl -> tl.data.key
in remove c k
let resize c =
let next_sz sz limit = min (2 * sz) limit in
let limit = if c.params.hard_limit = 0 then Sys.max_array_length else c.params.hard_limit in
let nsize = next_sz (HT.length c.table) limit in
c.params <- { c.params with max_size = nsize };
HT.iter (fun _ (n : ('a, 'b) node) ->
n.data.hits <- c.params.aging_factor *. n.data.hits
) c.table
let evict_or_resize c =
assert (HT.length c.table = c.params.max_size);
if (c.params.hard_limit <> 0 && c.params.max_size = c.params.hard_limit) ||
(float c.num_hit_rate) /. (float (HT.length c.table)) < c.params.keys_hit_rate then
evict c
else
resize c
let set_params c p =
if not (validate_params p) then invalid_arg "Cache params not valid";
c.params <- p;
c.num_hit_rate <- 0;
HT.iter (fun _ (n : ('a, 'b) node) ->
if p.min_hits <= n.data.hits then
c.num_hit_rate <- c.num_hit_rate + 1
) c.table;
while c.params.max_size < HT.length c.table do
evict_or_resize c
done
let add_hit c (n : ('a, 'b) node) =
let b4 = n.data.hits in
n.data.hits <- n.data.hits +. 1.0;
let after = n.data.hits in
if b4 < c.params.min_hits && c.params.min_hits <= after then
c.num_hit_rate <- c.num_hit_rate + 1
let add c k v =
match HT.find_opt c.table k with
| Some n ->
n.data.value <- v;
add_hit c n;
DList.move_front c.updates n
| None ->
Cache is full
evict_or_resize c;
let n = DList.add_front c.updates (new_data k v) in
HT.add c.table k n
let find c k =
match HT.find_opt c.table k with
| None -> raise Not_found
| Some n -> add_hit c n; DList.move_front c.updates n; n.data.value
let find_opt c k =
match HT.find_opt c.table k with
| None -> None
| Some n -> add_hit c n; DList.move_front c.updates n; Some n.data.value
let mem c k =
match HT.find_opt c.table k with
| None -> false
| Some n -> add_hit c n; DList.move_front c.updates n; true
let iter f c =
HT.iter (fun k n ->
add_hit c n; f k n.data.value
) c.table
let filter_map_inplace f c =
HT.filter_map_inplace (fun k (n : ('a, 'b) node) ->
match f k n.data.value with
| Some v -> add_hit c n; n.data.value <- v; Some n
| None ->
DList.remove c.updates n;
if c.params.min_hits <= n.data.hits then
c.num_hit_rate <- c.num_hit_rate - 1;
None
) c.table
let fold f c init =
HT.fold (fun k n acc ->
add_hit c n; f k n.data.value acc
) c.table init
let length c = HT.length c.table
end
end
| null | https://raw.githubusercontent.com/zkincaid/duet/eb3dbfe6c51d5e1a11cb39ab8f70584aaaa309f9/srk/src/cache.ml | ocaml | head is most recently updated, tail is least recently updated
number of keys that surpass min_hit threshold
head is most recently updated, tail is least recently updated
number of keys that surpass min_hit threshold | type cache_params = {
max_size : int;
hard_limit : int;
keys_hit_rate : float;
min_hits : float;
aging_factor : float;
}
let default_params = {
max_size = 1000;
hard_limit = 0;
keys_hit_rate = 0.9;
min_hits = 0.9;
aging_factor = 0.95;
}
module type S = sig
type ('a, 'b) t
val create : ?random:bool -> ?params:cache_params -> int -> ('a, 'b) t
val get_params : ('a, 'b) t -> cache_params
val set_params : ('a, 'b) t -> cache_params -> unit
val clear : ('a, 'b) t -> unit
val reset : ('a, 'b) t -> unit
val copy : ('a, 'b) t -> ('a, 'b) t
val add : ('a, 'b) t -> 'a -> 'b -> unit
val find : ('a, 'b) t -> 'a -> 'b
val find_opt : ('a, 'b) t -> 'a -> 'b option
val mem : ('a, 'b) t -> 'a -> bool
val remove : ('a, 'b) t -> 'a -> unit
val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
val filter_map_inplace : ('a -> 'b -> 'b option) -> ('a, 'b) t -> unit
val fold : ('a -> 'b -> 'c -> 'c) -> ('a, 'b) t -> 'c -> 'c
val length : ('a, 'b) t -> int
end
module type HashS = sig
type key
type 'a t
val create : ?params:cache_params -> int -> 'a t
val get_params : 'a t -> cache_params
val set_params : 'a t -> cache_params -> unit
val clear : 'a t -> unit
val reset : 'a t -> unit
val copy : 'a t -> 'a t
val add : 'a t -> key -> 'a -> unit
val find : 'a t -> key -> 'a
val find_opt : 'a t -> key -> 'a option
val mem : 'a t -> key -> bool
val remove : 'a t -> key -> unit
val iter : (key -> 'a -> unit) -> 'a t -> unit
val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit
val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
val length : 'a t -> int
end
module DList = struct
type 'a node = {
data : 'a;
mutable prev : 'a node option;
mutable next : 'a node option;
}
type 'a t = {
mutable head : 'a node option;
mutable tail : 'a node option;
}
let create _ =
{ head = None; tail = None }
let clear dl =
dl.head <- None; dl.tail <- None
let copy dl =
let rec go n cprev =
match n with
| None -> (Some cprev)
| Some n ->
let cn = { data = n.data; prev = (Some cprev); next = None } in
go n.next cn
in
match (dl.head, dl.tail) with
| None, None -> { head = None; tail = None }
| Some hd, Some _ ->
let chd = { data = hd.data; prev = None; next = None } in
{ head = Some chd; tail = (go hd.next chd) }
| _ -> assert false
let move_front dl n =
match n.prev with
| None -> ()
| Some prev ->
prev.next <- n.next;
(match n.next with
| None -> dl.tail <- Some prev
| Some next -> next.prev <- Some prev);
n.prev <- None;
n.next <- dl.head;
dl.head <- (Some n)
let add_front dl datum =
let n = {data = datum; prev = None; next = None } in
(match (dl.head, dl.tail) with
| None, None -> dl.head <- Some n; dl.tail <- Some n
| Some hd, Some _ -> hd.prev <- Some n; n.next <- dl.head; dl.head <- Some n
| _ -> assert false);
n
let remove dl n =
(match n.prev with
| None -> dl.head <- n.next
| Some prev -> prev.next <- n.next);
(match n.next with
| None -> dl.tail <- n.prev
| Some next -> next.prev <- n.prev);
n.prev <- None; n.next <- None
end
module LRU = struct
type ('a, 'b) data = {
key : 'a;
mutable value : 'b;
mutable hits : float;
}
let new_data k v = { key = k; value = v; hits = 0.0 }
type ('a, 'b) node = ('a, 'b) data DList.node
type ('a, 'b) dlist = ('a, 'b) data DList.t
type ('a, 'b) t = {
table : ('a, ('a, 'b) node) Hashtbl.t;
mutable params : cache_params;
init_params : cache_params;
}
let validate_params p =
0 < p.max_size &&
(p.hard_limit = 0 || p.max_size <= p.hard_limit) &&
0.0 <= p.keys_hit_rate && p.keys_hit_rate <= 1.0 &&
0.0 <= p.min_hits &&
0.0 <= p.aging_factor && p.aging_factor <= 1.0
let create ?(random = false) ?(params = default_params) init_sz =
if not (validate_params params) then invalid_arg "Cache params not valid" else
{ updates = DList.create ();
table = Hashtbl.create ~random init_sz;
num_hit_rate = 0;
params;
init_params = params;
}
let get_params c = c.params
let clear c =
DList.clear c.updates;
c.num_hit_rate <- 0;
Hashtbl.clear c.table
let reset c =
DList.clear c.updates;
c.num_hit_rate <- 0;
Hashtbl.reset c.table;
c.params <- c.init_params
let copy c =
{ c with updates = DList.copy c.updates; table = Hashtbl.copy c.table }
let remove c k =
match Hashtbl.find_opt c.table k with
| None -> ()
| Some n ->
DList.remove c.updates n;
Hashtbl.remove c.table k;
if c.params.min_hits <= n.data.hits then
c.num_hit_rate <- c.num_hit_rate - 1
let evict c =
let k =
match c.updates.tail with
| None -> assert false
| Some tl -> tl.data.key
in remove c k
let resize c =
let next_sz sz limit = min (2 * sz) limit in
let limit = if c.params.hard_limit = 0 then Sys.max_array_length else c.params.hard_limit in
let nsize = next_sz (Hashtbl.length c.table) limit in
c.params <- { c.params with max_size = nsize };
Hashtbl.iter (fun _ (n : ('a, 'b) node) ->
n.data.hits <- c.params.aging_factor *. n.data.hits
) c.table
let evict_or_resize c =
assert (Hashtbl.length c.table = c.params.max_size);
if (c.params.hard_limit <> 0 && c.params.max_size = c.params.hard_limit) ||
(float c.num_hit_rate) /. (float (Hashtbl.length c.table)) < c.params.keys_hit_rate then
evict c
else
resize c
let set_params c p =
if not (validate_params p) then invalid_arg "Cache params not valid";
c.params <- p;
c.num_hit_rate <- 0;
Hashtbl.iter (fun _ (n : ('a, 'b) node) ->
if p.min_hits <= n.data.hits then
c.num_hit_rate <- c.num_hit_rate + 1
) c.table;
while c.params.max_size < Hashtbl.length c.table do
evict_or_resize c
done
let add_hit c (n : ('a, 'b) node) =
let b4 = n.data.hits in
n.data.hits <- n.data.hits +. 1.0;
let after = n.data.hits in
if b4 < c.params.min_hits && c.params.min_hits <= after then
c.num_hit_rate <- c.num_hit_rate + 1
let add c k v =
match Hashtbl.find_opt c.table k with
| Some n ->
n.data.value <- v;
add_hit c n;
DList.move_front c.updates n
| None ->
Cache is full
evict_or_resize c;
let n = DList.add_front c.updates (new_data k v) in
Hashtbl.add c.table k n
let find c k =
match Hashtbl.find_opt c.table k with
| None -> raise Not_found
| Some n -> add_hit c n; DList.move_front c.updates n; n.data.value
let find_opt c k =
match Hashtbl.find_opt c.table k with
| None -> None
| Some n -> add_hit c n; DList.move_front c.updates n; Some n.data.value
let mem c k =
match Hashtbl.find_opt c.table k with
| None -> false
| Some n -> add_hit c n; DList.move_front c.updates n; true
let iter f c =
Hashtbl.iter (fun k n ->
add_hit c n; f k n.data.value
) c.table
let filter_map_inplace f c =
Hashtbl.filter_map_inplace (fun k (n : ('a, 'b) node) ->
match f k n.data.value with
| Some v -> add_hit c n; n.data.value <- v; Some n
| None ->
DList.remove c.updates n;
if c.params.min_hits <= n.data.hits then
c.num_hit_rate <- c.num_hit_rate - 1;
None
) c.table
let fold f c init =
Hashtbl.fold (fun k n acc ->
add_hit c n; f k n.data.value acc
) c.table init
let length c = Hashtbl.length c.table
module Make(K : Hashtbl.HashedType) = struct
type key = K.t
module HT = Hashtbl.Make(K)
type 'a t = {
table : (key, 'a) node HT.t;
mutable params : cache_params;
init_params : cache_params;
}
let create ?(params = default_params) init_sz =
if not (validate_params params) then invalid_arg "Cache params not valid" else
{ updates = DList.create ();
table = HT.create init_sz;
num_hit_rate = 0;
params;
init_params = params;
}
let get_params c = c.params
let clear c =
DList.clear c.updates;
c.num_hit_rate <- 0;
HT.clear c.table
let reset c =
DList.clear c.updates;
c.num_hit_rate <- 0;
HT.reset c.table;
c.params <- c.init_params
let copy c =
{ c with updates = DList.copy c.updates; table = HT.copy c.table }
let remove c k =
match HT.find_opt c.table k with
| None -> ()
| Some n ->
DList.remove c.updates n;
HT.remove c.table k;
if c.params.min_hits <= n.data.hits then
c.num_hit_rate <- c.num_hit_rate - 1
let evict c =
let k =
match c.updates.tail with
| None -> assert false
| Some tl -> tl.data.key
in remove c k
let resize c =
let next_sz sz limit = min (2 * sz) limit in
let limit = if c.params.hard_limit = 0 then Sys.max_array_length else c.params.hard_limit in
let nsize = next_sz (HT.length c.table) limit in
c.params <- { c.params with max_size = nsize };
HT.iter (fun _ (n : ('a, 'b) node) ->
n.data.hits <- c.params.aging_factor *. n.data.hits
) c.table
let evict_or_resize c =
assert (HT.length c.table = c.params.max_size);
if (c.params.hard_limit <> 0 && c.params.max_size = c.params.hard_limit) ||
(float c.num_hit_rate) /. (float (HT.length c.table)) < c.params.keys_hit_rate then
evict c
else
resize c
let set_params c p =
if not (validate_params p) then invalid_arg "Cache params not valid";
c.params <- p;
c.num_hit_rate <- 0;
HT.iter (fun _ (n : ('a, 'b) node) ->
if p.min_hits <= n.data.hits then
c.num_hit_rate <- c.num_hit_rate + 1
) c.table;
while c.params.max_size < HT.length c.table do
evict_or_resize c
done
let add_hit c (n : ('a, 'b) node) =
let b4 = n.data.hits in
n.data.hits <- n.data.hits +. 1.0;
let after = n.data.hits in
if b4 < c.params.min_hits && c.params.min_hits <= after then
c.num_hit_rate <- c.num_hit_rate + 1
let add c k v =
match HT.find_opt c.table k with
| Some n ->
n.data.value <- v;
add_hit c n;
DList.move_front c.updates n
| None ->
Cache is full
evict_or_resize c;
let n = DList.add_front c.updates (new_data k v) in
HT.add c.table k n
let find c k =
match HT.find_opt c.table k with
| None -> raise Not_found
| Some n -> add_hit c n; DList.move_front c.updates n; n.data.value
let find_opt c k =
match HT.find_opt c.table k with
| None -> None
| Some n -> add_hit c n; DList.move_front c.updates n; Some n.data.value
let mem c k =
match HT.find_opt c.table k with
| None -> false
| Some n -> add_hit c n; DList.move_front c.updates n; true
let iter f c =
HT.iter (fun k n ->
add_hit c n; f k n.data.value
) c.table
let filter_map_inplace f c =
HT.filter_map_inplace (fun k (n : ('a, 'b) node) ->
match f k n.data.value with
| Some v -> add_hit c n; n.data.value <- v; Some n
| None ->
DList.remove c.updates n;
if c.params.min_hits <= n.data.hits then
c.num_hit_rate <- c.num_hit_rate - 1;
None
) c.table
let fold f c init =
HT.fold (fun k n acc ->
add_hit c n; f k n.data.value acc
) c.table init
let length c = HT.length c.table
end
end
|
d16b1422e2e50f75fdd5df754e8e85a51331e340e80d7b7f2ea6bedc18588d8f | RolfRolles/PandemicML | CacheVerifiedResults.ml | open FrameworkUtil
open DataStructures
open Encodable
(* No encoding required *)
let cache_write_binops gc enc s_clobbered size s_vbvi =
VarBinopVarInt32Set.iter
(fun (vr,b,vm,d32) -> GadgetCache.accept_write_binop gc size vr b vm d32 enc s_clobbered)
s_vbvi
let cache_write_binops gc enc s_clobbered s_vbvi_t =
triplicate_iter (cache_write_binops gc enc s_clobbered) s_vbvi_t
(* No encoding required *)
let cache_write_regs gc enc s_clobbered size s_vvi =
VarVarInt32Set.iter
(fun (vr,vm,d32) -> GadgetCache.accept_write_reg gc size vr vm d32 enc s_clobbered)
s_vvi
let cache_write_regs gc enc s_clobbered s_vvi_t =
triplicate_iter (cache_write_regs gc enc s_clobbered) s_vvi_t
(* No encoding required *)
let cache_read_binops gc enc s_clobbered size s_vbvi =
VarBinopVarInt32Set.iter
(fun (vr,b,vm,d32) -> GadgetCache.accept_read_binop gc size vr b vm d32 enc s_clobbered)
s_vbvi
let cache_read_binops gc enc s_clobbered s_vbvi_t =
triplicate_iter (cache_read_binops gc enc s_clobbered) s_vbvi_t
(* No encoding required *)
let cache_read_regs gc enc s_clobbered size s_vvi =
VarVarInt32Set.iter
(fun (vr,vm,d32) -> GadgetCache.accept_read_reg gc size vr vm d32 enc s_clobbered)
s_vvi
let cache_read_regs gc enc s_clobbered s_vvi_t =
triplicate_iter (cache_read_regs gc enc s_clobbered) s_vvi_t
(* No encoding required *)
let cache_reg_binops gc enc s_clobbered size =
VarVarBinopVarSet.iter (fun (vd,vl,b,vr) -> GadgetCache.accept_reg_binop gc size vd vl b vr enc s_clobbered)
let cache_reg_binops gc enc s_clobbered s_vbv_t =
triplicate_iter (cache_reg_binops gc s_clobbered enc) s_vbv_t
(* No encoding required *)
let cache_reg_copies gc enc s_clobbered size =
(* Is this correct? Wrong ordering? *)
VarVarSet.iter (fun (vdst,vsrc) -> GadgetCache.accept_reg_copy gc size vdst vsrc enc s_clobbered)
let cache_reg_copies gc enc s_clobbered s_vv_t =
triplicate_iter (cache_reg_copies gc enc s_clobbered) s_vv_t
let cache_stack_reads gc enc s_clobbered size =
VarInt32Set.iter
(fun (v,d32) ->
let enc = { enc with constant_position = Some(Int32.to_int d32,size); } in
GadgetCache.accept_set_reg_value gc size v enc s_clobbered)
let cache_stack_reads gc enc s_clobbered =
triplicate_iter (cache_stack_reads gc enc s_clobbered)
let deopt f = function | None -> () | Some(s) -> f s
let cache_write_behaviors gc enc ver s_clobbered =
let open VerifyCandidates in
let _ = f_printf "cache_write_behaviors\n%!" in
deopt (cache_write_binops gc enc s_clobbered) ver.write_binops;
deopt (cache_write_regs gc enc s_clobbered) ver.mem_write_reg;
()
let cache_read_behaviors gc enc ver s_clobbered =
let open VerifyCandidates in
let _ = f_printf "cache_read_behaviors\n%!" in
deopt (cache_read_binops gc enc s_clobbered) ver.read_binops;
deopt (cache_read_regs gc enc s_clobbered) ver.mem_read_const;
()
let cache_reg_and_stack_behaviors gc enc ver s_clobbered =
let open VerifyCandidates in
let _ = f_printf "cache_reg_and_stack_behaviors\n%!" in
deopt (cache_reg_binops gc enc s_clobbered) ver.reg_binops;
deopt (cache_reg_copies gc enc s_clobbered) ver.copied_regs;
deopt (cache_stack_reads gc enc s_clobbered) ver.esp_read_const;
()
Basically , we want to reject if :
- write to the stack , OR
- write to the stack binop , OR
- read from the stack binop ( could maybe allow this later ) , OR
- write to multiple locations ( could just immediately reject if the number of writes is greater than one ) , OR
- if it reads and writes , the latter not is a subset of the former ( done ) , OR
- write to the stack, OR
- write to the stack binop, OR
- read from the stack binop (could maybe allow this later), OR
- write to multiple locations (could just immediately reject if the number of writes is greater than one), OR
- if it reads and writes, the latter not is a subset of the former (done), OR
*)
let cache_verified_results gc ver x86l =
(* Some syntax sugar to make the checks below shorter. *)
let vie_t t = let e = VarInt32Set.is_empty in e t.val32 && e t.val16 && e t.val8 in
let vvie_t t = let e = VarVarInt32Set.is_empty in e t.val32 && e t.val16 && e t.val8 in
let vbvie_t t = let e = VarBinopVarInt32Set.is_empty in e t.val32 && e t.val16 && e t.val8 in
let vbie_t t = let e = VarBinopInt32Set.is_empty in e t.val32 && e t.val16 && e t.val8 in
let wrap f = function | Some(x) -> f x | None -> true in
(* Determine the presence of memory read / write operations *)
let open VerifyCandidates in
let b_stack_write_binops = not (wrap vbie_t ver.write_esp_binops) in
let b_stack_writes = not (wrap vie_t ver.esp_write_reg) in
let b_mem_write_binops = not (wrap vbvie_t ver.write_binops) in
let b_mem_writes = not (wrap vvie_t ver.mem_write_reg) in
let b_stack_read_binops = not (wrap vbie_t ver.read_esp_binops) in
let b_stack_reads = not (wrap vie_t ver.esp_read_const) in
let b_mem_read_binops = not (wrap vbvie_t ver.read_binops) in
let b_mem_reads = not (wrap vvie_t ver.mem_read_const) in
(* Compute some statistics about the gadget necessary for encoding and
further synthesis *)
let framesize = Int32.to_int ver.stack_displacement in
let retpos = Int32.to_int ver.return_address_displacement in
let enc = mk_encodable x86l ver.addresses framesize retpos in
let s_clobbered = X86ToIRUtil.s_general_registers_noesp_nosp in
let s_clobbered =
fold_triple
(fun x -> x)
(fun x y -> IRUtil.VarSet.diff y x)
s_clobbered
ver.preserved_regs
in
(* Exclude writes to the stack and binops that read from the stack. Could
potentially use stack binops at a later time. *)
if (b_stack_write_binops || b_stack_writes || b_stack_read_binops)
then (f_printf "Rejected due to stack writes / stack read binops\n%!"; ())
else
begin
(* If gadget has write behaviors, use those and nothing else. This is so
we don't use something that writes to memory as a more innocuous gadget
that will not cause a memory fault if used spuriously. *)
if (b_mem_write_binops || b_mem_writes)
then cache_write_behaviors gc enc ver s_clobbered
else
begin
(* If gadget has read behaviors, use those for similar reasons.
Supposedly, by a check that I put in in the verification module,
write behaviors will be preferred over read ones but this is OK
since the reads are a subset of the writes. *)
if (b_mem_read_binops || b_mem_reads)
then cache_read_behaviors gc enc ver s_clobbered
(* If it does not have memory behaviors, then deal with its ordinary
register-based behaviors. *)
else cache_reg_and_stack_behaviors gc enc ver s_clobbered
end
end
| null | https://raw.githubusercontent.com/RolfRolles/PandemicML/9c31ecaf9c782dbbeb6cf502bc2a6730316d681e/Projects/Nxcroticism/CacheVerifiedResults.ml | ocaml | No encoding required
No encoding required
No encoding required
No encoding required
No encoding required
No encoding required
Is this correct? Wrong ordering?
Some syntax sugar to make the checks below shorter.
Determine the presence of memory read / write operations
Compute some statistics about the gadget necessary for encoding and
further synthesis
Exclude writes to the stack and binops that read from the stack. Could
potentially use stack binops at a later time.
If gadget has write behaviors, use those and nothing else. This is so
we don't use something that writes to memory as a more innocuous gadget
that will not cause a memory fault if used spuriously.
If gadget has read behaviors, use those for similar reasons.
Supposedly, by a check that I put in in the verification module,
write behaviors will be preferred over read ones but this is OK
since the reads are a subset of the writes.
If it does not have memory behaviors, then deal with its ordinary
register-based behaviors. | open FrameworkUtil
open DataStructures
open Encodable
let cache_write_binops gc enc s_clobbered size s_vbvi =
VarBinopVarInt32Set.iter
(fun (vr,b,vm,d32) -> GadgetCache.accept_write_binop gc size vr b vm d32 enc s_clobbered)
s_vbvi
let cache_write_binops gc enc s_clobbered s_vbvi_t =
triplicate_iter (cache_write_binops gc enc s_clobbered) s_vbvi_t
let cache_write_regs gc enc s_clobbered size s_vvi =
VarVarInt32Set.iter
(fun (vr,vm,d32) -> GadgetCache.accept_write_reg gc size vr vm d32 enc s_clobbered)
s_vvi
let cache_write_regs gc enc s_clobbered s_vvi_t =
triplicate_iter (cache_write_regs gc enc s_clobbered) s_vvi_t
let cache_read_binops gc enc s_clobbered size s_vbvi =
VarBinopVarInt32Set.iter
(fun (vr,b,vm,d32) -> GadgetCache.accept_read_binop gc size vr b vm d32 enc s_clobbered)
s_vbvi
let cache_read_binops gc enc s_clobbered s_vbvi_t =
triplicate_iter (cache_read_binops gc enc s_clobbered) s_vbvi_t
let cache_read_regs gc enc s_clobbered size s_vvi =
VarVarInt32Set.iter
(fun (vr,vm,d32) -> GadgetCache.accept_read_reg gc size vr vm d32 enc s_clobbered)
s_vvi
let cache_read_regs gc enc s_clobbered s_vvi_t =
triplicate_iter (cache_read_regs gc enc s_clobbered) s_vvi_t
let cache_reg_binops gc enc s_clobbered size =
VarVarBinopVarSet.iter (fun (vd,vl,b,vr) -> GadgetCache.accept_reg_binop gc size vd vl b vr enc s_clobbered)
let cache_reg_binops gc enc s_clobbered s_vbv_t =
triplicate_iter (cache_reg_binops gc s_clobbered enc) s_vbv_t
let cache_reg_copies gc enc s_clobbered size =
VarVarSet.iter (fun (vdst,vsrc) -> GadgetCache.accept_reg_copy gc size vdst vsrc enc s_clobbered)
let cache_reg_copies gc enc s_clobbered s_vv_t =
triplicate_iter (cache_reg_copies gc enc s_clobbered) s_vv_t
let cache_stack_reads gc enc s_clobbered size =
VarInt32Set.iter
(fun (v,d32) ->
let enc = { enc with constant_position = Some(Int32.to_int d32,size); } in
GadgetCache.accept_set_reg_value gc size v enc s_clobbered)
let cache_stack_reads gc enc s_clobbered =
triplicate_iter (cache_stack_reads gc enc s_clobbered)
let deopt f = function | None -> () | Some(s) -> f s
let cache_write_behaviors gc enc ver s_clobbered =
let open VerifyCandidates in
let _ = f_printf "cache_write_behaviors\n%!" in
deopt (cache_write_binops gc enc s_clobbered) ver.write_binops;
deopt (cache_write_regs gc enc s_clobbered) ver.mem_write_reg;
()
let cache_read_behaviors gc enc ver s_clobbered =
let open VerifyCandidates in
let _ = f_printf "cache_read_behaviors\n%!" in
deopt (cache_read_binops gc enc s_clobbered) ver.read_binops;
deopt (cache_read_regs gc enc s_clobbered) ver.mem_read_const;
()
let cache_reg_and_stack_behaviors gc enc ver s_clobbered =
let open VerifyCandidates in
let _ = f_printf "cache_reg_and_stack_behaviors\n%!" in
deopt (cache_reg_binops gc enc s_clobbered) ver.reg_binops;
deopt (cache_reg_copies gc enc s_clobbered) ver.copied_regs;
deopt (cache_stack_reads gc enc s_clobbered) ver.esp_read_const;
()
Basically , we want to reject if :
- write to the stack , OR
- write to the stack binop , OR
- read from the stack binop ( could maybe allow this later ) , OR
- write to multiple locations ( could just immediately reject if the number of writes is greater than one ) , OR
- if it reads and writes , the latter not is a subset of the former ( done ) , OR
- write to the stack, OR
- write to the stack binop, OR
- read from the stack binop (could maybe allow this later), OR
- write to multiple locations (could just immediately reject if the number of writes is greater than one), OR
- if it reads and writes, the latter not is a subset of the former (done), OR
*)
let cache_verified_results gc ver x86l =
let vie_t t = let e = VarInt32Set.is_empty in e t.val32 && e t.val16 && e t.val8 in
let vvie_t t = let e = VarVarInt32Set.is_empty in e t.val32 && e t.val16 && e t.val8 in
let vbvie_t t = let e = VarBinopVarInt32Set.is_empty in e t.val32 && e t.val16 && e t.val8 in
let vbie_t t = let e = VarBinopInt32Set.is_empty in e t.val32 && e t.val16 && e t.val8 in
let wrap f = function | Some(x) -> f x | None -> true in
let open VerifyCandidates in
let b_stack_write_binops = not (wrap vbie_t ver.write_esp_binops) in
let b_stack_writes = not (wrap vie_t ver.esp_write_reg) in
let b_mem_write_binops = not (wrap vbvie_t ver.write_binops) in
let b_mem_writes = not (wrap vvie_t ver.mem_write_reg) in
let b_stack_read_binops = not (wrap vbie_t ver.read_esp_binops) in
let b_stack_reads = not (wrap vie_t ver.esp_read_const) in
let b_mem_read_binops = not (wrap vbvie_t ver.read_binops) in
let b_mem_reads = not (wrap vvie_t ver.mem_read_const) in
let framesize = Int32.to_int ver.stack_displacement in
let retpos = Int32.to_int ver.return_address_displacement in
let enc = mk_encodable x86l ver.addresses framesize retpos in
let s_clobbered = X86ToIRUtil.s_general_registers_noesp_nosp in
let s_clobbered =
fold_triple
(fun x -> x)
(fun x y -> IRUtil.VarSet.diff y x)
s_clobbered
ver.preserved_regs
in
if (b_stack_write_binops || b_stack_writes || b_stack_read_binops)
then (f_printf "Rejected due to stack writes / stack read binops\n%!"; ())
else
begin
if (b_mem_write_binops || b_mem_writes)
then cache_write_behaviors gc enc ver s_clobbered
else
begin
if (b_mem_read_binops || b_mem_reads)
then cache_read_behaviors gc enc ver s_clobbered
else cache_reg_and_stack_behaviors gc enc ver s_clobbered
end
end
|
5130bd85b9776ec85988b20a83741b888e2325da1a835eb16152adf73ba0138a | vouch-opensource/krell | deps.clj | (ns krell.deps
(:require [cljs.analyzer.api :as ana-api]
[cljs.compiler.api :as comp-api]
[cljs.build.api :as build-api]
[cljs.closure :as closure]
[cljs.module-graph :as mg]
[cljs.repl :as repl]
[clojure.java.io :as io]
[krell.util :as util])
(:import [java.io File]))
(defn all-deps
"Returns a unsorted sequence of all dependencies for a namespace."
[state ns opts]
(let [ijs (mg/normalize-input (repl/ns->input ns opts))]
(ana-api/with-state state
(map mg/normalize-input
(closure/add-js-sources
(build-api/add-dependency-sources state [ijs] opts)
opts)))))
(defn deps->graph
"Given a sequence of namespace descriptor maps, returns a map representing
the dependency graph. Because some libraries can have multiple provides the
entries will often represent the same dependency. Deduplication may be
required."
[deps]
(reduce
(fn [acc dep]
(reduce
(fn [acc provide]
(assoc acc provide dep))
acc (:provides dep)))
{} deps))
(defn topo-sort
"Give a dep graph return the topologically sorted sequence of inputs."
[graph]
(let [sorted-keys (mg/topo-sort graph :requires)]
(distinct (map graph sorted-keys))))
(defn sorted-deps
"Given a compiler state, a ns symbol, and ClojureScript compiler options,
return a topologically sorted sequence of all the dependencies."
[state ns opts]
(let [all (all-deps state ns opts)
graph (deps->graph all)]
(topo-sort graph)))
(defn get-out-file ^File [dep opts]
(io/file
(if (:ns dep)
(build-api/src-file->target-file (:source-file dep) opts)
(io/file (:output-dir opts) (closure/rel-output-path dep)))))
(defn add-out-file [dep opts]
(let [out-file (get-out-file dep opts)]
(merge dep
{:out-file out-file}
(when (.exists out-file)
{:modified (util/last-modified out-file)}))))
(defn with-out-files
"Given a list of deps return a new list of deps with :out-file property
on each value."
[deps opts]
(into [] (map #(add-out-file % opts)) deps))
(defn ^:dynamic dependents*
([ns graph]
(dependents* ns graph :direct))
([ns graph mode]
(let [graph' (->> (filter
(fn [[k v]]
(some #{ns} (:requires v)))
graph)
(into {}))]
(condp = mode
:direct graph'
:all
(reduce
(fn [ret x]
(merge ret (dependents* x graph)))
graph' (keys graph'))
(throw (ex-info (str "Unsupported :mode, " mode) {}))))))
(defn dependents
"Given an ns symbol and a dependency graph return a topologically sorted
sequence of all ancestors."
([ns graph]
(dependents ns graph :direct))
([ns graph mode]
(topo-sort
(binding [dependents* (memoize dependents*)]
(dependents* (-> ns comp-api/munge str) graph mode)))))
| null | https://raw.githubusercontent.com/vouch-opensource/krell/61546493f3891d5603f3d2fbd03662230e9e6ee6/src/krell/deps.clj | clojure | (ns krell.deps
(:require [cljs.analyzer.api :as ana-api]
[cljs.compiler.api :as comp-api]
[cljs.build.api :as build-api]
[cljs.closure :as closure]
[cljs.module-graph :as mg]
[cljs.repl :as repl]
[clojure.java.io :as io]
[krell.util :as util])
(:import [java.io File]))
(defn all-deps
"Returns a unsorted sequence of all dependencies for a namespace."
[state ns opts]
(let [ijs (mg/normalize-input (repl/ns->input ns opts))]
(ana-api/with-state state
(map mg/normalize-input
(closure/add-js-sources
(build-api/add-dependency-sources state [ijs] opts)
opts)))))
(defn deps->graph
"Given a sequence of namespace descriptor maps, returns a map representing
the dependency graph. Because some libraries can have multiple provides the
entries will often represent the same dependency. Deduplication may be
required."
[deps]
(reduce
(fn [acc dep]
(reduce
(fn [acc provide]
(assoc acc provide dep))
acc (:provides dep)))
{} deps))
(defn topo-sort
"Give a dep graph return the topologically sorted sequence of inputs."
[graph]
(let [sorted-keys (mg/topo-sort graph :requires)]
(distinct (map graph sorted-keys))))
(defn sorted-deps
"Given a compiler state, a ns symbol, and ClojureScript compiler options,
return a topologically sorted sequence of all the dependencies."
[state ns opts]
(let [all (all-deps state ns opts)
graph (deps->graph all)]
(topo-sort graph)))
(defn get-out-file ^File [dep opts]
(io/file
(if (:ns dep)
(build-api/src-file->target-file (:source-file dep) opts)
(io/file (:output-dir opts) (closure/rel-output-path dep)))))
(defn add-out-file [dep opts]
(let [out-file (get-out-file dep opts)]
(merge dep
{:out-file out-file}
(when (.exists out-file)
{:modified (util/last-modified out-file)}))))
(defn with-out-files
"Given a list of deps return a new list of deps with :out-file property
on each value."
[deps opts]
(into [] (map #(add-out-file % opts)) deps))
(defn ^:dynamic dependents*
([ns graph]
(dependents* ns graph :direct))
([ns graph mode]
(let [graph' (->> (filter
(fn [[k v]]
(some #{ns} (:requires v)))
graph)
(into {}))]
(condp = mode
:direct graph'
:all
(reduce
(fn [ret x]
(merge ret (dependents* x graph)))
graph' (keys graph'))
(throw (ex-info (str "Unsupported :mode, " mode) {}))))))
(defn dependents
"Given an ns symbol and a dependency graph return a topologically sorted
sequence of all ancestors."
([ns graph]
(dependents ns graph :direct))
([ns graph mode]
(topo-sort
(binding [dependents* (memoize dependents*)]
(dependents* (-> ns comp-api/munge str) graph mode)))))
| |
984773fa3a8f69232702d28b37f1f499357403bddc15362d98c7d81448bfd216 | kowey/GenI | geni.hs | -- GenI surface realiser
Copyright ( C ) 2005 and
--
-- This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version 2
of the License , or ( at your option ) any later version .
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
module Main (module NLP.GenI.Main) where
import NLP.GenI.Main
| null | https://raw.githubusercontent.com/kowey/GenI/570a6ef70e61a7cb01fe0fc29732cd9c1c8f2d7a/geni/geni.hs | haskell | GenI surface realiser
This program is free software; you can redistribute it and/or
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program; if not, write to the Free Software | Copyright ( C ) 2005 and
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 .
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
module Main (module NLP.GenI.Main) where
import NLP.GenI.Main
|
d86ae0117a0defdc921433c8aba2a57e8484281e918f6c116beddebc85f51018 | amnh/ocamion | multiOptimize.mli | * { 1 Numerical Optimization Module }
This module unifies the signatures of the multi - dimensional optimization
routines by hiding and exploiting defaults to the functions in question .
This is used when one would like to test the efficacy of the functions
easily .
Accessing the optimization routines directly may allow better control over
the routine , but this module takes care of most of the parameters . Further
details of these routines can be found in their individual modules . The
[ all ] value contains a list of the contained modules .
This module unifies the signatures of the multi-dimensional optimization
routines by hiding and exploiting defaults to the functions in question.
This is used when one would like to test the efficacy of the functions
easily.
Accessing the optimization routines directly may allow better control over
the routine, but this module takes care of most of the parameters. Further
details of these routines can be found in their individual modules. The
[all] value contains a list of the contained modules. *)
(** {2 Types} *)
(** Define a module containing a single function to optimize a function. *)
module type MOPT =
sig
val name : string
val optimize :
?max_iter:int -> ?tol:float -> f:(float array -> 'a * float) ->
(float array * ('a * float)) -> (float array * ('a * float))
end
(* {2 Implementations} *)
(** Broyden-Fletcher-Goldfarb-Shanno method *)
module Bfgs : MOPT
(** Brents method with multiple dimensions *)
module BrentMulti : MOPT
(** The Simplex method *)
module Simplex : MOPT
* The method
module Subplex : MOPT
* { 2 Values }
(** A list of all the methods above. *)
val all : (module MOPT) list
| null | https://raw.githubusercontent.com/amnh/ocamion/699c2471b7fdac12f061cf24b588f9eef5bf5cb8/lib/multiOptimize.mli | ocaml | * {2 Types}
* Define a module containing a single function to optimize a function.
{2 Implementations}
* Broyden-Fletcher-Goldfarb-Shanno method
* Brents method with multiple dimensions
* The Simplex method
* A list of all the methods above. | * { 1 Numerical Optimization Module }
This module unifies the signatures of the multi - dimensional optimization
routines by hiding and exploiting defaults to the functions in question .
This is used when one would like to test the efficacy of the functions
easily .
Accessing the optimization routines directly may allow better control over
the routine , but this module takes care of most of the parameters . Further
details of these routines can be found in their individual modules . The
[ all ] value contains a list of the contained modules .
This module unifies the signatures of the multi-dimensional optimization
routines by hiding and exploiting defaults to the functions in question.
This is used when one would like to test the efficacy of the functions
easily.
Accessing the optimization routines directly may allow better control over
the routine, but this module takes care of most of the parameters. Further
details of these routines can be found in their individual modules. The
[all] value contains a list of the contained modules. *)
module type MOPT =
sig
val name : string
val optimize :
?max_iter:int -> ?tol:float -> f:(float array -> 'a * float) ->
(float array * ('a * float)) -> (float array * ('a * float))
end
module Bfgs : MOPT
module BrentMulti : MOPT
module Simplex : MOPT
* The method
module Subplex : MOPT
* { 2 Values }
val all : (module MOPT) list
|
c3f257ba2841182d46148bd212e19bdc102e7d55f1e3d971cfe6c351a83762f5 | barrucadu/dejafu | SingleThreaded.hs | # LANGUAGE FlexibleContexts #
module Integration.SingleThreaded where
import Control.Exception (ArithException(..),
ArrayException(..),
MaskingState(..))
import Test.DejaFu (Condition(..), gives, gives',
inspectIORef, inspectMVar,
inspectTVar, isDeadlock,
isInvariantFailure,
isUncaughtException,
registerInvariant, withSetup)
import Control.Concurrent.Classy
import Control.Monad (replicateM_, when)
import Control.Monad.Catch (throwM)
import Control.Monad.Fail (MonadFail)
import Control.Monad.IO.Class (liftIO)
import qualified Data.IORef as IORef
import Data.Maybe (isNothing)
import System.Random (mkStdGen)
import Common
tests :: [TestTree]
tests =
[ testGroup "MVar" mvarTests
, testGroup "IORef" iorefTests
, testGroup "STM" stmTests
, testGroup "Exceptions" exceptionTests
, testGroup "Capabilities" capabilityTests
, testGroup "Program" programTests
, testGroup "IO" ioTests
]
--------------------------------------------------------------------------------
mvarTests :: [TestTree]
mvarTests = toTestList
[ djfu "Taking from an empty MVar blocks" (gives [Left Deadlock]) $ do
var <- newEmptyMVarInt
takeMVar var
, djfu "Non-blockingly taking from an empty MVar gives nothing" (gives' [Nothing]) $ do
var <- newEmptyMVarInt
tryTakeMVar var
, djfu "Putting into an empty MVar updates it" (gives' [True]) $ do
var <- newEmptyMVarInt
putMVar var 7
(==7) <$> readMVar var
, djfu "Non-blockingly putting into an empty MVar updates it" (gives' [True]) $ do
var <- newEmptyMVarInt
_ <- tryPutMVar var 7
(==7) <$> readMVar var
, djfu "Reading an empty MVar blocks" (gives [Left Deadlock]) $ do
var <- newEmptyMVarInt
readMVar var
, djfu "Non-blockingly reading an empty MVar gives nothing" (gives' [Nothing]) $ do
var <- newEmptyMVarInt
tryReadMVar var
, djfu "Putting into a full MVar blocks" (gives [Left Deadlock]) $ do
var <- newMVarInt 7
putMVar var 10
, djfu "Non-blockingly putting into a full MVar fails" (gives' [False]) $ do
var <- newMVarInt 7
tryPutMVar var 10
, djfu "Taking from a full MVar works" (gives' [True]) $ do
var <- newMVarInt 7
(==7) <$> takeMVar var
, djfu "Non-blockingly taking from a full MVar works" (gives' [True]) $ do
var <- newMVarInt 7
(==Just 7) <$> tryTakeMVar var
, djfu "Reading a full MVar works" (gives' [True]) $ do
var <- newMVarInt 7
(==7) <$> readMVar var
, djfu "Non-blockingly reading a full MVar works" (gives' [True]) $ do
var <- newMVarInt 7
(==Just 7) <$> tryReadMVar var
]
--------------------------------------------------------------------------------
iorefTests :: [TestTree]
iorefTests = toTestList
[ djfu "Reading a non-updated IORef gives its initial value" (gives' [True]) $ do
ref <- newIORefInt 5
(5==) <$> readIORef ref
, djfu "Reading an updated IORef gives its new value" (gives' [True]) $ do
ref <- newIORefInt 5
writeIORef ref 6
(6==) <$> readIORef ref
, djfu "Updating a IORef by a function changes its value" (gives' [True]) $ do
ref <- newIORefInt 5
atomicModifyIORef ref (\i -> (i+1, ()))
(6==) <$> readIORef ref
, djfu "A ticket contains the value of the IORef at the time of its creation" (gives' [True]) $ do
ref <- newIORefInt 5
tick <- readForCAS ref
writeIORef ref 6
(5==) <$> peekTicket tick
, djfu "Compare-and-swap returns a ticket containing the new value" (gives' [True]) $ do
ref <- newIORefInt 5
tick <- readForCAS ref
(_, tick') <- casIORef ref tick 6
(6==) <$> peekTicket tick'
, djfu "Compare-and-swap on an unmodified IORef succeeds" (gives' [True]) $ do
ref <- newIORefInt 5
tick <- readForCAS ref
(suc, _) <- casIORef ref tick 6
val <- readIORef ref
pure (suc && (6 == val))
, djfu "Compare-and-swap on a modified IORef fails" (gives' [True]) $ do
ref <- newIORefInt 5
tick <- readForCAS ref
writeIORef ref 6
(suc, _) <- casIORef ref tick 7
val <- readIORef ref
pure (not suc && 7 /= val)
]
--------------------------------------------------------------------------------
stmTests :: [TestTree]
stmTests = toTestList
[ djfu "When a TVar is updated, its new value is visible later in same transaction" (gives' [True]) $
(6==) <$> atomically (do { v <- newTVarInt 5; writeTVar v 6; readTVar v })
, djfu "When a TVar is updated, its new value is visible in a later transaction" (gives' [True]) $ do
ctv <- atomically $ newTVarInt 5
(5==) <$> readTVarConc ctv
, djfu "Aborting a transaction blocks the thread" (gives [Left Deadlock])
(atomically retry :: MonadConc m => m ()) -- avoid an ambiguous type
, djfu "Aborting a transaction can be caught and recovered from" (gives' [True]) $ do
ctv <- atomically $ newTVarInt 5
atomically $ orElse retry (writeTVar ctv 6)
(6==) <$> readTVarConc ctv
, djfu "An exception thrown in a transaction can be caught" (gives' [True]) $ do
ctv <- atomically $ newTVarInt 5
atomically $ catchArithException
(throwSTM Overflow)
(\_ -> writeTVar ctv 6)
(6==) <$> readTVarConc ctv
, djfu "Nested exception handlers in transactions work" (gives' [True]) $ do
ctv <- atomically $ newTVarInt 5
atomically $ catchArithException
(catchArrayException
(throwSTM Overflow)
(\_ -> writeTVar ctv 0))
(\_ -> writeTVar ctv 6)
(6==) <$> readTVarConc ctv
, djfu "MonadSTM is a MonadFail" (alwaysFailsWith isUncaughtException)
(atomically $ fail "hello world" :: (MonadConc m, MonadFail (STM m)) => m ()) -- avoid an ambiguous type
, djfu "'retry' is not caught by 'catch'" (gives' [True]) $
atomically
((retry `catchSomeException` \_ -> pure False) `orElse` pure True)
, djfu "'throw' is not caught by 'orElse'" (gives' [True]) $
atomically
((throwSTM Overflow `orElse` pure False) `catchSomeException` \_ -> pure True)
, djfu "'retry' in a nested 'orElse' only aborts the innermost" (gives' [True]) $
atomically
((retry `orElse` pure True) `orElse` pure False)
]
--------------------------------------------------------------------------------
exceptionTests :: [TestTree]
exceptionTests = toTestList
[ djfu "An exception thrown can be caught" (gives' [True]) $
catchArithException
(throw Overflow)
(\_ -> pure True)
, djfu "Nested exception handlers work" (gives' [True]) $
catchArithException
(catchArrayException
(throw Overflow)
(\_ -> pure False))
(\_ -> pure True)
, djfu "Uncaught exceptions kill the computation" (alwaysFailsWith isUncaughtException) $
catchArithException
(throw $ IndexOutOfBounds "")
(\_ -> pure False)
, djfu "SomeException matches all exception types" (gives' [True]) $ do
a <- catchSomeException
(throw Overflow)
(\_ -> pure True)
b <- catchSomeException
(throw $ IndexOutOfBounds "")
(\_ -> pure True)
pure (a && b)
, djfu "Exceptions thrown in a transaction can be caught outside it" (gives' [True]) $
catchArithException
(atomically $ throwSTM Overflow)
(\_ -> pure True)
, djfu "Throwing an unhandled exception to the main thread kills it" (alwaysFailsWith isUncaughtException) $ do
tid <- myThreadId
throwTo tid Overflow
, djfu "Throwing a handled exception to the main thread does not kill it" (gives' [True]) $ do
tid <- myThreadId
catchArithException (throwTo tid Overflow >> pure False) (\_ -> pure True)
, djfu "MonadConc is a MonadFail" (alwaysFailsWith isUncaughtException)
(fail "hello world" :: (MonadConc m, MonadFail m) => m ()) -- avoid an ambiguous type
, djfu "Masking state is changed by a mask" (gives' [MaskedInterruptible]) $
mask_ getMaskingState
, djfu "Masking state is reset after the mask ends" (gives' [Unmasked]) $
mask_ getMaskingState >> getMaskingState
]
--------------------------------------------------------------------------------
capabilityTests :: [TestTree]
capabilityTests = toTestList
[ djfu "Reading the capabilities twice without update gives the same result" (gives' [True]) $ do
c1 <- getNumCapabilities
c2 <- getNumCapabilities
pure (c1 == c2)
, djfu "Getting the updated capabilities gives the new value" (gives' [True]) $ do
caps <- getNumCapabilities
setNumCapabilities (caps + 1)
(== caps + 1) <$> getNumCapabilities
]
--------------------------------------------------------------------------------
programTests :: [TestTree]
programTests = toTestList
[ testGroup "withSetup"
[ djfu "Inner state modifications are visible to the outside" (gives' [True]) $
withSetup
(do inner <- newEmptyMVarInt
putMVar inner 5
pure inner)
(fmap (==5) . takeMVar)
, djfu "Failures abort the whole computation" (alwaysFailsWith isDeadlock) $
withSetup (takeMVar =<< newEmptyMVarInt) (\_ -> pure True)
-- we use 'randomly' here because we specifically want to compare
-- multiple executions with snapshotting
, toTestList . testGroup "Snapshotting" $ let snapshotTest n p conc = W n conc p ("randomly", randomly (mkStdGen 0) 150) in
[ snapshotTest "State updates are applied correctly" (gives' [2]) $
withSetup
(do r <- newIORefInt 0
writeIORef r 1
writeIORef r 2
pure r)
readIORef
, snapshotTest "Lifted IO is re-run (1)" (gives' [2..151]) $
withSetup
(do r <- liftIO (IORef.newIORef (0::Int))
liftIO (IORef.modifyIORef r (+1))
pure r)
(liftIO . IORef.readIORef)
, snapshotTest "Lifted IO is re-run (2)" (gives' [1]) $
withSetup
(do let modify r f = liftIO (IORef.readIORef r) >>= liftIO . IORef.writeIORef r . f
r <- liftIO (IORef.newIORef (0::Int))
modify r (+1)
pure r)
(liftIO . IORef.readIORef)
, snapshotTest "Lifted IO is re-run (3)" (gives' [1]) $
withSetup
(do r <- liftIO (IORef.newIORef (0::Int))
liftIO (IORef.writeIORef r 0)
liftIO (IORef.modifyIORef r (+1))
pure r)
(liftIO . IORef.readIORef)
]
]
, testGroup "withSetupAndTeardown"
[ djfuS "Failures can be observed" (gives' [True]) $
withSetupAndTeardown
(pure ())
(\_ -> pure . either (== Deadlock) (const False))
(\_ -> newEmptyMVar >>= readMVar)
, djfuS "Teardown always happens" (gives' [True]) $
withSetupAndTeardown
(newMVarInt 0)
(\var x -> do
y <- readMVar var
pure (either (==Deadlock) (const False) x && y == 0))
(\var -> putMVar var 1)
, djfuS "Non-failing inner action returns the final result" (gives' [True]) $
withSetupAndTeardown
(newMVarInt 3)
(\_ x -> pure (either (const False) (==3) x))
takeMVar
]
, testGroup "registerInvariant"
[ djfuS "An uncaught exception fails an invariant" (alwaysFailsWith isInvariantFailure) $
withSetup (registerInvariant (throwM Overflow)) $
\() -> pure True
, djfuS "An invariant which never throws always passes" (gives' [True]) $
withSetup (registerInvariant (pure ())) $
\() -> pure True
, djfuS "An invariant can catch exceptions" (gives' [True]) $
withSetup (registerInvariant (throwM Overflow `catchArithException` \_ -> pure ())) $
\() -> pure True
, djfuS "Invariants can read MVars" (alwaysFailsWith isInvariantFailure) $
withSetup
(do v <- newMVarInt 10
registerInvariant (inspectMVar v >>= \x -> when (isNothing x) (throwM Overflow))
pure v)
takeMVar
, djfuS "Invariants can read TVars" (alwaysFailsWith isInvariantFailure) $
withSetup
(do v <- atomically (newTVar (10::Int))
registerInvariant (inspectTVar v >>= \x -> when (x < 5) (throwM Overflow))
pure v)
(\v -> atomically (writeTVar v 1))
, djfuS "Invariants aren't checked in the setup" (gives' [True]) $
withSetup
(do v <- newIORefInt 10
registerInvariant (inspectIORef v >>= \x -> when (x < 5) (throwM Overflow))
writeIORef v 1
writeIORef v 10)
(\_ -> pure True)
, djfuS "Invariants aren't checked in the teardown" (gives' [True]) $
withSetupAndTeardown
(do v <- newIORefInt 10
registerInvariant (inspectIORef v >>= \x -> when (x < 5) (throwM Overflow))
pure v)
(\v _ -> do
writeIORef v 1
writeIORef v 10
pure True)
(\_ -> pure ())
, djfuS "Invariants aren't checked if added in the main phase" (gives' [True]) $ do
v <- newIORefInt 10
registerInvariant (inspectIORef v >>= \x -> when (x < 5) (throwM Overflow))
writeIORef v 1
pure True
]
]
-------------------------------------------------------------------------------
ioTests :: [TestTree]
ioTests = toTestList
[ djfu "Lifted IO is performed" (gives' [3]) $ do
r <- liftIO (IORef.newIORef (0::Int))
replicateM_ 3 (liftIO (IORef.atomicModifyIORef r (\i -> (i+1, ()))))
liftIO (IORef.readIORef r)
]
| null | https://raw.githubusercontent.com/barrucadu/dejafu/f805783398e2be60ebabb56fce9f23506b9d1879/dejafu-tests/lib/Integration/SingleThreaded.hs | haskell | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
avoid an ambiguous type
avoid an ambiguous type
------------------------------------------------------------------------------
avoid an ambiguous type
------------------------------------------------------------------------------
------------------------------------------------------------------------------
we use 'randomly' here because we specifically want to compare
multiple executions with snapshotting
----------------------------------------------------------------------------- | # LANGUAGE FlexibleContexts #
module Integration.SingleThreaded where
import Control.Exception (ArithException(..),
ArrayException(..),
MaskingState(..))
import Test.DejaFu (Condition(..), gives, gives',
inspectIORef, inspectMVar,
inspectTVar, isDeadlock,
isInvariantFailure,
isUncaughtException,
registerInvariant, withSetup)
import Control.Concurrent.Classy
import Control.Monad (replicateM_, when)
import Control.Monad.Catch (throwM)
import Control.Monad.Fail (MonadFail)
import Control.Monad.IO.Class (liftIO)
import qualified Data.IORef as IORef
import Data.Maybe (isNothing)
import System.Random (mkStdGen)
import Common
tests :: [TestTree]
tests =
[ testGroup "MVar" mvarTests
, testGroup "IORef" iorefTests
, testGroup "STM" stmTests
, testGroup "Exceptions" exceptionTests
, testGroup "Capabilities" capabilityTests
, testGroup "Program" programTests
, testGroup "IO" ioTests
]
mvarTests :: [TestTree]
mvarTests = toTestList
[ djfu "Taking from an empty MVar blocks" (gives [Left Deadlock]) $ do
var <- newEmptyMVarInt
takeMVar var
, djfu "Non-blockingly taking from an empty MVar gives nothing" (gives' [Nothing]) $ do
var <- newEmptyMVarInt
tryTakeMVar var
, djfu "Putting into an empty MVar updates it" (gives' [True]) $ do
var <- newEmptyMVarInt
putMVar var 7
(==7) <$> readMVar var
, djfu "Non-blockingly putting into an empty MVar updates it" (gives' [True]) $ do
var <- newEmptyMVarInt
_ <- tryPutMVar var 7
(==7) <$> readMVar var
, djfu "Reading an empty MVar blocks" (gives [Left Deadlock]) $ do
var <- newEmptyMVarInt
readMVar var
, djfu "Non-blockingly reading an empty MVar gives nothing" (gives' [Nothing]) $ do
var <- newEmptyMVarInt
tryReadMVar var
, djfu "Putting into a full MVar blocks" (gives [Left Deadlock]) $ do
var <- newMVarInt 7
putMVar var 10
, djfu "Non-blockingly putting into a full MVar fails" (gives' [False]) $ do
var <- newMVarInt 7
tryPutMVar var 10
, djfu "Taking from a full MVar works" (gives' [True]) $ do
var <- newMVarInt 7
(==7) <$> takeMVar var
, djfu "Non-blockingly taking from a full MVar works" (gives' [True]) $ do
var <- newMVarInt 7
(==Just 7) <$> tryTakeMVar var
, djfu "Reading a full MVar works" (gives' [True]) $ do
var <- newMVarInt 7
(==7) <$> readMVar var
, djfu "Non-blockingly reading a full MVar works" (gives' [True]) $ do
var <- newMVarInt 7
(==Just 7) <$> tryReadMVar var
]
iorefTests :: [TestTree]
iorefTests = toTestList
[ djfu "Reading a non-updated IORef gives its initial value" (gives' [True]) $ do
ref <- newIORefInt 5
(5==) <$> readIORef ref
, djfu "Reading an updated IORef gives its new value" (gives' [True]) $ do
ref <- newIORefInt 5
writeIORef ref 6
(6==) <$> readIORef ref
, djfu "Updating a IORef by a function changes its value" (gives' [True]) $ do
ref <- newIORefInt 5
atomicModifyIORef ref (\i -> (i+1, ()))
(6==) <$> readIORef ref
, djfu "A ticket contains the value of the IORef at the time of its creation" (gives' [True]) $ do
ref <- newIORefInt 5
tick <- readForCAS ref
writeIORef ref 6
(5==) <$> peekTicket tick
, djfu "Compare-and-swap returns a ticket containing the new value" (gives' [True]) $ do
ref <- newIORefInt 5
tick <- readForCAS ref
(_, tick') <- casIORef ref tick 6
(6==) <$> peekTicket tick'
, djfu "Compare-and-swap on an unmodified IORef succeeds" (gives' [True]) $ do
ref <- newIORefInt 5
tick <- readForCAS ref
(suc, _) <- casIORef ref tick 6
val <- readIORef ref
pure (suc && (6 == val))
, djfu "Compare-and-swap on a modified IORef fails" (gives' [True]) $ do
ref <- newIORefInt 5
tick <- readForCAS ref
writeIORef ref 6
(suc, _) <- casIORef ref tick 7
val <- readIORef ref
pure (not suc && 7 /= val)
]
stmTests :: [TestTree]
stmTests = toTestList
[ djfu "When a TVar is updated, its new value is visible later in same transaction" (gives' [True]) $
(6==) <$> atomically (do { v <- newTVarInt 5; writeTVar v 6; readTVar v })
, djfu "When a TVar is updated, its new value is visible in a later transaction" (gives' [True]) $ do
ctv <- atomically $ newTVarInt 5
(5==) <$> readTVarConc ctv
, djfu "Aborting a transaction blocks the thread" (gives [Left Deadlock])
, djfu "Aborting a transaction can be caught and recovered from" (gives' [True]) $ do
ctv <- atomically $ newTVarInt 5
atomically $ orElse retry (writeTVar ctv 6)
(6==) <$> readTVarConc ctv
, djfu "An exception thrown in a transaction can be caught" (gives' [True]) $ do
ctv <- atomically $ newTVarInt 5
atomically $ catchArithException
(throwSTM Overflow)
(\_ -> writeTVar ctv 6)
(6==) <$> readTVarConc ctv
, djfu "Nested exception handlers in transactions work" (gives' [True]) $ do
ctv <- atomically $ newTVarInt 5
atomically $ catchArithException
(catchArrayException
(throwSTM Overflow)
(\_ -> writeTVar ctv 0))
(\_ -> writeTVar ctv 6)
(6==) <$> readTVarConc ctv
, djfu "MonadSTM is a MonadFail" (alwaysFailsWith isUncaughtException)
, djfu "'retry' is not caught by 'catch'" (gives' [True]) $
atomically
((retry `catchSomeException` \_ -> pure False) `orElse` pure True)
, djfu "'throw' is not caught by 'orElse'" (gives' [True]) $
atomically
((throwSTM Overflow `orElse` pure False) `catchSomeException` \_ -> pure True)
, djfu "'retry' in a nested 'orElse' only aborts the innermost" (gives' [True]) $
atomically
((retry `orElse` pure True) `orElse` pure False)
]
exceptionTests :: [TestTree]
exceptionTests = toTestList
[ djfu "An exception thrown can be caught" (gives' [True]) $
catchArithException
(throw Overflow)
(\_ -> pure True)
, djfu "Nested exception handlers work" (gives' [True]) $
catchArithException
(catchArrayException
(throw Overflow)
(\_ -> pure False))
(\_ -> pure True)
, djfu "Uncaught exceptions kill the computation" (alwaysFailsWith isUncaughtException) $
catchArithException
(throw $ IndexOutOfBounds "")
(\_ -> pure False)
, djfu "SomeException matches all exception types" (gives' [True]) $ do
a <- catchSomeException
(throw Overflow)
(\_ -> pure True)
b <- catchSomeException
(throw $ IndexOutOfBounds "")
(\_ -> pure True)
pure (a && b)
, djfu "Exceptions thrown in a transaction can be caught outside it" (gives' [True]) $
catchArithException
(atomically $ throwSTM Overflow)
(\_ -> pure True)
, djfu "Throwing an unhandled exception to the main thread kills it" (alwaysFailsWith isUncaughtException) $ do
tid <- myThreadId
throwTo tid Overflow
, djfu "Throwing a handled exception to the main thread does not kill it" (gives' [True]) $ do
tid <- myThreadId
catchArithException (throwTo tid Overflow >> pure False) (\_ -> pure True)
, djfu "MonadConc is a MonadFail" (alwaysFailsWith isUncaughtException)
, djfu "Masking state is changed by a mask" (gives' [MaskedInterruptible]) $
mask_ getMaskingState
, djfu "Masking state is reset after the mask ends" (gives' [Unmasked]) $
mask_ getMaskingState >> getMaskingState
]
capabilityTests :: [TestTree]
capabilityTests = toTestList
[ djfu "Reading the capabilities twice without update gives the same result" (gives' [True]) $ do
c1 <- getNumCapabilities
c2 <- getNumCapabilities
pure (c1 == c2)
, djfu "Getting the updated capabilities gives the new value" (gives' [True]) $ do
caps <- getNumCapabilities
setNumCapabilities (caps + 1)
(== caps + 1) <$> getNumCapabilities
]
programTests :: [TestTree]
programTests = toTestList
[ testGroup "withSetup"
[ djfu "Inner state modifications are visible to the outside" (gives' [True]) $
withSetup
(do inner <- newEmptyMVarInt
putMVar inner 5
pure inner)
(fmap (==5) . takeMVar)
, djfu "Failures abort the whole computation" (alwaysFailsWith isDeadlock) $
withSetup (takeMVar =<< newEmptyMVarInt) (\_ -> pure True)
, toTestList . testGroup "Snapshotting" $ let snapshotTest n p conc = W n conc p ("randomly", randomly (mkStdGen 0) 150) in
[ snapshotTest "State updates are applied correctly" (gives' [2]) $
withSetup
(do r <- newIORefInt 0
writeIORef r 1
writeIORef r 2
pure r)
readIORef
, snapshotTest "Lifted IO is re-run (1)" (gives' [2..151]) $
withSetup
(do r <- liftIO (IORef.newIORef (0::Int))
liftIO (IORef.modifyIORef r (+1))
pure r)
(liftIO . IORef.readIORef)
, snapshotTest "Lifted IO is re-run (2)" (gives' [1]) $
withSetup
(do let modify r f = liftIO (IORef.readIORef r) >>= liftIO . IORef.writeIORef r . f
r <- liftIO (IORef.newIORef (0::Int))
modify r (+1)
pure r)
(liftIO . IORef.readIORef)
, snapshotTest "Lifted IO is re-run (3)" (gives' [1]) $
withSetup
(do r <- liftIO (IORef.newIORef (0::Int))
liftIO (IORef.writeIORef r 0)
liftIO (IORef.modifyIORef r (+1))
pure r)
(liftIO . IORef.readIORef)
]
]
, testGroup "withSetupAndTeardown"
[ djfuS "Failures can be observed" (gives' [True]) $
withSetupAndTeardown
(pure ())
(\_ -> pure . either (== Deadlock) (const False))
(\_ -> newEmptyMVar >>= readMVar)
, djfuS "Teardown always happens" (gives' [True]) $
withSetupAndTeardown
(newMVarInt 0)
(\var x -> do
y <- readMVar var
pure (either (==Deadlock) (const False) x && y == 0))
(\var -> putMVar var 1)
, djfuS "Non-failing inner action returns the final result" (gives' [True]) $
withSetupAndTeardown
(newMVarInt 3)
(\_ x -> pure (either (const False) (==3) x))
takeMVar
]
, testGroup "registerInvariant"
[ djfuS "An uncaught exception fails an invariant" (alwaysFailsWith isInvariantFailure) $
withSetup (registerInvariant (throwM Overflow)) $
\() -> pure True
, djfuS "An invariant which never throws always passes" (gives' [True]) $
withSetup (registerInvariant (pure ())) $
\() -> pure True
, djfuS "An invariant can catch exceptions" (gives' [True]) $
withSetup (registerInvariant (throwM Overflow `catchArithException` \_ -> pure ())) $
\() -> pure True
, djfuS "Invariants can read MVars" (alwaysFailsWith isInvariantFailure) $
withSetup
(do v <- newMVarInt 10
registerInvariant (inspectMVar v >>= \x -> when (isNothing x) (throwM Overflow))
pure v)
takeMVar
, djfuS "Invariants can read TVars" (alwaysFailsWith isInvariantFailure) $
withSetup
(do v <- atomically (newTVar (10::Int))
registerInvariant (inspectTVar v >>= \x -> when (x < 5) (throwM Overflow))
pure v)
(\v -> atomically (writeTVar v 1))
, djfuS "Invariants aren't checked in the setup" (gives' [True]) $
withSetup
(do v <- newIORefInt 10
registerInvariant (inspectIORef v >>= \x -> when (x < 5) (throwM Overflow))
writeIORef v 1
writeIORef v 10)
(\_ -> pure True)
, djfuS "Invariants aren't checked in the teardown" (gives' [True]) $
withSetupAndTeardown
(do v <- newIORefInt 10
registerInvariant (inspectIORef v >>= \x -> when (x < 5) (throwM Overflow))
pure v)
(\v _ -> do
writeIORef v 1
writeIORef v 10
pure True)
(\_ -> pure ())
, djfuS "Invariants aren't checked if added in the main phase" (gives' [True]) $ do
v <- newIORefInt 10
registerInvariant (inspectIORef v >>= \x -> when (x < 5) (throwM Overflow))
writeIORef v 1
pure True
]
]
ioTests :: [TestTree]
ioTests = toTestList
[ djfu "Lifted IO is performed" (gives' [3]) $ do
r <- liftIO (IORef.newIORef (0::Int))
replicateM_ 3 (liftIO (IORef.atomicModifyIORef r (\i -> (i+1, ()))))
liftIO (IORef.readIORef r)
]
|
e5840aa74a8a9ba1bf7838ca6b593ef3f5c8fb1fb65ab7ed3b8408aad23e47de | tlehman/sicp-exercises | ex-1.23.scm | Exercise 1.23 : The smallest - divisor procedure shown at the start of this section does lots of needless testing : After it checks to see if the number is divisble by 2 , there is no point in checking to see if it is divisible by any larger even numbers . This suggests that the values used for test - divisor ( d ) should not be 2,3,4,5,6 ... but rather 2,3,5,7,9 ...
To implement this change , define a procedure next that returns 3 if its input is equal to 2 and otherwise returns its input plus 2 . Modify the smallest - divisor procedure to use ( next test - divisor ) instead of ( + test - divisor 1 ) . With timed - prime - test incorporating this modified version of smallest - divisor , run the test for each of the 12 primes found in Exercise 1.22 .
(define (next n)
(if (= n 2) 3
(+ n 2)))
; Since this modification halves the number of test steps, you should expect it to run about twice as fast.
(load "ex-1.22.scm")
(define (find-divisor n d)
(cond ((divides? d n) d)
((> (square d) n) n)
(else (find-divisor n (next d)))))
( search - for - primes 100000000001 999999999999 )
( search - for - primes 100000000000001 999999999999999 )
;; (search-for-primes 100000000000000001 999999999999999999)
;; The data:
;;
100000000003 * * * 11
100000000019 * * * 11
100000000057 * * * 11
100000000000031 * * * 347
100000000000067 * * * 348
100000000000097 * * * 347
100000000000000003 * * * 11240
100000000000000013 * * * 11123
100000000000000019 * * * 11017
(define (average a b c) (/ (+ a b c) 3.0))
(define (ratio m n) (/ m n))
(ratio
16556.33
Value : 1.4879865188735772
(ratio
514.67
Value : 1.4817754318618042
; Is this expectation confirmed?
;; No.
If not , what is the observed ratio of the speeds of the speeds of the two algorithms , and how do you explain the fact that it is different from 2 ?
It ran faster , but only 1.48 times faster . Not sure why this is the case .
(newline)
| null | https://raw.githubusercontent.com/tlehman/sicp-exercises/57151ec07d09a98318e91c83b6eacaa49361d156/ex-1.23.scm | scheme | Since this modification halves the number of test steps, you should expect it to run about twice as fast.
(search-for-primes 100000000000000001 999999999999999999)
The data:
Is this expectation confirmed?
No. | Exercise 1.23 : The smallest - divisor procedure shown at the start of this section does lots of needless testing : After it checks to see if the number is divisble by 2 , there is no point in checking to see if it is divisible by any larger even numbers . This suggests that the values used for test - divisor ( d ) should not be 2,3,4,5,6 ... but rather 2,3,5,7,9 ...
To implement this change , define a procedure next that returns 3 if its input is equal to 2 and otherwise returns its input plus 2 . Modify the smallest - divisor procedure to use ( next test - divisor ) instead of ( + test - divisor 1 ) . With timed - prime - test incorporating this modified version of smallest - divisor , run the test for each of the 12 primes found in Exercise 1.22 .
(define (next n)
(if (= n 2) 3
(+ n 2)))
(load "ex-1.22.scm")
(define (find-divisor n d)
(cond ((divides? d n) d)
((> (square d) n) n)
(else (find-divisor n (next d)))))
( search - for - primes 100000000001 999999999999 )
( search - for - primes 100000000000001 999999999999999 )
100000000003 * * * 11
100000000019 * * * 11
100000000057 * * * 11
100000000000031 * * * 347
100000000000067 * * * 348
100000000000097 * * * 347
100000000000000003 * * * 11240
100000000000000013 * * * 11123
100000000000000019 * * * 11017
(define (average a b c) (/ (+ a b c) 3.0))
(define (ratio m n) (/ m n))
(ratio
16556.33
Value : 1.4879865188735772
(ratio
514.67
Value : 1.4817754318618042
If not , what is the observed ratio of the speeds of the speeds of the two algorithms , and how do you explain the fact that it is different from 2 ?
It ran faster , but only 1.48 times faster . Not sure why this is the case .
(newline)
|
f47e3b537d9d5baea4480a1be6eff12bc32585a5ac4d5af44b5cd812334fbffc | mhjort/clj-gatling | example.clj | (ns clj-gatling.example)
(def test-simu
{:name "Test simulation"
:scenarios [{:name "Test scenario"
:steps [{:name "Step1" :request (fn [_]
(Thread/sleep 10)
true)}
{:name "Step2" :request (fn [_]
(Thread/sleep 10)
false)}]}]})
| null | https://raw.githubusercontent.com/mhjort/clj-gatling/0130622bd18cee9abad5085eaca0e868d3a5abd7/test/clj_gatling/example.clj | clojure | (ns clj-gatling.example)
(def test-simu
{:name "Test simulation"
:scenarios [{:name "Test scenario"
:steps [{:name "Step1" :request (fn [_]
(Thread/sleep 10)
true)}
{:name "Step2" :request (fn [_]
(Thread/sleep 10)
false)}]}]})
| |
065b28f58c35951390a3936ba3c4b7593af97f80fa29c70b04e4ea9a855f515a | haskell-opengl/GLUT | Checker.hs |
Checker.hs ( adapted from checker.c which is ( c ) Silicon Graphics , Inc )
Copyright ( c ) 2002 - 2018 < >
This file is part of HOpenGL and distributed under a BSD - style license
See the file libraries / GLUT / LICENSE
This program texture maps a checkerboard image onto two rectangles .
Texture objects are only used when GL_EXT_texture_object is supported .
Checker.hs (adapted from checker.c which is (c) Silicon Graphics, Inc)
Copyright (c) Sven Panne 2002-2018 <>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
This program texture maps a checkerboard image onto two rectangles.
Texture objects are only used when GL_EXT_texture_object is supported.
-}
import Control.Monad ( when )
import Data.Maybe ( isJust )
import Data.Bits ( (.&.) )
import Foreign ( withArray )
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import Graphics.UI.GLUT
-- Create checkerboard image
checkImageSize :: TextureSize2D
checkImageSize = TextureSize2D 64 64
withCheckImage :: TextureSize2D -> GLsizei -> (GLubyte -> (Color4 GLubyte))
-> (PixelData (Color4 GLubyte) -> IO ()) -> IO ()
withCheckImage (TextureSize2D w h) n f act =
withArray [ f c |
i <- [ 0 .. w - 1 ],
j <- [ 0 .. h - 1 ],
let c | (i .&. n) == (j .&. n) = 0
| otherwise = 255 ] $
act. PixelData RGBA UnsignedByte
myInit :: IO (Maybe TextureObject)
myInit = do
clearColor $= Color4 0 0 0 0
shadeModel $= Flat
depthFunc $= Just Less
rowAlignment Unpack $= 1
exts <- get glExtensions
mbTexName <- if "GL_EXT_texture_object" `elem` exts
then fmap Just genObjectName
else return Nothing
when (isJust mbTexName) $ textureBinding Texture2D $= mbTexName
textureWrapMode Texture2D S $= (Repeated, Repeat)
textureWrapMode Texture2D T $= (Repeated, Repeat)
textureFilter Texture2D $= ((Nearest, Nothing), Nearest)
withCheckImage checkImageSize 0x8 (\c -> Color4 c c c 255) $
texImage2D Texture2D NoProxy 0 RGBA' checkImageSize 0
return mbTexName
display :: Maybe TextureObject -> DisplayCallback
display mbTexName = do
clear [ ColorBuffer, DepthBuffer ]
texture Texture2D $= Enabled
textureFunction $= Decal
when (isJust mbTexName) $ textureBinding Texture2D $= mbTexName
-- resolve overloading, not needed in "real" programs
let texCoord2f = texCoord :: TexCoord2 GLfloat -> IO ()
vertex3f = vertex :: Vertex3 GLfloat -> IO ()
renderPrimitive Quads $ do
texCoord2f (TexCoord2 0 0); vertex3f (Vertex3 (-2.0) (-1.0) 0.0 )
texCoord2f (TexCoord2 0 1); vertex3f (Vertex3 (-2.0) 1.0 0.0 )
texCoord2f (TexCoord2 1 1); vertex3f (Vertex3 0.0 1.0 0.0 )
texCoord2f (TexCoord2 1 0); vertex3f (Vertex3 0.0 (-1.0) 0.0 )
texCoord2f (TexCoord2 0 0); vertex3f (Vertex3 1.0 (-1.0) 0.0 )
texCoord2f (TexCoord2 0 1); vertex3f (Vertex3 1.0 1.0 0.0 )
texCoord2f (TexCoord2 1 1); vertex3f (Vertex3 2.41421 1.0 (-1.41421))
texCoord2f (TexCoord2 1 0); vertex3f (Vertex3 2.41421 (-1.0) (-1.41421))
flush
texture Texture2D $= Disabled
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
perspective 60 (fromIntegral w / fromIntegral h) 1 30
matrixMode $= Modelview 0
loadIdentity
translate (Vector3 0 0 (-3.6 :: GLfloat))
keyboard :: KeyboardMouseCallback
keyboard (Char '\27') Down _ _ = exitWith ExitSuccess
keyboard _ _ _ _ = return ()
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode, WithDepthBuffer ]
initialWindowSize $= Size 250 250
initialWindowPosition $= Position 100 100
_ <- createWindow progName
mbTexName <- myInit
displayCallback $= display mbTexName
reshapeCallback $= Just reshape
keyboardMouseCallback $= Just keyboard
mainLoop
| null | https://raw.githubusercontent.com/haskell-opengl/GLUT/36207fa51e4c1ea1e5512aeaa373198a4a56cad0/examples/RedBook4/Checker.hs | haskell | Create checkerboard image
resolve overloading, not needed in "real" programs |
Checker.hs ( adapted from checker.c which is ( c ) Silicon Graphics , Inc )
Copyright ( c ) 2002 - 2018 < >
This file is part of HOpenGL and distributed under a BSD - style license
See the file libraries / GLUT / LICENSE
This program texture maps a checkerboard image onto two rectangles .
Texture objects are only used when GL_EXT_texture_object is supported .
Checker.hs (adapted from checker.c which is (c) Silicon Graphics, Inc)
Copyright (c) Sven Panne 2002-2018 <>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
This program texture maps a checkerboard image onto two rectangles.
Texture objects are only used when GL_EXT_texture_object is supported.
-}
import Control.Monad ( when )
import Data.Maybe ( isJust )
import Data.Bits ( (.&.) )
import Foreign ( withArray )
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import Graphics.UI.GLUT
checkImageSize :: TextureSize2D
checkImageSize = TextureSize2D 64 64
withCheckImage :: TextureSize2D -> GLsizei -> (GLubyte -> (Color4 GLubyte))
-> (PixelData (Color4 GLubyte) -> IO ()) -> IO ()
withCheckImage (TextureSize2D w h) n f act =
withArray [ f c |
i <- [ 0 .. w - 1 ],
j <- [ 0 .. h - 1 ],
let c | (i .&. n) == (j .&. n) = 0
| otherwise = 255 ] $
act. PixelData RGBA UnsignedByte
myInit :: IO (Maybe TextureObject)
myInit = do
clearColor $= Color4 0 0 0 0
shadeModel $= Flat
depthFunc $= Just Less
rowAlignment Unpack $= 1
exts <- get glExtensions
mbTexName <- if "GL_EXT_texture_object" `elem` exts
then fmap Just genObjectName
else return Nothing
when (isJust mbTexName) $ textureBinding Texture2D $= mbTexName
textureWrapMode Texture2D S $= (Repeated, Repeat)
textureWrapMode Texture2D T $= (Repeated, Repeat)
textureFilter Texture2D $= ((Nearest, Nothing), Nearest)
withCheckImage checkImageSize 0x8 (\c -> Color4 c c c 255) $
texImage2D Texture2D NoProxy 0 RGBA' checkImageSize 0
return mbTexName
display :: Maybe TextureObject -> DisplayCallback
display mbTexName = do
clear [ ColorBuffer, DepthBuffer ]
texture Texture2D $= Enabled
textureFunction $= Decal
when (isJust mbTexName) $ textureBinding Texture2D $= mbTexName
let texCoord2f = texCoord :: TexCoord2 GLfloat -> IO ()
vertex3f = vertex :: Vertex3 GLfloat -> IO ()
renderPrimitive Quads $ do
texCoord2f (TexCoord2 0 0); vertex3f (Vertex3 (-2.0) (-1.0) 0.0 )
texCoord2f (TexCoord2 0 1); vertex3f (Vertex3 (-2.0) 1.0 0.0 )
texCoord2f (TexCoord2 1 1); vertex3f (Vertex3 0.0 1.0 0.0 )
texCoord2f (TexCoord2 1 0); vertex3f (Vertex3 0.0 (-1.0) 0.0 )
texCoord2f (TexCoord2 0 0); vertex3f (Vertex3 1.0 (-1.0) 0.0 )
texCoord2f (TexCoord2 0 1); vertex3f (Vertex3 1.0 1.0 0.0 )
texCoord2f (TexCoord2 1 1); vertex3f (Vertex3 2.41421 1.0 (-1.41421))
texCoord2f (TexCoord2 1 0); vertex3f (Vertex3 2.41421 (-1.0) (-1.41421))
flush
texture Texture2D $= Disabled
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
perspective 60 (fromIntegral w / fromIntegral h) 1 30
matrixMode $= Modelview 0
loadIdentity
translate (Vector3 0 0 (-3.6 :: GLfloat))
keyboard :: KeyboardMouseCallback
keyboard (Char '\27') Down _ _ = exitWith ExitSuccess
keyboard _ _ _ _ = return ()
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode, WithDepthBuffer ]
initialWindowSize $= Size 250 250
initialWindowPosition $= Position 100 100
_ <- createWindow progName
mbTexName <- myInit
displayCallback $= display mbTexName
reshapeCallback $= Just reshape
keyboardMouseCallback $= Just keyboard
mainLoop
|
1514cd14eb75c67fa81bff695a7a228a7a12df7833c19d116d930c54694baed7 | MyDataFlow/ttalk-server | proper_gen.erl | Copyright 2010 - 2015 < > ,
< >
and < >
%%%
This file is part of PropEr .
%%%
%%% PropEr is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
%%% (at your option) any later version.
%%%
%%% PropEr is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
%%% GNU General Public License for more details.
%%%
You should have received a copy of the GNU General Public License
%%% along with PropEr. If not, see </>.
2010 - 2015 , and
%%% @version {@version}
@author
%%% @doc Generator subsystem and generators for basic types.
%%%
%%% You can use <a href="#index">these</a> functions to try out the random
%%% instance generation and shrinking subsystems.
%%%
%%% CAUTION: These functions should never be used inside properties. They are
%%% meant for demonstration purposes only.
-module(proper_gen).
-export([pick/1, pick/2, pick/3,
sample/1, sample/3, sampleshrink/1, sampleshrink/2]).
-export([safe_generate/1]).
-export([generate/1, normal_gen/1, alt_gens/1, clean_instance/1,
get_ret_type/1]).
-export([integer_gen/3, float_gen/3, atom_gen/1, atom_rev/1, binary_gen/1,
binary_rev/1, binary_len_gen/1, bitstring_gen/1, bitstring_rev/1,
bitstring_len_gen/1, list_gen/2, distlist_gen/3, vector_gen/2,
union_gen/1, weighted_union_gen/1, tuple_gen/1, loose_tuple_gen/2,
loose_tuple_rev/2, exactly_gen/1, fixed_list_gen/1, function_gen/2,
any_gen/1, native_type_gen/2, safe_weighted_union_gen/1,
safe_union_gen/1]).
-export_type([instance/0, imm_instance/0, sized_generator/0, nosize_generator/0,
generator/0, reverse_gen/0, combine_fun/0, alt_gens/0]).
-include("proper_internal.hrl").
-compile({parse_transform, vararg}).
%%-----------------------------------------------------------------------------
%% Types
%%-----------------------------------------------------------------------------
TODO : update ( ) when adding more types : be careful when reading
%% anything that returns it
@private_type
-type imm_instance() :: proper_types:raw_type()
| instance()
| {'$used', imm_instance(), imm_instance()}
| {'$to_part', imm_instance()}.
-type instance() :: term().
%% A value produced by the random instance generator.
-type error_reason() :: 'arity_limit' | 'cant_generate' | {'typeserver',term()}.
@private_type
-type sized_generator() :: fun((size()) -> imm_instance()).
@private_type
-type typed_sized_generator() :: {'typed',
fun((proper_types:type(),size()) ->
imm_instance())}.
@private_type
-type nosize_generator() :: fun(() -> imm_instance()).
@private_type
-type typed_nosize_generator() :: {'typed',
fun((proper_types:type()) ->
imm_instance())}.
@private_type
-type generator() :: sized_generator()
| typed_sized_generator()
| nosize_generator()
| typed_nosize_generator().
@private_type
-type plain_reverse_gen() :: fun((instance()) -> imm_instance()).
@private_type
-type typed_reverse_gen() :: {'typed',
fun((proper_types:type(),instance()) ->
imm_instance())}.
@private_type
-type reverse_gen() :: plain_reverse_gen() | typed_reverse_gen().
@private_type
-type combine_fun() :: fun((instance()) -> imm_instance()).
@private_type
-type alt_gens() :: fun(() -> [imm_instance()]).
@private_type
-type fun_seed() :: {non_neg_integer(),non_neg_integer()}.
%%-----------------------------------------------------------------------------
%% Instance generation functions
%%-----------------------------------------------------------------------------
@private
-spec safe_generate(proper_types:raw_type()) ->
{'ok',imm_instance()} | {'error',error_reason()}.
safe_generate(RawType) ->
try generate(RawType) of
ImmInstance -> {ok, ImmInstance}
catch
throw:'$arity_limit' -> {error, arity_limit};
throw:'$cant_generate' -> {error, cant_generate};
throw:{'$typeserver',SubReason} -> {error, {typeserver,SubReason}}
end.
@private
-spec generate(proper_types:raw_type()) -> imm_instance().
generate(RawType) ->
Type = proper_types:cook_outer(RawType),
ok = add_parameters(Type),
Instance = generate(Type, get('$constraint_tries'), none),
ok = remove_parameters(Type),
Instance.
-spec add_parameters(proper_types:type()) -> 'ok'.
add_parameters(Type) ->
case proper_types:find_prop(parameters, Type) of
{ok, Params} ->
OldParams = erlang:get('$parameters'),
case OldParams of
undefined ->
erlang:put('$parameters', Params);
_ ->
erlang:put('$parameters', Params ++ OldParams)
end,
ok;
_ ->
ok
end.
-spec remove_parameters(proper_types:type()) -> 'ok'.
remove_parameters(Type) ->
case proper_types:find_prop(parameters, Type) of
{ok, Params} ->
AllParams = erlang:get('$parameters'),
case AllParams of
Params->
erlang:erase('$parameters');
_ ->
erlang:put('$parameters', AllParams -- Params)
end,
ok;
_ ->
ok
end.
-spec generate(proper_types:type(), non_neg_integer(),
'none' | {'ok',imm_instance()}) -> imm_instance().
generate(_Type, 0, none) ->
throw('$cant_generate');
generate(_Type, 0, {ok,Fallback}) ->
Fallback;
generate(Type, TriesLeft, Fallback) ->
ImmInstance =
case proper_types:get_prop(kind, Type) of
constructed ->
PartsType = proper_types:get_prop(parts_type, Type),
Combine = proper_types:get_prop(combine, Type),
ImmParts = generate(PartsType),
Parts = clean_instance(ImmParts),
ImmInstance1 = Combine(Parts),
%% TODO: We can just generate the internal type: if it's not
%% a type, it will turn into an exactly.
ImmInstance2 =
case proper_types:is_raw_type(ImmInstance1) of
true -> generate(ImmInstance1);
false -> ImmInstance1
end,
{'$used',ImmParts,ImmInstance2};
_ ->
ImmInstance1 = normal_gen(Type),
case proper_types:is_raw_type(ImmInstance1) of
true -> generate(ImmInstance1);
false -> ImmInstance1
end
end,
case proper_types:satisfies_all(clean_instance(ImmInstance), Type) of
{_,true} -> ImmInstance;
{true,false} -> generate(Type, TriesLeft - 1, {ok,ImmInstance});
{false,false} -> generate(Type, TriesLeft - 1, Fallback)
end.
@equiv pick(Type , 10 )
-spec pick(Type::proper_types:raw_type()) -> {'ok',instance()} | 'error'.
pick(RawType) ->
pick(RawType, 10).
@equiv pick(Type , Size , os : timestamp ( ) )
-spec pick(Type::proper_types:raw_type(), size()) -> {'ok',instance()} | 'error'.
pick(RawType, Size) ->
pick(RawType, Size, os:timestamp()).
%% @doc Generates a random instance of `Type', of size `Size' with seed `Seed'.
-spec pick(Type::proper_types:raw_type(), size(), seed()) ->
{'ok',instance()} | 'error'.
pick(RawType, Size, Seed) ->
proper:global_state_init_size_seed(Size, Seed),
case clean_instance(safe_generate(RawType)) of
{ok,Instance} = Result ->
Msg = "WARNING: Some garbage has been left in the process registry "
"and the code server~n"
"to allow for the returned function(s) to run normally.~n"
"Please run proper:global_state_erase() when done.~n",
case contains_fun(Instance) of
true -> io:format(Msg, []);
false -> proper:global_state_erase()
end,
Result;
{error,Reason} ->
proper:report_error(Reason, fun io:format/2),
proper:global_state_erase(),
error
end.
@equiv sample(Type , 10 , 20 )
-spec sample(Type::proper_types:raw_type()) -> 'ok'.
sample(RawType) ->
sample(RawType, 10, 20).
@doc Generates and prints one random instance of ` Type ' for each size from
` StartSize ' up to ` EndSize ' .
-spec sample(Type::proper_types:raw_type(), size(), size()) -> 'ok'.
sample(RawType, StartSize, EndSize) when StartSize =< EndSize ->
Tests = EndSize - StartSize + 1,
Prop = ?FORALL(X, RawType, begin io:format("~p~n",[X]), true end),
Opts = [quiet,{start_size,StartSize},{max_size,EndSize},{numtests,Tests}],
_ = proper:quickcheck(Prop, Opts),
ok.
@equiv sampleshrink(Type , 10 )
-spec sampleshrink(Type::proper_types:raw_type()) -> 'ok'.
sampleshrink(RawType) ->
sampleshrink(RawType, 10).
%% @doc Generates a random instance of `Type', of size `Size', then shrinks it
%% as far as it goes. The value produced on each step of the shrinking process
%% is printed on the screen.
-spec sampleshrink(Type::proper_types:raw_type(), size()) -> 'ok'.
sampleshrink(RawType, Size) ->
proper:global_state_init_size(Size),
Type = proper_types:cook_outer(RawType),
case safe_generate(Type) of
{ok,ImmInstance} ->
Shrunk = keep_shrinking(ImmInstance, [], Type),
PrintInst = fun(I) -> io:format("~p~n",[clean_instance(I)]) end,
lists:foreach(PrintInst, Shrunk);
{error,Reason} ->
proper:report_error(Reason, fun io:format/2)
end,
proper:global_state_erase(),
ok.
-spec keep_shrinking(imm_instance(), [imm_instance()], proper_types:type()) ->
[imm_instance(),...].
keep_shrinking(ImmInstance, Acc, Type) ->
case proper_shrink:shrink(ImmInstance, Type, init) of
{[], _NewState} ->
lists:reverse([ImmInstance|Acc]);
{[Shrunk|_Rest], _NewState} ->
keep_shrinking(Shrunk, [ImmInstance|Acc], Type)
end.
-spec contains_fun(term()) -> boolean().
contains_fun(List) when is_list(List) ->
proper_arith:safe_any(fun contains_fun/1, List);
contains_fun(Tuple) when is_tuple(Tuple) ->
contains_fun(tuple_to_list(Tuple));
contains_fun(Fun) when is_function(Fun) ->
true;
contains_fun(_Term) ->
false.
%%-----------------------------------------------------------------------------
%% Utility functions
%%-----------------------------------------------------------------------------
@private
-spec normal_gen(proper_types:type()) -> imm_instance().
normal_gen(Type) ->
case proper_types:get_prop(generator, Type) of
{typed, Gen} ->
if
is_function(Gen, 1) -> Gen(Type);
is_function(Gen, 2) -> Gen(Type, proper:get_size(Type))
end;
Gen ->
if
is_function(Gen, 0) -> Gen();
is_function(Gen, 1) -> Gen(proper:get_size(Type))
end
end.
@private
-spec alt_gens(proper_types:type()) -> [imm_instance()].
alt_gens(Type) ->
case proper_types:find_prop(alt_gens, Type) of
{ok, AltGens} -> ?FORCE(AltGens);
error -> []
end.
@private
-spec clean_instance(imm_instance()) -> instance().
clean_instance({'$used',_ImmParts,ImmInstance}) ->
clean_instance(ImmInstance);
clean_instance({'$to_part',ImmInstance}) ->
clean_instance(ImmInstance);
clean_instance(ImmInstance) ->
if
is_list(ImmInstance) ->
%% CAUTION: this must handle improper lists
proper_arith:safe_map(fun clean_instance/1, ImmInstance);
is_tuple(ImmInstance) ->
proper_arith:tuple_map(fun clean_instance/1, ImmInstance);
true ->
ImmInstance
end.
%%-----------------------------------------------------------------------------
%% Basic type generators
%%-----------------------------------------------------------------------------
@private
-spec integer_gen(size(), proper_types:extint(), proper_types:extint()) ->
integer().
integer_gen(Size, inf, inf) ->
proper_arith:rand_int(Size);
integer_gen(Size, inf, High) ->
High - proper_arith:rand_non_neg_int(Size);
integer_gen(Size, Low, inf) ->
Low + proper_arith:rand_non_neg_int(Size);
integer_gen(Size, Low, High) ->
proper_arith:smart_rand_int(Size, Low, High).
@private
-spec float_gen(size(), proper_types:extnum(), proper_types:extnum()) ->
float().
float_gen(Size, inf, inf) ->
proper_arith:rand_float(Size);
float_gen(Size, inf, High) ->
High - proper_arith:rand_non_neg_float(Size);
float_gen(Size, Low, inf) ->
Low + proper_arith:rand_non_neg_float(Size);
float_gen(_Size, Low, High) ->
proper_arith:rand_float(Low, High).
@private
-spec atom_gen(size()) -> proper_types:type().
We make sure we never clash with internal atoms by checking that the first
%% character is not '$'.
atom_gen(Size) ->
?LET(Str,
?SUCHTHAT(X,
proper_types:resize(Size,
proper_types:list(proper_types:byte())),
X =:= [] orelse hd(X) =/= $$),
list_to_atom(Str)).
@private
-spec atom_rev(atom()) -> imm_instance().
atom_rev(Atom) ->
{'$used', atom_to_list(Atom), Atom}.
@private
-spec binary_gen(size()) -> proper_types:type().
binary_gen(Size) ->
?LET(Bytes,
proper_types:resize(Size,
proper_types:list(proper_types:byte())),
list_to_binary(Bytes)).
@private
-spec binary_rev(binary()) -> imm_instance().
binary_rev(Binary) ->
{'$used', binary_to_list(Binary), Binary}.
@private
-spec binary_len_gen(length()) -> proper_types:type().
binary_len_gen(Len) ->
?LET(Bytes,
proper_types:vector(Len, proper_types:byte()),
list_to_binary(Bytes)).
@private
-spec bitstring_gen(size()) -> proper_types:type().
bitstring_gen(Size) ->
?LET({BytesHead, NumBits, TailByte},
{proper_types:resize(Size,proper_types:binary()),
proper_types:range(0,7), proper_types:range(0,127)},
<<BytesHead/binary, TailByte:NumBits>>).
@private
-spec bitstring_rev(bitstring()) -> imm_instance().
bitstring_rev(BitString) ->
List = bitstring_to_list(BitString),
{BytesList, BitsTail} = lists:splitwith(fun erlang:is_integer/1, List),
{NumBits, TailByte} = case BitsTail of
[] -> {0, 0};
[Bits] -> N = bit_size(Bits),
<<Byte:N>> = Bits,
{N, Byte}
end,
{'$used',
{{'$used',BytesList,list_to_binary(BytesList)}, NumBits, TailByte},
BitString}.
@private
-spec bitstring_len_gen(length()) -> proper_types:type().
bitstring_len_gen(Len) ->
BytesLen = Len div 8,
BitsLen = Len rem 8,
?LET({BytesHead, NumBits, TailByte},
{proper_types:binary(BytesLen), BitsLen,
proper_types:range(0, 1 bsl BitsLen - 1)},
<<BytesHead/binary, TailByte:NumBits>>).
@private
-spec list_gen(size(), proper_types:type()) -> [imm_instance()].
list_gen(Size, ElemType) ->
Len = proper_arith:rand_int(0, Size),
vector_gen(Len, ElemType).
@private
-spec distlist_gen(size(), sized_generator(), boolean()) -> [imm_instance()].
distlist_gen(RawSize, Gen, NonEmpty) ->
Len = case NonEmpty of
true -> proper_arith:rand_int(1, erlang:max(1,RawSize));
false -> proper_arith:rand_int(0, RawSize)
end,
Size = case Len of
1 -> RawSize - 1;
_ -> RawSize
end,
%% TODO: this produces a lot of types: maybe a simple 'div' is sufficient?
Sizes = proper_arith:distribute(Size, Len),
InnerTypes = [Gen(S) || S <- Sizes],
fixed_list_gen(InnerTypes).
@private
-spec vector_gen(length(), proper_types:type()) -> [imm_instance()].
vector_gen(Len, ElemType) ->
vector_gen_tr(Len, ElemType, []).
-spec vector_gen_tr(length(), proper_types:type(), [imm_instance()]) ->
[imm_instance()].
vector_gen_tr(0, _ElemType, AccList) ->
AccList;
vector_gen_tr(Left, ElemType, AccList) ->
vector_gen_tr(Left - 1, ElemType, [generate(ElemType) | AccList]).
@private
-spec union_gen([proper_types:type(),...]) -> imm_instance().
union_gen(Choices) ->
{_Choice,Type} = proper_arith:rand_choose(Choices),
generate(Type).
@private
-spec weighted_union_gen([{frequency(),proper_types:type()},...]) ->
imm_instance().
weighted_union_gen(FreqChoices) ->
{_Choice,Type} = proper_arith:freq_choose(FreqChoices),
generate(Type).
@private
-spec safe_union_gen([proper_types:type(),...]) -> imm_instance().
safe_union_gen(Choices) ->
{Choice,Type} = proper_arith:rand_choose(Choices),
try generate(Type)
catch
error:_ ->
safe_union_gen(proper_arith:list_remove(Choice, Choices))
end.
@private
-spec safe_weighted_union_gen([{frequency(),proper_types:type()},...]) ->
imm_instance().
safe_weighted_union_gen(FreqChoices) ->
{Choice,Type} = proper_arith:freq_choose(FreqChoices),
try generate(Type)
catch
error:_ ->
safe_weighted_union_gen(proper_arith:list_remove(Choice,
FreqChoices))
end.
@private
-spec tuple_gen([proper_types:type()]) -> tuple().
tuple_gen(Fields) ->
list_to_tuple(fixed_list_gen(Fields)).
@private
-spec loose_tuple_gen(size(), proper_types:type()) -> proper_types:type().
loose_tuple_gen(Size, ElemType) ->
?LET(L,
proper_types:resize(Size, proper_types:list(ElemType)),
list_to_tuple(L)).
@private
-spec loose_tuple_rev(tuple(), proper_types:type()) -> imm_instance().
loose_tuple_rev(Tuple, ElemType) ->
CleanList = tuple_to_list(Tuple),
List = case proper_types:find_prop(reverse_gen, ElemType) of
{ok,{typed, ReverseGen}} ->
[ReverseGen(ElemType,X) || X <- CleanList];
{ok,ReverseGen} -> [ReverseGen(X) || X <- CleanList];
error -> CleanList
end,
{'$used', List, Tuple}.
@private
-spec exactly_gen(T) -> T.
exactly_gen(X) ->
X.
@private
-spec fixed_list_gen([proper_types:type()]) -> imm_instance()
; ({[proper_types:type()],proper_types:type()}) ->
maybe_improper_list(imm_instance(), imm_instance() | []).
fixed_list_gen({ProperHead,ImproperTail}) ->
[generate(F) || F <- ProperHead] ++ generate(ImproperTail);
fixed_list_gen(ProperFields) ->
[generate(F) || F <- ProperFields].
@private
-spec function_gen(arity(), proper_types:type()) -> function().
function_gen(Arity, RetType) ->
FunSeed = {proper_arith:rand_int(0, ?SEED_RANGE - 1),
proper_arith:rand_int(0, ?SEED_RANGE - 1)},
create_fun(Arity, RetType, FunSeed).
@private
-spec any_gen(size()) -> imm_instance().
any_gen(Size) ->
case get('$any_type') of
undefined -> real_any_gen(Size);
{type,AnyType} -> generate(proper_types:resize(Size, AnyType))
end.
-spec real_any_gen(size()) -> imm_instance().
real_any_gen(0) ->
SimpleTypes = [proper_types:integer(), proper_types:float(),
proper_types:atom()],
union_gen(SimpleTypes);
real_any_gen(Size) ->
FreqChoices = [{?ANY_SIMPLE_PROB,simple}, {?ANY_BINARY_PROB,binary},
{?ANY_EXPAND_PROB,expand}],
case proper_arith:freq_choose(FreqChoices) of
{_,simple} ->
real_any_gen(0);
{_,binary} ->
generate(proper_types:resize(Size, proper_types:bitstring()));
{_,expand} ->
%% TODO: statistics of produced terms?
NumElems = proper_arith:rand_int(0, Size - 1),
ElemSizes = proper_arith:distribute(Size - 1, NumElems),
ElemTypes = [?LAZY(real_any_gen(S)) || S <- ElemSizes],
case proper_arith:rand_int(1,2) of
1 -> fixed_list_gen(ElemTypes);
2 -> tuple_gen(ElemTypes)
end
end.
@private
-spec native_type_gen(mod_name(), string()) -> proper_types:type().
native_type_gen(Mod, TypeStr) ->
case proper_typeserver:translate_type({Mod,TypeStr}) of
{ok,Type} -> Type;
{error,Reason} -> throw({'$typeserver',Reason})
end.
%%------------------------------------------------------------------------------
%% Function-generation functions
%%------------------------------------------------------------------------------
-spec create_fun(arity(), proper_types:type(), fun_seed()) -> function().
create_fun(Arity, RetType, FunSeed) ->
Handler = fun(Args) -> function_body(Args, RetType, FunSeed) end,
Err = fun() -> throw('$arity_limit') end,
'MAKE_FUN'(Arity, Handler, Err).
@private
-spec get_ret_type(function()) -> proper_types:type().
get_ret_type(Fun) ->
{arity,Arity} = erlang:fun_info(Fun, arity),
put('$get_ret_type', true),
RetType = apply(Fun, lists:duplicate(Arity,dummy)),
erase('$get_ret_type'),
RetType.
-spec function_body([term()], proper_types:type(), fun_seed()) ->
proper_types:type() | instance().
function_body(Args, RetType, {Seed1,Seed2}) ->
case get('$get_ret_type') of
true ->
RetType;
_ ->
SavedSeed = get(?SEED_NAME),
update_seed({Seed1,Seed2,erlang:phash2(Args,?SEED_RANGE)}),
Ret = clean_instance(generate(RetType)),
put(?SEED_NAME, SavedSeed),
proper_symb:internal_eval(Ret)
end.
-ifdef(USE_SFMT).
update_seed(Seed) ->
sfmt:seed(Seed).
-else.
update_seed(Seed) ->
put(random_seed, Seed).
-endif.
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/proper/src/proper_gen.erl | erlang |
PropEr is free software: you can redistribute it and/or modify
(at your option) any later version.
PropEr is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with PropEr. If not, see </>.
@version {@version}
@doc Generator subsystem and generators for basic types.
You can use <a href="#index">these</a> functions to try out the random
instance generation and shrinking subsystems.
CAUTION: These functions should never be used inside properties. They are
meant for demonstration purposes only.
-----------------------------------------------------------------------------
Types
-----------------------------------------------------------------------------
anything that returns it
A value produced by the random instance generator.
-----------------------------------------------------------------------------
Instance generation functions
-----------------------------------------------------------------------------
TODO: We can just generate the internal type: if it's not
a type, it will turn into an exactly.
@doc Generates a random instance of `Type', of size `Size' with seed `Seed'.
@doc Generates a random instance of `Type', of size `Size', then shrinks it
as far as it goes. The value produced on each step of the shrinking process
is printed on the screen.
-----------------------------------------------------------------------------
Utility functions
-----------------------------------------------------------------------------
CAUTION: this must handle improper lists
-----------------------------------------------------------------------------
Basic type generators
-----------------------------------------------------------------------------
character is not '$'.
TODO: this produces a lot of types: maybe a simple 'div' is sufficient?
TODO: statistics of produced terms?
------------------------------------------------------------------------------
Function-generation functions
------------------------------------------------------------------------------ | Copyright 2010 - 2015 < > ,
< >
and < >
This file is part of PropEr .
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
2010 - 2015 , and
@author
-module(proper_gen).
-export([pick/1, pick/2, pick/3,
sample/1, sample/3, sampleshrink/1, sampleshrink/2]).
-export([safe_generate/1]).
-export([generate/1, normal_gen/1, alt_gens/1, clean_instance/1,
get_ret_type/1]).
-export([integer_gen/3, float_gen/3, atom_gen/1, atom_rev/1, binary_gen/1,
binary_rev/1, binary_len_gen/1, bitstring_gen/1, bitstring_rev/1,
bitstring_len_gen/1, list_gen/2, distlist_gen/3, vector_gen/2,
union_gen/1, weighted_union_gen/1, tuple_gen/1, loose_tuple_gen/2,
loose_tuple_rev/2, exactly_gen/1, fixed_list_gen/1, function_gen/2,
any_gen/1, native_type_gen/2, safe_weighted_union_gen/1,
safe_union_gen/1]).
-export_type([instance/0, imm_instance/0, sized_generator/0, nosize_generator/0,
generator/0, reverse_gen/0, combine_fun/0, alt_gens/0]).
-include("proper_internal.hrl").
-compile({parse_transform, vararg}).
TODO : update ( ) when adding more types : be careful when reading
@private_type
-type imm_instance() :: proper_types:raw_type()
| instance()
| {'$used', imm_instance(), imm_instance()}
| {'$to_part', imm_instance()}.
-type instance() :: term().
-type error_reason() :: 'arity_limit' | 'cant_generate' | {'typeserver',term()}.
@private_type
-type sized_generator() :: fun((size()) -> imm_instance()).
@private_type
-type typed_sized_generator() :: {'typed',
fun((proper_types:type(),size()) ->
imm_instance())}.
@private_type
-type nosize_generator() :: fun(() -> imm_instance()).
@private_type
-type typed_nosize_generator() :: {'typed',
fun((proper_types:type()) ->
imm_instance())}.
@private_type
-type generator() :: sized_generator()
| typed_sized_generator()
| nosize_generator()
| typed_nosize_generator().
@private_type
-type plain_reverse_gen() :: fun((instance()) -> imm_instance()).
@private_type
-type typed_reverse_gen() :: {'typed',
fun((proper_types:type(),instance()) ->
imm_instance())}.
@private_type
-type reverse_gen() :: plain_reverse_gen() | typed_reverse_gen().
@private_type
-type combine_fun() :: fun((instance()) -> imm_instance()).
@private_type
-type alt_gens() :: fun(() -> [imm_instance()]).
@private_type
-type fun_seed() :: {non_neg_integer(),non_neg_integer()}.
@private
-spec safe_generate(proper_types:raw_type()) ->
{'ok',imm_instance()} | {'error',error_reason()}.
safe_generate(RawType) ->
try generate(RawType) of
ImmInstance -> {ok, ImmInstance}
catch
throw:'$arity_limit' -> {error, arity_limit};
throw:'$cant_generate' -> {error, cant_generate};
throw:{'$typeserver',SubReason} -> {error, {typeserver,SubReason}}
end.
@private
-spec generate(proper_types:raw_type()) -> imm_instance().
generate(RawType) ->
Type = proper_types:cook_outer(RawType),
ok = add_parameters(Type),
Instance = generate(Type, get('$constraint_tries'), none),
ok = remove_parameters(Type),
Instance.
-spec add_parameters(proper_types:type()) -> 'ok'.
add_parameters(Type) ->
case proper_types:find_prop(parameters, Type) of
{ok, Params} ->
OldParams = erlang:get('$parameters'),
case OldParams of
undefined ->
erlang:put('$parameters', Params);
_ ->
erlang:put('$parameters', Params ++ OldParams)
end,
ok;
_ ->
ok
end.
-spec remove_parameters(proper_types:type()) -> 'ok'.
remove_parameters(Type) ->
case proper_types:find_prop(parameters, Type) of
{ok, Params} ->
AllParams = erlang:get('$parameters'),
case AllParams of
Params->
erlang:erase('$parameters');
_ ->
erlang:put('$parameters', AllParams -- Params)
end,
ok;
_ ->
ok
end.
-spec generate(proper_types:type(), non_neg_integer(),
'none' | {'ok',imm_instance()}) -> imm_instance().
generate(_Type, 0, none) ->
throw('$cant_generate');
generate(_Type, 0, {ok,Fallback}) ->
Fallback;
generate(Type, TriesLeft, Fallback) ->
ImmInstance =
case proper_types:get_prop(kind, Type) of
constructed ->
PartsType = proper_types:get_prop(parts_type, Type),
Combine = proper_types:get_prop(combine, Type),
ImmParts = generate(PartsType),
Parts = clean_instance(ImmParts),
ImmInstance1 = Combine(Parts),
ImmInstance2 =
case proper_types:is_raw_type(ImmInstance1) of
true -> generate(ImmInstance1);
false -> ImmInstance1
end,
{'$used',ImmParts,ImmInstance2};
_ ->
ImmInstance1 = normal_gen(Type),
case proper_types:is_raw_type(ImmInstance1) of
true -> generate(ImmInstance1);
false -> ImmInstance1
end
end,
case proper_types:satisfies_all(clean_instance(ImmInstance), Type) of
{_,true} -> ImmInstance;
{true,false} -> generate(Type, TriesLeft - 1, {ok,ImmInstance});
{false,false} -> generate(Type, TriesLeft - 1, Fallback)
end.
@equiv pick(Type , 10 )
-spec pick(Type::proper_types:raw_type()) -> {'ok',instance()} | 'error'.
pick(RawType) ->
pick(RawType, 10).
@equiv pick(Type , Size , os : timestamp ( ) )
-spec pick(Type::proper_types:raw_type(), size()) -> {'ok',instance()} | 'error'.
pick(RawType, Size) ->
pick(RawType, Size, os:timestamp()).
-spec pick(Type::proper_types:raw_type(), size(), seed()) ->
{'ok',instance()} | 'error'.
pick(RawType, Size, Seed) ->
proper:global_state_init_size_seed(Size, Seed),
case clean_instance(safe_generate(RawType)) of
{ok,Instance} = Result ->
Msg = "WARNING: Some garbage has been left in the process registry "
"and the code server~n"
"to allow for the returned function(s) to run normally.~n"
"Please run proper:global_state_erase() when done.~n",
case contains_fun(Instance) of
true -> io:format(Msg, []);
false -> proper:global_state_erase()
end,
Result;
{error,Reason} ->
proper:report_error(Reason, fun io:format/2),
proper:global_state_erase(),
error
end.
@equiv sample(Type , 10 , 20 )
-spec sample(Type::proper_types:raw_type()) -> 'ok'.
sample(RawType) ->
sample(RawType, 10, 20).
@doc Generates and prints one random instance of ` Type ' for each size from
` StartSize ' up to ` EndSize ' .
-spec sample(Type::proper_types:raw_type(), size(), size()) -> 'ok'.
sample(RawType, StartSize, EndSize) when StartSize =< EndSize ->
Tests = EndSize - StartSize + 1,
Prop = ?FORALL(X, RawType, begin io:format("~p~n",[X]), true end),
Opts = [quiet,{start_size,StartSize},{max_size,EndSize},{numtests,Tests}],
_ = proper:quickcheck(Prop, Opts),
ok.
@equiv sampleshrink(Type , 10 )
-spec sampleshrink(Type::proper_types:raw_type()) -> 'ok'.
sampleshrink(RawType) ->
sampleshrink(RawType, 10).
-spec sampleshrink(Type::proper_types:raw_type(), size()) -> 'ok'.
sampleshrink(RawType, Size) ->
proper:global_state_init_size(Size),
Type = proper_types:cook_outer(RawType),
case safe_generate(Type) of
{ok,ImmInstance} ->
Shrunk = keep_shrinking(ImmInstance, [], Type),
PrintInst = fun(I) -> io:format("~p~n",[clean_instance(I)]) end,
lists:foreach(PrintInst, Shrunk);
{error,Reason} ->
proper:report_error(Reason, fun io:format/2)
end,
proper:global_state_erase(),
ok.
-spec keep_shrinking(imm_instance(), [imm_instance()], proper_types:type()) ->
[imm_instance(),...].
keep_shrinking(ImmInstance, Acc, Type) ->
case proper_shrink:shrink(ImmInstance, Type, init) of
{[], _NewState} ->
lists:reverse([ImmInstance|Acc]);
{[Shrunk|_Rest], _NewState} ->
keep_shrinking(Shrunk, [ImmInstance|Acc], Type)
end.
-spec contains_fun(term()) -> boolean().
contains_fun(List) when is_list(List) ->
proper_arith:safe_any(fun contains_fun/1, List);
contains_fun(Tuple) when is_tuple(Tuple) ->
contains_fun(tuple_to_list(Tuple));
contains_fun(Fun) when is_function(Fun) ->
true;
contains_fun(_Term) ->
false.
@private
-spec normal_gen(proper_types:type()) -> imm_instance().
normal_gen(Type) ->
case proper_types:get_prop(generator, Type) of
{typed, Gen} ->
if
is_function(Gen, 1) -> Gen(Type);
is_function(Gen, 2) -> Gen(Type, proper:get_size(Type))
end;
Gen ->
if
is_function(Gen, 0) -> Gen();
is_function(Gen, 1) -> Gen(proper:get_size(Type))
end
end.
@private
-spec alt_gens(proper_types:type()) -> [imm_instance()].
alt_gens(Type) ->
case proper_types:find_prop(alt_gens, Type) of
{ok, AltGens} -> ?FORCE(AltGens);
error -> []
end.
@private
-spec clean_instance(imm_instance()) -> instance().
clean_instance({'$used',_ImmParts,ImmInstance}) ->
clean_instance(ImmInstance);
clean_instance({'$to_part',ImmInstance}) ->
clean_instance(ImmInstance);
clean_instance(ImmInstance) ->
if
is_list(ImmInstance) ->
proper_arith:safe_map(fun clean_instance/1, ImmInstance);
is_tuple(ImmInstance) ->
proper_arith:tuple_map(fun clean_instance/1, ImmInstance);
true ->
ImmInstance
end.
@private
-spec integer_gen(size(), proper_types:extint(), proper_types:extint()) ->
integer().
integer_gen(Size, inf, inf) ->
proper_arith:rand_int(Size);
integer_gen(Size, inf, High) ->
High - proper_arith:rand_non_neg_int(Size);
integer_gen(Size, Low, inf) ->
Low + proper_arith:rand_non_neg_int(Size);
integer_gen(Size, Low, High) ->
proper_arith:smart_rand_int(Size, Low, High).
@private
-spec float_gen(size(), proper_types:extnum(), proper_types:extnum()) ->
float().
float_gen(Size, inf, inf) ->
proper_arith:rand_float(Size);
float_gen(Size, inf, High) ->
High - proper_arith:rand_non_neg_float(Size);
float_gen(Size, Low, inf) ->
Low + proper_arith:rand_non_neg_float(Size);
float_gen(_Size, Low, High) ->
proper_arith:rand_float(Low, High).
@private
-spec atom_gen(size()) -> proper_types:type().
We make sure we never clash with internal atoms by checking that the first
atom_gen(Size) ->
?LET(Str,
?SUCHTHAT(X,
proper_types:resize(Size,
proper_types:list(proper_types:byte())),
X =:= [] orelse hd(X) =/= $$),
list_to_atom(Str)).
@private
-spec atom_rev(atom()) -> imm_instance().
atom_rev(Atom) ->
{'$used', atom_to_list(Atom), Atom}.
@private
-spec binary_gen(size()) -> proper_types:type().
binary_gen(Size) ->
?LET(Bytes,
proper_types:resize(Size,
proper_types:list(proper_types:byte())),
list_to_binary(Bytes)).
@private
-spec binary_rev(binary()) -> imm_instance().
binary_rev(Binary) ->
{'$used', binary_to_list(Binary), Binary}.
@private
-spec binary_len_gen(length()) -> proper_types:type().
binary_len_gen(Len) ->
?LET(Bytes,
proper_types:vector(Len, proper_types:byte()),
list_to_binary(Bytes)).
@private
-spec bitstring_gen(size()) -> proper_types:type().
bitstring_gen(Size) ->
?LET({BytesHead, NumBits, TailByte},
{proper_types:resize(Size,proper_types:binary()),
proper_types:range(0,7), proper_types:range(0,127)},
<<BytesHead/binary, TailByte:NumBits>>).
@private
-spec bitstring_rev(bitstring()) -> imm_instance().
bitstring_rev(BitString) ->
List = bitstring_to_list(BitString),
{BytesList, BitsTail} = lists:splitwith(fun erlang:is_integer/1, List),
{NumBits, TailByte} = case BitsTail of
[] -> {0, 0};
[Bits] -> N = bit_size(Bits),
<<Byte:N>> = Bits,
{N, Byte}
end,
{'$used',
{{'$used',BytesList,list_to_binary(BytesList)}, NumBits, TailByte},
BitString}.
@private
-spec bitstring_len_gen(length()) -> proper_types:type().
bitstring_len_gen(Len) ->
BytesLen = Len div 8,
BitsLen = Len rem 8,
?LET({BytesHead, NumBits, TailByte},
{proper_types:binary(BytesLen), BitsLen,
proper_types:range(0, 1 bsl BitsLen - 1)},
<<BytesHead/binary, TailByte:NumBits>>).
@private
-spec list_gen(size(), proper_types:type()) -> [imm_instance()].
list_gen(Size, ElemType) ->
Len = proper_arith:rand_int(0, Size),
vector_gen(Len, ElemType).
@private
-spec distlist_gen(size(), sized_generator(), boolean()) -> [imm_instance()].
distlist_gen(RawSize, Gen, NonEmpty) ->
Len = case NonEmpty of
true -> proper_arith:rand_int(1, erlang:max(1,RawSize));
false -> proper_arith:rand_int(0, RawSize)
end,
Size = case Len of
1 -> RawSize - 1;
_ -> RawSize
end,
Sizes = proper_arith:distribute(Size, Len),
InnerTypes = [Gen(S) || S <- Sizes],
fixed_list_gen(InnerTypes).
@private
-spec vector_gen(length(), proper_types:type()) -> [imm_instance()].
vector_gen(Len, ElemType) ->
vector_gen_tr(Len, ElemType, []).
-spec vector_gen_tr(length(), proper_types:type(), [imm_instance()]) ->
[imm_instance()].
vector_gen_tr(0, _ElemType, AccList) ->
AccList;
vector_gen_tr(Left, ElemType, AccList) ->
vector_gen_tr(Left - 1, ElemType, [generate(ElemType) | AccList]).
@private
-spec union_gen([proper_types:type(),...]) -> imm_instance().
union_gen(Choices) ->
{_Choice,Type} = proper_arith:rand_choose(Choices),
generate(Type).
@private
-spec weighted_union_gen([{frequency(),proper_types:type()},...]) ->
imm_instance().
weighted_union_gen(FreqChoices) ->
{_Choice,Type} = proper_arith:freq_choose(FreqChoices),
generate(Type).
@private
-spec safe_union_gen([proper_types:type(),...]) -> imm_instance().
safe_union_gen(Choices) ->
{Choice,Type} = proper_arith:rand_choose(Choices),
try generate(Type)
catch
error:_ ->
safe_union_gen(proper_arith:list_remove(Choice, Choices))
end.
@private
-spec safe_weighted_union_gen([{frequency(),proper_types:type()},...]) ->
imm_instance().
safe_weighted_union_gen(FreqChoices) ->
{Choice,Type} = proper_arith:freq_choose(FreqChoices),
try generate(Type)
catch
error:_ ->
safe_weighted_union_gen(proper_arith:list_remove(Choice,
FreqChoices))
end.
@private
-spec tuple_gen([proper_types:type()]) -> tuple().
tuple_gen(Fields) ->
list_to_tuple(fixed_list_gen(Fields)).
@private
-spec loose_tuple_gen(size(), proper_types:type()) -> proper_types:type().
loose_tuple_gen(Size, ElemType) ->
?LET(L,
proper_types:resize(Size, proper_types:list(ElemType)),
list_to_tuple(L)).
@private
-spec loose_tuple_rev(tuple(), proper_types:type()) -> imm_instance().
loose_tuple_rev(Tuple, ElemType) ->
CleanList = tuple_to_list(Tuple),
List = case proper_types:find_prop(reverse_gen, ElemType) of
{ok,{typed, ReverseGen}} ->
[ReverseGen(ElemType,X) || X <- CleanList];
{ok,ReverseGen} -> [ReverseGen(X) || X <- CleanList];
error -> CleanList
end,
{'$used', List, Tuple}.
@private
-spec exactly_gen(T) -> T.
exactly_gen(X) ->
X.
@private
-spec fixed_list_gen([proper_types:type()]) -> imm_instance()
; ({[proper_types:type()],proper_types:type()}) ->
maybe_improper_list(imm_instance(), imm_instance() | []).
fixed_list_gen({ProperHead,ImproperTail}) ->
[generate(F) || F <- ProperHead] ++ generate(ImproperTail);
fixed_list_gen(ProperFields) ->
[generate(F) || F <- ProperFields].
@private
-spec function_gen(arity(), proper_types:type()) -> function().
function_gen(Arity, RetType) ->
FunSeed = {proper_arith:rand_int(0, ?SEED_RANGE - 1),
proper_arith:rand_int(0, ?SEED_RANGE - 1)},
create_fun(Arity, RetType, FunSeed).
@private
-spec any_gen(size()) -> imm_instance().
any_gen(Size) ->
case get('$any_type') of
undefined -> real_any_gen(Size);
{type,AnyType} -> generate(proper_types:resize(Size, AnyType))
end.
-spec real_any_gen(size()) -> imm_instance().
real_any_gen(0) ->
SimpleTypes = [proper_types:integer(), proper_types:float(),
proper_types:atom()],
union_gen(SimpleTypes);
real_any_gen(Size) ->
FreqChoices = [{?ANY_SIMPLE_PROB,simple}, {?ANY_BINARY_PROB,binary},
{?ANY_EXPAND_PROB,expand}],
case proper_arith:freq_choose(FreqChoices) of
{_,simple} ->
real_any_gen(0);
{_,binary} ->
generate(proper_types:resize(Size, proper_types:bitstring()));
{_,expand} ->
NumElems = proper_arith:rand_int(0, Size - 1),
ElemSizes = proper_arith:distribute(Size - 1, NumElems),
ElemTypes = [?LAZY(real_any_gen(S)) || S <- ElemSizes],
case proper_arith:rand_int(1,2) of
1 -> fixed_list_gen(ElemTypes);
2 -> tuple_gen(ElemTypes)
end
end.
@private
-spec native_type_gen(mod_name(), string()) -> proper_types:type().
native_type_gen(Mod, TypeStr) ->
case proper_typeserver:translate_type({Mod,TypeStr}) of
{ok,Type} -> Type;
{error,Reason} -> throw({'$typeserver',Reason})
end.
-spec create_fun(arity(), proper_types:type(), fun_seed()) -> function().
create_fun(Arity, RetType, FunSeed) ->
Handler = fun(Args) -> function_body(Args, RetType, FunSeed) end,
Err = fun() -> throw('$arity_limit') end,
'MAKE_FUN'(Arity, Handler, Err).
@private
-spec get_ret_type(function()) -> proper_types:type().
get_ret_type(Fun) ->
{arity,Arity} = erlang:fun_info(Fun, arity),
put('$get_ret_type', true),
RetType = apply(Fun, lists:duplicate(Arity,dummy)),
erase('$get_ret_type'),
RetType.
-spec function_body([term()], proper_types:type(), fun_seed()) ->
proper_types:type() | instance().
function_body(Args, RetType, {Seed1,Seed2}) ->
case get('$get_ret_type') of
true ->
RetType;
_ ->
SavedSeed = get(?SEED_NAME),
update_seed({Seed1,Seed2,erlang:phash2(Args,?SEED_RANGE)}),
Ret = clean_instance(generate(RetType)),
put(?SEED_NAME, SavedSeed),
proper_symb:internal_eval(Ret)
end.
-ifdef(USE_SFMT).
update_seed(Seed) ->
sfmt:seed(Seed).
-else.
update_seed(Seed) ->
put(random_seed, Seed).
-endif.
|
03f920d7670e844a9784d8f08e37cec55debf56af7deebd0df58a22b8216665a | mikera/core.matrix | test_load.clj | (ns test.misc.test-load
(:require [clojure.core.matrix.macros :refer [error]]))
(defn foo []
(doall
(map deref (for [i (range 10)]
(future
(require 'test.misc.loading-test)
(if (not (deref (resolve 'test.misc.loading-test/loaded)))
(error "Not loaded!")
:OK))))))
| null | https://raw.githubusercontent.com/mikera/core.matrix/0a35f6e3d6d2335cb56f6f3e5744bfa1dd0390aa/src/test/clojure/test/misc/test_load.clj | clojure | (ns test.misc.test-load
(:require [clojure.core.matrix.macros :refer [error]]))
(defn foo []
(doall
(map deref (for [i (range 10)]
(future
(require 'test.misc.loading-test)
(if (not (deref (resolve 'test.misc.loading-test/loaded)))
(error "Not loaded!")
:OK))))))
| |
30073b73653adabfb2cfb169abf51aba388914692fdec9747fff7d1dc6a2dc0c | googleson78/fp-lab-2022-23 | TicTacToe.hs | module MinMax.TicTacToe where
optimiseFor :: a
optimiseFor = undefined
| null | https://raw.githubusercontent.com/googleson78/fp-lab-2022-23/0d5b8aa7a1c572352658cd41b082da6a29ad07ad/homeworks/draft-minmax/src/MinMax/TicTacToe.hs | haskell | module MinMax.TicTacToe where
optimiseFor :: a
optimiseFor = undefined
| |
f02e139f6104630fe2e2d1281f0d4a915b09293a91a01a778d2c973f98f08079 | data61/Mirza | Main.hs | # LANGUAGE DataKinds #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeApplications #
module Mirza.Trails.Main where
import Mirza.Trails.API
import Mirza.Trails.Database.Migrate
import Mirza.Trails.Service
import Mirza.Trails.Types
import Mirza.Common.Types
import Katip as K
import Servant
import Servant.Swagger.UI
import Database.PostgreSQL.Simple
import Network.Wai (Middleware)
import qualified Network.Wai.Handler.Warp as Warp
import Control.Exception (finally)
import Control.Monad (when)
import System.Exit (die)
import System.IO (FilePath, IOMode (AppendMode),
hPutStr, openFile, stderr,
stdout)
import Data.ByteString (ByteString)
import Data.Maybe (fromMaybe)
import qualified Data.Pool as Pool
import Data.Semigroup ((<>))
import Data.Text (pack)
import Options.Applicative hiding (action)
--------------------------------------------------------------------------------
-- Constants
--------------------------------------------------------------------------------
| Port number changed so that OR and SCS can be run at the same time
defaultPortNumber :: Int
defaultPortNumber = 8300
defaultDatabaseConnectionString :: ByteString
defaultDatabaseConnectionString = "dbname=devtrails"
--------------------------------------------------------------------------------
-- Command Line Options Data Types
--------------------------------------------------------------------------------
data InitOptionsTrails = InitOptionsTrails
{ iotGlobals :: ServerOptionsTrails
, iotExecMode :: ExecMode
}
data ExecMode
= RunServer RunServerOptions
| InitDb
data ServerOptionsTrails = ServerOptionsTrails
{ mandatoryOptionsDbConnStr :: ByteString
, mandatoryOptionsLoggingLevel :: K.Severity
, mandatoryOptionsLogLocation :: Maybe FilePath
, mandatoryOptionsEnvType :: EnvType
}
data RunServerOptions = RunServerOptions
{ runServerOptionsPortNumber :: Int
, runServerOptionsAutoMigrate :: Bool
}
--------------------------------------------------------------------------------
-- Main
--------------------------------------------------------------------------------
main :: IO ()
main = multiplexInitOptions =<< execParser opts where
opts = Options.Applicative.info (serverOptions <**> helper)
(fullDesc
<> progDesc "Here to meet all your trail needs"
<> header "Trails Service")
-- Handles the overriding server options (this effectively defines the point
-- where the single binary could be split into multiple binaries.
multiplexInitOptions :: InitOptionsTrails -> IO ()
multiplexInitOptions (InitOptionsTrails opts mode) = case mode of
RunServer rsOpts -> launchServer opts rsOpts
InitDb -> runMigration opts
--------------------------------------------------------------------------------
-- Service
--------------------------------------------------------------------------------
launchServer :: ServerOptionsTrails -> RunServerOptions -> IO ()
launchServer opts rso = do
let portNumber = runServerOptionsPortNumber rso
context <- initTrailsContext opts
app <- initApplication context
mids <- initMiddleware opts rso
when (runServerOptionsAutoMigrate rso) $ do
res <- runMigrationSimple @TrailsContext @SqlError context migrations
case res of
Left sqlError -> die ("Could not perform auto-migration:\n\t" <> show sqlError)
Right _ -> pure ()
putStrLn $ ":" ++ show portNumber ++ "/swagger-ui/"
Warp.run (fromIntegral portNumber) (mids app) `finally` closeScribes (_trailsKatipLogEnv context)
initTrailsContext :: ServerOptionsTrails -> IO TrailsContext
initTrailsContext (ServerOptionsTrails dbConnStr lev mlogPath envT) = do
logHandle <- maybe (pure stdout) (flip openFile AppendMode) mlogPath
hPutStr stderr $ "(Logging will be to: " ++ fromMaybe "stdout" mlogPath ++ ") "
handleScribe <- mkHandleScribe ColorIfTerminal logHandle lev V3
logEnv <- initLogEnv "trailsService" (Environment . pack . show $ envT)
>>= registerScribe "stdout" handleScribe defaultScribeSettings
connpool <- Pool.createPool (connectPostgreSQL dbConnStr) close
1 -- Number of "sub-pools",
How long in seconds to keep a connection open for reuse
number of connections to have open at any one time
TODO : Make this a config paramete
pure $ TrailsContext envT connpool logEnv mempty mempty
initApplication :: TrailsContext -> IO Application
initApplication ev =
pure $ serve api (server ev)
initMiddleware :: ServerOptionsTrails -> RunServerOptions -> IO Middleware
initMiddleware _ _ = pure id
-- Implementation
server :: TrailsContext -> Server API
server context =
swaggerSchemaUIServer serveSwaggerAPI
:<|> hoistServer
(Proxy @ServerAPI)
(appMToHandler context)
(appHandlers)
--------------------------------------------------------------------------------
Migration Command
--------------------------------------------------------------------------------
runMigration :: ServerOptionsTrails -> IO ()
runMigration opts = do
ctx <- initTrailsContext opts
res <- runMigrationSimple @TrailsContext @SqlError ctx migrations
print res
pure ()
--------------------------------------------------------------------------------
Command Line Options Argument Parsers
--------------------------------------------------------------------------------
standardCommand :: String -> Parser a -> String -> Mod CommandFields a
standardCommand name action desciption =
command name (info (action <**> helper) (progDesc desciption))
-- The standard format of the main command line options is [Command] [Action], this applies to things like org and user.
serverOptions :: Parser InitOptionsTrails
serverOptions = InitOptionsTrails
<$> parsedServerOptions
<*> subparser
( mconcat
[ standardCommand "server" runServer "Run HTTP server"
, standardCommand "initdb" initDb "Initialise the Database (Note: This command only works if the database \
\is empty and can't be used for migrations or if the database already \
\contains the schema."
]
)
runServer :: Parser ExecMode
runServer = RunServer <$> (RunServerOptions
<$> option auto ( long "port"
<> help "Port to run the service on."
<> showDefault
<> value defaultPortNumber
)
<*> switch ( long "migrate"
<> help "Run migrations on application start."
)
)
parsedServerOptions :: Parser ServerOptionsTrails
parsedServerOptions = ServerOptionsTrails
<$> strOption
(
long "conn"
<> short 'c'
<> help "Database connection string in libpq format. See: -connect.html#LIBPQ-CONNSTRING"
<> showDefault
<> value defaultDatabaseConnectionString
)
<*> option auto
( long "log-level"
<> value InfoS
<> showDefault
<> help ("Logging level: " ++ show [minBound .. maxBound :: Severity])
)
<*> optional (strOption
( long "log-path"
<> short 'l'
<> help "Path to write log output to (defaults to stdout)"
) )
<*> option auto
( long "env" <> short 'e'
<> value Dev <> showDefault
<> help "Environment, Dev | Prod"
)
TODO : Add flag to change from interactive confirmation to instead be automatic operation ( so this command can be used from scripts or whatnot ) ( e.g. ) .
initDb :: Parser ExecMode
initDb = pure InitDb
| null | https://raw.githubusercontent.com/data61/Mirza/24e5ccddfc307cceebcc5ce26d35e91020b8ee10/projects/trails/src/Mirza/Trails/Main.hs | haskell | # LANGUAGE OverloadedStrings #
------------------------------------------------------------------------------
Constants
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Command Line Options Data Types
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Main
------------------------------------------------------------------------------
Handles the overriding server options (this effectively defines the point
where the single binary could be split into multiple binaries.
------------------------------------------------------------------------------
Service
------------------------------------------------------------------------------
Number of "sub-pools",
Implementation
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
The standard format of the main command line options is [Command] [Action], this applies to things like org and user. | # LANGUAGE DataKinds #
# LANGUAGE TypeApplications #
module Mirza.Trails.Main where
import Mirza.Trails.API
import Mirza.Trails.Database.Migrate
import Mirza.Trails.Service
import Mirza.Trails.Types
import Mirza.Common.Types
import Katip as K
import Servant
import Servant.Swagger.UI
import Database.PostgreSQL.Simple
import Network.Wai (Middleware)
import qualified Network.Wai.Handler.Warp as Warp
import Control.Exception (finally)
import Control.Monad (when)
import System.Exit (die)
import System.IO (FilePath, IOMode (AppendMode),
hPutStr, openFile, stderr,
stdout)
import Data.ByteString (ByteString)
import Data.Maybe (fromMaybe)
import qualified Data.Pool as Pool
import Data.Semigroup ((<>))
import Data.Text (pack)
import Options.Applicative hiding (action)
| Port number changed so that OR and SCS can be run at the same time
defaultPortNumber :: Int
defaultPortNumber = 8300
defaultDatabaseConnectionString :: ByteString
defaultDatabaseConnectionString = "dbname=devtrails"
data InitOptionsTrails = InitOptionsTrails
{ iotGlobals :: ServerOptionsTrails
, iotExecMode :: ExecMode
}
data ExecMode
= RunServer RunServerOptions
| InitDb
data ServerOptionsTrails = ServerOptionsTrails
{ mandatoryOptionsDbConnStr :: ByteString
, mandatoryOptionsLoggingLevel :: K.Severity
, mandatoryOptionsLogLocation :: Maybe FilePath
, mandatoryOptionsEnvType :: EnvType
}
data RunServerOptions = RunServerOptions
{ runServerOptionsPortNumber :: Int
, runServerOptionsAutoMigrate :: Bool
}
main :: IO ()
main = multiplexInitOptions =<< execParser opts where
opts = Options.Applicative.info (serverOptions <**> helper)
(fullDesc
<> progDesc "Here to meet all your trail needs"
<> header "Trails Service")
multiplexInitOptions :: InitOptionsTrails -> IO ()
multiplexInitOptions (InitOptionsTrails opts mode) = case mode of
RunServer rsOpts -> launchServer opts rsOpts
InitDb -> runMigration opts
launchServer :: ServerOptionsTrails -> RunServerOptions -> IO ()
launchServer opts rso = do
let portNumber = runServerOptionsPortNumber rso
context <- initTrailsContext opts
app <- initApplication context
mids <- initMiddleware opts rso
when (runServerOptionsAutoMigrate rso) $ do
res <- runMigrationSimple @TrailsContext @SqlError context migrations
case res of
Left sqlError -> die ("Could not perform auto-migration:\n\t" <> show sqlError)
Right _ -> pure ()
putStrLn $ ":" ++ show portNumber ++ "/swagger-ui/"
Warp.run (fromIntegral portNumber) (mids app) `finally` closeScribes (_trailsKatipLogEnv context)
initTrailsContext :: ServerOptionsTrails -> IO TrailsContext
initTrailsContext (ServerOptionsTrails dbConnStr lev mlogPath envT) = do
logHandle <- maybe (pure stdout) (flip openFile AppendMode) mlogPath
hPutStr stderr $ "(Logging will be to: " ++ fromMaybe "stdout" mlogPath ++ ") "
handleScribe <- mkHandleScribe ColorIfTerminal logHandle lev V3
logEnv <- initLogEnv "trailsService" (Environment . pack . show $ envT)
>>= registerScribe "stdout" handleScribe defaultScribeSettings
connpool <- Pool.createPool (connectPostgreSQL dbConnStr) close
How long in seconds to keep a connection open for reuse
number of connections to have open at any one time
TODO : Make this a config paramete
pure $ TrailsContext envT connpool logEnv mempty mempty
initApplication :: TrailsContext -> IO Application
initApplication ev =
pure $ serve api (server ev)
initMiddleware :: ServerOptionsTrails -> RunServerOptions -> IO Middleware
initMiddleware _ _ = pure id
server :: TrailsContext -> Server API
server context =
swaggerSchemaUIServer serveSwaggerAPI
:<|> hoistServer
(Proxy @ServerAPI)
(appMToHandler context)
(appHandlers)
Migration Command
runMigration :: ServerOptionsTrails -> IO ()
runMigration opts = do
ctx <- initTrailsContext opts
res <- runMigrationSimple @TrailsContext @SqlError ctx migrations
print res
pure ()
Command Line Options Argument Parsers
standardCommand :: String -> Parser a -> String -> Mod CommandFields a
standardCommand name action desciption =
command name (info (action <**> helper) (progDesc desciption))
serverOptions :: Parser InitOptionsTrails
serverOptions = InitOptionsTrails
<$> parsedServerOptions
<*> subparser
( mconcat
[ standardCommand "server" runServer "Run HTTP server"
, standardCommand "initdb" initDb "Initialise the Database (Note: This command only works if the database \
\is empty and can't be used for migrations or if the database already \
\contains the schema."
]
)
runServer :: Parser ExecMode
runServer = RunServer <$> (RunServerOptions
<$> option auto ( long "port"
<> help "Port to run the service on."
<> showDefault
<> value defaultPortNumber
)
<*> switch ( long "migrate"
<> help "Run migrations on application start."
)
)
parsedServerOptions :: Parser ServerOptionsTrails
parsedServerOptions = ServerOptionsTrails
<$> strOption
(
long "conn"
<> short 'c'
<> help "Database connection string in libpq format. See: -connect.html#LIBPQ-CONNSTRING"
<> showDefault
<> value defaultDatabaseConnectionString
)
<*> option auto
( long "log-level"
<> value InfoS
<> showDefault
<> help ("Logging level: " ++ show [minBound .. maxBound :: Severity])
)
<*> optional (strOption
( long "log-path"
<> short 'l'
<> help "Path to write log output to (defaults to stdout)"
) )
<*> option auto
( long "env" <> short 'e'
<> value Dev <> showDefault
<> help "Environment, Dev | Prod"
)
TODO : Add flag to change from interactive confirmation to instead be automatic operation ( so this command can be used from scripts or whatnot ) ( e.g. ) .
initDb :: Parser ExecMode
initDb = pure InitDb
|
3434dd32c17d6d235280af21e0b9d2832758226b2e3db5f59b3b98c40af73ea7 | fantasytree/fancy_game_server | emysql_conn.erl | Copyright ( c ) 2009 - 2012
< > ,
< > ,
< > ,
%% Eonblast Corporation <>
%%
%% 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 restric-
%% tion, 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(emysql_conn).
-export([set_database/2, set_encoding/2,
execute/3, prepare/3, unprepare/2,
open_connections/1, open_connection/1,
reset_connection/3, close_connection/1,
open_n_connections/2, hstate/1
]).
-include("emysql.hrl").
set_database(_, undefined) -> ok;
set_database(_, Empty) when Empty == ""; Empty == <<>> -> ok;
set_database(Connection, Database) ->
Packet = <<?COM_QUERY, "use `", (iolist_to_binary(Database))/binary, "`">>, % todo: utf8?
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0).
set_encoding(Connection, Encoding) ->
Packet = <<?COM_QUERY, "set names '", (erlang:atom_to_binary(Encoding, utf8))/binary, "'">>,
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0).
execute(Connection, Query, []) when is_list(Query) ->
-% io : format("~p execute list : ~p using connection : ~p ~ n " , [ self ( ) , ) , Connection#emysql_connection.id ] ) ,
Packet = <<?COM_QUERY, (emysql_util:to_binary(Query, Connection#emysql_connection.encoding))/binary>>,
% Packet = <<?COM_QUERY, (iolist_to_binary(Query))/binary>>,
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0);
execute(Connection, Query, []) when is_binary(Query) ->
-% io : format("~p execute binary : ~p using connection : ~p ~ n " , [ self ( ) , Query , Connection#emysql_connection.id ] ) ,
Packet = <<?COM_QUERY, Query/binary>>,
% Packet = <<?COM_QUERY, (iolist_to_binary(Query))/binary>>,
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0);
execute(Connection, StmtName, []) when is_atom(StmtName) ->
prepare_statement(Connection, StmtName),
StmtNameBin = atom_to_binary(StmtName, utf8),
Packet = <<?COM_QUERY, "EXECUTE ", StmtNameBin/binary>>,
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0);
execute(Connection, Query, Args) when (is_list(Query) orelse is_binary(Query)) andalso is_list(Args) ->
StmtName = "stmt_"++integer_to_list(erlang:phash2(Query)),
ok = prepare(Connection, StmtName, Query),
Ret =
case set_params(Connection, 1, Args, undefined) of
OK when is_record(OK, ok_packet) ->
ParamNamesBin = list_to_binary(string:join([[$@ | integer_to_list(I)] || I <- lists:seq(1, length(Args))], ", ")), % todo: utf8?
Packet = <<?COM_QUERY, "EXECUTE ", (list_to_binary(StmtName))/binary, " USING ", ParamNamesBin/binary>>, % todo: utf8?
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0);
Error ->
Error
end,
unprepare(Connection, StmtName),
Ret;
execute(Connection, StmtName, Args) when is_atom(StmtName), is_list(Args) ->
prepare_statement(Connection, StmtName),
case set_params(Connection, 1, Args, undefined) of
OK when is_record(OK, ok_packet) ->
ParamNamesBin = list_to_binary(string:join([[$@ | integer_to_list(I)] || I <- lists:seq(1, length(Args))], ", ")), % todo: utf8?
StmtNameBin = atom_to_binary(StmtName, utf8),
Packet = <<?COM_QUERY, "EXECUTE ", StmtNameBin/binary, " USING ", ParamNamesBin/binary>>,
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0);
Error ->
Error
end.
prepare(Connection, Name, Statement) when is_atom(Name) ->
prepare(Connection, atom_to_list(Name), Statement);
prepare(Connection, Name, Statement) ->
StatementBin = emysql_util:encode(Statement, binary, Connection#emysql_connection.encoding),
Packet = <<?COM_QUERY, "PREPARE ", (list_to_binary(Name))/binary, " FROM ", StatementBin/binary>>, % todo: utf8?
case emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0) of
OK when is_record(OK, ok_packet) ->
ok;
Err when is_record(Err, error_packet) ->
exit({failed_to_prepare_statement, Err#error_packet.msg})
end.
unprepare(Connection, Name) when is_atom(Name)->
unprepare(Connection, atom_to_list(Name));
unprepare(Connection, Name) ->
Packet = <<?COM_QUERY, "DEALLOCATE PREPARE ", (list_to_binary(Name))/binary>>, % todo: utf8?
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0).
open_n_connections(PoolId, N) ->
-% io : format("open ~p connections for pool ~p ~ n " , [ N , PoolId ] ) ,
case emysql_conn_mgr:find_pool(PoolId, emysql_conn_mgr:pools()) of
{Pool, _} ->
lists:foldl(fun(_ ,Connections) ->
Catch { ' EXIT ' , _ } errors so newly opened connections are not orphaned .
case catch open_connection(Pool) of
#emysql_connection{} = Connection ->
[Connection | Connections];
_ ->
Connections
end
end, [], lists:seq(1, N));
_ ->
exit(pool_not_found)
end.
open_connections(Pool) ->
-% io : format("open connections loop : .. " ) ,
case (queue:len(Pool#pool.available) + gb_trees:size(Pool#pool.locked)) < Pool#pool.min_conn_num of
true ->
-% io : format ( " continues ~ n " ) ,
Conn = emysql_conn:open_connection(Pool),
-% io : connection : ~p ~ n " , [ ] ) ,
open_connections(Pool#pool{available = queue:in(Conn, Pool#pool.available)});
false ->
-% io : format ( " done ~ n " ) ,
Pool
end.
open_connection(#pool{pool_id=PoolId, host=Host, port=Port, user=User, password=Password, database=Database, encoding=Encoding}) ->
-% io : format("~p open connection for pool ~p host ~p port ~p user ~p base ~p ~ n " , [ self ( ) , PoolId , Host , Port , User , Database ] ) ,
-% io : format("~p open connection : ... connect ... ~n " , [ self ( ) ] ) ,
case gen_tcp:connect(Host, Port, [binary, {packet, raw}, {active, false}]) of
{ok, Sock} ->
-% io : format("~p open connection : ... got socket ~ n " , [ self ( ) ] ) ,
Mgr = whereis(emysql_conn_mgr),
Mgr /= undefined orelse
exit({failed_to_find_conn_mgr,
"Failed to find conn mgr when opening connection. Make sure crypto is started and emysql.app is in the Erlang path."}),
gen_tcp:controlling_process(Sock, Mgr),
-% io : format("~p open connection : ... greeting ~ n " , [ self ( ) ] ) ,
Greeting = emysql_auth:do_handshake(Sock, User, Password),
-% io : format("~p open connection : ... make new connection ~ n " , [ self ( ) ] ) ,
Connection = #emysql_connection{
id = erlang:port_to_list(Sock),
pool_id = PoolId,
encoding = Encoding,
socket = Sock,
version = Greeting#greeting.server_version,
thread_id = Greeting#greeting.thread_id,
caps = Greeting#greeting.caps,
language = Greeting#greeting.language
},
-% io : format("~p open connection : ... set db ... ~n " , [ self ( ) ] ) ,
case emysql_conn:set_database(Connection, Database) of
ok -> ok;
OK1 when is_record(OK1, ok_packet) ->
-% io : format("~p open connection : ... db set ok ~ n " , [ self ( ) ] ) ,
ok;
Err1 when is_record(Err1, error_packet) ->
-% io : format("~p open connection : ... db set error ~ n " , [ self ( ) ] ) ,
exit({failed_to_set_database, Err1#error_packet.msg})
end,
-% io : format("~p open connection : ... set encoding ... : ~p ~ n " , [ self ( ) , Encoding ] ) ,
case emysql_conn:set_encoding(Connection, Encoding) of
OK2 when is_record(OK2, ok_packet) ->
ok;
Err2 when is_record(Err2, error_packet) ->
exit({failed_to_set_encoding, Err2#error_packet.msg})
end,
-% io : format("~p open connection : ... ok , return connection ~ n " , [ self ( ) ] ) ,
Connection;
{error, Reason} ->
-% io : format("~p open connection : ... ERROR ~p ~ n " , [ self ( ) , Reason ] ) ,
-% io : format("~p open connection : ... exit with failed_to_connect_to_database ~ n " , [ self ( ) ] ) ,
exit({failed_to_connect_to_database, Reason});
What ->
-% io : format("~p open connection : ... UNKNOWN ERROR ~p ~ n " , [ self ( ) , What ] ) ,
exit({unknown_fail, What})
end.
reset_connection(Pools, Conn, StayLocked) ->
%% if a process dies or times out while doing work
%% the socket must be closed and the connection reset
in the conn_mgr state . Also a new connection needs
%% to be opened to replace the old one. If that fails,
%% we queue the old as available for the next try
%% by the next caller process coming along. So the
%% pool can't run dry, even though it can freeze.
-% io : format("resetting connection ~ n " ) ,
-% io : format("spawn process to close connection ~ n " ) ,
spawn(fun() -> close_connection(Conn) end),
%% OPEN NEW SOCKET
case emysql_conn_mgr:find_pool(Conn#emysql_connection.pool_id, Pools) of
{Pool, _} ->
-% io : format ( " ... open new connection to renew ~ n " ) ,
case catch open_connection(Pool) of
NewConn when is_record(NewConn, emysql_connection) ->
-% io : format ( " ... got it , replace old ( ~p)~n " , [ StayLocked ] ) ,
case StayLocked of
pass -> emysql_conn_mgr:replace_connection_as_available(Conn, NewConn);
keep -> emysql_conn_mgr:replace_connection_as_locked(Conn, NewConn)
end,
-% io : format ( " ... done , return new connection ~ n " ) ,
NewConn;
Error ->
DeadConn = Conn#emysql_connection{alive=false},
emysql_conn_mgr:replace_connection_as_available(Conn, DeadConn),
-% io : format ( " ... failed to re - open . Shelving dead connection as available.~n " ) ,
{error, {cannot_reopen_in_reset, Error}}
end;
undefined ->
exit(pool_not_found)
end.
close_connection(Conn) ->
%% DEALLOCATE PREPARED STATEMENTS
[(catch unprepare(Conn, Name)) || Name <- emysql_statements:remove(Conn#emysql_connection.id)],
%% CLOSE SOCKET
gen_tcp:close(Conn#emysql_connection.socket),
ok.
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
set_params(_, _, [], Result) -> Result;
set_params(_, _, _, Error) when is_record(Error, error_packet) -> Error;
set_params(Connection, Num, Values, _) ->
Packet = set_params_packet(Num, Values, Connection#emysql_connection.encoding),
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0).
set_params_packet(NumStart, Values, Encoding) ->
BinValues = [emysql_util:encode(Val, binary, Encoding) || Val <- Values],
BinNums = [emysql_util:encode(Num, binary, Encoding) || Num <- lists:seq(NumStart, NumStart + length(Values) - 1)],
BinPairs = lists:zip(BinNums, BinValues),
Parts = [<<"@", NumBin/binary, "=", ValBin/binary>> || {NumBin, ValBin} <- BinPairs],
Sets = list_to_binary(join(Parts, <<",">>)),
<<?COM_QUERY, "SET ", Sets/binary>>.
%% @doc Join elements of list with Sep
%%
1 > join([1,2,3 ] , 0 ) .
[ 1,0,2,0,3 ]
join([], _Sep) -> [];
join(L, Sep) -> join(L, Sep, []).
join([H], _Sep, Acc) -> lists:reverse([H|Acc]);
join([H|T], Sep, Acc) -> join(T, Sep, [Sep, H|Acc]).
prepare_statement(Connection, StmtName) ->
case emysql_statements:fetch(StmtName) of
undefined ->
exit(statement_has_not_been_prepared);
{Version, Statement} ->
case emysql_statements:version(Connection#emysql_connection.id, StmtName) of
Version ->
ok;
_ ->
ok = prepare(Connection, StmtName, Statement),
emysql_statements:prepare(Connection#emysql_connection.id, StmtName, Version)
end
end.
% human readable string rep of the server state flag
@private
hstate(State) ->
case (State band ?SERVER_STATUS_AUTOCOMMIT) of 0 -> ""; _-> "AUTOCOMMIT " end
++ case (State band ?SERVER_MORE_RESULTS_EXIST) of 0 -> ""; _-> "MORE_RESULTS_EXIST " end
++ case (State band ?SERVER_QUERY_NO_INDEX_USED) of 0 -> ""; _-> "NO_INDEX_USED " end.
| null | https://raw.githubusercontent.com/fantasytree/fancy_game_server/4ca93486fc0d5b6630170e79b48fb31e9c6e2358/apps/emysql/src/emysql_conn.erl | erlang | Eonblast Corporation <>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
tion, 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
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
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.
todo: utf8?
io : format("~p execute list : ~p using connection : ~p ~ n " , [ self ( ) , ) , Connection#emysql_connection.id ] ) ,
Packet = <<?COM_QUERY, (iolist_to_binary(Query))/binary>>,
io : format("~p execute binary : ~p using connection : ~p ~ n " , [ self ( ) , Query , Connection#emysql_connection.id ] ) ,
Packet = <<?COM_QUERY, (iolist_to_binary(Query))/binary>>,
todo: utf8?
todo: utf8?
todo: utf8?
todo: utf8?
todo: utf8?
io : format("open ~p connections for pool ~p ~ n " , [ N , PoolId ] ) ,
io : format("open connections loop : .. " ) ,
io : format ( " continues ~ n " ) ,
io : connection : ~p ~ n " , [ ] ) ,
io : format ( " done ~ n " ) ,
io : format("~p open connection for pool ~p host ~p port ~p user ~p base ~p ~ n " , [ self ( ) , PoolId , Host , Port , User , Database ] ) ,
io : format("~p open connection : ... connect ... ~n " , [ self ( ) ] ) ,
io : format("~p open connection : ... got socket ~ n " , [ self ( ) ] ) ,
io : format("~p open connection : ... greeting ~ n " , [ self ( ) ] ) ,
io : format("~p open connection : ... make new connection ~ n " , [ self ( ) ] ) ,
io : format("~p open connection : ... set db ... ~n " , [ self ( ) ] ) ,
io : format("~p open connection : ... db set ok ~ n " , [ self ( ) ] ) ,
io : format("~p open connection : ... db set error ~ n " , [ self ( ) ] ) ,
io : format("~p open connection : ... set encoding ... : ~p ~ n " , [ self ( ) , Encoding ] ) ,
io : format("~p open connection : ... ok , return connection ~ n " , [ self ( ) ] ) ,
io : format("~p open connection : ... ERROR ~p ~ n " , [ self ( ) , Reason ] ) ,
io : format("~p open connection : ... exit with failed_to_connect_to_database ~ n " , [ self ( ) ] ) ,
io : format("~p open connection : ... UNKNOWN ERROR ~p ~ n " , [ self ( ) , What ] ) ,
if a process dies or times out while doing work
the socket must be closed and the connection reset
to be opened to replace the old one. If that fails,
we queue the old as available for the next try
by the next caller process coming along. So the
pool can't run dry, even though it can freeze.
io : format("resetting connection ~ n " ) ,
io : format("spawn process to close connection ~ n " ) ,
OPEN NEW SOCKET
io : format ( " ... open new connection to renew ~ n " ) ,
io : format ( " ... got it , replace old ( ~p)~n " , [ StayLocked ] ) ,
io : format ( " ... done , return new connection ~ n " ) ,
io : format ( " ... failed to re - open . Shelving dead connection as available.~n " ) ,
DEALLOCATE PREPARED STATEMENTS
CLOSE SOCKET
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc Join elements of list with Sep
human readable string rep of the server state flag | Copyright ( c ) 2009 - 2012
< > ,
< > ,
< > ,
files ( the " Software"),to deal in the Software without restric-
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY ,
-module(emysql_conn).
-export([set_database/2, set_encoding/2,
execute/3, prepare/3, unprepare/2,
open_connections/1, open_connection/1,
reset_connection/3, close_connection/1,
open_n_connections/2, hstate/1
]).
-include("emysql.hrl").
set_database(_, undefined) -> ok;
set_database(_, Empty) when Empty == ""; Empty == <<>> -> ok;
set_database(Connection, Database) ->
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0).
set_encoding(Connection, Encoding) ->
Packet = <<?COM_QUERY, "set names '", (erlang:atom_to_binary(Encoding, utf8))/binary, "'">>,
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0).
execute(Connection, Query, []) when is_list(Query) ->
Packet = <<?COM_QUERY, (emysql_util:to_binary(Query, Connection#emysql_connection.encoding))/binary>>,
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0);
execute(Connection, Query, []) when is_binary(Query) ->
Packet = <<?COM_QUERY, Query/binary>>,
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0);
execute(Connection, StmtName, []) when is_atom(StmtName) ->
prepare_statement(Connection, StmtName),
StmtNameBin = atom_to_binary(StmtName, utf8),
Packet = <<?COM_QUERY, "EXECUTE ", StmtNameBin/binary>>,
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0);
execute(Connection, Query, Args) when (is_list(Query) orelse is_binary(Query)) andalso is_list(Args) ->
StmtName = "stmt_"++integer_to_list(erlang:phash2(Query)),
ok = prepare(Connection, StmtName, Query),
Ret =
case set_params(Connection, 1, Args, undefined) of
OK when is_record(OK, ok_packet) ->
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0);
Error ->
Error
end,
unprepare(Connection, StmtName),
Ret;
execute(Connection, StmtName, Args) when is_atom(StmtName), is_list(Args) ->
prepare_statement(Connection, StmtName),
case set_params(Connection, 1, Args, undefined) of
OK when is_record(OK, ok_packet) ->
StmtNameBin = atom_to_binary(StmtName, utf8),
Packet = <<?COM_QUERY, "EXECUTE ", StmtNameBin/binary, " USING ", ParamNamesBin/binary>>,
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0);
Error ->
Error
end.
prepare(Connection, Name, Statement) when is_atom(Name) ->
prepare(Connection, atom_to_list(Name), Statement);
prepare(Connection, Name, Statement) ->
StatementBin = emysql_util:encode(Statement, binary, Connection#emysql_connection.encoding),
case emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0) of
OK when is_record(OK, ok_packet) ->
ok;
Err when is_record(Err, error_packet) ->
exit({failed_to_prepare_statement, Err#error_packet.msg})
end.
unprepare(Connection, Name) when is_atom(Name)->
unprepare(Connection, atom_to_list(Name));
unprepare(Connection, Name) ->
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0).
open_n_connections(PoolId, N) ->
case emysql_conn_mgr:find_pool(PoolId, emysql_conn_mgr:pools()) of
{Pool, _} ->
lists:foldl(fun(_ ,Connections) ->
Catch { ' EXIT ' , _ } errors so newly opened connections are not orphaned .
case catch open_connection(Pool) of
#emysql_connection{} = Connection ->
[Connection | Connections];
_ ->
Connections
end
end, [], lists:seq(1, N));
_ ->
exit(pool_not_found)
end.
open_connections(Pool) ->
case (queue:len(Pool#pool.available) + gb_trees:size(Pool#pool.locked)) < Pool#pool.min_conn_num of
true ->
Conn = emysql_conn:open_connection(Pool),
open_connections(Pool#pool{available = queue:in(Conn, Pool#pool.available)});
false ->
Pool
end.
open_connection(#pool{pool_id=PoolId, host=Host, port=Port, user=User, password=Password, database=Database, encoding=Encoding}) ->
case gen_tcp:connect(Host, Port, [binary, {packet, raw}, {active, false}]) of
{ok, Sock} ->
Mgr = whereis(emysql_conn_mgr),
Mgr /= undefined orelse
exit({failed_to_find_conn_mgr,
"Failed to find conn mgr when opening connection. Make sure crypto is started and emysql.app is in the Erlang path."}),
gen_tcp:controlling_process(Sock, Mgr),
Greeting = emysql_auth:do_handshake(Sock, User, Password),
Connection = #emysql_connection{
id = erlang:port_to_list(Sock),
pool_id = PoolId,
encoding = Encoding,
socket = Sock,
version = Greeting#greeting.server_version,
thread_id = Greeting#greeting.thread_id,
caps = Greeting#greeting.caps,
language = Greeting#greeting.language
},
case emysql_conn:set_database(Connection, Database) of
ok -> ok;
OK1 when is_record(OK1, ok_packet) ->
ok;
Err1 when is_record(Err1, error_packet) ->
exit({failed_to_set_database, Err1#error_packet.msg})
end,
case emysql_conn:set_encoding(Connection, Encoding) of
OK2 when is_record(OK2, ok_packet) ->
ok;
Err2 when is_record(Err2, error_packet) ->
exit({failed_to_set_encoding, Err2#error_packet.msg})
end,
Connection;
{error, Reason} ->
exit({failed_to_connect_to_database, Reason});
What ->
exit({unknown_fail, What})
end.
reset_connection(Pools, Conn, StayLocked) ->
in the conn_mgr state . Also a new connection needs
spawn(fun() -> close_connection(Conn) end),
case emysql_conn_mgr:find_pool(Conn#emysql_connection.pool_id, Pools) of
{Pool, _} ->
case catch open_connection(Pool) of
NewConn when is_record(NewConn, emysql_connection) ->
case StayLocked of
pass -> emysql_conn_mgr:replace_connection_as_available(Conn, NewConn);
keep -> emysql_conn_mgr:replace_connection_as_locked(Conn, NewConn)
end,
NewConn;
Error ->
DeadConn = Conn#emysql_connection{alive=false},
emysql_conn_mgr:replace_connection_as_available(Conn, DeadConn),
{error, {cannot_reopen_in_reset, Error}}
end;
undefined ->
exit(pool_not_found)
end.
close_connection(Conn) ->
[(catch unprepare(Conn, Name)) || Name <- emysql_statements:remove(Conn#emysql_connection.id)],
gen_tcp:close(Conn#emysql_connection.socket),
ok.
Internal functions
set_params(_, _, [], Result) -> Result;
set_params(_, _, _, Error) when is_record(Error, error_packet) -> Error;
set_params(Connection, Num, Values, _) ->
Packet = set_params_packet(Num, Values, Connection#emysql_connection.encoding),
emysql_tcp:send_and_recv_packet(Connection#emysql_connection.socket, Packet, 0).
set_params_packet(NumStart, Values, Encoding) ->
BinValues = [emysql_util:encode(Val, binary, Encoding) || Val <- Values],
BinNums = [emysql_util:encode(Num, binary, Encoding) || Num <- lists:seq(NumStart, NumStart + length(Values) - 1)],
BinPairs = lists:zip(BinNums, BinValues),
Parts = [<<"@", NumBin/binary, "=", ValBin/binary>> || {NumBin, ValBin} <- BinPairs],
Sets = list_to_binary(join(Parts, <<",">>)),
<<?COM_QUERY, "SET ", Sets/binary>>.
1 > join([1,2,3 ] , 0 ) .
[ 1,0,2,0,3 ]
join([], _Sep) -> [];
join(L, Sep) -> join(L, Sep, []).
join([H], _Sep, Acc) -> lists:reverse([H|Acc]);
join([H|T], Sep, Acc) -> join(T, Sep, [Sep, H|Acc]).
prepare_statement(Connection, StmtName) ->
case emysql_statements:fetch(StmtName) of
undefined ->
exit(statement_has_not_been_prepared);
{Version, Statement} ->
case emysql_statements:version(Connection#emysql_connection.id, StmtName) of
Version ->
ok;
_ ->
ok = prepare(Connection, StmtName, Statement),
emysql_statements:prepare(Connection#emysql_connection.id, StmtName, Version)
end
end.
@private
hstate(State) ->
case (State band ?SERVER_STATUS_AUTOCOMMIT) of 0 -> ""; _-> "AUTOCOMMIT " end
++ case (State band ?SERVER_MORE_RESULTS_EXIST) of 0 -> ""; _-> "MORE_RESULTS_EXIST " end
++ case (State band ?SERVER_QUERY_NO_INDEX_USED) of 0 -> ""; _-> "NO_INDEX_USED " end.
|
40095d03d1a0c672b1f650415b5ed0da4e71f42ed8f10e3ba1e0592b20037279 | eclipse-archived/agent | heartbeat.ml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright ( c ) 2020 ADLINK Technology Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* -2.0 , or the Apache Software License 2.0
* which is available at -2.0 .
*
* SPDX - License - Identifier : EPL-2.0 OR Apache-2.0
* Contributors : 1
* ( gabriele ( dot ) baldoni ( at ) adlinktech ( dot ) com ) - Node heartbeat
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright (c) 2020 ADLINK Technology Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* -2.0, or the Apache Software License 2.0
* which is available at -2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
* Contributors: 1
* Gabriele Baldoni (gabriele (dot) baldoni (at) adlinktech (dot) com ) - Node heartbeat
*********************************************************************************)
open Lwt.Infix
open
module MVar = Apero.MVar_lwt
module HeartbeatMap = Map.Make(String)
module HeartbeatMessage = struct
type msg_type =
| PING
| PONG
type t = {
msg_type : msg_type;
sequence_number : int32;
node_id : Bytes.t
}
let msg_type_to_int = function
| PING -> 0x01
| PONG -> 0x02
let int_of_msg_type = function
| 0x01 -> PING
| 0x02 -> PONG
| _ -> failwith "Cannot match"
let header_size = 5
let make_ping sq =
{msg_type=PING; sequence_number=sq; node_id=(Bytes.create 0)}
let make_pong sq nodeid =
let buf = Bytes.create (String.length nodeid) in
let _ = Bytes.blit_string nodeid 0 buf 0 (String.length nodeid) in
{msg_type=PONG; sequence_number=sq; node_id=buf}
let to_buf msg =
let buf = Abuf.create ~grow:32 128 in
Abuf.write_byte (Char.chr (msg_type_to_int msg.msg_type)) buf;
Abuf.write_byte (Char.chr(Int32.to_int (Int32.shift_right msg.sequence_number 24))) buf;
Abuf.write_byte (Char.chr(Int32.to_int (Int32.shift_right (Int32.shift_left msg.sequence_number 8) 24))) buf;
Abuf.write_byte (Char.chr(Int32.to_int (Int32.shift_right (Int32.shift_left msg.sequence_number 16) 24))) buf;
Abuf.write_byte (Char.chr(Int32.to_int (Int32.shift_right (Int32.shift_left msg.sequence_number 24) 24))) buf;
Abuf.write_bytes msg.node_id buf;
buf
let from_buf buf =
let msg_type = int_of_msg_type (Char.code (Abuf.read_byte buf)) in
let b1 = Int32.shift_left (Int32.of_int (Char.code (Abuf.read_byte buf))) 24 in
let b2 = Int32.shift_left (Int32.of_int (Char.code (Abuf.read_byte buf))) 16 in
let b3 = Int32.shift_left (Int32.of_int (Char.code (Abuf.read_byte buf))) 8 in
let b4 = Int32.of_int (Char.code (Abuf.read_byte buf)) in
let seq = Int32.logor b4 (Int32.logor b3 (Int32.logor b1 b2))
in
match msg_type with
| PING -> {msg_type; sequence_number=seq; node_id=Bytes.create 0}
| PONG ->
let nid = Abuf.read_bytes 36 buf in
{msg_type; sequence_number=seq; node_id=nid}
end
type ping_statistics = {
peer: string;
timeout: float;
peer_address : string;
iface : string;
avg : float;
packet_sent: int;
packet_received: int;
bytes_sent: int;
bytes_received: int;
peer_sockaddr : Lwt_unix.sockaddr;
inflight_msgs : (float*int) list;
last_sq_num : int;
}
type ping_tasks = (string * ping_statistics list)
(* type status = ping_tasks list *)
type ping_status = {
sock : Lwt_unix.file_descr;
rbuf : Bytes.t;
blen : int;
run : bool Lwt.t;
tasks : ping_tasks list;
unreachable : string list;
}
Logs.debug ( fun m - > m " [ heartbeat_single_threaded.send_ping ] - Timeout too big removing % s % s " stat.peer stat.iface ) ;
let state = { state with tasks = List.append state.tasks [ ( peer_id , peer_tasks ) ] } in
Lwt.return state
let state = {state with tasks = List.append state.tasks [(peer_id,peer_tasks)]} in
Lwt.return state *)
let heartbeat_single_threaded (state : ping_status) =
Logs.debug (fun m -> m "[heartbeat_single_threaded] - Starting single threaed ping client");
let rec remove_unreachable tasks newtask =
match tasks with
| [] -> newtask
| hd::tl ->
let nid,stat = hd in
let stat = List.filter (fun st -> st.timeout < 10.0) stat in
remove_unreachable tl (List.append newtask [(nid,stat)])
in
let send_ping sock (ping_info : ping_statistics) =
Logs.debug (fun m -> m "[heartbeat_single_threaded.send_ping] - Sending for %s" ping_info.peer_address);
let sq_num = ping_info.last_sq_num+1 in
let msg = HeartbeatMessage.make_ping (Int32.of_int (sq_num)) in
let buf = HeartbeatMessage.to_buf msg in
let sbuf = Abuf.read_bytes (Abuf.w_pos buf) buf in
let t0 = Unix.gettimeofday () in
let%lwt sent = Lwt_unix.sendto sock sbuf 0 (Bytes.length sbuf) [] ping_info.peer_sockaddr in
let new_inflight = List.append ping_info.inflight_msgs [t0,sq_num] in
Lwt.return {ping_info with inflight_msgs = new_inflight; last_sq_num = sq_num; bytes_sent = ping_info.bytes_sent + sent; packet_sent = ping_info.packet_sent + 1}
in
let recv (state : ping_status) =
Logs.debug (fun m -> m "[heartbeat_single_threaded.recv] - Waiting reply with timeout on recv");
(* recv with timeout result is (bool * int * float * string) *)
let timeout = Lwt_unix.sleep 2.0 >>= fun _ -> let t1 = Unix.gettimeofday () in Lwt.return (false,0, t1, "") in
let recv = Lwt_unix.recvfrom state.sock state.rbuf 0 state.blen []
>>= fun (l, recv_addr) ->
Logs.debug (fun m -> m "[heartbeat_single_threaded.recv] - Received %d bytes" l);
let t1 = Unix.gettimeofday () in
let rcv_ip = match recv_addr with
| ADDR_INET (inet,_) -> Unix.string_of_inet_addr inet
| _ -> ""
in
Lwt.return (true, l, t1, rcv_ip)
in
let%lwt res,l,t1,rcv_ip = Lwt.pick [timeout;recv] in
match res with
| false ->
Logs.debug (fun m -> m "[heartbeat_single_threaded.recv] - Timeout");
let tasks = state.tasks in
let tasks = List.map (fun (nid,stat) ->
let stat = List.map (fun (st : ping_statistics ) ->
Logs.debug (fun m -> m "[heartbeat_single_threaded.recv] - Updating timeouts for %s" nid);
let st = {st with inflight_msgs = List.filter (fun (t,_) -> let rtt = t1-.t in rtt > st.timeout) st.inflight_msgs} in
match List.length st.inflight_msgs with
| 0 -> {st with timeout = (if st.timeout < 10.0 then 4.0*.st.timeout else 10.0)}
| _ ->
let (t0,_) = List.nth st.inflight_msgs ((List.length st.inflight_msgs)-1) in
let rtt = (t1-.t0) in
Logs.debug (fun m -> m "[heartbeat_single_threaded.recv] - Current RTT for %s is %f - Timeout %f" nid rtt st.timeout);
if rtt>st.timeout then {st with timeout = (if st.timeout < 10.0 then 4.0*.st.timeout else 10.0)} else st
) stat in
Logs.debug (fun m -> m "[heartbeat_single_threaded.recv] - Update done for %s" nid);
(nid,stat)
) tasks in
Logs.debug (fun m -> m "[heartbeat_single_threaded.recv] - Returning" );
Lwt.return {state with tasks = tasks}
| true ->
let rabuf = Abuf.from_bytes state.rbuf in
let rmsg = HeartbeatMessage.from_buf rabuf in
match rmsg.msg_type with
| PONG ->
let sq_num = Int32.to_int rmsg.sequence_number in
let peer_id = Bytes.to_string rmsg.node_id in
(* find peer tasks *)
let _,peer_tasks = List.find (fun (nid,_) -> String.compare nid peer_id == 0) state.tasks in
(* removing peer tasks it will be readded after the check *)
let state = {state with tasks = List.filter (fun (n,_) -> (String.compare peer_id n != 0)) state.tasks} in
(* get task associated with this ip *)
let stat = List.find (fun stat -> String.compare stat.peer_address rcv_ip == 0 ) peer_tasks in
(* removing task will be added after check *)
let peer_tasks = List.filter (fun stat -> String.compare stat.peer_address rcv_ip != 0 ) peer_tasks in
(* checking *)
let t0 = List.find (fun (_,sq) -> sq == sq_num) stat.inflight_msgs |> fun (t,_) -> t in
let rtt = (t1-.t0) in
if (rtt > stat.timeout) then
(* dropping if received after timeout *)
let new_inflight = List.remove_assoc t0 stat.inflight_msgs in
let new_timeout = if stat.timeout <= 10.0 then 4.0*.stat.timeout else 10.0 in
let stat = {stat with inflight_msgs = new_inflight; timeout=new_timeout} in
(* adding single task *)
let peer_tasks = List.append peer_tasks [stat] in
(* adding new tasks *)
let state = {state with tasks = List.append state.tasks [(peer_id,peer_tasks)]} in
Lwt.return state
else
let avg = (stat.avg *. float(stat.packet_received) +. rtt) /. float(stat.packet_received+1) in
let new_inflight = List.remove_assoc t0 stat.inflight_msgs in
let stat = {stat with timeout = 3.5*.avg; avg = avg; packet_received = stat.packet_received + 1; bytes_received = stat.bytes_received + l; inflight_msgs = new_inflight} in
(* adding single task *)
let peer_tasks = List.append peer_tasks [stat] in
(* adding new tasks *)
let state = {state with tasks = List.append state.tasks [(peer_id,peer_tasks)]} in
Lwt.return state
| PING -> Lwt.return state
in
let single_run state =
let peer_ping tasks =
Lwt_list.map_p (fun stat -> send_ping state.sock stat) tasks
in
let all_ping tasks =
Lwt_list.map_p (fun (p,stat) ->let%lwt pp = peer_ping stat in Lwt.return (p,pp) ) tasks
in
let%lwt new_tasks = all_ping state.tasks in
let state = {state with tasks = new_tasks} in
let%lwt state = recv state in
let state = {state with tasks = remove_unreachable state.tasks []} in
Lwt.return state
in single_run state
let run_server addr nodeid =
let server_sock = Lwt_unix.socket Lwt_unix.PF_INET Lwt_unix.SOCK_DGRAM 0 in
let _ = Lwt_unix.setsockopt server_sock Lwt_unix.SO_REUSEADDR true in
Logs.debug (fun m -> m "[run_server] Eclipse fog05 Ping Server -- %s\n" nodeid);
let%lwt _ = Lwt_unix.bind server_sock addr in
let blen = 1024 in
let buf = Bytes.create blen in
let rec serve_client sock addr =
(* receive, make pong with same sequence number and send *)
let%lwt l, client = Lwt_unix.recvfrom sock buf 0 blen [] in
let rmsg = HeartbeatMessage.from_buf (Abuf.from_bytes buf) in
let smsg = HeartbeatMessage.make_pong rmsg.sequence_number nodeid in
let sbuf = HeartbeatMessage.to_buf smsg in
let sbuf = Abuf.read_bytes (Abuf.w_pos sbuf) sbuf in
let%lwt n = Lwt_unix.sendto sock sbuf 0 (Bytes.length sbuf) [] client in
(* ignore variables to avoid error in build *)
ignore n; ignore l;
serve_client sock addr
in
serve_client server_sock addr
| null | https://raw.githubusercontent.com/eclipse-archived/agent/e2ee78050157eba3aa35f52496b590806c6d1d88/fos-agent/heartbeat.ml | ocaml | type status = ping_tasks list
recv with timeout result is (bool * int * float * string)
find peer tasks
removing peer tasks it will be readded after the check
get task associated with this ip
removing task will be added after check
checking
dropping if received after timeout
adding single task
adding new tasks
adding single task
adding new tasks
receive, make pong with same sequence number and send
ignore variables to avoid error in build | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright ( c ) 2020 ADLINK Technology Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* -2.0 , or the Apache Software License 2.0
* which is available at -2.0 .
*
* SPDX - License - Identifier : EPL-2.0 OR Apache-2.0
* Contributors : 1
* ( gabriele ( dot ) baldoni ( at ) adlinktech ( dot ) com ) - Node heartbeat
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright (c) 2020 ADLINK Technology Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* -2.0, or the Apache Software License 2.0
* which is available at -2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
* Contributors: 1
* Gabriele Baldoni (gabriele (dot) baldoni (at) adlinktech (dot) com ) - Node heartbeat
*********************************************************************************)
open Lwt.Infix
open
module MVar = Apero.MVar_lwt
module HeartbeatMap = Map.Make(String)
module HeartbeatMessage = struct
type msg_type =
| PING
| PONG
type t = {
msg_type : msg_type;
sequence_number : int32;
node_id : Bytes.t
}
let msg_type_to_int = function
| PING -> 0x01
| PONG -> 0x02
let int_of_msg_type = function
| 0x01 -> PING
| 0x02 -> PONG
| _ -> failwith "Cannot match"
let header_size = 5
let make_ping sq =
{msg_type=PING; sequence_number=sq; node_id=(Bytes.create 0)}
let make_pong sq nodeid =
let buf = Bytes.create (String.length nodeid) in
let _ = Bytes.blit_string nodeid 0 buf 0 (String.length nodeid) in
{msg_type=PONG; sequence_number=sq; node_id=buf}
let to_buf msg =
let buf = Abuf.create ~grow:32 128 in
Abuf.write_byte (Char.chr (msg_type_to_int msg.msg_type)) buf;
Abuf.write_byte (Char.chr(Int32.to_int (Int32.shift_right msg.sequence_number 24))) buf;
Abuf.write_byte (Char.chr(Int32.to_int (Int32.shift_right (Int32.shift_left msg.sequence_number 8) 24))) buf;
Abuf.write_byte (Char.chr(Int32.to_int (Int32.shift_right (Int32.shift_left msg.sequence_number 16) 24))) buf;
Abuf.write_byte (Char.chr(Int32.to_int (Int32.shift_right (Int32.shift_left msg.sequence_number 24) 24))) buf;
Abuf.write_bytes msg.node_id buf;
buf
let from_buf buf =
let msg_type = int_of_msg_type (Char.code (Abuf.read_byte buf)) in
let b1 = Int32.shift_left (Int32.of_int (Char.code (Abuf.read_byte buf))) 24 in
let b2 = Int32.shift_left (Int32.of_int (Char.code (Abuf.read_byte buf))) 16 in
let b3 = Int32.shift_left (Int32.of_int (Char.code (Abuf.read_byte buf))) 8 in
let b4 = Int32.of_int (Char.code (Abuf.read_byte buf)) in
let seq = Int32.logor b4 (Int32.logor b3 (Int32.logor b1 b2))
in
match msg_type with
| PING -> {msg_type; sequence_number=seq; node_id=Bytes.create 0}
| PONG ->
let nid = Abuf.read_bytes 36 buf in
{msg_type; sequence_number=seq; node_id=nid}
end
type ping_statistics = {
peer: string;
timeout: float;
peer_address : string;
iface : string;
avg : float;
packet_sent: int;
packet_received: int;
bytes_sent: int;
bytes_received: int;
peer_sockaddr : Lwt_unix.sockaddr;
inflight_msgs : (float*int) list;
last_sq_num : int;
}
type ping_tasks = (string * ping_statistics list)
type ping_status = {
sock : Lwt_unix.file_descr;
rbuf : Bytes.t;
blen : int;
run : bool Lwt.t;
tasks : ping_tasks list;
unreachable : string list;
}
Logs.debug ( fun m - > m " [ heartbeat_single_threaded.send_ping ] - Timeout too big removing % s % s " stat.peer stat.iface ) ;
let state = { state with tasks = List.append state.tasks [ ( peer_id , peer_tasks ) ] } in
Lwt.return state
let state = {state with tasks = List.append state.tasks [(peer_id,peer_tasks)]} in
Lwt.return state *)
let heartbeat_single_threaded (state : ping_status) =
Logs.debug (fun m -> m "[heartbeat_single_threaded] - Starting single threaed ping client");
let rec remove_unreachable tasks newtask =
match tasks with
| [] -> newtask
| hd::tl ->
let nid,stat = hd in
let stat = List.filter (fun st -> st.timeout < 10.0) stat in
remove_unreachable tl (List.append newtask [(nid,stat)])
in
let send_ping sock (ping_info : ping_statistics) =
Logs.debug (fun m -> m "[heartbeat_single_threaded.send_ping] - Sending for %s" ping_info.peer_address);
let sq_num = ping_info.last_sq_num+1 in
let msg = HeartbeatMessage.make_ping (Int32.of_int (sq_num)) in
let buf = HeartbeatMessage.to_buf msg in
let sbuf = Abuf.read_bytes (Abuf.w_pos buf) buf in
let t0 = Unix.gettimeofday () in
let%lwt sent = Lwt_unix.sendto sock sbuf 0 (Bytes.length sbuf) [] ping_info.peer_sockaddr in
let new_inflight = List.append ping_info.inflight_msgs [t0,sq_num] in
Lwt.return {ping_info with inflight_msgs = new_inflight; last_sq_num = sq_num; bytes_sent = ping_info.bytes_sent + sent; packet_sent = ping_info.packet_sent + 1}
in
let recv (state : ping_status) =
Logs.debug (fun m -> m "[heartbeat_single_threaded.recv] - Waiting reply with timeout on recv");
let timeout = Lwt_unix.sleep 2.0 >>= fun _ -> let t1 = Unix.gettimeofday () in Lwt.return (false,0, t1, "") in
let recv = Lwt_unix.recvfrom state.sock state.rbuf 0 state.blen []
>>= fun (l, recv_addr) ->
Logs.debug (fun m -> m "[heartbeat_single_threaded.recv] - Received %d bytes" l);
let t1 = Unix.gettimeofday () in
let rcv_ip = match recv_addr with
| ADDR_INET (inet,_) -> Unix.string_of_inet_addr inet
| _ -> ""
in
Lwt.return (true, l, t1, rcv_ip)
in
let%lwt res,l,t1,rcv_ip = Lwt.pick [timeout;recv] in
match res with
| false ->
Logs.debug (fun m -> m "[heartbeat_single_threaded.recv] - Timeout");
let tasks = state.tasks in
let tasks = List.map (fun (nid,stat) ->
let stat = List.map (fun (st : ping_statistics ) ->
Logs.debug (fun m -> m "[heartbeat_single_threaded.recv] - Updating timeouts for %s" nid);
let st = {st with inflight_msgs = List.filter (fun (t,_) -> let rtt = t1-.t in rtt > st.timeout) st.inflight_msgs} in
match List.length st.inflight_msgs with
| 0 -> {st with timeout = (if st.timeout < 10.0 then 4.0*.st.timeout else 10.0)}
| _ ->
let (t0,_) = List.nth st.inflight_msgs ((List.length st.inflight_msgs)-1) in
let rtt = (t1-.t0) in
Logs.debug (fun m -> m "[heartbeat_single_threaded.recv] - Current RTT for %s is %f - Timeout %f" nid rtt st.timeout);
if rtt>st.timeout then {st with timeout = (if st.timeout < 10.0 then 4.0*.st.timeout else 10.0)} else st
) stat in
Logs.debug (fun m -> m "[heartbeat_single_threaded.recv] - Update done for %s" nid);
(nid,stat)
) tasks in
Logs.debug (fun m -> m "[heartbeat_single_threaded.recv] - Returning" );
Lwt.return {state with tasks = tasks}
| true ->
let rabuf = Abuf.from_bytes state.rbuf in
let rmsg = HeartbeatMessage.from_buf rabuf in
match rmsg.msg_type with
| PONG ->
let sq_num = Int32.to_int rmsg.sequence_number in
let peer_id = Bytes.to_string rmsg.node_id in
let _,peer_tasks = List.find (fun (nid,_) -> String.compare nid peer_id == 0) state.tasks in
let state = {state with tasks = List.filter (fun (n,_) -> (String.compare peer_id n != 0)) state.tasks} in
let stat = List.find (fun stat -> String.compare stat.peer_address rcv_ip == 0 ) peer_tasks in
let peer_tasks = List.filter (fun stat -> String.compare stat.peer_address rcv_ip != 0 ) peer_tasks in
let t0 = List.find (fun (_,sq) -> sq == sq_num) stat.inflight_msgs |> fun (t,_) -> t in
let rtt = (t1-.t0) in
if (rtt > stat.timeout) then
let new_inflight = List.remove_assoc t0 stat.inflight_msgs in
let new_timeout = if stat.timeout <= 10.0 then 4.0*.stat.timeout else 10.0 in
let stat = {stat with inflight_msgs = new_inflight; timeout=new_timeout} in
let peer_tasks = List.append peer_tasks [stat] in
let state = {state with tasks = List.append state.tasks [(peer_id,peer_tasks)]} in
Lwt.return state
else
let avg = (stat.avg *. float(stat.packet_received) +. rtt) /. float(stat.packet_received+1) in
let new_inflight = List.remove_assoc t0 stat.inflight_msgs in
let stat = {stat with timeout = 3.5*.avg; avg = avg; packet_received = stat.packet_received + 1; bytes_received = stat.bytes_received + l; inflight_msgs = new_inflight} in
let peer_tasks = List.append peer_tasks [stat] in
let state = {state with tasks = List.append state.tasks [(peer_id,peer_tasks)]} in
Lwt.return state
| PING -> Lwt.return state
in
let single_run state =
let peer_ping tasks =
Lwt_list.map_p (fun stat -> send_ping state.sock stat) tasks
in
let all_ping tasks =
Lwt_list.map_p (fun (p,stat) ->let%lwt pp = peer_ping stat in Lwt.return (p,pp) ) tasks
in
let%lwt new_tasks = all_ping state.tasks in
let state = {state with tasks = new_tasks} in
let%lwt state = recv state in
let state = {state with tasks = remove_unreachable state.tasks []} in
Lwt.return state
in single_run state
let run_server addr nodeid =
let server_sock = Lwt_unix.socket Lwt_unix.PF_INET Lwt_unix.SOCK_DGRAM 0 in
let _ = Lwt_unix.setsockopt server_sock Lwt_unix.SO_REUSEADDR true in
Logs.debug (fun m -> m "[run_server] Eclipse fog05 Ping Server -- %s\n" nodeid);
let%lwt _ = Lwt_unix.bind server_sock addr in
let blen = 1024 in
let buf = Bytes.create blen in
let rec serve_client sock addr =
let%lwt l, client = Lwt_unix.recvfrom sock buf 0 blen [] in
let rmsg = HeartbeatMessage.from_buf (Abuf.from_bytes buf) in
let smsg = HeartbeatMessage.make_pong rmsg.sequence_number nodeid in
let sbuf = HeartbeatMessage.to_buf smsg in
let sbuf = Abuf.read_bytes (Abuf.w_pos sbuf) sbuf in
let%lwt n = Lwt_unix.sendto sock sbuf 0 (Bytes.length sbuf) [] client in
ignore n; ignore l;
serve_client sock addr
in
serve_client server_sock addr
|
59d830a102392c4d4ca3f2038d24e7edf70aba1a56be2d7ba1ff310ea79f9ac2 | kompendium-ano/api-factom | Config.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
module Factom.Rest.Server.Config
( AppConfig(..)
, ConnectConfig(..)
, MetaConfig(..)
, defaultConnectConfig
, readCfg
, readEvalCfg
, viewCfg
) where
import Data.Aeson
import qualified Data.ByteString.Char8 as BS
import Data.List
import Data.List.Split
import Data.Maybe (catMaybes,
fromMaybe)
import qualified Data.Text as T
import Data.Typeable
import Data.UUID
import Data.Word
import qualified Data.Yaml as Y
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromField
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.ToRow
import qualified Database.PostgreSQL.Simple.TypeInfo.Static as TI
import GHC.Generics
import GHC.Generics
import System.Environment (getEnv, lookupEnv)
import System.IO.Unsafe
--------------------------------------------------------------------------------
data ConnectConfig = ConnectConfig
{ host :: String
, port :: String
, dbs :: String
, user :: String
, pass :: String
} deriving (Generic, Eq, Read, Show, Typeable, ToJSON)
mkConnInfo :: ConnectConfig -- ^ Internal configuration representation
-> ConnectInfo -- ^ Representation used by Postgresql.Simple
mkConnInfo config =
defaultConnectInfo
{ connectHost = host config
, connectPort = fromInteger $ read $ port config
, connectDatabase = dbs config
, connectUser = user config
, connectPassword = pass config
}
--------------------------------------------------------------------------------
-- | Top level structure for storing config
--
data AppConfig =
AppConfig
{ lcDatabase :: ConnectConfig
, lcMeta :: MetaConfig -- ^ parameters related to meta information
, lcHost :: String -- ^ system host link
, lcApiHost :: String -- ^ API host link
} deriving (Generic, ToJSON, Show)
instance FromJSON AppConfig where
parseJSON = withObject "config" $ \o -> do
db <- o .: "database"
mt <- o .: "meta"
hh <- o .: "host"
ah <- o .: "host-api"
return $ AppConfig db mt hh ah
instance FromJSON ConnectConfig where
parseJSON = withObject "database" $ \o -> do
hs <- o .: "host"
pr <- o .: "port"
dd <- o .: "db"
us <- o .: "user"
ps <- o .: "password"
return $ ConnectConfig hs pr dd us ps
-- | Additional structure for specific meta values
--
data MetaConfig = MetaConfig
{ mcDelay :: Int -- ^ time delay between reimport for daemon mode
, mcThreads :: Int -- ^ number of threads we able to spawn
} deriving (Generic, ToJSON, Show)
instance FromJSON MetaConfig where
parseJSON = withObject "meta" $ \o -> do
dl <- o .: "delay"
th <- o .: "threads"
return $ MetaConfig dl th
--------------------------------------------------------------------------------
viewCfg :: ConnectConfig -> String
viewCfg (ConnectConfig h p db u ps) =
"Connection parameters:\n"
++ " server - " ++ h ++ "\n"
++ " port - " ++ p ++ "\n"
++ " db - " ++ db ++ "\n"
++ " user - " ++ u ++ "\n"
-- | Reading database config from specified file
--
readCfg :: String -> IO (Either Y.ParseException AppConfig)
readCfg path = Y.decodeFileEither path
-- | Reads config and check environment values
-- to override defaults
readEvalCfg :: String -> IO (Either String AppConfig)
readEvalCfg path =
do
content <- BS.readFile path
BS.unpack content
let parsedContent = Y.decodeEither' content :: Either Y.ParseException AppConfig
case parsedContent of
Left exc -> do
print $ show $ exc
return $ Left "Could not parse config file."
Right cfg@(AppConfig (ConnectConfig h p d u ps) m hh ap) ->
return $
Right AppConfig { lcDatabase = connConfig
, lcMeta = m
, lcHost = hh
, lcApiHost = ap
}
where
connConfig =
ConnectConfig { host = evalCfgField h
, port = evalCfgField p
, dbs = evalCfgField d
, user = evalCfgField u
, pass = evalCfgField ps
}
-- | Evaluates each field and take care of environment overloading
evalCfgField :: String -> String
evalCfgField s =
case isInfixOf "_env" s of
True ->
fromMaybe lvar $ unsafePerformIO $ lookupEnv evar
where rs = tail $ splitOn ":" s
evar = head rs
lvar = last rs
False -> s
-- | Reading import config from specified file
-- this file have information about table name, field names,
-- and other useful information that need to be stored in DB
-- since some of files doesn't have metadata we need to provide additional
-- information for parsing
readImportCfg :: String -> IO (Either Y.ParseException ConnectConfig)
readImportCfg path = Y.decodeFileEither path
-- | This is default parameters that
-- are in use if config wasn't supplied
defaultConnectConfig = ConnectConfig {
host = "db"
, port = "5432"
, dbs = "factom-oapi"
, user = "factom"
, pass = "factom-drum"
}
| null | https://raw.githubusercontent.com/kompendium-ano/api-factom/68359e60d82515c6fd66134f8b3661e827eb6599/factom-oapi-server/src/Factom/Rest/Server/Config.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
------------------------------------------------------------------------------
^ Internal configuration representation
^ Representation used by Postgresql.Simple
------------------------------------------------------------------------------
| Top level structure for storing config
^ parameters related to meta information
^ system host link
^ API host link
| Additional structure for specific meta values
^ time delay between reimport for daemon mode
^ number of threads we able to spawn
------------------------------------------------------------------------------
| Reading database config from specified file
| Reads config and check environment values
to override defaults
| Evaluates each field and take care of environment overloading
| Reading import config from specified file
this file have information about table name, field names,
and other useful information that need to be stored in DB
since some of files doesn't have metadata we need to provide additional
information for parsing
| This is default parameters that
are in use if config wasn't supplied | # LANGUAGE DeriveGeneric #
module Factom.Rest.Server.Config
( AppConfig(..)
, ConnectConfig(..)
, MetaConfig(..)
, defaultConnectConfig
, readCfg
, readEvalCfg
, viewCfg
) where
import Data.Aeson
import qualified Data.ByteString.Char8 as BS
import Data.List
import Data.List.Split
import Data.Maybe (catMaybes,
fromMaybe)
import qualified Data.Text as T
import Data.Typeable
import Data.UUID
import Data.Word
import qualified Data.Yaml as Y
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromField
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.ToRow
import qualified Database.PostgreSQL.Simple.TypeInfo.Static as TI
import GHC.Generics
import GHC.Generics
import System.Environment (getEnv, lookupEnv)
import System.IO.Unsafe
data ConnectConfig = ConnectConfig
{ host :: String
, port :: String
, dbs :: String
, user :: String
, pass :: String
} deriving (Generic, Eq, Read, Show, Typeable, ToJSON)
mkConnInfo config =
defaultConnectInfo
{ connectHost = host config
, connectPort = fromInteger $ read $ port config
, connectDatabase = dbs config
, connectUser = user config
, connectPassword = pass config
}
data AppConfig =
AppConfig
{ lcDatabase :: ConnectConfig
} deriving (Generic, ToJSON, Show)
instance FromJSON AppConfig where
parseJSON = withObject "config" $ \o -> do
db <- o .: "database"
mt <- o .: "meta"
hh <- o .: "host"
ah <- o .: "host-api"
return $ AppConfig db mt hh ah
instance FromJSON ConnectConfig where
parseJSON = withObject "database" $ \o -> do
hs <- o .: "host"
pr <- o .: "port"
dd <- o .: "db"
us <- o .: "user"
ps <- o .: "password"
return $ ConnectConfig hs pr dd us ps
data MetaConfig = MetaConfig
} deriving (Generic, ToJSON, Show)
instance FromJSON MetaConfig where
parseJSON = withObject "meta" $ \o -> do
dl <- o .: "delay"
th <- o .: "threads"
return $ MetaConfig dl th
viewCfg :: ConnectConfig -> String
viewCfg (ConnectConfig h p db u ps) =
"Connection parameters:\n"
++ " server - " ++ h ++ "\n"
++ " port - " ++ p ++ "\n"
++ " db - " ++ db ++ "\n"
++ " user - " ++ u ++ "\n"
readCfg :: String -> IO (Either Y.ParseException AppConfig)
readCfg path = Y.decodeFileEither path
readEvalCfg :: String -> IO (Either String AppConfig)
readEvalCfg path =
do
content <- BS.readFile path
BS.unpack content
let parsedContent = Y.decodeEither' content :: Either Y.ParseException AppConfig
case parsedContent of
Left exc -> do
print $ show $ exc
return $ Left "Could not parse config file."
Right cfg@(AppConfig (ConnectConfig h p d u ps) m hh ap) ->
return $
Right AppConfig { lcDatabase = connConfig
, lcMeta = m
, lcHost = hh
, lcApiHost = ap
}
where
connConfig =
ConnectConfig { host = evalCfgField h
, port = evalCfgField p
, dbs = evalCfgField d
, user = evalCfgField u
, pass = evalCfgField ps
}
evalCfgField :: String -> String
evalCfgField s =
case isInfixOf "_env" s of
True ->
fromMaybe lvar $ unsafePerformIO $ lookupEnv evar
where rs = tail $ splitOn ":" s
evar = head rs
lvar = last rs
False -> s
readImportCfg :: String -> IO (Either Y.ParseException ConnectConfig)
readImportCfg path = Y.decodeFileEither path
defaultConnectConfig = ConnectConfig {
host = "db"
, port = "5432"
, dbs = "factom-oapi"
, user = "factom"
, pass = "factom-drum"
}
|
3d0fd37947c10e4ed5207c8e890de38cb68081f1cf280418596a55966ee9ec1f | owickstrom/komposition | Focus.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE KindSignatures #
{-# LANGUAGE LambdaCase #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
module Komposition.Focus where
import Komposition.Prelude
import Control.Lens
import Control.Monad.Except (throwError)
import qualified Data.List.NonEmpty as NonEmpty
import Komposition.Composition
import Komposition.Duration
import Komposition.MediaType
data FocusType
= SequenceFocusType
| ParallelFocusType
| TrackFocusType
| ClipFocusType
type family ToFocusType (ct :: * -> *) :: FocusType where
ToFocusType Timeline = 'SequenceFocusType
ToFocusType Sequence = 'ParallelFocusType
ToFocusType Parallel = 'TrackFocusType
ToFocusType VideoTrack = 'ClipFocusType
ToFocusType AudioTrack = 'ClipFocusType
data SequenceFocus = SequenceFocus Int (Maybe ParallelFocus)
deriving (Eq, Show, Ord, Generic)
data ParallelFocus = ParallelFocus Int (Maybe TrackFocus)
deriving (Eq, Show, Ord, Generic)
data TrackFocus = TrackFocus MediaType (Maybe ClipFocus)
deriving (Eq, Show, Ord, Generic)
newtype ClipFocus = ClipFocus Int
deriving (Eq, Show, Ord, Generic)
type family Focus (t :: FocusType) where
Focus 'SequenceFocusType = SequenceFocus
Focus 'ParallelFocusType = ParallelFocus
Focus 'TrackFocusType = TrackFocus
Focus 'ClipFocusType = ClipFocus
class HasLeafFocusIndexLens focus where
leafFocusIndex :: Applicative f => (Int -> f Int) -> focus -> f focus
instance HasLeafFocusIndexLens SequenceFocus where
leafFocusIndex f (SequenceFocus i Nothing) = flip SequenceFocus Nothing <$> f i
leafFocusIndex f (SequenceFocus i (Just pf)) = SequenceFocus i . Just <$> leafFocusIndex f pf
instance HasLeafFocusIndexLens ParallelFocus where
leafFocusIndex f (ParallelFocus i Nothing) = flip ParallelFocus Nothing <$> f i
leafFocusIndex f (ParallelFocus i (Just tf)) = ParallelFocus i . Just <$> leafFocusIndex f tf
instance HasLeafFocusIndexLens TrackFocus where
leafFocusIndex f (TrackFocus mt cf) = TrackFocus mt <$> maybe (pure Nothing) (fmap Just <$> leafFocusIndex f) cf
instance HasLeafFocusIndexLens ClipFocus where
leafFocusIndex f (ClipFocus i ) = ClipFocus <$> f i
class ChangeFocusUp focus where
changeFocusUp :: focus -> Maybe focus
instance ChangeFocusUp SequenceFocus where
changeFocusUp (SequenceFocus _ Nothing) = mzero
changeFocusUp (SequenceFocus i (Just pf)) = pure (SequenceFocus i (changeFocusUp pf))
instance ChangeFocusUp ParallelFocus where
changeFocusUp (ParallelFocus _ Nothing) = mzero
changeFocusUp (ParallelFocus i (Just tf)) = pure (ParallelFocus i (changeFocusUp tf))
instance ChangeFocusUp TrackFocus where
changeFocusUp (TrackFocus _ Nothing) = mzero
changeFocusUp (TrackFocus mt (Just cf)) = pure (TrackFocus mt (changeFocusUp cf))
instance ChangeFocusUp ClipFocus where
changeFocusUp (ClipFocus _) = mzero
focusType :: SequenceFocus -> FocusType
focusType = \case
SequenceFocus _ Nothing -> SequenceFocusType
SequenceFocus _ (Just pf) ->
case pf of
ParallelFocus _ Nothing -> ParallelFocusType
ParallelFocus _ (Just tf) ->
case tf of
TrackFocus _ Nothing -> TrackFocusType
TrackFocus _ (Just _) -> ClipFocusType
data FocusCommand = FocusUp | FocusDown | FocusLeft | FocusRight
deriving (Eq, Show, Ord, Enum, Bounded)
data FocusError
= OutOfBounds
| CannotMove FocusCommand
| UnhandledFocusModification FocusCommand
deriving (Show, Eq)
indicesWithStartPoints :: HasDuration a => [a] -> [(Int, Duration)]
indicesWithStartPoints clips =
zip [0 .. (length clips - 1)] (scanl (\acc c -> durationOf AdjustedDuration c + acc) 0 clips)
nearestPartIndexLeftOf
:: (HasDuration a, HasDuration b) => [a] -> Int -> [b] -> Maybe Int
nearestPartIndexLeftOf focusedParts i blurredParts
| i >= 0 && i < length focusedParts && not (null blurredParts)
= let cutoffPoint = foldMap (durationOf AdjustedDuration) (take i focusedParts)
below' = takeWhile ((<= cutoffPoint) . snd)
(indicesWithStartPoints blurredParts)
in (fst <$> lastMay below') <|> Just 0
| otherwise
= Nothing
compositionAt :: NonEmpty (t a) -> Int -> Either FocusError (t a)
compositionAt ss i = maybe (throwError OutOfBounds) pure (toList ss `atMay` i)
-- | Changes a focus with respect to a composition (timeline,
-- sequence, parallel, or track).
class ModifyFocus (t :: * -> *) where
modifyFocus ::
(ft ~ ToFocusType t)
=> t a
-> FocusCommand
-> Focus ft
-> Either FocusError (Focus ft)
instance ModifyFocus Timeline where
modifyFocus s e f = case (s, e, f) of
-- Up
(Timeline{}, FocusUp, SequenceFocus _ Nothing) -> throwError (CannotMove FocusUp)
(Timeline seqs, FocusUp, SequenceFocus idx (Just parallelFocus)) -> do
sequence' <- seqs `compositionAt` idx
case modifyFocus sequence' FocusUp parallelFocus of
Left (CannotMove FocusUp) -> pure (SequenceFocus idx Nothing)
Left err -> throwError err
Right f' -> pure (SequenceFocus idx (Just f'))
-- Left
(Timeline{}, FocusLeft, SequenceFocus idx Nothing)
| idx > 0 -> pure (SequenceFocus (pred idx) Nothing)
| otherwise -> throwError OutOfBounds
-- Right
(Timeline sub, FocusRight, SequenceFocus idx Nothing)
| idx < (length sub - 1) -> pure (SequenceFocus (succ idx) Nothing)
| otherwise -> throwError OutOfBounds
-- Down
(Timeline seqs, FocusDown, SequenceFocus idx pf) -> do
sequence'@(Sequence _ parallels') <- seqs `compositionAt` idx
case pf of
-- Down further within sequence.
Just parallelFocus ->
SequenceFocus idx
. Just
<$> modifyFocus sequence' FocusDown parallelFocus
-- Down from sequence into parallel.
Nothing
| null parallels' -> throwError (CannotMove FocusDown)
| otherwise -> pure (SequenceFocus idx (Just (ParallelFocus 0 Nothing)))
(Timeline seqs, _, SequenceFocus idx (Just parallelFocus)) -> do
seq' <- seqs `compositionAt` idx
SequenceFocus idx . Just <$> modifyFocus seq' e parallelFocus
instance ModifyFocus Sequence where
modifyFocus s e f = case (s, e, f) of
-- Up
(Sequence{}, FocusUp, ParallelFocus _ Nothing) -> throwError (CannotMove FocusUp)
-- In case we have a parent, we try to move up within the child, or
-- fall back to focus this parent.
(Sequence _ sub, FocusUp, ParallelFocus i (Just subFocus)) -> do
sub' <- sub `compositionAt` i
case modifyFocus sub' FocusUp subFocus of
Left (CannotMove FocusUp) -> pure (ParallelFocus i Nothing)
Left err -> throwError err
Right f' -> pure (ParallelFocus i (Just f'))
-- Right
(Sequence _ sub, FocusRight, ParallelFocus idx Nothing)
| idx < (length sub - 1) -> pure (ParallelFocus (succ idx) Nothing)
| otherwise -> throwError OutOfBounds
-- Left
(Sequence{}, FocusLeft, ParallelFocus idx Nothing)
| idx > 0 -> pure (ParallelFocus (pred idx) Nothing)
| otherwise -> throwError OutOfBounds
-- Down further within a focused parallel.
(Sequence _ parallels', FocusDown, ParallelFocus idx (Just trackFocus)) -> do
parallel <- parallels' `compositionAt` idx
ParallelFocus idx . Just <$> modifyFocus parallel FocusDown trackFocus
(Sequence{}, FocusDown, ParallelFocus idx Nothing) ->
pure (ParallelFocus idx (Just (TrackFocus Video Nothing)))
-- Left or right further down within sequence.
(Sequence _ pars, _, ParallelFocus idx (Just trackFocus)) -> do
par <- pars `compositionAt` idx
ParallelFocus idx . Just <$> modifyFocus par e trackFocus
instance ModifyFocus Parallel where
modifyFocus s e f = case (s, e, f) of
-- Up
(Parallel{}, FocusUp, TrackFocus Video subFocus) ->
case subFocus of
Just _ -> pure (TrackFocus Video Nothing)
Nothing -> throwError (CannotMove FocusUp)
(Parallel{}, FocusUp, TrackFocus Audio subFocus) ->
case subFocus of
Just _ -> pure (TrackFocus Audio Nothing)
Nothing -> pure (TrackFocus Video Nothing)
-- We can move down from video to audio.
(Parallel{}, FocusDown, TrackFocus Video subFocus) ->
case subFocus of
Just _ -> throwError (CannotMove FocusDown)
Nothing -> pure (TrackFocus Audio Nothing)
-- We cannot move down any further when focusing an audio track or clip.
(Parallel{}, FocusDown, TrackFocus Audio _) -> throwError (CannotMove FocusDown)
-- Left
(Parallel{}, FocusLeft, TrackFocus _ Nothing) -> throwError (CannotMove FocusLeft)
(Parallel{}, FocusLeft, TrackFocus type' (Just (ClipFocus 0))) -> pure (TrackFocus type' Nothing)
(Parallel _ videoTrack' audioTrack', FocusLeft, TrackFocus type' (Just subFocus)) ->
case type' of
Video -> TrackFocus type' . Just <$> modifyFocus videoTrack' FocusLeft subFocus
Audio -> TrackFocus type' . Just <$> modifyFocus audioTrack' FocusLeft subFocus
-- Right
(Parallel _ (VideoTrack _ vs) _, FocusRight, TrackFocus Video Nothing)
| not (null vs) -> pure (TrackFocus Video (Just (ClipFocus 0)))
| otherwise -> throwError (CannotMove FocusRight)
(Parallel _ _ (AudioTrack _ as), FocusRight, TrackFocus Audio Nothing)
| not (null as) -> pure (TrackFocus Audio (Just (ClipFocus 0)))
| otherwise -> throwError (CannotMove FocusRight)
(Parallel _ videoTrack' audioTrack', FocusRight, TrackFocus type' (Just subFocus)) ->
case type' of
Video -> TrackFocus type' . Just <$> modifyFocus videoTrack' FocusRight subFocus
Audio -> TrackFocus type' . Just <$> modifyFocus audioTrack' FocusRight subFocus
instance ModifyFocus VideoTrack where
modifyFocus s e f = case (s, e, f) of
-- Left
(VideoTrack _ parts', FocusLeft, ClipFocus idx)
| idx > 0 && idx < length parts' -> pure (ClipFocus (pred idx))
| otherwise -> throwError OutOfBounds
-- Right
(VideoTrack _ parts', FocusRight, ClipFocus idx)
| idx >= 0 && idx < (length parts' - 1) -> pure (ClipFocus (succ idx))
| otherwise -> throwError OutOfBounds
(VideoTrack{}, cmd, _) -> throwError (CannotMove cmd)
instance ModifyFocus AudioTrack where
modifyFocus s e f = case (s, e, f) of
-- Left
(AudioTrack _ parts', FocusLeft, ClipFocus idx)
| idx > 0 && idx < length parts' -> pure (ClipFocus (pred idx))
| otherwise -> throwError OutOfBounds
-- Right
(AudioTrack _ parts', FocusRight, ClipFocus idx)
| idx >= 0 && idx < (length parts' - 1) -> pure (ClipFocus (succ idx))
| otherwise -> throwError OutOfBounds
(AudioTrack{}, cmd, _) -> throwError (CannotMove cmd)
data FocusedTraversal (f :: * -> *) a = FocusedTraversal
{ mapSequence :: Sequence a -> f (Sequence a)
, mapParallel :: Parallel a -> f (Parallel a)
, mapVideoTrack :: VideoTrack a -> f (VideoTrack a)
, mapAudioTrack :: AudioTrack a -> f (AudioTrack a)
, mapTrackPart :: forall mt. SMediaType mt -> TrackPart mt a -> f (TrackPart mt a)
}
class MapAtFocus (t :: * -> *) where
mapAtFocus ::
Applicative f
=> Focus (ToFocusType t)
-> FocusedTraversal f a
-> t a
-> f (t a)
instance MapAtFocus Timeline where
mapAtFocus focus t@FocusedTraversal{..} (Timeline sub) =
case focus of
SequenceFocus idx Nothing ->
Timeline <$> mapAt idx mapSequence sub
SequenceFocus idx (Just subFocus) ->
Timeline <$> mapAt idx (mapAtFocus subFocus t) sub
instance MapAtFocus Sequence where
mapAtFocus focus t@FocusedTraversal {..} (Sequence ann sub) =
case focus of
ParallelFocus idx Nothing -> Sequence ann <$> mapAt idx mapParallel sub
ParallelFocus idx (Just subFocus) ->
Sequence ann <$> mapAt idx (mapAtFocus subFocus t) sub
instance MapAtFocus Parallel where
mapAtFocus (TrackFocus clipType (Just clipFocus)) traversal (Parallel ann videoTrack' audioTrack') =
case clipType of
Video ->
Parallel ann <$> mapAtFocus clipFocus traversal videoTrack' <*> pure audioTrack'
Audio ->
Parallel ann <$> pure videoTrack' <*> mapAtFocus clipFocus traversal audioTrack'
mapAtFocus (TrackFocus clipType Nothing) FocusedTraversal {..} (Parallel ann videoTrack' audioTrack') =
case clipType of
Video ->
Parallel ann <$> mapVideoTrack videoTrack' <*> pure audioTrack'
Audio ->
Parallel ann <$> pure videoTrack' <*> mapAudioTrack audioTrack'
instance MapAtFocus VideoTrack where
mapAtFocus (ClipFocus idx) FocusedTraversal {..} (VideoTrack ann videoParts') =
VideoTrack ann <$> (videoParts' & ix idx %%~ mapTrackPart SVideo)
instance MapAtFocus AudioTrack where
mapAtFocus (ClipFocus idx) FocusedTraversal {..} (AudioTrack ann audioParts') =
AudioTrack ann <$> (audioParts' & ix idx %%~ mapTrackPart SAudio)
mapAt :: Applicative f => Int -> (a -> f a) -> NonEmpty a -> f (NonEmpty a)
mapAt idx f xs = toList xs & ix idx %%~ f <&> NonEmpty.fromList
type FocusedAt = SomeComposition
atFocus :: Focus 'SequenceFocusType -> Timeline a -> Maybe (FocusedAt a)
atFocus focus comp = execState (mapAtFocus focus traversal comp) Nothing
where
remember
:: forall (t :: * -> *) a
. (t a -> FocusedAt a)
-> t a
-> State (Maybe (FocusedAt a)) (t a)
remember focused x = put (Just (focused x)) >> pure x
traversal = FocusedTraversal
{ mapSequence = remember SomeSequence
, mapParallel = remember SomeParallel
, mapVideoTrack = remember SomeVideoTrack
, mapAudioTrack = remember SomeAudioTrack
, mapTrackPart = \case
SVideo -> remember SomeVideoPart
SAudio -> remember SomeAudioPart
}
data FirstTrackPart a
= FirstVideoPart (TrackPart 'Video a)
| FirstAudioPart (TrackPart 'Audio a)
firstTrackPart
:: Focus 'SequenceFocusType -> Timeline a -> Maybe (FirstTrackPart a)
firstTrackPart f s = atFocus f s >>= \case
SomeSequence s' -> firstInSequence s'
SomeParallel p -> firstInParallel p
SomeVideoTrack v -> firstInVideoTrack v
SomeAudioTrack a -> firstInAudioTrack a
SomeVideoPart v -> Just (FirstVideoPart v)
SomeAudioPart a -> Just (FirstAudioPart a)
where
firstInSequence :: Sequence a -> Maybe (FirstTrackPart a)
firstInSequence (Sequence _ ps) = firstInParallel (NonEmpty.head ps)
firstInParallel :: Parallel a -> Maybe (FirstTrackPart a)
firstInParallel = \case
Parallel _ vt at' -> firstInVideoTrack vt <|> firstInAudioTrack at'
firstInVideoTrack (VideoTrack _ vs) = FirstVideoPart <$> headMay vs
firstInAudioTrack (AudioTrack _ as) = FirstAudioPart <$> headMay as
-- * Lenses
someCompositionAt
:: Applicative f
=> Focus 'SequenceFocusType
-> (Sequence a -> f (Sequence a))
-> (Parallel a -> f (Parallel a))
-> (VideoTrack a -> f (VideoTrack a))
-> (AudioTrack a -> f (AudioTrack a))
-> (VideoPart a -> f (VideoPart a))
-> (AudioPart a -> f (AudioPart a))
-> Timeline a
-> f (Timeline a)
someCompositionAt focus sl pl vtl atl vpl apl = mapAtFocus
focus
FocusedTraversal
{ mapSequence = sl
, mapParallel = pl
, mapVideoTrack = vtl
, mapAudioTrack = atl
, mapTrackPart = \case
SVideo -> vpl
SAudio -> apl
}
class CompositionTraversal parent child where
focusing
:: forall a
. Focus (ToFocusType parent)
-> Traversal' (parent a) (child a)
instance CompositionTraversal Timeline Sequence where
focusing focus f (Timeline tl) = case focus of
SequenceFocus idx Nothing -> tl & ix idx %%~ f & fmap Timeline
SequenceFocus _ (Just _Focus) -> pure (Timeline tl)
instance CompositionTraversal Timeline Parallel where
focusing focus f (Timeline tl) = case focus of
SequenceFocus _ Nothing -> pure (Timeline tl)
SequenceFocus idx (Just subFocus) ->
tl & ix idx . focusing subFocus %%~ f & fmap Timeline
instance CompositionTraversal Timeline VideoPart where
focusing focus f (Timeline tl) = case focus of
SequenceFocus _ Nothing -> pure (Timeline tl)
SequenceFocus idx (Just subFocus) ->
tl & ix idx . focusing subFocus %%~ f & fmap Timeline
instance CompositionTraversal Timeline AudioPart where
focusing focus f (Timeline tl) = case focus of
SequenceFocus _ Nothing -> pure (Timeline tl)
SequenceFocus idx (Just subFocus) ->
tl & ix idx . focusing subFocus %%~ f & fmap Timeline
instance CompositionTraversal Sequence Parallel where
focusing focus f (Sequence ann ps) = case focus of
ParallelFocus idx Nothing -> ps & ix idx %%~ f & fmap (Sequence ann)
ParallelFocus _ (Just _Focus) -> pure (Sequence ann ps)
instance CompositionTraversal Sequence VideoPart where
focusing focus f (Sequence ann ps) = case focus of
ParallelFocus _ Nothing -> pure (Sequence ann ps)
ParallelFocus idx (Just subFocus) ->
ps & ix idx . focusing subFocus %%~ f & fmap (Sequence ann)
instance CompositionTraversal Sequence AudioPart where
focusing focus f (Sequence ann ps) = case focus of
ParallelFocus _ Nothing -> pure (Sequence ann ps)
ParallelFocus idx (Just subFocus) ->
ps & ix idx . focusing subFocus %%~ f & fmap (Sequence ann)
instance CompositionTraversal Parallel VideoPart where
focusing (TrackFocus _ Nothing) _ p = pure p
focusing (TrackFocus clipType (Just clipFocus)) f (Parallel ann videoTrack' audioTrack') =
case clipType of
Video ->
videoTrack'
& focusing clipFocus %%~ f
& fmap (\vs -> Parallel ann vs audioTrack')
Audio -> pure (Parallel ann videoTrack' audioTrack')
instance CompositionTraversal Parallel AudioPart where
focusing (TrackFocus _ Nothing) _ p = pure p
focusing (TrackFocus clipType (Just clipFocus)) f (Parallel ann videoTrack' audioTrack') =
case clipType of
Video -> pure (Parallel ann videoTrack' audioTrack')
Audio ->
audioTrack'
& focusing clipFocus %%~ f
& fmap (Parallel ann videoTrack')
instance CompositionTraversal VideoTrack VideoPart where
focusing (ClipFocus idx) f (VideoTrack ann parts') =
parts'
& ix idx %%~ f
& fmap (VideoTrack ann)
instance CompositionTraversal AudioTrack AudioPart where
focusing (ClipFocus idx) f (AudioTrack ann parts') =
parts'
& ix idx %%~ f
& fmap (AudioTrack ann)
| null | https://raw.githubusercontent.com/owickstrom/komposition/64893d50941b90f44d77fea0dc6d30c061464cf3/src/Komposition/Focus.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE ExplicitForAll #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE RankNTypes #
# LANGUAGE TypeOperators #
| Changes a focus with respect to a composition (timeline,
sequence, parallel, or track).
Up
Left
Right
Down
Down further within sequence.
Down from sequence into parallel.
Up
In case we have a parent, we try to move up within the child, or
fall back to focus this parent.
Right
Left
Down further within a focused parallel.
Left or right further down within sequence.
Up
We can move down from video to audio.
We cannot move down any further when focusing an audio track or clip.
Left
Right
Left
Right
Left
Right
* Lenses | # LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE KindSignatures #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
module Komposition.Focus where
import Komposition.Prelude
import Control.Lens
import Control.Monad.Except (throwError)
import qualified Data.List.NonEmpty as NonEmpty
import Komposition.Composition
import Komposition.Duration
import Komposition.MediaType
data FocusType
= SequenceFocusType
| ParallelFocusType
| TrackFocusType
| ClipFocusType
type family ToFocusType (ct :: * -> *) :: FocusType where
ToFocusType Timeline = 'SequenceFocusType
ToFocusType Sequence = 'ParallelFocusType
ToFocusType Parallel = 'TrackFocusType
ToFocusType VideoTrack = 'ClipFocusType
ToFocusType AudioTrack = 'ClipFocusType
data SequenceFocus = SequenceFocus Int (Maybe ParallelFocus)
deriving (Eq, Show, Ord, Generic)
data ParallelFocus = ParallelFocus Int (Maybe TrackFocus)
deriving (Eq, Show, Ord, Generic)
data TrackFocus = TrackFocus MediaType (Maybe ClipFocus)
deriving (Eq, Show, Ord, Generic)
newtype ClipFocus = ClipFocus Int
deriving (Eq, Show, Ord, Generic)
type family Focus (t :: FocusType) where
Focus 'SequenceFocusType = SequenceFocus
Focus 'ParallelFocusType = ParallelFocus
Focus 'TrackFocusType = TrackFocus
Focus 'ClipFocusType = ClipFocus
class HasLeafFocusIndexLens focus where
leafFocusIndex :: Applicative f => (Int -> f Int) -> focus -> f focus
instance HasLeafFocusIndexLens SequenceFocus where
leafFocusIndex f (SequenceFocus i Nothing) = flip SequenceFocus Nothing <$> f i
leafFocusIndex f (SequenceFocus i (Just pf)) = SequenceFocus i . Just <$> leafFocusIndex f pf
instance HasLeafFocusIndexLens ParallelFocus where
leafFocusIndex f (ParallelFocus i Nothing) = flip ParallelFocus Nothing <$> f i
leafFocusIndex f (ParallelFocus i (Just tf)) = ParallelFocus i . Just <$> leafFocusIndex f tf
instance HasLeafFocusIndexLens TrackFocus where
leafFocusIndex f (TrackFocus mt cf) = TrackFocus mt <$> maybe (pure Nothing) (fmap Just <$> leafFocusIndex f) cf
instance HasLeafFocusIndexLens ClipFocus where
leafFocusIndex f (ClipFocus i ) = ClipFocus <$> f i
class ChangeFocusUp focus where
changeFocusUp :: focus -> Maybe focus
instance ChangeFocusUp SequenceFocus where
changeFocusUp (SequenceFocus _ Nothing) = mzero
changeFocusUp (SequenceFocus i (Just pf)) = pure (SequenceFocus i (changeFocusUp pf))
instance ChangeFocusUp ParallelFocus where
changeFocusUp (ParallelFocus _ Nothing) = mzero
changeFocusUp (ParallelFocus i (Just tf)) = pure (ParallelFocus i (changeFocusUp tf))
instance ChangeFocusUp TrackFocus where
changeFocusUp (TrackFocus _ Nothing) = mzero
changeFocusUp (TrackFocus mt (Just cf)) = pure (TrackFocus mt (changeFocusUp cf))
instance ChangeFocusUp ClipFocus where
changeFocusUp (ClipFocus _) = mzero
focusType :: SequenceFocus -> FocusType
focusType = \case
SequenceFocus _ Nothing -> SequenceFocusType
SequenceFocus _ (Just pf) ->
case pf of
ParallelFocus _ Nothing -> ParallelFocusType
ParallelFocus _ (Just tf) ->
case tf of
TrackFocus _ Nothing -> TrackFocusType
TrackFocus _ (Just _) -> ClipFocusType
data FocusCommand = FocusUp | FocusDown | FocusLeft | FocusRight
deriving (Eq, Show, Ord, Enum, Bounded)
data FocusError
= OutOfBounds
| CannotMove FocusCommand
| UnhandledFocusModification FocusCommand
deriving (Show, Eq)
indicesWithStartPoints :: HasDuration a => [a] -> [(Int, Duration)]
indicesWithStartPoints clips =
zip [0 .. (length clips - 1)] (scanl (\acc c -> durationOf AdjustedDuration c + acc) 0 clips)
nearestPartIndexLeftOf
:: (HasDuration a, HasDuration b) => [a] -> Int -> [b] -> Maybe Int
nearestPartIndexLeftOf focusedParts i blurredParts
| i >= 0 && i < length focusedParts && not (null blurredParts)
= let cutoffPoint = foldMap (durationOf AdjustedDuration) (take i focusedParts)
below' = takeWhile ((<= cutoffPoint) . snd)
(indicesWithStartPoints blurredParts)
in (fst <$> lastMay below') <|> Just 0
| otherwise
= Nothing
compositionAt :: NonEmpty (t a) -> Int -> Either FocusError (t a)
compositionAt ss i = maybe (throwError OutOfBounds) pure (toList ss `atMay` i)
class ModifyFocus (t :: * -> *) where
modifyFocus ::
(ft ~ ToFocusType t)
=> t a
-> FocusCommand
-> Focus ft
-> Either FocusError (Focus ft)
instance ModifyFocus Timeline where
modifyFocus s e f = case (s, e, f) of
(Timeline{}, FocusUp, SequenceFocus _ Nothing) -> throwError (CannotMove FocusUp)
(Timeline seqs, FocusUp, SequenceFocus idx (Just parallelFocus)) -> do
sequence' <- seqs `compositionAt` idx
case modifyFocus sequence' FocusUp parallelFocus of
Left (CannotMove FocusUp) -> pure (SequenceFocus idx Nothing)
Left err -> throwError err
Right f' -> pure (SequenceFocus idx (Just f'))
(Timeline{}, FocusLeft, SequenceFocus idx Nothing)
| idx > 0 -> pure (SequenceFocus (pred idx) Nothing)
| otherwise -> throwError OutOfBounds
(Timeline sub, FocusRight, SequenceFocus idx Nothing)
| idx < (length sub - 1) -> pure (SequenceFocus (succ idx) Nothing)
| otherwise -> throwError OutOfBounds
(Timeline seqs, FocusDown, SequenceFocus idx pf) -> do
sequence'@(Sequence _ parallels') <- seqs `compositionAt` idx
case pf of
Just parallelFocus ->
SequenceFocus idx
. Just
<$> modifyFocus sequence' FocusDown parallelFocus
Nothing
| null parallels' -> throwError (CannotMove FocusDown)
| otherwise -> pure (SequenceFocus idx (Just (ParallelFocus 0 Nothing)))
(Timeline seqs, _, SequenceFocus idx (Just parallelFocus)) -> do
seq' <- seqs `compositionAt` idx
SequenceFocus idx . Just <$> modifyFocus seq' e parallelFocus
instance ModifyFocus Sequence where
modifyFocus s e f = case (s, e, f) of
(Sequence{}, FocusUp, ParallelFocus _ Nothing) -> throwError (CannotMove FocusUp)
(Sequence _ sub, FocusUp, ParallelFocus i (Just subFocus)) -> do
sub' <- sub `compositionAt` i
case modifyFocus sub' FocusUp subFocus of
Left (CannotMove FocusUp) -> pure (ParallelFocus i Nothing)
Left err -> throwError err
Right f' -> pure (ParallelFocus i (Just f'))
(Sequence _ sub, FocusRight, ParallelFocus idx Nothing)
| idx < (length sub - 1) -> pure (ParallelFocus (succ idx) Nothing)
| otherwise -> throwError OutOfBounds
(Sequence{}, FocusLeft, ParallelFocus idx Nothing)
| idx > 0 -> pure (ParallelFocus (pred idx) Nothing)
| otherwise -> throwError OutOfBounds
(Sequence _ parallels', FocusDown, ParallelFocus idx (Just trackFocus)) -> do
parallel <- parallels' `compositionAt` idx
ParallelFocus idx . Just <$> modifyFocus parallel FocusDown trackFocus
(Sequence{}, FocusDown, ParallelFocus idx Nothing) ->
pure (ParallelFocus idx (Just (TrackFocus Video Nothing)))
(Sequence _ pars, _, ParallelFocus idx (Just trackFocus)) -> do
par <- pars `compositionAt` idx
ParallelFocus idx . Just <$> modifyFocus par e trackFocus
instance ModifyFocus Parallel where
modifyFocus s e f = case (s, e, f) of
(Parallel{}, FocusUp, TrackFocus Video subFocus) ->
case subFocus of
Just _ -> pure (TrackFocus Video Nothing)
Nothing -> throwError (CannotMove FocusUp)
(Parallel{}, FocusUp, TrackFocus Audio subFocus) ->
case subFocus of
Just _ -> pure (TrackFocus Audio Nothing)
Nothing -> pure (TrackFocus Video Nothing)
(Parallel{}, FocusDown, TrackFocus Video subFocus) ->
case subFocus of
Just _ -> throwError (CannotMove FocusDown)
Nothing -> pure (TrackFocus Audio Nothing)
(Parallel{}, FocusDown, TrackFocus Audio _) -> throwError (CannotMove FocusDown)
(Parallel{}, FocusLeft, TrackFocus _ Nothing) -> throwError (CannotMove FocusLeft)
(Parallel{}, FocusLeft, TrackFocus type' (Just (ClipFocus 0))) -> pure (TrackFocus type' Nothing)
(Parallel _ videoTrack' audioTrack', FocusLeft, TrackFocus type' (Just subFocus)) ->
case type' of
Video -> TrackFocus type' . Just <$> modifyFocus videoTrack' FocusLeft subFocus
Audio -> TrackFocus type' . Just <$> modifyFocus audioTrack' FocusLeft subFocus
(Parallel _ (VideoTrack _ vs) _, FocusRight, TrackFocus Video Nothing)
| not (null vs) -> pure (TrackFocus Video (Just (ClipFocus 0)))
| otherwise -> throwError (CannotMove FocusRight)
(Parallel _ _ (AudioTrack _ as), FocusRight, TrackFocus Audio Nothing)
| not (null as) -> pure (TrackFocus Audio (Just (ClipFocus 0)))
| otherwise -> throwError (CannotMove FocusRight)
(Parallel _ videoTrack' audioTrack', FocusRight, TrackFocus type' (Just subFocus)) ->
case type' of
Video -> TrackFocus type' . Just <$> modifyFocus videoTrack' FocusRight subFocus
Audio -> TrackFocus type' . Just <$> modifyFocus audioTrack' FocusRight subFocus
instance ModifyFocus VideoTrack where
modifyFocus s e f = case (s, e, f) of
(VideoTrack _ parts', FocusLeft, ClipFocus idx)
| idx > 0 && idx < length parts' -> pure (ClipFocus (pred idx))
| otherwise -> throwError OutOfBounds
(VideoTrack _ parts', FocusRight, ClipFocus idx)
| idx >= 0 && idx < (length parts' - 1) -> pure (ClipFocus (succ idx))
| otherwise -> throwError OutOfBounds
(VideoTrack{}, cmd, _) -> throwError (CannotMove cmd)
instance ModifyFocus AudioTrack where
modifyFocus s e f = case (s, e, f) of
(AudioTrack _ parts', FocusLeft, ClipFocus idx)
| idx > 0 && idx < length parts' -> pure (ClipFocus (pred idx))
| otherwise -> throwError OutOfBounds
(AudioTrack _ parts', FocusRight, ClipFocus idx)
| idx >= 0 && idx < (length parts' - 1) -> pure (ClipFocus (succ idx))
| otherwise -> throwError OutOfBounds
(AudioTrack{}, cmd, _) -> throwError (CannotMove cmd)
data FocusedTraversal (f :: * -> *) a = FocusedTraversal
{ mapSequence :: Sequence a -> f (Sequence a)
, mapParallel :: Parallel a -> f (Parallel a)
, mapVideoTrack :: VideoTrack a -> f (VideoTrack a)
, mapAudioTrack :: AudioTrack a -> f (AudioTrack a)
, mapTrackPart :: forall mt. SMediaType mt -> TrackPart mt a -> f (TrackPart mt a)
}
class MapAtFocus (t :: * -> *) where
mapAtFocus ::
Applicative f
=> Focus (ToFocusType t)
-> FocusedTraversal f a
-> t a
-> f (t a)
instance MapAtFocus Timeline where
mapAtFocus focus t@FocusedTraversal{..} (Timeline sub) =
case focus of
SequenceFocus idx Nothing ->
Timeline <$> mapAt idx mapSequence sub
SequenceFocus idx (Just subFocus) ->
Timeline <$> mapAt idx (mapAtFocus subFocus t) sub
instance MapAtFocus Sequence where
mapAtFocus focus t@FocusedTraversal {..} (Sequence ann sub) =
case focus of
ParallelFocus idx Nothing -> Sequence ann <$> mapAt idx mapParallel sub
ParallelFocus idx (Just subFocus) ->
Sequence ann <$> mapAt idx (mapAtFocus subFocus t) sub
instance MapAtFocus Parallel where
mapAtFocus (TrackFocus clipType (Just clipFocus)) traversal (Parallel ann videoTrack' audioTrack') =
case clipType of
Video ->
Parallel ann <$> mapAtFocus clipFocus traversal videoTrack' <*> pure audioTrack'
Audio ->
Parallel ann <$> pure videoTrack' <*> mapAtFocus clipFocus traversal audioTrack'
mapAtFocus (TrackFocus clipType Nothing) FocusedTraversal {..} (Parallel ann videoTrack' audioTrack') =
case clipType of
Video ->
Parallel ann <$> mapVideoTrack videoTrack' <*> pure audioTrack'
Audio ->
Parallel ann <$> pure videoTrack' <*> mapAudioTrack audioTrack'
instance MapAtFocus VideoTrack where
mapAtFocus (ClipFocus idx) FocusedTraversal {..} (VideoTrack ann videoParts') =
VideoTrack ann <$> (videoParts' & ix idx %%~ mapTrackPart SVideo)
instance MapAtFocus AudioTrack where
mapAtFocus (ClipFocus idx) FocusedTraversal {..} (AudioTrack ann audioParts') =
AudioTrack ann <$> (audioParts' & ix idx %%~ mapTrackPart SAudio)
mapAt :: Applicative f => Int -> (a -> f a) -> NonEmpty a -> f (NonEmpty a)
mapAt idx f xs = toList xs & ix idx %%~ f <&> NonEmpty.fromList
type FocusedAt = SomeComposition
atFocus :: Focus 'SequenceFocusType -> Timeline a -> Maybe (FocusedAt a)
atFocus focus comp = execState (mapAtFocus focus traversal comp) Nothing
where
remember
:: forall (t :: * -> *) a
. (t a -> FocusedAt a)
-> t a
-> State (Maybe (FocusedAt a)) (t a)
remember focused x = put (Just (focused x)) >> pure x
traversal = FocusedTraversal
{ mapSequence = remember SomeSequence
, mapParallel = remember SomeParallel
, mapVideoTrack = remember SomeVideoTrack
, mapAudioTrack = remember SomeAudioTrack
, mapTrackPart = \case
SVideo -> remember SomeVideoPart
SAudio -> remember SomeAudioPart
}
data FirstTrackPart a
= FirstVideoPart (TrackPart 'Video a)
| FirstAudioPart (TrackPart 'Audio a)
firstTrackPart
:: Focus 'SequenceFocusType -> Timeline a -> Maybe (FirstTrackPart a)
firstTrackPart f s = atFocus f s >>= \case
SomeSequence s' -> firstInSequence s'
SomeParallel p -> firstInParallel p
SomeVideoTrack v -> firstInVideoTrack v
SomeAudioTrack a -> firstInAudioTrack a
SomeVideoPart v -> Just (FirstVideoPart v)
SomeAudioPart a -> Just (FirstAudioPart a)
where
firstInSequence :: Sequence a -> Maybe (FirstTrackPart a)
firstInSequence (Sequence _ ps) = firstInParallel (NonEmpty.head ps)
firstInParallel :: Parallel a -> Maybe (FirstTrackPart a)
firstInParallel = \case
Parallel _ vt at' -> firstInVideoTrack vt <|> firstInAudioTrack at'
firstInVideoTrack (VideoTrack _ vs) = FirstVideoPart <$> headMay vs
firstInAudioTrack (AudioTrack _ as) = FirstAudioPart <$> headMay as
someCompositionAt
:: Applicative f
=> Focus 'SequenceFocusType
-> (Sequence a -> f (Sequence a))
-> (Parallel a -> f (Parallel a))
-> (VideoTrack a -> f (VideoTrack a))
-> (AudioTrack a -> f (AudioTrack a))
-> (VideoPart a -> f (VideoPart a))
-> (AudioPart a -> f (AudioPart a))
-> Timeline a
-> f (Timeline a)
someCompositionAt focus sl pl vtl atl vpl apl = mapAtFocus
focus
FocusedTraversal
{ mapSequence = sl
, mapParallel = pl
, mapVideoTrack = vtl
, mapAudioTrack = atl
, mapTrackPart = \case
SVideo -> vpl
SAudio -> apl
}
class CompositionTraversal parent child where
focusing
:: forall a
. Focus (ToFocusType parent)
-> Traversal' (parent a) (child a)
instance CompositionTraversal Timeline Sequence where
focusing focus f (Timeline tl) = case focus of
SequenceFocus idx Nothing -> tl & ix idx %%~ f & fmap Timeline
SequenceFocus _ (Just _Focus) -> pure (Timeline tl)
instance CompositionTraversal Timeline Parallel where
focusing focus f (Timeline tl) = case focus of
SequenceFocus _ Nothing -> pure (Timeline tl)
SequenceFocus idx (Just subFocus) ->
tl & ix idx . focusing subFocus %%~ f & fmap Timeline
instance CompositionTraversal Timeline VideoPart where
focusing focus f (Timeline tl) = case focus of
SequenceFocus _ Nothing -> pure (Timeline tl)
SequenceFocus idx (Just subFocus) ->
tl & ix idx . focusing subFocus %%~ f & fmap Timeline
instance CompositionTraversal Timeline AudioPart where
focusing focus f (Timeline tl) = case focus of
SequenceFocus _ Nothing -> pure (Timeline tl)
SequenceFocus idx (Just subFocus) ->
tl & ix idx . focusing subFocus %%~ f & fmap Timeline
instance CompositionTraversal Sequence Parallel where
focusing focus f (Sequence ann ps) = case focus of
ParallelFocus idx Nothing -> ps & ix idx %%~ f & fmap (Sequence ann)
ParallelFocus _ (Just _Focus) -> pure (Sequence ann ps)
instance CompositionTraversal Sequence VideoPart where
focusing focus f (Sequence ann ps) = case focus of
ParallelFocus _ Nothing -> pure (Sequence ann ps)
ParallelFocus idx (Just subFocus) ->
ps & ix idx . focusing subFocus %%~ f & fmap (Sequence ann)
instance CompositionTraversal Sequence AudioPart where
focusing focus f (Sequence ann ps) = case focus of
ParallelFocus _ Nothing -> pure (Sequence ann ps)
ParallelFocus idx (Just subFocus) ->
ps & ix idx . focusing subFocus %%~ f & fmap (Sequence ann)
instance CompositionTraversal Parallel VideoPart where
focusing (TrackFocus _ Nothing) _ p = pure p
focusing (TrackFocus clipType (Just clipFocus)) f (Parallel ann videoTrack' audioTrack') =
case clipType of
Video ->
videoTrack'
& focusing clipFocus %%~ f
& fmap (\vs -> Parallel ann vs audioTrack')
Audio -> pure (Parallel ann videoTrack' audioTrack')
instance CompositionTraversal Parallel AudioPart where
focusing (TrackFocus _ Nothing) _ p = pure p
focusing (TrackFocus clipType (Just clipFocus)) f (Parallel ann videoTrack' audioTrack') =
case clipType of
Video -> pure (Parallel ann videoTrack' audioTrack')
Audio ->
audioTrack'
& focusing clipFocus %%~ f
& fmap (Parallel ann videoTrack')
instance CompositionTraversal VideoTrack VideoPart where
focusing (ClipFocus idx) f (VideoTrack ann parts') =
parts'
& ix idx %%~ f
& fmap (VideoTrack ann)
instance CompositionTraversal AudioTrack AudioPart where
focusing (ClipFocus idx) f (AudioTrack ann parts') =
parts'
& ix idx %%~ f
& fmap (AudioTrack ann)
|
97440aa5c17d489cae4c66f70e2f4ec7db042b289950c7e5b5dff1ff18aea505 | pascal-knodel/haskell-craft | E'11'16.hs | --
--
--
------------------
Exercise 11.16 .
------------------
--
--
--
module E'11'16 where
import Test.QuickCheck
prop_uncurryZip :: [Bool] -> [Bool] -> Property
prop_uncurryZip leftList rightList
( -- 1 )
==> ( unzip $ (uncurry zip) (leftList , rightList) ) == (leftList , rightList)
-- GHCi> quickCheck prop_uncurryZip
* * * Gave up ! Passed only 50 tests .
-- Note: Not nice. I have the feeling the authors want us to suffer a little.
-- I guess, that it will be possible to define ELLs (Equal Lengths Lists) later.
-- Other solutions for "prop_uncurryZip":
prop_uncurryZip' :: ([Bool] , [Bool]) -> Property
prop_uncurryZip' lists
( -- 1 )
==> ( unzip $ (uncurry zip) lists ) == lists
-- GHCi> quickCheck prop_uncurryZip'
| null | https://raw.githubusercontent.com/pascal-knodel/haskell-craft/c03d6eb857abd8b4785b6de075b094ec3653c968/Chapter%C2%A011/E'11'16.hs | haskell |
----------------
----------------
1 )
GHCi> quickCheck prop_uncurryZip
Note: Not nice. I have the feeling the authors want us to suffer a little.
I guess, that it will be possible to define ELLs (Equal Lengths Lists) later.
Other solutions for "prop_uncurryZip":
1 )
GHCi> quickCheck prop_uncurryZip' | Exercise 11.16 .
module E'11'16 where
import Test.QuickCheck
prop_uncurryZip :: [Bool] -> [Bool] -> Property
prop_uncurryZip leftList rightList
==> ( unzip $ (uncurry zip) (leftList , rightList) ) == (leftList , rightList)
* * * Gave up ! Passed only 50 tests .
prop_uncurryZip' :: ([Bool] , [Bool]) -> Property
prop_uncurryZip' lists
==> ( unzip $ (uncurry zip) lists ) == lists
|
29828d20b961f6bf213e717dc882bf9d8e67ee6f2578bd46d35593e500deb5ad | philnguyen/soft-contract | app.rkt | #lang typed/racket/base
(provide app@)
(require racket/set
racket/list
racket/match
racket/vector
typed/racket/unit
syntax/parse/define
set-extras
bnf
unreachable
"../utils/patterns.rkt"
"../utils/map.rkt"
"../ast/signatures.rkt"
"../runtime/signatures.rkt"
"../signatures.rkt"
"signatures.rkt"
)
(⟦F⟧ . ≜ . (Σ ℓ W → (Values R (℘ Err))))
(⟦G⟧ . ≜ . (Σ ℓ W V^ → (Values R (℘ Err))))
(define-unit app@
(import meta-functions^ static-info^ ast-pretty-print^
params^ sto^ cache^ val^ pretty-print^
prims^ prover^
exec^ evl^ mon^ hv^ gc^)
(export app^)
;; A call history tracks the call chain that leads to the current expression, modulo loops
(Stk . ≜ . (Listof E))
(define current-chain ((inst make-parameter Stk) '()))
;; Global table remembering the widest store for each chain
;; FIXME: memory leak. Reset for each program.
(define global-stores : (HashTable (Pairof Stk Σ) Σ) (make-hash))
(: app : Σ ℓ V^ W → (Values R (℘ Err)))
(define (app Σ ℓ Vₕ^ W*)
(define-values (W ΔΣ) (escape-clos Σ W*))
(define root₀ (∪ (W-root W) (B-root (current-parameters))))
((inst fold-ans V)
(λ (Vₕ)
(define root (∪ root₀ (V-root Vₕ)))
(define Σ* (gc root (⧺ Σ ΔΣ)))
(log-scv-preval-debug "~n~a~a ⊢ₐ:~a ~a ~a~n"
(make-string (* 4 (db:depth)) #\space)
(show-Σ Σ*)
(show-full-ℓ ℓ)
(show-V Vₕ)
(show-W W))
(define-values (r es) (parameterize ([db:depth (+ (db:depth))]) (ref-$! ($:Key:App Σ* (current-parameters) ℓ Vₕ W)
(λ () (with-gc root Σ* (λ () (with-pre ΔΣ (app₁ Σ* ℓ Vₕ W))))))))
(log-scv-eval-debug "~n~a~a ⊢ₐ:~a ~a ~a ⇓ ~a~n"
(make-string (* 4 (db:depth)) #\space)
(show-Σ Σ*)
(show-full-ℓ ℓ)
(show-V Vₕ)
(show-W W)
(show-R r))
(values r es))
(unpack Vₕ^ Σ)))
(: app/C : Σ ℓ V^ W → (Values R (℘ Err)))
(define (app/C Σ ℓ Cs W)
(define-values (bs Cs*) (set-partition -b? Cs))
(define-values (r₁ es₁) (cond [(set-empty? Cs*) (values ⊥R ∅)]
[else (app Σ ℓ Cs* W)]))
(define-values (r₂ es₂) (cond [(set-empty? bs) (values ⊥R ∅)]
[else (app₁ Σ ℓ 'equal? (cons bs W))]))
(values (R⊔ r₁ r₂) (∪ es₁ es₂)))
(: app₁ : Σ ℓ V W → (Values R (℘ Err)))
(define (app₁ Σ ℓ V W)
(define f (match V
[(? -λ? V) (app-λ V)]
[(? Clo? V) (app-Clo V)]
[(? Case-Clo? V) (app-Case-Clo V)]
[(-st-mk 𝒾) (app-st-mk 𝒾)]
[(-st-p 𝒾) (app-st-p 𝒾)]
[(-st-ac 𝒾 i) (app-st-ac 𝒾 i)]
[(-st-mut 𝒾 i) (app-st-mut 𝒾 i)]
[(? symbol? o) (app-prim o)]
[(Param α) (app-param α)]
[(Guarded ctx (? Fn/C? G) α)
(cond [(==>i? G) (app-==>i ctx G α)]
[(∀/C? G) (app-∀/C ctx G α)]
[(Case-=>? G) (app-Case-=> ctx G α)]
[(Param/C? G) (app-Param/C ctx G α)]
[else (app-Terminating/C ctx α)])]
[(And/C α₁ α₂ ℓ) #:when (C-flat? V Σ) (app-And/C α₁ α₂ ℓ)]
[(Or/C α₁ α₂ ℓ) #:when (C-flat? V Σ) (app-Or/C α₁ α₂ ℓ)]
[(Not/C α ℓ) (app-Not/C α ℓ)]
[(Rec/C α) (app-Rec/C α)]
[(One-Of/C bs) (app-One-Of/C bs)]
[(? St/C?) #:when (C-flat? V Σ) (app-St/C V)]
[(-● Ps) (app-opq Ps)]
[(P:≡ T) (app-P 'equal? T)]
[(P:= T) (app-P '= T)]
[(P:> T) (app-P '< T)]
[(P:≥ T) (app-P '<= T)]
[(P:< T) (app-P '> T)]
[(P:≤ T) (app-P '>= T)]
[V (app-err V)]))
(f Σ ℓ W))
(: app-λ : -λ → ⟦F⟧)
(define ((app-λ Vₕ) Σ ℓ Wₓ*)
(match-define (-λ fml E ℓₕ) Vₕ)
(cond [(arity-includes? (shape fml) (length Wₓ*))
(match-define (-var xs xᵣ) fml)
(define Wₓ (unpack-W Wₓ* Σ))
(define ΔΣₓ
(let-values ([(W₀ Wᵣ) (if xᵣ (split-at Wₓ (length xs)) (values Wₓ '()))])
(⧺ (alloc-lex* xs W₀)
(if xᵣ (alloc-vararg xᵣ Wᵣ) ⊥ΔΣ))))
gc one more time against unpacked arguments
;; TODO: clean this up so only need to gc once?
;; TODO: code dup
(let ([root (∪ (E-root Vₕ) (W-root Wₓ) (B-root (current-parameters)))])
(define Σ₁ (gc root Σ))
(define-values (rₐ es) (evl/history (⧺ Σ₁ ΔΣₓ) E))
(define rn (trim-renamings (make-renamings fml Wₓ* assignable?)))
(values (fix-return rn Σ₁ (R-escape-clos Σ₁ (ΔΣ⧺R ΔΣₓ rₐ))) es))]
[else (err (Err:Arity ℓₕ (length Wₓ*) ℓ))]))
(: app-Clo : Clo → ⟦F⟧)
(define ((app-Clo Vₕ) Σ ℓ Wₓ*)
(match-define (Clo fml E H ℓₕ) Vₕ)
(cond [(arity-includes? (shape fml) (length Wₓ*))
(match-define (-var xs xᵣ) fml)
(define Wₓ (unpack-W Wₓ* Σ))
(define ΔΣₓ
(let-values ([(W₀ Wᵣ) (if xᵣ (split-at Wₓ (length xs)) (values Wₓ '()))])
(⧺ (stack-copy (Clo-escapes fml E H ℓₕ) Σ)
(alloc-lex* xs W₀)
(if xᵣ (alloc-vararg xᵣ Wᵣ) ⊥ΔΣ))))
gc one more time against unpacked arguments
;; TODO: clean this up so only need to gc once?
(let ([root (∪ (V-root Vₕ) (W-root Wₓ) (B-root (current-parameters)))])
(define Σ₁ (gc root Σ))
(define-values (rₐ es) (evl/history (⧺ Σ₁ ΔΣₓ) E)) ; no `ΔΣₓ` in result
(define rn (trim-renamings (insert-fv-erasures ΔΣₓ (make-renamings fml Wₓ* assignable?))))
(values (fix-return rn Σ₁ (R-escape-clos Σ₁ (ΔΣ⧺R ΔΣₓ rₐ))) es))]
[else (err (Err:Arity ℓₕ (length Wₓ*) ℓ))]))
(: evl/history : Σ E → (Values R (℘ Err)))
(define (evl/history Σ₁ E)
(define stk (current-chain))
(define stk* (cond [(memq E stk) => values]
[else (cons E stk)]))
(define k (cons stk* (Σ-stk Σ₁)))
(define Σ* (match (hash-ref global-stores k #f)
[(? values Σ₀) (ΔΣ⊔ Σ₀ Σ₁)]
[_ Σ₁]))
(hash-set! global-stores k Σ*)
(parameterize ([current-chain stk*])
(evl Σ* E)))
(: Σ-stk : Σ → Σ)
(define (Σ-stk Σ₀)
(for/fold ([Σ* : Σ Σ₀]) ([α (in-hash-keys Σ₀)] #:unless (γ:lex? α))
(hash-remove Σ* α)))
(: app-Case-Clo : Case-Clo → ⟦F⟧)
(define ((app-Case-Clo Vₕ) Σ ℓ Wₓ)
(match-define (Case-Clo cases ℓₕ) Vₕ)
(define n (length Wₓ))
(match ((inst findf Clo) (λ (clo) (arity-includes? (shape (Clo-_0 clo)) n)) cases)
[(? values clo) ((app-Clo clo) Σ ℓ Wₓ)]
[#f (err (Err:Arity ℓₕ n ℓ))]))
(: app-st-mk : -𝒾 → ⟦F⟧)
(define ((app-st-mk 𝒾) Σ ℓ Wₓ)
(define n (count-struct-fields 𝒾))
(if (= n (length Wₓ))
(let ([α (α:dyn (β:st-elems ℓ 𝒾) H₀)])
(just (St α ∅) (alloc α (list->vector (unpack-W Wₓ Σ)))))
(err (Err:Arity (-st-mk 𝒾) (length Wₓ) ℓ))))
(: app-st-p : -𝒾 → ⟦F⟧)
(define ((app-st-p 𝒾) Σ ℓ Wₓ)
(with-guarded-arity Wₓ (-st-p 𝒾) ℓ
[(list _) (implement-predicate Σ (-st-p 𝒾) Wₓ)]))
(: app-st-ac : -𝒾 Index → ⟦F⟧)
(define ((app-st-ac 𝒾 i) Σ ℓ Wₓ)
(with-guarded-arity Wₓ (-st-ac 𝒾 i) ℓ
[(list Vₓ)
(with-split-Σ Σ (-st-p 𝒾) Wₓ
(λ (Wₓ* ΔΣ₁) (with-pre ΔΣ₁ ((unchecked-app-st-ac 𝒾 i) (⧺ Σ ΔΣ₁) ℓ (car Wₓ*))))
(λ (Wₓ* ΔΣ₂)
(define ℓₒ (ℓ-with-src +ℓ₀ (show-o (-st-ac 𝒾 i))))
(err (blm (ℓ-src ℓ) ℓ ℓₒ (list {set (-st-p 𝒾)}) Wₓ*))))]))
(: unchecked-app-st-ac : -𝒾 Index → Σ ℓ V^ → (Values R (℘ Err)))
(define ((unchecked-app-st-ac 𝒾 i) Σ ℓ Vₓ)
(define ac₁ : (V → (Values R (℘ Err)))
(match-lambda
[(St α Ps)
(define Vᵢ (vector-ref (Σ@/blob α Σ) i))
(define-values (V* ΔΣ)
(refine (unpack Vᵢ Σ) (ac-Ps (-st-ac 𝒾 i) Ps) Σ))
(just V* ΔΣ)]
[(and T (or (? T:@?) (? γ?))) #:when (not (struct-mutable? 𝒾 i))
(define T* (T:@ (-st-ac 𝒾 i) (list T)))
(if (set-empty? (unpack T* Σ)) (values ⊥R ∅) (just T*))]
[(Guarded (cons l+ l-) (? St/C? C) αᵥ)
(define-values (αₕ ℓₕ _) (St/C-fields C))
(define Cᵢ (vector-ref (Σ@/blob αₕ Σ) i))
(with-collapsing/R [(ΔΣ Ws) ((unchecked-app-st-ac 𝒾 i) Σ ℓ (unpack αᵥ Σ))]
(with-pre ΔΣ (mon (⧺ Σ ΔΣ) (Ctx l+ l- ℓₕ ℓ) Cᵢ (car (collapse-W^ Ws)))))]
[(and V₀ (-● Ps))
(case (sat Σ (-st-p 𝒾) {set V₀})
[(✗) (values ⊥R ∅)]
[else (just (st-ac-● 𝒾 i Ps Σ))])]
[(? α? α) (fold-ans ac₁ (unpack α Σ))]
[_ (values ⊥R ∅)]))
(fold-ans/collapsing ac₁ Vₓ))
(: st-ac-● : -𝒾 Index (℘ P) Σ → V^)
(define (st-ac-● 𝒾 i Ps Σ)
(define V
(if (prim-struct? 𝒾)
{set (-● ∅)}
;; Track access to user-defined structs
(Σ@ (γ:escaped-field 𝒾 i) Σ)))
(cond [(set-empty? V) ∅]
[else (define-values (V* _) (refine V (ac-Ps (-st-ac 𝒾 i) Ps) Σ))
V*]))
(: app-st-mut : -𝒾 Index → ⟦F⟧)
(define ((app-st-mut 𝒾 i) Σ ℓ Wₓ)
(with-guarded-arity Wₓ (-st-mut 𝒾 i) ℓ
[(list Vₓ V*)
(with-split-Σ Σ (-st-p 𝒾) (list Vₓ)
(λ (Wₓ* ΔΣ₁) (with-pre ΔΣ₁ ((unchecked-app-st-mut 𝒾 i) (⧺ Σ ΔΣ₁) ℓ (car Wₓ*) V*)))
(λ (Wₓ* ΔΣ₂) (err (blm (ℓ-src ℓ) ℓ (ℓ-with-src +ℓ₀ (show-o (-st-mut 𝒾 i))) (list {set (-st-p 𝒾)}) Wₓ*))))]))
(: unchecked-app-st-mut : -𝒾 Index → Σ ℓ V^ V^ → (Values R (℘ Err)))
(define ((unchecked-app-st-mut 𝒾 i) Σ ℓ Vₓ V*)
((inst fold-ans V)
(match-lambda
[(St α _)
(define S (Σ@/blob α Σ))
(define S* (vector-copy S))
(vector-set! S* i V*)
(just -void (mut α S* Σ))]
[(Guarded (cons l+ l-) (? St/C? C) αᵥ)
(define-values (αₕ ℓₕ _) (St/C-fields C))
(define Cᵢ (vector-ref (Σ@/blob αₕ Σ) i))
(with-collapsing/R [(ΔΣ Ws) (mon Σ (Ctx l- l+ ℓₕ ℓ) Cᵢ V*)]
(with-pre ΔΣ ((unchecked-app-st-mut 𝒾 i) (⧺ Σ ΔΣ) ℓ (unpack αᵥ Σ) V*)))]
[(? -●?) (just -void (alloc (γ:hv #f) V*))]
[_ (values ⊥R ∅)])
(unpack Vₓ Σ)))
(: app-prim : Symbol → ⟦F⟧)
(define ((app-prim o) Σ ℓ Wₓ)
TODO massage raw result
((get-prim o) Σ ℓ Wₓ))
(: app-param : α → ⟦F⟧)
(define ((app-param α) Σ ℓ Wₓ)
(match Wₓ
[(list) (just (current-parameter α))]
[(list V) (set-parameter α V)
(just -void)]
[_ (err (Err:Arity (Param α) (length Wₓ) ℓ))]))
(: app-==>i : (Pairof -l -l) ==>i α → ⟦F⟧)
(define ((app-==>i ctx:saved G αₕ) Σ₀-full ℓ Wₓ*)
(match-define (cons l+ l-) ctx:saved)
(define Wₓ (unpack-W Wₓ* Σ₀-full))
(define Σ₀ (gc (∪ (set-add (V-root G) αₕ) (W-root Wₓ) (B-root (current-parameters))) Σ₀-full))
(match-define (==>i (-var Doms ?Doms:rest) Rngs) G)
(: mon-doms : Σ -l -l (Listof Dom) W → (Values R (℘ Err)))
(define (mon-doms Σ₀ l+ l- Doms₀ Wₓ₀)
(let go ([Σ : Σ Σ₀] [Doms : (Listof Dom) Doms₀] [Wₓ : W Wₓ₀])
(match* (Doms Wₓ)
[('() '()) (values (R-of '()) ∅)]
[((cons Dom Doms) (cons Vₓ Wₓ))
(with-each-ans ([(ΔΣₓ Wₓ*) (mon-dom Σ l+ l- Dom Vₓ)]
[(ΔΣ* W*) (go (⧺ Σ ΔΣₓ) Doms Wₓ)])
(just (cons (car Wₓ*) W*) (⧺ ΔΣₓ ΔΣ*)))]
[(_ _)
FIXME
(: mon-dom : Σ -l -l Dom V^ → (Values R (℘ Err)))
(define (mon-dom Σ l+ l- dom V)
(match-define (Dom x c ℓₓ) dom)
(define ctx (Ctx l+ l- ℓₓ ℓ))
(match c
;; Dependent domain
[(Clo (-var xs #f) E H ℓ)
(define ΔΣ₀ (stack-copy (Clo-escapes xs E H ℓ) Σ))
(define Σ₀ (⧺ Σ ΔΣ₀))
(with-each-ans ([(ΔΣ₁ W) (evl Σ₀ E)]
[(ΔΣ₂ W) (mon (⧺ Σ₀ ΔΣ₁) ctx (car W) V)])
FIXME catch
(just W (⧺ ΔΣ₀ ΔΣ₁ ΔΣ₂ (alloc (γ:lex x) V*))))]
;; Non-dependent domain
[(? α? α)
(with-each-ans ([(ΔΣ W) (mon Σ ctx (Σ@ α Σ₀) V)])
(match-define (list V*) W)
(just W (⧺ ΔΣ (alloc (γ:lex x) V*))))]))
(define Dom-ref (match-lambda [(Dom x _ _) {set (γ:lex x)}]))
(define (with-result [ΔΣ-acc : ΔΣ] [comp : (→ (Values R (℘ Err)))])
(define-values (r es)
(if Rngs
(with-each-ans ([(ΔΣₐ Wₐ) (comp)])
(with-pre (⧺ ΔΣ-acc ΔΣₐ) (mon-doms (⧺ Σ₀ ΔΣ-acc ΔΣₐ) l+ l- Rngs Wₐ)))
(with-pre ΔΣ-acc (comp))))
(define rn (for/hash : (Immutable-HashTable α (Option α))
([d (in-list Doms)]
[Vₓ (in-list Wₓ*)])
(values (γ:lex (Dom-name d))
(match Vₓ
[{singleton-set (? α? α)}
;; renaming is only valid for values monitored by
;; flat contract
#:when (and (α? (Dom-ctc d))
(C^-flat? (unpack (Dom-ctc d) Σ₀) Σ₀))
α]
[_ #f]))))
(values (fix-return rn Σ₀ r) es))
(with-guarded-arity Wₓ G ℓ
[Wₓ
#:when (and (not ?Doms:rest) (= (length Wₓ) (length Doms)))
(with-each-ans ([(ΔΣₓ _) (mon-doms Σ₀ l- l+ Doms Wₓ)])
(define args (map Dom-ref Doms))
(with-result ΔΣₓ (λ () (app (⧺ Σ₀ ΔΣₓ) (ℓ-with-src ℓ l+) (Σ@ αₕ Σ₀) args))))]
[Wₓ
#:when (and ?Doms:rest (>= (length Wₓ) (length Doms)))
(define-values (W₀ Wᵣ) (split-at Wₓ (length Doms)))
(define-values (Vᵣ ΔΣᵣ) (alloc-rest (Dom-loc ?Doms:rest) Wᵣ))
(with-each-ans ([(ΔΣ-init _) (mon-doms Σ₀ l- l+ Doms W₀)]
[(ΔΣ-rest _) (mon-dom (⧺ Σ₀ ΔΣ-init ΔΣᵣ) l- l+ ?Doms:rest Vᵣ)])
(define args-init (map Dom-ref Doms))
(define arg-rest (Dom-ref ?Doms:rest))
(with-result (⧺ ΔΣ-init ΔΣᵣ ΔΣ-rest)
(λ () (app/rest (⧺ Σ₀ ΔΣ-init ΔΣᵣ ΔΣ-rest) (ℓ-with-src ℓ l+) (Σ@ αₕ Σ₀) args-init arg-rest))))]))
(: app-∀/C : (Pairof -l -l) ∀/C α → ⟦F⟧)
(define ((app-∀/C ctx G α) Σ₀ ℓ Wₓ)
(with-each-ans ([(ΔΣ Wₕ) (inst-∀/C Σ₀ ctx G α ℓ)])
(with-pre ΔΣ (app (⧺ Σ₀ ΔΣ) ℓ (car Wₕ) Wₓ))))
(: app-Case-=> : (Pairof -l -l) Case-=> α → ⟦F⟧)
(define ((app-Case-=> ctx G α) Σ ℓ Wₓ)
(define n (length Wₓ))
(match-define (Case-=> Cs) G)
(match ((inst findf ==>i)
(match-lambda [(==>i doms _) (arity-includes? (shape doms) n)])
Cs)
[(? values C) ((app-==>i ctx C α) Σ ℓ Wₓ)]
[#f (err (Err:Arity G n ℓ))]))
(: app-Param/C : (Pairof -l -l) Param/C α → ⟦F⟧)
(define ((app-Param/C ctx:saved G α) Σ ℓ Wₓ)
(match-define (cons l+ l-) ctx:saved)
(match-define (Param/C αₕ ℓₕ) G)
(define ctx (Ctx l+ l- ℓₕ ℓ))
(define C (Σ@ αₕ Σ))
(match Wₓ
[(list)
(with-collapsing/R [(ΔΣ (app collapse-W^ (list V))) (app Σ (ℓ-with-src ℓ l+) (Σ@ α Σ) '())]
(with-pre ΔΣ
(mon (⧺ Σ ΔΣ) ctx C V)))]
[(list V)
(with-collapsing/R [(ΔΣ Ws) (mon Σ (Ctx l- l+ ℓₕ ℓ) C V)]
(with-pre ΔΣ
(app (⧺ Σ ΔΣ) (ℓ-with-src ℓ l+) (Σ@ α Σ) (collapse-W^ Ws))))]
[_ (err (Err:Arity G (length Wₓ) ℓ))]))
(: app-Terminating/C : Ctx α → ⟦F⟧)
(define ((app-Terminating/C ctx α) Σ ℓ Wₓ)
???)
(: app-And/C : α α ℓ → ⟦F⟧)
(define ((app-And/C α₁ α₂ ℓₕ) Σ ℓ Wₓ)
(with-guarded-arity Wₓ ℓₕ ℓ
[(list _)
(with-each-ans ([(ΔΣ₁ W₁) (app/C Σ ℓ (unpack α₁ Σ) Wₓ)])
(define Σ₁ (⧺ Σ ΔΣ₁))
(with-split-Σ Σ₁ 'values W₁
(λ (_ ΔΣ*) (with-pre (⧺ ΔΣ₁ ΔΣ*) (app/C (⧺ Σ₁ ΔΣ*) ℓ (unpack α₂ Σ) Wₓ)))
(λ (_ ΔΣ*) (values (R-of -ff (⧺ ΔΣ₁ ΔΣ*)) ∅))))]))
(: app-Or/C : α α ℓ → ⟦F⟧)
(define ((app-Or/C α₁ α₂ ℓₕ) Σ ℓ Wₓ)
(with-guarded-arity Wₓ ℓₕ ℓ
[(list _)
(with-each-ans ([(ΔΣ₁ W₁) (app/C Σ ℓ (unpack α₁ Σ) Wₓ)])
(define Σ₁ (⧺ Σ ΔΣ₁))
(with-split-Σ Σ₁ 'values W₁
(λ (_ ΔΣ*) (values (R-of W₁ (⧺ ΔΣ₁ ΔΣ*)) ∅))
(λ (_ ΔΣ*) (with-pre (⧺ ΔΣ₁ ΔΣ*) (app/C (⧺ Σ₁ ΔΣ*) ℓ (unpack α₂ Σ) Wₓ)))))]))
(: app-Not/C : α ℓ → ⟦F⟧)
(define ((app-Not/C α ℓₕ) Σ ℓ Wₓ)
(with-guarded-arity Wₓ ℓₕ ℓ
[(list _)
(with-each-ans ([(ΔΣ W) (app/C Σ ℓ (unpack α Σ) Wₓ)])
(define Σ* (⧺ Σ ΔΣ))
(with-split-Σ Σ* 'values W
(λ (_ ΔΣ*) (just -ff (⧺ ΔΣ ΔΣ*)))
(λ (_ ΔΣ*) (just -tt (⧺ ΔΣ ΔΣ*)))))]))
(: app-Rec/C : α → ⟦F⟧)
(define ((app-Rec/C α) Σ ℓ Wₓ) (app/C Σ ℓ (unpack α Σ) (unpack-W Wₓ Σ)))
(: app-One-Of/C : (℘ Base) → ⟦F⟧)
(define ((app-One-Of/C bs) Σ ℓ Wₓ)
(with-guarded-arity Wₓ (One-Of/C bs) ℓ
[(list V)
(with-split-Σ Σ (One-Of/C bs) Wₓ
(λ (_ ΔΣ) (just -tt ΔΣ))
(λ (_ ΔΣ) (just -ff ΔΣ)))]))
(: app-St/C : St/C → ⟦F⟧)
(define ((app-St/C C) Σ ℓ Wₓ)
(define-values (α ℓₕ 𝒾) (St/C-fields C))
(define S (Σ@/blob α Σ))
(with-guarded-arity Wₓ ℓₕ ℓ
[(list Vₓ)
(with-split-Σ Σ (-st-p 𝒾) Wₓ
(λ (Wₓ* ΔΣ*) (with-pre ΔΣ* ((app-St/C-fields 𝒾 0 S ℓₕ) (⧺ Σ ΔΣ*) ℓ (car Wₓ*))))
(λ (_ ΔΣ*) (just -ff ΔΣ*)))]))
(: app-St/C-fields : -𝒾 Index (Vectorof V^) ℓ → Σ ℓ V^ → (Values R (℘ Err)))
(define ((app-St/C-fields 𝒾 i Cs ℓₕ) Σ₀ ℓ Vₓ)
(let loop ([i : Index 0] [Σ : Σ Σ₀])
(if (>= i (vector-length Cs))
(just -tt)
(with-collapsing/R [(ΔΣᵢ Wᵢs) ((unchecked-app-st-ac 𝒾 i) Σ ℓ Vₓ)]
(with-each-ans ([(ΔΣₜ Wₜ) (app/C (⧺ Σ ΔΣᵢ) ℓ (vector-ref Cs i) (collapse-W^ Wᵢs))])
(define ΔΣ (⧺ ΔΣᵢ ΔΣₜ))
(define Σ* (⧺ Σ ΔΣ))
(with-split-Σ Σ* 'values Wₜ
(λ _ (with-pre ΔΣ (loop (assert (+ 1 i) index?) Σ*)))
(λ _ (just -ff ΔΣ))))))))
(: app-opq : (℘ P) → ⟦F⟧)
(define ((app-opq Ps) Σ ℓ Wₓ*)
(define Wₕ (list {set (-● Ps)}))
(define ℓₒ (ℓ-with-src +ℓ₀ 'Λ))
(with-split-Σ Σ 'procedure? Wₕ
(λ _
(define P-arity (P:arity-includes (length Wₓ*)))
(with-split-Σ Σ P-arity Wₕ
(λ _ (leak Σ (γ:hv #f) ((inst foldl V^ V^) ∪ ∅ (unpack-W Wₓ* Σ))))
(λ _ (err (blm (ℓ-src ℓ) ℓ ℓₒ (list {set P-arity}) Wₕ)))))
(λ _ (err (blm (ℓ-src ℓ) ℓ ℓₒ (list {set 'procedure?}) Wₕ)))))
(: app-P : Symbol (U T -b) → ⟦F⟧)
(define ((app-P o T) Σ ℓ Wₓ) ((app-prim o) Σ ℓ (cons {set T} Wₓ)))
(: app-err : V → ⟦F⟧)
(define ((app-err V) Σ ℓ Wₓ)
(err (blm (ℓ-src ℓ) ℓ (ℓ-with-src +ℓ₀ 'Λ) (list {set 'procedure?}) (list {set V}))))
(: app/rest : Σ ℓ V^ W V^ → (Values R (℘ Err)))
(define (app/rest Σ ℓ Vₕ^ Wₓ Vᵣ)
(define args:root (∪ (W-root Wₓ) (V^-root Vᵣ)))
(define-values (Wᵣs snd?) (unalloc Vᵣ Σ))
(define-values (r es) (fold-ans (λ ([Wᵣ : W]) (app Σ ℓ Vₕ^ (append Wₓ Wᵣ))) Wᵣs))
(values r (if snd? es (set-add es (Err:Varargs Wₓ Vᵣ ℓ)))))
(: trim-renamings : Renamings → Renamings)
;; Prevent some renaming from propagating based on what the caller has
(define (trim-renamings rn)
(for/fold ([rn : Renamings rn])
([(x ?T) (in-hash rn)]
FIXME this erasure is too aggressive
#:when (T:@? ?T))
(hash-set rn x #f)))
(: insert-fv-erasures : ΔΣ Renamings → Renamings)
;; Add erasure of free variables that were stack-copied
(define (insert-fv-erasures ΔΣ rn)
(for/fold ([rn : Renamings rn]) ([α (in-hash-keys ΔΣ)]
#:unless (hash-has-key? rn α))
(hash-set rn α #f)))
(: unalloc : V^ Σ → (Values (℘ W) Boolean))
;; Convert list in object language into one in meta-language
(define (unalloc Vs Σ)
(define-set touched : α #:mutable? #t)
(define elems : (Mutable-HashTable Integer V^) (make-hasheq))
(define-set ends : Integer #:eq? #t #:mutable? #t)
(define sound? : Boolean #t)
(let touch! ([i : Integer 0] [Vs : V^ Vs])
(for ([V (in-set Vs)])
(match V
[(St (and α (α:dyn (β:st-elems _ (== -𝒾-cons)) _)) _)
(match-define (vector Vₕ Vₜ) (Σ@/blob α Σ))
(hash-update! elems i (λ ([V₀ : V^]) (V⊔ V₀ Vₕ)) mk-∅)
(cond [(touched-has? α)
(set! sound? #f)
(ends-add! (+ 1 i))]
[else (touched-add! α)
(touch! (+ 1 i) Vₜ)])]
[(-b '()) (ends-add! i)]
[_ (set! sound? #f)
(ends-add! i)])))
(define Ws (for/set: : W^ ([n (in-ends)])
(for/list : W ([i (in-range n)]) (hash-ref elems i))))
(values Ws sound?))
(: inst-∀/C : Σ (Pairof -l -l) ∀/C α ℓ → (Values R (℘ Err)))
;; Monitor function against freshly instantiated parametric contract
(define (inst-∀/C Σ₀ ctx G α ℓ)
(match-define (∀/C xs c H ℓₒ) G)
(match-define (cons l+ (and l- l-seal)) ctx)
(define ΔΣ₀
(let ([ΔΣ:seals
(for/fold ([acc : ΔΣ ⊥ΔΣ]) ([x (in-list xs)])
(define αₓ (α:dyn (β:sealed x ℓ) H₀))
(⧺ acc
(alloc αₓ ∅)
(alloc (γ:lex x) {set (Seal/C αₓ l-seal)})))]
[ΔΣ:stk (stack-copy (Clo-escapes xs c H ℓₒ) Σ₀)])
(⧺ ΔΣ:seals ΔΣ:stk)))
(define Σ₁ (⧺ Σ₀ ΔΣ₀))
(with-each-ans ([(ΔΣ₁ W:c) (evl Σ₁ c)])
(with-pre (⧺ ΔΣ₀ ΔΣ₁)
(mon (⧺ Σ₁ ΔΣ₁) (Ctx l+ l- ℓₒ ℓ) (car W:c) (Σ@ α Σ₀)))))
(define-simple-macro (with-guarded-arity W f ℓ [p body ...] ...)
(match W
[p body ...] ...
[_ (err (Err:Arity f (length W) ℓ))]))
)
| null | https://raw.githubusercontent.com/philnguyen/soft-contract/5e07dc2d622ee80b961f4e8aebd04ce950720239/soft-contract/execution/app.rkt | racket | A call history tracks the call chain that leads to the current expression, modulo loops
Global table remembering the widest store for each chain
FIXME: memory leak. Reset for each program.
TODO: clean this up so only need to gc once?
TODO: code dup
TODO: clean this up so only need to gc once?
no `ΔΣₓ` in result
Track access to user-defined structs
Dependent domain
Non-dependent domain
renaming is only valid for values monitored by
flat contract
Prevent some renaming from propagating based on what the caller has
Add erasure of free variables that were stack-copied
Convert list in object language into one in meta-language
Monitor function against freshly instantiated parametric contract | #lang typed/racket/base
(provide app@)
(require racket/set
racket/list
racket/match
racket/vector
typed/racket/unit
syntax/parse/define
set-extras
bnf
unreachable
"../utils/patterns.rkt"
"../utils/map.rkt"
"../ast/signatures.rkt"
"../runtime/signatures.rkt"
"../signatures.rkt"
"signatures.rkt"
)
(⟦F⟧ . ≜ . (Σ ℓ W → (Values R (℘ Err))))
(⟦G⟧ . ≜ . (Σ ℓ W V^ → (Values R (℘ Err))))
(define-unit app@
(import meta-functions^ static-info^ ast-pretty-print^
params^ sto^ cache^ val^ pretty-print^
prims^ prover^
exec^ evl^ mon^ hv^ gc^)
(export app^)
(Stk . ≜ . (Listof E))
(define current-chain ((inst make-parameter Stk) '()))
(define global-stores : (HashTable (Pairof Stk Σ) Σ) (make-hash))
(: app : Σ ℓ V^ W → (Values R (℘ Err)))
(define (app Σ ℓ Vₕ^ W*)
(define-values (W ΔΣ) (escape-clos Σ W*))
(define root₀ (∪ (W-root W) (B-root (current-parameters))))
((inst fold-ans V)
(λ (Vₕ)
(define root (∪ root₀ (V-root Vₕ)))
(define Σ* (gc root (⧺ Σ ΔΣ)))
(log-scv-preval-debug "~n~a~a ⊢ₐ:~a ~a ~a~n"
(make-string (* 4 (db:depth)) #\space)
(show-Σ Σ*)
(show-full-ℓ ℓ)
(show-V Vₕ)
(show-W W))
(define-values (r es) (parameterize ([db:depth (+ (db:depth))]) (ref-$! ($:Key:App Σ* (current-parameters) ℓ Vₕ W)
(λ () (with-gc root Σ* (λ () (with-pre ΔΣ (app₁ Σ* ℓ Vₕ W))))))))
(log-scv-eval-debug "~n~a~a ⊢ₐ:~a ~a ~a ⇓ ~a~n"
(make-string (* 4 (db:depth)) #\space)
(show-Σ Σ*)
(show-full-ℓ ℓ)
(show-V Vₕ)
(show-W W)
(show-R r))
(values r es))
(unpack Vₕ^ Σ)))
(: app/C : Σ ℓ V^ W → (Values R (℘ Err)))
(define (app/C Σ ℓ Cs W)
(define-values (bs Cs*) (set-partition -b? Cs))
(define-values (r₁ es₁) (cond [(set-empty? Cs*) (values ⊥R ∅)]
[else (app Σ ℓ Cs* W)]))
(define-values (r₂ es₂) (cond [(set-empty? bs) (values ⊥R ∅)]
[else (app₁ Σ ℓ 'equal? (cons bs W))]))
(values (R⊔ r₁ r₂) (∪ es₁ es₂)))
(: app₁ : Σ ℓ V W → (Values R (℘ Err)))
(define (app₁ Σ ℓ V W)
(define f (match V
[(? -λ? V) (app-λ V)]
[(? Clo? V) (app-Clo V)]
[(? Case-Clo? V) (app-Case-Clo V)]
[(-st-mk 𝒾) (app-st-mk 𝒾)]
[(-st-p 𝒾) (app-st-p 𝒾)]
[(-st-ac 𝒾 i) (app-st-ac 𝒾 i)]
[(-st-mut 𝒾 i) (app-st-mut 𝒾 i)]
[(? symbol? o) (app-prim o)]
[(Param α) (app-param α)]
[(Guarded ctx (? Fn/C? G) α)
(cond [(==>i? G) (app-==>i ctx G α)]
[(∀/C? G) (app-∀/C ctx G α)]
[(Case-=>? G) (app-Case-=> ctx G α)]
[(Param/C? G) (app-Param/C ctx G α)]
[else (app-Terminating/C ctx α)])]
[(And/C α₁ α₂ ℓ) #:when (C-flat? V Σ) (app-And/C α₁ α₂ ℓ)]
[(Or/C α₁ α₂ ℓ) #:when (C-flat? V Σ) (app-Or/C α₁ α₂ ℓ)]
[(Not/C α ℓ) (app-Not/C α ℓ)]
[(Rec/C α) (app-Rec/C α)]
[(One-Of/C bs) (app-One-Of/C bs)]
[(? St/C?) #:when (C-flat? V Σ) (app-St/C V)]
[(-● Ps) (app-opq Ps)]
[(P:≡ T) (app-P 'equal? T)]
[(P:= T) (app-P '= T)]
[(P:> T) (app-P '< T)]
[(P:≥ T) (app-P '<= T)]
[(P:< T) (app-P '> T)]
[(P:≤ T) (app-P '>= T)]
[V (app-err V)]))
(f Σ ℓ W))
(: app-λ : -λ → ⟦F⟧)
(define ((app-λ Vₕ) Σ ℓ Wₓ*)
(match-define (-λ fml E ℓₕ) Vₕ)
(cond [(arity-includes? (shape fml) (length Wₓ*))
(match-define (-var xs xᵣ) fml)
(define Wₓ (unpack-W Wₓ* Σ))
(define ΔΣₓ
(let-values ([(W₀ Wᵣ) (if xᵣ (split-at Wₓ (length xs)) (values Wₓ '()))])
(⧺ (alloc-lex* xs W₀)
(if xᵣ (alloc-vararg xᵣ Wᵣ) ⊥ΔΣ))))
gc one more time against unpacked arguments
(let ([root (∪ (E-root Vₕ) (W-root Wₓ) (B-root (current-parameters)))])
(define Σ₁ (gc root Σ))
(define-values (rₐ es) (evl/history (⧺ Σ₁ ΔΣₓ) E))
(define rn (trim-renamings (make-renamings fml Wₓ* assignable?)))
(values (fix-return rn Σ₁ (R-escape-clos Σ₁ (ΔΣ⧺R ΔΣₓ rₐ))) es))]
[else (err (Err:Arity ℓₕ (length Wₓ*) ℓ))]))
(: app-Clo : Clo → ⟦F⟧)
(define ((app-Clo Vₕ) Σ ℓ Wₓ*)
(match-define (Clo fml E H ℓₕ) Vₕ)
(cond [(arity-includes? (shape fml) (length Wₓ*))
(match-define (-var xs xᵣ) fml)
(define Wₓ (unpack-W Wₓ* Σ))
(define ΔΣₓ
(let-values ([(W₀ Wᵣ) (if xᵣ (split-at Wₓ (length xs)) (values Wₓ '()))])
(⧺ (stack-copy (Clo-escapes fml E H ℓₕ) Σ)
(alloc-lex* xs W₀)
(if xᵣ (alloc-vararg xᵣ Wᵣ) ⊥ΔΣ))))
gc one more time against unpacked arguments
(let ([root (∪ (V-root Vₕ) (W-root Wₓ) (B-root (current-parameters)))])
(define Σ₁ (gc root Σ))
(define rn (trim-renamings (insert-fv-erasures ΔΣₓ (make-renamings fml Wₓ* assignable?))))
(values (fix-return rn Σ₁ (R-escape-clos Σ₁ (ΔΣ⧺R ΔΣₓ rₐ))) es))]
[else (err (Err:Arity ℓₕ (length Wₓ*) ℓ))]))
(: evl/history : Σ E → (Values R (℘ Err)))
(define (evl/history Σ₁ E)
(define stk (current-chain))
(define stk* (cond [(memq E stk) => values]
[else (cons E stk)]))
(define k (cons stk* (Σ-stk Σ₁)))
(define Σ* (match (hash-ref global-stores k #f)
[(? values Σ₀) (ΔΣ⊔ Σ₀ Σ₁)]
[_ Σ₁]))
(hash-set! global-stores k Σ*)
(parameterize ([current-chain stk*])
(evl Σ* E)))
(: Σ-stk : Σ → Σ)
(define (Σ-stk Σ₀)
(for/fold ([Σ* : Σ Σ₀]) ([α (in-hash-keys Σ₀)] #:unless (γ:lex? α))
(hash-remove Σ* α)))
(: app-Case-Clo : Case-Clo → ⟦F⟧)
(define ((app-Case-Clo Vₕ) Σ ℓ Wₓ)
(match-define (Case-Clo cases ℓₕ) Vₕ)
(define n (length Wₓ))
(match ((inst findf Clo) (λ (clo) (arity-includes? (shape (Clo-_0 clo)) n)) cases)
[(? values clo) ((app-Clo clo) Σ ℓ Wₓ)]
[#f (err (Err:Arity ℓₕ n ℓ))]))
(: app-st-mk : -𝒾 → ⟦F⟧)
(define ((app-st-mk 𝒾) Σ ℓ Wₓ)
(define n (count-struct-fields 𝒾))
(if (= n (length Wₓ))
(let ([α (α:dyn (β:st-elems ℓ 𝒾) H₀)])
(just (St α ∅) (alloc α (list->vector (unpack-W Wₓ Σ)))))
(err (Err:Arity (-st-mk 𝒾) (length Wₓ) ℓ))))
(: app-st-p : -𝒾 → ⟦F⟧)
(define ((app-st-p 𝒾) Σ ℓ Wₓ)
(with-guarded-arity Wₓ (-st-p 𝒾) ℓ
[(list _) (implement-predicate Σ (-st-p 𝒾) Wₓ)]))
(: app-st-ac : -𝒾 Index → ⟦F⟧)
(define ((app-st-ac 𝒾 i) Σ ℓ Wₓ)
(with-guarded-arity Wₓ (-st-ac 𝒾 i) ℓ
[(list Vₓ)
(with-split-Σ Σ (-st-p 𝒾) Wₓ
(λ (Wₓ* ΔΣ₁) (with-pre ΔΣ₁ ((unchecked-app-st-ac 𝒾 i) (⧺ Σ ΔΣ₁) ℓ (car Wₓ*))))
(λ (Wₓ* ΔΣ₂)
(define ℓₒ (ℓ-with-src +ℓ₀ (show-o (-st-ac 𝒾 i))))
(err (blm (ℓ-src ℓ) ℓ ℓₒ (list {set (-st-p 𝒾)}) Wₓ*))))]))
(: unchecked-app-st-ac : -𝒾 Index → Σ ℓ V^ → (Values R (℘ Err)))
(define ((unchecked-app-st-ac 𝒾 i) Σ ℓ Vₓ)
(define ac₁ : (V → (Values R (℘ Err)))
(match-lambda
[(St α Ps)
(define Vᵢ (vector-ref (Σ@/blob α Σ) i))
(define-values (V* ΔΣ)
(refine (unpack Vᵢ Σ) (ac-Ps (-st-ac 𝒾 i) Ps) Σ))
(just V* ΔΣ)]
[(and T (or (? T:@?) (? γ?))) #:when (not (struct-mutable? 𝒾 i))
(define T* (T:@ (-st-ac 𝒾 i) (list T)))
(if (set-empty? (unpack T* Σ)) (values ⊥R ∅) (just T*))]
[(Guarded (cons l+ l-) (? St/C? C) αᵥ)
(define-values (αₕ ℓₕ _) (St/C-fields C))
(define Cᵢ (vector-ref (Σ@/blob αₕ Σ) i))
(with-collapsing/R [(ΔΣ Ws) ((unchecked-app-st-ac 𝒾 i) Σ ℓ (unpack αᵥ Σ))]
(with-pre ΔΣ (mon (⧺ Σ ΔΣ) (Ctx l+ l- ℓₕ ℓ) Cᵢ (car (collapse-W^ Ws)))))]
[(and V₀ (-● Ps))
(case (sat Σ (-st-p 𝒾) {set V₀})
[(✗) (values ⊥R ∅)]
[else (just (st-ac-● 𝒾 i Ps Σ))])]
[(? α? α) (fold-ans ac₁ (unpack α Σ))]
[_ (values ⊥R ∅)]))
(fold-ans/collapsing ac₁ Vₓ))
(: st-ac-● : -𝒾 Index (℘ P) Σ → V^)
(define (st-ac-● 𝒾 i Ps Σ)
(define V
(if (prim-struct? 𝒾)
{set (-● ∅)}
(Σ@ (γ:escaped-field 𝒾 i) Σ)))
(cond [(set-empty? V) ∅]
[else (define-values (V* _) (refine V (ac-Ps (-st-ac 𝒾 i) Ps) Σ))
V*]))
(: app-st-mut : -𝒾 Index → ⟦F⟧)
(define ((app-st-mut 𝒾 i) Σ ℓ Wₓ)
(with-guarded-arity Wₓ (-st-mut 𝒾 i) ℓ
[(list Vₓ V*)
(with-split-Σ Σ (-st-p 𝒾) (list Vₓ)
(λ (Wₓ* ΔΣ₁) (with-pre ΔΣ₁ ((unchecked-app-st-mut 𝒾 i) (⧺ Σ ΔΣ₁) ℓ (car Wₓ*) V*)))
(λ (Wₓ* ΔΣ₂) (err (blm (ℓ-src ℓ) ℓ (ℓ-with-src +ℓ₀ (show-o (-st-mut 𝒾 i))) (list {set (-st-p 𝒾)}) Wₓ*))))]))
(: unchecked-app-st-mut : -𝒾 Index → Σ ℓ V^ V^ → (Values R (℘ Err)))
(define ((unchecked-app-st-mut 𝒾 i) Σ ℓ Vₓ V*)
((inst fold-ans V)
(match-lambda
[(St α _)
(define S (Σ@/blob α Σ))
(define S* (vector-copy S))
(vector-set! S* i V*)
(just -void (mut α S* Σ))]
[(Guarded (cons l+ l-) (? St/C? C) αᵥ)
(define-values (αₕ ℓₕ _) (St/C-fields C))
(define Cᵢ (vector-ref (Σ@/blob αₕ Σ) i))
(with-collapsing/R [(ΔΣ Ws) (mon Σ (Ctx l- l+ ℓₕ ℓ) Cᵢ V*)]
(with-pre ΔΣ ((unchecked-app-st-mut 𝒾 i) (⧺ Σ ΔΣ) ℓ (unpack αᵥ Σ) V*)))]
[(? -●?) (just -void (alloc (γ:hv #f) V*))]
[_ (values ⊥R ∅)])
(unpack Vₓ Σ)))
(: app-prim : Symbol → ⟦F⟧)
(define ((app-prim o) Σ ℓ Wₓ)
TODO massage raw result
((get-prim o) Σ ℓ Wₓ))
(: app-param : α → ⟦F⟧)
(define ((app-param α) Σ ℓ Wₓ)
(match Wₓ
[(list) (just (current-parameter α))]
[(list V) (set-parameter α V)
(just -void)]
[_ (err (Err:Arity (Param α) (length Wₓ) ℓ))]))
(: app-==>i : (Pairof -l -l) ==>i α → ⟦F⟧)
(define ((app-==>i ctx:saved G αₕ) Σ₀-full ℓ Wₓ*)
(match-define (cons l+ l-) ctx:saved)
(define Wₓ (unpack-W Wₓ* Σ₀-full))
(define Σ₀ (gc (∪ (set-add (V-root G) αₕ) (W-root Wₓ) (B-root (current-parameters))) Σ₀-full))
(match-define (==>i (-var Doms ?Doms:rest) Rngs) G)
(: mon-doms : Σ -l -l (Listof Dom) W → (Values R (℘ Err)))
(define (mon-doms Σ₀ l+ l- Doms₀ Wₓ₀)
(let go ([Σ : Σ Σ₀] [Doms : (Listof Dom) Doms₀] [Wₓ : W Wₓ₀])
(match* (Doms Wₓ)
[('() '()) (values (R-of '()) ∅)]
[((cons Dom Doms) (cons Vₓ Wₓ))
(with-each-ans ([(ΔΣₓ Wₓ*) (mon-dom Σ l+ l- Dom Vₓ)]
[(ΔΣ* W*) (go (⧺ Σ ΔΣₓ) Doms Wₓ)])
(just (cons (car Wₓ*) W*) (⧺ ΔΣₓ ΔΣ*)))]
[(_ _)
FIXME
(: mon-dom : Σ -l -l Dom V^ → (Values R (℘ Err)))
(define (mon-dom Σ l+ l- dom V)
(match-define (Dom x c ℓₓ) dom)
(define ctx (Ctx l+ l- ℓₓ ℓ))
(match c
[(Clo (-var xs #f) E H ℓ)
(define ΔΣ₀ (stack-copy (Clo-escapes xs E H ℓ) Σ))
(define Σ₀ (⧺ Σ ΔΣ₀))
(with-each-ans ([(ΔΣ₁ W) (evl Σ₀ E)]
[(ΔΣ₂ W) (mon (⧺ Σ₀ ΔΣ₁) ctx (car W) V)])
FIXME catch
(just W (⧺ ΔΣ₀ ΔΣ₁ ΔΣ₂ (alloc (γ:lex x) V*))))]
[(? α? α)
(with-each-ans ([(ΔΣ W) (mon Σ ctx (Σ@ α Σ₀) V)])
(match-define (list V*) W)
(just W (⧺ ΔΣ (alloc (γ:lex x) V*))))]))
(define Dom-ref (match-lambda [(Dom x _ _) {set (γ:lex x)}]))
(define (with-result [ΔΣ-acc : ΔΣ] [comp : (→ (Values R (℘ Err)))])
(define-values (r es)
(if Rngs
(with-each-ans ([(ΔΣₐ Wₐ) (comp)])
(with-pre (⧺ ΔΣ-acc ΔΣₐ) (mon-doms (⧺ Σ₀ ΔΣ-acc ΔΣₐ) l+ l- Rngs Wₐ)))
(with-pre ΔΣ-acc (comp))))
(define rn (for/hash : (Immutable-HashTable α (Option α))
([d (in-list Doms)]
[Vₓ (in-list Wₓ*)])
(values (γ:lex (Dom-name d))
(match Vₓ
[{singleton-set (? α? α)}
#:when (and (α? (Dom-ctc d))
(C^-flat? (unpack (Dom-ctc d) Σ₀) Σ₀))
α]
[_ #f]))))
(values (fix-return rn Σ₀ r) es))
(with-guarded-arity Wₓ G ℓ
[Wₓ
#:when (and (not ?Doms:rest) (= (length Wₓ) (length Doms)))
(with-each-ans ([(ΔΣₓ _) (mon-doms Σ₀ l- l+ Doms Wₓ)])
(define args (map Dom-ref Doms))
(with-result ΔΣₓ (λ () (app (⧺ Σ₀ ΔΣₓ) (ℓ-with-src ℓ l+) (Σ@ αₕ Σ₀) args))))]
[Wₓ
#:when (and ?Doms:rest (>= (length Wₓ) (length Doms)))
(define-values (W₀ Wᵣ) (split-at Wₓ (length Doms)))
(define-values (Vᵣ ΔΣᵣ) (alloc-rest (Dom-loc ?Doms:rest) Wᵣ))
(with-each-ans ([(ΔΣ-init _) (mon-doms Σ₀ l- l+ Doms W₀)]
[(ΔΣ-rest _) (mon-dom (⧺ Σ₀ ΔΣ-init ΔΣᵣ) l- l+ ?Doms:rest Vᵣ)])
(define args-init (map Dom-ref Doms))
(define arg-rest (Dom-ref ?Doms:rest))
(with-result (⧺ ΔΣ-init ΔΣᵣ ΔΣ-rest)
(λ () (app/rest (⧺ Σ₀ ΔΣ-init ΔΣᵣ ΔΣ-rest) (ℓ-with-src ℓ l+) (Σ@ αₕ Σ₀) args-init arg-rest))))]))
(: app-∀/C : (Pairof -l -l) ∀/C α → ⟦F⟧)
(define ((app-∀/C ctx G α) Σ₀ ℓ Wₓ)
(with-each-ans ([(ΔΣ Wₕ) (inst-∀/C Σ₀ ctx G α ℓ)])
(with-pre ΔΣ (app (⧺ Σ₀ ΔΣ) ℓ (car Wₕ) Wₓ))))
(: app-Case-=> : (Pairof -l -l) Case-=> α → ⟦F⟧)
(define ((app-Case-=> ctx G α) Σ ℓ Wₓ)
(define n (length Wₓ))
(match-define (Case-=> Cs) G)
(match ((inst findf ==>i)
(match-lambda [(==>i doms _) (arity-includes? (shape doms) n)])
Cs)
[(? values C) ((app-==>i ctx C α) Σ ℓ Wₓ)]
[#f (err (Err:Arity G n ℓ))]))
(: app-Param/C : (Pairof -l -l) Param/C α → ⟦F⟧)
(define ((app-Param/C ctx:saved G α) Σ ℓ Wₓ)
(match-define (cons l+ l-) ctx:saved)
(match-define (Param/C αₕ ℓₕ) G)
(define ctx (Ctx l+ l- ℓₕ ℓ))
(define C (Σ@ αₕ Σ))
(match Wₓ
[(list)
(with-collapsing/R [(ΔΣ (app collapse-W^ (list V))) (app Σ (ℓ-with-src ℓ l+) (Σ@ α Σ) '())]
(with-pre ΔΣ
(mon (⧺ Σ ΔΣ) ctx C V)))]
[(list V)
(with-collapsing/R [(ΔΣ Ws) (mon Σ (Ctx l- l+ ℓₕ ℓ) C V)]
(with-pre ΔΣ
(app (⧺ Σ ΔΣ) (ℓ-with-src ℓ l+) (Σ@ α Σ) (collapse-W^ Ws))))]
[_ (err (Err:Arity G (length Wₓ) ℓ))]))
(: app-Terminating/C : Ctx α → ⟦F⟧)
(define ((app-Terminating/C ctx α) Σ ℓ Wₓ)
???)
(: app-And/C : α α ℓ → ⟦F⟧)
(define ((app-And/C α₁ α₂ ℓₕ) Σ ℓ Wₓ)
(with-guarded-arity Wₓ ℓₕ ℓ
[(list _)
(with-each-ans ([(ΔΣ₁ W₁) (app/C Σ ℓ (unpack α₁ Σ) Wₓ)])
(define Σ₁ (⧺ Σ ΔΣ₁))
(with-split-Σ Σ₁ 'values W₁
(λ (_ ΔΣ*) (with-pre (⧺ ΔΣ₁ ΔΣ*) (app/C (⧺ Σ₁ ΔΣ*) ℓ (unpack α₂ Σ) Wₓ)))
(λ (_ ΔΣ*) (values (R-of -ff (⧺ ΔΣ₁ ΔΣ*)) ∅))))]))
(: app-Or/C : α α ℓ → ⟦F⟧)
(define ((app-Or/C α₁ α₂ ℓₕ) Σ ℓ Wₓ)
(with-guarded-arity Wₓ ℓₕ ℓ
[(list _)
(with-each-ans ([(ΔΣ₁ W₁) (app/C Σ ℓ (unpack α₁ Σ) Wₓ)])
(define Σ₁ (⧺ Σ ΔΣ₁))
(with-split-Σ Σ₁ 'values W₁
(λ (_ ΔΣ*) (values (R-of W₁ (⧺ ΔΣ₁ ΔΣ*)) ∅))
(λ (_ ΔΣ*) (with-pre (⧺ ΔΣ₁ ΔΣ*) (app/C (⧺ Σ₁ ΔΣ*) ℓ (unpack α₂ Σ) Wₓ)))))]))
(: app-Not/C : α ℓ → ⟦F⟧)
(define ((app-Not/C α ℓₕ) Σ ℓ Wₓ)
(with-guarded-arity Wₓ ℓₕ ℓ
[(list _)
(with-each-ans ([(ΔΣ W) (app/C Σ ℓ (unpack α Σ) Wₓ)])
(define Σ* (⧺ Σ ΔΣ))
(with-split-Σ Σ* 'values W
(λ (_ ΔΣ*) (just -ff (⧺ ΔΣ ΔΣ*)))
(λ (_ ΔΣ*) (just -tt (⧺ ΔΣ ΔΣ*)))))]))
(: app-Rec/C : α → ⟦F⟧)
(define ((app-Rec/C α) Σ ℓ Wₓ) (app/C Σ ℓ (unpack α Σ) (unpack-W Wₓ Σ)))
(: app-One-Of/C : (℘ Base) → ⟦F⟧)
(define ((app-One-Of/C bs) Σ ℓ Wₓ)
(with-guarded-arity Wₓ (One-Of/C bs) ℓ
[(list V)
(with-split-Σ Σ (One-Of/C bs) Wₓ
(λ (_ ΔΣ) (just -tt ΔΣ))
(λ (_ ΔΣ) (just -ff ΔΣ)))]))
(: app-St/C : St/C → ⟦F⟧)
(define ((app-St/C C) Σ ℓ Wₓ)
(define-values (α ℓₕ 𝒾) (St/C-fields C))
(define S (Σ@/blob α Σ))
(with-guarded-arity Wₓ ℓₕ ℓ
[(list Vₓ)
(with-split-Σ Σ (-st-p 𝒾) Wₓ
(λ (Wₓ* ΔΣ*) (with-pre ΔΣ* ((app-St/C-fields 𝒾 0 S ℓₕ) (⧺ Σ ΔΣ*) ℓ (car Wₓ*))))
(λ (_ ΔΣ*) (just -ff ΔΣ*)))]))
(: app-St/C-fields : -𝒾 Index (Vectorof V^) ℓ → Σ ℓ V^ → (Values R (℘ Err)))
(define ((app-St/C-fields 𝒾 i Cs ℓₕ) Σ₀ ℓ Vₓ)
(let loop ([i : Index 0] [Σ : Σ Σ₀])
(if (>= i (vector-length Cs))
(just -tt)
(with-collapsing/R [(ΔΣᵢ Wᵢs) ((unchecked-app-st-ac 𝒾 i) Σ ℓ Vₓ)]
(with-each-ans ([(ΔΣₜ Wₜ) (app/C (⧺ Σ ΔΣᵢ) ℓ (vector-ref Cs i) (collapse-W^ Wᵢs))])
(define ΔΣ (⧺ ΔΣᵢ ΔΣₜ))
(define Σ* (⧺ Σ ΔΣ))
(with-split-Σ Σ* 'values Wₜ
(λ _ (with-pre ΔΣ (loop (assert (+ 1 i) index?) Σ*)))
(λ _ (just -ff ΔΣ))))))))
(: app-opq : (℘ P) → ⟦F⟧)
(define ((app-opq Ps) Σ ℓ Wₓ*)
(define Wₕ (list {set (-● Ps)}))
(define ℓₒ (ℓ-with-src +ℓ₀ 'Λ))
(with-split-Σ Σ 'procedure? Wₕ
(λ _
(define P-arity (P:arity-includes (length Wₓ*)))
(with-split-Σ Σ P-arity Wₕ
(λ _ (leak Σ (γ:hv #f) ((inst foldl V^ V^) ∪ ∅ (unpack-W Wₓ* Σ))))
(λ _ (err (blm (ℓ-src ℓ) ℓ ℓₒ (list {set P-arity}) Wₕ)))))
(λ _ (err (blm (ℓ-src ℓ) ℓ ℓₒ (list {set 'procedure?}) Wₕ)))))
(: app-P : Symbol (U T -b) → ⟦F⟧)
(define ((app-P o T) Σ ℓ Wₓ) ((app-prim o) Σ ℓ (cons {set T} Wₓ)))
(: app-err : V → ⟦F⟧)
(define ((app-err V) Σ ℓ Wₓ)
(err (blm (ℓ-src ℓ) ℓ (ℓ-with-src +ℓ₀ 'Λ) (list {set 'procedure?}) (list {set V}))))
(: app/rest : Σ ℓ V^ W V^ → (Values R (℘ Err)))
(define (app/rest Σ ℓ Vₕ^ Wₓ Vᵣ)
(define args:root (∪ (W-root Wₓ) (V^-root Vᵣ)))
(define-values (Wᵣs snd?) (unalloc Vᵣ Σ))
(define-values (r es) (fold-ans (λ ([Wᵣ : W]) (app Σ ℓ Vₕ^ (append Wₓ Wᵣ))) Wᵣs))
(values r (if snd? es (set-add es (Err:Varargs Wₓ Vᵣ ℓ)))))
(: trim-renamings : Renamings → Renamings)
(define (trim-renamings rn)
(for/fold ([rn : Renamings rn])
([(x ?T) (in-hash rn)]
FIXME this erasure is too aggressive
#:when (T:@? ?T))
(hash-set rn x #f)))
(: insert-fv-erasures : ΔΣ Renamings → Renamings)
(define (insert-fv-erasures ΔΣ rn)
(for/fold ([rn : Renamings rn]) ([α (in-hash-keys ΔΣ)]
#:unless (hash-has-key? rn α))
(hash-set rn α #f)))
(: unalloc : V^ Σ → (Values (℘ W) Boolean))
(define (unalloc Vs Σ)
(define-set touched : α #:mutable? #t)
(define elems : (Mutable-HashTable Integer V^) (make-hasheq))
(define-set ends : Integer #:eq? #t #:mutable? #t)
(define sound? : Boolean #t)
(let touch! ([i : Integer 0] [Vs : V^ Vs])
(for ([V (in-set Vs)])
(match V
[(St (and α (α:dyn (β:st-elems _ (== -𝒾-cons)) _)) _)
(match-define (vector Vₕ Vₜ) (Σ@/blob α Σ))
(hash-update! elems i (λ ([V₀ : V^]) (V⊔ V₀ Vₕ)) mk-∅)
(cond [(touched-has? α)
(set! sound? #f)
(ends-add! (+ 1 i))]
[else (touched-add! α)
(touch! (+ 1 i) Vₜ)])]
[(-b '()) (ends-add! i)]
[_ (set! sound? #f)
(ends-add! i)])))
(define Ws (for/set: : W^ ([n (in-ends)])
(for/list : W ([i (in-range n)]) (hash-ref elems i))))
(values Ws sound?))
(: inst-∀/C : Σ (Pairof -l -l) ∀/C α ℓ → (Values R (℘ Err)))
(define (inst-∀/C Σ₀ ctx G α ℓ)
(match-define (∀/C xs c H ℓₒ) G)
(match-define (cons l+ (and l- l-seal)) ctx)
(define ΔΣ₀
(let ([ΔΣ:seals
(for/fold ([acc : ΔΣ ⊥ΔΣ]) ([x (in-list xs)])
(define αₓ (α:dyn (β:sealed x ℓ) H₀))
(⧺ acc
(alloc αₓ ∅)
(alloc (γ:lex x) {set (Seal/C αₓ l-seal)})))]
[ΔΣ:stk (stack-copy (Clo-escapes xs c H ℓₒ) Σ₀)])
(⧺ ΔΣ:seals ΔΣ:stk)))
(define Σ₁ (⧺ Σ₀ ΔΣ₀))
(with-each-ans ([(ΔΣ₁ W:c) (evl Σ₁ c)])
(with-pre (⧺ ΔΣ₀ ΔΣ₁)
(mon (⧺ Σ₁ ΔΣ₁) (Ctx l+ l- ℓₒ ℓ) (car W:c) (Σ@ α Σ₀)))))
(define-simple-macro (with-guarded-arity W f ℓ [p body ...] ...)
(match W
[p body ...] ...
[_ (err (Err:Arity f (length W) ℓ))]))
)
|
2b84e30e934c85c83ab917ef8ad475fc4d17333fdf1eda421d1cae4ed17e1e81 | reborg/clojure-essential-reference | 1.clj | (eduction [& xforms]) | null | https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/ReducersandTransducers/Transducers/eduction/1.clj | clojure | (eduction [& xforms]) | |
45f8e36cccb7cf003a181e7398c1f73718177e1426bb65b6a9672bb60f1a8ad3 | techascent/tech.datatype | binary_reader.clj | (ns tech.v2.datatype.binary-reader
(:require [tech.v2.datatype.typecast :as typecast]
[tech.v2.datatype.protocols
:refer [default-endianness]
:as dtype-proto]
[tech.v2.datatype.binary-impl-helper :refer [reify-binary-reader-header]])
(:import [tech.v2.datatype BinaryReader ByteReader ByteConversions]
[java.nio ByteBuffer Buffer ByteOrder]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn reader-matches?
[buffer options]
(boolean (and (instance? BinaryReader buffer)
(= (dtype-proto/endianness buffer)
(default-endianness (:endianness options))))))
(defmacro short-from-reader
[endianness reader offset]
(case endianness
:little-endian `(ByteConversions/shortFromReaderLE ~reader ~offset)
:big-endian `(ByteConversions/shortFromReaderBE ~reader ~offset)))
(defmacro int-from-reader
[endianness reader offset]
(case endianness
:little-endian `(ByteConversions/intFromReaderLE ~reader ~offset)
:big-endian `(ByteConversions/intFromReaderBE ~reader ~offset)))
(defmacro long-from-reader
[endianness reader offset]
(case endianness
:little-endian `(ByteConversions/longFromReaderLE ~reader ~offset)
:big-endian `(ByteConversions/longFromReaderBE ~reader ~offset)))
(defmacro float-from-reader
[endianness reader offset]
(case endianness
:little-endian `(ByteConversions/floatFromReaderLE ~reader ~offset)
:big-endian `(ByteConversions/floatFromReaderBE ~reader ~offset)))
(defmacro double-from-reader
[endianness reader offset]
(case endianness
:little-endian `(ByteConversions/doubleFromReaderLE ~reader ~offset)
:big-endian `(ByteConversions/doubleFromReaderBE ~reader ~offset)))
(defmacro make-reader-binary-reader
[endianness buffer options]
`(let [buffer# ~buffer
reader# (typecast/datatype->reader :int8 buffer#)
lsize# (.lsize reader#)]
(reify-binary-reader-header
~endianness buffer# lsize# ~options reader->binary-reader
BinaryReader
(readBoolean [rdr# offset#]
(if (== 0 (.read reader# offset#))
false
true))
(readByte [rdr# offset#]
(.read reader# offset#))
(readShort [rdr# offset#]
(short-from-reader ~endianness reader# offset#))
(readInt [rdr# offset#]
(int-from-reader ~endianness reader# offset#))
(readLong [rdr# offset#]
(long-from-reader ~endianness reader# offset#))
(readFloat [rdr# offset#]
(float-from-reader ~endianness reader# offset#))
(readDouble [rdr# offset#]
(double-from-reader ~endianness reader# offset#)))))
(defn reader->binary-reader
(^BinaryReader [buffer {user-endianness :endianness :as options}]
(let [user-endianness (default-endianness user-endianness)]
(if (reader-matches? buffer options)
buffer
(case user-endianness
:little-endian (make-reader-binary-reader :little-endian buffer options)
:big-endian (make-reader-binary-reader :big-endian buffer options)))))
(^BinaryReader [reader]
(reader->binary-reader reader {})))
(defn byte-nio-buf->binary-reader
(^BinaryReader [^ByteBuffer nio-buf {user-endianness :endianness :as options}]
(let [user-endianness (default-endianness user-endianness)
buffer-endianness (dtype-proto/endianness nio-buf)
^ByteBuffer nio-buf
(if (= user-endianness buffer-endianness)
nio-buf
;;I know that sub-buffer produces a new nio buffer that is safe to change.
(let [^ByteBuffer new-buf (dtype-proto/sub-buffer nio-buf 0
(dtype-proto/ecount
nio-buf))]
(case user-endianness
:little-endian (.order new-buf ByteOrder/LITTLE_ENDIAN)
:big-endian (.order new-buf ByteOrder/BIG_ENDIAN))
new-buf))
buffer-start (.position nio-buf)
lsize (long (dtype-proto/ecount nio-buf))]
(assert (= (dtype-proto/endianness nio-buf) user-endianness)
(format "buffer %s user %s"
(dtype-proto/endianness nio-buf)
user-endianness))
(reify-binary-reader-header
user-endianness nio-buf lsize options byte-nio-buf->binary-reader
BinaryReader
(readBoolean [rdr offset]
(if (== 0 (.get nio-buf (+ buffer-start (unchecked-int offset))))
false
true))
(readByte [rdr offset]
(.get nio-buf (+ buffer-start (unchecked-int offset))))
(readShort [reader offset]
(.getShort nio-buf (+ buffer-start (unchecked-int offset))))
(readInt [rdr offset]
(.getInt nio-buf (+ buffer-start (unchecked-int offset))))
(readLong [rdr offset]
(.getLong nio-buf (+ buffer-start (unchecked-int offset))))
(readFloat [rdr offset]
(.getFloat nio-buf (+ buffer-start (unchecked-int offset))))
(readDouble [rdr offset]
(.getDouble nio-buf (+ buffer-start (unchecked-int offset)))))))
(^BinaryReader [nio-buf]
(byte-nio-buf->binary-reader nio-buf {})))
(extend-protocol dtype-proto/PConvertibleToBinaryReader
ByteBuffer
(convertible-to-binary-reader? [item] true)
(->binary-reader [item options] (byte-nio-buf->binary-reader item options))
ByteReader
(convertible-to-binary-reader? [item] true)
(->binary-reader [item options] (reader->binary-reader item options)))
(defn ->binary-reader
"Make a binary reader out of something. May return nil."
(^BinaryReader [item options]
(when item
(cond
(reader-matches? item options)
item
(dtype-proto/convertible-to-binary-reader? item)
(dtype-proto/->binary-reader item options)
(and (= (dtype-proto/get-datatype item) :int8)
(dtype-proto/convertible-to-reader? item))
(reader->binary-reader (dtype-proto/->reader item {:datatype :int8})))))
(^BinaryReader [item]
(->binary-reader item {})))
(comment
(require '[tech.v2.datatype :as dtype])
(def test-buf (dtype-proto/->binary-reader (dtype/make-container :nio-buffer :int8 (range 10))
{}))
(def sub-buffer (dtype-proto/->binary-reader (dtype/sub-buffer test-buf 4 4)
{}))
(.readShort test-buf 0)
(.readShort sub-buffer 0)
)
| null | https://raw.githubusercontent.com/techascent/tech.datatype/8cc83d771d9621d580fd5d4d0625005bd7ab0e0c/src/tech/v2/datatype/binary_reader.clj | clojure | I know that sub-buffer produces a new nio buffer that is safe to change. | (ns tech.v2.datatype.binary-reader
(:require [tech.v2.datatype.typecast :as typecast]
[tech.v2.datatype.protocols
:refer [default-endianness]
:as dtype-proto]
[tech.v2.datatype.binary-impl-helper :refer [reify-binary-reader-header]])
(:import [tech.v2.datatype BinaryReader ByteReader ByteConversions]
[java.nio ByteBuffer Buffer ByteOrder]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn reader-matches?
[buffer options]
(boolean (and (instance? BinaryReader buffer)
(= (dtype-proto/endianness buffer)
(default-endianness (:endianness options))))))
(defmacro short-from-reader
[endianness reader offset]
(case endianness
:little-endian `(ByteConversions/shortFromReaderLE ~reader ~offset)
:big-endian `(ByteConversions/shortFromReaderBE ~reader ~offset)))
(defmacro int-from-reader
[endianness reader offset]
(case endianness
:little-endian `(ByteConversions/intFromReaderLE ~reader ~offset)
:big-endian `(ByteConversions/intFromReaderBE ~reader ~offset)))
(defmacro long-from-reader
[endianness reader offset]
(case endianness
:little-endian `(ByteConversions/longFromReaderLE ~reader ~offset)
:big-endian `(ByteConversions/longFromReaderBE ~reader ~offset)))
(defmacro float-from-reader
[endianness reader offset]
(case endianness
:little-endian `(ByteConversions/floatFromReaderLE ~reader ~offset)
:big-endian `(ByteConversions/floatFromReaderBE ~reader ~offset)))
(defmacro double-from-reader
[endianness reader offset]
(case endianness
:little-endian `(ByteConversions/doubleFromReaderLE ~reader ~offset)
:big-endian `(ByteConversions/doubleFromReaderBE ~reader ~offset)))
(defmacro make-reader-binary-reader
[endianness buffer options]
`(let [buffer# ~buffer
reader# (typecast/datatype->reader :int8 buffer#)
lsize# (.lsize reader#)]
(reify-binary-reader-header
~endianness buffer# lsize# ~options reader->binary-reader
BinaryReader
(readBoolean [rdr# offset#]
(if (== 0 (.read reader# offset#))
false
true))
(readByte [rdr# offset#]
(.read reader# offset#))
(readShort [rdr# offset#]
(short-from-reader ~endianness reader# offset#))
(readInt [rdr# offset#]
(int-from-reader ~endianness reader# offset#))
(readLong [rdr# offset#]
(long-from-reader ~endianness reader# offset#))
(readFloat [rdr# offset#]
(float-from-reader ~endianness reader# offset#))
(readDouble [rdr# offset#]
(double-from-reader ~endianness reader# offset#)))))
(defn reader->binary-reader
(^BinaryReader [buffer {user-endianness :endianness :as options}]
(let [user-endianness (default-endianness user-endianness)]
(if (reader-matches? buffer options)
buffer
(case user-endianness
:little-endian (make-reader-binary-reader :little-endian buffer options)
:big-endian (make-reader-binary-reader :big-endian buffer options)))))
(^BinaryReader [reader]
(reader->binary-reader reader {})))
(defn byte-nio-buf->binary-reader
(^BinaryReader [^ByteBuffer nio-buf {user-endianness :endianness :as options}]
(let [user-endianness (default-endianness user-endianness)
buffer-endianness (dtype-proto/endianness nio-buf)
^ByteBuffer nio-buf
(if (= user-endianness buffer-endianness)
nio-buf
(let [^ByteBuffer new-buf (dtype-proto/sub-buffer nio-buf 0
(dtype-proto/ecount
nio-buf))]
(case user-endianness
:little-endian (.order new-buf ByteOrder/LITTLE_ENDIAN)
:big-endian (.order new-buf ByteOrder/BIG_ENDIAN))
new-buf))
buffer-start (.position nio-buf)
lsize (long (dtype-proto/ecount nio-buf))]
(assert (= (dtype-proto/endianness nio-buf) user-endianness)
(format "buffer %s user %s"
(dtype-proto/endianness nio-buf)
user-endianness))
(reify-binary-reader-header
user-endianness nio-buf lsize options byte-nio-buf->binary-reader
BinaryReader
(readBoolean [rdr offset]
(if (== 0 (.get nio-buf (+ buffer-start (unchecked-int offset))))
false
true))
(readByte [rdr offset]
(.get nio-buf (+ buffer-start (unchecked-int offset))))
(readShort [reader offset]
(.getShort nio-buf (+ buffer-start (unchecked-int offset))))
(readInt [rdr offset]
(.getInt nio-buf (+ buffer-start (unchecked-int offset))))
(readLong [rdr offset]
(.getLong nio-buf (+ buffer-start (unchecked-int offset))))
(readFloat [rdr offset]
(.getFloat nio-buf (+ buffer-start (unchecked-int offset))))
(readDouble [rdr offset]
(.getDouble nio-buf (+ buffer-start (unchecked-int offset)))))))
(^BinaryReader [nio-buf]
(byte-nio-buf->binary-reader nio-buf {})))
(extend-protocol dtype-proto/PConvertibleToBinaryReader
ByteBuffer
(convertible-to-binary-reader? [item] true)
(->binary-reader [item options] (byte-nio-buf->binary-reader item options))
ByteReader
(convertible-to-binary-reader? [item] true)
(->binary-reader [item options] (reader->binary-reader item options)))
(defn ->binary-reader
"Make a binary reader out of something. May return nil."
(^BinaryReader [item options]
(when item
(cond
(reader-matches? item options)
item
(dtype-proto/convertible-to-binary-reader? item)
(dtype-proto/->binary-reader item options)
(and (= (dtype-proto/get-datatype item) :int8)
(dtype-proto/convertible-to-reader? item))
(reader->binary-reader (dtype-proto/->reader item {:datatype :int8})))))
(^BinaryReader [item]
(->binary-reader item {})))
(comment
(require '[tech.v2.datatype :as dtype])
(def test-buf (dtype-proto/->binary-reader (dtype/make-container :nio-buffer :int8 (range 10))
{}))
(def sub-buffer (dtype-proto/->binary-reader (dtype/sub-buffer test-buf 4 4)
{}))
(.readShort test-buf 0)
(.readShort sub-buffer 0)
)
|
bb1ab51b30dbb8f4b4d6c0490b44d1dc0e693c23ba54350c78e2f7470d53b5fd | 2600hz/kazoo | cb_tests.erl | %%%-----------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz
%%% @doc
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 /.
%%%
%%% @end
%%%-----------------------------------------------------------------------------
-module(cb_tests).
-export([start/0, start/1]).
-spec start() -> tuple().
start() ->
start(100).
-spec start(pos_integer()) -> tuple().
start(N) ->
start(N, N, 0, 0, []).
start(N, 0, CDR, ECDR, Raw) ->
{{total, N}
,{cdr, CDR, CDR div N}
,{ecdr, ECDR, ECDR div N}
,{diff, CDR - ECDR, ECDR - CDR}
,{avg_diff, (CDR - ECDR) div N, (ECDR - CDR) div N}
,{raw, Raw}
};
start(N, X, CDRTot, ECDRTot, Raw) ->
StartKey = start_key(),
EndKey = end_key(StartKey),
{ECDR, _} = timer:tc(kz_datamgr, get_results, [<<"account%2F50%2F3d%2F96f14def94f7ce08cf3e1a025375">>, <<"ecdrs/crossbar_listing">>, [{<<"startkey">>,StartKey},{<<"endkey">>,EndKey}]]),
{CDR,_} = timer:tc(kz_datamgr, get_results, [<<"account%2F50%2F3d%2F96f14def94f7ce08cf3e1a025375">>, <<"cdrs/crossbar_listing">>, [{<<"startkey">>,StartKey},{<<"endkey">>,EndKey}]]),
start(N, X-1, CDRTot + CDR, ECDRTot + ECDR, [ [{range, EndKey - StartKey}, {run, X}] | Raw]).
start_key() ->
365 days * secs / day + start seconds - start somewhere within the year
(rand:uniform(365) * 86400) + 63477725277.
end_key(Start) ->
up to 30 days in the future
| null | https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/applications/crossbar/src/cb_tests.erl | erlang | -----------------------------------------------------------------------------
@doc
@end
----------------------------------------------------------------------------- | ( C ) 2010 - 2020 , 2600Hz
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(cb_tests).
-export([start/0, start/1]).
-spec start() -> tuple().
start() ->
start(100).
-spec start(pos_integer()) -> tuple().
start(N) ->
start(N, N, 0, 0, []).
start(N, 0, CDR, ECDR, Raw) ->
{{total, N}
,{cdr, CDR, CDR div N}
,{ecdr, ECDR, ECDR div N}
,{diff, CDR - ECDR, ECDR - CDR}
,{avg_diff, (CDR - ECDR) div N, (ECDR - CDR) div N}
,{raw, Raw}
};
start(N, X, CDRTot, ECDRTot, Raw) ->
StartKey = start_key(),
EndKey = end_key(StartKey),
{ECDR, _} = timer:tc(kz_datamgr, get_results, [<<"account%2F50%2F3d%2F96f14def94f7ce08cf3e1a025375">>, <<"ecdrs/crossbar_listing">>, [{<<"startkey">>,StartKey},{<<"endkey">>,EndKey}]]),
{CDR,_} = timer:tc(kz_datamgr, get_results, [<<"account%2F50%2F3d%2F96f14def94f7ce08cf3e1a025375">>, <<"cdrs/crossbar_listing">>, [{<<"startkey">>,StartKey},{<<"endkey">>,EndKey}]]),
start(N, X-1, CDRTot + CDR, ECDRTot + ECDR, [ [{range, EndKey - StartKey}, {run, X}] | Raw]).
start_key() ->
365 days * secs / day + start seconds - start somewhere within the year
(rand:uniform(365) * 86400) + 63477725277.
end_key(Start) ->
up to 30 days in the future
|
085c2328e2009a4d435e00ea07a442892315e966e7ee0cbe445a442d0cb85cf9 | ericfinster/catt.io | typecheck.ml | (*****************************************************************************)
(* *)
(* Typechecking *)
(* *)
(*****************************************************************************)
open Format
open Pd
open Suite
open Term
open Expr
open Mtl
(*****************************************************************************)
(*****************************************************************************)
type normalization_type =
| None
| StrictlyUnital
type tc_config = {
norm_type: normalization_type;
debug_streams: (string * int) list;
}
let default_config = {
norm_type = None;
debug_streams = [];
}
type tc_err =
| TypeMismatch of (tm_term * ty_term * ty_term)
| InvalidIndex of int
| UnknownIdentifier of string
| NonFullSource of (tm_term pd * tm_term pd)
| NonFullTarget of (tm_term pd * tm_term pd)
| UnderApplication
| OverApplication
| InternalError of string
let print_tc_err terr =
match terr with
| TypeMismatch (tm,ex_ty,in_ty) ->
asprintf "@[<v>The term@,@,%a@,@,was expected to have type@,@,%a@,@,but was inferred to have type@,@,%a@]"
pp_print_expr_tm (term_to_expr_tm_default tm)
pp_print_expr_ty (term_to_expr_ty_default ex_ty)
pp_print_expr_ty (term_to_expr_ty_default in_ty)
| InvalidIndex i -> sprintf "Unknown variable index %d" i
| UnknownIdentifier s -> sprintf "Unknown identifier %s" s
| NonFullSource (_, _) -> "Non-full source"
| NonFullTarget (_, _) -> "Non-full target"
| UnderApplication -> "Not enough arguments"
| OverApplication -> "Too many arguments"
| InternalError s -> s
type tc_def =
| TCCohDef of tm_term pd * ty_term
| TCTermDef of ty_term suite * ty_term * tm_term
type tc_env = {
gma : ty_term suite;
rho : (string * tc_def) suite;
config : tc_config;
modules : string list;
}
let empty_env = {
gma = Emp ;
rho = Emp ;
config = default_config;
modules = [];
}
(* module StringErr = ErrMnd(struct type t = string end) *)
module TcErrMnd = ErrMnd(struct type t = tc_err end)
module TcmMnd = ReaderT(struct type t = tc_env end)(TcErrMnd)
(* Bring syntax into scope *)
open TcmMnd
open MonadSyntax(TcmMnd)
type 'a tcm = 'a TcmMnd.m
let tc_ok a = pure a
let tc_fail e = lift (Fail e)
(* Not sure how to lift the lower error instance effectively ... *)
let tc_catch m f env =
match m env with
| Ok a -> Ok a
| Fail s -> f s env
let ensure b e =
if b then tc_ok ()
else tc_fail e
let tc_in_ctx g m env = m { env with gma = g }
let tc_ctx env = Ok env.gma
let tc_env env = Ok env
let tc_with_env e m _ = m e
let tc_lift m _ = m
let tc_depth env = Ok (length env.gma)
let tc_from_str_err m _ =
match m with
| Ok a -> Ok a
| Fail s -> Fail (InternalError s)
let tc_with_coh id pd typ m env =
m { env with rho = Ext (env.rho, (id, TCCohDef (pd,typ))) }
let tc_with_let id gma ty tm m env =
m { env with rho = Ext (env.rho, (id, TCTermDef (gma,ty,tm))) }
let tc_lookup_var i env =
try Ok (nth i env.gma)
with Not_found -> Fail (InvalidIndex i)
let tc_lookup_def id env =
try Ok (assoc id env.rho)
with Not_found -> Fail (UnknownIdentifier id)
(*****************************************************************************)
(* Debugging routines *)
(*****************************************************************************)
let tc_dump_rho =
let* env = tc_env in
fprintf std_formatter "Environment: %a@,"
(pp_print_suite_horiz (fun ppf (id,_) -> fprintf ppf "%s" id)) env.rho;
tc_ok ()
(*****************************************************************************)
(* Unfolding *)
(*****************************************************************************)
module ST = SuiteTraverse(MndToApp(TcmMnd))
let rec tc_unfold_ty ty =
match ty with
| ObjT -> tc_ok ObjT
| ArrT (typ,src,tgt) ->
let* typ' = tc_unfold_ty typ in
let* src' = tc_unfold_tm src in
let* tgt' = tc_unfold_tm tgt in
tc_ok (ArrT (typ',src',tgt'))
and tc_unfold_tm tm =
match tm with
| VarT i -> tc_ok (VarT i)
| DefAppT (id, sub) -> (
let* sub' = ST.traverse tc_unfold_tm sub in
let* def = tc_lookup_def id in
match def with
| TCCohDef (pd,typ) ->
let* typ' = tc_unfold_ty typ in
tc_ok (CohT (pd,typ',sub'))
| TCTermDef (_, _, tm) ->
let* tm' = tc_unfold_tm tm in
tc_ok (subst_tm sub' tm')
)
| CohT (pd,typ,sub) ->
let* sub' = ST.traverse tc_unfold_tm sub in
let* typ' = tc_unfold_ty typ in
tc_ok (CohT (pd,typ',sub'))
(*****************************************************************************)
(* Strict Unit Normalization *)
(*****************************************************************************)
let rec id_typ k =
if (k <= 0) then ObjT else
ArrT (id_typ (k-1), VarT (2*k - 2), VarT (2*k - 1))
let id_cell k =
(pd_to_db (disc k),
ArrT (id_typ k, VarT (2*k), VarT (2*k)))
let identity_on ty tm =
let (id_pd, id_ty) = id_cell (dim_typ ty) in
CohT (id_pd, id_ty, disc_sub ty tm)
(* Extract the type of the current
focus in a pasting diagram context *)
let rec ctx_typ ctx =
match ctx with
| Emp -> ObjT
| Ext (ctx',(s,t,_,_)) ->
ArrT (ctx_typ ctx', s, t)
(* Not used currently ... *)
let match_identity tm =
match tm with
| CohT (pd,typ,args) ->
let (id_pd, id_ty) = id_cell (dim_pd pd) in
if (pd = id_pd && typ = id_ty) then
Ok (last args)
else
Fail "Not an identity"
(* perhaps you should unfold? *)
| _ -> Fail "Not an identity"
let is_identity tm =
(* printf "Checking if term is ident: %a@," pp_print_tm tm; *)
match tm with
| CohT (pd,typ,_) ->
let ( id_pd , id_typ ) = id_cell ( dim_pd pd ) in
* printf " Expected i d cell : @[<hov>%a:%a@]@ , " pp_print_term_pd id_pd pp_print_ty id_typ ;
* printf "Expected id cell: @[<hov>%a:%a@]@," pp_print_term_pd id_pd pp_print_ty id_typ; *)
(pd,typ)=(id_cell (dim_pd pd))
| _ -> false
let (>>==) = StringErr.bind
let (<||>) = StringErr.(<||>)
type prune_result =
| NothingPruned
| PrunedData of (tm_term pd * tm_term suite * tm_term suite)
(* Assumes we are at a leaf. Finds the next
(moving right) leaf with a prunable term
or fails *)
let rec next_prunable z =
printf " At leaf : % a@ , " pp_print_term_pd ( snd z ) ;
if (is_identity (label_of (snd z))) then Ok z
else leaf_right z >>==
next_prunable
let prune_once pd =
let open MonadSyntax(StringErr) in
let* lz = to_leftmost_leaf (Emp,pd) in
match next_prunable lz with
| Fail _ -> Ok NothingPruned
| Ok pz ->
printf " Found a prunable argument : % a@ , " pp_print_tm ( label_of ( snd pz ) ) ;
let* (addr,dir) = (
match addr_of pz with
| Emp -> Fail "Invalid address during pruning"
| Ext(a,d) -> Ok (a,d)
) in
printf " Address : % a@ , " pp_print_addr ( Ext(addr , dir ) ) ;
let* dz = pd_drop pz in
let pd' = pd_close dz in
let db_pd = pd_to_db pd' in
(* printf "New pasting diagram is: %a@," pp_print_term_pd db_pd; *)
let* (ctx,fcs) = seek addr (Emp, db_pd) in
(* printf "Seek has focus: %a@," pp_print_term_pd fcs; *)
let* newfcs =
(match fcs with
| Br (s,brs) ->
let id_ty = ctx_typ ctx in
let id_tm = identity_on id_ty s in
let id_br = Br (id_tm, Emp) in
let (l,r) = split_at dir brs in
let src = (match l with
| Emp -> s
| Ext(_,(t,_)) -> t) in
Ok (Br (s, append_list (Ext (l,(src,id_br))) r))) in
(* printf "Got new focus@,"; *)
let pi_pd = pd_close (ctx, newfcs) in
let pi = labels pi_pd in
let sigma = labels pd' in
printf " pi : % a@ , " pp_print_sub pi ;
* printf " sigma : % a@ , " pp_print_sub sigma ;
* printf "sigma: %a@," pp_print_sub sigma; *)
Ok (PrunedData (db_pd, pi, sigma))
let rec prune pd typ args =
let open MonadSyntax(StringErr) in
let* arg_pd = args_to_pd pd args in
let* pr = prune_once arg_pd in
match pr with
| NothingPruned -> Ok (pd,typ,args)
| PrunedData (pd',pi,args') ->
(* printf "Pruned an argument!@,"; *)
prune pd' (subst_ty pi typ) args'
let disc_cell k =
(pd_to_db (disc k), id_typ k)
let disc_remove pd typ sub =
match tm with
* | VarT i - > Ok ( VarT i )
* ( pd , typ , sub ) - >
* | VarT i -> Ok (VarT i)
* | CohT (pd, typ, sub) -> *)
if ((pd,typ) = disc_cell (dim_pd pd)) then
Ok (last sub)
else Ok (CohT (pd,typ,sub))
(* | _ -> Fail "unfold in disc remove" *)
type endo_result =
| NoEndoReduction
| EndoReduced of tm_term
let endo_coherence tm =
let nored = Ok NoEndoReduction in
(* printf "In endo coh with: %a@," pp_print_tm tm; *)
match tm with
| VarT _ -> nored
| CohT (_, ObjT, _) -> nored
| CohT (_, ArrT (btyp,src,tgt), sub) ->
if (src = tgt) then
let src' = subst_tm sub src in
let typ' = subst_ty sub btyp in
printf " Endo - coherence for : % a@ , " pp_print_tm src ;
Ok (EndoReduced (identity_on typ' src'))
else nored
| _ -> Fail "Unfold in endo-coh"
let rec strict_unit_normalize_ty ty =
match ty with
| ObjT -> tc_ok ObjT
| ArrT (typ,src,tgt) ->
let* typ' = strict_unit_normalize_ty typ in
let* src' = strict_unit_normalize_tm src in
let* tgt' = strict_unit_normalize_tm tgt in
tc_ok (ArrT (typ',src',tgt'))
and strict_unit_normalize_tm ?debug:(dbg=false) tm =
let print_debug s = if dbg then printf " % s " s else ( ) in
print_debug ( asprintf " In su normalizer ... @ , " ) ;
if dbg then () else ();
match tm with
| VarT i -> tc_ok (VarT i)
| DefAppT (id, sub) -> (
let* def = tc_lookup_def id in
match def with
| TCCohDef (pd,typ) ->
print_debug ( asprintf " Normalizing a defined coherence@ , " ) ;
strict_unit_normalize_tm ~debug:true (CohT (pd,typ,sub))
| TCTermDef (_, _, tm) ->
strict_unit_normalize_tm (subst_tm sub tm)
)
| CohT (pd,typ,sub) ->
print_debug ( asprintf " Normalizing a coherence@ , " ) ;
let* sub' = ST.traverse strict_unit_normalize_tm sub in
let* (ppd,ptyp,psub) =
if (not (is_identity tm)) then
tc_from_str_err (prune pd typ sub')
else tc_ok (pd,typ,sub') in
printf " After pruning : % a@ , " pp_print_tm ( CohT ( ppd , ptyp , ) ) ;
let* typ' = strict_unit_normalize_ty ptyp in
print_debug ( asprintf " Normalized boundary : % a@ , " pp_print_ty typ ' ) ;
let* dtm = tc_lift (disc_remove ppd typ' psub) in
if (not (is_identity dtm)) then
let* er = tc_from_str_err (endo_coherence dtm) in
match er with
| NoEndoReduction -> tc_ok dtm
| EndoReduced tm' ->
print_debug ( asprintf " Reduced an endo - coherence@ , " ) ;
(* printf "Endo coherence resulted in: %a@," pp_print_tm tm'; *)
strict_unit_normalize_tm tm'
else tc_ok dtm
(*****************************************************************************)
Toplevel Normalization
(*****************************************************************************)
let tc_normalize_tm ?debug:(dbg=false) tm =
let* env = tc_env in
match env.config.norm_type with
| None -> tc_unfold_tm tm
| StrictlyUnital -> strict_unit_normalize_tm ~debug:dbg tm
let tc_normalize_ty ty =
let* env = tc_env in
match env.config.norm_type with
| None -> tc_unfold_ty ty
| StrictlyUnital -> strict_unit_normalize_ty ty
(*****************************************************************************)
(* Typing Rules *)
(*****************************************************************************)
let rec tc_check_ty t =
match t with
| ObjT -> tc_ok ObjT
| ArrT (typ, src, tgt) ->
let* typ' = tc_check_ty typ in
let* src' = tc_check_tm src typ' in
let* tgt' = tc_check_tm tgt typ' in
tc_ok (ArrT (typ', src', tgt'))
and tc_check_tm tm ty =
let* (tm', ty') = tc_infer_tm tm in
let* ty_nf = tc_normalize_ty ty in
let* ty_nf' = tc_normalize_ty ty' in
if (ty_nf = ty_nf') then
tc_ok tm'
else
tc_fail (TypeMismatch (tm,ty,ty'))
let * _ = tc_catch ( tc_eq_nf_ty ty ty ' )
*
* ( fun _ - > let msg = asprintf " @[<v > The term@,@,%a@,@,was expected to have type@,@,%a@,@,but was inferred to have type@,@,%a@ ] "
* pp_print_expr_tm ( term_to_expr_tm tm )
* ( term_to_expr_ty ty )
* ( term_to_expr_ty ty ' )
* in tc_fail msg ) in
*
* tc_ok tm '
*
* (fun _ -> let msg = asprintf "@[<v>The term@,@,%a@,@,was expected to have type@,@,%a@,@,but was inferred to have type@,@,%a@]"
* pp_print_expr_tm (term_to_expr_tm tm)
* pp_print_expr_ty (term_to_expr_ty ty)
* pp_print_expr_ty (term_to_expr_ty ty')
* in tc_fail msg) in
*
* tc_ok tm' *)
and tc_infer_tm tm =
match tm with
| VarT i ->
let* typ = tc_lookup_var i in
tc_ok (VarT i , typ)
| DefAppT (id, sub) -> (
let* def = tc_lookup_def id in
match def with
| TCCohDef (pd,typ) ->
let pd_ctx = pd_to_ctx pd in
let* sub' = tc_check_args sub pd_ctx in
tc_ok (DefAppT (id, sub'), subst_ty sub' typ)
| TCTermDef (ctx, typ, _) ->
let* sub' = tc_check_args sub ctx in
tc_ok (DefAppT (id, sub'), subst_ty sub' typ)
)
| CohT (pd, typ, sub) ->
let pd_ctx = pd_to_ctx pd in
let* typ' = tc_in_ctx pd_ctx
(let* rtyp = tc_check_ty typ in
tc_check_is_full pd rtyp) in
(* Check the substitution and calculate the return type *)
let* sub' = tc_check_args sub pd_ctx in
tc_ok (CohT (pd, typ', sub'), subst_ty sub' typ')
and tc_check_is_full pd typ =
let pd_dim = dim_pd pd in
(* printf "Checking fullness..."; *)
printf " Pd : % a@ , " ( pp_print_pd pp_print_tm ) pd ;
* printf " Type : @[<hov>%a@]@ , " pp_print_ty typ ;
* printf "Type: @[<hov>%a@]@," pp_print_ty typ; *)
match typ with
| ObjT -> tc_fail (InternalError "Coherence cannot have object type")
| ArrT (btyp,src,tgt) ->
let* src_pd = tc_term_pd src in
let* tgt_pd = tc_term_pd tgt in
let typ_dim = dim_typ btyp in
if (typ_dim >= pd_dim) then
(* let _ = () in printf "Checking coherence@,"; *)
let* _ = ensure (src_pd = pd) (NonFullSource (src_pd, pd)) in
let* _ = ensure (tgt_pd = pd) (NonFullTarget (tgt_pd, pd)) in
tc_ok typ
else
let _ = ( ) in printf " Checking composite@ , " ;
let pd_src = truncate true (pd_dim - 1) pd in
let pd_tgt = truncate false (pd_dim - 1) pd in
printf " Expected source pd : % a@ , " ( pp_print_pd pp_print_tm ) pd_src ;
* printf " Provided source pd : % a@ , " ( pp_print_pd pp_print_tm ) src_pd ;
* printf " Expected target pd : % a@ , " ( pp_print_pd pp_print_tm ) pd_tgt ;
* printf " Provided target pd : % a@ , " ( pp_print_pd pp_print_tm ) tgt_pd ;
* printf "Provided source pd: %a@," (pp_print_pd pp_print_tm) src_pd;
* printf "Expected target pd: %a@," (pp_print_pd pp_print_tm) pd_tgt;
* printf "Provided target pd: %a@," (pp_print_pd pp_print_tm) tgt_pd; *)
let* _ = ensure (src_pd = pd_src) (NonFullSource (src_pd, pd)) in
let* _ = ensure (tgt_pd = pd_tgt) (NonFullTarget (tgt_pd, pd)) in
tc_ok typ
and tc_check_args sub gma =
match (sub,gma) with
| (Ext (_,_), Emp) -> tc_fail UnderApplication
| (Emp, Ext (_,_)) -> tc_fail OverApplication
| (Emp, Emp) -> tc_ok Emp
| (Ext (sub',tm), Ext (gma',typ)) ->
let* rsub = tc_check_args sub' gma' in
let typ' = subst_ty rsub typ in
let* rtm = tc_check_tm tm typ' in
tc_ok (Ext (rsub, rtm))
(* Extract the pasting diagram of a well typed term.
* Note that the term is assumed to be well typed in
* the current context *)
and tc_term_pd tm =
match tm with
| VarT i ->
let* typ = tc_lookup_var i in
tc_ok (disc_pd typ (VarT i))
| DefAppT (id , args) -> (
let* def = tc_lookup_def id in
match def with
| TCCohDef (pd,typ) ->
tc_term_pd (CohT (pd,typ,args))
| TCTermDef (_, _, tm) ->
tc_term_pd (subst_tm args tm)
)
| CohT (pd, _, sub) ->
let* pd_sub = ST.traverse tc_term_pd sub in
let* ppd = tc_from_str_err (args_to_pd pd pd_sub) in
printf " To Join : % a@ , " ( pp_print_pd ( pp_print_pd pp_print_tm ) ) ppd ;
let jres = join_pd 0 ppd in
printf " Result : % a@ , " ( pp_print_pd pp_print_tm ) jres ;
tc_ok jres
| null | https://raw.githubusercontent.com/ericfinster/catt.io/0f2446860b7daba8ac2c343f933056195151a819/lib/typecheck.ml | ocaml | ***************************************************************************
Typechecking
***************************************************************************
***************************************************************************
***************************************************************************
module StringErr = ErrMnd(struct type t = string end)
Bring syntax into scope
Not sure how to lift the lower error instance effectively ...
***************************************************************************
Debugging routines
***************************************************************************
***************************************************************************
Unfolding
***************************************************************************
***************************************************************************
Strict Unit Normalization
***************************************************************************
Extract the type of the current
focus in a pasting diagram context
Not used currently ...
perhaps you should unfold?
printf "Checking if term is ident: %a@," pp_print_tm tm;
Assumes we are at a leaf. Finds the next
(moving right) leaf with a prunable term
or fails
printf "New pasting diagram is: %a@," pp_print_term_pd db_pd;
printf "Seek has focus: %a@," pp_print_term_pd fcs;
printf "Got new focus@,";
printf "Pruned an argument!@,";
| _ -> Fail "unfold in disc remove"
printf "In endo coh with: %a@," pp_print_tm tm;
printf "Endo coherence resulted in: %a@," pp_print_tm tm';
***************************************************************************
***************************************************************************
***************************************************************************
Typing Rules
***************************************************************************
Check the substitution and calculate the return type
printf "Checking fullness...";
let _ = () in printf "Checking coherence@,";
Extract the pasting diagram of a well typed term.
* Note that the term is assumed to be well typed in
* the current context |
open Format
open Pd
open Suite
open Term
open Expr
open Mtl
type normalization_type =
| None
| StrictlyUnital
type tc_config = {
norm_type: normalization_type;
debug_streams: (string * int) list;
}
let default_config = {
norm_type = None;
debug_streams = [];
}
type tc_err =
| TypeMismatch of (tm_term * ty_term * ty_term)
| InvalidIndex of int
| UnknownIdentifier of string
| NonFullSource of (tm_term pd * tm_term pd)
| NonFullTarget of (tm_term pd * tm_term pd)
| UnderApplication
| OverApplication
| InternalError of string
let print_tc_err terr =
match terr with
| TypeMismatch (tm,ex_ty,in_ty) ->
asprintf "@[<v>The term@,@,%a@,@,was expected to have type@,@,%a@,@,but was inferred to have type@,@,%a@]"
pp_print_expr_tm (term_to_expr_tm_default tm)
pp_print_expr_ty (term_to_expr_ty_default ex_ty)
pp_print_expr_ty (term_to_expr_ty_default in_ty)
| InvalidIndex i -> sprintf "Unknown variable index %d" i
| UnknownIdentifier s -> sprintf "Unknown identifier %s" s
| NonFullSource (_, _) -> "Non-full source"
| NonFullTarget (_, _) -> "Non-full target"
| UnderApplication -> "Not enough arguments"
| OverApplication -> "Too many arguments"
| InternalError s -> s
type tc_def =
| TCCohDef of tm_term pd * ty_term
| TCTermDef of ty_term suite * ty_term * tm_term
type tc_env = {
gma : ty_term suite;
rho : (string * tc_def) suite;
config : tc_config;
modules : string list;
}
let empty_env = {
gma = Emp ;
rho = Emp ;
config = default_config;
modules = [];
}
module TcErrMnd = ErrMnd(struct type t = tc_err end)
module TcmMnd = ReaderT(struct type t = tc_env end)(TcErrMnd)
open TcmMnd
open MonadSyntax(TcmMnd)
type 'a tcm = 'a TcmMnd.m
let tc_ok a = pure a
let tc_fail e = lift (Fail e)
let tc_catch m f env =
match m env with
| Ok a -> Ok a
| Fail s -> f s env
let ensure b e =
if b then tc_ok ()
else tc_fail e
let tc_in_ctx g m env = m { env with gma = g }
let tc_ctx env = Ok env.gma
let tc_env env = Ok env
let tc_with_env e m _ = m e
let tc_lift m _ = m
let tc_depth env = Ok (length env.gma)
let tc_from_str_err m _ =
match m with
| Ok a -> Ok a
| Fail s -> Fail (InternalError s)
let tc_with_coh id pd typ m env =
m { env with rho = Ext (env.rho, (id, TCCohDef (pd,typ))) }
let tc_with_let id gma ty tm m env =
m { env with rho = Ext (env.rho, (id, TCTermDef (gma,ty,tm))) }
let tc_lookup_var i env =
try Ok (nth i env.gma)
with Not_found -> Fail (InvalidIndex i)
let tc_lookup_def id env =
try Ok (assoc id env.rho)
with Not_found -> Fail (UnknownIdentifier id)
let tc_dump_rho =
let* env = tc_env in
fprintf std_formatter "Environment: %a@,"
(pp_print_suite_horiz (fun ppf (id,_) -> fprintf ppf "%s" id)) env.rho;
tc_ok ()
module ST = SuiteTraverse(MndToApp(TcmMnd))
let rec tc_unfold_ty ty =
match ty with
| ObjT -> tc_ok ObjT
| ArrT (typ,src,tgt) ->
let* typ' = tc_unfold_ty typ in
let* src' = tc_unfold_tm src in
let* tgt' = tc_unfold_tm tgt in
tc_ok (ArrT (typ',src',tgt'))
and tc_unfold_tm tm =
match tm with
| VarT i -> tc_ok (VarT i)
| DefAppT (id, sub) -> (
let* sub' = ST.traverse tc_unfold_tm sub in
let* def = tc_lookup_def id in
match def with
| TCCohDef (pd,typ) ->
let* typ' = tc_unfold_ty typ in
tc_ok (CohT (pd,typ',sub'))
| TCTermDef (_, _, tm) ->
let* tm' = tc_unfold_tm tm in
tc_ok (subst_tm sub' tm')
)
| CohT (pd,typ,sub) ->
let* sub' = ST.traverse tc_unfold_tm sub in
let* typ' = tc_unfold_ty typ in
tc_ok (CohT (pd,typ',sub'))
let rec id_typ k =
if (k <= 0) then ObjT else
ArrT (id_typ (k-1), VarT (2*k - 2), VarT (2*k - 1))
let id_cell k =
(pd_to_db (disc k),
ArrT (id_typ k, VarT (2*k), VarT (2*k)))
let identity_on ty tm =
let (id_pd, id_ty) = id_cell (dim_typ ty) in
CohT (id_pd, id_ty, disc_sub ty tm)
let rec ctx_typ ctx =
match ctx with
| Emp -> ObjT
| Ext (ctx',(s,t,_,_)) ->
ArrT (ctx_typ ctx', s, t)
let match_identity tm =
match tm with
| CohT (pd,typ,args) ->
let (id_pd, id_ty) = id_cell (dim_pd pd) in
if (pd = id_pd && typ = id_ty) then
Ok (last args)
else
Fail "Not an identity"
| _ -> Fail "Not an identity"
let is_identity tm =
match tm with
| CohT (pd,typ,_) ->
let ( id_pd , id_typ ) = id_cell ( dim_pd pd ) in
* printf " Expected i d cell : @[<hov>%a:%a@]@ , " pp_print_term_pd id_pd pp_print_ty id_typ ;
* printf "Expected id cell: @[<hov>%a:%a@]@," pp_print_term_pd id_pd pp_print_ty id_typ; *)
(pd,typ)=(id_cell (dim_pd pd))
| _ -> false
let (>>==) = StringErr.bind
let (<||>) = StringErr.(<||>)
type prune_result =
| NothingPruned
| PrunedData of (tm_term pd * tm_term suite * tm_term suite)
let rec next_prunable z =
printf " At leaf : % a@ , " pp_print_term_pd ( snd z ) ;
if (is_identity (label_of (snd z))) then Ok z
else leaf_right z >>==
next_prunable
let prune_once pd =
let open MonadSyntax(StringErr) in
let* lz = to_leftmost_leaf (Emp,pd) in
match next_prunable lz with
| Fail _ -> Ok NothingPruned
| Ok pz ->
printf " Found a prunable argument : % a@ , " pp_print_tm ( label_of ( snd pz ) ) ;
let* (addr,dir) = (
match addr_of pz with
| Emp -> Fail "Invalid address during pruning"
| Ext(a,d) -> Ok (a,d)
) in
printf " Address : % a@ , " pp_print_addr ( Ext(addr , dir ) ) ;
let* dz = pd_drop pz in
let pd' = pd_close dz in
let db_pd = pd_to_db pd' in
let* (ctx,fcs) = seek addr (Emp, db_pd) in
let* newfcs =
(match fcs with
| Br (s,brs) ->
let id_ty = ctx_typ ctx in
let id_tm = identity_on id_ty s in
let id_br = Br (id_tm, Emp) in
let (l,r) = split_at dir brs in
let src = (match l with
| Emp -> s
| Ext(_,(t,_)) -> t) in
Ok (Br (s, append_list (Ext (l,(src,id_br))) r))) in
let pi_pd = pd_close (ctx, newfcs) in
let pi = labels pi_pd in
let sigma = labels pd' in
printf " pi : % a@ , " pp_print_sub pi ;
* printf " sigma : % a@ , " pp_print_sub sigma ;
* printf "sigma: %a@," pp_print_sub sigma; *)
Ok (PrunedData (db_pd, pi, sigma))
let rec prune pd typ args =
let open MonadSyntax(StringErr) in
let* arg_pd = args_to_pd pd args in
let* pr = prune_once arg_pd in
match pr with
| NothingPruned -> Ok (pd,typ,args)
| PrunedData (pd',pi,args') ->
prune pd' (subst_ty pi typ) args'
let disc_cell k =
(pd_to_db (disc k), id_typ k)
let disc_remove pd typ sub =
match tm with
* | VarT i - > Ok ( VarT i )
* ( pd , typ , sub ) - >
* | VarT i -> Ok (VarT i)
* | CohT (pd, typ, sub) -> *)
if ((pd,typ) = disc_cell (dim_pd pd)) then
Ok (last sub)
else Ok (CohT (pd,typ,sub))
type endo_result =
| NoEndoReduction
| EndoReduced of tm_term
let endo_coherence tm =
let nored = Ok NoEndoReduction in
match tm with
| VarT _ -> nored
| CohT (_, ObjT, _) -> nored
| CohT (_, ArrT (btyp,src,tgt), sub) ->
if (src = tgt) then
let src' = subst_tm sub src in
let typ' = subst_ty sub btyp in
printf " Endo - coherence for : % a@ , " pp_print_tm src ;
Ok (EndoReduced (identity_on typ' src'))
else nored
| _ -> Fail "Unfold in endo-coh"
let rec strict_unit_normalize_ty ty =
match ty with
| ObjT -> tc_ok ObjT
| ArrT (typ,src,tgt) ->
let* typ' = strict_unit_normalize_ty typ in
let* src' = strict_unit_normalize_tm src in
let* tgt' = strict_unit_normalize_tm tgt in
tc_ok (ArrT (typ',src',tgt'))
and strict_unit_normalize_tm ?debug:(dbg=false) tm =
let print_debug s = if dbg then printf " % s " s else ( ) in
print_debug ( asprintf " In su normalizer ... @ , " ) ;
if dbg then () else ();
match tm with
| VarT i -> tc_ok (VarT i)
| DefAppT (id, sub) -> (
let* def = tc_lookup_def id in
match def with
| TCCohDef (pd,typ) ->
print_debug ( asprintf " Normalizing a defined coherence@ , " ) ;
strict_unit_normalize_tm ~debug:true (CohT (pd,typ,sub))
| TCTermDef (_, _, tm) ->
strict_unit_normalize_tm (subst_tm sub tm)
)
| CohT (pd,typ,sub) ->
print_debug ( asprintf " Normalizing a coherence@ , " ) ;
let* sub' = ST.traverse strict_unit_normalize_tm sub in
let* (ppd,ptyp,psub) =
if (not (is_identity tm)) then
tc_from_str_err (prune pd typ sub')
else tc_ok (pd,typ,sub') in
printf " After pruning : % a@ , " pp_print_tm ( CohT ( ppd , ptyp , ) ) ;
let* typ' = strict_unit_normalize_ty ptyp in
print_debug ( asprintf " Normalized boundary : % a@ , " pp_print_ty typ ' ) ;
let* dtm = tc_lift (disc_remove ppd typ' psub) in
if (not (is_identity dtm)) then
let* er = tc_from_str_err (endo_coherence dtm) in
match er with
| NoEndoReduction -> tc_ok dtm
| EndoReduced tm' ->
print_debug ( asprintf " Reduced an endo - coherence@ , " ) ;
strict_unit_normalize_tm tm'
else tc_ok dtm
Toplevel Normalization
let tc_normalize_tm ?debug:(dbg=false) tm =
let* env = tc_env in
match env.config.norm_type with
| None -> tc_unfold_tm tm
| StrictlyUnital -> strict_unit_normalize_tm ~debug:dbg tm
let tc_normalize_ty ty =
let* env = tc_env in
match env.config.norm_type with
| None -> tc_unfold_ty ty
| StrictlyUnital -> strict_unit_normalize_ty ty
let rec tc_check_ty t =
match t with
| ObjT -> tc_ok ObjT
| ArrT (typ, src, tgt) ->
let* typ' = tc_check_ty typ in
let* src' = tc_check_tm src typ' in
let* tgt' = tc_check_tm tgt typ' in
tc_ok (ArrT (typ', src', tgt'))
and tc_check_tm tm ty =
let* (tm', ty') = tc_infer_tm tm in
let* ty_nf = tc_normalize_ty ty in
let* ty_nf' = tc_normalize_ty ty' in
if (ty_nf = ty_nf') then
tc_ok tm'
else
tc_fail (TypeMismatch (tm,ty,ty'))
let * _ = tc_catch ( tc_eq_nf_ty ty ty ' )
*
* ( fun _ - > let msg = asprintf " @[<v > The term@,@,%a@,@,was expected to have type@,@,%a@,@,but was inferred to have type@,@,%a@ ] "
* pp_print_expr_tm ( term_to_expr_tm tm )
* ( term_to_expr_ty ty )
* ( term_to_expr_ty ty ' )
* in tc_fail msg ) in
*
* tc_ok tm '
*
* (fun _ -> let msg = asprintf "@[<v>The term@,@,%a@,@,was expected to have type@,@,%a@,@,but was inferred to have type@,@,%a@]"
* pp_print_expr_tm (term_to_expr_tm tm)
* pp_print_expr_ty (term_to_expr_ty ty)
* pp_print_expr_ty (term_to_expr_ty ty')
* in tc_fail msg) in
*
* tc_ok tm' *)
and tc_infer_tm tm =
match tm with
| VarT i ->
let* typ = tc_lookup_var i in
tc_ok (VarT i , typ)
| DefAppT (id, sub) -> (
let* def = tc_lookup_def id in
match def with
| TCCohDef (pd,typ) ->
let pd_ctx = pd_to_ctx pd in
let* sub' = tc_check_args sub pd_ctx in
tc_ok (DefAppT (id, sub'), subst_ty sub' typ)
| TCTermDef (ctx, typ, _) ->
let* sub' = tc_check_args sub ctx in
tc_ok (DefAppT (id, sub'), subst_ty sub' typ)
)
| CohT (pd, typ, sub) ->
let pd_ctx = pd_to_ctx pd in
let* typ' = tc_in_ctx pd_ctx
(let* rtyp = tc_check_ty typ in
tc_check_is_full pd rtyp) in
let* sub' = tc_check_args sub pd_ctx in
tc_ok (CohT (pd, typ', sub'), subst_ty sub' typ')
and tc_check_is_full pd typ =
let pd_dim = dim_pd pd in
printf " Pd : % a@ , " ( pp_print_pd pp_print_tm ) pd ;
* printf " Type : @[<hov>%a@]@ , " pp_print_ty typ ;
* printf "Type: @[<hov>%a@]@," pp_print_ty typ; *)
match typ with
| ObjT -> tc_fail (InternalError "Coherence cannot have object type")
| ArrT (btyp,src,tgt) ->
let* src_pd = tc_term_pd src in
let* tgt_pd = tc_term_pd tgt in
let typ_dim = dim_typ btyp in
if (typ_dim >= pd_dim) then
let* _ = ensure (src_pd = pd) (NonFullSource (src_pd, pd)) in
let* _ = ensure (tgt_pd = pd) (NonFullTarget (tgt_pd, pd)) in
tc_ok typ
else
let _ = ( ) in printf " Checking composite@ , " ;
let pd_src = truncate true (pd_dim - 1) pd in
let pd_tgt = truncate false (pd_dim - 1) pd in
printf " Expected source pd : % a@ , " ( pp_print_pd pp_print_tm ) pd_src ;
* printf " Provided source pd : % a@ , " ( pp_print_pd pp_print_tm ) src_pd ;
* printf " Expected target pd : % a@ , " ( pp_print_pd pp_print_tm ) pd_tgt ;
* printf " Provided target pd : % a@ , " ( pp_print_pd pp_print_tm ) tgt_pd ;
* printf "Provided source pd: %a@," (pp_print_pd pp_print_tm) src_pd;
* printf "Expected target pd: %a@," (pp_print_pd pp_print_tm) pd_tgt;
* printf "Provided target pd: %a@," (pp_print_pd pp_print_tm) tgt_pd; *)
let* _ = ensure (src_pd = pd_src) (NonFullSource (src_pd, pd)) in
let* _ = ensure (tgt_pd = pd_tgt) (NonFullTarget (tgt_pd, pd)) in
tc_ok typ
and tc_check_args sub gma =
match (sub,gma) with
| (Ext (_,_), Emp) -> tc_fail UnderApplication
| (Emp, Ext (_,_)) -> tc_fail OverApplication
| (Emp, Emp) -> tc_ok Emp
| (Ext (sub',tm), Ext (gma',typ)) ->
let* rsub = tc_check_args sub' gma' in
let typ' = subst_ty rsub typ in
let* rtm = tc_check_tm tm typ' in
tc_ok (Ext (rsub, rtm))
and tc_term_pd tm =
match tm with
| VarT i ->
let* typ = tc_lookup_var i in
tc_ok (disc_pd typ (VarT i))
| DefAppT (id , args) -> (
let* def = tc_lookup_def id in
match def with
| TCCohDef (pd,typ) ->
tc_term_pd (CohT (pd,typ,args))
| TCTermDef (_, _, tm) ->
tc_term_pd (subst_tm args tm)
)
| CohT (pd, _, sub) ->
let* pd_sub = ST.traverse tc_term_pd sub in
let* ppd = tc_from_str_err (args_to_pd pd pd_sub) in
printf " To Join : % a@ , " ( pp_print_pd ( pp_print_pd pp_print_tm ) ) ppd ;
let jres = join_pd 0 ppd in
printf " Result : % a@ , " ( pp_print_pd pp_print_tm ) jres ;
tc_ok jres
|
e01b2db368d74df25bf258262c255f4d147a84ecb69a7247a7a2d80db1a77804 | chef/chef-server | bksw_wm_base.erl | Copyright Chef Software , 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.
%%
@author Hsiao < >
@author < >
@author < >
-module(bksw_wm_base).
Complete webmachine callbacks
-export([finish_request/2,
init/1,
is_authorized/2,
malformed_request/2,
service_available/2]).
%% Helper functions
-export([create_500_response/2]).
-ifdef(TEST).
-compile([export_all, nowarn_export_all]).
-include_lib("eunit/include/eunit.hrl").
-endif.
-include("internal.hrl").
%%
Complete webmachine callbacks
%%
-define(SECONDS_IN_WEEK, 604800).
-define(NOT_APPLICABLE, "1").
init(Config) ->
{ok, bksw_conf:get_context(Config)}.
malformed_request(Req0, #context{auth_check_disabled=true} = Context) -> {false, Req0, Context};
malformed_request(Req0, #context{ } = Context) ->
HeadersRaw = mochiweb_headers:to_list(wrq:req_headers(Req0)),
Headers = process_headers(HeadersRaw),
{RequestId, Req1} = bksw_req:with_amz_request_id(Req0),
try
case proplists:get_value("authorization", Headers) of
undefined ->
% presigned url verification
% -query-string-auth.html
AuthType = presigned_url,
[XAmzAlgorithm, Credential, XAmzDate, SignedHeaderKeysString, XAmzExpiresString, IncomingSignature] =
[wrq:get_qs_value(X, "", Req1) || X <- ["X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date", "X-Amz-SignedHeaders", "X-Amz-Expires", "X-Amz-Signature"]],
case XAmzAlgorithm of
"AWS4-HMAC-SHA256" -> ok;
_ -> throw({RequestId, Req1, Context})
end,
SignedHeaders = get_signed_headers(parse_x_amz_signed_headers(SignedHeaderKeysString), Headers, []),
case check_signed_headers_common(SignedHeaders, Headers) of
true -> ok;
_ -> throw({RequestId, Req1, Context})
end;
IncomingAuth ->
% authorization header verification
% -auth-using-authorization-header.html
case bksw_sec:parse_authorization(IncomingAuth) of
{ok, [Credential, SignedHeaderKeysString, IncomingSignature]} ->
AuthType = auth_header,
XAmzDate = wrq:get_req_header("x-amz-date", Req1),
X - Amz - Expires is not used for authorization header - style authentication ,
% -query-string-auth.html
XAmzExpiresString = ?NOT_APPLICABLE,
SignedHeaders = get_signed_headers(parse_x_amz_signed_headers(SignedHeaderKeysString), Headers, []),
case check_signed_headers_authhead(SignedHeaders, Headers) of
true -> ok;
_ -> throw({RequestId, Req1, Context})
end;
_ ->
{AuthType, Credential, XAmzDate, SignedHeaders, XAmzExpiresString, IncomingSignature} =
{err, err, err, err, err, err},
throw({RequestId, Req1, Context})
end
end,
case wrq:get_req_header("Host", Req1) of
undefined -> throw({RequestId, Req1, Context});
_ -> ok
end,
[AWSAccessKeyId, CredentialScopeDate, Region | _] =
case parse_x_amz_credential(Credential) of
{error, _} -> throw({RequestId, Req1, Context});
{ok, ParseCred} -> ParseCred
end,
% -date-handling.html
DateIfUndefined = wrq:get_req_header("date", Req1),
case {_, Date} = get_check_date(XAmzDate, DateIfUndefined, CredentialScopeDate) of
{error, _} -> throw({RequestId, Req1, Context});
{ok, _} -> ok
end,
XAmzExpiresInt = list_to_integer(XAmzExpiresString),
case XAmzExpiresInt > 0 andalso XAmzExpiresInt =< ?SECONDS_IN_WEEK of
true -> ok;
_ -> throw({RequestId, Req1, Context})
end,
{false, Req1, Context#context{
aws_access_key_id = AWSAccessKeyId,
auth_type = AuthType,
date = Date,
incoming_sig = IncomingSignature,
region = Region,
signed_headers = SignedHeaders,
x_amz_expires_int = XAmzExpiresInt,
x_amz_expires_str = XAmzExpiresString}}
catch
throw:{RequestId, Req1, Context} ->
bksw_sec:encode_access_denied_error_response(RequestId, Req1, Context)
end.
is_authorized(Rq, Ctx) ->
bksw_sec:is_authorized(Rq, Ctx).
finish_request(Rq0, Ctx) ->
try
case wrq:response_code(Rq0) of
500 ->
Rq1 = create_500_response(Rq0, Ctx),
{true, Rq1, Ctx};
Ensure we do n't tell upstream servers to cache 404s
C when C >= 400 andalso C < 500 ->
Rq1 = wrq:remove_resp_header("Cache-Control", Rq0),
{true, Rq1, Ctx};
_ ->
{true, Rq0, Ctx}
end
catch
X:Y:Stacktrace ->
error_logger:error_report({X, Y, Stacktrace})
end.
service_available(Req, #context{reqid_header_name = HeaderName} = State) ->
%% Extract or generate a request id
ReqId = oc_wm_request:read_req_id(HeaderName, Req),
%% If no UserId is generated, this will return undefined. The opscoderl_wm request
%% logger will omit user=; downstream.
UserId = wrq:get_req_header("x-ops-userid", Req),
Req0 = oc_wm_request:add_notes([{req_id, ReqId},
{user, UserId}], Req),
{true, Req0, State#context{reqid = ReqId}}.
%%
%% Helper functions
%%
% -v4-header-based-auth.html
-spec check_signed_headers_authhead(proplists:proplist(), proplists:proplist()) -> boolean().
check_signed_headers_authhead(SignedHeaders, Headers) ->
check_signed_headers_common(SignedHeaders, Headers) andalso
% x-amz-content-sha256 header is required
proplists:is_defined("x-amz-content-sha256", SignedHeaders) andalso
% if content-type header is present in request, it is required
case proplists:is_defined("content-type", Headers) of
true -> proplists:is_defined("content-type", SignedHeaders);
_ -> true
end.
% required signed headers common to both authorization header verification
% and presigned url verification.
% -query-string-auth.html
-spec check_signed_headers_common(proplists:proplist(), proplists:proplist()) -> boolean().
check_signed_headers_common(SignedHeaders, Headers) ->
% host header is required
proplists:is_defined("host", SignedHeaders) andalso
% any x-amz-* headers present in request are required
[] == [Key || {Key, _} <- Headers, is_amz(Key), not proplists:is_defined(Key, SignedHeaders)].
% -date-handling.html
-spec get_check_date(ISO8601Date::string() | undefined, DateIfUndefined::string(), string()) -> {ok, string()} | {error, get_check_date}.
get_check_date(ISO8601Date, DateIfUndefined, [Y1, Y2, Y3, Y4, M1, M2, D1, D2]) ->
Date = case ISO8601Date of
undefined -> DateIfUndefined;
_ -> ISO8601Date
end,
case Date of
[Y1, Y2, Y3, Y4, M1, M2, D1, D2, $T, _, _, _, _, _, _, $Z] -> {ok, Date};
_ -> {error, get_check_date}
end.
% @doc get key-value pairs (headers) associated with specified keys.
for each key , get first occurance of key - value . for duplicated
% keys, get corresponding key-value pairs. results are undefined
for nonexistent ) .
-spec get_signed_headers(proplist ( ) , proplist ( ) , proplist ( ) ) - > proplist ( ) . % for erlang20 +
-spec get_signed_headers(SignedHeaderKeys::[string()], Headers::[tuple()], SignedHeaders::[tuple()]) -> [tuple()].
get_signed_headers([], _, SignedHeaders) -> lists:reverse(SignedHeaders);
get_signed_headers(_, [], SignedHeaders) -> lists:reverse(SignedHeaders);
get_signed_headers([Key | SignedHeaderKeys], Headers0, SignedHeaders) ->
{_, SignedHeader, Headers} = lists:keytake(Key, 1, Headers0),
get_signed_headers(SignedHeaderKeys, Headers, [SignedHeader | SignedHeaders]).
-spec is_amz(string()) -> boolean().
is_amz([$x, $-, $a, $m, $z, $- | _]) ->
true;
is_amz([$X, $-, $A, $m, $z, $- | _]) ->
true;
is_amz(_) ->
false.
% @doc split credentials string into component parts
% Cred = "<access-key-id>/<date>/<AWS-region>/<AWS-service>/aws4_request"
-spec parse_x_amz_credential(string()) -> {ok, [string()]} | {error, parse_x_amz_credential}.
parse_x_amz_credential(Cred) ->
Parse = string:split(Cred, "/", all),
case Parse of
[_access_key_id, _date, _aws_region, "s3", "aws4_request"] -> {ok, Parse};
_ -> {error, parse_x_amz_credential}
end.
% @doc split signed header string into component parts. return empty string on empty string.
% Headers = "<header1>;<header2>;...<headerN>"
-spec parse_x_amz_signed_headers(string()) -> [string()].
parse_x_amz_signed_headers(Headers) ->
string:split(Headers, ";", all).
% @doc convert the keys of key-value pairs to lowercase strings
-spec process_headers(Headers::[tuple()]) -> [tuple()].
process_headers(Headers) ->
[{string:casefold(
case is_atom(Key) of
true -> atom_to_list(Key);
_ -> Key
end), Val} || {Key, Val} <- Headers].
create_500_response(Rq0, _Ctx) ->
%% sanitize response body
Msg = <<"internal service error">>,
Rq1 = wrq:set_resp_header("Content-Type",
"text/plain", Rq0),
wrq:set_resp_body(Msg, Rq1).
| null | https://raw.githubusercontent.com/chef/chef-server/775e6b24229e46884dcd8801e0534a07627327b2/src/bookshelf/src/bksw_wm_base.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.
Helper functions
presigned url verification
-query-string-auth.html
authorization header verification
-auth-using-authorization-header.html
-query-string-auth.html
-date-handling.html
Extract or generate a request id
If no UserId is generated, this will return undefined. The opscoderl_wm request
logger will omit user=; downstream.
Helper functions
-v4-header-based-auth.html
x-amz-content-sha256 header is required
if content-type header is present in request, it is required
required signed headers common to both authorization header verification
and presigned url verification.
-query-string-auth.html
host header is required
any x-amz-* headers present in request are required
-date-handling.html
@doc get key-value pairs (headers) associated with specified keys.
keys, get corresponding key-value pairs. results are undefined
for erlang20 +
@doc split credentials string into component parts
Cred = "<access-key-id>/<date>/<AWS-region>/<AWS-service>/aws4_request"
@doc split signed header string into component parts. return empty string on empty string.
Headers = "<header1>;<header2>;...<headerN>"
@doc convert the keys of key-value pairs to lowercase strings
sanitize response body | Copyright Chef Software , 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
@author Hsiao < >
@author < >
@author < >
-module(bksw_wm_base).
Complete webmachine callbacks
-export([finish_request/2,
init/1,
is_authorized/2,
malformed_request/2,
service_available/2]).
-export([create_500_response/2]).
-ifdef(TEST).
-compile([export_all, nowarn_export_all]).
-include_lib("eunit/include/eunit.hrl").
-endif.
-include("internal.hrl").
Complete webmachine callbacks
-define(SECONDS_IN_WEEK, 604800).
-define(NOT_APPLICABLE, "1").
init(Config) ->
{ok, bksw_conf:get_context(Config)}.
malformed_request(Req0, #context{auth_check_disabled=true} = Context) -> {false, Req0, Context};
malformed_request(Req0, #context{ } = Context) ->
HeadersRaw = mochiweb_headers:to_list(wrq:req_headers(Req0)),
Headers = process_headers(HeadersRaw),
{RequestId, Req1} = bksw_req:with_amz_request_id(Req0),
try
case proplists:get_value("authorization", Headers) of
undefined ->
AuthType = presigned_url,
[XAmzAlgorithm, Credential, XAmzDate, SignedHeaderKeysString, XAmzExpiresString, IncomingSignature] =
[wrq:get_qs_value(X, "", Req1) || X <- ["X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date", "X-Amz-SignedHeaders", "X-Amz-Expires", "X-Amz-Signature"]],
case XAmzAlgorithm of
"AWS4-HMAC-SHA256" -> ok;
_ -> throw({RequestId, Req1, Context})
end,
SignedHeaders = get_signed_headers(parse_x_amz_signed_headers(SignedHeaderKeysString), Headers, []),
case check_signed_headers_common(SignedHeaders, Headers) of
true -> ok;
_ -> throw({RequestId, Req1, Context})
end;
IncomingAuth ->
case bksw_sec:parse_authorization(IncomingAuth) of
{ok, [Credential, SignedHeaderKeysString, IncomingSignature]} ->
AuthType = auth_header,
XAmzDate = wrq:get_req_header("x-amz-date", Req1),
X - Amz - Expires is not used for authorization header - style authentication ,
XAmzExpiresString = ?NOT_APPLICABLE,
SignedHeaders = get_signed_headers(parse_x_amz_signed_headers(SignedHeaderKeysString), Headers, []),
case check_signed_headers_authhead(SignedHeaders, Headers) of
true -> ok;
_ -> throw({RequestId, Req1, Context})
end;
_ ->
{AuthType, Credential, XAmzDate, SignedHeaders, XAmzExpiresString, IncomingSignature} =
{err, err, err, err, err, err},
throw({RequestId, Req1, Context})
end
end,
case wrq:get_req_header("Host", Req1) of
undefined -> throw({RequestId, Req1, Context});
_ -> ok
end,
[AWSAccessKeyId, CredentialScopeDate, Region | _] =
case parse_x_amz_credential(Credential) of
{error, _} -> throw({RequestId, Req1, Context});
{ok, ParseCred} -> ParseCred
end,
DateIfUndefined = wrq:get_req_header("date", Req1),
case {_, Date} = get_check_date(XAmzDate, DateIfUndefined, CredentialScopeDate) of
{error, _} -> throw({RequestId, Req1, Context});
{ok, _} -> ok
end,
XAmzExpiresInt = list_to_integer(XAmzExpiresString),
case XAmzExpiresInt > 0 andalso XAmzExpiresInt =< ?SECONDS_IN_WEEK of
true -> ok;
_ -> throw({RequestId, Req1, Context})
end,
{false, Req1, Context#context{
aws_access_key_id = AWSAccessKeyId,
auth_type = AuthType,
date = Date,
incoming_sig = IncomingSignature,
region = Region,
signed_headers = SignedHeaders,
x_amz_expires_int = XAmzExpiresInt,
x_amz_expires_str = XAmzExpiresString}}
catch
throw:{RequestId, Req1, Context} ->
bksw_sec:encode_access_denied_error_response(RequestId, Req1, Context)
end.
is_authorized(Rq, Ctx) ->
bksw_sec:is_authorized(Rq, Ctx).
finish_request(Rq0, Ctx) ->
try
case wrq:response_code(Rq0) of
500 ->
Rq1 = create_500_response(Rq0, Ctx),
{true, Rq1, Ctx};
Ensure we do n't tell upstream servers to cache 404s
C when C >= 400 andalso C < 500 ->
Rq1 = wrq:remove_resp_header("Cache-Control", Rq0),
{true, Rq1, Ctx};
_ ->
{true, Rq0, Ctx}
end
catch
X:Y:Stacktrace ->
error_logger:error_report({X, Y, Stacktrace})
end.
service_available(Req, #context{reqid_header_name = HeaderName} = State) ->
ReqId = oc_wm_request:read_req_id(HeaderName, Req),
UserId = wrq:get_req_header("x-ops-userid", Req),
Req0 = oc_wm_request:add_notes([{req_id, ReqId},
{user, UserId}], Req),
{true, Req0, State#context{reqid = ReqId}}.
-spec check_signed_headers_authhead(proplists:proplist(), proplists:proplist()) -> boolean().
check_signed_headers_authhead(SignedHeaders, Headers) ->
check_signed_headers_common(SignedHeaders, Headers) andalso
proplists:is_defined("x-amz-content-sha256", SignedHeaders) andalso
case proplists:is_defined("content-type", Headers) of
true -> proplists:is_defined("content-type", SignedHeaders);
_ -> true
end.
-spec check_signed_headers_common(proplists:proplist(), proplists:proplist()) -> boolean().
check_signed_headers_common(SignedHeaders, Headers) ->
proplists:is_defined("host", SignedHeaders) andalso
[] == [Key || {Key, _} <- Headers, is_amz(Key), not proplists:is_defined(Key, SignedHeaders)].
-spec get_check_date(ISO8601Date::string() | undefined, DateIfUndefined::string(), string()) -> {ok, string()} | {error, get_check_date}.
get_check_date(ISO8601Date, DateIfUndefined, [Y1, Y2, Y3, Y4, M1, M2, D1, D2]) ->
Date = case ISO8601Date of
undefined -> DateIfUndefined;
_ -> ISO8601Date
end,
case Date of
[Y1, Y2, Y3, Y4, M1, M2, D1, D2, $T, _, _, _, _, _, _, $Z] -> {ok, Date};
_ -> {error, get_check_date}
end.
for each key , get first occurance of key - value . for duplicated
for nonexistent ) .
-spec get_signed_headers(SignedHeaderKeys::[string()], Headers::[tuple()], SignedHeaders::[tuple()]) -> [tuple()].
get_signed_headers([], _, SignedHeaders) -> lists:reverse(SignedHeaders);
get_signed_headers(_, [], SignedHeaders) -> lists:reverse(SignedHeaders);
get_signed_headers([Key | SignedHeaderKeys], Headers0, SignedHeaders) ->
{_, SignedHeader, Headers} = lists:keytake(Key, 1, Headers0),
get_signed_headers(SignedHeaderKeys, Headers, [SignedHeader | SignedHeaders]).
-spec is_amz(string()) -> boolean().
is_amz([$x, $-, $a, $m, $z, $- | _]) ->
true;
is_amz([$X, $-, $A, $m, $z, $- | _]) ->
true;
is_amz(_) ->
false.
-spec parse_x_amz_credential(string()) -> {ok, [string()]} | {error, parse_x_amz_credential}.
parse_x_amz_credential(Cred) ->
Parse = string:split(Cred, "/", all),
case Parse of
[_access_key_id, _date, _aws_region, "s3", "aws4_request"] -> {ok, Parse};
_ -> {error, parse_x_amz_credential}
end.
-spec parse_x_amz_signed_headers(string()) -> [string()].
parse_x_amz_signed_headers(Headers) ->
string:split(Headers, ";", all).
-spec process_headers(Headers::[tuple()]) -> [tuple()].
process_headers(Headers) ->
[{string:casefold(
case is_atom(Key) of
true -> atom_to_list(Key);
_ -> Key
end), Val} || {Key, Val} <- Headers].
create_500_response(Rq0, _Ctx) ->
Msg = <<"internal service error">>,
Rq1 = wrq:set_resp_header("Content-Type",
"text/plain", Rq0),
wrq:set_resp_body(Msg, Rq1).
|
b4af5867ea7b4b1a721f93400dbdfbddeefa7f0cccca2660d7abbea31df6f369 | rizo/streaming-zoo | iterator.ml |
module A = struct
type ('a, 's) iter = ('s * ('s -> ('a * 's) option))
let take n ((init, next)) =
let next' (i, s) =
if i <= 0 then None
else match next s with
| Some (a, s') -> Some (a, (i - 1, s'))
| None -> None in
((n, init), next')
let init n f =
let next i =
if i = n then None
else Some (f i, i + 1) in
(0, next)
let count () =
let next i = Some (i, i + 1) in
(0, next)
let map f ((init, next)) =
let next' s =
match next s with
| Some (a, s') -> Some (f a, s')
| None -> None in
(init, next')
let filter p ((init, next)) =
let rec next' s =
match next s with
| Some (a, s') ->
if p a then Some (a, s')
else next s'
| None -> None in
(init, next')
let fold f acc ((init, next)) =
let rec loop acc s =
match next s with
| None -> acc
| Some (a, s') -> loop (f acc a) s' in
loop acc init
let to_list ((s0, next)) =
let rec loop acc s =
match next s with
| None -> List.rev acc
| Some (x, s') -> loop (x :: acc) s' in
loop [] s0
let of_list l =
let next = function
| [] -> None
| x::xs -> Some (x, xs) in
(l, next)
end
module B = struct
type ('a, 's) iter =
('s * ('s -> ('a * 's) option))
let take n ((init, next)) =
let next' (i, s) =
match next s with
| Some (a, s') -> Some (a, (i - 1, s'))
| None -> None in
((n, init), next')
let count () =
let next i = Some (i, i + 1) in
(0, next)
let map f ((init, next)) =
let next' s =
match next s with
| Some (a, s') -> Some (f a, s')
| None -> None in
(init, next')
let filter p ((init, next)) =
let rec next' s =
match next s with
| Some (a, s') ->
if p a then Some (a, s')
else next s'
| None -> None in
(init, next')
let fold f acc ((init, next)) =
let rec loop acc s =
match next s with
| None -> acc
| Some (a, s') -> loop (f acc a) s' in
loop acc init
end
module C = struct
let count k =
let next i = Some (i, i + 1) in
k (0, next)
let map f (s0, next) k =
let next' s =
match next s with
| Some (a, s') -> Some (f a, s')
| None -> None in
k (s0, next')
let filter p (init, next) k =
let rec next' s =
match next s with
| Some (a, s') ->
if p a then Some (a, s')
else next s'
| None -> None in
k (init, next')
let take n (init, next) k =
let next' (i, s) =
if i <= 0 then None
else match next s with
| Some (a, s') -> Some (a, (i - 1, s'))
| None -> None in
k ((n, init), next')
let fold f acc (s0, next) =
let rec loop acc s =
match next s with
| Some (a, s') -> loop (f acc a) s'
| None -> acc in
loop acc s0
let (>>>) f x = f x
end
module D = struct
let count k =
let next i = Some (i, i + 1) in
k 0 next
let map f s0 next k =
let next' s =
match next s with
| Some (a, s') -> Some (f a, s')
| None -> None in
k s0 next'
let filter p init next k =
let rec next' s =
match next s with
| Some (a, s') ->
if p a then Some (a, s')
else next s'
| None -> None in
k init next'
let take n init next k =
let next' (i, s) =
if i <= 0 then None
else match next s with
| Some (a, s') -> Some (a, (i - 1, s'))
| None -> None in
k (n, init) next'
let fold f acc s0 next =
let rec loop acc s =
match next s with
| Some (a, s') -> loop (f acc a) s'
| None -> acc in
loop acc s0
let (>>>) f x = f x
end
include A
| null | https://raw.githubusercontent.com/rizo/streaming-zoo/bf586c8b986a41353f5e3963de01047b83e7649a/src/iterator.ml | ocaml |
module A = struct
type ('a, 's) iter = ('s * ('s -> ('a * 's) option))
let take n ((init, next)) =
let next' (i, s) =
if i <= 0 then None
else match next s with
| Some (a, s') -> Some (a, (i - 1, s'))
| None -> None in
((n, init), next')
let init n f =
let next i =
if i = n then None
else Some (f i, i + 1) in
(0, next)
let count () =
let next i = Some (i, i + 1) in
(0, next)
let map f ((init, next)) =
let next' s =
match next s with
| Some (a, s') -> Some (f a, s')
| None -> None in
(init, next')
let filter p ((init, next)) =
let rec next' s =
match next s with
| Some (a, s') ->
if p a then Some (a, s')
else next s'
| None -> None in
(init, next')
let fold f acc ((init, next)) =
let rec loop acc s =
match next s with
| None -> acc
| Some (a, s') -> loop (f acc a) s' in
loop acc init
let to_list ((s0, next)) =
let rec loop acc s =
match next s with
| None -> List.rev acc
| Some (x, s') -> loop (x :: acc) s' in
loop [] s0
let of_list l =
let next = function
| [] -> None
| x::xs -> Some (x, xs) in
(l, next)
end
module B = struct
type ('a, 's) iter =
('s * ('s -> ('a * 's) option))
let take n ((init, next)) =
let next' (i, s) =
match next s with
| Some (a, s') -> Some (a, (i - 1, s'))
| None -> None in
((n, init), next')
let count () =
let next i = Some (i, i + 1) in
(0, next)
let map f ((init, next)) =
let next' s =
match next s with
| Some (a, s') -> Some (f a, s')
| None -> None in
(init, next')
let filter p ((init, next)) =
let rec next' s =
match next s with
| Some (a, s') ->
if p a then Some (a, s')
else next s'
| None -> None in
(init, next')
let fold f acc ((init, next)) =
let rec loop acc s =
match next s with
| None -> acc
| Some (a, s') -> loop (f acc a) s' in
loop acc init
end
module C = struct
let count k =
let next i = Some (i, i + 1) in
k (0, next)
let map f (s0, next) k =
let next' s =
match next s with
| Some (a, s') -> Some (f a, s')
| None -> None in
k (s0, next')
let filter p (init, next) k =
let rec next' s =
match next s with
| Some (a, s') ->
if p a then Some (a, s')
else next s'
| None -> None in
k (init, next')
let take n (init, next) k =
let next' (i, s) =
if i <= 0 then None
else match next s with
| Some (a, s') -> Some (a, (i - 1, s'))
| None -> None in
k ((n, init), next')
let fold f acc (s0, next) =
let rec loop acc s =
match next s with
| Some (a, s') -> loop (f acc a) s'
| None -> acc in
loop acc s0
let (>>>) f x = f x
end
module D = struct
let count k =
let next i = Some (i, i + 1) in
k 0 next
let map f s0 next k =
let next' s =
match next s with
| Some (a, s') -> Some (f a, s')
| None -> None in
k s0 next'
let filter p init next k =
let rec next' s =
match next s with
| Some (a, s') ->
if p a then Some (a, s')
else next s'
| None -> None in
k init next'
let take n init next k =
let next' (i, s) =
if i <= 0 then None
else match next s with
| Some (a, s') -> Some (a, (i - 1, s'))
| None -> None in
k (n, init) next'
let fold f acc s0 next =
let rec loop acc s =
match next s with
| Some (a, s') -> loop (f acc a) s'
| None -> acc in
loop acc s0
let (>>>) f x = f x
end
include A
| |
6a656a2249205510f33010294f99ae07d27a90449da2b2bf2f77464c9c7f6ff3 | cardmagic/lucash | errno.scm | ;;; Errno constant definitions.
Copyright ( c ) 1993 by . See file COPYING .
These are the correct values for the GNU .
(define (hurd-errno n)
(bitwise-ior (arithmetic-shift #x10 26) (bitwise-and n #x3fff)))
(define errno/perm (hurd-errno 1)) ; Operation not permitted
(define errno/noent (hurd-errno 2)) ; No such file or directory
(define errno/srch (hurd-errno 3)) ; No such process
(define errno/intr (hurd-errno 4)) ; Interrupted system call
(define errno/io (hurd-errno 5)) ; Input/output error
(define errno/nxio (hurd-errno 6)) ; No such device or address
(define errno/2big (hurd-errno 7)) ; Argument list too long
Exec format error
(define errno/badf (hurd-errno 9)) ; Bad file descriptor
(define errno/child (hurd-errno 10)) ; No child processes
Resource deadlock avoided
(define errno/nomem (hurd-errno 12)) ; Cannot allocate memory
(define errno/acces (hurd-errno 13)) ; Permission denied
(define errno/fault (hurd-errno 14)) ; Bad address
(define errno/notblk (hurd-errno 15)) ; Block device required
(define errno/busy (hurd-errno 16)) ; Device or resource busy
(define errno/exist (hurd-errno 17)) ; File exists
Invalid cross - device link
(define errno/nodev (hurd-errno 19)) ; No such device
(define errno/notdir (hurd-errno 20)) ; Not a directory
(define errno/isdir (hurd-errno 21)) ; Is a directory
Invalid argument
(define errno/nfile (hurd-errno 23)) ; Too many open files in system
(define errno/mfile (hurd-errno 24)) ; Too many open files
(define errno/notty (hurd-errno 25)) ; Inappropriate ioctl for device
(define errno/txtbsy (hurd-errno 26)) ; Text file busy
(define errno/fbig (hurd-errno 27)) ; File too large
(define errno/nospc (hurd-errno 28)) ; No space left on device
(define errno/spipe (hurd-errno 29)) ; Illegal seek
(define errno/rofs (hurd-errno 30)) ; Read-only file system
(define errno/mlink (hurd-errno 31)) ; Too many links
(define errno/pipe (hurd-errno 32)) ; Broken pipe
(define errno/dom (hurd-errno 33)) ; Numerical argument out of domain
(define errno/range (hurd-errno 34)) ; Numerical result out of range
(define errno/again (hurd-errno 35)) ; Resource temporarily unavailable
(define errno/wouldblock (hurd-errno 35)) ; Operation would block
(define errno/inprogress (hurd-errno 36)) ; Operation now in progress
(define errno/already (hurd-errno 37)) ; Operation already in progress
(define errno/notsock (hurd-errno 38)) ; Socket operation on non-socket
(define errno/destaddrreq (hurd-errno 39)) ; Destination address required
(define errno/msgsize (hurd-errno 40)) ; Message too long
(define errno/prototype (hurd-errno 41)) ; Protocol wrong type for socket
(define errno/noprotoopt (hurd-errno 42)) ; Protocol not available
(define errno/protonosupport (hurd-errno 43)) ; Protocol not supported
(define errno/socktnosupport (hurd-errno 44)) ; Socket type not supported
(define errno/opnotsupp (hurd-errno 45)) ; Operation not supported
Protocol family not supported
(define errno/afnosupport (hurd-errno 47)) ; Address family not supported by protocol
(define errno/addrinuse (hurd-errno 48)) ; Address already in use
(define errno/addrnotavail (hurd-errno 49)) ; Cannot assign requested address
(define errno/netdown (hurd-errno 50)) ; Network is down
Network is unreachable
Network dropped connection on reset
(define errno/connaborted (hurd-errno 53)) ; Software caused connection abort
(define errno/connreset (hurd-errno 54)) ; Connection reset by peer
(define errno/nobufs (hurd-errno 55)) ; No buffer space available
(define errno/isconn (hurd-errno 56)) ; Transport endpoint is already connected
(define errno/notconn (hurd-errno 57)) ; Transport endpoint is not connected
(define errno/shutdown (hurd-errno 58)) ; Cannot send after transport endpoint shutdown
(define errno/toomanyrefs (hurd-errno 59)) ; Too many references: cannot splice
Connection timed out
Connection refused
(define errno/loop (hurd-errno 62)) ; Too many levels of symbolic links
(define errno/nametoolong (hurd-errno 63)) ; File name too long
(define errno/hostdown (hurd-errno 64)) ; Host is down
(define errno/hostunreach (hurd-errno 65)) ; No route to host
(define errno/notempty (hurd-errno 66)) ; Directory not empty
(define errno/proclim (hurd-errno 67)) ; Too many processes
(define errno/users (hurd-errno 68)) ; Too many users
(define errno/dquot (hurd-errno 69)) ; Disk quota exceeded
Stale NFS file handle
(define errno/remote (hurd-errno 71)) ; Object is remote
(define errno/badrpc (hurd-errno 72)) ; RPC struct is bad
(define errno/rpcmismatch (hurd-errno 73)) ; RPC version wrong
(define errno/progunavail (hurd-errno 74)) ; RPC program not available
(define errno/progmismatch (hurd-errno 75)) ; RPC program version wrong
(define errno/procunavail (hurd-errno 76)) ; RPC bad procedure for program
(define errno/nolck (hurd-errno 77)) ; No locks available
(define errno/nosys (hurd-errno 78)) ; Function not implemented
(define errno/ftype (hurd-errno 79)) ; Inappropriate file type or format
(define errno/auth (hurd-errno 80)) ; Authentication error
(define errno/needauth (hurd-errno 81)) ; Need authenticator
(define errno/background (hurd-errno 100)) ; Inappropriate operation for background process
(define errno/died (hurd-errno 101)) ; Translator died
(define errno/d (hurd-errno 102)) ; ?
(define errno/gregious (hurd-errno 103)) ; You really blew it this time
(define errno/ieio (hurd-errno 104)) ; Computer bought the farm
(define errno/gratuitous (hurd-errno 105)) ; Gratuitous error
Invalid or incomplete or wide character
(define errno/badmsg (hurd-errno 107)) ; Bad message
(define errno/idrm (hurd-errno 108)) ; Identifier removed
attempted
(define errno/nodata (hurd-errno 110)) ; No data available
(define errno/nolink (hurd-errno 111)) ; Link has been severed
(define errno/nomsg (hurd-errno 112)) ; No message of desired type
(define errno/nosr (hurd-errno 113)) ; Out of streams resources
(define errno/nostr (hurd-errno 114)) ; Device not a stream
(define errno/overflow (hurd-errno 115)) ; Value too large for defined data type
Protocol error
Timer expired
(define errno/canceled (hurd-errno 118)) ; Operation cancelled
(define errno/notsup (hurd-errno 118)) ; Not supported
| null | https://raw.githubusercontent.com/cardmagic/lucash/0452d410430d12140c14948f7f583624f819cdad/reference/scsh-0.6.6/scsh/gnu/errno.scm | scheme | Errno constant definitions.
Operation not permitted
No such file or directory
No such process
Interrupted system call
Input/output error
No such device or address
Argument list too long
Bad file descriptor
No child processes
Cannot allocate memory
Permission denied
Bad address
Block device required
Device or resource busy
File exists
No such device
Not a directory
Is a directory
Too many open files in system
Too many open files
Inappropriate ioctl for device
Text file busy
File too large
No space left on device
Illegal seek
Read-only file system
Too many links
Broken pipe
Numerical argument out of domain
Numerical result out of range
Resource temporarily unavailable
Operation would block
Operation now in progress
Operation already in progress
Socket operation on non-socket
Destination address required
Message too long
Protocol wrong type for socket
Protocol not available
Protocol not supported
Socket type not supported
Operation not supported
Address family not supported by protocol
Address already in use
Cannot assign requested address
Network is down
Software caused connection abort
Connection reset by peer
No buffer space available
Transport endpoint is already connected
Transport endpoint is not connected
Cannot send after transport endpoint shutdown
Too many references: cannot splice
Too many levels of symbolic links
File name too long
Host is down
No route to host
Directory not empty
Too many processes
Too many users
Disk quota exceeded
Object is remote
RPC struct is bad
RPC version wrong
RPC program not available
RPC program version wrong
RPC bad procedure for program
No locks available
Function not implemented
Inappropriate file type or format
Authentication error
Need authenticator
Inappropriate operation for background process
Translator died
?
You really blew it this time
Computer bought the farm
Gratuitous error
Bad message
Identifier removed
No data available
Link has been severed
No message of desired type
Out of streams resources
Device not a stream
Value too large for defined data type
Operation cancelled
Not supported | Copyright ( c ) 1993 by . See file COPYING .
These are the correct values for the GNU .
(define (hurd-errno n)
(bitwise-ior (arithmetic-shift #x10 26) (bitwise-and n #x3fff)))
Exec format error
Resource deadlock avoided
Invalid cross - device link
Invalid argument
Protocol family not supported
Network is unreachable
Network dropped connection on reset
Connection timed out
Connection refused
Stale NFS file handle
Invalid or incomplete or wide character
attempted
Protocol error
Timer expired
|
4e06bd11c7f4d9567a2147e6656727478c1547160b22e2388edb0a56d3083476 | mishun/tangles | PatternMatching.hs | # LANGUAGE FlexibleContexts , FlexibleInstances , RankNTypes #
module Math.Topology.KnotTh.Moves.PatternMatching
( Pattern
, PatternM
, subTangleP
, crossingP
, connectionP
, reconnectP
, makePattern
, searchMoves
) where
import Control.Applicative (Alternative(..))
import Control.Monad (MonadPlus(..), unless, guard)
import qualified Control.Monad.State as State
import Data.Maybe (mapMaybe)
import Data.List ((\\), subsequences)
import qualified Data.Set as Set
import qualified Data.Vector.Unboxed as UV
import Math.Topology.KnotTh.Tangle
import Math.Topology.KnotTh.Moves.ModifyDSL
data PatternS a =
PatternS ([Dart Tangle a] -> [Dart Tangle a]) (Tangle a) [Vertex Tangle a]
newtype PatternM s a x =
PatternM
{ runPatternMatching :: PatternS a -> [(PatternS a, x)]
}
newtype Pattern a x =
Pattern
{ patternMatching :: Tangle a -> [x]
}
instance Functor (PatternM s a) where
fmap f x = PatternM (map (fmap f) . runPatternMatching x)
instance Applicative (PatternM s a) where
pure = return
(<*>) f' x' = do
f <- f'
x <- x'
return $! f x
instance Monad (PatternM s a) where
return x = PatternM (\ s -> [(s, x)])
(>>=) val act = PatternM (concatMap (\ (s', x) -> runPatternMatching (act x) s') . runPatternMatching val)
instance Alternative (PatternM s a) where
empty = PatternM (const [])
(<|>) a b = PatternM (\ s -> runPatternMatching a s ++ runPatternMatching b s)
instance MonadPlus (PatternM s a) where
mzero = empty
mplus = (<|>)
subTangleP :: Int -> PatternM s a ([Dart Tangle a], [Vertex Tangle a])
subTangleP legs =
PatternM $ \ (PatternS reorder tangle cs) -> do
subList <- subsequences cs
guard $ not $ null subList
let sub = UV.replicate (1 + numberOfVertices tangle) False
UV.// map (\ d -> (vertexIndex d, True)) subList
guard $
let mask = State.execState (dfs $ head subList) Set.empty
dfs c = do
visited <- State.gets $ Set.member c
unless visited $ do
State.modify $ Set.insert c
mapM_ dfs $
filter ((sub UV.!) . vertexIndex) $
mapMaybe maybeEndVertex $ outcomingDarts c
in all (`Set.member` mask) subList
let onBorder xy =
let yx = opposite xy
x = beginVertex xy
y = beginVertex yx
in isDart xy && (sub UV.! vertexIndex x) && (isLeg yx || not (sub UV.! vertexIndex y))
let border = filter onBorder $ concatMap outcomingDarts cs
guard $ legs == length border
let borderCCW =
let traverseNext = nextCW . opposite
restoreOutcoming out d | d == head border = d : out
| onBorder d = restoreOutcoming (d : out) (opposite d)
| otherwise = restoreOutcoming out (traverseNext d)
in restoreOutcoming [] (opposite $ head border)
guard $ legs == length borderCCW
i <- [0 .. legs - 1]
return (PatternS reorder tangle (cs \\ subList), (reorder $ drop i borderCCW ++ take i borderCCW, subList))
crossingP :: PatternM s a ([Dart Tangle a], Vertex Tangle a)
crossingP =
PatternM $ \ (PatternS reorder tangle cs) ->
let try res _ [] = res
try res skipped (cur : rest) =
let next = PatternS reorder tangle (skipped ++ rest)
sh i = let od = outcomingDarts cur
in reorder $ drop i od ++ take i od
in try ((next, (sh 0, cur)) : (next, (sh 1, cur)) : (next, (sh 2, cur)) : (next, (sh 3, cur)) : res) (cur : skipped) rest
in try [] [] cs
connectionP :: [(Dart Tangle a, Dart Tangle a)] -> PatternM s a ()
connectionP = mapM_ (\ (a, b) -> guard (opposite a == b))
reconnectP :: (Show a) => (forall s. ModifyM Tangle a s ()) -> PatternM s' a (Tangle a)
reconnectP m =
PatternM $ \ s@(PatternS _ tangle _) ->
[(s, modifyKnot tangle m)]
makePattern :: Bool -> (forall s. PatternM s a x) -> Pattern a x
makePattern mirrored pattern =
Pattern $ \ tangle -> do
reorder <- id : [reverse | mirrored]
let initial = PatternS reorder tangle (allVertices tangle)
(_, res) <- runPatternMatching pattern initial
return res
class (Knotted k) => PatternMatching k where
searchMoves :: [Pattern a (Tangle a)] -> k a -> [k a]
instance PatternMatching Tangle where
searchMoves patterns tangle = do
pattern <- patterns
patternMatching pattern tangle
instance PatternMatching Tangle0 where
searchMoves patterns =
map tangle' . searchMoves patterns . toTangle
| null | https://raw.githubusercontent.com/mishun/tangles/9af39dd48e3dcc5e3944f8d060c8769ff3d81d02/src/Math/Topology/KnotTh/Moves/PatternMatching.hs | haskell | # LANGUAGE FlexibleContexts , FlexibleInstances , RankNTypes #
module Math.Topology.KnotTh.Moves.PatternMatching
( Pattern
, PatternM
, subTangleP
, crossingP
, connectionP
, reconnectP
, makePattern
, searchMoves
) where
import Control.Applicative (Alternative(..))
import Control.Monad (MonadPlus(..), unless, guard)
import qualified Control.Monad.State as State
import Data.Maybe (mapMaybe)
import Data.List ((\\), subsequences)
import qualified Data.Set as Set
import qualified Data.Vector.Unboxed as UV
import Math.Topology.KnotTh.Tangle
import Math.Topology.KnotTh.Moves.ModifyDSL
data PatternS a =
PatternS ([Dart Tangle a] -> [Dart Tangle a]) (Tangle a) [Vertex Tangle a]
newtype PatternM s a x =
PatternM
{ runPatternMatching :: PatternS a -> [(PatternS a, x)]
}
newtype Pattern a x =
Pattern
{ patternMatching :: Tangle a -> [x]
}
instance Functor (PatternM s a) where
fmap f x = PatternM (map (fmap f) . runPatternMatching x)
instance Applicative (PatternM s a) where
pure = return
(<*>) f' x' = do
f <- f'
x <- x'
return $! f x
instance Monad (PatternM s a) where
return x = PatternM (\ s -> [(s, x)])
(>>=) val act = PatternM (concatMap (\ (s', x) -> runPatternMatching (act x) s') . runPatternMatching val)
instance Alternative (PatternM s a) where
empty = PatternM (const [])
(<|>) a b = PatternM (\ s -> runPatternMatching a s ++ runPatternMatching b s)
instance MonadPlus (PatternM s a) where
mzero = empty
mplus = (<|>)
subTangleP :: Int -> PatternM s a ([Dart Tangle a], [Vertex Tangle a])
subTangleP legs =
PatternM $ \ (PatternS reorder tangle cs) -> do
subList <- subsequences cs
guard $ not $ null subList
let sub = UV.replicate (1 + numberOfVertices tangle) False
UV.// map (\ d -> (vertexIndex d, True)) subList
guard $
let mask = State.execState (dfs $ head subList) Set.empty
dfs c = do
visited <- State.gets $ Set.member c
unless visited $ do
State.modify $ Set.insert c
mapM_ dfs $
filter ((sub UV.!) . vertexIndex) $
mapMaybe maybeEndVertex $ outcomingDarts c
in all (`Set.member` mask) subList
let onBorder xy =
let yx = opposite xy
x = beginVertex xy
y = beginVertex yx
in isDart xy && (sub UV.! vertexIndex x) && (isLeg yx || not (sub UV.! vertexIndex y))
let border = filter onBorder $ concatMap outcomingDarts cs
guard $ legs == length border
let borderCCW =
let traverseNext = nextCW . opposite
restoreOutcoming out d | d == head border = d : out
| onBorder d = restoreOutcoming (d : out) (opposite d)
| otherwise = restoreOutcoming out (traverseNext d)
in restoreOutcoming [] (opposite $ head border)
guard $ legs == length borderCCW
i <- [0 .. legs - 1]
return (PatternS reorder tangle (cs \\ subList), (reorder $ drop i borderCCW ++ take i borderCCW, subList))
crossingP :: PatternM s a ([Dart Tangle a], Vertex Tangle a)
crossingP =
PatternM $ \ (PatternS reorder tangle cs) ->
let try res _ [] = res
try res skipped (cur : rest) =
let next = PatternS reorder tangle (skipped ++ rest)
sh i = let od = outcomingDarts cur
in reorder $ drop i od ++ take i od
in try ((next, (sh 0, cur)) : (next, (sh 1, cur)) : (next, (sh 2, cur)) : (next, (sh 3, cur)) : res) (cur : skipped) rest
in try [] [] cs
connectionP :: [(Dart Tangle a, Dart Tangle a)] -> PatternM s a ()
connectionP = mapM_ (\ (a, b) -> guard (opposite a == b))
reconnectP :: (Show a) => (forall s. ModifyM Tangle a s ()) -> PatternM s' a (Tangle a)
reconnectP m =
PatternM $ \ s@(PatternS _ tangle _) ->
[(s, modifyKnot tangle m)]
makePattern :: Bool -> (forall s. PatternM s a x) -> Pattern a x
makePattern mirrored pattern =
Pattern $ \ tangle -> do
reorder <- id : [reverse | mirrored]
let initial = PatternS reorder tangle (allVertices tangle)
(_, res) <- runPatternMatching pattern initial
return res
class (Knotted k) => PatternMatching k where
searchMoves :: [Pattern a (Tangle a)] -> k a -> [k a]
instance PatternMatching Tangle where
searchMoves patterns tangle = do
pattern <- patterns
patternMatching pattern tangle
instance PatternMatching Tangle0 where
searchMoves patterns =
map tangle' . searchMoves patterns . toTangle
| |
f115c539b7de5b46570733f016aaa9dd78c2dc5b67663f12e215bf98518426f6 | pink-gorilla/notebook | component.cljs | (ns pinkgorilla.notebook-ui.completion.component
(:require-macros
[cljs.core.async.macros :refer [go go-loop]]
[reagent.ratom :refer [reaction]])
(:require
[taoensso.timbre :refer-macros [debug info]]
[cljs.core.async :as async :refer [<! >! chan timeout close!]]
[reagent.core :as r]
[re-frame.core :refer [reg-event-db reg-sub subscribe dispatch]]
[webly.user.notifications.core :refer [add-notification]]
[pinkgorilla.notebook-ui.completion.view :refer [completion-list]]
[pinkgorilla.notebook-ui.completion.docstring :refer [docs-view]]))
; active completion component:
(reg-event-db
:completion/hint
(fn [db [_ word namespace context]]
(let [current-word (get-in db [:completion :word])]
(if (not (= current-word word))
(do
(info "getting complete for: " word)
(add-notification :danger (str "completing: " word))
(dispatch [:nrepl/completion word namespace context])
(assoc-in db [:completion :word] word))
(do
(info "completion word unchanged: " word)
(dispatch [:completion/next])
db)))))
(reg-event-db
:completion/select
(fn [db [_ active]]
(dispatch [:nrepl/docstring (:candidate active) (:ns active)])
(assoc-in db [:completion :active] active)))
(defn indices [pred coll]
(keep-indexed #(when (pred %2) %1) coll))
(defn current-index [active candidates]
(first (indices #(= active %) candidates)))
(reg-event-db
:completion/next
(fn [db [_]]
(info ":completion/next")
(when-let [candidates (get-in db [:completion :candidates])]
(let [active (get-in db [:completion :active])
idx (current-index active candidates)
n-idx (min (- (count candidates) 1) (+ idx 1))
n-active (get candidates n-idx)]
(info "next completion: " n-active)
(dispatch [:completion/select n-active])))
db))
(reg-event-db
:completion/prior
(fn [db [_]]
(info ":completion/prior")
(when-let [candidates (get-in db [:completion :candidates])]
(let [active (get-in db [:completion :active])
idx (current-index active candidates)
p-idx (max 0 (- idx 1))
p-active (get candidates p-idx)]
(info "prior completion: " p-active)
(dispatch [:completion/select p-active])))
db))
(reg-sub
:completion
(fn [db _]
(get-in db [:completion])))
(reg-event-db
:completion/show-all
(fn [db [_ show-all]]
(info "completion show-all: " show-all)
(assoc-in db [:completion :show-all] show-all)))
(reg-event-db
:completion/show-all-toggle
(fn [db [_]]
(let [show-all (get-in db [:completion :show-all])]
(info "completion show-all toggle: " show-all)
(assoc-in db [:completion :show-all] (not show-all)))))
#_(reg-event-db
:completion/hide
(fn [db [_]]
(info "hiding completions")
db))
#_(reg-event-db
:completion/clear
(fn [db [_]]
(info "clearing completions")
db))
(defn completion-component []
(let [ncomp (subscribe [:completion])]
(fn []
(let [i @ncomp
{:keys [show-all active docstring candidates]} i
_ (debug "nrepl-completion candidates: " candidates " docstring: " docstring)]
[:div
[:h1 "completions show-all: " (str show-all)]
[:p show-all]
;(when i
[completion-list {:pos 1
( map : candidate )
:active active
:show-all show-all
:set-active (fn [a]
(info "set active: " a)
(dispatch [:completion/select a]))}]
[docs-view docstring]
;[completion-view cc ds]
]))))
| null | https://raw.githubusercontent.com/pink-gorilla/notebook/b01c806535f204c1c6e24c75a6619d747aba5655/src/pinkgorilla/notebook_ui/completion/component.cljs | clojure | active completion component:
(when i
[completion-view cc ds] | (ns pinkgorilla.notebook-ui.completion.component
(:require-macros
[cljs.core.async.macros :refer [go go-loop]]
[reagent.ratom :refer [reaction]])
(:require
[taoensso.timbre :refer-macros [debug info]]
[cljs.core.async :as async :refer [<! >! chan timeout close!]]
[reagent.core :as r]
[re-frame.core :refer [reg-event-db reg-sub subscribe dispatch]]
[webly.user.notifications.core :refer [add-notification]]
[pinkgorilla.notebook-ui.completion.view :refer [completion-list]]
[pinkgorilla.notebook-ui.completion.docstring :refer [docs-view]]))
(reg-event-db
:completion/hint
(fn [db [_ word namespace context]]
(let [current-word (get-in db [:completion :word])]
(if (not (= current-word word))
(do
(info "getting complete for: " word)
(add-notification :danger (str "completing: " word))
(dispatch [:nrepl/completion word namespace context])
(assoc-in db [:completion :word] word))
(do
(info "completion word unchanged: " word)
(dispatch [:completion/next])
db)))))
(reg-event-db
:completion/select
(fn [db [_ active]]
(dispatch [:nrepl/docstring (:candidate active) (:ns active)])
(assoc-in db [:completion :active] active)))
(defn indices [pred coll]
(keep-indexed #(when (pred %2) %1) coll))
(defn current-index [active candidates]
(first (indices #(= active %) candidates)))
(reg-event-db
:completion/next
(fn [db [_]]
(info ":completion/next")
(when-let [candidates (get-in db [:completion :candidates])]
(let [active (get-in db [:completion :active])
idx (current-index active candidates)
n-idx (min (- (count candidates) 1) (+ idx 1))
n-active (get candidates n-idx)]
(info "next completion: " n-active)
(dispatch [:completion/select n-active])))
db))
(reg-event-db
:completion/prior
(fn [db [_]]
(info ":completion/prior")
(when-let [candidates (get-in db [:completion :candidates])]
(let [active (get-in db [:completion :active])
idx (current-index active candidates)
p-idx (max 0 (- idx 1))
p-active (get candidates p-idx)]
(info "prior completion: " p-active)
(dispatch [:completion/select p-active])))
db))
(reg-sub
:completion
(fn [db _]
(get-in db [:completion])))
(reg-event-db
:completion/show-all
(fn [db [_ show-all]]
(info "completion show-all: " show-all)
(assoc-in db [:completion :show-all] show-all)))
(reg-event-db
:completion/show-all-toggle
(fn [db [_]]
(let [show-all (get-in db [:completion :show-all])]
(info "completion show-all toggle: " show-all)
(assoc-in db [:completion :show-all] (not show-all)))))
#_(reg-event-db
:completion/hide
(fn [db [_]]
(info "hiding completions")
db))
#_(reg-event-db
:completion/clear
(fn [db [_]]
(info "clearing completions")
db))
(defn completion-component []
(let [ncomp (subscribe [:completion])]
(fn []
(let [i @ncomp
{:keys [show-all active docstring candidates]} i
_ (debug "nrepl-completion candidates: " candidates " docstring: " docstring)]
[:div
[:h1 "completions show-all: " (str show-all)]
[:p show-all]
[completion-list {:pos 1
( map : candidate )
:active active
:show-all show-all
:set-active (fn [a]
(info "set active: " a)
(dispatch [:completion/select a]))}]
[docs-view docstring]
]))))
|
64f93deb64975ba5aef34baece7d0ab9da603d87768159b55d2bdac5ddb903b8 | haskell-works/hw-xml | Parser.hs | module App.XPath.Parser
( path
) where
import Control.Applicative
import Data.Attoparsec.Text
import Data.Text (Text)
import qualified App.XPath.Types as XP
import qualified Data.Text as T
tag :: Parser Text
tag = T.cons <$> letter <*> tagTail
tagTail :: Parser Text
tagTail = T.pack <$> many (letter <|> digit <|> char '-' <|> char '_')
path :: Parser XP.XPath
path = XP.XPath <$> sepBy1 tag (char '/')
| null | https://raw.githubusercontent.com/haskell-works/hw-xml/e30a4cd8e6dc7451263a3d45c1ae28b3f35d0079/app/App/XPath/Parser.hs | haskell | module App.XPath.Parser
( path
) where
import Control.Applicative
import Data.Attoparsec.Text
import Data.Text (Text)
import qualified App.XPath.Types as XP
import qualified Data.Text as T
tag :: Parser Text
tag = T.cons <$> letter <*> tagTail
tagTail :: Parser Text
tagTail = T.pack <$> many (letter <|> digit <|> char '-' <|> char '_')
path :: Parser XP.XPath
path = XP.XPath <$> sepBy1 tag (char '/')
| |
e4a8b87570a9aa181b4dfb79bca815468eb1f97993a7c0a18735033a18f10260 | scslab/hails | TCB.hs | # LANGUAGE Unsafe #
{-# LANGUAGE DeriveDataTypeable #-}
|
This module exports the type for a Hails BSON document , ' HsonDoc ' . A
Hails document is akin to " Data . 's documents , but differs in two
ways . First , Hails restricts the number of types to a subset of BSON 's
( see ' BsonVal ' ) . This restriction is primarily due to the fact that
many of the BSON types are redundant and not used ( at least within
Hails ) . Second , Hails allows for documents to contain policy - labeled
values .
Policy labeled values ( ' PolicyLabeled ' ) are permitted only at the
\"top - level\ " of a document . ( This is primarily done to keep
policy - specification simple and may change in the future . )
Consequently to allow for nested documents and documents containing an
array of values we separate top - level fields ( ' HsonField ' ) , that may
contain policy labeled values , from potentially - nested fields
( ' BsonField ' ) . A top - level field ' HsonField ' is thus either a
' BsonField ' or a ' PolicyLabled ' value .
To keep the TCB compact , this module does not export the combinators
used to create documents in a friendly fashion . See " Hails . Data . Hson "
for the safe external API .
/Credit:/ Much of this code is based on / reuses " Data . " .
This module exports the type for a Hails BSON document, 'HsonDoc'. A
Hails document is akin to "Data.Bson"\'s documents, but differs in two
ways. First, Hails restricts the number of types to a subset of BSON's
(see 'BsonVal'). This restriction is primarily due to the fact that
many of the BSON types are redundant and not used (at least within
Hails). Second, Hails allows for documents to contain policy-labeled
values.
Policy labeled values ('PolicyLabeled') are permitted only at the
\"top-level\" of a document. (This is primarily done to keep
policy-specification simple and may change in the future.)
Consequently to allow for nested documents and documents containing an
array of values we separate top-level fields ('HsonField'), that may
contain policy labeled values, from potentially-nested fields
('BsonField'). A top-level field 'HsonField' is thus either a
'BsonField' or a 'PolicyLabled' value.
To keep the TCB compact, this module does not export the combinators
used to create documents in a friendly fashion. See "Hails.Data.Hson"
for the safe external API.
/Credit:/ Much of this code is based on/reuses "Data.Bson".
-}
module Hails.Data.Hson.TCB (
-- * Documents
HsonDocument, BsonDocument
-- * Fields
, FieldName, HsonField(..), BsonField(..)
-- * Values
, HsonValue(..), BsonValue(..)
, PolicyLabeled(..), ObjectId(..), Binary(..), S8
* to / from " Data . "
, hsonDocToDataBsonDocTCB
, dataBsonDocToHsonDocTCB
, bsonDocToDataBsonDocTCB
, dataBsonValueToHsonValueTCB
-- * Internal
, add__hails_prefix
) where
import Data.Text (Text)
import qualified Data.Text as T
import Data.Int (Int32, Int64)
import Data.Time.Clock (UTCTime)
import Data.Typeable
import qualified Data.Bson as Bson
import qualified Data.Bson.Binary as Bson
import Data.Bson ( ObjectId(..) )
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as L8
import qualified Data.Binary.Put as Binary
import qualified Data.Binary.Get as Binary
import LIO.DCLabel
import LIO.TCB
-- | Strict ByeString
type S8 = S8.ByteString
--
-- Document
--
| A top - level document containing ' HsonField 's .
type HsonDocument = [HsonField]
| A ( possibly top-)level document containing ' BsonField 's .
type BsonDocument = [BsonField]
--
-- Fields
--
-- | The name of a field.
type FieldName = Text
| A field containing a named ' BsonValue '
data BsonField = BsonField !FieldName BsonValue
deriving (Typeable, Eq, Ord)
| A field containing a named ' HsonValue '
data HsonField = HsonField !FieldName HsonValue
deriving (Typeable, Eq, Ord)
--
-- Values
--
| A @BsonValue@ is a subset of BSON ( " Data . " ) values . Note that a
-- @BsonValue@ cannot contain any labeled values; all labeled values
occur in a document as ' HsonValue 's . Correspondingly , @BsonValue@s
-- may be arbitrarily nested.
data BsonValue = BsonFloat Double
-- ^ Float value
| BsonString Text
-- ^ String value
| BsonDoc BsonDocument
-- ^ Inner document
| BsonArray [BsonValue]
-- ^ List of values
| BsonBlob Binary
-- ^ Binary blob value
| BsonObjId ObjectId
-- ^ Object Id value
| BsonBool Bool
-- ^ Boolean value
| BsonUTC UTCTime
-- ^ Time stamp value
| BsonNull
-- ^ The @NULL@ value
| BsonInt32 Int32
^ 32 - bit integer
| BsonInt64 Int64
^ 64 - bit integer
deriving (Typeable, Eq, Ord)
-- | An @HsonValue@ is a top-level value that may either be a
' BsonValue ' or a policy labeled value . The separation of values
into ' BsonValue ' and ' HsonValue ' is solely due to the restriction
-- that policy-labeled values may only occur at the top level and
' BsonValue 's may be nested ( e.g. using ' BsonArray ' and ' BsonDoc ' ) .
data HsonValue = HsonValue BsonValue
^ Bson value
| HsonLabeled PolicyLabeled
-- ^ Policy labeled value
deriving (Typeable, Eq, Ord)
-- | A @PolicyLabeled@ value can be either an unlabeled value for which
-- the policy needs to be applied (@NeedPolicyTCB@), or an already
-- labeled value (@HasPolicyTCB@). @PolicyLabeled@ is a partially-opaque
-- type; code should not be able to inspect the value of an unlabeleda
-- value, but may inspect an already labeled value.
data PolicyLabeled = NeedPolicyTCB BsonValue
-- ^ Policy was not applied
| HasPolicyTCB (DCLabeled BsonValue)
-- ^ Policy applied
deriving (Typeable)
instance Eq PolicyLabeled where (==) _ _ = True
instance Ord PolicyLabeled where (<=) _ _ = False
instance Show PolicyLabeled where show _ = "PolicyLabeled"
-- | Arbitrary binary blob
newtype Binary = Binary { unBinary :: S8 }
deriving (Typeable, Show, Read, Eq, Ord)
--
Convert to " Data . "
--
| Convert ' HsonValue ' to a " Data . " @Value@. Note that
' PolicyLabeled ' values are marshalled out as " Data . " @UserDefined@
-- values. This means that the @UserDefined@ type is reserved and
exposing it as a type in ' BsonValue ' would potentially lead to leaks .
Note that the label is /NOT/ serialized , only the value . Hence ,
-- after marshalling such that back it is important that a policy is
-- applied to label the field.
hsonToDataBsonTCB :: HsonValue -> Bson.Value
hsonToDataBsonTCB (HsonValue b) = bsonToDataBsonTCB b
hsonToDataBsonTCB (HsonLabeled (HasPolicyTCB (LabeledTCB _ lv))) =
toUserDef . hsonDocToDataBsonDocTCB $
[ HsonField __hails_HsonLabeled_value $
HsonValue lv ]
where toUserDef = Bson.UserDef
. Bson.UserDefined
. strictify
. Binary.runPut
. Bson.putDocument
strictify = S8.concat . L.toChunks
hsonToDataBsonTCB _ =
error $ "hsonToDataBsonTCB: all policy labeled values" ++
" must have labeled values"
| Convert ' BsonValue ' to a " Data . " @Value@.
bsonToDataBsonTCB :: BsonValue -> Bson.Value
bsonToDataBsonTCB bv = case bv of
(BsonFloat d) -> Bson.Float d
(BsonString t) -> Bson.String t
(BsonDoc d) -> Bson.Doc $ bsonDocToDataBsonDocTCB d
(BsonArray hs) -> Bson.Array $ bsonToDataBsonTCB `map` hs
(BsonBlob b) -> Bson.Bin . Bson.Binary . unBinary $ b
(BsonObjId oid) -> Bson.ObjId oid
(BsonBool b) -> Bson.Bool b
(BsonUTC t) -> Bson.UTC t
BsonNull -> Bson.Null
(BsonInt32 i) -> Bson.Int32 i
(BsonInt64 i) -> Bson.Int64 i
| Convert an ' HsonField ' to a " Data . " @Field@.
hsonFieldToDataBsonFieldTCB :: HsonField -> Bson.Field
hsonFieldToDataBsonFieldTCB (HsonField n v) =
(Bson.:=) n (hsonToDataBsonTCB v)
| Convert a top - level document ( i.e. , ' HsonDocument ' ) to a " Data . "
-- @Document@. This is the primary marshall-out function. All
' PolicyLabeled ' values are marshalled out as " Data . " @UserDefined@
-- values. This means that the @UserDefined@ type is reserved and
exposing it as a type in ' BsonValue ' would potentially lead to
-- vulnerabilities in which labeled values can be marshalled in from
well - crafted ByteStrings . Moreover , untrusted code should not have
-- access to this function; having such access would allow it to
inspect the serialized labeled values and thus violate IFC .
hsonDocToDataBsonDocTCB :: HsonDocument -> Bson.Document
hsonDocToDataBsonDocTCB = map hsonFieldToDataBsonFieldTCB
| Convert a ' BsonField ' to a " Data . " @Field@.
bsonFieldToDataBsonFieldTCB :: BsonField -> Bson.Field
bsonFieldToDataBsonFieldTCB (BsonField n v) =
(Bson.:=) n (bsonToDataBsonTCB v)
| Convert a ' BsonDocument ' to a " Data . " @Document@.
bsonDocToDataBsonDocTCB :: BsonDocument -> Bson.Document
bsonDocToDataBsonDocTCB = map bsonFieldToDataBsonFieldTCB
--
Convert from " Data . "
--
| Convert a " Data . " @Field@ to ' BsonField ' .
dataBsonFieldToBsonFieldTCB :: Bson.Field -> BsonField
dataBsonFieldToBsonFieldTCB ((Bson.:=) n v) = BsonField n (dataBsonToBsonTCB v)
| Convert a " Data . " @Document@ to a ' BsonDocument ' .
dataBsonDocToBsonDocTCB :: Bson.Document -> BsonDocument
dataBsonDocToBsonDocTCB = map dataBsonFieldToBsonFieldTCB
| Convert " Data . " @Value@ to a ' BsonValue ' .
dataBsonToBsonTCB :: Bson.Value -> BsonValue
dataBsonToBsonTCB bv = case bv of
(Bson.Float d) -> BsonFloat d
(Bson.String t) -> BsonString t
(Bson.Doc d) -> BsonDoc $ dataBsonDocToBsonDocTCB d
(Bson.Array hs) -> BsonArray $ dataBsonToBsonTCB `map` hs
(Bson.Bin (Bson.Binary b)) -> BsonBlob . Binary $ b
(Bson.ObjId oid) -> BsonObjId oid
(Bson.Bool b) -> BsonBool b
(Bson.UTC t) -> BsonUTC t
Bson.Null -> BsonNull
(Bson.Int32 i) -> BsonInt32 i
(Bson.Int64 i) -> BsonInt64 i
_ -> error "dataBsonToBsonTCB: only support subset of BSON"
| Convert " Data . " @Document@ to a ' HsonDocument ' . This is the
top - level function that marshalls BSON documents to Hails
-- documents. This function assumes that all documents have been
-- marshalled out using 'hsonDocToDataBsonDocTCB'. Otherwise, the
-- 'PolicyLabled' values that are created from the document may be
-- forged.
dataBsonDocToHsonDocTCB :: Bson.Document -> HsonDocument
dataBsonDocToHsonDocTCB =
map (\((Bson.:=) n bv) -> HsonField n $ dataBsonValueToHsonValueTCB bv)
|Convert a " Data . " @Value@ to a ' HsonValue ' . See
-- 'dataBsonDocToHsonDocTCB'.
dataBsonValueToHsonValueTCB :: Bson.Value -> HsonValue
dataBsonValueToHsonValueTCB bv = case bv of
(Bson.UserDef (Bson.UserDefined b)) ->
let bdoc = Binary.runGet Bson.getDocument (lazyfy b)
in case maybePolicyLabeledTCB bdoc of
Nothing -> error $ "dataBsonValueToHsonValueTCB: "
++ "Expected PolicyLabeled"
Just lv -> HsonLabeled lv
v -> HsonValue $ dataBsonToBsonTCB v
where lazyfy x = L8.fromChunks [x]
-- | Hails internal field name for a policy labeled value (label part)
-- (name part).
__hails_HsonLabeled_value :: FieldName
__hails_HsonLabeled_value = add__hails_prefix $ T.pack "HsonLabeled_value"
-- | Hails internal prefix that is used to serialized labeled values.
add__hails_prefix :: FieldName -> FieldName
add__hails_prefix t = T.pack "__hails_" `T.append` t
| Convert a " Data . " @Document@ to a policy labeled value .
maybePolicyLabeledTCB :: Bson.Document -> Maybe PolicyLabeled
maybePolicyLabeledTCB doc = do
v <- Bson.look __hails_HsonLabeled_value doc
return . NeedPolicyTCB $ dataBsonToBsonTCB v
| null | https://raw.githubusercontent.com/scslab/hails/4d4dfe0cdfb7c8941a55ce882cba20d82c6d9cfd/Hails/Data/Hson/TCB.hs | haskell | # LANGUAGE DeriveDataTypeable #
* Documents
* Fields
* Values
* Internal
| Strict ByeString
Document
Fields
| The name of a field.
Values
@BsonValue@ cannot contain any labeled values; all labeled values
may be arbitrarily nested.
^ Float value
^ String value
^ Inner document
^ List of values
^ Binary blob value
^ Object Id value
^ Boolean value
^ Time stamp value
^ The @NULL@ value
| An @HsonValue@ is a top-level value that may either be a
that policy-labeled values may only occur at the top level and
^ Policy labeled value
| A @PolicyLabeled@ value can be either an unlabeled value for which
the policy needs to be applied (@NeedPolicyTCB@), or an already
labeled value (@HasPolicyTCB@). @PolicyLabeled@ is a partially-opaque
type; code should not be able to inspect the value of an unlabeleda
value, but may inspect an already labeled value.
^ Policy was not applied
^ Policy applied
| Arbitrary binary blob
values. This means that the @UserDefined@ type is reserved and
after marshalling such that back it is important that a policy is
applied to label the field.
@Document@. This is the primary marshall-out function. All
values. This means that the @UserDefined@ type is reserved and
vulnerabilities in which labeled values can be marshalled in from
access to this function; having such access would allow it to
documents. This function assumes that all documents have been
marshalled out using 'hsonDocToDataBsonDocTCB'. Otherwise, the
'PolicyLabled' values that are created from the document may be
forged.
'dataBsonDocToHsonDocTCB'.
| Hails internal field name for a policy labeled value (label part)
(name part).
| Hails internal prefix that is used to serialized labeled values. | # LANGUAGE Unsafe #
|
This module exports the type for a Hails BSON document , ' HsonDoc ' . A
Hails document is akin to " Data . 's documents , but differs in two
ways . First , Hails restricts the number of types to a subset of BSON 's
( see ' BsonVal ' ) . This restriction is primarily due to the fact that
many of the BSON types are redundant and not used ( at least within
Hails ) . Second , Hails allows for documents to contain policy - labeled
values .
Policy labeled values ( ' PolicyLabeled ' ) are permitted only at the
\"top - level\ " of a document . ( This is primarily done to keep
policy - specification simple and may change in the future . )
Consequently to allow for nested documents and documents containing an
array of values we separate top - level fields ( ' HsonField ' ) , that may
contain policy labeled values , from potentially - nested fields
( ' BsonField ' ) . A top - level field ' HsonField ' is thus either a
' BsonField ' or a ' PolicyLabled ' value .
To keep the TCB compact , this module does not export the combinators
used to create documents in a friendly fashion . See " Hails . Data . Hson "
for the safe external API .
/Credit:/ Much of this code is based on / reuses " Data . " .
This module exports the type for a Hails BSON document, 'HsonDoc'. A
Hails document is akin to "Data.Bson"\'s documents, but differs in two
ways. First, Hails restricts the number of types to a subset of BSON's
(see 'BsonVal'). This restriction is primarily due to the fact that
many of the BSON types are redundant and not used (at least within
Hails). Second, Hails allows for documents to contain policy-labeled
values.
Policy labeled values ('PolicyLabeled') are permitted only at the
\"top-level\" of a document. (This is primarily done to keep
policy-specification simple and may change in the future.)
Consequently to allow for nested documents and documents containing an
array of values we separate top-level fields ('HsonField'), that may
contain policy labeled values, from potentially-nested fields
('BsonField'). A top-level field 'HsonField' is thus either a
'BsonField' or a 'PolicyLabled' value.
To keep the TCB compact, this module does not export the combinators
used to create documents in a friendly fashion. See "Hails.Data.Hson"
for the safe external API.
/Credit:/ Much of this code is based on/reuses "Data.Bson".
-}
module Hails.Data.Hson.TCB (
HsonDocument, BsonDocument
, FieldName, HsonField(..), BsonField(..)
, HsonValue(..), BsonValue(..)
, PolicyLabeled(..), ObjectId(..), Binary(..), S8
* to / from " Data . "
, hsonDocToDataBsonDocTCB
, dataBsonDocToHsonDocTCB
, bsonDocToDataBsonDocTCB
, dataBsonValueToHsonValueTCB
, add__hails_prefix
) where
import Data.Text (Text)
import qualified Data.Text as T
import Data.Int (Int32, Int64)
import Data.Time.Clock (UTCTime)
import Data.Typeable
import qualified Data.Bson as Bson
import qualified Data.Bson.Binary as Bson
import Data.Bson ( ObjectId(..) )
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as L8
import qualified Data.Binary.Put as Binary
import qualified Data.Binary.Get as Binary
import LIO.DCLabel
import LIO.TCB
type S8 = S8.ByteString
| A top - level document containing ' HsonField 's .
type HsonDocument = [HsonField]
| A ( possibly top-)level document containing ' BsonField 's .
type BsonDocument = [BsonField]
type FieldName = Text
| A field containing a named ' BsonValue '
data BsonField = BsonField !FieldName BsonValue
deriving (Typeable, Eq, Ord)
| A field containing a named ' HsonValue '
data HsonField = HsonField !FieldName HsonValue
deriving (Typeable, Eq, Ord)
| A @BsonValue@ is a subset of BSON ( " Data . " ) values . Note that a
occur in a document as ' HsonValue 's . Correspondingly , @BsonValue@s
data BsonValue = BsonFloat Double
| BsonString Text
| BsonDoc BsonDocument
| BsonArray [BsonValue]
| BsonBlob Binary
| BsonObjId ObjectId
| BsonBool Bool
| BsonUTC UTCTime
| BsonNull
| BsonInt32 Int32
^ 32 - bit integer
| BsonInt64 Int64
^ 64 - bit integer
deriving (Typeable, Eq, Ord)
' BsonValue ' or a policy labeled value . The separation of values
into ' BsonValue ' and ' HsonValue ' is solely due to the restriction
' BsonValue 's may be nested ( e.g. using ' BsonArray ' and ' BsonDoc ' ) .
data HsonValue = HsonValue BsonValue
^ Bson value
| HsonLabeled PolicyLabeled
deriving (Typeable, Eq, Ord)
data PolicyLabeled = NeedPolicyTCB BsonValue
| HasPolicyTCB (DCLabeled BsonValue)
deriving (Typeable)
instance Eq PolicyLabeled where (==) _ _ = True
instance Ord PolicyLabeled where (<=) _ _ = False
instance Show PolicyLabeled where show _ = "PolicyLabeled"
newtype Binary = Binary { unBinary :: S8 }
deriving (Typeable, Show, Read, Eq, Ord)
Convert to " Data . "
| Convert ' HsonValue ' to a " Data . " @Value@. Note that
' PolicyLabeled ' values are marshalled out as " Data . " @UserDefined@
exposing it as a type in ' BsonValue ' would potentially lead to leaks .
Note that the label is /NOT/ serialized , only the value . Hence ,
hsonToDataBsonTCB :: HsonValue -> Bson.Value
hsonToDataBsonTCB (HsonValue b) = bsonToDataBsonTCB b
hsonToDataBsonTCB (HsonLabeled (HasPolicyTCB (LabeledTCB _ lv))) =
toUserDef . hsonDocToDataBsonDocTCB $
[ HsonField __hails_HsonLabeled_value $
HsonValue lv ]
where toUserDef = Bson.UserDef
. Bson.UserDefined
. strictify
. Binary.runPut
. Bson.putDocument
strictify = S8.concat . L.toChunks
hsonToDataBsonTCB _ =
error $ "hsonToDataBsonTCB: all policy labeled values" ++
" must have labeled values"
| Convert ' BsonValue ' to a " Data . " @Value@.
bsonToDataBsonTCB :: BsonValue -> Bson.Value
bsonToDataBsonTCB bv = case bv of
(BsonFloat d) -> Bson.Float d
(BsonString t) -> Bson.String t
(BsonDoc d) -> Bson.Doc $ bsonDocToDataBsonDocTCB d
(BsonArray hs) -> Bson.Array $ bsonToDataBsonTCB `map` hs
(BsonBlob b) -> Bson.Bin . Bson.Binary . unBinary $ b
(BsonObjId oid) -> Bson.ObjId oid
(BsonBool b) -> Bson.Bool b
(BsonUTC t) -> Bson.UTC t
BsonNull -> Bson.Null
(BsonInt32 i) -> Bson.Int32 i
(BsonInt64 i) -> Bson.Int64 i
| Convert an ' HsonField ' to a " Data . " @Field@.
hsonFieldToDataBsonFieldTCB :: HsonField -> Bson.Field
hsonFieldToDataBsonFieldTCB (HsonField n v) =
(Bson.:=) n (hsonToDataBsonTCB v)
| Convert a top - level document ( i.e. , ' HsonDocument ' ) to a " Data . "
' PolicyLabeled ' values are marshalled out as " Data . " @UserDefined@
exposing it as a type in ' BsonValue ' would potentially lead to
well - crafted ByteStrings . Moreover , untrusted code should not have
inspect the serialized labeled values and thus violate IFC .
hsonDocToDataBsonDocTCB :: HsonDocument -> Bson.Document
hsonDocToDataBsonDocTCB = map hsonFieldToDataBsonFieldTCB
| Convert a ' BsonField ' to a " Data . " @Field@.
bsonFieldToDataBsonFieldTCB :: BsonField -> Bson.Field
bsonFieldToDataBsonFieldTCB (BsonField n v) =
(Bson.:=) n (bsonToDataBsonTCB v)
| Convert a ' BsonDocument ' to a " Data . " @Document@.
bsonDocToDataBsonDocTCB :: BsonDocument -> Bson.Document
bsonDocToDataBsonDocTCB = map bsonFieldToDataBsonFieldTCB
Convert from " Data . "
| Convert a " Data . " @Field@ to ' BsonField ' .
dataBsonFieldToBsonFieldTCB :: Bson.Field -> BsonField
dataBsonFieldToBsonFieldTCB ((Bson.:=) n v) = BsonField n (dataBsonToBsonTCB v)
| Convert a " Data . " @Document@ to a ' BsonDocument ' .
dataBsonDocToBsonDocTCB :: Bson.Document -> BsonDocument
dataBsonDocToBsonDocTCB = map dataBsonFieldToBsonFieldTCB
| Convert " Data . " @Value@ to a ' BsonValue ' .
dataBsonToBsonTCB :: Bson.Value -> BsonValue
dataBsonToBsonTCB bv = case bv of
(Bson.Float d) -> BsonFloat d
(Bson.String t) -> BsonString t
(Bson.Doc d) -> BsonDoc $ dataBsonDocToBsonDocTCB d
(Bson.Array hs) -> BsonArray $ dataBsonToBsonTCB `map` hs
(Bson.Bin (Bson.Binary b)) -> BsonBlob . Binary $ b
(Bson.ObjId oid) -> BsonObjId oid
(Bson.Bool b) -> BsonBool b
(Bson.UTC t) -> BsonUTC t
Bson.Null -> BsonNull
(Bson.Int32 i) -> BsonInt32 i
(Bson.Int64 i) -> BsonInt64 i
_ -> error "dataBsonToBsonTCB: only support subset of BSON"
| Convert " Data . " @Document@ to a ' HsonDocument ' . This is the
top - level function that marshalls BSON documents to Hails
dataBsonDocToHsonDocTCB :: Bson.Document -> HsonDocument
dataBsonDocToHsonDocTCB =
map (\((Bson.:=) n bv) -> HsonField n $ dataBsonValueToHsonValueTCB bv)
|Convert a " Data . " @Value@ to a ' HsonValue ' . See
dataBsonValueToHsonValueTCB :: Bson.Value -> HsonValue
dataBsonValueToHsonValueTCB bv = case bv of
(Bson.UserDef (Bson.UserDefined b)) ->
let bdoc = Binary.runGet Bson.getDocument (lazyfy b)
in case maybePolicyLabeledTCB bdoc of
Nothing -> error $ "dataBsonValueToHsonValueTCB: "
++ "Expected PolicyLabeled"
Just lv -> HsonLabeled lv
v -> HsonValue $ dataBsonToBsonTCB v
where lazyfy x = L8.fromChunks [x]
__hails_HsonLabeled_value :: FieldName
__hails_HsonLabeled_value = add__hails_prefix $ T.pack "HsonLabeled_value"
add__hails_prefix :: FieldName -> FieldName
add__hails_prefix t = T.pack "__hails_" `T.append` t
| Convert a " Data . " @Document@ to a policy labeled value .
maybePolicyLabeledTCB :: Bson.Document -> Maybe PolicyLabeled
maybePolicyLabeledTCB doc = do
v <- Bson.look __hails_HsonLabeled_value doc
return . NeedPolicyTCB $ dataBsonToBsonTCB v
|
c07899412306a10eefbdc6d94307c28e5136d19a34f09b2a40ae7c4dd4ad01ce | zkincaid/duet | test_transition.ml | open Srk
open OUnit
open Syntax
open Test_pervasives
module V = struct
type t = string
let typ_table = Hashtbl.create 991
let sym_table = Hashtbl.create 991
let rev_sym_table = Hashtbl.create 991
let register_var name typ =
assert (not (Hashtbl.mem typ_table name));
let sym = Ctx.mk_symbol ~name (typ :> typ) in
Hashtbl.add typ_table name typ;
Hashtbl.add sym_table name sym;
Hashtbl.add rev_sym_table sym name
let pp = Format.pp_print_string
let show x = x
let typ = Hashtbl.find typ_table
let compare = Stdlib.compare
let symbol_of = Hashtbl.find sym_table
let of_symbol sym =
if Hashtbl.mem rev_sym_table sym then
Some (Hashtbl.find rev_sym_table sym)
else
None
end
module T = Transition.Make(Ctx)(V)
let () =
T.domain := (module Iteration.Split(val !T.domain))
let () =
V.register_var "i" `TyInt;
V.register_var "j" `TyInt;
V.register_var "k" `TyInt;
V.register_var "n" `TyInt;
V.register_var "x" `TyInt;
V.register_var "y" `TyInt;
V.register_var "z" `TyInt
let x = Ctx.mk_const (V.symbol_of "x")
let y = Ctx.mk_const (V.symbol_of "y")
let z = Ctx.mk_const (V.symbol_of "z")
let i = Ctx.mk_const (V.symbol_of "i")
let j = Ctx.mk_const (V.symbol_of "j")
let k = Ctx.mk_const (V.symbol_of "k")
let n = Ctx.mk_const (V.symbol_of "n")
let assert_post tr phi =
let not_post =
rewrite srk ~down:(pos_rewriter srk) (Ctx.mk_not phi)
in
let pathcond =
T.guard (T.mul tr (T.assume not_post))
in
if Wedge.is_sat srk pathcond != `Unsat then
assert_failure (Printf.sprintf "%s\n is not a post-condition of\n%s"
(Formula.show srk phi)
(T.show tr))
let assert_equal_tr = assert_equal ~cmp:T.equal ~printer:T.show
let mk_block = BatList.reduce T.mul
let mk_if cond bthen belse =
T.add
(mk_block ((T.assume cond)::bthen))
(mk_block ((T.assume (Ctx.mk_not cond))::belse))
let mk_while cond body =
T.mul
(T.star (mk_block ((T.assume cond)::body)))
(T.assume (Ctx.mk_not cond))
let degree1 () =
let tr =
let open Infix in
mk_block [
T.assign "i" (int 0);
mk_while (i < n) [
T.assign "i" (i + (int 1));
]
]
in
let post =
let open Infix in
n < (int 0) || i = n
in
assert_post tr post
let degree2 () =
let tr =
let open Infix in
mk_block [
T.assume ((int 0) <= n);
T.assign "i" (int 0);
T.assign "x" (int 0);
mk_while (i < n) [
T.assume ((int 0) <= n); (* Needed w/o forward inv gen *)
T.assign "i" (i + (int 1));
T.assign "j" (int 0);
mk_while (j < n) [
T.assign "j" (j + (int 1));
T.assign "x" (x + (int 1));
]
]
]
in
let post =
let open Infix in
x = n*n
in
assert_post tr post
let degree3 () =
let tr =
let open Infix in
mk_block [
T.assume ((int 0) <= n);
T.assign "i" (int 0);
T.assign "x" (int 0);
mk_while (i < n) [
T.assume ((int 0) <= n); (* Needed w/o forward inv gen *)
T.assign "i" (i + (int 1));
T.assign "j" (int 0);
mk_while (j < n) [
T.assume ((int 0) <= n); (* Needed w/o forward inv gen *)
T.assign "j" (j + (int 1));
T.assign "k" (int 0);
mk_while (k < n) [
T.assign "k" (k + (int 1));
T.assign "x" (x + (int 1));
]
]
]
]
in
let post =
let open Infix in
x = n*n*n
in
assert_post tr post
let gauss_sum () =
let tr =
let open Infix in
mk_block [
T.assume ((int 0) <= n);
T.assign "i" (int 0);
T.assign "x" (int 0);
mk_while (i < n) [
T.assume ((int 0) <= n); (* Needed w/o forward inv gen *)
T.assume ((int 0) <= i); (* Needed w/o forward inv gen *)
T.assign "j" i;
T.assign "i" (i + (int 1));
mk_while (j < n) [
T.assign "j" (j + (int 1));
T.assign "x" (x + (int 1));
]
]
]
in
let post =
let open Infix in
(int 2) * x <= (n*(n+(int 1)))
in
assert_post tr post
let inc_nondet () =
let tr =
let open Infix in
mk_block [
T.assign "x" (int 0);
T.assign "y" (int 0);
T.assign "z" (int 0);
mk_while (z < n) [
T.assign "z" (z + (int 1));
mk_if (z mod (int 2) = (int 0)) [
T.assign "x" (x + (int 1));
] [
T.assign "y" (y + (int 1));
]
]
]
in
let post =
let open Infix in
n < (int 0) || x + y = n
in
assert_post tr post
let split () =
let tr =
let open Infix in
mk_block [
T.assume ((int 0) <= n);
T.assign "x" (int 0);
T.assign "y" (int 0);
T.havoc ["z"];
mk_while (x + y < n) [
mk_if (z <= (int 0)) [
T.assign "x" (x + (int 1));
] [
T.assign "y" (y + (int 1));
]
]
]
in
let post =
let open Infix in
x = n || y = n
in
assert_post tr post
let split2 () =
let tr =
let open Infix in
mk_block [
T.assign "n" (int 100);
T.assign "x" (int 0);
T.assign "y" (int 0);
T.havoc ["z"];
mk_while (x + y < n) [
mk_if (x < (int 50)) [
T.assign "x" (x + (int 1));
] [
T.assign "y" (y + (int 1));
]
]
]
in
let post =
let open Infix in
x = y
in
assert_post tr post
let equal1 () =
let tr1 =
mk_block [
T.havoc ["x"];
T.assign "y" x;
]
in
let tr2 =
mk_block [
T.havoc ["y"];
T.assign "x" y;
]
in
assert_equal_tr tr1 tr2
let assert_valid pre tr post =
if (T.valid_triple pre [tr] post) != `Valid then
assert_failure (Printf.sprintf "Invalid Hoare triple: {%s} %s {%s}"
(Formula.show srk pre)
(T.show tr)
(Formula.show srk post))
let check_interpolant path itp =
let rec go path itp =
match path, itp with
| tr::path, pre::post::itp ->
assert_valid pre tr post;
go path (post::itp)
| [], [_] -> ()
| _, _ -> assert false
in
go path (Ctx.mk_true::itp)
let interpolate1 () =
let path =
let open Infix in
[T.assign "x" (int 0);
T.assign "y" (int 0);
T.assume (x < (int 10));
T.assign "x" (x + (int 1));
T.assign "y" (y + (int 1));
T.assume ((int 10) <= x);
T.assume ((int 10) < x || x < (int 10))]
in
let post = Ctx.mk_false in
match T.interpolate path post with
| `Valid itp ->
check_interpolant path itp
| _ -> assert_failure "Invalid post-condition"
let interpolate2 () =
let path =
let open Infix in
[T.assume (x < (int 10));
T.assign "x" (x + (int 1));
T.assign "y" (y + (int 1));
T.assume ((int 10) <= x);
T.assume ((int 10) < x || x < (int 10))]
in
let post = Ctx.mk_false in
match T.interpolate path post with
| `Valid itp ->
check_interpolant path itp
| _ -> assert_failure "Invalid post-condition"
let interpolate_havoc () =
let path =
let open Infix in
[T.assign "x" (int 0);
T.assign "y" v; (* havoc *)
T.assume (x <= y);
T.assume (y < (int 0))]
in
let post = Ctx.mk_false in
match T.interpolate path post with
| `Valid itp ->
check_interpolant path itp
| _ -> assert_failure "Invalid post-condition"
let negative_eigenvalue () =
let tr =
let open Infix in
mk_block [
T.assume ((int 0) < x);
T.assume ((int 0) < y);
T.assign "n" (x + y);
T.assign "k" (int 0);
T.assume ((int 0) < y);
mk_while ((int 0) < x && (int 0) <= y) [
T.parallel_assign [("x", y);
("y", x - (int 1));
("k", k + (int 1))]
]
]
in
let post = mk_leq srk k n in
assert_post tr post
let suite = "Transition" >::: [
"degree1" >:: degree1;
"degree2" >:: degree2;
"degree3" >:: degree3;
"gauss_sum" >:: gauss_sum;
"inc_nondet" >:: inc_nondet;
"split" >:: split;
"split2" >:: split2;
"equal1" >:: equal1;
"interpolate1" >:: interpolate1;
"interpolate2" >:: interpolate2;
"interpolate_havoc" >:: interpolate_havoc;
"negative_eigenvalue" >:: negative_eigenvalue;
]
| null | https://raw.githubusercontent.com/zkincaid/duet/162d3da830f12ab8e8d51f7757cddcb49c4084ca/srk/test/test_transition.ml | ocaml | Needed w/o forward inv gen
Needed w/o forward inv gen
Needed w/o forward inv gen
Needed w/o forward inv gen
Needed w/o forward inv gen
havoc | open Srk
open OUnit
open Syntax
open Test_pervasives
module V = struct
type t = string
let typ_table = Hashtbl.create 991
let sym_table = Hashtbl.create 991
let rev_sym_table = Hashtbl.create 991
let register_var name typ =
assert (not (Hashtbl.mem typ_table name));
let sym = Ctx.mk_symbol ~name (typ :> typ) in
Hashtbl.add typ_table name typ;
Hashtbl.add sym_table name sym;
Hashtbl.add rev_sym_table sym name
let pp = Format.pp_print_string
let show x = x
let typ = Hashtbl.find typ_table
let compare = Stdlib.compare
let symbol_of = Hashtbl.find sym_table
let of_symbol sym =
if Hashtbl.mem rev_sym_table sym then
Some (Hashtbl.find rev_sym_table sym)
else
None
end
module T = Transition.Make(Ctx)(V)
let () =
T.domain := (module Iteration.Split(val !T.domain))
let () =
V.register_var "i" `TyInt;
V.register_var "j" `TyInt;
V.register_var "k" `TyInt;
V.register_var "n" `TyInt;
V.register_var "x" `TyInt;
V.register_var "y" `TyInt;
V.register_var "z" `TyInt
let x = Ctx.mk_const (V.symbol_of "x")
let y = Ctx.mk_const (V.symbol_of "y")
let z = Ctx.mk_const (V.symbol_of "z")
let i = Ctx.mk_const (V.symbol_of "i")
let j = Ctx.mk_const (V.symbol_of "j")
let k = Ctx.mk_const (V.symbol_of "k")
let n = Ctx.mk_const (V.symbol_of "n")
let assert_post tr phi =
let not_post =
rewrite srk ~down:(pos_rewriter srk) (Ctx.mk_not phi)
in
let pathcond =
T.guard (T.mul tr (T.assume not_post))
in
if Wedge.is_sat srk pathcond != `Unsat then
assert_failure (Printf.sprintf "%s\n is not a post-condition of\n%s"
(Formula.show srk phi)
(T.show tr))
let assert_equal_tr = assert_equal ~cmp:T.equal ~printer:T.show
let mk_block = BatList.reduce T.mul
let mk_if cond bthen belse =
T.add
(mk_block ((T.assume cond)::bthen))
(mk_block ((T.assume (Ctx.mk_not cond))::belse))
let mk_while cond body =
T.mul
(T.star (mk_block ((T.assume cond)::body)))
(T.assume (Ctx.mk_not cond))
let degree1 () =
let tr =
let open Infix in
mk_block [
T.assign "i" (int 0);
mk_while (i < n) [
T.assign "i" (i + (int 1));
]
]
in
let post =
let open Infix in
n < (int 0) || i = n
in
assert_post tr post
let degree2 () =
let tr =
let open Infix in
mk_block [
T.assume ((int 0) <= n);
T.assign "i" (int 0);
T.assign "x" (int 0);
mk_while (i < n) [
T.assign "i" (i + (int 1));
T.assign "j" (int 0);
mk_while (j < n) [
T.assign "j" (j + (int 1));
T.assign "x" (x + (int 1));
]
]
]
in
let post =
let open Infix in
x = n*n
in
assert_post tr post
let degree3 () =
let tr =
let open Infix in
mk_block [
T.assume ((int 0) <= n);
T.assign "i" (int 0);
T.assign "x" (int 0);
mk_while (i < n) [
T.assign "i" (i + (int 1));
T.assign "j" (int 0);
mk_while (j < n) [
T.assign "j" (j + (int 1));
T.assign "k" (int 0);
mk_while (k < n) [
T.assign "k" (k + (int 1));
T.assign "x" (x + (int 1));
]
]
]
]
in
let post =
let open Infix in
x = n*n*n
in
assert_post tr post
let gauss_sum () =
let tr =
let open Infix in
mk_block [
T.assume ((int 0) <= n);
T.assign "i" (int 0);
T.assign "x" (int 0);
mk_while (i < n) [
T.assign "j" i;
T.assign "i" (i + (int 1));
mk_while (j < n) [
T.assign "j" (j + (int 1));
T.assign "x" (x + (int 1));
]
]
]
in
let post =
let open Infix in
(int 2) * x <= (n*(n+(int 1)))
in
assert_post tr post
let inc_nondet () =
let tr =
let open Infix in
mk_block [
T.assign "x" (int 0);
T.assign "y" (int 0);
T.assign "z" (int 0);
mk_while (z < n) [
T.assign "z" (z + (int 1));
mk_if (z mod (int 2) = (int 0)) [
T.assign "x" (x + (int 1));
] [
T.assign "y" (y + (int 1));
]
]
]
in
let post =
let open Infix in
n < (int 0) || x + y = n
in
assert_post tr post
let split () =
let tr =
let open Infix in
mk_block [
T.assume ((int 0) <= n);
T.assign "x" (int 0);
T.assign "y" (int 0);
T.havoc ["z"];
mk_while (x + y < n) [
mk_if (z <= (int 0)) [
T.assign "x" (x + (int 1));
] [
T.assign "y" (y + (int 1));
]
]
]
in
let post =
let open Infix in
x = n || y = n
in
assert_post tr post
let split2 () =
let tr =
let open Infix in
mk_block [
T.assign "n" (int 100);
T.assign "x" (int 0);
T.assign "y" (int 0);
T.havoc ["z"];
mk_while (x + y < n) [
mk_if (x < (int 50)) [
T.assign "x" (x + (int 1));
] [
T.assign "y" (y + (int 1));
]
]
]
in
let post =
let open Infix in
x = y
in
assert_post tr post
let equal1 () =
let tr1 =
mk_block [
T.havoc ["x"];
T.assign "y" x;
]
in
let tr2 =
mk_block [
T.havoc ["y"];
T.assign "x" y;
]
in
assert_equal_tr tr1 tr2
let assert_valid pre tr post =
if (T.valid_triple pre [tr] post) != `Valid then
assert_failure (Printf.sprintf "Invalid Hoare triple: {%s} %s {%s}"
(Formula.show srk pre)
(T.show tr)
(Formula.show srk post))
let check_interpolant path itp =
let rec go path itp =
match path, itp with
| tr::path, pre::post::itp ->
assert_valid pre tr post;
go path (post::itp)
| [], [_] -> ()
| _, _ -> assert false
in
go path (Ctx.mk_true::itp)
let interpolate1 () =
let path =
let open Infix in
[T.assign "x" (int 0);
T.assign "y" (int 0);
T.assume (x < (int 10));
T.assign "x" (x + (int 1));
T.assign "y" (y + (int 1));
T.assume ((int 10) <= x);
T.assume ((int 10) < x || x < (int 10))]
in
let post = Ctx.mk_false in
match T.interpolate path post with
| `Valid itp ->
check_interpolant path itp
| _ -> assert_failure "Invalid post-condition"
let interpolate2 () =
let path =
let open Infix in
[T.assume (x < (int 10));
T.assign "x" (x + (int 1));
T.assign "y" (y + (int 1));
T.assume ((int 10) <= x);
T.assume ((int 10) < x || x < (int 10))]
in
let post = Ctx.mk_false in
match T.interpolate path post with
| `Valid itp ->
check_interpolant path itp
| _ -> assert_failure "Invalid post-condition"
let interpolate_havoc () =
let path =
let open Infix in
[T.assign "x" (int 0);
T.assume (x <= y);
T.assume (y < (int 0))]
in
let post = Ctx.mk_false in
match T.interpolate path post with
| `Valid itp ->
check_interpolant path itp
| _ -> assert_failure "Invalid post-condition"
let negative_eigenvalue () =
let tr =
let open Infix in
mk_block [
T.assume ((int 0) < x);
T.assume ((int 0) < y);
T.assign "n" (x + y);
T.assign "k" (int 0);
T.assume ((int 0) < y);
mk_while ((int 0) < x && (int 0) <= y) [
T.parallel_assign [("x", y);
("y", x - (int 1));
("k", k + (int 1))]
]
]
in
let post = mk_leq srk k n in
assert_post tr post
let suite = "Transition" >::: [
"degree1" >:: degree1;
"degree2" >:: degree2;
"degree3" >:: degree3;
"gauss_sum" >:: gauss_sum;
"inc_nondet" >:: inc_nondet;
"split" >:: split;
"split2" >:: split2;
"equal1" >:: equal1;
"interpolate1" >:: interpolate1;
"interpolate2" >:: interpolate2;
"interpolate_havoc" >:: interpolate_havoc;
"negative_eigenvalue" >:: negative_eigenvalue;
]
|
f0a13e2c0fc4b5db4f53b9cbaa3170c5fa888d172f9e1ff0382b5436159e2ad5 | haskell-opengl/GLUT | Functions.hs | # LANGUAGE CPP #
{-# OPTIONS_HADDOCK hide #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.UI.GLUT.Raw.Functions
Copyright : ( c ) 2018
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
All raw functions from GLUT and freeglut .
--
--------------------------------------------------------------------------------
module Graphics.UI.GLUT.Raw.Functions (
isKnown,
glutAddMenuEntry,
glutAddSubMenu,
glutAppStatusFunc,
glutAttachMenu,
glutBitmapCharacter,
glutBitmapHeight,
glutBitmapLength,
glutBitmapString,
glutBitmapWidth,
glutButtonBoxFunc,
glutChangeToMenuEntry,
glutChangeToSubMenu,
glutCloseFunc,
glutCopyColormap,
glutCreateMenu,
glutCreateSubWindow,
glutCreateWindow,
glutDestroyMenu,
glutDestroyWindow,
glutDetachMenu,
glutDeviceGet,
glutDialsFunc,
glutDisplayFunc,
glutEnterGameMode,
glutEntryFunc,
glutEstablishOverlay,
glutExit,
glutExtensionSupported,
glutForceJoystickFunc,
glutFullScreen,
glutFullScreenToggle,
glutGameModeGet,
glutGameModeString,
glutGet,
glutGetColor,
glutGetMenu,
glutGetMenuData,
glutGetModeValues,
glutGetModifiers,
glutGetProcAddress,
glutGetWindow,
glutGetWindowData,
glutHideOverlay,
glutHideWindow,
glutIconifyWindow,
glutIdleFunc,
glutIgnoreKeyRepeat,
glutInit,
glutInitContextFlags,
glutInitContextFunc,
glutInitContextProfile,
glutInitContextVersion,
glutInitDisplayMode,
glutInitDisplayString,
glutInitWindowPosition,
glutInitWindowSize,
glutJoystickFunc,
glutKeyboardFunc,
glutKeyboardUpFunc,
glutLayerGet,
glutLeaveFullScreen,
glutLeaveGameMode,
glutLeaveMainLoop,
glutMainLoop,
glutMainLoopEvent,
glutMenuDestroyFunc,
glutMenuStateFunc,
glutMenuStatusFunc,
glutMotionFunc,
glutMouseFunc,
glutMouseWheelFunc,
glutMultiButtonFunc,
glutMultiEntryFunc,
glutMultiMotionFunc,
glutMultiPassiveFunc,
glutOverlayDisplayFunc,
glutPassiveMotionFunc,
glutPopWindow,
glutPositionFunc,
glutPositionWindow,
glutPostOverlayRedisplay,
glutPostRedisplay,
glutPostWindowOverlayRedisplay,
glutPostWindowRedisplay,
glutPushWindow,
glutRemoveMenuItem,
glutRemoveOverlay,
glutReportErrors,
glutReshapeFunc,
glutReshapeWindow,
glutSetColor,
glutSetCursor,
glutSetIconTitle,
glutSetKeyRepeat,
glutSetMenu,
glutSetMenuData,
glutSetMenuFont,
glutSetOption,
glutSetVertexAttribCoord3,
glutSetVertexAttribNormal,
glutSetVertexAttribTexCoord2,
glutSetWindow,
glutSetWindowData,
glutSetWindowTitle,
glutSetupVideoResizing,
glutShowOverlay,
glutShowWindow,
glutSolidCone,
glutSolidCube,
glutSolidCylinder,
glutSolidDodecahedron,
glutSolidIcosahedron,
glutSolidOctahedron,
glutSolidRhombicDodecahedron,
glutSolidSierpinskiSponge,
glutSolidSphere,
glutSolidTeacup,
glutSolidTeapot,
glutSolidTeaspoon,
glutSolidTetrahedron,
glutSolidTorus,
glutSpaceballButtonFunc,
glutSpaceballMotionFunc,
glutSpaceballRotateFunc,
glutSpecialFunc,
glutSpecialUpFunc,
glutStopVideoResizing,
glutStrokeCharacter,
glutStrokeHeight,
glutStrokeLength,
glutStrokeString,
glutStrokeWidth,
glutSwapBuffers,
glutTabletButtonFunc,
glutTabletMotionFunc,
glutTimerFunc,
glutUseLayer,
glutVideoPan,
glutVideoResize,
glutVideoResizeGet,
glutVisibilityFunc,
glutWMCloseFunc,
glutWarpPointer,
glutWindowStatusFunc,
glutWireCone,
glutWireCube,
glutWireCylinder,
glutWireDodecahedron,
glutWireIcosahedron,
glutWireOctahedron,
glutWireRhombicDodecahedron,
glutWireSierpinskiSponge,
glutWireSphere,
glutWireTeacup,
glutWireTeapot,
glutWireTeaspoon,
glutWireTetrahedron,
glutWireTorus
) where
-- Make the foreign imports happy.
import Foreign.C.Types
import Control.Monad.IO.Class ( MonadIO(..) )
import Foreign.C.String ( withCString, CString )
import Foreign.Marshal.Error ( throwIf )
import Foreign.Ptr ( Ptr, FunPtr, nullFunPtr )
import Graphics.Rendering.OpenGL ( GLdouble, GLenum, GLfloat, GLint )
import System.IO.Unsafe ( unsafePerformIO )
import Graphics.UI.GLUT.Raw.Callbacks
--------------------------------------------------------------------------------
| Retrieve a GLUT API entry by name . Throws a userError when no entry with
-- the given name was found.
getAPIEntry :: String -> IO (FunPtr a)
getAPIEntry extensionEntry =
throwIfNullFunPtr ("unknown GLUT entry " ++ extensionEntry) $
getAPIEntryInternal extensionEntry
throwIfNullFunPtr :: String -> IO (FunPtr a) -> IO (FunPtr a)
throwIfNullFunPtr = throwIf (== nullFunPtr) . const
getAPIEntryInternal :: String -> IO (FunPtr a)
getAPIEntryInternal extensionEntry =
withCString extensionEntry hs_GLUT_getProcAddress
isKnown :: MonadIO m => String -> m Bool
isKnown = liftIO . fmap (/= nullFunPtr) . getAPIEntryInternal
foreign import ccall unsafe "hs_GLUT_getProcAddress"
hs_GLUT_getProcAddress :: CString -> IO (FunPtr a)
-- glutAddMenuEntry ------------------------------------------------------------
glutAddMenuEntry :: MonadIO m => Ptr CChar -> CInt -> m ()
glutAddMenuEntry v1 v2 = liftIO $ dyn_glutAddMenuEntry ptr_glutAddMenuEntry v1 v2
foreign import CALLCONV "dynamic" dyn_glutAddMenuEntry
:: FunPtr (Ptr CChar -> CInt -> IO ())
-> Ptr CChar -> CInt -> IO ()
# NOINLINE ptr_glutAddMenuEntry #
ptr_glutAddMenuEntry :: FunPtr a
ptr_glutAddMenuEntry = unsafePerformIO $ getAPIEntry "glutAddMenuEntry"
-- glutAddSubMenu --------------------------------------------------------------
glutAddSubMenu :: MonadIO m => Ptr CChar -> CInt -> m ()
glutAddSubMenu v1 v2 = liftIO $ dyn_glutAddSubMenu ptr_glutAddSubMenu v1 v2
foreign import CALLCONV "dynamic" dyn_glutAddSubMenu
:: FunPtr (Ptr CChar -> CInt -> IO ())
-> Ptr CChar -> CInt -> IO ()
# NOINLINE ptr_glutAddSubMenu #
ptr_glutAddSubMenu :: FunPtr a
ptr_glutAddSubMenu = unsafePerformIO $ getAPIEntry "glutAddSubMenu"
-- glutAppStatusFunc -----------------------------------------------------------
glutAppStatusFunc :: MonadIO m => FunPtr AppStatusFunc -> m ()
glutAppStatusFunc v1 = liftIO $ dyn_glutAppStatusFunc ptr_glutAppStatusFunc v1
foreign import CALLCONV "dynamic" dyn_glutAppStatusFunc
:: FunPtr (FunPtr AppStatusFunc -> IO ())
-> FunPtr AppStatusFunc -> IO ()
# NOINLINE ptr_glutAppStatusFunc #
ptr_glutAppStatusFunc :: FunPtr a
ptr_glutAppStatusFunc = unsafePerformIO $ getAPIEntry "glutAppStatusFunc"
-- glutAttachMenu --------------------------------------------------------------
glutAttachMenu :: MonadIO m => CInt -> m ()
glutAttachMenu v1 = liftIO $ dyn_glutAttachMenu ptr_glutAttachMenu v1
foreign import CALLCONV "dynamic" dyn_glutAttachMenu
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutAttachMenu #
ptr_glutAttachMenu :: FunPtr a
ptr_glutAttachMenu = unsafePerformIO $ getAPIEntry "glutAttachMenu"
-- glutBitmapCharacter ---------------------------------------------------------
glutBitmapCharacter :: MonadIO m => Ptr a -> CInt -> m ()
glutBitmapCharacter v1 v2 = liftIO $ dyn_glutBitmapCharacter ptr_glutBitmapCharacter v1 v2
foreign import CALLCONV "dynamic" dyn_glutBitmapCharacter
:: FunPtr (Ptr a -> CInt -> IO ())
-> Ptr a -> CInt -> IO ()
# NOINLINE ptr_glutBitmapCharacter #
ptr_glutBitmapCharacter :: FunPtr a
ptr_glutBitmapCharacter = unsafePerformIO $ getAPIEntry "glutBitmapCharacter"
-- glutBitmapHeight ------------------------------------------------------------
glutBitmapHeight :: MonadIO m => Ptr a -> m CInt
glutBitmapHeight v1 = liftIO $ dyn_glutBitmapHeight ptr_glutBitmapHeight v1
foreign import CALLCONV "dynamic" dyn_glutBitmapHeight
:: FunPtr (Ptr a -> IO CInt)
-> Ptr a -> IO CInt
# NOINLINE ptr_glutBitmapHeight #
ptr_glutBitmapHeight :: FunPtr a
ptr_glutBitmapHeight = unsafePerformIO $ getAPIEntry "glutBitmapHeight"
-- glutBitmapLength ------------------------------------------------------------
glutBitmapLength :: MonadIO m => Ptr a -> Ptr CUChar -> m CInt
glutBitmapLength v1 v2 = liftIO $ dyn_glutBitmapLength ptr_glutBitmapLength v1 v2
foreign import CALLCONV "dynamic" dyn_glutBitmapLength
:: FunPtr (Ptr a -> Ptr CUChar -> IO CInt)
-> Ptr a -> Ptr CUChar -> IO CInt
# NOINLINE ptr_glutBitmapLength #
ptr_glutBitmapLength :: FunPtr a
ptr_glutBitmapLength = unsafePerformIO $ getAPIEntry "glutBitmapLength"
-- glutBitmapString ------------------------------------------------------------
glutBitmapString :: MonadIO m => Ptr a -> Ptr CUChar -> m ()
glutBitmapString v1 v2 = liftIO $ dyn_glutBitmapString ptr_glutBitmapString v1 v2
foreign import CALLCONV "dynamic" dyn_glutBitmapString
:: FunPtr (Ptr a -> Ptr CUChar -> IO ())
-> Ptr a -> Ptr CUChar -> IO ()
# NOINLINE ptr_glutBitmapString #
ptr_glutBitmapString :: FunPtr a
ptr_glutBitmapString = unsafePerformIO $ getAPIEntry "glutBitmapString"
-- glutBitmapWidth -------------------------------------------------------------
glutBitmapWidth :: MonadIO m => Ptr a -> CInt -> m CInt
glutBitmapWidth v1 v2 = liftIO $ dyn_glutBitmapWidth ptr_glutBitmapWidth v1 v2
foreign import CALLCONV "dynamic" dyn_glutBitmapWidth
:: FunPtr (Ptr a -> CInt -> IO CInt)
-> Ptr a -> CInt -> IO CInt
# NOINLINE ptr_glutBitmapWidth #
ptr_glutBitmapWidth :: FunPtr a
ptr_glutBitmapWidth = unsafePerformIO $ getAPIEntry "glutBitmapWidth"
-- glutButtonBoxFunc -----------------------------------------------------------
glutButtonBoxFunc :: MonadIO m => FunPtr ButtonBoxFunc -> m ()
glutButtonBoxFunc v1 = liftIO $ dyn_glutButtonBoxFunc ptr_glutButtonBoxFunc v1
foreign import CALLCONV "dynamic" dyn_glutButtonBoxFunc
:: FunPtr (FunPtr ButtonBoxFunc -> IO ())
-> FunPtr ButtonBoxFunc -> IO ()
# NOINLINE ptr_glutButtonBoxFunc #
ptr_glutButtonBoxFunc :: FunPtr a
ptr_glutButtonBoxFunc = unsafePerformIO $ getAPIEntry "glutButtonBoxFunc"
-- glutChangeToMenuEntry -------------------------------------------------------
glutChangeToMenuEntry :: MonadIO m => CInt -> Ptr CChar -> CInt -> m ()
glutChangeToMenuEntry v1 v2 v3 = liftIO $ dyn_glutChangeToMenuEntry ptr_glutChangeToMenuEntry v1 v2 v3
foreign import CALLCONV "dynamic" dyn_glutChangeToMenuEntry
:: FunPtr (CInt -> Ptr CChar -> CInt -> IO ())
-> CInt -> Ptr CChar -> CInt -> IO ()
# NOINLINE ptr_glutChangeToMenuEntry #
ptr_glutChangeToMenuEntry :: FunPtr a
ptr_glutChangeToMenuEntry = unsafePerformIO $ getAPIEntry "glutChangeToMenuEntry"
-- glutChangeToSubMenu ---------------------------------------------------------
glutChangeToSubMenu :: MonadIO m => CInt -> Ptr CChar -> CInt -> m ()
glutChangeToSubMenu v1 v2 v3 = liftIO $ dyn_glutChangeToSubMenu ptr_glutChangeToSubMenu v1 v2 v3
foreign import CALLCONV "dynamic" dyn_glutChangeToSubMenu
:: FunPtr (CInt -> Ptr CChar -> CInt -> IO ())
-> CInt -> Ptr CChar -> CInt -> IO ()
# NOINLINE ptr_glutChangeToSubMenu #
ptr_glutChangeToSubMenu :: FunPtr a
ptr_glutChangeToSubMenu = unsafePerformIO $ getAPIEntry "glutChangeToSubMenu"
-- glutCloseFunc ---------------------------------------------------------------
glutCloseFunc :: MonadIO m => FunPtr CloseFunc -> m ()
glutCloseFunc v1 = liftIO $ dyn_glutCloseFunc ptr_glutCloseFunc v1
foreign import CALLCONV "dynamic" dyn_glutCloseFunc
:: FunPtr (FunPtr CloseFunc -> IO ())
-> FunPtr CloseFunc -> IO ()
# NOINLINE ptr_glutCloseFunc #
ptr_glutCloseFunc :: FunPtr a
ptr_glutCloseFunc = unsafePerformIO $ getAPIEntry "glutCloseFunc"
-- glutCopyColormap ------------------------------------------------------------
glutCopyColormap :: MonadIO m => CInt -> m ()
glutCopyColormap v1 = liftIO $ dyn_glutCopyColormap ptr_glutCopyColormap v1
foreign import CALLCONV "dynamic" dyn_glutCopyColormap
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutCopyColormap #
ptr_glutCopyColormap :: FunPtr a
ptr_glutCopyColormap = unsafePerformIO $ getAPIEntry "glutCopyColormap"
-- glutCreateMenu --------------------------------------------------------------
glutCreateMenu :: MonadIO m => FunPtr MenuFunc -> m CInt
glutCreateMenu v1 = liftIO $ dyn_glutCreateMenu ptr_glutCreateMenu v1
foreign import CALLCONV "dynamic" dyn_glutCreateMenu
:: FunPtr (FunPtr MenuFunc -> IO CInt)
-> FunPtr MenuFunc -> IO CInt
# NOINLINE ptr_glutCreateMenu #
ptr_glutCreateMenu :: FunPtr a
ptr_glutCreateMenu = unsafePerformIO $ getAPIEntry "glutCreateMenu"
-- glutCreateSubWindow ---------------------------------------------------------
glutCreateSubWindow :: MonadIO m => CInt -> CInt -> CInt -> CInt -> CInt -> m CInt
glutCreateSubWindow v1 v2 v3 v4 v5 = liftIO $ dyn_glutCreateSubWindow ptr_glutCreateSubWindow v1 v2 v3 v4 v5
foreign import CALLCONV "dynamic" dyn_glutCreateSubWindow
:: FunPtr (CInt -> CInt -> CInt -> CInt -> CInt -> IO CInt)
-> CInt -> CInt -> CInt -> CInt -> CInt -> IO CInt
# NOINLINE ptr_glutCreateSubWindow #
ptr_glutCreateSubWindow :: FunPtr a
ptr_glutCreateSubWindow = unsafePerformIO $ getAPIEntry "glutCreateSubWindow"
-- glutCreateWindow ------------------------------------------------------------
glutCreateWindow :: MonadIO m => Ptr CChar -> m CInt
glutCreateWindow v1 = liftIO $ dyn_glutCreateWindow ptr_glutCreateWindow v1
foreign import CALLCONV "dynamic" dyn_glutCreateWindow
:: FunPtr (Ptr CChar -> IO CInt)
-> Ptr CChar -> IO CInt
# NOINLINE ptr_glutCreateWindow #
ptr_glutCreateWindow :: FunPtr a
ptr_glutCreateWindow = unsafePerformIO $ getAPIEntry "glutCreateWindow"
-- glutDestroyMenu -------------------------------------------------------------
glutDestroyMenu :: MonadIO m => CInt -> m ()
glutDestroyMenu v1 = liftIO $ dyn_glutDestroyMenu ptr_glutDestroyMenu v1
foreign import CALLCONV "dynamic" dyn_glutDestroyMenu
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutDestroyMenu #
ptr_glutDestroyMenu :: FunPtr a
ptr_glutDestroyMenu = unsafePerformIO $ getAPIEntry "glutDestroyMenu"
-- glutDestroyWindow -----------------------------------------------------------
glutDestroyWindow :: MonadIO m => CInt -> m ()
glutDestroyWindow v1 = liftIO $ dyn_glutDestroyWindow ptr_glutDestroyWindow v1
foreign import CALLCONV "dynamic" dyn_glutDestroyWindow
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutDestroyWindow #
ptr_glutDestroyWindow :: FunPtr a
ptr_glutDestroyWindow = unsafePerformIO $ getAPIEntry "glutDestroyWindow"
-- glutDetachMenu --------------------------------------------------------------
glutDetachMenu :: MonadIO m => CInt -> m ()
glutDetachMenu v1 = liftIO $ dyn_glutDetachMenu ptr_glutDetachMenu v1
foreign import CALLCONV "dynamic" dyn_glutDetachMenu
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutDetachMenu #
ptr_glutDetachMenu :: FunPtr a
ptr_glutDetachMenu = unsafePerformIO $ getAPIEntry "glutDetachMenu"
-- glutDeviceGet ---------------------------------------------------------------
glutDeviceGet :: MonadIO m => GLenum -> m CInt
glutDeviceGet v1 = liftIO $ dyn_glutDeviceGet ptr_glutDeviceGet v1
foreign import CALLCONV "dynamic" dyn_glutDeviceGet
:: FunPtr (GLenum -> IO CInt)
-> GLenum -> IO CInt
# NOINLINE ptr_glutDeviceGet #
ptr_glutDeviceGet :: FunPtr a
ptr_glutDeviceGet = unsafePerformIO $ getAPIEntry "glutDeviceGet"
-- glutDialsFunc ---------------------------------------------------------------
glutDialsFunc :: MonadIO m => FunPtr DialsFunc -> m ()
glutDialsFunc v1 = liftIO $ dyn_glutDialsFunc ptr_glutDialsFunc v1
foreign import CALLCONV "dynamic" dyn_glutDialsFunc
:: FunPtr (FunPtr DialsFunc -> IO ())
-> FunPtr DialsFunc -> IO ()
# NOINLINE ptr_glutDialsFunc #
ptr_glutDialsFunc :: FunPtr a
ptr_glutDialsFunc = unsafePerformIO $ getAPIEntry "glutDialsFunc"
-- glutDisplayFunc -------------------------------------------------------------
glutDisplayFunc :: MonadIO m => FunPtr DisplayFunc -> m ()
glutDisplayFunc v1 = liftIO $ dyn_glutDisplayFunc ptr_glutDisplayFunc v1
foreign import CALLCONV "dynamic" dyn_glutDisplayFunc
:: FunPtr (FunPtr DisplayFunc -> IO ())
-> FunPtr DisplayFunc -> IO ()
# NOINLINE ptr_glutDisplayFunc #
ptr_glutDisplayFunc :: FunPtr a
ptr_glutDisplayFunc = unsafePerformIO $ getAPIEntry "glutDisplayFunc"
-- glutEnterGameMode -----------------------------------------------------------
glutEnterGameMode :: MonadIO m => m CInt
glutEnterGameMode = liftIO $ dyn_glutEnterGameMode ptr_glutEnterGameMode
foreign import CALLCONV "dynamic" dyn_glutEnterGameMode
:: FunPtr (IO CInt)
-> IO CInt
# NOINLINE ptr_glutEnterGameMode #
ptr_glutEnterGameMode :: FunPtr a
ptr_glutEnterGameMode = unsafePerformIO $ getAPIEntry "glutEnterGameMode"
-- glutEntryFunc ---------------------------------------------------------------
glutEntryFunc :: MonadIO m => FunPtr EntryFunc -> m ()
glutEntryFunc v1 = liftIO $ dyn_glutEntryFunc ptr_glutEntryFunc v1
foreign import CALLCONV "dynamic" dyn_glutEntryFunc
:: FunPtr (FunPtr EntryFunc -> IO ())
-> FunPtr EntryFunc -> IO ()
# NOINLINE ptr_glutEntryFunc #
ptr_glutEntryFunc :: FunPtr a
ptr_glutEntryFunc = unsafePerformIO $ getAPIEntry "glutEntryFunc"
-- glutEstablishOverlay --------------------------------------------------------
glutEstablishOverlay :: MonadIO m => m ()
glutEstablishOverlay = liftIO $ dyn_glutEstablishOverlay ptr_glutEstablishOverlay
foreign import CALLCONV "dynamic" dyn_glutEstablishOverlay
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutEstablishOverlay #
ptr_glutEstablishOverlay :: FunPtr a
ptr_glutEstablishOverlay = unsafePerformIO $ getAPIEntry "glutEstablishOverlay"
-- glutExit --------------------------------------------------------------------
glutExit :: MonadIO m => m ()
glutExit = liftIO $ dyn_glutExit ptr_glutExit
foreign import CALLCONV "dynamic" dyn_glutExit
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutExit #
ptr_glutExit :: FunPtr a
ptr_glutExit = unsafePerformIO $ getAPIEntry "glutExit"
-- glutExtensionSupported ------------------------------------------------------
glutExtensionSupported :: MonadIO m => Ptr CChar -> m CInt
glutExtensionSupported v1 = liftIO $ dyn_glutExtensionSupported ptr_glutExtensionSupported v1
foreign import CALLCONV "dynamic" dyn_glutExtensionSupported
:: FunPtr (Ptr CChar -> IO CInt)
-> Ptr CChar -> IO CInt
# NOINLINE ptr_glutExtensionSupported #
ptr_glutExtensionSupported :: FunPtr a
ptr_glutExtensionSupported = unsafePerformIO $ getAPIEntry "glutExtensionSupported"
-- glutForceJoystickFunc -------------------------------------------------------
glutForceJoystickFunc :: MonadIO m => m ()
glutForceJoystickFunc = liftIO $ dyn_glutForceJoystickFunc ptr_glutForceJoystickFunc
foreign import CALLCONV "dynamic" dyn_glutForceJoystickFunc
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutForceJoystickFunc #
ptr_glutForceJoystickFunc :: FunPtr a
ptr_glutForceJoystickFunc = unsafePerformIO $ getAPIEntry "glutForceJoystickFunc"
-- glutFullScreen --------------------------------------------------------------
glutFullScreen :: MonadIO m => m ()
glutFullScreen = liftIO $ dyn_glutFullScreen ptr_glutFullScreen
foreign import CALLCONV "dynamic" dyn_glutFullScreen
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutFullScreen #
ptr_glutFullScreen :: FunPtr a
ptr_glutFullScreen = unsafePerformIO $ getAPIEntry "glutFullScreen"
-- glutFullScreenToggle --------------------------------------------------------
glutFullScreenToggle :: MonadIO m => m ()
glutFullScreenToggle = liftIO $ dyn_glutFullScreenToggle ptr_glutFullScreenToggle
foreign import CALLCONV "dynamic" dyn_glutFullScreenToggle
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutFullScreenToggle #
ptr_glutFullScreenToggle :: FunPtr a
ptr_glutFullScreenToggle = unsafePerformIO $ getAPIEntry "glutFullScreenToggle"
glutGameModeGet -------------------------------------------------------------
glutGameModeGet :: MonadIO m => GLenum -> m CInt
glutGameModeGet v1 = liftIO $ dyn_glutGameModeGet ptr_glutGameModeGet v1
foreign import CALLCONV "dynamic" dyn_glutGameModeGet
:: FunPtr (GLenum -> IO CInt)
-> GLenum -> IO CInt
# NOINLINE ptr_glutGameModeGet #
ptr_glutGameModeGet :: FunPtr a
ptr_glutGameModeGet = unsafePerformIO $ getAPIEntry "glutGameModeGet"
-- glutGameModeString ----------------------------------------------------------
glutGameModeString :: MonadIO m => Ptr CChar -> m ()
glutGameModeString v1 = liftIO $ dyn_glutGameModeString ptr_glutGameModeString v1
foreign import CALLCONV "dynamic" dyn_glutGameModeString
:: FunPtr (Ptr CChar -> IO ())
-> Ptr CChar -> IO ()
# NOINLINE ptr_glutGameModeString #
ptr_glutGameModeString :: FunPtr a
ptr_glutGameModeString = unsafePerformIO $ getAPIEntry "glutGameModeString"
-- glutGet ---------------------------------------------------------------------
glutGet :: MonadIO m => GLenum -> m CInt
glutGet v1 = liftIO $ dyn_glutGet ptr_glutGet v1
foreign import CALLCONV "dynamic" dyn_glutGet
:: FunPtr (GLenum -> IO CInt)
-> GLenum -> IO CInt
# NOINLINE ptr_glutGet #
ptr_glutGet :: FunPtr a
ptr_glutGet = unsafePerformIO $ getAPIEntry "glutGet"
-- glutGetColor ----------------------------------------------------------------
glutGetColor :: MonadIO m => CInt -> CInt -> m GLfloat
glutGetColor v1 v2 = liftIO $ dyn_glutGetColor ptr_glutGetColor v1 v2
foreign import CALLCONV "dynamic" dyn_glutGetColor
:: FunPtr (CInt -> CInt -> IO GLfloat)
-> CInt -> CInt -> IO GLfloat
# NOINLINE ptr_glutGetColor #
ptr_glutGetColor :: FunPtr a
ptr_glutGetColor = unsafePerformIO $ getAPIEntry "glutGetColor"
-- glutGetMenu -----------------------------------------------------------------
glutGetMenu :: MonadIO m => m CInt
glutGetMenu = liftIO $ dyn_glutGetMenu ptr_glutGetMenu
foreign import CALLCONV "dynamic" dyn_glutGetMenu
:: FunPtr (IO CInt)
-> IO CInt
# NOINLINE ptr_glutGetMenu #
ptr_glutGetMenu :: FunPtr a
ptr_glutGetMenu = unsafePerformIO $ getAPIEntry "glutGetMenu"
glutGetMenuData -------------------------------------------------------------
glutGetMenuData :: MonadIO m => m (Ptr a)
glutGetMenuData = liftIO $ dyn_glutGetMenuData ptr_glutGetMenuData
foreign import CALLCONV "dynamic" dyn_glutGetMenuData
:: FunPtr (IO (Ptr a))
-> IO (Ptr a)
# NOINLINE ptr_glutGetMenuData #
ptr_glutGetMenuData :: FunPtr a
ptr_glutGetMenuData = unsafePerformIO $ getAPIEntry "glutGetMenuData"
-- glutGetModeValues -----------------------------------------------------------
glutGetModeValues :: MonadIO m => GLenum -> Ptr CInt -> m (Ptr CInt)
glutGetModeValues v1 v2 = liftIO $ dyn_glutGetModeValues ptr_glutGetModeValues v1 v2
foreign import CALLCONV "dynamic" dyn_glutGetModeValues
:: FunPtr (GLenum -> Ptr CInt -> IO (Ptr CInt))
-> GLenum -> Ptr CInt -> IO (Ptr CInt)
# NOINLINE ptr_glutGetModeValues #
ptr_glutGetModeValues :: FunPtr a
ptr_glutGetModeValues = unsafePerformIO $ getAPIEntry "glutGetModeValues"
-- glutGetModifiers ------------------------------------------------------------
glutGetModifiers :: MonadIO m => m CInt
glutGetModifiers = liftIO $ dyn_glutGetModifiers ptr_glutGetModifiers
foreign import CALLCONV "dynamic" dyn_glutGetModifiers
:: FunPtr (IO CInt)
-> IO CInt
# NOINLINE ptr_glutGetModifiers #
ptr_glutGetModifiers :: FunPtr a
ptr_glutGetModifiers = unsafePerformIO $ getAPIEntry "glutGetModifiers"
glutGetProcAddress ----------------------------------------------------------
glutGetProcAddress :: MonadIO m => Ptr CChar -> m (FunPtr a)
glutGetProcAddress v1 = liftIO $ dyn_glutGetProcAddress ptr_glutGetProcAddress v1
foreign import CALLCONV "dynamic" dyn_glutGetProcAddress
:: FunPtr (Ptr CChar -> IO (FunPtr a))
-> Ptr CChar -> IO (FunPtr a)
# NOINLINE ptr_glutGetProcAddress #
ptr_glutGetProcAddress :: FunPtr a
ptr_glutGetProcAddress = unsafePerformIO $ getAPIEntry "glutGetProcAddress"
-- glutGetWindow ---------------------------------------------------------------
glutGetWindow :: MonadIO m => m CInt
glutGetWindow = liftIO $ dyn_glutGetWindow ptr_glutGetWindow
foreign import CALLCONV "dynamic" dyn_glutGetWindow
:: FunPtr (IO CInt)
-> IO CInt
# NOINLINE ptr_glutGetWindow #
ptr_glutGetWindow :: FunPtr a
ptr_glutGetWindow = unsafePerformIO $ getAPIEntry "glutGetWindow"
-- glutGetWindowData -----------------------------------------------------------
glutGetWindowData :: MonadIO m => m (Ptr a)
glutGetWindowData = liftIO $ dyn_glutGetWindowData ptr_glutGetWindowData
foreign import CALLCONV "dynamic" dyn_glutGetWindowData
:: FunPtr (IO (Ptr a))
-> IO (Ptr a)
# NOINLINE ptr_glutGetWindowData #
ptr_glutGetWindowData :: FunPtr a
ptr_glutGetWindowData = unsafePerformIO $ getAPIEntry "glutGetWindowData"
-- glutHideOverlay -------------------------------------------------------------
glutHideOverlay :: MonadIO m => m ()
glutHideOverlay = liftIO $ dyn_glutHideOverlay ptr_glutHideOverlay
foreign import CALLCONV "dynamic" dyn_glutHideOverlay
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutHideOverlay #
ptr_glutHideOverlay :: FunPtr a
ptr_glutHideOverlay = unsafePerformIO $ getAPIEntry "glutHideOverlay"
-- glutHideWindow --------------------------------------------------------------
glutHideWindow :: MonadIO m => m ()
glutHideWindow = liftIO $ dyn_glutHideWindow ptr_glutHideWindow
foreign import CALLCONV "dynamic" dyn_glutHideWindow
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutHideWindow #
ptr_glutHideWindow :: FunPtr a
ptr_glutHideWindow = unsafePerformIO $ getAPIEntry "glutHideWindow"
-- glutIconifyWindow -----------------------------------------------------------
glutIconifyWindow :: MonadIO m => m ()
glutIconifyWindow = liftIO $ dyn_glutIconifyWindow ptr_glutIconifyWindow
foreign import CALLCONV "dynamic" dyn_glutIconifyWindow
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutIconifyWindow #
ptr_glutIconifyWindow :: FunPtr a
ptr_glutIconifyWindow = unsafePerformIO $ getAPIEntry "glutIconifyWindow"
-- glutIdleFunc ----------------------------------------------------------------
glutIdleFunc :: MonadIO m => FunPtr IdleFunc -> m ()
glutIdleFunc v1 = liftIO $ dyn_glutIdleFunc ptr_glutIdleFunc v1
foreign import CALLCONV "dynamic" dyn_glutIdleFunc
:: FunPtr (FunPtr IdleFunc -> IO ())
-> FunPtr IdleFunc -> IO ()
# NOINLINE ptr_glutIdleFunc #
ptr_glutIdleFunc :: FunPtr a
ptr_glutIdleFunc = unsafePerformIO $ getAPIEntry "glutIdleFunc"
-- glutIgnoreKeyRepeat ---------------------------------------------------------
glutIgnoreKeyRepeat :: MonadIO m => CInt -> m ()
glutIgnoreKeyRepeat v1 = liftIO $ dyn_glutIgnoreKeyRepeat ptr_glutIgnoreKeyRepeat v1
foreign import CALLCONV "dynamic" dyn_glutIgnoreKeyRepeat
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
{-# NOINLINE ptr_glutIgnoreKeyRepeat #-}
ptr_glutIgnoreKeyRepeat :: FunPtr a
ptr_glutIgnoreKeyRepeat = unsafePerformIO $ getAPIEntry "glutIgnoreKeyRepeat"
-- glutInit --------------------------------------------------------------------
glutInit :: MonadIO m => Ptr CInt -> Ptr (Ptr CChar) -> m ()
glutInit v1 v2 = liftIO $ dyn_glutInit ptr_glutInit v1 v2
foreign import CALLCONV "dynamic" dyn_glutInit
:: FunPtr (Ptr CInt -> Ptr (Ptr CChar) -> IO ())
-> Ptr CInt -> Ptr (Ptr CChar) -> IO ()
# NOINLINE ptr_glutInit #
ptr_glutInit :: FunPtr a
ptr_glutInit = unsafePerformIO $ getAPIEntry "glutInit"
-- glutInitContextFlags --------------------------------------------------------
glutInitContextFlags :: MonadIO m => CInt -> m ()
glutInitContextFlags v1 = liftIO $ dyn_glutInitContextFlags ptr_glutInitContextFlags v1
foreign import CALLCONV "dynamic" dyn_glutInitContextFlags
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutInitContextFlags #
ptr_glutInitContextFlags :: FunPtr a
ptr_glutInitContextFlags = unsafePerformIO $ getAPIEntry "glutInitContextFlags"
-- glutInitContextFunc ---------------------------------------------------------
glutInitContextFunc :: MonadIO m => FunPtr InitContextFunc -> m ()
glutInitContextFunc v1 = liftIO $ dyn_glutInitContextFunc ptr_glutInitContextFunc v1
foreign import CALLCONV "dynamic" dyn_glutInitContextFunc
:: FunPtr (FunPtr InitContextFunc -> IO ())
-> FunPtr InitContextFunc -> IO ()
# NOINLINE ptr_glutInitContextFunc #
ptr_glutInitContextFunc :: FunPtr a
ptr_glutInitContextFunc = unsafePerformIO $ getAPIEntry "glutInitContextFunc"
glutInitContextProfile ------------------------------------------------------
glutInitContextProfile :: MonadIO m => CInt -> m ()
glutInitContextProfile v1 = liftIO $ dyn_glutInitContextProfile ptr_glutInitContextProfile v1
foreign import CALLCONV "dynamic" dyn_glutInitContextProfile
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutInitContextProfile #
ptr_glutInitContextProfile :: FunPtr a
ptr_glutInitContextProfile = unsafePerformIO $ getAPIEntry "glutInitContextProfile"
-- glutInitContextVersion ------------------------------------------------------
glutInitContextVersion :: MonadIO m => CInt -> CInt -> m ()
glutInitContextVersion v1 v2 = liftIO $ dyn_glutInitContextVersion ptr_glutInitContextVersion v1 v2
foreign import CALLCONV "dynamic" dyn_glutInitContextVersion
:: FunPtr (CInt -> CInt -> IO ())
-> CInt -> CInt -> IO ()
# NOINLINE ptr_glutInitContextVersion #
ptr_glutInitContextVersion :: FunPtr a
ptr_glutInitContextVersion = unsafePerformIO $ getAPIEntry "glutInitContextVersion"
-- glutInitDisplayMode ---------------------------------------------------------
glutInitDisplayMode :: MonadIO m => CUInt -> m ()
glutInitDisplayMode v1 = liftIO $ dyn_glutInitDisplayMode ptr_glutInitDisplayMode v1
foreign import CALLCONV "dynamic" dyn_glutInitDisplayMode
:: FunPtr (CUInt -> IO ())
-> CUInt -> IO ()
# NOINLINE ptr_glutInitDisplayMode #
ptr_glutInitDisplayMode :: FunPtr a
ptr_glutInitDisplayMode = unsafePerformIO $ getAPIEntry "glutInitDisplayMode"
-- glutInitDisplayString -------------------------------------------------------
glutInitDisplayString :: MonadIO m => Ptr CChar -> m ()
glutInitDisplayString v1 = liftIO $ dyn_glutInitDisplayString ptr_glutInitDisplayString v1
foreign import CALLCONV "dynamic" dyn_glutInitDisplayString
:: FunPtr (Ptr CChar -> IO ())
-> Ptr CChar -> IO ()
# NOINLINE ptr_glutInitDisplayString #
ptr_glutInitDisplayString :: FunPtr a
ptr_glutInitDisplayString = unsafePerformIO $ getAPIEntry "glutInitDisplayString"
-- glutInitWindowPosition ------------------------------------------------------
glutInitWindowPosition :: MonadIO m => CInt -> CInt -> m ()
glutInitWindowPosition v1 v2 = liftIO $ dyn_glutInitWindowPosition ptr_glutInitWindowPosition v1 v2
foreign import CALLCONV "dynamic" dyn_glutInitWindowPosition
:: FunPtr (CInt -> CInt -> IO ())
-> CInt -> CInt -> IO ()
# NOINLINE ptr_glutInitWindowPosition #
ptr_glutInitWindowPosition :: FunPtr a
ptr_glutInitWindowPosition = unsafePerformIO $ getAPIEntry "glutInitWindowPosition"
-- glutInitWindowSize ----------------------------------------------------------
glutInitWindowSize :: MonadIO m => CInt -> CInt -> m ()
glutInitWindowSize v1 v2 = liftIO $ dyn_glutInitWindowSize ptr_glutInitWindowSize v1 v2
foreign import CALLCONV "dynamic" dyn_glutInitWindowSize
:: FunPtr (CInt -> CInt -> IO ())
-> CInt -> CInt -> IO ()
# NOINLINE ptr_glutInitWindowSize #
ptr_glutInitWindowSize :: FunPtr a
ptr_glutInitWindowSize = unsafePerformIO $ getAPIEntry "glutInitWindowSize"
-- glutJoystickFunc ------------------------------------------------------------
glutJoystickFunc :: MonadIO m => FunPtr JoystickFunc -> CInt -> m ()
glutJoystickFunc v1 v2 = liftIO $ dyn_glutJoystickFunc ptr_glutJoystickFunc v1 v2
foreign import CALLCONV "dynamic" dyn_glutJoystickFunc
:: FunPtr (FunPtr JoystickFunc -> CInt -> IO ())
-> FunPtr JoystickFunc -> CInt -> IO ()
# NOINLINE ptr_glutJoystickFunc #
ptr_glutJoystickFunc :: FunPtr a
ptr_glutJoystickFunc = unsafePerformIO $ getAPIEntry "glutJoystickFunc"
-- glutKeyboardFunc ------------------------------------------------------------
glutKeyboardFunc :: MonadIO m => FunPtr KeyboardFunc -> m ()
glutKeyboardFunc v1 = liftIO $ dyn_glutKeyboardFunc ptr_glutKeyboardFunc v1
foreign import CALLCONV "dynamic" dyn_glutKeyboardFunc
:: FunPtr (FunPtr KeyboardFunc -> IO ())
-> FunPtr KeyboardFunc -> IO ()
# NOINLINE ptr_glutKeyboardFunc #
ptr_glutKeyboardFunc :: FunPtr a
ptr_glutKeyboardFunc = unsafePerformIO $ getAPIEntry "glutKeyboardFunc"
-- glutKeyboardUpFunc ----------------------------------------------------------
glutKeyboardUpFunc :: MonadIO m => FunPtr KeyboardUpFunc -> m ()
glutKeyboardUpFunc v1 = liftIO $ dyn_glutKeyboardUpFunc ptr_glutKeyboardUpFunc v1
foreign import CALLCONV "dynamic" dyn_glutKeyboardUpFunc
:: FunPtr (FunPtr KeyboardUpFunc -> IO ())
-> FunPtr KeyboardUpFunc -> IO ()
# NOINLINE ptr_glutKeyboardUpFunc #
ptr_glutKeyboardUpFunc :: FunPtr a
ptr_glutKeyboardUpFunc = unsafePerformIO $ getAPIEntry "glutKeyboardUpFunc"
glutLayerGet ----------------------------------------------------------------
glutLayerGet :: MonadIO m => GLenum -> m CInt
glutLayerGet v1 = liftIO $ dyn_glutLayerGet ptr_glutLayerGet v1
foreign import CALLCONV "dynamic" dyn_glutLayerGet
:: FunPtr (GLenum -> IO CInt)
-> GLenum -> IO CInt
# NOINLINE ptr_glutLayerGet #
ptr_glutLayerGet :: FunPtr a
ptr_glutLayerGet = unsafePerformIO $ getAPIEntry "glutLayerGet"
-- glutLeaveFullScreen ---------------------------------------------------------
glutLeaveFullScreen :: MonadIO m => m ()
glutLeaveFullScreen = liftIO $ dyn_glutLeaveFullScreen ptr_glutLeaveFullScreen
foreign import CALLCONV "dynamic" dyn_glutLeaveFullScreen
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutLeaveFullScreen #
ptr_glutLeaveFullScreen :: FunPtr a
ptr_glutLeaveFullScreen = unsafePerformIO $ getAPIEntry "glutLeaveFullScreen"
glutLeaveGameMode -----------------------------------------------------------
glutLeaveGameMode :: MonadIO m => m ()
glutLeaveGameMode = liftIO $ dyn_glutLeaveGameMode ptr_glutLeaveGameMode
foreign import CALLCONV "dynamic" dyn_glutLeaveGameMode
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutLeaveGameMode #
ptr_glutLeaveGameMode :: FunPtr a
ptr_glutLeaveGameMode = unsafePerformIO $ getAPIEntry "glutLeaveGameMode"
-- glutLeaveMainLoop -----------------------------------------------------------
glutLeaveMainLoop :: MonadIO m => m ()
glutLeaveMainLoop = liftIO $ dyn_glutLeaveMainLoop ptr_glutLeaveMainLoop
foreign import CALLCONV "dynamic" dyn_glutLeaveMainLoop
:: FunPtr (IO ())
-> IO ()
{-# NOINLINE ptr_glutLeaveMainLoop #-}
ptr_glutLeaveMainLoop :: FunPtr a
ptr_glutLeaveMainLoop = unsafePerformIO $ getAPIEntry "glutLeaveMainLoop"
-- glutMainLoop ----------------------------------------------------------------
glutMainLoop :: MonadIO m => m ()
glutMainLoop = liftIO $ dyn_glutMainLoop ptr_glutMainLoop
foreign import CALLCONV "dynamic" dyn_glutMainLoop
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutMainLoop #
ptr_glutMainLoop :: FunPtr a
ptr_glutMainLoop = unsafePerformIO $ getAPIEntry "glutMainLoop"
-- glutMainLoopEvent -----------------------------------------------------------
glutMainLoopEvent :: MonadIO m => m ()
glutMainLoopEvent = liftIO $ dyn_glutMainLoopEvent ptr_glutMainLoopEvent
foreign import CALLCONV "dynamic" dyn_glutMainLoopEvent
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutMainLoopEvent #
ptr_glutMainLoopEvent :: FunPtr a
ptr_glutMainLoopEvent = unsafePerformIO $ getAPIEntry "glutMainLoopEvent"
-- glutMenuDestroyFunc ---------------------------------------------------------
glutMenuDestroyFunc :: MonadIO m => FunPtr MenuDestroyFunc -> m ()
glutMenuDestroyFunc v1 = liftIO $ dyn_glutMenuDestroyFunc ptr_glutMenuDestroyFunc v1
foreign import CALLCONV "dynamic" dyn_glutMenuDestroyFunc
:: FunPtr (FunPtr MenuDestroyFunc -> IO ())
-> FunPtr MenuDestroyFunc -> IO ()
# NOINLINE ptr_glutMenuDestroyFunc #
ptr_glutMenuDestroyFunc :: FunPtr a
ptr_glutMenuDestroyFunc = unsafePerformIO $ getAPIEntry "glutMenuDestroyFunc"
-- glutMenuStateFunc -----------------------------------------------------------
glutMenuStateFunc :: MonadIO m => FunPtr MenuStateFunc -> m ()
glutMenuStateFunc v1 = liftIO $ dyn_glutMenuStateFunc ptr_glutMenuStateFunc v1
foreign import CALLCONV "dynamic" dyn_glutMenuStateFunc
:: FunPtr (FunPtr MenuStateFunc -> IO ())
-> FunPtr MenuStateFunc -> IO ()
# NOINLINE ptr_glutMenuStateFunc #
ptr_glutMenuStateFunc :: FunPtr a
ptr_glutMenuStateFunc = unsafePerformIO $ getAPIEntry "glutMenuStateFunc"
-- glutMenuStatusFunc ----------------------------------------------------------
glutMenuStatusFunc :: MonadIO m => FunPtr MenuStatusFunc -> m ()
glutMenuStatusFunc v1 = liftIO $ dyn_glutMenuStatusFunc ptr_glutMenuStatusFunc v1
foreign import CALLCONV "dynamic" dyn_glutMenuStatusFunc
:: FunPtr (FunPtr MenuStatusFunc -> IO ())
-> FunPtr MenuStatusFunc -> IO ()
# NOINLINE ptr_glutMenuStatusFunc #
ptr_glutMenuStatusFunc :: FunPtr a
ptr_glutMenuStatusFunc = unsafePerformIO $ getAPIEntry "glutMenuStatusFunc"
-- glutMotionFunc --------------------------------------------------------------
glutMotionFunc :: MonadIO m => FunPtr MotionFunc -> m ()
glutMotionFunc v1 = liftIO $ dyn_glutMotionFunc ptr_glutMotionFunc v1
foreign import CALLCONV "dynamic" dyn_glutMotionFunc
:: FunPtr (FunPtr MotionFunc -> IO ())
-> FunPtr MotionFunc -> IO ()
# NOINLINE ptr_glutMotionFunc #
ptr_glutMotionFunc :: FunPtr a
ptr_glutMotionFunc = unsafePerformIO $ getAPIEntry "glutMotionFunc"
-- glutMouseFunc ---------------------------------------------------------------
glutMouseFunc :: MonadIO m => FunPtr MouseFunc -> m ()
glutMouseFunc v1 = liftIO $ dyn_glutMouseFunc ptr_glutMouseFunc v1
foreign import CALLCONV "dynamic" dyn_glutMouseFunc
:: FunPtr (FunPtr MouseFunc -> IO ())
-> FunPtr MouseFunc -> IO ()
# NOINLINE ptr_glutMouseFunc #
ptr_glutMouseFunc :: FunPtr a
ptr_glutMouseFunc = unsafePerformIO $ getAPIEntry "glutMouseFunc"
-- glutMouseWheelFunc ----------------------------------------------------------
glutMouseWheelFunc :: MonadIO m => FunPtr MouseWheelFunc -> m ()
glutMouseWheelFunc v1 = liftIO $ dyn_glutMouseWheelFunc ptr_glutMouseWheelFunc v1
foreign import CALLCONV "dynamic" dyn_glutMouseWheelFunc
:: FunPtr (FunPtr MouseWheelFunc -> IO ())
-> FunPtr MouseWheelFunc -> IO ()
# NOINLINE ptr_glutMouseWheelFunc #
ptr_glutMouseWheelFunc :: FunPtr a
ptr_glutMouseWheelFunc = unsafePerformIO $ getAPIEntry "glutMouseWheelFunc"
-- glutMultiButtonFunc ---------------------------------------------------------
glutMultiButtonFunc :: MonadIO m => FunPtr MultiButtonFunc -> m ()
glutMultiButtonFunc v1 = liftIO $ dyn_glutMultiButtonFunc ptr_glutMultiButtonFunc v1
foreign import CALLCONV "dynamic" dyn_glutMultiButtonFunc
:: FunPtr (FunPtr MultiButtonFunc -> IO ())
-> FunPtr MultiButtonFunc -> IO ()
# NOINLINE ptr_glutMultiButtonFunc #
ptr_glutMultiButtonFunc :: FunPtr a
ptr_glutMultiButtonFunc = unsafePerformIO $ getAPIEntry "glutMultiButtonFunc"
-- glutMultiEntryFunc ----------------------------------------------------------
glutMultiEntryFunc :: MonadIO m => FunPtr MultiEntryFunc -> m ()
glutMultiEntryFunc v1 = liftIO $ dyn_glutMultiEntryFunc ptr_glutMultiEntryFunc v1
foreign import CALLCONV "dynamic" dyn_glutMultiEntryFunc
:: FunPtr (FunPtr MultiEntryFunc -> IO ())
-> FunPtr MultiEntryFunc -> IO ()
# NOINLINE ptr_glutMultiEntryFunc #
ptr_glutMultiEntryFunc :: FunPtr a
ptr_glutMultiEntryFunc = unsafePerformIO $ getAPIEntry "glutMultiEntryFunc"
-- glutMultiMotionFunc ---------------------------------------------------------
glutMultiMotionFunc :: MonadIO m => FunPtr MultiMotionFunc -> m ()
glutMultiMotionFunc v1 = liftIO $ dyn_glutMultiMotionFunc ptr_glutMultiMotionFunc v1
foreign import CALLCONV "dynamic" dyn_glutMultiMotionFunc
:: FunPtr (FunPtr MultiMotionFunc -> IO ())
-> FunPtr MultiMotionFunc -> IO ()
# NOINLINE ptr_glutMultiMotionFunc #
ptr_glutMultiMotionFunc :: FunPtr a
ptr_glutMultiMotionFunc = unsafePerformIO $ getAPIEntry "glutMultiMotionFunc"
-- glutMultiPassiveFunc --------------------------------------------------------
glutMultiPassiveFunc :: MonadIO m => FunPtr MultiPassiveFunc -> m ()
glutMultiPassiveFunc v1 = liftIO $ dyn_glutMultiPassiveFunc ptr_glutMultiPassiveFunc v1
foreign import CALLCONV "dynamic" dyn_glutMultiPassiveFunc
:: FunPtr (FunPtr MultiPassiveFunc -> IO ())
-> FunPtr MultiPassiveFunc -> IO ()
# NOINLINE ptr_glutMultiPassiveFunc #
ptr_glutMultiPassiveFunc :: FunPtr a
ptr_glutMultiPassiveFunc = unsafePerformIO $ getAPIEntry "glutMultiPassiveFunc"
glutOverlayDisplayFunc ------------------------------------------------------
glutOverlayDisplayFunc :: MonadIO m => FunPtr OverlayDisplayFunc -> m ()
glutOverlayDisplayFunc v1 = liftIO $ dyn_glutOverlayDisplayFunc ptr_glutOverlayDisplayFunc v1
foreign import CALLCONV "dynamic" dyn_glutOverlayDisplayFunc
:: FunPtr (FunPtr OverlayDisplayFunc -> IO ())
-> FunPtr OverlayDisplayFunc -> IO ()
# NOINLINE ptr_glutOverlayDisplayFunc #
ptr_glutOverlayDisplayFunc :: FunPtr a
ptr_glutOverlayDisplayFunc = unsafePerformIO $ getAPIEntry "glutOverlayDisplayFunc"
-- glutPassiveMotionFunc -------------------------------------------------------
glutPassiveMotionFunc :: MonadIO m => FunPtr PassiveMotionFunc -> m ()
glutPassiveMotionFunc v1 = liftIO $ dyn_glutPassiveMotionFunc ptr_glutPassiveMotionFunc v1
foreign import CALLCONV "dynamic" dyn_glutPassiveMotionFunc
:: FunPtr (FunPtr PassiveMotionFunc -> IO ())
-> FunPtr PassiveMotionFunc -> IO ()
# NOINLINE ptr_glutPassiveMotionFunc #
ptr_glutPassiveMotionFunc :: FunPtr a
ptr_glutPassiveMotionFunc = unsafePerformIO $ getAPIEntry "glutPassiveMotionFunc"
-- glutPopWindow ---------------------------------------------------------------
glutPopWindow :: MonadIO m => m ()
glutPopWindow = liftIO $ dyn_glutPopWindow ptr_glutPopWindow
foreign import CALLCONV "dynamic" dyn_glutPopWindow
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutPopWindow #
ptr_glutPopWindow :: FunPtr a
ptr_glutPopWindow = unsafePerformIO $ getAPIEntry "glutPopWindow"
-- glutPositionFunc ------------------------------------------------------------
glutPositionFunc :: MonadIO m => FunPtr PositionFunc -> m ()
glutPositionFunc v1 = liftIO $ dyn_glutPositionFunc ptr_glutPositionFunc v1
foreign import CALLCONV "dynamic" dyn_glutPositionFunc
:: FunPtr (FunPtr PositionFunc -> IO ())
-> FunPtr PositionFunc -> IO ()
# NOINLINE ptr_glutPositionFunc #
ptr_glutPositionFunc :: FunPtr a
ptr_glutPositionFunc = unsafePerformIO $ getAPIEntry "glutPositionFunc"
-- glutPositionWindow ----------------------------------------------------------
glutPositionWindow :: MonadIO m => CInt -> CInt -> m ()
glutPositionWindow v1 v2 = liftIO $ dyn_glutPositionWindow ptr_glutPositionWindow v1 v2
foreign import CALLCONV "dynamic" dyn_glutPositionWindow
:: FunPtr (CInt -> CInt -> IO ())
-> CInt -> CInt -> IO ()
# NOINLINE ptr_glutPositionWindow #
ptr_glutPositionWindow :: FunPtr a
ptr_glutPositionWindow = unsafePerformIO $ getAPIEntry "glutPositionWindow"
-- glutPostOverlayRedisplay ----------------------------------------------------
glutPostOverlayRedisplay :: MonadIO m => m ()
glutPostOverlayRedisplay = liftIO $ dyn_glutPostOverlayRedisplay ptr_glutPostOverlayRedisplay
foreign import CALLCONV "dynamic" dyn_glutPostOverlayRedisplay
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutPostOverlayRedisplay #
ptr_glutPostOverlayRedisplay :: FunPtr a
ptr_glutPostOverlayRedisplay = unsafePerformIO $ getAPIEntry "glutPostOverlayRedisplay"
-- glutPostRedisplay -----------------------------------------------------------
glutPostRedisplay :: MonadIO m => m ()
glutPostRedisplay = liftIO $ dyn_glutPostRedisplay ptr_glutPostRedisplay
foreign import CALLCONV "dynamic" dyn_glutPostRedisplay
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutPostRedisplay #
ptr_glutPostRedisplay :: FunPtr a
ptr_glutPostRedisplay = unsafePerformIO $ getAPIEntry "glutPostRedisplay"
-- glutPostWindowOverlayRedisplay ----------------------------------------------
glutPostWindowOverlayRedisplay :: MonadIO m => CInt -> m ()
glutPostWindowOverlayRedisplay v1 = liftIO $ dyn_glutPostWindowOverlayRedisplay ptr_glutPostWindowOverlayRedisplay v1
foreign import CALLCONV "dynamic" dyn_glutPostWindowOverlayRedisplay
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutPostWindowOverlayRedisplay #
ptr_glutPostWindowOverlayRedisplay :: FunPtr a
ptr_glutPostWindowOverlayRedisplay = unsafePerformIO $ getAPIEntry "glutPostWindowOverlayRedisplay"
-- glutPostWindowRedisplay -----------------------------------------------------
glutPostWindowRedisplay :: MonadIO m => CInt -> m ()
glutPostWindowRedisplay v1 = liftIO $ dyn_glutPostWindowRedisplay ptr_glutPostWindowRedisplay v1
foreign import CALLCONV "dynamic" dyn_glutPostWindowRedisplay
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutPostWindowRedisplay #
ptr_glutPostWindowRedisplay :: FunPtr a
ptr_glutPostWindowRedisplay = unsafePerformIO $ getAPIEntry "glutPostWindowRedisplay"
-- glutPushWindow --------------------------------------------------------------
glutPushWindow :: MonadIO m => m ()
glutPushWindow = liftIO $ dyn_glutPushWindow ptr_glutPushWindow
foreign import CALLCONV "dynamic" dyn_glutPushWindow
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutPushWindow #
ptr_glutPushWindow :: FunPtr a
ptr_glutPushWindow = unsafePerformIO $ getAPIEntry "glutPushWindow"
glutRemoveMenuItem ----------------------------------------------------------
glutRemoveMenuItem :: MonadIO m => CInt -> m ()
glutRemoveMenuItem v1 = liftIO $ dyn_glutRemoveMenuItem ptr_glutRemoveMenuItem v1
foreign import CALLCONV "dynamic" dyn_glutRemoveMenuItem
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutRemoveMenuItem #
ptr_glutRemoveMenuItem :: FunPtr a
ptr_glutRemoveMenuItem = unsafePerformIO $ getAPIEntry "glutRemoveMenuItem"
-- glutRemoveOverlay -----------------------------------------------------------
glutRemoveOverlay :: MonadIO m => m ()
glutRemoveOverlay = liftIO $ dyn_glutRemoveOverlay ptr_glutRemoveOverlay
foreign import CALLCONV "dynamic" dyn_glutRemoveOverlay
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutRemoveOverlay #
ptr_glutRemoveOverlay :: FunPtr a
ptr_glutRemoveOverlay = unsafePerformIO $ getAPIEntry "glutRemoveOverlay"
-- glutReportErrors ------------------------------------------------------------
glutReportErrors :: MonadIO m => m ()
glutReportErrors = liftIO $ dyn_glutReportErrors ptr_glutReportErrors
foreign import CALLCONV "dynamic" dyn_glutReportErrors
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutReportErrors #
ptr_glutReportErrors :: FunPtr a
ptr_glutReportErrors = unsafePerformIO $ getAPIEntry "glutReportErrors"
-- glutReshapeFunc -------------------------------------------------------------
glutReshapeFunc :: MonadIO m => FunPtr ReshapeFunc -> m ()
glutReshapeFunc v1 = liftIO $ dyn_glutReshapeFunc ptr_glutReshapeFunc v1
foreign import CALLCONV "dynamic" dyn_glutReshapeFunc
:: FunPtr (FunPtr ReshapeFunc -> IO ())
-> FunPtr ReshapeFunc -> IO ()
# NOINLINE ptr_glutReshapeFunc #
ptr_glutReshapeFunc :: FunPtr a
ptr_glutReshapeFunc = unsafePerformIO $ getAPIEntry "glutReshapeFunc"
-- glutReshapeWindow -----------------------------------------------------------
glutReshapeWindow :: MonadIO m => CInt -> CInt -> m ()
glutReshapeWindow v1 v2 = liftIO $ dyn_glutReshapeWindow ptr_glutReshapeWindow v1 v2
foreign import CALLCONV "dynamic" dyn_glutReshapeWindow
:: FunPtr (CInt -> CInt -> IO ())
-> CInt -> CInt -> IO ()
# NOINLINE ptr_glutReshapeWindow #
ptr_glutReshapeWindow :: FunPtr a
ptr_glutReshapeWindow = unsafePerformIO $ getAPIEntry "glutReshapeWindow"
-- glutSetColor ----------------------------------------------------------------
glutSetColor :: MonadIO m => CInt -> GLfloat -> GLfloat -> GLfloat -> m ()
glutSetColor v1 v2 v3 v4 = liftIO $ dyn_glutSetColor ptr_glutSetColor v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutSetColor
:: FunPtr (CInt -> GLfloat -> GLfloat -> GLfloat -> IO ())
-> CInt -> GLfloat -> GLfloat -> GLfloat -> IO ()
# NOINLINE ptr_glutSetColor #
ptr_glutSetColor :: FunPtr a
ptr_glutSetColor = unsafePerformIO $ getAPIEntry "glutSetColor"
-- glutSetCursor ---------------------------------------------------------------
glutSetCursor :: MonadIO m => CInt -> m ()
glutSetCursor v1 = liftIO $ dyn_glutSetCursor ptr_glutSetCursor v1
foreign import CALLCONV "dynamic" dyn_glutSetCursor
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutSetCursor #
ptr_glutSetCursor :: FunPtr a
ptr_glutSetCursor = unsafePerformIO $ getAPIEntry "glutSetCursor"
-- glutSetIconTitle ------------------------------------------------------------
glutSetIconTitle :: MonadIO m => Ptr CChar -> m ()
glutSetIconTitle v1 = liftIO $ dyn_glutSetIconTitle ptr_glutSetIconTitle v1
foreign import CALLCONV "dynamic" dyn_glutSetIconTitle
:: FunPtr (Ptr CChar -> IO ())
-> Ptr CChar -> IO ()
# NOINLINE ptr_glutSetIconTitle #
ptr_glutSetIconTitle :: FunPtr a
ptr_glutSetIconTitle = unsafePerformIO $ getAPIEntry "glutSetIconTitle"
-- glutSetKeyRepeat ------------------------------------------------------------
glutSetKeyRepeat :: MonadIO m => CInt -> m ()
glutSetKeyRepeat v1 = liftIO $ dyn_glutSetKeyRepeat ptr_glutSetKeyRepeat v1
foreign import CALLCONV "dynamic" dyn_glutSetKeyRepeat
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutSetKeyRepeat #
ptr_glutSetKeyRepeat :: FunPtr a
ptr_glutSetKeyRepeat = unsafePerformIO $ getAPIEntry "glutSetKeyRepeat"
-- glutSetMenu -----------------------------------------------------------------
glutSetMenu :: MonadIO m => CInt -> m ()
glutSetMenu v1 = liftIO $ dyn_glutSetMenu ptr_glutSetMenu v1
foreign import CALLCONV "dynamic" dyn_glutSetMenu
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutSetMenu #
ptr_glutSetMenu :: FunPtr a
ptr_glutSetMenu = unsafePerformIO $ getAPIEntry "glutSetMenu"
-- glutSetMenuData -------------------------------------------------------------
glutSetMenuData :: MonadIO m => Ptr a -> m ()
glutSetMenuData v1 = liftIO $ dyn_glutSetMenuData ptr_glutSetMenuData v1
foreign import CALLCONV "dynamic" dyn_glutSetMenuData
:: FunPtr (Ptr a -> IO ())
-> Ptr a -> IO ()
# NOINLINE ptr_glutSetMenuData #
ptr_glutSetMenuData :: FunPtr a
ptr_glutSetMenuData = unsafePerformIO $ getAPIEntry "glutSetMenuData"
-- glutSetMenuFont -------------------------------------------------------------
glutSetMenuFont :: MonadIO m => CInt -> Ptr a -> m ()
glutSetMenuFont v1 v2 = liftIO $ dyn_glutSetMenuFont ptr_glutSetMenuFont v1 v2
foreign import CALLCONV "dynamic" dyn_glutSetMenuFont
:: FunPtr (CInt -> Ptr a -> IO ())
-> CInt -> Ptr a -> IO ()
# NOINLINE ptr_glutSetMenuFont #
ptr_glutSetMenuFont :: FunPtr a
ptr_glutSetMenuFont = unsafePerformIO $ getAPIEntry "glutSetMenuFont"
-- glutSetOption ---------------------------------------------------------------
glutSetOption :: MonadIO m => GLenum -> CInt -> m ()
glutSetOption v1 v2 = liftIO $ dyn_glutSetOption ptr_glutSetOption v1 v2
foreign import CALLCONV "dynamic" dyn_glutSetOption
:: FunPtr (GLenum -> CInt -> IO ())
-> GLenum -> CInt -> IO ()
# NOINLINE ptr_glutSetOption #
ptr_glutSetOption :: FunPtr a
ptr_glutSetOption = unsafePerformIO $ getAPIEntry "glutSetOption"
-- glutSetVertexAttribCoord3 ---------------------------------------------------
glutSetVertexAttribCoord3 :: MonadIO m => GLint -> m ()
glutSetVertexAttribCoord3 v1 = liftIO $ dyn_glutSetVertexAttribCoord3 ptr_glutSetVertexAttribCoord3 v1
foreign import CALLCONV "dynamic" dyn_glutSetVertexAttribCoord3
:: FunPtr (GLint -> IO ())
-> GLint -> IO ()
# NOINLINE ptr_glutSetVertexAttribCoord3 #
ptr_glutSetVertexAttribCoord3 :: FunPtr a
ptr_glutSetVertexAttribCoord3 = unsafePerformIO $ getAPIEntry "glutSetVertexAttribCoord3"
-- glutSetVertexAttribNormal ---------------------------------------------------
glutSetVertexAttribNormal :: MonadIO m => GLint -> m ()
glutSetVertexAttribNormal v1 = liftIO $ dyn_glutSetVertexAttribNormal ptr_glutSetVertexAttribNormal v1
foreign import CALLCONV "dynamic" dyn_glutSetVertexAttribNormal
:: FunPtr (GLint -> IO ())
-> GLint -> IO ()
# NOINLINE ptr_glutSetVertexAttribNormal #
ptr_glutSetVertexAttribNormal :: FunPtr a
ptr_glutSetVertexAttribNormal = unsafePerformIO $ getAPIEntry "glutSetVertexAttribNormal"
-- glutSetVertexAttribTexCoord2 ------------------------------------------------
glutSetVertexAttribTexCoord2 :: MonadIO m => GLint -> m ()
glutSetVertexAttribTexCoord2 v1 = liftIO $ dyn_glutSetVertexAttribTexCoord2 ptr_glutSetVertexAttribTexCoord2 v1
foreign import CALLCONV "dynamic" dyn_glutSetVertexAttribTexCoord2
:: FunPtr (GLint -> IO ())
-> GLint -> IO ()
# NOINLINE ptr_glutSetVertexAttribTexCoord2 #
ptr_glutSetVertexAttribTexCoord2 :: FunPtr a
ptr_glutSetVertexAttribTexCoord2 = unsafePerformIO $ getAPIEntry "glutSetVertexAttribTexCoord2"
-- glutSetWindow ---------------------------------------------------------------
glutSetWindow :: MonadIO m => CInt -> m ()
glutSetWindow v1 = liftIO $ dyn_glutSetWindow ptr_glutSetWindow v1
foreign import CALLCONV "dynamic" dyn_glutSetWindow
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutSetWindow #
ptr_glutSetWindow :: FunPtr a
ptr_glutSetWindow = unsafePerformIO $ getAPIEntry "glutSetWindow"
-- glutSetWindowData -----------------------------------------------------------
glutSetWindowData :: MonadIO m => Ptr a -> m ()
glutSetWindowData v1 = liftIO $ dyn_glutSetWindowData ptr_glutSetWindowData v1
foreign import CALLCONV "dynamic" dyn_glutSetWindowData
:: FunPtr (Ptr a -> IO ())
-> Ptr a -> IO ()
# NOINLINE ptr_glutSetWindowData #
ptr_glutSetWindowData :: FunPtr a
ptr_glutSetWindowData = unsafePerformIO $ getAPIEntry "glutSetWindowData"
-- glutSetWindowTitle ----------------------------------------------------------
glutSetWindowTitle :: MonadIO m => Ptr CChar -> m ()
glutSetWindowTitle v1 = liftIO $ dyn_glutSetWindowTitle ptr_glutSetWindowTitle v1
foreign import CALLCONV "dynamic" dyn_glutSetWindowTitle
:: FunPtr (Ptr CChar -> IO ())
-> Ptr CChar -> IO ()
# NOINLINE ptr_glutSetWindowTitle #
ptr_glutSetWindowTitle :: FunPtr a
ptr_glutSetWindowTitle = unsafePerformIO $ getAPIEntry "glutSetWindowTitle"
-- glutSetupVideoResizing ------------------------------------------------------
glutSetupVideoResizing :: MonadIO m => m ()
glutSetupVideoResizing = liftIO $ dyn_glutSetupVideoResizing ptr_glutSetupVideoResizing
foreign import CALLCONV "dynamic" dyn_glutSetupVideoResizing
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutSetupVideoResizing #
ptr_glutSetupVideoResizing :: FunPtr a
ptr_glutSetupVideoResizing = unsafePerformIO $ getAPIEntry "glutSetupVideoResizing"
-- glutShowOverlay -------------------------------------------------------------
glutShowOverlay :: MonadIO m => m ()
glutShowOverlay = liftIO $ dyn_glutShowOverlay ptr_glutShowOverlay
foreign import CALLCONV "dynamic" dyn_glutShowOverlay
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutShowOverlay #
ptr_glutShowOverlay :: FunPtr a
ptr_glutShowOverlay = unsafePerformIO $ getAPIEntry "glutShowOverlay"
-- glutShowWindow --------------------------------------------------------------
glutShowWindow :: MonadIO m => m ()
glutShowWindow = liftIO $ dyn_glutShowWindow ptr_glutShowWindow
foreign import CALLCONV "dynamic" dyn_glutShowWindow
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutShowWindow #
ptr_glutShowWindow :: FunPtr a
ptr_glutShowWindow = unsafePerformIO $ getAPIEntry "glutShowWindow"
-- glutSolidCone ---------------------------------------------------------------
glutSolidCone :: MonadIO m => GLdouble -> GLdouble -> GLint -> GLint -> m ()
glutSolidCone v1 v2 v3 v4 = liftIO $ dyn_glutSolidCone ptr_glutSolidCone v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutSolidCone
:: FunPtr (GLdouble -> GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLdouble -> GLint -> GLint -> IO ()
# NOINLINE ptr_glutSolidCone #
ptr_glutSolidCone :: FunPtr a
ptr_glutSolidCone = unsafePerformIO $ getAPIEntry "glutSolidCone"
---------------------------------------------------------------
glutSolidCube :: MonadIO m => GLdouble -> m ()
glutSolidCube v1 = liftIO $ dyn_glutSolidCube ptr_glutSolidCube v1
foreign import CALLCONV "dynamic" dyn_glutSolidCube
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutSolidCube #
ptr_glutSolidCube :: FunPtr a
ptr_glutSolidCube = unsafePerformIO $ getAPIEntry "glutSolidCube"
-- glutSolidCylinder -----------------------------------------------------------
glutSolidCylinder :: MonadIO m => GLdouble -> GLdouble -> GLint -> GLint -> m ()
glutSolidCylinder v1 v2 v3 v4 = liftIO $ dyn_glutSolidCylinder ptr_glutSolidCylinder v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutSolidCylinder
:: FunPtr (GLdouble -> GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLdouble -> GLint -> GLint -> IO ()
# NOINLINE ptr_glutSolidCylinder #
ptr_glutSolidCylinder :: FunPtr a
ptr_glutSolidCylinder = unsafePerformIO $ getAPIEntry "glutSolidCylinder"
glutSolidDodecahedron -------------------------------------------------------
glutSolidDodecahedron :: MonadIO m => m ()
glutSolidDodecahedron = liftIO $ dyn_glutSolidDodecahedron ptr_glutSolidDodecahedron
foreign import CALLCONV "dynamic" dyn_glutSolidDodecahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutSolidDodecahedron #
ptr_glutSolidDodecahedron :: FunPtr a
ptr_glutSolidDodecahedron = unsafePerformIO $ getAPIEntry "glutSolidDodecahedron"
glutSolidIcosahedron --------------------------------------------------------
glutSolidIcosahedron :: MonadIO m => m ()
glutSolidIcosahedron = liftIO $ dyn_glutSolidIcosahedron ptr_glutSolidIcosahedron
foreign import CALLCONV "dynamic" dyn_glutSolidIcosahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutSolidIcosahedron #
ptr_glutSolidIcosahedron :: FunPtr a
ptr_glutSolidIcosahedron = unsafePerformIO $ getAPIEntry "glutSolidIcosahedron"
glutSolidOctahedron ---------------------------------------------------------
glutSolidOctahedron :: MonadIO m => m ()
glutSolidOctahedron = liftIO $ dyn_glutSolidOctahedron ptr_glutSolidOctahedron
foreign import CALLCONV "dynamic" dyn_glutSolidOctahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutSolidOctahedron #
ptr_glutSolidOctahedron :: FunPtr a
ptr_glutSolidOctahedron = unsafePerformIO $ getAPIEntry "glutSolidOctahedron"
-- glutSolidRhombicDodecahedron ------------------------------------------------
glutSolidRhombicDodecahedron :: MonadIO m => m ()
glutSolidRhombicDodecahedron = liftIO $ dyn_glutSolidRhombicDodecahedron ptr_glutSolidRhombicDodecahedron
foreign import CALLCONV "dynamic" dyn_glutSolidRhombicDodecahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutSolidRhombicDodecahedron #
ptr_glutSolidRhombicDodecahedron :: FunPtr a
ptr_glutSolidRhombicDodecahedron = unsafePerformIO $ getAPIEntry "glutSolidRhombicDodecahedron"
-- glutSolidSierpinskiSponge ---------------------------------------------------
glutSolidSierpinskiSponge :: MonadIO m => CInt -> Ptr GLdouble -> GLdouble -> m ()
glutSolidSierpinskiSponge v1 v2 v3 = liftIO $ dyn_glutSolidSierpinskiSponge ptr_glutSolidSierpinskiSponge v1 v2 v3
foreign import CALLCONV "dynamic" dyn_glutSolidSierpinskiSponge
:: FunPtr (CInt -> Ptr GLdouble -> GLdouble -> IO ())
-> CInt -> Ptr GLdouble -> GLdouble -> IO ()
# NOINLINE ptr_glutSolidSierpinskiSponge #
ptr_glutSolidSierpinskiSponge :: FunPtr a
ptr_glutSolidSierpinskiSponge = unsafePerformIO $ getAPIEntry "glutSolidSierpinskiSponge"
-- glutSolidSphere -------------------------------------------------------------
glutSolidSphere :: MonadIO m => GLdouble -> GLint -> GLint -> m ()
glutSolidSphere v1 v2 v3 = liftIO $ dyn_glutSolidSphere ptr_glutSolidSphere v1 v2 v3
foreign import CALLCONV "dynamic" dyn_glutSolidSphere
:: FunPtr (GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLint -> GLint -> IO ()
# NOINLINE ptr_glutSolidSphere #
ptr_glutSolidSphere :: FunPtr a
ptr_glutSolidSphere = unsafePerformIO $ getAPIEntry "glutSolidSphere"
-- glutSolidTeacup -------------------------------------------------------------
glutSolidTeacup :: MonadIO m => GLdouble -> m ()
glutSolidTeacup v1 = liftIO $ dyn_glutSolidTeacup ptr_glutSolidTeacup v1
foreign import CALLCONV "dynamic" dyn_glutSolidTeacup
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutSolidTeacup #
ptr_glutSolidTeacup :: FunPtr a
ptr_glutSolidTeacup = unsafePerformIO $ getAPIEntry "glutSolidTeacup"
-- glutSolidTeapot -------------------------------------------------------------
glutSolidTeapot :: MonadIO m => GLdouble -> m ()
glutSolidTeapot v1 = liftIO $ dyn_glutSolidTeapot ptr_glutSolidTeapot v1
foreign import CALLCONV "dynamic" dyn_glutSolidTeapot
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutSolidTeapot #
ptr_glutSolidTeapot :: FunPtr a
ptr_glutSolidTeapot = unsafePerformIO $ getAPIEntry "glutSolidTeapot"
-- glutSolidTeaspoon -----------------------------------------------------------
glutSolidTeaspoon :: MonadIO m => GLdouble -> m ()
glutSolidTeaspoon v1 = liftIO $ dyn_glutSolidTeaspoon ptr_glutSolidTeaspoon v1
foreign import CALLCONV "dynamic" dyn_glutSolidTeaspoon
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutSolidTeaspoon #
ptr_glutSolidTeaspoon :: FunPtr a
ptr_glutSolidTeaspoon = unsafePerformIO $ getAPIEntry "glutSolidTeaspoon"
-- glutSolidTetrahedron --------------------------------------------------------
glutSolidTetrahedron :: MonadIO m => m ()
glutSolidTetrahedron = liftIO $ dyn_glutSolidTetrahedron ptr_glutSolidTetrahedron
foreign import CALLCONV "dynamic" dyn_glutSolidTetrahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutSolidTetrahedron #
ptr_glutSolidTetrahedron :: FunPtr a
ptr_glutSolidTetrahedron = unsafePerformIO $ getAPIEntry "glutSolidTetrahedron"
-- glutSolidTorus --------------------------------------------------------------
glutSolidTorus :: MonadIO m => GLdouble -> GLdouble -> GLint -> GLint -> m ()
glutSolidTorus v1 v2 v3 v4 = liftIO $ dyn_glutSolidTorus ptr_glutSolidTorus v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutSolidTorus
:: FunPtr (GLdouble -> GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLdouble -> GLint -> GLint -> IO ()
# NOINLINE ptr_glutSolidTorus #
ptr_glutSolidTorus :: FunPtr a
ptr_glutSolidTorus = unsafePerformIO $ getAPIEntry "glutSolidTorus"
-- glutSpaceballButtonFunc -----------------------------------------------------
glutSpaceballButtonFunc :: MonadIO m => FunPtr SpaceballButtonFunc -> m ()
glutSpaceballButtonFunc v1 = liftIO $ dyn_glutSpaceballButtonFunc ptr_glutSpaceballButtonFunc v1
foreign import CALLCONV "dynamic" dyn_glutSpaceballButtonFunc
:: FunPtr (FunPtr SpaceballButtonFunc -> IO ())
-> FunPtr SpaceballButtonFunc -> IO ()
# NOINLINE ptr_glutSpaceballButtonFunc #
ptr_glutSpaceballButtonFunc :: FunPtr a
ptr_glutSpaceballButtonFunc = unsafePerformIO $ getAPIEntry "glutSpaceballButtonFunc"
glutSpaceballMotionFunc -----------------------------------------------------
glutSpaceballMotionFunc :: MonadIO m => FunPtr SpaceballMotionFunc -> m ()
glutSpaceballMotionFunc v1 = liftIO $ dyn_glutSpaceballMotionFunc ptr_glutSpaceballMotionFunc v1
foreign import CALLCONV "dynamic" dyn_glutSpaceballMotionFunc
:: FunPtr (FunPtr SpaceballMotionFunc -> IO ())
-> FunPtr SpaceballMotionFunc -> IO ()
# NOINLINE ptr_glutSpaceballMotionFunc #
ptr_glutSpaceballMotionFunc :: FunPtr a
ptr_glutSpaceballMotionFunc = unsafePerformIO $ getAPIEntry "glutSpaceballMotionFunc"
-- glutSpaceballRotateFunc -----------------------------------------------------
glutSpaceballRotateFunc :: MonadIO m => FunPtr SpaceballRotateFunc -> m ()
glutSpaceballRotateFunc v1 = liftIO $ dyn_glutSpaceballRotateFunc ptr_glutSpaceballRotateFunc v1
foreign import CALLCONV "dynamic" dyn_glutSpaceballRotateFunc
:: FunPtr (FunPtr SpaceballRotateFunc -> IO ())
-> FunPtr SpaceballRotateFunc -> IO ()
# NOINLINE ptr_glutSpaceballRotateFunc #
ptr_glutSpaceballRotateFunc :: FunPtr a
ptr_glutSpaceballRotateFunc = unsafePerformIO $ getAPIEntry "glutSpaceballRotateFunc"
-- glutSpecialFunc -------------------------------------------------------------
glutSpecialFunc :: MonadIO m => FunPtr SpecialFunc -> m ()
glutSpecialFunc v1 = liftIO $ dyn_glutSpecialFunc ptr_glutSpecialFunc v1
foreign import CALLCONV "dynamic" dyn_glutSpecialFunc
:: FunPtr (FunPtr SpecialFunc -> IO ())
-> FunPtr SpecialFunc -> IO ()
# NOINLINE ptr_glutSpecialFunc #
ptr_glutSpecialFunc :: FunPtr a
ptr_glutSpecialFunc = unsafePerformIO $ getAPIEntry "glutSpecialFunc"
-- glutSpecialUpFunc -----------------------------------------------------------
glutSpecialUpFunc :: MonadIO m => FunPtr SpecialUpFunc -> m ()
glutSpecialUpFunc v1 = liftIO $ dyn_glutSpecialUpFunc ptr_glutSpecialUpFunc v1
foreign import CALLCONV "dynamic" dyn_glutSpecialUpFunc
:: FunPtr (FunPtr SpecialUpFunc -> IO ())
-> FunPtr SpecialUpFunc -> IO ()
# NOINLINE ptr_glutSpecialUpFunc #
ptr_glutSpecialUpFunc :: FunPtr a
ptr_glutSpecialUpFunc = unsafePerformIO $ getAPIEntry "glutSpecialUpFunc"
-- glutStopVideoResizing -------------------------------------------------------
glutStopVideoResizing :: MonadIO m => m ()
glutStopVideoResizing = liftIO $ dyn_glutStopVideoResizing ptr_glutStopVideoResizing
foreign import CALLCONV "dynamic" dyn_glutStopVideoResizing
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutStopVideoResizing #
ptr_glutStopVideoResizing :: FunPtr a
ptr_glutStopVideoResizing = unsafePerformIO $ getAPIEntry "glutStopVideoResizing"
-- glutStrokeCharacter ---------------------------------------------------------
glutStrokeCharacter :: MonadIO m => Ptr a -> CInt -> m ()
glutStrokeCharacter v1 v2 = liftIO $ dyn_glutStrokeCharacter ptr_glutStrokeCharacter v1 v2
foreign import CALLCONV "dynamic" dyn_glutStrokeCharacter
:: FunPtr (Ptr a -> CInt -> IO ())
-> Ptr a -> CInt -> IO ()
# NOINLINE ptr_glutStrokeCharacter #
ptr_glutStrokeCharacter :: FunPtr a
ptr_glutStrokeCharacter = unsafePerformIO $ getAPIEntry "glutStrokeCharacter"
-- glutStrokeHeight ------------------------------------------------------------
glutStrokeHeight :: MonadIO m => Ptr a -> m GLfloat
glutStrokeHeight v1 = liftIO $ dyn_glutStrokeHeight ptr_glutStrokeHeight v1
foreign import CALLCONV "dynamic" dyn_glutStrokeHeight
:: FunPtr (Ptr a -> IO GLfloat)
-> Ptr a -> IO GLfloat
# NOINLINE ptr_glutStrokeHeight #
ptr_glutStrokeHeight :: FunPtr a
ptr_glutStrokeHeight = unsafePerformIO $ getAPIEntry "glutStrokeHeight"
-- glutStrokeLength ------------------------------------------------------------
glutStrokeLength :: MonadIO m => Ptr a -> Ptr CUChar -> m CInt
glutStrokeLength v1 v2 = liftIO $ dyn_glutStrokeLength ptr_glutStrokeLength v1 v2
foreign import CALLCONV "dynamic" dyn_glutStrokeLength
:: FunPtr (Ptr a -> Ptr CUChar -> IO CInt)
-> Ptr a -> Ptr CUChar -> IO CInt
# NOINLINE ptr_glutStrokeLength #
ptr_glutStrokeLength :: FunPtr a
ptr_glutStrokeLength = unsafePerformIO $ getAPIEntry "glutStrokeLength"
-- glutStrokeString ------------------------------------------------------------
glutStrokeString :: MonadIO m => Ptr a -> Ptr CUChar -> m ()
glutStrokeString v1 v2 = liftIO $ dyn_glutStrokeString ptr_glutStrokeString v1 v2
foreign import CALLCONV "dynamic" dyn_glutStrokeString
:: FunPtr (Ptr a -> Ptr CUChar -> IO ())
-> Ptr a -> Ptr CUChar -> IO ()
# NOINLINE ptr_glutStrokeString #
ptr_glutStrokeString :: FunPtr a
ptr_glutStrokeString = unsafePerformIO $ getAPIEntry "glutStrokeString"
-- glutStrokeWidth -------------------------------------------------------------
glutStrokeWidth :: MonadIO m => Ptr a -> CInt -> m CInt
glutStrokeWidth v1 v2 = liftIO $ dyn_glutStrokeWidth ptr_glutStrokeWidth v1 v2
foreign import CALLCONV "dynamic" dyn_glutStrokeWidth
:: FunPtr (Ptr a -> CInt -> IO CInt)
-> Ptr a -> CInt -> IO CInt
# NOINLINE ptr_glutStrokeWidth #
ptr_glutStrokeWidth :: FunPtr a
ptr_glutStrokeWidth = unsafePerformIO $ getAPIEntry "glutStrokeWidth"
-- glutSwapBuffers -------------------------------------------------------------
glutSwapBuffers :: MonadIO m => m ()
glutSwapBuffers = liftIO $ dyn_glutSwapBuffers ptr_glutSwapBuffers
foreign import CALLCONV "dynamic" dyn_glutSwapBuffers
:: FunPtr (IO ())
-> IO ()
{-# NOINLINE ptr_glutSwapBuffers #-}
ptr_glutSwapBuffers :: FunPtr a
ptr_glutSwapBuffers = unsafePerformIO $ getAPIEntry "glutSwapBuffers"
-- glutTabletButtonFunc --------------------------------------------------------
glutTabletButtonFunc :: MonadIO m => FunPtr TabletButtonFunc -> m ()
glutTabletButtonFunc v1 = liftIO $ dyn_glutTabletButtonFunc ptr_glutTabletButtonFunc v1
foreign import CALLCONV "dynamic" dyn_glutTabletButtonFunc
:: FunPtr (FunPtr TabletButtonFunc -> IO ())
-> FunPtr TabletButtonFunc -> IO ()
# NOINLINE ptr_glutTabletButtonFunc #
ptr_glutTabletButtonFunc :: FunPtr a
ptr_glutTabletButtonFunc = unsafePerformIO $ getAPIEntry "glutTabletButtonFunc"
-- glutTabletMotionFunc --------------------------------------------------------
glutTabletMotionFunc :: MonadIO m => FunPtr TabletMotionFunc -> m ()
glutTabletMotionFunc v1 = liftIO $ dyn_glutTabletMotionFunc ptr_glutTabletMotionFunc v1
foreign import CALLCONV "dynamic" dyn_glutTabletMotionFunc
:: FunPtr (FunPtr TabletMotionFunc -> IO ())
-> FunPtr TabletMotionFunc -> IO ()
# NOINLINE ptr_glutTabletMotionFunc #
ptr_glutTabletMotionFunc :: FunPtr a
ptr_glutTabletMotionFunc = unsafePerformIO $ getAPIEntry "glutTabletMotionFunc"
-- glutTimerFunc ---------------------------------------------------------------
glutTimerFunc :: MonadIO m => CUInt -> FunPtr TimerFunc -> CInt -> m ()
glutTimerFunc v1 v2 v3 = liftIO $ dyn_glutTimerFunc ptr_glutTimerFunc v1 v2 v3
foreign import CALLCONV "dynamic" dyn_glutTimerFunc
:: FunPtr (CUInt -> FunPtr TimerFunc -> CInt -> IO ())
-> CUInt -> FunPtr TimerFunc -> CInt -> IO ()
# NOINLINE ptr_glutTimerFunc #
ptr_glutTimerFunc :: FunPtr a
ptr_glutTimerFunc = unsafePerformIO $ getAPIEntry "glutTimerFunc"
-- glutUseLayer ----------------------------------------------------------------
glutUseLayer :: MonadIO m => GLenum -> m ()
glutUseLayer v1 = liftIO $ dyn_glutUseLayer ptr_glutUseLayer v1
foreign import CALLCONV "dynamic" dyn_glutUseLayer
:: FunPtr (GLenum -> IO ())
-> GLenum -> IO ()
# NOINLINE ptr_glutUseLayer #
ptr_glutUseLayer :: FunPtr a
ptr_glutUseLayer = unsafePerformIO $ getAPIEntry "glutUseLayer"
-- glutVideoPan ----------------------------------------------------------------
glutVideoPan :: MonadIO m => CInt -> CInt -> CInt -> CInt -> m ()
glutVideoPan v1 v2 v3 v4 = liftIO $ dyn_glutVideoPan ptr_glutVideoPan v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutVideoPan
:: FunPtr (CInt -> CInt -> CInt -> CInt -> IO ())
-> CInt -> CInt -> CInt -> CInt -> IO ()
# NOINLINE ptr_glutVideoPan #
ptr_glutVideoPan :: FunPtr a
ptr_glutVideoPan = unsafePerformIO $ getAPIEntry "glutVideoPan"
-- glutVideoResize -------------------------------------------------------------
glutVideoResize :: MonadIO m => CInt -> CInt -> CInt -> CInt -> m ()
glutVideoResize v1 v2 v3 v4 = liftIO $ dyn_glutVideoResize ptr_glutVideoResize v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutVideoResize
:: FunPtr (CInt -> CInt -> CInt -> CInt -> IO ())
-> CInt -> CInt -> CInt -> CInt -> IO ()
# NOINLINE ptr_glutVideoResize #
ptr_glutVideoResize :: FunPtr a
ptr_glutVideoResize = unsafePerformIO $ getAPIEntry "glutVideoResize"
-- glutVideoResizeGet ----------------------------------------------------------
glutVideoResizeGet :: MonadIO m => GLenum -> m CInt
glutVideoResizeGet v1 = liftIO $ dyn_glutVideoResizeGet ptr_glutVideoResizeGet v1
foreign import CALLCONV "dynamic" dyn_glutVideoResizeGet
:: FunPtr (GLenum -> IO CInt)
-> GLenum -> IO CInt
# NOINLINE ptr_glutVideoResizeGet #
ptr_glutVideoResizeGet :: FunPtr a
ptr_glutVideoResizeGet = unsafePerformIO $ getAPIEntry "glutVideoResizeGet"
-- glutVisibilityFunc ----------------------------------------------------------
glutVisibilityFunc :: MonadIO m => FunPtr VisibilityFunc -> m ()
glutVisibilityFunc v1 = liftIO $ dyn_glutVisibilityFunc ptr_glutVisibilityFunc v1
foreign import CALLCONV "dynamic" dyn_glutVisibilityFunc
:: FunPtr (FunPtr VisibilityFunc -> IO ())
-> FunPtr VisibilityFunc -> IO ()
# NOINLINE ptr_glutVisibilityFunc #
ptr_glutVisibilityFunc :: FunPtr a
ptr_glutVisibilityFunc = unsafePerformIO $ getAPIEntry "glutVisibilityFunc"
-- glutWMCloseFunc -------------------------------------------------------------
glutWMCloseFunc :: MonadIO m => FunPtr WMCloseFunc -> m ()
glutWMCloseFunc v1 = liftIO $ dyn_glutWMCloseFunc ptr_glutWMCloseFunc v1
foreign import CALLCONV "dynamic" dyn_glutWMCloseFunc
:: FunPtr (FunPtr WMCloseFunc -> IO ())
-> FunPtr WMCloseFunc -> IO ()
# NOINLINE ptr_glutWMCloseFunc #
ptr_glutWMCloseFunc :: FunPtr a
ptr_glutWMCloseFunc = unsafePerformIO $ getAPIEntry "glutWMCloseFunc"
-- glutWarpPointer -------------------------------------------------------------
glutWarpPointer :: MonadIO m => CInt -> CInt -> m ()
glutWarpPointer v1 v2 = liftIO $ dyn_glutWarpPointer ptr_glutWarpPointer v1 v2
foreign import CALLCONV "dynamic" dyn_glutWarpPointer
:: FunPtr (CInt -> CInt -> IO ())
-> CInt -> CInt -> IO ()
# NOINLINE ptr_glutWarpPointer #
ptr_glutWarpPointer :: FunPtr a
ptr_glutWarpPointer = unsafePerformIO $ getAPIEntry "glutWarpPointer"
-- glutWindowStatusFunc --------------------------------------------------------
glutWindowStatusFunc :: MonadIO m => FunPtr WindowStatusFunc -> m ()
glutWindowStatusFunc v1 = liftIO $ dyn_glutWindowStatusFunc ptr_glutWindowStatusFunc v1
foreign import CALLCONV "dynamic" dyn_glutWindowStatusFunc
:: FunPtr (FunPtr WindowStatusFunc -> IO ())
-> FunPtr WindowStatusFunc -> IO ()
# NOINLINE ptr_glutWindowStatusFunc #
ptr_glutWindowStatusFunc :: FunPtr a
ptr_glutWindowStatusFunc = unsafePerformIO $ getAPIEntry "glutWindowStatusFunc"
-- glutWireCone ----------------------------------------------------------------
glutWireCone :: MonadIO m => GLdouble -> GLdouble -> GLint -> GLint -> m ()
glutWireCone v1 v2 v3 v4 = liftIO $ dyn_glutWireCone ptr_glutWireCone v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutWireCone
:: FunPtr (GLdouble -> GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLdouble -> GLint -> GLint -> IO ()
# NOINLINE ptr_glutWireCone #
ptr_glutWireCone :: FunPtr a
ptr_glutWireCone = unsafePerformIO $ getAPIEntry "glutWireCone"
glutWireCube ----------------------------------------------------------------
glutWireCube :: MonadIO m => GLdouble -> m ()
glutWireCube v1 = liftIO $ dyn_glutWireCube ptr_glutWireCube v1
foreign import CALLCONV "dynamic" dyn_glutWireCube
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutWireCube #
ptr_glutWireCube :: FunPtr a
ptr_glutWireCube = unsafePerformIO $ getAPIEntry "glutWireCube"
-- glutWireCylinder ------------------------------------------------------------
glutWireCylinder :: MonadIO m => GLdouble -> GLdouble -> GLint -> GLint -> m ()
glutWireCylinder v1 v2 v3 v4 = liftIO $ dyn_glutWireCylinder ptr_glutWireCylinder v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutWireCylinder
:: FunPtr (GLdouble -> GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLdouble -> GLint -> GLint -> IO ()
# NOINLINE ptr_glutWireCylinder #
ptr_glutWireCylinder :: FunPtr a
ptr_glutWireCylinder = unsafePerformIO $ getAPIEntry "glutWireCylinder"
-- glutWireDodecahedron --------------------------------------------------------
glutWireDodecahedron :: MonadIO m => m ()
glutWireDodecahedron = liftIO $ dyn_glutWireDodecahedron ptr_glutWireDodecahedron
foreign import CALLCONV "dynamic" dyn_glutWireDodecahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutWireDodecahedron #
ptr_glutWireDodecahedron :: FunPtr a
ptr_glutWireDodecahedron = unsafePerformIO $ getAPIEntry "glutWireDodecahedron"
-- glutWireIcosahedron ---------------------------------------------------------
glutWireIcosahedron :: MonadIO m => m ()
glutWireIcosahedron = liftIO $ dyn_glutWireIcosahedron ptr_glutWireIcosahedron
foreign import CALLCONV "dynamic" dyn_glutWireIcosahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutWireIcosahedron #
ptr_glutWireIcosahedron :: FunPtr a
ptr_glutWireIcosahedron = unsafePerformIO $ getAPIEntry "glutWireIcosahedron"
glutWireOctahedron ----------------------------------------------------------
glutWireOctahedron :: MonadIO m => m ()
glutWireOctahedron = liftIO $ dyn_glutWireOctahedron ptr_glutWireOctahedron
foreign import CALLCONV "dynamic" dyn_glutWireOctahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutWireOctahedron #
ptr_glutWireOctahedron :: FunPtr a
ptr_glutWireOctahedron = unsafePerformIO $ getAPIEntry "glutWireOctahedron"
-- glutWireRhombicDodecahedron -------------------------------------------------
glutWireRhombicDodecahedron :: MonadIO m => m ()
glutWireRhombicDodecahedron = liftIO $ dyn_glutWireRhombicDodecahedron ptr_glutWireRhombicDodecahedron
foreign import CALLCONV "dynamic" dyn_glutWireRhombicDodecahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutWireRhombicDodecahedron #
ptr_glutWireRhombicDodecahedron :: FunPtr a
ptr_glutWireRhombicDodecahedron = unsafePerformIO $ getAPIEntry "glutWireRhombicDodecahedron"
-- glutWireSierpinskiSponge ----------------------------------------------------
glutWireSierpinskiSponge :: MonadIO m => CInt -> Ptr GLdouble -> GLdouble -> m ()
glutWireSierpinskiSponge v1 v2 v3 = liftIO $ dyn_glutWireSierpinskiSponge ptr_glutWireSierpinskiSponge v1 v2 v3
foreign import CALLCONV "dynamic" dyn_glutWireSierpinskiSponge
:: FunPtr (CInt -> Ptr GLdouble -> GLdouble -> IO ())
-> CInt -> Ptr GLdouble -> GLdouble -> IO ()
# NOINLINE ptr_glutWireSierpinskiSponge #
ptr_glutWireSierpinskiSponge :: FunPtr a
ptr_glutWireSierpinskiSponge = unsafePerformIO $ getAPIEntry "glutWireSierpinskiSponge"
-- glutWireSphere --------------------------------------------------------------
glutWireSphere :: MonadIO m => GLdouble -> GLint -> GLint -> m ()
glutWireSphere v1 v2 v3 = liftIO $ dyn_glutWireSphere ptr_glutWireSphere v1 v2 v3
foreign import CALLCONV "dynamic" dyn_glutWireSphere
:: FunPtr (GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLint -> GLint -> IO ()
{-# NOINLINE ptr_glutWireSphere #-}
ptr_glutWireSphere :: FunPtr a
ptr_glutWireSphere = unsafePerformIO $ getAPIEntry "glutWireSphere"
glutWireTeacup --------------------------------------------------------------
glutWireTeacup :: MonadIO m => GLdouble -> m ()
glutWireTeacup v1 = liftIO $ dyn_glutWireTeacup ptr_glutWireTeacup v1
foreign import CALLCONV "dynamic" dyn_glutWireTeacup
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutWireTeacup #
ptr_glutWireTeacup :: FunPtr a
ptr_glutWireTeacup = unsafePerformIO $ getAPIEntry "glutWireTeacup"
-- glutWireTeapot --------------------------------------------------------------
glutWireTeapot :: MonadIO m => GLdouble -> m ()
glutWireTeapot v1 = liftIO $ dyn_glutWireTeapot ptr_glutWireTeapot v1
foreign import CALLCONV "dynamic" dyn_glutWireTeapot
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutWireTeapot #
ptr_glutWireTeapot :: FunPtr a
ptr_glutWireTeapot = unsafePerformIO $ getAPIEntry "glutWireTeapot"
-- glutWireTeaspoon ------------------------------------------------------------
glutWireTeaspoon :: MonadIO m => GLdouble -> m ()
glutWireTeaspoon v1 = liftIO $ dyn_glutWireTeaspoon ptr_glutWireTeaspoon v1
foreign import CALLCONV "dynamic" dyn_glutWireTeaspoon
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutWireTeaspoon #
ptr_glutWireTeaspoon :: FunPtr a
ptr_glutWireTeaspoon = unsafePerformIO $ getAPIEntry "glutWireTeaspoon"
glutWireTetrahedron ---------------------------------------------------------
glutWireTetrahedron :: MonadIO m => m ()
glutWireTetrahedron = liftIO $ dyn_glutWireTetrahedron ptr_glutWireTetrahedron
foreign import CALLCONV "dynamic" dyn_glutWireTetrahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutWireTetrahedron #
ptr_glutWireTetrahedron :: FunPtr a
ptr_glutWireTetrahedron = unsafePerformIO $ getAPIEntry "glutWireTetrahedron"
-- glutWireTorus ---------------------------------------------------------------
glutWireTorus :: MonadIO m => GLdouble -> GLdouble -> GLint -> GLint -> m ()
glutWireTorus v1 v2 v3 v4 = liftIO $ dyn_glutWireTorus ptr_glutWireTorus v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutWireTorus
:: FunPtr (GLdouble -> GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLdouble -> GLint -> GLint -> IO ()
# NOINLINE ptr_glutWireTorus #
ptr_glutWireTorus :: FunPtr a
ptr_glutWireTorus = unsafePerformIO $ getAPIEntry "glutWireTorus"
| null | https://raw.githubusercontent.com/haskell-opengl/GLUT/36207fa51e4c1ea1e5512aeaa373198a4a56cad0/src/Graphics/UI/GLUT/Raw/Functions.hs | haskell | # OPTIONS_HADDOCK hide #
------------------------------------------------------------------------------
|
Module : Graphics.UI.GLUT.Raw.Functions
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
Make the foreign imports happy.
------------------------------------------------------------------------------
the given name was found.
glutAddMenuEntry ------------------------------------------------------------
glutAddSubMenu --------------------------------------------------------------
glutAppStatusFunc -----------------------------------------------------------
glutAttachMenu --------------------------------------------------------------
glutBitmapCharacter ---------------------------------------------------------
glutBitmapHeight ------------------------------------------------------------
glutBitmapLength ------------------------------------------------------------
glutBitmapString ------------------------------------------------------------
glutBitmapWidth -------------------------------------------------------------
glutButtonBoxFunc -----------------------------------------------------------
glutChangeToMenuEntry -------------------------------------------------------
glutChangeToSubMenu ---------------------------------------------------------
glutCloseFunc ---------------------------------------------------------------
glutCopyColormap ------------------------------------------------------------
glutCreateMenu --------------------------------------------------------------
glutCreateSubWindow ---------------------------------------------------------
glutCreateWindow ------------------------------------------------------------
glutDestroyMenu -------------------------------------------------------------
glutDestroyWindow -----------------------------------------------------------
glutDetachMenu --------------------------------------------------------------
glutDeviceGet ---------------------------------------------------------------
glutDialsFunc ---------------------------------------------------------------
glutDisplayFunc -------------------------------------------------------------
glutEnterGameMode -----------------------------------------------------------
glutEntryFunc ---------------------------------------------------------------
glutEstablishOverlay --------------------------------------------------------
glutExit --------------------------------------------------------------------
glutExtensionSupported ------------------------------------------------------
glutForceJoystickFunc -------------------------------------------------------
glutFullScreen --------------------------------------------------------------
glutFullScreenToggle --------------------------------------------------------
-----------------------------------------------------------
glutGameModeString ----------------------------------------------------------
glutGet ---------------------------------------------------------------------
glutGetColor ----------------------------------------------------------------
glutGetMenu -----------------------------------------------------------------
-----------------------------------------------------------
glutGetModeValues -----------------------------------------------------------
glutGetModifiers ------------------------------------------------------------
--------------------------------------------------------
glutGetWindow ---------------------------------------------------------------
glutGetWindowData -----------------------------------------------------------
glutHideOverlay -------------------------------------------------------------
glutHideWindow --------------------------------------------------------------
glutIconifyWindow -----------------------------------------------------------
glutIdleFunc ----------------------------------------------------------------
glutIgnoreKeyRepeat ---------------------------------------------------------
# NOINLINE ptr_glutIgnoreKeyRepeat #
glutInit --------------------------------------------------------------------
glutInitContextFlags --------------------------------------------------------
glutInitContextFunc ---------------------------------------------------------
----------------------------------------------------
glutInitContextVersion ------------------------------------------------------
glutInitDisplayMode ---------------------------------------------------------
glutInitDisplayString -------------------------------------------------------
glutInitWindowPosition ------------------------------------------------------
glutInitWindowSize ----------------------------------------------------------
glutJoystickFunc ------------------------------------------------------------
glutKeyboardFunc ------------------------------------------------------------
glutKeyboardUpFunc ----------------------------------------------------------
--------------------------------------------------------------
glutLeaveFullScreen ---------------------------------------------------------
---------------------------------------------------------
glutLeaveMainLoop -----------------------------------------------------------
# NOINLINE ptr_glutLeaveMainLoop #
glutMainLoop ----------------------------------------------------------------
glutMainLoopEvent -----------------------------------------------------------
glutMenuDestroyFunc ---------------------------------------------------------
glutMenuStateFunc -----------------------------------------------------------
glutMenuStatusFunc ----------------------------------------------------------
glutMotionFunc --------------------------------------------------------------
glutMouseFunc ---------------------------------------------------------------
glutMouseWheelFunc ----------------------------------------------------------
glutMultiButtonFunc ---------------------------------------------------------
glutMultiEntryFunc ----------------------------------------------------------
glutMultiMotionFunc ---------------------------------------------------------
glutMultiPassiveFunc --------------------------------------------------------
----------------------------------------------------
glutPassiveMotionFunc -------------------------------------------------------
glutPopWindow ---------------------------------------------------------------
glutPositionFunc ------------------------------------------------------------
glutPositionWindow ----------------------------------------------------------
glutPostOverlayRedisplay ----------------------------------------------------
glutPostRedisplay -----------------------------------------------------------
glutPostWindowOverlayRedisplay ----------------------------------------------
glutPostWindowRedisplay -----------------------------------------------------
glutPushWindow --------------------------------------------------------------
--------------------------------------------------------
glutRemoveOverlay -----------------------------------------------------------
glutReportErrors ------------------------------------------------------------
glutReshapeFunc -------------------------------------------------------------
glutReshapeWindow -----------------------------------------------------------
glutSetColor ----------------------------------------------------------------
glutSetCursor ---------------------------------------------------------------
glutSetIconTitle ------------------------------------------------------------
glutSetKeyRepeat ------------------------------------------------------------
glutSetMenu -----------------------------------------------------------------
glutSetMenuData -------------------------------------------------------------
glutSetMenuFont -------------------------------------------------------------
glutSetOption ---------------------------------------------------------------
glutSetVertexAttribCoord3 ---------------------------------------------------
glutSetVertexAttribNormal ---------------------------------------------------
glutSetVertexAttribTexCoord2 ------------------------------------------------
glutSetWindow ---------------------------------------------------------------
glutSetWindowData -----------------------------------------------------------
glutSetWindowTitle ----------------------------------------------------------
glutSetupVideoResizing ------------------------------------------------------
glutShowOverlay -------------------------------------------------------------
glutShowWindow --------------------------------------------------------------
glutSolidCone ---------------------------------------------------------------
-------------------------------------------------------------
glutSolidCylinder -----------------------------------------------------------
-----------------------------------------------------
------------------------------------------------------
-------------------------------------------------------
glutSolidRhombicDodecahedron ------------------------------------------------
glutSolidSierpinskiSponge ---------------------------------------------------
glutSolidSphere -------------------------------------------------------------
glutSolidTeacup -------------------------------------------------------------
glutSolidTeapot -------------------------------------------------------------
glutSolidTeaspoon -----------------------------------------------------------
glutSolidTetrahedron --------------------------------------------------------
glutSolidTorus --------------------------------------------------------------
glutSpaceballButtonFunc -----------------------------------------------------
---------------------------------------------------
glutSpaceballRotateFunc -----------------------------------------------------
glutSpecialFunc -------------------------------------------------------------
glutSpecialUpFunc -----------------------------------------------------------
glutStopVideoResizing -------------------------------------------------------
glutStrokeCharacter ---------------------------------------------------------
glutStrokeHeight ------------------------------------------------------------
glutStrokeLength ------------------------------------------------------------
glutStrokeString ------------------------------------------------------------
glutStrokeWidth -------------------------------------------------------------
glutSwapBuffers -------------------------------------------------------------
# NOINLINE ptr_glutSwapBuffers #
glutTabletButtonFunc --------------------------------------------------------
glutTabletMotionFunc --------------------------------------------------------
glutTimerFunc ---------------------------------------------------------------
glutUseLayer ----------------------------------------------------------------
glutVideoPan ----------------------------------------------------------------
glutVideoResize -------------------------------------------------------------
glutVideoResizeGet ----------------------------------------------------------
glutVisibilityFunc ----------------------------------------------------------
glutWMCloseFunc -------------------------------------------------------------
glutWarpPointer -------------------------------------------------------------
glutWindowStatusFunc --------------------------------------------------------
glutWireCone ----------------------------------------------------------------
--------------------------------------------------------------
glutWireCylinder ------------------------------------------------------------
glutWireDodecahedron --------------------------------------------------------
glutWireIcosahedron ---------------------------------------------------------
--------------------------------------------------------
glutWireRhombicDodecahedron -------------------------------------------------
glutWireSierpinskiSponge ----------------------------------------------------
glutWireSphere --------------------------------------------------------------
# NOINLINE ptr_glutWireSphere #
------------------------------------------------------------
glutWireTeapot --------------------------------------------------------------
glutWireTeaspoon ------------------------------------------------------------
-------------------------------------------------------
glutWireTorus --------------------------------------------------------------- | # LANGUAGE CPP #
Copyright : ( c ) 2018
Maintainer : < >
All raw functions from GLUT and freeglut .
module Graphics.UI.GLUT.Raw.Functions (
isKnown,
glutAddMenuEntry,
glutAddSubMenu,
glutAppStatusFunc,
glutAttachMenu,
glutBitmapCharacter,
glutBitmapHeight,
glutBitmapLength,
glutBitmapString,
glutBitmapWidth,
glutButtonBoxFunc,
glutChangeToMenuEntry,
glutChangeToSubMenu,
glutCloseFunc,
glutCopyColormap,
glutCreateMenu,
glutCreateSubWindow,
glutCreateWindow,
glutDestroyMenu,
glutDestroyWindow,
glutDetachMenu,
glutDeviceGet,
glutDialsFunc,
glutDisplayFunc,
glutEnterGameMode,
glutEntryFunc,
glutEstablishOverlay,
glutExit,
glutExtensionSupported,
glutForceJoystickFunc,
glutFullScreen,
glutFullScreenToggle,
glutGameModeGet,
glutGameModeString,
glutGet,
glutGetColor,
glutGetMenu,
glutGetMenuData,
glutGetModeValues,
glutGetModifiers,
glutGetProcAddress,
glutGetWindow,
glutGetWindowData,
glutHideOverlay,
glutHideWindow,
glutIconifyWindow,
glutIdleFunc,
glutIgnoreKeyRepeat,
glutInit,
glutInitContextFlags,
glutInitContextFunc,
glutInitContextProfile,
glutInitContextVersion,
glutInitDisplayMode,
glutInitDisplayString,
glutInitWindowPosition,
glutInitWindowSize,
glutJoystickFunc,
glutKeyboardFunc,
glutKeyboardUpFunc,
glutLayerGet,
glutLeaveFullScreen,
glutLeaveGameMode,
glutLeaveMainLoop,
glutMainLoop,
glutMainLoopEvent,
glutMenuDestroyFunc,
glutMenuStateFunc,
glutMenuStatusFunc,
glutMotionFunc,
glutMouseFunc,
glutMouseWheelFunc,
glutMultiButtonFunc,
glutMultiEntryFunc,
glutMultiMotionFunc,
glutMultiPassiveFunc,
glutOverlayDisplayFunc,
glutPassiveMotionFunc,
glutPopWindow,
glutPositionFunc,
glutPositionWindow,
glutPostOverlayRedisplay,
glutPostRedisplay,
glutPostWindowOverlayRedisplay,
glutPostWindowRedisplay,
glutPushWindow,
glutRemoveMenuItem,
glutRemoveOverlay,
glutReportErrors,
glutReshapeFunc,
glutReshapeWindow,
glutSetColor,
glutSetCursor,
glutSetIconTitle,
glutSetKeyRepeat,
glutSetMenu,
glutSetMenuData,
glutSetMenuFont,
glutSetOption,
glutSetVertexAttribCoord3,
glutSetVertexAttribNormal,
glutSetVertexAttribTexCoord2,
glutSetWindow,
glutSetWindowData,
glutSetWindowTitle,
glutSetupVideoResizing,
glutShowOverlay,
glutShowWindow,
glutSolidCone,
glutSolidCube,
glutSolidCylinder,
glutSolidDodecahedron,
glutSolidIcosahedron,
glutSolidOctahedron,
glutSolidRhombicDodecahedron,
glutSolidSierpinskiSponge,
glutSolidSphere,
glutSolidTeacup,
glutSolidTeapot,
glutSolidTeaspoon,
glutSolidTetrahedron,
glutSolidTorus,
glutSpaceballButtonFunc,
glutSpaceballMotionFunc,
glutSpaceballRotateFunc,
glutSpecialFunc,
glutSpecialUpFunc,
glutStopVideoResizing,
glutStrokeCharacter,
glutStrokeHeight,
glutStrokeLength,
glutStrokeString,
glutStrokeWidth,
glutSwapBuffers,
glutTabletButtonFunc,
glutTabletMotionFunc,
glutTimerFunc,
glutUseLayer,
glutVideoPan,
glutVideoResize,
glutVideoResizeGet,
glutVisibilityFunc,
glutWMCloseFunc,
glutWarpPointer,
glutWindowStatusFunc,
glutWireCone,
glutWireCube,
glutWireCylinder,
glutWireDodecahedron,
glutWireIcosahedron,
glutWireOctahedron,
glutWireRhombicDodecahedron,
glutWireSierpinskiSponge,
glutWireSphere,
glutWireTeacup,
glutWireTeapot,
glutWireTeaspoon,
glutWireTetrahedron,
glutWireTorus
) where
import Foreign.C.Types
import Control.Monad.IO.Class ( MonadIO(..) )
import Foreign.C.String ( withCString, CString )
import Foreign.Marshal.Error ( throwIf )
import Foreign.Ptr ( Ptr, FunPtr, nullFunPtr )
import Graphics.Rendering.OpenGL ( GLdouble, GLenum, GLfloat, GLint )
import System.IO.Unsafe ( unsafePerformIO )
import Graphics.UI.GLUT.Raw.Callbacks
| Retrieve a GLUT API entry by name . Throws a userError when no entry with
getAPIEntry :: String -> IO (FunPtr a)
getAPIEntry extensionEntry =
throwIfNullFunPtr ("unknown GLUT entry " ++ extensionEntry) $
getAPIEntryInternal extensionEntry
throwIfNullFunPtr :: String -> IO (FunPtr a) -> IO (FunPtr a)
throwIfNullFunPtr = throwIf (== nullFunPtr) . const
getAPIEntryInternal :: String -> IO (FunPtr a)
getAPIEntryInternal extensionEntry =
withCString extensionEntry hs_GLUT_getProcAddress
isKnown :: MonadIO m => String -> m Bool
isKnown = liftIO . fmap (/= nullFunPtr) . getAPIEntryInternal
foreign import ccall unsafe "hs_GLUT_getProcAddress"
hs_GLUT_getProcAddress :: CString -> IO (FunPtr a)
glutAddMenuEntry :: MonadIO m => Ptr CChar -> CInt -> m ()
glutAddMenuEntry v1 v2 = liftIO $ dyn_glutAddMenuEntry ptr_glutAddMenuEntry v1 v2
foreign import CALLCONV "dynamic" dyn_glutAddMenuEntry
:: FunPtr (Ptr CChar -> CInt -> IO ())
-> Ptr CChar -> CInt -> IO ()
# NOINLINE ptr_glutAddMenuEntry #
ptr_glutAddMenuEntry :: FunPtr a
ptr_glutAddMenuEntry = unsafePerformIO $ getAPIEntry "glutAddMenuEntry"
glutAddSubMenu :: MonadIO m => Ptr CChar -> CInt -> m ()
glutAddSubMenu v1 v2 = liftIO $ dyn_glutAddSubMenu ptr_glutAddSubMenu v1 v2
foreign import CALLCONV "dynamic" dyn_glutAddSubMenu
:: FunPtr (Ptr CChar -> CInt -> IO ())
-> Ptr CChar -> CInt -> IO ()
# NOINLINE ptr_glutAddSubMenu #
ptr_glutAddSubMenu :: FunPtr a
ptr_glutAddSubMenu = unsafePerformIO $ getAPIEntry "glutAddSubMenu"
glutAppStatusFunc :: MonadIO m => FunPtr AppStatusFunc -> m ()
glutAppStatusFunc v1 = liftIO $ dyn_glutAppStatusFunc ptr_glutAppStatusFunc v1
foreign import CALLCONV "dynamic" dyn_glutAppStatusFunc
:: FunPtr (FunPtr AppStatusFunc -> IO ())
-> FunPtr AppStatusFunc -> IO ()
# NOINLINE ptr_glutAppStatusFunc #
ptr_glutAppStatusFunc :: FunPtr a
ptr_glutAppStatusFunc = unsafePerformIO $ getAPIEntry "glutAppStatusFunc"
glutAttachMenu :: MonadIO m => CInt -> m ()
glutAttachMenu v1 = liftIO $ dyn_glutAttachMenu ptr_glutAttachMenu v1
foreign import CALLCONV "dynamic" dyn_glutAttachMenu
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutAttachMenu #
ptr_glutAttachMenu :: FunPtr a
ptr_glutAttachMenu = unsafePerformIO $ getAPIEntry "glutAttachMenu"
glutBitmapCharacter :: MonadIO m => Ptr a -> CInt -> m ()
glutBitmapCharacter v1 v2 = liftIO $ dyn_glutBitmapCharacter ptr_glutBitmapCharacter v1 v2
foreign import CALLCONV "dynamic" dyn_glutBitmapCharacter
:: FunPtr (Ptr a -> CInt -> IO ())
-> Ptr a -> CInt -> IO ()
# NOINLINE ptr_glutBitmapCharacter #
ptr_glutBitmapCharacter :: FunPtr a
ptr_glutBitmapCharacter = unsafePerformIO $ getAPIEntry "glutBitmapCharacter"
glutBitmapHeight :: MonadIO m => Ptr a -> m CInt
glutBitmapHeight v1 = liftIO $ dyn_glutBitmapHeight ptr_glutBitmapHeight v1
foreign import CALLCONV "dynamic" dyn_glutBitmapHeight
:: FunPtr (Ptr a -> IO CInt)
-> Ptr a -> IO CInt
# NOINLINE ptr_glutBitmapHeight #
ptr_glutBitmapHeight :: FunPtr a
ptr_glutBitmapHeight = unsafePerformIO $ getAPIEntry "glutBitmapHeight"
glutBitmapLength :: MonadIO m => Ptr a -> Ptr CUChar -> m CInt
glutBitmapLength v1 v2 = liftIO $ dyn_glutBitmapLength ptr_glutBitmapLength v1 v2
foreign import CALLCONV "dynamic" dyn_glutBitmapLength
:: FunPtr (Ptr a -> Ptr CUChar -> IO CInt)
-> Ptr a -> Ptr CUChar -> IO CInt
# NOINLINE ptr_glutBitmapLength #
ptr_glutBitmapLength :: FunPtr a
ptr_glutBitmapLength = unsafePerformIO $ getAPIEntry "glutBitmapLength"
glutBitmapString :: MonadIO m => Ptr a -> Ptr CUChar -> m ()
glutBitmapString v1 v2 = liftIO $ dyn_glutBitmapString ptr_glutBitmapString v1 v2
foreign import CALLCONV "dynamic" dyn_glutBitmapString
:: FunPtr (Ptr a -> Ptr CUChar -> IO ())
-> Ptr a -> Ptr CUChar -> IO ()
# NOINLINE ptr_glutBitmapString #
ptr_glutBitmapString :: FunPtr a
ptr_glutBitmapString = unsafePerformIO $ getAPIEntry "glutBitmapString"
glutBitmapWidth :: MonadIO m => Ptr a -> CInt -> m CInt
glutBitmapWidth v1 v2 = liftIO $ dyn_glutBitmapWidth ptr_glutBitmapWidth v1 v2
foreign import CALLCONV "dynamic" dyn_glutBitmapWidth
:: FunPtr (Ptr a -> CInt -> IO CInt)
-> Ptr a -> CInt -> IO CInt
# NOINLINE ptr_glutBitmapWidth #
ptr_glutBitmapWidth :: FunPtr a
ptr_glutBitmapWidth = unsafePerformIO $ getAPIEntry "glutBitmapWidth"
glutButtonBoxFunc :: MonadIO m => FunPtr ButtonBoxFunc -> m ()
glutButtonBoxFunc v1 = liftIO $ dyn_glutButtonBoxFunc ptr_glutButtonBoxFunc v1
foreign import CALLCONV "dynamic" dyn_glutButtonBoxFunc
:: FunPtr (FunPtr ButtonBoxFunc -> IO ())
-> FunPtr ButtonBoxFunc -> IO ()
# NOINLINE ptr_glutButtonBoxFunc #
ptr_glutButtonBoxFunc :: FunPtr a
ptr_glutButtonBoxFunc = unsafePerformIO $ getAPIEntry "glutButtonBoxFunc"
glutChangeToMenuEntry :: MonadIO m => CInt -> Ptr CChar -> CInt -> m ()
glutChangeToMenuEntry v1 v2 v3 = liftIO $ dyn_glutChangeToMenuEntry ptr_glutChangeToMenuEntry v1 v2 v3
foreign import CALLCONV "dynamic" dyn_glutChangeToMenuEntry
:: FunPtr (CInt -> Ptr CChar -> CInt -> IO ())
-> CInt -> Ptr CChar -> CInt -> IO ()
# NOINLINE ptr_glutChangeToMenuEntry #
ptr_glutChangeToMenuEntry :: FunPtr a
ptr_glutChangeToMenuEntry = unsafePerformIO $ getAPIEntry "glutChangeToMenuEntry"
glutChangeToSubMenu :: MonadIO m => CInt -> Ptr CChar -> CInt -> m ()
glutChangeToSubMenu v1 v2 v3 = liftIO $ dyn_glutChangeToSubMenu ptr_glutChangeToSubMenu v1 v2 v3
foreign import CALLCONV "dynamic" dyn_glutChangeToSubMenu
:: FunPtr (CInt -> Ptr CChar -> CInt -> IO ())
-> CInt -> Ptr CChar -> CInt -> IO ()
# NOINLINE ptr_glutChangeToSubMenu #
ptr_glutChangeToSubMenu :: FunPtr a
ptr_glutChangeToSubMenu = unsafePerformIO $ getAPIEntry "glutChangeToSubMenu"
glutCloseFunc :: MonadIO m => FunPtr CloseFunc -> m ()
glutCloseFunc v1 = liftIO $ dyn_glutCloseFunc ptr_glutCloseFunc v1
foreign import CALLCONV "dynamic" dyn_glutCloseFunc
:: FunPtr (FunPtr CloseFunc -> IO ())
-> FunPtr CloseFunc -> IO ()
# NOINLINE ptr_glutCloseFunc #
ptr_glutCloseFunc :: FunPtr a
ptr_glutCloseFunc = unsafePerformIO $ getAPIEntry "glutCloseFunc"
glutCopyColormap :: MonadIO m => CInt -> m ()
glutCopyColormap v1 = liftIO $ dyn_glutCopyColormap ptr_glutCopyColormap v1
foreign import CALLCONV "dynamic" dyn_glutCopyColormap
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutCopyColormap #
ptr_glutCopyColormap :: FunPtr a
ptr_glutCopyColormap = unsafePerformIO $ getAPIEntry "glutCopyColormap"
glutCreateMenu :: MonadIO m => FunPtr MenuFunc -> m CInt
glutCreateMenu v1 = liftIO $ dyn_glutCreateMenu ptr_glutCreateMenu v1
foreign import CALLCONV "dynamic" dyn_glutCreateMenu
:: FunPtr (FunPtr MenuFunc -> IO CInt)
-> FunPtr MenuFunc -> IO CInt
# NOINLINE ptr_glutCreateMenu #
ptr_glutCreateMenu :: FunPtr a
ptr_glutCreateMenu = unsafePerformIO $ getAPIEntry "glutCreateMenu"
glutCreateSubWindow :: MonadIO m => CInt -> CInt -> CInt -> CInt -> CInt -> m CInt
glutCreateSubWindow v1 v2 v3 v4 v5 = liftIO $ dyn_glutCreateSubWindow ptr_glutCreateSubWindow v1 v2 v3 v4 v5
foreign import CALLCONV "dynamic" dyn_glutCreateSubWindow
:: FunPtr (CInt -> CInt -> CInt -> CInt -> CInt -> IO CInt)
-> CInt -> CInt -> CInt -> CInt -> CInt -> IO CInt
# NOINLINE ptr_glutCreateSubWindow #
ptr_glutCreateSubWindow :: FunPtr a
ptr_glutCreateSubWindow = unsafePerformIO $ getAPIEntry "glutCreateSubWindow"
glutCreateWindow :: MonadIO m => Ptr CChar -> m CInt
glutCreateWindow v1 = liftIO $ dyn_glutCreateWindow ptr_glutCreateWindow v1
foreign import CALLCONV "dynamic" dyn_glutCreateWindow
:: FunPtr (Ptr CChar -> IO CInt)
-> Ptr CChar -> IO CInt
# NOINLINE ptr_glutCreateWindow #
ptr_glutCreateWindow :: FunPtr a
ptr_glutCreateWindow = unsafePerformIO $ getAPIEntry "glutCreateWindow"
glutDestroyMenu :: MonadIO m => CInt -> m ()
glutDestroyMenu v1 = liftIO $ dyn_glutDestroyMenu ptr_glutDestroyMenu v1
foreign import CALLCONV "dynamic" dyn_glutDestroyMenu
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutDestroyMenu #
ptr_glutDestroyMenu :: FunPtr a
ptr_glutDestroyMenu = unsafePerformIO $ getAPIEntry "glutDestroyMenu"
glutDestroyWindow :: MonadIO m => CInt -> m ()
glutDestroyWindow v1 = liftIO $ dyn_glutDestroyWindow ptr_glutDestroyWindow v1
foreign import CALLCONV "dynamic" dyn_glutDestroyWindow
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutDestroyWindow #
ptr_glutDestroyWindow :: FunPtr a
ptr_glutDestroyWindow = unsafePerformIO $ getAPIEntry "glutDestroyWindow"
glutDetachMenu :: MonadIO m => CInt -> m ()
glutDetachMenu v1 = liftIO $ dyn_glutDetachMenu ptr_glutDetachMenu v1
foreign import CALLCONV "dynamic" dyn_glutDetachMenu
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutDetachMenu #
ptr_glutDetachMenu :: FunPtr a
ptr_glutDetachMenu = unsafePerformIO $ getAPIEntry "glutDetachMenu"
glutDeviceGet :: MonadIO m => GLenum -> m CInt
glutDeviceGet v1 = liftIO $ dyn_glutDeviceGet ptr_glutDeviceGet v1
foreign import CALLCONV "dynamic" dyn_glutDeviceGet
:: FunPtr (GLenum -> IO CInt)
-> GLenum -> IO CInt
# NOINLINE ptr_glutDeviceGet #
ptr_glutDeviceGet :: FunPtr a
ptr_glutDeviceGet = unsafePerformIO $ getAPIEntry "glutDeviceGet"
glutDialsFunc :: MonadIO m => FunPtr DialsFunc -> m ()
glutDialsFunc v1 = liftIO $ dyn_glutDialsFunc ptr_glutDialsFunc v1
foreign import CALLCONV "dynamic" dyn_glutDialsFunc
:: FunPtr (FunPtr DialsFunc -> IO ())
-> FunPtr DialsFunc -> IO ()
# NOINLINE ptr_glutDialsFunc #
ptr_glutDialsFunc :: FunPtr a
ptr_glutDialsFunc = unsafePerformIO $ getAPIEntry "glutDialsFunc"
glutDisplayFunc :: MonadIO m => FunPtr DisplayFunc -> m ()
glutDisplayFunc v1 = liftIO $ dyn_glutDisplayFunc ptr_glutDisplayFunc v1
foreign import CALLCONV "dynamic" dyn_glutDisplayFunc
:: FunPtr (FunPtr DisplayFunc -> IO ())
-> FunPtr DisplayFunc -> IO ()
# NOINLINE ptr_glutDisplayFunc #
ptr_glutDisplayFunc :: FunPtr a
ptr_glutDisplayFunc = unsafePerformIO $ getAPIEntry "glutDisplayFunc"
glutEnterGameMode :: MonadIO m => m CInt
glutEnterGameMode = liftIO $ dyn_glutEnterGameMode ptr_glutEnterGameMode
foreign import CALLCONV "dynamic" dyn_glutEnterGameMode
:: FunPtr (IO CInt)
-> IO CInt
# NOINLINE ptr_glutEnterGameMode #
ptr_glutEnterGameMode :: FunPtr a
ptr_glutEnterGameMode = unsafePerformIO $ getAPIEntry "glutEnterGameMode"
glutEntryFunc :: MonadIO m => FunPtr EntryFunc -> m ()
glutEntryFunc v1 = liftIO $ dyn_glutEntryFunc ptr_glutEntryFunc v1
foreign import CALLCONV "dynamic" dyn_glutEntryFunc
:: FunPtr (FunPtr EntryFunc -> IO ())
-> FunPtr EntryFunc -> IO ()
# NOINLINE ptr_glutEntryFunc #
ptr_glutEntryFunc :: FunPtr a
ptr_glutEntryFunc = unsafePerformIO $ getAPIEntry "glutEntryFunc"
glutEstablishOverlay :: MonadIO m => m ()
glutEstablishOverlay = liftIO $ dyn_glutEstablishOverlay ptr_glutEstablishOverlay
foreign import CALLCONV "dynamic" dyn_glutEstablishOverlay
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutEstablishOverlay #
ptr_glutEstablishOverlay :: FunPtr a
ptr_glutEstablishOverlay = unsafePerformIO $ getAPIEntry "glutEstablishOverlay"
glutExit :: MonadIO m => m ()
glutExit = liftIO $ dyn_glutExit ptr_glutExit
foreign import CALLCONV "dynamic" dyn_glutExit
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutExit #
ptr_glutExit :: FunPtr a
ptr_glutExit = unsafePerformIO $ getAPIEntry "glutExit"
glutExtensionSupported :: MonadIO m => Ptr CChar -> m CInt
glutExtensionSupported v1 = liftIO $ dyn_glutExtensionSupported ptr_glutExtensionSupported v1
foreign import CALLCONV "dynamic" dyn_glutExtensionSupported
:: FunPtr (Ptr CChar -> IO CInt)
-> Ptr CChar -> IO CInt
# NOINLINE ptr_glutExtensionSupported #
ptr_glutExtensionSupported :: FunPtr a
ptr_glutExtensionSupported = unsafePerformIO $ getAPIEntry "glutExtensionSupported"
glutForceJoystickFunc :: MonadIO m => m ()
glutForceJoystickFunc = liftIO $ dyn_glutForceJoystickFunc ptr_glutForceJoystickFunc
foreign import CALLCONV "dynamic" dyn_glutForceJoystickFunc
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutForceJoystickFunc #
ptr_glutForceJoystickFunc :: FunPtr a
ptr_glutForceJoystickFunc = unsafePerformIO $ getAPIEntry "glutForceJoystickFunc"
glutFullScreen :: MonadIO m => m ()
glutFullScreen = liftIO $ dyn_glutFullScreen ptr_glutFullScreen
foreign import CALLCONV "dynamic" dyn_glutFullScreen
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutFullScreen #
ptr_glutFullScreen :: FunPtr a
ptr_glutFullScreen = unsafePerformIO $ getAPIEntry "glutFullScreen"
glutFullScreenToggle :: MonadIO m => m ()
glutFullScreenToggle = liftIO $ dyn_glutFullScreenToggle ptr_glutFullScreenToggle
foreign import CALLCONV "dynamic" dyn_glutFullScreenToggle
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutFullScreenToggle #
ptr_glutFullScreenToggle :: FunPtr a
ptr_glutFullScreenToggle = unsafePerformIO $ getAPIEntry "glutFullScreenToggle"
glutGameModeGet :: MonadIO m => GLenum -> m CInt
glutGameModeGet v1 = liftIO $ dyn_glutGameModeGet ptr_glutGameModeGet v1
foreign import CALLCONV "dynamic" dyn_glutGameModeGet
:: FunPtr (GLenum -> IO CInt)
-> GLenum -> IO CInt
# NOINLINE ptr_glutGameModeGet #
ptr_glutGameModeGet :: FunPtr a
ptr_glutGameModeGet = unsafePerformIO $ getAPIEntry "glutGameModeGet"
glutGameModeString :: MonadIO m => Ptr CChar -> m ()
glutGameModeString v1 = liftIO $ dyn_glutGameModeString ptr_glutGameModeString v1
foreign import CALLCONV "dynamic" dyn_glutGameModeString
:: FunPtr (Ptr CChar -> IO ())
-> Ptr CChar -> IO ()
# NOINLINE ptr_glutGameModeString #
ptr_glutGameModeString :: FunPtr a
ptr_glutGameModeString = unsafePerformIO $ getAPIEntry "glutGameModeString"
glutGet :: MonadIO m => GLenum -> m CInt
glutGet v1 = liftIO $ dyn_glutGet ptr_glutGet v1
foreign import CALLCONV "dynamic" dyn_glutGet
:: FunPtr (GLenum -> IO CInt)
-> GLenum -> IO CInt
# NOINLINE ptr_glutGet #
ptr_glutGet :: FunPtr a
ptr_glutGet = unsafePerformIO $ getAPIEntry "glutGet"
glutGetColor :: MonadIO m => CInt -> CInt -> m GLfloat
glutGetColor v1 v2 = liftIO $ dyn_glutGetColor ptr_glutGetColor v1 v2
foreign import CALLCONV "dynamic" dyn_glutGetColor
:: FunPtr (CInt -> CInt -> IO GLfloat)
-> CInt -> CInt -> IO GLfloat
# NOINLINE ptr_glutGetColor #
ptr_glutGetColor :: FunPtr a
ptr_glutGetColor = unsafePerformIO $ getAPIEntry "glutGetColor"
glutGetMenu :: MonadIO m => m CInt
glutGetMenu = liftIO $ dyn_glutGetMenu ptr_glutGetMenu
foreign import CALLCONV "dynamic" dyn_glutGetMenu
:: FunPtr (IO CInt)
-> IO CInt
# NOINLINE ptr_glutGetMenu #
ptr_glutGetMenu :: FunPtr a
ptr_glutGetMenu = unsafePerformIO $ getAPIEntry "glutGetMenu"
glutGetMenuData :: MonadIO m => m (Ptr a)
glutGetMenuData = liftIO $ dyn_glutGetMenuData ptr_glutGetMenuData
foreign import CALLCONV "dynamic" dyn_glutGetMenuData
:: FunPtr (IO (Ptr a))
-> IO (Ptr a)
# NOINLINE ptr_glutGetMenuData #
ptr_glutGetMenuData :: FunPtr a
ptr_glutGetMenuData = unsafePerformIO $ getAPIEntry "glutGetMenuData"
glutGetModeValues :: MonadIO m => GLenum -> Ptr CInt -> m (Ptr CInt)
glutGetModeValues v1 v2 = liftIO $ dyn_glutGetModeValues ptr_glutGetModeValues v1 v2
foreign import CALLCONV "dynamic" dyn_glutGetModeValues
:: FunPtr (GLenum -> Ptr CInt -> IO (Ptr CInt))
-> GLenum -> Ptr CInt -> IO (Ptr CInt)
# NOINLINE ptr_glutGetModeValues #
ptr_glutGetModeValues :: FunPtr a
ptr_glutGetModeValues = unsafePerformIO $ getAPIEntry "glutGetModeValues"
glutGetModifiers :: MonadIO m => m CInt
glutGetModifiers = liftIO $ dyn_glutGetModifiers ptr_glutGetModifiers
foreign import CALLCONV "dynamic" dyn_glutGetModifiers
:: FunPtr (IO CInt)
-> IO CInt
# NOINLINE ptr_glutGetModifiers #
ptr_glutGetModifiers :: FunPtr a
ptr_glutGetModifiers = unsafePerformIO $ getAPIEntry "glutGetModifiers"
glutGetProcAddress :: MonadIO m => Ptr CChar -> m (FunPtr a)
glutGetProcAddress v1 = liftIO $ dyn_glutGetProcAddress ptr_glutGetProcAddress v1
foreign import CALLCONV "dynamic" dyn_glutGetProcAddress
:: FunPtr (Ptr CChar -> IO (FunPtr a))
-> Ptr CChar -> IO (FunPtr a)
# NOINLINE ptr_glutGetProcAddress #
ptr_glutGetProcAddress :: FunPtr a
ptr_glutGetProcAddress = unsafePerformIO $ getAPIEntry "glutGetProcAddress"
glutGetWindow :: MonadIO m => m CInt
glutGetWindow = liftIO $ dyn_glutGetWindow ptr_glutGetWindow
foreign import CALLCONV "dynamic" dyn_glutGetWindow
:: FunPtr (IO CInt)
-> IO CInt
# NOINLINE ptr_glutGetWindow #
ptr_glutGetWindow :: FunPtr a
ptr_glutGetWindow = unsafePerformIO $ getAPIEntry "glutGetWindow"
glutGetWindowData :: MonadIO m => m (Ptr a)
glutGetWindowData = liftIO $ dyn_glutGetWindowData ptr_glutGetWindowData
foreign import CALLCONV "dynamic" dyn_glutGetWindowData
:: FunPtr (IO (Ptr a))
-> IO (Ptr a)
# NOINLINE ptr_glutGetWindowData #
ptr_glutGetWindowData :: FunPtr a
ptr_glutGetWindowData = unsafePerformIO $ getAPIEntry "glutGetWindowData"
glutHideOverlay :: MonadIO m => m ()
glutHideOverlay = liftIO $ dyn_glutHideOverlay ptr_glutHideOverlay
foreign import CALLCONV "dynamic" dyn_glutHideOverlay
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutHideOverlay #
ptr_glutHideOverlay :: FunPtr a
ptr_glutHideOverlay = unsafePerformIO $ getAPIEntry "glutHideOverlay"
glutHideWindow :: MonadIO m => m ()
glutHideWindow = liftIO $ dyn_glutHideWindow ptr_glutHideWindow
foreign import CALLCONV "dynamic" dyn_glutHideWindow
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutHideWindow #
ptr_glutHideWindow :: FunPtr a
ptr_glutHideWindow = unsafePerformIO $ getAPIEntry "glutHideWindow"
glutIconifyWindow :: MonadIO m => m ()
glutIconifyWindow = liftIO $ dyn_glutIconifyWindow ptr_glutIconifyWindow
foreign import CALLCONV "dynamic" dyn_glutIconifyWindow
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutIconifyWindow #
ptr_glutIconifyWindow :: FunPtr a
ptr_glutIconifyWindow = unsafePerformIO $ getAPIEntry "glutIconifyWindow"
glutIdleFunc :: MonadIO m => FunPtr IdleFunc -> m ()
glutIdleFunc v1 = liftIO $ dyn_glutIdleFunc ptr_glutIdleFunc v1
foreign import CALLCONV "dynamic" dyn_glutIdleFunc
:: FunPtr (FunPtr IdleFunc -> IO ())
-> FunPtr IdleFunc -> IO ()
# NOINLINE ptr_glutIdleFunc #
ptr_glutIdleFunc :: FunPtr a
ptr_glutIdleFunc = unsafePerformIO $ getAPIEntry "glutIdleFunc"
glutIgnoreKeyRepeat :: MonadIO m => CInt -> m ()
glutIgnoreKeyRepeat v1 = liftIO $ dyn_glutIgnoreKeyRepeat ptr_glutIgnoreKeyRepeat v1
foreign import CALLCONV "dynamic" dyn_glutIgnoreKeyRepeat
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
ptr_glutIgnoreKeyRepeat :: FunPtr a
ptr_glutIgnoreKeyRepeat = unsafePerformIO $ getAPIEntry "glutIgnoreKeyRepeat"
glutInit :: MonadIO m => Ptr CInt -> Ptr (Ptr CChar) -> m ()
glutInit v1 v2 = liftIO $ dyn_glutInit ptr_glutInit v1 v2
foreign import CALLCONV "dynamic" dyn_glutInit
:: FunPtr (Ptr CInt -> Ptr (Ptr CChar) -> IO ())
-> Ptr CInt -> Ptr (Ptr CChar) -> IO ()
# NOINLINE ptr_glutInit #
ptr_glutInit :: FunPtr a
ptr_glutInit = unsafePerformIO $ getAPIEntry "glutInit"
glutInitContextFlags :: MonadIO m => CInt -> m ()
glutInitContextFlags v1 = liftIO $ dyn_glutInitContextFlags ptr_glutInitContextFlags v1
foreign import CALLCONV "dynamic" dyn_glutInitContextFlags
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutInitContextFlags #
ptr_glutInitContextFlags :: FunPtr a
ptr_glutInitContextFlags = unsafePerformIO $ getAPIEntry "glutInitContextFlags"
glutInitContextFunc :: MonadIO m => FunPtr InitContextFunc -> m ()
glutInitContextFunc v1 = liftIO $ dyn_glutInitContextFunc ptr_glutInitContextFunc v1
foreign import CALLCONV "dynamic" dyn_glutInitContextFunc
:: FunPtr (FunPtr InitContextFunc -> IO ())
-> FunPtr InitContextFunc -> IO ()
# NOINLINE ptr_glutInitContextFunc #
ptr_glutInitContextFunc :: FunPtr a
ptr_glutInitContextFunc = unsafePerformIO $ getAPIEntry "glutInitContextFunc"
glutInitContextProfile :: MonadIO m => CInt -> m ()
glutInitContextProfile v1 = liftIO $ dyn_glutInitContextProfile ptr_glutInitContextProfile v1
foreign import CALLCONV "dynamic" dyn_glutInitContextProfile
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutInitContextProfile #
ptr_glutInitContextProfile :: FunPtr a
ptr_glutInitContextProfile = unsafePerformIO $ getAPIEntry "glutInitContextProfile"
glutInitContextVersion :: MonadIO m => CInt -> CInt -> m ()
glutInitContextVersion v1 v2 = liftIO $ dyn_glutInitContextVersion ptr_glutInitContextVersion v1 v2
foreign import CALLCONV "dynamic" dyn_glutInitContextVersion
:: FunPtr (CInt -> CInt -> IO ())
-> CInt -> CInt -> IO ()
# NOINLINE ptr_glutInitContextVersion #
ptr_glutInitContextVersion :: FunPtr a
ptr_glutInitContextVersion = unsafePerformIO $ getAPIEntry "glutInitContextVersion"
glutInitDisplayMode :: MonadIO m => CUInt -> m ()
glutInitDisplayMode v1 = liftIO $ dyn_glutInitDisplayMode ptr_glutInitDisplayMode v1
foreign import CALLCONV "dynamic" dyn_glutInitDisplayMode
:: FunPtr (CUInt -> IO ())
-> CUInt -> IO ()
# NOINLINE ptr_glutInitDisplayMode #
ptr_glutInitDisplayMode :: FunPtr a
ptr_glutInitDisplayMode = unsafePerformIO $ getAPIEntry "glutInitDisplayMode"
glutInitDisplayString :: MonadIO m => Ptr CChar -> m ()
glutInitDisplayString v1 = liftIO $ dyn_glutInitDisplayString ptr_glutInitDisplayString v1
foreign import CALLCONV "dynamic" dyn_glutInitDisplayString
:: FunPtr (Ptr CChar -> IO ())
-> Ptr CChar -> IO ()
# NOINLINE ptr_glutInitDisplayString #
ptr_glutInitDisplayString :: FunPtr a
ptr_glutInitDisplayString = unsafePerformIO $ getAPIEntry "glutInitDisplayString"
glutInitWindowPosition :: MonadIO m => CInt -> CInt -> m ()
glutInitWindowPosition v1 v2 = liftIO $ dyn_glutInitWindowPosition ptr_glutInitWindowPosition v1 v2
foreign import CALLCONV "dynamic" dyn_glutInitWindowPosition
:: FunPtr (CInt -> CInt -> IO ())
-> CInt -> CInt -> IO ()
# NOINLINE ptr_glutInitWindowPosition #
ptr_glutInitWindowPosition :: FunPtr a
ptr_glutInitWindowPosition = unsafePerformIO $ getAPIEntry "glutInitWindowPosition"
glutInitWindowSize :: MonadIO m => CInt -> CInt -> m ()
glutInitWindowSize v1 v2 = liftIO $ dyn_glutInitWindowSize ptr_glutInitWindowSize v1 v2
foreign import CALLCONV "dynamic" dyn_glutInitWindowSize
:: FunPtr (CInt -> CInt -> IO ())
-> CInt -> CInt -> IO ()
# NOINLINE ptr_glutInitWindowSize #
ptr_glutInitWindowSize :: FunPtr a
ptr_glutInitWindowSize = unsafePerformIO $ getAPIEntry "glutInitWindowSize"
glutJoystickFunc :: MonadIO m => FunPtr JoystickFunc -> CInt -> m ()
glutJoystickFunc v1 v2 = liftIO $ dyn_glutJoystickFunc ptr_glutJoystickFunc v1 v2
foreign import CALLCONV "dynamic" dyn_glutJoystickFunc
:: FunPtr (FunPtr JoystickFunc -> CInt -> IO ())
-> FunPtr JoystickFunc -> CInt -> IO ()
# NOINLINE ptr_glutJoystickFunc #
ptr_glutJoystickFunc :: FunPtr a
ptr_glutJoystickFunc = unsafePerformIO $ getAPIEntry "glutJoystickFunc"
glutKeyboardFunc :: MonadIO m => FunPtr KeyboardFunc -> m ()
glutKeyboardFunc v1 = liftIO $ dyn_glutKeyboardFunc ptr_glutKeyboardFunc v1
foreign import CALLCONV "dynamic" dyn_glutKeyboardFunc
:: FunPtr (FunPtr KeyboardFunc -> IO ())
-> FunPtr KeyboardFunc -> IO ()
# NOINLINE ptr_glutKeyboardFunc #
ptr_glutKeyboardFunc :: FunPtr a
ptr_glutKeyboardFunc = unsafePerformIO $ getAPIEntry "glutKeyboardFunc"
glutKeyboardUpFunc :: MonadIO m => FunPtr KeyboardUpFunc -> m ()
glutKeyboardUpFunc v1 = liftIO $ dyn_glutKeyboardUpFunc ptr_glutKeyboardUpFunc v1
foreign import CALLCONV "dynamic" dyn_glutKeyboardUpFunc
:: FunPtr (FunPtr KeyboardUpFunc -> IO ())
-> FunPtr KeyboardUpFunc -> IO ()
# NOINLINE ptr_glutKeyboardUpFunc #
ptr_glutKeyboardUpFunc :: FunPtr a
ptr_glutKeyboardUpFunc = unsafePerformIO $ getAPIEntry "glutKeyboardUpFunc"
glutLayerGet :: MonadIO m => GLenum -> m CInt
glutLayerGet v1 = liftIO $ dyn_glutLayerGet ptr_glutLayerGet v1
foreign import CALLCONV "dynamic" dyn_glutLayerGet
:: FunPtr (GLenum -> IO CInt)
-> GLenum -> IO CInt
# NOINLINE ptr_glutLayerGet #
ptr_glutLayerGet :: FunPtr a
ptr_glutLayerGet = unsafePerformIO $ getAPIEntry "glutLayerGet"
glutLeaveFullScreen :: MonadIO m => m ()
glutLeaveFullScreen = liftIO $ dyn_glutLeaveFullScreen ptr_glutLeaveFullScreen
foreign import CALLCONV "dynamic" dyn_glutLeaveFullScreen
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutLeaveFullScreen #
ptr_glutLeaveFullScreen :: FunPtr a
ptr_glutLeaveFullScreen = unsafePerformIO $ getAPIEntry "glutLeaveFullScreen"
glutLeaveGameMode :: MonadIO m => m ()
glutLeaveGameMode = liftIO $ dyn_glutLeaveGameMode ptr_glutLeaveGameMode
foreign import CALLCONV "dynamic" dyn_glutLeaveGameMode
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutLeaveGameMode #
ptr_glutLeaveGameMode :: FunPtr a
ptr_glutLeaveGameMode = unsafePerformIO $ getAPIEntry "glutLeaveGameMode"
glutLeaveMainLoop :: MonadIO m => m ()
glutLeaveMainLoop = liftIO $ dyn_glutLeaveMainLoop ptr_glutLeaveMainLoop
foreign import CALLCONV "dynamic" dyn_glutLeaveMainLoop
:: FunPtr (IO ())
-> IO ()
ptr_glutLeaveMainLoop :: FunPtr a
ptr_glutLeaveMainLoop = unsafePerformIO $ getAPIEntry "glutLeaveMainLoop"
glutMainLoop :: MonadIO m => m ()
glutMainLoop = liftIO $ dyn_glutMainLoop ptr_glutMainLoop
foreign import CALLCONV "dynamic" dyn_glutMainLoop
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutMainLoop #
ptr_glutMainLoop :: FunPtr a
ptr_glutMainLoop = unsafePerformIO $ getAPIEntry "glutMainLoop"
glutMainLoopEvent :: MonadIO m => m ()
glutMainLoopEvent = liftIO $ dyn_glutMainLoopEvent ptr_glutMainLoopEvent
foreign import CALLCONV "dynamic" dyn_glutMainLoopEvent
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutMainLoopEvent #
ptr_glutMainLoopEvent :: FunPtr a
ptr_glutMainLoopEvent = unsafePerformIO $ getAPIEntry "glutMainLoopEvent"
glutMenuDestroyFunc :: MonadIO m => FunPtr MenuDestroyFunc -> m ()
glutMenuDestroyFunc v1 = liftIO $ dyn_glutMenuDestroyFunc ptr_glutMenuDestroyFunc v1
foreign import CALLCONV "dynamic" dyn_glutMenuDestroyFunc
:: FunPtr (FunPtr MenuDestroyFunc -> IO ())
-> FunPtr MenuDestroyFunc -> IO ()
# NOINLINE ptr_glutMenuDestroyFunc #
ptr_glutMenuDestroyFunc :: FunPtr a
ptr_glutMenuDestroyFunc = unsafePerformIO $ getAPIEntry "glutMenuDestroyFunc"
glutMenuStateFunc :: MonadIO m => FunPtr MenuStateFunc -> m ()
glutMenuStateFunc v1 = liftIO $ dyn_glutMenuStateFunc ptr_glutMenuStateFunc v1
foreign import CALLCONV "dynamic" dyn_glutMenuStateFunc
:: FunPtr (FunPtr MenuStateFunc -> IO ())
-> FunPtr MenuStateFunc -> IO ()
# NOINLINE ptr_glutMenuStateFunc #
ptr_glutMenuStateFunc :: FunPtr a
ptr_glutMenuStateFunc = unsafePerformIO $ getAPIEntry "glutMenuStateFunc"
glutMenuStatusFunc :: MonadIO m => FunPtr MenuStatusFunc -> m ()
glutMenuStatusFunc v1 = liftIO $ dyn_glutMenuStatusFunc ptr_glutMenuStatusFunc v1
foreign import CALLCONV "dynamic" dyn_glutMenuStatusFunc
:: FunPtr (FunPtr MenuStatusFunc -> IO ())
-> FunPtr MenuStatusFunc -> IO ()
# NOINLINE ptr_glutMenuStatusFunc #
ptr_glutMenuStatusFunc :: FunPtr a
ptr_glutMenuStatusFunc = unsafePerformIO $ getAPIEntry "glutMenuStatusFunc"
glutMotionFunc :: MonadIO m => FunPtr MotionFunc -> m ()
glutMotionFunc v1 = liftIO $ dyn_glutMotionFunc ptr_glutMotionFunc v1
foreign import CALLCONV "dynamic" dyn_glutMotionFunc
:: FunPtr (FunPtr MotionFunc -> IO ())
-> FunPtr MotionFunc -> IO ()
# NOINLINE ptr_glutMotionFunc #
ptr_glutMotionFunc :: FunPtr a
ptr_glutMotionFunc = unsafePerformIO $ getAPIEntry "glutMotionFunc"
glutMouseFunc :: MonadIO m => FunPtr MouseFunc -> m ()
glutMouseFunc v1 = liftIO $ dyn_glutMouseFunc ptr_glutMouseFunc v1
foreign import CALLCONV "dynamic" dyn_glutMouseFunc
:: FunPtr (FunPtr MouseFunc -> IO ())
-> FunPtr MouseFunc -> IO ()
# NOINLINE ptr_glutMouseFunc #
ptr_glutMouseFunc :: FunPtr a
ptr_glutMouseFunc = unsafePerformIO $ getAPIEntry "glutMouseFunc"
glutMouseWheelFunc :: MonadIO m => FunPtr MouseWheelFunc -> m ()
glutMouseWheelFunc v1 = liftIO $ dyn_glutMouseWheelFunc ptr_glutMouseWheelFunc v1
foreign import CALLCONV "dynamic" dyn_glutMouseWheelFunc
:: FunPtr (FunPtr MouseWheelFunc -> IO ())
-> FunPtr MouseWheelFunc -> IO ()
# NOINLINE ptr_glutMouseWheelFunc #
ptr_glutMouseWheelFunc :: FunPtr a
ptr_glutMouseWheelFunc = unsafePerformIO $ getAPIEntry "glutMouseWheelFunc"
glutMultiButtonFunc :: MonadIO m => FunPtr MultiButtonFunc -> m ()
glutMultiButtonFunc v1 = liftIO $ dyn_glutMultiButtonFunc ptr_glutMultiButtonFunc v1
foreign import CALLCONV "dynamic" dyn_glutMultiButtonFunc
:: FunPtr (FunPtr MultiButtonFunc -> IO ())
-> FunPtr MultiButtonFunc -> IO ()
# NOINLINE ptr_glutMultiButtonFunc #
ptr_glutMultiButtonFunc :: FunPtr a
ptr_glutMultiButtonFunc = unsafePerformIO $ getAPIEntry "glutMultiButtonFunc"
glutMultiEntryFunc :: MonadIO m => FunPtr MultiEntryFunc -> m ()
glutMultiEntryFunc v1 = liftIO $ dyn_glutMultiEntryFunc ptr_glutMultiEntryFunc v1
foreign import CALLCONV "dynamic" dyn_glutMultiEntryFunc
:: FunPtr (FunPtr MultiEntryFunc -> IO ())
-> FunPtr MultiEntryFunc -> IO ()
# NOINLINE ptr_glutMultiEntryFunc #
ptr_glutMultiEntryFunc :: FunPtr a
ptr_glutMultiEntryFunc = unsafePerformIO $ getAPIEntry "glutMultiEntryFunc"
glutMultiMotionFunc :: MonadIO m => FunPtr MultiMotionFunc -> m ()
glutMultiMotionFunc v1 = liftIO $ dyn_glutMultiMotionFunc ptr_glutMultiMotionFunc v1
foreign import CALLCONV "dynamic" dyn_glutMultiMotionFunc
:: FunPtr (FunPtr MultiMotionFunc -> IO ())
-> FunPtr MultiMotionFunc -> IO ()
# NOINLINE ptr_glutMultiMotionFunc #
ptr_glutMultiMotionFunc :: FunPtr a
ptr_glutMultiMotionFunc = unsafePerformIO $ getAPIEntry "glutMultiMotionFunc"
glutMultiPassiveFunc :: MonadIO m => FunPtr MultiPassiveFunc -> m ()
glutMultiPassiveFunc v1 = liftIO $ dyn_glutMultiPassiveFunc ptr_glutMultiPassiveFunc v1
foreign import CALLCONV "dynamic" dyn_glutMultiPassiveFunc
:: FunPtr (FunPtr MultiPassiveFunc -> IO ())
-> FunPtr MultiPassiveFunc -> IO ()
# NOINLINE ptr_glutMultiPassiveFunc #
ptr_glutMultiPassiveFunc :: FunPtr a
ptr_glutMultiPassiveFunc = unsafePerformIO $ getAPIEntry "glutMultiPassiveFunc"
glutOverlayDisplayFunc :: MonadIO m => FunPtr OverlayDisplayFunc -> m ()
glutOverlayDisplayFunc v1 = liftIO $ dyn_glutOverlayDisplayFunc ptr_glutOverlayDisplayFunc v1
foreign import CALLCONV "dynamic" dyn_glutOverlayDisplayFunc
:: FunPtr (FunPtr OverlayDisplayFunc -> IO ())
-> FunPtr OverlayDisplayFunc -> IO ()
# NOINLINE ptr_glutOverlayDisplayFunc #
ptr_glutOverlayDisplayFunc :: FunPtr a
ptr_glutOverlayDisplayFunc = unsafePerformIO $ getAPIEntry "glutOverlayDisplayFunc"
glutPassiveMotionFunc :: MonadIO m => FunPtr PassiveMotionFunc -> m ()
glutPassiveMotionFunc v1 = liftIO $ dyn_glutPassiveMotionFunc ptr_glutPassiveMotionFunc v1
foreign import CALLCONV "dynamic" dyn_glutPassiveMotionFunc
:: FunPtr (FunPtr PassiveMotionFunc -> IO ())
-> FunPtr PassiveMotionFunc -> IO ()
# NOINLINE ptr_glutPassiveMotionFunc #
ptr_glutPassiveMotionFunc :: FunPtr a
ptr_glutPassiveMotionFunc = unsafePerformIO $ getAPIEntry "glutPassiveMotionFunc"
glutPopWindow :: MonadIO m => m ()
glutPopWindow = liftIO $ dyn_glutPopWindow ptr_glutPopWindow
foreign import CALLCONV "dynamic" dyn_glutPopWindow
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutPopWindow #
ptr_glutPopWindow :: FunPtr a
ptr_glutPopWindow = unsafePerformIO $ getAPIEntry "glutPopWindow"
glutPositionFunc :: MonadIO m => FunPtr PositionFunc -> m ()
glutPositionFunc v1 = liftIO $ dyn_glutPositionFunc ptr_glutPositionFunc v1
foreign import CALLCONV "dynamic" dyn_glutPositionFunc
:: FunPtr (FunPtr PositionFunc -> IO ())
-> FunPtr PositionFunc -> IO ()
# NOINLINE ptr_glutPositionFunc #
ptr_glutPositionFunc :: FunPtr a
ptr_glutPositionFunc = unsafePerformIO $ getAPIEntry "glutPositionFunc"
glutPositionWindow :: MonadIO m => CInt -> CInt -> m ()
glutPositionWindow v1 v2 = liftIO $ dyn_glutPositionWindow ptr_glutPositionWindow v1 v2
foreign import CALLCONV "dynamic" dyn_glutPositionWindow
:: FunPtr (CInt -> CInt -> IO ())
-> CInt -> CInt -> IO ()
# NOINLINE ptr_glutPositionWindow #
ptr_glutPositionWindow :: FunPtr a
ptr_glutPositionWindow = unsafePerformIO $ getAPIEntry "glutPositionWindow"
glutPostOverlayRedisplay :: MonadIO m => m ()
glutPostOverlayRedisplay = liftIO $ dyn_glutPostOverlayRedisplay ptr_glutPostOverlayRedisplay
foreign import CALLCONV "dynamic" dyn_glutPostOverlayRedisplay
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutPostOverlayRedisplay #
ptr_glutPostOverlayRedisplay :: FunPtr a
ptr_glutPostOverlayRedisplay = unsafePerformIO $ getAPIEntry "glutPostOverlayRedisplay"
glutPostRedisplay :: MonadIO m => m ()
glutPostRedisplay = liftIO $ dyn_glutPostRedisplay ptr_glutPostRedisplay
foreign import CALLCONV "dynamic" dyn_glutPostRedisplay
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutPostRedisplay #
ptr_glutPostRedisplay :: FunPtr a
ptr_glutPostRedisplay = unsafePerformIO $ getAPIEntry "glutPostRedisplay"
glutPostWindowOverlayRedisplay :: MonadIO m => CInt -> m ()
glutPostWindowOverlayRedisplay v1 = liftIO $ dyn_glutPostWindowOverlayRedisplay ptr_glutPostWindowOverlayRedisplay v1
foreign import CALLCONV "dynamic" dyn_glutPostWindowOverlayRedisplay
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutPostWindowOverlayRedisplay #
ptr_glutPostWindowOverlayRedisplay :: FunPtr a
ptr_glutPostWindowOverlayRedisplay = unsafePerformIO $ getAPIEntry "glutPostWindowOverlayRedisplay"
glutPostWindowRedisplay :: MonadIO m => CInt -> m ()
glutPostWindowRedisplay v1 = liftIO $ dyn_glutPostWindowRedisplay ptr_glutPostWindowRedisplay v1
foreign import CALLCONV "dynamic" dyn_glutPostWindowRedisplay
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutPostWindowRedisplay #
ptr_glutPostWindowRedisplay :: FunPtr a
ptr_glutPostWindowRedisplay = unsafePerformIO $ getAPIEntry "glutPostWindowRedisplay"
glutPushWindow :: MonadIO m => m ()
glutPushWindow = liftIO $ dyn_glutPushWindow ptr_glutPushWindow
foreign import CALLCONV "dynamic" dyn_glutPushWindow
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutPushWindow #
ptr_glutPushWindow :: FunPtr a
ptr_glutPushWindow = unsafePerformIO $ getAPIEntry "glutPushWindow"
glutRemoveMenuItem :: MonadIO m => CInt -> m ()
glutRemoveMenuItem v1 = liftIO $ dyn_glutRemoveMenuItem ptr_glutRemoveMenuItem v1
foreign import CALLCONV "dynamic" dyn_glutRemoveMenuItem
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutRemoveMenuItem #
ptr_glutRemoveMenuItem :: FunPtr a
ptr_glutRemoveMenuItem = unsafePerformIO $ getAPIEntry "glutRemoveMenuItem"
glutRemoveOverlay :: MonadIO m => m ()
glutRemoveOverlay = liftIO $ dyn_glutRemoveOverlay ptr_glutRemoveOverlay
foreign import CALLCONV "dynamic" dyn_glutRemoveOverlay
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutRemoveOverlay #
ptr_glutRemoveOverlay :: FunPtr a
ptr_glutRemoveOverlay = unsafePerformIO $ getAPIEntry "glutRemoveOverlay"
glutReportErrors :: MonadIO m => m ()
glutReportErrors = liftIO $ dyn_glutReportErrors ptr_glutReportErrors
foreign import CALLCONV "dynamic" dyn_glutReportErrors
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutReportErrors #
ptr_glutReportErrors :: FunPtr a
ptr_glutReportErrors = unsafePerformIO $ getAPIEntry "glutReportErrors"
glutReshapeFunc :: MonadIO m => FunPtr ReshapeFunc -> m ()
glutReshapeFunc v1 = liftIO $ dyn_glutReshapeFunc ptr_glutReshapeFunc v1
foreign import CALLCONV "dynamic" dyn_glutReshapeFunc
:: FunPtr (FunPtr ReshapeFunc -> IO ())
-> FunPtr ReshapeFunc -> IO ()
# NOINLINE ptr_glutReshapeFunc #
ptr_glutReshapeFunc :: FunPtr a
ptr_glutReshapeFunc = unsafePerformIO $ getAPIEntry "glutReshapeFunc"
glutReshapeWindow :: MonadIO m => CInt -> CInt -> m ()
glutReshapeWindow v1 v2 = liftIO $ dyn_glutReshapeWindow ptr_glutReshapeWindow v1 v2
foreign import CALLCONV "dynamic" dyn_glutReshapeWindow
:: FunPtr (CInt -> CInt -> IO ())
-> CInt -> CInt -> IO ()
# NOINLINE ptr_glutReshapeWindow #
ptr_glutReshapeWindow :: FunPtr a
ptr_glutReshapeWindow = unsafePerformIO $ getAPIEntry "glutReshapeWindow"
glutSetColor :: MonadIO m => CInt -> GLfloat -> GLfloat -> GLfloat -> m ()
glutSetColor v1 v2 v3 v4 = liftIO $ dyn_glutSetColor ptr_glutSetColor v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutSetColor
:: FunPtr (CInt -> GLfloat -> GLfloat -> GLfloat -> IO ())
-> CInt -> GLfloat -> GLfloat -> GLfloat -> IO ()
# NOINLINE ptr_glutSetColor #
ptr_glutSetColor :: FunPtr a
ptr_glutSetColor = unsafePerformIO $ getAPIEntry "glutSetColor"
glutSetCursor :: MonadIO m => CInt -> m ()
glutSetCursor v1 = liftIO $ dyn_glutSetCursor ptr_glutSetCursor v1
foreign import CALLCONV "dynamic" dyn_glutSetCursor
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutSetCursor #
ptr_glutSetCursor :: FunPtr a
ptr_glutSetCursor = unsafePerformIO $ getAPIEntry "glutSetCursor"
glutSetIconTitle :: MonadIO m => Ptr CChar -> m ()
glutSetIconTitle v1 = liftIO $ dyn_glutSetIconTitle ptr_glutSetIconTitle v1
foreign import CALLCONV "dynamic" dyn_glutSetIconTitle
:: FunPtr (Ptr CChar -> IO ())
-> Ptr CChar -> IO ()
# NOINLINE ptr_glutSetIconTitle #
ptr_glutSetIconTitle :: FunPtr a
ptr_glutSetIconTitle = unsafePerformIO $ getAPIEntry "glutSetIconTitle"
glutSetKeyRepeat :: MonadIO m => CInt -> m ()
glutSetKeyRepeat v1 = liftIO $ dyn_glutSetKeyRepeat ptr_glutSetKeyRepeat v1
foreign import CALLCONV "dynamic" dyn_glutSetKeyRepeat
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutSetKeyRepeat #
ptr_glutSetKeyRepeat :: FunPtr a
ptr_glutSetKeyRepeat = unsafePerformIO $ getAPIEntry "glutSetKeyRepeat"
glutSetMenu :: MonadIO m => CInt -> m ()
glutSetMenu v1 = liftIO $ dyn_glutSetMenu ptr_glutSetMenu v1
foreign import CALLCONV "dynamic" dyn_glutSetMenu
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutSetMenu #
ptr_glutSetMenu :: FunPtr a
ptr_glutSetMenu = unsafePerformIO $ getAPIEntry "glutSetMenu"
glutSetMenuData :: MonadIO m => Ptr a -> m ()
glutSetMenuData v1 = liftIO $ dyn_glutSetMenuData ptr_glutSetMenuData v1
foreign import CALLCONV "dynamic" dyn_glutSetMenuData
:: FunPtr (Ptr a -> IO ())
-> Ptr a -> IO ()
# NOINLINE ptr_glutSetMenuData #
ptr_glutSetMenuData :: FunPtr a
ptr_glutSetMenuData = unsafePerformIO $ getAPIEntry "glutSetMenuData"
glutSetMenuFont :: MonadIO m => CInt -> Ptr a -> m ()
glutSetMenuFont v1 v2 = liftIO $ dyn_glutSetMenuFont ptr_glutSetMenuFont v1 v2
foreign import CALLCONV "dynamic" dyn_glutSetMenuFont
:: FunPtr (CInt -> Ptr a -> IO ())
-> CInt -> Ptr a -> IO ()
# NOINLINE ptr_glutSetMenuFont #
ptr_glutSetMenuFont :: FunPtr a
ptr_glutSetMenuFont = unsafePerformIO $ getAPIEntry "glutSetMenuFont"
glutSetOption :: MonadIO m => GLenum -> CInt -> m ()
glutSetOption v1 v2 = liftIO $ dyn_glutSetOption ptr_glutSetOption v1 v2
foreign import CALLCONV "dynamic" dyn_glutSetOption
:: FunPtr (GLenum -> CInt -> IO ())
-> GLenum -> CInt -> IO ()
# NOINLINE ptr_glutSetOption #
ptr_glutSetOption :: FunPtr a
ptr_glutSetOption = unsafePerformIO $ getAPIEntry "glutSetOption"
glutSetVertexAttribCoord3 :: MonadIO m => GLint -> m ()
glutSetVertexAttribCoord3 v1 = liftIO $ dyn_glutSetVertexAttribCoord3 ptr_glutSetVertexAttribCoord3 v1
foreign import CALLCONV "dynamic" dyn_glutSetVertexAttribCoord3
:: FunPtr (GLint -> IO ())
-> GLint -> IO ()
# NOINLINE ptr_glutSetVertexAttribCoord3 #
ptr_glutSetVertexAttribCoord3 :: FunPtr a
ptr_glutSetVertexAttribCoord3 = unsafePerformIO $ getAPIEntry "glutSetVertexAttribCoord3"
glutSetVertexAttribNormal :: MonadIO m => GLint -> m ()
glutSetVertexAttribNormal v1 = liftIO $ dyn_glutSetVertexAttribNormal ptr_glutSetVertexAttribNormal v1
foreign import CALLCONV "dynamic" dyn_glutSetVertexAttribNormal
:: FunPtr (GLint -> IO ())
-> GLint -> IO ()
# NOINLINE ptr_glutSetVertexAttribNormal #
ptr_glutSetVertexAttribNormal :: FunPtr a
ptr_glutSetVertexAttribNormal = unsafePerformIO $ getAPIEntry "glutSetVertexAttribNormal"
glutSetVertexAttribTexCoord2 :: MonadIO m => GLint -> m ()
glutSetVertexAttribTexCoord2 v1 = liftIO $ dyn_glutSetVertexAttribTexCoord2 ptr_glutSetVertexAttribTexCoord2 v1
foreign import CALLCONV "dynamic" dyn_glutSetVertexAttribTexCoord2
:: FunPtr (GLint -> IO ())
-> GLint -> IO ()
# NOINLINE ptr_glutSetVertexAttribTexCoord2 #
ptr_glutSetVertexAttribTexCoord2 :: FunPtr a
ptr_glutSetVertexAttribTexCoord2 = unsafePerformIO $ getAPIEntry "glutSetVertexAttribTexCoord2"
glutSetWindow :: MonadIO m => CInt -> m ()
glutSetWindow v1 = liftIO $ dyn_glutSetWindow ptr_glutSetWindow v1
foreign import CALLCONV "dynamic" dyn_glutSetWindow
:: FunPtr (CInt -> IO ())
-> CInt -> IO ()
# NOINLINE ptr_glutSetWindow #
ptr_glutSetWindow :: FunPtr a
ptr_glutSetWindow = unsafePerformIO $ getAPIEntry "glutSetWindow"
glutSetWindowData :: MonadIO m => Ptr a -> m ()
glutSetWindowData v1 = liftIO $ dyn_glutSetWindowData ptr_glutSetWindowData v1
foreign import CALLCONV "dynamic" dyn_glutSetWindowData
:: FunPtr (Ptr a -> IO ())
-> Ptr a -> IO ()
# NOINLINE ptr_glutSetWindowData #
ptr_glutSetWindowData :: FunPtr a
ptr_glutSetWindowData = unsafePerformIO $ getAPIEntry "glutSetWindowData"
glutSetWindowTitle :: MonadIO m => Ptr CChar -> m ()
glutSetWindowTitle v1 = liftIO $ dyn_glutSetWindowTitle ptr_glutSetWindowTitle v1
foreign import CALLCONV "dynamic" dyn_glutSetWindowTitle
:: FunPtr (Ptr CChar -> IO ())
-> Ptr CChar -> IO ()
# NOINLINE ptr_glutSetWindowTitle #
ptr_glutSetWindowTitle :: FunPtr a
ptr_glutSetWindowTitle = unsafePerformIO $ getAPIEntry "glutSetWindowTitle"
glutSetupVideoResizing :: MonadIO m => m ()
glutSetupVideoResizing = liftIO $ dyn_glutSetupVideoResizing ptr_glutSetupVideoResizing
foreign import CALLCONV "dynamic" dyn_glutSetupVideoResizing
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutSetupVideoResizing #
ptr_glutSetupVideoResizing :: FunPtr a
ptr_glutSetupVideoResizing = unsafePerformIO $ getAPIEntry "glutSetupVideoResizing"
glutShowOverlay :: MonadIO m => m ()
glutShowOverlay = liftIO $ dyn_glutShowOverlay ptr_glutShowOverlay
foreign import CALLCONV "dynamic" dyn_glutShowOverlay
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutShowOverlay #
ptr_glutShowOverlay :: FunPtr a
ptr_glutShowOverlay = unsafePerformIO $ getAPIEntry "glutShowOverlay"
glutShowWindow :: MonadIO m => m ()
glutShowWindow = liftIO $ dyn_glutShowWindow ptr_glutShowWindow
foreign import CALLCONV "dynamic" dyn_glutShowWindow
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutShowWindow #
ptr_glutShowWindow :: FunPtr a
ptr_glutShowWindow = unsafePerformIO $ getAPIEntry "glutShowWindow"
glutSolidCone :: MonadIO m => GLdouble -> GLdouble -> GLint -> GLint -> m ()
glutSolidCone v1 v2 v3 v4 = liftIO $ dyn_glutSolidCone ptr_glutSolidCone v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutSolidCone
:: FunPtr (GLdouble -> GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLdouble -> GLint -> GLint -> IO ()
# NOINLINE ptr_glutSolidCone #
ptr_glutSolidCone :: FunPtr a
ptr_glutSolidCone = unsafePerformIO $ getAPIEntry "glutSolidCone"
glutSolidCube :: MonadIO m => GLdouble -> m ()
glutSolidCube v1 = liftIO $ dyn_glutSolidCube ptr_glutSolidCube v1
foreign import CALLCONV "dynamic" dyn_glutSolidCube
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutSolidCube #
ptr_glutSolidCube :: FunPtr a
ptr_glutSolidCube = unsafePerformIO $ getAPIEntry "glutSolidCube"
glutSolidCylinder :: MonadIO m => GLdouble -> GLdouble -> GLint -> GLint -> m ()
glutSolidCylinder v1 v2 v3 v4 = liftIO $ dyn_glutSolidCylinder ptr_glutSolidCylinder v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutSolidCylinder
:: FunPtr (GLdouble -> GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLdouble -> GLint -> GLint -> IO ()
# NOINLINE ptr_glutSolidCylinder #
ptr_glutSolidCylinder :: FunPtr a
ptr_glutSolidCylinder = unsafePerformIO $ getAPIEntry "glutSolidCylinder"
glutSolidDodecahedron :: MonadIO m => m ()
glutSolidDodecahedron = liftIO $ dyn_glutSolidDodecahedron ptr_glutSolidDodecahedron
foreign import CALLCONV "dynamic" dyn_glutSolidDodecahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutSolidDodecahedron #
ptr_glutSolidDodecahedron :: FunPtr a
ptr_glutSolidDodecahedron = unsafePerformIO $ getAPIEntry "glutSolidDodecahedron"
glutSolidIcosahedron :: MonadIO m => m ()
glutSolidIcosahedron = liftIO $ dyn_glutSolidIcosahedron ptr_glutSolidIcosahedron
foreign import CALLCONV "dynamic" dyn_glutSolidIcosahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutSolidIcosahedron #
ptr_glutSolidIcosahedron :: FunPtr a
ptr_glutSolidIcosahedron = unsafePerformIO $ getAPIEntry "glutSolidIcosahedron"
glutSolidOctahedron :: MonadIO m => m ()
glutSolidOctahedron = liftIO $ dyn_glutSolidOctahedron ptr_glutSolidOctahedron
foreign import CALLCONV "dynamic" dyn_glutSolidOctahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutSolidOctahedron #
ptr_glutSolidOctahedron :: FunPtr a
ptr_glutSolidOctahedron = unsafePerformIO $ getAPIEntry "glutSolidOctahedron"
glutSolidRhombicDodecahedron :: MonadIO m => m ()
glutSolidRhombicDodecahedron = liftIO $ dyn_glutSolidRhombicDodecahedron ptr_glutSolidRhombicDodecahedron
foreign import CALLCONV "dynamic" dyn_glutSolidRhombicDodecahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutSolidRhombicDodecahedron #
ptr_glutSolidRhombicDodecahedron :: FunPtr a
ptr_glutSolidRhombicDodecahedron = unsafePerformIO $ getAPIEntry "glutSolidRhombicDodecahedron"
glutSolidSierpinskiSponge :: MonadIO m => CInt -> Ptr GLdouble -> GLdouble -> m ()
glutSolidSierpinskiSponge v1 v2 v3 = liftIO $ dyn_glutSolidSierpinskiSponge ptr_glutSolidSierpinskiSponge v1 v2 v3
foreign import CALLCONV "dynamic" dyn_glutSolidSierpinskiSponge
:: FunPtr (CInt -> Ptr GLdouble -> GLdouble -> IO ())
-> CInt -> Ptr GLdouble -> GLdouble -> IO ()
# NOINLINE ptr_glutSolidSierpinskiSponge #
ptr_glutSolidSierpinskiSponge :: FunPtr a
ptr_glutSolidSierpinskiSponge = unsafePerformIO $ getAPIEntry "glutSolidSierpinskiSponge"
glutSolidSphere :: MonadIO m => GLdouble -> GLint -> GLint -> m ()
glutSolidSphere v1 v2 v3 = liftIO $ dyn_glutSolidSphere ptr_glutSolidSphere v1 v2 v3
foreign import CALLCONV "dynamic" dyn_glutSolidSphere
:: FunPtr (GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLint -> GLint -> IO ()
# NOINLINE ptr_glutSolidSphere #
ptr_glutSolidSphere :: FunPtr a
ptr_glutSolidSphere = unsafePerformIO $ getAPIEntry "glutSolidSphere"
glutSolidTeacup :: MonadIO m => GLdouble -> m ()
glutSolidTeacup v1 = liftIO $ dyn_glutSolidTeacup ptr_glutSolidTeacup v1
foreign import CALLCONV "dynamic" dyn_glutSolidTeacup
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutSolidTeacup #
ptr_glutSolidTeacup :: FunPtr a
ptr_glutSolidTeacup = unsafePerformIO $ getAPIEntry "glutSolidTeacup"
glutSolidTeapot :: MonadIO m => GLdouble -> m ()
glutSolidTeapot v1 = liftIO $ dyn_glutSolidTeapot ptr_glutSolidTeapot v1
foreign import CALLCONV "dynamic" dyn_glutSolidTeapot
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutSolidTeapot #
ptr_glutSolidTeapot :: FunPtr a
ptr_glutSolidTeapot = unsafePerformIO $ getAPIEntry "glutSolidTeapot"
glutSolidTeaspoon :: MonadIO m => GLdouble -> m ()
glutSolidTeaspoon v1 = liftIO $ dyn_glutSolidTeaspoon ptr_glutSolidTeaspoon v1
foreign import CALLCONV "dynamic" dyn_glutSolidTeaspoon
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutSolidTeaspoon #
ptr_glutSolidTeaspoon :: FunPtr a
ptr_glutSolidTeaspoon = unsafePerformIO $ getAPIEntry "glutSolidTeaspoon"
glutSolidTetrahedron :: MonadIO m => m ()
glutSolidTetrahedron = liftIO $ dyn_glutSolidTetrahedron ptr_glutSolidTetrahedron
foreign import CALLCONV "dynamic" dyn_glutSolidTetrahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutSolidTetrahedron #
ptr_glutSolidTetrahedron :: FunPtr a
ptr_glutSolidTetrahedron = unsafePerformIO $ getAPIEntry "glutSolidTetrahedron"
glutSolidTorus :: MonadIO m => GLdouble -> GLdouble -> GLint -> GLint -> m ()
glutSolidTorus v1 v2 v3 v4 = liftIO $ dyn_glutSolidTorus ptr_glutSolidTorus v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutSolidTorus
:: FunPtr (GLdouble -> GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLdouble -> GLint -> GLint -> IO ()
# NOINLINE ptr_glutSolidTorus #
ptr_glutSolidTorus :: FunPtr a
ptr_glutSolidTorus = unsafePerformIO $ getAPIEntry "glutSolidTorus"
glutSpaceballButtonFunc :: MonadIO m => FunPtr SpaceballButtonFunc -> m ()
glutSpaceballButtonFunc v1 = liftIO $ dyn_glutSpaceballButtonFunc ptr_glutSpaceballButtonFunc v1
foreign import CALLCONV "dynamic" dyn_glutSpaceballButtonFunc
:: FunPtr (FunPtr SpaceballButtonFunc -> IO ())
-> FunPtr SpaceballButtonFunc -> IO ()
# NOINLINE ptr_glutSpaceballButtonFunc #
ptr_glutSpaceballButtonFunc :: FunPtr a
ptr_glutSpaceballButtonFunc = unsafePerformIO $ getAPIEntry "glutSpaceballButtonFunc"
glutSpaceballMotionFunc :: MonadIO m => FunPtr SpaceballMotionFunc -> m ()
glutSpaceballMotionFunc v1 = liftIO $ dyn_glutSpaceballMotionFunc ptr_glutSpaceballMotionFunc v1
foreign import CALLCONV "dynamic" dyn_glutSpaceballMotionFunc
:: FunPtr (FunPtr SpaceballMotionFunc -> IO ())
-> FunPtr SpaceballMotionFunc -> IO ()
# NOINLINE ptr_glutSpaceballMotionFunc #
ptr_glutSpaceballMotionFunc :: FunPtr a
ptr_glutSpaceballMotionFunc = unsafePerformIO $ getAPIEntry "glutSpaceballMotionFunc"
glutSpaceballRotateFunc :: MonadIO m => FunPtr SpaceballRotateFunc -> m ()
glutSpaceballRotateFunc v1 = liftIO $ dyn_glutSpaceballRotateFunc ptr_glutSpaceballRotateFunc v1
foreign import CALLCONV "dynamic" dyn_glutSpaceballRotateFunc
:: FunPtr (FunPtr SpaceballRotateFunc -> IO ())
-> FunPtr SpaceballRotateFunc -> IO ()
# NOINLINE ptr_glutSpaceballRotateFunc #
ptr_glutSpaceballRotateFunc :: FunPtr a
ptr_glutSpaceballRotateFunc = unsafePerformIO $ getAPIEntry "glutSpaceballRotateFunc"
glutSpecialFunc :: MonadIO m => FunPtr SpecialFunc -> m ()
glutSpecialFunc v1 = liftIO $ dyn_glutSpecialFunc ptr_glutSpecialFunc v1
foreign import CALLCONV "dynamic" dyn_glutSpecialFunc
:: FunPtr (FunPtr SpecialFunc -> IO ())
-> FunPtr SpecialFunc -> IO ()
# NOINLINE ptr_glutSpecialFunc #
ptr_glutSpecialFunc :: FunPtr a
ptr_glutSpecialFunc = unsafePerformIO $ getAPIEntry "glutSpecialFunc"
glutSpecialUpFunc :: MonadIO m => FunPtr SpecialUpFunc -> m ()
glutSpecialUpFunc v1 = liftIO $ dyn_glutSpecialUpFunc ptr_glutSpecialUpFunc v1
foreign import CALLCONV "dynamic" dyn_glutSpecialUpFunc
:: FunPtr (FunPtr SpecialUpFunc -> IO ())
-> FunPtr SpecialUpFunc -> IO ()
# NOINLINE ptr_glutSpecialUpFunc #
ptr_glutSpecialUpFunc :: FunPtr a
ptr_glutSpecialUpFunc = unsafePerformIO $ getAPIEntry "glutSpecialUpFunc"
glutStopVideoResizing :: MonadIO m => m ()
glutStopVideoResizing = liftIO $ dyn_glutStopVideoResizing ptr_glutStopVideoResizing
foreign import CALLCONV "dynamic" dyn_glutStopVideoResizing
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutStopVideoResizing #
ptr_glutStopVideoResizing :: FunPtr a
ptr_glutStopVideoResizing = unsafePerformIO $ getAPIEntry "glutStopVideoResizing"
glutStrokeCharacter :: MonadIO m => Ptr a -> CInt -> m ()
glutStrokeCharacter v1 v2 = liftIO $ dyn_glutStrokeCharacter ptr_glutStrokeCharacter v1 v2
foreign import CALLCONV "dynamic" dyn_glutStrokeCharacter
:: FunPtr (Ptr a -> CInt -> IO ())
-> Ptr a -> CInt -> IO ()
# NOINLINE ptr_glutStrokeCharacter #
ptr_glutStrokeCharacter :: FunPtr a
ptr_glutStrokeCharacter = unsafePerformIO $ getAPIEntry "glutStrokeCharacter"
glutStrokeHeight :: MonadIO m => Ptr a -> m GLfloat
glutStrokeHeight v1 = liftIO $ dyn_glutStrokeHeight ptr_glutStrokeHeight v1
foreign import CALLCONV "dynamic" dyn_glutStrokeHeight
:: FunPtr (Ptr a -> IO GLfloat)
-> Ptr a -> IO GLfloat
# NOINLINE ptr_glutStrokeHeight #
ptr_glutStrokeHeight :: FunPtr a
ptr_glutStrokeHeight = unsafePerformIO $ getAPIEntry "glutStrokeHeight"
glutStrokeLength :: MonadIO m => Ptr a -> Ptr CUChar -> m CInt
glutStrokeLength v1 v2 = liftIO $ dyn_glutStrokeLength ptr_glutStrokeLength v1 v2
foreign import CALLCONV "dynamic" dyn_glutStrokeLength
:: FunPtr (Ptr a -> Ptr CUChar -> IO CInt)
-> Ptr a -> Ptr CUChar -> IO CInt
# NOINLINE ptr_glutStrokeLength #
ptr_glutStrokeLength :: FunPtr a
ptr_glutStrokeLength = unsafePerformIO $ getAPIEntry "glutStrokeLength"
glutStrokeString :: MonadIO m => Ptr a -> Ptr CUChar -> m ()
glutStrokeString v1 v2 = liftIO $ dyn_glutStrokeString ptr_glutStrokeString v1 v2
foreign import CALLCONV "dynamic" dyn_glutStrokeString
:: FunPtr (Ptr a -> Ptr CUChar -> IO ())
-> Ptr a -> Ptr CUChar -> IO ()
# NOINLINE ptr_glutStrokeString #
ptr_glutStrokeString :: FunPtr a
ptr_glutStrokeString = unsafePerformIO $ getAPIEntry "glutStrokeString"
glutStrokeWidth :: MonadIO m => Ptr a -> CInt -> m CInt
glutStrokeWidth v1 v2 = liftIO $ dyn_glutStrokeWidth ptr_glutStrokeWidth v1 v2
foreign import CALLCONV "dynamic" dyn_glutStrokeWidth
:: FunPtr (Ptr a -> CInt -> IO CInt)
-> Ptr a -> CInt -> IO CInt
# NOINLINE ptr_glutStrokeWidth #
ptr_glutStrokeWidth :: FunPtr a
ptr_glutStrokeWidth = unsafePerformIO $ getAPIEntry "glutStrokeWidth"
glutSwapBuffers :: MonadIO m => m ()
glutSwapBuffers = liftIO $ dyn_glutSwapBuffers ptr_glutSwapBuffers
foreign import CALLCONV "dynamic" dyn_glutSwapBuffers
:: FunPtr (IO ())
-> IO ()
ptr_glutSwapBuffers :: FunPtr a
ptr_glutSwapBuffers = unsafePerformIO $ getAPIEntry "glutSwapBuffers"
glutTabletButtonFunc :: MonadIO m => FunPtr TabletButtonFunc -> m ()
glutTabletButtonFunc v1 = liftIO $ dyn_glutTabletButtonFunc ptr_glutTabletButtonFunc v1
foreign import CALLCONV "dynamic" dyn_glutTabletButtonFunc
:: FunPtr (FunPtr TabletButtonFunc -> IO ())
-> FunPtr TabletButtonFunc -> IO ()
# NOINLINE ptr_glutTabletButtonFunc #
ptr_glutTabletButtonFunc :: FunPtr a
ptr_glutTabletButtonFunc = unsafePerformIO $ getAPIEntry "glutTabletButtonFunc"
glutTabletMotionFunc :: MonadIO m => FunPtr TabletMotionFunc -> m ()
glutTabletMotionFunc v1 = liftIO $ dyn_glutTabletMotionFunc ptr_glutTabletMotionFunc v1
foreign import CALLCONV "dynamic" dyn_glutTabletMotionFunc
:: FunPtr (FunPtr TabletMotionFunc -> IO ())
-> FunPtr TabletMotionFunc -> IO ()
# NOINLINE ptr_glutTabletMotionFunc #
ptr_glutTabletMotionFunc :: FunPtr a
ptr_glutTabletMotionFunc = unsafePerformIO $ getAPIEntry "glutTabletMotionFunc"
glutTimerFunc :: MonadIO m => CUInt -> FunPtr TimerFunc -> CInt -> m ()
glutTimerFunc v1 v2 v3 = liftIO $ dyn_glutTimerFunc ptr_glutTimerFunc v1 v2 v3
foreign import CALLCONV "dynamic" dyn_glutTimerFunc
:: FunPtr (CUInt -> FunPtr TimerFunc -> CInt -> IO ())
-> CUInt -> FunPtr TimerFunc -> CInt -> IO ()
# NOINLINE ptr_glutTimerFunc #
ptr_glutTimerFunc :: FunPtr a
ptr_glutTimerFunc = unsafePerformIO $ getAPIEntry "glutTimerFunc"
glutUseLayer :: MonadIO m => GLenum -> m ()
glutUseLayer v1 = liftIO $ dyn_glutUseLayer ptr_glutUseLayer v1
foreign import CALLCONV "dynamic" dyn_glutUseLayer
:: FunPtr (GLenum -> IO ())
-> GLenum -> IO ()
# NOINLINE ptr_glutUseLayer #
ptr_glutUseLayer :: FunPtr a
ptr_glutUseLayer = unsafePerformIO $ getAPIEntry "glutUseLayer"
glutVideoPan :: MonadIO m => CInt -> CInt -> CInt -> CInt -> m ()
glutVideoPan v1 v2 v3 v4 = liftIO $ dyn_glutVideoPan ptr_glutVideoPan v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutVideoPan
:: FunPtr (CInt -> CInt -> CInt -> CInt -> IO ())
-> CInt -> CInt -> CInt -> CInt -> IO ()
# NOINLINE ptr_glutVideoPan #
ptr_glutVideoPan :: FunPtr a
ptr_glutVideoPan = unsafePerformIO $ getAPIEntry "glutVideoPan"
glutVideoResize :: MonadIO m => CInt -> CInt -> CInt -> CInt -> m ()
glutVideoResize v1 v2 v3 v4 = liftIO $ dyn_glutVideoResize ptr_glutVideoResize v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutVideoResize
:: FunPtr (CInt -> CInt -> CInt -> CInt -> IO ())
-> CInt -> CInt -> CInt -> CInt -> IO ()
# NOINLINE ptr_glutVideoResize #
ptr_glutVideoResize :: FunPtr a
ptr_glutVideoResize = unsafePerformIO $ getAPIEntry "glutVideoResize"
glutVideoResizeGet :: MonadIO m => GLenum -> m CInt
glutVideoResizeGet v1 = liftIO $ dyn_glutVideoResizeGet ptr_glutVideoResizeGet v1
foreign import CALLCONV "dynamic" dyn_glutVideoResizeGet
:: FunPtr (GLenum -> IO CInt)
-> GLenum -> IO CInt
# NOINLINE ptr_glutVideoResizeGet #
ptr_glutVideoResizeGet :: FunPtr a
ptr_glutVideoResizeGet = unsafePerformIO $ getAPIEntry "glutVideoResizeGet"
glutVisibilityFunc :: MonadIO m => FunPtr VisibilityFunc -> m ()
glutVisibilityFunc v1 = liftIO $ dyn_glutVisibilityFunc ptr_glutVisibilityFunc v1
foreign import CALLCONV "dynamic" dyn_glutVisibilityFunc
:: FunPtr (FunPtr VisibilityFunc -> IO ())
-> FunPtr VisibilityFunc -> IO ()
# NOINLINE ptr_glutVisibilityFunc #
ptr_glutVisibilityFunc :: FunPtr a
ptr_glutVisibilityFunc = unsafePerformIO $ getAPIEntry "glutVisibilityFunc"
glutWMCloseFunc :: MonadIO m => FunPtr WMCloseFunc -> m ()
glutWMCloseFunc v1 = liftIO $ dyn_glutWMCloseFunc ptr_glutWMCloseFunc v1
foreign import CALLCONV "dynamic" dyn_glutWMCloseFunc
:: FunPtr (FunPtr WMCloseFunc -> IO ())
-> FunPtr WMCloseFunc -> IO ()
# NOINLINE ptr_glutWMCloseFunc #
ptr_glutWMCloseFunc :: FunPtr a
ptr_glutWMCloseFunc = unsafePerformIO $ getAPIEntry "glutWMCloseFunc"
glutWarpPointer :: MonadIO m => CInt -> CInt -> m ()
glutWarpPointer v1 v2 = liftIO $ dyn_glutWarpPointer ptr_glutWarpPointer v1 v2
foreign import CALLCONV "dynamic" dyn_glutWarpPointer
:: FunPtr (CInt -> CInt -> IO ())
-> CInt -> CInt -> IO ()
# NOINLINE ptr_glutWarpPointer #
ptr_glutWarpPointer :: FunPtr a
ptr_glutWarpPointer = unsafePerformIO $ getAPIEntry "glutWarpPointer"
glutWindowStatusFunc :: MonadIO m => FunPtr WindowStatusFunc -> m ()
glutWindowStatusFunc v1 = liftIO $ dyn_glutWindowStatusFunc ptr_glutWindowStatusFunc v1
foreign import CALLCONV "dynamic" dyn_glutWindowStatusFunc
:: FunPtr (FunPtr WindowStatusFunc -> IO ())
-> FunPtr WindowStatusFunc -> IO ()
# NOINLINE ptr_glutWindowStatusFunc #
ptr_glutWindowStatusFunc :: FunPtr a
ptr_glutWindowStatusFunc = unsafePerformIO $ getAPIEntry "glutWindowStatusFunc"
glutWireCone :: MonadIO m => GLdouble -> GLdouble -> GLint -> GLint -> m ()
glutWireCone v1 v2 v3 v4 = liftIO $ dyn_glutWireCone ptr_glutWireCone v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutWireCone
:: FunPtr (GLdouble -> GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLdouble -> GLint -> GLint -> IO ()
# NOINLINE ptr_glutWireCone #
ptr_glutWireCone :: FunPtr a
ptr_glutWireCone = unsafePerformIO $ getAPIEntry "glutWireCone"
glutWireCube :: MonadIO m => GLdouble -> m ()
glutWireCube v1 = liftIO $ dyn_glutWireCube ptr_glutWireCube v1
foreign import CALLCONV "dynamic" dyn_glutWireCube
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutWireCube #
ptr_glutWireCube :: FunPtr a
ptr_glutWireCube = unsafePerformIO $ getAPIEntry "glutWireCube"
glutWireCylinder :: MonadIO m => GLdouble -> GLdouble -> GLint -> GLint -> m ()
glutWireCylinder v1 v2 v3 v4 = liftIO $ dyn_glutWireCylinder ptr_glutWireCylinder v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutWireCylinder
:: FunPtr (GLdouble -> GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLdouble -> GLint -> GLint -> IO ()
# NOINLINE ptr_glutWireCylinder #
ptr_glutWireCylinder :: FunPtr a
ptr_glutWireCylinder = unsafePerformIO $ getAPIEntry "glutWireCylinder"
glutWireDodecahedron :: MonadIO m => m ()
glutWireDodecahedron = liftIO $ dyn_glutWireDodecahedron ptr_glutWireDodecahedron
foreign import CALLCONV "dynamic" dyn_glutWireDodecahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutWireDodecahedron #
ptr_glutWireDodecahedron :: FunPtr a
ptr_glutWireDodecahedron = unsafePerformIO $ getAPIEntry "glutWireDodecahedron"
glutWireIcosahedron :: MonadIO m => m ()
glutWireIcosahedron = liftIO $ dyn_glutWireIcosahedron ptr_glutWireIcosahedron
foreign import CALLCONV "dynamic" dyn_glutWireIcosahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutWireIcosahedron #
ptr_glutWireIcosahedron :: FunPtr a
ptr_glutWireIcosahedron = unsafePerformIO $ getAPIEntry "glutWireIcosahedron"
glutWireOctahedron :: MonadIO m => m ()
glutWireOctahedron = liftIO $ dyn_glutWireOctahedron ptr_glutWireOctahedron
foreign import CALLCONV "dynamic" dyn_glutWireOctahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutWireOctahedron #
ptr_glutWireOctahedron :: FunPtr a
ptr_glutWireOctahedron = unsafePerformIO $ getAPIEntry "glutWireOctahedron"
glutWireRhombicDodecahedron :: MonadIO m => m ()
glutWireRhombicDodecahedron = liftIO $ dyn_glutWireRhombicDodecahedron ptr_glutWireRhombicDodecahedron
foreign import CALLCONV "dynamic" dyn_glutWireRhombicDodecahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutWireRhombicDodecahedron #
ptr_glutWireRhombicDodecahedron :: FunPtr a
ptr_glutWireRhombicDodecahedron = unsafePerformIO $ getAPIEntry "glutWireRhombicDodecahedron"
glutWireSierpinskiSponge :: MonadIO m => CInt -> Ptr GLdouble -> GLdouble -> m ()
glutWireSierpinskiSponge v1 v2 v3 = liftIO $ dyn_glutWireSierpinskiSponge ptr_glutWireSierpinskiSponge v1 v2 v3
foreign import CALLCONV "dynamic" dyn_glutWireSierpinskiSponge
:: FunPtr (CInt -> Ptr GLdouble -> GLdouble -> IO ())
-> CInt -> Ptr GLdouble -> GLdouble -> IO ()
# NOINLINE ptr_glutWireSierpinskiSponge #
ptr_glutWireSierpinskiSponge :: FunPtr a
ptr_glutWireSierpinskiSponge = unsafePerformIO $ getAPIEntry "glutWireSierpinskiSponge"
glutWireSphere :: MonadIO m => GLdouble -> GLint -> GLint -> m ()
glutWireSphere v1 v2 v3 = liftIO $ dyn_glutWireSphere ptr_glutWireSphere v1 v2 v3
foreign import CALLCONV "dynamic" dyn_glutWireSphere
:: FunPtr (GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLint -> GLint -> IO ()
ptr_glutWireSphere :: FunPtr a
ptr_glutWireSphere = unsafePerformIO $ getAPIEntry "glutWireSphere"
glutWireTeacup :: MonadIO m => GLdouble -> m ()
glutWireTeacup v1 = liftIO $ dyn_glutWireTeacup ptr_glutWireTeacup v1
foreign import CALLCONV "dynamic" dyn_glutWireTeacup
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutWireTeacup #
ptr_glutWireTeacup :: FunPtr a
ptr_glutWireTeacup = unsafePerformIO $ getAPIEntry "glutWireTeacup"
glutWireTeapot :: MonadIO m => GLdouble -> m ()
glutWireTeapot v1 = liftIO $ dyn_glutWireTeapot ptr_glutWireTeapot v1
foreign import CALLCONV "dynamic" dyn_glutWireTeapot
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutWireTeapot #
ptr_glutWireTeapot :: FunPtr a
ptr_glutWireTeapot = unsafePerformIO $ getAPIEntry "glutWireTeapot"
glutWireTeaspoon :: MonadIO m => GLdouble -> m ()
glutWireTeaspoon v1 = liftIO $ dyn_glutWireTeaspoon ptr_glutWireTeaspoon v1
foreign import CALLCONV "dynamic" dyn_glutWireTeaspoon
:: FunPtr (GLdouble -> IO ())
-> GLdouble -> IO ()
# NOINLINE ptr_glutWireTeaspoon #
ptr_glutWireTeaspoon :: FunPtr a
ptr_glutWireTeaspoon = unsafePerformIO $ getAPIEntry "glutWireTeaspoon"
glutWireTetrahedron :: MonadIO m => m ()
glutWireTetrahedron = liftIO $ dyn_glutWireTetrahedron ptr_glutWireTetrahedron
foreign import CALLCONV "dynamic" dyn_glutWireTetrahedron
:: FunPtr (IO ())
-> IO ()
# NOINLINE ptr_glutWireTetrahedron #
ptr_glutWireTetrahedron :: FunPtr a
ptr_glutWireTetrahedron = unsafePerformIO $ getAPIEntry "glutWireTetrahedron"
glutWireTorus :: MonadIO m => GLdouble -> GLdouble -> GLint -> GLint -> m ()
glutWireTorus v1 v2 v3 v4 = liftIO $ dyn_glutWireTorus ptr_glutWireTorus v1 v2 v3 v4
foreign import CALLCONV "dynamic" dyn_glutWireTorus
:: FunPtr (GLdouble -> GLdouble -> GLint -> GLint -> IO ())
-> GLdouble -> GLdouble -> GLint -> GLint -> IO ()
# NOINLINE ptr_glutWireTorus #
ptr_glutWireTorus :: FunPtr a
ptr_glutWireTorus = unsafePerformIO $ getAPIEntry "glutWireTorus"
|
1963ae437ae9e148355df998ebc99c20242e9fd2e89a812b4765a4689deaeab6 | bfontaine/grape | parsing.clj | (ns grape.impl.parsing
"Internal parsing utilities."
(:require [parcera.core :as parcera]
[grape.impl.models :as m]))
(defn parse-code
"Parse code. Options are passed to parcera.core/ast."
([code]
(parse-code code nil))
([code options]
; parcera/ast takes options as [code & {:as options}]
(apply parcera/ast code (mapcat vec options))))
(defn unparse-code
"Unparse code."
([ast]
(unparse-code ast nil))
([ast {:keys [inline?]}]
(parcera/code
(cond->> ast
inline?
m/compact-whitespaces)))) | null | https://raw.githubusercontent.com/bfontaine/grape/51d741943595f55fd51c34b0213037ca484a1bfb/src/grape/impl/parsing.clj | clojure | parcera/ast takes options as [code & {:as options}] | (ns grape.impl.parsing
"Internal parsing utilities."
(:require [parcera.core :as parcera]
[grape.impl.models :as m]))
(defn parse-code
"Parse code. Options are passed to parcera.core/ast."
([code]
(parse-code code nil))
([code options]
(apply parcera/ast code (mapcat vec options))))
(defn unparse-code
"Unparse code."
([ast]
(unparse-code ast nil))
([ast {:keys [inline?]}]
(parcera/code
(cond->> ast
inline?
m/compact-whitespaces)))) |
cccaaa60c3b791c33ec0427a824c18d3a9e1442c86043d99e53cd0182b17d504 | NorfairKing/validity | Persist.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - orphans #
module Data.GenValidity.Persist where
import Data.GenValidity
import Data.GenValidity.Containers
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NE
import Data.Validity.Containers
import Data.Validity.Persist ()
import Database.Persist
import Database.Persist.Sql
import Test.QuickCheck
instance ToBackendKey SqlBackend record => GenValid (Key record) where
genValid = toSqlKey <$> genValid
shrinkValid = fmap toSqlKey . shrinkValid . fromSqlKey
instance (GenValid a, ToBackendKey SqlBackend a) => GenValid (Entity a) where
genValid = Entity <$> genValid <*> genValid
shrinkValid (Entity k v) = [Entity k' v' | (k', v') <- shrinkValid (k, v)]
validsWithSeperateIDs ::
forall a.
(ToBackendKey SqlBackend a, GenValid a) =>
Gen [Entity a]
validsWithSeperateIDs = genValidsWithSeperateIDs genValid
genValidsWithSeperateIDs ::
forall a.
(PersistEntity a, ToBackendKey SqlBackend a) =>
Gen a ->
Gen [Entity a]
genValidsWithSeperateIDs gen =
sized $ \n -> do
list <- arbPartition n
go list
where
go :: [Int] -> Gen [Entity a]
go [] = pure []
go (s : ss) = do
es <- go ss
resize s $ do
ei <- genValid `suchThat` (`notElem` map entityKey es)
e <- gen
pure $ Entity ei e : es
genSeperateIdsForNE ::
forall a.
(PersistEntity a, ToBackendKey SqlBackend a, GenValid a) =>
NonEmpty a ->
Gen (NonEmpty (Entity a))
genSeperateIdsForNE (a :| as) = do
es <- genSeperateIdsFor as
i <- genValid `suchThat` (`notElem` map entityKey es)
pure (Entity i a :| es)
genSeperateIds ::
forall a.
(PersistEntity a, ToBackendKey SqlBackend a) =>
Gen [Key a]
genSeperateIds = genSeperate genValid
genSeperateIdsFor ::
forall a.
(ToBackendKey SqlBackend a, GenValid a) =>
[a] ->
Gen [Entity a]
genSeperateIdsFor [] = pure []
genSeperateIdsFor (a : as) = NE.toList <$> genSeperateIdsForNE (a :| as)
shrinkValidWithSeperateIds ::
(PersistEntity a, ToBackendKey SqlBackend a, GenValid a) =>
[Entity a] ->
[[Entity a]]
shrinkValidWithSeperateIds = filter (distinctOrd . map entityKey) . shrinkValid
| null | https://raw.githubusercontent.com/NorfairKing/validity/35bc8d45b27e6c21429e4b681b16e46ccd541b3b/genvalidity-persistent/src/Data/GenValidity/Persist.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - orphans #
module Data.GenValidity.Persist where
import Data.GenValidity
import Data.GenValidity.Containers
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NE
import Data.Validity.Containers
import Data.Validity.Persist ()
import Database.Persist
import Database.Persist.Sql
import Test.QuickCheck
instance ToBackendKey SqlBackend record => GenValid (Key record) where
genValid = toSqlKey <$> genValid
shrinkValid = fmap toSqlKey . shrinkValid . fromSqlKey
instance (GenValid a, ToBackendKey SqlBackend a) => GenValid (Entity a) where
genValid = Entity <$> genValid <*> genValid
shrinkValid (Entity k v) = [Entity k' v' | (k', v') <- shrinkValid (k, v)]
validsWithSeperateIDs ::
forall a.
(ToBackendKey SqlBackend a, GenValid a) =>
Gen [Entity a]
validsWithSeperateIDs = genValidsWithSeperateIDs genValid
genValidsWithSeperateIDs ::
forall a.
(PersistEntity a, ToBackendKey SqlBackend a) =>
Gen a ->
Gen [Entity a]
genValidsWithSeperateIDs gen =
sized $ \n -> do
list <- arbPartition n
go list
where
go :: [Int] -> Gen [Entity a]
go [] = pure []
go (s : ss) = do
es <- go ss
resize s $ do
ei <- genValid `suchThat` (`notElem` map entityKey es)
e <- gen
pure $ Entity ei e : es
genSeperateIdsForNE ::
forall a.
(PersistEntity a, ToBackendKey SqlBackend a, GenValid a) =>
NonEmpty a ->
Gen (NonEmpty (Entity a))
genSeperateIdsForNE (a :| as) = do
es <- genSeperateIdsFor as
i <- genValid `suchThat` (`notElem` map entityKey es)
pure (Entity i a :| es)
genSeperateIds ::
forall a.
(PersistEntity a, ToBackendKey SqlBackend a) =>
Gen [Key a]
genSeperateIds = genSeperate genValid
genSeperateIdsFor ::
forall a.
(ToBackendKey SqlBackend a, GenValid a) =>
[a] ->
Gen [Entity a]
genSeperateIdsFor [] = pure []
genSeperateIdsFor (a : as) = NE.toList <$> genSeperateIdsForNE (a :| as)
shrinkValidWithSeperateIds ::
(PersistEntity a, ToBackendKey SqlBackend a, GenValid a) =>
[Entity a] ->
[[Entity a]]
shrinkValidWithSeperateIds = filter (distinctOrd . map entityKey) . shrinkValid
| |
b5722e828155e64ad2122e6785fd02de991ff60eb5a9a692d8dac47b07760986 | janestreet/async_unix | interruptor.mli | * An interruptor provides a file descriptor that can be used to cause a
file - descr - watcher to detect the file descriptor is ready for reading . We use an
interruptor when a thread needs the Async scheduler to service a request .
Knock , knock .
Who 's there ?
Interruptor cow .
Interrup-
{ v
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/ \
| _ _ _ _ _ _ _ _ _ _ _ _ |
| | \/ |/ _ _ \ / _ _ \ |
| | \ / | | | | | | | |
| | |\/| | | | | | | | |
| | | | | |__| | |__| | |
| |_| |_|\____/ \____/ |
\ /
-------------------------
\ ^__^
\ ( oo)\ _ _ _ _ _ _ _
( _ _ ) \ ) \/\
||----w |
|| ||
v }
file-descr-watcher to detect the file descriptor is ready for reading. We use an
interruptor when a thread needs the Async scheduler to service a request.
Knock, knock.
Who's there?
Interruptor cow.
Interrup-
{v
_________________________
/ \
| __ __ ____ ____ |
| | \/ |/ __ \ / __ \ |
| | \ / | | | | | | | |
| | |\/| | | | | | | | |
| | | | | |__| | |__| | |
| |_| |_|\____/ \____/ |
\ /
-------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
v}
*)
open! Core
open! Import
type t [@@deriving sexp_of]
include Invariant.S with type t := t
val create : create_fd:(Raw_fd.Kind.t -> Unix.File_descr.t -> Info.t -> Raw_fd.t) -> t
val read_fd : t -> Raw_fd.t
(** [thread_safe_interrupt t] causes [read_fd t] to become ready for reading. *)
val thread_safe_interrupt : t -> unit
(** [clear t] causes [read_fd t] to become not ready for reading. It is guaranteed that
any calls to [thread_safe_interrupt] after [clear t] returns (and prior to another
call to [clear t]) will cause [read_fd] to become ready for reading. *)
val clear : t -> unit
(** [already_interrupted t] is true if [thread_safe_interrupt t] has completed since the
last call to [clear t]. *)
val already_interrupted : t -> bool
| null | https://raw.githubusercontent.com/janestreet/async_unix/e5d9e9d388a23237cec3bf42d7e310c459de4309/src/interruptor.mli | ocaml | * [thread_safe_interrupt t] causes [read_fd t] to become ready for reading.
* [clear t] causes [read_fd t] to become not ready for reading. It is guaranteed that
any calls to [thread_safe_interrupt] after [clear t] returns (and prior to another
call to [clear t]) will cause [read_fd] to become ready for reading.
* [already_interrupted t] is true if [thread_safe_interrupt t] has completed since the
last call to [clear t]. | * An interruptor provides a file descriptor that can be used to cause a
file - descr - watcher to detect the file descriptor is ready for reading . We use an
interruptor when a thread needs the Async scheduler to service a request .
Knock , knock .
Who 's there ?
Interruptor cow .
Interrup-
{ v
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/ \
| _ _ _ _ _ _ _ _ _ _ _ _ |
| | \/ |/ _ _ \ / _ _ \ |
| | \ / | | | | | | | |
| | |\/| | | | | | | | |
| | | | | |__| | |__| | |
| |_| |_|\____/ \____/ |
\ /
-------------------------
\ ^__^
\ ( oo)\ _ _ _ _ _ _ _
( _ _ ) \ ) \/\
||----w |
|| ||
v }
file-descr-watcher to detect the file descriptor is ready for reading. We use an
interruptor when a thread needs the Async scheduler to service a request.
Knock, knock.
Who's there?
Interruptor cow.
Interrup-
{v
_________________________
/ \
| __ __ ____ ____ |
| | \/ |/ __ \ / __ \ |
| | \ / | | | | | | | |
| | |\/| | | | | | | | |
| | | | | |__| | |__| | |
| |_| |_|\____/ \____/ |
\ /
-------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
v}
*)
open! Core
open! Import
type t [@@deriving sexp_of]
include Invariant.S with type t := t
val create : create_fd:(Raw_fd.Kind.t -> Unix.File_descr.t -> Info.t -> Raw_fd.t) -> t
val read_fd : t -> Raw_fd.t
val thread_safe_interrupt : t -> unit
val clear : t -> unit
val already_interrupted : t -> bool
|
5f662cb3710b5c488426f1442086f0d8a81a25149220a404758ea4f5015cca2e | spechub/Hets | ProveCommands.hs | module HetsAPI.ProveCommands (
availableComorphisms
, usableProvers
, usableConsistencyCheckers
, autoProveNode
, proveNode
, checkConsistency
, checkConservativityNode
) where
import Data.Functor ()
import Control.Monad.Trans ( MonadTrans(lift) )
import Common.LibName (LibName)
import Common.ResultT (ResultT)
import Comorphisms.KnownProvers (knownProversWithKind)
import Comorphisms.LogicGraph (logicGraph)
import Logic.Comorphism (AnyComorphism)
import Logic.Prover (ProofStatus, ProverKind (..))
import Proofs.AbstractState (G_prover, ProofState, G_proof_tree, autoProofAtNode, getUsableProvers, G_cons_checker (..), getProverName, getConsCheckers)
import Static.DevGraph (LibEnv, DGraph, lookupDGraph, DGNodeLab, labNodesDG, ProofHistory)
import Static.GTheory (G_theory (..), sublogicOfTh, proveSens)
import Data.Graph.Inductive (LNode)
import Proofs.ConsistencyCheck (ConsistencyStatus, consistencyCheck)
import Logic.Logic (Logic(cons_checkers))
import qualified Interfaces.Utils (checkConservativityNode)
import Logic.Grothendieck (findComorphismPaths)
-- | @availableComorphisms theory@ yields all available comorphisms for @theory@
availableComorphisms :: G_theory -> [AnyComorphism]
availableComorphisms = findComorphismPaths logicGraph . sublogicOfTh
| @usableConsistencyCheckers theory@ checks for usable consistencey checkers
-- for @theory@ available on the machine
usableConsistencyCheckers :: G_theory -> IO [(G_cons_checker, AnyComorphism)]
usableConsistencyCheckers = getConsCheckers . availableComorphisms
-- | @usableProvers theory@ checks for usable provers available on the machine
usableProvers :: G_theory -> IO [(G_prover, AnyComorphism)]
usableProvers th = getUsableProvers ProveCMDLautomatic (sublogicOfTh th) logicGraph
-- | @proveNode theory prover comorphism@ proves all goals in @theory@ using all
all axioms in @theory@. If @prover@ or @comorphism@ is @Nothing@ the first
-- usable prover or comorphism, respectively, is used.
autoProveNode :: G_theory -> Maybe G_prover -> Maybe AnyComorphism -> ResultT IO (G_theory, ProofState, [ProofStatus G_proof_tree])
autoProveNode theory proverM comorphismM = do
(prover, comorphism) <- case (proverM, comorphismM) of
(Just prover, Just comorphism) -> return (prover, comorphism)
(Just prover, Nothing) -> do
let proverName = getProverName prover
comorphism <- lift
(snd . head . filter ((== proverName) . getProverName . fst) <$> usableProvers theory)
return (prover, comorphism)
(Nothing, Just comorphism) -> do
prover <- lift
(fst . head . filter ((== comorphism) . snd) <$> usableProvers theory)
return (prover, comorphism)
(Nothing, Nothing) -> head <$> lift (usableProvers theory)
((th, out), (state, steps)) <- autoProofAtNode True 600 [] [] theory (prover, comorphism)
return (th, state, steps)
-- | @proveNode sub timeout goals axioms theory (prover, comorphism)@ proves
-- @goals@ with @prover@ after applying @comorphism@. If @goals@ is empty all
goals are selected . Same for @axioms@. If @sub@ is set theorems are used in
-- subsequent proofs. The runtime is restricted by @timeout@.
proveNode ::
-- Use theorems is subsequent proofs
Bool
Timeout limit
-> Int
-- Goals to prove
-> [String]
Axioms useable for the prove
-> [String]
-- Theory
-> G_theory
-- Combination of prover and comorphism
-> (G_prover, AnyComorphism)
returns new GoalStatus for the Node
-> ResultT IO (ProofState, [ProofStatus G_proof_tree])
proveNode sub timeout goals axioms theory pc = snd <$>
autoProofAtNode sub timeout goals axioms theory pc
| @checkConsistency includeTheorems
dg node timeout@ first applies the comorphism @cc@ to the theory at @node@
-- in the developmentGraph @dg@ inside the library @libname@ in the environment
-- @libenv@, then checks the consistency using the consistency checker @cc@
-- with a timeout of @timeout@ seconds.
checkConsistency :: Bool -> G_cons_checker -> AnyComorphism -> LibName -> LibEnv
-> DGraph -> LNode DGNodeLab -> Int -> IO ConsistencyStatus
checkConsistency = consistencyCheck
checkConservativityNode ::LNode DGNodeLab -> LibEnv -> LibName
-> IO (String, LibEnv, ProofHistory)
checkConservativityNode = Interfaces.Utils.checkConservativityNode False | null | https://raw.githubusercontent.com/spechub/Hets/0dfcaf6a049bd686ee64f0cb245b0d3694a5f8ac/HetsAPI/ProveCommands.hs | haskell | | @availableComorphisms theory@ yields all available comorphisms for @theory@
for @theory@ available on the machine
| @usableProvers theory@ checks for usable provers available on the machine
| @proveNode theory prover comorphism@ proves all goals in @theory@ using all
usable prover or comorphism, respectively, is used.
| @proveNode sub timeout goals axioms theory (prover, comorphism)@ proves
@goals@ with @prover@ after applying @comorphism@. If @goals@ is empty all
subsequent proofs. The runtime is restricted by @timeout@.
Use theorems is subsequent proofs
Goals to prove
Theory
Combination of prover and comorphism
in the developmentGraph @dg@ inside the library @libname@ in the environment
@libenv@, then checks the consistency using the consistency checker @cc@
with a timeout of @timeout@ seconds. | module HetsAPI.ProveCommands (
availableComorphisms
, usableProvers
, usableConsistencyCheckers
, autoProveNode
, proveNode
, checkConsistency
, checkConservativityNode
) where
import Data.Functor ()
import Control.Monad.Trans ( MonadTrans(lift) )
import Common.LibName (LibName)
import Common.ResultT (ResultT)
import Comorphisms.KnownProvers (knownProversWithKind)
import Comorphisms.LogicGraph (logicGraph)
import Logic.Comorphism (AnyComorphism)
import Logic.Prover (ProofStatus, ProverKind (..))
import Proofs.AbstractState (G_prover, ProofState, G_proof_tree, autoProofAtNode, getUsableProvers, G_cons_checker (..), getProverName, getConsCheckers)
import Static.DevGraph (LibEnv, DGraph, lookupDGraph, DGNodeLab, labNodesDG, ProofHistory)
import Static.GTheory (G_theory (..), sublogicOfTh, proveSens)
import Data.Graph.Inductive (LNode)
import Proofs.ConsistencyCheck (ConsistencyStatus, consistencyCheck)
import Logic.Logic (Logic(cons_checkers))
import qualified Interfaces.Utils (checkConservativityNode)
import Logic.Grothendieck (findComorphismPaths)
availableComorphisms :: G_theory -> [AnyComorphism]
availableComorphisms = findComorphismPaths logicGraph . sublogicOfTh
| @usableConsistencyCheckers theory@ checks for usable consistencey checkers
usableConsistencyCheckers :: G_theory -> IO [(G_cons_checker, AnyComorphism)]
usableConsistencyCheckers = getConsCheckers . availableComorphisms
usableProvers :: G_theory -> IO [(G_prover, AnyComorphism)]
usableProvers th = getUsableProvers ProveCMDLautomatic (sublogicOfTh th) logicGraph
all axioms in @theory@. If @prover@ or @comorphism@ is @Nothing@ the first
autoProveNode :: G_theory -> Maybe G_prover -> Maybe AnyComorphism -> ResultT IO (G_theory, ProofState, [ProofStatus G_proof_tree])
autoProveNode theory proverM comorphismM = do
(prover, comorphism) <- case (proverM, comorphismM) of
(Just prover, Just comorphism) -> return (prover, comorphism)
(Just prover, Nothing) -> do
let proverName = getProverName prover
comorphism <- lift
(snd . head . filter ((== proverName) . getProverName . fst) <$> usableProvers theory)
return (prover, comorphism)
(Nothing, Just comorphism) -> do
prover <- lift
(fst . head . filter ((== comorphism) . snd) <$> usableProvers theory)
return (prover, comorphism)
(Nothing, Nothing) -> head <$> lift (usableProvers theory)
((th, out), (state, steps)) <- autoProofAtNode True 600 [] [] theory (prover, comorphism)
return (th, state, steps)
goals are selected . Same for @axioms@. If @sub@ is set theorems are used in
proveNode ::
Bool
Timeout limit
-> Int
-> [String]
Axioms useable for the prove
-> [String]
-> G_theory
-> (G_prover, AnyComorphism)
returns new GoalStatus for the Node
-> ResultT IO (ProofState, [ProofStatus G_proof_tree])
proveNode sub timeout goals axioms theory pc = snd <$>
autoProofAtNode sub timeout goals axioms theory pc
| @checkConsistency includeTheorems
dg node timeout@ first applies the comorphism @cc@ to the theory at @node@
checkConsistency :: Bool -> G_cons_checker -> AnyComorphism -> LibName -> LibEnv
-> DGraph -> LNode DGNodeLab -> Int -> IO ConsistencyStatus
checkConsistency = consistencyCheck
checkConservativityNode ::LNode DGNodeLab -> LibEnv -> LibName
-> IO (String, LibEnv, ProofHistory)
checkConservativityNode = Interfaces.Utils.checkConservativityNode False |
6434b953d34cbf0bafd5849a3487bcf30971563be365e163b9e7392f1087d701 | UCSD-PL/nano-smt | Tests.hs | -- | Module with candidate test Values for Each Type
module Language.Nano.SMT.Tests (runTests, tests) where
import Test.HUnit
import Language.Nano.SMT.Types
import Language.Nano.SMT.SAT
runTests :: IO ()
runTests = runTestTT tests >>= putStrLn . show
---------------------------------------------------------------------------
-- Tests for SAT ----------------------------------------------------------
---------------------------------------------------------------------------
tests = test $ zipWith satTest [0..] satTests
satTest i (b, f) = name ~: name ~: b ~=? exec f
where
name = "sat" ++ show i
exec = asBool . sat_solver
asBool (Asgn _) = True
asBool _ = False
satTests :: [(Bool , CnfFormula)]
satTests
= [ (False, cnf [[]])
, (True , cnf [[1 , 2]
,[-1, 3]
,[-3 ]])
, (False, cnf [[ 1]
,[-1]])
, (True , cnf [[-9, 1, 2]
,[ 9, 2, 3]
,[ 9, 2,-3]
,[ 9,-2, 3]
,[ 9,-2,-3]
,[-1,-2, 3]
,[-9, 1,-2]
,[-9,-1, 2]])
, (True , cnf [ [1 , 4]
, [1 , -3, -8]
, [1 , 8, 12]
, [2 , 11]
, [-7, -3, 9]
, [-7, 8, -9]
, [7 , 8, -10]
, [7 , 10, -12]])
]
| null | https://raw.githubusercontent.com/UCSD-PL/nano-smt/0fe3be6cf5ecf82f61ea9b3b3a4047d8f72c04f1/Language/Nano/SMT/Tests.hs | haskell | | Module with candidate test Values for Each Type
-------------------------------------------------------------------------
Tests for SAT ----------------------------------------------------------
------------------------------------------------------------------------- |
module Language.Nano.SMT.Tests (runTests, tests) where
import Test.HUnit
import Language.Nano.SMT.Types
import Language.Nano.SMT.SAT
runTests :: IO ()
runTests = runTestTT tests >>= putStrLn . show
tests = test $ zipWith satTest [0..] satTests
satTest i (b, f) = name ~: name ~: b ~=? exec f
where
name = "sat" ++ show i
exec = asBool . sat_solver
asBool (Asgn _) = True
asBool _ = False
satTests :: [(Bool , CnfFormula)]
satTests
= [ (False, cnf [[]])
, (True , cnf [[1 , 2]
,[-1, 3]
,[-3 ]])
, (False, cnf [[ 1]
,[-1]])
, (True , cnf [[-9, 1, 2]
,[ 9, 2, 3]
,[ 9, 2,-3]
,[ 9,-2, 3]
,[ 9,-2,-3]
,[-1,-2, 3]
,[-9, 1,-2]
,[-9,-1, 2]])
, (True , cnf [ [1 , 4]
, [1 , -3, -8]
, [1 , 8, 12]
, [2 , 11]
, [-7, -3, 9]
, [-7, 8, -9]
, [7 , 8, -10]
, [7 , 10, -12]])
]
|
9e6e4a2b431f7c216b841bb5a52b889cbc51f6180f375e5300c96756ebc3a4b6 | kahua/Kahua | gsid.scm | ;; Manages global session ID
;;
Copyright ( c ) 2003 - 2007 Scheme Arts , L.L.C. , All rights reserved .
Copyright ( c ) 2003 - 2007 Time Intermedia Corporation , All rights reserved .
;; See COPYING for terms and conditions of using this software
;;
(define-module kahua.gsid
(use gauche.uvector)
(use gauche.net)
(use file.util)
(use srfi-1)
(use srfi-27)
(export make-gsid decompose-gsid gsid->worker-id
worker-id->sockaddr make-worker-id
supervisor-sockaddr
get-gsid-from-header add-gsid-to-header)
)
(select-module kahua.gsid)
Global session ID ( GSID ) -------------------------------------------
;;
Session ID consists of two strings . One is a continuation ID , which
;; corresponds to a continuation of the session. It can be restartable,
;; that is, the same continuation ID can be reused to backtrack the
;; session as far as it hasn't explicitly invalidated. In other word,
;; a continuation ID has an unlimited extent by default.
;;
;; The other is a state ID, which stands for a monadic state of
;; the session. It carries a stateful information---therefore can't
;; be backtracked.
;;
;; In a typical web session, the continuation ID is kept in parameters
;; in POST request or in URL, whereas the state ID is kept in cookies.
;;
;; Both ID consists of the following format:
;;
1 - HHHHH - BBBBBBB
;;
The first ' 1 ' desginates the GSID version . Hs and Bs are for a header
;; and a body. The format after the version number can be changed
in the later versions . For version 1 , the header just includes worker ID .
The body is up to the worker . Hs and Bs should n't include a minus sign .
(define (make-gsid worker-id body)
(format "1-~a-~a" worker-id body))
(define (decompose-gsid gsid)
(if (string? gsid)
(let1 l (string-split gsid #\-)
(if (and (= (length l) 3)
(equal? (car l) "1"))
(values (cadr l) (caddr l))
(values #f gsid)))
(values #f #f)))
(define (gsid->worker-id gsid)
(and gsid (receive (h b) (decompose-gsid gsid) h)))
;; Convenience routines.
Header is like ( ( " name1 " " value1 " ) ( " " " value2 " ) ) but may be
;; changed later.
(define (get-gsid-from-header header)
(values (cond ((assoc "x-kahua-sgsid" header) => cadr) (else #f))
(cond ((assoc "x-kahua-cgsid" header) => cadr) (else #f))))
(define (add-gsid-to-header header stat-gsid cont-gsid)
(define (add header name id)
(if id
(cons (list name id)
(remove (lambda (entry) (equal? (car entry) name)) header))
header))
(add (add header "x-kahua-cgsid" cont-gsid) "x-kahua-sgsid" stat-gsid))
NB : This should be configurable !
(define *kahua-sock-base* "unix:/tmp/kahua")
(define (worker-id->sockaddr worker-id . opts)
(if worker-id
(receive (proto param)
(string-scan (or (get-optional opts #f) *kahua-sock-base*) ":" 'both)
(cond
((equal? proto "unix")
(make <sockaddr-un> :path (build-path param worker-id)))
(else
(error "unsupported socket base: "
(get-optional opts *kahua-sock-base*)))))
(apply supervisor-sockaddr opts)))
(define (make-worker-id worker-type)
(format "~a:~a"
(number->string (sys-getpid) 36)
(number->string (random-integer 10000000) 36)))
(define (supervisor-sockaddr . opts)
;; this may not be correct if we use inet domain socket.
(apply worker-id->sockaddr "kahua" opts))
;; TODO: should be done in system's initialize routine?
(random-source-randomize! default-random-source)
(provide "kahua/gsid")
| null | https://raw.githubusercontent.com/kahua/Kahua/c90fe590233e4540923e4e5cc9f61da32873692c/src/kahua/gsid.scm | scheme | Manages global session ID
See COPYING for terms and conditions of using this software
corresponds to a continuation of the session. It can be restartable,
that is, the same continuation ID can be reused to backtrack the
session as far as it hasn't explicitly invalidated. In other word,
a continuation ID has an unlimited extent by default.
The other is a state ID, which stands for a monadic state of
the session. It carries a stateful information---therefore can't
be backtracked.
In a typical web session, the continuation ID is kept in parameters
in POST request or in URL, whereas the state ID is kept in cookies.
Both ID consists of the following format:
and a body. The format after the version number can be changed
Convenience routines.
changed later.
this may not be correct if we use inet domain socket.
TODO: should be done in system's initialize routine? | Copyright ( c ) 2003 - 2007 Scheme Arts , L.L.C. , All rights reserved .
Copyright ( c ) 2003 - 2007 Time Intermedia Corporation , All rights reserved .
(define-module kahua.gsid
(use gauche.uvector)
(use gauche.net)
(use file.util)
(use srfi-1)
(use srfi-27)
(export make-gsid decompose-gsid gsid->worker-id
worker-id->sockaddr make-worker-id
supervisor-sockaddr
get-gsid-from-header add-gsid-to-header)
)
(select-module kahua.gsid)
Global session ID ( GSID ) -------------------------------------------
Session ID consists of two strings . One is a continuation ID , which
1 - HHHHH - BBBBBBB
The first ' 1 ' desginates the GSID version . Hs and Bs are for a header
in the later versions . For version 1 , the header just includes worker ID .
The body is up to the worker . Hs and Bs should n't include a minus sign .
(define (make-gsid worker-id body)
(format "1-~a-~a" worker-id body))
(define (decompose-gsid gsid)
(if (string? gsid)
(let1 l (string-split gsid #\-)
(if (and (= (length l) 3)
(equal? (car l) "1"))
(values (cadr l) (caddr l))
(values #f gsid)))
(values #f #f)))
(define (gsid->worker-id gsid)
(and gsid (receive (h b) (decompose-gsid gsid) h)))
Header is like ( ( " name1 " " value1 " ) ( " " " value2 " ) ) but may be
(define (get-gsid-from-header header)
(values (cond ((assoc "x-kahua-sgsid" header) => cadr) (else #f))
(cond ((assoc "x-kahua-cgsid" header) => cadr) (else #f))))
(define (add-gsid-to-header header stat-gsid cont-gsid)
(define (add header name id)
(if id
(cons (list name id)
(remove (lambda (entry) (equal? (car entry) name)) header))
header))
(add (add header "x-kahua-cgsid" cont-gsid) "x-kahua-sgsid" stat-gsid))
NB : This should be configurable !
(define *kahua-sock-base* "unix:/tmp/kahua")
(define (worker-id->sockaddr worker-id . opts)
(if worker-id
(receive (proto param)
(string-scan (or (get-optional opts #f) *kahua-sock-base*) ":" 'both)
(cond
((equal? proto "unix")
(make <sockaddr-un> :path (build-path param worker-id)))
(else
(error "unsupported socket base: "
(get-optional opts *kahua-sock-base*)))))
(apply supervisor-sockaddr opts)))
(define (make-worker-id worker-type)
(format "~a:~a"
(number->string (sys-getpid) 36)
(number->string (random-integer 10000000) 36)))
(define (supervisor-sockaddr . opts)
(apply worker-id->sockaddr "kahua" opts))
(random-source-randomize! default-random-source)
(provide "kahua/gsid")
|
28a26fa341eddf6efc7020b96fc7fbf666e721eb722dfaa63a1906c03ebe1d22 | esl/lager_graylog | lager_graylog_gelf_formatter_SUITE.erl | -module(lager_graylog_gelf_formatter_SUITE).
-include_lib("eunit/include/eunit.hrl").
-compile(export_all).
%% Suite configuration
all() ->
[formats_log_with_mandatory_attributes,
formats_all_metadata_by_default,
formats_only_selected_metadata,
formats_all_metadata_if_configured,
doesnt_format_default_timestamp_if_configured,
formats_metadata_using_configured_function,
overrides_host_if_configured_as_binary,
overrides_host_if_configured_as_string,
binary_metadata_formatting,
atom_metadata_formatting,
integer_metadata_formatting,
float_metadata_formatting,
reference_metadata_formatting,
pid_metadata_formatting,
list_metadata_formatting,
tuple_metadata_formatting,
map_metadata_formatting,
bitstring_metadata_formatting,
formats_iolist_message_correctly,
on_encode_failure_crashes,
on_encode_failure_returns_configured_string,
on_encode_failure_returns_configured_binary,
on_encode_failure_crashes_if_second_encode_crashes_too
].
%% Test cases
formats_log_with_mandatory_attributes(_Config) ->
Message = "hello",
Timestamp = erlang:timestamp(),
{ok, Host} = inet:gethostname(),
Log = lager_msg:new(Message, Timestamp, debug, [], []),
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, []),
ct:pal("~s", [Formatted]),
Gelf = decode(Formatted),
?assertEqual(<<"1.1">>, maps:get(<<"version">>, Gelf)),
?assertEqual(list_to_binary(Message), maps:get(<<"short_message">>, Gelf)),
?assertEqual(list_to_binary(Host), maps:get(<<"host">>, Gelf)),
?assertEqual(7, maps:get(<<"level">>, Gelf)),
UnixTS = maps:get(<<"timestamp">>, Gelf),
?assert(is_float(UnixTS)),
assert_same_timestamp(Timestamp, UnixTS).
formats_all_metadata_by_default(_Config) ->
Log = lager_msg:new("hello", erlang:timestamp(), debug, [{module, mod}, {line, 99}], []),
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, []),
Gelf = decode(Formatted),
?assertEqual(<<"mod">>, maps:get(<<"_module">>, Gelf)),
?assertEqual(99, maps:get(<<"_line">>, Gelf)).
formats_only_selected_metadata(_Config) ->
Log = lager_msg:new("hello", erlang:timestamp(), debug, [{module, mod}, {line, 99}], []),
Opts = [{metadata, [module]}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertEqual(<<"mod">>, maps:get(<<"_module">>, Gelf)),
?assertNot(maps:is_key(<<"_line">>, Gelf)).
formats_all_metadata_if_configured(_Config) ->
Log = lager_msg:new("hello", erlang:timestamp(), debug, [{module, mod}, {line, 99}], []),
Opts = [{metadata, all}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertEqual(<<"mod">>, maps:get(<<"_module">>, Gelf)),
?assertEqual(99, maps:get(<<"_line">>, Gelf)).
doesnt_format_default_timestamp_if_configured(_Config) ->
Log = lager_msg:new("hello", erlang:timestamp(), debug, [], []),
Opts = [{include_timestamp, false}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertNot(maps:is_key(<<"timestamp">>, Gelf)).
formats_metadata_using_configured_function(_Config) ->
Log = lager_msg:new("hello", erlang:timestamp(), debug, [], []),
Opts = [{metadata, {?MODULE, metadata_fun}}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertEqual(<<"\"sample\"">>, maps:get(<<"_meta">>, Gelf)).
overrides_host_if_configured_as_binary(_Config) ->
Log = lager_msg:new("hello", erlang:timestamp(), debug, [], []),
Host = <<"some-host">>,
Opts = [{override_host, Host}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertEqual(Host, maps:get(<<"host">>, Gelf)).
overrides_host_if_configured_as_string(_Config) ->
Log = lager_msg:new("hello", erlang:timestamp(), debug, [], []),
Host = "some-host",
Opts = [{override_host, Host}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertEqual(list_to_binary(Host), maps:get(<<"host">>, Gelf)).
binary_metadata_formatting(_Config) ->
assert_metadata_format([{<<"printable">>, <<"<<\"printable\">>">>},
{<<1, 2, 3>>, <<"<<1,2,3>>">>}]).
atom_metadata_formatting(_Config) ->
assert_metadata_format([{'some-atom', <<"some-atom">>}]).
integer_metadata_formatting(_Config) ->
assert_metadata_format([{-1, -1},
{1, 1},
{0, 0}]).
float_metadata_formatting(_Config) ->
assert_metadata_format([{-1.12345, -1.12345},
{1.12345, 1.12345},
{0.0, 0.0}]).
reference_metadata_formatting(_Config) ->
Ref = make_ref(),
assert_metadata_format([{Ref, list_to_binary(erlang:ref_to_list(Ref))}]).
pid_metadata_formatting(_Config) ->
Pid = spawn(fun() -> ok end),
assert_metadata_format([{Pid, list_to_binary(pid_to_list(Pid))}]).
list_metadata_formatting(_Config) ->
assert_metadata_format([{"string", <<"\"string\"">>},
{[1, 2, 3], <<"[1,2,3]">>},
{[], <<"[]">>},
{[48, [<<"hello">>], 21], <<"[48,[<<\"hello\">>],21]">>}]).
tuple_metadata_formatting(_Config) ->
assert_metadata_format([{{}, <<"{}">>},
{{1}, <<"{1}">>},
{{"hello", there}, <<"{\"hello\",there}">>}]).
map_metadata_formatting(_Config) ->
assert_metadata_format([{#{}, <<"#{}">>},
{#{key => val}, <<"#{key => val}">>}]).
bitstring_metadata_formatting(_Config) ->
assert_metadata_format([{<<1:3>>, <<"<<1:3>>">>}]).
formats_iolist_message_correctly(_Config) ->
IolistMsg = ["alice", ["has" | "a"], <<"cat">>, 20],
Log = lager_msg:new(IolistMsg, erlang:timestamp(), debug, [], []),
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, []),
Gelf = decode(Formatted),
?assertEqual(iolist_to_binary(IolistMsg), maps:get(<<"short_message">>, Gelf)).
on_encode_failure_crashes(_Config) ->
Log = lager_msg:new(<<"strange character: ·">>, erlang:timestamp(), debug, [], []),
Opts = [{on_encode_failure, crash}],
?assertThrow({error, {invalid_string, _}}, lager_graylog_gelf_formatter:format(Log, undefined, Opts)).
on_encode_failure_returns_configured_string(_Config) ->
Log = lager_msg:new(<<"strange character: ·">>, erlang:timestamp(), debug, [], []),
OnFailMessage = "Encoding GELF failed",
Opts = [{on_encode_failure, OnFailMessage}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertEqual(list_to_binary(OnFailMessage), maps:get(<<"short_message">>, Gelf)).
on_encode_failure_returns_configured_binary(_Config) ->
Log = lager_msg:new(<<"strange character: ·">>, erlang:timestamp(), debug, [], []),
OnFailMessage = <<"Encoding GELF failed">>,
Opts = [{on_encode_failure, OnFailMessage}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertEqual(OnFailMessage, maps:get(<<"short_message">>, Gelf)).
on_encode_failure_crashes_if_second_encode_crashes_too(_Config) ->
Log = lager_msg:new(<<"strange character: ·">>, erlang:timestamp(), debug, [], []),
Opts = [{on_encode_failure, <<"this message is invalid, too :( ·">>}],
?assertThrow({error, {invalid_string, _}}, lager_graylog_gelf_formatter:format(Log, undefined, Opts)).
metadata_fun(_) ->
[{meta, "sample"}].
%% Helpers
-spec decode(iodata()) -> map().
decode(JSON) when is_binary(JSON) ->
jiffy:decode(JSON, [return_maps]);
decode(JSON) ->
decode(iolist_to_binary(JSON)).
-spec assert_same_timestamp(erlang:timestamp(), float()) -> ok | no_return().
assert_same_timestamp({MegaSecs, Secs, MicroSecs}, UnixTS) ->
?assertEqual((MegaSecs * 1000000) + Secs + (MicroSecs / 1000000), UnixTS),
ok.
-spec assert_metadata_format([{term(), binary()}]) -> ok | no_return().
assert_metadata_format(ValuesWithExpectedFormat) ->
MetadataWithExpectedFormat0 = lists:zip(lists:seq(1, length(ValuesWithExpectedFormat)),
ValuesWithExpectedFormat),
MetadataWithExpectedFormat = lists:map(fun({IntKey, {V, F}}) ->
{list_to_atom(integer_to_list(IntKey)), {V, F}}
end, MetadataWithExpectedFormat0),
MetadataToLog = [{Key, Value} || {Key, {Value, _Format}} <- MetadataWithExpectedFormat],
Log = lager_msg:new("hello", erlang:timestamp(), debug, MetadataToLog, []),
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, []),
Gelf = decode(Formatted),
lists:foreach(fun({Key, {_Value, ExpectedFormat}}) ->
GelfKey = iolist_to_binary(io_lib:format("_~s", [Key])),
?assertEqual(ExpectedFormat, maps:get(GelfKey, Gelf))
end, MetadataWithExpectedFormat).
| null | https://raw.githubusercontent.com/esl/lager_graylog/6ed0f8d5b5aa5b63702944a585ed8ac0ae51c0eb/test/lager_graylog_gelf_formatter_SUITE.erl | erlang | Suite configuration
Test cases
Helpers | -module(lager_graylog_gelf_formatter_SUITE).
-include_lib("eunit/include/eunit.hrl").
-compile(export_all).
all() ->
[formats_log_with_mandatory_attributes,
formats_all_metadata_by_default,
formats_only_selected_metadata,
formats_all_metadata_if_configured,
doesnt_format_default_timestamp_if_configured,
formats_metadata_using_configured_function,
overrides_host_if_configured_as_binary,
overrides_host_if_configured_as_string,
binary_metadata_formatting,
atom_metadata_formatting,
integer_metadata_formatting,
float_metadata_formatting,
reference_metadata_formatting,
pid_metadata_formatting,
list_metadata_formatting,
tuple_metadata_formatting,
map_metadata_formatting,
bitstring_metadata_formatting,
formats_iolist_message_correctly,
on_encode_failure_crashes,
on_encode_failure_returns_configured_string,
on_encode_failure_returns_configured_binary,
on_encode_failure_crashes_if_second_encode_crashes_too
].
formats_log_with_mandatory_attributes(_Config) ->
Message = "hello",
Timestamp = erlang:timestamp(),
{ok, Host} = inet:gethostname(),
Log = lager_msg:new(Message, Timestamp, debug, [], []),
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, []),
ct:pal("~s", [Formatted]),
Gelf = decode(Formatted),
?assertEqual(<<"1.1">>, maps:get(<<"version">>, Gelf)),
?assertEqual(list_to_binary(Message), maps:get(<<"short_message">>, Gelf)),
?assertEqual(list_to_binary(Host), maps:get(<<"host">>, Gelf)),
?assertEqual(7, maps:get(<<"level">>, Gelf)),
UnixTS = maps:get(<<"timestamp">>, Gelf),
?assert(is_float(UnixTS)),
assert_same_timestamp(Timestamp, UnixTS).
formats_all_metadata_by_default(_Config) ->
Log = lager_msg:new("hello", erlang:timestamp(), debug, [{module, mod}, {line, 99}], []),
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, []),
Gelf = decode(Formatted),
?assertEqual(<<"mod">>, maps:get(<<"_module">>, Gelf)),
?assertEqual(99, maps:get(<<"_line">>, Gelf)).
formats_only_selected_metadata(_Config) ->
Log = lager_msg:new("hello", erlang:timestamp(), debug, [{module, mod}, {line, 99}], []),
Opts = [{metadata, [module]}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertEqual(<<"mod">>, maps:get(<<"_module">>, Gelf)),
?assertNot(maps:is_key(<<"_line">>, Gelf)).
formats_all_metadata_if_configured(_Config) ->
Log = lager_msg:new("hello", erlang:timestamp(), debug, [{module, mod}, {line, 99}], []),
Opts = [{metadata, all}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertEqual(<<"mod">>, maps:get(<<"_module">>, Gelf)),
?assertEqual(99, maps:get(<<"_line">>, Gelf)).
doesnt_format_default_timestamp_if_configured(_Config) ->
Log = lager_msg:new("hello", erlang:timestamp(), debug, [], []),
Opts = [{include_timestamp, false}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertNot(maps:is_key(<<"timestamp">>, Gelf)).
formats_metadata_using_configured_function(_Config) ->
Log = lager_msg:new("hello", erlang:timestamp(), debug, [], []),
Opts = [{metadata, {?MODULE, metadata_fun}}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertEqual(<<"\"sample\"">>, maps:get(<<"_meta">>, Gelf)).
overrides_host_if_configured_as_binary(_Config) ->
Log = lager_msg:new("hello", erlang:timestamp(), debug, [], []),
Host = <<"some-host">>,
Opts = [{override_host, Host}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertEqual(Host, maps:get(<<"host">>, Gelf)).
overrides_host_if_configured_as_string(_Config) ->
Log = lager_msg:new("hello", erlang:timestamp(), debug, [], []),
Host = "some-host",
Opts = [{override_host, Host}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertEqual(list_to_binary(Host), maps:get(<<"host">>, Gelf)).
binary_metadata_formatting(_Config) ->
assert_metadata_format([{<<"printable">>, <<"<<\"printable\">>">>},
{<<1, 2, 3>>, <<"<<1,2,3>>">>}]).
atom_metadata_formatting(_Config) ->
assert_metadata_format([{'some-atom', <<"some-atom">>}]).
integer_metadata_formatting(_Config) ->
assert_metadata_format([{-1, -1},
{1, 1},
{0, 0}]).
float_metadata_formatting(_Config) ->
assert_metadata_format([{-1.12345, -1.12345},
{1.12345, 1.12345},
{0.0, 0.0}]).
reference_metadata_formatting(_Config) ->
Ref = make_ref(),
assert_metadata_format([{Ref, list_to_binary(erlang:ref_to_list(Ref))}]).
pid_metadata_formatting(_Config) ->
Pid = spawn(fun() -> ok end),
assert_metadata_format([{Pid, list_to_binary(pid_to_list(Pid))}]).
list_metadata_formatting(_Config) ->
assert_metadata_format([{"string", <<"\"string\"">>},
{[1, 2, 3], <<"[1,2,3]">>},
{[], <<"[]">>},
{[48, [<<"hello">>], 21], <<"[48,[<<\"hello\">>],21]">>}]).
tuple_metadata_formatting(_Config) ->
assert_metadata_format([{{}, <<"{}">>},
{{1}, <<"{1}">>},
{{"hello", there}, <<"{\"hello\",there}">>}]).
map_metadata_formatting(_Config) ->
assert_metadata_format([{#{}, <<"#{}">>},
{#{key => val}, <<"#{key => val}">>}]).
bitstring_metadata_formatting(_Config) ->
assert_metadata_format([{<<1:3>>, <<"<<1:3>>">>}]).
formats_iolist_message_correctly(_Config) ->
IolistMsg = ["alice", ["has" | "a"], <<"cat">>, 20],
Log = lager_msg:new(IolistMsg, erlang:timestamp(), debug, [], []),
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, []),
Gelf = decode(Formatted),
?assertEqual(iolist_to_binary(IolistMsg), maps:get(<<"short_message">>, Gelf)).
on_encode_failure_crashes(_Config) ->
Log = lager_msg:new(<<"strange character: ·">>, erlang:timestamp(), debug, [], []),
Opts = [{on_encode_failure, crash}],
?assertThrow({error, {invalid_string, _}}, lager_graylog_gelf_formatter:format(Log, undefined, Opts)).
on_encode_failure_returns_configured_string(_Config) ->
Log = lager_msg:new(<<"strange character: ·">>, erlang:timestamp(), debug, [], []),
OnFailMessage = "Encoding GELF failed",
Opts = [{on_encode_failure, OnFailMessage}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertEqual(list_to_binary(OnFailMessage), maps:get(<<"short_message">>, Gelf)).
on_encode_failure_returns_configured_binary(_Config) ->
Log = lager_msg:new(<<"strange character: ·">>, erlang:timestamp(), debug, [], []),
OnFailMessage = <<"Encoding GELF failed">>,
Opts = [{on_encode_failure, OnFailMessage}],
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, Opts),
Gelf = decode(Formatted),
?assertEqual(OnFailMessage, maps:get(<<"short_message">>, Gelf)).
on_encode_failure_crashes_if_second_encode_crashes_too(_Config) ->
Log = lager_msg:new(<<"strange character: ·">>, erlang:timestamp(), debug, [], []),
Opts = [{on_encode_failure, <<"this message is invalid, too :( ·">>}],
?assertThrow({error, {invalid_string, _}}, lager_graylog_gelf_formatter:format(Log, undefined, Opts)).
metadata_fun(_) ->
[{meta, "sample"}].
-spec decode(iodata()) -> map().
decode(JSON) when is_binary(JSON) ->
jiffy:decode(JSON, [return_maps]);
decode(JSON) ->
decode(iolist_to_binary(JSON)).
-spec assert_same_timestamp(erlang:timestamp(), float()) -> ok | no_return().
assert_same_timestamp({MegaSecs, Secs, MicroSecs}, UnixTS) ->
?assertEqual((MegaSecs * 1000000) + Secs + (MicroSecs / 1000000), UnixTS),
ok.
-spec assert_metadata_format([{term(), binary()}]) -> ok | no_return().
assert_metadata_format(ValuesWithExpectedFormat) ->
MetadataWithExpectedFormat0 = lists:zip(lists:seq(1, length(ValuesWithExpectedFormat)),
ValuesWithExpectedFormat),
MetadataWithExpectedFormat = lists:map(fun({IntKey, {V, F}}) ->
{list_to_atom(integer_to_list(IntKey)), {V, F}}
end, MetadataWithExpectedFormat0),
MetadataToLog = [{Key, Value} || {Key, {Value, _Format}} <- MetadataWithExpectedFormat],
Log = lager_msg:new("hello", erlang:timestamp(), debug, MetadataToLog, []),
Formatted = lager_graylog_gelf_formatter:format(Log, undefined, []),
Gelf = decode(Formatted),
lists:foreach(fun({Key, {_Value, ExpectedFormat}}) ->
GelfKey = iolist_to_binary(io_lib:format("_~s", [Key])),
?assertEqual(ExpectedFormat, maps:get(GelfKey, Gelf))
end, MetadataWithExpectedFormat).
|
01792ab2c22189d33bde980c0a564570a45175e197c51e7a12786edd8322d487 | chaoxu/fancy-walks | B.hs | {-# OPTIONS_GHC -O2 #-}
import Data.List
import Data.Maybe
import Data.Char
import Data.Array
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Tree
import Data.Graph
parseInput = do
cas <- readInt
replicateM cas $ do
n <- readInt
m <- readInt
edges <- replicateM m $ (,) <$> readInt <*> readInt
return (n, edges)
where
readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
main = do
input <- evalState parseInput <$> BS.getContents
forM_ (zip [1..] input) $ \(cas, (n, edges)) -> do
putStrLn $ "Case #" ++ show cas ++ ": " ++ show (solve n edges)
solve n edges
| comps == 1 = head oddInComps `div` 2
| otherwise = comps + sum [0 `max` (x - 2) | x <- oddInComps] `div` 2
where
swap (a,b) = (b,a)
graph = buildG (0, n-1) (edges ++ map swap edges)
degree = indegree graph
appeared = filter (\x -> (degree ! x) > 0) [0..n-1]
oddInComps = drop (n - length appeared) . sort $ map (length . filter odd . map (degree!) . F.toList) $ components graph
comps = length oddInComps
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/code.google.com/codejam/Code%20Jam%20Africa%20and%20Arabia%202011/Online%20Competition/B.hs | haskell | # OPTIONS_GHC -O2 # |
import Data.List
import Data.Maybe
import Data.Char
import Data.Array
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Tree
import Data.Graph
parseInput = do
cas <- readInt
replicateM cas $ do
n <- readInt
m <- readInt
edges <- replicateM m $ (,) <$> readInt <*> readInt
return (n, edges)
where
readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
main = do
input <- evalState parseInput <$> BS.getContents
forM_ (zip [1..] input) $ \(cas, (n, edges)) -> do
putStrLn $ "Case #" ++ show cas ++ ": " ++ show (solve n edges)
solve n edges
| comps == 1 = head oddInComps `div` 2
| otherwise = comps + sum [0 `max` (x - 2) | x <- oddInComps] `div` 2
where
swap (a,b) = (b,a)
graph = buildG (0, n-1) (edges ++ map swap edges)
degree = indegree graph
appeared = filter (\x -> (degree ! x) > 0) [0..n-1]
oddInComps = drop (n - length appeared) . sort $ map (length . filter odd . map (degree!) . F.toList) $ components graph
comps = length oddInComps
|
14fbba1c3d3565297dc9afc5e30e6c55c3ef6ec9c5a94847b7d0e6b9cf02595a | monadbobo/ocaml-core | common_test.ml | open OUnit;;
open Core.Std
let test =
"common" >:::
[ "% and /%" >::
(fun () ->
let gen_int_pair () = (Quickcheck.uig (), abs (Quickcheck.uig ())) in
let modulus_invariant (a, b) =
let r = a % b in
let q = a /% b in
r >= 0 && a = q * b + r
in
Quickcheck.laws_exn "modulus invariant"
1000 gen_int_pair modulus_invariant
);
"memoize" >::
(fun () ->
let f x = x * x in
let memo_f = Memo.general f in
Quickcheck.laws_exn "memoize"
1000 Quickcheck.uig (fun i -> f i = memo_f i)
);
"nan" >::
(fun () ->
let nan = 0. /. 0. in
"fmin1" @? (Float.is_nan (Float.min 1. nan));
"fmin2" @? (Float.is_nan (Float.min nan 0.));
"fmin3" @? (Float.is_nan (Float.min nan nan));
"fmax1" @? (Float.is_nan (Float.max 1. nan));
"fmax2" @? (Float.is_nan (Float.max nan 0.));
"fmax3" @? (Float.is_nan (Float.max nan nan));
"fmin_inan1" @? (1. = (Float.min_inan 1. nan));
"fmin_inan2" @? (0. = (Float.min_inan nan 0.));
"fmin_inan3" @? (Float.is_nan (Float.min_inan nan nan));
"fmax_inan1" @? (1. = (Float.max_inan 1. nan));
"fmax_inan2" @? (0. = (Float.max_inan nan 0.));
"fmax_inan3" @? (Float.is_nan (Float.max_inan nan nan));
);
"round" >::
(fun () ->
"zero" @? (Float.iround_nearest_exn 0.2 = 0);
"negative zero" @? (Float.iround_nearest_exn (-0.2) = 0);
"positive" @? (Float.iround_nearest_exn 3.4 = 3);
"negative" @? (Float.iround_nearest_exn (-3.4) = -3);
);
]
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/lib_test/common_test.ml | ocaml | open OUnit;;
open Core.Std
let test =
"common" >:::
[ "% and /%" >::
(fun () ->
let gen_int_pair () = (Quickcheck.uig (), abs (Quickcheck.uig ())) in
let modulus_invariant (a, b) =
let r = a % b in
let q = a /% b in
r >= 0 && a = q * b + r
in
Quickcheck.laws_exn "modulus invariant"
1000 gen_int_pair modulus_invariant
);
"memoize" >::
(fun () ->
let f x = x * x in
let memo_f = Memo.general f in
Quickcheck.laws_exn "memoize"
1000 Quickcheck.uig (fun i -> f i = memo_f i)
);
"nan" >::
(fun () ->
let nan = 0. /. 0. in
"fmin1" @? (Float.is_nan (Float.min 1. nan));
"fmin2" @? (Float.is_nan (Float.min nan 0.));
"fmin3" @? (Float.is_nan (Float.min nan nan));
"fmax1" @? (Float.is_nan (Float.max 1. nan));
"fmax2" @? (Float.is_nan (Float.max nan 0.));
"fmax3" @? (Float.is_nan (Float.max nan nan));
"fmin_inan1" @? (1. = (Float.min_inan 1. nan));
"fmin_inan2" @? (0. = (Float.min_inan nan 0.));
"fmin_inan3" @? (Float.is_nan (Float.min_inan nan nan));
"fmax_inan1" @? (1. = (Float.max_inan 1. nan));
"fmax_inan2" @? (0. = (Float.max_inan nan 0.));
"fmax_inan3" @? (Float.is_nan (Float.max_inan nan nan));
);
"round" >::
(fun () ->
"zero" @? (Float.iround_nearest_exn 0.2 = 0);
"negative zero" @? (Float.iround_nearest_exn (-0.2) = 0);
"positive" @? (Float.iround_nearest_exn 3.4 = 3);
"negative" @? (Float.iround_nearest_exn (-3.4) = -3);
);
]
| |
c0db3922ca132ccbcb7420a62f9fdbe6db5407af58e7d1b238927bd9b226054f | mikera/clisk | test_core.clj | (ns clisk.test-core
(:use clojure.test)
(:use clisk.core)
(:use clisk.node)
(:use clisk.functions)
(:require [mikera.vectorz.core :as v])
(:import clisk.Util)
(:import [mikera.vectorz Vector]))
(deftest test-colour
(testing "Colours"
(is (= (unchecked-int 0xFF000000) (Util/toARGB 0.0 0.0 0.0)))
(is (= (unchecked-int 0xFFFF0000) (Util/toARGB 1.0 0.0 0.0)))
(is (= (unchecked-int 0xFFFFFFFF) (Util/toARGB 1.0 1.0 1.0)))))
(deftest test-vector-function
(testing "vector-function"
(is (= (v/of 1 2) ((vector-function [1 2]) [0 0 0 0])))))
(deftest test-sampler
(testing "sampler of [x y z]"
(let [samp (sampler [x y z])]
(is (= [1.0 2.0 3.0] (samp [1 2 3])))
(is (= [1.0 2.0 0.0] (samp [1 2])))))
(testing "scalar sampler"
(let [samp (sampler y)]
(is (== 3.0 (samp [2 3 4 5])))
(is (== 0.0 (samp [2])))))
(testing "extended sampler"
(let [samp (sampler [x y z t '(+ x z) ])]
(is (= [2.0 3.0 4.0 5.0 6.0] (samp [2 3 4 5]))))))
| null | https://raw.githubusercontent.com/mikera/clisk/44dd35fabbae68ad44f0e8ac2dec4c580203f7b9/src/test/clojure/clisk/test_core.clj | clojure | (ns clisk.test-core
(:use clojure.test)
(:use clisk.core)
(:use clisk.node)
(:use clisk.functions)
(:require [mikera.vectorz.core :as v])
(:import clisk.Util)
(:import [mikera.vectorz Vector]))
(deftest test-colour
(testing "Colours"
(is (= (unchecked-int 0xFF000000) (Util/toARGB 0.0 0.0 0.0)))
(is (= (unchecked-int 0xFFFF0000) (Util/toARGB 1.0 0.0 0.0)))
(is (= (unchecked-int 0xFFFFFFFF) (Util/toARGB 1.0 1.0 1.0)))))
(deftest test-vector-function
(testing "vector-function"
(is (= (v/of 1 2) ((vector-function [1 2]) [0 0 0 0])))))
(deftest test-sampler
(testing "sampler of [x y z]"
(let [samp (sampler [x y z])]
(is (= [1.0 2.0 3.0] (samp [1 2 3])))
(is (= [1.0 2.0 0.0] (samp [1 2])))))
(testing "scalar sampler"
(let [samp (sampler y)]
(is (== 3.0 (samp [2 3 4 5])))
(is (== 0.0 (samp [2])))))
(testing "extended sampler"
(let [samp (sampler [x y z t '(+ x z) ])]
(is (= [2.0 3.0 4.0 5.0 6.0] (samp [2 3 4 5]))))))
| |
42cd88c8ff59c81654a24cccebdc71c63943dff6aeb6ddf9016da0a811e13d3f | IUCompilerCourse/public-student-support-code | interp.rkt | #lang racket
(require racket/fixnum)
(require "utilities.rkt" (prefix-in runtime-config: "runtime-config.rkt"))
(provide interp-F1 interp-F2 interp-F3 interp-F4
interp-pseudo-x86-0 interp-x86-0
interp-pseudo-x86-1 interp-x86-1
interp-pseudo-x86-2 interp-x86-2
interp-pseudo-x86-3 interp-x86-3
interp-pseudo-x86-4 interp-x86-4
interp-pseudo-x86-5 interp-x86-5
interp-R6-class-alt
)
;; The interpreters in this file are for the intermediate languages
;; produced by the various passes of the compiler.
;;
The interpreters for the source languages ( Lvar , , ... )
and the C intermediate languages Cvar and
are in separate files , e.g. , .
( define interp - R3 - prime
(lambda (p)
((send (new interp-R3-class) interp-scheme '()) p)))
(define interp-F1
(lambda (p)
((send (new interp-R4-class) interp-F '()) p)))
(define interp-F2
(lambda (p)
((send (new interp-R5-class) interp-F '()) p)))
(define interp-F3
(lambda (p)
((send (new interp-R6-class-alt) interp-F '()) p)))
(define interp-F4
(lambda (p)
((send (new interp-R8-class) interp-F '()) p)))
Interpreters for C2 and C3 .
( define interp - C2
(lambda (p)
(send (new interp-R3-class) interp-C p)))
( define interp - C3
(lambda (p)
(send (new interp-R4-class) interp-C p)))
( define interp - C4
(lambda (p)
(send (new interp-R5-class) interp-C p)))
( define interp - C5
(lambda (p)
(send (new interp-R6-class-alt) interp-C p)))
( define interp - C7
(lambda (p)
(send (new interp-R8-class) interp-C p)))
;; Interpreters for x86 with names that correspond to the book.
;; TODO: update the following names!
(define interp-pseudo-x86-0
(lambda (p)
((send (new interp-R1-class) interp-pseudo-x86 '()) p)))
(define interp-x86-0
(lambda (p)
((send (new interp-R1-class) interp-x86 '()) p)))
(define interp-pseudo-x86-1
(lambda (p)
((send (new interp-R2-class) interp-pseudo-x86 '()) p)))
(define interp-x86-1
(lambda (p)
((send (new interp-R2-class) interp-x86 '()) p)))
(define interp-pseudo-x86-2
(lambda (p)
((send (new interp-R3-class) interp-pseudo-x86 '()) p)))
;; The interp-x86-2 interpreter takes a program of the form
;; (X86Program info blocks)
;; Also, the info field must be an association list
;; with a key 'num-root-spills whose values is
;; the number of spills to the root stack.
(define interp-x86-2
(lambda (p)
((send (new interp-R3-class) interp-x86 '()) p)))
(define interp-pseudo-x86-3
(lambda (p)
((send (new interp-R4-class) interp-pseudo-x86 '()) p)))
;; The interp-x86-3 interpreter requires that the info field of the
;; Def struct be an association list with a key 'num-root-spills whose
;; values is the number of spills to the root stack.
(define interp-x86-3
(lambda (p)
((send (new interp-R4-class) interp-x86 '()) p)))
(define interp-pseudo-x86-4
(lambda (p)
((send (new interp-R6-class-alt) interp-pseudo-x86 '()) p)))
(define interp-x86-4
(lambda (p)
((send (new interp-R6-class-alt) interp-x86 '()) p)))
(define interp-pseudo-x86-5
(lambda (p)
((send (new interp-gradual-class) interp-pseudo-x86 '()) p)))
(define interp-x86-5
(lambda (p)
((send (new interp-gradual-class) interp-x86 '()) p)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Interpreters for R1: integer arithmetic and 'let'
(define interp-R1-class
(class object%
(super-new)
(field (result (gensym 'result)))
;; Hide details for debug output.
(define/public (observe-value v)
v)
(define/public (return-from-tail v env)
(cons (cons result v) env))
(define/public (is-return? e)
(match e
[(cons (cons res v) env) (equal? res result)]
[else #f]))
(define/public (primitives)
(set '+ '- 'read))
(define/public (interp-op op)
(match op
['+ fx+]
['- fx-]
['read read-fixnum]
[else (error "in interp-op R1, unmatched" op)]))
(define/public (interp-scheme-exp env)
(lambda (ast)
(define recur (interp-scheme-exp env))
(verbose "R1/interp-scheme-exp" ast)
(match ast
[(Var x)
(lookup x env)]
[(Int n) n]
[(Let x e body)
(define v (recur e))
((interp-scheme-exp (cons (cons x v) env)) body)]
[(Prim op args)
(apply (interp-op op)
(for/list ([e args]) (recur e)))]
[else
(error (format "R1/no match in interp-scheme-exp for ~a" ast))]
)))
(define/public (interp-scheme env)
(lambda (ast)
(verbose "R1/interp-scheme" ast)
(match ast
[(Program _ e)
((interp-scheme-exp '()) e)]
[else
(error (format "R1/no match in interp-scheme for ~a" ast))]
)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C0
(define/public (interp-C-exp env)
(lambda (ast)
(define result
(match ast
[(Var x) (lookup x env)]
[(Int n) n]
[(Prim op args)
(apply (interp-op op) (map (interp-C-exp env) args))]
[else
(error "C0/interp-C-exp unhandled" ast)]
))
(verbose "C0/interp-C-exp" ast result)
result))
(define/public (interp-C-tail env)
(lambda (ast)
(match ast
[(Return e)
((interp-C-exp env) e)]
( return - from - tail v env ) hmm
[(Seq s t)
(define new-env ((interp-C-stmt env) s))
((interp-C-tail new-env) t)]
[else
(error "interp-C-tail unhandled" ast)]
)))
(define/public (interp-C-stmt env)
(lambda (ast)
(verbose "C0/interp-C-stmt" ast)
(match ast
[(Assign (Var x) e)
(let ([v ((interp-C-exp env) e)])
(cons (cons x v) env))]
[(Prim op args)
((interp-C-exp env) ast)
env]
[else
(error "interp-C-stmt unhandled" ast)]
)))
(define/public (interp-C ast)
(debug "R1/interp-C" ast)
(match ast
[(CProgram info blocks)
(define start (dict-ref blocks 'start))
((interp-C-tail '()) start)]
[else (error "no match in interp-C for " ast)]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; psuedo-x86 and x86
s , d : : = ( var x ) | ( int n ) | ( reg r ) | ( deref r n )
i : : = ( movq s d ) | ( ) | ( subq s d ) | ( imulq s d )
;; | (negq d) | (callq f)
;; psuedo-x86 ::= (program info i ...)
(define/public (get-name ast)
(match ast
[(or (Var x) (Reg x)) x]
[(Deref 'rbp n) n]
[else
(error 'interp-R1-class/get-name "doesn't have a name: ~a" ast)]))
(field [x86-ops (make-immutable-hash
`((addq 2 ,+)
(imulq 2 ,*)
(subq 2 ,(lambda (s d) (- d s)))
(negq 1 ,-)))])
(define/public (interp-x86-op op)
(define (err)
(error 'interp-R1-class/interp-x86-op "unmatched ~a" op))
(cadr (hash-ref x86-ops op err)))
(define/public (interp-x86-exp env)
(lambda (ast)
(copious "interp-x86-exp" ast)
(define result
(match ast
[(or (Var x) (Reg x))
(lookup (get-name ast) env)]
[(Deref r n)
(lookup (get-name ast) env)]
[(Imm n) n]
[else
(error 'interp-R1-class/interp-x86-exp "unhandled ~a" ast)]))
(copious "R1/interp-x86-exp" (observe-value result))
result))
(define/public (interp-x86-instr env)
(lambda (ast)
(when (pair? ast)
(copious "R1/interp-x86-instr" (car ast)))
(match ast
['() env]
[(cons (Callq 'read_int _) ss)
(let ([v (read)])
(copious "read " v)
((interp-x86-instr (cons (cons 'rax v) env)) ss))]
[(cons (Instr 'movq (list s d)) ss)
(define x (get-name d))
(define v ((interp-x86-exp env) s))
(copious "move " (observe-value v))
((interp-x86-instr (cons (cons x v) env)) ss)]
[(cons (Jmp conclusion) ss)
#:when (string-suffix? (symbol->string conclusion) "conclusion")
env]
[(cons (Jmp label) ss)
((interp-x86-block env) (goto-label label))]
[(X86Program info ss)
(let ([env ((interp-x86-instr '()) ss)])
(lookup 'rax env))]
[(cons (Instr binary-op (list s d)) ss)
(let ([s ((interp-x86-exp env) s)]
[d ((interp-x86-exp env) d)]
[x (get-name d)]
[f (interp-x86-op binary-op)])
(let ([v (f s d)])
(copious "binary-op result " (observe-value v))
((interp-x86-instr (cons (cons x v) env)) ss)))]
[(cons (Instr unary-op (list d)) ss)
(let ([d ((interp-x86-exp env) d)]
[x (get-name d)]
[f (interp-x86-op unary-op)])
(let ([v (f d)])
(copious "unary-op result " (observe-value v))
((interp-x86-instr (cons (cons x v) env)) ss)))]
[else (error "R1/interp-x86-instr no match for" ast)]
)))
(define/public (interp-pseudo-x86 env)
(lambda (ast)
((interp-x86 env) ast)))
(define/public (interp-x86-block env)
(lambda (ast)
(match ast
[(Block info ss)
((interp-x86-instr env) ss)]
[else
(error "R1/interp-x86-block unhandled" ast)])))
(define/public (interp-x86 env)
(lambda (ast)
(when (pair? ast)
(copious "R1/interp-x86" (car ast)))
(match ast
[(X86Program info blocks)
(parameterize ([get-basic-blocks blocks])
(define start-block (dict-ref blocks 'start))
(define result-env ((interp-x86-block '()) start-block))
(lookup 'rax result-env))]
[else (error "R1/interp-x86 no match in for" ast)]
)))
)) ;; class interp-R1-class
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Interpreters for R2 : Booleans and conditionals
(define interp-R2-class
(class interp-R1-class
(super-new)
(inherit interp-x86-block observe-value)
(inherit-field x86-ops)
;; We do not include 'and' because it has a funky order of evaluation.
;; -Jeremy
(define/override (primitives)
(set-union (super primitives)
(set 'eq? 'not 'or '< '<= '> '>=)))
(define/override (interp-op op)
(match op
['eq? (lambda (v1 v2)
(cond [(and (fixnum? v1) (fixnum? v2)) (eq? v1 v2)]
[(and (boolean? v1) (boolean? v2)) (eq? v1 v2)]
[else (error 'interp-op "unhandled case")]))]
['and (lambda (v1 v2)
(cond [(and (boolean? v1) (boolean? v2))
(and v1 v2)]
[else (error 'interp-op "unhandled case")]
))]
['not (lambda (v) (match v
[#t #f] [#f #t]
[else (error 'interp-op "unhandled case")]))]
['or (lambda (v1 v2)
(cond [(and (boolean? v1) (boolean? v2))
(or v1 v2)]
[else (error 'interp-op "unhandled case")]))]
['< (lambda (v1 v2)
(cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]
[else (error 'interp-op "unhandled case")]
))]
['<= (lambda (v1 v2)
(cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]
[else (error 'interp-op "unhandled case")]
))]
['> (lambda (v1 v2)
(cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]
[else (error 'interp-op "unhandled case")]
))]
['>= (lambda (v1 v2)
(cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]
[else (error 'interp-op "unhandled case")]
))]
[else (super interp-op op)]))
(define/override (interp-scheme-exp env)
(lambda (ast)
(define recur (interp-scheme-exp env))
(verbose "R2/interp-scheme-exp" ast)
(match ast
[(HasType e t) (recur e)]
[(Bool b) b]
[(Prim 'and (list e1 e2))
(match (recur e1)
[#t (match (recur e2)
[#t #t] [#f #f])]
[#f #f])]
[(If cnd thn els)
(match (recur cnd)
[#t (recur thn)]
[#f (recur els)]
[else
(error 'interp-scheme-exp "R2 expected Boolean, not ~a" cnd)])]
[else ((super interp-scheme-exp env) ast)]
)))
(define/override (interp-C-exp env)
(lambda (ast)
(define result
(match ast
[(HasType e t) ((interp-C-exp env) e)]
[(Bool b) b]
[else ((super interp-C-exp env) ast)]
))
(copious "R2/interp-C-exp" ast result)
result))
(define/override (interp-C-tail env)
(lambda (ast)
(copious "R2/interp-C-tail" ast)
(match ast
[(IfStmt cnd thn els)
(if ((interp-C-exp env) cnd)
((interp-C-tail env) thn)
((interp-C-tail env) els))]
[(Goto label)
((interp-C-tail env) (goto-label label))]
[else ((super interp-C-tail env) ast)]
)))
(define/override (interp-C ast)
(copious "R2/interp-C" ast)
(match ast
[(CProgram info blocks)
(parameterize ([get-basic-blocks blocks])
(super interp-C (CProgram info blocks)))]
[else (error "R2/interp-C unhandled" ast)]
))
(define byte2full-reg
(lambda (r)
(match r
['al 'rax]
['bl 'rbx]
['cl 'rcx]
['dl 'rdx]
)))
(define/override (get-name ast)
(match ast
[(ByteReg r)
(super get-name (Reg (byte2full-reg r)))]
[else (super get-name ast)]))
;; Extending the set of known operators is essentially the
same as overriding the interp - x86 - op with new functionallity
(set! x86-ops (hash-set* x86-ops
'notq `(1 ,bitwise-not)
'andq `(2 ,bitwise-and)
'xorq `(2 ,bitwise-xor)))
(define/override (interp-x86-exp env)
(lambda (ast)
(copious "R2/interp-x86-exp" ast)
(define result
(match ast
[(ByteReg r)
((interp-x86-exp env) (Reg (byte2full-reg r)))]
[(Bool #t) 1]
[(Bool #f) 0]
[(Prim 'eq? (list e1 e2))
(if (eq? ((interp-x86-exp env) e1)
((interp-x86-exp env) e2))
1 0)]
[(Prim '< (list e1 e2))
(if (< ((interp-x86-exp env) e1)
((interp-x86-exp env) e2))
1 0)]
[(Prim '<= (list e1 e2))
(if (<= ((interp-x86-exp env) e1)
((interp-x86-exp env) e2))
1 0)]
[(Prim '> (list e1 e2))
(if (> ((interp-x86-exp env) e1)
((interp-x86-exp env) e2))
1 0)]
[(Prim '>= (list e1 e2))
(if (>= ((interp-x86-exp env) e1)
((interp-x86-exp env) e2))
1 0)]
[else ((super interp-x86-exp env) ast)]
))
(copious "R2/interp-x86-exp" (observe-value result))
result))
(define (eflags-status env cc)
(define eflags ((interp-x86-exp env) (Reg '__flag)))
(match cc
['e (if (equal? eflags 'equal) 1 0)]
['l (if (equal? eflags 'less) 1 0)]
['le
(if (or (eq? 1 (eflags-status env 'e))
(eq? 1 (eflags-status env 'l)))
1 0)]
['g
(if (not (eq? 1 (eflags-status env 'le)))
1 0)]
['ge
(if (not (eq? 1 (eflags-status env 'l)))
1 0)]))
(define/override (interp-x86-instr env)
(lambda (ast)
(when (pair? ast)
(copious "R2/interp-x86-instr" (car ast)))
(match ast
[(Block `(lives ,lives) ss)
((interp-x86-instr env) ss)]
[(Block `(lives ,lives) ss)
((interp-x86-instr env) ss)]
[(cons (Instr 'set (list cc d)) ss)
(define name (get-name d))
(define val (eflags-status env cc))
(verbose "set" cc val)
((interp-x86-instr (cons (cons name val) env)) ss)]
[(cons (IfStmt cnd thn els) ss)
(if (not (eq? 0 ((interp-x86-exp env) cnd)))
((interp-x86-instr env) (append thn ss))
((interp-x86-instr env) (append els ss)))]
Notice that the argument order of cmpq is confusing :
( cmpq , s2 , s1 ) ( jl thn ) ( jmp els )
;; is eqivalent to
( if ( < s1 s2 ) thn els )
[(cons (Instr 'cmpq (list s2 s1)) ss)
(let* ([v1 ((interp-x86-exp env) s1)]
[v2 ((interp-x86-exp env) s2)]
[eflags
(cond [(< v1 v2) 'less]
[(> v1 v2) 'greater]
[else 'equal])])
((interp-x86-instr (cons (cons '__flag eflags) env)) ss))]
[(cons (Instr 'movzbq (list s d)) ss)
(define x (get-name d))
(define v ((interp-x86-exp env) s))
((interp-x86-instr (cons (cons x v) env)) ss)]
[(cons (JmpIf cc label) ss)
(cond [(eq? (eflags-status env cc) 1)
((interp-x86-block env) (goto-label label))]
[else ((interp-x86-instr env) ss)])]
[else ((super interp-x86-instr env) ast)]
)))
));; class interp-R2-class
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Interpreters for R3: Vectors
(define interp-R3-class
(class interp-R2-class
(super-new)
(inherit get-name interp-x86-op interp-x86-block observe-value)
(inherit-field x86-ops)
;; The simulated global state of the program
;; define produces private fields
(define memory (box '()))
;; field is like define but public
(field [stack-size (runtime-config:rootstack-size)]
[heap-size (runtime-config:heap-size)]
[uninitialized 'uninitialized-value-from-memory]
[fromspace_begin (box uninitialized)]
[rootstack_end (box uninitialized)]
[free_ptr (box uninitialized)]
[fromspace_end (box uninitialized)]
[rootstack_begin (box uninitialized)]
[global-label-table
(make-hash
`((free_ptr . ,free_ptr)
(fromspace_begin . ,fromspace_begin)
(fromspace_end . ,fromspace_end)
(rootstack_begin . ,rootstack_begin)
(rootstack_end . ,rootstack_end)))])
(define/public (memory-read)
(lambda (addr)
(let-values ([(start stop name vect) (fetch-page addr)])
(let ([value (vector-ref vect (arithmetic-shift (- addr start) -3))])
(when (equal? value uninitialized)
(error 'interp-R3-class/memory-read
"read uninitialized memory at address ~s"
addr))
value))))
(define/public (memory-write!)
(lambda (addr value)
(let-values ([(start stop name vect) (fetch-page addr)])
(vector-set! vect (arithmetic-shift (- addr start) -3) value))))
(define/public (collect!)
(lambda (rootset bytes-requested)
(verbose "collect!" bytes-requested)
;; after a call to collect we must guarantee there is enough
;; memory to allocate the requested block of memory
(let double-heap ([hs heap-size])
(if (< hs bytes-requested)
(double-heap (* 2 hs))
(let ((h-begin (allocate-page! 'fromspace hs)))
;; I am only advancing the end of the heap because we
;; are not reclaiming memory
(set-box! fromspace_end (+ h-begin hs))
(set-box! free_ptr h-begin))))))
(define/public (initialize!)
(lambda (stack-length heap_length)
(verbose "initialize!")
(set-box! memory '())
(let* ([s-begin (allocate-page! 'rootstack stack-size)]
[h-begin (allocate-page! 'fromspace heap-size)])
(set-box! rootstack_begin s-begin)
(set-box! rootstack_end (+ s-begin stack-size))
(set-box! fromspace_begin h-begin)
(set-box! fromspace_end (+ h-begin heap-size))
(set-box! free_ptr h-begin))))
(define (allocate-page! name size)
(verbose "allocate-page!" name size)
(unless (and (fixnum? size)
(positive? size)
(= 0 (modulo size 8)))
(error 'allocate-page! "expected non-negative fixnum in ~a" size))
;; Find the last address
(define max-addr
(for/fold ([next 8])
([page (in-list (unbox memory))])
(match-let ([`(page ,_ ,stop ,_ ,_) page])
(max next stop))))
Allocate with a small pad 100 words so that it is n't likely to
;; accidentally use another region.
The randomness is to dispell any reliance on interp always allocating
;; the same way. -Andre
(define start-addr (+ max-addr 800))
;; The range is of valid addresses in memory are [start, stop)
(define stop-addr (+ start-addr size))
(define vect (make-vector (arithmetic-shift size -3) uninitialized))
(verbose "allocated" name start-addr stop-addr)
(set-box! memory (cons `(page ,start-addr ,stop-addr ,name ,vect)
(unbox memory)))
start-addr)
(define (free! addr)
(set-box! memory
(let loop ([memory (unbox memory)])
(match memory
[`() (error 'free "invalid address ~a, not currently allocated")]
[`(,(and page `(page ,ptr ,_ ,_ ,_)) . ,pages)
(if (= addr ptr)
pages
(cons page (loop pages)))]))))
(define (fetch-page addr)
;; Create a string containing
(define (fmt-err addr memory)
(apply
string-append
(cons (format "address ~a out of bounds\n\tcurrent memory regions:\n"
addr)
(for/list ([page (in-list (unbox memory))])
(match-let ([`(page ,start ,stop ,name ,_) page])
(format "\t\t~a\t\t[~a,~a)\n" name start stop))))))
(unless (fixnum? addr)
(error 'fetch-page "invalid address ~a, not a fixnum" addr))
(unless (positive? addr)
(error 'fetch-page "invalid address ~a, negative" addr))
(unless (= 0 (modulo addr 8))
(error 'fetch-page "invalid address ~a, not 8-byte aligned" addr))
(let search ([m (unbox memory)])
(match m
[`() (error 'fetch-page (fmt-err addr memory))]
[`((page ,min ,max ,name ,vect) . ,rest-memory)
;(copious "R3/fetch page" addr min max name vect)
; vect is too large to print, makes things hard to read.
;(copious "R3/fetch page" addr min max name)
(if (and (<= min addr) (< addr max))
(values min max name vect)
(search rest-memory))]
[other (error 'fetch-page "unmatched ~a" m)])))
(define/override (primitives)
(set-union (super primitives)
(set 'vector 'vector-ref 'vector-set! vector-length
todo : move the following to a different interpreter
'vector-proxy)))
(define/override (interp-op op)
(match op
['eq? (lambda (v1 v2)
(cond [(or (and (fixnum? v1) (fixnum? v2))
(and (boolean? v1) (boolean? v2))
(and (vector? v1) (vector? v2))
(and (void? v1) (void? v2)))
(eq? v1 v2)]))]
['vector-proxy
(lambda (vec rs ws)
`(vector-proxy ,vec ,rs ,ws))]
['vector vector]
['vector-length vector-length]
['vector-ref vector-ref]
['vector-set! vector-set!]
#;['vector-proxy-set! vector-set!]
[else (super interp-op op)]))
#;(define/public (scheme-vector-ref vec i)
(match vec
[`(vector-proxy ,v ,rs ,ws)
(define v^ (scheme-vector-ref v i))
(define r (vector-ref rs i))
(apply-fun (lambda (env) (interp-scheme-exp env))
r (list v^))]
[else
(vector-ref vec i)]))
( define / public ( scheme - vector - set ! i arg )
(match vec
[`(vector-proxy ,v ,rs ,ws)
(define w (vector-ref ws i))
(define arg^ (apply-fun (lambda (env) (interp-scheme-exp env))
w (list arg)))
(scheme-vector-set! v i arg^)]
[else
(vector-set! vec i arg)]))
(define/override (interp-scheme-exp env)
(lambda (ast)
(define recur (interp-scheme-exp env))
(verbose "R3/interp-scheme" ast)
(match ast
[(Void) (void)]
[(GlobalValue 'free_ptr)
(unbox free_ptr)]
[(GlobalValue 'fromspace_end)
(unbox fromspace_end)]
[(Allocate l ty) (build-vector l (lambda a uninitialized))]
[(AllocateClosure l ty arity)
(define vec (build-vector (add1 l) (lambda a uninitialized)))
(vector-set! vec l `(arity ,arity))
vec]
[(AllocateProxy ty) (build-vector 3 (lambda a uninitialized))]
[(Collect size)
(unless (exact-nonnegative-integer? size)
(error 'interp-C "invalid argument to collect in ~a" ast))
(void)]
#;[`(vector-ref ,e-vec ,e-i)
(define vec (recur e-vec))
(define i (recur e-i))
(scheme-vector-ref vec i)]
#;[`(vector-set! ,e-vec ,e-i ,e-arg)
(define vec (recur e-vec))
(define i (recur e-i))
(define arg (recur e-arg))
(scheme-vector-set! vec i arg)]
[else ((super interp-scheme-exp env) ast)]
)))
(define/override (interp-scheme env)
(lambda (ast)
(verbose "R3/interp-scheme" ast)
(match ast
[(Program info e)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
((interp-scheme-exp '()) e)]
[else ((super interp-scheme env) ast)]
)))
(define (mem-error message expr)
(lambda (who fmt . args)
(error who "~a in ~a raise error:\n~a"
message expr
(apply format (cons fmt args)))))
(define (global-value-err ast)
(lambda ()
(error 'interp-R3-class "global label is unknown in ~a" ast)))
(define/public (fetch-global label)
(let* ([err (global-value-err label)]
[ref (hash-ref global-label-table label err)]
[value (unbox ref)])
(when (equal? value uninitialized)
(debug "fetch" global-label-table)
(error 'interp-R3-class/fetch-global
"global value, ~a, used before initialization"
label))
value))
(define/override (interp-C-exp env)
(lambda (ast)
(define result
(match ast
[(Void) (void)]
[(GlobalValue 'free_ptr)
(unbox free_ptr)]
[(GlobalValue 'fromspace_end)
(unbox fromspace_end)]
[(CollectionNeeded? size)
(when (or (eq? (unbox free_ptr) uninitialized)
(eq? (unbox fromspace_end) uninitialized))
(error 'interp-C "uninitialized state in ~a" ast))
#t]
;; allocate a vector of length l and type t that is initialized.
[(Allocate l ty) (build-vector l (lambda a uninitialized))]
[(AllocateClosure l ty arity)
(define vec (build-vector (add1 l) (lambda a uninitialized)))
(vector-set! vec l `(arity ,arity))
vec]
#;[(AllocateClosure l ty arity)
(build-vector l (lambda a uninitialized))]
[(AllocateProxy ty) (build-vector 3 (lambda a uninitialized))]
[else
((super interp-C-exp env) ast)]
))
(copious "R3/interp-C-exp" ast result)
result))
(define/override (interp-C-stmt env)
(lambda (ast)
(copious "R3/interp-C-stmt" ast)
(match ast
;; Determine if a collection is needed.
;; Which it isn't because vectors stored in the environment
;; is the representation of the heap in the C language,
;; but collection is a no-op so we should check to see if
;; everything is well formed anyhow.
;; Collection isn't needed or possible in this representation
[(Collect size)
(unless (exact-nonnegative-integer? size)
(error 'interp-C "invalid argument to collect in ~a" ast))
env]
[else
((super interp-C-stmt env) ast)]
)))
(define/override (interp-C-tail env)
(lambda (ast)
(copious "R3/interp-C-tail" ast)
(match ast
[(Seq s t)
(define new-env ((interp-C-stmt env) s))
((interp-C-tail new-env) t)]
[else ((super interp-C-tail env) ast)])))
(define/override (interp-C ast)
(copious "R3/interp-C" ast)
(match ast
[(CProgram info blocks)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(super interp-C (CProgram info blocks))]
[else (error "R3/interp-C unhandled" ast)]))
(define/override (interp-x86-exp env)
(lambda (ast)
(copious "interp-x86-exp" ast)
(define result
(match ast
[(Global label) (fetch-global label)]
[(Deref r i) #:when (not (eq? r 'rbp))
(define base ((interp-x86-exp env) (Reg r)))
(define addr (+ base i))
((memory-read) addr)]
[else ((super interp-x86-exp env) ast)]))
(copious "R3/interp-x86-exp" (observe-value result))
result))
(define/public (interp-x86-store env)
(lambda (ast value)
(copious "interp-x86-store" ast (observe-value value))
(match ast
[(Global label)
(define loc (hash-ref global-label-table label
(global-value-err ast)))
(set-box! loc value)
env]
[(Deref r i)
#:when (not (eq? r 'rbp))
(define base ((interp-x86-exp env) (Reg r)))
(define addr (+ base i))
((memory-write!) addr value)
env]
[dest
(define name (get-name dest))
(cons (cons name value) env)])))
(define (x86-binary-op? x)
(let ([val (hash-ref x86-ops x #f)])
(and val (= (car val) 2))))
(define (x86-unary-op? x)
(let ([val (hash-ref x86-ops x #f)])
(and val (= (car val) 1))))
(define/override (interp-x86-instr env)
(lambda (ast)
(when (pair? ast)
(copious "R3/interp-x86-instr" (car ast)))
(match ast
[ ( cons ( Callq ' malloc ) ss )
(define num-bytes ((interp-x86-exp env) (Reg 'rdi)))
((interp-x86-instr
`((rax . ,(allocate-page! 'malloc num-bytes)) . ,env))
ss)]
[ ( cons ( ' alloc ) ss )
(define num-bytes ((interp-x86-exp env) (Reg 'rdi)))
((interp-x86-instr
`((rax . ,(allocate-page! 'alloc num-bytes)) . ,env))
ss)]
[(cons (Callq 'collect _) ss)
(define rootstack ((interp-x86-exp env) (Reg 'rdi)))
(define bytes-requested ((interp-x86-exp env) (Reg 'rsi)))
((collect!) rootstack bytes-requested)
((interp-x86-instr env) ss)]
[(cons (Instr 'movq (list s d)) ss)
(define value ((interp-x86-exp env) s))
(define new-env ((interp-x86-store env) d value))
((interp-x86-instr new-env) ss)]
[(cons (Instr (? x86-binary-op? binop) (list s d)) ss)
(define src ((interp-x86-exp env) s))
(define dst ((interp-x86-exp env) d))
(define op (interp-x86-op binop))
(define new-env ((interp-x86-store env) d (op src dst)))
((interp-x86-instr new-env) ss)]
[(cons (Instr (? x86-unary-op? unary-op) (list d)) ss)
(define dst ((interp-x86-exp env) d))
(define op (interp-x86-op unary-op))
(define new-env ((interp-x86-store env) d (op dst)))
((interp-x86-instr new-env) ss)]
[else
((super interp-x86-instr env) ast)]
)))
;; before register allocation
(define/override (interp-pseudo-x86 env)
(lambda (ast)
(copious "R3/interp-pseudo-x86" ast)
(match ast
[(X86Program info blocks)
;(define ty (dict-ref info 'type))
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(define env (cons (cons 'r15 (unbox rootstack_begin)) '()))
(parameterize ([get-basic-blocks blocks])
(let ([env^ ((interp-x86-block env) (dict-ref blocks 'start))])
(lookup 'rax env^)))]
)))
;; after register allocation
(define/override (interp-x86 env)
(lambda (ast)
(copious "R3/interp-x86" ast)
(match ast
[(X86Program info blocks)
;;#:when (dict-has-key? info 'num-spills)
(define root-spills (dict-ref info 'num-root-spills))
(define variable-size 8) ;; ugh -Jeremy
(define root-space (* variable-size root-spills))
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(define env (cons (cons 'r15 (+ root-space (unbox rootstack_begin)))
'()))
(parameterize ([get-basic-blocks blocks])
(let ([env^ ((interp-x86-block env) (dict-ref blocks 'start))])
(lookup 'rax env^)))]
)))
(set! x86-ops
(hash-set* x86-ops
'sarq `(2 ,(lambda (n v) (arithmetic-shift v (- n))))
'salq `(2 ,(lambda (n v)
(crop-to-64bits (arithmetic-shift v n))))
'orq `(2 ,bitwise-ior)
))
));; interp-R3-class
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Interpreters for R4 : functions
(define interp-R4-class
(class interp-R3-class
(super-new)
(inherit primitives interp-op initialize!
return-from-tail interp-x86-block memory-read memory-write!
interp-x86-store)
(inherit-field result rootstack_begin free_ptr fromspace_end
uninitialized global-label-table)
(define/public (apply-fun interp fun-val arg-vals)
(match fun-val
#;[`(tagged ,fun-val^ ,t) ;; for dynamically typed
(apply-fun interp fun-val^ arg-vals)]
[(Function xs body lam-env)
(define new-env (append (map cons xs arg-vals) lam-env))
((interp new-env) body)]
[else (error 'apply-fun "expected function, not ~a" fun-val)]))
(define/public (non-apply-ast)
(set-union (primitives)
(set 'if 'let 'define 'program 'has-type 'void)))
(define/public (interp-scheme-def d)
(match d
[(Def f `([,xs : ,ps] ...) rt info body)
(mcons f (Function xs body '()))]
))
(define/override (interp-scheme-exp env)
(lambda (ast)
(verbose "R4/interp-scheme" ast)
(define recur (interp-scheme-exp env))
(match ast
[(Apply fun args)
(define fun-val (recur fun))
(define new-args (for/list ([e args]) (recur e)))
(apply-fun (lambda (env) (interp-scheme-exp env)) fun-val new-args)]
[else ((super interp-scheme-exp env) ast)]
)))
(define/override (interp-scheme env)
(lambda (ast)
(verbose "R4/interp-scheme" ast)
(match ast
#;[`(program (type ,ty) ,ds ... ,body)
((interp-scheme '()) `(program ,@ds ,body))]
[(Program info (cons ds body))
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(let ([top-level (for/list ([d ds]) (interp-scheme-def d))])
(for ([b top-level])
(set-mcdr! b (match (mcdr b)
[(Function xs body '())
(Function xs body top-level)])))
((interp-scheme-exp top-level) body))]
[else ((super interp-scheme env) ast)]
)))
#;(define/public (F-vector-ref vec i)
(match vec
[`(vector-proxy ,v ,rs ,ws)
(define v^ (F-vector-ref v i))
(define r (vector-ref rs i))
(apply-fun (lambda (env) (interp-F env))
r (list v^))]
[else
(vector-ref vec i)]))
( define / public ( F - vector - set ! i arg )
(match vec
[`(vector-proxy ,v ,rs ,ws)
(define w (vector-ref ws i))
(define arg^ (apply-fun (lambda (env) (interp-F env))
w (list arg)))
(F-vector-set! v i arg^)]
[else
(vector-set! vec i arg)]))
(define/public (interp-F env)
(lambda (ast)
(define result
(match ast
For R4
[(Def f `([,xs : ,ps] ...) rt info body)
(cons f (Function xs body '()))]
[(FunRef f n)
(lookup f env)]
[(Apply fun args)
(define fun-val ((interp-F env) fun))
(define arg-vals (map (interp-F env) args))
(match fun-val
[(Function xs body fenv)
(define new-env (append (map cons xs arg-vals) env))
((interp-F new-env) body)]
[else (error "interp-F, expected function, not" fun-val)])]
[(ProgramDefs info ds)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(let ([top-level (map (interp-F '()) ds)])
((interp-F top-level) (Apply (Var 'main) '())))]
;; For R3
[(GlobalValue 'free_ptr)
(unbox free_ptr)]
[(GlobalValue 'fromspace_end)
(unbox fromspace_end)]
[(Allocate l ty) (build-vector l (lambda a uninitialized))]
[(AllocateClosure l ty arity)
(define vec (build-vector (add1 l) (lambda a uninitialized)))
(vector-set! vec l `(arity ,arity))
vec]
#;[(AllocateClosure l ty arity)
(build-vector l (lambda a uninitialized))]
[(AllocateProxy ty) (build-vector 3 (lambda a uninitialized))]
[(Collect size)
(unless (exact-nonnegative-integer? size)
(error 'interp-F "invalid argument to collect in ~a" ast))
(void)]
[(Void) (void)]
For R2
[(HasType e t) ((interp-F env) e)]
[(Bool b) b]
[(Prim 'and (list e1 e2))
(match ((interp-F env) e1)
[#t (match ((interp-F env) e2)
[#t #t] [#f #f])]
[#f #f])]
[(If cnd thn els)
(if ((interp-F env) cnd)
((interp-F env) thn)
((interp-F env) els))]
;; For R1
[(Var x)
(lookup x env)]
[(Int n) n]
[(Let x e body)
(let ([v ((interp-F env) e)])
((interp-F (cons (cons x v) env)) body))]
[(Prim op args)
(apply (interp-op op) (for/list ([e args]) ((interp-F env) e)))]
[(Apply f args)
((interp-F env) (Apply f args))]
[else
(error 'interp-F "R4 unmatched ~a" ast)]
))
(verbose "R4/interp-F" ast result)
result
))
(define/override (interp-C-exp env)
(lambda (ast)
(define result
(match ast
[(FunRef f n)
(lookup f env)]
[(Call f args)
(define arg-vals (map (interp-C-exp env) args))
(define f-val ((interp-C-exp env) f))
(match f-val
[(CFunction xs info blocks def-env)
(define f (dict-ref info 'name))
(define f-start (symbol-append f 'start))
(define new-env (append (map cons xs arg-vals) def-env))
(parameterize ([get-basic-blocks blocks])
((interp-C-tail new-env) (dict-ref blocks f-start)))]
[else (error "interp-C, expected a function, not" f-val)])]
[else
((super interp-C-exp env) ast)]
))
(verbose "R4/interp-C-exp" ast result)
result))
(define/override (interp-C-tail env)
(lambda (ast)
(define result
(match ast
[(TailCall f args)
(define arg-vals (map (interp-C-exp env) args))
(define f-val ((interp-C-exp env) f))
(match f-val
[(CFunction xs info blocks def-env)
(define f (dict-ref info 'name))
(define f-start (symbol-append f 'start))
(define new-env (append (map cons xs arg-vals) def-env))
(parameterize ([get-basic-blocks blocks])
((interp-C-tail new-env) (dict-ref blocks f-start)))]
[else (error "interp-C, expected a funnction, not" f-val)])]
[else
((super interp-C-tail env) ast)]
))
(verbose "R4/interp-C-tail" ast result)
result))
(define/public (interp-C-def ast)
(verbose "R4/interp-C-def" ast)
(match ast
[(Def f `([,xs : ,ps] ...) rt info blocks)
(mcons f (CFunction xs `((name . ,f)) blocks '()))]
[else
(error "R4/interp-C-def unhandled" ast)]
))
(define/override (interp-C ast)
(verbose "R4/interp-C" ast)
(match ast
[(ProgramDefs info ds)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(define top-level (for/list ([d ds]) (interp-C-def d)))
;; tie the knot
(for/list ([b top-level])
(set-mcdr! b (match (mcdr b)
[(CFunction xs info blocks '())
(CFunction xs info blocks top-level)])))
((interp-C-tail top-level) (TailCall (Var 'main) '()))]
[else
(error "R4/interp-C unhandled" ast)]
))
(define (stack-arg-name n)
(string->symbol (string-append "rsp_" (number->string n))))
(define/public (builtin-funs)
(set 'malloc 'alloc 'collect 'initialize 'read_int 'exit))
(define/override (get-name ast)
(match ast
[(StackArg n) (stack-arg-name n)]
[else (super get-name ast)]))
;; Hide function details to avoid spamming the debug output.
(define/override (observe-value v)
(match v
[(X86Function info blocks def-env)
`(function ,(dict-ref info 'name))]
[else v]))
(define root-stack-pointer 0)
(define/public (call-function f-val cont-ss env)
(match f-val
[(X86Function info blocks def-env)
(debug "interp-x86 call-function" (observe-value f-val))
(define n (dict-ref info 'num-params))
(define f (dict-ref info 'name))
(define root-spills (dict-ref info 'num-root-spills #f))
;; copy argument registers over to new-env
(define passing-regs
(filter (lambda (p) p)
(for/list ([r (vector-take arg-registers n)])
(let ([v (lookup r env #f)])
(if v (cons r v) #f)))))
(debug "interp-x86 call-function" passing-regs)
(define variable-size 8) ;; ugh -Jeremy
(define root-size
(cond [root-spills (* variable-size root-spills)]
[else 0]))
(set! root-stack-pointer (+ root-stack-pointer root-size))
(define new-env (cons (cons 'r15 root-stack-pointer)
(append passing-regs def-env)))
;; interpret the body of the function in the new-env
(define result-env
(parameterize ([get-basic-blocks blocks])
((interp-x86-block new-env)
(dict-ref blocks (symbol-append f 'start)))))
(set! root-stack-pointer (- root-stack-pointer root-size))
(define res (lookup 'rax result-env))
;; return and continue after the function call, back in env
((interp-x86-instr (cons (cons 'rax res) env)) cont-ss)]
[else (error "interp-x86, expected a function, not" f-val)]))
(define/override (interp-x86-exp env)
(lambda (ast)
(copious "R4/interp-x86-exp" ast)
(define result
(match ast
[(StackArg n)
(define x (stack-arg-name n))
(lookup x env)]
#;[(FunRef f n)
(lookup f env)]
[else ((super interp-x86-exp env) ast)]))
(copious "R4/interp-x86-exp" (observe-value result))
result))
( define ( apply - vector - ref vec i cont - ss env )
(define tag ((memory-read) vec))
(verbose 'apply-vector-ref ((memory-read) vec))
(cond [(equal? (arithmetic-shift tag -63) 1)
(define vec^ ((memory-read) (+ vec (* 1 8))))
(define val^ (apply-vector-ref vec^ i '() env))
(define read-clos ((memory-read) (+ vec (* 2 8))))
(apply-closure read-clos val^ cont-ss env)]
[else
(define res ((memory-read) (+ vec (* (add1 i) 8))))
((interp-x86-instr (cons (cons 'rax res) env)) cont-ss)]
))
( define ( apply - vector - set ! vec i val cont - ss env )
(define tag ((memory-read) vec))
(cond [(equal? (arithmetic-shift tag -63) 1)
(define write-clos ((memory-read) (+ vec (* 3 8))))
(define val^ (apply-closure write-clos val '() env))
(apply-vector-set! vec i val^ cont-ss env)]
[else
((memory-write!) (+ vec (* (add1 i) 8)) val)
((interp-x86-instr env) cont-ss)]
))
(define/override (interp-x86-instr env)
(lambda (ast)
(when (pair? ast)
(copious "R4/interp-x86-instr" (car ast)))
(match ast
Treat leaq like movq -Jeremy
[(cons (Instr 'leaq (list s d)) ss)
(define value ((interp-x86-exp env) s))
(define new-env ((interp-x86-store env) d value))
((interp-x86-instr new-env) ss)]
[(cons (IndirectCallq f _) ss)
(debug "indirect callq" ast)
(define f-val ((interp-x86-exp env) f))
(call-function f-val ss env)]
[(cons (TailJmp f n) ss)
(debug "tail jmp" ast)
(define f-val ((interp-x86-exp env) f))
(call-function f-val '() env)]
[(cons (Callq f _) ss)
#:when (not (set-member? (builtin-funs) f))
(call-function (lookup f env) ss env)]
[(cons (Callq 'exit _) ss)
(error 'interp-x86 "exiting")]
[else
((super interp-x86-instr env) ast)]
)))
(define/public (interp-x86-def ast)
(match ast
[(Def f ps rt info blocks)
(cons f (X86Function (dict-set info 'name f) blocks '()))]
))
;; The below applies before register allocation
(define/override (interp-pseudo-x86 env)
(lambda (ast)
(copious "R4/interp-pseudo-x86" ast)
(match ast
[(ProgramDefs info ds)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(set! root-stack-pointer (unbox rootstack_begin))
(define top-level (for/list ([d ds]) (interp-x86-def d)))
;; Put the functions in the globals table
(for ([(label fun) (in-dict top-level)])
(dict-set! global-label-table label (box fun)))
(define env^ (list (cons 'r15 (unbox rootstack_begin))))
(define result-env (call-function (lookup 'main top-level) '() env^))
(lookup 'rax result-env)]
)))
;; The below applies after register allocation -Jeremy
(define/override (interp-x86 env)
(lambda (ast)
(verbose "R4/interp-x86" ast)
(match ast
[(ProgramDefs info ds)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(set! root-stack-pointer (unbox rootstack_begin))
(define top-level (for/list ([d ds]) (interp-x86-def d)))
;; Put the functions in the globals table
(for ([(label fun) (in-dict top-level)])
(dict-set! global-label-table label (box fun)))
(define env^ '())
(define result-env
(call-function (lookup 'main top-level) '() env^))
(lookup 'rax result-env)]
)))
)) ;; end interp-R4-class
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Interpreters for R5: lambda
(define interp-R5-class
(class interp-R4-class
(super-new)
(inherit initialize! return-from-tail apply-fun)
(inherit-field result)
(define/override (primitives)
(set-union (super primitives)
(set 'procedure-arity)))
(define/override (non-apply-ast)
(set-union (super non-apply-ast)
(set 'global-value 'allocate 'collect)))
(define/override (interp-op op)
(match op
['procedure-arity (lambda (v)
(match v
[(Function xs body lam-env)
(length xs)]
[(vector (Function ps body env) vs ... `(arity ,n))
n]
[else
(error 'interp-op "expected function, not ~a" v)]
))]
[else (super interp-op op)]
))
(define/override (interp-scheme-exp env)
(lambda (ast)
(verbose "R5/interp-scheme" ast)
(match ast
[(Lambda `([,xs : ,Ts] ...) rT body)
(Function xs body env)]
[else ((super interp-scheme-exp env) ast)]
)))
(define/override (interp-F env)
(lambda (ast)
(define result
(match ast
[(Lambda `([,xs : ,Ts] ...) rT body)
(Function xs body env)]
[(Def f `([,xs : ,ps] ...) rt info body)
(mcons f (Function xs body '()))]
[(ProgramDefs info ds)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(let ([top-level (map (interp-F '()) ds)])
;; tie the knot
(for/list ([b top-level])
(set-mcdr! b (match (mcdr b)
[(Function xs body '())
(Function xs body top-level)])))
((interp-F top-level) (Apply (Var 'main) '())))]
[(Closure arity args)
(define arg-vals (map (interp-F env) args))
(apply vector (append arg-vals (list `(arity ,arity))))]
[(Apply fun args)
(define fun-val ((interp-F env) fun))
(define arg-vals (map (interp-F env) args))
(apply-fun (lambda (env) (interp-F env)) fun-val arg-vals)]
[else ((super interp-F env) ast)]
))
(verbose "R5/interp-F result of" ast result)
result))
end interp - R5 - class
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Interpreters for R6: type Any and inject/project
(define (crop-to-64bits n)
(let ([s (string->list (number->string n 2))])
(cond [(> (length s) 64)
(let ([s^ (list-tail s (- (length s) 64))])
(string->number (list->string s^) 2))]
[else n])))
(define interp-R6-class-alt
(class interp-R5-class
(super-new)
(inherit initialize!)
(inherit-field result)
(define/override (primitives)
(set-union (super primitives)
(set 'boolean? 'integer? 'vector? 'procedure?
'tag-of-any 'value-of-any 'tag-of-vector)))
(define/override (interp-op op)
(match op
['boolean? (lambda (v)
(match v
[`(tagged ,v1 Boolean) #t]
[else #f]))]
['integer? (lambda (v)
(match v
[`(tagged ,v1 Integer) #t]
[else #f]))]
['vector? (lambda (v)
(match v
[`(tagged ,v1 (Vector ,ts ...)) #t]
[else #f]))]
['procedure? (lambda (v)
(match v
[`(tagged ,v1 (,ts ... -> ,rt)) #t]
[else #f]))]
['eq? (lambda (v1 v2)
(match (list v1 v2)
[`((tagged ,v1^ ,ty1) (tagged ,v2^ ,ty2))
(and (eq? v1^ v2^) (equal? ty1 ty2))]
[else
(cond [(or (and (fixnum? v1) (fixnum? v2))
(and (boolean? v1) (boolean? v2))
(and (vector? v1) (vector? v2))
(and (void? v1) (void? v2)))
(eq? v1 v2)])]))]
['make-any (lambda (v tg) `(tagged ,v ,tg))]
['tag-of-any (lambda (v)
(match v
[`(tagged ,v^ ,tg)
tg]
[else
(error "interp expected tagged value, not" v)]))]
['value-of-any (lambda (v)
(match v
[`(tagged ,v^ ,tg)
v^]
[else
(error "interp expected tagged value, not" v)]))]
['tag-of-vector (lambda (v)
(match v
[`(vector-proxy ,vec ,rs ,ws) 1]
[else 0]))]
['any-vector-ref (lambda (v i)
(match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
['any-vector-set! (lambda (v i a)
(match v [`(tagged ,v^ ,tg)
(vector-set! v^ i a)]))]
['any-vector-length (lambda (v)
(match v [`(tagged ,v^ ,tg)
(vector-length v^)]))]
['any-vectorof-length (lambda (v)
(match v [`(tagged ,v^ ,tg)
(vector-length v^)]))]
[else (super interp-op op)]
))
;; Equality for flat types.
(define/public (tyeq? t1 t2)
(match `(,t1 ,t2)
[`((Vectorof Any) (Vector ,t2s ...))
(for/and ([t2 t2s])
(eq? t2 'Any))]
[`((Vector ,t1s ...) (Vectorof Any))
(for/and ([t1 t1s])
(eq? t1 'Any))]
[else (equal? t1 t2)]))
(define/override (interp-scheme-exp env)
(lambda (ast)
(verbose "R6/interp-scheme" ast)
(define recur (interp-scheme-exp env))
(match ast
[(Inject e t)
`(tagged ,(recur e) ,t)]
[(Project e t2)
(define v (recur e))
(match v
[`(tagged ,v1 ,t1)
(cond [(tyeq? t1 t2) v1]
[else (error "in project, type mismatch" t1 t2)])]
[else (error "in project, expected injected value" v)])]
[else
((super interp-scheme-exp env) ast)]
)))
(define/override (interp-F env)
(lambda (ast)
(define recur (interp-F env))
(define result
(match ast
[(Inject e t)
`(tagged ,(recur e) ,t)]
[(Project e t2)
(define v (recur e))
(match v
[`(tagged ,v1 ,t1)
(cond [(tyeq? t1 t2) v1]
[else (error "in project, type mismatch" t1 t2)])]
[else (error "in project, expected injected value" v)])]
[(ValueOf e ty)
(define v ((interp-F env) e))
((interp-op 'value-of-any) v)]
The following belongs in a new R7 interp class
[(Def f xs _ info body)
#:when (andmap symbol? xs)
#;(define anys (for/list ([x xs]) 'Any))
#;(mcons f `(tagged (lambda ,xs ,body) (,anys -> Any)))
(mcons f (Function xs body '()))]
[(Lambda xs _ body)
#:when (andmap symbol? xs)
#;(define anys (for/list ([x xs]) 'Any))
#;`(tagged ,(lambda ,xs ,body ,env) (,anys -> Any))
(Function xs body env)]
[(FunRef f n)
(lookup f env)]
[(Prim 'and (list e1 e2))
(if ((interp-F env) e1)
((interp-F env) e2)
#f)]
[(Prim op args)
(apply (interp-op op) (map (interp-F env) args))]
[(ProgramDefs info ds)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(let ([top-level (map (interp-F '()) ds)])
;; tie the knot
(for/list ([b top-level])
(set-mcdr! b (match (mcdr b)
the following belongs in new R7 interp
#;[`(tagged (lambda ,xs ,body) ,t)
`(tagged (lambda ,xs ,body ,top-level) ,t)]
[(Function xs body '())
(Function xs body top-level)])))
((interp-F top-level) (Apply (Var 'main) '())))]
[else ((super interp-F env) ast)]
))
(verbose "R6/interp-F result of" ast result)
result))
(define/override (interp-C-exp env)
(lambda (ast)
(define result
(match ast
#;[(Inject e t)
`(tagged ,((interp-C-exp env) e) ,t)]
#;[(Project e t2)
(define v ((interp-C-exp env) e))
(match v
[`(tagged ,v1 ,t1)
(cond [(tyeq? t1 t2)
v1]
[else
(error "in project, type mismatch" t1 t2)])]
[else
(error "in project, expected injected value" v)])]
[(ValueOf e ty)
((interp-op 'value-of-any) ((interp-C-exp env) e))]
[else
((super interp-C-exp env) ast)]
))
(verbose "R6/interp-C-exp ===> " ast result)
result))
#;(define/override (display-by-type ty val)
(match ty
['Any
(define tag (bitwise-and val 7))
(cond [(eq? tag 1) ;; integer
`(tagged ,(arithmetic-shift val (- 3)) Integer)]
[(eq? tag 4) ;; boolean
(if (eq? 0 (arithmetic-shift val (- 3)))
`(tagged #f Boolean)
`(tagged #t Boolean))]
[(eq? tag 2) ;; vector
;; This needs work. I need to find out how to get the
length of the vector from in memory .
`(tagged vector (Vectorof Any))]
[(eq? tag 3) ;; procedure (represented by a closure)
`(tagged procedure ,ty)]
[(eq? tag 5) ;; void
`(tagged void Void)])]
[else (super display-by-type ty val)]))
)) ;; interp-R6-class-alt
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Interpreters for R8 : for loops
(define interp-R8-class
(class interp-R6-class-alt
(super-new)
(inherit initialize! interp-C-exp)
(inherit-field result)
(define/override (apply-fun interp fun-val arg-vals)
(match fun-val
#;[`(tagged ,fun-val^ ,t) ;; for dynamically typed
(apply-fun interp fun-val^ arg-vals)]
[(Function xs body lam-env)
(define new-env (append (for/list ([x xs] [arg arg-vals])
(cons x (box arg)))
lam-env))
((interp new-env) body)]
[else (error 'apply-fun "expected function, not ~a" fun-val)]))
(define/override (interp-F env)
(lambda (ast)
(verbose "R8/interp-F starting" ast)
(define recur (interp-F env))
(define result
(match ast
[(Var x) (unbox (lookup x env))]
[(Let x e body)
(define new-env (cons (cons x (box (recur e))) env))
((interp-F new-env) body)]
[(ProgramDefs info ds)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(let ([top-level (map (interp-F '()) ds)])
;; tie the knot
(for/list ([b top-level])
(set-mcdr! b (match (mcdr b)
[(Function xs body '())
(Function xs body top-level)])))
((interp-F top-level) (Apply (FunRef 'main 0) '())))]
[(WhileLoop cnd body)
(define (loop)
(cond [((interp-F env) cnd)
((interp-F env) body)
(loop)]
[else
(void)]))
(loop)]
#;[(ForLoop x seq body)
(define vec (recur seq))
(for ([i vec])
(define new-env (cons (cons x (box i)) env))
((interp-F new-env) body))
(void)]
[(Begin es body)
(for ([e es]) (recur e))
(recur body)]
[(SetBang x rhs)
(set-box! (lookup x env) (recur rhs))]
[else ((super interp-F env) ast)]
))
(verbose "R8/interp-F result of" ast result)
result))
(define/override (interp-C-stmt env)
(lambda (ast)
(copious "R8/interp-C-stmt" ast)
(match ast
[(Call f args)
((interp-C-exp env) ast)
env]
[else ((super interp-C-stmt env) ast)]
)))
)) ;; interp-R8-class
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Interpreters for gradual
(define interp-gradual-class
(class interp-R8-class
(super-new)
(inherit memory-read memory-write! call-function interp-x86-exp)
(define (interp-vector-length vec)
(copious "gradual/interp-vector-length" vec)
(define tag ((memory-read) vec))
(bitwise-and #b111111 (arithmetic-shift tag -1)))
(define (interp-vector-ref vec i)
(define offset (* (+ i 1) 8))
((memory-read) (+ vec offset)))
(define (interp-vector-set! vec i arg)
(define offset (* (+ i 1) 8))
((memory-write!) (+ vec offset) arg))
(define (apply-closure clos arg cont-ss env)
(define f (interp-vector-ref clos 0))
(define env^ (append (list (cons 'rdi clos) (cons 'rsi arg)) env))
(define result-env (call-function f cont-ss env^))
(lookup 'rax result-env))
(define (vector-proxy? vec)
(define tag ((memory-read) vec))
(equal? 1 (bitwise-and (arithmetic-shift tag -57) 1)))
(define (proxy-vector-length vec)
(copious "gradual/proxy-vector-length" vec)
(cond [(vector-proxy? vec)
(define vec^ (interp-vector-ref vec 0))
(copious "proxy: underlying vec " vec^)
(proxy-vector-length vec^)]
[else (interp-vector-length vec)]))
(define (proxy-vector-ref vec i)
(cond [(vector-proxy? vec)
(define vec^ (interp-vector-ref vec 0))
(define val (proxy-vector-ref vec^ i))
(define rd (interp-vector-ref (interp-vector-ref vec 1) i))
(apply-closure rd val '() '())]
[else (interp-vector-ref vec i)]))
(define (proxy-vector-set! vec i arg)
(cond [(vector-proxy? vec)
(define vec^ (interp-vector-ref vec 0))
(define wr (interp-vector-ref (interp-vector-ref vec 2) i))
(define arg^ (apply-closure wr arg '() '()))
(proxy-vector-set! vec^ i arg^)]
[else (interp-vector-set! vec i arg)]))
(define/override (interp-x86-instr env)
(lambda (ast)
(when (pair? ast)
(copious "gradual/interp-x86-instr" (car ast)))
(match ast
[(cons (Callq 'proxy_vector_length _) ss)
(define vec ((interp-x86-exp env) (Reg 'rdi)))
(define v (proxy-vector-length vec))
((interp-x86-instr (cons (cons 'rax v) env)) ss)]
[(cons (Callq 'proxy_vector_ref _) ss)
(define vec ((interp-x86-exp env) (Reg 'rdi)))
(define i ((interp-x86-exp env) (Reg 'rsi)))
(define v (proxy-vector-ref vec i))
((interp-x86-instr (cons (cons 'rax v) env)) ss)]
[(cons (Callq 'proxy_vector_set _) ss)
(define vec ((interp-x86-exp env) (Reg 'rdi)))
(define i ((interp-x86-exp env) (Reg 'rsi)))
(define arg ((interp-x86-exp env) (Reg 'rdx)))
(define v (proxy-vector-set! vec i arg))
((interp-x86-instr (cons (cons 'rax v) env)) ss)]
[else ((super interp-x86-instr env) ast)]
)))
))
| null | https://raw.githubusercontent.com/IUCompilerCourse/public-student-support-code/fe5f4a657f4622eba596454c14bc8f72765004d9/interp.rkt | racket | The interpreters in this file are for the intermediate languages
produced by the various passes of the compiler.
Interpreters for x86 with names that correspond to the book.
TODO: update the following names!
The interp-x86-2 interpreter takes a program of the form
(X86Program info blocks)
Also, the info field must be an association list
with a key 'num-root-spills whose values is
the number of spills to the root stack.
The interp-x86-3 interpreter requires that the info field of the
Def struct be an association list with a key 'num-root-spills whose
values is the number of spills to the root stack.
Interpreters for R1: integer arithmetic and 'let'
Hide details for debug output.
C0
psuedo-x86 and x86
| (negq d) | (callq f)
psuedo-x86 ::= (program info i ...)
class interp-R1-class
We do not include 'and' because it has a funky order of evaluation.
-Jeremy
Extending the set of known operators is essentially the
is eqivalent to
class interp-R2-class
Interpreters for R3: Vectors
The simulated global state of the program
define produces private fields
field is like define but public
after a call to collect we must guarantee there is enough
memory to allocate the requested block of memory
I am only advancing the end of the heap because we
are not reclaiming memory
Find the last address
accidentally use another region.
the same way. -Andre
The range is of valid addresses in memory are [start, stop)
Create a string containing
(copious "R3/fetch page" addr min max name vect)
vect is too large to print, makes things hard to read.
(copious "R3/fetch page" addr min max name)
['vector-proxy-set! vector-set!]
(define/public (scheme-vector-ref vec i)
[`(vector-ref ,e-vec ,e-i)
[`(vector-set! ,e-vec ,e-i ,e-arg)
allocate a vector of length l and type t that is initialized.
[(AllocateClosure l ty arity)
Determine if a collection is needed.
Which it isn't because vectors stored in the environment
is the representation of the heap in the C language,
but collection is a no-op so we should check to see if
everything is well formed anyhow.
Collection isn't needed or possible in this representation
before register allocation
(define ty (dict-ref info 'type))
after register allocation
#:when (dict-has-key? info 'num-spills)
ugh -Jeremy
interp-R3-class
[`(tagged ,fun-val^ ,t) ;; for dynamically typed
[`(program (type ,ty) ,ds ... ,body)
(define/public (F-vector-ref vec i)
For R3
[(AllocateClosure l ty arity)
For R1
tie the knot
Hide function details to avoid spamming the debug output.
copy argument registers over to new-env
ugh -Jeremy
interpret the body of the function in the new-env
return and continue after the function call, back in env
[(FunRef f n)
The below applies before register allocation
Put the functions in the globals table
The below applies after register allocation -Jeremy
Put the functions in the globals table
end interp-R4-class
Interpreters for R5: lambda
tie the knot
Interpreters for R6: type Any and inject/project
Equality for flat types.
(define anys (for/list ([x xs]) 'Any))
(mcons f `(tagged (lambda ,xs ,body) (,anys -> Any)))
(define anys (for/list ([x xs]) 'Any))
`(tagged ,(lambda ,xs ,body ,env) (,anys -> Any))
tie the knot
[`(tagged (lambda ,xs ,body) ,t)
[(Inject e t)
[(Project e t2)
(define/override (display-by-type ty val)
integer
boolean
vector
This needs work. I need to find out how to get the
procedure (represented by a closure)
void
interp-R6-class-alt
[`(tagged ,fun-val^ ,t) ;; for dynamically typed
tie the knot
[(ForLoop x seq body)
interp-R8-class
Interpreters for gradual | #lang racket
(require racket/fixnum)
(require "utilities.rkt" (prefix-in runtime-config: "runtime-config.rkt"))
(provide interp-F1 interp-F2 interp-F3 interp-F4
interp-pseudo-x86-0 interp-x86-0
interp-pseudo-x86-1 interp-x86-1
interp-pseudo-x86-2 interp-x86-2
interp-pseudo-x86-3 interp-x86-3
interp-pseudo-x86-4 interp-x86-4
interp-pseudo-x86-5 interp-x86-5
interp-R6-class-alt
)
The interpreters for the source languages ( Lvar , , ... )
and the C intermediate languages Cvar and
are in separate files , e.g. , .
( define interp - R3 - prime
(lambda (p)
((send (new interp-R3-class) interp-scheme '()) p)))
(define interp-F1
(lambda (p)
((send (new interp-R4-class) interp-F '()) p)))
(define interp-F2
(lambda (p)
((send (new interp-R5-class) interp-F '()) p)))
(define interp-F3
(lambda (p)
((send (new interp-R6-class-alt) interp-F '()) p)))
(define interp-F4
(lambda (p)
((send (new interp-R8-class) interp-F '()) p)))
Interpreters for C2 and C3 .
( define interp - C2
(lambda (p)
(send (new interp-R3-class) interp-C p)))
( define interp - C3
(lambda (p)
(send (new interp-R4-class) interp-C p)))
( define interp - C4
(lambda (p)
(send (new interp-R5-class) interp-C p)))
( define interp - C5
(lambda (p)
(send (new interp-R6-class-alt) interp-C p)))
( define interp - C7
(lambda (p)
(send (new interp-R8-class) interp-C p)))
(define interp-pseudo-x86-0
(lambda (p)
((send (new interp-R1-class) interp-pseudo-x86 '()) p)))
(define interp-x86-0
(lambda (p)
((send (new interp-R1-class) interp-x86 '()) p)))
(define interp-pseudo-x86-1
(lambda (p)
((send (new interp-R2-class) interp-pseudo-x86 '()) p)))
(define interp-x86-1
(lambda (p)
((send (new interp-R2-class) interp-x86 '()) p)))
(define interp-pseudo-x86-2
(lambda (p)
((send (new interp-R3-class) interp-pseudo-x86 '()) p)))
(define interp-x86-2
(lambda (p)
((send (new interp-R3-class) interp-x86 '()) p)))
(define interp-pseudo-x86-3
(lambda (p)
((send (new interp-R4-class) interp-pseudo-x86 '()) p)))
(define interp-x86-3
(lambda (p)
((send (new interp-R4-class) interp-x86 '()) p)))
(define interp-pseudo-x86-4
(lambda (p)
((send (new interp-R6-class-alt) interp-pseudo-x86 '()) p)))
(define interp-x86-4
(lambda (p)
((send (new interp-R6-class-alt) interp-x86 '()) p)))
(define interp-pseudo-x86-5
(lambda (p)
((send (new interp-gradual-class) interp-pseudo-x86 '()) p)))
(define interp-x86-5
(lambda (p)
((send (new interp-gradual-class) interp-x86 '()) p)))
(define interp-R1-class
(class object%
(super-new)
(field (result (gensym 'result)))
(define/public (observe-value v)
v)
(define/public (return-from-tail v env)
(cons (cons result v) env))
(define/public (is-return? e)
(match e
[(cons (cons res v) env) (equal? res result)]
[else #f]))
(define/public (primitives)
(set '+ '- 'read))
(define/public (interp-op op)
(match op
['+ fx+]
['- fx-]
['read read-fixnum]
[else (error "in interp-op R1, unmatched" op)]))
(define/public (interp-scheme-exp env)
(lambda (ast)
(define recur (interp-scheme-exp env))
(verbose "R1/interp-scheme-exp" ast)
(match ast
[(Var x)
(lookup x env)]
[(Int n) n]
[(Let x e body)
(define v (recur e))
((interp-scheme-exp (cons (cons x v) env)) body)]
[(Prim op args)
(apply (interp-op op)
(for/list ([e args]) (recur e)))]
[else
(error (format "R1/no match in interp-scheme-exp for ~a" ast))]
)))
(define/public (interp-scheme env)
(lambda (ast)
(verbose "R1/interp-scheme" ast)
(match ast
[(Program _ e)
((interp-scheme-exp '()) e)]
[else
(error (format "R1/no match in interp-scheme for ~a" ast))]
)))
(define/public (interp-C-exp env)
(lambda (ast)
(define result
(match ast
[(Var x) (lookup x env)]
[(Int n) n]
[(Prim op args)
(apply (interp-op op) (map (interp-C-exp env) args))]
[else
(error "C0/interp-C-exp unhandled" ast)]
))
(verbose "C0/interp-C-exp" ast result)
result))
(define/public (interp-C-tail env)
(lambda (ast)
(match ast
[(Return e)
((interp-C-exp env) e)]
( return - from - tail v env ) hmm
[(Seq s t)
(define new-env ((interp-C-stmt env) s))
((interp-C-tail new-env) t)]
[else
(error "interp-C-tail unhandled" ast)]
)))
(define/public (interp-C-stmt env)
(lambda (ast)
(verbose "C0/interp-C-stmt" ast)
(match ast
[(Assign (Var x) e)
(let ([v ((interp-C-exp env) e)])
(cons (cons x v) env))]
[(Prim op args)
((interp-C-exp env) ast)
env]
[else
(error "interp-C-stmt unhandled" ast)]
)))
(define/public (interp-C ast)
(debug "R1/interp-C" ast)
(match ast
[(CProgram info blocks)
(define start (dict-ref blocks 'start))
((interp-C-tail '()) start)]
[else (error "no match in interp-C for " ast)]))
s , d : : = ( var x ) | ( int n ) | ( reg r ) | ( deref r n )
i : : = ( movq s d ) | ( ) | ( subq s d ) | ( imulq s d )
(define/public (get-name ast)
(match ast
[(or (Var x) (Reg x)) x]
[(Deref 'rbp n) n]
[else
(error 'interp-R1-class/get-name "doesn't have a name: ~a" ast)]))
(field [x86-ops (make-immutable-hash
`((addq 2 ,+)
(imulq 2 ,*)
(subq 2 ,(lambda (s d) (- d s)))
(negq 1 ,-)))])
(define/public (interp-x86-op op)
(define (err)
(error 'interp-R1-class/interp-x86-op "unmatched ~a" op))
(cadr (hash-ref x86-ops op err)))
(define/public (interp-x86-exp env)
(lambda (ast)
(copious "interp-x86-exp" ast)
(define result
(match ast
[(or (Var x) (Reg x))
(lookup (get-name ast) env)]
[(Deref r n)
(lookup (get-name ast) env)]
[(Imm n) n]
[else
(error 'interp-R1-class/interp-x86-exp "unhandled ~a" ast)]))
(copious "R1/interp-x86-exp" (observe-value result))
result))
(define/public (interp-x86-instr env)
(lambda (ast)
(when (pair? ast)
(copious "R1/interp-x86-instr" (car ast)))
(match ast
['() env]
[(cons (Callq 'read_int _) ss)
(let ([v (read)])
(copious "read " v)
((interp-x86-instr (cons (cons 'rax v) env)) ss))]
[(cons (Instr 'movq (list s d)) ss)
(define x (get-name d))
(define v ((interp-x86-exp env) s))
(copious "move " (observe-value v))
((interp-x86-instr (cons (cons x v) env)) ss)]
[(cons (Jmp conclusion) ss)
#:when (string-suffix? (symbol->string conclusion) "conclusion")
env]
[(cons (Jmp label) ss)
((interp-x86-block env) (goto-label label))]
[(X86Program info ss)
(let ([env ((interp-x86-instr '()) ss)])
(lookup 'rax env))]
[(cons (Instr binary-op (list s d)) ss)
(let ([s ((interp-x86-exp env) s)]
[d ((interp-x86-exp env) d)]
[x (get-name d)]
[f (interp-x86-op binary-op)])
(let ([v (f s d)])
(copious "binary-op result " (observe-value v))
((interp-x86-instr (cons (cons x v) env)) ss)))]
[(cons (Instr unary-op (list d)) ss)
(let ([d ((interp-x86-exp env) d)]
[x (get-name d)]
[f (interp-x86-op unary-op)])
(let ([v (f d)])
(copious "unary-op result " (observe-value v))
((interp-x86-instr (cons (cons x v) env)) ss)))]
[else (error "R1/interp-x86-instr no match for" ast)]
)))
(define/public (interp-pseudo-x86 env)
(lambda (ast)
((interp-x86 env) ast)))
(define/public (interp-x86-block env)
(lambda (ast)
(match ast
[(Block info ss)
((interp-x86-instr env) ss)]
[else
(error "R1/interp-x86-block unhandled" ast)])))
(define/public (interp-x86 env)
(lambda (ast)
(when (pair? ast)
(copious "R1/interp-x86" (car ast)))
(match ast
[(X86Program info blocks)
(parameterize ([get-basic-blocks blocks])
(define start-block (dict-ref blocks 'start))
(define result-env ((interp-x86-block '()) start-block))
(lookup 'rax result-env))]
[else (error "R1/interp-x86 no match in for" ast)]
)))
Interpreters for R2 : Booleans and conditionals
(define interp-R2-class
(class interp-R1-class
(super-new)
(inherit interp-x86-block observe-value)
(inherit-field x86-ops)
(define/override (primitives)
(set-union (super primitives)
(set 'eq? 'not 'or '< '<= '> '>=)))
(define/override (interp-op op)
(match op
['eq? (lambda (v1 v2)
(cond [(and (fixnum? v1) (fixnum? v2)) (eq? v1 v2)]
[(and (boolean? v1) (boolean? v2)) (eq? v1 v2)]
[else (error 'interp-op "unhandled case")]))]
['and (lambda (v1 v2)
(cond [(and (boolean? v1) (boolean? v2))
(and v1 v2)]
[else (error 'interp-op "unhandled case")]
))]
['not (lambda (v) (match v
[#t #f] [#f #t]
[else (error 'interp-op "unhandled case")]))]
['or (lambda (v1 v2)
(cond [(and (boolean? v1) (boolean? v2))
(or v1 v2)]
[else (error 'interp-op "unhandled case")]))]
['< (lambda (v1 v2)
(cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]
[else (error 'interp-op "unhandled case")]
))]
['<= (lambda (v1 v2)
(cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]
[else (error 'interp-op "unhandled case")]
))]
['> (lambda (v1 v2)
(cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]
[else (error 'interp-op "unhandled case")]
))]
['>= (lambda (v1 v2)
(cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]
[else (error 'interp-op "unhandled case")]
))]
[else (super interp-op op)]))
(define/override (interp-scheme-exp env)
(lambda (ast)
(define recur (interp-scheme-exp env))
(verbose "R2/interp-scheme-exp" ast)
(match ast
[(HasType e t) (recur e)]
[(Bool b) b]
[(Prim 'and (list e1 e2))
(match (recur e1)
[#t (match (recur e2)
[#t #t] [#f #f])]
[#f #f])]
[(If cnd thn els)
(match (recur cnd)
[#t (recur thn)]
[#f (recur els)]
[else
(error 'interp-scheme-exp "R2 expected Boolean, not ~a" cnd)])]
[else ((super interp-scheme-exp env) ast)]
)))
(define/override (interp-C-exp env)
(lambda (ast)
(define result
(match ast
[(HasType e t) ((interp-C-exp env) e)]
[(Bool b) b]
[else ((super interp-C-exp env) ast)]
))
(copious "R2/interp-C-exp" ast result)
result))
(define/override (interp-C-tail env)
(lambda (ast)
(copious "R2/interp-C-tail" ast)
(match ast
[(IfStmt cnd thn els)
(if ((interp-C-exp env) cnd)
((interp-C-tail env) thn)
((interp-C-tail env) els))]
[(Goto label)
((interp-C-tail env) (goto-label label))]
[else ((super interp-C-tail env) ast)]
)))
(define/override (interp-C ast)
(copious "R2/interp-C" ast)
(match ast
[(CProgram info blocks)
(parameterize ([get-basic-blocks blocks])
(super interp-C (CProgram info blocks)))]
[else (error "R2/interp-C unhandled" ast)]
))
(define byte2full-reg
(lambda (r)
(match r
['al 'rax]
['bl 'rbx]
['cl 'rcx]
['dl 'rdx]
)))
(define/override (get-name ast)
(match ast
[(ByteReg r)
(super get-name (Reg (byte2full-reg r)))]
[else (super get-name ast)]))
same as overriding the interp - x86 - op with new functionallity
(set! x86-ops (hash-set* x86-ops
'notq `(1 ,bitwise-not)
'andq `(2 ,bitwise-and)
'xorq `(2 ,bitwise-xor)))
(define/override (interp-x86-exp env)
(lambda (ast)
(copious "R2/interp-x86-exp" ast)
(define result
(match ast
[(ByteReg r)
((interp-x86-exp env) (Reg (byte2full-reg r)))]
[(Bool #t) 1]
[(Bool #f) 0]
[(Prim 'eq? (list e1 e2))
(if (eq? ((interp-x86-exp env) e1)
((interp-x86-exp env) e2))
1 0)]
[(Prim '< (list e1 e2))
(if (< ((interp-x86-exp env) e1)
((interp-x86-exp env) e2))
1 0)]
[(Prim '<= (list e1 e2))
(if (<= ((interp-x86-exp env) e1)
((interp-x86-exp env) e2))
1 0)]
[(Prim '> (list e1 e2))
(if (> ((interp-x86-exp env) e1)
((interp-x86-exp env) e2))
1 0)]
[(Prim '>= (list e1 e2))
(if (>= ((interp-x86-exp env) e1)
((interp-x86-exp env) e2))
1 0)]
[else ((super interp-x86-exp env) ast)]
))
(copious "R2/interp-x86-exp" (observe-value result))
result))
(define (eflags-status env cc)
(define eflags ((interp-x86-exp env) (Reg '__flag)))
(match cc
['e (if (equal? eflags 'equal) 1 0)]
['l (if (equal? eflags 'less) 1 0)]
['le
(if (or (eq? 1 (eflags-status env 'e))
(eq? 1 (eflags-status env 'l)))
1 0)]
['g
(if (not (eq? 1 (eflags-status env 'le)))
1 0)]
['ge
(if (not (eq? 1 (eflags-status env 'l)))
1 0)]))
(define/override (interp-x86-instr env)
(lambda (ast)
(when (pair? ast)
(copious "R2/interp-x86-instr" (car ast)))
(match ast
[(Block `(lives ,lives) ss)
((interp-x86-instr env) ss)]
[(Block `(lives ,lives) ss)
((interp-x86-instr env) ss)]
[(cons (Instr 'set (list cc d)) ss)
(define name (get-name d))
(define val (eflags-status env cc))
(verbose "set" cc val)
((interp-x86-instr (cons (cons name val) env)) ss)]
[(cons (IfStmt cnd thn els) ss)
(if (not (eq? 0 ((interp-x86-exp env) cnd)))
((interp-x86-instr env) (append thn ss))
((interp-x86-instr env) (append els ss)))]
Notice that the argument order of cmpq is confusing :
( cmpq , s2 , s1 ) ( jl thn ) ( jmp els )
( if ( < s1 s2 ) thn els )
[(cons (Instr 'cmpq (list s2 s1)) ss)
(let* ([v1 ((interp-x86-exp env) s1)]
[v2 ((interp-x86-exp env) s2)]
[eflags
(cond [(< v1 v2) 'less]
[(> v1 v2) 'greater]
[else 'equal])])
((interp-x86-instr (cons (cons '__flag eflags) env)) ss))]
[(cons (Instr 'movzbq (list s d)) ss)
(define x (get-name d))
(define v ((interp-x86-exp env) s))
((interp-x86-instr (cons (cons x v) env)) ss)]
[(cons (JmpIf cc label) ss)
(cond [(eq? (eflags-status env cc) 1)
((interp-x86-block env) (goto-label label))]
[else ((interp-x86-instr env) ss)])]
[else ((super interp-x86-instr env) ast)]
)))
(define interp-R3-class
(class interp-R2-class
(super-new)
(inherit get-name interp-x86-op interp-x86-block observe-value)
(inherit-field x86-ops)
(define memory (box '()))
(field [stack-size (runtime-config:rootstack-size)]
[heap-size (runtime-config:heap-size)]
[uninitialized 'uninitialized-value-from-memory]
[fromspace_begin (box uninitialized)]
[rootstack_end (box uninitialized)]
[free_ptr (box uninitialized)]
[fromspace_end (box uninitialized)]
[rootstack_begin (box uninitialized)]
[global-label-table
(make-hash
`((free_ptr . ,free_ptr)
(fromspace_begin . ,fromspace_begin)
(fromspace_end . ,fromspace_end)
(rootstack_begin . ,rootstack_begin)
(rootstack_end . ,rootstack_end)))])
(define/public (memory-read)
(lambda (addr)
(let-values ([(start stop name vect) (fetch-page addr)])
(let ([value (vector-ref vect (arithmetic-shift (- addr start) -3))])
(when (equal? value uninitialized)
(error 'interp-R3-class/memory-read
"read uninitialized memory at address ~s"
addr))
value))))
(define/public (memory-write!)
(lambda (addr value)
(let-values ([(start stop name vect) (fetch-page addr)])
(vector-set! vect (arithmetic-shift (- addr start) -3) value))))
(define/public (collect!)
(lambda (rootset bytes-requested)
(verbose "collect!" bytes-requested)
(let double-heap ([hs heap-size])
(if (< hs bytes-requested)
(double-heap (* 2 hs))
(let ((h-begin (allocate-page! 'fromspace hs)))
(set-box! fromspace_end (+ h-begin hs))
(set-box! free_ptr h-begin))))))
(define/public (initialize!)
(lambda (stack-length heap_length)
(verbose "initialize!")
(set-box! memory '())
(let* ([s-begin (allocate-page! 'rootstack stack-size)]
[h-begin (allocate-page! 'fromspace heap-size)])
(set-box! rootstack_begin s-begin)
(set-box! rootstack_end (+ s-begin stack-size))
(set-box! fromspace_begin h-begin)
(set-box! fromspace_end (+ h-begin heap-size))
(set-box! free_ptr h-begin))))
(define (allocate-page! name size)
(verbose "allocate-page!" name size)
(unless (and (fixnum? size)
(positive? size)
(= 0 (modulo size 8)))
(error 'allocate-page! "expected non-negative fixnum in ~a" size))
(define max-addr
(for/fold ([next 8])
([page (in-list (unbox memory))])
(match-let ([`(page ,_ ,stop ,_ ,_) page])
(max next stop))))
Allocate with a small pad 100 words so that it is n't likely to
The randomness is to dispell any reliance on interp always allocating
(define start-addr (+ max-addr 800))
(define stop-addr (+ start-addr size))
(define vect (make-vector (arithmetic-shift size -3) uninitialized))
(verbose "allocated" name start-addr stop-addr)
(set-box! memory (cons `(page ,start-addr ,stop-addr ,name ,vect)
(unbox memory)))
start-addr)
(define (free! addr)
(set-box! memory
(let loop ([memory (unbox memory)])
(match memory
[`() (error 'free "invalid address ~a, not currently allocated")]
[`(,(and page `(page ,ptr ,_ ,_ ,_)) . ,pages)
(if (= addr ptr)
pages
(cons page (loop pages)))]))))
(define (fetch-page addr)
(define (fmt-err addr memory)
(apply
string-append
(cons (format "address ~a out of bounds\n\tcurrent memory regions:\n"
addr)
(for/list ([page (in-list (unbox memory))])
(match-let ([`(page ,start ,stop ,name ,_) page])
(format "\t\t~a\t\t[~a,~a)\n" name start stop))))))
(unless (fixnum? addr)
(error 'fetch-page "invalid address ~a, not a fixnum" addr))
(unless (positive? addr)
(error 'fetch-page "invalid address ~a, negative" addr))
(unless (= 0 (modulo addr 8))
(error 'fetch-page "invalid address ~a, not 8-byte aligned" addr))
(let search ([m (unbox memory)])
(match m
[`() (error 'fetch-page (fmt-err addr memory))]
[`((page ,min ,max ,name ,vect) . ,rest-memory)
(if (and (<= min addr) (< addr max))
(values min max name vect)
(search rest-memory))]
[other (error 'fetch-page "unmatched ~a" m)])))
(define/override (primitives)
(set-union (super primitives)
(set 'vector 'vector-ref 'vector-set! vector-length
todo : move the following to a different interpreter
'vector-proxy)))
(define/override (interp-op op)
(match op
['eq? (lambda (v1 v2)
(cond [(or (and (fixnum? v1) (fixnum? v2))
(and (boolean? v1) (boolean? v2))
(and (vector? v1) (vector? v2))
(and (void? v1) (void? v2)))
(eq? v1 v2)]))]
['vector-proxy
(lambda (vec rs ws)
`(vector-proxy ,vec ,rs ,ws))]
['vector vector]
['vector-length vector-length]
['vector-ref vector-ref]
['vector-set! vector-set!]
[else (super interp-op op)]))
(match vec
[`(vector-proxy ,v ,rs ,ws)
(define v^ (scheme-vector-ref v i))
(define r (vector-ref rs i))
(apply-fun (lambda (env) (interp-scheme-exp env))
r (list v^))]
[else
(vector-ref vec i)]))
( define / public ( scheme - vector - set ! i arg )
(match vec
[`(vector-proxy ,v ,rs ,ws)
(define w (vector-ref ws i))
(define arg^ (apply-fun (lambda (env) (interp-scheme-exp env))
w (list arg)))
(scheme-vector-set! v i arg^)]
[else
(vector-set! vec i arg)]))
(define/override (interp-scheme-exp env)
(lambda (ast)
(define recur (interp-scheme-exp env))
(verbose "R3/interp-scheme" ast)
(match ast
[(Void) (void)]
[(GlobalValue 'free_ptr)
(unbox free_ptr)]
[(GlobalValue 'fromspace_end)
(unbox fromspace_end)]
[(Allocate l ty) (build-vector l (lambda a uninitialized))]
[(AllocateClosure l ty arity)
(define vec (build-vector (add1 l) (lambda a uninitialized)))
(vector-set! vec l `(arity ,arity))
vec]
[(AllocateProxy ty) (build-vector 3 (lambda a uninitialized))]
[(Collect size)
(unless (exact-nonnegative-integer? size)
(error 'interp-C "invalid argument to collect in ~a" ast))
(void)]
(define vec (recur e-vec))
(define i (recur e-i))
(scheme-vector-ref vec i)]
(define vec (recur e-vec))
(define i (recur e-i))
(define arg (recur e-arg))
(scheme-vector-set! vec i arg)]
[else ((super interp-scheme-exp env) ast)]
)))
(define/override (interp-scheme env)
(lambda (ast)
(verbose "R3/interp-scheme" ast)
(match ast
[(Program info e)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
((interp-scheme-exp '()) e)]
[else ((super interp-scheme env) ast)]
)))
(define (mem-error message expr)
(lambda (who fmt . args)
(error who "~a in ~a raise error:\n~a"
message expr
(apply format (cons fmt args)))))
(define (global-value-err ast)
(lambda ()
(error 'interp-R3-class "global label is unknown in ~a" ast)))
(define/public (fetch-global label)
(let* ([err (global-value-err label)]
[ref (hash-ref global-label-table label err)]
[value (unbox ref)])
(when (equal? value uninitialized)
(debug "fetch" global-label-table)
(error 'interp-R3-class/fetch-global
"global value, ~a, used before initialization"
label))
value))
(define/override (interp-C-exp env)
(lambda (ast)
(define result
(match ast
[(Void) (void)]
[(GlobalValue 'free_ptr)
(unbox free_ptr)]
[(GlobalValue 'fromspace_end)
(unbox fromspace_end)]
[(CollectionNeeded? size)
(when (or (eq? (unbox free_ptr) uninitialized)
(eq? (unbox fromspace_end) uninitialized))
(error 'interp-C "uninitialized state in ~a" ast))
#t]
[(Allocate l ty) (build-vector l (lambda a uninitialized))]
[(AllocateClosure l ty arity)
(define vec (build-vector (add1 l) (lambda a uninitialized)))
(vector-set! vec l `(arity ,arity))
vec]
(build-vector l (lambda a uninitialized))]
[(AllocateProxy ty) (build-vector 3 (lambda a uninitialized))]
[else
((super interp-C-exp env) ast)]
))
(copious "R3/interp-C-exp" ast result)
result))
(define/override (interp-C-stmt env)
(lambda (ast)
(copious "R3/interp-C-stmt" ast)
(match ast
[(Collect size)
(unless (exact-nonnegative-integer? size)
(error 'interp-C "invalid argument to collect in ~a" ast))
env]
[else
((super interp-C-stmt env) ast)]
)))
(define/override (interp-C-tail env)
(lambda (ast)
(copious "R3/interp-C-tail" ast)
(match ast
[(Seq s t)
(define new-env ((interp-C-stmt env) s))
((interp-C-tail new-env) t)]
[else ((super interp-C-tail env) ast)])))
(define/override (interp-C ast)
(copious "R3/interp-C" ast)
(match ast
[(CProgram info blocks)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(super interp-C (CProgram info blocks))]
[else (error "R3/interp-C unhandled" ast)]))
(define/override (interp-x86-exp env)
(lambda (ast)
(copious "interp-x86-exp" ast)
(define result
(match ast
[(Global label) (fetch-global label)]
[(Deref r i) #:when (not (eq? r 'rbp))
(define base ((interp-x86-exp env) (Reg r)))
(define addr (+ base i))
((memory-read) addr)]
[else ((super interp-x86-exp env) ast)]))
(copious "R3/interp-x86-exp" (observe-value result))
result))
(define/public (interp-x86-store env)
(lambda (ast value)
(copious "interp-x86-store" ast (observe-value value))
(match ast
[(Global label)
(define loc (hash-ref global-label-table label
(global-value-err ast)))
(set-box! loc value)
env]
[(Deref r i)
#:when (not (eq? r 'rbp))
(define base ((interp-x86-exp env) (Reg r)))
(define addr (+ base i))
((memory-write!) addr value)
env]
[dest
(define name (get-name dest))
(cons (cons name value) env)])))
(define (x86-binary-op? x)
(let ([val (hash-ref x86-ops x #f)])
(and val (= (car val) 2))))
(define (x86-unary-op? x)
(let ([val (hash-ref x86-ops x #f)])
(and val (= (car val) 1))))
(define/override (interp-x86-instr env)
(lambda (ast)
(when (pair? ast)
(copious "R3/interp-x86-instr" (car ast)))
(match ast
[ ( cons ( Callq ' malloc ) ss )
(define num-bytes ((interp-x86-exp env) (Reg 'rdi)))
((interp-x86-instr
`((rax . ,(allocate-page! 'malloc num-bytes)) . ,env))
ss)]
[ ( cons ( ' alloc ) ss )
(define num-bytes ((interp-x86-exp env) (Reg 'rdi)))
((interp-x86-instr
`((rax . ,(allocate-page! 'alloc num-bytes)) . ,env))
ss)]
[(cons (Callq 'collect _) ss)
(define rootstack ((interp-x86-exp env) (Reg 'rdi)))
(define bytes-requested ((interp-x86-exp env) (Reg 'rsi)))
((collect!) rootstack bytes-requested)
((interp-x86-instr env) ss)]
[(cons (Instr 'movq (list s d)) ss)
(define value ((interp-x86-exp env) s))
(define new-env ((interp-x86-store env) d value))
((interp-x86-instr new-env) ss)]
[(cons (Instr (? x86-binary-op? binop) (list s d)) ss)
(define src ((interp-x86-exp env) s))
(define dst ((interp-x86-exp env) d))
(define op (interp-x86-op binop))
(define new-env ((interp-x86-store env) d (op src dst)))
((interp-x86-instr new-env) ss)]
[(cons (Instr (? x86-unary-op? unary-op) (list d)) ss)
(define dst ((interp-x86-exp env) d))
(define op (interp-x86-op unary-op))
(define new-env ((interp-x86-store env) d (op dst)))
((interp-x86-instr new-env) ss)]
[else
((super interp-x86-instr env) ast)]
)))
(define/override (interp-pseudo-x86 env)
(lambda (ast)
(copious "R3/interp-pseudo-x86" ast)
(match ast
[(X86Program info blocks)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(define env (cons (cons 'r15 (unbox rootstack_begin)) '()))
(parameterize ([get-basic-blocks blocks])
(let ([env^ ((interp-x86-block env) (dict-ref blocks 'start))])
(lookup 'rax env^)))]
)))
(define/override (interp-x86 env)
(lambda (ast)
(copious "R3/interp-x86" ast)
(match ast
[(X86Program info blocks)
(define root-spills (dict-ref info 'num-root-spills))
(define root-space (* variable-size root-spills))
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(define env (cons (cons 'r15 (+ root-space (unbox rootstack_begin)))
'()))
(parameterize ([get-basic-blocks blocks])
(let ([env^ ((interp-x86-block env) (dict-ref blocks 'start))])
(lookup 'rax env^)))]
)))
(set! x86-ops
(hash-set* x86-ops
'sarq `(2 ,(lambda (n v) (arithmetic-shift v (- n))))
'salq `(2 ,(lambda (n v)
(crop-to-64bits (arithmetic-shift v n))))
'orq `(2 ,bitwise-ior)
))
Interpreters for R4 : functions
(define interp-R4-class
(class interp-R3-class
(super-new)
(inherit primitives interp-op initialize!
return-from-tail interp-x86-block memory-read memory-write!
interp-x86-store)
(inherit-field result rootstack_begin free_ptr fromspace_end
uninitialized global-label-table)
(define/public (apply-fun interp fun-val arg-vals)
(match fun-val
(apply-fun interp fun-val^ arg-vals)]
[(Function xs body lam-env)
(define new-env (append (map cons xs arg-vals) lam-env))
((interp new-env) body)]
[else (error 'apply-fun "expected function, not ~a" fun-val)]))
(define/public (non-apply-ast)
(set-union (primitives)
(set 'if 'let 'define 'program 'has-type 'void)))
(define/public (interp-scheme-def d)
(match d
[(Def f `([,xs : ,ps] ...) rt info body)
(mcons f (Function xs body '()))]
))
(define/override (interp-scheme-exp env)
(lambda (ast)
(verbose "R4/interp-scheme" ast)
(define recur (interp-scheme-exp env))
(match ast
[(Apply fun args)
(define fun-val (recur fun))
(define new-args (for/list ([e args]) (recur e)))
(apply-fun (lambda (env) (interp-scheme-exp env)) fun-val new-args)]
[else ((super interp-scheme-exp env) ast)]
)))
(define/override (interp-scheme env)
(lambda (ast)
(verbose "R4/interp-scheme" ast)
(match ast
((interp-scheme '()) `(program ,@ds ,body))]
[(Program info (cons ds body))
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(let ([top-level (for/list ([d ds]) (interp-scheme-def d))])
(for ([b top-level])
(set-mcdr! b (match (mcdr b)
[(Function xs body '())
(Function xs body top-level)])))
((interp-scheme-exp top-level) body))]
[else ((super interp-scheme env) ast)]
)))
(match vec
[`(vector-proxy ,v ,rs ,ws)
(define v^ (F-vector-ref v i))
(define r (vector-ref rs i))
(apply-fun (lambda (env) (interp-F env))
r (list v^))]
[else
(vector-ref vec i)]))
( define / public ( F - vector - set ! i arg )
(match vec
[`(vector-proxy ,v ,rs ,ws)
(define w (vector-ref ws i))
(define arg^ (apply-fun (lambda (env) (interp-F env))
w (list arg)))
(F-vector-set! v i arg^)]
[else
(vector-set! vec i arg)]))
(define/public (interp-F env)
(lambda (ast)
(define result
(match ast
For R4
[(Def f `([,xs : ,ps] ...) rt info body)
(cons f (Function xs body '()))]
[(FunRef f n)
(lookup f env)]
[(Apply fun args)
(define fun-val ((interp-F env) fun))
(define arg-vals (map (interp-F env) args))
(match fun-val
[(Function xs body fenv)
(define new-env (append (map cons xs arg-vals) env))
((interp-F new-env) body)]
[else (error "interp-F, expected function, not" fun-val)])]
[(ProgramDefs info ds)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(let ([top-level (map (interp-F '()) ds)])
((interp-F top-level) (Apply (Var 'main) '())))]
[(GlobalValue 'free_ptr)
(unbox free_ptr)]
[(GlobalValue 'fromspace_end)
(unbox fromspace_end)]
[(Allocate l ty) (build-vector l (lambda a uninitialized))]
[(AllocateClosure l ty arity)
(define vec (build-vector (add1 l) (lambda a uninitialized)))
(vector-set! vec l `(arity ,arity))
vec]
(build-vector l (lambda a uninitialized))]
[(AllocateProxy ty) (build-vector 3 (lambda a uninitialized))]
[(Collect size)
(unless (exact-nonnegative-integer? size)
(error 'interp-F "invalid argument to collect in ~a" ast))
(void)]
[(Void) (void)]
For R2
[(HasType e t) ((interp-F env) e)]
[(Bool b) b]
[(Prim 'and (list e1 e2))
(match ((interp-F env) e1)
[#t (match ((interp-F env) e2)
[#t #t] [#f #f])]
[#f #f])]
[(If cnd thn els)
(if ((interp-F env) cnd)
((interp-F env) thn)
((interp-F env) els))]
[(Var x)
(lookup x env)]
[(Int n) n]
[(Let x e body)
(let ([v ((interp-F env) e)])
((interp-F (cons (cons x v) env)) body))]
[(Prim op args)
(apply (interp-op op) (for/list ([e args]) ((interp-F env) e)))]
[(Apply f args)
((interp-F env) (Apply f args))]
[else
(error 'interp-F "R4 unmatched ~a" ast)]
))
(verbose "R4/interp-F" ast result)
result
))
(define/override (interp-C-exp env)
(lambda (ast)
(define result
(match ast
[(FunRef f n)
(lookup f env)]
[(Call f args)
(define arg-vals (map (interp-C-exp env) args))
(define f-val ((interp-C-exp env) f))
(match f-val
[(CFunction xs info blocks def-env)
(define f (dict-ref info 'name))
(define f-start (symbol-append f 'start))
(define new-env (append (map cons xs arg-vals) def-env))
(parameterize ([get-basic-blocks blocks])
((interp-C-tail new-env) (dict-ref blocks f-start)))]
[else (error "interp-C, expected a function, not" f-val)])]
[else
((super interp-C-exp env) ast)]
))
(verbose "R4/interp-C-exp" ast result)
result))
(define/override (interp-C-tail env)
(lambda (ast)
(define result
(match ast
[(TailCall f args)
(define arg-vals (map (interp-C-exp env) args))
(define f-val ((interp-C-exp env) f))
(match f-val
[(CFunction xs info blocks def-env)
(define f (dict-ref info 'name))
(define f-start (symbol-append f 'start))
(define new-env (append (map cons xs arg-vals) def-env))
(parameterize ([get-basic-blocks blocks])
((interp-C-tail new-env) (dict-ref blocks f-start)))]
[else (error "interp-C, expected a funnction, not" f-val)])]
[else
((super interp-C-tail env) ast)]
))
(verbose "R4/interp-C-tail" ast result)
result))
(define/public (interp-C-def ast)
(verbose "R4/interp-C-def" ast)
(match ast
[(Def f `([,xs : ,ps] ...) rt info blocks)
(mcons f (CFunction xs `((name . ,f)) blocks '()))]
[else
(error "R4/interp-C-def unhandled" ast)]
))
(define/override (interp-C ast)
(verbose "R4/interp-C" ast)
(match ast
[(ProgramDefs info ds)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(define top-level (for/list ([d ds]) (interp-C-def d)))
(for/list ([b top-level])
(set-mcdr! b (match (mcdr b)
[(CFunction xs info blocks '())
(CFunction xs info blocks top-level)])))
((interp-C-tail top-level) (TailCall (Var 'main) '()))]
[else
(error "R4/interp-C unhandled" ast)]
))
(define (stack-arg-name n)
(string->symbol (string-append "rsp_" (number->string n))))
(define/public (builtin-funs)
(set 'malloc 'alloc 'collect 'initialize 'read_int 'exit))
(define/override (get-name ast)
(match ast
[(StackArg n) (stack-arg-name n)]
[else (super get-name ast)]))
(define/override (observe-value v)
(match v
[(X86Function info blocks def-env)
`(function ,(dict-ref info 'name))]
[else v]))
(define root-stack-pointer 0)
(define/public (call-function f-val cont-ss env)
(match f-val
[(X86Function info blocks def-env)
(debug "interp-x86 call-function" (observe-value f-val))
(define n (dict-ref info 'num-params))
(define f (dict-ref info 'name))
(define root-spills (dict-ref info 'num-root-spills #f))
(define passing-regs
(filter (lambda (p) p)
(for/list ([r (vector-take arg-registers n)])
(let ([v (lookup r env #f)])
(if v (cons r v) #f)))))
(debug "interp-x86 call-function" passing-regs)
(define root-size
(cond [root-spills (* variable-size root-spills)]
[else 0]))
(set! root-stack-pointer (+ root-stack-pointer root-size))
(define new-env (cons (cons 'r15 root-stack-pointer)
(append passing-regs def-env)))
(define result-env
(parameterize ([get-basic-blocks blocks])
((interp-x86-block new-env)
(dict-ref blocks (symbol-append f 'start)))))
(set! root-stack-pointer (- root-stack-pointer root-size))
(define res (lookup 'rax result-env))
((interp-x86-instr (cons (cons 'rax res) env)) cont-ss)]
[else (error "interp-x86, expected a function, not" f-val)]))
(define/override (interp-x86-exp env)
(lambda (ast)
(copious "R4/interp-x86-exp" ast)
(define result
(match ast
[(StackArg n)
(define x (stack-arg-name n))
(lookup x env)]
(lookup f env)]
[else ((super interp-x86-exp env) ast)]))
(copious "R4/interp-x86-exp" (observe-value result))
result))
( define ( apply - vector - ref vec i cont - ss env )
(define tag ((memory-read) vec))
(verbose 'apply-vector-ref ((memory-read) vec))
(cond [(equal? (arithmetic-shift tag -63) 1)
(define vec^ ((memory-read) (+ vec (* 1 8))))
(define val^ (apply-vector-ref vec^ i '() env))
(define read-clos ((memory-read) (+ vec (* 2 8))))
(apply-closure read-clos val^ cont-ss env)]
[else
(define res ((memory-read) (+ vec (* (add1 i) 8))))
((interp-x86-instr (cons (cons 'rax res) env)) cont-ss)]
))
( define ( apply - vector - set ! vec i val cont - ss env )
(define tag ((memory-read) vec))
(cond [(equal? (arithmetic-shift tag -63) 1)
(define write-clos ((memory-read) (+ vec (* 3 8))))
(define val^ (apply-closure write-clos val '() env))
(apply-vector-set! vec i val^ cont-ss env)]
[else
((memory-write!) (+ vec (* (add1 i) 8)) val)
((interp-x86-instr env) cont-ss)]
))
(define/override (interp-x86-instr env)
(lambda (ast)
(when (pair? ast)
(copious "R4/interp-x86-instr" (car ast)))
(match ast
Treat leaq like movq -Jeremy
[(cons (Instr 'leaq (list s d)) ss)
(define value ((interp-x86-exp env) s))
(define new-env ((interp-x86-store env) d value))
((interp-x86-instr new-env) ss)]
[(cons (IndirectCallq f _) ss)
(debug "indirect callq" ast)
(define f-val ((interp-x86-exp env) f))
(call-function f-val ss env)]
[(cons (TailJmp f n) ss)
(debug "tail jmp" ast)
(define f-val ((interp-x86-exp env) f))
(call-function f-val '() env)]
[(cons (Callq f _) ss)
#:when (not (set-member? (builtin-funs) f))
(call-function (lookup f env) ss env)]
[(cons (Callq 'exit _) ss)
(error 'interp-x86 "exiting")]
[else
((super interp-x86-instr env) ast)]
)))
(define/public (interp-x86-def ast)
(match ast
[(Def f ps rt info blocks)
(cons f (X86Function (dict-set info 'name f) blocks '()))]
))
(define/override (interp-pseudo-x86 env)
(lambda (ast)
(copious "R4/interp-pseudo-x86" ast)
(match ast
[(ProgramDefs info ds)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(set! root-stack-pointer (unbox rootstack_begin))
(define top-level (for/list ([d ds]) (interp-x86-def d)))
(for ([(label fun) (in-dict top-level)])
(dict-set! global-label-table label (box fun)))
(define env^ (list (cons 'r15 (unbox rootstack_begin))))
(define result-env (call-function (lookup 'main top-level) '() env^))
(lookup 'rax result-env)]
)))
(define/override (interp-x86 env)
(lambda (ast)
(verbose "R4/interp-x86" ast)
(match ast
[(ProgramDefs info ds)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(set! root-stack-pointer (unbox rootstack_begin))
(define top-level (for/list ([d ds]) (interp-x86-def d)))
(for ([(label fun) (in-dict top-level)])
(dict-set! global-label-table label (box fun)))
(define env^ '())
(define result-env
(call-function (lookup 'main top-level) '() env^))
(lookup 'rax result-env)]
)))
(define interp-R5-class
(class interp-R4-class
(super-new)
(inherit initialize! return-from-tail apply-fun)
(inherit-field result)
(define/override (primitives)
(set-union (super primitives)
(set 'procedure-arity)))
(define/override (non-apply-ast)
(set-union (super non-apply-ast)
(set 'global-value 'allocate 'collect)))
(define/override (interp-op op)
(match op
['procedure-arity (lambda (v)
(match v
[(Function xs body lam-env)
(length xs)]
[(vector (Function ps body env) vs ... `(arity ,n))
n]
[else
(error 'interp-op "expected function, not ~a" v)]
))]
[else (super interp-op op)]
))
(define/override (interp-scheme-exp env)
(lambda (ast)
(verbose "R5/interp-scheme" ast)
(match ast
[(Lambda `([,xs : ,Ts] ...) rT body)
(Function xs body env)]
[else ((super interp-scheme-exp env) ast)]
)))
(define/override (interp-F env)
(lambda (ast)
(define result
(match ast
[(Lambda `([,xs : ,Ts] ...) rT body)
(Function xs body env)]
[(Def f `([,xs : ,ps] ...) rt info body)
(mcons f (Function xs body '()))]
[(ProgramDefs info ds)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(let ([top-level (map (interp-F '()) ds)])
(for/list ([b top-level])
(set-mcdr! b (match (mcdr b)
[(Function xs body '())
(Function xs body top-level)])))
((interp-F top-level) (Apply (Var 'main) '())))]
[(Closure arity args)
(define arg-vals (map (interp-F env) args))
(apply vector (append arg-vals (list `(arity ,arity))))]
[(Apply fun args)
(define fun-val ((interp-F env) fun))
(define arg-vals (map (interp-F env) args))
(apply-fun (lambda (env) (interp-F env)) fun-val arg-vals)]
[else ((super interp-F env) ast)]
))
(verbose "R5/interp-F result of" ast result)
result))
end interp - R5 - class
(define (crop-to-64bits n)
(let ([s (string->list (number->string n 2))])
(cond [(> (length s) 64)
(let ([s^ (list-tail s (- (length s) 64))])
(string->number (list->string s^) 2))]
[else n])))
(define interp-R6-class-alt
(class interp-R5-class
(super-new)
(inherit initialize!)
(inherit-field result)
(define/override (primitives)
(set-union (super primitives)
(set 'boolean? 'integer? 'vector? 'procedure?
'tag-of-any 'value-of-any 'tag-of-vector)))
(define/override (interp-op op)
(match op
['boolean? (lambda (v)
(match v
[`(tagged ,v1 Boolean) #t]
[else #f]))]
['integer? (lambda (v)
(match v
[`(tagged ,v1 Integer) #t]
[else #f]))]
['vector? (lambda (v)
(match v
[`(tagged ,v1 (Vector ,ts ...)) #t]
[else #f]))]
['procedure? (lambda (v)
(match v
[`(tagged ,v1 (,ts ... -> ,rt)) #t]
[else #f]))]
['eq? (lambda (v1 v2)
(match (list v1 v2)
[`((tagged ,v1^ ,ty1) (tagged ,v2^ ,ty2))
(and (eq? v1^ v2^) (equal? ty1 ty2))]
[else
(cond [(or (and (fixnum? v1) (fixnum? v2))
(and (boolean? v1) (boolean? v2))
(and (vector? v1) (vector? v2))
(and (void? v1) (void? v2)))
(eq? v1 v2)])]))]
['make-any (lambda (v tg) `(tagged ,v ,tg))]
['tag-of-any (lambda (v)
(match v
[`(tagged ,v^ ,tg)
tg]
[else
(error "interp expected tagged value, not" v)]))]
['value-of-any (lambda (v)
(match v
[`(tagged ,v^ ,tg)
v^]
[else
(error "interp expected tagged value, not" v)]))]
['tag-of-vector (lambda (v)
(match v
[`(vector-proxy ,vec ,rs ,ws) 1]
[else 0]))]
['any-vector-ref (lambda (v i)
(match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
['any-vector-set! (lambda (v i a)
(match v [`(tagged ,v^ ,tg)
(vector-set! v^ i a)]))]
['any-vector-length (lambda (v)
(match v [`(tagged ,v^ ,tg)
(vector-length v^)]))]
['any-vectorof-length (lambda (v)
(match v [`(tagged ,v^ ,tg)
(vector-length v^)]))]
[else (super interp-op op)]
))
(define/public (tyeq? t1 t2)
(match `(,t1 ,t2)
[`((Vectorof Any) (Vector ,t2s ...))
(for/and ([t2 t2s])
(eq? t2 'Any))]
[`((Vector ,t1s ...) (Vectorof Any))
(for/and ([t1 t1s])
(eq? t1 'Any))]
[else (equal? t1 t2)]))
(define/override (interp-scheme-exp env)
(lambda (ast)
(verbose "R6/interp-scheme" ast)
(define recur (interp-scheme-exp env))
(match ast
[(Inject e t)
`(tagged ,(recur e) ,t)]
[(Project e t2)
(define v (recur e))
(match v
[`(tagged ,v1 ,t1)
(cond [(tyeq? t1 t2) v1]
[else (error "in project, type mismatch" t1 t2)])]
[else (error "in project, expected injected value" v)])]
[else
((super interp-scheme-exp env) ast)]
)))
(define/override (interp-F env)
(lambda (ast)
(define recur (interp-F env))
(define result
(match ast
[(Inject e t)
`(tagged ,(recur e) ,t)]
[(Project e t2)
(define v (recur e))
(match v
[`(tagged ,v1 ,t1)
(cond [(tyeq? t1 t2) v1]
[else (error "in project, type mismatch" t1 t2)])]
[else (error "in project, expected injected value" v)])]
[(ValueOf e ty)
(define v ((interp-F env) e))
((interp-op 'value-of-any) v)]
The following belongs in a new R7 interp class
[(Def f xs _ info body)
#:when (andmap symbol? xs)
(mcons f (Function xs body '()))]
[(Lambda xs _ body)
#:when (andmap symbol? xs)
(Function xs body env)]
[(FunRef f n)
(lookup f env)]
[(Prim 'and (list e1 e2))
(if ((interp-F env) e1)
((interp-F env) e2)
#f)]
[(Prim op args)
(apply (interp-op op) (map (interp-F env) args))]
[(ProgramDefs info ds)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(let ([top-level (map (interp-F '()) ds)])
(for/list ([b top-level])
(set-mcdr! b (match (mcdr b)
the following belongs in new R7 interp
`(tagged (lambda ,xs ,body ,top-level) ,t)]
[(Function xs body '())
(Function xs body top-level)])))
((interp-F top-level) (Apply (Var 'main) '())))]
[else ((super interp-F env) ast)]
))
(verbose "R6/interp-F result of" ast result)
result))
(define/override (interp-C-exp env)
(lambda (ast)
(define result
(match ast
`(tagged ,((interp-C-exp env) e) ,t)]
(define v ((interp-C-exp env) e))
(match v
[`(tagged ,v1 ,t1)
(cond [(tyeq? t1 t2)
v1]
[else
(error "in project, type mismatch" t1 t2)])]
[else
(error "in project, expected injected value" v)])]
[(ValueOf e ty)
((interp-op 'value-of-any) ((interp-C-exp env) e))]
[else
((super interp-C-exp env) ast)]
))
(verbose "R6/interp-C-exp ===> " ast result)
result))
(match ty
['Any
(define tag (bitwise-and val 7))
`(tagged ,(arithmetic-shift val (- 3)) Integer)]
(if (eq? 0 (arithmetic-shift val (- 3)))
`(tagged #f Boolean)
`(tagged #t Boolean))]
length of the vector from in memory .
`(tagged vector (Vectorof Any))]
`(tagged procedure ,ty)]
`(tagged void Void)])]
[else (super display-by-type ty val)]))
Interpreters for R8 : for loops
(define interp-R8-class
(class interp-R6-class-alt
(super-new)
(inherit initialize! interp-C-exp)
(inherit-field result)
(define/override (apply-fun interp fun-val arg-vals)
(match fun-val
(apply-fun interp fun-val^ arg-vals)]
[(Function xs body lam-env)
(define new-env (append (for/list ([x xs] [arg arg-vals])
(cons x (box arg)))
lam-env))
((interp new-env) body)]
[else (error 'apply-fun "expected function, not ~a" fun-val)]))
(define/override (interp-F env)
(lambda (ast)
(verbose "R8/interp-F starting" ast)
(define recur (interp-F env))
(define result
(match ast
[(Var x) (unbox (lookup x env))]
[(Let x e body)
(define new-env (cons (cons x (box (recur e))) env))
((interp-F new-env) body)]
[(ProgramDefs info ds)
((initialize!) runtime-config:rootstack-size
runtime-config:heap-size)
(let ([top-level (map (interp-F '()) ds)])
(for/list ([b top-level])
(set-mcdr! b (match (mcdr b)
[(Function xs body '())
(Function xs body top-level)])))
((interp-F top-level) (Apply (FunRef 'main 0) '())))]
[(WhileLoop cnd body)
(define (loop)
(cond [((interp-F env) cnd)
((interp-F env) body)
(loop)]
[else
(void)]))
(loop)]
(define vec (recur seq))
(for ([i vec])
(define new-env (cons (cons x (box i)) env))
((interp-F new-env) body))
(void)]
[(Begin es body)
(for ([e es]) (recur e))
(recur body)]
[(SetBang x rhs)
(set-box! (lookup x env) (recur rhs))]
[else ((super interp-F env) ast)]
))
(verbose "R8/interp-F result of" ast result)
result))
(define/override (interp-C-stmt env)
(lambda (ast)
(copious "R8/interp-C-stmt" ast)
(match ast
[(Call f args)
((interp-C-exp env) ast)
env]
[else ((super interp-C-stmt env) ast)]
)))
(define interp-gradual-class
(class interp-R8-class
(super-new)
(inherit memory-read memory-write! call-function interp-x86-exp)
(define (interp-vector-length vec)
(copious "gradual/interp-vector-length" vec)
(define tag ((memory-read) vec))
(bitwise-and #b111111 (arithmetic-shift tag -1)))
(define (interp-vector-ref vec i)
(define offset (* (+ i 1) 8))
((memory-read) (+ vec offset)))
(define (interp-vector-set! vec i arg)
(define offset (* (+ i 1) 8))
((memory-write!) (+ vec offset) arg))
(define (apply-closure clos arg cont-ss env)
(define f (interp-vector-ref clos 0))
(define env^ (append (list (cons 'rdi clos) (cons 'rsi arg)) env))
(define result-env (call-function f cont-ss env^))
(lookup 'rax result-env))
(define (vector-proxy? vec)
(define tag ((memory-read) vec))
(equal? 1 (bitwise-and (arithmetic-shift tag -57) 1)))
(define (proxy-vector-length vec)
(copious "gradual/proxy-vector-length" vec)
(cond [(vector-proxy? vec)
(define vec^ (interp-vector-ref vec 0))
(copious "proxy: underlying vec " vec^)
(proxy-vector-length vec^)]
[else (interp-vector-length vec)]))
(define (proxy-vector-ref vec i)
(cond [(vector-proxy? vec)
(define vec^ (interp-vector-ref vec 0))
(define val (proxy-vector-ref vec^ i))
(define rd (interp-vector-ref (interp-vector-ref vec 1) i))
(apply-closure rd val '() '())]
[else (interp-vector-ref vec i)]))
(define (proxy-vector-set! vec i arg)
(cond [(vector-proxy? vec)
(define vec^ (interp-vector-ref vec 0))
(define wr (interp-vector-ref (interp-vector-ref vec 2) i))
(define arg^ (apply-closure wr arg '() '()))
(proxy-vector-set! vec^ i arg^)]
[else (interp-vector-set! vec i arg)]))
(define/override (interp-x86-instr env)
(lambda (ast)
(when (pair? ast)
(copious "gradual/interp-x86-instr" (car ast)))
(match ast
[(cons (Callq 'proxy_vector_length _) ss)
(define vec ((interp-x86-exp env) (Reg 'rdi)))
(define v (proxy-vector-length vec))
((interp-x86-instr (cons (cons 'rax v) env)) ss)]
[(cons (Callq 'proxy_vector_ref _) ss)
(define vec ((interp-x86-exp env) (Reg 'rdi)))
(define i ((interp-x86-exp env) (Reg 'rsi)))
(define v (proxy-vector-ref vec i))
((interp-x86-instr (cons (cons 'rax v) env)) ss)]
[(cons (Callq 'proxy_vector_set _) ss)
(define vec ((interp-x86-exp env) (Reg 'rdi)))
(define i ((interp-x86-exp env) (Reg 'rsi)))
(define arg ((interp-x86-exp env) (Reg 'rdx)))
(define v (proxy-vector-set! vec i arg))
((interp-x86-instr (cons (cons 'rax v) env)) ss)]
[else ((super interp-x86-instr env) ast)]
)))
))
|
cc1830488e14c654022465cae280e17ca84f0e6b01cb1dff08fcc69aed1cf9e9 | lpw25/ocaml-typed-effects | includecore.mli | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
(* Inclusion checks for the core language *)
open
open Typedtree
open Types
exception Dont_match
type type_mismatch =
Arity
| Privacy
| Kind
| Constraint
| Manifest
| Variance
| Sort of bool
| Param_sort of int * bool
| Field_type of Ident.t
| Field_mutable of Ident.t
| Field_arity of Ident.t
| Field_names of int * Ident.t * Ident.t
| Field_missing of bool * Ident.t
| Record_representation of bool
type effect_mismatch =
* | Effect_kind
* | Effect_manifest
* | Effect_constructor_arg_type of label
* | Effect_constructor_ret_type of label
* | Effect_constructor_arity of label
* | Effect_constructor_names of int * label * label
* | Effect_constructor_missing of bool * label
* | Effect_kind
* | Effect_manifest
* | Effect_constructor_arg_type of label
* | Effect_constructor_ret_type of label
* | Effect_constructor_arity of label
* | Effect_constructor_names of int * label * label
* | Effect_constructor_missing of bool * label *)
val value_descriptions:
Env.t -> value_description -> value_description -> module_coercion
val type_declarations:
?equality:bool ->
Env.t -> string ->
type_declaration -> Ident.t -> type_declaration -> type_mismatch list
val extension_constructors:
Env.t -> Ident.t -> extension_constructor -> extension_constructor -> bool
val effect_declarations :
* - > string - >
* effect_declaration - > Ident.t - > effect_declaration - > effect_mismatch list
* Env.t -> string ->
* effect_declaration -> Ident.t -> effect_declaration -> effect_mismatch list *)
val :
- > class_type - > class_type - > bool
val class_types:
Env.t -> class_type -> class_type -> bool
*)
val report_type_mismatch:
string -> string -> string -> Format.formatter -> type_mismatch list -> unit
(* val report_effect_mismatch:
* string -> string -> string -> Format.formatter -> effect_mismatch list -> unit *)
| null | https://raw.githubusercontent.com/lpw25/ocaml-typed-effects/79ea08b285c1fd9caf3f5a4d2aa112877f882bea/typing/includecore.mli | ocaml | *********************************************************************
OCaml
*********************************************************************
Inclusion checks for the core language
val report_effect_mismatch:
* string -> string -> string -> Format.formatter -> effect_mismatch list -> unit | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
open
open Typedtree
open Types
exception Dont_match
type type_mismatch =
Arity
| Privacy
| Kind
| Constraint
| Manifest
| Variance
| Sort of bool
| Param_sort of int * bool
| Field_type of Ident.t
| Field_mutable of Ident.t
| Field_arity of Ident.t
| Field_names of int * Ident.t * Ident.t
| Field_missing of bool * Ident.t
| Record_representation of bool
type effect_mismatch =
* | Effect_kind
* | Effect_manifest
* | Effect_constructor_arg_type of label
* | Effect_constructor_ret_type of label
* | Effect_constructor_arity of label
* | Effect_constructor_names of int * label * label
* | Effect_constructor_missing of bool * label
* | Effect_kind
* | Effect_manifest
* | Effect_constructor_arg_type of label
* | Effect_constructor_ret_type of label
* | Effect_constructor_arity of label
* | Effect_constructor_names of int * label * label
* | Effect_constructor_missing of bool * label *)
val value_descriptions:
Env.t -> value_description -> value_description -> module_coercion
val type_declarations:
?equality:bool ->
Env.t -> string ->
type_declaration -> Ident.t -> type_declaration -> type_mismatch list
val extension_constructors:
Env.t -> Ident.t -> extension_constructor -> extension_constructor -> bool
val effect_declarations :
* - > string - >
* effect_declaration - > Ident.t - > effect_declaration - > effect_mismatch list
* Env.t -> string ->
* effect_declaration -> Ident.t -> effect_declaration -> effect_mismatch list *)
val :
- > class_type - > class_type - > bool
val class_types:
Env.t -> class_type -> class_type -> bool
*)
val report_type_mismatch:
string -> string -> string -> Format.formatter -> type_mismatch list -> unit
|
b9e09aaabf57f204d9958930e09105be9413d9ef169ca4c48be28d814b329414 | tek/polysemy-hasql | DeriveStatement.hs | module Polysemy.Hasql.DeriveStatement where
import Hasql.Statement (Statement(Statement))
import Polysemy.Db.Data.Rep (Auto)
import Polysemy.Hasql.Data.SqlCode (SqlCode(SqlCode))
import Polysemy.Hasql.QueryParams (QueryParams, queryParams)
import Polysemy.Hasql.QueryRows (QueryRows, queryRows)
import Polysemy.Hasql.Table.ResultShape (ResultShape, resultShape)
import Polysemy.Hasql.Tree.Table (TableRoot)
class DeriveQuery p r where
deriveQuery :: SqlCode -> Statement p r
instance (
ResultShape d r,
TableRoot Auto d dc,
TableRoot Auto p pc,
QueryRows dc d,
QueryParams pc p
) => DeriveQuery p r where
deriveQuery (SqlCode sql) =
Statement (encodeUtf8 sql) (queryParams @pc @p) (resultShape (queryRows @dc @d)) True
| null | https://raw.githubusercontent.com/tek/polysemy-hasql/e0570eeb51d0f1362029e93de4a9d9f04e3f2434/packages/hasql/lib/Polysemy/Hasql/DeriveStatement.hs | haskell | module Polysemy.Hasql.DeriveStatement where
import Hasql.Statement (Statement(Statement))
import Polysemy.Db.Data.Rep (Auto)
import Polysemy.Hasql.Data.SqlCode (SqlCode(SqlCode))
import Polysemy.Hasql.QueryParams (QueryParams, queryParams)
import Polysemy.Hasql.QueryRows (QueryRows, queryRows)
import Polysemy.Hasql.Table.ResultShape (ResultShape, resultShape)
import Polysemy.Hasql.Tree.Table (TableRoot)
class DeriveQuery p r where
deriveQuery :: SqlCode -> Statement p r
instance (
ResultShape d r,
TableRoot Auto d dc,
TableRoot Auto p pc,
QueryRows dc d,
QueryParams pc p
) => DeriveQuery p r where
deriveQuery (SqlCode sql) =
Statement (encodeUtf8 sql) (queryParams @pc @p) (resultShape (queryRows @dc @d)) True
| |
e886efd67d71a20ad8d931536ec8cc1a48f2871ac7964bebd4f3d3c9bf335a2a | codinuum/cca | common.ml |
Copyright 2012 - 2020 Codinuum Software Lab < >
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 .
Copyright 2012-2020 Codinuum Software Lab <>
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.
*)
let warning_msg = Xprint.warning ~head:"[Astml]"
let decode_digest =
let pat = Str.regexp_string Entity.sub_sep in
let decode s =
match Str.split pat s with
| [] | [_] -> s
| [_;d] -> d
| _ -> s
in
decode
| null | https://raw.githubusercontent.com/codinuum/cca/88ea07f3fe3671b78518769d804fdebabcd28e90/src/ast/analyzing/langs/astml/common.ml | ocaml |
Copyright 2012 - 2020 Codinuum Software Lab < >
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 .
Copyright 2012-2020 Codinuum Software Lab <>
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.
*)
let warning_msg = Xprint.warning ~head:"[Astml]"
let decode_digest =
let pat = Str.regexp_string Entity.sub_sep in
let decode s =
match Str.split pat s with
| [] | [_] -> s
| [_;d] -> d
| _ -> s
in
decode
| |
9f6c67b3fa380087079ab6c53434b0fefaa2fd446e53a2f4474549125ae5ee1e | borkdude/advent-of-cljc | dfuenzalida.cljc | (ns aoc.y2017.d05.dfuenzalida
(:refer-clojure :exclude [read-string format])
(:require
[aoc.utils :as u :refer [deftest read-string format]]
[aoc.y2017.d05.data :refer [input answer-1 answer-2]]
[clojure.test :as t :refer [is testing]]))
(defn iter-offsets [pos offsets steps]
(if (>= pos (count offsets))
steps ;; we escaped!
(let [curr (offsets pos)
new-pos (+ pos curr)]
(recur new-pos
(assoc-in offsets [pos] (inc curr))
(inc steps)))))
(defn read-input []
(read-string (str "[" input "]")))
(defn solve-1 []
(iter-offsets 0 (read-input) 0))
(defn iter-offsets2 [pos offsets steps]
(if (>= pos (count offsets))
steps ;; we escaped!
(let [curr (offsets pos)
new-pos (+ pos curr)
change (if (>= curr 3) dec inc)]
(recur new-pos
(assoc-in offsets [pos] (change curr))
(inc steps)))))
(defn solve-2 []
(iter-offsets2 0 (read-input) 0))
(deftest ^:skip part-1
(is (= (str answer-1)
(str (solve-1)))))
(deftest ^:skip part-2
(is (= (str answer-2)
(str (solve-2)))))
;;;; Scratch
(comment
(t/run-tests)
)
| null | https://raw.githubusercontent.com/borkdude/advent-of-cljc/17c8abb876b95ab01eee418f1da2e402e845c596/src/aoc/y2017/d05/dfuenzalida.cljc | clojure | we escaped!
we escaped!
Scratch | (ns aoc.y2017.d05.dfuenzalida
(:refer-clojure :exclude [read-string format])
(:require
[aoc.utils :as u :refer [deftest read-string format]]
[aoc.y2017.d05.data :refer [input answer-1 answer-2]]
[clojure.test :as t :refer [is testing]]))
(defn iter-offsets [pos offsets steps]
(if (>= pos (count offsets))
(let [curr (offsets pos)
new-pos (+ pos curr)]
(recur new-pos
(assoc-in offsets [pos] (inc curr))
(inc steps)))))
(defn read-input []
(read-string (str "[" input "]")))
(defn solve-1 []
(iter-offsets 0 (read-input) 0))
(defn iter-offsets2 [pos offsets steps]
(if (>= pos (count offsets))
(let [curr (offsets pos)
new-pos (+ pos curr)
change (if (>= curr 3) dec inc)]
(recur new-pos
(assoc-in offsets [pos] (change curr))
(inc steps)))))
(defn solve-2 []
(iter-offsets2 0 (read-input) 0))
(deftest ^:skip part-1
(is (= (str answer-1)
(str (solve-1)))))
(deftest ^:skip part-2
(is (= (str answer-2)
(str (solve-2)))))
(comment
(t/run-tests)
)
|
093ae958fd358a3bbd730aed586d28fd9fa4aa14c5f85e32963be287ec404742 | clojure-interop/google-cloud-clients | WebRiskServiceV1Beta1StubSettings$Builder.clj | (ns com.google.cloud.webrisk.v1beta1.stub.WebRiskServiceV1Beta1StubSettings$Builder
"Builder for WebRiskServiceV1Beta1StubSettings."
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.webrisk.v1beta1.stub WebRiskServiceV1Beta1StubSettings$Builder]))
(defn apply-to-all-unary-methods
"Applies the given settings updater function to all of the unary API methods in this service.
Note: This method does not support applying settings to streaming methods.
settings-updater - `com.google.api.core.ApiFunction`
returns: `com.google.cloud.webrisk.v1beta1.stub.WebRiskServiceV1Beta1StubSettings$Builder`
throws: java.lang.Exception"
(^com.google.cloud.webrisk.v1beta1.stub.WebRiskServiceV1Beta1StubSettings$Builder [^WebRiskServiceV1Beta1StubSettings$Builder this ^com.google.api.core.ApiFunction settings-updater]
(-> this (.applyToAllUnaryMethods settings-updater))))
(defn unary-method-settings-builders
"returns: `com.google.common.collect.ImmutableList<com.google.api.gax.rpc.UnaryCallSettings.Builder<?,?>>`"
(^com.google.common.collect.ImmutableList [^WebRiskServiceV1Beta1StubSettings$Builder this]
(-> this (.unaryMethodSettingsBuilders))))
(defn compute-threat-list-diff-settings
"Returns the builder for the settings used for calls to computeThreatListDiff.
returns: `com.google.api.gax.rpc.UnaryCallSettings.Builder<com.google.webrisk.v1beta1.ComputeThreatListDiffRequest,com.google.webrisk.v1beta1.ComputeThreatListDiffResponse>`"
(^com.google.api.gax.rpc.UnaryCallSettings.Builder [^WebRiskServiceV1Beta1StubSettings$Builder this]
(-> this (.computeThreatListDiffSettings))))
(defn search-uris-settings
"Returns the builder for the settings used for calls to searchUris.
returns: `com.google.api.gax.rpc.UnaryCallSettings.Builder<com.google.webrisk.v1beta1.SearchUrisRequest,com.google.webrisk.v1beta1.SearchUrisResponse>`"
(^com.google.api.gax.rpc.UnaryCallSettings.Builder [^WebRiskServiceV1Beta1StubSettings$Builder this]
(-> this (.searchUrisSettings))))
(defn search-hashes-settings
"Returns the builder for the settings used for calls to searchHashes.
returns: `com.google.api.gax.rpc.UnaryCallSettings.Builder<com.google.webrisk.v1beta1.SearchHashesRequest,com.google.webrisk.v1beta1.SearchHashesResponse>`"
(^com.google.api.gax.rpc.UnaryCallSettings.Builder [^WebRiskServiceV1Beta1StubSettings$Builder this]
(-> this (.searchHashesSettings))))
(defn build
"returns: `com.google.cloud.webrisk.v1beta1.stub.WebRiskServiceV1Beta1StubSettings`
throws: java.io.IOException"
(^com.google.cloud.webrisk.v1beta1.stub.WebRiskServiceV1Beta1StubSettings [^WebRiskServiceV1Beta1StubSettings$Builder this]
(-> this (.build))))
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.webrisk/src/com/google/cloud/webrisk/v1beta1/stub/WebRiskServiceV1Beta1StubSettings%24Builder.clj | clojure | (ns com.google.cloud.webrisk.v1beta1.stub.WebRiskServiceV1Beta1StubSettings$Builder
"Builder for WebRiskServiceV1Beta1StubSettings."
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.webrisk.v1beta1.stub WebRiskServiceV1Beta1StubSettings$Builder]))
(defn apply-to-all-unary-methods
"Applies the given settings updater function to all of the unary API methods in this service.
Note: This method does not support applying settings to streaming methods.
settings-updater - `com.google.api.core.ApiFunction`
returns: `com.google.cloud.webrisk.v1beta1.stub.WebRiskServiceV1Beta1StubSettings$Builder`
throws: java.lang.Exception"
(^com.google.cloud.webrisk.v1beta1.stub.WebRiskServiceV1Beta1StubSettings$Builder [^WebRiskServiceV1Beta1StubSettings$Builder this ^com.google.api.core.ApiFunction settings-updater]
(-> this (.applyToAllUnaryMethods settings-updater))))
(defn unary-method-settings-builders
"returns: `com.google.common.collect.ImmutableList<com.google.api.gax.rpc.UnaryCallSettings.Builder<?,?>>`"
(^com.google.common.collect.ImmutableList [^WebRiskServiceV1Beta1StubSettings$Builder this]
(-> this (.unaryMethodSettingsBuilders))))
(defn compute-threat-list-diff-settings
"Returns the builder for the settings used for calls to computeThreatListDiff.
returns: `com.google.api.gax.rpc.UnaryCallSettings.Builder<com.google.webrisk.v1beta1.ComputeThreatListDiffRequest,com.google.webrisk.v1beta1.ComputeThreatListDiffResponse>`"
(^com.google.api.gax.rpc.UnaryCallSettings.Builder [^WebRiskServiceV1Beta1StubSettings$Builder this]
(-> this (.computeThreatListDiffSettings))))
(defn search-uris-settings
"Returns the builder for the settings used for calls to searchUris.
returns: `com.google.api.gax.rpc.UnaryCallSettings.Builder<com.google.webrisk.v1beta1.SearchUrisRequest,com.google.webrisk.v1beta1.SearchUrisResponse>`"
(^com.google.api.gax.rpc.UnaryCallSettings.Builder [^WebRiskServiceV1Beta1StubSettings$Builder this]
(-> this (.searchUrisSettings))))
(defn search-hashes-settings
"Returns the builder for the settings used for calls to searchHashes.
returns: `com.google.api.gax.rpc.UnaryCallSettings.Builder<com.google.webrisk.v1beta1.SearchHashesRequest,com.google.webrisk.v1beta1.SearchHashesResponse>`"
(^com.google.api.gax.rpc.UnaryCallSettings.Builder [^WebRiskServiceV1Beta1StubSettings$Builder this]
(-> this (.searchHashesSettings))))
(defn build
"returns: `com.google.cloud.webrisk.v1beta1.stub.WebRiskServiceV1Beta1StubSettings`
throws: java.io.IOException"
(^com.google.cloud.webrisk.v1beta1.stub.WebRiskServiceV1Beta1StubSettings [^WebRiskServiceV1Beta1StubSettings$Builder this]
(-> this (.build))))
| |
dd8242f63574bbcf6ee0c387a5d80f2b0ac6e9a361c88306d9ab8df814fdde64 | janestreet/shexp | env.mli | (** Runtime environment
If we were to compile a script to an OCaml program, all functions would have to take
this environment as argument. *)
open Import
type t
module Working_dir_spec : sig
type t =
| Inherit
| Path of string
| Physical of
{ path : string
; fd : Unix.file_descr
}
end
val create
: ?stdin:Unix.file_descr
-> ?stdout:Unix.file_descr
-> ?stderr:Unix.file_descr
-> ?cwd:Working_dir_spec.t
-> ?unix_env:(string * string) list
-> unit
-> t
(** Increment the reference of the working directory *)
val add_cwd_ref : t -> unit
(** Decrement the reference of the working directory *)
val deref_cwd : t -> unit
(** Unix environment *)
val find_executable : t -> string -> string option
val get_env : t -> string -> string option
val set_env : t -> string -> string -> t
val unset_env : t -> string -> t
val set_env_many : t -> (string * string) list -> t
val unset_env_many : t -> string list -> t
val cwd_logical : t -> string
val chdir : t -> string -> t
val stdin : t -> Unix.file_descr
val stdout : t -> Unix.file_descr
val stderr : t -> Unix.file_descr
val set_stdin : t -> Unix.file_descr -> t
val set_stdout : t -> Unix.file_descr -> t
val set_stderr : t -> Unix.file_descr -> t
val set_outputs : t -> Unix.file_descr -> t
val set_stdios
: t
-> stdin:Unix.file_descr
-> stdout:Unix.file_descr
-> stderr:Unix.file_descr
-> t
val get_stdio : t -> Std_io.t -> Unix.file_descr
val set_stdio : t -> Std_io.t -> Unix.file_descr -> t
type run_error = Command_not_found
val spawn : t -> prog:string -> args:string list -> (int, run_error) result
val open_file
: t
-> ?perm:Posixat.File_perm.t
-> flags:Posixat.Open_flag.t list
-> string
-> Unix.file_descr
val with_file
: t
-> ?perm:Posixat.File_perm.t
-> flags:Posixat.Open_flag.t list
-> string
-> f:(Unix.file_descr -> 'a)
-> 'a
val chmod : t -> string -> perm:int -> unit
val chown : t -> string -> uid:int -> gid:int -> unit
val mkdir : t -> ?perm:int -> ?p:bool -> string -> unit
val rm : t -> string -> unit
val rmdir : t -> string -> unit
val mkfifo : t -> ?perm:int -> string -> unit
val link : t -> string -> string -> unit
val rename : t -> string -> string -> unit
val symlink : t -> string -> string -> unit
val stat : t -> string -> Unix.stats
val lstat : t -> string -> Unix.stats
val readlink : t -> string -> string
val readdir : t -> string -> string list
val access : t -> string -> Unix.access_permission list -> unit
| null | https://raw.githubusercontent.com/janestreet/shexp/635989a9065f94e309707f113d6647dc62d6932f/process-lib/src/env.mli | ocaml | * Runtime environment
If we were to compile a script to an OCaml program, all functions would have to take
this environment as argument.
* Increment the reference of the working directory
* Decrement the reference of the working directory
* Unix environment |
open Import
type t
module Working_dir_spec : sig
type t =
| Inherit
| Path of string
| Physical of
{ path : string
; fd : Unix.file_descr
}
end
val create
: ?stdin:Unix.file_descr
-> ?stdout:Unix.file_descr
-> ?stderr:Unix.file_descr
-> ?cwd:Working_dir_spec.t
-> ?unix_env:(string * string) list
-> unit
-> t
val add_cwd_ref : t -> unit
val deref_cwd : t -> unit
val find_executable : t -> string -> string option
val get_env : t -> string -> string option
val set_env : t -> string -> string -> t
val unset_env : t -> string -> t
val set_env_many : t -> (string * string) list -> t
val unset_env_many : t -> string list -> t
val cwd_logical : t -> string
val chdir : t -> string -> t
val stdin : t -> Unix.file_descr
val stdout : t -> Unix.file_descr
val stderr : t -> Unix.file_descr
val set_stdin : t -> Unix.file_descr -> t
val set_stdout : t -> Unix.file_descr -> t
val set_stderr : t -> Unix.file_descr -> t
val set_outputs : t -> Unix.file_descr -> t
val set_stdios
: t
-> stdin:Unix.file_descr
-> stdout:Unix.file_descr
-> stderr:Unix.file_descr
-> t
val get_stdio : t -> Std_io.t -> Unix.file_descr
val set_stdio : t -> Std_io.t -> Unix.file_descr -> t
type run_error = Command_not_found
val spawn : t -> prog:string -> args:string list -> (int, run_error) result
val open_file
: t
-> ?perm:Posixat.File_perm.t
-> flags:Posixat.Open_flag.t list
-> string
-> Unix.file_descr
val with_file
: t
-> ?perm:Posixat.File_perm.t
-> flags:Posixat.Open_flag.t list
-> string
-> f:(Unix.file_descr -> 'a)
-> 'a
val chmod : t -> string -> perm:int -> unit
val chown : t -> string -> uid:int -> gid:int -> unit
val mkdir : t -> ?perm:int -> ?p:bool -> string -> unit
val rm : t -> string -> unit
val rmdir : t -> string -> unit
val mkfifo : t -> ?perm:int -> string -> unit
val link : t -> string -> string -> unit
val rename : t -> string -> string -> unit
val symlink : t -> string -> string -> unit
val stat : t -> string -> Unix.stats
val lstat : t -> string -> Unix.stats
val readlink : t -> string -> string
val readdir : t -> string -> string list
val access : t -> string -> Unix.access_permission list -> unit
|
1685a25899144cfc1332724f11a51657ac75d9b2ca74437803a5aead7ca08102 | geophf/1HaskellADay | Solution.hs | module Y2021.M03.D11.Solution where
import Data.Map (Map)
import qualified Data.Map as Map
-
Today 's # haskell problem , we 're going to provide unique identifier for words .
This is very computer - science - y , and is well - suited to take on this
problem .
For example , variables , bound or unbound ( ' free ' ) , are named ' foo , ' ' bar , '
and ' quux ' in your program ...
RIGHT ? DON'T YOU NAME ALL YOUR VARIABLES THOSE NAMES , AND NOT ' i ' and ' x '
BECAUSE THIS ISN'T FORTRAN , , I HATE TO BREAK IT TO YOU !
* whew * I 'm glad I kept my cool there . O.o
So , given a list of words , provide a set of unique identifiers for them .
-
Today's #haskell problem, we're going to provide unique identifier for words.
This is very computer-science-y, and Haskell is well-suited to take on this
problem.
For example, variables, bound or unbound ('free'), are named 'foo,' 'bar,'
and 'quux' in your program ...
RIGHT? DON'T YOU NAME ALL YOUR VARIABLES THOSE NAMES, AND NOT 'i' and 'x'
BECAUSE THIS ISN'T FORTRAN, FOLKS, I HATE TO BREAK IT TO YOU!
*whew* I'm glad I kept my cool there. O.o
So, given a list of words, provide a set of unique identifiers for them.
--}
uniqueIds :: Ord a => [a] -> Map a Integer
uniqueIds = Map.fromList . flip zip [1..]
-- give a set of unique ids for the following
names :: [String]
names = words "Tom Dick Harry"
{--
>>> uniqueIds names
fromList [("Dick",2),("Harry",3),("Tom",1)]
--}
| null | https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2021/M03/D11/Solution.hs | haskell | }
give a set of unique ids for the following
-
>>> uniqueIds names
fromList [("Dick",2),("Harry",3),("Tom",1)]
- | module Y2021.M03.D11.Solution where
import Data.Map (Map)
import qualified Data.Map as Map
-
Today 's # haskell problem , we 're going to provide unique identifier for words .
This is very computer - science - y , and is well - suited to take on this
problem .
For example , variables , bound or unbound ( ' free ' ) , are named ' foo , ' ' bar , '
and ' quux ' in your program ...
RIGHT ? DON'T YOU NAME ALL YOUR VARIABLES THOSE NAMES , AND NOT ' i ' and ' x '
BECAUSE THIS ISN'T FORTRAN , , I HATE TO BREAK IT TO YOU !
* whew * I 'm glad I kept my cool there . O.o
So , given a list of words , provide a set of unique identifiers for them .
-
Today's #haskell problem, we're going to provide unique identifier for words.
This is very computer-science-y, and Haskell is well-suited to take on this
problem.
For example, variables, bound or unbound ('free'), are named 'foo,' 'bar,'
and 'quux' in your program ...
RIGHT? DON'T YOU NAME ALL YOUR VARIABLES THOSE NAMES, AND NOT 'i' and 'x'
BECAUSE THIS ISN'T FORTRAN, FOLKS, I HATE TO BREAK IT TO YOU!
*whew* I'm glad I kept my cool there. O.o
So, given a list of words, provide a set of unique identifiers for them.
uniqueIds :: Ord a => [a] -> Map a Integer
uniqueIds = Map.fromList . flip zip [1..]
names :: [String]
names = words "Tom Dick Harry"
|
65f73d4445e5720b1e9fe759233d993f2cc3b39c6d8f4583c2f1db287d496c45 | bobot/FetedelascienceINRIAsaclay | test_threads.ml | open Printf
module Sensor = Mindstorm.Sensor
module Motor = Mindstorm.Motor
let c_touch = Condition.create ()
let m = Mutex.create ()
let test_touch conn =
Sensor.set conn `S1 `Switch `Bool;
while true do
let sensor = Sensor.get conn `S1 in
printf "sensor = %i\n%!" sensor.Sensor.scaled;
if sensor.Sensor.scaled <> 0 then begin
Condition.signal c_touch
end;
Thread.delay 0.3
done;;
let react_touch conn =
while true do
Condition.wait c_touch m;
printf "touche\n%!";
Thread.delay 0.3;
done;;
let () =
let bt =
if Array.length Sys.argv < 2 then (
printf "%s <bluetooth addr>\n" Sys.argv.(0);
exit 1;
)
else Sys.argv.(1) in
let conn = Mindstorm.connect_bluetooth bt in
printf "Connected\n%!";
let _t1 = Thread.create react_touch conn in
let _t2 = Thread.create test_touch conn in
Thread.delay 10.;
printf "FIN\n%!";;
| null | https://raw.githubusercontent.com/bobot/FetedelascienceINRIAsaclay/87765db9f9c7211a26a09eb93e9c92f99a49b0bc/2010/robot/mindstorm-bzr/examples/test_threads.ml | ocaml | open Printf
module Sensor = Mindstorm.Sensor
module Motor = Mindstorm.Motor
let c_touch = Condition.create ()
let m = Mutex.create ()
let test_touch conn =
Sensor.set conn `S1 `Switch `Bool;
while true do
let sensor = Sensor.get conn `S1 in
printf "sensor = %i\n%!" sensor.Sensor.scaled;
if sensor.Sensor.scaled <> 0 then begin
Condition.signal c_touch
end;
Thread.delay 0.3
done;;
let react_touch conn =
while true do
Condition.wait c_touch m;
printf "touche\n%!";
Thread.delay 0.3;
done;;
let () =
let bt =
if Array.length Sys.argv < 2 then (
printf "%s <bluetooth addr>\n" Sys.argv.(0);
exit 1;
)
else Sys.argv.(1) in
let conn = Mindstorm.connect_bluetooth bt in
printf "Connected\n%!";
let _t1 = Thread.create react_touch conn in
let _t2 = Thread.create test_touch conn in
Thread.delay 10.;
printf "FIN\n%!";;
| |
41789193772312dca0ea19960a527e23d644b50f7f1a131246e0056ac07c53bf | grin-compiler/ghc-grin | genObj.hs | # LANGUAGE RecordWildCards #
module Main where
import Control.Monad
import Control.Monad.IO.Class
import System.Environment
import StgLoopback
import Stg.Util
import Stg.ToStg
import Stg.DeadFunctionElimination.StripModule
import qualified GHC.Driver.Types as GHC
import GHC
import GHC.Paths ( libdir )
= StgModule
{ stgUnitId : : UnitId
, stgModuleName : : ModuleName
, stgModuleTyCons : : [ TyCon ]
, stgTopBindings : : [ StgTopBinding ]
, stgForeignStubs : : , stgForeignFiles : : [ ( ForeignSrcLang , FilePath ) ]
}
= StgModule
{ stgUnitId :: UnitId
, stgModuleName :: ModuleName
, stgModuleTyCons :: [TyCon]
, stgTopBindings :: [StgTopBinding]
, stgForeignStubs :: ForeignStubs
, stgForeignFiles :: [(ForeignSrcLang, FilePath)]
}
-}
main :: IO ()
main = runGhc (Just libdir) $ do
let cg = NCG
stgbins <- liftIO getArgs
forM_ stgbins $ \stgbinName -> do
extStgModule <- liftIO $ do
putStrLn $ stgbinName
readStgbin stgbinName
strippedExtModule <- liftIO $ tryStripDeadParts {-stgbinName-}"." extStgModule -- TODO: fix liveness input name
let StgModule{..} = toStg strippedExtModule
oName = stgbinName ++ ".o"
liftIO $ putStrLn $ " compiling " + + oName
putStrLn $ unlines $ map show stgIdUniqueMap
-- HINT: the stubs are compiled at link time
compileToObjectM cg stgUnitId stgModuleName GHC.NoStubs stgModuleTyCons stgTopBindings oName
TODO : simplify API to : compileToObject cg stgModule oName
| null | https://raw.githubusercontent.com/grin-compiler/ghc-grin/ebc4dca2e1f5b3581d4b84726730564ce909d786/patched-lambda-to-ghc-stg/mini-ghc-grin/app/genObj.hs | haskell | stgbinName
TODO: fix liveness input name
HINT: the stubs are compiled at link time | # LANGUAGE RecordWildCards #
module Main where
import Control.Monad
import Control.Monad.IO.Class
import System.Environment
import StgLoopback
import Stg.Util
import Stg.ToStg
import Stg.DeadFunctionElimination.StripModule
import qualified GHC.Driver.Types as GHC
import GHC
import GHC.Paths ( libdir )
= StgModule
{ stgUnitId : : UnitId
, stgModuleName : : ModuleName
, stgModuleTyCons : : [ TyCon ]
, stgTopBindings : : [ StgTopBinding ]
, stgForeignStubs : : , stgForeignFiles : : [ ( ForeignSrcLang , FilePath ) ]
}
= StgModule
{ stgUnitId :: UnitId
, stgModuleName :: ModuleName
, stgModuleTyCons :: [TyCon]
, stgTopBindings :: [StgTopBinding]
, stgForeignStubs :: ForeignStubs
, stgForeignFiles :: [(ForeignSrcLang, FilePath)]
}
-}
main :: IO ()
main = runGhc (Just libdir) $ do
let cg = NCG
stgbins <- liftIO getArgs
forM_ stgbins $ \stgbinName -> do
extStgModule <- liftIO $ do
putStrLn $ stgbinName
readStgbin stgbinName
let StgModule{..} = toStg strippedExtModule
oName = stgbinName ++ ".o"
liftIO $ putStrLn $ " compiling " + + oName
putStrLn $ unlines $ map show stgIdUniqueMap
compileToObjectM cg stgUnitId stgModuleName GHC.NoStubs stgModuleTyCons stgTopBindings oName
TODO : simplify API to : compileToObject cg stgModule oName
|
deaa5c1da5a8cd3ac6c54f643415fa5e5a49b41c142cda9b241b3356076082d9 | camfort/camfort | DenotationalSemantics.hs | # LANGUAGE LambdaCase #
# LANGUAGE TypeFamilies #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE DataKinds #
module Camfort.Specification.Stencils.DenotationalSemantics ( intervalsToRegions
, regionsToIntervals ) where
import Algebra.Lattice
import qualified Data.List.NonEmpty as NE
import qualified Data.Semigroup as SG
import qualified Camfort.Helpers.Vec as V
import Camfort.Specification.Stencils.Model
import Camfort.Specification.Stencils.Syntax
-- preconditions:
1 . If finite interval , all have " lower bound < = 0 < = upper bound " ;
2 . No dimensionality of 0 ; ( insured by dep . type ) ;
3 . All unioned interval lists are of equal length ( insured by dep . type ) .
intervalsToRegions :: UnionNF ('V.S n) (Interval 'Standard)
-> Either String Spatial
intervalsToRegions as = do
sums <- mapM toProd
. maximas -- Final subsumption optimisation
. NE.toList
. SG.sconcat
. fmap asymmetryElim
$ as
return . Spatial . Sum $ sums
where
asymmetryElim :: V.Vec n (Interval a) -> UnionNF n (Interval a)
asymmetryElim ints
| Just ix <- findAsymmetry ints =
case ints V.!! ix of
IntervHoled m n p ->
asymmetryElim (V.replace ix (IntervHoled m 0 p) ints) SG.<>
asymmetryElim (V.replace ix (IntervHoled 0 n p) ints)
_ -> error "intervalsToRegions: asymmetryElim: case ints V.!! ix of ..."
| otherwise = return ints
findAsymmetry =
V.findIndex $ \case
(IntervHoled m n _) -> m /= 0 && n /= 0 && m /= -n
_ -> False
toProd :: V.Vec n (Interval 'Standard) -> Either String RegionProd
toProd ints =
fmap Product $ mapM convert
. filter (isNonInf . fst)
$ zip (V.toList ints) [0..]
isNonInf :: Interval 'Standard -> Bool
isNonInf IntervInfinite = False
isNonInf _ = True
convert :: (Interval 'Standard, Int) -> Either String Region
convert (IntervHoled 0 0 False, _) =
Left "Empty set cannot be realised as a region."
convert (IntervHoled 0 0 True, ix) = return $ Centered 0 (ix + 1) True
convert (IntervHoled 0 m p, ix) = return $ Forward (fromIntegral m) (ix + 1) p
convert (IntervHoled m 0 p, ix) = return $ Backward (fromIntegral $ -m) (ix + 1) p
convert (IntervHoled m n p, ix)
| m == -n = return $ Centered (fromIntegral n) (ix + 1) p
| otherwise = Left $
"Impossible: the lower bound is not negation of upper bound. " ++
"Should have been separated before."
convert _ = Left "Infinite interval cannot be realised as a region."
regionsToIntervals :: forall n .
V.Natural n
-> Spatial
-> Either String (UnionNF n (Interval 'Standard))
regionsToIntervals nOfDims (Spatial (Sum prods))
| null prods = Left "Empty region sum"
| otherwise =
fmap SG.sconcat . sequence . fmap convert . NE.fromList $ prods
where
convert :: RegionProd -> Either String (UnionNF n (Interval 'Standard))
convert (Product rs)
| null rs = Left "Empty region product"
| otherwise = Right $ meets1 . NE.fromList . map convert' $ rs
convert' r = return $ proto nOfDims $
case r of
Forward dep dim p -> (dim-1, IntervHoled 0 (fromIntegral dep) p)
Backward dep dim p -> (dim-1, IntervHoled (- fromIntegral dep) 0 p)
Centered dep dim p -> (dim-1, IntervHoled (- fromIntegral dep) (fromIntegral dep) p)
proto :: forall n' .
V.Natural n'
-> (Int, Interval 'Standard)
-> V.Vec n' (Interval 'Standard)
proto V.Zero _ = V.Nil
proto (V.Succ n) (i, interv) = V.Cons
(if i == 0 then interv else IntervInfinite)
(proto n (i-1, interv))
| null | https://raw.githubusercontent.com/camfort/camfort/3421e85f6fbbcaa6503a266b3fae029a09d2ff24/src/Camfort/Specification/Stencils/DenotationalSemantics.hs | haskell | preconditions:
Final subsumption optimisation | # LANGUAGE LambdaCase #
# LANGUAGE TypeFamilies #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE DataKinds #
module Camfort.Specification.Stencils.DenotationalSemantics ( intervalsToRegions
, regionsToIntervals ) where
import Algebra.Lattice
import qualified Data.List.NonEmpty as NE
import qualified Data.Semigroup as SG
import qualified Camfort.Helpers.Vec as V
import Camfort.Specification.Stencils.Model
import Camfort.Specification.Stencils.Syntax
1 . If finite interval , all have " lower bound < = 0 < = upper bound " ;
2 . No dimensionality of 0 ; ( insured by dep . type ) ;
3 . All unioned interval lists are of equal length ( insured by dep . type ) .
intervalsToRegions :: UnionNF ('V.S n) (Interval 'Standard)
-> Either String Spatial
intervalsToRegions as = do
sums <- mapM toProd
. NE.toList
. SG.sconcat
. fmap asymmetryElim
$ as
return . Spatial . Sum $ sums
where
asymmetryElim :: V.Vec n (Interval a) -> UnionNF n (Interval a)
asymmetryElim ints
| Just ix <- findAsymmetry ints =
case ints V.!! ix of
IntervHoled m n p ->
asymmetryElim (V.replace ix (IntervHoled m 0 p) ints) SG.<>
asymmetryElim (V.replace ix (IntervHoled 0 n p) ints)
_ -> error "intervalsToRegions: asymmetryElim: case ints V.!! ix of ..."
| otherwise = return ints
findAsymmetry =
V.findIndex $ \case
(IntervHoled m n _) -> m /= 0 && n /= 0 && m /= -n
_ -> False
toProd :: V.Vec n (Interval 'Standard) -> Either String RegionProd
toProd ints =
fmap Product $ mapM convert
. filter (isNonInf . fst)
$ zip (V.toList ints) [0..]
isNonInf :: Interval 'Standard -> Bool
isNonInf IntervInfinite = False
isNonInf _ = True
convert :: (Interval 'Standard, Int) -> Either String Region
convert (IntervHoled 0 0 False, _) =
Left "Empty set cannot be realised as a region."
convert (IntervHoled 0 0 True, ix) = return $ Centered 0 (ix + 1) True
convert (IntervHoled 0 m p, ix) = return $ Forward (fromIntegral m) (ix + 1) p
convert (IntervHoled m 0 p, ix) = return $ Backward (fromIntegral $ -m) (ix + 1) p
convert (IntervHoled m n p, ix)
| m == -n = return $ Centered (fromIntegral n) (ix + 1) p
| otherwise = Left $
"Impossible: the lower bound is not negation of upper bound. " ++
"Should have been separated before."
convert _ = Left "Infinite interval cannot be realised as a region."
regionsToIntervals :: forall n .
V.Natural n
-> Spatial
-> Either String (UnionNF n (Interval 'Standard))
regionsToIntervals nOfDims (Spatial (Sum prods))
| null prods = Left "Empty region sum"
| otherwise =
fmap SG.sconcat . sequence . fmap convert . NE.fromList $ prods
where
convert :: RegionProd -> Either String (UnionNF n (Interval 'Standard))
convert (Product rs)
| null rs = Left "Empty region product"
| otherwise = Right $ meets1 . NE.fromList . map convert' $ rs
convert' r = return $ proto nOfDims $
case r of
Forward dep dim p -> (dim-1, IntervHoled 0 (fromIntegral dep) p)
Backward dep dim p -> (dim-1, IntervHoled (- fromIntegral dep) 0 p)
Centered dep dim p -> (dim-1, IntervHoled (- fromIntegral dep) (fromIntegral dep) p)
proto :: forall n' .
V.Natural n'
-> (Int, Interval 'Standard)
-> V.Vec n' (Interval 'Standard)
proto V.Zero _ = V.Nil
proto (V.Succ n) (i, interv) = V.Cons
(if i == 0 then interv else IntervInfinite)
(proto n (i-1, interv))
|
c826be46bfde33ef8e0fa7bbb6b740b8643d2d21e175791722510999f0b9ddbd | MLanguage/mlang | common.ml |
let ( => ) x l = List.mem x l
let ( =: ) x (l, u) = x >= l && x <= u
module StrMap = Map.Make(String)
type nature = Indefinie | Revenu | Charge
type genre = Saisie | Calculee | Base
type type_ = Reel | Booleen | Date
type domaine = Indefini | Contexte | Famille | Revenu |
RevenuCorr | Variation | Penalite
module Var = struct
type t = {
code: string;
alias: string option;
genre: genre;
domaine: domaine;
type_: type_;
nature: nature;
classe: int;
cat_tl: int;
cot_soc: int;
ind_abat: bool;
rap_cat: int;
sanction: int;
acompte: bool;
avfisc: int;
restituee: bool;
}
let compare v1 v2 = String.compare v1.code v2.code
let has_alias var =
match var.alias with
| None -> false
| Some _ -> true
end
module VarDict = struct
type t = (string, Var.t) Hashtbl.t
external charge_vars :
unit -> (string * string option * int * int * int * int * int * int *
int * bool * int * int * int * bool * int * bool) list
= "ml_charge_vars"
let vars : t =
let vars = Hashtbl.create 70000 in
List.iter (fun (code, alias, genre, domaine, type_, nature,
classe, cat_tl, cot_soc, ind_abat, rap_cat,
sanction, indice_tab, acompte, avfisc,
restituee) ->
let genre =
match genre with
| 1 -> Saisie
| 2 -> Calculee
| 3 -> Base
| _ -> assert false
in
let domaine =
match domaine with
| -1 -> Indefini
| 1 -> Contexte
| 2 -> Famille
| 3 -> Revenu
| 4 -> RevenuCorr
| 5 -> Variation
| 6 -> Penalite
| _ -> assert false
in
let type_ =
match type_ with
| 1 -> Reel
| 2 -> Booleen
| 3 -> Date
| _ -> assert false
in
let nature =
match nature with
| -1 -> Indefinie
| 1 -> Revenu
| 2 -> Charge
| _ -> assert false
in
let var = Var.{ code; alias; genre; domaine; type_; nature;
classe; cat_tl; cot_soc; ind_abat; rap_cat;
sanction; acompte; avfisc; restituee } in
Hashtbl.add vars code var;
match alias with
| None -> ()
| Some alias -> Hashtbl.add vars alias var
) (charge_vars ());
vars
let is_alias code =
try
let var = Hashtbl.find vars code in
match var.Var.alias with
| None -> false
| Some alias -> code = alias
with e ->
Printf.printf "Variable non trouvee: %s\n" code;
raise e
let alias code =
try
let var = Hashtbl.find vars code in
match var.Var.alias with
| None -> var.code
| Some alias -> alias
with e ->
Printf.printf "Variable non trouvee: %s\n" code;
raise e
let unalias code =
try
let var = Hashtbl.find vars code in
var.Var.code
with e ->
Printf.printf "Variable non trouvee: %s\n" code;
raise e
let mem code =
Hashtbl.mem vars code
let find code =
try
Hashtbl.find vars code
with e ->
Printf.printf "Variable non trouvee: %s\n" code;
raise e
let filter pred =
Hashtbl.fold
(fun a b map -> if pred a b then StrMap.add a b map else map)
vars StrMap.empty
let fold f acc =
Hashtbl.fold f vars acc
end
module TGV = struct
type t
external alloc_tgv : unit -> t = "ml_tgv_alloc"
external udefined : t -> string -> bool = "ml_tgv_defined"
external ureset : t -> string -> unit = "ml_tgv_reset"
external uget : t -> string -> float option = "ml_tgv_get"
external uget_array : t -> string -> int -> float option = "ml_tgv_get_array"
external uset : t -> string -> float -> unit = "ml_tgv_set"
external reset_calculee : t -> unit = "ml_tgv_reset_calculee"
external reset_base : t -> unit = "ml_tgv_reset_base"
external reset_saisie_calculee : t -> unit = "ml_tgv_reset_saisie_calculee"
external copy_all : t -> t -> unit = "ml_tgv_copy"
let defined tgv var = udefined tgv (VarDict.unalias var)
let reset tgv var = ureset tgv (VarDict.unalias var)
let reset_list (tgv : t) var_list =
List.iter (fun var -> reset tgv var) var_list
let get_opt (tgv : t) var = uget tgv (VarDict.unalias var)
let get_bool_opt (tgv : t) var =
match get_opt tgv var with
| None -> None
| Some v -> Some (v <> 0.0)
let get_int_opt (tgv : t) var =
match get_opt tgv var with
| None -> None
| Some v -> Some (int_of_float v)
let get_def (tgv : t) var def =
match get_opt tgv var with
| None -> def
| Some v -> v
let get_bool_def (tgv : t) var def =
match get_opt tgv var with
| None -> def
| Some v -> v <> 0.0
let get_int_def (tgv : t) var def =
match get_opt tgv var with
| None -> def
| Some v -> int_of_float v
let get_map_opt (tgv : t) var_list =
List.fold_left (fun map var ->
match get_opt tgv var with
| None -> map
| Some v -> StrMap.add (VarDict.unalias var) v map)
StrMap.empty var_list
let get_map_def (tgv : t) var_list def =
List.fold_left (fun map var ->
StrMap.add (VarDict.unalias var) (get_def tgv var def) map)
StrMap.empty var_list
let get_array_opt (tgv : t) var idx =
uget_array tgv (VarDict.unalias var) idx
let get_array_def (tgv : t) var idx def =
match get_array_opt tgv var idx with
| None -> def
| Some v -> v
let set ?(ignore_negative=false) (tgv : t) var v =
if ignore_negative && v < 0.0 then ()
else uset tgv (VarDict.unalias var) v
let set_bool (tgv : t) var v =
set tgv var (if v then 1.0 else 0.0)
let set_int (tgv : t) var v =
set tgv var (float_of_int v)
let set_list0 set (tgv : t) var_v_list =
List.iter (fun (var, v) -> set tgv var v) var_v_list
let set_list (tgv : t) var_v_list =
set_list0 set tgv var_v_list
let set_bool_list (tgv : t) var_v_list =
set_list0 set_bool tgv var_v_list
let set_int_list (tgv : t) var_v_list =
set_list0 set_int tgv var_v_list
let set_map ?(ignore_negative=false) (tgv : t) var_v_map =
StrMap.iter (fun var montant ->
if ignore_negative && montant < 0.0 then ()
else set tgv var montant
) var_v_map
let update (tgv : t) var v_opt =
match v_opt with
| None -> reset tgv var
| Some v -> set tgv var v
let update_bool (tgv : t) var v_opt =
match v_opt with
| None -> reset tgv var
| Some v -> set_bool tgv var v
let update_int (tgv : t) var v_opt =
match v_opt with
| None -> reset tgv var
| Some v -> set_int tgv var v
let copy_abs (tgv : t) svar dvar signvar =
match get_opt tgv svar with
| None -> ()
| Some v ->
set tgv svar (Float.abs v);
set_bool tgv signvar (v < 0.0);
set tgv dvar (Float.abs v)
let reset_saisie_calc ~except tgv =
let save = get_map_opt tgv except in
reset_saisie_calculee tgv;
set_map tgv save
type undef_action =
| UDIgnore
| UDZero
| UDCopy
let internal_copy ~undef (tgv : t) var_list =
List.iter (fun (svar, dvar) ->
match get_opt tgv svar with
| Some v -> set tgv dvar v
| None ->
match undef with
| UDIgnore -> ()
| UDZero -> set tgv dvar 0.0
| UDCopy -> reset tgv dvar
) var_list
let copy_list ~undef (stgv : t) (dtgv : t) var_list =
List.iter (fun (svar, dvar) ->
match get_opt stgv svar with
| Some v -> set dtgv dvar v
| None ->
match undef with
| UDIgnore -> ()
| UDZero -> set dtgv dvar 0.0
| UDCopy -> reset dtgv dvar
) var_list
end
| null | https://raw.githubusercontent.com/MLanguage/mlang/7b8dec6010e1d4124bedc1c0a8dac5dc1eb8987d/examples/dgfip_c/ml_primitif/common.ml | ocaml |
let ( => ) x l = List.mem x l
let ( =: ) x (l, u) = x >= l && x <= u
module StrMap = Map.Make(String)
type nature = Indefinie | Revenu | Charge
type genre = Saisie | Calculee | Base
type type_ = Reel | Booleen | Date
type domaine = Indefini | Contexte | Famille | Revenu |
RevenuCorr | Variation | Penalite
module Var = struct
type t = {
code: string;
alias: string option;
genre: genre;
domaine: domaine;
type_: type_;
nature: nature;
classe: int;
cat_tl: int;
cot_soc: int;
ind_abat: bool;
rap_cat: int;
sanction: int;
acompte: bool;
avfisc: int;
restituee: bool;
}
let compare v1 v2 = String.compare v1.code v2.code
let has_alias var =
match var.alias with
| None -> false
| Some _ -> true
end
module VarDict = struct
type t = (string, Var.t) Hashtbl.t
external charge_vars :
unit -> (string * string option * int * int * int * int * int * int *
int * bool * int * int * int * bool * int * bool) list
= "ml_charge_vars"
let vars : t =
let vars = Hashtbl.create 70000 in
List.iter (fun (code, alias, genre, domaine, type_, nature,
classe, cat_tl, cot_soc, ind_abat, rap_cat,
sanction, indice_tab, acompte, avfisc,
restituee) ->
let genre =
match genre with
| 1 -> Saisie
| 2 -> Calculee
| 3 -> Base
| _ -> assert false
in
let domaine =
match domaine with
| -1 -> Indefini
| 1 -> Contexte
| 2 -> Famille
| 3 -> Revenu
| 4 -> RevenuCorr
| 5 -> Variation
| 6 -> Penalite
| _ -> assert false
in
let type_ =
match type_ with
| 1 -> Reel
| 2 -> Booleen
| 3 -> Date
| _ -> assert false
in
let nature =
match nature with
| -1 -> Indefinie
| 1 -> Revenu
| 2 -> Charge
| _ -> assert false
in
let var = Var.{ code; alias; genre; domaine; type_; nature;
classe; cat_tl; cot_soc; ind_abat; rap_cat;
sanction; acompte; avfisc; restituee } in
Hashtbl.add vars code var;
match alias with
| None -> ()
| Some alias -> Hashtbl.add vars alias var
) (charge_vars ());
vars
let is_alias code =
try
let var = Hashtbl.find vars code in
match var.Var.alias with
| None -> false
| Some alias -> code = alias
with e ->
Printf.printf "Variable non trouvee: %s\n" code;
raise e
let alias code =
try
let var = Hashtbl.find vars code in
match var.Var.alias with
| None -> var.code
| Some alias -> alias
with e ->
Printf.printf "Variable non trouvee: %s\n" code;
raise e
let unalias code =
try
let var = Hashtbl.find vars code in
var.Var.code
with e ->
Printf.printf "Variable non trouvee: %s\n" code;
raise e
let mem code =
Hashtbl.mem vars code
let find code =
try
Hashtbl.find vars code
with e ->
Printf.printf "Variable non trouvee: %s\n" code;
raise e
let filter pred =
Hashtbl.fold
(fun a b map -> if pred a b then StrMap.add a b map else map)
vars StrMap.empty
let fold f acc =
Hashtbl.fold f vars acc
end
module TGV = struct
type t
external alloc_tgv : unit -> t = "ml_tgv_alloc"
external udefined : t -> string -> bool = "ml_tgv_defined"
external ureset : t -> string -> unit = "ml_tgv_reset"
external uget : t -> string -> float option = "ml_tgv_get"
external uget_array : t -> string -> int -> float option = "ml_tgv_get_array"
external uset : t -> string -> float -> unit = "ml_tgv_set"
external reset_calculee : t -> unit = "ml_tgv_reset_calculee"
external reset_base : t -> unit = "ml_tgv_reset_base"
external reset_saisie_calculee : t -> unit = "ml_tgv_reset_saisie_calculee"
external copy_all : t -> t -> unit = "ml_tgv_copy"
let defined tgv var = udefined tgv (VarDict.unalias var)
let reset tgv var = ureset tgv (VarDict.unalias var)
let reset_list (tgv : t) var_list =
List.iter (fun var -> reset tgv var) var_list
let get_opt (tgv : t) var = uget tgv (VarDict.unalias var)
let get_bool_opt (tgv : t) var =
match get_opt tgv var with
| None -> None
| Some v -> Some (v <> 0.0)
let get_int_opt (tgv : t) var =
match get_opt tgv var with
| None -> None
| Some v -> Some (int_of_float v)
let get_def (tgv : t) var def =
match get_opt tgv var with
| None -> def
| Some v -> v
let get_bool_def (tgv : t) var def =
match get_opt tgv var with
| None -> def
| Some v -> v <> 0.0
let get_int_def (tgv : t) var def =
match get_opt tgv var with
| None -> def
| Some v -> int_of_float v
let get_map_opt (tgv : t) var_list =
List.fold_left (fun map var ->
match get_opt tgv var with
| None -> map
| Some v -> StrMap.add (VarDict.unalias var) v map)
StrMap.empty var_list
let get_map_def (tgv : t) var_list def =
List.fold_left (fun map var ->
StrMap.add (VarDict.unalias var) (get_def tgv var def) map)
StrMap.empty var_list
let get_array_opt (tgv : t) var idx =
uget_array tgv (VarDict.unalias var) idx
let get_array_def (tgv : t) var idx def =
match get_array_opt tgv var idx with
| None -> def
| Some v -> v
let set ?(ignore_negative=false) (tgv : t) var v =
if ignore_negative && v < 0.0 then ()
else uset tgv (VarDict.unalias var) v
let set_bool (tgv : t) var v =
set tgv var (if v then 1.0 else 0.0)
let set_int (tgv : t) var v =
set tgv var (float_of_int v)
let set_list0 set (tgv : t) var_v_list =
List.iter (fun (var, v) -> set tgv var v) var_v_list
let set_list (tgv : t) var_v_list =
set_list0 set tgv var_v_list
let set_bool_list (tgv : t) var_v_list =
set_list0 set_bool tgv var_v_list
let set_int_list (tgv : t) var_v_list =
set_list0 set_int tgv var_v_list
let set_map ?(ignore_negative=false) (tgv : t) var_v_map =
StrMap.iter (fun var montant ->
if ignore_negative && montant < 0.0 then ()
else set tgv var montant
) var_v_map
let update (tgv : t) var v_opt =
match v_opt with
| None -> reset tgv var
| Some v -> set tgv var v
let update_bool (tgv : t) var v_opt =
match v_opt with
| None -> reset tgv var
| Some v -> set_bool tgv var v
let update_int (tgv : t) var v_opt =
match v_opt with
| None -> reset tgv var
| Some v -> set_int tgv var v
let copy_abs (tgv : t) svar dvar signvar =
match get_opt tgv svar with
| None -> ()
| Some v ->
set tgv svar (Float.abs v);
set_bool tgv signvar (v < 0.0);
set tgv dvar (Float.abs v)
let reset_saisie_calc ~except tgv =
let save = get_map_opt tgv except in
reset_saisie_calculee tgv;
set_map tgv save
type undef_action =
| UDIgnore
| UDZero
| UDCopy
let internal_copy ~undef (tgv : t) var_list =
List.iter (fun (svar, dvar) ->
match get_opt tgv svar with
| Some v -> set tgv dvar v
| None ->
match undef with
| UDIgnore -> ()
| UDZero -> set tgv dvar 0.0
| UDCopy -> reset tgv dvar
) var_list
let copy_list ~undef (stgv : t) (dtgv : t) var_list =
List.iter (fun (svar, dvar) ->
match get_opt stgv svar with
| Some v -> set dtgv dvar v
| None ->
match undef with
| UDIgnore -> ()
| UDZero -> set dtgv dvar 0.0
| UDCopy -> reset dtgv dvar
) var_list
end
| |
ff58ef077ad4556476d08502d93f6d9c846f65c279e54862e2f26ce3a902b835 | s-expressionists/Cleavir | definitions.lisp | (in-package #:cleavir-primop-info)
(macrolet ((defprimops (&rest specs)
`(progn
,@(loop for spec in specs
collect `(defprimop ,@spec)))))
(defprimops
(cleavir-primop:car 1 :value :flushable)
(cleavir-primop:cdr 1 :value :flushable)
(cleavir-primop:rplaca 2 :effect)
(cleavir-primop:rplacd 2 :effect)
(symbol-value 1 :value :flushable)
((setf symbol-value) 2 :effect)
(fdefinition 1 :value :flushable)
(cleavir-primop:slot-read 2 :value :flushable)
(cleavir-primop:slot-write 3 :effect)
(cleavir-primop:funcallable-slot-read 2 :value :flushable)
(cleavir-primop:funcallable-slot-write 3 :effect)
(cleavir-primop:fixnum-less 2 2 :flushable)
(cleavir-primop:fixnum-not-greater 2 2 :flushable)
(cleavir-primop:fixnum-equal 2 2 :flushable)))
| null | https://raw.githubusercontent.com/s-expressionists/Cleavir/cb66dc81b880a096edbd5a7028b74f7fda0daef3/Primop/definitions.lisp | lisp | (in-package #:cleavir-primop-info)
(macrolet ((defprimops (&rest specs)
`(progn
,@(loop for spec in specs
collect `(defprimop ,@spec)))))
(defprimops
(cleavir-primop:car 1 :value :flushable)
(cleavir-primop:cdr 1 :value :flushable)
(cleavir-primop:rplaca 2 :effect)
(cleavir-primop:rplacd 2 :effect)
(symbol-value 1 :value :flushable)
((setf symbol-value) 2 :effect)
(fdefinition 1 :value :flushable)
(cleavir-primop:slot-read 2 :value :flushable)
(cleavir-primop:slot-write 3 :effect)
(cleavir-primop:funcallable-slot-read 2 :value :flushable)
(cleavir-primop:funcallable-slot-write 3 :effect)
(cleavir-primop:fixnum-less 2 2 :flushable)
(cleavir-primop:fixnum-not-greater 2 2 :flushable)
(cleavir-primop:fixnum-equal 2 2 :flushable)))
| |
49cd2a819842e855b565c032d67390c0e4bacadb12f3e58aa59eca407335784f | metosin/compojure-api | server.clj | (ns examples.server
(:gen-class)
(:require [org.httpkit.server :as httpkit]
[compojure.api.middleware :refer [wrap-components]]
[com.stuartsierra.component :as component]
[examples.thingie :refer [app]]
[reloaded.repl :refer [go set-init!]]))
(defrecord Example []
component/Lifecycle
(start [this]
(assoc this :example "hello world"))
(stop [this]
this))
(defrecord HttpKit []
component/Lifecycle
(start [this]
(println "Server started at :3000")
(assoc this :http-kit (httpkit/run-server
(wrap-components
#'app
(select-keys this [:example]))
{:port 3000})))
(stop [this]
(if-let [http-kit (:http-kit this)]
(http-kit))
(dissoc this :http-kit)))
(defn new-system []
(component/system-map
:example (->Example)
:http-kit (component/using (->HttpKit) [:example])))
(defn -main []
(set-init! #(new-system))
(go))
| null | https://raw.githubusercontent.com/metosin/compojure-api/5c88f32fe56cdb6fcdb3cc506bb956943fcd8c17/examples/thingie/src/examples/server.clj | clojure | (ns examples.server
(:gen-class)
(:require [org.httpkit.server :as httpkit]
[compojure.api.middleware :refer [wrap-components]]
[com.stuartsierra.component :as component]
[examples.thingie :refer [app]]
[reloaded.repl :refer [go set-init!]]))
(defrecord Example []
component/Lifecycle
(start [this]
(assoc this :example "hello world"))
(stop [this]
this))
(defrecord HttpKit []
component/Lifecycle
(start [this]
(println "Server started at :3000")
(assoc this :http-kit (httpkit/run-server
(wrap-components
#'app
(select-keys this [:example]))
{:port 3000})))
(stop [this]
(if-let [http-kit (:http-kit this)]
(http-kit))
(dissoc this :http-kit)))
(defn new-system []
(component/system-map
:example (->Example)
:http-kit (component/using (->HttpKit) [:example])))
(defn -main []
(set-init! #(new-system))
(go))
| |
289bbe7f75d998bafc8d7e8b64515660f952d2cd1972216fab331dc06767fe7b | chaw/r7rs-libs | format-test.sps | " formatst.scm " SLIB FORMAT Version 3.0 conformance test
Written by ( )
;
; This code is in the public domain.
Packaged for R7RS Scheme and SRFI 64 tests by , 2017
;;
-- passes all but 3 tests
(import (scheme base)
(scheme char)
(scheme write)
(slib format)
(slib string-case)
(srfi 64))
(define (test format-args out-str)
(let ((format-out (apply format `(#f ,@format-args))))
(if (string=? out-str format-out)
(test-assert #t)
(begin
(format #t "Failed ~a ~a ~a~&" format-args out-str format-out)
(test-assert #f)))))
(test-begin "slib-format")
; any object test
(test '("abc") "abc")
(test '("~a" 10) "10")
(test '("~a" -1.2) "-1.2")
(test '("~a" a) "a")
(test '("~a" #t) "#t")
(test '("~a" #f) "#f")
(test '("~a" "abc") "abc")
(test '("~a" #(1 2 3)) "#(1 2 3)")
(test '("~a" ()) "()")
(test '("~a" (a)) "(a)")
(test '("~a" (a b)) "(a b)")
(test '("~a" (a (b c) d)) "(a (b c) d)")
(test '("~a" (a . b)) "(a . b)")
(test '("~a" (a (b c . d))) "(a (b . (c . d)))") ; this is ugly
(test `("~a" ,display) (format:iobj->str display #f))
(test `("~a" ,(current-input-port)) (format:iobj->str (current-input-port) #f))
(test `("~a" ,(current-output-port)) (format:iobj->str (current-output-port) #f))
; # argument test
(test '("~a ~a" 10 20) "10 20")
(test '("~a abc ~a def" 10 20) "10 abc 20 def")
; numerical test
(test '("~d" 100) "100")
(test '("~x" 100) "64")
(test '("~o" 100) "144")
(test '("~b" 100) "1100100")
(test '("~@d" 100) "+100")
(test '("~@d" -100) "-100")
(test '("~@x" 100) "+64")
(test '("~@o" 100) "+144")
(test '("~@b" 100) "+1100100")
(test '("~10d" 100) " 100")
(test '("~:d" 123) "123")
(test '("~:d" 1234) "1,234")
(test '("~:d" 12345) "12,345")
(test '("~:d" 123456) "123,456")
(test '("~:d" 12345678) "12,345,678")
(test '("~:d" -123) "-123")
(test '("~:d" -1234) "-1,234")
(test '("~:d" -12345) "-12,345")
(test '("~:d" -123456) "-123,456")
(test '("~:d" -12345678) "-12,345,678")
(test '("~10:d" 1234) " 1,234")
(test '("~10:d" -1234) " -1,234")
(test '("~10,'*d" 100) "*******100")
(test '("~10,,'|:d" 12345678) "12|345|678")
(test '("~10,,,2:d" 12345678) "12,34,56,78")
(test '("~14,'*,'|,4:@d" 12345678) "****+1234|5678")
(test '("~10r" 100) "100")
(test '("~2r" 100) "1100100")
(test '("~8r" 100) "144")
(test '("~16r" 100) "64")
(test '("~16,10,'*r" 100) "********64")
; roman numeral test
(test '("~@r" 4) "IV")
(test '("~@r" 19) "XIX")
(test '("~@r" 50) "L")
(test '("~@r" 100) "C")
(test '("~@r" 1000) "M")
(test '("~@r" 99) "XCIX")
(test '("~@r" 1994) "MCMXCIV")
; old roman numeral test
(test '("~:@r" 4) "IIII")
(test '("~:@r" 5) "V")
(test '("~:@r" 10) "X")
(test '("~:@r" 9) "VIIII")
cardinal / ordinal English number test
(test '("~r" 4) "four")
(test '("~r" 10) "ten")
(test '("~r" 19) "nineteen")
(test '("~r" 1984) "one thousand, nine hundred eighty-four")
(test '("~:r" -1984) "minus one thousand, nine hundred eighty-fourth")
; character test
(test '("~c" #\a) "a")
(test '("~@c" #\a) "#\\a")
(test `("~@c" ,(integer->char 32)) "#\\space")
(test `("~@c" ,(integer->char 0)) "#\\nul")
(test `("~@c" ,(integer->char 27)) "#\\esc")
(test `("~@c" ,(integer->char 127)) "#\\del")
(test `("~@c" ,(integer->char 128)) "#\\200")
(test `("~@c" ,(integer->char 255)) "#\\377")
(test '("~65c") "A")
(test '("~7@c") "#\\bel")
(test '("~:c" #\a) "a")
(test `("~:c" ,(integer->char 1)) "^A")
(test `("~:c" ,(integer->char 27)) "^[")
(test '("~7:c") "^G")
(test `("~:c" ,(integer->char 128)) "#\\200")
(test `("~:c" ,(integer->char 127)) "#\\177")
(test `("~:c" ,(integer->char 255)) "#\\377")
; plural test
(test '("test~p" 1) "test")
(test '("test~p" 2) "tests")
(test '("test~p" 0) "tests")
(test '("tr~@p" 1) "try")
(test '("tr~@p" 2) "tries")
(test '("tr~@p" 0) "tries")
(test '("~a test~:p" 10) "10 tests")
(test '("~a test~:p" 1) "1 test")
; tilde test
(test '("~~~~") "~~")
(test '("~3~") "~~~")
; whitespace character test
(test '("~%") "
")
(test '("~3%") "
")
(test '("~&") "")
(test '("abc~&") "abc
")
(test '("abc~&def") "abc
def")
(test '("~&") "
")
(test '("~3&") "
")
(test '("abc~3&") "abc
")
(test '("~|") (string #\x0C))
(test '("~_~_~_") " ")
(test '("~3_") " ")
(test '("~/") (string #\tab))
(test '("~3/") (make-string 3 #\tab))
; tabulate test
(test '("~0&~3t") " ")
(test '("~0&~10t") " ")
(test '("~10t") "")
(test '("~0&1234567890~,8tABC") "1234567890 ABC")
(test '("~0&1234567890~0,8tABC") "1234567890 ABC")
(test '("~0&1234567890~1,8tABC") "1234567890 ABC")
(test '("~0&1234567890~2,8tABC") "1234567890ABC")
(test '("~0&1234567890~3,8tABC") "1234567890 ABC")
(test '("~0&1234567890~4,8tABC") "1234567890 ABC")
(test '("~0&1234567890~5,8tABC") "1234567890 ABC")
(test '("~0&1234567890~6,8tABC") "1234567890 ABC")
(test '("~0&1234567890~7,8tABC") "1234567890 ABC")
(test '("~0&1234567890~8,8tABC") "1234567890 ABC")
(test '("~0&1234567890~9,8tABC") "1234567890 ABC")
(test '("~0&1234567890~10,8tABC") "1234567890ABC")
(test '("~0&1234567890~11,8tABC") "1234567890 ABC")
(test '("~0&12345~,8tABCDE~,8tXYZ") "12345 ABCDE XYZ")
(test '("~,8t+++~,8t===") " +++ ===")
(test '("~0&ABC~,8,'.tDEF") "ABC......DEF")
(test '("~0&~3,8@tABC") " ABC")
(test '("~0&1234~3,8@tABC") "1234 ABC")
(test '("~0&12~3,8@tABC~3,8@tDEF") "12 ABC DEF")
; indirection test
(test '("~a ~? ~a" 10 "~a ~a" (20 30) 40) "10 20 30 40")
(test '("~a ~@? ~a" 10 "~a ~a" 20 30 40) "10 20 30 40")
; field test
(test '("~10a" "abc") "abc ")
(test '("~10@a" "abc") " abc")
(test '("~10a" "0123456789abc") "0123456789abc")
(test '("~10@a" "0123456789abc") "0123456789abc")
; pad character test
(test '("~10,,,'*a" "abc") "abc*******")
(test '("~10,,,'Xa" "abc") "abcXXXXXXX")
(test '("~10,,,42a" "abc") "abc*******")
(test '("~10,,,'*@a" "abc") "*******abc")
(test '("~10,,3,'*a" "abc") "abc*******")
(test '("~10,,3,'*a" "0123456789abc") "0123456789abc***") ; min. padchar length
(test '("~10,,3,'*@a" "0123456789abc") "***0123456789abc")
colinc , minpad padding test
(test '("~10,8,0,'*a" 123) "123********")
(test '("~10,9,0,'*a" 123) "123*********")
(test '("~10,10,0,'*a" 123) "123**********")
(test '("~10,11,0,'*a" 123) "123***********")
(test '("~8,1,0,'*a" 123) "123*****")
(test '("~8,2,0,'*a" 123) "123******")
(test '("~8,3,0,'*a" 123) "123******")
(test '("~8,4,0,'*a" 123) "123********")
(test '("~8,5,0,'*a" 123) "123*****")
(test '("~8,1,3,'*a" 123) "123*****")
(test '("~8,1,5,'*a" 123) "123*****")
(test '("~8,1,6,'*a" 123) "123******")
(test '("~8,1,9,'*a" 123) "123*********")
; slashify test
(test '("~s" "abc") "\"abc\"")
(test '("~s" "abc \\ abc") "\"abc \\\\ abc\"")
(test '("~a" "abc \\ abc") "abc \\ abc")
(test '("~s" "abc \" abc") "\"abc \\\" abc\"")
(test '("~a" "abc \" abc") "abc \" abc")
(test '("~s" #\space) "#\\space")
(test '("~s" #\newline) "#\\newline")
(test `("~s" ,#\tab) "#\\ht")
(test '("~s" #\a) "#\\a")
(test '("~a" (a "b" c)) "(a \"b\" c)")
; symbol case force test
(parameterize ((format:symbol-case-conv string-upcase))
(test '("~a" abc) "ABC"))
(parameterize ((format:symbol-case-conv string-downcase))
(test '("~s" abc) "abc"))
(parameterize ((format:symbol-case-conv string-capitalize))
(test '("~s" abc) "Abc"))
; read proof test
(test `("~:s" ,display) (format:iobj->str display #t))
(test `("~:a" ,display) (format:iobj->str display #t))
(test `("~:a" (1 2 ,display)) (string-append "(1 2 " (format:iobj->str display #t) ")"))
(test '("~:a" "abc") "abc")
; internal object case type force test
(parameterize ((format:iobj-case-conv string-upcase))
(test `("~a" ,display) (string-upcase (format:iobj->str display #f))))
(parameterize ((format:iobj-case-conv string-downcase))
(test `("~s" ,display) (string-downcase (format:iobj->str display #f))))
(parameterize ((format:iobj-case-conv string-capitalize))
(test `("~s" ,display) (string-capitalize (format:iobj->str display #f))))
; continuation line test
(test '("abc~
123") "abc123")
(test '("abc~
123") "abc123")
(test '("abc~
") "abc")
(test '("abc~:
def") "abc def")
(test '("abc~@
def")
"abc
def")
; flush output (can't test it here really)
(test '("abc ~! xyz") "abc xyz")
; string case conversion
(test '("~a ~(~a~) ~a" "abc" "HELLO WORLD" "xyz") "abc hello world xyz")
(test '("~a ~:(~a~) ~a" "abc" "HELLO WORLD" "xyz") "abc Hello World xyz")
(test '("~a ~@(~a~) ~a" "abc" "HELLO WORLD" "xyz") "abc Hello world xyz")
(test '("~a ~:@(~a~) ~a" "abc" "hello world" "xyz") "abc HELLO WORLD xyz")
(test '("~:@(~a~)" (a b c)) "(A B C)")
(test '("~:@(~x~)" 255) "FF")
(test '("~:@(~p~)" 2) "S")
;(test `("~:@(~a~)" ,display) (string-upcase (format:iobj->str display #f)))
(test '("~:(~a ~a ~a~) ~a" "abc" "xyz" "123" "world") "Abc Xyz 123 world")
; variable parameter
(test '("~va" 10 "abc") "abc ")
(test '("~v,,,va" 10 42 "abc") "abc*******")
; number of remaining arguments as parameter
(test '("~#,,,'*@a ~a ~a ~a" 1 1 1 1) "***1 1 1 1")
; argument jumping
(test '("~a ~* ~a" 10 20 30) "10 30")
(test '("~a ~2* ~a" 10 20 30 40) "10 40")
(test '("~a ~:* ~a" 10) "10 10")
(test '("~a ~a ~2:* ~a ~a" 10 20) "10 20 10 20")
(test '("~a ~a ~@* ~a ~a" 10 20) "10 20 10 20")
(test '("~a ~a ~4@* ~a ~a" 10 20 30 40 50 60) "10 20 50 60")
; conditionals
(test '("~[abc~;xyz~]" 0) "abc")
(test '("~[abc~;xyz~]" 1) "xyz")
(test '("~[abc~;xyz~:;456~]" 99) "456")
(test '("~0[abc~;xyz~:;456~]") "abc")
(test '("~1[abc~;xyz~:;456~] ~a" 100) "xyz 100")
(test '("~#[no arg~;~a~;~a and ~a~;~a, ~a and ~a~]") "no arg")
(test '("~#[no arg~;~a~;~a and ~a~;~a, ~a and ~a~]" 10) "10")
(test '("~#[no arg~;~a~;~a and ~a~;~a, ~a and ~a~]" 10 20) "10 and 20")
(test '("~#[no arg~;~a~;~a and ~a~;~a, ~a and ~a~]" 10 20 30) "10, 20 and 30")
(test '("~:[hello~;world~] ~a" #t 10) "world 10")
(test '("~:[hello~;world~] ~a" #f 10) "hello 10")
(test '("~@[~a tests~]" #f) "")
(test '("~@[~a tests~]" 10) "10 tests")
(test '("~@[~a test~:p~] ~a" 10 done) "10 tests done")
(test '("~@[~a test~:p~] ~a" 1 done) "1 test done")
(test '("~@[~a test~:p~] ~a" 0 done) "0 tests done")
(test '("~@[~a test~:p~] ~a" #f done) " done")
(test '("~@[ level = ~d~]~@[ length = ~d~]" #f 5) " length = 5")
(test '("~[abc~;~[4~;5~;6~]~;xyz~]" 0) "abc") ; nested conditionals (irrghh)
(test '("~[abc~;~[4~;5~;6~]~;xyz~]" 2) "xyz")
(test '("~[abc~;~[4~;5~;6~]~;xyz~]" 1 2) "6")
; iteration
(test '("~{ ~a ~}" (a b c)) " a b c ")
(test '("~{ ~a ~}" ()) "")
(test '("~{ ~a ~5,,,'*a~}" (a b c d)) " a b**** c d****")
(test '("~{ ~a,~a ~}" (a 1 b 2 c 3)) " a,1 b,2 c,3 ")
(test '("~2{ ~a,~a ~}" (a 1 b 2 c 3)) " a,1 b,2 ")
(test '("~3{~a ~} ~a" (a b c d e) 100) "a b c 100")
(test '("~0{~a ~} ~a" (a b c d e) 100) " 100")
(test '("~:{ ~a,~a ~}" ((a b) (c d e f) (g h))) " a,b c,d g,h ")
(test '("~2:{ ~a,~a ~}" ((a b) (c d e f) (g h))) " a,b c,d ")
(test '("~@{ ~a,~a ~}" a 1 b 2 c 3) " a,1 b,2 c,3 ")
(test '("~2@{ ~a,~a ~} <~a|~a>" a 1 b 2 c 3) " a,1 b,2 <c|3>")
(test '("~:@{ ~a,~a ~}" (a 1) (b 2) (c 3)) " a,1 b,2 c,3 ")
(test '("~2:@{ ~a,~a ~} ~a" (a 1) (b 2) (c 3)) " a,1 b,2 (c 3)")
(test '("~{~}" "<~a,~a>" (a 1 b 2 c 3)) "<a,1><b,2><c,3>")
(test '("~{ ~a ~{<~a>~}~} ~a" (a (1 2) b (3 4)) 10) " a <1><2> b <3><4> 10")
(let ((nums (let iter ((ns '()) (l 0))
(if (> l 105) (reverse ns) (iter (cons l ns) (+ l 1))))))
Test default , only 100 items formatted out :
(test `("~D~{, ~D~}" ,(car nums) ,(cdr nums))
"0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100")
;; Test control of number of items formatted out:
(parameterize ((format:max-iterations 90))
(test `("~D~{, ~D~}" ,(car nums) ,(cdr nums))
"0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90")
;; Test control of imposing bound on number of items formatted out:
(parameterize ((format:iteration-bounded #f))
(test `("~D~{, ~D~}" ,(car nums) ,(cdr nums))
"0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105"))))
; up and out
(test '("abc ~^ xyz") "abc ")
(test '("~@(abc ~^ xyz~) ~a" 10) "ABC xyz 10")
(test '("done. ~^ ~d warning~:p. ~^ ~d error~:p.") "done. ")
(test '("done. ~^ ~d warning~:p. ~^ ~d error~:p." 10) "done. 10 warnings. ")
(test '("done. ~^ ~d warning~:p. ~^ ~d error~:p." 10 1)
"done. 10 warnings. 1 error.")
(test '("~{ ~a ~^<~a>~} ~a" (a b c d e f) 10) " a <b> c <d> e <f> 10")
(test '("~{ ~a ~^<~a>~} ~a" (a b c d e) 10) " a <b> c <d> e 10")
(test '("abc~0^ xyz") "abc")
(test '("abc~9^ xyz") "abc xyz")
(test '("abc~7,4^ xyz") "abc xyz")
(test '("abc~7,7^ xyz") "abc")
(test '("abc~3,7,9^ xyz") "abc")
(test '("abc~8,7,9^ xyz") "abc xyz")
(test '("abc~3,7,5^ xyz") "abc xyz")
complexity tests ( oh my god , I hardly understand them myself ( see CL std ) )
(define fmt "Items:~#[ none~; ~a~; ~a and ~a~:;~@{~#[~; and~] ~a~^,~}~].")
(test `(,fmt ) "Items: none.")
(test `(,fmt foo) "Items: foo.")
(test `(,fmt foo bar) "Items: foo and bar.")
(test `(,fmt foo bar baz) "Items: foo, bar, and baz.")
(test `(,fmt foo bar baz zok) "Items: foo, bar, baz, and zok.")
; fixed floating points
(test '("~6,2f" 3.14159) " 3.14")
(test '("~6,1f" 3.14159) " 3.1")
(test '("~6,0f" 3.14159) " 3.")
(test '("~5,1f" 0) " 0.0")
(test '("~10,7f" 3.14159) " 3.1415900")
(test '("~10,7f" -3.14159) "-3.1415900")
(test '("~10,7@f" 3.14159) "+3.1415900")
(test '("~6,3f" 0.0) " 0.000")
(test '("~6,4f" 0.007) "0.0070")
(test '("~6,3f" 0.007) " 0.007")
(test '("~6,2f" 0.007) " 0.01")
(test '("~3,2f" 0.007) ".01")
(test '("~3,2f" -0.007) "-.01")
(test '("~6,2,,,'*f" 3.14159) "**3.14")
(test '("~6,3,,'?f" 12345.56789) "??????")
(test '("~6,3f" 12345.6789) "12345.679")
(test '("~,3f" 12345.6789) "12345.679")
(test '("~,3f" 9.9999) "10.000")
(test '("~6f" 23.4) " 23.4")
(test '("~6f" 1234.5) "1234.5")
(test '("~6f" 12345678) "12345678.0")
(test '("~6,,,'?f" 12345678) "??????")
(test '("~6f" 123.56789) "123.57")
(test '("~6f" 123.0) " 123.0")
(test '("~6f" -123.0) "-123.0")
(test '("~6f" 0.0) " 0.0")
(test '("~3f" 3.141) "3.1")
(test '("~2f" 3.141) "3.")
(test '("~1f" 3.141) "3.141")
(test '("~f" 123.56789) "123.56789")
(test '("~f" -314.0) "-314.0")
(test '("~f" 1e4) "10000.0")
(test '("~f" -1.23e10) "-12300000000.0")
(test '("~f" 1e-4) "0.0001")
(test '("~f" -1.23e-10) "-0.000000000123")
(test '("~@f" 314.0) "+314.0")
(test '("~,,3f" 0.123456) "123.456")
(test '("~,,-3f" -123.456) "-0.123456")
(test '("~5,,3f" 0.123456) "123.5")
; exponent floating points
(test '("~e" 3.14159) "3.14159E+0")
(test '("~e" 0.00001234) "1.234E-5")
(test '("~,,,0e" 0.00001234) "0.1234E-4")
(test '("~,3e" 3.14159) "3.142E+0")
(test '("~,3@e" 3.14159) "+3.142E+0")
(test '("~,3@e" 0.0) "+0.000E+0")
(test '("~,0e" 3.141) "3.E+0")
(test '("~,3,,0e" 3.14159) "0.314E+1")
(test '("~,5,3,-2e" 3.14159) "0.00314E+003")
(test '("~,5,3,-5e" -3.14159) "-0.00000E+006")
(test '("~,5,2,2e" 3.14159) "31.4159E-01")
(test '("~,5,2,,,,'ee" 0.0) "0.00000e+00")
(test '("~12,3e" -3.141) " -3.141E+0")
(test '("~12,3,,,,'#e" -3.141) "###-3.141E+0")
(test '("~10,2e" -1.236e-4) " -1.24E-4")
(test '("~5,3e" -3.141) "-3.141E+0")
(test '("~5,3,,,'*e" -3.141) "*****")
(test '("~3e" 3.14159) "3.14159E+0")
(test '("~4e" 3.14159) "3.14159E+0")
(test '("~5e" 3.14159) "3.E+0")
(test '("~5,,,,'*e" 3.14159) "3.E+0")
(test '("~6e" 3.14159) "3.1E+0")
(test '("~7e" 3.14159) "3.14E+0")
(test '("~7e" -3.14159) "-3.1E+0")
(test '("~8e" 3.14159) "3.142E+0")
(test '("~9e" 3.14159) "3.1416E+0")
(test '("~9,,,,,,'ee" 3.14159) "3.1416e+0")
(test '("~10e" 3.14159) "3.14159E+0")
(test '("~11e" 3.14159) " 3.14159E+0")
(test '("~12e" 3.14159) " 3.14159E+0")
(test '("~13,6,2,-5e" 3.14159) " 0.000003E+06")
(test '("~13,6,2,-4e" 3.14159) " 0.000031E+05")
(test '("~13,6,2,-3e" 3.14159) " 0.000314E+04")
(test '("~13,6,2,-2e" 3.14159) " 0.003142E+03")
(test '("~13,6,2,-1e" 3.14159) " 0.031416E+02")
(test '("~13,6,2,0e" 3.14159) " 0.314159E+01")
(test '("~13,6,2,1e" 3.14159) " 3.141590E+00")
(test '("~13,6,2,2e" 3.14159) " 31.41590E-01")
(test '("~13,6,2,3e" 3.14159) " 314.1590E-02")
(test '("~13,6,2,4e" 3.14159) " 3141.590E-03")
(test '("~13,6,2,5e" 3.14159) " 31415.90E-04")
(test '("~13,6,2,6e" 3.14159) " 314159.0E-05")
(test '("~13,6,2,7e" 3.14159) " 3141590.E-06")
(test '("~13,6,2,8e" 3.14159) "31415900.E-07")
(test '("~7,3,,-2e" 0.001) ".001E+0")
(test '("~8,3,,-2@e" 0.001) "+.001E+0")
(test '("~8,3,,-2@e" -0.001) "-.001E+0")
(test '("~8,3,,-2e" 0.001) "0.001E+0")
(test '("~7,,,-2e" 0.001) "0.00E+0")
(test '("~12,3,1e" 3.14159e12) " 3.142E+12")
(test '("~12,3,1,,'*e" 3.14159e12) "************")
(test '("~5,3,1e" 3.14159e12) "3.142E+12")
general floating point ( this test is from Steele 's CL book )
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
0.0314159 0.0314159 0.0314159 0.0314159)
" 3.14E-2|314.2$-04|0.314E-01| 3.14E-2")
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
0.314159 0.314159 0.314159 0.314159)
" 0.31 |0.314 |0.314 | 0.31 ")
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
3.14159 3.14159 3.14159 3.14159)
" 3.1 | 3.14 | 3.14 | 3.1 ")
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
31.4159 31.4159 31.4159 31.4159)
" 31. | 31.4 | 31.4 | 31. ")
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
314.159 314.159 314.159 314.159)
" 3.14E+2| 314. | 314. | 3.14E+2")
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
3141.59 3141.59 3141.59 3141.59)
" 3.14E+3|314.2$+01|0.314E+04| 3.14E+3")
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
3.14E12 3.14E12 3.14E12 3.14E12)
"*********|314.0$+10|0.314E+13| 3.14E+12")
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
3.14E120 3.14E120 3.14E120 3.14E120)
"*********|?????????|%%%%%%%%%|3.14E+120")
(test '("~g" 0.0) "0.0 ") ; further ~g tests
(test '("~g" 0.1) "0.1 ")
(test '("~g" 0.01) "1.0E-2")
(test '("~g" 123.456) "123.456 ")
(test '("~g" 123456.7) "123456.7 ")
(test '("~g" 123456.78) "123456.78 ")
(test '("~g" 0.9282) "0.9282 ")
(test '("~g" 0.09282) "9.282E-2")
(test '("~g" 1) "1.0 ")
(test '("~g" 12) "12.0 ")
; dollar floating point
(test '("~$" 1.23) "1.23")
(test '("~$" 1.2) "1.20")
(test '("~$" 0.0) "0.00")
(test '("~$" 9.999) "10.00")
(test '("~3$" 9.9999) "10.000")
(test '("~,4$" 3.2) "0003.20")
(test '("~,4$" 10000.2) "10000.20")
(test '("~,4,10$" 3.2) " 0003.20")
(test '("~,4,10@$" 3.2) " +0003.20")
(test '("~,4,10:@$" 3.2) "+ 0003.20")
(test '("~,4,10:$" -3.2) "- 0003.20")
(test '("~,4,10$" -3.2) " -0003.20")
(test '("~,,10@$" 3.2) " +3.20")
(test '("~,,10:@$" 3.2) "+ 3.20")
(test '("~,,10:@$" -3.2) "- 3.20")
(test '("~,,10,'_@$" 3.2) "_____+3.20")
(test '("~,,4$" 1234.4) "1234.40")
; complex numbers
(test '("~i" 3.0) "3.0+0.0i")
(test '("~,3i" 3.0) "3.000+0.000i")
(test `("~7,2i" ,(string->number "3.0+5.0i")) " 3.00 +5.00i")
(test `("~7,2,1i" ,(string->number "3.0+5.0i")) " 30.00 +50.00i")
(test `("~7,2@i" ,(string->number "3.0+5.0i")) " +3.00 +5.00i")
(test `("~7,2,,,'*@i" ,(string->number "3.0+5.0i")) "**+3.00**+5.00i")
; note: some parsers choke syntactically on reading a complex
; number though format:complex is #f; this is why we put them in
; strings
(test-end)
| null | https://raw.githubusercontent.com/chaw/r7rs-libs/b8b625c36b040ff3d4b723e4346629a8a0e8d6c2/slib-tests/format-test.sps | scheme |
This code is in the public domain.
any object test
this is ugly
# argument test
numerical test
roman numeral test
old roman numeral test
character test
plural test
tilde test
whitespace character test
tabulate test
indirection test
field test
pad character test
min. padchar length
slashify test
symbol case force test
read proof test
internal object case type force test
continuation line test
flush output (can't test it here really)
string case conversion
(test `("~:@(~a~)" ,display) (string-upcase (format:iobj->str display #f)))
variable parameter
number of remaining arguments as parameter
argument jumping
conditionals
nested conditionals (irrghh)
iteration
Test control of number of items formatted out:
Test control of imposing bound on number of items formatted out:
up and out
fixed floating points
exponent floating points
further ~g tests
dollar floating point
complex numbers
note: some parsers choke syntactically on reading a complex
number though format:complex is #f; this is why we put them in
strings | " formatst.scm " SLIB FORMAT Version 3.0 conformance test
Written by ( )
Packaged for R7RS Scheme and SRFI 64 tests by , 2017
-- passes all but 3 tests
(import (scheme base)
(scheme char)
(scheme write)
(slib format)
(slib string-case)
(srfi 64))
(define (test format-args out-str)
(let ((format-out (apply format `(#f ,@format-args))))
(if (string=? out-str format-out)
(test-assert #t)
(begin
(format #t "Failed ~a ~a ~a~&" format-args out-str format-out)
(test-assert #f)))))
(test-begin "slib-format")
(test '("abc") "abc")
(test '("~a" 10) "10")
(test '("~a" -1.2) "-1.2")
(test '("~a" a) "a")
(test '("~a" #t) "#t")
(test '("~a" #f) "#f")
(test '("~a" "abc") "abc")
(test '("~a" #(1 2 3)) "#(1 2 3)")
(test '("~a" ()) "()")
(test '("~a" (a)) "(a)")
(test '("~a" (a b)) "(a b)")
(test '("~a" (a (b c) d)) "(a (b c) d)")
(test '("~a" (a . b)) "(a . b)")
(test `("~a" ,display) (format:iobj->str display #f))
(test `("~a" ,(current-input-port)) (format:iobj->str (current-input-port) #f))
(test `("~a" ,(current-output-port)) (format:iobj->str (current-output-port) #f))
(test '("~a ~a" 10 20) "10 20")
(test '("~a abc ~a def" 10 20) "10 abc 20 def")
(test '("~d" 100) "100")
(test '("~x" 100) "64")
(test '("~o" 100) "144")
(test '("~b" 100) "1100100")
(test '("~@d" 100) "+100")
(test '("~@d" -100) "-100")
(test '("~@x" 100) "+64")
(test '("~@o" 100) "+144")
(test '("~@b" 100) "+1100100")
(test '("~10d" 100) " 100")
(test '("~:d" 123) "123")
(test '("~:d" 1234) "1,234")
(test '("~:d" 12345) "12,345")
(test '("~:d" 123456) "123,456")
(test '("~:d" 12345678) "12,345,678")
(test '("~:d" -123) "-123")
(test '("~:d" -1234) "-1,234")
(test '("~:d" -12345) "-12,345")
(test '("~:d" -123456) "-123,456")
(test '("~:d" -12345678) "-12,345,678")
(test '("~10:d" 1234) " 1,234")
(test '("~10:d" -1234) " -1,234")
(test '("~10,'*d" 100) "*******100")
(test '("~10,,'|:d" 12345678) "12|345|678")
(test '("~10,,,2:d" 12345678) "12,34,56,78")
(test '("~14,'*,'|,4:@d" 12345678) "****+1234|5678")
(test '("~10r" 100) "100")
(test '("~2r" 100) "1100100")
(test '("~8r" 100) "144")
(test '("~16r" 100) "64")
(test '("~16,10,'*r" 100) "********64")
(test '("~@r" 4) "IV")
(test '("~@r" 19) "XIX")
(test '("~@r" 50) "L")
(test '("~@r" 100) "C")
(test '("~@r" 1000) "M")
(test '("~@r" 99) "XCIX")
(test '("~@r" 1994) "MCMXCIV")
(test '("~:@r" 4) "IIII")
(test '("~:@r" 5) "V")
(test '("~:@r" 10) "X")
(test '("~:@r" 9) "VIIII")
cardinal / ordinal English number test
(test '("~r" 4) "four")
(test '("~r" 10) "ten")
(test '("~r" 19) "nineteen")
(test '("~r" 1984) "one thousand, nine hundred eighty-four")
(test '("~:r" -1984) "minus one thousand, nine hundred eighty-fourth")
(test '("~c" #\a) "a")
(test '("~@c" #\a) "#\\a")
(test `("~@c" ,(integer->char 32)) "#\\space")
(test `("~@c" ,(integer->char 0)) "#\\nul")
(test `("~@c" ,(integer->char 27)) "#\\esc")
(test `("~@c" ,(integer->char 127)) "#\\del")
(test `("~@c" ,(integer->char 128)) "#\\200")
(test `("~@c" ,(integer->char 255)) "#\\377")
(test '("~65c") "A")
(test '("~7@c") "#\\bel")
(test '("~:c" #\a) "a")
(test `("~:c" ,(integer->char 1)) "^A")
(test `("~:c" ,(integer->char 27)) "^[")
(test '("~7:c") "^G")
(test `("~:c" ,(integer->char 128)) "#\\200")
(test `("~:c" ,(integer->char 127)) "#\\177")
(test `("~:c" ,(integer->char 255)) "#\\377")
(test '("test~p" 1) "test")
(test '("test~p" 2) "tests")
(test '("test~p" 0) "tests")
(test '("tr~@p" 1) "try")
(test '("tr~@p" 2) "tries")
(test '("tr~@p" 0) "tries")
(test '("~a test~:p" 10) "10 tests")
(test '("~a test~:p" 1) "1 test")
(test '("~~~~") "~~")
(test '("~3~") "~~~")
(test '("~%") "
")
(test '("~3%") "
")
(test '("~&") "")
(test '("abc~&") "abc
")
(test '("abc~&def") "abc
def")
(test '("~&") "
")
(test '("~3&") "
")
(test '("abc~3&") "abc
")
(test '("~|") (string #\x0C))
(test '("~_~_~_") " ")
(test '("~3_") " ")
(test '("~/") (string #\tab))
(test '("~3/") (make-string 3 #\tab))
(test '("~0&~3t") " ")
(test '("~0&~10t") " ")
(test '("~10t") "")
(test '("~0&1234567890~,8tABC") "1234567890 ABC")
(test '("~0&1234567890~0,8tABC") "1234567890 ABC")
(test '("~0&1234567890~1,8tABC") "1234567890 ABC")
(test '("~0&1234567890~2,8tABC") "1234567890ABC")
(test '("~0&1234567890~3,8tABC") "1234567890 ABC")
(test '("~0&1234567890~4,8tABC") "1234567890 ABC")
(test '("~0&1234567890~5,8tABC") "1234567890 ABC")
(test '("~0&1234567890~6,8tABC") "1234567890 ABC")
(test '("~0&1234567890~7,8tABC") "1234567890 ABC")
(test '("~0&1234567890~8,8tABC") "1234567890 ABC")
(test '("~0&1234567890~9,8tABC") "1234567890 ABC")
(test '("~0&1234567890~10,8tABC") "1234567890ABC")
(test '("~0&1234567890~11,8tABC") "1234567890 ABC")
(test '("~0&12345~,8tABCDE~,8tXYZ") "12345 ABCDE XYZ")
(test '("~,8t+++~,8t===") " +++ ===")
(test '("~0&ABC~,8,'.tDEF") "ABC......DEF")
(test '("~0&~3,8@tABC") " ABC")
(test '("~0&1234~3,8@tABC") "1234 ABC")
(test '("~0&12~3,8@tABC~3,8@tDEF") "12 ABC DEF")
(test '("~a ~? ~a" 10 "~a ~a" (20 30) 40) "10 20 30 40")
(test '("~a ~@? ~a" 10 "~a ~a" 20 30 40) "10 20 30 40")
(test '("~10a" "abc") "abc ")
(test '("~10@a" "abc") " abc")
(test '("~10a" "0123456789abc") "0123456789abc")
(test '("~10@a" "0123456789abc") "0123456789abc")
(test '("~10,,,'*a" "abc") "abc*******")
(test '("~10,,,'Xa" "abc") "abcXXXXXXX")
(test '("~10,,,42a" "abc") "abc*******")
(test '("~10,,,'*@a" "abc") "*******abc")
(test '("~10,,3,'*a" "abc") "abc*******")
(test '("~10,,3,'*@a" "0123456789abc") "***0123456789abc")
colinc , minpad padding test
(test '("~10,8,0,'*a" 123) "123********")
(test '("~10,9,0,'*a" 123) "123*********")
(test '("~10,10,0,'*a" 123) "123**********")
(test '("~10,11,0,'*a" 123) "123***********")
(test '("~8,1,0,'*a" 123) "123*****")
(test '("~8,2,0,'*a" 123) "123******")
(test '("~8,3,0,'*a" 123) "123******")
(test '("~8,4,0,'*a" 123) "123********")
(test '("~8,5,0,'*a" 123) "123*****")
(test '("~8,1,3,'*a" 123) "123*****")
(test '("~8,1,5,'*a" 123) "123*****")
(test '("~8,1,6,'*a" 123) "123******")
(test '("~8,1,9,'*a" 123) "123*********")
(test '("~s" "abc") "\"abc\"")
(test '("~s" "abc \\ abc") "\"abc \\\\ abc\"")
(test '("~a" "abc \\ abc") "abc \\ abc")
(test '("~s" "abc \" abc") "\"abc \\\" abc\"")
(test '("~a" "abc \" abc") "abc \" abc")
(test '("~s" #\space) "#\\space")
(test '("~s" #\newline) "#\\newline")
(test `("~s" ,#\tab) "#\\ht")
(test '("~s" #\a) "#\\a")
(test '("~a" (a "b" c)) "(a \"b\" c)")
(parameterize ((format:symbol-case-conv string-upcase))
(test '("~a" abc) "ABC"))
(parameterize ((format:symbol-case-conv string-downcase))
(test '("~s" abc) "abc"))
(parameterize ((format:symbol-case-conv string-capitalize))
(test '("~s" abc) "Abc"))
(test `("~:s" ,display) (format:iobj->str display #t))
(test `("~:a" ,display) (format:iobj->str display #t))
(test `("~:a" (1 2 ,display)) (string-append "(1 2 " (format:iobj->str display #t) ")"))
(test '("~:a" "abc") "abc")
(parameterize ((format:iobj-case-conv string-upcase))
(test `("~a" ,display) (string-upcase (format:iobj->str display #f))))
(parameterize ((format:iobj-case-conv string-downcase))
(test `("~s" ,display) (string-downcase (format:iobj->str display #f))))
(parameterize ((format:iobj-case-conv string-capitalize))
(test `("~s" ,display) (string-capitalize (format:iobj->str display #f))))
(test '("abc~
123") "abc123")
(test '("abc~
123") "abc123")
(test '("abc~
") "abc")
(test '("abc~:
def") "abc def")
(test '("abc~@
def")
"abc
def")
(test '("abc ~! xyz") "abc xyz")
(test '("~a ~(~a~) ~a" "abc" "HELLO WORLD" "xyz") "abc hello world xyz")
(test '("~a ~:(~a~) ~a" "abc" "HELLO WORLD" "xyz") "abc Hello World xyz")
(test '("~a ~@(~a~) ~a" "abc" "HELLO WORLD" "xyz") "abc Hello world xyz")
(test '("~a ~:@(~a~) ~a" "abc" "hello world" "xyz") "abc HELLO WORLD xyz")
(test '("~:@(~a~)" (a b c)) "(A B C)")
(test '("~:@(~x~)" 255) "FF")
(test '("~:@(~p~)" 2) "S")
(test '("~:(~a ~a ~a~) ~a" "abc" "xyz" "123" "world") "Abc Xyz 123 world")
(test '("~va" 10 "abc") "abc ")
(test '("~v,,,va" 10 42 "abc") "abc*******")
(test '("~#,,,'*@a ~a ~a ~a" 1 1 1 1) "***1 1 1 1")
(test '("~a ~* ~a" 10 20 30) "10 30")
(test '("~a ~2* ~a" 10 20 30 40) "10 40")
(test '("~a ~:* ~a" 10) "10 10")
(test '("~a ~a ~2:* ~a ~a" 10 20) "10 20 10 20")
(test '("~a ~a ~@* ~a ~a" 10 20) "10 20 10 20")
(test '("~a ~a ~4@* ~a ~a" 10 20 30 40 50 60) "10 20 50 60")
(test '("~[abc~;xyz~]" 0) "abc")
(test '("~[abc~;xyz~]" 1) "xyz")
(test '("~[abc~;xyz~:;456~]" 99) "456")
(test '("~0[abc~;xyz~:;456~]") "abc")
(test '("~1[abc~;xyz~:;456~] ~a" 100) "xyz 100")
(test '("~#[no arg~;~a~;~a and ~a~;~a, ~a and ~a~]") "no arg")
(test '("~#[no arg~;~a~;~a and ~a~;~a, ~a and ~a~]" 10) "10")
(test '("~#[no arg~;~a~;~a and ~a~;~a, ~a and ~a~]" 10 20) "10 and 20")
(test '("~#[no arg~;~a~;~a and ~a~;~a, ~a and ~a~]" 10 20 30) "10, 20 and 30")
(test '("~:[hello~;world~] ~a" #t 10) "world 10")
(test '("~:[hello~;world~] ~a" #f 10) "hello 10")
(test '("~@[~a tests~]" #f) "")
(test '("~@[~a tests~]" 10) "10 tests")
(test '("~@[~a test~:p~] ~a" 10 done) "10 tests done")
(test '("~@[~a test~:p~] ~a" 1 done) "1 test done")
(test '("~@[~a test~:p~] ~a" 0 done) "0 tests done")
(test '("~@[~a test~:p~] ~a" #f done) " done")
(test '("~@[ level = ~d~]~@[ length = ~d~]" #f 5) " length = 5")
(test '("~[abc~;~[4~;5~;6~]~;xyz~]" 2) "xyz")
(test '("~[abc~;~[4~;5~;6~]~;xyz~]" 1 2) "6")
(test '("~{ ~a ~}" (a b c)) " a b c ")
(test '("~{ ~a ~}" ()) "")
(test '("~{ ~a ~5,,,'*a~}" (a b c d)) " a b**** c d****")
(test '("~{ ~a,~a ~}" (a 1 b 2 c 3)) " a,1 b,2 c,3 ")
(test '("~2{ ~a,~a ~}" (a 1 b 2 c 3)) " a,1 b,2 ")
(test '("~3{~a ~} ~a" (a b c d e) 100) "a b c 100")
(test '("~0{~a ~} ~a" (a b c d e) 100) " 100")
(test '("~:{ ~a,~a ~}" ((a b) (c d e f) (g h))) " a,b c,d g,h ")
(test '("~2:{ ~a,~a ~}" ((a b) (c d e f) (g h))) " a,b c,d ")
(test '("~@{ ~a,~a ~}" a 1 b 2 c 3) " a,1 b,2 c,3 ")
(test '("~2@{ ~a,~a ~} <~a|~a>" a 1 b 2 c 3) " a,1 b,2 <c|3>")
(test '("~:@{ ~a,~a ~}" (a 1) (b 2) (c 3)) " a,1 b,2 c,3 ")
(test '("~2:@{ ~a,~a ~} ~a" (a 1) (b 2) (c 3)) " a,1 b,2 (c 3)")
(test '("~{~}" "<~a,~a>" (a 1 b 2 c 3)) "<a,1><b,2><c,3>")
(test '("~{ ~a ~{<~a>~}~} ~a" (a (1 2) b (3 4)) 10) " a <1><2> b <3><4> 10")
(let ((nums (let iter ((ns '()) (l 0))
(if (> l 105) (reverse ns) (iter (cons l ns) (+ l 1))))))
Test default , only 100 items formatted out :
(test `("~D~{, ~D~}" ,(car nums) ,(cdr nums))
"0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100")
(parameterize ((format:max-iterations 90))
(test `("~D~{, ~D~}" ,(car nums) ,(cdr nums))
"0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90")
(parameterize ((format:iteration-bounded #f))
(test `("~D~{, ~D~}" ,(car nums) ,(cdr nums))
"0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105"))))
(test '("abc ~^ xyz") "abc ")
(test '("~@(abc ~^ xyz~) ~a" 10) "ABC xyz 10")
(test '("done. ~^ ~d warning~:p. ~^ ~d error~:p.") "done. ")
(test '("done. ~^ ~d warning~:p. ~^ ~d error~:p." 10) "done. 10 warnings. ")
(test '("done. ~^ ~d warning~:p. ~^ ~d error~:p." 10 1)
"done. 10 warnings. 1 error.")
(test '("~{ ~a ~^<~a>~} ~a" (a b c d e f) 10) " a <b> c <d> e <f> 10")
(test '("~{ ~a ~^<~a>~} ~a" (a b c d e) 10) " a <b> c <d> e 10")
(test '("abc~0^ xyz") "abc")
(test '("abc~9^ xyz") "abc xyz")
(test '("abc~7,4^ xyz") "abc xyz")
(test '("abc~7,7^ xyz") "abc")
(test '("abc~3,7,9^ xyz") "abc")
(test '("abc~8,7,9^ xyz") "abc xyz")
(test '("abc~3,7,5^ xyz") "abc xyz")
complexity tests ( oh my god , I hardly understand them myself ( see CL std ) )
(define fmt "Items:~#[ none~; ~a~; ~a and ~a~:;~@{~#[~; and~] ~a~^,~}~].")
(test `(,fmt ) "Items: none.")
(test `(,fmt foo) "Items: foo.")
(test `(,fmt foo bar) "Items: foo and bar.")
(test `(,fmt foo bar baz) "Items: foo, bar, and baz.")
(test `(,fmt foo bar baz zok) "Items: foo, bar, baz, and zok.")
(test '("~6,2f" 3.14159) " 3.14")
(test '("~6,1f" 3.14159) " 3.1")
(test '("~6,0f" 3.14159) " 3.")
(test '("~5,1f" 0) " 0.0")
(test '("~10,7f" 3.14159) " 3.1415900")
(test '("~10,7f" -3.14159) "-3.1415900")
(test '("~10,7@f" 3.14159) "+3.1415900")
(test '("~6,3f" 0.0) " 0.000")
(test '("~6,4f" 0.007) "0.0070")
(test '("~6,3f" 0.007) " 0.007")
(test '("~6,2f" 0.007) " 0.01")
(test '("~3,2f" 0.007) ".01")
(test '("~3,2f" -0.007) "-.01")
(test '("~6,2,,,'*f" 3.14159) "**3.14")
(test '("~6,3,,'?f" 12345.56789) "??????")
(test '("~6,3f" 12345.6789) "12345.679")
(test '("~,3f" 12345.6789) "12345.679")
(test '("~,3f" 9.9999) "10.000")
(test '("~6f" 23.4) " 23.4")
(test '("~6f" 1234.5) "1234.5")
(test '("~6f" 12345678) "12345678.0")
(test '("~6,,,'?f" 12345678) "??????")
(test '("~6f" 123.56789) "123.57")
(test '("~6f" 123.0) " 123.0")
(test '("~6f" -123.0) "-123.0")
(test '("~6f" 0.0) " 0.0")
(test '("~3f" 3.141) "3.1")
(test '("~2f" 3.141) "3.")
(test '("~1f" 3.141) "3.141")
(test '("~f" 123.56789) "123.56789")
(test '("~f" -314.0) "-314.0")
(test '("~f" 1e4) "10000.0")
(test '("~f" -1.23e10) "-12300000000.0")
(test '("~f" 1e-4) "0.0001")
(test '("~f" -1.23e-10) "-0.000000000123")
(test '("~@f" 314.0) "+314.0")
(test '("~,,3f" 0.123456) "123.456")
(test '("~,,-3f" -123.456) "-0.123456")
(test '("~5,,3f" 0.123456) "123.5")
(test '("~e" 3.14159) "3.14159E+0")
(test '("~e" 0.00001234) "1.234E-5")
(test '("~,,,0e" 0.00001234) "0.1234E-4")
(test '("~,3e" 3.14159) "3.142E+0")
(test '("~,3@e" 3.14159) "+3.142E+0")
(test '("~,3@e" 0.0) "+0.000E+0")
(test '("~,0e" 3.141) "3.E+0")
(test '("~,3,,0e" 3.14159) "0.314E+1")
(test '("~,5,3,-2e" 3.14159) "0.00314E+003")
(test '("~,5,3,-5e" -3.14159) "-0.00000E+006")
(test '("~,5,2,2e" 3.14159) "31.4159E-01")
(test '("~,5,2,,,,'ee" 0.0) "0.00000e+00")
(test '("~12,3e" -3.141) " -3.141E+0")
(test '("~12,3,,,,'#e" -3.141) "###-3.141E+0")
(test '("~10,2e" -1.236e-4) " -1.24E-4")
(test '("~5,3e" -3.141) "-3.141E+0")
(test '("~5,3,,,'*e" -3.141) "*****")
(test '("~3e" 3.14159) "3.14159E+0")
(test '("~4e" 3.14159) "3.14159E+0")
(test '("~5e" 3.14159) "3.E+0")
(test '("~5,,,,'*e" 3.14159) "3.E+0")
(test '("~6e" 3.14159) "3.1E+0")
(test '("~7e" 3.14159) "3.14E+0")
(test '("~7e" -3.14159) "-3.1E+0")
(test '("~8e" 3.14159) "3.142E+0")
(test '("~9e" 3.14159) "3.1416E+0")
(test '("~9,,,,,,'ee" 3.14159) "3.1416e+0")
(test '("~10e" 3.14159) "3.14159E+0")
(test '("~11e" 3.14159) " 3.14159E+0")
(test '("~12e" 3.14159) " 3.14159E+0")
(test '("~13,6,2,-5e" 3.14159) " 0.000003E+06")
(test '("~13,6,2,-4e" 3.14159) " 0.000031E+05")
(test '("~13,6,2,-3e" 3.14159) " 0.000314E+04")
(test '("~13,6,2,-2e" 3.14159) " 0.003142E+03")
(test '("~13,6,2,-1e" 3.14159) " 0.031416E+02")
(test '("~13,6,2,0e" 3.14159) " 0.314159E+01")
(test '("~13,6,2,1e" 3.14159) " 3.141590E+00")
(test '("~13,6,2,2e" 3.14159) " 31.41590E-01")
(test '("~13,6,2,3e" 3.14159) " 314.1590E-02")
(test '("~13,6,2,4e" 3.14159) " 3141.590E-03")
(test '("~13,6,2,5e" 3.14159) " 31415.90E-04")
(test '("~13,6,2,6e" 3.14159) " 314159.0E-05")
(test '("~13,6,2,7e" 3.14159) " 3141590.E-06")
(test '("~13,6,2,8e" 3.14159) "31415900.E-07")
(test '("~7,3,,-2e" 0.001) ".001E+0")
(test '("~8,3,,-2@e" 0.001) "+.001E+0")
(test '("~8,3,,-2@e" -0.001) "-.001E+0")
(test '("~8,3,,-2e" 0.001) "0.001E+0")
(test '("~7,,,-2e" 0.001) "0.00E+0")
(test '("~12,3,1e" 3.14159e12) " 3.142E+12")
(test '("~12,3,1,,'*e" 3.14159e12) "************")
(test '("~5,3,1e" 3.14159e12) "3.142E+12")
general floating point ( this test is from Steele 's CL book )
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
0.0314159 0.0314159 0.0314159 0.0314159)
" 3.14E-2|314.2$-04|0.314E-01| 3.14E-2")
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
0.314159 0.314159 0.314159 0.314159)
" 0.31 |0.314 |0.314 | 0.31 ")
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
3.14159 3.14159 3.14159 3.14159)
" 3.1 | 3.14 | 3.14 | 3.1 ")
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
31.4159 31.4159 31.4159 31.4159)
" 31. | 31.4 | 31.4 | 31. ")
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
314.159 314.159 314.159 314.159)
" 3.14E+2| 314. | 314. | 3.14E+2")
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
3141.59 3141.59 3141.59 3141.59)
" 3.14E+3|314.2$+01|0.314E+04| 3.14E+3")
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
3.14E12 3.14E12 3.14E12 3.14E12)
"*********|314.0$+10|0.314E+13| 3.14E+12")
(test '("~9,2,1,,'*g|~9,3,2,3,'?,,'$g|~9,3,2,0,'%g|~9,2g"
3.14E120 3.14E120 3.14E120 3.14E120)
"*********|?????????|%%%%%%%%%|3.14E+120")
(test '("~g" 0.1) "0.1 ")
(test '("~g" 0.01) "1.0E-2")
(test '("~g" 123.456) "123.456 ")
(test '("~g" 123456.7) "123456.7 ")
(test '("~g" 123456.78) "123456.78 ")
(test '("~g" 0.9282) "0.9282 ")
(test '("~g" 0.09282) "9.282E-2")
(test '("~g" 1) "1.0 ")
(test '("~g" 12) "12.0 ")
(test '("~$" 1.23) "1.23")
(test '("~$" 1.2) "1.20")
(test '("~$" 0.0) "0.00")
(test '("~$" 9.999) "10.00")
(test '("~3$" 9.9999) "10.000")
(test '("~,4$" 3.2) "0003.20")
(test '("~,4$" 10000.2) "10000.20")
(test '("~,4,10$" 3.2) " 0003.20")
(test '("~,4,10@$" 3.2) " +0003.20")
(test '("~,4,10:@$" 3.2) "+ 0003.20")
(test '("~,4,10:$" -3.2) "- 0003.20")
(test '("~,4,10$" -3.2) " -0003.20")
(test '("~,,10@$" 3.2) " +3.20")
(test '("~,,10:@$" 3.2) "+ 3.20")
(test '("~,,10:@$" -3.2) "- 3.20")
(test '("~,,10,'_@$" 3.2) "_____+3.20")
(test '("~,,4$" 1234.4) "1234.40")
(test '("~i" 3.0) "3.0+0.0i")
(test '("~,3i" 3.0) "3.000+0.000i")
(test `("~7,2i" ,(string->number "3.0+5.0i")) " 3.00 +5.00i")
(test `("~7,2,1i" ,(string->number "3.0+5.0i")) " 30.00 +50.00i")
(test `("~7,2@i" ,(string->number "3.0+5.0i")) " +3.00 +5.00i")
(test `("~7,2,,,'*@i" ,(string->number "3.0+5.0i")) "**+3.00**+5.00i")
(test-end)
|
1c10567d9d2d8db807df25a834ab22a725d7c130ed0de5b9c858c9afc501d104 | beerose/proof-checker | rules.ml | (** Module implementing natural deduction rules *)
(** They are applied in inverse way - it checks if all facts needed to inferr an expression are already proven.
Flags:
bind - allows to use already proven facts in further proofs
*)
open Expr
(** Common type for all inversed rules *)
type inverse_nd_rule = (expr * expr list) -> bool
(**/**)
(** Expressions comparator *)
let (===) expr1 expr2 =
to_string expr1 = to_string expr2 ||
expr1 = expr2 || (`Paren(expr1)) = expr2 || expr1 = (`Paren(expr2))
(** Function find looks for expresion in given list *)
let find = fun (expr, env) ->
List.length (List.find_all (fun x -> x === expr) env) > 0
(** Aksjomat for classical logic *)
let negAksj = fun (expr1, expr2) ->
expr1 === (`Neg (expr2)) || (`Neg (expr1)) === expr2
(**/**)
(** Inverse rule: conjunction introduction *)
let andI : inverse_nd_rule = fun (expr, env) ->
match expr with
| `And (left, right) ->
find (left, env) && find (right, env)
| _ -> false
(** Inverse rule: conjunction elimination *)
let andE : inverse_nd_rule = fun (expr, env) ->
let rec aux = fun (expr, env) -> match env with
| (`And(left, right))::rest ->
if left === expr || right === expr then true else aux (expr, rest)
| _::rest -> aux(expr, rest)
| [] -> false
in aux (expr, env)
(** Inverse rule: disjunction introduction *)
let orI : inverse_nd_rule = fun (expr, env) ->
match expr with
| `Or (left, right) -> negAksj(left, right) || find (left, env) || find (right, env)
| _ -> false
(**/**)
let find_orE = fun (expr, env, left_goal) ->
let rec aux aux_env = match aux_env with
| `Impl(left, right)::rest ->
if right = expr &&
(find ((`Or (left, left_goal)), aux_env) || find ((`Or (left_goal, left)), aux_env))
then true
else aux rest
| _::rest -> aux rest
| [] -> false
in aux env
(**/**)
(** Inverse rule: disjunction elimination *)
let orE : inverse_nd_rule = fun (expr, env) ->
let rec aux aux_env = match aux_env with
| `Impl(left, right)::rest ->
if right = expr && find_orE (expr, env, left)
then true
else aux rest
| _::rest -> aux rest
| [] -> false
in aux env
(** Inverse rule: implication introduction *)
let implI : inverse_nd_rule = fun (expr, env) ->
find (expr, env)
(** Inverse rule: implication elimination *)
let implE : inverse_nd_rule = fun (expr, env) ->
let rec aux (expr, local_env) = match local_env with
| `Impl(left, right)::rest ->
if right = expr && find(left, env) then true else aux (expr, rest)
| _::rest -> aux (expr, rest)
| [] -> false
in aux (expr, env)
(** Inverse rule: negation introduction *)
let negI : inverse_nd_rule = fun (expr, env) ->
find (expr, env)
(** Inverse rule: negation elimination *)
let negE : inverse_nd_rule = fun (expr, env) ->
find (`Neg(`Neg(expr)), env)
(** Inverse rule: false introduction *)
let falseI : inverse_nd_rule = fun (expr, env) ->
let rec aux = fun env ->
match env with
| (`Neg x)::xs -> if find (x, env) then true else aux env
| x::xs -> if find (`Neg(x), env) then true else aux env
| [] -> false
in aux env
(**/**)
| null | https://raw.githubusercontent.com/beerose/proof-checker/19da83a54d728017f6699c8a6d8e69c9d5efd1ba/src/rules.ml | ocaml | * Module implementing natural deduction rules
* They are applied in inverse way - it checks if all facts needed to inferr an expression are already proven.
Flags:
bind - allows to use already proven facts in further proofs
* Common type for all inversed rules
*/*
* Expressions comparator
* Function find looks for expresion in given list
* Aksjomat for classical logic
*/*
* Inverse rule: conjunction introduction
* Inverse rule: conjunction elimination
* Inverse rule: disjunction introduction
*/*
*/*
* Inverse rule: disjunction elimination
* Inverse rule: implication introduction
* Inverse rule: implication elimination
* Inverse rule: negation introduction
* Inverse rule: negation elimination
* Inverse rule: false introduction
*/* |
open Expr
type inverse_nd_rule = (expr * expr list) -> bool
let (===) expr1 expr2 =
to_string expr1 = to_string expr2 ||
expr1 = expr2 || (`Paren(expr1)) = expr2 || expr1 = (`Paren(expr2))
let find = fun (expr, env) ->
List.length (List.find_all (fun x -> x === expr) env) > 0
let negAksj = fun (expr1, expr2) ->
expr1 === (`Neg (expr2)) || (`Neg (expr1)) === expr2
let andI : inverse_nd_rule = fun (expr, env) ->
match expr with
| `And (left, right) ->
find (left, env) && find (right, env)
| _ -> false
let andE : inverse_nd_rule = fun (expr, env) ->
let rec aux = fun (expr, env) -> match env with
| (`And(left, right))::rest ->
if left === expr || right === expr then true else aux (expr, rest)
| _::rest -> aux(expr, rest)
| [] -> false
in aux (expr, env)
let orI : inverse_nd_rule = fun (expr, env) ->
match expr with
| `Or (left, right) -> negAksj(left, right) || find (left, env) || find (right, env)
| _ -> false
let find_orE = fun (expr, env, left_goal) ->
let rec aux aux_env = match aux_env with
| `Impl(left, right)::rest ->
if right = expr &&
(find ((`Or (left, left_goal)), aux_env) || find ((`Or (left_goal, left)), aux_env))
then true
else aux rest
| _::rest -> aux rest
| [] -> false
in aux env
let orE : inverse_nd_rule = fun (expr, env) ->
let rec aux aux_env = match aux_env with
| `Impl(left, right)::rest ->
if right = expr && find_orE (expr, env, left)
then true
else aux rest
| _::rest -> aux rest
| [] -> false
in aux env
let implI : inverse_nd_rule = fun (expr, env) ->
find (expr, env)
let implE : inverse_nd_rule = fun (expr, env) ->
let rec aux (expr, local_env) = match local_env with
| `Impl(left, right)::rest ->
if right = expr && find(left, env) then true else aux (expr, rest)
| _::rest -> aux (expr, rest)
| [] -> false
in aux (expr, env)
let negI : inverse_nd_rule = fun (expr, env) ->
find (expr, env)
let negE : inverse_nd_rule = fun (expr, env) ->
find (`Neg(`Neg(expr)), env)
let falseI : inverse_nd_rule = fun (expr, env) ->
let rec aux = fun env ->
match env with
| (`Neg x)::xs -> if find (x, env) then true else aux env
| x::xs -> if find (`Neg(x), env) then true else aux env
| [] -> false
in aux env
|
c5feaa572a97fbc32db1695aa1c1e8e4547312622f69f35b3a7a68b0f46608de | khotyn/4clojure-answer | 146-trees-into-tables.clj | (fn [t]
(apply hash-map
(apply concat
(apply concat
(for
[key (keys t)]
(for
[inner-key (keys (get t key))]
[[key inner-key] (get (get t key) inner-key)])))))) | null | https://raw.githubusercontent.com/khotyn/4clojure-answer/3de82d732faedceafac4f1585a72d0712fe5d3c6/146-trees-into-tables.clj | clojure | (fn [t]
(apply hash-map
(apply concat
(apply concat
(for
[key (keys t)]
(for
[inner-key (keys (get t key))]
[[key inner-key] (get (get t key) inner-key)])))))) | |
a1509cdf72fa2856914101dc365370cfb3176d95b70b715bb7d78d6eac044ee9 | swlkr/majestic-web | logic.clj | (ns {{name}}.users.logic
(:require [buddy.hashers :as hashers]
[{{name}}.users.db :as users.db]
[{{name}}.utils :as utils]))
(defn email? [str]
(and
(string? str)
(not (nil? (re-find #".+@.+\." str)))))
(defn decent-password? [password]
(let [min-length 12]
(and
(string? password)
(>= (count password) min-length))))
(defn validate-email [{:keys [email] :as user}]
(if (email? email)
user
(throw (Exception. "That's not an email"))))
(defn validate-password [{:keys [password] :as user}]
(if (decent-password? password)
user
(throw (Exception. "Passwords need to be at least 12 characters"))))
(defn validate-matching-passwords [{:keys [password confirm-password] :as user}]
(if (= password confirm-password)
user
(throw (Exception. "Passwords need to match"))))
(defn validate [{:keys [email password confirm-password] :as user}]
(-> user
validate-email
validate-password
validate-matching-passwords))
(defn encrypt-password [user]
(let [encrypted-password (hashers/derive (:password user))]
(assoc user :password encrypted-password)))
(defn db-params [user]
{:id (or (:id user) (utils/uuid))
:email (:email user)
:password (:password user)})
(defn create! [user]
(-> user
validate
encrypt-password
db-params
users.db/insert<!))
| null | https://raw.githubusercontent.com/swlkr/majestic-web/3d247f6b5ccc4ff3662a64544a4ca27beada971b/resources/leiningen/new/majestic_web/src/users/logic.clj | clojure | (ns {{name}}.users.logic
(:require [buddy.hashers :as hashers]
[{{name}}.users.db :as users.db]
[{{name}}.utils :as utils]))
(defn email? [str]
(and
(string? str)
(not (nil? (re-find #".+@.+\." str)))))
(defn decent-password? [password]
(let [min-length 12]
(and
(string? password)
(>= (count password) min-length))))
(defn validate-email [{:keys [email] :as user}]
(if (email? email)
user
(throw (Exception. "That's not an email"))))
(defn validate-password [{:keys [password] :as user}]
(if (decent-password? password)
user
(throw (Exception. "Passwords need to be at least 12 characters"))))
(defn validate-matching-passwords [{:keys [password confirm-password] :as user}]
(if (= password confirm-password)
user
(throw (Exception. "Passwords need to match"))))
(defn validate [{:keys [email password confirm-password] :as user}]
(-> user
validate-email
validate-password
validate-matching-passwords))
(defn encrypt-password [user]
(let [encrypted-password (hashers/derive (:password user))]
(assoc user :password encrypted-password)))
(defn db-params [user]
{:id (or (:id user) (utils/uuid))
:email (:email user)
:password (:password user)})
(defn create! [user]
(-> user
validate
encrypt-password
db-params
users.db/insert<!))
| |
90539fa3dca80103924add3a8ddb4a41bf4fd16c2060e63c8b13322a65e1d1ba | amosr/folderol | Unagi.hs | {-# LANGUAGE BangPatterns #-}
module Bench.Chan.Unagi where
import Bench.Chan.Chunk
import Folderol.Spawn
import Control.Concurrent.Chan.Unagi
import qualified Data.Vector as Vector
runMaybe :: Vector.Vector a -> IO ()
runMaybe v = do
(i,o) <- newChan
join2 (pushMaybe v i) (pullMaybe o)
pushMaybe :: Vector.Vector a -> InChan (Maybe a) -> IO ()
pushMaybe !v c = go 0
where
go i
| i < Vector.length v
= writeChan c (Just $ Vector.unsafeIndex v i) >> go (i+1)
| otherwise
= writeChan c Nothing
pullMaybe :: OutChan (Maybe a) -> IO ()
pullMaybe c = go
where
go = do
v <- readChan c
case v of
Nothing -> return ()
Just _ -> go
runChunked :: Int -> Vector.Vector a -> IO ()
runChunked chunkSize v = do
(i,o) <- newChan
join2 (pushChunk chunkSize v $ writeChan i)
(pullChunk (\_ -> return ()) $ readChan o)
runChunkedUnbox :: Int -> Vector.Vector Int -> IO ()
runChunkedUnbox chunkSize v = do
(i,o) <- newChan
join2 (pushChunkUnbox chunkSize v $ writeChan i)
(pullChunkUnbox (\_ -> return ()) $ readChan o)
| null | https://raw.githubusercontent.com/amosr/folderol/9b8c0cd30cfb798dadaa404cc66404765b1fc4fe/bench/Bench/Chan/Unagi.hs | haskell | # LANGUAGE BangPatterns # | module Bench.Chan.Unagi where
import Bench.Chan.Chunk
import Folderol.Spawn
import Control.Concurrent.Chan.Unagi
import qualified Data.Vector as Vector
runMaybe :: Vector.Vector a -> IO ()
runMaybe v = do
(i,o) <- newChan
join2 (pushMaybe v i) (pullMaybe o)
pushMaybe :: Vector.Vector a -> InChan (Maybe a) -> IO ()
pushMaybe !v c = go 0
where
go i
| i < Vector.length v
= writeChan c (Just $ Vector.unsafeIndex v i) >> go (i+1)
| otherwise
= writeChan c Nothing
pullMaybe :: OutChan (Maybe a) -> IO ()
pullMaybe c = go
where
go = do
v <- readChan c
case v of
Nothing -> return ()
Just _ -> go
runChunked :: Int -> Vector.Vector a -> IO ()
runChunked chunkSize v = do
(i,o) <- newChan
join2 (pushChunk chunkSize v $ writeChan i)
(pullChunk (\_ -> return ()) $ readChan o)
runChunkedUnbox :: Int -> Vector.Vector Int -> IO ()
runChunkedUnbox chunkSize v = do
(i,o) <- newChan
join2 (pushChunkUnbox chunkSize v $ writeChan i)
(pullChunkUnbox (\_ -> return ()) $ readChan o)
|
5267b7d62e96a44a0bf00ec858bb66e823dd3a92a234cf027478214a1cbdda45 | simonmichael/hledger | JournalReader.hs | --- * -*- outline-regexp:"--- *"; -*-
--- ** doc
In Emacs , use TAB on lines beginning with " -- * " to collapse / expand sections .
|
A reader for hledger 's journal file format
( < #the-journal-file > ) . hledger 's journal
format is a compatible subset of
( < -cli.org/3.0/doc/ledger3.html#Journal-Format > ) , so this
reader should handle many ledger files as well . Example :
@
2012\/3\/24 gift
expenses : gifts $ 10
assets : cash
@
Journal format supports the include directive which can read files in
other formats , so the other file format readers need to be importable
and invocable here .
Some important parts of journal parsing are therefore kept in
Hledger . Read . Common , to avoid import cycles .
A reader for hledger's journal file format
(<#the-journal-file>). hledger's journal
format is a compatible subset of c++ ledger's
(<-cli.org/3.0/doc/ledger3.html#Journal-Format>), so this
reader should handle many ledger files as well. Example:
@
2012\/3\/24 gift
expenses:gifts $10
assets:cash
@
Journal format supports the include directive which can read files in
other formats, so the other file format readers need to be importable
and invocable here.
Some important parts of journal parsing are therefore kept in
Hledger.Read.Common, to avoid import cycles.
-}
--- ** language
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE NoMonoLocalBinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
# LANGUAGE ScopedTypeVariables #
--- ** exports
module Hledger.Read.JournalReader (
-- * Reader-finding utils
findReader,
splitReaderPrefix,
-- * Reader
reader,
-- * Parsing utils
parseAndFinaliseJournal,
runJournalParser,
rjp,
runErroringJournalParser,
rejp,
* used elsewhere
getParentAccount,
journalp,
directivep,
defaultyeardirectivep,
marketpricedirectivep,
datetimep,
datep,
modifiedaccountnamep,
tmpostingrulep,
statusp,
emptyorcommentlinep,
followingcommentp,
accountaliasp
-- * Tests
,tests_JournalReader
)
where
--- ** imports
import qualified Control.Monad.Fail as Fail (fail)
import qualified Control.Exception as C
import Control.Monad (forM_, when, void, unless)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Except (ExceptT(..), runExceptT)
import Control.Monad.State.Strict (evalStateT,get,modify',put)
import Control.Monad.Trans.Class (lift)
import Data.Char (toLower)
import Data.Either (isRight, lefts)
import qualified Data.Map.Strict as M
import Data.Text (Text)
import Data.String
import Data.List
import Data.Maybe
import qualified Data.Text as T
import Data.Time.Calendar
import Data.Time.LocalTime
import Safe
import Text.Megaparsec hiding (parse)
import Text.Megaparsec.Char
import Text.Megaparsec.Custom
import Text.Printf
import System.FilePath
import "Glob" System.FilePath.Glob hiding (match)
import Hledger.Data
import Hledger.Read.Common
import Hledger.Utils
import qualified Hledger.Read.TimedotReader as TimedotReader (reader)
import qualified Hledger.Read.TimeclockReader as TimeclockReader (reader)
import qualified Hledger.Read.CsvReader as CsvReader (reader)
--- ** doctest setup
-- $setup
-- >>> :set -XOverloadedStrings
--
--- ** parsing utilities
-- | Run a journal parser in some monad. See also: parseWithState.
runJournalParser, rjp
:: Monad m
=> JournalParser m a -> Text -> m (Either HledgerParseErrors a)
runJournalParser p = runParserT (evalStateT p nulljournal) ""
rjp = runJournalParser
-- | Run an erroring journal parser in some monad. See also: parseWithState.
runErroringJournalParser, rejp
:: Monad m
=> ErroringJournalParser m a
-> Text
-> m (Either FinalParseError (Either HledgerParseErrors a))
runErroringJournalParser p t =
runExceptT $ runParserT (evalStateT p nulljournal) "" t
rejp = runErroringJournalParser
--- ** reader finding utilities
Defined here rather than Hledger . Read so that we can use them in includedirectivep below .
-- The available journal readers, each one handling a particular data format.
readers' :: MonadIO m => [Reader m]
readers' = [
reader
,TimeclockReader.reader
,TimedotReader.reader
,CsvReader.reader
-- ,LedgerReader.reader
]
readerNames :: [String]
readerNames = map rFormat (readers'::[Reader IO])
-- | @findReader mformat mpath@
--
Find the reader named by @mformat@ , if provided .
Or , if a file path is provided , find the first reader that handles
-- its file extension, if any.
findReader :: MonadIO m => Maybe StorageFormat -> Maybe FilePath -> Maybe (Reader m)
findReader Nothing Nothing = Nothing
findReader (Just fmt) _ = headMay [r | r <- readers', rFormat r == fmt]
findReader Nothing (Just path) =
case prefix of
Just fmt -> headMay [r | r <- readers', rFormat r == fmt]
Nothing -> headMay [r | r <- readers', ext `elem` rExtensions r]
where
(prefix,path') = splitReaderPrefix path
ext = map toLower $ drop 1 $ takeExtension path'
-- | A file path optionally prefixed by a reader name and colon
-- (journal:, csv:, timedot:, etc.).
type PrefixedFilePath = FilePath
| If a filepath is prefixed by one of the reader names and a colon ,
-- split that off. Eg "csv:-" -> (Just "csv", "-").
splitReaderPrefix :: PrefixedFilePath -> (Maybe String, FilePath)
splitReaderPrefix f =
headDef (Nothing, f)
[(Just r, drop (length r + 1) f) | r <- readerNames, (r++":") `isPrefixOf` f]
--- ** reader
reader :: MonadIO m => Reader m
reader = Reader
{rFormat = "journal"
,rExtensions = ["journal", "j", "hledger", "ledger"]
,rReadFn = parse
,rParser = journalp -- no need to add command line aliases like journalp'
-- when called as a subparser I think
}
| Parse and post - process a " Journal " from hledger 's journal file
-- format, or give an error.
parse :: InputOpts -> FilePath -> Text -> ExceptT String IO Journal
parse iopts f = parseAndFinaliseJournal journalp' iopts f
where
journalp' = do
-- reverse parsed aliases to ensure that they are applied in order given on commandline
mapM_ addAccountAlias (reverse $ aliasesFromOpts iopts)
journalp
--- ** parsers
--- *** journal
-- | A journal parser. Accumulates and returns a "ParsedJournal",
-- which should be finalised/validated before use.
--
> > > rejp ( < * eof ) " 2015/1/1\n a 0\n "
Right ( Right Journal ( unknown ) with 1 transactions , 1 accounts )
--
journalp :: MonadIO m => ErroringJournalParser m ParsedJournal
journalp = do
many addJournalItemP
eof
get
-- | A side-effecting parser; parses any kind of journal item
-- and updates the parse state accordingly.
addJournalItemP :: MonadIO m => ErroringJournalParser m ()
addJournalItemP =
all journal line types can be distinguished by the first
-- character, can use choice without backtracking
choice [
directivep
, transactionp >>= modify' . addTransaction
, transactionmodifierp >>= modify' . addTransactionModifier
, periodictransactionp >>= modify' . addPeriodicTransaction
, marketpricedirectivep >>= modify' . addPriceDirective
, void (lift emptyorcommentlinep)
, void (lift multilinecommentp)
] <?> "transaction or directive"
--- *** directives
| Parse any journal directive and update the parse state accordingly .
-- Cf #directives,
-- -cli.org/3.0/doc/ledger3.html#Command-Directives
directivep :: MonadIO m => ErroringJournalParser m ()
directivep = (do
optional $ oneOf ['!','@']
choice [
includedirectivep
,aliasdirectivep
,endaliasesdirectivep
,accountdirectivep
,applyaccountdirectivep
,applyfixeddirectivep
,applytagdirectivep
,assertdirectivep
,bucketdirectivep
,capturedirectivep
,checkdirectivep
,commandlineflagdirectivep
,commoditydirectivep
,commodityconversiondirectivep
,decimalmarkdirectivep
,defaultyeardirectivep
,defaultcommoditydirectivep
,definedirectivep
,endapplyaccountdirectivep
,endapplyfixeddirectivep
,endapplytagdirectivep
,endapplyyeardirectivep
,endtagdirectivep
,evaldirectivep
,exprdirectivep
,ignoredpricecommoditydirectivep
,payeedirectivep
,pythondirectivep
,tagdirectivep
,valuedirectivep
]
) <?> "directive"
-- | Parse an include directive. include's argument is an optionally
-- file-format-prefixed file path or glob pattern. In the latter case,
-- the prefix is applied to each matched path. Examples:
-- foo.j, foo/bar.j, timedot:foo/2020*.md
includedirectivep :: MonadIO m => ErroringJournalParser m ()
includedirectivep = do
string "include"
lift skipNonNewlineSpaces1
prefixedglob <- T.unpack <$> takeWhileP Nothing (/= '\n') -- don't consume newline yet
parentoff <- getOffset
parentpos <- getSourcePos
let (mprefix,glb) = splitReaderPrefix prefixedglob
paths <- getFilePaths parentoff parentpos glb
let prefixedpaths = case mprefix of
Nothing -> paths
Just fmt -> map ((fmt++":")++) paths
forM_ prefixedpaths $ parseChild parentpos
void newline
where
getFilePaths
:: MonadIO m => Int -> SourcePos -> FilePath -> JournalParser m [FilePath]
getFilePaths parseroff parserpos filename = do
let curdir = takeDirectory (sourceName parserpos)
filename' <- lift $ expandHomePath filename
`orRethrowIOError` (show parserpos ++ " locating " ++ filename)
-- Compiling filename as a glob pattern works even if it is a literal
fileglob <- case tryCompileWith compDefault{errorRecovery=False} filename' of
Right x -> pure x
Left e -> customFailure $
parseErrorAt parseroff $ "Invalid glob pattern: " ++ e
-- Get all matching files in the current working directory, sorting in
-- lexicographic order to simulate the output of 'ls'.
filepaths <- liftIO $ sort <$> globDir1 fileglob curdir
if (not . null) filepaths
then pure filepaths
else customFailure $ parseErrorAt parseroff $
"No existing files match pattern: " ++ filename
parseChild :: MonadIO m => SourcePos -> PrefixedFilePath -> ErroringJournalParser m ()
parseChild parentpos prefixedpath = do
let (_mprefix,filepath) = splitReaderPrefix prefixedpath
parentj <- get
let parentfilestack = jincludefilestack parentj
when (filepath `elem` parentfilestack) $
Fail.fail ("Cyclic include: " ++ filepath)
childInput <-
traceOrLogAt 6 ("parseChild: "++takeFileName filepath) $
lift $ readFilePortably filepath
`orRethrowIOError` (show parentpos ++ " reading " ++ filepath)
let initChildj = newJournalWithParseStateFrom filepath parentj
-- Choose a reader/parser based on the file path prefix or file extension,
-- defaulting to JournalReader. Duplicating readJournal a bit here.
let r = fromMaybe reader $ findReader Nothing (Just prefixedpath)
parser = rParser r
dbg6IO "parseChild: trying reader" (rFormat r)
Parse the file ( of whichever format ) to a Journal , with file path and source text attached .
updatedChildj <- journalAddFile (filepath, childInput) <$>
parseIncludeFile parser initChildj filepath childInput
-- Merge this child journal into the parent journal
-- (with debug logging for troubleshooting account display order).
The parent journal is the second argument to journalConcat ; this means
-- its parse state is kept, and its lists are appended to child's (which
-- ultimately produces the right list order, because parent's and child's
-- lists are in reverse order at this stage. Cf #1909).
let
parentj' =
dbgJournalAcctDeclOrder ("parseChild: child " <> childfilename <> " acct decls: ") updatedChildj
`journalConcat`
dbgJournalAcctDeclOrder ("parseChild: parent " <> parentfilename <> " acct decls: ") parentj
where
childfilename = takeFileName filepath
parentfilename = maybe "(unknown)" takeFileName $ headMay $ jincludefilestack parentj -- XXX more accurate than journalFilePath for some reason
-- Update the parse state.
put parentj'
newJournalWithParseStateFrom :: FilePath -> Journal -> Journal
newJournalWithParseStateFrom filepath j = nulljournal{
jparsedefaultyear = jparsedefaultyear j
,jparsedefaultcommodity = jparsedefaultcommodity j
,jparseparentaccounts = jparseparentaccounts j
,jparsedecimalmark = jparsedecimalmark j
,jparsealiases = jparsealiases j
,jcommodities = jcommodities j
, jparsetransactioncount = jparsetransactioncount j
,jparsetimeclockentries = jparsetimeclockentries j
,jincludefilestack = filepath : jincludefilestack j
}
-- | Lift an IO action into the exception monad, rethrowing any IO
-- error with the given message prepended.
orRethrowIOError :: MonadIO m => IO a -> String -> TextParser m a
orRethrowIOError io msg = do
eResult <- liftIO $ (Right <$> io) `C.catch` \(e::C.IOException) -> pure $ Left $ printf "%s:\n%s" msg (show e)
case eResult of
Right res -> pure res
Left errMsg -> Fail.fail errMsg
Parse an account directive , adding its info to the journal 's
-- list of account declarations.
accountdirectivep :: JournalParser m ()
accountdirectivep = do
off <- getOffset -- XXX figure out a more precise position later
pos <- getSourcePos
string "account"
lift skipNonNewlineSpaces1
-- the account name, possibly modified by preceding alias or apply account directives
acct <- (notFollowedBy (char '(' <|> char '[') <?> "account name without brackets") >>
modifiedaccountnamep
-- maybe a comment, on this and/or following lines
(cmt, tags) <- lift transactioncommentp
-- maybe Ledger-style subdirectives (ignored)
skipMany indentedlinep
-- an account type may have been set by account type code or a tag;
-- the latter takes precedence
let
metype = parseAccountTypeCode <$> lookup accountTypeTagName tags
-- update the journal
addAccountDeclaration (acct, cmt, tags, pos)
unless (null tags) $ addDeclaredAccountTags acct tags
case metype of
Nothing -> return ()
Just (Right t) -> addDeclaredAccountType acct t
Just (Left err) -> customFailure $ parseErrorAt off err
-- The special tag used for declaring account type. XXX change to "class" ?
accountTypeTagName = "type"
parseAccountTypeCode :: Text -> Either String AccountType
parseAccountTypeCode s =
case T.toLower s of
"asset" -> Right Asset
"a" -> Right Asset
"liability" -> Right Liability
"l" -> Right Liability
"equity" -> Right Equity
"e" -> Right Equity
"revenue" -> Right Revenue
"r" -> Right Revenue
"expense" -> Right Expense
"x" -> Right Expense
"cash" -> Right Cash
"c" -> Right Cash
"conversion" -> Right Conversion
"v" -> Right Conversion
_ -> Left err
where
err = T.unpack $ "invalid account type code "<>s<>", should be one of " <>
T.intercalate ", " ["A","L","E","R","X","C","V","Asset","Liability","Equity","Revenue","Expense","Cash","Conversion"]
-- Add an account declaration to the journal, auto-numbering it.
addAccountDeclaration :: (AccountName,Text,[Tag],SourcePos) -> JournalParser m ()
addAccountDeclaration (a,cmt,tags,pos) = do
modify' (\j ->
let
decls = jdeclaredaccounts j
d = (a, nullaccountdeclarationinfo{
adicomment = cmt
,aditags = tags
,adideclarationorder = length decls + 1 -- gets renumbered when Journals are finalised or merged
,adisourcepos = pos
})
in
j{jdeclaredaccounts = d:decls})
-- Add a payee declaration to the journal.
addPayeeDeclaration :: (Payee,Text,[Tag]) -> JournalParser m ()
addPayeeDeclaration (p, cmt, tags) =
modify' (\j@Journal{jdeclaredpayees} -> j{jdeclaredpayees=d:jdeclaredpayees})
where
d = (p
,nullpayeedeclarationinfo{
pdicomment = cmt
,pditags = tags
})
-- Add a tag declaration to the journal.
addTagDeclaration :: (TagName,Text) -> JournalParser m ()
addTagDeclaration (t, cmt) =
modify' (\j@Journal{jdeclaredtags} -> j{jdeclaredtags=tagandinfo:jdeclaredtags})
where
tagandinfo = (t, nulltagdeclarationinfo{tdicomment=cmt})
indentedlinep :: JournalParser m String
indentedlinep = lift skipNonNewlineSpaces1 >> (rstrip <$> lift restofline)
| Parse a one - line or multi - line commodity directive .
--
> > > Right _ < - rjp commoditydirectivep " commodity $ 1.00 "
> > > Right _ < - rjp commoditydirectivep " commodity $ \n format $ 1.00 "
-- >>> Right _ <- rjp commoditydirectivep "commodity $\n\n" -- a commodity with no format
> > > Right _ < - rjp commoditydirectivep " commodity $ 1.00\n format $ 1.00 " -- both , what happens ?
commoditydirectivep :: JournalParser m ()
commoditydirectivep = commoditydirectiveonelinep <|> commoditydirectivemultilinep
| Parse a one - line commodity directive .
--
> > > Right _ < - rjp commoditydirectiveonelinep " commodity $ 1.00 "
> > > Right _ < - rjp commoditydirectiveonelinep " commodity $ 1.00 ; blah\n "
commoditydirectiveonelinep :: JournalParser m ()
commoditydirectiveonelinep = do
(off, Amount{acommodity,astyle}) <- try $ do
string "commodity"
lift skipNonNewlineSpaces1
off <- getOffset
amt <- amountp
pure $ (off, amt)
lift skipNonNewlineSpaces
_ <- lift followingcommentp
let comm = Commodity{csymbol=acommodity, cformat=Just $ dbg6 "style from commodity directive" astyle}
if isNothing $ asdecimalpoint astyle
then customFailure $ parseErrorAt off pleaseincludedecimalpoint
else modify' (\j -> j{jcommodities=M.insert acommodity comm $ jcommodities j})
pleaseincludedecimalpoint :: String
pleaseincludedecimalpoint = chomp $ unlines [
"Please include a decimal point or decimal comma in commodity directives,"
,"to help us parse correctly. It may be followed by zero or more decimal digits."
,"Examples:"
,"commodity $1000. ; no thousands mark, decimal period, no decimals"
,"commodity 1.234,00 ARS ; period at thousands, decimal comma, 2 decimals"
,"commodity EUR 1 000,000 ; space at thousands, decimal comma, 3 decimals"
,"commodity INR1,23,45,678.0 ; comma at thousands/lakhs/crores, decimal period, 1 decimal"
]
-- | Parse a multi-line commodity directive, containing 0 or more format subdirectives.
--
> > > Right _ < - rjp commoditydirectivemultilinep " commodity $ ; blah \n format $ 1.00 ; blah "
commoditydirectivemultilinep :: JournalParser m ()
commoditydirectivemultilinep = do
string "commodity"
lift skipNonNewlineSpaces1
sym <- lift commoditysymbolp
_ <- lift followingcommentp
-- read all subdirectives, saving format subdirectives as Lefts
subdirectives <- many $ indented (eitherP (formatdirectivep sym) (lift restofline))
let mfmt = lastMay $ lefts subdirectives
let comm = Commodity{csymbol=sym, cformat=mfmt}
modify' (\j -> j{jcommodities=M.insert sym comm $ jcommodities j})
where
indented = (lift skipNonNewlineSpaces1 >>)
| Parse a format ( sub)directive , throwing a parse error if its
-- symbol does not match the one given.
formatdirectivep :: CommoditySymbol -> JournalParser m AmountStyle
formatdirectivep expectedsym = do
string "format"
lift skipNonNewlineSpaces1
off <- getOffset
Amount{acommodity,astyle} <- amountp
_ <- lift followingcommentp
if acommodity==expectedsym
then
if isNothing $ asdecimalpoint astyle
then customFailure $ parseErrorAt off pleaseincludedecimalpoint
else return $ dbg6 "style from format subdirective" astyle
else customFailure $ parseErrorAt off $
printf "commodity directive symbol \"%s\" and format directive symbol \"%s\" should be the same" expectedsym acommodity
-- More Ledger directives, ignore for now:
-- apply fixed, apply tag, assert, bucket, A, capture, check, define, expr
applyfixeddirectivep, endapplyfixeddirectivep, applytagdirectivep, endapplytagdirectivep,
assertdirectivep, bucketdirectivep, capturedirectivep, checkdirectivep,
endapplyyeardirectivep, definedirectivep, exprdirectivep, valuedirectivep,
evaldirectivep, pythondirectivep, commandlineflagdirectivep
:: JournalParser m ()
applyfixeddirectivep = do string "apply fixed" >> lift restofline >> return ()
endapplyfixeddirectivep = do string "end apply fixed" >> lift restofline >> return ()
applytagdirectivep = do string "apply tag" >> lift restofline >> return ()
endapplytagdirectivep = do string "end apply tag" >> lift restofline >> return ()
endapplyyeardirectivep = do string "end apply year" >> lift restofline >> return ()
assertdirectivep = do string "assert" >> lift restofline >> return ()
bucketdirectivep = do string "A " <|> string "bucket " >> lift restofline >> return ()
capturedirectivep = do string "capture" >> lift restofline >> return ()
checkdirectivep = do string "check" >> lift restofline >> return ()
definedirectivep = do string "define" >> lift restofline >> return ()
exprdirectivep = do string "expr" >> lift restofline >> return ()
valuedirectivep = do string "value" >> lift restofline >> return ()
evaldirectivep = do string "eval" >> lift restofline >> return ()
commandlineflagdirectivep = do string "--" >> lift restofline >> return ()
pythondirectivep = do
string "python" >> lift restofline
many $ indentedline <|> blankline
return ()
where
indentedline = lift skipNonNewlineSpaces1 >> lift restofline
blankline = lift skipNonNewlineSpaces >> newline >> return "" <?> "blank line"
keywordp :: String -> JournalParser m ()
keywordp = void . string . fromString
spacesp :: JournalParser m ()
spacesp = void $ lift skipNonNewlineSpaces1
-- | Backtracking parser similar to string, but allows varying amount of space between words
keywordsp :: String -> JournalParser m ()
keywordsp = try . sequence_ . intersperse spacesp . map keywordp . words
applyaccountdirectivep :: JournalParser m ()
applyaccountdirectivep = do
keywordsp "apply account" <?> "apply account directive"
lift skipNonNewlineSpaces1
parent <- lift accountnamep
newline
pushParentAccount parent
endapplyaccountdirectivep :: JournalParser m ()
endapplyaccountdirectivep = do
keywordsp "end apply account" <?> "end apply account directive"
popParentAccount
aliasdirectivep :: JournalParser m ()
aliasdirectivep = do
string "alias"
lift skipNonNewlineSpaces1
alias <- lift accountaliasp
addAccountAlias alias
endaliasesdirectivep :: JournalParser m ()
endaliasesdirectivep = do
keywordsp "end aliases" <?> "end aliases directive"
clearAccountAliases
tagdirectivep :: JournalParser m ()
tagdirectivep = do
string "tag" <?> "tag directive"
lift skipNonNewlineSpaces1
tagname <- lift $ T.pack <$> some nonspace
(comment, _) <- lift transactioncommentp
skipMany indentedlinep
addTagDeclaration (tagname,comment)
return ()
-- end tag or end apply tag
endtagdirectivep :: JournalParser m ()
endtagdirectivep = (do
string "end"
lift skipNonNewlineSpaces1
optional $ string "apply" >> lift skipNonNewlineSpaces1
string "tag"
lift skipNonNewlineSpaces
eol
return ()
) <?> "end tag or end apply tag directive"
payeedirectivep :: JournalParser m ()
payeedirectivep = do
string "payee" <?> "payee directive"
lift skipNonNewlineSpaces1
payee <- lift $ T.strip <$> noncommenttext1p
(comment, tags) <- lift transactioncommentp
skipMany indentedlinep
addPayeeDeclaration (payee, comment, tags)
return ()
defaultyeardirectivep :: JournalParser m ()
defaultyeardirectivep = do
(string "Y" <|> string "year" <|> string "apply year") <?> "default year"
lift skipNonNewlineSpaces
setYear =<< lift yearp
defaultcommoditydirectivep :: JournalParser m ()
defaultcommoditydirectivep = do
char 'D' <?> "default commodity"
lift skipNonNewlineSpaces1
off <- getOffset
Amount{acommodity,astyle} <- amountp
lift restofline
if isNothing $ asdecimalpoint astyle
then customFailure $ parseErrorAt off pleaseincludedecimalpoint
else setDefaultCommodityAndStyle (acommodity, astyle)
marketpricedirectivep :: JournalParser m PriceDirective
marketpricedirectivep = do
char 'P' <?> "market price"
lift skipNonNewlineSpaces
date <- try (do {LocalTime d _ <- datetimep; return d}) <|> datep -- a time is ignored
lift skipNonNewlineSpaces1
symbol <- lift commoditysymbolp
lift skipNonNewlineSpaces
price <- amountp
lift restofline
return $ PriceDirective date symbol price
ignoredpricecommoditydirectivep :: JournalParser m ()
ignoredpricecommoditydirectivep = do
char 'N' <?> "ignored-price commodity"
lift skipNonNewlineSpaces1
lift commoditysymbolp
lift restofline
return ()
commodityconversiondirectivep :: JournalParser m ()
commodityconversiondirectivep = do
char 'C' <?> "commodity conversion"
lift skipNonNewlineSpaces1
amountp
lift skipNonNewlineSpaces
char '='
lift skipNonNewlineSpaces
amountp
lift restofline
return ()
-- | Read a valid decimal mark from the decimal-mark directive e.g
--
-- decimal-mark ,
decimalmarkdirectivep :: JournalParser m ()
decimalmarkdirectivep = do
string "decimal-mark" <?> "decimal mark"
lift skipNonNewlineSpaces1
mark <- satisfy isDecimalMark
modify' $ \j -> j{jparsedecimalmark=Just mark}
lift restofline
return ()
--- *** transactions
-- | Parse a transaction modifier (auto postings) rule.
transactionmodifierp :: JournalParser m TransactionModifier
transactionmodifierp = do
char '=' <?> "modifier transaction"
lift skipNonNewlineSpaces
querytxt <- lift $ T.strip <$> descriptionp
TODO apply these to modified txns ?
postingrules <- tmpostingrulesp Nothing
return $ TransactionModifier querytxt postingrules
-- | Parse a periodic transaction rule.
--
-- This reuses periodexprp which parses period expressions on the command line.
-- This is awkward because periodexprp supports relative and partial dates,
-- which we don't really need here, and it doesn't support the notion of a
-- default year set by a Y directive, which we do need to consider here.
-- We resolve it as follows: in periodic transactions' period expressions,
-- if there is a default year Y in effect, partial/relative dates are calculated
relative to Y/1/1 . If not , they are calculated related to today as usual .
periodictransactionp :: MonadIO m => JournalParser m PeriodicTransaction
periodictransactionp = do
startpos <- getSourcePos
-- first line
char '~' <?> "periodic transaction"
lift $ skipNonNewlineSpaces
-- if there's a default year in effect, use Y/1/1 as base for partial/relative dates
today <- liftIO getCurrentDay
mdefaultyear <- getYear
let refdate = case mdefaultyear of
Nothing -> today
Just y -> fromGregorian y 1 1
periodExcerpt <- lift $ excerpt_ $
singlespacedtextsatisfying1p (\c -> c /= ';' && c /= '\n')
let periodtxt = T.strip $ getExcerptText periodExcerpt
first parsing with ' ' , then " re - parsing " with
-- 'periodexprp' saves 'periodexprp' from having to respect the single-
-- and double-space parsing rules
(interval, spn) <- lift $ reparseExcerpt periodExcerpt $ do
pexp <- periodexprp refdate
(<|>) eof $ do
offset1 <- getOffset
void takeRest
offset2 <- getOffset
customFailure $ parseErrorAtRegion offset1 offset2 $
"remainder of period expression cannot be parsed"
<> "\nperhaps you need to terminate the period expression with a double space?"
<> "\na double space is required between period expression and description/comment"
pure pexp
status <- lift statusp <?> "cleared status"
code <- lift codep <?> "transaction code"
description <- lift $ T.strip <$> descriptionp
(comment, tags) <- lift transactioncommentp
next lines ; use same year determined above
postings <- postingsp (Just $ first3 $ toGregorian refdate)
endpos <- getSourcePos
let sourcepos = (startpos, endpos)
return $ nullperiodictransaction{
ptperiodexpr=periodtxt
,ptinterval=interval
,ptspan=spn
,ptsourcepos=sourcepos
,ptstatus=status
,ptcode=code
,ptdescription=description
,ptcomment=comment
,pttags=tags
,ptpostings=postings
}
-- | Parse a (possibly unbalanced) transaction.
transactionp :: JournalParser m Transaction
transactionp = do
dbgparse 0 " "
startpos <- getSourcePos
date <- datep <?> "transaction"
edate <- optional (lift $ secondarydatep date) <?> "secondary date"
lookAhead (lift spacenonewline <|> newline) <?> "whitespace or newline"
status <- lift statusp <?> "cleared status"
code <- lift codep <?> "transaction code"
description <- lift $ T.strip <$> descriptionp
(comment, tags) <- lift transactioncommentp
let year = first3 $ toGregorian date
postings <- postingsp (Just year)
endpos <- getSourcePos
let sourcepos = (startpos, endpos)
return $ txnTieKnot $ Transaction 0 "" sourcepos date edate status code description comment tags postings
--- *** postings
-- Parse the following whitespace-beginning lines as postings, posting
-- tags, and/or comments (inferring year, if needed, from the given date).
postingsp :: Maybe Year -> JournalParser m [Posting]
postingsp mTransactionYear = many (postingp mTransactionYear) <?> "postings"
-- linebeginningwithspaces :: JournalParser m String
-- linebeginningwithspaces = do
-- sp <- lift skipNonNewlineSpaces1
-- c <- nonspace
-- cs <- lift restofline
return $ sp + + ( c : cs ) + + " \n "
postingp :: Maybe Year -> JournalParser m Posting
postingp = fmap fst . postingphelper False
-- Parse the following whitespace-beginning lines as transaction posting rules, posting
-- tags, and/or comments (inferring year, if needed, from the given date).
tmpostingrulesp :: Maybe Year -> JournalParser m [TMPostingRule]
tmpostingrulesp mTransactionYear = many (tmpostingrulep mTransactionYear) <?> "posting rules"
tmpostingrulep :: Maybe Year -> JournalParser m TMPostingRule
tmpostingrulep = fmap (uncurry TMPostingRule) . postingphelper True
-- Parse a Posting, and return a flag with whether a multiplier has been detected.
-- The multiplier is used in TMPostingRules.
postingphelper :: Bool -> Maybe Year -> JournalParser m (Posting, Bool)
postingphelper isPostingRule mTransactionYear = do
lift $ dbgparse 0 " postingp "
(status, account) <- try $ do
lift skipNonNewlineSpaces1
status <- lift statusp
lift skipNonNewlineSpaces
account <- modifiedaccountnamep
return (status, account)
let (ptype, account') = (accountNamePostingType account, textUnbracket account)
lift skipNonNewlineSpaces
mult <- if isPostingRule then multiplierp else pure False
amt <- optional $ amountp' mult
lift skipNonNewlineSpaces
massertion <- optional balanceassertionp
lift skipNonNewlineSpaces
(comment,tags,mdate,mdate2) <- lift $ postingcommentp mTransactionYear
let p = posting
{ pdate=mdate
, pdate2=mdate2
, pstatus=status
, paccount=account'
, pamount=maybe missingmixedamt mixedAmount amt
, pcomment=comment
, ptype=ptype
, ptags=tags
, pbalanceassertion=massertion
}
return (p, mult)
where
multiplierp = option False $ True <$ char '*'
--- ** tests
tests_JournalReader = testGroup "JournalReader" [
let p = lift accountnamep :: JournalParser IO AccountName in
testGroup "accountnamep" [
testCase "basic" $ assertParse p "a:b:c"
, " empty inner component " $ assertParseError p " a::c " " " -- TODO
, " empty leading component " $ assertParseError p " : b : c " " x "
, " empty trailing component " $ assertParseError p " a : b : " " x "
]
" a date in YYYY / MM / DD format .
-- Hyphen (-) and period (.) are also allowed as separators.
The year may be omitted if a default year has been set .
-- Leading zeroes may be omitted."
,testGroup "datep" [
testCase "YYYY/MM/DD" $ assertParseEq datep "2018/01/01" (fromGregorian 2018 1 1)
,testCase "YYYY-MM-DD" $ assertParse datep "2018-01-01"
,testCase "YYYY.MM.DD" $ assertParse datep "2018.01.01"
,testCase "yearless date with no default year" $ assertParseError datep "1/1" "current year is unknown"
,testCase "yearless date with default year" $ do
let s = "1/1"
ep <- parseWithState nulljournal{jparsedefaultyear=Just 2018} datep s
either (assertFailure . ("parse error at "++) . customErrorBundlePretty) (const $ return ()) ep
,testCase "no leading zero" $ assertParse datep "2018/1/1"
]
,testCase "datetimep" $ do
let
good = assertParse datetimep
bad t = assertParseError datetimep t ""
good "2011/1/1 00:00"
good "2011/1/1 23:59:59"
bad "2011/1/1"
bad "2011/1/1 24:00:00"
bad "2011/1/1 00:60:00"
bad "2011/1/1 00:00:60"
bad "2011/1/1 3:5:7"
-- timezone is parsed but ignored
let t = LocalTime (fromGregorian 2018 1 1) (TimeOfDay 0 0 0)
assertParseEq datetimep "2018/1/1 00:00-0800" t
assertParseEq datetimep "2018/1/1 00:00+1234" t
,testGroup "periodictransactionp" [
testCase "more period text in comment after one space" $ assertParseEq periodictransactionp
"~ monthly from 2018/6 ;In 2019 we will change this\n"
nullperiodictransaction {
ptperiodexpr = "monthly from 2018/6"
,ptinterval = Months 1
,ptspan = DateSpan (Just $ Flex $ fromGregorian 2018 6 1) Nothing
,ptsourcepos = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))
,ptdescription = ""
,ptcomment = "In 2019 we will change this\n"
}
,testCase "more period text in description after two spaces" $ assertParseEq periodictransactionp
"~ monthly from 2018/6 In 2019 we will change this\n"
nullperiodictransaction {
ptperiodexpr = "monthly from 2018/6"
,ptinterval = Months 1
,ptspan = DateSpan (Just $ Flex $ fromGregorian 2018 6 1) Nothing
,ptsourcepos = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))
,ptdescription = "In 2019 we will change this"
,ptcomment = ""
}
,testCase "Next year in description" $ assertParseEq periodictransactionp
"~ monthly Next year blah blah\n"
nullperiodictransaction {
ptperiodexpr = "monthly"
,ptinterval = Months 1
,ptspan = DateSpan Nothing Nothing
,ptsourcepos = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))
,ptdescription = "Next year blah blah"
,ptcomment = ""
}
,testCase "Just date, no description" $ assertParseEq periodictransactionp
"~ 2019-01-04\n"
nullperiodictransaction {
ptperiodexpr = "2019-01-04"
,ptinterval = NoInterval
,ptspan = DateSpan (Just $ Exact $ fromGregorian 2019 1 4) (Just $ Exact $ fromGregorian 2019 1 5)
,ptsourcepos = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))
,ptdescription = ""
,ptcomment = ""
}
,testCase "Just date, no description + empty transaction comment" $ assertParse periodictransactionp
"~ 2019-01-04\n ;\n a 1\n b\n"
]
,testGroup "postingp" [
testCase "basic" $ assertParseEq (postingp Nothing)
" expenses:food:dining $10.00 ; a: a a \n ; b: b b \n"
posting{
paccount="expenses:food:dining",
pamount=mixedAmount (usd 10),
pcomment="a: a a\nb: b b\n",
ptags=[("a","a a"), ("b","b b")]
}
,testCase "posting dates" $ assertParseEq (postingp Nothing)
" a 1. ; date:2012/11/28, date2=2012/11/29,b:b\n"
nullposting{
paccount="a"
,pamount=mixedAmount (num 1)
,pcomment="date:2012/11/28, date2=2012/11/29,b:b\n"
TODO tag name parsed too greedily
,pdate=Just $ fromGregorian 2012 11 28
Just $ fromGregorian 2012 11 29
}
,testCase "posting dates bracket syntax" $ assertParseEq (postingp Nothing)
" a 1. ; [2012/11/28=2012/11/29]\n"
nullposting{
paccount="a"
,pamount=mixedAmount (num 1)
,pcomment="[2012/11/28=2012/11/29]\n"
,ptags=[]
,pdate= Just $ fromGregorian 2012 11 28
,pdate2=Just $ fromGregorian 2012 11 29
}
,testCase "quoted commodity symbol with digits" $ assertParse (postingp Nothing) " a 1 \"DE123\"\n"
,testCase "only lot price" $ assertParse (postingp Nothing) " a 1A {1B}\n"
,testCase "fixed lot price" $ assertParse (postingp Nothing) " a 1A {=1B}\n"
,testCase "total lot price" $ assertParse (postingp Nothing) " a 1A {{1B}}\n"
,testCase "fixed total lot price, and spaces" $ assertParse (postingp Nothing) " a 1A {{ = 1B }}\n"
,testCase "lot price before transaction price" $ assertParse (postingp Nothing) " a 1A {1B} @ 1B\n"
,testCase "lot price after transaction price" $ assertParse (postingp Nothing) " a 1A @ 1B {1B}\n"
,testCase "lot price after balance assertion not allowed" $ assertParseError (postingp Nothing) " a 1A @ 1B = 1A {1B}\n" "unexpected '{'"
,testCase "only lot date" $ assertParse (postingp Nothing) " a 1A [2000-01-01]\n"
,testCase "transaction price, lot price, lot date" $ assertParse (postingp Nothing) " a 1A @ 1B {1B} [2000-01-01]\n"
,testCase "lot date, lot price, transaction price" $ assertParse (postingp Nothing) " a 1A [2000-01-01] {1B} @ 1B\n"
,testCase "balance assertion over entire contents of account" $ assertParse (postingp Nothing) " a $1 == $1\n"
]
,testGroup "transactionmodifierp" [
testCase "basic" $ assertParseEq transactionmodifierp
"= (some value expr)\n some:postings 1.\n"
nulltransactionmodifier {
tmquerytxt = "(some value expr)"
,tmpostingrules = [TMPostingRule nullposting{paccount="some:postings", pamount=mixedAmount (num 1)} False]
}
]
,testGroup "transactionp" [
testCase "just a date" $ assertParseEq transactionp "2015/1/1\n" nulltransaction{tdate=fromGregorian 2015 1 1}
,testCase "more complex" $ assertParseEq transactionp
(T.unlines [
"2012/05/14=2012/05/15 (code) desc ; tcomment1",
" ; tcomment2",
" ; ttag1: val1",
" * a $1.00 ; pcomment1",
" ; pcomment2",
" ; ptag1: val1",
" ; ptag2: val2"
])
nulltransaction{
8 because there are 7 lines
tprecedingcomment="",
tdate=fromGregorian 2012 5 14,
tdate2=Just $ fromGregorian 2012 5 15,
tstatus=Unmarked,
tcode="code",
tdescription="desc",
tcomment="tcomment1\ntcomment2\nttag1: val1\n",
ttags=[("ttag1","val1")],
tpostings=[
nullposting{
pdate=Nothing,
pstatus=Cleared,
paccount="a",
pamount=mixedAmount (usd 1),
pcomment="pcomment1\npcomment2\nptag1: val1\nptag2: val2\n",
ptype=RegularPosting,
ptags=[("ptag1","val1"),("ptag2","val2")],
ptransaction=Nothing
}
]
}
,testCase "parses a well-formed transaction" $
assertBool "" $ isRight $ rjp transactionp $ T.unlines
["2007/01/28 coopportunity"
," expenses:food:groceries $47.18"
," assets:checking $-47.18"
,""
]
,testCase "does not parse a following comment as part of the description" $
assertParseEqOn transactionp "2009/1/1 a ;comment\n b 1\n" tdescription "a"
,testCase "parses a following whitespace line" $
assertBool "" $ isRight $ rjp transactionp $ T.unlines
["2012/1/1"
," a 1"
," b"
," "
]
,testCase "parses an empty transaction comment following whitespace line" $
assertBool "" $ isRight $ rjp transactionp $ T.unlines
["2012/1/1"
," ;"
," a 1"
," b"
," "
]
,testCase "comments everywhere, two postings parsed" $
assertParseEqOn transactionp
(T.unlines
["2009/1/1 x ; transaction comment"
," a 1 ; posting 1 comment"
," ; posting 1 comment 2"
," b"
," ; posting 2 comment"
])
(length . tpostings)
2
]
-- directives
,testGroup "directivep" [
testCase "supports !" $ do
assertParseE directivep "!account a\n"
assertParseE directivep "!D 1.0\n"
]
,testGroup "accountdirectivep" [
testCase "with-comment" $ assertParse accountdirectivep "account a:b ; a comment\n"
,testCase "does-not-support-!" $ assertParseError accountdirectivep "!account a:b\n" ""
,testCase "account-type-code" $ assertParse accountdirectivep "account a:b ; type:A\n"
,testCase "account-type-tag" $ assertParseStateOn accountdirectivep "account a:b ; type:asset\n"
jdeclaredaccounts
[("a:b", AccountDeclarationInfo{adicomment = "type:asset\n"
,aditags = [("type","asset")]
,adideclarationorder = 1
,adisourcepos = fst nullsourcepos
})
]
]
,testCase "commodityconversiondirectivep" $ do
assertParse commodityconversiondirectivep "C 1h = $50.00\n"
,testCase "defaultcommoditydirectivep" $ do
assertParse defaultcommoditydirectivep "D $1,000.0\n"
assertParseError defaultcommoditydirectivep "D $1000\n" "Please include a decimal point or decimal comma"
,testGroup "defaultyeardirectivep" [
testCase "1000" $ assertParse defaultyeardirectivep "Y 1000" -- XXX no \n like the others
, " 999 " $ assertParseError defaultyeardirectivep " Y 999 " " bad year number "
,testCase "12345" $ assertParse defaultyeardirectivep "Y 12345"
]
,testCase "ignoredpricecommoditydirectivep" $ do
assertParse ignoredpricecommoditydirectivep "N $\n"
,testGroup "includedirectivep" [
testCase "include" $ assertParseErrorE includedirectivep "include nosuchfile\n" "No existing files match pattern: nosuchfile"
,testCase "glob" $ assertParseErrorE includedirectivep "include nosuchfile*\n" "No existing files match pattern: nosuchfile*"
]
,testCase "marketpricedirectivep" $ assertParseEq marketpricedirectivep
"P 2017/01/30 BTC $922.83\n"
PriceDirective{
pddate = fromGregorian 2017 1 30,
pdcommodity = "BTC",
pdamount = usd 922.83
}
,testGroup "payeedirectivep" [
testCase "simple" $ assertParse payeedirectivep "payee foo\n"
,testCase "with-comment" $ assertParse payeedirectivep "payee foo ; comment\n"
]
,testCase "tagdirectivep" $ do
assertParse tagdirectivep "tag foo \n"
,testCase "endtagdirectivep" $ do
assertParse endtagdirectivep "end tag \n"
assertParse endtagdirectivep "end apply tag \n"
,testGroup "journalp" [
testCase "empty file" $ assertParseEqE journalp "" nulljournal
]
-- these are defined here rather than in Common so they can use journalp
,testCase "parseAndFinaliseJournal" $ do
ej <- runExceptT $ parseAndFinaliseJournal journalp definputopts "" "2019-1-1\n"
let Right j = ej
assertEqual "" [""] $ journalFilePaths j
]
| null | https://raw.githubusercontent.com/simonmichael/hledger/fa70f160aef091fa672050adb704a1d88d14ea20/hledger-lib/Hledger/Read/JournalReader.hs | haskell | - * -*- outline-regexp:"--- *"; -*-
- ** doc
- ** language
# LANGUAGE FlexibleContexts #
# LANGUAGE NoMonoLocalBinds #
# LANGUAGE OverloadedStrings #
# LANGUAGE PackageImports #
- ** exports
* Reader-finding utils
* Reader
* Parsing utils
* Tests
- ** imports
- ** doctest setup
$setup
>>> :set -XOverloadedStrings
- ** parsing utilities
| Run a journal parser in some monad. See also: parseWithState.
| Run an erroring journal parser in some monad. See also: parseWithState.
- ** reader finding utilities
The available journal readers, each one handling a particular data format.
,LedgerReader.reader
| @findReader mformat mpath@
its file extension, if any.
| A file path optionally prefixed by a reader name and colon
(journal:, csv:, timedot:, etc.).
split that off. Eg "csv:-" -> (Just "csv", "-").
- ** reader
no need to add command line aliases like journalp'
when called as a subparser I think
format, or give an error.
reverse parsed aliases to ensure that they are applied in order given on commandline
- ** parsers
- *** journal
| A journal parser. Accumulates and returns a "ParsedJournal",
which should be finalised/validated before use.
| A side-effecting parser; parses any kind of journal item
and updates the parse state accordingly.
character, can use choice without backtracking
- *** directives
Cf #directives,
-cli.org/3.0/doc/ledger3.html#Command-Directives
| Parse an include directive. include's argument is an optionally
file-format-prefixed file path or glob pattern. In the latter case,
the prefix is applied to each matched path. Examples:
foo.j, foo/bar.j, timedot:foo/2020*.md
don't consume newline yet
Compiling filename as a glob pattern works even if it is a literal
Get all matching files in the current working directory, sorting in
lexicographic order to simulate the output of 'ls'.
Choose a reader/parser based on the file path prefix or file extension,
defaulting to JournalReader. Duplicating readJournal a bit here.
Merge this child journal into the parent journal
(with debug logging for troubleshooting account display order).
its parse state is kept, and its lists are appended to child's (which
ultimately produces the right list order, because parent's and child's
lists are in reverse order at this stage. Cf #1909).
XXX more accurate than journalFilePath for some reason
Update the parse state.
| Lift an IO action into the exception monad, rethrowing any IO
error with the given message prepended.
list of account declarations.
XXX figure out a more precise position later
the account name, possibly modified by preceding alias or apply account directives
maybe a comment, on this and/or following lines
maybe Ledger-style subdirectives (ignored)
an account type may have been set by account type code or a tag;
the latter takes precedence
update the journal
The special tag used for declaring account type. XXX change to "class" ?
Add an account declaration to the journal, auto-numbering it.
gets renumbered when Journals are finalised or merged
Add a payee declaration to the journal.
Add a tag declaration to the journal.
>>> Right _ <- rjp commoditydirectivep "commodity $\n\n" -- a commodity with no format
both , what happens ?
| Parse a multi-line commodity directive, containing 0 or more format subdirectives.
read all subdirectives, saving format subdirectives as Lefts
symbol does not match the one given.
More Ledger directives, ignore for now:
apply fixed, apply tag, assert, bucket, A, capture, check, define, expr
| Backtracking parser similar to string, but allows varying amount of space between words
end tag or end apply tag
a time is ignored
| Read a valid decimal mark from the decimal-mark directive e.g
decimal-mark ,
- *** transactions
| Parse a transaction modifier (auto postings) rule.
| Parse a periodic transaction rule.
This reuses periodexprp which parses period expressions on the command line.
This is awkward because periodexprp supports relative and partial dates,
which we don't really need here, and it doesn't support the notion of a
default year set by a Y directive, which we do need to consider here.
We resolve it as follows: in periodic transactions' period expressions,
if there is a default year Y in effect, partial/relative dates are calculated
first line
if there's a default year in effect, use Y/1/1 as base for partial/relative dates
'periodexprp' saves 'periodexprp' from having to respect the single-
and double-space parsing rules
| Parse a (possibly unbalanced) transaction.
- *** postings
Parse the following whitespace-beginning lines as postings, posting
tags, and/or comments (inferring year, if needed, from the given date).
linebeginningwithspaces :: JournalParser m String
linebeginningwithspaces = do
sp <- lift skipNonNewlineSpaces1
c <- nonspace
cs <- lift restofline
Parse the following whitespace-beginning lines as transaction posting rules, posting
tags, and/or comments (inferring year, if needed, from the given date).
Parse a Posting, and return a flag with whether a multiplier has been detected.
The multiplier is used in TMPostingRules.
- ** tests
TODO
Hyphen (-) and period (.) are also allowed as separators.
Leading zeroes may be omitted."
timezone is parsed but ignored
directives
XXX no \n like the others
these are defined here rather than in Common so they can use journalp | In Emacs , use TAB on lines beginning with " -- * " to collapse / expand sections .
|
A reader for hledger 's journal file format
( < #the-journal-file > ) . hledger 's journal
format is a compatible subset of
( < -cli.org/3.0/doc/ledger3.html#Journal-Format > ) , so this
reader should handle many ledger files as well . Example :
@
2012\/3\/24 gift
expenses : gifts $ 10
assets : cash
@
Journal format supports the include directive which can read files in
other formats , so the other file format readers need to be importable
and invocable here .
Some important parts of journal parsing are therefore kept in
Hledger . Read . Common , to avoid import cycles .
A reader for hledger's journal file format
(<#the-journal-file>). hledger's journal
format is a compatible subset of c++ ledger's
(<-cli.org/3.0/doc/ledger3.html#Journal-Format>), so this
reader should handle many ledger files as well. Example:
@
2012\/3\/24 gift
expenses:gifts $10
assets:cash
@
Journal format supports the include directive which can read files in
other formats, so the other file format readers need to be importable
and invocable here.
Some important parts of journal parsing are therefore kept in
Hledger.Read.Common, to avoid import cycles.
-}
# LANGUAGE NamedFieldPuns #
# LANGUAGE ScopedTypeVariables #
module Hledger.Read.JournalReader (
findReader,
splitReaderPrefix,
reader,
parseAndFinaliseJournal,
runJournalParser,
rjp,
runErroringJournalParser,
rejp,
* used elsewhere
getParentAccount,
journalp,
directivep,
defaultyeardirectivep,
marketpricedirectivep,
datetimep,
datep,
modifiedaccountnamep,
tmpostingrulep,
statusp,
emptyorcommentlinep,
followingcommentp,
accountaliasp
,tests_JournalReader
)
where
import qualified Control.Monad.Fail as Fail (fail)
import qualified Control.Exception as C
import Control.Monad (forM_, when, void, unless)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Except (ExceptT(..), runExceptT)
import Control.Monad.State.Strict (evalStateT,get,modify',put)
import Control.Monad.Trans.Class (lift)
import Data.Char (toLower)
import Data.Either (isRight, lefts)
import qualified Data.Map.Strict as M
import Data.Text (Text)
import Data.String
import Data.List
import Data.Maybe
import qualified Data.Text as T
import Data.Time.Calendar
import Data.Time.LocalTime
import Safe
import Text.Megaparsec hiding (parse)
import Text.Megaparsec.Char
import Text.Megaparsec.Custom
import Text.Printf
import System.FilePath
import "Glob" System.FilePath.Glob hiding (match)
import Hledger.Data
import Hledger.Read.Common
import Hledger.Utils
import qualified Hledger.Read.TimedotReader as TimedotReader (reader)
import qualified Hledger.Read.TimeclockReader as TimeclockReader (reader)
import qualified Hledger.Read.CsvReader as CsvReader (reader)
runJournalParser, rjp
:: Monad m
=> JournalParser m a -> Text -> m (Either HledgerParseErrors a)
runJournalParser p = runParserT (evalStateT p nulljournal) ""
rjp = runJournalParser
runErroringJournalParser, rejp
:: Monad m
=> ErroringJournalParser m a
-> Text
-> m (Either FinalParseError (Either HledgerParseErrors a))
runErroringJournalParser p t =
runExceptT $ runParserT (evalStateT p nulljournal) "" t
rejp = runErroringJournalParser
Defined here rather than Hledger . Read so that we can use them in includedirectivep below .
readers' :: MonadIO m => [Reader m]
readers' = [
reader
,TimeclockReader.reader
,TimedotReader.reader
,CsvReader.reader
]
readerNames :: [String]
readerNames = map rFormat (readers'::[Reader IO])
Find the reader named by @mformat@ , if provided .
Or , if a file path is provided , find the first reader that handles
findReader :: MonadIO m => Maybe StorageFormat -> Maybe FilePath -> Maybe (Reader m)
findReader Nothing Nothing = Nothing
findReader (Just fmt) _ = headMay [r | r <- readers', rFormat r == fmt]
findReader Nothing (Just path) =
case prefix of
Just fmt -> headMay [r | r <- readers', rFormat r == fmt]
Nothing -> headMay [r | r <- readers', ext `elem` rExtensions r]
where
(prefix,path') = splitReaderPrefix path
ext = map toLower $ drop 1 $ takeExtension path'
type PrefixedFilePath = FilePath
| If a filepath is prefixed by one of the reader names and a colon ,
splitReaderPrefix :: PrefixedFilePath -> (Maybe String, FilePath)
splitReaderPrefix f =
headDef (Nothing, f)
[(Just r, drop (length r + 1) f) | r <- readerNames, (r++":") `isPrefixOf` f]
reader :: MonadIO m => Reader m
reader = Reader
{rFormat = "journal"
,rExtensions = ["journal", "j", "hledger", "ledger"]
,rReadFn = parse
}
| Parse and post - process a " Journal " from hledger 's journal file
parse :: InputOpts -> FilePath -> Text -> ExceptT String IO Journal
parse iopts f = parseAndFinaliseJournal journalp' iopts f
where
journalp' = do
mapM_ addAccountAlias (reverse $ aliasesFromOpts iopts)
journalp
> > > rejp ( < * eof ) " 2015/1/1\n a 0\n "
Right ( Right Journal ( unknown ) with 1 transactions , 1 accounts )
journalp :: MonadIO m => ErroringJournalParser m ParsedJournal
journalp = do
many addJournalItemP
eof
get
addJournalItemP :: MonadIO m => ErroringJournalParser m ()
addJournalItemP =
all journal line types can be distinguished by the first
choice [
directivep
, transactionp >>= modify' . addTransaction
, transactionmodifierp >>= modify' . addTransactionModifier
, periodictransactionp >>= modify' . addPeriodicTransaction
, marketpricedirectivep >>= modify' . addPriceDirective
, void (lift emptyorcommentlinep)
, void (lift multilinecommentp)
] <?> "transaction or directive"
| Parse any journal directive and update the parse state accordingly .
directivep :: MonadIO m => ErroringJournalParser m ()
directivep = (do
optional $ oneOf ['!','@']
choice [
includedirectivep
,aliasdirectivep
,endaliasesdirectivep
,accountdirectivep
,applyaccountdirectivep
,applyfixeddirectivep
,applytagdirectivep
,assertdirectivep
,bucketdirectivep
,capturedirectivep
,checkdirectivep
,commandlineflagdirectivep
,commoditydirectivep
,commodityconversiondirectivep
,decimalmarkdirectivep
,defaultyeardirectivep
,defaultcommoditydirectivep
,definedirectivep
,endapplyaccountdirectivep
,endapplyfixeddirectivep
,endapplytagdirectivep
,endapplyyeardirectivep
,endtagdirectivep
,evaldirectivep
,exprdirectivep
,ignoredpricecommoditydirectivep
,payeedirectivep
,pythondirectivep
,tagdirectivep
,valuedirectivep
]
) <?> "directive"
includedirectivep :: MonadIO m => ErroringJournalParser m ()
includedirectivep = do
string "include"
lift skipNonNewlineSpaces1
parentoff <- getOffset
parentpos <- getSourcePos
let (mprefix,glb) = splitReaderPrefix prefixedglob
paths <- getFilePaths parentoff parentpos glb
let prefixedpaths = case mprefix of
Nothing -> paths
Just fmt -> map ((fmt++":")++) paths
forM_ prefixedpaths $ parseChild parentpos
void newline
where
getFilePaths
:: MonadIO m => Int -> SourcePos -> FilePath -> JournalParser m [FilePath]
getFilePaths parseroff parserpos filename = do
let curdir = takeDirectory (sourceName parserpos)
filename' <- lift $ expandHomePath filename
`orRethrowIOError` (show parserpos ++ " locating " ++ filename)
fileglob <- case tryCompileWith compDefault{errorRecovery=False} filename' of
Right x -> pure x
Left e -> customFailure $
parseErrorAt parseroff $ "Invalid glob pattern: " ++ e
filepaths <- liftIO $ sort <$> globDir1 fileglob curdir
if (not . null) filepaths
then pure filepaths
else customFailure $ parseErrorAt parseroff $
"No existing files match pattern: " ++ filename
parseChild :: MonadIO m => SourcePos -> PrefixedFilePath -> ErroringJournalParser m ()
parseChild parentpos prefixedpath = do
let (_mprefix,filepath) = splitReaderPrefix prefixedpath
parentj <- get
let parentfilestack = jincludefilestack parentj
when (filepath `elem` parentfilestack) $
Fail.fail ("Cyclic include: " ++ filepath)
childInput <-
traceOrLogAt 6 ("parseChild: "++takeFileName filepath) $
lift $ readFilePortably filepath
`orRethrowIOError` (show parentpos ++ " reading " ++ filepath)
let initChildj = newJournalWithParseStateFrom filepath parentj
let r = fromMaybe reader $ findReader Nothing (Just prefixedpath)
parser = rParser r
dbg6IO "parseChild: trying reader" (rFormat r)
Parse the file ( of whichever format ) to a Journal , with file path and source text attached .
updatedChildj <- journalAddFile (filepath, childInput) <$>
parseIncludeFile parser initChildj filepath childInput
The parent journal is the second argument to journalConcat ; this means
let
parentj' =
dbgJournalAcctDeclOrder ("parseChild: child " <> childfilename <> " acct decls: ") updatedChildj
`journalConcat`
dbgJournalAcctDeclOrder ("parseChild: parent " <> parentfilename <> " acct decls: ") parentj
where
childfilename = takeFileName filepath
put parentj'
newJournalWithParseStateFrom :: FilePath -> Journal -> Journal
newJournalWithParseStateFrom filepath j = nulljournal{
jparsedefaultyear = jparsedefaultyear j
,jparsedefaultcommodity = jparsedefaultcommodity j
,jparseparentaccounts = jparseparentaccounts j
,jparsedecimalmark = jparsedecimalmark j
,jparsealiases = jparsealiases j
,jcommodities = jcommodities j
, jparsetransactioncount = jparsetransactioncount j
,jparsetimeclockentries = jparsetimeclockentries j
,jincludefilestack = filepath : jincludefilestack j
}
orRethrowIOError :: MonadIO m => IO a -> String -> TextParser m a
orRethrowIOError io msg = do
eResult <- liftIO $ (Right <$> io) `C.catch` \(e::C.IOException) -> pure $ Left $ printf "%s:\n%s" msg (show e)
case eResult of
Right res -> pure res
Left errMsg -> Fail.fail errMsg
Parse an account directive , adding its info to the journal 's
accountdirectivep :: JournalParser m ()
accountdirectivep = do
pos <- getSourcePos
string "account"
lift skipNonNewlineSpaces1
acct <- (notFollowedBy (char '(' <|> char '[') <?> "account name without brackets") >>
modifiedaccountnamep
(cmt, tags) <- lift transactioncommentp
skipMany indentedlinep
let
metype = parseAccountTypeCode <$> lookup accountTypeTagName tags
addAccountDeclaration (acct, cmt, tags, pos)
unless (null tags) $ addDeclaredAccountTags acct tags
case metype of
Nothing -> return ()
Just (Right t) -> addDeclaredAccountType acct t
Just (Left err) -> customFailure $ parseErrorAt off err
accountTypeTagName = "type"
parseAccountTypeCode :: Text -> Either String AccountType
parseAccountTypeCode s =
case T.toLower s of
"asset" -> Right Asset
"a" -> Right Asset
"liability" -> Right Liability
"l" -> Right Liability
"equity" -> Right Equity
"e" -> Right Equity
"revenue" -> Right Revenue
"r" -> Right Revenue
"expense" -> Right Expense
"x" -> Right Expense
"cash" -> Right Cash
"c" -> Right Cash
"conversion" -> Right Conversion
"v" -> Right Conversion
_ -> Left err
where
err = T.unpack $ "invalid account type code "<>s<>", should be one of " <>
T.intercalate ", " ["A","L","E","R","X","C","V","Asset","Liability","Equity","Revenue","Expense","Cash","Conversion"]
addAccountDeclaration :: (AccountName,Text,[Tag],SourcePos) -> JournalParser m ()
addAccountDeclaration (a,cmt,tags,pos) = do
modify' (\j ->
let
decls = jdeclaredaccounts j
d = (a, nullaccountdeclarationinfo{
adicomment = cmt
,aditags = tags
,adisourcepos = pos
})
in
j{jdeclaredaccounts = d:decls})
addPayeeDeclaration :: (Payee,Text,[Tag]) -> JournalParser m ()
addPayeeDeclaration (p, cmt, tags) =
modify' (\j@Journal{jdeclaredpayees} -> j{jdeclaredpayees=d:jdeclaredpayees})
where
d = (p
,nullpayeedeclarationinfo{
pdicomment = cmt
,pditags = tags
})
addTagDeclaration :: (TagName,Text) -> JournalParser m ()
addTagDeclaration (t, cmt) =
modify' (\j@Journal{jdeclaredtags} -> j{jdeclaredtags=tagandinfo:jdeclaredtags})
where
tagandinfo = (t, nulltagdeclarationinfo{tdicomment=cmt})
indentedlinep :: JournalParser m String
indentedlinep = lift skipNonNewlineSpaces1 >> (rstrip <$> lift restofline)
| Parse a one - line or multi - line commodity directive .
> > > Right _ < - rjp commoditydirectivep " commodity $ 1.00 "
> > > Right _ < - rjp commoditydirectivep " commodity $ \n format $ 1.00 "
commoditydirectivep :: JournalParser m ()
commoditydirectivep = commoditydirectiveonelinep <|> commoditydirectivemultilinep
| Parse a one - line commodity directive .
> > > Right _ < - rjp commoditydirectiveonelinep " commodity $ 1.00 "
> > > Right _ < - rjp commoditydirectiveonelinep " commodity $ 1.00 ; blah\n "
commoditydirectiveonelinep :: JournalParser m ()
commoditydirectiveonelinep = do
(off, Amount{acommodity,astyle}) <- try $ do
string "commodity"
lift skipNonNewlineSpaces1
off <- getOffset
amt <- amountp
pure $ (off, amt)
lift skipNonNewlineSpaces
_ <- lift followingcommentp
let comm = Commodity{csymbol=acommodity, cformat=Just $ dbg6 "style from commodity directive" astyle}
if isNothing $ asdecimalpoint astyle
then customFailure $ parseErrorAt off pleaseincludedecimalpoint
else modify' (\j -> j{jcommodities=M.insert acommodity comm $ jcommodities j})
pleaseincludedecimalpoint :: String
pleaseincludedecimalpoint = chomp $ unlines [
"Please include a decimal point or decimal comma in commodity directives,"
,"to help us parse correctly. It may be followed by zero or more decimal digits."
,"Examples:"
,"commodity $1000. ; no thousands mark, decimal period, no decimals"
,"commodity 1.234,00 ARS ; period at thousands, decimal comma, 2 decimals"
,"commodity EUR 1 000,000 ; space at thousands, decimal comma, 3 decimals"
,"commodity INR1,23,45,678.0 ; comma at thousands/lakhs/crores, decimal period, 1 decimal"
]
> > > Right _ < - rjp commoditydirectivemultilinep " commodity $ ; blah \n format $ 1.00 ; blah "
commoditydirectivemultilinep :: JournalParser m ()
commoditydirectivemultilinep = do
string "commodity"
lift skipNonNewlineSpaces1
sym <- lift commoditysymbolp
_ <- lift followingcommentp
subdirectives <- many $ indented (eitherP (formatdirectivep sym) (lift restofline))
let mfmt = lastMay $ lefts subdirectives
let comm = Commodity{csymbol=sym, cformat=mfmt}
modify' (\j -> j{jcommodities=M.insert sym comm $ jcommodities j})
where
indented = (lift skipNonNewlineSpaces1 >>)
| Parse a format ( sub)directive , throwing a parse error if its
formatdirectivep :: CommoditySymbol -> JournalParser m AmountStyle
formatdirectivep expectedsym = do
string "format"
lift skipNonNewlineSpaces1
off <- getOffset
Amount{acommodity,astyle} <- amountp
_ <- lift followingcommentp
if acommodity==expectedsym
then
if isNothing $ asdecimalpoint astyle
then customFailure $ parseErrorAt off pleaseincludedecimalpoint
else return $ dbg6 "style from format subdirective" astyle
else customFailure $ parseErrorAt off $
printf "commodity directive symbol \"%s\" and format directive symbol \"%s\" should be the same" expectedsym acommodity
applyfixeddirectivep, endapplyfixeddirectivep, applytagdirectivep, endapplytagdirectivep,
assertdirectivep, bucketdirectivep, capturedirectivep, checkdirectivep,
endapplyyeardirectivep, definedirectivep, exprdirectivep, valuedirectivep,
evaldirectivep, pythondirectivep, commandlineflagdirectivep
:: JournalParser m ()
applyfixeddirectivep = do string "apply fixed" >> lift restofline >> return ()
endapplyfixeddirectivep = do string "end apply fixed" >> lift restofline >> return ()
applytagdirectivep = do string "apply tag" >> lift restofline >> return ()
endapplytagdirectivep = do string "end apply tag" >> lift restofline >> return ()
endapplyyeardirectivep = do string "end apply year" >> lift restofline >> return ()
assertdirectivep = do string "assert" >> lift restofline >> return ()
bucketdirectivep = do string "A " <|> string "bucket " >> lift restofline >> return ()
capturedirectivep = do string "capture" >> lift restofline >> return ()
checkdirectivep = do string "check" >> lift restofline >> return ()
definedirectivep = do string "define" >> lift restofline >> return ()
exprdirectivep = do string "expr" >> lift restofline >> return ()
valuedirectivep = do string "value" >> lift restofline >> return ()
evaldirectivep = do string "eval" >> lift restofline >> return ()
commandlineflagdirectivep = do string "--" >> lift restofline >> return ()
pythondirectivep = do
string "python" >> lift restofline
many $ indentedline <|> blankline
return ()
where
indentedline = lift skipNonNewlineSpaces1 >> lift restofline
blankline = lift skipNonNewlineSpaces >> newline >> return "" <?> "blank line"
keywordp :: String -> JournalParser m ()
keywordp = void . string . fromString
spacesp :: JournalParser m ()
spacesp = void $ lift skipNonNewlineSpaces1
keywordsp :: String -> JournalParser m ()
keywordsp = try . sequence_ . intersperse spacesp . map keywordp . words
applyaccountdirectivep :: JournalParser m ()
applyaccountdirectivep = do
keywordsp "apply account" <?> "apply account directive"
lift skipNonNewlineSpaces1
parent <- lift accountnamep
newline
pushParentAccount parent
endapplyaccountdirectivep :: JournalParser m ()
endapplyaccountdirectivep = do
keywordsp "end apply account" <?> "end apply account directive"
popParentAccount
aliasdirectivep :: JournalParser m ()
aliasdirectivep = do
string "alias"
lift skipNonNewlineSpaces1
alias <- lift accountaliasp
addAccountAlias alias
endaliasesdirectivep :: JournalParser m ()
endaliasesdirectivep = do
keywordsp "end aliases" <?> "end aliases directive"
clearAccountAliases
tagdirectivep :: JournalParser m ()
tagdirectivep = do
string "tag" <?> "tag directive"
lift skipNonNewlineSpaces1
tagname <- lift $ T.pack <$> some nonspace
(comment, _) <- lift transactioncommentp
skipMany indentedlinep
addTagDeclaration (tagname,comment)
return ()
endtagdirectivep :: JournalParser m ()
endtagdirectivep = (do
string "end"
lift skipNonNewlineSpaces1
optional $ string "apply" >> lift skipNonNewlineSpaces1
string "tag"
lift skipNonNewlineSpaces
eol
return ()
) <?> "end tag or end apply tag directive"
payeedirectivep :: JournalParser m ()
payeedirectivep = do
string "payee" <?> "payee directive"
lift skipNonNewlineSpaces1
payee <- lift $ T.strip <$> noncommenttext1p
(comment, tags) <- lift transactioncommentp
skipMany indentedlinep
addPayeeDeclaration (payee, comment, tags)
return ()
defaultyeardirectivep :: JournalParser m ()
defaultyeardirectivep = do
(string "Y" <|> string "year" <|> string "apply year") <?> "default year"
lift skipNonNewlineSpaces
setYear =<< lift yearp
defaultcommoditydirectivep :: JournalParser m ()
defaultcommoditydirectivep = do
char 'D' <?> "default commodity"
lift skipNonNewlineSpaces1
off <- getOffset
Amount{acommodity,astyle} <- amountp
lift restofline
if isNothing $ asdecimalpoint astyle
then customFailure $ parseErrorAt off pleaseincludedecimalpoint
else setDefaultCommodityAndStyle (acommodity, astyle)
marketpricedirectivep :: JournalParser m PriceDirective
marketpricedirectivep = do
char 'P' <?> "market price"
lift skipNonNewlineSpaces
lift skipNonNewlineSpaces1
symbol <- lift commoditysymbolp
lift skipNonNewlineSpaces
price <- amountp
lift restofline
return $ PriceDirective date symbol price
ignoredpricecommoditydirectivep :: JournalParser m ()
ignoredpricecommoditydirectivep = do
char 'N' <?> "ignored-price commodity"
lift skipNonNewlineSpaces1
lift commoditysymbolp
lift restofline
return ()
commodityconversiondirectivep :: JournalParser m ()
commodityconversiondirectivep = do
char 'C' <?> "commodity conversion"
lift skipNonNewlineSpaces1
amountp
lift skipNonNewlineSpaces
char '='
lift skipNonNewlineSpaces
amountp
lift restofline
return ()
decimalmarkdirectivep :: JournalParser m ()
decimalmarkdirectivep = do
string "decimal-mark" <?> "decimal mark"
lift skipNonNewlineSpaces1
mark <- satisfy isDecimalMark
modify' $ \j -> j{jparsedecimalmark=Just mark}
lift restofline
return ()
transactionmodifierp :: JournalParser m TransactionModifier
transactionmodifierp = do
char '=' <?> "modifier transaction"
lift skipNonNewlineSpaces
querytxt <- lift $ T.strip <$> descriptionp
TODO apply these to modified txns ?
postingrules <- tmpostingrulesp Nothing
return $ TransactionModifier querytxt postingrules
relative to Y/1/1 . If not , they are calculated related to today as usual .
periodictransactionp :: MonadIO m => JournalParser m PeriodicTransaction
periodictransactionp = do
startpos <- getSourcePos
char '~' <?> "periodic transaction"
lift $ skipNonNewlineSpaces
today <- liftIO getCurrentDay
mdefaultyear <- getYear
let refdate = case mdefaultyear of
Nothing -> today
Just y -> fromGregorian y 1 1
periodExcerpt <- lift $ excerpt_ $
singlespacedtextsatisfying1p (\c -> c /= ';' && c /= '\n')
let periodtxt = T.strip $ getExcerptText periodExcerpt
first parsing with ' ' , then " re - parsing " with
(interval, spn) <- lift $ reparseExcerpt periodExcerpt $ do
pexp <- periodexprp refdate
(<|>) eof $ do
offset1 <- getOffset
void takeRest
offset2 <- getOffset
customFailure $ parseErrorAtRegion offset1 offset2 $
"remainder of period expression cannot be parsed"
<> "\nperhaps you need to terminate the period expression with a double space?"
<> "\na double space is required between period expression and description/comment"
pure pexp
status <- lift statusp <?> "cleared status"
code <- lift codep <?> "transaction code"
description <- lift $ T.strip <$> descriptionp
(comment, tags) <- lift transactioncommentp
next lines ; use same year determined above
postings <- postingsp (Just $ first3 $ toGregorian refdate)
endpos <- getSourcePos
let sourcepos = (startpos, endpos)
return $ nullperiodictransaction{
ptperiodexpr=periodtxt
,ptinterval=interval
,ptspan=spn
,ptsourcepos=sourcepos
,ptstatus=status
,ptcode=code
,ptdescription=description
,ptcomment=comment
,pttags=tags
,ptpostings=postings
}
transactionp :: JournalParser m Transaction
transactionp = do
dbgparse 0 " "
startpos <- getSourcePos
date <- datep <?> "transaction"
edate <- optional (lift $ secondarydatep date) <?> "secondary date"
lookAhead (lift spacenonewline <|> newline) <?> "whitespace or newline"
status <- lift statusp <?> "cleared status"
code <- lift codep <?> "transaction code"
description <- lift $ T.strip <$> descriptionp
(comment, tags) <- lift transactioncommentp
let year = first3 $ toGregorian date
postings <- postingsp (Just year)
endpos <- getSourcePos
let sourcepos = (startpos, endpos)
return $ txnTieKnot $ Transaction 0 "" sourcepos date edate status code description comment tags postings
postingsp :: Maybe Year -> JournalParser m [Posting]
postingsp mTransactionYear = many (postingp mTransactionYear) <?> "postings"
return $ sp + + ( c : cs ) + + " \n "
postingp :: Maybe Year -> JournalParser m Posting
postingp = fmap fst . postingphelper False
tmpostingrulesp :: Maybe Year -> JournalParser m [TMPostingRule]
tmpostingrulesp mTransactionYear = many (tmpostingrulep mTransactionYear) <?> "posting rules"
tmpostingrulep :: Maybe Year -> JournalParser m TMPostingRule
tmpostingrulep = fmap (uncurry TMPostingRule) . postingphelper True
postingphelper :: Bool -> Maybe Year -> JournalParser m (Posting, Bool)
postingphelper isPostingRule mTransactionYear = do
lift $ dbgparse 0 " postingp "
(status, account) <- try $ do
lift skipNonNewlineSpaces1
status <- lift statusp
lift skipNonNewlineSpaces
account <- modifiedaccountnamep
return (status, account)
let (ptype, account') = (accountNamePostingType account, textUnbracket account)
lift skipNonNewlineSpaces
mult <- if isPostingRule then multiplierp else pure False
amt <- optional $ amountp' mult
lift skipNonNewlineSpaces
massertion <- optional balanceassertionp
lift skipNonNewlineSpaces
(comment,tags,mdate,mdate2) <- lift $ postingcommentp mTransactionYear
let p = posting
{ pdate=mdate
, pdate2=mdate2
, pstatus=status
, paccount=account'
, pamount=maybe missingmixedamt mixedAmount amt
, pcomment=comment
, ptype=ptype
, ptags=tags
, pbalanceassertion=massertion
}
return (p, mult)
where
multiplierp = option False $ True <$ char '*'
tests_JournalReader = testGroup "JournalReader" [
let p = lift accountnamep :: JournalParser IO AccountName in
testGroup "accountnamep" [
testCase "basic" $ assertParse p "a:b:c"
, " empty leading component " $ assertParseError p " : b : c " " x "
, " empty trailing component " $ assertParseError p " a : b : " " x "
]
" a date in YYYY / MM / DD format .
The year may be omitted if a default year has been set .
,testGroup "datep" [
testCase "YYYY/MM/DD" $ assertParseEq datep "2018/01/01" (fromGregorian 2018 1 1)
,testCase "YYYY-MM-DD" $ assertParse datep "2018-01-01"
,testCase "YYYY.MM.DD" $ assertParse datep "2018.01.01"
,testCase "yearless date with no default year" $ assertParseError datep "1/1" "current year is unknown"
,testCase "yearless date with default year" $ do
let s = "1/1"
ep <- parseWithState nulljournal{jparsedefaultyear=Just 2018} datep s
either (assertFailure . ("parse error at "++) . customErrorBundlePretty) (const $ return ()) ep
,testCase "no leading zero" $ assertParse datep "2018/1/1"
]
,testCase "datetimep" $ do
let
good = assertParse datetimep
bad t = assertParseError datetimep t ""
good "2011/1/1 00:00"
good "2011/1/1 23:59:59"
bad "2011/1/1"
bad "2011/1/1 24:00:00"
bad "2011/1/1 00:60:00"
bad "2011/1/1 00:00:60"
bad "2011/1/1 3:5:7"
let t = LocalTime (fromGregorian 2018 1 1) (TimeOfDay 0 0 0)
assertParseEq datetimep "2018/1/1 00:00-0800" t
assertParseEq datetimep "2018/1/1 00:00+1234" t
,testGroup "periodictransactionp" [
testCase "more period text in comment after one space" $ assertParseEq periodictransactionp
"~ monthly from 2018/6 ;In 2019 we will change this\n"
nullperiodictransaction {
ptperiodexpr = "monthly from 2018/6"
,ptinterval = Months 1
,ptspan = DateSpan (Just $ Flex $ fromGregorian 2018 6 1) Nothing
,ptsourcepos = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))
,ptdescription = ""
,ptcomment = "In 2019 we will change this\n"
}
,testCase "more period text in description after two spaces" $ assertParseEq periodictransactionp
"~ monthly from 2018/6 In 2019 we will change this\n"
nullperiodictransaction {
ptperiodexpr = "monthly from 2018/6"
,ptinterval = Months 1
,ptspan = DateSpan (Just $ Flex $ fromGregorian 2018 6 1) Nothing
,ptsourcepos = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))
,ptdescription = "In 2019 we will change this"
,ptcomment = ""
}
,testCase "Next year in description" $ assertParseEq periodictransactionp
"~ monthly Next year blah blah\n"
nullperiodictransaction {
ptperiodexpr = "monthly"
,ptinterval = Months 1
,ptspan = DateSpan Nothing Nothing
,ptsourcepos = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))
,ptdescription = "Next year blah blah"
,ptcomment = ""
}
,testCase "Just date, no description" $ assertParseEq periodictransactionp
"~ 2019-01-04\n"
nullperiodictransaction {
ptperiodexpr = "2019-01-04"
,ptinterval = NoInterval
,ptspan = DateSpan (Just $ Exact $ fromGregorian 2019 1 4) (Just $ Exact $ fromGregorian 2019 1 5)
,ptsourcepos = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))
,ptdescription = ""
,ptcomment = ""
}
,testCase "Just date, no description + empty transaction comment" $ assertParse periodictransactionp
"~ 2019-01-04\n ;\n a 1\n b\n"
]
,testGroup "postingp" [
testCase "basic" $ assertParseEq (postingp Nothing)
" expenses:food:dining $10.00 ; a: a a \n ; b: b b \n"
posting{
paccount="expenses:food:dining",
pamount=mixedAmount (usd 10),
pcomment="a: a a\nb: b b\n",
ptags=[("a","a a"), ("b","b b")]
}
,testCase "posting dates" $ assertParseEq (postingp Nothing)
" a 1. ; date:2012/11/28, date2=2012/11/29,b:b\n"
nullposting{
paccount="a"
,pamount=mixedAmount (num 1)
,pcomment="date:2012/11/28, date2=2012/11/29,b:b\n"
TODO tag name parsed too greedily
,pdate=Just $ fromGregorian 2012 11 28
Just $ fromGregorian 2012 11 29
}
,testCase "posting dates bracket syntax" $ assertParseEq (postingp Nothing)
" a 1. ; [2012/11/28=2012/11/29]\n"
nullposting{
paccount="a"
,pamount=mixedAmount (num 1)
,pcomment="[2012/11/28=2012/11/29]\n"
,ptags=[]
,pdate= Just $ fromGregorian 2012 11 28
,pdate2=Just $ fromGregorian 2012 11 29
}
,testCase "quoted commodity symbol with digits" $ assertParse (postingp Nothing) " a 1 \"DE123\"\n"
,testCase "only lot price" $ assertParse (postingp Nothing) " a 1A {1B}\n"
,testCase "fixed lot price" $ assertParse (postingp Nothing) " a 1A {=1B}\n"
,testCase "total lot price" $ assertParse (postingp Nothing) " a 1A {{1B}}\n"
,testCase "fixed total lot price, and spaces" $ assertParse (postingp Nothing) " a 1A {{ = 1B }}\n"
,testCase "lot price before transaction price" $ assertParse (postingp Nothing) " a 1A {1B} @ 1B\n"
,testCase "lot price after transaction price" $ assertParse (postingp Nothing) " a 1A @ 1B {1B}\n"
,testCase "lot price after balance assertion not allowed" $ assertParseError (postingp Nothing) " a 1A @ 1B = 1A {1B}\n" "unexpected '{'"
,testCase "only lot date" $ assertParse (postingp Nothing) " a 1A [2000-01-01]\n"
,testCase "transaction price, lot price, lot date" $ assertParse (postingp Nothing) " a 1A @ 1B {1B} [2000-01-01]\n"
,testCase "lot date, lot price, transaction price" $ assertParse (postingp Nothing) " a 1A [2000-01-01] {1B} @ 1B\n"
,testCase "balance assertion over entire contents of account" $ assertParse (postingp Nothing) " a $1 == $1\n"
]
,testGroup "transactionmodifierp" [
testCase "basic" $ assertParseEq transactionmodifierp
"= (some value expr)\n some:postings 1.\n"
nulltransactionmodifier {
tmquerytxt = "(some value expr)"
,tmpostingrules = [TMPostingRule nullposting{paccount="some:postings", pamount=mixedAmount (num 1)} False]
}
]
,testGroup "transactionp" [
testCase "just a date" $ assertParseEq transactionp "2015/1/1\n" nulltransaction{tdate=fromGregorian 2015 1 1}
,testCase "more complex" $ assertParseEq transactionp
(T.unlines [
"2012/05/14=2012/05/15 (code) desc ; tcomment1",
" ; tcomment2",
" ; ttag1: val1",
" * a $1.00 ; pcomment1",
" ; pcomment2",
" ; ptag1: val1",
" ; ptag2: val2"
])
nulltransaction{
8 because there are 7 lines
tprecedingcomment="",
tdate=fromGregorian 2012 5 14,
tdate2=Just $ fromGregorian 2012 5 15,
tstatus=Unmarked,
tcode="code",
tdescription="desc",
tcomment="tcomment1\ntcomment2\nttag1: val1\n",
ttags=[("ttag1","val1")],
tpostings=[
nullposting{
pdate=Nothing,
pstatus=Cleared,
paccount="a",
pamount=mixedAmount (usd 1),
pcomment="pcomment1\npcomment2\nptag1: val1\nptag2: val2\n",
ptype=RegularPosting,
ptags=[("ptag1","val1"),("ptag2","val2")],
ptransaction=Nothing
}
]
}
,testCase "parses a well-formed transaction" $
assertBool "" $ isRight $ rjp transactionp $ T.unlines
["2007/01/28 coopportunity"
," expenses:food:groceries $47.18"
," assets:checking $-47.18"
,""
]
,testCase "does not parse a following comment as part of the description" $
assertParseEqOn transactionp "2009/1/1 a ;comment\n b 1\n" tdescription "a"
,testCase "parses a following whitespace line" $
assertBool "" $ isRight $ rjp transactionp $ T.unlines
["2012/1/1"
," a 1"
," b"
," "
]
,testCase "parses an empty transaction comment following whitespace line" $
assertBool "" $ isRight $ rjp transactionp $ T.unlines
["2012/1/1"
," ;"
," a 1"
," b"
," "
]
,testCase "comments everywhere, two postings parsed" $
assertParseEqOn transactionp
(T.unlines
["2009/1/1 x ; transaction comment"
," a 1 ; posting 1 comment"
," ; posting 1 comment 2"
," b"
," ; posting 2 comment"
])
(length . tpostings)
2
]
,testGroup "directivep" [
testCase "supports !" $ do
assertParseE directivep "!account a\n"
assertParseE directivep "!D 1.0\n"
]
,testGroup "accountdirectivep" [
testCase "with-comment" $ assertParse accountdirectivep "account a:b ; a comment\n"
,testCase "does-not-support-!" $ assertParseError accountdirectivep "!account a:b\n" ""
,testCase "account-type-code" $ assertParse accountdirectivep "account a:b ; type:A\n"
,testCase "account-type-tag" $ assertParseStateOn accountdirectivep "account a:b ; type:asset\n"
jdeclaredaccounts
[("a:b", AccountDeclarationInfo{adicomment = "type:asset\n"
,aditags = [("type","asset")]
,adideclarationorder = 1
,adisourcepos = fst nullsourcepos
})
]
]
,testCase "commodityconversiondirectivep" $ do
assertParse commodityconversiondirectivep "C 1h = $50.00\n"
,testCase "defaultcommoditydirectivep" $ do
assertParse defaultcommoditydirectivep "D $1,000.0\n"
assertParseError defaultcommoditydirectivep "D $1000\n" "Please include a decimal point or decimal comma"
,testGroup "defaultyeardirectivep" [
, " 999 " $ assertParseError defaultyeardirectivep " Y 999 " " bad year number "
,testCase "12345" $ assertParse defaultyeardirectivep "Y 12345"
]
,testCase "ignoredpricecommoditydirectivep" $ do
assertParse ignoredpricecommoditydirectivep "N $\n"
,testGroup "includedirectivep" [
testCase "include" $ assertParseErrorE includedirectivep "include nosuchfile\n" "No existing files match pattern: nosuchfile"
,testCase "glob" $ assertParseErrorE includedirectivep "include nosuchfile*\n" "No existing files match pattern: nosuchfile*"
]
,testCase "marketpricedirectivep" $ assertParseEq marketpricedirectivep
"P 2017/01/30 BTC $922.83\n"
PriceDirective{
pddate = fromGregorian 2017 1 30,
pdcommodity = "BTC",
pdamount = usd 922.83
}
,testGroup "payeedirectivep" [
testCase "simple" $ assertParse payeedirectivep "payee foo\n"
,testCase "with-comment" $ assertParse payeedirectivep "payee foo ; comment\n"
]
,testCase "tagdirectivep" $ do
assertParse tagdirectivep "tag foo \n"
,testCase "endtagdirectivep" $ do
assertParse endtagdirectivep "end tag \n"
assertParse endtagdirectivep "end apply tag \n"
,testGroup "journalp" [
testCase "empty file" $ assertParseEqE journalp "" nulljournal
]
,testCase "parseAndFinaliseJournal" $ do
ej <- runExceptT $ parseAndFinaliseJournal journalp definputopts "" "2019-1-1\n"
let Right j = ej
assertEqual "" [""] $ journalFilePaths j
]
|
26929e224578234132bf044cfe26d26132cfc436b5a3895c0da8178fdc8240e0 | lambdaisland/deep-diff2 | ansi.cljc | (ns lambdaisland.deep-diff2.puget.color.ansi
"Coloring implementation that applies ANSI color codes to text designed to be
output to a terminal.
Use with a `:color-markup` of `:ansi`."
(:require
[clojure.string :as str]
[lambdaisland.deep-diff2.puget.color :as color]))
(def sgr-code
"Map of symbols to numeric SGR (select graphic rendition) codes."
{:none 0
:bold 1
:underline 3
:blink 5
:reverse 7
:hidden 8
:strike 9
:black 30
:red 31
:green 32
:yellow 33
:blue 34
:magenta 35
:cyan 36
:white 37
:fg-256 38
:fg-reset 39
:bg-black 40
:bg-red 41
:bg-green 42
:bg-yellow 43
:bg-blue 44
:bg-magenta 45
:bg-cyan 46
:bg-white 47
:bg-256 48
:bg-reset 49})
(defn esc
"Returns an ANSI escope string which will apply the given collection of SGR
codes."
[codes]
(let [codes (map sgr-code codes codes)
codes (str/join \; codes)]
(str \u001b \[ codes \m)))
(defn escape
"Returns an ANSI escope string which will enact the given SGR codes."
[& codes]
(esc codes))
(defn sgr
"Wraps the given string with SGR escapes to apply the given codes, then reset
the graphics."
[string & codes]
(str (esc codes) string (escape :none)))
(defn strip
"Removes color codes from the given string."
[string]
(str/replace string #"\u001b\[[0-9;]*[mK]" ""))
(defmethod color/document :ansi
[options element document]
(if-let [codes (-> options :color-scheme (get element) seq)]
[:span [:pass (esc codes)] document [:pass (escape :none)]]
document))
(defmethod color/text :ansi
[options element text]
(if-let [codes (-> options :color-scheme (get element) seq)]
(str (esc codes) text (escape :none))
text))
| null | https://raw.githubusercontent.com/lambdaisland/deep-diff2/2ef429227ac9986024e6c8f63ded9a88eb3fe9c2/src/lambdaisland/deep_diff2/puget/color/ansi.cljc | clojure | codes)] | (ns lambdaisland.deep-diff2.puget.color.ansi
"Coloring implementation that applies ANSI color codes to text designed to be
output to a terminal.
Use with a `:color-markup` of `:ansi`."
(:require
[clojure.string :as str]
[lambdaisland.deep-diff2.puget.color :as color]))
(def sgr-code
"Map of symbols to numeric SGR (select graphic rendition) codes."
{:none 0
:bold 1
:underline 3
:blink 5
:reverse 7
:hidden 8
:strike 9
:black 30
:red 31
:green 32
:yellow 33
:blue 34
:magenta 35
:cyan 36
:white 37
:fg-256 38
:fg-reset 39
:bg-black 40
:bg-red 41
:bg-green 42
:bg-yellow 43
:bg-blue 44
:bg-magenta 45
:bg-cyan 46
:bg-white 47
:bg-256 48
:bg-reset 49})
(defn esc
"Returns an ANSI escope string which will apply the given collection of SGR
codes."
[codes]
(let [codes (map sgr-code codes codes)
(str \u001b \[ codes \m)))
(defn escape
"Returns an ANSI escope string which will enact the given SGR codes."
[& codes]
(esc codes))
(defn sgr
"Wraps the given string with SGR escapes to apply the given codes, then reset
the graphics."
[string & codes]
(str (esc codes) string (escape :none)))
(defn strip
"Removes color codes from the given string."
[string]
(str/replace string #"\u001b\[[0-9;]*[mK]" ""))
(defmethod color/document :ansi
[options element document]
(if-let [codes (-> options :color-scheme (get element) seq)]
[:span [:pass (esc codes)] document [:pass (escape :none)]]
document))
(defmethod color/text :ansi
[options element text]
(if-let [codes (-> options :color-scheme (get element) seq)]
(str (esc codes) text (escape :none))
text))
|
06762882b4052234ccf09cca4f2d7ae6ba2269790e9915e88dbd9ddca5412a5b | MyDataFlow/ttalk-server | proper_symb.erl | Copyright 2010 - 2013 < > ,
< >
and < >
%%%
This file is part of PropEr .
%%%
%%% PropEr is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
%%% (at your option) any later version.
%%%
%%% PropEr is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
%%% GNU General Public License for more details.
%%%
You should have received a copy of the GNU General Public License
%%% along with PropEr. If not, see </>.
2010 - 2013 , and
%%% @version {@version}
@author
%%% @doc Symbolic datatypes handling functions.
%%%
%%% == Symbolic datatypes ==
When writing properties that involve abstract data types , such as dicts or
%%% sets, it is usually best to avoid dealing with the ADTs' internal
%%% representation directly. Working, instead, with a symbolic representation of
the ADT 's construction process ( series of API calls ) has several benefits :
%%% <ul>
%%% <li>Failing testcases are easier to read and understand. Compare:
%%% ``` {call,sets,from_list,[[1,2,3]]} '''
%%% with:
%%% ``` {set,3,16,16,8,80,48,
%%% {[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
%%% {{[],[3],[],[],[],[],[2],[],[],[],[],[1],[],[],[],[]}}} '''</li>
%%% <li>Failing testcases are easier to shrink.</li>
%%% <li>It is especially useful when testing the datatype itself: Certain
%%% implementation errors may depend on some particular selection and
ordering of API calls , thus it is important to cover the entire ADT
%%% construction API.</li>
%%% </ul>
%%%
%%% PropEr supports the symbolic representation of datatypes, using the
%%% following syntax:
%%% <dl>
< dt>`{call , Module , Function , Arguments}'</dt >
%%% <dd>This represents a call to the API function `Module:Function' with
%%% arguments `Arguments'. Each of the arguments may be a symbolic call itself
%%% or contain other symbolic calls in lists or tuples of arbitrary
%%% depth.</dd>
< dt id="$call">``{'$call',Module , Function , Arguments}''</dt >
%%% <dd>Identical to the above, but gets evaluated automatically before being
%%% applied to a property.</dd>
%%% <dt id="var">`{var,'{@type var_id()}`}'</dt>
%%% <dd>This contruct serves as a placeholder for values that are not known at
%%% type construction time. It will be replaced by the actual value of the
%%% variable during evaluation.</dd>
%%% </dl>
%%%
%%% When including the PropEr header file, all
%%% <a href="#index">API functions</a> of this module are automatically
imported , unless ` ' is defined .
%%%
%%% == Auto-ADT ==
To simplify the symbolic testing of ADTs , PropEr comes with the Auto - ADT
%%% subsystem: An opaque native type, if exported from its module, is assumed
%%% to be an abstract data type, causing PropEr to ignore its internal
%%% representation and instead construct symbolic instances of the type. The
API functions used in these symbolic instances are extracted from the ADT 's
defining module , which is expected to contain one or more ` -spec'ed and
exported functions that can be used to construct instances of the ADT .
Specifically , PropEr will use all functions that return at least one
instance of the ADT . As with recursive native types , the base case is
automatically detected ( in the case of , calls to functions like
` new/0 ' and ` from_list/1 ' would be considered the base case ) . The produced
symbolic calls will be < a href="#$call">`$call ' tuples</a > , which are
%%% automatically evaluated, thus no call to {@link eval/1} is required inside
%%% the property. Produced instances are guaranteed to evaluate successfully.
Parametric ADTs are supported , so long as they appear fully instantiated
%%% inside `?FORALL's.
%%%
ADTs hard - coded in the Erlang type system ( ` array ' , ` dict ' , ` digraph ' ,
%%% `gb_set', `gb_tree', `queue', and `set') are automatically detected and
%%% handled as such. PropEr also accepts parametric versions of the above ADTs
in ` ? FORALL 's ( ` array/1 ' , ` dict/2 ' , ` gb_set/1 ' , ` gb_tree/2 ' , ` queue/1 ' ,
` ' , also ` orddict/2 ' and ` ordset/1 ' ) . If you would like to use these
%%% parametric versions in `-type' and `-spec' declarations as well, to better
%%% document your code and facilitate spec testing, you can include the
%%% complementary header file `proper/include/proper_param_adts.hrl', which
provides the corresponding ` -type ' definitions . Please note that
%%% currenty treats these the same way as their non-parametric counterparts.
%%%
The use of Auto - ADT is currently subject to the following limitations :
%%% <ul>
< li > In the ADT 's ` -opaque ' declaration , as in all types ' declarations ,
only type variables should be used as parameters in the LHS . None of
%%% these variables can be the special `_' variable and no variable should
%%% appear more than once in the parameters.</li>
< li > inside specs can only have simple variables as parameters . These
variables can not be bound by any is_subtype constraint . Also , the special
` _ ' variable is not allowed in ADT parameters . If this would result in
singleton variables , as in the specs of functions like ` new/0 ' , use
%%% variable names that begin with an underscore.</li>
%%% <li>Specs that introduce an implicit binding among the parameters of an
ADT are rejected , e.g. :
%%% ``` -spec foo(mydict(T,S),mydict(S,T)) -> mydict(T,S). '''
%%% This includes using the same type variable twice in the parameters of
%%% an ADT.</li>
< li > While parsing the return type of specs in search of ADT references ,
%%% PropEr only recurses into tuples, unions and lists; all other constructs
are ignored . This prohibits , among others , indirect references to the ADT
%%% through other custom types and records.</li>
%%% <li>When encountering a union in the return type, PropEr will pick the
first choice that can return an ADT . This choice must be distinguishable
%%% from the others either by having a unique term structure or by having a
%%% unique tag (if it's a tagged tuple).</li>
< li > When parsing multi - clause specs , only the first clause is considered .
%%% </li>
< li > The only spec constraints we accept are ` is_subtype ' constraints whose
first argument is a simple , non- ` _ ' variable . It is not checked whether or
not these variables actually appear in the spec . The second argument of an
` is_subtype ' constraint can not contain any non- ` _ ' variables . Multiple
%%% constraints for the same variable are not supported.</li>
%%% <li> Unexported opaques and opaques with no suitable specs to serve as API
%%% calls are silently discarded. Those will be treated like ordinary types.
%%% </li>
< li > Unexported or unspecced functions are silently rejected.</li >
%%% <li>Functions with unsuitable return values are silently rejected.</li>
%%% <li>Specs that make bad use of variables are silently rejected.</li>
%%% </ul>
%%%
For an example on how to write Auto - ADT - compatible parametric specs , see
%%% the `examples/stack' module, which contains a simple implementation of a
%%% stack, or the `proper/proper_dict module', which wraps the `STDLIB' `dict'
ADT .
-module(proper_symb).
-export([eval/1, eval/2, defined/1, well_defined/1, pretty_print/1,
pretty_print/2]).
-export([internal_eval/1, internal_well_defined/1]).
-export_type([var_values/0]).
-include("proper_internal.hrl").
%%------------------------------------------------------------------------------
%% Types
%%------------------------------------------------------------------------------
%% -type symb_call() :: {'call' | '$call',mod_name(),fun_name(),[symb_term()]}.
%% TODO: only atoms are allowed as variable identifiers?
-type var_id() :: atom() | pos_integer().
-type var_values() :: [{var_id(),term()}].
%% @type symb_term()
-type symb_term() :: term().
-type handled_term() :: term().
-type caller() :: 'user' | 'system'.
-type call_handler() :: fun((mod_name(),fun_name(),[handled_term()]) ->
handled_term()).
-type term_handler() :: fun((term()) -> handled_term()).
-type handle_info() :: {caller(),call_handler(),term_handler()}.
%%------------------------------------------------------------------------------
%% Evaluation functions
%%------------------------------------------------------------------------------
%% @equiv eval([], SymbTerm)
-spec eval(symb_term()) -> term().
eval(SymbTerm) ->
eval([], SymbTerm).
%% @doc Intended for use inside the property-testing code, this function
evaluates a symbolic instance ` SymbTerm ' . It also accepts a proplist
` VarValues ' that maps variable names to values , which is used to replace any
< a href="#var">var tuples</a > inside ` SymbTerm ' before proceeding with its
%% evaluation.
-spec eval(var_values(), symb_term()) -> term().
eval(VarValues, SymbTerm) ->
eval(VarValues, SymbTerm, user).
-spec eval(var_values(), symb_term(), caller()) -> term().
eval(VarValues, SymbTerm, Caller) ->
HandleInfo = {Caller, fun erlang:apply/3, fun(X) -> X end},
symb_walk(VarValues, SymbTerm, HandleInfo).
@private
-spec internal_eval(symb_term()) -> term().
internal_eval(SymbTerm) ->
eval([], SymbTerm, system).
@doc Returns true if the ` SymbTerm ' symbolic instance can be successfully
%% evaluated (its evaluation doesn't raise an error or exception).
-spec defined(symb_term()) -> boolean().
defined(SymbTerm) ->
defined(SymbTerm, user).
-spec defined(symb_term(), caller()) -> boolean().
defined(SymbTerm, Caller) ->
try eval([], SymbTerm, Caller) of
_Term -> true
catch
_Exception:_Reason -> false
end.
%% @doc An attribute which can be applied to any symbolic generator `SymbType'
%% that may produce invalid sequences of operations when called. The resulting
%% generator is guaranteed to only produce well-defined symbolic instances.
-spec well_defined(proper_types:raw_type()) -> proper_types:type().
well_defined(SymbType) ->
well_defined(SymbType, user).
-spec well_defined(proper_types:raw_type(), caller()) -> proper_types:type().
well_defined(SymbType, Caller) ->
?SUCHTHAT(X, SymbType, defined(X,Caller)).
@private
-spec internal_well_defined(proper_types:type()) -> proper_types:type().
internal_well_defined(SymbType) ->
well_defined(SymbType, system).
%%------------------------------------------------------------------------------
%% Pretty-printing functions
%%------------------------------------------------------------------------------
%% @equiv pretty_print([], SymbTerm)
-spec pretty_print(symb_term()) -> string().
pretty_print(SymbTerm) ->
pretty_print([], SymbTerm).
%% @doc Similar in calling convention to {@link eval/2}, but returns a string
representation of the call sequence ` SymbTerm ' instead of evaluating it .
-spec pretty_print(var_values(), symb_term()) -> string().
pretty_print(VarValues, SymbTerm) ->
HandleInfo = {user, fun parse_fun/3, fun parse_term/1},
ExprTree = symb_walk(VarValues, SymbTerm, HandleInfo),
lists:flatten(erl_pp:expr(ExprTree)).
-spec parse_fun(mod_name(), fun_name(), [abs_expr()]) -> abs_expr().
parse_fun(Module, Function, ArgTreeList) ->
{call,0,{remote,0,{atom,0,Module},{atom,0,Function}},ArgTreeList}.
-spec parse_term(term()) -> abs_expr().
parse_term(TreeList) when is_list(TreeList) ->
{RestOfList, Acc0} =
case proper_arith:cut_improper_tail(TreeList) of
{_ProperHead,_ImproperTail} = X -> X;
ProperList -> {ProperList,{nil,0}}
end,
lists:foldr(fun(X,Acc) -> {cons,0,X,Acc} end, Acc0, RestOfList);
parse_term(TreeTuple) when is_tuple(TreeTuple) ->
{tuple,0,tuple_to_list(TreeTuple)};
parse_term(Term) ->
%% TODO: pid, port, reference, function value?
erl_parse:abstract(Term).
%%------------------------------------------------------------------------------
Generic symbolic handler function
%%------------------------------------------------------------------------------
-spec symb_walk(var_values(), symb_term(), handle_info()) -> handled_term().
symb_walk(VarValues, {call,Mod,Fun,Args},
{user,_HandleCall,_HandleTerm} = HandleInfo) ->
symb_walk_call(VarValues, Mod, Fun, Args, HandleInfo);
symb_walk(VarValues, {'$call',Mod,Fun,Args}, HandleInfo) ->
symb_walk_call(VarValues, Mod, Fun, Args, HandleInfo);
symb_walk(VarValues, {var,VarId},
{user,_HandleCall,HandleTerm} = HandleInfo) ->
SymbWalk = fun(X) -> symb_walk(VarValues, X, HandleInfo) end,
case lists:keyfind(VarId, 1, VarValues) of
{VarId,VarValue} ->
%% TODO: this allows symbolic calls and vars inside var values,
%% which may result in an infinite loop, as in:
%% [{a,{call,m,f,[{var,a}]}}], {var,a}
SymbWalk(VarValue);
false ->
HandleTerm({HandleTerm(var),SymbWalk(VarId)})
end;
symb_walk(VarValues, SymbTerm, HandleInfo) ->
symb_walk_gen(VarValues, SymbTerm, HandleInfo).
-spec symb_walk_call(var_values(), mod_name(), fun_name(), [symb_term()],
handle_info()) -> handled_term().
symb_walk_call(VarValues, Mod, Fun, Args,
{_Caller,HandleCall,_HandleTerm} = HandleInfo) ->
SymbWalk = fun(X) -> symb_walk(VarValues, X, HandleInfo) end,
HandledArgs = [SymbWalk(A) || A <- Args],
HandleCall(Mod, Fun, HandledArgs).
-spec symb_walk_gen(var_values(), symb_term(), handle_info()) -> handled_term().
symb_walk_gen(VarValues, SymbTerm,
{_Caller,_HandleCall,HandleTerm} = HandleInfo) ->
SymbWalk = fun(X) -> symb_walk(VarValues, X, HandleInfo) end,
Term =
if
is_list(SymbTerm) -> proper_arith:safe_map(SymbWalk, SymbTerm);
is_tuple(SymbTerm) -> proper_arith:tuple_map(SymbWalk, SymbTerm);
true -> SymbTerm
end,
HandleTerm(Term).
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/proper/src/proper_symb.erl | erlang |
PropEr is free software: you can redistribute it and/or modify
(at your option) any later version.
PropEr is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with PropEr. If not, see </>.
@version {@version}
@doc Symbolic datatypes handling functions.
== Symbolic datatypes ==
sets, it is usually best to avoid dealing with the ADTs' internal
representation directly. Working, instead, with a symbolic representation of
<ul>
<li>Failing testcases are easier to read and understand. Compare:
``` {call,sets,from_list,[[1,2,3]]} '''
with:
``` {set,3,16,16,8,80,48,
{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
{{[],[3],[],[],[],[],[2],[],[],[],[],[1],[],[],[],[]}}} '''</li>
<li>Failing testcases are easier to shrink.</li>
<li>It is especially useful when testing the datatype itself: Certain
implementation errors may depend on some particular selection and
construction API.</li>
</ul>
PropEr supports the symbolic representation of datatypes, using the
following syntax:
<dl>
<dd>This represents a call to the API function `Module:Function' with
arguments `Arguments'. Each of the arguments may be a symbolic call itself
or contain other symbolic calls in lists or tuples of arbitrary
depth.</dd>
<dd>Identical to the above, but gets evaluated automatically before being
applied to a property.</dd>
<dt id="var">`{var,'{@type var_id()}`}'</dt>
<dd>This contruct serves as a placeholder for values that are not known at
type construction time. It will be replaced by the actual value of the
variable during evaluation.</dd>
</dl>
When including the PropEr header file, all
<a href="#index">API functions</a> of this module are automatically
== Auto-ADT ==
subsystem: An opaque native type, if exported from its module, is assumed
to be an abstract data type, causing PropEr to ignore its internal
representation and instead construct symbolic instances of the type. The
automatically evaluated, thus no call to {@link eval/1} is required inside
the property. Produced instances are guaranteed to evaluate successfully.
inside `?FORALL's.
`gb_set', `gb_tree', `queue', and `set') are automatically detected and
handled as such. PropEr also accepts parametric versions of the above ADTs
parametric versions in `-type' and `-spec' declarations as well, to better
document your code and facilitate spec testing, you can include the
complementary header file `proper/include/proper_param_adts.hrl', which
currenty treats these the same way as their non-parametric counterparts.
<ul>
these variables can be the special `_' variable and no variable should
appear more than once in the parameters.</li>
variable names that begin with an underscore.</li>
<li>Specs that introduce an implicit binding among the parameters of an
``` -spec foo(mydict(T,S),mydict(S,T)) -> mydict(T,S). '''
This includes using the same type variable twice in the parameters of
an ADT.</li>
PropEr only recurses into tuples, unions and lists; all other constructs
through other custom types and records.</li>
<li>When encountering a union in the return type, PropEr will pick the
from the others either by having a unique term structure or by having a
unique tag (if it's a tagged tuple).</li>
</li>
constraints for the same variable are not supported.</li>
<li> Unexported opaques and opaques with no suitable specs to serve as API
calls are silently discarded. Those will be treated like ordinary types.
</li>
<li>Functions with unsuitable return values are silently rejected.</li>
<li>Specs that make bad use of variables are silently rejected.</li>
</ul>
the `examples/stack' module, which contains a simple implementation of a
stack, or the `proper/proper_dict module', which wraps the `STDLIB' `dict'
------------------------------------------------------------------------------
Types
------------------------------------------------------------------------------
-type symb_call() :: {'call' | '$call',mod_name(),fun_name(),[symb_term()]}.
TODO: only atoms are allowed as variable identifiers?
@type symb_term()
------------------------------------------------------------------------------
Evaluation functions
------------------------------------------------------------------------------
@equiv eval([], SymbTerm)
@doc Intended for use inside the property-testing code, this function
evaluation.
evaluated (its evaluation doesn't raise an error or exception).
@doc An attribute which can be applied to any symbolic generator `SymbType'
that may produce invalid sequences of operations when called. The resulting
generator is guaranteed to only produce well-defined symbolic instances.
------------------------------------------------------------------------------
Pretty-printing functions
------------------------------------------------------------------------------
@equiv pretty_print([], SymbTerm)
@doc Similar in calling convention to {@link eval/2}, but returns a string
TODO: pid, port, reference, function value?
------------------------------------------------------------------------------
------------------------------------------------------------------------------
TODO: this allows symbolic calls and vars inside var values,
which may result in an infinite loop, as in:
[{a,{call,m,f,[{var,a}]}}], {var,a} | Copyright 2010 - 2013 < > ,
< >
and < >
This file is part of PropEr .
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
2010 - 2013 , and
@author
When writing properties that involve abstract data types , such as dicts or
the ADT 's construction process ( series of API calls ) has several benefits :
ordering of API calls , thus it is important to cover the entire ADT
< dt>`{call , Module , Function , Arguments}'</dt >
< dt id="$call">``{'$call',Module , Function , Arguments}''</dt >
imported , unless ` ' is defined .
To simplify the symbolic testing of ADTs , PropEr comes with the Auto - ADT
API functions used in these symbolic instances are extracted from the ADT 's
defining module , which is expected to contain one or more ` -spec'ed and
exported functions that can be used to construct instances of the ADT .
Specifically , PropEr will use all functions that return at least one
instance of the ADT . As with recursive native types , the base case is
automatically detected ( in the case of , calls to functions like
` new/0 ' and ` from_list/1 ' would be considered the base case ) . The produced
symbolic calls will be < a href="#$call">`$call ' tuples</a > , which are
Parametric ADTs are supported , so long as they appear fully instantiated
ADTs hard - coded in the Erlang type system ( ` array ' , ` dict ' , ` digraph ' ,
in ` ? FORALL 's ( ` array/1 ' , ` dict/2 ' , ` gb_set/1 ' , ` gb_tree/2 ' , ` queue/1 ' ,
` ' , also ` orddict/2 ' and ` ordset/1 ' ) . If you would like to use these
provides the corresponding ` -type ' definitions . Please note that
The use of Auto - ADT is currently subject to the following limitations :
< li > In the ADT 's ` -opaque ' declaration , as in all types ' declarations ,
only type variables should be used as parameters in the LHS . None of
< li > inside specs can only have simple variables as parameters . These
variables can not be bound by any is_subtype constraint . Also , the special
` _ ' variable is not allowed in ADT parameters . If this would result in
singleton variables , as in the specs of functions like ` new/0 ' , use
ADT are rejected , e.g. :
< li > While parsing the return type of specs in search of ADT references ,
are ignored . This prohibits , among others , indirect references to the ADT
first choice that can return an ADT . This choice must be distinguishable
< li > When parsing multi - clause specs , only the first clause is considered .
< li > The only spec constraints we accept are ` is_subtype ' constraints whose
first argument is a simple , non- ` _ ' variable . It is not checked whether or
not these variables actually appear in the spec . The second argument of an
` is_subtype ' constraint can not contain any non- ` _ ' variables . Multiple
< li > Unexported or unspecced functions are silently rejected.</li >
For an example on how to write Auto - ADT - compatible parametric specs , see
ADT .
-module(proper_symb).
-export([eval/1, eval/2, defined/1, well_defined/1, pretty_print/1,
pretty_print/2]).
-export([internal_eval/1, internal_well_defined/1]).
-export_type([var_values/0]).
-include("proper_internal.hrl").
-type var_id() :: atom() | pos_integer().
-type var_values() :: [{var_id(),term()}].
-type symb_term() :: term().
-type handled_term() :: term().
-type caller() :: 'user' | 'system'.
-type call_handler() :: fun((mod_name(),fun_name(),[handled_term()]) ->
handled_term()).
-type term_handler() :: fun((term()) -> handled_term()).
-type handle_info() :: {caller(),call_handler(),term_handler()}.
-spec eval(symb_term()) -> term().
eval(SymbTerm) ->
eval([], SymbTerm).
evaluates a symbolic instance ` SymbTerm ' . It also accepts a proplist
` VarValues ' that maps variable names to values , which is used to replace any
< a href="#var">var tuples</a > inside ` SymbTerm ' before proceeding with its
-spec eval(var_values(), symb_term()) -> term().
eval(VarValues, SymbTerm) ->
eval(VarValues, SymbTerm, user).
-spec eval(var_values(), symb_term(), caller()) -> term().
eval(VarValues, SymbTerm, Caller) ->
HandleInfo = {Caller, fun erlang:apply/3, fun(X) -> X end},
symb_walk(VarValues, SymbTerm, HandleInfo).
@private
-spec internal_eval(symb_term()) -> term().
internal_eval(SymbTerm) ->
eval([], SymbTerm, system).
@doc Returns true if the ` SymbTerm ' symbolic instance can be successfully
-spec defined(symb_term()) -> boolean().
defined(SymbTerm) ->
defined(SymbTerm, user).
-spec defined(symb_term(), caller()) -> boolean().
defined(SymbTerm, Caller) ->
try eval([], SymbTerm, Caller) of
_Term -> true
catch
_Exception:_Reason -> false
end.
-spec well_defined(proper_types:raw_type()) -> proper_types:type().
well_defined(SymbType) ->
well_defined(SymbType, user).
-spec well_defined(proper_types:raw_type(), caller()) -> proper_types:type().
well_defined(SymbType, Caller) ->
?SUCHTHAT(X, SymbType, defined(X,Caller)).
@private
-spec internal_well_defined(proper_types:type()) -> proper_types:type().
internal_well_defined(SymbType) ->
well_defined(SymbType, system).
-spec pretty_print(symb_term()) -> string().
pretty_print(SymbTerm) ->
pretty_print([], SymbTerm).
representation of the call sequence ` SymbTerm ' instead of evaluating it .
-spec pretty_print(var_values(), symb_term()) -> string().
pretty_print(VarValues, SymbTerm) ->
HandleInfo = {user, fun parse_fun/3, fun parse_term/1},
ExprTree = symb_walk(VarValues, SymbTerm, HandleInfo),
lists:flatten(erl_pp:expr(ExprTree)).
-spec parse_fun(mod_name(), fun_name(), [abs_expr()]) -> abs_expr().
parse_fun(Module, Function, ArgTreeList) ->
{call,0,{remote,0,{atom,0,Module},{atom,0,Function}},ArgTreeList}.
-spec parse_term(term()) -> abs_expr().
parse_term(TreeList) when is_list(TreeList) ->
{RestOfList, Acc0} =
case proper_arith:cut_improper_tail(TreeList) of
{_ProperHead,_ImproperTail} = X -> X;
ProperList -> {ProperList,{nil,0}}
end,
lists:foldr(fun(X,Acc) -> {cons,0,X,Acc} end, Acc0, RestOfList);
parse_term(TreeTuple) when is_tuple(TreeTuple) ->
{tuple,0,tuple_to_list(TreeTuple)};
parse_term(Term) ->
erl_parse:abstract(Term).
Generic symbolic handler function
-spec symb_walk(var_values(), symb_term(), handle_info()) -> handled_term().
symb_walk(VarValues, {call,Mod,Fun,Args},
{user,_HandleCall,_HandleTerm} = HandleInfo) ->
symb_walk_call(VarValues, Mod, Fun, Args, HandleInfo);
symb_walk(VarValues, {'$call',Mod,Fun,Args}, HandleInfo) ->
symb_walk_call(VarValues, Mod, Fun, Args, HandleInfo);
symb_walk(VarValues, {var,VarId},
{user,_HandleCall,HandleTerm} = HandleInfo) ->
SymbWalk = fun(X) -> symb_walk(VarValues, X, HandleInfo) end,
case lists:keyfind(VarId, 1, VarValues) of
{VarId,VarValue} ->
SymbWalk(VarValue);
false ->
HandleTerm({HandleTerm(var),SymbWalk(VarId)})
end;
symb_walk(VarValues, SymbTerm, HandleInfo) ->
symb_walk_gen(VarValues, SymbTerm, HandleInfo).
-spec symb_walk_call(var_values(), mod_name(), fun_name(), [symb_term()],
handle_info()) -> handled_term().
symb_walk_call(VarValues, Mod, Fun, Args,
{_Caller,HandleCall,_HandleTerm} = HandleInfo) ->
SymbWalk = fun(X) -> symb_walk(VarValues, X, HandleInfo) end,
HandledArgs = [SymbWalk(A) || A <- Args],
HandleCall(Mod, Fun, HandledArgs).
-spec symb_walk_gen(var_values(), symb_term(), handle_info()) -> handled_term().
symb_walk_gen(VarValues, SymbTerm,
{_Caller,_HandleCall,HandleTerm} = HandleInfo) ->
SymbWalk = fun(X) -> symb_walk(VarValues, X, HandleInfo) end,
Term =
if
is_list(SymbTerm) -> proper_arith:safe_map(SymbWalk, SymbTerm);
is_tuple(SymbTerm) -> proper_arith:tuple_map(SymbWalk, SymbTerm);
true -> SymbTerm
end,
HandleTerm(Term).
|
c1e66b131c2c6a2e693f1b51e5f3fe9cebb34c55d6c591ee42be0668d599f5e1 | wireless-net/erlang-nommu | wxPaintEvent.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2013 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%% This file is generated DO NOT EDIT
%% @doc See external documentation: <a href="">wxPaintEvent</a>.
%% <dl><dt>Use {@link wxEvtHandler:connect/3.} with EventType:</dt>
%% <dd><em>paint</em></dd></dl>
%% See also the message variant {@link wxEvtHandler:wxPaint(). #wxPaint{}} event record type.
%%
%% <p>This class is derived (and can use functions) from:
%% <br />{@link wxEvent}
%% </p>
%% @type wxPaintEvent(). An object reference, The representation is internal
%% and can be changed without notice. It can't be used for comparsion
%% stored on disc or distributed for use on other nodes.
-module(wxPaintEvent).
-include("wxe.hrl").
-export([]).
%% inherited exports
-export([getId/1,getSkipped/1,getTimestamp/1,isCommandEvent/1,parent_class/1,
resumePropagation/2,shouldPropagate/1,skip/1,skip/2,stopPropagation/1]).
-export_type([wxPaintEvent/0]).
%% @hidden
parent_class(wxEvent) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
-type wxPaintEvent() :: wx:wx_object().
%% From wxEvent
%% @hidden
stopPropagation(This) -> wxEvent:stopPropagation(This).
%% @hidden
skip(This, Options) -> wxEvent:skip(This, Options).
%% @hidden
skip(This) -> wxEvent:skip(This).
%% @hidden
shouldPropagate(This) -> wxEvent:shouldPropagate(This).
%% @hidden
resumePropagation(This,PropagationLevel) -> wxEvent:resumePropagation(This,PropagationLevel).
%% @hidden
isCommandEvent(This) -> wxEvent:isCommandEvent(This).
%% @hidden
getTimestamp(This) -> wxEvent:getTimestamp(This).
%% @hidden
getSkipped(This) -> wxEvent:getSkipped(This).
%% @hidden
getId(This) -> wxEvent:getId(This).
| null | https://raw.githubusercontent.com/wireless-net/erlang-nommu/79f32f81418e022d8ad8e0e447deaea407289926/lib/wx/src/gen/wxPaintEvent.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
This file is generated DO NOT EDIT
@doc See external documentation: <a href="">wxPaintEvent</a>.
<dl><dt>Use {@link wxEvtHandler:connect/3.} with EventType:</dt>
<dd><em>paint</em></dd></dl>
See also the message variant {@link wxEvtHandler:wxPaint(). #wxPaint{}} event record type.
<p>This class is derived (and can use functions) from:
<br />{@link wxEvent}
</p>
@type wxPaintEvent(). An object reference, The representation is internal
and can be changed without notice. It can't be used for comparsion
stored on disc or distributed for use on other nodes.
inherited exports
@hidden
From wxEvent
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden | Copyright Ericsson AB 2008 - 2013 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(wxPaintEvent).
-include("wxe.hrl").
-export([]).
-export([getId/1,getSkipped/1,getTimestamp/1,isCommandEvent/1,parent_class/1,
resumePropagation/2,shouldPropagate/1,skip/1,skip/2,stopPropagation/1]).
-export_type([wxPaintEvent/0]).
parent_class(wxEvent) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
-type wxPaintEvent() :: wx:wx_object().
stopPropagation(This) -> wxEvent:stopPropagation(This).
skip(This, Options) -> wxEvent:skip(This, Options).
skip(This) -> wxEvent:skip(This).
shouldPropagate(This) -> wxEvent:shouldPropagate(This).
resumePropagation(This,PropagationLevel) -> wxEvent:resumePropagation(This,PropagationLevel).
isCommandEvent(This) -> wxEvent:isCommandEvent(This).
getTimestamp(This) -> wxEvent:getTimestamp(This).
getSkipped(This) -> wxEvent:getSkipped(This).
getId(This) -> wxEvent:getId(This).
|
ec68825f7ab95ff901d1d9c157ffb4d7a72fa8a81341eeae04918078db158511 | janestreet/rpc_parallel | rpc_settings.mli | open! Core
open! Async
type t =
{ max_message_size : int option
; handshake_timeout : Time_float.Span.t option
; heartbeat_config : Rpc.Connection.Heartbeat_config.t option
}
[@@deriving bin_io, sexp]
(** [env_var] is the name of the environment variable read by rpc-parallel on start-up
to inject additional rpc-settings for the application. *)
val env_var : string
(** Use all the default rpc settings. This is the record with [None] in every field. *)
val default : t
(** [to_string_for_env_var] generates the expected string format from the arguments
matching the [start_app] function to be used with the [env_var] above. *)
val to_string_for_env_var
: ?max_message_size:int
-> ?handshake_timeout:Time_float.Span.t
-> ?heartbeat_config:Rpc.Connection.Heartbeat_config.t
-> unit
-> string
val create_with_env_override
: max_message_size:int option
-> handshake_timeout:Time_float.Span.t option
-> heartbeat_config:Rpc.Connection.Heartbeat_config.t option
-> t
module For_internal_testing : sig
val create_with_env_override
: env_var:string
-> max_message_size:int option
-> handshake_timeout:Time_float.Span.t option
-> heartbeat_config:Rpc.Connection.Heartbeat_config.t option
-> t
end
| null | https://raw.githubusercontent.com/janestreet/rpc_parallel/968259d389c35aa33cc1c02e089bfc442fb4294d/src/rpc_settings.mli | ocaml | * [env_var] is the name of the environment variable read by rpc-parallel on start-up
to inject additional rpc-settings for the application.
* Use all the default rpc settings. This is the record with [None] in every field.
* [to_string_for_env_var] generates the expected string format from the arguments
matching the [start_app] function to be used with the [env_var] above. | open! Core
open! Async
type t =
{ max_message_size : int option
; handshake_timeout : Time_float.Span.t option
; heartbeat_config : Rpc.Connection.Heartbeat_config.t option
}
[@@deriving bin_io, sexp]
val env_var : string
val default : t
val to_string_for_env_var
: ?max_message_size:int
-> ?handshake_timeout:Time_float.Span.t
-> ?heartbeat_config:Rpc.Connection.Heartbeat_config.t
-> unit
-> string
val create_with_env_override
: max_message_size:int option
-> handshake_timeout:Time_float.Span.t option
-> heartbeat_config:Rpc.Connection.Heartbeat_config.t option
-> t
module For_internal_testing : sig
val create_with_env_override
: env_var:string
-> max_message_size:int option
-> handshake_timeout:Time_float.Span.t option
-> heartbeat_config:Rpc.Connection.Heartbeat_config.t option
-> t
end
|
f2daa61b986928362fae38a862c20aed14220a8f931d0c84a044e3379b96e0b5 | basho/riak_search | solr_search.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved .
%%
%% -------------------------------------------------------------------
-module(solr_search).
-export([
index_dir/1,
index_dir/2
]).
-include("riak_search.hrl").
%% Full text index the specified file or directory, which is expected
%% to contain a solr formatted file.
index_dir(Directory) ->
index_dir(?DEFAULT_INDEX, Directory).
%% Full text index the specified file or directory, which is expected
%% to contain a solr formatted file.
index_dir(Index, Directory) ->
{ok, SolrClient} = riak_search:local_solr_client(),
Fun = fun(Schema, Files) ->
F = fun(File) ->
{ok, Body} = file:read_file(File),
{ok, Command, Docs} = SolrClient:parse_solr_xml(Schema, Body),
SolrClient:run_solr_command(Schema, Command, Docs)
end,
[F(X) || X <- Files]
end,
riak_search_dir_indexer:index(Index, Directory, Fun).
| null | https://raw.githubusercontent.com/basho/riak_search/79c034350f37706a1db42ffca8f6449d4cce99e1/src/solr_search.erl | erlang | -------------------------------------------------------------------
-------------------------------------------------------------------
Full text index the specified file or directory, which is expected
to contain a solr formatted file.
Full text index the specified file or directory, which is expected
to contain a solr formatted file. | Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved .
-module(solr_search).
-export([
index_dir/1,
index_dir/2
]).
-include("riak_search.hrl").
index_dir(Directory) ->
index_dir(?DEFAULT_INDEX, Directory).
index_dir(Index, Directory) ->
{ok, SolrClient} = riak_search:local_solr_client(),
Fun = fun(Schema, Files) ->
F = fun(File) ->
{ok, Body} = file:read_file(File),
{ok, Command, Docs} = SolrClient:parse_solr_xml(Schema, Body),
SolrClient:run_solr_command(Schema, Command, Docs)
end,
[F(X) || X <- Files]
end,
riak_search_dir_indexer:index(Index, Directory, Fun).
|
51d455059e0eab0ac2bec6e6d4623368dbf06a954acd09c5a8c68ffc090f159a | sealchain-project/sealchain | Context.hs | {-# LANGUAGE DeriveAnyClass #-}
# OPTIONS_GHC -fno - warn - orphans #
-- | Context needed for the translation between DSL and Cardano types
module UTxO.Context (
-- * Cardano provided context
CardanoContext(..)
, initCardanoContext
-- * Actors
, Actors(..)
, Rich(..)
, Poor(..)
, Stakeholder(..)
, Avvm(..)
, initActors
-- * Mapping between addresses
, ActorIx(..)
, AddrIx
, Addr(..)
, maxAddrSize
, isAvvmAddr
, isPoorAddr
, AddrInfo(..)
, AddrMap(..)
, initAddrMap
-- * Our custom context
, TransCtxt(..)
, initContext
-- * Derived information
, leaderForSlot
, resolveAddr
, resolveAddress
, transCtxtAddrs
-- ** Block sign info
, BlockSignInfo(..)
, blockSignInfo
, blockSignInfoForSlot
) where
import qualified Data.HashMap.Strict as HM
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as Map
import Formatting (bprint, build, sformat, (%))
import qualified Formatting.Buildable
import Serokell.Util (listJson, mapJson, pairF)
import Serokell.Util.Base16 (base16F)
import Universum
import Pos.Chain.Block (BlockHeader (..), GenesisBlock, HeaderHash,
blockHeaderHash, gbHeader, genesisBlock0)
import Pos.Chain.Delegation (ProxySKHeavy)
import Pos.Chain.Genesis as Genesis (Config (..),
GeneratedSecrets (..), GenesisData (..),
GenesisDelegation (..), PoorSecret (..), RichSecrets (..),
configEpochSlots)
import Pos.Chain.Lrc
import Pos.Chain.Txp
import Pos.Core as Core
import Pos.Core.NetworkMagic (NetworkMagic (..))
import Pos.Crypto
import UTxO.Crypto
------------------------------------------------------------------------------
Summary of the information we get about the genesis block from Cardano core
------------------------------------------------------------------------------
Summary of the information we get about the genesis block from Cardano core
-------------------------------------------------------------------------------}
-- | The information returned by core
data CardanoContext = CardanoContext {
ccStakes :: StakesMap
, ccBlock0 :: GenesisBlock
, ccData :: GenesisData
, ccUtxo :: Utxo
, ccSecrets :: GeneratedSecrets
, ccMagic :: ProtocolMagic
-- | Initial stake distribution
, ccInitLeaders :: SlotLeaders
-- | Initial balances
--
-- Derived from 'ccUtxo'.
, ccBalances :: [(Address, Coin)]
| Hash of block0
--
NOTE : Derived from ' ccBlock0 ' , /not/ the same as ' genesisHash ' .
, ccHash0 :: HeaderHash
-- | Number of slots in an epoch
, ccEpochSlots :: SlotCount
}
initCardanoContext
:: Genesis.Config
-> CardanoContext
initCardanoContext genesisConfig = CardanoContext
{ ccStakes = genesisStakes ccData
, ccBlock0 = ccBlock0
, ccData = ccData
, ccUtxo = ccUtxo
, ccSecrets = fromMaybe (error "initCardanoContext: no secrets") $
configGeneratedSecrets genesisConfig
, ccMagic = ccMagic
, ccInitLeaders = ccLeaders
, ccBalances = map (\(addr, (coin, _)) -> (addr, coin)) $ utxoToAddressCoinPairs ccUtxo
, ccHash0 = blockHeaderHash . BlockHeaderGenesis $ ccBlock0 ^. gbHeader
, ccEpochSlots = configEpochSlots genesisConfig
}
where
ccData = configGenesisData genesisConfig
ccLeaders = genesisLeaders genesisConfig
ccMagic = configProtocolMagic genesisConfig
ccBlock0 = genesisBlock0 ccMagic (configGenesisHash genesisConfig) ccLeaders
ccUtxo = genesisUtxo ccData
------------------------------------------------------------------------------
More explicit representation of the various actors in the genesis block
When heavy - weight delegation is enabled , ' generateGenesisData ' creates three
sets of actors , each with their own set of secret keys :
* The ' poor ' actors , with a small balance ( ' gsPoorSecrets ' )
( these use HD addresses )
* The ' rich ' actors , with a large balance ( ' gsRichSecrets ' )
( these do not use HD addresses )
* The stakeholders ( ' gsDlgIssuersSecrets ' )
( no addresses get generated for these )
* A set of AVVM accounts , with a small balance ( ' gsFakeAvvmSeeds ' )
( Using the Ouroboros - neutral word " actor " intentionally to avoid confusion . )
All addresses ( for the poor and rich actors ) use ' BootstrapEraDistr ' as their
stake distribution attribute ; in ' bootstrapEraDistr ' this is interpreted as
a distribution over the ' gdBootStakeholders ' in the genesis data , which in
turn is derived from ' gsDlgIssuersSecrets ' in ' generateGenesisData ' .
Additionally , ' generateGenesisData ' generates a set of ' ProxySKHeavy ' ( aka
' ProxySecretKey EpochIndex ' ) delegating from the stakeholders ( the
' pskIssuerPk ' ) to the rich actors ( the ' pskDelegatePk ' ) . The following excerpt
from Section 8.2 , Delegation Schema , of the Ouroboros paper is relevant here :
> A stakeholder can transfer the right to generate blocks by creating a proxy
> signing key that allows the delegate to sign messages of the form ( st , d ,
> slj ) ( i.e. , the format of messages signed in Protocol πDPoS to authenticate
> a block ) .
So it 's actually the rich actors that sign blocks on behalf of the
stakeholders .
The genesis UTxO computed by ' genesisUtxo ' , being a Utxo , is simply a set of
unspent transaction outputs ; ' genesisStakes ' then uses ' utxoToStakes ' to turn
this into a ' StakeMap ' . A key component of this transaction is ' txOutStake ' ,
which relies on ' bootstrapEtaDistr ' for addresses marked ' BootstrapEraDistr ' .
Thus the ' ' computed by ' genesisStakes ' will contain ' StakeholderId 's
of the stakeholders , even though ( somewhat confusingly ) the stakeholders are
never actually assigned any addresses .
In order to compute the stake distribution , ` txOutStake ` needs a series of
weights for each of the stakeholders . In the test configuration these
are all set to 1
> 1a1ff7035103d8a9 : 1
> 281e5ae9e357970a : 1
> 44283ce5c44e6e00 : 1
> 5f53e01e1366aeda : 1
Finally , ' genesisLeaders ' uses ' followTheSatoshiUtxo ' applied to the
' genesisUtxo ' to compute the ' SlotLeaders ' ( aka ' NonEmpty StakeholderId ' ) .
Since the stake holders have delegated their signing privilege to the rich
actors , however , it is actually the rich actors that sign the blocks . The
mapping from the ( public keys ) of the stakeholders to the ( public keys ) of the
rich actors is recorded in ' gdHeavyDelegation ' of ' GenesisData ' .
Concretely , the generated genesis data looks something like this :
> TransCtxt {
> cardano : {
> leaders : [ S3 , S4 , S1 , S1 , S3 , S2 , S2 , S1 , S4 , S4 , .. ]
> , stakes : [
> ( S3 , 11249999999999992 coin(s ) )
> , ( S1 , 11250000000000016 coin(s ) )
> , ( S2 , 11249999999999992 coin(s ) )
> , ( S4 , 11249999999999992 coin(s ) )
> ]
> , balances : [
> ( AVVM1 , 100000 coin(s ) )
> , ( AVVM2 , 100000 coin(s ) )
> , ( AVVM3 , 100000 coin(s ) )
> , ( AVVM4 , 100000 coin(s ) )
> , ( AVVM5 , 100000 coin(s ) )
> , ( AVVM6 , 100000 coin(s ) )
> , ( AVVM7 , 100000 coin(s ) )
> , ( AVVM8 , 100000 coin(s ) )
> , ( AVVM9 , 100000 coin(s ) )
> , ( AVVM10 , 100000 coin(s ) )
> , ( P01_1 , 37499999999166 coin(s ) )
> , ( P02_1 , 37499999999166 coin(s ) )
> , ( P03_1 , 37499999999166 coin(s ) )
> , ( P04_1 , 37499999999166 coin(s ) )
> , ( P05_1 , 37499999999166 coin(s ) )
> , ( P06_1 , 37499999999166 coin(s ) )
> , ( P07_1 , 37499999999166 coin(s ) )
> , ( P08_1 , 37499999999166 coin(s ) )
> , ( P09_1 , 37499999999166 coin(s ) )
> , ( , 37499999999166 coin(s ) )
> , ( P11_1 , 37499999999166 coin(s ) )
> , ( P12_1 , 37499999999166 coin(s ) )
> , ( R1 , 11137499999752500 coin(s ) )
> , ( R2 , 11137499999752500 coin(s ) )
> , ( R3 , 11137499999752500 coin(s)P04_1
> , ( R4 , 11137499999752500 coin(s ) )
> ]
> }
> , actors : Actors {
> rich : [
> Rich { .. , addr : R1 }
> ..
> , , addr : R4 }
> ]
> , poor : [
> Poor { .. , , : [ ( .. , P01_1 ) ] }
> ..
> , Poor { .. , , : [ ( .. , P12_1 ) ] }
> ]
> , stake : [
> Stakeholder { key : RegularKeyPair { .. , hash : S1 } , del : DelegatedTo { to : Rich { .. , addr : R1 } , : ProxySk { w = epoch # 0 , .. } } }
> , Stakeholder { key : RegularKeyPair { .. , hash : S2 } , del : DelegatedTo { to : Rich { .. , addr : R3 } , : ProxySk { w = epoch # 0 , .. } } }
> , Stakeholder { key : RegularKeyPair { .. , hash : S3 } , del : DelegatedTo { to : Rich { .. , addr : R4 } , : ProxySk { w = epoch # 0 , .. } } }
> , Stakeholder { key : RegularKeyPair { .. , hash : S4 } , del : DelegatedTo { to : Rich { .. , addr : R2 } , : ProxySk { w = epoch # 0 , .. } } }
> ]
> , avvm : [
> Avvm { .. , addr : AVVM1 }
> ..
> , , addr : AVVM10 }
> ]
> }
> }
where there is a delegation from each of the stakeholders to one of the
rich actors .
NOTE : It is somewhat odd that the stakeholders delegate " back " to the rich
actors . In reality this would n't happen , and instead there would be a fourth
set of actors , with no stake nor any balance , whose sole role is to sign
blocks . This means that if their keys get compromised , the actual stakeholders
can then delegate to a new set and the keys of the stakeholders themselves
never need to be online .
------------------------------------------------------------------------------
More explicit representation of the various actors in the genesis block
When heavy-weight delegation is enabled, 'generateGenesisData' creates three
sets of actors, each with their own set of secret keys:
* The 'poor' actors, with a small balance ('gsPoorSecrets')
(these use HD addresses)
* The 'rich' actors, with a large balance ('gsRichSecrets')
(these do not use HD addresses)
* The stakeholders ('gsDlgIssuersSecrets')
(no addresses get generated for these)
* A set of AVVM accounts, with a small balance ('gsFakeAvvmSeeds')
(Using the Ouroboros-neutral word "actor" intentionally to avoid confusion.)
All addresses (for the poor and rich actors) use 'BootstrapEraDistr' as their
stake distribution attribute; in 'bootstrapEraDistr' this is interpreted as
a distribution over the 'gdBootStakeholders' in the genesis data, which in
turn is derived from 'gsDlgIssuersSecrets' in 'generateGenesisData'.
Additionally, 'generateGenesisData' generates a set of 'ProxySKHeavy' (aka
'ProxySecretKey EpochIndex') delegating from the stakeholders (the
'pskIssuerPk') to the rich actors (the 'pskDelegatePk'). The following excerpt
from Section 8.2, Delegation Schema, of the Ouroboros paper is relevant here:
> A stakeholder can transfer the right to generate blocks by creating a proxy
> signing key that allows the delegate to sign messages of the form (st, d,
> slj) (i.e., the format of messages signed in Protocol πDPoS to authenticate
> a block).
So it's actually the rich actors that sign blocks on behalf of the
stakeholders.
The genesis UTxO computed by 'genesisUtxo', being a Utxo, is simply a set of
unspent transaction outputs; 'genesisStakes' then uses 'utxoToStakes' to turn
this into a 'StakeMap'. A key component of this transaction is 'txOutStake',
which relies on 'bootstrapEtaDistr' for addresses marked 'BootstrapEraDistr'.
Thus the 'StakesMap' computed by 'genesisStakes' will contain 'StakeholderId's
of the stakeholders, even though (somewhat confusingly) the stakeholders are
never actually assigned any addresses.
In order to compute the stake distribution, `txOutStake` needs a series of
weights for each of the stakeholders. In the test configuration these
are all set to 1
> 1a1ff7035103d8a9: 1
> 281e5ae9e357970a: 1
> 44283ce5c44e6e00: 1
> 5f53e01e1366aeda: 1
Finally, 'genesisLeaders' uses 'followTheSatoshiUtxo' applied to the
'genesisUtxo' to compute the 'SlotLeaders' (aka 'NonEmpty StakeholderId').
Since the stake holders have delegated their signing privilege to the rich
actors, however, it is actually the rich actors that sign the blocks. The
mapping from the (public keys) of the stakeholders to the (public keys) of the
rich actors is recorded in 'gdHeavyDelegation' of 'GenesisData'.
Concretely, the generated genesis data looks something like this:
> TransCtxt{
> cardano: CardanoContext{
> leaders: [ S3, S4, S1, S1, S3, S2, S2, S1, S4, S4, .. ]
> , stakes: [
> (S3, 11249999999999992 coin(s))
> , (S1, 11250000000000016 coin(s))
> , (S2, 11249999999999992 coin(s))
> , (S4, 11249999999999992 coin(s))
> ]
> , balances: [
> (AVVM1, 100000 coin(s))
> , (AVVM2, 100000 coin(s))
> , (AVVM3, 100000 coin(s))
> , (AVVM4, 100000 coin(s))
> , (AVVM5, 100000 coin(s))
> , (AVVM6, 100000 coin(s))
> , (AVVM7, 100000 coin(s))
> , (AVVM8, 100000 coin(s))
> , (AVVM9, 100000 coin(s))
> , (AVVM10, 100000 coin(s))
> , (P01_1, 37499999999166 coin(s))
> , (P02_1, 37499999999166 coin(s))
> , (P03_1, 37499999999166 coin(s))
> , (P04_1, 37499999999166 coin(s))
> , (P05_1, 37499999999166 coin(s))
> , (P06_1, 37499999999166 coin(s))
> , (P07_1, 37499999999166 coin(s))
> , (P08_1, 37499999999166 coin(s))
> , (P09_1, 37499999999166 coin(s))
> , (P10_1, 37499999999166 coin(s))
> , (P11_1, 37499999999166 coin(s))
> , (P12_1, 37499999999166 coin(s))
> , (R1, 11137499999752500 coin(s))
> , (R2, 11137499999752500 coin(s))
> , (R3, 11137499999752500 coin(s)P04_1
> , (R4, 11137499999752500 coin(s))
> ]
> }
> , actors: Actors{
> rich: [
> Rich{ .., addr: R1 }
> ..
> , Rich{ .., addr: R4 }
> ]
> , poor: [
> Poor{ ..,, addrs: [ (.., P01_1) ] }
> ..
> , Poor{ ..,, addrs: [ (.., P12_1) ] }
> ]
> , stake: [
> Stakeholder{ key: RegularKeyPair{ .., hash: S1 } , del: DelegatedTo{ to: Rich{ .., addr: R1 }, psk: ProxySk { w = epoch #0, .. } } }
> , Stakeholder{ key: RegularKeyPair{ .., hash: S2 } , del: DelegatedTo{ to: Rich{ .., addr: R3 }, psk: ProxySk { w = epoch #0, .. } } }
> , Stakeholder{ key: RegularKeyPair{ .., hash: S3 } , del: DelegatedTo{ to: Rich{ .., addr: R4 }, psk: ProxySk { w = epoch #0, .. } } }
> , Stakeholder{ key: RegularKeyPair{ .., hash: S4 } , del: DelegatedTo{ to: Rich{ .., addr: R2 }, psk: ProxySk { w = epoch #0, .. } } }
> ]
> , avvm: [
> Avvm{ .., addr: AVVM1 }
> ..
> , Avvm{ .., addr: AVVM10 }
> ]
> }
> }
where there is a delegation from each of the stakeholders to one of the
rich actors.
NOTE: It is somewhat odd that the stakeholders delegate " back " to the rich
actors. In reality this wouldn't happen, and instead there would be a fourth
set of actors, with no stake nor any balance, whose sole role is to sign
blocks. This means that if their keys get compromised, the actual stakeholders
can then delegate to a new set and the keys of the stakeholders themselves
never need to be online.
-------------------------------------------------------------------------------}
-- | Actors in the translation context
data Actors = Actors {
actorsRich :: Map PublicKey Rich
, actorsPoor :: Map PublicKey Poor
, actorsStake :: Map StakeholderId Stakeholder
, actorsAvvm :: Map RedeemPublicKey Avvm
}
deriving (Show)
-- | A rich actor has a key and a "simple" (non-HD) address
data Rich = Rich {
richKey :: RegularKeyPair
, richAddr :: Address
}
deriving (Show)
-- | A poor actor gets a HD wallet, so it has a keypair per address
-- (current generation just creates a single address though)
data Poor = Poor {
poorKey :: EncKeyPair
}
deriving (Show)
data Stakeholder = Stakeholder {
stkKey :: RegularKeyPair
, stkDel :: DelegatedTo Rich
}
deriving (Show)
| AVVM acount
data Avvm = Avvm {
avvmKey :: RedeemKeyPair
, avvmSeed :: ByteString
, avvmAddr :: Address
}
deriving (Show)
------------------------------------------------------------------------------
Deriving ' Actors ' from ' CardanoContext '
TODO : This derivation is more complicated than it ought to be . The mapping
from the secret keys to the corresponding addresses is already present in
generateGenesisData , but it is not returned . I see no choice currently but to
recompute it . This is unfortunate because it means that when
' generateGenesisData ' changes , we 'll be out of sync here . Also , we 're assuming
here that ' tboUseHDAddresses ' is true ( ' useHDAddresses ' must be set to true in
the config yaml file ) .
------------------------------------------------------------------------------
Deriving 'Actors' from 'CardanoContext'
TODO: This derivation is more complicated than it ought to be. The mapping
from the secret keys to the corresponding addresses is already present in
generateGenesisData, but it is not returned. I see no choice currently but to
recompute it. This is unfortunate because it means that when
'generateGenesisData' changes, we'll be out of sync here. Also, we're assuming
here that 'tboUseHDAddresses' is true ('useHDAddresses' must be set to true in
the config yaml file).
-------------------------------------------------------------------------------}
-- | Compute generated actors
initActors :: NetworkMagic -> CardanoContext -> Actors
initActors nm CardanoContext{..} = Actors{..}
where
actorsRich :: Map PublicKey Rich
actorsPoor :: Map PublicKey Poor
actorsStake :: Map StakeholderId Stakeholder
actorsAvvm :: Map RedeemPublicKey Avvm
actorsRich = Map.fromList $ map mkRich $ gsRichSecrets ccSecrets
actorsPoor = Map.fromList $ map mkPoor $ gsPoorSecrets ccSecrets
actorsStake = Map.fromList $ map mkStake $ gsDlgIssuersSecrets ccSecrets
actorsAvvm = Map.fromList $ map mkAvvm $ gsFakeAvvmSeeds ccSecrets
-- Intentially not using record wildcards here so that we fail to compile
-- when the structure of the record changes.
mkRich :: RichSecrets -> (PublicKey, Rich)
mkRich (RichSecrets richSec _vss) =
(regKpPub richKey, Rich {..})
where
richKey :: RegularKeyPair
richKey = regularKeyPair richSec
richAddr :: Address
richAddr = makePubKeyAddressBoot nm (toPublic richSec)
mkPoor :: PoorSecret -> (PublicKey, Poor)
mkPoor (PoorSecret _) = error err
where
err :: Text
err = sformat (
"Unexpected unecrypted secret key "
% "(this is only used in non-HD mode)"
)
mkPoor (PoorEncryptedSecret poorSec) = (encKpPub poorKey, Poor {..})
where
poorKey :: EncKeyPair
poorKey = encKeyPair poorSec
mkStake :: SecretKey -> (StakeholderId, Stakeholder)
mkStake stkSec = (regKpHash stkKey, Stakeholder{..})
where
stkKey :: RegularKeyPair
stkKey = regularKeyPair stkSec
stkDel :: DelegatedTo Rich
stkDel = DelegatedTo{..}
delTo :: Rich
delTo = Map.findWithDefault
(error ("initActors: delegate not found"))
(pskDelegatePk delPSK)
actorsRich
delPSK :: ProxySKHeavy
delPSK = HM.lookupDefault
(error ("initActors: issuer not found"))
(regKpHash stkKey)
(unGenesisDelegation $ gdHeavyDelegation ccData)
mkAvvm :: ByteString -> (RedeemPublicKey, Avvm)
mkAvvm avvmSeed = (redKpPub, Avvm{..})
where
avvmKey :: RedeemKeyPair
avvmKey = RedeemKeyPair{..}
avvmAddr :: Address
avvmAddr = makeRedeemAddress nm redKpPub
Just (redKpPub, redKpSec) = redeemDeterministicKeyGen avvmSeed
{-------------------------------------------------------------------------------
In many cases the difference between rich and poor actors is not important
-------------------------------------------------------------------------------}
-- | Index the actors by number
data ActorIx
= IxRich Int
| IxPoor Int
| IxAvvm Int
^ refers to the special accounts set up at the start of the Cardano
-- blockchain that could then be redeemed from, once, for an initial balance.
-- They can never receive a deposit.
deriving (Show, Eq, Ord)
-- | Address index of a regular actor
--
-- We don't track the difference between the various actors at the type
-- level to make things a bit more uniform.
type AddrIx = Int
-- | Address is given by an actor index and an address index
data Addr = Addr {
addrActorIx :: ActorIx
, addrIx :: AddrIx
}
deriving (Show, Eq, Ord)
| The maximum size in bytes of the serialized Cardano form of these addresses
--
-- This is needed for fee estimation.
maxAddrSize :: Int
maxAddrSize = error "TODO: maxAddrSize: not defined!"
| Returns true if this is the address of an AVVM account
isAvvmAddr :: Addr -> Bool
isAvvmAddr addr =
case addrActorIx addr of
IxAvvm _ -> True
_ -> False
-- | Returns true if this is the address of a poor actor
isPoorAddr :: Addr -> Bool
isPoorAddr addr =
case addrActorIx addr of
IxPoor _ -> True
_ -> False
-- | Information about the translation of a DSL address
data AddrInfo = AddrInfo {
-- | The master key for the actor owning this address (for HD addresses)
addrInfoMasterKey :: Maybe EncKeyPair
-- | The key for this particular address
, addrInfoAddrKey :: SomeKeyPair
-- | The Cardano address
, addrInfoCardano :: Address
}
-- | Mapping between our addresses and Cardano addresses
data AddrMap = AddrMap {
-- | Map from the DSL address to 'AddrInfo'
addrMap :: Map Addr AddrInfo
-- | Reverse map from Cardano addresses to DSL addresses
, addrRevMap :: Map Address Addr
}
-- | Compute initial address mapping
initAddrMap :: NetworkMagic -> Actors -> AddrMap
initAddrMap nm Actors{..} = AddrMap{
addrMap = Map.fromList mkMap
, addrRevMap = Map.fromList $ map (swap . second addrInfoCardano) mkMap
}
where
mkMap :: [(Addr, AddrInfo)]
mkMap = concat [
zipWith mkRich [0..] (Map.elems actorsRich)
, concat $ zipWith mkPoor [0..] (Map.elems actorsPoor)
, zipWith mkAvvm [0..] (Map.elems actorsAvvm)
]
mkRich :: Int -> Rich -> (Addr, AddrInfo)
mkRich actorIx Rich{..} = (
Addr (IxRich actorIx) 0
, AddrInfo {
addrInfoMasterKey = Nothing
, addrInfoAddrKey = KeyPairRegular richKey
, addrInfoCardano = richAddr
}
)
-- | Adds a number of addresses (`numPoorAddrs`) for each Poor actor
mkPoor :: Int -> Poor -> [(Addr, AddrInfo)]
mkPoor actorIx Poor{..} =
[ poorRawAddr addrIxI (deriveHDAddress' poorSec accId0 addrIxW)
| (addrIxI, addrIxW) <- addrIxs
]
where
the first HD account and address
accId0 = accountGenesisIndex
addrIx0 = wAddressGenesisIndex
poorSec = encKpEnc poorKey
10 addresses for each Poor actor
addrIxs = map (\i -> (i, addrIx0 + (fromIntegral i)) )
[0 .. numPoorAddrs - 1]
^ AddrIx
-> (EncKeyPair, Address)
-> (Addr, AddrInfo)
poorRawAddr addrIx' (ekp, addr) = (
Addr (IxPoor actorIx) addrIx'
, AddrInfo {
addrInfoMasterKey = Just poorKey
, addrInfoAddrKey = KeyPairEncrypted ekp
, addrInfoCardano = addr
}
)
deriveHDAddress' :: EncryptedSecretKey
-> Word32 -- ^ account index
-> Word32 -- ^ address index
-> (EncKeyPair, Address)
deriveHDAddress' esk accIx' addrIx'
= case deriveLvl2KeyPair nm bootstrapEra scp emptyPassphrase esk accIx' addrIx' of
Nothing -> error "impossible"
Just (addr, key) -> (encKeyPair key, addr)
where
bootstrapEra = IsBootstrapEraAddr True
scp = ShouldCheckPassphrase False
mkAvvm :: Int -> Avvm -> (Addr, AddrInfo)
mkAvvm actorIx Avvm{..} = (
Addr (IxAvvm actorIx) 0
, AddrInfo {
addrInfoMasterKey = Nothing
, addrInfoAddrKey = KeyPairRedeem avvmKey
, addrInfoCardano = avvmAddr
}
)
{-------------------------------------------------------------------------------
Translation context
The environment we need to be able to do the translation between the DSL
and Cardano types. Accumulation of the environments above.
-------------------------------------------------------------------------------}
data TransCtxt = TransCtxt {
tcCardano :: CardanoContext
, tcActors :: Actors
, tcAddrMap :: AddrMap
}
initContext :: NetworkMagic -> CardanoContext -> TransCtxt
initContext nm tcCardano = TransCtxt{..}
where
tcActors = initActors nm tcCardano
tcAddrMap = initAddrMap nm tcActors
-- | All actor addresses present in the translation context
transCtxtAddrs :: TransCtxt -> [Addr]
transCtxtAddrs transCtxt = filter (not . avvm) addrs
where
addrs = Map.keys $ addrMap (tcAddrMap transCtxt)
avvm (Addr (IxAvvm _) _) = True
avvm _ = False
{-------------------------------------------------------------------------------
Derived information
-------------------------------------------------------------------------------}
resolveAddr :: Addr -> TransCtxt -> AddrInfo
resolveAddr addr TransCtxt{..} =
fromMaybe
(error $ sformat ("resolveAddr: " % build % " not found") addr)
(Map.lookup addr addrMap)
where
AddrMap{..} = tcAddrMap
resolveAddress :: Address -> TransCtxt -> Addr
resolveAddress addr TransCtxt{..} =
fromMaybe
(error $ sformat ("resolveAddress: " % build % " not found") addr)
(Map.lookup addr addrRevMap)
where
AddrMap{..} = tcAddrMap
leaderForSlot :: SlotLeaders -> SlotId -> TransCtxt -> Stakeholder
leaderForSlot leaders slotId TransCtxt{..} = actorsStake Map.! leader
where
Actors{..} = tcActors
CardanoContext{..} = tcCardano
leader :: StakeholderId
leader = leaders NE.!! slotIx
slotIx :: Int
slotIx = fromIntegral $ getSlotIndex (siSlot slotId)
------------------------------------------------------------------------------
Derive block sign info from a ' Stakeholder '
------------------------------------------------------------------------------
Derive block sign info from a 'Stakeholder'
-------------------------------------------------------------------------------}
-- | Information needed to sign a block
data BlockSignInfo = BlockSignInfo {
bsiLeader :: PublicKey -- ^ Real slot leader
, bsiKey :: SecretKey -- ^ Secret key of the actor signing it
, bsiPSK :: ProxySKHeavy -- ^ Prove that the actor may sign the block
}
-- | 'BlockSignInfo' can be derived from the slot's 'Stakeholder'
blockSignInfo :: Stakeholder -> BlockSignInfo
blockSignInfo Stakeholder{..} = BlockSignInfo{..}
where
DelegatedTo{..} = stkDel
Rich{..} = delTo
bsiLeader = regKpPub stkKey
bsiKey = regKpSec richKey
bsiPSK = delPSK
blockSignInfoForSlot :: SlotLeaders -> SlotId -> TransCtxt -> BlockSignInfo
blockSignInfoForSlot leaders slotId =
blockSignInfo
. leaderForSlot leaders slotId
{-------------------------------------------------------------------------------
Pretty-printing
-------------------------------------------------------------------------------}
instance Buildable Rich where
build Rich{..} = bprint
( "Rich"
% "{ key: " % build
% ", addr: " % build
% "}"
)
richKey
richAddr
instance Buildable Poor where
build Poor{..} = bprint
( "Poor"
% "{ key: " % build
% "}"
)
poorKey
instance Buildable Stakeholder where
build Stakeholder{..} = bprint
( "Stakeholder"
% "{ key: " % build
% ", del: " % build
% "}"
)
stkKey
stkDel
instance Buildable Avvm where
build Avvm{..} = bprint
( "Avvm"
% "{ key: " % build
% ", seed: " % base16F
% ", addr: " % build
% "}"
)
avvmKey
avvmSeed
avvmAddr
instance Buildable Actors where
build Actors{..} = bprint
( "Actors"
% "{ rich: " % listJson
% ", poor: " % listJson
% ", stake: " % listJson
% ", avvm: " % listJson
% "}"
)
(Map.elems actorsRich)
(Map.elems actorsPoor)
(Map.elems actorsStake)
(Map.elems actorsAvvm)
instance Buildable ActorIx where
build (IxRich ix) = bprint ("IxRich " % build) ix
build (IxPoor ix) = bprint ("IxPoor " % build) ix
build (IxAvvm ix) = bprint ("IxAvvm " % build) ix
instance Buildable Addr where
build Addr{..} = bprint
( "Addr"
% "{ actorIx: " % build
% ", addrIx: " % build
% "}"
)
addrActorIx
addrIx
-- | We don't show the whole thing, this is for debugging primarily
instance Buildable CardanoContext where
build CardanoContext{..} = bprint
( "CardanoContext"
% "{ initLeaders: " % listJson
% ", stakes: " % listJson
% ", balances: " % listJson
% ", utxo: " % mapJson
% ", data: " % build
% "}"
)
ccInitLeaders
(map (bprint pairF) (HM.toList ccStakes))
(map (bprint pairF) ccBalances)
ccUtxo
ccData
instance Buildable AddrMap where
build AddrMap{..} = bprint
( "AddrMap"
% "{ revMap: " % mapJson
% "}"
)
addrRevMap
instance Buildable TransCtxt where
build TransCtxt{..} = bprint
( "TransCtxt"
% "{ cardano: " % build
% ", actors: " % build
% ", addrMap: " % build
% "}"
)
tcCardano
tcActors
tcAddrMap
instance Buildable GenesisData where
build GenesisData{..} = bprint
( "GenesisData"
% "{ bootStakeholders: " % build
% "}"
)
gdBootStakeholders
| null | https://raw.githubusercontent.com/sealchain-project/sealchain/e97b4bac865fb147979cb14723a12c716a62e51e/utxo/src/UTxO/Context.hs | haskell | # LANGUAGE DeriveAnyClass #
| Context needed for the translation between DSL and Cardano types
* Cardano provided context
* Actors
* Mapping between addresses
* Our custom context
* Derived information
** Block sign info
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
| The information returned by core
| Initial stake distribution
| Initial balances
Derived from 'ccUtxo'.
| Number of slots in an epoch
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
| Actors in the translation context
| A rich actor has a key and a "simple" (non-HD) address
| A poor actor gets a HD wallet, so it has a keypair per address
(current generation just creates a single address though)
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
| Compute generated actors
Intentially not using record wildcards here so that we fail to compile
when the structure of the record changes.
------------------------------------------------------------------------------
In many cases the difference between rich and poor actors is not important
------------------------------------------------------------------------------
| Index the actors by number
blockchain that could then be redeemed from, once, for an initial balance.
They can never receive a deposit.
| Address index of a regular actor
We don't track the difference between the various actors at the type
level to make things a bit more uniform.
| Address is given by an actor index and an address index
This is needed for fee estimation.
| Returns true if this is the address of a poor actor
| Information about the translation of a DSL address
| The master key for the actor owning this address (for HD addresses)
| The key for this particular address
| The Cardano address
| Mapping between our addresses and Cardano addresses
| Map from the DSL address to 'AddrInfo'
| Reverse map from Cardano addresses to DSL addresses
| Compute initial address mapping
| Adds a number of addresses (`numPoorAddrs`) for each Poor actor
^ account index
^ address index
------------------------------------------------------------------------------
Translation context
The environment we need to be able to do the translation between the DSL
and Cardano types. Accumulation of the environments above.
------------------------------------------------------------------------------
| All actor addresses present in the translation context
------------------------------------------------------------------------------
Derived information
------------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
| Information needed to sign a block
^ Real slot leader
^ Secret key of the actor signing it
^ Prove that the actor may sign the block
| 'BlockSignInfo' can be derived from the slot's 'Stakeholder'
------------------------------------------------------------------------------
Pretty-printing
------------------------------------------------------------------------------
| We don't show the whole thing, this is for debugging primarily |
# OPTIONS_GHC -fno - warn - orphans #
module UTxO.Context (
CardanoContext(..)
, initCardanoContext
, Actors(..)
, Rich(..)
, Poor(..)
, Stakeholder(..)
, Avvm(..)
, initActors
, ActorIx(..)
, AddrIx
, Addr(..)
, maxAddrSize
, isAvvmAddr
, isPoorAddr
, AddrInfo(..)
, AddrMap(..)
, initAddrMap
, TransCtxt(..)
, initContext
, leaderForSlot
, resolveAddr
, resolveAddress
, transCtxtAddrs
, BlockSignInfo(..)
, blockSignInfo
, blockSignInfoForSlot
) where
import qualified Data.HashMap.Strict as HM
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as Map
import Formatting (bprint, build, sformat, (%))
import qualified Formatting.Buildable
import Serokell.Util (listJson, mapJson, pairF)
import Serokell.Util.Base16 (base16F)
import Universum
import Pos.Chain.Block (BlockHeader (..), GenesisBlock, HeaderHash,
blockHeaderHash, gbHeader, genesisBlock0)
import Pos.Chain.Delegation (ProxySKHeavy)
import Pos.Chain.Genesis as Genesis (Config (..),
GeneratedSecrets (..), GenesisData (..),
GenesisDelegation (..), PoorSecret (..), RichSecrets (..),
configEpochSlots)
import Pos.Chain.Lrc
import Pos.Chain.Txp
import Pos.Core as Core
import Pos.Core.NetworkMagic (NetworkMagic (..))
import Pos.Crypto
import UTxO.Crypto
Summary of the information we get about the genesis block from Cardano core
Summary of the information we get about the genesis block from Cardano core
data CardanoContext = CardanoContext {
ccStakes :: StakesMap
, ccBlock0 :: GenesisBlock
, ccData :: GenesisData
, ccUtxo :: Utxo
, ccSecrets :: GeneratedSecrets
, ccMagic :: ProtocolMagic
, ccInitLeaders :: SlotLeaders
, ccBalances :: [(Address, Coin)]
| Hash of block0
NOTE : Derived from ' ccBlock0 ' , /not/ the same as ' genesisHash ' .
, ccHash0 :: HeaderHash
, ccEpochSlots :: SlotCount
}
initCardanoContext
:: Genesis.Config
-> CardanoContext
initCardanoContext genesisConfig = CardanoContext
{ ccStakes = genesisStakes ccData
, ccBlock0 = ccBlock0
, ccData = ccData
, ccUtxo = ccUtxo
, ccSecrets = fromMaybe (error "initCardanoContext: no secrets") $
configGeneratedSecrets genesisConfig
, ccMagic = ccMagic
, ccInitLeaders = ccLeaders
, ccBalances = map (\(addr, (coin, _)) -> (addr, coin)) $ utxoToAddressCoinPairs ccUtxo
, ccHash0 = blockHeaderHash . BlockHeaderGenesis $ ccBlock0 ^. gbHeader
, ccEpochSlots = configEpochSlots genesisConfig
}
where
ccData = configGenesisData genesisConfig
ccLeaders = genesisLeaders genesisConfig
ccMagic = configProtocolMagic genesisConfig
ccBlock0 = genesisBlock0 ccMagic (configGenesisHash genesisConfig) ccLeaders
ccUtxo = genesisUtxo ccData
More explicit representation of the various actors in the genesis block
When heavy - weight delegation is enabled , ' generateGenesisData ' creates three
sets of actors , each with their own set of secret keys :
* The ' poor ' actors , with a small balance ( ' gsPoorSecrets ' )
( these use HD addresses )
* The ' rich ' actors , with a large balance ( ' gsRichSecrets ' )
( these do not use HD addresses )
* The stakeholders ( ' gsDlgIssuersSecrets ' )
( no addresses get generated for these )
* A set of AVVM accounts , with a small balance ( ' gsFakeAvvmSeeds ' )
( Using the Ouroboros - neutral word " actor " intentionally to avoid confusion . )
All addresses ( for the poor and rich actors ) use ' BootstrapEraDistr ' as their
stake distribution attribute ; in ' bootstrapEraDistr ' this is interpreted as
a distribution over the ' gdBootStakeholders ' in the genesis data , which in
turn is derived from ' gsDlgIssuersSecrets ' in ' generateGenesisData ' .
Additionally , ' generateGenesisData ' generates a set of ' ProxySKHeavy ' ( aka
' ProxySecretKey EpochIndex ' ) delegating from the stakeholders ( the
' pskIssuerPk ' ) to the rich actors ( the ' pskDelegatePk ' ) . The following excerpt
from Section 8.2 , Delegation Schema , of the Ouroboros paper is relevant here :
> A stakeholder can transfer the right to generate blocks by creating a proxy
> signing key that allows the delegate to sign messages of the form ( st , d ,
> slj ) ( i.e. , the format of messages signed in Protocol πDPoS to authenticate
> a block ) .
So it 's actually the rich actors that sign blocks on behalf of the
stakeholders .
The genesis UTxO computed by ' genesisUtxo ' , being a Utxo , is simply a set of
unspent transaction outputs ; ' genesisStakes ' then uses ' utxoToStakes ' to turn
this into a ' StakeMap ' . A key component of this transaction is ' txOutStake ' ,
which relies on ' bootstrapEtaDistr ' for addresses marked ' BootstrapEraDistr ' .
Thus the ' ' computed by ' genesisStakes ' will contain ' StakeholderId 's
of the stakeholders , even though ( somewhat confusingly ) the stakeholders are
never actually assigned any addresses .
In order to compute the stake distribution , ` txOutStake ` needs a series of
weights for each of the stakeholders . In the test configuration these
are all set to 1
> 1a1ff7035103d8a9 : 1
> 281e5ae9e357970a : 1
> 44283ce5c44e6e00 : 1
> 5f53e01e1366aeda : 1
Finally , ' genesisLeaders ' uses ' followTheSatoshiUtxo ' applied to the
' genesisUtxo ' to compute the ' SlotLeaders ' ( aka ' NonEmpty StakeholderId ' ) .
Since the stake holders have delegated their signing privilege to the rich
actors , however , it is actually the rich actors that sign the blocks . The
mapping from the ( public keys ) of the stakeholders to the ( public keys ) of the
rich actors is recorded in ' gdHeavyDelegation ' of ' GenesisData ' .
Concretely , the generated genesis data looks something like this :
> TransCtxt {
> cardano : {
> leaders : [ S3 , S4 , S1 , S1 , S3 , S2 , S2 , S1 , S4 , S4 , .. ]
> , stakes : [
> ( S3 , 11249999999999992 coin(s ) )
> , ( S1 , 11250000000000016 coin(s ) )
> , ( S2 , 11249999999999992 coin(s ) )
> , ( S4 , 11249999999999992 coin(s ) )
> ]
> , balances : [
> ( AVVM1 , 100000 coin(s ) )
> , ( AVVM2 , 100000 coin(s ) )
> , ( AVVM3 , 100000 coin(s ) )
> , ( AVVM4 , 100000 coin(s ) )
> , ( AVVM5 , 100000 coin(s ) )
> , ( AVVM6 , 100000 coin(s ) )
> , ( AVVM7 , 100000 coin(s ) )
> , ( AVVM8 , 100000 coin(s ) )
> , ( AVVM9 , 100000 coin(s ) )
> , ( AVVM10 , 100000 coin(s ) )
> , ( P01_1 , 37499999999166 coin(s ) )
> , ( P02_1 , 37499999999166 coin(s ) )
> , ( P03_1 , 37499999999166 coin(s ) )
> , ( P04_1 , 37499999999166 coin(s ) )
> , ( P05_1 , 37499999999166 coin(s ) )
> , ( P06_1 , 37499999999166 coin(s ) )
> , ( P07_1 , 37499999999166 coin(s ) )
> , ( P08_1 , 37499999999166 coin(s ) )
> , ( P09_1 , 37499999999166 coin(s ) )
> , ( , 37499999999166 coin(s ) )
> , ( P11_1 , 37499999999166 coin(s ) )
> , ( P12_1 , 37499999999166 coin(s ) )
> , ( R1 , 11137499999752500 coin(s ) )
> , ( R2 , 11137499999752500 coin(s ) )
> , ( R3 , 11137499999752500 coin(s)P04_1
> , ( R4 , 11137499999752500 coin(s ) )
> ]
> }
> , actors : Actors {
> rich : [
> Rich { .. , addr : R1 }
> ..
> , , addr : R4 }
> ]
> , poor : [
> Poor { .. , , : [ ( .. , P01_1 ) ] }
> ..
> , Poor { .. , , : [ ( .. , P12_1 ) ] }
> ]
> , stake : [
> Stakeholder { key : RegularKeyPair { .. , hash : S1 } , del : DelegatedTo { to : Rich { .. , addr : R1 } , : ProxySk { w = epoch # 0 , .. } } }
> , Stakeholder { key : RegularKeyPair { .. , hash : S2 } , del : DelegatedTo { to : Rich { .. , addr : R3 } , : ProxySk { w = epoch # 0 , .. } } }
> , Stakeholder { key : RegularKeyPair { .. , hash : S3 } , del : DelegatedTo { to : Rich { .. , addr : R4 } , : ProxySk { w = epoch # 0 , .. } } }
> , Stakeholder { key : RegularKeyPair { .. , hash : S4 } , del : DelegatedTo { to : Rich { .. , addr : R2 } , : ProxySk { w = epoch # 0 , .. } } }
> ]
> , avvm : [
> Avvm { .. , addr : AVVM1 }
> ..
> , , addr : AVVM10 }
> ]
> }
> }
where there is a delegation from each of the stakeholders to one of the
rich actors .
NOTE : It is somewhat odd that the stakeholders delegate " back " to the rich
actors . In reality this would n't happen , and instead there would be a fourth
set of actors , with no stake nor any balance , whose sole role is to sign
blocks . This means that if their keys get compromised , the actual stakeholders
can then delegate to a new set and the keys of the stakeholders themselves
never need to be online .
More explicit representation of the various actors in the genesis block
When heavy-weight delegation is enabled, 'generateGenesisData' creates three
sets of actors, each with their own set of secret keys:
* The 'poor' actors, with a small balance ('gsPoorSecrets')
(these use HD addresses)
* The 'rich' actors, with a large balance ('gsRichSecrets')
(these do not use HD addresses)
* The stakeholders ('gsDlgIssuersSecrets')
(no addresses get generated for these)
* A set of AVVM accounts, with a small balance ('gsFakeAvvmSeeds')
(Using the Ouroboros-neutral word "actor" intentionally to avoid confusion.)
All addresses (for the poor and rich actors) use 'BootstrapEraDistr' as their
stake distribution attribute; in 'bootstrapEraDistr' this is interpreted as
a distribution over the 'gdBootStakeholders' in the genesis data, which in
turn is derived from 'gsDlgIssuersSecrets' in 'generateGenesisData'.
Additionally, 'generateGenesisData' generates a set of 'ProxySKHeavy' (aka
'ProxySecretKey EpochIndex') delegating from the stakeholders (the
'pskIssuerPk') to the rich actors (the 'pskDelegatePk'). The following excerpt
from Section 8.2, Delegation Schema, of the Ouroboros paper is relevant here:
> A stakeholder can transfer the right to generate blocks by creating a proxy
> signing key that allows the delegate to sign messages of the form (st, d,
> slj) (i.e., the format of messages signed in Protocol πDPoS to authenticate
> a block).
So it's actually the rich actors that sign blocks on behalf of the
stakeholders.
The genesis UTxO computed by 'genesisUtxo', being a Utxo, is simply a set of
unspent transaction outputs; 'genesisStakes' then uses 'utxoToStakes' to turn
this into a 'StakeMap'. A key component of this transaction is 'txOutStake',
which relies on 'bootstrapEtaDistr' for addresses marked 'BootstrapEraDistr'.
Thus the 'StakesMap' computed by 'genesisStakes' will contain 'StakeholderId's
of the stakeholders, even though (somewhat confusingly) the stakeholders are
never actually assigned any addresses.
In order to compute the stake distribution, `txOutStake` needs a series of
weights for each of the stakeholders. In the test configuration these
are all set to 1
> 1a1ff7035103d8a9: 1
> 281e5ae9e357970a: 1
> 44283ce5c44e6e00: 1
> 5f53e01e1366aeda: 1
Finally, 'genesisLeaders' uses 'followTheSatoshiUtxo' applied to the
'genesisUtxo' to compute the 'SlotLeaders' (aka 'NonEmpty StakeholderId').
Since the stake holders have delegated their signing privilege to the rich
actors, however, it is actually the rich actors that sign the blocks. The
mapping from the (public keys) of the stakeholders to the (public keys) of the
rich actors is recorded in 'gdHeavyDelegation' of 'GenesisData'.
Concretely, the generated genesis data looks something like this:
> TransCtxt{
> cardano: CardanoContext{
> leaders: [ S3, S4, S1, S1, S3, S2, S2, S1, S4, S4, .. ]
> , stakes: [
> (S3, 11249999999999992 coin(s))
> , (S1, 11250000000000016 coin(s))
> , (S2, 11249999999999992 coin(s))
> , (S4, 11249999999999992 coin(s))
> ]
> , balances: [
> (AVVM1, 100000 coin(s))
> , (AVVM2, 100000 coin(s))
> , (AVVM3, 100000 coin(s))
> , (AVVM4, 100000 coin(s))
> , (AVVM5, 100000 coin(s))
> , (AVVM6, 100000 coin(s))
> , (AVVM7, 100000 coin(s))
> , (AVVM8, 100000 coin(s))
> , (AVVM9, 100000 coin(s))
> , (AVVM10, 100000 coin(s))
> , (P01_1, 37499999999166 coin(s))
> , (P02_1, 37499999999166 coin(s))
> , (P03_1, 37499999999166 coin(s))
> , (P04_1, 37499999999166 coin(s))
> , (P05_1, 37499999999166 coin(s))
> , (P06_1, 37499999999166 coin(s))
> , (P07_1, 37499999999166 coin(s))
> , (P08_1, 37499999999166 coin(s))
> , (P09_1, 37499999999166 coin(s))
> , (P10_1, 37499999999166 coin(s))
> , (P11_1, 37499999999166 coin(s))
> , (P12_1, 37499999999166 coin(s))
> , (R1, 11137499999752500 coin(s))
> , (R2, 11137499999752500 coin(s))
> , (R3, 11137499999752500 coin(s)P04_1
> , (R4, 11137499999752500 coin(s))
> ]
> }
> , actors: Actors{
> rich: [
> Rich{ .., addr: R1 }
> ..
> , Rich{ .., addr: R4 }
> ]
> , poor: [
> Poor{ ..,, addrs: [ (.., P01_1) ] }
> ..
> , Poor{ ..,, addrs: [ (.., P12_1) ] }
> ]
> , stake: [
> Stakeholder{ key: RegularKeyPair{ .., hash: S1 } , del: DelegatedTo{ to: Rich{ .., addr: R1 }, psk: ProxySk { w = epoch #0, .. } } }
> , Stakeholder{ key: RegularKeyPair{ .., hash: S2 } , del: DelegatedTo{ to: Rich{ .., addr: R3 }, psk: ProxySk { w = epoch #0, .. } } }
> , Stakeholder{ key: RegularKeyPair{ .., hash: S3 } , del: DelegatedTo{ to: Rich{ .., addr: R4 }, psk: ProxySk { w = epoch #0, .. } } }
> , Stakeholder{ key: RegularKeyPair{ .., hash: S4 } , del: DelegatedTo{ to: Rich{ .., addr: R2 }, psk: ProxySk { w = epoch #0, .. } } }
> ]
> , avvm: [
> Avvm{ .., addr: AVVM1 }
> ..
> , Avvm{ .., addr: AVVM10 }
> ]
> }
> }
where there is a delegation from each of the stakeholders to one of the
rich actors.
NOTE: It is somewhat odd that the stakeholders delegate " back " to the rich
actors. In reality this wouldn't happen, and instead there would be a fourth
set of actors, with no stake nor any balance, whose sole role is to sign
blocks. This means that if their keys get compromised, the actual stakeholders
can then delegate to a new set and the keys of the stakeholders themselves
never need to be online.
data Actors = Actors {
actorsRich :: Map PublicKey Rich
, actorsPoor :: Map PublicKey Poor
, actorsStake :: Map StakeholderId Stakeholder
, actorsAvvm :: Map RedeemPublicKey Avvm
}
deriving (Show)
data Rich = Rich {
richKey :: RegularKeyPair
, richAddr :: Address
}
deriving (Show)
data Poor = Poor {
poorKey :: EncKeyPair
}
deriving (Show)
data Stakeholder = Stakeholder {
stkKey :: RegularKeyPair
, stkDel :: DelegatedTo Rich
}
deriving (Show)
| AVVM acount
data Avvm = Avvm {
avvmKey :: RedeemKeyPair
, avvmSeed :: ByteString
, avvmAddr :: Address
}
deriving (Show)
Deriving ' Actors ' from ' CardanoContext '
TODO : This derivation is more complicated than it ought to be . The mapping
from the secret keys to the corresponding addresses is already present in
generateGenesisData , but it is not returned . I see no choice currently but to
recompute it . This is unfortunate because it means that when
' generateGenesisData ' changes , we 'll be out of sync here . Also , we 're assuming
here that ' tboUseHDAddresses ' is true ( ' useHDAddresses ' must be set to true in
the config yaml file ) .
Deriving 'Actors' from 'CardanoContext'
TODO: This derivation is more complicated than it ought to be. The mapping
from the secret keys to the corresponding addresses is already present in
generateGenesisData, but it is not returned. I see no choice currently but to
recompute it. This is unfortunate because it means that when
'generateGenesisData' changes, we'll be out of sync here. Also, we're assuming
here that 'tboUseHDAddresses' is true ('useHDAddresses' must be set to true in
the config yaml file).
initActors :: NetworkMagic -> CardanoContext -> Actors
initActors nm CardanoContext{..} = Actors{..}
where
actorsRich :: Map PublicKey Rich
actorsPoor :: Map PublicKey Poor
actorsStake :: Map StakeholderId Stakeholder
actorsAvvm :: Map RedeemPublicKey Avvm
actorsRich = Map.fromList $ map mkRich $ gsRichSecrets ccSecrets
actorsPoor = Map.fromList $ map mkPoor $ gsPoorSecrets ccSecrets
actorsStake = Map.fromList $ map mkStake $ gsDlgIssuersSecrets ccSecrets
actorsAvvm = Map.fromList $ map mkAvvm $ gsFakeAvvmSeeds ccSecrets
mkRich :: RichSecrets -> (PublicKey, Rich)
mkRich (RichSecrets richSec _vss) =
(regKpPub richKey, Rich {..})
where
richKey :: RegularKeyPair
richKey = regularKeyPair richSec
richAddr :: Address
richAddr = makePubKeyAddressBoot nm (toPublic richSec)
mkPoor :: PoorSecret -> (PublicKey, Poor)
mkPoor (PoorSecret _) = error err
where
err :: Text
err = sformat (
"Unexpected unecrypted secret key "
% "(this is only used in non-HD mode)"
)
mkPoor (PoorEncryptedSecret poorSec) = (encKpPub poorKey, Poor {..})
where
poorKey :: EncKeyPair
poorKey = encKeyPair poorSec
mkStake :: SecretKey -> (StakeholderId, Stakeholder)
mkStake stkSec = (regKpHash stkKey, Stakeholder{..})
where
stkKey :: RegularKeyPair
stkKey = regularKeyPair stkSec
stkDel :: DelegatedTo Rich
stkDel = DelegatedTo{..}
delTo :: Rich
delTo = Map.findWithDefault
(error ("initActors: delegate not found"))
(pskDelegatePk delPSK)
actorsRich
delPSK :: ProxySKHeavy
delPSK = HM.lookupDefault
(error ("initActors: issuer not found"))
(regKpHash stkKey)
(unGenesisDelegation $ gdHeavyDelegation ccData)
mkAvvm :: ByteString -> (RedeemPublicKey, Avvm)
mkAvvm avvmSeed = (redKpPub, Avvm{..})
where
avvmKey :: RedeemKeyPair
avvmKey = RedeemKeyPair{..}
avvmAddr :: Address
avvmAddr = makeRedeemAddress nm redKpPub
Just (redKpPub, redKpSec) = redeemDeterministicKeyGen avvmSeed
data ActorIx
= IxRich Int
| IxPoor Int
| IxAvvm Int
^ refers to the special accounts set up at the start of the Cardano
deriving (Show, Eq, Ord)
type AddrIx = Int
data Addr = Addr {
addrActorIx :: ActorIx
, addrIx :: AddrIx
}
deriving (Show, Eq, Ord)
| The maximum size in bytes of the serialized Cardano form of these addresses
maxAddrSize :: Int
maxAddrSize = error "TODO: maxAddrSize: not defined!"
| Returns true if this is the address of an AVVM account
isAvvmAddr :: Addr -> Bool
isAvvmAddr addr =
case addrActorIx addr of
IxAvvm _ -> True
_ -> False
isPoorAddr :: Addr -> Bool
isPoorAddr addr =
case addrActorIx addr of
IxPoor _ -> True
_ -> False
data AddrInfo = AddrInfo {
addrInfoMasterKey :: Maybe EncKeyPair
, addrInfoAddrKey :: SomeKeyPair
, addrInfoCardano :: Address
}
data AddrMap = AddrMap {
addrMap :: Map Addr AddrInfo
, addrRevMap :: Map Address Addr
}
initAddrMap :: NetworkMagic -> Actors -> AddrMap
initAddrMap nm Actors{..} = AddrMap{
addrMap = Map.fromList mkMap
, addrRevMap = Map.fromList $ map (swap . second addrInfoCardano) mkMap
}
where
mkMap :: [(Addr, AddrInfo)]
mkMap = concat [
zipWith mkRich [0..] (Map.elems actorsRich)
, concat $ zipWith mkPoor [0..] (Map.elems actorsPoor)
, zipWith mkAvvm [0..] (Map.elems actorsAvvm)
]
mkRich :: Int -> Rich -> (Addr, AddrInfo)
mkRich actorIx Rich{..} = (
Addr (IxRich actorIx) 0
, AddrInfo {
addrInfoMasterKey = Nothing
, addrInfoAddrKey = KeyPairRegular richKey
, addrInfoCardano = richAddr
}
)
mkPoor :: Int -> Poor -> [(Addr, AddrInfo)]
mkPoor actorIx Poor{..} =
[ poorRawAddr addrIxI (deriveHDAddress' poorSec accId0 addrIxW)
| (addrIxI, addrIxW) <- addrIxs
]
where
the first HD account and address
accId0 = accountGenesisIndex
addrIx0 = wAddressGenesisIndex
poorSec = encKpEnc poorKey
10 addresses for each Poor actor
addrIxs = map (\i -> (i, addrIx0 + (fromIntegral i)) )
[0 .. numPoorAddrs - 1]
^ AddrIx
-> (EncKeyPair, Address)
-> (Addr, AddrInfo)
poorRawAddr addrIx' (ekp, addr) = (
Addr (IxPoor actorIx) addrIx'
, AddrInfo {
addrInfoMasterKey = Just poorKey
, addrInfoAddrKey = KeyPairEncrypted ekp
, addrInfoCardano = addr
}
)
deriveHDAddress' :: EncryptedSecretKey
-> (EncKeyPair, Address)
deriveHDAddress' esk accIx' addrIx'
= case deriveLvl2KeyPair nm bootstrapEra scp emptyPassphrase esk accIx' addrIx' of
Nothing -> error "impossible"
Just (addr, key) -> (encKeyPair key, addr)
where
bootstrapEra = IsBootstrapEraAddr True
scp = ShouldCheckPassphrase False
mkAvvm :: Int -> Avvm -> (Addr, AddrInfo)
mkAvvm actorIx Avvm{..} = (
Addr (IxAvvm actorIx) 0
, AddrInfo {
addrInfoMasterKey = Nothing
, addrInfoAddrKey = KeyPairRedeem avvmKey
, addrInfoCardano = avvmAddr
}
)
data TransCtxt = TransCtxt {
tcCardano :: CardanoContext
, tcActors :: Actors
, tcAddrMap :: AddrMap
}
initContext :: NetworkMagic -> CardanoContext -> TransCtxt
initContext nm tcCardano = TransCtxt{..}
where
tcActors = initActors nm tcCardano
tcAddrMap = initAddrMap nm tcActors
transCtxtAddrs :: TransCtxt -> [Addr]
transCtxtAddrs transCtxt = filter (not . avvm) addrs
where
addrs = Map.keys $ addrMap (tcAddrMap transCtxt)
avvm (Addr (IxAvvm _) _) = True
avvm _ = False
resolveAddr :: Addr -> TransCtxt -> AddrInfo
resolveAddr addr TransCtxt{..} =
fromMaybe
(error $ sformat ("resolveAddr: " % build % " not found") addr)
(Map.lookup addr addrMap)
where
AddrMap{..} = tcAddrMap
resolveAddress :: Address -> TransCtxt -> Addr
resolveAddress addr TransCtxt{..} =
fromMaybe
(error $ sformat ("resolveAddress: " % build % " not found") addr)
(Map.lookup addr addrRevMap)
where
AddrMap{..} = tcAddrMap
leaderForSlot :: SlotLeaders -> SlotId -> TransCtxt -> Stakeholder
leaderForSlot leaders slotId TransCtxt{..} = actorsStake Map.! leader
where
Actors{..} = tcActors
CardanoContext{..} = tcCardano
leader :: StakeholderId
leader = leaders NE.!! slotIx
slotIx :: Int
slotIx = fromIntegral $ getSlotIndex (siSlot slotId)
Derive block sign info from a ' Stakeholder '
Derive block sign info from a 'Stakeholder'
data BlockSignInfo = BlockSignInfo {
}
blockSignInfo :: Stakeholder -> BlockSignInfo
blockSignInfo Stakeholder{..} = BlockSignInfo{..}
where
DelegatedTo{..} = stkDel
Rich{..} = delTo
bsiLeader = regKpPub stkKey
bsiKey = regKpSec richKey
bsiPSK = delPSK
blockSignInfoForSlot :: SlotLeaders -> SlotId -> TransCtxt -> BlockSignInfo
blockSignInfoForSlot leaders slotId =
blockSignInfo
. leaderForSlot leaders slotId
instance Buildable Rich where
build Rich{..} = bprint
( "Rich"
% "{ key: " % build
% ", addr: " % build
% "}"
)
richKey
richAddr
instance Buildable Poor where
build Poor{..} = bprint
( "Poor"
% "{ key: " % build
% "}"
)
poorKey
instance Buildable Stakeholder where
build Stakeholder{..} = bprint
( "Stakeholder"
% "{ key: " % build
% ", del: " % build
% "}"
)
stkKey
stkDel
instance Buildable Avvm where
build Avvm{..} = bprint
( "Avvm"
% "{ key: " % build
% ", seed: " % base16F
% ", addr: " % build
% "}"
)
avvmKey
avvmSeed
avvmAddr
instance Buildable Actors where
build Actors{..} = bprint
( "Actors"
% "{ rich: " % listJson
% ", poor: " % listJson
% ", stake: " % listJson
% ", avvm: " % listJson
% "}"
)
(Map.elems actorsRich)
(Map.elems actorsPoor)
(Map.elems actorsStake)
(Map.elems actorsAvvm)
instance Buildable ActorIx where
build (IxRich ix) = bprint ("IxRich " % build) ix
build (IxPoor ix) = bprint ("IxPoor " % build) ix
build (IxAvvm ix) = bprint ("IxAvvm " % build) ix
instance Buildable Addr where
build Addr{..} = bprint
( "Addr"
% "{ actorIx: " % build
% ", addrIx: " % build
% "}"
)
addrActorIx
addrIx
instance Buildable CardanoContext where
build CardanoContext{..} = bprint
( "CardanoContext"
% "{ initLeaders: " % listJson
% ", stakes: " % listJson
% ", balances: " % listJson
% ", utxo: " % mapJson
% ", data: " % build
% "}"
)
ccInitLeaders
(map (bprint pairF) (HM.toList ccStakes))
(map (bprint pairF) ccBalances)
ccUtxo
ccData
instance Buildable AddrMap where
build AddrMap{..} = bprint
( "AddrMap"
% "{ revMap: " % mapJson
% "}"
)
addrRevMap
instance Buildable TransCtxt where
build TransCtxt{..} = bprint
( "TransCtxt"
% "{ cardano: " % build
% ", actors: " % build
% ", addrMap: " % build
% "}"
)
tcCardano
tcActors
tcAddrMap
instance Buildable GenesisData where
build GenesisData{..} = bprint
( "GenesisData"
% "{ bootStakeholders: " % build
% "}"
)
gdBootStakeholders
|
61ee2cb3376a353eb9fd696a130f6bddc96765b5962e3d4398a87a574dd92d25 | chebert/schemeish | expand-stream-collect.lisp | (in-package #:schemeish.backend)
(install-syntax!)
(define (stream-collect-bindings-fn binding-names body)
(let ((arg-name (gensym)))
`(lambda (,arg-name)
(destructuring-bind ,binding-names ,arg-name
(declare (ignorable ,@binding-names))
,@body))))
(define (stream-collect-filter-form binding-names test-form stream-form)
`(stream-filter
,(stream-collect-bindings-fn binding-names (list test-form))
,stream-form))
(stream-collect-filter-form '(i j) '(even? (+ i j)) :stream)
'(STREAM-FILTER
(LAMBDA (#:G586)
(DESTRUCTURING-BIND (I J) #:G586 (DECLARE (IGNORABLE I J)) (EVEN? (+ I J))))
:STREAM)
(define (stream-collect-inner-map-form binding binding-names)
`(stream-map (lambda (,(first binding))
(list ,@binding-names))
,(second binding)))
(assert (equal? (stream-collect-inner-map-form '(j (stream-range 1 (1- i)))
'(i j))
'(STREAM-MAP
(LAMBDA (J)
(LIST I J))
(STREAM-RANGE 1 (1- I)))))
(define (stream-collect-flatmap-form binding body)
`(stream-flatmap (lambda (,(first binding))
,@body)
,(second binding)))
(assert (equal? (stream-collect-flatmap-form '(i (stream-range 1 n)) '(:body))
'(STREAM-FLATMAP
(LAMBDA (I)
:BODY)
(STREAM-RANGE 1 N))))
(define (stream-collect-outer-map binding-names form stream)
`(stream-map
,(stream-collect-bindings-fn binding-names (list form))
,stream))
(stream-collect-outer-map '(i j) '(list i j (+ i j)) :stream)
'(STREAM-MAP
(LAMBDA (#:G588)
(DESTRUCTURING-BIND
(I J)
#:G588
(DECLARE (IGNORABLE I J))
(LIST I J (+ I J))))
:STREAM)
(define (stream-collect-inner-flatmaps bindings)
(when (null? bindings)
(error "stream-collect: requires at least one binding."))
(let ((binding-names (map 'car bindings))
(bindings (reverse bindings)))
(let rec ((result (stream-collect-inner-map-form (first bindings)
binding-names))
(bindings (rest bindings)))
(if (null? bindings)
result
(rec
(stream-collect-flatmap-form (first bindings) (list result))
(rest bindings))))))
(assert (equal? (stream-collect-inner-flatmaps '((i (stream-range 1 n))
(j (stream-range 1 (1- i)))))
'(STREAM-FLATMAP
(LAMBDA (I)
(STREAM-MAP
(LAMBDA (J)
(LIST I J))
(STREAM-RANGE 1 (1- I))))
(STREAM-RANGE 1 N))))
(define (stream-collect-form map-form bindings filter-form)
(let ((binding-names (map 'car bindings)))
(stream-collect-outer-map
binding-names
map-form
(stream-collect-filter-form
binding-names
filter-form
(stream-collect-inner-flatmaps bindings)))))
(stream-collect-form '(list i j (+ i j))
'((i (stream-range 1 n))
(j (stream-range 1 (1- i))))
'(even? (+ i j)))
'(STREAM-MAP
(LAMBDA (#:G594)
(DESTRUCTURING-BIND
(I J)
#:G594
(DECLARE (IGNORABLE I J))
(LIST I J (+ I J))))
(STREAM-FILTER
(LAMBDA (#:G593)
(DESTRUCTURING-BIND
(I J)
#:G593
(DECLARE (IGNORABLE I J))
(EVEN? (+ I J))))
(STREAM-FLATMAP
(LAMBDA (I)
(STREAM-MAP
(LAMBDA (J)
(LIST I J))
(STREAM-RANGE 1 (1- I))))
(STREAM-RANGE 1 N))))
(uninstall-syntax!)
| null | https://raw.githubusercontent.com/chebert/schemeish/93ea08b17e6d8876f086e1a34a21b538174b2c39/src/expand-stream-collect.lisp | lisp | (in-package #:schemeish.backend)
(install-syntax!)
(define (stream-collect-bindings-fn binding-names body)
(let ((arg-name (gensym)))
`(lambda (,arg-name)
(destructuring-bind ,binding-names ,arg-name
(declare (ignorable ,@binding-names))
,@body))))
(define (stream-collect-filter-form binding-names test-form stream-form)
`(stream-filter
,(stream-collect-bindings-fn binding-names (list test-form))
,stream-form))
(stream-collect-filter-form '(i j) '(even? (+ i j)) :stream)
'(STREAM-FILTER
(LAMBDA (#:G586)
(DESTRUCTURING-BIND (I J) #:G586 (DECLARE (IGNORABLE I J)) (EVEN? (+ I J))))
:STREAM)
(define (stream-collect-inner-map-form binding binding-names)
`(stream-map (lambda (,(first binding))
(list ,@binding-names))
,(second binding)))
(assert (equal? (stream-collect-inner-map-form '(j (stream-range 1 (1- i)))
'(i j))
'(STREAM-MAP
(LAMBDA (J)
(LIST I J))
(STREAM-RANGE 1 (1- I)))))
(define (stream-collect-flatmap-form binding body)
`(stream-flatmap (lambda (,(first binding))
,@body)
,(second binding)))
(assert (equal? (stream-collect-flatmap-form '(i (stream-range 1 n)) '(:body))
'(STREAM-FLATMAP
(LAMBDA (I)
:BODY)
(STREAM-RANGE 1 N))))
(define (stream-collect-outer-map binding-names form stream)
`(stream-map
,(stream-collect-bindings-fn binding-names (list form))
,stream))
(stream-collect-outer-map '(i j) '(list i j (+ i j)) :stream)
'(STREAM-MAP
(LAMBDA (#:G588)
(DESTRUCTURING-BIND
(I J)
#:G588
(DECLARE (IGNORABLE I J))
(LIST I J (+ I J))))
:STREAM)
(define (stream-collect-inner-flatmaps bindings)
(when (null? bindings)
(error "stream-collect: requires at least one binding."))
(let ((binding-names (map 'car bindings))
(bindings (reverse bindings)))
(let rec ((result (stream-collect-inner-map-form (first bindings)
binding-names))
(bindings (rest bindings)))
(if (null? bindings)
result
(rec
(stream-collect-flatmap-form (first bindings) (list result))
(rest bindings))))))
(assert (equal? (stream-collect-inner-flatmaps '((i (stream-range 1 n))
(j (stream-range 1 (1- i)))))
'(STREAM-FLATMAP
(LAMBDA (I)
(STREAM-MAP
(LAMBDA (J)
(LIST I J))
(STREAM-RANGE 1 (1- I))))
(STREAM-RANGE 1 N))))
(define (stream-collect-form map-form bindings filter-form)
(let ((binding-names (map 'car bindings)))
(stream-collect-outer-map
binding-names
map-form
(stream-collect-filter-form
binding-names
filter-form
(stream-collect-inner-flatmaps bindings)))))
(stream-collect-form '(list i j (+ i j))
'((i (stream-range 1 n))
(j (stream-range 1 (1- i))))
'(even? (+ i j)))
'(STREAM-MAP
(LAMBDA (#:G594)
(DESTRUCTURING-BIND
(I J)
#:G594
(DECLARE (IGNORABLE I J))
(LIST I J (+ I J))))
(STREAM-FILTER
(LAMBDA (#:G593)
(DESTRUCTURING-BIND
(I J)
#:G593
(DECLARE (IGNORABLE I J))
(EVEN? (+ I J))))
(STREAM-FLATMAP
(LAMBDA (I)
(STREAM-MAP
(LAMBDA (J)
(LIST I J))
(STREAM-RANGE 1 (1- I))))
(STREAM-RANGE 1 N))))
(uninstall-syntax!)
| |
f6395c62a328a8720fb9de60814a2b9fa941bfdda3fa7c14ba667ac72ac36c23 | chef/mixer | multiple.erl | -module(multiple).
-include("mixer.hrl").
-mixin([{foo, [doit/0]},
bar,
{foo, except, [doit/0, doit/1]}]).
| null | https://raw.githubusercontent.com/chef/mixer/0d1322433e7e2237eb1270dc5a028fa014335134/test/multiple.erl | erlang | -module(multiple).
-include("mixer.hrl").
-mixin([{foo, [doit/0]},
bar,
{foo, except, [doit/0, doit/1]}]).
| |
6aba16b5c8be69b685fd1f9664c5c464368b058d62203cdb923907f7f094c410 | emil0r/reverie | module.clj | (ns reverie.module
(:require [clojure.core.match :refer [match]]
[reverie.auth :refer [with-access]]
[reverie.http.response :as response]
[reverie.http.route :as route]
[reverie.module.entity :as entity]
[reverie.page :as page]
[reverie.render :as render]
[reverie.system :as sys]
[reverie.util :as util]
[reverie.ModuleException]
[reverie.RenderException])
(:refer-clojure :exclude [list name])
(:import [reverie ModuleException RenderException]))
(defprotocol IModuleDatabase
(get-data
[module entity params]
[module entity params id])
(save-data [module entity id data])
(add-data [module entity data])
(delete-data [module entity id] [module entity id cascade?])
(publish-data [module entity id])
(unpublish-data [module entity id]))
(defprotocol IModule
(interface? [entity]
"Should this be automatically interfaced?")
(entities [module]
"Entities of the module")
(get-entity [module slug]
"Get entity based on slug")
(options [module]
"Options of the module")
(name [module]
"Name of the module")
(list [module entity] [module entity params offset limit]
"List the fields in an entity in the admin interface")
(filters [module entity]
"Get possible filters")
(slug [module]
"Get slug to be used as part of a URI"))
(defrecord Module [name database entities options routes route]
IModule
(options [this] options)
(entities [this] entities)
(get-entity [this slug]
(first (filter #(= slug (entity/slug %)) entities)))
(name [this] (or (:name options) (clojure.core/name name)))
(slug [this]
(or (:slug options) (util/slugify name)))
render/IRender
(render [this request]
(let [request (merge request
{:shortened-uri (util/shorten-uri
(:uri request) (:path route))})]
(with-access
(get-in request [:reverie :user]) (:required-roles options)
(if-let [page-route (first (filter #(route/match? % request) routes))]
(let [{:keys [request method]} (route/match? page-route request)
resp (method request this (:params request))
t (if (:template options)
(get (:templates @sys/storage) (:template options)))
renderer (sys/renderer (:renderer options))
out (if (and t
(map? resp)
(not (contains? resp :status))
(not (contains? resp :body))
(not (contains? resp :headers)))
(render/render t request (assoc this :rendered resp))
resp)]
(match [;; raw response
(and (map? resp)
(contains? resp :status)
(contains? resp :body)
(contains? resp :headers))
;; renderer
(not (nil? renderer))
;; routes
(not (nil? (:methods-or-routes renderer)))
;; map
(map? resp)
;; template
(not (nil? t))]
;; raw response
[true _ _ _ _] resp
;; ~renderer, _ , map, template
[_ false _ true true] (render/render t request (assoc this :rendered resp))
;; renderer, routes, map, template
[_ true true true true] (let [out (render/render renderer (:request-method request)
{:data resp
::render/type :page/routes
:meta {:route-name (get-in page-route [:options :name])}})]
(render/render t request (assoc this :rendered out)))
;; renderer, ~routes, map, template
[_ true false true true] (let [out (render/render renderer (:request-method request)
{:data resp
::render/type :page/no-routes
:meta {:route-name (get-in page-route [:options :name])}})]
(render/render t request (assoc this :rendered out)))
renderer , ~routes , ~map ,
[_ true false false false] (render/render renderer (:request-method request)
{:data resp
::render/type :page/no-routes
:meta {:route-name (get-in page-route [:options :name])}})
;; default
[_ _ _ _ _] resp))
(response/get 404)))))
(render [this _ _]
(throw (RenderException. "[component request sub-component] not implemented for reverie.module/Module")))
page/IPage
(properties [this] nil)
(type [this] :module)
(cache? [this] false)
(version [this] 0))
(defn module [name entities options routes]
(map->Module {:name name :entities entities
:options options :routes routes}))
| null | https://raw.githubusercontent.com/emil0r/reverie/a29c223b7326e6d5a5e0874d33c37ff2fa0dfd4d/reverie-core/src/reverie/module.clj | clojure | raw response
renderer
routes
map
template
raw response
~renderer, _ , map, template
renderer, routes, map, template
renderer, ~routes, map, template
default | (ns reverie.module
(:require [clojure.core.match :refer [match]]
[reverie.auth :refer [with-access]]
[reverie.http.response :as response]
[reverie.http.route :as route]
[reverie.module.entity :as entity]
[reverie.page :as page]
[reverie.render :as render]
[reverie.system :as sys]
[reverie.util :as util]
[reverie.ModuleException]
[reverie.RenderException])
(:refer-clojure :exclude [list name])
(:import [reverie ModuleException RenderException]))
(defprotocol IModuleDatabase
(get-data
[module entity params]
[module entity params id])
(save-data [module entity id data])
(add-data [module entity data])
(delete-data [module entity id] [module entity id cascade?])
(publish-data [module entity id])
(unpublish-data [module entity id]))
(defprotocol IModule
(interface? [entity]
"Should this be automatically interfaced?")
(entities [module]
"Entities of the module")
(get-entity [module slug]
"Get entity based on slug")
(options [module]
"Options of the module")
(name [module]
"Name of the module")
(list [module entity] [module entity params offset limit]
"List the fields in an entity in the admin interface")
(filters [module entity]
"Get possible filters")
(slug [module]
"Get slug to be used as part of a URI"))
(defrecord Module [name database entities options routes route]
IModule
(options [this] options)
(entities [this] entities)
(get-entity [this slug]
(first (filter #(= slug (entity/slug %)) entities)))
(name [this] (or (:name options) (clojure.core/name name)))
(slug [this]
(or (:slug options) (util/slugify name)))
render/IRender
(render [this request]
(let [request (merge request
{:shortened-uri (util/shorten-uri
(:uri request) (:path route))})]
(with-access
(get-in request [:reverie :user]) (:required-roles options)
(if-let [page-route (first (filter #(route/match? % request) routes))]
(let [{:keys [request method]} (route/match? page-route request)
resp (method request this (:params request))
t (if (:template options)
(get (:templates @sys/storage) (:template options)))
renderer (sys/renderer (:renderer options))
out (if (and t
(map? resp)
(not (contains? resp :status))
(not (contains? resp :body))
(not (contains? resp :headers)))
(render/render t request (assoc this :rendered resp))
resp)]
(and (map? resp)
(contains? resp :status)
(contains? resp :body)
(contains? resp :headers))
(not (nil? renderer))
(not (nil? (:methods-or-routes renderer)))
(map? resp)
(not (nil? t))]
[true _ _ _ _] resp
[_ false _ true true] (render/render t request (assoc this :rendered resp))
[_ true true true true] (let [out (render/render renderer (:request-method request)
{:data resp
::render/type :page/routes
:meta {:route-name (get-in page-route [:options :name])}})]
(render/render t request (assoc this :rendered out)))
[_ true false true true] (let [out (render/render renderer (:request-method request)
{:data resp
::render/type :page/no-routes
:meta {:route-name (get-in page-route [:options :name])}})]
(render/render t request (assoc this :rendered out)))
renderer , ~routes , ~map ,
[_ true false false false] (render/render renderer (:request-method request)
{:data resp
::render/type :page/no-routes
:meta {:route-name (get-in page-route [:options :name])}})
[_ _ _ _ _] resp))
(response/get 404)))))
(render [this _ _]
(throw (RenderException. "[component request sub-component] not implemented for reverie.module/Module")))
page/IPage
(properties [this] nil)
(type [this] :module)
(cache? [this] false)
(version [this] 0))
(defn module [name entities options routes]
(map->Module {:name name :entities entities
:options options :routes routes}))
|
66fb91a85e46e273380b7dcc2b036161c57d1fd875d9fe6ff895aa13fcdf5e1a | daigotanaka/mern-cljs | models.cljs | (ns common.models
(:require-macros
[mern-utils.macros :refer [node-require]])
(:require
[cljs.nodejs :as nodejs]
[mern-utils.db :as db]
[common.models.user-schema :refer [user-schema api-token-schema
facebook-account-schema
google-account-schema
twitter-account-schema]]
))
(defn user-model [] (db/model "User" (user-schema)))
(defn api-token-model [] (db/model "ApiToken" (api-token-schema)))
(defn facebook-account-model [] (db/model "FacebookAccount" (facebook-account-schema)))
(defn google-account-model [] (db/model "GoogleAccount" (google-account-schema)))
(defn twitter-account-model [] (db/model "TwitterAccount" (twitter-account-schema)))
| null | https://raw.githubusercontent.com/daigotanaka/mern-cljs/a9dedbb3b622f96dd0b06832733b4fd961e6437d/example/common/src/common/models.cljs | clojure | (ns common.models
(:require-macros
[mern-utils.macros :refer [node-require]])
(:require
[cljs.nodejs :as nodejs]
[mern-utils.db :as db]
[common.models.user-schema :refer [user-schema api-token-schema
facebook-account-schema
google-account-schema
twitter-account-schema]]
))
(defn user-model [] (db/model "User" (user-schema)))
(defn api-token-model [] (db/model "ApiToken" (api-token-schema)))
(defn facebook-account-model [] (db/model "FacebookAccount" (facebook-account-schema)))
(defn google-account-model [] (db/model "GoogleAccount" (google-account-schema)))
(defn twitter-account-model [] (db/model "TwitterAccount" (twitter-account-schema)))
| |
8c29fe29a85428afa607abdb9e9bc41fbcfe6cb81d9b02041422d94dac5529fb | slyrus/mcclim-old | utils.lisp | ;;; -*- Mode: Lisp; Package: ESA-UTILS -*-
( c ) copyright 2006 by
( )
;;; This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation ; either
version 2 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
Library General Public License for more details .
;;;
You should have received a copy of the GNU Library General Public
;;; License along with this library; if not, write to the
Free Software Foundation , Inc. , 59 Temple Place - Suite 330 ,
Boston , MA 02111 - 1307 USA .
Miscellaneous utilities used in ESA .
(in-package :esa-utils)
Cribbed from
(defmacro with-gensyms (syms &body body)
`(let ,(mapcar #'(lambda (s) `(,s (gensym))) syms)
,@body))
Cribbed from PCL by Seibel
(defmacro once-only ((&rest names) &body body)
(let ((gensyms (loop for n in names collect (gensym))))
`(let (,@(loop for g in gensyms collect `(,g (gensym))))
`(let (,,@(loop for g in gensyms for n in names collect ``(,,g ,,n)))
,(let (,@(loop for n in names for g in gensyms collect `(,n ,g)))
,@body)))))
(defun unlisted (obj &optional (fn #'first))
(if (listp obj)
(funcall fn obj)
obj))
(defun fully-unlisted (obj &optional (fn #'first))
(if (listp obj)
(fully-unlisted (funcall fn obj))
obj))
(defun listed (obj)
(if (listp obj)
obj
(list obj)))
(defun list-aref (list &rest subscripts)
(if subscripts
(apply #'list-aref (nth (first subscripts) list)
(rest subscripts))
list))
Cribbed from McCLIM .
(defun check-letf-form (form)
(assert (and (listp form)
(= 2 (length form)))))
(defun valueify (list)
(if (and (consp list)
(endp (rest list)))
(first list)
`(values ,@list)))
(defmacro letf ((&rest forms) &body body &environment env)
"LETF ({(Place Value)}*) Declaration* Form* During evaluation of the
Forms, SETF the Places to the result of evaluating the Value forms.
The places are SETF-ed in parallel after all of the Values are
evaluated."
(mapc #'check-letf-form forms)
(let* (init-let-form save-old-values-setf-form
new-values-set-form old-values-set-form
update-form)
(loop for (place new-value) in forms
for (vars vals store-vars writer-form reader-form)
= (multiple-value-list (get-setf-expansion place env))
for old-value-names = (mapcar (lambda (var)
(declare (ignore var))
(gensym))
store-vars)
nconc (mapcar #'list vars vals) into temp-init-let-form
nconc (copy-list store-vars) into temp-init-let-form
nconc (copy-list old-value-names) into temp-init-let-form
nconc `(,(valueify old-value-names) ,reader-form) into temp-save-old-values-setf-form
nconc `(,(valueify store-vars) ,new-value) into temp-new-values-set-form
nconc `(,(valueify store-vars) ,(valueify old-value-names)) into temp-old-values-set-form
collect writer-form into temp-update-form
finally (setq init-let-form temp-init-let-form
save-old-values-setf-form temp-save-old-values-setf-form
new-values-set-form temp-new-values-set-form
old-values-set-form temp-old-values-set-form
update-form (cons 'progn temp-update-form)))
`(let* ,init-let-form
(setf ,@save-old-values-setf-form)
(unwind-protect
(progn (setf ,@new-values-set-form)
,update-form
(progn ,@body))
(setf ,@old-values-set-form)
,update-form))))
(defun invoke-with-dynamic-bindings-1 (bindings continuation)
(let ((old-values (mapcar #'(lambda (elt)
(symbol-value (first elt)))
bindings)))
(unwind-protect (progn
(mapcar #'(lambda (elt)
(setf (symbol-value (first elt))
(funcall (second elt))))
bindings)
(funcall continuation))
(mapcar #'(lambda (elt value)
(setf (symbol-value (first elt))
value))
bindings old-values))))
(defmacro invoke-with-dynamic-bindings ((&rest bindings) &body body)
`(invoke-with-dynamic-bindings-1
,(loop for (symbol expression) in bindings
collect (list `',symbol
`#'(lambda ()
,expression)))
#'(lambda ()
,@body)))
;;; XXX This is currently broken with respect to declarations
(defmacro letf* ((&rest forms) &body body)
(if (null forms)
`(locally
,@body)
`(letf (,(car forms))
(letf* (,(cdr forms))
,@body))))
(defun display-string (string)
(with-output-to-string (result)
(loop for char across string
do (cond ((graphic-char-p char) (princ char result))
((char= char #\Space) (princ char result))
(t (prin1 char result))))))
(defun object-equal (x y)
"Case insensitive equality that doesn't require characters"
(if (characterp x)
(and (characterp y) (char-equal x y))
(eql x y)))
(defun object= (x y)
"Case sensitive equality that doesn't require characters"
(if (characterp x)
(and (characterp y) (char= x y))
(eql x y)))
(defun no-upper-p (string)
"Does STRING contain no uppercase characters"
(notany #'upper-case-p string))
(defun case-relevant-test (string)
"Returns a test function based on the search-string STRING.
If STRING contains no uppercase characters the test is case-insensitive,
otherwise it is case-sensitive."
(if (no-upper-p string)
#'object-equal
#'object=))
(defun remove-keywords (arg-list keywords)
(let ((clean-tail arg-list))
First , determine a tail in which there are no keywords to be removed .
(loop for arg-tail on arg-list by #'cddr
for (key) = arg-tail
do (when (member key keywords :test #'eq)
(setq clean-tail (cddr arg-tail))))
;; Cons up the new arg list until we hit the clean-tail, then nconc that on
;; the end.
(loop for arg-tail on arg-list by #'cddr
for (key value) = arg-tail
if (eq arg-tail clean-tail)
nconc clean-tail
and do (loop-finish)
else if (not (member key keywords :test #'eq))
nconc (list key value)
end)))
(defmacro with-keywords-removed ((var keywords &optional (new-var var))
&body body)
"binds NEW-VAR (defaults to VAR) to VAR with the keyword arguments specified
in KEYWORDS removed."
`(let ((,new-var (remove-keywords ,var ',keywords)))
,@body))
(defun maptree (fn x)
"This auxiliary function is like MAPCAR but has two extra
( 2 ) it tries to make the
result share with the argument x as much as possible."
(if (atom x)
(funcall fn x)
(let ((a (funcall fn (car x)))
(d (maptree fn (cdr x))))
(if (and (eql a (car x)) (eql d (cdr x)))
x
(cons a d)))))
(defun subtype-compatible-p (types)
"Return true if an element of `types' is a subtype of every
other type specifier in `types'. `Types' must be a list of type
specifiers."
(some (lambda (x)
(subtypep x `(and ,@types))) types))
(defun capitalize (string)
"Return `string' with the first character
capitalized (destructively modified)."
(setf (elt string 0) (char-upcase (elt string 0)))
string)
(defun ensure-array-size (array min-size new-elem-fn)
"Ensure that `array' is at least of size `min-size'. If `array'
needs to be resized, call `new-elem-fn' with no arguments to
generate the elements of the new cells in the array. Returns
`array'. Currently, this function only works when `array' is a
vector."
(when (< (length array) min-size)
(let ((old-length (length array)))
(setf array (adjust-array array
(max (* old-length 2) min-size)))
(loop for i from old-length below (length array)
do (setf (elt array i) (funcall new-elem-fn)))))
array)
(define-method-combination values-max-min
(&optional (order ':most-specific-first))
((around (:around))
(before (:before))
(after (:after))
(primary (values-max-min) :order order :required t))
(flet ((call-methods (methods)
(mapcar (lambda (m) `(call-method ,m)) methods))
(call-vmm-methods (methods)
`(multiple-value-bind (max min)
(call-method ,(first methods))
(progn
,@(loop for m in (rest methods)
collect `(multiple-value-bind (mmax mmin)
(call-method ,m)
(setq max (max max mmax)
min (min min mmin)))))
(values max min))))
(let ((form (if (or around before after (rest primary))
`(multiple-value-prog1
(progn ,@(call-methods before)
,(call-vmm-methods primary))
(progn ,@(call-methods (reverse after))))
`(call-method ,(first primary)))))
(if around
`(call-method ,(first around) (,@(rest around) (make-method ,form)))
form))))
(defmacro retaining-value ((bound-symbol &optional initial-value) &body body)
"Evaluate `body' with `bound-symbol' bound to
`initial-value' (default NIL). Th next time `body' is evaluated,
`bound-symbol' will be bound to whatever its value was the last
time evaluation of `body' ended."
(let ((symbol (gensym)))
`(progn (unless (boundp ',symbol)
(setf (symbol-value ',symbol) ,initial-value))
(let ((,bound-symbol (symbol-value ',symbol)))
(unwind-protect (progn ,@body)
(setf (symbol-value ',symbol) ,bound-symbol))))))
(defun format-sym (format-string &rest args)
"Return `format-string' with args spliced in, where all
arguments that are symbols with have their `symbol-name' spliced
instead, this makes sure the result is correct even on systems
where read/print case is other than default."
(apply #'format nil format-string
(mapcar #'(lambda (arg)
(if (symbolp arg)
(symbol-name arg)
arg))
args)))
(defun build-menu (command-tables &rest commands)
"Create a command table inheriting commands from
`command-tables', which must be a list of command table
designators. The created command table will have a menu
consisting of `commands', elements of which must be one of:
* A named command accessible in one of `command-tables'. This may
either be a command name, or a cons of a command name and
arguments. The command will appear directly in the menu.
* A list of the symbol `:menu' and something that will evaluate
to a command table designator. This will create a submenu
showing the name and menu of the designated command table.
* A list of the symbol `:submenu', a string, and a &rest list
of the same form as `commands'. This is equivalent to `:menu'
with a call to `build-menu' with `command-tables' and
the specified list as arguments.
* A symbol `:divider', which will present a horizontal divider
line.
An error of type`command-table-error' will be signalled if a
command cannot be found in any of the provided command tables."
(labels ((get-command-name (command)
(or (loop for table in command-tables
for name = (command-line-name-for-command command table :errorp nil)
when name return name)
(error 'command-table-error
:format-string "Command ~A not found in any provided command table"
:format-arguments (list command))))
(make-menu-entry (entry)
(cond ((and (listp entry)
(eq (first entry) :menu))
(list (command-table-name (find-command-table (second entry)))
:menu (second entry)))
((and (listp entry)
(eq (first entry) :submenu))
(list (second entry)
:menu (apply #'build-menu command-tables
(cddr entry))))
((eq entry :divider)
'(nil :divider :line))
(t (list (get-command-name (command-name (listed entry)))
:command entry)))))
(make-command-table nil
:inherit-from command-tables
:menu (mapcar #'make-menu-entry commands))))
(defmacro define-menu-table (name (&rest command-tables) &body commands)
"Define a command table with a menu named `name' and containing
`commands'. `Command-tables' must be a list of command table
designators containing the named commands that will be included
in the menu. `Commands' must have the same format as the
`commands' argument to `build-menu'. If `name' already names a
command table, the old definition will be destroyed."
`(make-command-table ',name
:inherit-from (list (build-menu ',command-tables
,@commands))
:inherit-menu t
:errorp nil))
(defclass observable-mixin ()
((%observers :accessor observers
:initform '()))
(:documentation "A mixin class that adds the capability for a
subclass to have a list of \"event subscribers\" (observers) that
can be informed via callback (the function `observer-notified')
whenever the state of the object changes. The order in which
observers will be notified is undefined."))
(defgeneric add-observer (observable observer)
(:documentation "Add an observer to an observable object. If
the observer is already observing `observable', it will not be
added again."))
(defmethod add-observer ((observable observable-mixin) observer)
Linear in complexity , perhaps a transparent switch to a hash
;; table would be a good idea for large amounts of observers.
(pushnew observer (observers observable)))
(defgeneric remove-observer (observable observer)
(:documentation "Remove an observer from an observable
object. If observer is not in the list of observers of
`observable', nothing will happen."))
(defmethod remove-observer ((observable observable-mixin) observer)
(setf (observers observable)
(delete observer (observers observable))))
(defgeneric observer-notified (observer observable data)
(:documentation "This function is called by `observable' when
its state changes on each observer that is observing
it. `Observer' is the observing object, `observable' is the
observed object. `Data' is arbitrary data that might be of
interest to `observer', it is recommended that subclasses of
`observable-mixin' specify exactly which form this data will
take, the observer protocol does not guarantee anything. It is
non-&optional so that methods may be specialised on it, if
applicable. The default method on this function is a no-op, so it
is never an error to not define a method on this generic function
for an observer.")
(:method (observer (observable observable-mixin) data)
;; Never a no-applicable-method error.
nil))
(defgeneric notify-observers (observable &optional data-fn)
(:documentation "Notify each observer of `observable' by
calling `observer-notified' on them. `Data-fn' will be called,
with the observer as the single argument, to obtain the `data'
argument to `observer-notified'. The default value of `data-fn'
should cause the `data' argument to be NIL."))
(defmethod notify-observers ((observable observable-mixin)
&optional (data-fn (constantly nil)))
(dolist (observer (observers observable))
(observer-notified observer observable
(funcall data-fn observer))))
(defclass name-mixin ()
((%name :accessor name
:initarg :name
:type string
:documentation "The name of the named object."))
(:documentation "A class used for defining named objects."))
(defclass subscriptable-name-mixin (name-mixin)
((%subscript :accessor subscript
:documentation "The subscript of the named object.")
(%subscript-generator :accessor subscript-generator
:initarg :subscript-generator
:initform (constantly 1)
:documentation "A function used for
finding the subscript of a `name-mixin' whenever the name is
set (including during object initialization). This function will
be called with the name as the single argument."))
(:documentation "A class used for defining named objects. A
facility is provided for assigning a named object a \"subscript\"
uniquely identifying the object if there are other objects of the
same name in its collection (in particular, if an editor has two
buffers with the same name)."))
(defmethod initialize-instance :after ((name-mixin subscriptable-name-mixin)
&rest initargs)
(declare (ignore initargs))
(setf (subscript name-mixin)
(funcall (subscript-generator name-mixin) (name name-mixin))))
(defmethod subscripted-name ((name-mixin subscriptable-name-mixin))
;; Perhaps this could be written as a single format statement?
(if (/= (subscript name-mixin) 1)
(format nil "~A <~D>" (name name-mixin) (subscript name-mixin))
(name name-mixin)))
(defmethod (setf name) :after (new-name (name-mixin subscriptable-name-mixin))
(setf (subscript name-mixin)
(funcall (subscript-generator name-mixin) new-name)))
;;; "Modes" are a generally useful concept, so let's define some
;;; primitives for them here.
(defclass mode ()
()
(:documentation "A superclass for all modes."))
(defconstant +default-modes-plist-symbol+ 'modual-class-default-modes
"The symbol that is pushed onto the property list of the name
of a class to contain the list of default modes for the class.")
(defun default-modes (modual-class)
"Return the list of default modes for `modual-class', which
must be a symbol and the name of a modual class. The modes are
returned as a list of conses, with the car of each cons being the
name of the mode as a symbol, and the cdr of each cons being a
list of initargs"
(getf (symbol-plist modual-class) +default-modes-plist-symbol+))
(defun (setf default-modes) (new-default-modes modual-class)
"Set the list of default modes for `modual-class', which must
be a symbol and the name of a modual class. The modes should be
given as a list of conses, with the car of each cons being the
name of the mode as a symbol, and the cdr of each cons being a
list of initargs"
(setf (getf (symbol-plist modual-class) +default-modes-plist-symbol+)
new-default-modes))
(defclass modual-class (standard-class)
()
(:documentation "A metaclass for defining classes supporting
changing of modes."))
(defmethod validate-superclass ((c1 modual-class) (c2 standard-class))
t)
(defmethod compute-slots ((c modual-class))
(append (call-next-method)
(list (make-instance 'standard-effective-slot-definition
:name '%original-class-name
:allocation :instance
:documentation "The original name of the class
the `modual-mixin' is part of, the actual name will change as
modes are added and removed."))))
(defmethod make-instance ((class modual-class) &rest initargs)
(declare (ignore initargs))
(let ((instance (call-next-method)))
(setf (slot-value instance '%original-class-name)
(class-name class))
(dolist (class (reverse (class-precedence-list class)) instance)
(when (symbolp (class-name class))
(dolist (mode-and-initargs (default-modes (class-name class)))
(apply #'enable-mode instance (first mode-and-initargs)
(rest mode-and-initargs)))))))
(defgeneric available-modes (modual)
(:documentation "Return all available modes for `modual'. Not
all of the modes may be applicable, use the `applicable-modes'
function if you're only interested in these.")
(:method-combination append)
(:method append ((modual t))
'()))
(defgeneric mode-directly-applicable-p (modual mode-name)
(:documentation "Return true if the mode of the name
`mode-name' can be directly enabled for `modual'. If the mode of
name `mode-name' is unapplicable, an error of type
`nonapplicable-mode' will be signalled. This allows a sort of
\"opt-out\" where a mode can forcefully prevent another specific
mode from being enabled. ")
(:method-combination or)
(:method or ((modual t) mode-name)
nil))
(defgeneric mode-applicable-p (modual mode-name)
(:documentation "Return true if the mode of the name
`mode-name' can be enabled for `modual' or some sub-object of
`modual'. If the mode of name `mode-name' is unapplicable, an
error of type `nonapplicable-mode' will be signalled. This allows
a sort of \"opt-out\" where a mode can forcefully prevent another
specific mode from being enabled. ")
(:method-combination or)
(:method or ((modual t) mode-name)
(mode-directly-applicable-p modual mode-name)))
(defgeneric enabled-modes (modual)
(:documentation "Return a list of the names of the modes
directly enabled for `modual'.")
(:method ((modual t))
'()))
(defgeneric mode-enabled-p (modual mode-name)
(:documentation "Return true if `mode-name' is enabled for
`modual' or any modual \"sub-objects\"." )
(:method-combination or)
(:method or ((modual t) mode-name)
(member mode-name (enabled-modes modual) :test #'equal)))
(define-condition nonapplicable-mode (error)
((%modual :accessor modual
:initarg :modual
:initform (error "The modual used in the error-causing operation must be supplied")
:documentation "The modual that the mode is attempted to be enabled for")
(%mode-name :accessor mode-name
:initarg :mode-name
:initform (error "The name of the problematic mode must be supplied")
:documentation "The name of the mode that cannot be enabled for the view"))
(:documentation "This error is signalled if a mode is attempted
enabled for a modual that the mode is not applicable to.")
(:report (lambda (condition stream)
(format
stream "The mode ~A is not applicable for ~A"
(mode-name condition) (modual condition)))))
(defun nonapplicable-mode (modual mode-name)
"Signal an error of type `nonapplicable-mode' with `modual' and
`mode-name' as arguments."
(error 'nonapplicable-mode :modual modual :mode-name mode-name))
(defgeneric enable-mode (modual mode-name &rest initargs)
(:documentation "Enable the mode of the name `mode-name' for
`modual', using `initargs' as options for the mode. If the mode
is already enabled, do nothing. If the mode is not applicable to
`modual', signal an `nonapplicable-mode' error.")
(:method :around ((modual t) mode-name &rest initargs)
(declare (ignore initargs))
(unless (mode-enabled-p modual mode-name)
(call-next-method))))
(defgeneric disable-mode (modual mode-name)
(:documentation "Disable the mode of the name `mode-name' for
`modual'. If a mode of the provided name is not enabled, do
nothing.")
(:method :around ((modual t) mode-name)
(when (mode-enabled-p modual mode-name)
(call-next-method))))
;;; In a perfect world, we would just combine `change-class' with
;;; anonymous classes to transparently add and remove mode classes
;;; (the "stealth mixin" concept). However, anonymous classes are the
ugly child of CL , not well supported at all , so we 'll have to do
;;; some ugly hacks involving the `eval'ing of constructed `defclass'
;;; forms, and caching the created classes to prevent memory leaking.
(defvar *class-cache* (make-hash-table :test #'equal)
"A hash table mapping the name of a \"modual\" class to a
second hash table. This second hash table maps a list of mode
names to a class implementing this particular set of modes for
the modual class. Note that the order in which the modes appear
in the list is significant.")
(defun make-class-implementing-modes (modual modes)
"Generate a class that is a subclass of `modual' that
implements all the modes listed as names in `modes'."
;; Avert thine eyes, thy of gentle spirit.
(if (null modes)
(find-class modual)
;; We're kind and put the active modes into the class name.
(eval `(defclass ,(gensym (format nil "~A~{-~A~}" (string modual) modes))
(,modual ,@modes)
((%enabled-modes :reader enabled-modes
:initform ',modes))
(:metaclass modual-class)))))
(defun find-class-implementing-modes (modual modes)
"Find, possibly create, the class implementing `modual' (a
class name) with `modes' (a list of mode names) as the enabled
modes."
(let* ((modual-cache-hit (gethash modual *class-cache*))
(modes-cache-hit (and modual-cache-hit
(gethash modes modual-cache-hit))))
(or modes-cache-hit
(setf (gethash modes
(or modual-cache-hit
(setf (gethash modual *class-cache*)
(make-hash-table :test #'equal))))
(make-class-implementing-modes modual modes)))))
(defun change-class-for-enabled-mode (modual mode-name &rest initargs)
"Change the class of `modual' so that it has a mode of name
`mode-name', created with the provided `initargs'."
(apply #'change-class modual (find-class-implementing-modes
(slot-value modual '%original-class-name)
(cons mode-name (enabled-modes modual)))
initargs))
(defun change-class-for-disabled-mode (modual mode-name)
"Change the class of `modual' so that it does not have a mode
of name `mode-name'."
(change-class modual (find-class-implementing-modes
(slot-value modual '%original-class-name)
(remove mode-name (enabled-modes modual)
:test #'equal))))
(defmethod enable-mode ((modual t) mode-name &rest initargs)
(if (mode-directly-applicable-p modual mode-name)
(apply #'change-class-for-enabled-mode modual mode-name initargs)
(nonapplicable-mode modual mode-name)))
(defmethod disable-mode ((modual t) mode-name)
(when (mode-directly-applicable-p modual mode-name)
(change-class-for-disabled-mode modual mode-name)))
(defmacro add-default-modes (modual-class &body modes)
"Add `modes' to the list of default modes for
`modual-class'. Will not replace any already existing modes. The
elements in `modes' can either be a single symbol, the name of a
mode, or a cons of the name of a mode and a list of initargs for
the mode. In the former case, no initargs will be given. Please
do not use default modes as a programming tool, they should be
reserved for user-oriented functionality."
(dolist (mode modes)
(let ((mode-name (unlisted mode)))
(check-type mode-name symbol)
;; Take care not to add the same mode twice, this is risky enough
;; as it is.
(setf (default-modes modual-class)
(cons (listed mode)
(delete mode-name (default-modes modual-class) :key #'first))))))
(defmacro remove-default-modes (modual-class &body modes)
"Remove `modes' from the list of default modes for
`modual-class'. `Modes' must be a list of names of modes in the
form of symbols. If a provided mode is not set as a default mode,
nothing will be done."
(dolist (mode modes)
(check-type mode symbol)
;; Take care not to add the same mode twice, this is risky enough
;; as it is.
(setf (default-modes modual-class)
(delete mode (default-modes modual-class) :key #'first))))
| null | https://raw.githubusercontent.com/slyrus/mcclim-old/354cdf73c1a4c70e619ccd7d390cb2f416b21c1a/ESA/utils.lisp | lisp | -*- Mode: Lisp; Package: ESA-UTILS -*-
This library is free software; you can redistribute it and/or
either
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
License along with this library; if not, write to the
XXX This is currently broken with respect to declarations
Cons up the new arg list until we hit the clean-tail, then nconc that on
the end.
table would be a good idea for large amounts of observers.
Never a no-applicable-method error.
Perhaps this could be written as a single format statement?
"Modes" are a generally useful concept, so let's define some
primitives for them here.
In a perfect world, we would just combine `change-class' with
anonymous classes to transparently add and remove mode classes
(the "stealth mixin" concept). However, anonymous classes are the
some ugly hacks involving the `eval'ing of constructed `defclass'
forms, and caching the created classes to prevent memory leaking.
Avert thine eyes, thy of gentle spirit.
We're kind and put the active modes into the class name.
Take care not to add the same mode twice, this is risky enough
as it is.
Take care not to add the same mode twice, this is risky enough
as it is. |
( c ) copyright 2006 by
( )
modify it under the terms of the GNU Library General Public
version 2 of the License , or ( at your option ) any later version .
Library General Public License for more details .
You should have received a copy of the GNU Library General Public
Free Software Foundation , Inc. , 59 Temple Place - Suite 330 ,
Boston , MA 02111 - 1307 USA .
Miscellaneous utilities used in ESA .
(in-package :esa-utils)
Cribbed from
(defmacro with-gensyms (syms &body body)
`(let ,(mapcar #'(lambda (s) `(,s (gensym))) syms)
,@body))
Cribbed from PCL by Seibel
(defmacro once-only ((&rest names) &body body)
(let ((gensyms (loop for n in names collect (gensym))))
`(let (,@(loop for g in gensyms collect `(,g (gensym))))
`(let (,,@(loop for g in gensyms for n in names collect ``(,,g ,,n)))
,(let (,@(loop for n in names for g in gensyms collect `(,n ,g)))
,@body)))))
(defun unlisted (obj &optional (fn #'first))
(if (listp obj)
(funcall fn obj)
obj))
(defun fully-unlisted (obj &optional (fn #'first))
(if (listp obj)
(fully-unlisted (funcall fn obj))
obj))
(defun listed (obj)
(if (listp obj)
obj
(list obj)))
(defun list-aref (list &rest subscripts)
(if subscripts
(apply #'list-aref (nth (first subscripts) list)
(rest subscripts))
list))
Cribbed from McCLIM .
(defun check-letf-form (form)
(assert (and (listp form)
(= 2 (length form)))))
(defun valueify (list)
(if (and (consp list)
(endp (rest list)))
(first list)
`(values ,@list)))
(defmacro letf ((&rest forms) &body body &environment env)
"LETF ({(Place Value)}*) Declaration* Form* During evaluation of the
Forms, SETF the Places to the result of evaluating the Value forms.
The places are SETF-ed in parallel after all of the Values are
evaluated."
(mapc #'check-letf-form forms)
(let* (init-let-form save-old-values-setf-form
new-values-set-form old-values-set-form
update-form)
(loop for (place new-value) in forms
for (vars vals store-vars writer-form reader-form)
= (multiple-value-list (get-setf-expansion place env))
for old-value-names = (mapcar (lambda (var)
(declare (ignore var))
(gensym))
store-vars)
nconc (mapcar #'list vars vals) into temp-init-let-form
nconc (copy-list store-vars) into temp-init-let-form
nconc (copy-list old-value-names) into temp-init-let-form
nconc `(,(valueify old-value-names) ,reader-form) into temp-save-old-values-setf-form
nconc `(,(valueify store-vars) ,new-value) into temp-new-values-set-form
nconc `(,(valueify store-vars) ,(valueify old-value-names)) into temp-old-values-set-form
collect writer-form into temp-update-form
finally (setq init-let-form temp-init-let-form
save-old-values-setf-form temp-save-old-values-setf-form
new-values-set-form temp-new-values-set-form
old-values-set-form temp-old-values-set-form
update-form (cons 'progn temp-update-form)))
`(let* ,init-let-form
(setf ,@save-old-values-setf-form)
(unwind-protect
(progn (setf ,@new-values-set-form)
,update-form
(progn ,@body))
(setf ,@old-values-set-form)
,update-form))))
(defun invoke-with-dynamic-bindings-1 (bindings continuation)
(let ((old-values (mapcar #'(lambda (elt)
(symbol-value (first elt)))
bindings)))
(unwind-protect (progn
(mapcar #'(lambda (elt)
(setf (symbol-value (first elt))
(funcall (second elt))))
bindings)
(funcall continuation))
(mapcar #'(lambda (elt value)
(setf (symbol-value (first elt))
value))
bindings old-values))))
(defmacro invoke-with-dynamic-bindings ((&rest bindings) &body body)
`(invoke-with-dynamic-bindings-1
,(loop for (symbol expression) in bindings
collect (list `',symbol
`#'(lambda ()
,expression)))
#'(lambda ()
,@body)))
(defmacro letf* ((&rest forms) &body body)
(if (null forms)
`(locally
,@body)
`(letf (,(car forms))
(letf* (,(cdr forms))
,@body))))
(defun display-string (string)
(with-output-to-string (result)
(loop for char across string
do (cond ((graphic-char-p char) (princ char result))
((char= char #\Space) (princ char result))
(t (prin1 char result))))))
(defun object-equal (x y)
"Case insensitive equality that doesn't require characters"
(if (characterp x)
(and (characterp y) (char-equal x y))
(eql x y)))
(defun object= (x y)
"Case sensitive equality that doesn't require characters"
(if (characterp x)
(and (characterp y) (char= x y))
(eql x y)))
(defun no-upper-p (string)
"Does STRING contain no uppercase characters"
(notany #'upper-case-p string))
(defun case-relevant-test (string)
"Returns a test function based on the search-string STRING.
If STRING contains no uppercase characters the test is case-insensitive,
otherwise it is case-sensitive."
(if (no-upper-p string)
#'object-equal
#'object=))
(defun remove-keywords (arg-list keywords)
(let ((clean-tail arg-list))
First , determine a tail in which there are no keywords to be removed .
(loop for arg-tail on arg-list by #'cddr
for (key) = arg-tail
do (when (member key keywords :test #'eq)
(setq clean-tail (cddr arg-tail))))
(loop for arg-tail on arg-list by #'cddr
for (key value) = arg-tail
if (eq arg-tail clean-tail)
nconc clean-tail
and do (loop-finish)
else if (not (member key keywords :test #'eq))
nconc (list key value)
end)))
(defmacro with-keywords-removed ((var keywords &optional (new-var var))
&body body)
"binds NEW-VAR (defaults to VAR) to VAR with the keyword arguments specified
in KEYWORDS removed."
`(let ((,new-var (remove-keywords ,var ',keywords)))
,@body))
(defun maptree (fn x)
"This auxiliary function is like MAPCAR but has two extra
( 2 ) it tries to make the
result share with the argument x as much as possible."
(if (atom x)
(funcall fn x)
(let ((a (funcall fn (car x)))
(d (maptree fn (cdr x))))
(if (and (eql a (car x)) (eql d (cdr x)))
x
(cons a d)))))
(defun subtype-compatible-p (types)
"Return true if an element of `types' is a subtype of every
other type specifier in `types'. `Types' must be a list of type
specifiers."
(some (lambda (x)
(subtypep x `(and ,@types))) types))
(defun capitalize (string)
"Return `string' with the first character
capitalized (destructively modified)."
(setf (elt string 0) (char-upcase (elt string 0)))
string)
(defun ensure-array-size (array min-size new-elem-fn)
"Ensure that `array' is at least of size `min-size'. If `array'
needs to be resized, call `new-elem-fn' with no arguments to
generate the elements of the new cells in the array. Returns
`array'. Currently, this function only works when `array' is a
vector."
(when (< (length array) min-size)
(let ((old-length (length array)))
(setf array (adjust-array array
(max (* old-length 2) min-size)))
(loop for i from old-length below (length array)
do (setf (elt array i) (funcall new-elem-fn)))))
array)
(define-method-combination values-max-min
(&optional (order ':most-specific-first))
((around (:around))
(before (:before))
(after (:after))
(primary (values-max-min) :order order :required t))
(flet ((call-methods (methods)
(mapcar (lambda (m) `(call-method ,m)) methods))
(call-vmm-methods (methods)
`(multiple-value-bind (max min)
(call-method ,(first methods))
(progn
,@(loop for m in (rest methods)
collect `(multiple-value-bind (mmax mmin)
(call-method ,m)
(setq max (max max mmax)
min (min min mmin)))))
(values max min))))
(let ((form (if (or around before after (rest primary))
`(multiple-value-prog1
(progn ,@(call-methods before)
,(call-vmm-methods primary))
(progn ,@(call-methods (reverse after))))
`(call-method ,(first primary)))))
(if around
`(call-method ,(first around) (,@(rest around) (make-method ,form)))
form))))
(defmacro retaining-value ((bound-symbol &optional initial-value) &body body)
"Evaluate `body' with `bound-symbol' bound to
`initial-value' (default NIL). Th next time `body' is evaluated,
`bound-symbol' will be bound to whatever its value was the last
time evaluation of `body' ended."
(let ((symbol (gensym)))
`(progn (unless (boundp ',symbol)
(setf (symbol-value ',symbol) ,initial-value))
(let ((,bound-symbol (symbol-value ',symbol)))
(unwind-protect (progn ,@body)
(setf (symbol-value ',symbol) ,bound-symbol))))))
(defun format-sym (format-string &rest args)
"Return `format-string' with args spliced in, where all
arguments that are symbols with have their `symbol-name' spliced
instead, this makes sure the result is correct even on systems
where read/print case is other than default."
(apply #'format nil format-string
(mapcar #'(lambda (arg)
(if (symbolp arg)
(symbol-name arg)
arg))
args)))
(defun build-menu (command-tables &rest commands)
"Create a command table inheriting commands from
`command-tables', which must be a list of command table
designators. The created command table will have a menu
consisting of `commands', elements of which must be one of:
* A named command accessible in one of `command-tables'. This may
either be a command name, or a cons of a command name and
arguments. The command will appear directly in the menu.
* A list of the symbol `:menu' and something that will evaluate
to a command table designator. This will create a submenu
showing the name and menu of the designated command table.
* A list of the symbol `:submenu', a string, and a &rest list
of the same form as `commands'. This is equivalent to `:menu'
with a call to `build-menu' with `command-tables' and
the specified list as arguments.
* A symbol `:divider', which will present a horizontal divider
line.
An error of type`command-table-error' will be signalled if a
command cannot be found in any of the provided command tables."
(labels ((get-command-name (command)
(or (loop for table in command-tables
for name = (command-line-name-for-command command table :errorp nil)
when name return name)
(error 'command-table-error
:format-string "Command ~A not found in any provided command table"
:format-arguments (list command))))
(make-menu-entry (entry)
(cond ((and (listp entry)
(eq (first entry) :menu))
(list (command-table-name (find-command-table (second entry)))
:menu (second entry)))
((and (listp entry)
(eq (first entry) :submenu))
(list (second entry)
:menu (apply #'build-menu command-tables
(cddr entry))))
((eq entry :divider)
'(nil :divider :line))
(t (list (get-command-name (command-name (listed entry)))
:command entry)))))
(make-command-table nil
:inherit-from command-tables
:menu (mapcar #'make-menu-entry commands))))
(defmacro define-menu-table (name (&rest command-tables) &body commands)
"Define a command table with a menu named `name' and containing
`commands'. `Command-tables' must be a list of command table
designators containing the named commands that will be included
in the menu. `Commands' must have the same format as the
`commands' argument to `build-menu'. If `name' already names a
command table, the old definition will be destroyed."
`(make-command-table ',name
:inherit-from (list (build-menu ',command-tables
,@commands))
:inherit-menu t
:errorp nil))
(defclass observable-mixin ()
((%observers :accessor observers
:initform '()))
(:documentation "A mixin class that adds the capability for a
subclass to have a list of \"event subscribers\" (observers) that
can be informed via callback (the function `observer-notified')
whenever the state of the object changes. The order in which
observers will be notified is undefined."))
(defgeneric add-observer (observable observer)
(:documentation "Add an observer to an observable object. If
the observer is already observing `observable', it will not be
added again."))
(defmethod add-observer ((observable observable-mixin) observer)
Linear in complexity , perhaps a transparent switch to a hash
(pushnew observer (observers observable)))
(defgeneric remove-observer (observable observer)
(:documentation "Remove an observer from an observable
object. If observer is not in the list of observers of
`observable', nothing will happen."))
(defmethod remove-observer ((observable observable-mixin) observer)
(setf (observers observable)
(delete observer (observers observable))))
(defgeneric observer-notified (observer observable data)
(:documentation "This function is called by `observable' when
its state changes on each observer that is observing
it. `Observer' is the observing object, `observable' is the
observed object. `Data' is arbitrary data that might be of
interest to `observer', it is recommended that subclasses of
`observable-mixin' specify exactly which form this data will
take, the observer protocol does not guarantee anything. It is
non-&optional so that methods may be specialised on it, if
applicable. The default method on this function is a no-op, so it
is never an error to not define a method on this generic function
for an observer.")
(:method (observer (observable observable-mixin) data)
nil))
(defgeneric notify-observers (observable &optional data-fn)
(:documentation "Notify each observer of `observable' by
calling `observer-notified' on them. `Data-fn' will be called,
with the observer as the single argument, to obtain the `data'
argument to `observer-notified'. The default value of `data-fn'
should cause the `data' argument to be NIL."))
(defmethod notify-observers ((observable observable-mixin)
&optional (data-fn (constantly nil)))
(dolist (observer (observers observable))
(observer-notified observer observable
(funcall data-fn observer))))
(defclass name-mixin ()
((%name :accessor name
:initarg :name
:type string
:documentation "The name of the named object."))
(:documentation "A class used for defining named objects."))
(defclass subscriptable-name-mixin (name-mixin)
((%subscript :accessor subscript
:documentation "The subscript of the named object.")
(%subscript-generator :accessor subscript-generator
:initarg :subscript-generator
:initform (constantly 1)
:documentation "A function used for
finding the subscript of a `name-mixin' whenever the name is
set (including during object initialization). This function will
be called with the name as the single argument."))
(:documentation "A class used for defining named objects. A
facility is provided for assigning a named object a \"subscript\"
uniquely identifying the object if there are other objects of the
same name in its collection (in particular, if an editor has two
buffers with the same name)."))
(defmethod initialize-instance :after ((name-mixin subscriptable-name-mixin)
&rest initargs)
(declare (ignore initargs))
(setf (subscript name-mixin)
(funcall (subscript-generator name-mixin) (name name-mixin))))
(defmethod subscripted-name ((name-mixin subscriptable-name-mixin))
(if (/= (subscript name-mixin) 1)
(format nil "~A <~D>" (name name-mixin) (subscript name-mixin))
(name name-mixin)))
(defmethod (setf name) :after (new-name (name-mixin subscriptable-name-mixin))
(setf (subscript name-mixin)
(funcall (subscript-generator name-mixin) new-name)))
(defclass mode ()
()
(:documentation "A superclass for all modes."))
(defconstant +default-modes-plist-symbol+ 'modual-class-default-modes
"The symbol that is pushed onto the property list of the name
of a class to contain the list of default modes for the class.")
(defun default-modes (modual-class)
"Return the list of default modes for `modual-class', which
must be a symbol and the name of a modual class. The modes are
returned as a list of conses, with the car of each cons being the
name of the mode as a symbol, and the cdr of each cons being a
list of initargs"
(getf (symbol-plist modual-class) +default-modes-plist-symbol+))
(defun (setf default-modes) (new-default-modes modual-class)
"Set the list of default modes for `modual-class', which must
be a symbol and the name of a modual class. The modes should be
given as a list of conses, with the car of each cons being the
name of the mode as a symbol, and the cdr of each cons being a
list of initargs"
(setf (getf (symbol-plist modual-class) +default-modes-plist-symbol+)
new-default-modes))
(defclass modual-class (standard-class)
()
(:documentation "A metaclass for defining classes supporting
changing of modes."))
(defmethod validate-superclass ((c1 modual-class) (c2 standard-class))
t)
(defmethod compute-slots ((c modual-class))
(append (call-next-method)
(list (make-instance 'standard-effective-slot-definition
:name '%original-class-name
:allocation :instance
:documentation "The original name of the class
the `modual-mixin' is part of, the actual name will change as
modes are added and removed."))))
(defmethod make-instance ((class modual-class) &rest initargs)
(declare (ignore initargs))
(let ((instance (call-next-method)))
(setf (slot-value instance '%original-class-name)
(class-name class))
(dolist (class (reverse (class-precedence-list class)) instance)
(when (symbolp (class-name class))
(dolist (mode-and-initargs (default-modes (class-name class)))
(apply #'enable-mode instance (first mode-and-initargs)
(rest mode-and-initargs)))))))
(defgeneric available-modes (modual)
(:documentation "Return all available modes for `modual'. Not
all of the modes may be applicable, use the `applicable-modes'
function if you're only interested in these.")
(:method-combination append)
(:method append ((modual t))
'()))
(defgeneric mode-directly-applicable-p (modual mode-name)
(:documentation "Return true if the mode of the name
`mode-name' can be directly enabled for `modual'. If the mode of
name `mode-name' is unapplicable, an error of type
`nonapplicable-mode' will be signalled. This allows a sort of
\"opt-out\" where a mode can forcefully prevent another specific
mode from being enabled. ")
(:method-combination or)
(:method or ((modual t) mode-name)
nil))
(defgeneric mode-applicable-p (modual mode-name)
(:documentation "Return true if the mode of the name
`mode-name' can be enabled for `modual' or some sub-object of
`modual'. If the mode of name `mode-name' is unapplicable, an
error of type `nonapplicable-mode' will be signalled. This allows
a sort of \"opt-out\" where a mode can forcefully prevent another
specific mode from being enabled. ")
(:method-combination or)
(:method or ((modual t) mode-name)
(mode-directly-applicable-p modual mode-name)))
(defgeneric enabled-modes (modual)
(:documentation "Return a list of the names of the modes
directly enabled for `modual'.")
(:method ((modual t))
'()))
(defgeneric mode-enabled-p (modual mode-name)
(:documentation "Return true if `mode-name' is enabled for
`modual' or any modual \"sub-objects\"." )
(:method-combination or)
(:method or ((modual t) mode-name)
(member mode-name (enabled-modes modual) :test #'equal)))
(define-condition nonapplicable-mode (error)
((%modual :accessor modual
:initarg :modual
:initform (error "The modual used in the error-causing operation must be supplied")
:documentation "The modual that the mode is attempted to be enabled for")
(%mode-name :accessor mode-name
:initarg :mode-name
:initform (error "The name of the problematic mode must be supplied")
:documentation "The name of the mode that cannot be enabled for the view"))
(:documentation "This error is signalled if a mode is attempted
enabled for a modual that the mode is not applicable to.")
(:report (lambda (condition stream)
(format
stream "The mode ~A is not applicable for ~A"
(mode-name condition) (modual condition)))))
(defun nonapplicable-mode (modual mode-name)
"Signal an error of type `nonapplicable-mode' with `modual' and
`mode-name' as arguments."
(error 'nonapplicable-mode :modual modual :mode-name mode-name))
(defgeneric enable-mode (modual mode-name &rest initargs)
(:documentation "Enable the mode of the name `mode-name' for
`modual', using `initargs' as options for the mode. If the mode
is already enabled, do nothing. If the mode is not applicable to
`modual', signal an `nonapplicable-mode' error.")
(:method :around ((modual t) mode-name &rest initargs)
(declare (ignore initargs))
(unless (mode-enabled-p modual mode-name)
(call-next-method))))
(defgeneric disable-mode (modual mode-name)
(:documentation "Disable the mode of the name `mode-name' for
`modual'. If a mode of the provided name is not enabled, do
nothing.")
(:method :around ((modual t) mode-name)
(when (mode-enabled-p modual mode-name)
(call-next-method))))
ugly child of CL , not well supported at all , so we 'll have to do
(defvar *class-cache* (make-hash-table :test #'equal)
"A hash table mapping the name of a \"modual\" class to a
second hash table. This second hash table maps a list of mode
names to a class implementing this particular set of modes for
the modual class. Note that the order in which the modes appear
in the list is significant.")
(defun make-class-implementing-modes (modual modes)
"Generate a class that is a subclass of `modual' that
implements all the modes listed as names in `modes'."
(if (null modes)
(find-class modual)
(eval `(defclass ,(gensym (format nil "~A~{-~A~}" (string modual) modes))
(,modual ,@modes)
((%enabled-modes :reader enabled-modes
:initform ',modes))
(:metaclass modual-class)))))
(defun find-class-implementing-modes (modual modes)
"Find, possibly create, the class implementing `modual' (a
class name) with `modes' (a list of mode names) as the enabled
modes."
(let* ((modual-cache-hit (gethash modual *class-cache*))
(modes-cache-hit (and modual-cache-hit
(gethash modes modual-cache-hit))))
(or modes-cache-hit
(setf (gethash modes
(or modual-cache-hit
(setf (gethash modual *class-cache*)
(make-hash-table :test #'equal))))
(make-class-implementing-modes modual modes)))))
(defun change-class-for-enabled-mode (modual mode-name &rest initargs)
"Change the class of `modual' so that it has a mode of name
`mode-name', created with the provided `initargs'."
(apply #'change-class modual (find-class-implementing-modes
(slot-value modual '%original-class-name)
(cons mode-name (enabled-modes modual)))
initargs))
(defun change-class-for-disabled-mode (modual mode-name)
"Change the class of `modual' so that it does not have a mode
of name `mode-name'."
(change-class modual (find-class-implementing-modes
(slot-value modual '%original-class-name)
(remove mode-name (enabled-modes modual)
:test #'equal))))
(defmethod enable-mode ((modual t) mode-name &rest initargs)
(if (mode-directly-applicable-p modual mode-name)
(apply #'change-class-for-enabled-mode modual mode-name initargs)
(nonapplicable-mode modual mode-name)))
(defmethod disable-mode ((modual t) mode-name)
(when (mode-directly-applicable-p modual mode-name)
(change-class-for-disabled-mode modual mode-name)))
(defmacro add-default-modes (modual-class &body modes)
"Add `modes' to the list of default modes for
`modual-class'. Will not replace any already existing modes. The
elements in `modes' can either be a single symbol, the name of a
mode, or a cons of the name of a mode and a list of initargs for
the mode. In the former case, no initargs will be given. Please
do not use default modes as a programming tool, they should be
reserved for user-oriented functionality."
(dolist (mode modes)
(let ((mode-name (unlisted mode)))
(check-type mode-name symbol)
(setf (default-modes modual-class)
(cons (listed mode)
(delete mode-name (default-modes modual-class) :key #'first))))))
(defmacro remove-default-modes (modual-class &body modes)
"Remove `modes' from the list of default modes for
`modual-class'. `Modes' must be a list of names of modes in the
form of symbols. If a provided mode is not set as a default mode,
nothing will be done."
(dolist (mode modes)
(check-type mode symbol)
(setf (default-modes modual-class)
(delete mode (default-modes modual-class) :key #'first))))
|
e6294387729d6b86c251c03e79a7a8481948a5c63d185c221fdf3c8cccea15d5 | sjl/coding-math | make-quickutils.lisp | (ql:quickload 'quickutil)
(qtlc:save-utils-as
"quickutils.lisp"
:utilities '(:define-constant
:switch
; :while
:ensure-boolean
:with-gensyms
:once-only
:iota
:curry
:rcurry
:compose
:n-grams
)
:package "CODING-MATH.QUICKUTILS")
| null | https://raw.githubusercontent.com/sjl/coding-math/8e2add14d033da41cb3ac0aac63ad67edb4dd66a/make-quickutils.lisp | lisp | :while | (ql:quickload 'quickutil)
(qtlc:save-utils-as
"quickutils.lisp"
:utilities '(:define-constant
:switch
:ensure-boolean
:with-gensyms
:once-only
:iota
:curry
:rcurry
:compose
:n-grams
)
:package "CODING-MATH.QUICKUTILS")
|
b2395cf6a4bd56aa54ae46380b8535129344ded04eb1081f96ecd2f6222bb22c | Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library | InvoicesPaymentMethodOptions.hs | {-# LANGUAGE MultiWayIf #-}
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
{-# LANGUAGE OverloadedStrings #-}
-- | Contains the types generated from the schema InvoicesPaymentMethodOptions
module StripeAPI.Types.InvoicesPaymentMethodOptions where
import qualified Control.Monad.Fail
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified StripeAPI.Common
import StripeAPI.TypeAlias
import {-# SOURCE #-} StripeAPI.Types.InvoicePaymentMethodOptionsAcssDebit
import {-# SOURCE #-} StripeAPI.Types.InvoicePaymentMethodOptionsAcssDebitMandateOptions
import {-# SOURCE #-} StripeAPI.Types.InvoicePaymentMethodOptionsBancontact
import {-# SOURCE #-} StripeAPI.Types.InvoicePaymentMethodOptionsCard
import {-# SOURCE #-} StripeAPI.Types.InvoicePaymentMethodOptionsCustomerBalance
import {-# SOURCE #-} StripeAPI.Types.InvoicePaymentMethodOptionsCustomerBalanceBankTransfer
import {-# SOURCE #-} StripeAPI.Types.InvoicePaymentMethodOptionsUsBankAccount
import {-# SOURCE #-} StripeAPI.Types.InvoicePaymentMethodOptionsUsBankAccountLinkedAccountOptions
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
-- | Defines the object schema located at @components.schemas.invoices_payment_method_options@ in the specification.
data InvoicesPaymentMethodOptions = InvoicesPaymentMethodOptions
| acss_debit : If paying by \`acss_debit\ ` , this sub - hash contains details about the Canadian pre - authorized debit payment method options to pass to the invoice ’s PaymentIntent .
invoicesPaymentMethodOptionsAcssDebit :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable InvoicesPaymentMethodOptionsAcssDebit'NonNullable)),
| bancontact : If paying by ` , this sub - hash contains details about the payment method options to pass to the invoice ’s PaymentIntent .
invoicesPaymentMethodOptionsBancontact :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable InvoicesPaymentMethodOptionsBancontact'NonNullable)),
| card : If paying by , this sub - hash contains details about the Card payment method options to pass to the invoice ’s PaymentIntent .
invoicesPaymentMethodOptionsCard :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable InvoicesPaymentMethodOptionsCard'NonNullable)),
| customer_balance : If paying by \`customer_balance\ ` , this sub - hash contains details about the Bank transfer payment method options to pass to the invoice ’s PaymentIntent .
invoicesPaymentMethodOptionsCustomerBalance :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable InvoicesPaymentMethodOptionsCustomerBalance'NonNullable)),
| konbini : If paying by \`konbini\ ` , this sub - hash contains details about the Konbini payment method options to pass to the invoice ’s PaymentIntent .
invoicesPaymentMethodOptionsKonbini :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Aeson.Types.Internal.Object)),
| us_bank_account : If paying by \`us_bank_account\ ` , this sub - hash contains details about the ACH direct debit payment method options to pass to the invoice ’s PaymentIntent .
invoicesPaymentMethodOptionsUsBankAccount :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable InvoicesPaymentMethodOptionsUsBankAccount'NonNullable))
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptions where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("acss_debit" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsAcssDebit obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("bancontact" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsBancontact obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("card" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCard obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("customer_balance" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCustomerBalance obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("konbini" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsKonbini obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("us_bank_account" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsUsBankAccount obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("acss_debit" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsAcssDebit obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("bancontact" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsBancontact obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("card" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCard obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("customer_balance" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCustomerBalance obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("konbini" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsKonbini obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("us_bank_account" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsUsBankAccount obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptions where
parseJSON = Data.Aeson.Types.FromJSON.withObject "InvoicesPaymentMethodOptions" (\obj -> (((((GHC.Base.pure InvoicesPaymentMethodOptions GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "acss_debit")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "bancontact")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "card")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "customer_balance")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "konbini")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "us_bank_account"))
-- | Create a new 'InvoicesPaymentMethodOptions' with all required fields.
mkInvoicesPaymentMethodOptions :: InvoicesPaymentMethodOptions
mkInvoicesPaymentMethodOptions =
InvoicesPaymentMethodOptions
{ invoicesPaymentMethodOptionsAcssDebit = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsBancontact = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsCard = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsCustomerBalance = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsKonbini = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsUsBankAccount = GHC.Maybe.Nothing
}
-- | Defines the object schema located at @components.schemas.invoices_payment_method_options.properties.acss_debit.anyOf@ in the specification.
--
If paying by \\\`acss_debit\\\ ` , this sub - hash contains details about the Canadian pre - authorized debit payment method options to pass to the invoice ’s PaymentIntent .
data InvoicesPaymentMethodOptionsAcssDebit'NonNullable = InvoicesPaymentMethodOptionsAcssDebit'NonNullable
{ -- | mandate_options:
invoicesPaymentMethodOptionsAcssDebit'NonNullableMandateOptions :: (GHC.Maybe.Maybe InvoicePaymentMethodOptionsAcssDebitMandateOptions),
-- | verification_method: Bank account verification method.
invoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod :: (GHC.Maybe.Maybe InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod')
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsAcssDebit'NonNullable where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("mandate_options" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsAcssDebit'NonNullableMandateOptions obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("verification_method" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("mandate_options" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsAcssDebit'NonNullableMandateOptions obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("verification_method" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsAcssDebit'NonNullable where
parseJSON = Data.Aeson.Types.FromJSON.withObject "InvoicesPaymentMethodOptionsAcssDebit'NonNullable" (\obj -> (GHC.Base.pure InvoicesPaymentMethodOptionsAcssDebit'NonNullable GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "mandate_options")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "verification_method"))
-- | Create a new 'InvoicesPaymentMethodOptionsAcssDebit'NonNullable' with all required fields.
mkInvoicesPaymentMethodOptionsAcssDebit'NonNullable :: InvoicesPaymentMethodOptionsAcssDebit'NonNullable
mkInvoicesPaymentMethodOptionsAcssDebit'NonNullable =
InvoicesPaymentMethodOptionsAcssDebit'NonNullable
{ invoicesPaymentMethodOptionsAcssDebit'NonNullableMandateOptions = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod = GHC.Maybe.Nothing
}
| Defines the enum schema located at @components.schemas.invoices_payment_method_options.properties.acss_debit.anyOf.properties.verification_method@ in the specification .
--
Bank account verification method .
data InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'
= -- | This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'Other Data.Aeson.Types.Internal.Value
| -- | This constructor can be used to send values to the server which are not present in the specification yet.
InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'Typed Data.Text.Internal.Text
| -- | Represents the JSON value @"automatic"@
InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumAutomatic
| Represents the JSON value
InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumInstant
| -- | Represents the JSON value @"microdeposits"@
InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumMicrodeposits
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod' where
toJSON (InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'Other val) = val
toJSON (InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'Typed val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumAutomatic) = "automatic"
toJSON (InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumInstant) = "instant"
toJSON (InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumMicrodeposits) = "microdeposits"
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod' where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "automatic" -> InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumAutomatic
| val GHC.Classes.== "instant" -> InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumInstant
| val GHC.Classes.== "microdeposits" -> InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumMicrodeposits
| GHC.Base.otherwise -> InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'Other val
)
| Defines the object schema located at @components.schemas.invoices_payment_method_options.properties.bancontact.anyOf@ in the specification .
--
If paying by \\\`bancontact\\\ ` , this sub - hash contains details about the payment method options to pass to the invoice ’s PaymentIntent .
data InvoicesPaymentMethodOptionsBancontact'NonNullable = InvoicesPaymentMethodOptionsBancontact'NonNullable
| preferred_language : Preferred language of the authorization page that the customer is redirected to .
invoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage :: (GHC.Maybe.Maybe InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage')
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsBancontact'NonNullable where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("preferred_language" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("preferred_language" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsBancontact'NonNullable where
parseJSON = Data.Aeson.Types.FromJSON.withObject "InvoicesPaymentMethodOptionsBancontact'NonNullable" (\obj -> GHC.Base.pure InvoicesPaymentMethodOptionsBancontact'NonNullable GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "preferred_language"))
-- | Create a new 'InvoicesPaymentMethodOptionsBancontact'NonNullable' with all required fields.
mkInvoicesPaymentMethodOptionsBancontact'NonNullable :: InvoicesPaymentMethodOptionsBancontact'NonNullable
mkInvoicesPaymentMethodOptionsBancontact'NonNullable = InvoicesPaymentMethodOptionsBancontact'NonNullable {invoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage = GHC.Maybe.Nothing}
| Defines the enum schema located at @components.schemas.invoices_payment_method_options.properties.bancontact.anyOf.properties.preferred_language@ in the specification .
--
Preferred language of the authorization page that the customer is redirected to .
data InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'
= -- | This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'Other Data.Aeson.Types.Internal.Value
| -- | This constructor can be used to send values to the server which are not present in the specification yet.
InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'Typed Data.Text.Internal.Text
| Represents the JSON value @"de"@
InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumDe
| Represents the JSON value @"en"@
InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumEn
| -- | Represents the JSON value @"fr"@
InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumFr
| Represents the JSON value @"nl"@
InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumNl
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage' where
toJSON (InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'Other val) = val
toJSON (InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'Typed val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumDe) = "de"
toJSON (InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumEn) = "en"
toJSON (InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumFr) = "fr"
toJSON (InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumNl) = "nl"
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage' where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "de" -> InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumDe
| val GHC.Classes.== "en" -> InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumEn
| val GHC.Classes.== "fr" -> InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumFr
| val GHC.Classes.== "nl" -> InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumNl
| GHC.Base.otherwise -> InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'Other val
)
-- | Defines the object schema located at @components.schemas.invoices_payment_method_options.properties.card.anyOf@ in the specification.
--
If paying by \\\`card\\\ ` , this sub - hash contains details about the Card payment method options to pass to the invoice ’s PaymentIntent .
data InvoicesPaymentMethodOptionsCard'NonNullable = InvoicesPaymentMethodOptionsCard'NonNullable
| request_three_d_secure : We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [ other requirements](https:\/\/stripe.com\/docs\/strong - customer - authentication ) . However , if you wish to request 3D Secure based on logic from your own fraud engine , provide this option . Read our guide on [ manually requesting 3D Secure](https:\/\/stripe.com\/docs\/payments\/3d - secure\#manual - three - ds ) for more information on how this configuration interacts with Radar and our SCA Engine .
invoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullable))
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsCard'NonNullable where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("request_three_d_secure" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("request_three_d_secure" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsCard'NonNullable where
parseJSON = Data.Aeson.Types.FromJSON.withObject "InvoicesPaymentMethodOptionsCard'NonNullable" (\obj -> GHC.Base.pure InvoicesPaymentMethodOptionsCard'NonNullable GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "request_three_d_secure"))
| Create a new ' InvoicesPaymentMethodOptionsCard'NonNullable ' with all required fields .
mkInvoicesPaymentMethodOptionsCard'NonNullable :: InvoicesPaymentMethodOptionsCard'NonNullable
mkInvoicesPaymentMethodOptionsCard'NonNullable = InvoicesPaymentMethodOptionsCard'NonNullable {invoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure = GHC.Maybe.Nothing}
-- | Defines the enum schema located at @components.schemas.invoices_payment_method_options.properties.card.anyOf.properties.request_three_d_secure@ in the specification.
--
We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [ other requirements](https:\/\/stripe.com\/docs\/strong - customer - authentication ) . However , if you wish to request 3D Secure based on logic from your own fraud engine , provide this option . Read our guide on [ manually requesting 3D Secure](https:\/\/stripe.com\/docs\/payments\/3d - secure\#manual - three - ds ) for more information on how this configuration interacts with Radar and our SCA Engine .
data InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullable
= -- | This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableOther Data.Aeson.Types.Internal.Value
| -- | This constructor can be used to send values to the server which are not present in the specification yet.
InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableTyped Data.Text.Internal.Text
| Represents the JSON value @"any"@
InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableEnumAny
| -- | Represents the JSON value @"automatic"@
InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableEnumAutomatic
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullable where
toJSON (InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableOther val) = val
toJSON (InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableTyped val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableEnumAny) = "any"
toJSON (InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableEnumAutomatic) = "automatic"
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullable where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "any" -> InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableEnumAny
| val GHC.Classes.== "automatic" -> InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableEnumAutomatic
| GHC.Base.otherwise -> InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableOther val
)
| Defines the object schema located at @components.schemas.invoices_payment_method_options.properties.customer_balance.anyOf@ in the specification .
--
If paying by \\\`customer_balance\\\ ` , this sub - hash contains details about the Bank transfer payment method options to pass to the invoice ’s PaymentIntent .
data InvoicesPaymentMethodOptionsCustomerBalance'NonNullable = InvoicesPaymentMethodOptionsCustomerBalance'NonNullable
{ -- | bank_transfer:
invoicesPaymentMethodOptionsCustomerBalance'NonNullableBankTransfer :: (GHC.Maybe.Maybe InvoicePaymentMethodOptionsCustomerBalanceBankTransfer),
| funding_type : The funding method type to be used when there are not enough funds in the customer balance . Permitted values include : \`bank_transfer\ ` .
invoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullable))
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsCustomerBalance'NonNullable where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("bank_transfer" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCustomerBalance'NonNullableBankTransfer obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("funding_type" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("bank_transfer" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCustomerBalance'NonNullableBankTransfer obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("funding_type" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsCustomerBalance'NonNullable where
parseJSON = Data.Aeson.Types.FromJSON.withObject "InvoicesPaymentMethodOptionsCustomerBalance'NonNullable" (\obj -> (GHC.Base.pure InvoicesPaymentMethodOptionsCustomerBalance'NonNullable GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "bank_transfer")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "funding_type"))
-- | Create a new 'InvoicesPaymentMethodOptionsCustomerBalance'NonNullable' with all required fields.
mkInvoicesPaymentMethodOptionsCustomerBalance'NonNullable :: InvoicesPaymentMethodOptionsCustomerBalance'NonNullable
mkInvoicesPaymentMethodOptionsCustomerBalance'NonNullable =
InvoicesPaymentMethodOptionsCustomerBalance'NonNullable
{ invoicesPaymentMethodOptionsCustomerBalance'NonNullableBankTransfer = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType = GHC.Maybe.Nothing
}
-- | Defines the enum schema located at @components.schemas.invoices_payment_method_options.properties.customer_balance.anyOf.properties.funding_type@ in the specification.
--
The funding method type to be used when there are not enough funds in the customer balance . Permitted values include : \`bank_transfer\ ` .
data InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullable
= -- | This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableOther Data.Aeson.Types.Internal.Value
| -- | This constructor can be used to send values to the server which are not present in the specification yet.
InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableTyped Data.Text.Internal.Text
| -- | Represents the JSON value @"bank_transfer"@
InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableEnumBankTransfer
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullable where
toJSON (InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableOther val) = val
toJSON (InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableTyped val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableEnumBankTransfer) = "bank_transfer"
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullable where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "bank_transfer" -> InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableEnumBankTransfer
| GHC.Base.otherwise -> InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableOther val
)
-- | Defines the object schema located at @components.schemas.invoices_payment_method_options.properties.us_bank_account.anyOf@ in the specification.
--
If paying by \\\`us_bank_account\\\ ` , this sub - hash contains details about the ACH direct debit payment method options to pass to the invoice ’s PaymentIntent .
data InvoicesPaymentMethodOptionsUsBankAccount'NonNullable = InvoicesPaymentMethodOptionsUsBankAccount'NonNullable
{ -- | financial_connections:
invoicesPaymentMethodOptionsUsBankAccount'NonNullableFinancialConnections :: (GHC.Maybe.Maybe InvoicePaymentMethodOptionsUsBankAccountLinkedAccountOptions),
-- | verification_method: Bank account verification method.
invoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod :: (GHC.Maybe.Maybe InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod')
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsUsBankAccount'NonNullable where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("financial_connections" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsUsBankAccount'NonNullableFinancialConnections obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("verification_method" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("financial_connections" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsUsBankAccount'NonNullableFinancialConnections obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("verification_method" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsUsBankAccount'NonNullable where
parseJSON = Data.Aeson.Types.FromJSON.withObject "InvoicesPaymentMethodOptionsUsBankAccount'NonNullable" (\obj -> (GHC.Base.pure InvoicesPaymentMethodOptionsUsBankAccount'NonNullable GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "financial_connections")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "verification_method"))
-- | Create a new 'InvoicesPaymentMethodOptionsUsBankAccount'NonNullable' with all required fields.
mkInvoicesPaymentMethodOptionsUsBankAccount'NonNullable :: InvoicesPaymentMethodOptionsUsBankAccount'NonNullable
mkInvoicesPaymentMethodOptionsUsBankAccount'NonNullable =
InvoicesPaymentMethodOptionsUsBankAccount'NonNullable
{ invoicesPaymentMethodOptionsUsBankAccount'NonNullableFinancialConnections = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod = GHC.Maybe.Nothing
}
| Defines the enum schema located at @components.schemas.invoices_payment_method_options.properties.us_bank_account.anyOf.properties.verification_method@ in the specification .
--
Bank account verification method .
data InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'
= -- | This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'Other Data.Aeson.Types.Internal.Value
| -- | This constructor can be used to send values to the server which are not present in the specification yet.
InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'Typed Data.Text.Internal.Text
| -- | Represents the JSON value @"automatic"@
InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumAutomatic
| Represents the JSON value
InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumInstant
| -- | Represents the JSON value @"microdeposits"@
InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumMicrodeposits
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod' where
toJSON (InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'Other val) = val
toJSON (InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'Typed val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumAutomatic) = "automatic"
toJSON (InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumInstant) = "instant"
toJSON (InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumMicrodeposits) = "microdeposits"
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod' where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "automatic" -> InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumAutomatic
| val GHC.Classes.== "instant" -> InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumInstant
| val GHC.Classes.== "microdeposits" -> InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumMicrodeposits
| GHC.Base.otherwise -> InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'Other val
)
| null | https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/InvoicesPaymentMethodOptions.hs | haskell | # LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
| Contains the types generated from the schema InvoicesPaymentMethodOptions
# SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
| Defines the object schema located at @components.schemas.invoices_payment_method_options@ in the specification.
| Create a new 'InvoicesPaymentMethodOptions' with all required fields.
| Defines the object schema located at @components.schemas.invoices_payment_method_options.properties.acss_debit.anyOf@ in the specification.
| mandate_options:
| verification_method: Bank account verification method.
| Create a new 'InvoicesPaymentMethodOptionsAcssDebit'NonNullable' with all required fields.
| This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
| This constructor can be used to send values to the server which are not present in the specification yet.
| Represents the JSON value @"automatic"@
| Represents the JSON value @"microdeposits"@
| Create a new 'InvoicesPaymentMethodOptionsBancontact'NonNullable' with all required fields.
| This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
| This constructor can be used to send values to the server which are not present in the specification yet.
| Represents the JSON value @"fr"@
| Defines the object schema located at @components.schemas.invoices_payment_method_options.properties.card.anyOf@ in the specification.
| Defines the enum schema located at @components.schemas.invoices_payment_method_options.properties.card.anyOf.properties.request_three_d_secure@ in the specification.
| This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
| This constructor can be used to send values to the server which are not present in the specification yet.
| Represents the JSON value @"automatic"@
| bank_transfer:
| Create a new 'InvoicesPaymentMethodOptionsCustomerBalance'NonNullable' with all required fields.
| Defines the enum schema located at @components.schemas.invoices_payment_method_options.properties.customer_balance.anyOf.properties.funding_type@ in the specification.
| This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
| This constructor can be used to send values to the server which are not present in the specification yet.
| Represents the JSON value @"bank_transfer"@
| Defines the object schema located at @components.schemas.invoices_payment_method_options.properties.us_bank_account.anyOf@ in the specification.
| financial_connections:
| verification_method: Bank account verification method.
| Create a new 'InvoicesPaymentMethodOptionsUsBankAccount'NonNullable' with all required fields.
| This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
| This constructor can be used to send values to the server which are not present in the specification yet.
| Represents the JSON value @"automatic"@
| Represents the JSON value @"microdeposits"@ | CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
module StripeAPI.Types.InvoicesPaymentMethodOptions where
import qualified Control.Monad.Fail
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified StripeAPI.Common
import StripeAPI.TypeAlias
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
data InvoicesPaymentMethodOptions = InvoicesPaymentMethodOptions
| acss_debit : If paying by \`acss_debit\ ` , this sub - hash contains details about the Canadian pre - authorized debit payment method options to pass to the invoice ’s PaymentIntent .
invoicesPaymentMethodOptionsAcssDebit :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable InvoicesPaymentMethodOptionsAcssDebit'NonNullable)),
| bancontact : If paying by ` , this sub - hash contains details about the payment method options to pass to the invoice ’s PaymentIntent .
invoicesPaymentMethodOptionsBancontact :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable InvoicesPaymentMethodOptionsBancontact'NonNullable)),
| card : If paying by , this sub - hash contains details about the Card payment method options to pass to the invoice ’s PaymentIntent .
invoicesPaymentMethodOptionsCard :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable InvoicesPaymentMethodOptionsCard'NonNullable)),
| customer_balance : If paying by \`customer_balance\ ` , this sub - hash contains details about the Bank transfer payment method options to pass to the invoice ’s PaymentIntent .
invoicesPaymentMethodOptionsCustomerBalance :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable InvoicesPaymentMethodOptionsCustomerBalance'NonNullable)),
| konbini : If paying by \`konbini\ ` , this sub - hash contains details about the Konbini payment method options to pass to the invoice ’s PaymentIntent .
invoicesPaymentMethodOptionsKonbini :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Aeson.Types.Internal.Object)),
| us_bank_account : If paying by \`us_bank_account\ ` , this sub - hash contains details about the ACH direct debit payment method options to pass to the invoice ’s PaymentIntent .
invoicesPaymentMethodOptionsUsBankAccount :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable InvoicesPaymentMethodOptionsUsBankAccount'NonNullable))
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptions where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("acss_debit" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsAcssDebit obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("bancontact" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsBancontact obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("card" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCard obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("customer_balance" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCustomerBalance obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("konbini" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsKonbini obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("us_bank_account" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsUsBankAccount obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("acss_debit" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsAcssDebit obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("bancontact" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsBancontact obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("card" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCard obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("customer_balance" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCustomerBalance obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("konbini" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsKonbini obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("us_bank_account" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsUsBankAccount obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptions where
parseJSON = Data.Aeson.Types.FromJSON.withObject "InvoicesPaymentMethodOptions" (\obj -> (((((GHC.Base.pure InvoicesPaymentMethodOptions GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "acss_debit")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "bancontact")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "card")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "customer_balance")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "konbini")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "us_bank_account"))
mkInvoicesPaymentMethodOptions :: InvoicesPaymentMethodOptions
mkInvoicesPaymentMethodOptions =
InvoicesPaymentMethodOptions
{ invoicesPaymentMethodOptionsAcssDebit = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsBancontact = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsCard = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsCustomerBalance = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsKonbini = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsUsBankAccount = GHC.Maybe.Nothing
}
If paying by \\\`acss_debit\\\ ` , this sub - hash contains details about the Canadian pre - authorized debit payment method options to pass to the invoice ’s PaymentIntent .
data InvoicesPaymentMethodOptionsAcssDebit'NonNullable = InvoicesPaymentMethodOptionsAcssDebit'NonNullable
invoicesPaymentMethodOptionsAcssDebit'NonNullableMandateOptions :: (GHC.Maybe.Maybe InvoicePaymentMethodOptionsAcssDebitMandateOptions),
invoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod :: (GHC.Maybe.Maybe InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod')
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsAcssDebit'NonNullable where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("mandate_options" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsAcssDebit'NonNullableMandateOptions obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("verification_method" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("mandate_options" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsAcssDebit'NonNullableMandateOptions obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("verification_method" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsAcssDebit'NonNullable where
parseJSON = Data.Aeson.Types.FromJSON.withObject "InvoicesPaymentMethodOptionsAcssDebit'NonNullable" (\obj -> (GHC.Base.pure InvoicesPaymentMethodOptionsAcssDebit'NonNullable GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "mandate_options")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "verification_method"))
mkInvoicesPaymentMethodOptionsAcssDebit'NonNullable :: InvoicesPaymentMethodOptionsAcssDebit'NonNullable
mkInvoicesPaymentMethodOptionsAcssDebit'NonNullable =
InvoicesPaymentMethodOptionsAcssDebit'NonNullable
{ invoicesPaymentMethodOptionsAcssDebit'NonNullableMandateOptions = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod = GHC.Maybe.Nothing
}
| Defines the enum schema located at @components.schemas.invoices_payment_method_options.properties.acss_debit.anyOf.properties.verification_method@ in the specification .
Bank account verification method .
data InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'
InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'Other Data.Aeson.Types.Internal.Value
InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'Typed Data.Text.Internal.Text
InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumAutomatic
| Represents the JSON value
InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumInstant
InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumMicrodeposits
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod' where
toJSON (InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'Other val) = val
toJSON (InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'Typed val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumAutomatic) = "automatic"
toJSON (InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumInstant) = "instant"
toJSON (InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumMicrodeposits) = "microdeposits"
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod' where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "automatic" -> InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumAutomatic
| val GHC.Classes.== "instant" -> InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumInstant
| val GHC.Classes.== "microdeposits" -> InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'EnumMicrodeposits
| GHC.Base.otherwise -> InvoicesPaymentMethodOptionsAcssDebit'NonNullableVerificationMethod'Other val
)
| Defines the object schema located at @components.schemas.invoices_payment_method_options.properties.bancontact.anyOf@ in the specification .
If paying by \\\`bancontact\\\ ` , this sub - hash contains details about the payment method options to pass to the invoice ’s PaymentIntent .
data InvoicesPaymentMethodOptionsBancontact'NonNullable = InvoicesPaymentMethodOptionsBancontact'NonNullable
| preferred_language : Preferred language of the authorization page that the customer is redirected to .
invoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage :: (GHC.Maybe.Maybe InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage')
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsBancontact'NonNullable where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("preferred_language" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("preferred_language" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsBancontact'NonNullable where
parseJSON = Data.Aeson.Types.FromJSON.withObject "InvoicesPaymentMethodOptionsBancontact'NonNullable" (\obj -> GHC.Base.pure InvoicesPaymentMethodOptionsBancontact'NonNullable GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "preferred_language"))
mkInvoicesPaymentMethodOptionsBancontact'NonNullable :: InvoicesPaymentMethodOptionsBancontact'NonNullable
mkInvoicesPaymentMethodOptionsBancontact'NonNullable = InvoicesPaymentMethodOptionsBancontact'NonNullable {invoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage = GHC.Maybe.Nothing}
| Defines the enum schema located at @components.schemas.invoices_payment_method_options.properties.bancontact.anyOf.properties.preferred_language@ in the specification .
Preferred language of the authorization page that the customer is redirected to .
data InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'
InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'Other Data.Aeson.Types.Internal.Value
InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'Typed Data.Text.Internal.Text
| Represents the JSON value @"de"@
InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumDe
| Represents the JSON value @"en"@
InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumEn
InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumFr
| Represents the JSON value @"nl"@
InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumNl
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage' where
toJSON (InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'Other val) = val
toJSON (InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'Typed val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumDe) = "de"
toJSON (InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumEn) = "en"
toJSON (InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumFr) = "fr"
toJSON (InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumNl) = "nl"
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage' where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "de" -> InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumDe
| val GHC.Classes.== "en" -> InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumEn
| val GHC.Classes.== "fr" -> InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumFr
| val GHC.Classes.== "nl" -> InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'EnumNl
| GHC.Base.otherwise -> InvoicesPaymentMethodOptionsBancontact'NonNullablePreferredLanguage'Other val
)
If paying by \\\`card\\\ ` , this sub - hash contains details about the Card payment method options to pass to the invoice ’s PaymentIntent .
data InvoicesPaymentMethodOptionsCard'NonNullable = InvoicesPaymentMethodOptionsCard'NonNullable
| request_three_d_secure : We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [ other requirements](https:\/\/stripe.com\/docs\/strong - customer - authentication ) . However , if you wish to request 3D Secure based on logic from your own fraud engine , provide this option . Read our guide on [ manually requesting 3D Secure](https:\/\/stripe.com\/docs\/payments\/3d - secure\#manual - three - ds ) for more information on how this configuration interacts with Radar and our SCA Engine .
invoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullable))
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsCard'NonNullable where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("request_three_d_secure" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("request_three_d_secure" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsCard'NonNullable where
parseJSON = Data.Aeson.Types.FromJSON.withObject "InvoicesPaymentMethodOptionsCard'NonNullable" (\obj -> GHC.Base.pure InvoicesPaymentMethodOptionsCard'NonNullable GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "request_three_d_secure"))
| Create a new ' InvoicesPaymentMethodOptionsCard'NonNullable ' with all required fields .
mkInvoicesPaymentMethodOptionsCard'NonNullable :: InvoicesPaymentMethodOptionsCard'NonNullable
mkInvoicesPaymentMethodOptionsCard'NonNullable = InvoicesPaymentMethodOptionsCard'NonNullable {invoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure = GHC.Maybe.Nothing}
We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [ other requirements](https:\/\/stripe.com\/docs\/strong - customer - authentication ) . However , if you wish to request 3D Secure based on logic from your own fraud engine , provide this option . Read our guide on [ manually requesting 3D Secure](https:\/\/stripe.com\/docs\/payments\/3d - secure\#manual - three - ds ) for more information on how this configuration interacts with Radar and our SCA Engine .
data InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullable
InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableOther Data.Aeson.Types.Internal.Value
InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableTyped Data.Text.Internal.Text
| Represents the JSON value @"any"@
InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableEnumAny
InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableEnumAutomatic
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullable where
toJSON (InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableOther val) = val
toJSON (InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableTyped val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableEnumAny) = "any"
toJSON (InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableEnumAutomatic) = "automatic"
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullable where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "any" -> InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableEnumAny
| val GHC.Classes.== "automatic" -> InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableEnumAutomatic
| GHC.Base.otherwise -> InvoicesPaymentMethodOptionsCard'NonNullableRequestThreeDSecure'NonNullableOther val
)
| Defines the object schema located at @components.schemas.invoices_payment_method_options.properties.customer_balance.anyOf@ in the specification .
If paying by \\\`customer_balance\\\ ` , this sub - hash contains details about the Bank transfer payment method options to pass to the invoice ’s PaymentIntent .
data InvoicesPaymentMethodOptionsCustomerBalance'NonNullable = InvoicesPaymentMethodOptionsCustomerBalance'NonNullable
invoicesPaymentMethodOptionsCustomerBalance'NonNullableBankTransfer :: (GHC.Maybe.Maybe InvoicePaymentMethodOptionsCustomerBalanceBankTransfer),
| funding_type : The funding method type to be used when there are not enough funds in the customer balance . Permitted values include : \`bank_transfer\ ` .
invoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullable))
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsCustomerBalance'NonNullable where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("bank_transfer" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCustomerBalance'NonNullableBankTransfer obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("funding_type" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("bank_transfer" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCustomerBalance'NonNullableBankTransfer obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("funding_type" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsCustomerBalance'NonNullable where
parseJSON = Data.Aeson.Types.FromJSON.withObject "InvoicesPaymentMethodOptionsCustomerBalance'NonNullable" (\obj -> (GHC.Base.pure InvoicesPaymentMethodOptionsCustomerBalance'NonNullable GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "bank_transfer")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "funding_type"))
mkInvoicesPaymentMethodOptionsCustomerBalance'NonNullable :: InvoicesPaymentMethodOptionsCustomerBalance'NonNullable
mkInvoicesPaymentMethodOptionsCustomerBalance'NonNullable =
InvoicesPaymentMethodOptionsCustomerBalance'NonNullable
{ invoicesPaymentMethodOptionsCustomerBalance'NonNullableBankTransfer = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType = GHC.Maybe.Nothing
}
The funding method type to be used when there are not enough funds in the customer balance . Permitted values include : \`bank_transfer\ ` .
data InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullable
InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableOther Data.Aeson.Types.Internal.Value
InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableTyped Data.Text.Internal.Text
InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableEnumBankTransfer
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullable where
toJSON (InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableOther val) = val
toJSON (InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableTyped val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableEnumBankTransfer) = "bank_transfer"
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullable where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "bank_transfer" -> InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableEnumBankTransfer
| GHC.Base.otherwise -> InvoicesPaymentMethodOptionsCustomerBalance'NonNullableFundingType'NonNullableOther val
)
If paying by \\\`us_bank_account\\\ ` , this sub - hash contains details about the ACH direct debit payment method options to pass to the invoice ’s PaymentIntent .
data InvoicesPaymentMethodOptionsUsBankAccount'NonNullable = InvoicesPaymentMethodOptionsUsBankAccount'NonNullable
invoicesPaymentMethodOptionsUsBankAccount'NonNullableFinancialConnections :: (GHC.Maybe.Maybe InvoicePaymentMethodOptionsUsBankAccountLinkedAccountOptions),
invoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod :: (GHC.Maybe.Maybe InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod')
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsUsBankAccount'NonNullable where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("financial_connections" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsUsBankAccount'NonNullableFinancialConnections obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("verification_method" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("financial_connections" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsUsBankAccount'NonNullableFinancialConnections obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("verification_method" Data.Aeson.Types.ToJSON..=)) (invoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsUsBankAccount'NonNullable where
parseJSON = Data.Aeson.Types.FromJSON.withObject "InvoicesPaymentMethodOptionsUsBankAccount'NonNullable" (\obj -> (GHC.Base.pure InvoicesPaymentMethodOptionsUsBankAccount'NonNullable GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "financial_connections")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "verification_method"))
mkInvoicesPaymentMethodOptionsUsBankAccount'NonNullable :: InvoicesPaymentMethodOptionsUsBankAccount'NonNullable
mkInvoicesPaymentMethodOptionsUsBankAccount'NonNullable =
InvoicesPaymentMethodOptionsUsBankAccount'NonNullable
{ invoicesPaymentMethodOptionsUsBankAccount'NonNullableFinancialConnections = GHC.Maybe.Nothing,
invoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod = GHC.Maybe.Nothing
}
| Defines the enum schema located at @components.schemas.invoices_payment_method_options.properties.us_bank_account.anyOf.properties.verification_method@ in the specification .
Bank account verification method .
data InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'
InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'Other Data.Aeson.Types.Internal.Value
InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'Typed Data.Text.Internal.Text
InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumAutomatic
| Represents the JSON value
InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumInstant
InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumMicrodeposits
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod' where
toJSON (InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'Other val) = val
toJSON (InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'Typed val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumAutomatic) = "automatic"
toJSON (InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumInstant) = "instant"
toJSON (InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumMicrodeposits) = "microdeposits"
instance Data.Aeson.Types.FromJSON.FromJSON InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod' where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "automatic" -> InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumAutomatic
| val GHC.Classes.== "instant" -> InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumInstant
| val GHC.Classes.== "microdeposits" -> InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'EnumMicrodeposits
| GHC.Base.otherwise -> InvoicesPaymentMethodOptionsUsBankAccount'NonNullableVerificationMethod'Other val
)
|
a8f9dcaa04eedbfd265d0fb82671357e4eca53c7ac55028864c4380a22653f9a | objecthub/swift-lispkit | EUStats.scm | ;;; Text table demo
;;;
;;; This is a short example showcasing how library `(lispkit text-tables)` works.
;;; A new text table is created and populated with data from countries of the
European Union . Finally , the text table is printed on the console .
;;;
Author :
Copyright © 2021 . 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.
(import (lispkit base)
(lispkit text-table))
Make a new text table , consisting of four columns
(define eu (make-text-table
'(("Country" center left)
("Population\n(millions)" center right)
("Area\n(km²)" center right)
("Density\n(people/km²)" center right))
double-line-sep
round-edges))
;; Populate the text table with rows
(add-text-table-row! eu '("Austria" "8.3" "83,858" "99"))
(add-text-table-row! eu '("Belgium" "10.5" "30,510" "344"))
(add-text-table-row! eu '("Bulgaria" "7.7" "110,912" "70"))
(add-text-table-row! eu '("Croatia" "4.3" "56,594" "75.8"))
(add-text-table-row! eu '("Cyprus" "0.8" "9,250" "84"))
(add-text-table-row! eu '("Czech Republic" "10.3" "78,866" "131"))
(add-text-table-row! eu '("Denmark" "5.4" "43,094" "126"))
(add-text-table-row! eu '("Estonia" "1.3" "45,226" "29"))
(add-text-table-row! eu '("Finland" "5.3" "337,030" "16"))
(add-text-table-row! eu '("France" "65.03" "643,548" "111"))
(add-text-table-row! eu '("Germany" "80.4" "357,021" "225"))
(add-text-table-row! eu '("Greece" "11.1" "131,940" "84"))
(add-text-table-row! eu '("Hungary" "10.1" "93,030" "108"))
(add-text-table-row! eu '("Ireland" "4.6" "70,280" "60"))
(add-text-table-row! eu '("Italy" "58.8" "301,320" "195"))
(add-text-table-row! eu '("Latvia" "2.3" "64,589" "35"))
(add-text-table-row! eu '("Lithuania" "3.4" "65,200" "45"))
(add-text-table-row! eu '("Luxembourg" "0.5" "2,586" "181"))
(add-text-table-row! eu '("Malta" "0.5" "316" "1,261"))
(add-text-table-row! eu '("Netherlands" "17" "41,526" "394"))
(add-text-table-row! eu '("Poland" "38.1" "312,685" "122"))
(add-text-table-row! eu '("Portugal" "10.6" "92,931" "114"))
(add-text-table-row! eu '("Romania" "21.6" "238,391" "91"))
(add-text-table-row! eu '("Spain" "44.7" "504,782" "87"))
(add-text-table-row! eu '("Slovakia" "5.4" "48,845" "111"))
(add-text-table-row! eu '("Slovenia" "2.0" "20,253" "99"))
(add-text-table-row! eu '("Sweden" "10" "449,964" "20"))
(add-text-table-separator! eu line-sep)
(add-text-table-row! eu '("European Union" "494.8" "4,422,773" "112"))
;; Display the text table on the console
(display (text-table->string eu))
(newline)
| null | https://raw.githubusercontent.com/objecthub/swift-lispkit/c9a3dc13216e121da266244d576ad032322ab77c/Sources/LispKit/Resources/Examples/EUStats.scm | scheme | Text table demo
This is a short example showcasing how library `(lispkit text-tables)` works.
A new text table is created and populated with data from countries of the
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
either express or implied. See the License for the specific language governing permissions
and limitations under the License.
Populate the text table with rows
Display the text table on the console | European Union . Finally , the text table is printed on the console .
Author :
Copyright © 2021 . All rights reserved .
License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND ,
(import (lispkit base)
(lispkit text-table))
Make a new text table , consisting of four columns
(define eu (make-text-table
'(("Country" center left)
("Population\n(millions)" center right)
("Area\n(km²)" center right)
("Density\n(people/km²)" center right))
double-line-sep
round-edges))
(add-text-table-row! eu '("Austria" "8.3" "83,858" "99"))
(add-text-table-row! eu '("Belgium" "10.5" "30,510" "344"))
(add-text-table-row! eu '("Bulgaria" "7.7" "110,912" "70"))
(add-text-table-row! eu '("Croatia" "4.3" "56,594" "75.8"))
(add-text-table-row! eu '("Cyprus" "0.8" "9,250" "84"))
(add-text-table-row! eu '("Czech Republic" "10.3" "78,866" "131"))
(add-text-table-row! eu '("Denmark" "5.4" "43,094" "126"))
(add-text-table-row! eu '("Estonia" "1.3" "45,226" "29"))
(add-text-table-row! eu '("Finland" "5.3" "337,030" "16"))
(add-text-table-row! eu '("France" "65.03" "643,548" "111"))
(add-text-table-row! eu '("Germany" "80.4" "357,021" "225"))
(add-text-table-row! eu '("Greece" "11.1" "131,940" "84"))
(add-text-table-row! eu '("Hungary" "10.1" "93,030" "108"))
(add-text-table-row! eu '("Ireland" "4.6" "70,280" "60"))
(add-text-table-row! eu '("Italy" "58.8" "301,320" "195"))
(add-text-table-row! eu '("Latvia" "2.3" "64,589" "35"))
(add-text-table-row! eu '("Lithuania" "3.4" "65,200" "45"))
(add-text-table-row! eu '("Luxembourg" "0.5" "2,586" "181"))
(add-text-table-row! eu '("Malta" "0.5" "316" "1,261"))
(add-text-table-row! eu '("Netherlands" "17" "41,526" "394"))
(add-text-table-row! eu '("Poland" "38.1" "312,685" "122"))
(add-text-table-row! eu '("Portugal" "10.6" "92,931" "114"))
(add-text-table-row! eu '("Romania" "21.6" "238,391" "91"))
(add-text-table-row! eu '("Spain" "44.7" "504,782" "87"))
(add-text-table-row! eu '("Slovakia" "5.4" "48,845" "111"))
(add-text-table-row! eu '("Slovenia" "2.0" "20,253" "99"))
(add-text-table-row! eu '("Sweden" "10" "449,964" "20"))
(add-text-table-separator! eu line-sep)
(add-text-table-row! eu '("European Union" "494.8" "4,422,773" "112"))
(display (text-table->string eu))
(newline)
|
45d712d6b1775cca3fea1e5a1496721d3fe6902ce148862f640dbf14734829e6 | cs136/seashell | updates.rkt | #lang typed/racket
Seashell 's SQLite3 + Dexie bindings .
Copyright ( C ) 2013 - 2015 The Seashell Maintainers .
;;
;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;; (at your option) any later version.
;;
;; See also 'ADDITIONAL TERMS' at the end of the included LICENSE file.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
You should have received a copy of the GNU General Public License
;; along with this program. If not, see </>.
(require typed/json)
(require typed/db)
(require typed/db/sqlite3)
(require "support.rkt")
(provide apply-modifications
fold-create-and-update
fold-update-and-update)
;; (apply-modifications object updates) -> newObject
Given an JSON object and a JSON object representing updates as { key : } pairs
;; applies the updates and returns the resulting object as a string.
;;
;; Arguments:
object - JSON object to update , as JSExpr | String .
updates - Updates to apply , as either a JSExpr HashTable or a String .
(: apply-modifications (-> (U String JSExpr) (U String (HashTable Symbol JSExpr)) String))
(define (apply-modifications _object _updates)
(define updates (assert (jsexpr-or-string->jsexpr _updates) hash?))
(for/fold ([object (string-or-jsexpr->string _object)])
([(_key _value) (in-hash updates)])
(define key-path (symbol->string _key))
(define update (jsexpr->string _value))
(set-by-key-path object key-path update)))
( fold - update - and - update first second ) - > newUpdate
;; Given a create and an update on the same object, returns the CREATE change
;; that is the result of applying the update on the create.
;;
;; Arguments:
first , second - Updates to apply , as JSExpr | String .
(: fold-create-and-update (-> (U String JSExpr) (U String (HashTable Symbol JSExpr)) String))
(define (fold-create-and-update object update)
(apply-modifications object update))
( fold - update - and - update first second ) - > newUpdate
Given two updates to apply on a JSON object , returns the update that is the result
of applying the first update followed by the second update .
;;
;; Arguments:
first , second - Updates to apply , as JSExpr | String .
(: fold-update-and-update (-> (U String JSExpr) (U String JSExpr) String))
(define (fold-update-and-update _update-old _update-new)
(define update-old (assert (jsexpr-or-string->jsexpr _update-old) hash?))
(define update-new (assert (jsexpr-or-string->jsexpr _update-new) hash?))
(jsexpr->string (for/fold ([new-change update-old])
([(_key-new _value-new) (in-hash update-new)])
(define key-new (symbol->string _key-new))
(define-values (had-parent? updated-change)
(for/fold ([had-parent? : Boolean #f]
[updated-change : (HashTable Symbol JSExpr) new-change])
([(_key-old _) (in-hash update-old)])
(define key-old (symbol->string _key-old))
(cond
[(string-prefix? key-new (string-append key-old "."))
(define key-new-rest (substring key-new (add1 (string-length key-old))))
(values #t (hash-set updated-change
_key-old
(string->jsexpr (set-by-key-path
(hash-ref updated-change _key-old)
key-new-rest
(jsexpr->string _value-new)))))]
[else
(values (or had-parent? #f) updated-change)])))
(define new-updated-change
(cond
[had-parent? updated-change]
[else
(hash-set updated-change _key-new _value-new)]))
(define finalized-updated-change
(for/fold ([finalized-updated-change : (HashTable Symbol JSExpr) new-updated-change])
([(_key-old _) (in-hash update-old)])
(define key-old (symbol->string _key-old))
(cond
[(string-prefix? key-old (string-append key-new "."))
(hash-remove finalized-updated-change _key-old)]
[else finalized-updated-change])))
finalized-updated-change)))
| null | https://raw.githubusercontent.com/cs136/seashell/17cc2b0a6d2cdac270d7168e03aa5fed88f9eb02/src/collects/seashell/db/updates.rkt | racket |
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
See also 'ADDITIONAL TERMS' at the end of the included LICENSE file.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
(apply-modifications object updates) -> newObject
applies the updates and returns the resulting object as a string.
Arguments:
Given a create and an update on the same object, returns the CREATE change
that is the result of applying the update on the create.
Arguments:
Arguments: | #lang typed/racket
Seashell 's SQLite3 + Dexie bindings .
Copyright ( C ) 2013 - 2015 The Seashell Maintainers .
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(require typed/json)
(require typed/db)
(require typed/db/sqlite3)
(require "support.rkt")
(provide apply-modifications
fold-create-and-update
fold-update-and-update)
Given an JSON object and a JSON object representing updates as { key : } pairs
object - JSON object to update , as JSExpr | String .
updates - Updates to apply , as either a JSExpr HashTable or a String .
(: apply-modifications (-> (U String JSExpr) (U String (HashTable Symbol JSExpr)) String))
(define (apply-modifications _object _updates)
(define updates (assert (jsexpr-or-string->jsexpr _updates) hash?))
(for/fold ([object (string-or-jsexpr->string _object)])
([(_key _value) (in-hash updates)])
(define key-path (symbol->string _key))
(define update (jsexpr->string _value))
(set-by-key-path object key-path update)))
( fold - update - and - update first second ) - > newUpdate
first , second - Updates to apply , as JSExpr | String .
(: fold-create-and-update (-> (U String JSExpr) (U String (HashTable Symbol JSExpr)) String))
(define (fold-create-and-update object update)
(apply-modifications object update))
( fold - update - and - update first second ) - > newUpdate
Given two updates to apply on a JSON object , returns the update that is the result
of applying the first update followed by the second update .
first , second - Updates to apply , as JSExpr | String .
(: fold-update-and-update (-> (U String JSExpr) (U String JSExpr) String))
(define (fold-update-and-update _update-old _update-new)
(define update-old (assert (jsexpr-or-string->jsexpr _update-old) hash?))
(define update-new (assert (jsexpr-or-string->jsexpr _update-new) hash?))
(jsexpr->string (for/fold ([new-change update-old])
([(_key-new _value-new) (in-hash update-new)])
(define key-new (symbol->string _key-new))
(define-values (had-parent? updated-change)
(for/fold ([had-parent? : Boolean #f]
[updated-change : (HashTable Symbol JSExpr) new-change])
([(_key-old _) (in-hash update-old)])
(define key-old (symbol->string _key-old))
(cond
[(string-prefix? key-new (string-append key-old "."))
(define key-new-rest (substring key-new (add1 (string-length key-old))))
(values #t (hash-set updated-change
_key-old
(string->jsexpr (set-by-key-path
(hash-ref updated-change _key-old)
key-new-rest
(jsexpr->string _value-new)))))]
[else
(values (or had-parent? #f) updated-change)])))
(define new-updated-change
(cond
[had-parent? updated-change]
[else
(hash-set updated-change _key-new _value-new)]))
(define finalized-updated-change
(for/fold ([finalized-updated-change : (HashTable Symbol JSExpr) new-updated-change])
([(_key-old _) (in-hash update-old)])
(define key-old (symbol->string _key-old))
(cond
[(string-prefix? key-old (string-append key-new "."))
(hash-remove finalized-updated-change _key-old)]
[else finalized-updated-change])))
finalized-updated-change)))
|
fed48a46fdaee4a2ec217359bb9df12ec34b12921b335d242db23d22c3176104 | pietervdvn/ALGT | SyntaxStyle.hs | # LANGUAGE TemplateHaskell , TypeSynonymInstances , FlexibleInstances , MultiParamTypeClasses #
module TypeSystem.SyntaxStyle where
{-
This module defines style highlightings for rules
-}
import Utils.Utils
import Utils.ToString
import Data.Map as M hiding (filter)
import Data.List (sort, intercalate, tails)
import Data.Maybe (catMaybes, listToMaybe)
import TypeSystem.Types
import TypeSystem.ParseTree
import Lens.Micro.TH
import Lens.Micro hiding ((&))
import Debug.Trace
import Data.Bifunctor (first)
-- A little extra, cause I like fancy colors
data SyntaxStyle = SyntaxStyle
{ _styles :: Map [(TypeName, Maybe Int)] Name
} deriving (Show, Eq)
makeLenses ''SyntaxStyle
determineStyle' :: SyntaxStyle -> ParseTree -> ParseTreeA (Maybe Name)
determineStyle' styling pt
= pt & annot () & determineStyle styling |> snd
determineStyle :: SyntaxStyle -> ParseTreeA a -> ParseTreeA (a, Maybe Name)
determineStyle styling
= _determineStyle (_prepStyle' styling) [] Nothing
data PreppedStyle = PreppedStyle
{ _preppedStyle :: Map [TypeName] [([Maybe Int], Name)]
} deriving (Show, Eq)
_prepStyle' :: SyntaxStyle -> PreppedStyle
_prepStyle' (SyntaxStyle style)
= style & M.toList & _prepStyle & merge & M.fromList & PreppedStyle
_prepStyle :: [([(TypeName, Maybe Int)], Name)] -> [([TypeName], ([Maybe Int], Name))]
_prepStyle [] = []
_prepStyle ((pth, nm):rest)
= let (nms, ints) = unzip pth
rest' = _prepStyle rest in
((nms, (ints, nm)):rest')
_determineStyle :: PreppedStyle -> [(Name, Int)] -> Maybe Name -> ParseTreeA a -> ParseTreeA (a, Maybe Name)
_determineStyle style path fallBack node
= let path' = get ptaInf node :path
styleName = firstJusts [_lookupStyleSuffix style path', fallBack]
in
case node of
(PtSeq a info pts) -> pts |> _determineStyle style (info:path) styleName & PtSeq (a, styleName) info
node -> node |> flip (,) styleName
_lookupStyleSuffix :: PreppedStyle -> [(Name, Int)] -> Maybe Name
_lookupStyleSuffix ps path
= path & reverse & tails & init |> _lookupStyle ps & firstJusts
_lookupStyle :: PreppedStyle -> [(Name, Int)] -> Maybe Name
_lookupStyle (PreppedStyle style) path
= do let (nms, ints) = unzip path
choices <- M.lookup nms style
_lookupStyle' choices ints
_lookupStyle' :: [([Maybe Int], Name)] -> [Int] -> Maybe Name
_lookupStyle' choices path
= let checkPath path' = zip path path' |> sndEffect & catMaybes & all (uncurry (==))
in
choices & filter (checkPath . fst)
|> snd
& listToMaybe
instance Refactorable TypeName SyntaxStyle where
refactor ftn style
= style & over styles (M.mapKeys (|> first ftn))
instance ToString SyntaxStyle where
toParsable (SyntaxStyle styles)
= styles & M.toList |> (\(pth, val) -> _showPth pth ++"\t-> "++show val) & unlines
_showPth :: [(String, Maybe Int)] -> String
_showPth pth
= pth |> _showPthEl & intercalate "."
_showPthEl (tn, Nothing)
= tn
_showPthEl (tn, Just i)
= tn ++ "." ++ show i
| null | https://raw.githubusercontent.com/pietervdvn/ALGT/43a2811931be6daf1362f37cb16f99375ca4999e/src/TypeSystem/SyntaxStyle.hs | haskell |
This module defines style highlightings for rules
A little extra, cause I like fancy colors | # LANGUAGE TemplateHaskell , TypeSynonymInstances , FlexibleInstances , MultiParamTypeClasses #
module TypeSystem.SyntaxStyle where
import Utils.Utils
import Utils.ToString
import Data.Map as M hiding (filter)
import Data.List (sort, intercalate, tails)
import Data.Maybe (catMaybes, listToMaybe)
import TypeSystem.Types
import TypeSystem.ParseTree
import Lens.Micro.TH
import Lens.Micro hiding ((&))
import Debug.Trace
import Data.Bifunctor (first)
data SyntaxStyle = SyntaxStyle
{ _styles :: Map [(TypeName, Maybe Int)] Name
} deriving (Show, Eq)
makeLenses ''SyntaxStyle
determineStyle' :: SyntaxStyle -> ParseTree -> ParseTreeA (Maybe Name)
determineStyle' styling pt
= pt & annot () & determineStyle styling |> snd
determineStyle :: SyntaxStyle -> ParseTreeA a -> ParseTreeA (a, Maybe Name)
determineStyle styling
= _determineStyle (_prepStyle' styling) [] Nothing
data PreppedStyle = PreppedStyle
{ _preppedStyle :: Map [TypeName] [([Maybe Int], Name)]
} deriving (Show, Eq)
_prepStyle' :: SyntaxStyle -> PreppedStyle
_prepStyle' (SyntaxStyle style)
= style & M.toList & _prepStyle & merge & M.fromList & PreppedStyle
_prepStyle :: [([(TypeName, Maybe Int)], Name)] -> [([TypeName], ([Maybe Int], Name))]
_prepStyle [] = []
_prepStyle ((pth, nm):rest)
= let (nms, ints) = unzip pth
rest' = _prepStyle rest in
((nms, (ints, nm)):rest')
_determineStyle :: PreppedStyle -> [(Name, Int)] -> Maybe Name -> ParseTreeA a -> ParseTreeA (a, Maybe Name)
_determineStyle style path fallBack node
= let path' = get ptaInf node :path
styleName = firstJusts [_lookupStyleSuffix style path', fallBack]
in
case node of
(PtSeq a info pts) -> pts |> _determineStyle style (info:path) styleName & PtSeq (a, styleName) info
node -> node |> flip (,) styleName
_lookupStyleSuffix :: PreppedStyle -> [(Name, Int)] -> Maybe Name
_lookupStyleSuffix ps path
= path & reverse & tails & init |> _lookupStyle ps & firstJusts
_lookupStyle :: PreppedStyle -> [(Name, Int)] -> Maybe Name
_lookupStyle (PreppedStyle style) path
= do let (nms, ints) = unzip path
choices <- M.lookup nms style
_lookupStyle' choices ints
_lookupStyle' :: [([Maybe Int], Name)] -> [Int] -> Maybe Name
_lookupStyle' choices path
= let checkPath path' = zip path path' |> sndEffect & catMaybes & all (uncurry (==))
in
choices & filter (checkPath . fst)
|> snd
& listToMaybe
instance Refactorable TypeName SyntaxStyle where
refactor ftn style
= style & over styles (M.mapKeys (|> first ftn))
instance ToString SyntaxStyle where
toParsable (SyntaxStyle styles)
= styles & M.toList |> (\(pth, val) -> _showPth pth ++"\t-> "++show val) & unlines
_showPth :: [(String, Maybe Int)] -> String
_showPth pth
= pth |> _showPthEl & intercalate "."
_showPthEl (tn, Nothing)
= tn
_showPthEl (tn, Just i)
= tn ++ "." ++ show i
|
929fa3dccdbe4267a7001e7ce50097234338da3b0a44f818d5f42b02af74cb1b | funimagej/fun.imagej | fast_segmentation.clj | (ns fun.imagej.segmentation.fast-segmentation
(:require [fun.imagej.img :as img]
[fun.imagej.core :as imagej]
[fun.imagej.img.shape :as shape]
[fun.imagej.ops :as ops]
[random-forests.core :as rf])
(:import [org.apache.commons.math3.linear QRDecomposition Array2DRowRealMatrix ArrayRealVector SingularValueDecomposition]))
;; The Fast Segmentation paradigm uses a hash map as the base data structure
(defn create-segmentation-meta
"Create the metadata for a fast segmentation"
([]
(create-segmentation-meta {:segmentation-type :2D}))
([seg]
(assoc seg
:weights []
:feature-map-fns [])))
(defn add-feature-map-fn
"Add a feature map generator to a segmentation. These are stored as maps"
[seg feature-name feature-fn]
(assoc seg
:feature-map-fns
(conj (:feature-map-fns seg)
{:name feature-name
:fn (if (:verbose seg)
(fn [target] (let [start-time (System/nanoTime)
feature-map (feature-fn target)
stop-time (System/nanoTime)]
(println "Time taken:" (- stop-time start-time) (double (/ (- stop-time start-time) 1000000)))
feature-map))
feature-fn)
})))
(defn generate-position
"Generate a candidate sample position.
We should probably give a way of providing a custom dimension ordering."
[seg label]
(cond (= (:segmentation-type seg) :3D)
^longs (long-array [(rand-int (img/get-width label))
(rand-int (img/get-height label))
(rand-int (img/get-size-dimension label 2))])
(= (:segmentation-type seg) :2D)
^longs (long-array [(rand-int (img/get-width label))
(rand-int (img/get-height label))])
:else
(println "We should autodetect here")))
(defn generate-sample-points
"Generate the positive and negative sample points given a segmentation and the target labeling.
Positive samples are drawn from the labeling, while negative samples come from regions outside the labeling."
[seg label]
;(println "generate-sample-points " (class label))
(loop [seg (assoc seg
:positive-samples []
:negative-samples [])]
(if (or (< (count (:positive-samples seg))
(:num-positive-samples seg))
(< (count (:negative-samples seg))
(:num-negative-samples seg)))
(let [candidate-pos (generate-position seg label)
candidate-val (img/get-val ^net.imglib2.img.imageplus.ByteImagePlus label ^longs candidate-pos)]
;(println "Positive " (count (:positive-samples seg)) " Negative " (count (:negative-samples seg)) " val " candidate-val)
(cond ; True, and need positive samples
(and candidate-val
(< (count (:positive-samples seg)) (:num-positive-samples seg)))
(do
(when (:verbose seg)
(println "pos:" (count (:positive-samples seg))
"neg:" (count (:negative-samples seg))))
(recur (assoc seg
:positive-samples (conj (:positive-samples seg) candidate-pos))))
; False, and need negative samples
(and (or (not candidate-val)
(zero? candidate-val))
(< (count (:negative-samples seg)) (:num-negative-samples seg)))
(do
(when (:verbose seg)
(println "pos:" (count (:positive-samples seg))
"neg:" (count (:negative-samples seg))))
(recur (assoc seg
:negative-samples (conj (:negative-samples seg) candidate-pos))))
:else
(recur seg)))
seg)))
;; Maybe deprecate
(defn generate-sample-points-negative-labels
"Generate the positive and negative sample points given a segmentation and the target labeling.
Positive samples are drawn from the labeling, while negative samples come from regions outside the labeling."
[seg label negative-labels]
(loop [seg seg]
(if (or (< (count (:positive-samples seg))
(:num-positive-samples seg))
(< (count (:negative-samples seg))
(:num-negative-samples seg)))
(let [candidate-pos (generate-position seg label)
candidate-val (img/get-val label candidate-pos)]
#_(println candidate-val)
#_(println (map #(img/get-val % candidate-pos)
negative-labels)
(reduce #(or %1 %2) (map #(img/get-val % candidate-pos)
negative-labels)))
(cond ; True, and need positive samples
(and (or (and (number? candidate-val) (pos? candidate-val))
(and (not (number? candidate-val)) candidate-val))
(< (count (:positive-samples seg)) (:num-positive-samples seg)))
(do
(when (:verbose seg)
(println "pos:" (count (:positive-samples seg))
"neg:" (count (:negative-samples seg))))
(recur (assoc seg
:positive-samples (conj (:positive-samples seg) candidate-pos))))
; False, and need negative samples
(and (and (not candidate-val)
(reduce #(or %1 %2)
(map #(img/get-val % candidate-pos)
negative-labels)))
(< (count (:negative-samples seg)) (:num-negative-samples seg)))
(do
(when (:verbose seg)
(println "pos:" (count (:positive-samples seg))
"neg:" (count (:negative-samples seg))))
(recur (assoc seg
:negative-samples (conj (:negative-samples seg) candidate-pos))))
:else
(recur seg)))
seg)))
(defn generate-sample-points-negative-label
"Generate the positive and negative sample points given a segmentation and the target labeling.
Positive samples are drawn from the labeling, while negative samples come from regions outside the labeling."
[seg label negative-label]
(loop [seg seg]
(if (or (< (count (:positive-samples seg))
(:num-positive-samples seg))
(< (count (:negative-samples seg))
(:num-negative-samples seg)))
(let [candidate-pos (generate-position seg label)
candidate-val (img/get-val label candidate-pos)
negative-candidate-val (img/get-val negative-label candidate-pos)]
#_(println candidate-val
(or (and (number? candidate-val) (pos? candidate-val))
(and (not (number? candidate-val)) candidate-val))
negative-candidate-val
(or (and (number? negative-candidate-val) (pos? negative-candidate-val))
(and (not (number? negative-candidate-val)) negative-candidate-val)))
#_(println (map #(img/get-val % candidate-pos)
negative-labels)
(reduce #(or %1 %2) (map #(img/get-val % candidate-pos)
negative-labels)))
(cond ; True, and need positive samples
(and (or (and (number? candidate-val) (pos? candidate-val))
(and (not (number? candidate-val)) candidate-val))
(< (count (:positive-samples seg)) (:num-positive-samples seg)))
(do
(when (:verbose seg)
(println "pos:" (count (:positive-samples seg))
"neg:" (count (:negative-samples seg))))
(recur (assoc seg
:positive-samples (conj (:positive-samples seg) candidate-pos))))
; False, and need negative samples
(and (or (and (number? negative-candidate-val) (pos? negative-candidate-val))
(and (not (number? negative-candidate-val)) negative-candidate-val))
(< (count (:negative-samples seg)) (:num-negative-samples seg)))
(do
(when (:verbose seg)
(println "pos:" (count (:positive-samples seg))
"neg:" (count (:negative-samples seg))))
(recur (assoc seg
:negative-samples (conj (:negative-samples seg) candidate-pos))))
:else
(recur seg)))
seg)))
(defn generate-dataset
"Generate a dataset for training"
[seg input-img]
(loop [seg (assoc seg
:feature-vals []
:target-vals (concat (repeat (count (:positive-samples seg)) 1)
(repeat (count (:negative-samples seg)) 0)))
feature-map-fns (:feature-map-fns seg)]
(if (empty? feature-map-fns)
seg
(let [feature-name (:name (first feature-map-fns))
_ (when (:verbose seg) (println "generate-dataset working on" feature-name ))
feature-map-fn (:fn (first feature-map-fns))
feature-map (fun.imagej.ops.convert/float32
(if (and
(:cache-directory seg)
(.exists (java.io.File. (str (:cache-directory seg)
(:basename seg) "_"
feature-name ".tif"))))
(imagej/open-img (str (:cache-directory seg) (:basename seg) "_" feature-name ".tif"))
(feature-map-fn input-img)))
next-feature-vals (doall
(map #(img/get-val feature-map %)
(concat (:positive-samples seg)
(:negative-samples seg))))]
(when (:verbose seg) (println "feature map generated."))
(when (:cache-directory seg)
(imagej/save-img feature-map (str (:cache-directory seg) (:basename seg) "_" feature-name ".tif")))
(recur (assoc seg
:feature-vals
(conj (:feature-vals seg)
next-feature-vals))
(rest feature-map-fns))))))
(defn solve-segmentation
"Solve the segmentation for fully populated metadata."
[seg]
(let [data-matrix (into-array
(map double-array
(apply (partial map list)
(:feature-vals seg))))
coefficients (org.apache.commons.math3.linear.Array2DRowRealMatrix. data-matrix false)
solver ( .getSolver ( org.apache.commons.math3.linear . QRDecomposition . coefficients ) )
solver (.getSolver (org.apache.commons.math3.linear.SingularValueDecomposition. coefficients))
constants (org.apache.commons.math3.linear.ArrayRealVector. (double-array (:target-vals seg)) false)
solution (.solve solver constants)]
(assoc seg
:weights (doall
(map #(.getEntry solution %)
(range (.getDimension solution)))))))
#_(defn solve-segmentation-random-forest
"Solve the segmentatino using random-forest"
[seg]
(let [features (set (conj (into []
(map #(rf/feature (name (nth feature-seq %))
%
:continuous)
(range (count feature-seq))))
#_(rf/feature "class" (count feature-seq) :categorical)))
forest (take (or (:forest-size seg) 200)
(rf/build-random-forest examples features
(or (:tree-depth seg) 8)
(or (:tree-samples seg) 50)))]
(assoc seg
:forest forest)))
(defn segment-image
"Use a solved segmentation and an input image to segment an input."
[seg to-segment]
(let [solution-img
(fun.imagej.ops.convert/float32 (fun.imagej.ops.create/img to-segment)
#_(img/create-img-like to-segment))]
(dotimes [k (count (:feature-map-fns seg))]
(let [ffmap (nth (:feature-map-fns seg) k)
feature-name (:name ffmap)
feature-map-fn (:fn ffmap)
feature-map (fun.imagej.ops.convert/float32
(if (and
(:cache-directory seg)
(.exists (java.io.File. (str (:cache-directory seg)
(:cache-basename seg) "_"
feature-name ".tif"))))
(imagej/open-img (str (:cache-directory seg) (:basename seg) "_" feature-name ".tif"))
(feature-map-fn to-segment)))]
(when (:verbose seg) (println feature-name (str (:cache-directory seg) (:basename seg) "_" feature-name ".tif")))
(fun.imagej.ops.math/add solution-img
solution-img
(fun.imagej.ops.convert/float32
(fun.imagej.ops.math/multiply (fun.imagej.ops.convert/float32 feature-map)
^float (float (nth (:weights seg) k)))))))
(when (:cache-directory seg)
(imagej/save-img solution-img (str (:cache-directory seg) (:basename seg) "_segmentation.tif")))
solution-img))
(defn save-segmentation-config
"Save a clean version of the segmentation configuration."
[seg filename]
(spit filename
{:weights seg
:positive-samples seg
:negative-samples seg
:feature-vals seg
:num-positive-samples seg
:num-negative-samples seg}))
(defn clear-cache
"Clear the cache we created for our featuremaps"
[seg]
(dotimes [k (count (:feature-map-fns seg))]
(let [ffmap (nth (:feature-map-fns seg) k)
feature-name (:name ffmap)
feature-map-fn (:fn ffmap)]
(when (:cache-directory seg)
(.delete (java.io.File. (str (:cache-directory seg) (:cache-basename seg) "_" feature-name ".tif")))))))
| null | https://raw.githubusercontent.com/funimagej/fun.imagej/dcbe14581ba9394d8ecc6e254e02fac8130a942d/src/fun/imagej/segmentation/fast_segmentation.clj | clojure | The Fast Segmentation paradigm uses a hash map as the base data structure
(println "generate-sample-points " (class label))
(println "Positive " (count (:positive-samples seg)) " Negative " (count (:negative-samples seg)) " val " candidate-val)
True, and need positive samples
False, and need negative samples
Maybe deprecate
True, and need positive samples
False, and need negative samples
True, and need positive samples
False, and need negative samples | (ns fun.imagej.segmentation.fast-segmentation
(:require [fun.imagej.img :as img]
[fun.imagej.core :as imagej]
[fun.imagej.img.shape :as shape]
[fun.imagej.ops :as ops]
[random-forests.core :as rf])
(:import [org.apache.commons.math3.linear QRDecomposition Array2DRowRealMatrix ArrayRealVector SingularValueDecomposition]))
(defn create-segmentation-meta
"Create the metadata for a fast segmentation"
([]
(create-segmentation-meta {:segmentation-type :2D}))
([seg]
(assoc seg
:weights []
:feature-map-fns [])))
(defn add-feature-map-fn
"Add a feature map generator to a segmentation. These are stored as maps"
[seg feature-name feature-fn]
(assoc seg
:feature-map-fns
(conj (:feature-map-fns seg)
{:name feature-name
:fn (if (:verbose seg)
(fn [target] (let [start-time (System/nanoTime)
feature-map (feature-fn target)
stop-time (System/nanoTime)]
(println "Time taken:" (- stop-time start-time) (double (/ (- stop-time start-time) 1000000)))
feature-map))
feature-fn)
})))
(defn generate-position
"Generate a candidate sample position.
We should probably give a way of providing a custom dimension ordering."
[seg label]
(cond (= (:segmentation-type seg) :3D)
^longs (long-array [(rand-int (img/get-width label))
(rand-int (img/get-height label))
(rand-int (img/get-size-dimension label 2))])
(= (:segmentation-type seg) :2D)
^longs (long-array [(rand-int (img/get-width label))
(rand-int (img/get-height label))])
:else
(println "We should autodetect here")))
(defn generate-sample-points
"Generate the positive and negative sample points given a segmentation and the target labeling.
Positive samples are drawn from the labeling, while negative samples come from regions outside the labeling."
[seg label]
(loop [seg (assoc seg
:positive-samples []
:negative-samples [])]
(if (or (< (count (:positive-samples seg))
(:num-positive-samples seg))
(< (count (:negative-samples seg))
(:num-negative-samples seg)))
(let [candidate-pos (generate-position seg label)
candidate-val (img/get-val ^net.imglib2.img.imageplus.ByteImagePlus label ^longs candidate-pos)]
(and candidate-val
(< (count (:positive-samples seg)) (:num-positive-samples seg)))
(do
(when (:verbose seg)
(println "pos:" (count (:positive-samples seg))
"neg:" (count (:negative-samples seg))))
(recur (assoc seg
:positive-samples (conj (:positive-samples seg) candidate-pos))))
(and (or (not candidate-val)
(zero? candidate-val))
(< (count (:negative-samples seg)) (:num-negative-samples seg)))
(do
(when (:verbose seg)
(println "pos:" (count (:positive-samples seg))
"neg:" (count (:negative-samples seg))))
(recur (assoc seg
:negative-samples (conj (:negative-samples seg) candidate-pos))))
:else
(recur seg)))
seg)))
(defn generate-sample-points-negative-labels
"Generate the positive and negative sample points given a segmentation and the target labeling.
Positive samples are drawn from the labeling, while negative samples come from regions outside the labeling."
[seg label negative-labels]
(loop [seg seg]
(if (or (< (count (:positive-samples seg))
(:num-positive-samples seg))
(< (count (:negative-samples seg))
(:num-negative-samples seg)))
(let [candidate-pos (generate-position seg label)
candidate-val (img/get-val label candidate-pos)]
#_(println candidate-val)
#_(println (map #(img/get-val % candidate-pos)
negative-labels)
(reduce #(or %1 %2) (map #(img/get-val % candidate-pos)
negative-labels)))
(and (or (and (number? candidate-val) (pos? candidate-val))
(and (not (number? candidate-val)) candidate-val))
(< (count (:positive-samples seg)) (:num-positive-samples seg)))
(do
(when (:verbose seg)
(println "pos:" (count (:positive-samples seg))
"neg:" (count (:negative-samples seg))))
(recur (assoc seg
:positive-samples (conj (:positive-samples seg) candidate-pos))))
(and (and (not candidate-val)
(reduce #(or %1 %2)
(map #(img/get-val % candidate-pos)
negative-labels)))
(< (count (:negative-samples seg)) (:num-negative-samples seg)))
(do
(when (:verbose seg)
(println "pos:" (count (:positive-samples seg))
"neg:" (count (:negative-samples seg))))
(recur (assoc seg
:negative-samples (conj (:negative-samples seg) candidate-pos))))
:else
(recur seg)))
seg)))
(defn generate-sample-points-negative-label
"Generate the positive and negative sample points given a segmentation and the target labeling.
Positive samples are drawn from the labeling, while negative samples come from regions outside the labeling."
[seg label negative-label]
(loop [seg seg]
(if (or (< (count (:positive-samples seg))
(:num-positive-samples seg))
(< (count (:negative-samples seg))
(:num-negative-samples seg)))
(let [candidate-pos (generate-position seg label)
candidate-val (img/get-val label candidate-pos)
negative-candidate-val (img/get-val negative-label candidate-pos)]
#_(println candidate-val
(or (and (number? candidate-val) (pos? candidate-val))
(and (not (number? candidate-val)) candidate-val))
negative-candidate-val
(or (and (number? negative-candidate-val) (pos? negative-candidate-val))
(and (not (number? negative-candidate-val)) negative-candidate-val)))
#_(println (map #(img/get-val % candidate-pos)
negative-labels)
(reduce #(or %1 %2) (map #(img/get-val % candidate-pos)
negative-labels)))
(and (or (and (number? candidate-val) (pos? candidate-val))
(and (not (number? candidate-val)) candidate-val))
(< (count (:positive-samples seg)) (:num-positive-samples seg)))
(do
(when (:verbose seg)
(println "pos:" (count (:positive-samples seg))
"neg:" (count (:negative-samples seg))))
(recur (assoc seg
:positive-samples (conj (:positive-samples seg) candidate-pos))))
(and (or (and (number? negative-candidate-val) (pos? negative-candidate-val))
(and (not (number? negative-candidate-val)) negative-candidate-val))
(< (count (:negative-samples seg)) (:num-negative-samples seg)))
(do
(when (:verbose seg)
(println "pos:" (count (:positive-samples seg))
"neg:" (count (:negative-samples seg))))
(recur (assoc seg
:negative-samples (conj (:negative-samples seg) candidate-pos))))
:else
(recur seg)))
seg)))
(defn generate-dataset
"Generate a dataset for training"
[seg input-img]
(loop [seg (assoc seg
:feature-vals []
:target-vals (concat (repeat (count (:positive-samples seg)) 1)
(repeat (count (:negative-samples seg)) 0)))
feature-map-fns (:feature-map-fns seg)]
(if (empty? feature-map-fns)
seg
(let [feature-name (:name (first feature-map-fns))
_ (when (:verbose seg) (println "generate-dataset working on" feature-name ))
feature-map-fn (:fn (first feature-map-fns))
feature-map (fun.imagej.ops.convert/float32
(if (and
(:cache-directory seg)
(.exists (java.io.File. (str (:cache-directory seg)
(:basename seg) "_"
feature-name ".tif"))))
(imagej/open-img (str (:cache-directory seg) (:basename seg) "_" feature-name ".tif"))
(feature-map-fn input-img)))
next-feature-vals (doall
(map #(img/get-val feature-map %)
(concat (:positive-samples seg)
(:negative-samples seg))))]
(when (:verbose seg) (println "feature map generated."))
(when (:cache-directory seg)
(imagej/save-img feature-map (str (:cache-directory seg) (:basename seg) "_" feature-name ".tif")))
(recur (assoc seg
:feature-vals
(conj (:feature-vals seg)
next-feature-vals))
(rest feature-map-fns))))))
(defn solve-segmentation
"Solve the segmentation for fully populated metadata."
[seg]
(let [data-matrix (into-array
(map double-array
(apply (partial map list)
(:feature-vals seg))))
coefficients (org.apache.commons.math3.linear.Array2DRowRealMatrix. data-matrix false)
solver ( .getSolver ( org.apache.commons.math3.linear . QRDecomposition . coefficients ) )
solver (.getSolver (org.apache.commons.math3.linear.SingularValueDecomposition. coefficients))
constants (org.apache.commons.math3.linear.ArrayRealVector. (double-array (:target-vals seg)) false)
solution (.solve solver constants)]
(assoc seg
:weights (doall
(map #(.getEntry solution %)
(range (.getDimension solution)))))))
#_(defn solve-segmentation-random-forest
"Solve the segmentatino using random-forest"
[seg]
(let [features (set (conj (into []
(map #(rf/feature (name (nth feature-seq %))
%
:continuous)
(range (count feature-seq))))
#_(rf/feature "class" (count feature-seq) :categorical)))
forest (take (or (:forest-size seg) 200)
(rf/build-random-forest examples features
(or (:tree-depth seg) 8)
(or (:tree-samples seg) 50)))]
(assoc seg
:forest forest)))
(defn segment-image
"Use a solved segmentation and an input image to segment an input."
[seg to-segment]
(let [solution-img
(fun.imagej.ops.convert/float32 (fun.imagej.ops.create/img to-segment)
#_(img/create-img-like to-segment))]
(dotimes [k (count (:feature-map-fns seg))]
(let [ffmap (nth (:feature-map-fns seg) k)
feature-name (:name ffmap)
feature-map-fn (:fn ffmap)
feature-map (fun.imagej.ops.convert/float32
(if (and
(:cache-directory seg)
(.exists (java.io.File. (str (:cache-directory seg)
(:cache-basename seg) "_"
feature-name ".tif"))))
(imagej/open-img (str (:cache-directory seg) (:basename seg) "_" feature-name ".tif"))
(feature-map-fn to-segment)))]
(when (:verbose seg) (println feature-name (str (:cache-directory seg) (:basename seg) "_" feature-name ".tif")))
(fun.imagej.ops.math/add solution-img
solution-img
(fun.imagej.ops.convert/float32
(fun.imagej.ops.math/multiply (fun.imagej.ops.convert/float32 feature-map)
^float (float (nth (:weights seg) k)))))))
(when (:cache-directory seg)
(imagej/save-img solution-img (str (:cache-directory seg) (:basename seg) "_segmentation.tif")))
solution-img))
(defn save-segmentation-config
"Save a clean version of the segmentation configuration."
[seg filename]
(spit filename
{:weights seg
:positive-samples seg
:negative-samples seg
:feature-vals seg
:num-positive-samples seg
:num-negative-samples seg}))
(defn clear-cache
"Clear the cache we created for our featuremaps"
[seg]
(dotimes [k (count (:feature-map-fns seg))]
(let [ffmap (nth (:feature-map-fns seg) k)
feature-name (:name ffmap)
feature-map-fn (:fn ffmap)]
(when (:cache-directory seg)
(.delete (java.io.File. (str (:cache-directory seg) (:cache-basename seg) "_" feature-name ".tif")))))))
|
de437de3e8599529877407482580b79ac9c0de5482d5507ee52c8d3f98ae6f05 | solita/mnt-teet | owner_opinion_style.cljs | (ns teet.land.owner-opinion-style
(:require [teet.theme.theme-colors :as theme-colors]))
(defn opinion-container-heading-box
[]
{:width "100%"
:display :flex
:justify-content :space-between
:align-items :center})
(defn opinion-container-heading
[]
{:border-bottom (str "1px solid " theme-colors/gray-lighter)
:padding-bottom "1rem"
:padding-top "1rem"})
| null | https://raw.githubusercontent.com/solita/mnt-teet/7a5124975ce1c7f3e7a7c55fe23257ca3f7b6411/app/frontend/src/cljs/teet/land/owner_opinion_style.cljs | clojure | (ns teet.land.owner-opinion-style
(:require [teet.theme.theme-colors :as theme-colors]))
(defn opinion-container-heading-box
[]
{:width "100%"
:display :flex
:justify-content :space-between
:align-items :center})
(defn opinion-container-heading
[]
{:border-bottom (str "1px solid " theme-colors/gray-lighter)
:padding-bottom "1rem"
:padding-top "1rem"})
| |
9ea9abf54d929c4806e494c0f7e27300c2051152df312984d89e8402ea724b29 | g-andrade/tls_certificate_check | tls_certificate_check_cross_signing_SUITE.erl | Copyright ( c ) 2021 - 2023
%%
%% 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(tls_certificate_check_cross_signing_SUITE).
-compile(export_all).
%% ------------------------------------------------------------------
Macros
%% ------------------------------------------------------------------
-define(PEMS_PATH, "../../../../test/cross_signing").
-define(REPEAT_N, 20).
%% ------------------------------------------------------------------
%% Setup
%% ------------------------------------------------------------------
all() ->
[{group, GroupName} || {GroupName, _Options, _TestCases} <- groups()].
groups() ->
[{individual_tests, [{repeat, ?REPEAT_N}, shuffle], test_names()}].
test_names() ->
[good_chain_with_expired_root_test,
bad_chain_with_expired_root_test,
cross_signing_with_one_recognized_ca_test,
cross_signing_with_one_other_recognized_ca_test].
init_per_testcase(_TestConfig, Config) ->
{ok, _} = application:ensure_all_started(tls_certificate_check),
Config.
end_per_testcase(_TestConfig, _Config) ->
ok = application:stop(tls_certificate_check).
%% ------------------------------------------------------------------
%% Test Cases
%% ------------------------------------------------------------------
good_chain_with_expired_root_test(_Config) ->
tls_certificate_check_test_utils:connect(
?PEMS_PATH, "good_ca_store_for_expiry.pem",
chain, "localhost_chain_for_expiry.pem",
fun ({ok, Socket}) ->
ssl:close(Socket)
end).
-ifdef(EXPIRED_CAs_ARE_CONSIDERED_VALID).
-ifdef(FLAKY_CROSS_SIGNING_VALIDATION).
bad_chain_with_expired_root_test(_Config) ->
{skip, "This test fails non-deterministically on the present OTP version"}.
-else.
bad_chain_with_expired_root_test(_Config) ->
tls_certificate_check_test_utils:connect(
?PEMS_PATH, "bad_ca_store_for_expiry.pem",
chain, "localhost_chain_for_expiry.pem",
fun ({ok, Socket}) ->
ssl:close(Socket)
end).
-endif. % ifdef(FLAKY_CROSS_SIGNING_VALIDATION
-else. % ifdef(EXPIRED_CAs_ARE_CONSIDERED_VALID)
bad_chain_with_expired_root_test(_Config) ->
tls_certificate_check_test_utils:connect(
?PEMS_PATH, "bad_ca_store_for_expiry.pem",
chain, "localhost_chain_for_expiry.pem",
fun ({error, {tls_alert, {certificate_expired, _}}}) ->
ok
end).
-endif. % -ifdef(EXPIRED_CAs_ARE_CONSIDERED_VALID)
cross_signing_with_one_recognized_ca_test(_Config) ->
tls_certificate_check_test_utils:connect(
?PEMS_PATH, "ca_store1_for_cross_signing.pem",
chain, "localhost_chain_for_cross_signing.pem",
fun ({ok, Socket}) ->
ssl:close(Socket)
end).
-ifdef(FLAKY_CROSS_SIGNING_VALIDATION).
cross_signing_with_one_other_recognized_ca_test(_Config) ->
{skip, "This test fails non-deterministically on the present OTP version"}.
-else.
cross_signing_with_one_other_recognized_ca_test(_Config) ->
tls_certificate_check_test_utils:connect(
?PEMS_PATH, "ca_store2_for_cross_signing.pem",
chain, "localhost_chain_for_cross_signing.pem",
fun ({ok, Socket}) ->
ssl:close(Socket)
end).
-endif. % -ifdef(FLAKY_CROSS_SIGNING_VALIDATION)
| null | https://raw.githubusercontent.com/g-andrade/tls_certificate_check/fbdfcc9779d3448e66375f2a73257f74813f2f8a/test/tls_certificate_check_cross_signing_SUITE.erl | erlang |
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is 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
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
Setup
------------------------------------------------------------------
------------------------------------------------------------------
Test Cases
------------------------------------------------------------------
ifdef(FLAKY_CROSS_SIGNING_VALIDATION
ifdef(EXPIRED_CAs_ARE_CONSIDERED_VALID)
-ifdef(EXPIRED_CAs_ARE_CONSIDERED_VALID)
-ifdef(FLAKY_CROSS_SIGNING_VALIDATION) | Copyright ( c ) 2021 - 2023
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
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
-module(tls_certificate_check_cross_signing_SUITE).
-compile(export_all).
Macros
-define(PEMS_PATH, "../../../../test/cross_signing").
-define(REPEAT_N, 20).
all() ->
[{group, GroupName} || {GroupName, _Options, _TestCases} <- groups()].
groups() ->
[{individual_tests, [{repeat, ?REPEAT_N}, shuffle], test_names()}].
test_names() ->
[good_chain_with_expired_root_test,
bad_chain_with_expired_root_test,
cross_signing_with_one_recognized_ca_test,
cross_signing_with_one_other_recognized_ca_test].
init_per_testcase(_TestConfig, Config) ->
{ok, _} = application:ensure_all_started(tls_certificate_check),
Config.
end_per_testcase(_TestConfig, _Config) ->
ok = application:stop(tls_certificate_check).
good_chain_with_expired_root_test(_Config) ->
tls_certificate_check_test_utils:connect(
?PEMS_PATH, "good_ca_store_for_expiry.pem",
chain, "localhost_chain_for_expiry.pem",
fun ({ok, Socket}) ->
ssl:close(Socket)
end).
-ifdef(EXPIRED_CAs_ARE_CONSIDERED_VALID).
-ifdef(FLAKY_CROSS_SIGNING_VALIDATION).
bad_chain_with_expired_root_test(_Config) ->
{skip, "This test fails non-deterministically on the present OTP version"}.
-else.
bad_chain_with_expired_root_test(_Config) ->
tls_certificate_check_test_utils:connect(
?PEMS_PATH, "bad_ca_store_for_expiry.pem",
chain, "localhost_chain_for_expiry.pem",
fun ({ok, Socket}) ->
ssl:close(Socket)
end).
bad_chain_with_expired_root_test(_Config) ->
tls_certificate_check_test_utils:connect(
?PEMS_PATH, "bad_ca_store_for_expiry.pem",
chain, "localhost_chain_for_expiry.pem",
fun ({error, {tls_alert, {certificate_expired, _}}}) ->
ok
end).
cross_signing_with_one_recognized_ca_test(_Config) ->
tls_certificate_check_test_utils:connect(
?PEMS_PATH, "ca_store1_for_cross_signing.pem",
chain, "localhost_chain_for_cross_signing.pem",
fun ({ok, Socket}) ->
ssl:close(Socket)
end).
-ifdef(FLAKY_CROSS_SIGNING_VALIDATION).
cross_signing_with_one_other_recognized_ca_test(_Config) ->
{skip, "This test fails non-deterministically on the present OTP version"}.
-else.
cross_signing_with_one_other_recognized_ca_test(_Config) ->
tls_certificate_check_test_utils:connect(
?PEMS_PATH, "ca_store2_for_cross_signing.pem",
chain, "localhost_chain_for_cross_signing.pem",
fun ({ok, Socket}) ->
ssl:close(Socket)
end).
|
529db8467e4cb046959ea8509c0fec1a4b1818268d9f30f88a9114fb4b71be3d | ijvcms/chuanqi_dev | map_20211.erl | -module(map_20211).
-export([
range/0,
data/0
]).
range() -> {60, 52}.
data() ->
{
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,2,2,1,1,1,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,0,1,1,1,1},
{1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,1,1,1,1},
{1,0,0,0,2,2,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1},
{1,0,0,2,2,2,0,0,0,0,0,0,0,0,0,2,2,2,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1},
{1,0,2,2,1,1,0,0,0,0,0,0,0,2,2,2,2,2,0,2,2,1,1,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1},
{1,0,2,1,1,1,0,0,0,0,0,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1},
{1,0,1,1,0,0,0,0,0,2,2,2,2,1,1,1,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,1},
{1,0,0,0,0,0,0,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,1,1},
{1,2,0,0,0,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,1,1,1},
{1,2,2,2,2,2,2,1,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,0,0,0,0,2,0,0,0,0,0,2,2,2,2,2,1,1,1,1},
{1,1,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,0,0,0,2,2,2,2,2,0,2,2,2,1,2,2,2,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,2,2,2,2,2,2,2,2,2,2,1,2,2,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,1,1,1,1,2,2,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,2,0,0,0,0,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,2,2,2,2,0,2,2,2,0,0,0,0,0,0,0,2,2,2,2,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2,0,0,0,0,0,0,2,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,1,2,0,0,0,0,0,0,2,2,2,1,2,2,2,2,2,2,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,0,2,2,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1},
{1,0,0,1,1,1,1,1,1,1,0,2,2,0,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1,0,0,0,0,0,0,1,1,2,2,1,1,1,1,2,2,0,0,0,0,0,0,0,0,0,0,2,2,1,1,1},
{1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,2,2,0,0,0,2,2,1,1,1,1,0,0,0,0,0,0,2,2,2,2,2,2,1,1,1,1,1,1,0,0,0,0,0,0,0,0,2,2,2,1,1,1,1},
{1,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,2,2,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,2,1,1,2,1,1,1,1,1,1,1,1,1,0,0,0,0,0,2,2,1,1,1,1,1,1,1},
{1,0,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1,1},
{1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1,1},
{1,2,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,2,2,0,2,2,2,2,2,1,1,1,1,1,1,1,1,2,2,2,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1},
{1,2,0,0,0,0,0,0,0,0,2,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1},
{1,2,0,0,0,0,0,0,0,0,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1},
{1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,2,2,2,1,1,1,1,1,1},
{1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,2,2,1,1,1,1,1,1,1},
{1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,2,1,1,1,1,1,1,1,1},
{1,1,1,1,1,2,2,2,0,0,0,0,0,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,2,2,2,0,0,0,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,1,1,1,1,1,0,0,0,0,2,2,1,2,0,0,0,0,0,0,0,0,2,2,0,2,2,2,0,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,2,2,2,2,2,1,1,1,2,2,2,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,1,1,2,2,2,2,2,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
}.
| null | https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/map_data/map_20211.erl | erlang | -module(map_20211).
-export([
range/0,
data/0
]).
range() -> {60, 52}.
data() ->
{
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,2,2,1,1,1,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,0,1,1,1,1},
{1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,1,1,1,1},
{1,0,0,0,2,2,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1},
{1,0,0,2,2,2,0,0,0,0,0,0,0,0,0,2,2,2,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1},
{1,0,2,2,1,1,0,0,0,0,0,0,0,2,2,2,2,2,0,2,2,1,1,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1},
{1,0,2,1,1,1,0,0,0,0,0,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1},
{1,0,1,1,0,0,0,0,0,2,2,2,2,1,1,1,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,1},
{1,0,0,0,0,0,0,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,1,1},
{1,2,0,0,0,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,1,1,1},
{1,2,2,2,2,2,2,1,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,0,0,0,0,2,0,0,0,0,0,2,2,2,2,2,1,1,1,1},
{1,1,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,0,0,0,2,2,2,2,2,0,2,2,2,1,2,2,2,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,2,2,2,2,2,2,2,2,2,2,1,2,2,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,1,1,1,1,2,2,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,2,0,0,0,0,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,2,2,2,2,0,2,2,2,0,0,0,0,0,0,0,2,2,2,2,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2,0,0,0,0,0,0,2,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,1,2,0,0,0,0,0,0,2,2,2,1,2,2,2,2,2,2,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,0,2,2,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1},
{1,0,0,1,1,1,1,1,1,1,0,2,2,0,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1,0,0,0,0,0,0,1,1,2,2,1,1,1,1,2,2,0,0,0,0,0,0,0,0,0,0,2,2,1,1,1},
{1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,2,2,0,0,0,2,2,1,1,1,1,0,0,0,0,0,0,2,2,2,2,2,2,1,1,1,1,1,1,0,0,0,0,0,0,0,0,2,2,2,1,1,1,1},
{1,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,2,2,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,2,1,1,2,1,1,1,1,1,1,1,1,1,0,0,0,0,0,2,2,1,1,1,1,1,1,1},
{1,0,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1,1},
{1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1,1},
{1,2,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,2,2,0,2,2,2,2,2,1,1,1,1,1,1,1,1,2,2,2,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1},
{1,2,0,0,0,0,0,0,0,0,2,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1},
{1,2,0,0,0,0,0,0,0,0,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1},
{1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,2,2,2,1,1,1,1,1,1},
{1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,2,2,1,1,1,1,1,1,1},
{1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,2,1,1,1,1,1,1,1,1},
{1,1,1,1,1,2,2,2,0,0,0,0,0,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,2,2,2,0,0,0,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,1,1,1,1,1,0,0,0,0,2,2,1,2,0,0,0,0,0,0,0,0,2,2,0,2,2,2,0,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,2,2,2,2,2,1,1,1,2,2,2,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,1,1,2,2,2,2,2,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
}.
| |
03554d5d2678cd513959a15931a45c2498e8b9cbdad2e92d8bd15d725978ae4a | ucsd-progsys/liquidhaskell | CyclicExprAlias2.hs | {-@ LIQUID "--expect-error-containing=Cyclic type alias definition" @-}
module CyclicExprAlias2 () where
@ expression CyclicC1 Q = ( CyclicC2 Q ) & & ( CyclicC3 Q ) @
{-@ expression CyclicC2 Q = CyclicC1 Q @-}
{-@ expression CyclicC3 Q = CyclicC1 Q @-}
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/errors/CyclicExprAlias2.hs | haskell | @ LIQUID "--expect-error-containing=Cyclic type alias definition" @
@ expression CyclicC2 Q = CyclicC1 Q @
@ expression CyclicC3 Q = CyclicC1 Q @ | module CyclicExprAlias2 () where
@ expression CyclicC1 Q = ( CyclicC2 Q ) & & ( CyclicC3 Q ) @
|
bf29535cd07e86b4d4c37092971772bd09af00b8ff68e58d486543a9547b019a | ksuandi/role-based-auth-api | pool.clj | (ns role-based-auth-api.db.pool
(:import com.mchange.v2.c3p0.ComboPooledDataSource)
(:require [taoensso.timbre :as log]))
(def ^:private db-spec
{:host "127.0.0.1"
:port 3306
:user "root"
:password ""
:database "testdb"})
(def ds (doto (ComboPooledDataSource.)
(.setJdbcUrl (str "jdbc:mysql://" (:host db-spec) ":" (:port db-spec) "/" (:database db-spec) "?useSSL=false"))
(.setUser (:user db-spec))
(.setPassword (:password db-spec))
Pool Size Management
(.setMinPoolSize 3)
(.setMaxPoolSize 10)
;; Connection eviction
6 hour
3 hour
4 minutes
Connection testing
(.setTestConnectionOnCheckin true)
5 minutes
(defn pool []
(log/info (str "Starting db pool at " (:host db-spec) ":" (:port db-spec)))
{:datasource ds})
| null | https://raw.githubusercontent.com/ksuandi/role-based-auth-api/e22af336650a2e3663292775c29ac1b3bead05dd/src/role_based_auth_api/db/pool.clj | clojure | Connection eviction
| (ns role-based-auth-api.db.pool
(:import com.mchange.v2.c3p0.ComboPooledDataSource)
(:require [taoensso.timbre :as log]))
(def ^:private db-spec
{:host "127.0.0.1"
:port 3306
:user "root"
:password ""
:database "testdb"})
(def ds (doto (ComboPooledDataSource.)
(.setJdbcUrl (str "jdbc:mysql://" (:host db-spec) ":" (:port db-spec) "/" (:database db-spec) "?useSSL=false"))
(.setUser (:user db-spec))
(.setPassword (:password db-spec))
Pool Size Management
(.setMinPoolSize 3)
(.setMaxPoolSize 10)
6 hour
3 hour
4 minutes
Connection testing
(.setTestConnectionOnCheckin true)
5 minutes
(defn pool []
(log/info (str "Starting db pool at " (:host db-spec) ":" (:port db-spec)))
{:datasource ds})
|
ee1e547a1df9324001122e018ce3e2dec1bc5c17931a4a58040ec63cee2f156e | binsec/haunted | binstream.ml | (**************************************************************************)
This file is part of BINSEC .
(* *)
Copyright ( C ) 2016 - 2019
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 ) .
(* *)
(**************************************************************************)
module Logger = Base_logger
type t = int Sequence.t
(* The list is stored in reversed order *)
let length = Sequence.length
let empty = Sequence.empty
let is_byte_value n = n >= 0 && n < 256
let iteri f s =
let i = ref 0 in
Sequence.iter_forward
(fun x -> f !i x; incr i) s
let get_byte_exn t n =
let exception Byte_found of int in
if n < 0 || n > length t then raise Not_found
else
let find m x = if m = n then raise (Byte_found x) in
try iteri find t; raise Not_found
with
| Byte_found x -> x
let get_byte t n =
match get_byte_exn t n with
| by -> Some by
| exception Not_found -> None
;;
let value_of c =
let cc = Char.code c in
if c <= '9' then cc - Char.code '0'
else 10 + cc - Char.code 'a'
let add_zeros hs =
let len = String.length hs in
if len mod 2 = 0 then hs
else
let b = Buffer.create 8 in
let rec add_zero len =
if len mod 2 = 0 then Buffer.contents b ^ hs
else begin
Buffer.add_char b '0';
add_zero (len + 1)
end
in add_zero len
let append_int n h =
assert (is_byte_value n);
Sequence.push_back n h
let append_int64 n64 h =
let n = Int64.to_int n64 in append_int n h
let prepend_int n h =
assert (is_byte_value n);
Sequence.push_front n h
let prepend_int64 n64 h = prepend_int (Int64.to_int n64) h
let prepend_char c = prepend_int (Char.code c)
let append_char c = append_int (Char.code c)
let of_list l =
List.fold_left (fun seq e -> prepend_int e seq) empty l
let of_bytes s =
Logger.debug ~level:5 "Binstream.oXf_bytes %s" s;
let len = String.length s in
let rec loop acc idx =
if idx >= len then acc
else
let byte = s.[idx] in
let ascii = Char.code byte in
let acc = prepend_int ascii acc in
loop acc (idx + 1)
in loop empty 0
let clean_string s =
let len = String.length s in
let b = Buffer.create len in (* len is the upper bound *)
for i = 0 to len - 1 do
let c = s.[i] in
if c <> ' ' then Buffer.add_char b (Char.lowercase_ascii c);
done;
Buffer.contents b
let of_nibbles s =
Logger.debug ~level:5 "Binstream.of_string %s" s;
let s = clean_string s in
let s = add_zeros s in
let len = String.length s in
assert (len mod 2 = 0);
let rec loop acc idx =
if idx >= len then acc
else
let byte_str = String.sub s idx 2 in
let v = 16 * value_of byte_str.[0] + value_of byte_str.[1] in
let acc = prepend_int v acc in
loop acc (idx + 2)
in loop empty 0
let iter = Sequence.iter_forward
let map = Sequence.map_forward
let fold = Sequence.fold_forward
let rev sq = fold Sequence.push_back sq empty ;;
let pp ppf t =
let open Format in
pp_open_hbox ppf ();
iter
(fun by -> Format.fprintf ppf "%02x@ " by) t;
pp_close_box ppf ()
let to_string t = Format.asprintf "%a" pp t
| null | https://raw.githubusercontent.com/binsec/haunted/7ffc5f4072950fe138f53fe953ace98fff181c73/src/base/binstream.ml | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
The list is stored in reversed order
len is the upper bound | This file is part of BINSEC .
Copyright ( C ) 2016 - 2019
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 ) .
module Logger = Base_logger
type t = int Sequence.t
let length = Sequence.length
let empty = Sequence.empty
let is_byte_value n = n >= 0 && n < 256
let iteri f s =
let i = ref 0 in
Sequence.iter_forward
(fun x -> f !i x; incr i) s
let get_byte_exn t n =
let exception Byte_found of int in
if n < 0 || n > length t then raise Not_found
else
let find m x = if m = n then raise (Byte_found x) in
try iteri find t; raise Not_found
with
| Byte_found x -> x
let get_byte t n =
match get_byte_exn t n with
| by -> Some by
| exception Not_found -> None
;;
let value_of c =
let cc = Char.code c in
if c <= '9' then cc - Char.code '0'
else 10 + cc - Char.code 'a'
let add_zeros hs =
let len = String.length hs in
if len mod 2 = 0 then hs
else
let b = Buffer.create 8 in
let rec add_zero len =
if len mod 2 = 0 then Buffer.contents b ^ hs
else begin
Buffer.add_char b '0';
add_zero (len + 1)
end
in add_zero len
let append_int n h =
assert (is_byte_value n);
Sequence.push_back n h
let append_int64 n64 h =
let n = Int64.to_int n64 in append_int n h
let prepend_int n h =
assert (is_byte_value n);
Sequence.push_front n h
let prepend_int64 n64 h = prepend_int (Int64.to_int n64) h
let prepend_char c = prepend_int (Char.code c)
let append_char c = append_int (Char.code c)
let of_list l =
List.fold_left (fun seq e -> prepend_int e seq) empty l
let of_bytes s =
Logger.debug ~level:5 "Binstream.oXf_bytes %s" s;
let len = String.length s in
let rec loop acc idx =
if idx >= len then acc
else
let byte = s.[idx] in
let ascii = Char.code byte in
let acc = prepend_int ascii acc in
loop acc (idx + 1)
in loop empty 0
let clean_string s =
let len = String.length s in
for i = 0 to len - 1 do
let c = s.[i] in
if c <> ' ' then Buffer.add_char b (Char.lowercase_ascii c);
done;
Buffer.contents b
let of_nibbles s =
Logger.debug ~level:5 "Binstream.of_string %s" s;
let s = clean_string s in
let s = add_zeros s in
let len = String.length s in
assert (len mod 2 = 0);
let rec loop acc idx =
if idx >= len then acc
else
let byte_str = String.sub s idx 2 in
let v = 16 * value_of byte_str.[0] + value_of byte_str.[1] in
let acc = prepend_int v acc in
loop acc (idx + 2)
in loop empty 0
let iter = Sequence.iter_forward
let map = Sequence.map_forward
let fold = Sequence.fold_forward
let rev sq = fold Sequence.push_back sq empty ;;
let pp ppf t =
let open Format in
pp_open_hbox ppf ();
iter
(fun by -> Format.fprintf ppf "%02x@ " by) t;
pp_close_box ppf ()
let to_string t = Format.asprintf "%a" pp t
|
63e1aba0bcdc9770c356013f66c18b07a5f71b1243084348f782199d05ab2cfa | CrossRef/cayenne | doi.clj | (ns cayenne.tasks.doi
(:require [cayenne.conf :as conf]
[cayenne.ids.doi :as doi-id]
[somnium.congomongo :as m]))
;; calculate stats about DOIs
rfc 3986
(def url-reserved #{\: \/ \? \# \[ \] \@ \! \$ \& \' \( \) \* \+ \, \; \=})
(def doi-stats (agent {:count 0
:max-string ""
:min-string ""
:max-length Integer/MIN_VALUE
:min-length Integer/MAX_VALUE
:count-reserved 0
:total-length 0}))
; :count-with-url-char
; :prefix max min avg len
(defn update-stats [stats doi]
(let [doi-length (count doi)
doi-suffix (doi-id/extract-long-suffix doi)]
(-> stats
(update-in [:count-reserved] #(if (some url-reserved doi-suffix) (inc %) %))
(update-in [:histogram doi-length] #(if % (inc %) 1))
(update-in [:max-string] #(if (> doi-length (count %))
doi
(:max-string stats)))
(update-in [:min-string] #(if (< doi-length (count %))
doi
(:min-string stats)))
(update-in [:count] inc)
(update-in [:total-length] (partial + doi-length))
(update-in [:max-length] (partial max doi-length))
(update-in [:min-length] (partial min doi-length)))))
(defn aggregate-stats [stats]
(-> stats
(assoc-in [:avg-length] (/ (:total-length stats)
(:count stats)))))
(defn update-stats-with-doc [stats doc]
(->> doc (:id) (first) (update-stats stats)))
(defn run-stats [doi-collection]
(m/with-mongo (conf/get-service :mongo)
(doseq [doc (m/fetch doi-collection :only [:doi "published.year"])]
(send doi-stats update-stats-with-doc doc)))
(send doi-stats aggregate-stats))
| null | https://raw.githubusercontent.com/CrossRef/cayenne/02321ad23dbb1edd3f203a415f4a4b11ebf810d7/src/cayenne/tasks/doi.clj | clojure | calculate stats about DOIs
\=})
:count-with-url-char
:prefix max min avg len | (ns cayenne.tasks.doi
(:require [cayenne.conf :as conf]
[cayenne.ids.doi :as doi-id]
[somnium.congomongo :as m]))
rfc 3986
(def doi-stats (agent {:count 0
:max-string ""
:min-string ""
:max-length Integer/MIN_VALUE
:min-length Integer/MAX_VALUE
:count-reserved 0
:total-length 0}))
(defn update-stats [stats doi]
(let [doi-length (count doi)
doi-suffix (doi-id/extract-long-suffix doi)]
(-> stats
(update-in [:count-reserved] #(if (some url-reserved doi-suffix) (inc %) %))
(update-in [:histogram doi-length] #(if % (inc %) 1))
(update-in [:max-string] #(if (> doi-length (count %))
doi
(:max-string stats)))
(update-in [:min-string] #(if (< doi-length (count %))
doi
(:min-string stats)))
(update-in [:count] inc)
(update-in [:total-length] (partial + doi-length))
(update-in [:max-length] (partial max doi-length))
(update-in [:min-length] (partial min doi-length)))))
(defn aggregate-stats [stats]
(-> stats
(assoc-in [:avg-length] (/ (:total-length stats)
(:count stats)))))
(defn update-stats-with-doc [stats doc]
(->> doc (:id) (first) (update-stats stats)))
(defn run-stats [doi-collection]
(m/with-mongo (conf/get-service :mongo)
(doseq [doc (m/fetch doi-collection :only [:doi "published.year"])]
(send doi-stats update-stats-with-doc doc)))
(send doi-stats aggregate-stats))
|
bb3945060863435254937081f6d53b1bf3e6242167d8e4cfad1987e01af5e663 | pyr/recordbus | project.clj | (defproject org.spootnik/recordbus "0.1.1"
:description "MySQL binlog to kafka"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:aot :all
:main org.spootnik.recordbus
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/tools.logging "0.3.1"]
[spootnik/unilog "0.7.8"]
[cheshire "5.5.0"]
[com.github.shyiko/mysql-binlog-connector-java "0.2.0"]
[org.apache.kafka/kafka-clients "0.8.2.1"]])
| null | https://raw.githubusercontent.com/pyr/recordbus/fdfb753645bac9be11dfdd6825731904219c7275/project.clj | clojure | (defproject org.spootnik/recordbus "0.1.1"
:description "MySQL binlog to kafka"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:aot :all
:main org.spootnik.recordbus
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/tools.logging "0.3.1"]
[spootnik/unilog "0.7.8"]
[cheshire "5.5.0"]
[com.github.shyiko/mysql-binlog-connector-java "0.2.0"]
[org.apache.kafka/kafka-clients "0.8.2.1"]])
| |
e3505c9d014ab011779c42a6b46019c2930cd560cffe0649d04d6a0b2bd9f611 | nominolo/lambdachine | Bc0011.hs | # LANGUAGE NoImplicitPrelude , BangPatterns , MagicHash #
-- RUN: %bc_vm_chk
CHECK : @Result@ IND - > GHC.Bool . True`con_info
module Bc.Bc0011 where
import GHC.Base
import GHC.Integer
import GHC.Num
import GHC.Classes
fib :: Int -> Int
fib n | n <= 1 = 1
| otherwise = fib (n - 2) + fib (n - 1)
test = fib 5 == 8
| null | https://raw.githubusercontent.com/nominolo/lambdachine/49d97cf7a367a650ab421f7aa19feb90bfe14731/tests/Bc/Bc0011.hs | haskell | RUN: %bc_vm_chk | # LANGUAGE NoImplicitPrelude , BangPatterns , MagicHash #
CHECK : @Result@ IND - > GHC.Bool . True`con_info
module Bc.Bc0011 where
import GHC.Base
import GHC.Integer
import GHC.Num
import GHC.Classes
fib :: Int -> Int
fib n | n <= 1 = 1
| otherwise = fib (n - 2) + fib (n - 1)
test = fib 5 == 8
|
2cfde096944843c559aa480dcc240e31f69a2f2b43fd676c1344908be28e4971 | oakes/Nightcode | project.clj | (defproject {{app-name}} "0.0.1-SNAPSHOT"
:description "FIXME: write description"
:dependencies [[org.clojure/clojure "1.10.1"]]
:aot [{{namespace}}]
:main {{namespace}})
| null | https://raw.githubusercontent.com/oakes/Nightcode/2e112c59cddc5fdec96059a08912c73b880f9ae8/resources/leiningen/new/console/project.clj | clojure | (defproject {{app-name}} "0.0.1-SNAPSHOT"
:description "FIXME: write description"
:dependencies [[org.clojure/clojure "1.10.1"]]
:aot [{{namespace}}]
:main {{namespace}})
| |
0b4bbc4720cb25a631b5c23f3a51e590c95306ec8fc43e7c3a429dd4623e22b5 | linkfluence/inventory | leaseweb.clj | (ns com.linkfluence.inventory.leaseweb
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[com.linkfluence.inventory.core :as inventory]
[com.linkfluence.inventory.caller :as caller] ;; to set ssh keys
[clojure.java.shell :as shell]
[com.linkfluence.store :as store]
[com.linkfluence.utils :as u]
[com.linkfluence.inventory.net :as net]
[leaseweb.v2.core :as lsw]
[leaseweb.v2.server :as server]
[leaseweb.v2.pnet :as pnet]
[chime.core :as chime :refer [chime-at]]
[clojure.spec.alpha :as spec]
[clj-yaml.core :as yaml]
[com.linkfluence.inventory.queue :as queue :refer [init-queue put tke]])
(:import [java.io File]
[java.time Instant Duration]))
@author
SAS 2018
;;this inventory is based on lsw server name
(def test (atom false))
(def lsw-inventory (atom {}))
(def lsw-pscheme (atom {}))
(def lsw-conf (atom nil))
(def lsw-api-client (atom nil))
(defn ro?
[]
(:read-only @lsw-conf))
(def current-address (atom ""))
;;contain list of server to be setup
(def monitored-install (atom {}))
(defn disable-server-install!
[state]
(swap! lsw-conf assoc :disable-install state)
(log/info "[LSW] installation disabled : " (:disable-install @lsw-conf))
state)
(defn get-install-loop-state
[]
{:monitoredInstall @monitored-install
:installCount (count @monitored-install)})
(def last-save (atom (System/currentTimeMillis)))
(def items-not-saved (atom 0))
(def lsw-queue (atom nil))
(defn load-inventory!
[]
;;default use s3
(when-not @test
(when-let [inventory (store/load-map (assoc (:store @lsw-conf) :key (str (:key (:store @lsw-conf)) "-inventory")))]
(reset! lsw-inventory inventory))))
(defn load-pscheme!
[]
;;default use s3
(when-not @test
(when-let [pscheme (store/load-map (assoc (:store @lsw-conf) :key (str (:key (:store @lsw-conf)) "-pscheme")))]
(reset! lsw-pscheme pscheme))))
(defn save-pscheme
"Save on both local file and s3"
[]
(when-not (:read-only @lsw-conf)
(store/save-map (assoc (:store @lsw-conf) :key (str (:key (:store @lsw-conf)) "-pscheme")) @lsw-pscheme)
(u/fsync "lsw")))
(defn save-inventory
"Save on both local file and s3"
[]
(when (and (not (:read-only @lsw-conf)) (not @test))
(if (u/save? last-save items-not-saved)
(do
(store/save-map (assoc (:store @lsw-conf) :key (str (:key (:store @lsw-conf)) "-inventory")) @lsw-inventory)
(u/reset-save! last-save items-not-saved)
(u/fsync "lsw"))
(swap! items-not-saved))))
(defn- cached?
"check if corresponding server-name exist in cache inventory
args:
server-id : a string of the server identifier"
[server-id]
(let [sidkey (if (keyword? server-id) server-id (keyword (str server-id)))]
(if-let [server (get @lsw-inventory sidkey nil)]
true
false)))
(defn get-server-with-ref
"Return server"
[ref]
(when (some? ref)
(when-let [server (reduce (fn [acc [k v]]
(when (= ref (get-in v [:contract :reference]))
(reduced v))) nil @lsw-inventory)]
server)))
(defn get-server-inventory-id-with-ref
"Return server"
[ref]
(when-let [server-id (reduce (fn [acc [k v]]
(when (= ref (get-in v [:contract :reference]))
(reduced k))) nil @lsw-inventory)]
server-id))
(defn- fix-missing-reference
[server id]
(let [server* (server/describe @lsw-api-client (:id server))]
(swap!
lsw-inventory
assoc-in
[id :contract :reference]
(get-in server* [:contract :reference])))
(save-inventory))
(defn get-server
"Return server"
[id]
(when-let [server (get @lsw-inventory id nil)]
(when (nil? (get-in server [:contract :reference]))
(fix-missing-reference server id))
server))
(defn get-server-jobs
"Return server jobs"
[id]
(if-not (ro?)
(when-let [server (get @lsw-inventory id nil)]
(server/list-jobs @lsw-api-client (:id server)))
{:error "this inventory is ro for leaseweb"}))
(defn describe-server-job
"Return a server job full description"
[id job-id]
(if-not (ro?)
(when-let [server (get @lsw-inventory id nil)]
(server/describe-job @lsw-api-client (:id server) job-id))
{:error "this inventory is ro for leaseweb"}))
(defn delete-server!
"delete"
[server-id]
(when-not (:read-only @lsw-conf)
(let [server-to-delete (get @lsw-inventory (keyword server-id))]
(swap! lsw-inventory dissoc (keyword server-id))
;;send delete update to main inventory
(inventory/add-inventory-event {:type "resource"
:id (get-in server-to-delete [:contract :reference])
:tags []
:delete true})
(save-inventory))))
(defn- reboot-server
"Reboot"
[server-id]
(let [sidkey (if (keyword? server-id) server-id (keyword (str server-id)))]
(when-not (:read-only @lsw-conf)
(when (nil? (sidkey @monitored-install))
(when-let [server (get @lsw-inventory (keyword server-id))]
(log/info "[LSW] rebooting server :" (name server-id) "/" (:id server))
(server/reboot @lsw-api-client (:id server)))))))
(defn add-operation
[server-name operation params]
(when-not (ro?)
(.put lsw-queue [server-name operation params])))
(defn get-current-addr
[]
@current-address)
(defn set-private-ip
"set private ip of server"
[server-id ip]
(let [sidkey (keyword (if (keyword? server-id) server-id (str server-id)))]
(swap! lsw-inventory assoc-in [sidkey :privateIp] ip)
(inventory/add-inventory-event {:type "resource"
:id (get-in @lsw-inventory [sidkey :contract :reference] (str "lsw-" (name server-id)))
:tags [{:name "privateIp" :value ip}]})
(save-inventory)))
(defn is-address-already-used?
[address]
(let [lsw-inventory-state (reduce (fn [acc [k v]] (if (= (:privateIp v) address)
(reduced true)
false)) false @lsw-inventory)
main-inventory-state (inventory/get-resources [{:name "provider" :value "LSW"}
{:name "privateIp" :value "privateIp"}])]
(log/info "IP Duplicate check: - lsw side:" lsw-inventory-state "- inventory-side:" main-inventory-state)
first check that ip is not set in lsw inventory
(if lsw-inventory-state
true
;; in not check that it is not in main inventory
(if (= 0 (count main-inventory-state))
;; check that we can't ping this address
(let [pingres (shell/sh "ping" "-c" "2" address)]
(log/info "Ip duplicate check : ping output" (:out pingres))
(if (= 1 (:exit pingres))
false
true))
(let [[ref res] (first main-inventory-state)
server-id (get-server-inventory-id-with-ref (name ref))]
(set-private-ip server-id (:privateIp res))
true)))))
(defn get-available-address
[server-id]
(let [sidkey (keyword (if (keyword? server-id) server-id (str server-id)))]
(if-let [private-ip (get-in @lsw-inventory [sidkey :privateIp])]
private-ip
(let [n (:net @lsw-conf)
final-addr (loop [addr (net/get-next-address (:network n) (:netmask n) @current-address)]
(if (is-address-already-used? addr)
(recur (net/get-next-address (:network n) (:netmask n) addr))
addr))]
(swap! lsw-inventory assoc-in [(keyword server-id) :privateIp] final-addr)
(save-inventory)
(reset! current-address final-addr)))))
(defn- configure-debian-if
[ifname server-id n]
[(str "echo \"auto " ifname "\" >> /etc/network/interfaces")
(str "echo \"iface " ifname " inet static\" >> /etc/network/interfaces")
(str "echo 'address " (get-available-address server-id) "' >> /etc/network/interfaces")
(str "echo 'netmask " (:netmask n) "' >> /etc/network/interfaces")
(str "echo 'broadcast " (net/get-broadcast-addr (:network n) (:netmask n)) "' >> /etc/network/interfaces")
(str "ifconfig " ifname " down")
(str "ifup " ifname)
(str "ifconfig " ifname " up")
"sleep 20"])
(defn- configure-netplan-if
[ifname server-id n]
(let [nfile (str "/etc/netplan/02-" ifname ".yaml")
netplan-conf {:network {
:version 2
:ethernets {
(keyword ifname) {
:dhcp4 "no"
:addresses [
(str
(get-available-address server-id)
(net/get-cidr (:network n) (:netmask n)))
]}}}}]
[(str "echo \"" (yaml/generate-string netplan-conf)"\" > " nfile)
(str "netplan apply")
"sleep 20"]))
(defn- configure-red-hat-if
[ifname server-id n]
[(str "echo \"DEVICE=" ifname "\" >> /etc/sysconfig/network-scripts/ifcfg-" ifname)
(str "echo 'BOOTPROTO=none' >> /etc/sysconfig/network-scripts/ifcfg-" ifname)
(str "echo 'ONBOOT=yes' >> /etc/sysconfig/network-scripts/ifcfg-" ifname)
(str "echo 'IPADDR=" (get-available-address server-id) "' >> /etc/sysconfig/network-scripts/ifcfg-" ifname)
(str "echo 'NETMASK=" (:netmask n) "' >> /etc/sysconfig/network-scripts/ifcfg-" ifname)
(str "echo 'BROADCAST=" (net/get-broadcast-addr (:network n) (:netmask n)) "' >> /etc/sysconfig/network-scripts/ifcfg-" ifname)
(str "echo 'USERCTL=no' >> /etc/sysconfig/network-scripts/ifcfg-" ifname)
(str "ifconfig " ifname " down")
(str "ifup " ifname)
(str "ifconfig " ifname " up")
"sleep 20"])
(defn- configure-if
[ifname server-id n]
(condp = (get @lsw-conf :base-distrib :debian)
:debian (configure-debian-if ifname server-id n)
:red-hat (configure-red-hat-if ifname server-id n)
:netplan (configure-netplan-if ifname server-id n)
[]))
(defn- choose-if
[ifs]
(concat
["IF_NAME=\"\""]
(vec
(mapcat (fn [iface]
[(str "ip link show " iface)
(str "if [ $? -eq 0 -a \"$IF_NAME\" == \"\" ]; then IF_NAME=" iface ";fi")])
ifs))))
(defn- mk-commands
[server-id]
(let [n (:net @lsw-conf)
ifs (get-in @lsw-conf [:net :interface-name] "eth1")
ifname (if (string? ifs) ifs "$IF_NAME")
sidkey (keyword (if (keyword? server-id) server-id (str server-id)))
server-ref (get-in @lsw-inventory [sidkey :contract :reference] (str "lsw-" (name sidkey)))]
(concat
(get @lsw-conf :post-install-optional-cmd [])
["[ ! -d /root/.ssh ] && mkdir /root/.ssh"
(str "echo \"" (slurp (:public-keys @lsw-conf)) "\" >> /root/.ssh/authorized_keys")
"passwd --lock root"
(str "echo "
server-ref
" > /etc/resource-id")
(str "echo LSW > /etc/provider-id")]
(if (get-in @lsw-conf [:net :configure-if] true)
(if (string? ifs)
(configure-if ifname server-id n)
(concat
(choose-if ifs)
(configure-if ifname server-id n)))
[])
[(str "while ! ping -c 2 " (:inventory-host @lsw-conf) "; do echo 'Network still unreachable waiting...';sleep 5; done")
(str "curl http://" (:inventory-host @lsw-conf) "/lsw/server/" (name sidkey) "/install/finish")
(str "curl http://" (:inventory-host @lsw-conf) "/provision/" server-ref)
(str "echo postinstall-ended > /root/postinstall-flag")])))
(defn clean-install-loop!
"Reset install loop in case of issue"
([]
(reset! monitored-install {}))
([id]
(let [sidkey (if (keyword? id) id (keyword (str id)))]
(swap! monitored-install dissoc sidkey))))
(defn- mark-as-installed!
"update installed state"
[server-id]
(let [sidkey (keyword (if (keyword? server-id) server-id (str server-id)))]
(when-not (:read-only @lsw-conf)
;;mark as installed
(inventory/add-inventory-event {:type "resource"
:id (get-in @lsw-inventory [sidkey :contract :reference])
:tags [{:name "state" :value "installed"}]})
(swap! lsw-inventory assoc-in [sidkey :setup] true)
(swap! monitored-install dissoc sidkey)
(save-inventory))))
(defn- lsw-region
[az]
(let [mt (re-matches #"([a-z-]*)([0-9]+)" (str/lower-case az))
region (get mt 1)]
(if-not (nil? region)
(if (= "-" (str (last region)))
(str/join (butlast region))
region)
az)))
(defn- update-inventory
[server-id reinstall]
(when-not (:read-only @lsw-conf)
(let [skey (keyword (if (keyword? server-id) server-id (str server-id)))
server (get @lsw-inventory skey)
az (get-in server [:location :site])
suite (get-in server [:location :suite])
tags (if reinstall
[{:name "state" :value "install_pending"}
{:name "privateIp" :value "" :delete true}
{:name "FQDN" :value "" :delete true}]
[{:name "state" :value "install_pending"}
{:name "provider" :value "LSW"}
{:name "publicIp" :value (get-in @lsw-inventory [skey :publicIp])}
{:name "REGION" :value (lsw-region az)}
{:name "SHORT_AZ" :value az}
{:name "AZ" :value (str az "-" suite)}])]
(inventory/add-inventory-event {:type "resource"
:id (get-in server [:contract :reference] (str "lsw-" (name server-id)))
:reinstall reinstall
:default-host (name server-id)
:tags tags}))))
(defn- install-server!
([server-id]
(install-server! server-id (:default-partition-scheme @lsw-conf) false))
([server-id reinstall]
(install-server! server-id (:default-partition-scheme @lsw-conf) reinstall))
([server-id pschema-name reinstall]
(when-not (:read-only @lsw-conf)
(let [sidkey (if (keyword? server-id) server-id (keyword (str server-id)))]
(when (nil? (sidkey @monitored-install))
(let [pschema ((keyword pschema-name) @lsw-pscheme)
server (get @lsw-inventory sidkey nil)
raid-sugg (try (server/suggested-raid-configuration server)
(catch Exception e
(log/error "Server raid configuration not set do nothing")
nil))]
(if-not (or (:disable-install @lsw-conf) (nil? raid-sugg))
(do
(log/info "[LSW] install" (name server-id) "/reference:" (get-in server [:contract :reference]) "with os :" (:default-os @lsw-conf) " - pschema :" pschema " - raid " (:raid-level raid-sugg))
(if-not (= "error" (server/install @lsw-api-client
(name server-id)
(:default-os @lsw-conf)
pschema
(:raid-level raid-sugg)
(:number-disks raid-sugg)
(if (some? (:raid-level raid-sugg)) "SW" "NONE")
nil
(server/mk-post-install-script (mk-commands (name server-id)))))
(do
(server/set-reference @lsw-api-client (name server-id) (str "lsw-" (name server-id)))
(log/info "[LSW] reference : server is now referenced with reference :" (str "lsw-" (name server-id)))
;;mark server has not setup
(swap! lsw-inventory assoc-in [sidkey :contract :reference] (str "lsw-" (name server-id)))
(swap! lsw-inventory assoc-in [sidkey :setup] false)
(swap! lsw-inventory assoc-in [sidkey :os] (:default-os @lsw-conf))
;;update install
(swap! monitored-install assoc sidkey true)
;;save to inventory
(update-inventory server-id reinstall)
(save-inventory))
(do
(save-inventory)
(log/error "[LSW] installation call fail"))))
(do
(log/info "[LSW] install : install disabled" )
(if-not (nil? raid-sugg)
(do
(server/set-reference @lsw-api-client server-id (str "lsw-" (name server-id)))
(log/info "[LSW] reference : server is now referenced with reference :" (str "lsw-" (name server-id)))
;;mark server has not setup
(swap! lsw-inventory assoc-in [sidkey :setup] true)
(swap! lsw-inventory assoc-in [sidkey :contract :reference] (str "lsw-" (name server-id)))
(swap! lsw-inventory assoc-in [sidkey :os] (:default-os @lsw-conf))
(update-inventory server-id reinstall)
(mark-as-installed! server-id)
(save-inventory))
(log/error "Server info not fullfiled skip" server))))))))))
(defn- bootstrap
"server bootstrap"
[server-id]
(when-not (:read-only @lsw-conf)
(let [server-id (name server-id)
desc (server/describe @lsw-api-client server-id)
contract (:contract desc)
sidkey (keyword (str (:id desc)))
ip (net/get-ip (get-in desc [:networkInterfaces :public :ip] nil))]
(log/info "[LSW] bootstraping" server-id "- reference :" (:reference contract))
(if-not (or (nil? (:specs desc)) (nil? ip) (nil? (:location desc)))
(when-not (cached? server-id)
(if (and
(not (nil? (:reference contract)))
(.startsWith (:reference contract) "lsw-"))
;;Server has a reference : Don't install server mark it as deployed
(do
(log/info "[LSW] Server already setup detected")
(swap! lsw-inventory assoc sidkey (assoc desc :api-version "v2"
:setup true
:init false
:publicIp ip
:os (:default-os @lsw-conf)))
(update-inventory server-id false)
(inventory/add-inventory-event {:type "resource"
:id (:reference contract)
:tags [{:name "state" :value "deployed"}]})
(save-inventory))
;;Server has no reference : proceed to server setup
(do
(log/info "[LSW] save server info")
(swap! lsw-inventory assoc sidkey (assoc desc :api-version "v2"
:setup false
:init true
:publicIp ip))
(log/info "[LSW] Adding server" server-id "to private network" (:default-private-net @lsw-conf))
(pnet/add-server @lsw-api-client (:default-private-net @lsw-conf) server-id)
(log/info "[LSW] Launch install on server" server-id "- reference :" (str "lsw-" (name server-id)))
(install-server! server-id))))
(save-inventory)))))
(defn- refresh-server-ids
[server]
(let [contract-id (get-in server [:contract :id])
reference (get-in server [:contract :reference])
server-id (:id server)
skey (if (keyword? server-id) server-id (keyword (str server-id)))]
(when (and
(some? reference)
(not (= reference "")))
(when-let [server-stored (get-server-with-ref reference)]
(let [server-ii (get-server-inventory-id-with-ref reference)
server-updated-id (assoc server-stored :id (name server-id))
server-updated (assoc-in server-updated-id [:contract :id] contract-id)]
(log/info "[LSW] updating lsw server with current id" (name server-ii) "with new id" (name server-id))
;;add updated map with new ids
(swap!
lsw-inventory
assoc
skey
server-updated)
;;remove deprecated server map
(swap!
lsw-inventory
dissoc
server-ii))
(save-inventory)))))
(defn- server-operation!
"Send bootstrap, reverse or delete operation
NB: because of api v2, identifier can be server-id or reference"
[[identifier action params]]
(when-not (:read-only @lsw-conf)
(condp = action
"delete" (delete-server! identifier)
"bootstrap" (bootstrap identifier)
"reboot" (reboot-server identifier)
"reinstall" (install-server! identifier true)
"custom-reinstall" (install-server! identifier params true)
"end-setup" (mark-as-installed! identifier)
"set-private-ip" (set-private-ip identifier params)
(log/info "unknow action for lsw handler"))))
;;loop to poll lsw api
(defn- start-lsw-loop
"get server list and check inventory consistency
add server to queue if it is absent, remove deleted server"
[]
(when-not (or (ro?) (nil? (:refresh-period @lsw-conf)))
(let [refresh-period (chime/periodic-seq (chime/now) (Duration/ofMinutes (:refresh-period @lsw-conf)))]
(log/info "[LSW][Refresh] starting LSW refresh loop")
(chime-at refresh-period
(fn [_]
(when-let [slist (:servers (server/list-all @lsw-api-client))]
(let [smap (into {} (map (fn [x] {(keyword (str (:id x))) true}) slist))]
;;detection of new server
(doseq [base-server slist]
(let [contract-id (str (get-in base-server [:contract :id]))
reference (get-in base-server [:contract :reference])
server-id (:id base-server)]
;;update server id/contract-id if a server has the same reference -> only when server doesn't exist
(when-not (cached? server-id)
(refresh-server-ids base-server))
;;check if server already exist
(when-not (cached? server-id)
(log/info "Adding server" contract-id "/" server-id "to lsw queue")
(.put lsw-queue [server-id "bootstrap" nil]))))
;;detection of deleted servers
(doseq [[k v] @lsw-inventory]
(when-not (k smap)
(log/info "Deleting server" (name k) "from lsw inventory")
(.put lsw-queue [(name k) "delete" nil]))))))))))
;;loop to setup
(defn- start-op-consumer!
"consum install queue"
[]
(when-not (:read-only @lsw-conf)
(u/start-thread!
(fn [] ;;consume queue
(when-let [ev (.take lsw-queue)]
;; extract queue and pids from :radarly and dissoc :radarly data
(server-operation! ev)))
"lsw operation consumer")))
(defn get-install-state
"Return server"
[server-id]
(let [sidkey (if (keyword? server-id) server-id (keyword (str server-id)))]
(if-let [install-state (get @monitored-install sidkey nil)]
install-state
nil)))
;;return an lsw view of our infrastructure
(defn get-lsw-inventory
"Return lsw inventory"
[]
(into [] (map (fn [[k v]] k) @lsw-inventory)))
;;return an lsw view of our infrastructure
(defn get-lsw-inventory-with-ref
"Return lsw inventory reference"
[]
(into [] (map (fn [[k v]] (get-in v [:contract :reference])) @lsw-inventory)))
;;return an lsw view of our infrastructure
(defn get-lsw-pscheme
"Return lsw partition scheme list"
[]
(into [] (map (fn [[k v]] (name k)) @lsw-pscheme)))
(defn create-partition-schema
"Return lsw partition scheme"
[name pscheme]
(when-not (:read-only @lsw-conf)
(swap! lsw-pscheme assoc (keyword name) pscheme)
(save-pscheme)))
(defn delete-partition-schema
"Return lsw partition scheme"
[id]
(when-not (:read-only @lsw-conf)
(swap! lsw-pscheme dissoc (keyword id))
(save-pscheme)))
(defn get-partition-schema
"Return lsw partition scheme"
[id]
(get @lsw-pscheme (keyword id) nil))
(defn end-setup
"Send event Update inventory when setup is ended"
[server-name]
(when-not (ro?)
(.put lsw-queue [server-name "end-setup" nil])))
(defn start-saver!
[]
(chime-at (chime/periodic-seq (chime/now) (Duration/ofSeconds 5))
(fn [_]
(when (u/save? last-save items-not-saved)
(save-inventory)))))
(defn start!
[]
(if-not (or (nil? @lsw-conf) (nil? (:refresh-period @lsw-conf)) (:read-only @lsw-conf))
[{:stop (start-lsw-loop)} (start-op-consumer!) (start-saver!)]
(do
(if-not (:read-only @lsw-conf)
(log/info "[LSW] missing parameters can't load refresh loop")
(log/info "[LSW] mode set to READ_ONLY, API actions are limited"))
[])))
(defn configure!
[conf]
(reset! lsw-conf conf)
(log/info "[LSW]" (:store @lsw-conf))
(when-not (nil? @lsw-conf)
(log/info "[LSW] installation disabled : " (get @lsw-conf :disable-install true))
(load-inventory!)
(load-pscheme!)
(reset! current-address (:offset (:net conf)))
(reset! lsw-api-client (lsw/mk-client (:token @lsw-conf)))))
| null | https://raw.githubusercontent.com/linkfluence/inventory/b69110494f8db210d14cc7093834c441440cd4e8/src/clj/com/linkfluence/inventory/leaseweb.clj | clojure | to set ssh keys
this inventory is based on lsw server name
contain list of server to be setup
default use s3
default use s3
send delete update to main inventory
in not check that it is not in main inventory
check that we can't ping this address
mark as installed
mark server has not setup
update install
save to inventory
mark server has not setup
Server has a reference : Don't install server mark it as deployed
Server has no reference : proceed to server setup
add updated map with new ids
remove deprecated server map
loop to poll lsw api
detection of new server
update server id/contract-id if a server has the same reference -> only when server doesn't exist
check if server already exist
detection of deleted servers
loop to setup
consume queue
extract queue and pids from :radarly and dissoc :radarly data
return an lsw view of our infrastructure
return an lsw view of our infrastructure
return an lsw view of our infrastructure | (ns com.linkfluence.inventory.leaseweb
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[com.linkfluence.inventory.core :as inventory]
[clojure.java.shell :as shell]
[com.linkfluence.store :as store]
[com.linkfluence.utils :as u]
[com.linkfluence.inventory.net :as net]
[leaseweb.v2.core :as lsw]
[leaseweb.v2.server :as server]
[leaseweb.v2.pnet :as pnet]
[chime.core :as chime :refer [chime-at]]
[clojure.spec.alpha :as spec]
[clj-yaml.core :as yaml]
[com.linkfluence.inventory.queue :as queue :refer [init-queue put tke]])
(:import [java.io File]
[java.time Instant Duration]))
@author
SAS 2018
(def test (atom false))
(def lsw-inventory (atom {}))
(def lsw-pscheme (atom {}))
(def lsw-conf (atom nil))
(def lsw-api-client (atom nil))
(defn ro?
[]
(:read-only @lsw-conf))
(def current-address (atom ""))
(def monitored-install (atom {}))
(defn disable-server-install!
[state]
(swap! lsw-conf assoc :disable-install state)
(log/info "[LSW] installation disabled : " (:disable-install @lsw-conf))
state)
(defn get-install-loop-state
[]
{:monitoredInstall @monitored-install
:installCount (count @monitored-install)})
(def last-save (atom (System/currentTimeMillis)))
(def items-not-saved (atom 0))
(def lsw-queue (atom nil))
(defn load-inventory!
[]
(when-not @test
(when-let [inventory (store/load-map (assoc (:store @lsw-conf) :key (str (:key (:store @lsw-conf)) "-inventory")))]
(reset! lsw-inventory inventory))))
(defn load-pscheme!
[]
(when-not @test
(when-let [pscheme (store/load-map (assoc (:store @lsw-conf) :key (str (:key (:store @lsw-conf)) "-pscheme")))]
(reset! lsw-pscheme pscheme))))
(defn save-pscheme
"Save on both local file and s3"
[]
(when-not (:read-only @lsw-conf)
(store/save-map (assoc (:store @lsw-conf) :key (str (:key (:store @lsw-conf)) "-pscheme")) @lsw-pscheme)
(u/fsync "lsw")))
(defn save-inventory
"Save on both local file and s3"
[]
(when (and (not (:read-only @lsw-conf)) (not @test))
(if (u/save? last-save items-not-saved)
(do
(store/save-map (assoc (:store @lsw-conf) :key (str (:key (:store @lsw-conf)) "-inventory")) @lsw-inventory)
(u/reset-save! last-save items-not-saved)
(u/fsync "lsw"))
(swap! items-not-saved))))
(defn- cached?
"check if corresponding server-name exist in cache inventory
args:
server-id : a string of the server identifier"
[server-id]
(let [sidkey (if (keyword? server-id) server-id (keyword (str server-id)))]
(if-let [server (get @lsw-inventory sidkey nil)]
true
false)))
(defn get-server-with-ref
"Return server"
[ref]
(when (some? ref)
(when-let [server (reduce (fn [acc [k v]]
(when (= ref (get-in v [:contract :reference]))
(reduced v))) nil @lsw-inventory)]
server)))
(defn get-server-inventory-id-with-ref
"Return server"
[ref]
(when-let [server-id (reduce (fn [acc [k v]]
(when (= ref (get-in v [:contract :reference]))
(reduced k))) nil @lsw-inventory)]
server-id))
(defn- fix-missing-reference
[server id]
(let [server* (server/describe @lsw-api-client (:id server))]
(swap!
lsw-inventory
assoc-in
[id :contract :reference]
(get-in server* [:contract :reference])))
(save-inventory))
(defn get-server
"Return server"
[id]
(when-let [server (get @lsw-inventory id nil)]
(when (nil? (get-in server [:contract :reference]))
(fix-missing-reference server id))
server))
(defn get-server-jobs
"Return server jobs"
[id]
(if-not (ro?)
(when-let [server (get @lsw-inventory id nil)]
(server/list-jobs @lsw-api-client (:id server)))
{:error "this inventory is ro for leaseweb"}))
(defn describe-server-job
"Return a server job full description"
[id job-id]
(if-not (ro?)
(when-let [server (get @lsw-inventory id nil)]
(server/describe-job @lsw-api-client (:id server) job-id))
{:error "this inventory is ro for leaseweb"}))
(defn delete-server!
"delete"
[server-id]
(when-not (:read-only @lsw-conf)
(let [server-to-delete (get @lsw-inventory (keyword server-id))]
(swap! lsw-inventory dissoc (keyword server-id))
(inventory/add-inventory-event {:type "resource"
:id (get-in server-to-delete [:contract :reference])
:tags []
:delete true})
(save-inventory))))
(defn- reboot-server
"Reboot"
[server-id]
(let [sidkey (if (keyword? server-id) server-id (keyword (str server-id)))]
(when-not (:read-only @lsw-conf)
(when (nil? (sidkey @monitored-install))
(when-let [server (get @lsw-inventory (keyword server-id))]
(log/info "[LSW] rebooting server :" (name server-id) "/" (:id server))
(server/reboot @lsw-api-client (:id server)))))))
(defn add-operation
[server-name operation params]
(when-not (ro?)
(.put lsw-queue [server-name operation params])))
(defn get-current-addr
[]
@current-address)
(defn set-private-ip
"set private ip of server"
[server-id ip]
(let [sidkey (keyword (if (keyword? server-id) server-id (str server-id)))]
(swap! lsw-inventory assoc-in [sidkey :privateIp] ip)
(inventory/add-inventory-event {:type "resource"
:id (get-in @lsw-inventory [sidkey :contract :reference] (str "lsw-" (name server-id)))
:tags [{:name "privateIp" :value ip}]})
(save-inventory)))
(defn is-address-already-used?
[address]
(let [lsw-inventory-state (reduce (fn [acc [k v]] (if (= (:privateIp v) address)
(reduced true)
false)) false @lsw-inventory)
main-inventory-state (inventory/get-resources [{:name "provider" :value "LSW"}
{:name "privateIp" :value "privateIp"}])]
(log/info "IP Duplicate check: - lsw side:" lsw-inventory-state "- inventory-side:" main-inventory-state)
first check that ip is not set in lsw inventory
(if lsw-inventory-state
true
(if (= 0 (count main-inventory-state))
(let [pingres (shell/sh "ping" "-c" "2" address)]
(log/info "Ip duplicate check : ping output" (:out pingres))
(if (= 1 (:exit pingres))
false
true))
(let [[ref res] (first main-inventory-state)
server-id (get-server-inventory-id-with-ref (name ref))]
(set-private-ip server-id (:privateIp res))
true)))))
(defn get-available-address
[server-id]
(let [sidkey (keyword (if (keyword? server-id) server-id (str server-id)))]
(if-let [private-ip (get-in @lsw-inventory [sidkey :privateIp])]
private-ip
(let [n (:net @lsw-conf)
final-addr (loop [addr (net/get-next-address (:network n) (:netmask n) @current-address)]
(if (is-address-already-used? addr)
(recur (net/get-next-address (:network n) (:netmask n) addr))
addr))]
(swap! lsw-inventory assoc-in [(keyword server-id) :privateIp] final-addr)
(save-inventory)
(reset! current-address final-addr)))))
(defn- configure-debian-if
[ifname server-id n]
[(str "echo \"auto " ifname "\" >> /etc/network/interfaces")
(str "echo \"iface " ifname " inet static\" >> /etc/network/interfaces")
(str "echo 'address " (get-available-address server-id) "' >> /etc/network/interfaces")
(str "echo 'netmask " (:netmask n) "' >> /etc/network/interfaces")
(str "echo 'broadcast " (net/get-broadcast-addr (:network n) (:netmask n)) "' >> /etc/network/interfaces")
(str "ifconfig " ifname " down")
(str "ifup " ifname)
(str "ifconfig " ifname " up")
"sleep 20"])
(defn- configure-netplan-if
[ifname server-id n]
(let [nfile (str "/etc/netplan/02-" ifname ".yaml")
netplan-conf {:network {
:version 2
:ethernets {
(keyword ifname) {
:dhcp4 "no"
:addresses [
(str
(get-available-address server-id)
(net/get-cidr (:network n) (:netmask n)))
]}}}}]
[(str "echo \"" (yaml/generate-string netplan-conf)"\" > " nfile)
(str "netplan apply")
"sleep 20"]))
(defn- configure-red-hat-if
[ifname server-id n]
[(str "echo \"DEVICE=" ifname "\" >> /etc/sysconfig/network-scripts/ifcfg-" ifname)
(str "echo 'BOOTPROTO=none' >> /etc/sysconfig/network-scripts/ifcfg-" ifname)
(str "echo 'ONBOOT=yes' >> /etc/sysconfig/network-scripts/ifcfg-" ifname)
(str "echo 'IPADDR=" (get-available-address server-id) "' >> /etc/sysconfig/network-scripts/ifcfg-" ifname)
(str "echo 'NETMASK=" (:netmask n) "' >> /etc/sysconfig/network-scripts/ifcfg-" ifname)
(str "echo 'BROADCAST=" (net/get-broadcast-addr (:network n) (:netmask n)) "' >> /etc/sysconfig/network-scripts/ifcfg-" ifname)
(str "echo 'USERCTL=no' >> /etc/sysconfig/network-scripts/ifcfg-" ifname)
(str "ifconfig " ifname " down")
(str "ifup " ifname)
(str "ifconfig " ifname " up")
"sleep 20"])
(defn- configure-if
[ifname server-id n]
(condp = (get @lsw-conf :base-distrib :debian)
:debian (configure-debian-if ifname server-id n)
:red-hat (configure-red-hat-if ifname server-id n)
:netplan (configure-netplan-if ifname server-id n)
[]))
(defn- choose-if
[ifs]
(concat
["IF_NAME=\"\""]
(vec
(mapcat (fn [iface]
[(str "ip link show " iface)
(str "if [ $? -eq 0 -a \"$IF_NAME\" == \"\" ]; then IF_NAME=" iface ";fi")])
ifs))))
(defn- mk-commands
[server-id]
(let [n (:net @lsw-conf)
ifs (get-in @lsw-conf [:net :interface-name] "eth1")
ifname (if (string? ifs) ifs "$IF_NAME")
sidkey (keyword (if (keyword? server-id) server-id (str server-id)))
server-ref (get-in @lsw-inventory [sidkey :contract :reference] (str "lsw-" (name sidkey)))]
(concat
(get @lsw-conf :post-install-optional-cmd [])
["[ ! -d /root/.ssh ] && mkdir /root/.ssh"
(str "echo \"" (slurp (:public-keys @lsw-conf)) "\" >> /root/.ssh/authorized_keys")
"passwd --lock root"
(str "echo "
server-ref
" > /etc/resource-id")
(str "echo LSW > /etc/provider-id")]
(if (get-in @lsw-conf [:net :configure-if] true)
(if (string? ifs)
(configure-if ifname server-id n)
(concat
(choose-if ifs)
(configure-if ifname server-id n)))
[])
[(str "while ! ping -c 2 " (:inventory-host @lsw-conf) "; do echo 'Network still unreachable waiting...';sleep 5; done")
(str "curl http://" (:inventory-host @lsw-conf) "/lsw/server/" (name sidkey) "/install/finish")
(str "curl http://" (:inventory-host @lsw-conf) "/provision/" server-ref)
(str "echo postinstall-ended > /root/postinstall-flag")])))
(defn clean-install-loop!
"Reset install loop in case of issue"
([]
(reset! monitored-install {}))
([id]
(let [sidkey (if (keyword? id) id (keyword (str id)))]
(swap! monitored-install dissoc sidkey))))
(defn- mark-as-installed!
"update installed state"
[server-id]
(let [sidkey (keyword (if (keyword? server-id) server-id (str server-id)))]
(when-not (:read-only @lsw-conf)
(inventory/add-inventory-event {:type "resource"
:id (get-in @lsw-inventory [sidkey :contract :reference])
:tags [{:name "state" :value "installed"}]})
(swap! lsw-inventory assoc-in [sidkey :setup] true)
(swap! monitored-install dissoc sidkey)
(save-inventory))))
(defn- lsw-region
[az]
(let [mt (re-matches #"([a-z-]*)([0-9]+)" (str/lower-case az))
region (get mt 1)]
(if-not (nil? region)
(if (= "-" (str (last region)))
(str/join (butlast region))
region)
az)))
(defn- update-inventory
[server-id reinstall]
(when-not (:read-only @lsw-conf)
(let [skey (keyword (if (keyword? server-id) server-id (str server-id)))
server (get @lsw-inventory skey)
az (get-in server [:location :site])
suite (get-in server [:location :suite])
tags (if reinstall
[{:name "state" :value "install_pending"}
{:name "privateIp" :value "" :delete true}
{:name "FQDN" :value "" :delete true}]
[{:name "state" :value "install_pending"}
{:name "provider" :value "LSW"}
{:name "publicIp" :value (get-in @lsw-inventory [skey :publicIp])}
{:name "REGION" :value (lsw-region az)}
{:name "SHORT_AZ" :value az}
{:name "AZ" :value (str az "-" suite)}])]
(inventory/add-inventory-event {:type "resource"
:id (get-in server [:contract :reference] (str "lsw-" (name server-id)))
:reinstall reinstall
:default-host (name server-id)
:tags tags}))))
(defn- install-server!
([server-id]
(install-server! server-id (:default-partition-scheme @lsw-conf) false))
([server-id reinstall]
(install-server! server-id (:default-partition-scheme @lsw-conf) reinstall))
([server-id pschema-name reinstall]
(when-not (:read-only @lsw-conf)
(let [sidkey (if (keyword? server-id) server-id (keyword (str server-id)))]
(when (nil? (sidkey @monitored-install))
(let [pschema ((keyword pschema-name) @lsw-pscheme)
server (get @lsw-inventory sidkey nil)
raid-sugg (try (server/suggested-raid-configuration server)
(catch Exception e
(log/error "Server raid configuration not set do nothing")
nil))]
(if-not (or (:disable-install @lsw-conf) (nil? raid-sugg))
(do
(log/info "[LSW] install" (name server-id) "/reference:" (get-in server [:contract :reference]) "with os :" (:default-os @lsw-conf) " - pschema :" pschema " - raid " (:raid-level raid-sugg))
(if-not (= "error" (server/install @lsw-api-client
(name server-id)
(:default-os @lsw-conf)
pschema
(:raid-level raid-sugg)
(:number-disks raid-sugg)
(if (some? (:raid-level raid-sugg)) "SW" "NONE")
nil
(server/mk-post-install-script (mk-commands (name server-id)))))
(do
(server/set-reference @lsw-api-client (name server-id) (str "lsw-" (name server-id)))
(log/info "[LSW] reference : server is now referenced with reference :" (str "lsw-" (name server-id)))
(swap! lsw-inventory assoc-in [sidkey :contract :reference] (str "lsw-" (name server-id)))
(swap! lsw-inventory assoc-in [sidkey :setup] false)
(swap! lsw-inventory assoc-in [sidkey :os] (:default-os @lsw-conf))
(swap! monitored-install assoc sidkey true)
(update-inventory server-id reinstall)
(save-inventory))
(do
(save-inventory)
(log/error "[LSW] installation call fail"))))
(do
(log/info "[LSW] install : install disabled" )
(if-not (nil? raid-sugg)
(do
(server/set-reference @lsw-api-client server-id (str "lsw-" (name server-id)))
(log/info "[LSW] reference : server is now referenced with reference :" (str "lsw-" (name server-id)))
(swap! lsw-inventory assoc-in [sidkey :setup] true)
(swap! lsw-inventory assoc-in [sidkey :contract :reference] (str "lsw-" (name server-id)))
(swap! lsw-inventory assoc-in [sidkey :os] (:default-os @lsw-conf))
(update-inventory server-id reinstall)
(mark-as-installed! server-id)
(save-inventory))
(log/error "Server info not fullfiled skip" server))))))))))
(defn- bootstrap
"server bootstrap"
[server-id]
(when-not (:read-only @lsw-conf)
(let [server-id (name server-id)
desc (server/describe @lsw-api-client server-id)
contract (:contract desc)
sidkey (keyword (str (:id desc)))
ip (net/get-ip (get-in desc [:networkInterfaces :public :ip] nil))]
(log/info "[LSW] bootstraping" server-id "- reference :" (:reference contract))
(if-not (or (nil? (:specs desc)) (nil? ip) (nil? (:location desc)))
(when-not (cached? server-id)
(if (and
(not (nil? (:reference contract)))
(.startsWith (:reference contract) "lsw-"))
(do
(log/info "[LSW] Server already setup detected")
(swap! lsw-inventory assoc sidkey (assoc desc :api-version "v2"
:setup true
:init false
:publicIp ip
:os (:default-os @lsw-conf)))
(update-inventory server-id false)
(inventory/add-inventory-event {:type "resource"
:id (:reference contract)
:tags [{:name "state" :value "deployed"}]})
(save-inventory))
(do
(log/info "[LSW] save server info")
(swap! lsw-inventory assoc sidkey (assoc desc :api-version "v2"
:setup false
:init true
:publicIp ip))
(log/info "[LSW] Adding server" server-id "to private network" (:default-private-net @lsw-conf))
(pnet/add-server @lsw-api-client (:default-private-net @lsw-conf) server-id)
(log/info "[LSW] Launch install on server" server-id "- reference :" (str "lsw-" (name server-id)))
(install-server! server-id))))
(save-inventory)))))
(defn- refresh-server-ids
[server]
(let [contract-id (get-in server [:contract :id])
reference (get-in server [:contract :reference])
server-id (:id server)
skey (if (keyword? server-id) server-id (keyword (str server-id)))]
(when (and
(some? reference)
(not (= reference "")))
(when-let [server-stored (get-server-with-ref reference)]
(let [server-ii (get-server-inventory-id-with-ref reference)
server-updated-id (assoc server-stored :id (name server-id))
server-updated (assoc-in server-updated-id [:contract :id] contract-id)]
(log/info "[LSW] updating lsw server with current id" (name server-ii) "with new id" (name server-id))
(swap!
lsw-inventory
assoc
skey
server-updated)
(swap!
lsw-inventory
dissoc
server-ii))
(save-inventory)))))
(defn- server-operation!
"Send bootstrap, reverse or delete operation
NB: because of api v2, identifier can be server-id or reference"
[[identifier action params]]
(when-not (:read-only @lsw-conf)
(condp = action
"delete" (delete-server! identifier)
"bootstrap" (bootstrap identifier)
"reboot" (reboot-server identifier)
"reinstall" (install-server! identifier true)
"custom-reinstall" (install-server! identifier params true)
"end-setup" (mark-as-installed! identifier)
"set-private-ip" (set-private-ip identifier params)
(log/info "unknow action for lsw handler"))))
(defn- start-lsw-loop
"get server list and check inventory consistency
add server to queue if it is absent, remove deleted server"
[]
(when-not (or (ro?) (nil? (:refresh-period @lsw-conf)))
(let [refresh-period (chime/periodic-seq (chime/now) (Duration/ofMinutes (:refresh-period @lsw-conf)))]
(log/info "[LSW][Refresh] starting LSW refresh loop")
(chime-at refresh-period
(fn [_]
(when-let [slist (:servers (server/list-all @lsw-api-client))]
(let [smap (into {} (map (fn [x] {(keyword (str (:id x))) true}) slist))]
(doseq [base-server slist]
(let [contract-id (str (get-in base-server [:contract :id]))
reference (get-in base-server [:contract :reference])
server-id (:id base-server)]
(when-not (cached? server-id)
(refresh-server-ids base-server))
(when-not (cached? server-id)
(log/info "Adding server" contract-id "/" server-id "to lsw queue")
(.put lsw-queue [server-id "bootstrap" nil]))))
(doseq [[k v] @lsw-inventory]
(when-not (k smap)
(log/info "Deleting server" (name k) "from lsw inventory")
(.put lsw-queue [(name k) "delete" nil]))))))))))
(defn- start-op-consumer!
"consum install queue"
[]
(when-not (:read-only @lsw-conf)
(u/start-thread!
(when-let [ev (.take lsw-queue)]
(server-operation! ev)))
"lsw operation consumer")))
(defn get-install-state
"Return server"
[server-id]
(let [sidkey (if (keyword? server-id) server-id (keyword (str server-id)))]
(if-let [install-state (get @monitored-install sidkey nil)]
install-state
nil)))
(defn get-lsw-inventory
"Return lsw inventory"
[]
(into [] (map (fn [[k v]] k) @lsw-inventory)))
(defn get-lsw-inventory-with-ref
"Return lsw inventory reference"
[]
(into [] (map (fn [[k v]] (get-in v [:contract :reference])) @lsw-inventory)))
(defn get-lsw-pscheme
"Return lsw partition scheme list"
[]
(into [] (map (fn [[k v]] (name k)) @lsw-pscheme)))
(defn create-partition-schema
"Return lsw partition scheme"
[name pscheme]
(when-not (:read-only @lsw-conf)
(swap! lsw-pscheme assoc (keyword name) pscheme)
(save-pscheme)))
(defn delete-partition-schema
"Return lsw partition scheme"
[id]
(when-not (:read-only @lsw-conf)
(swap! lsw-pscheme dissoc (keyword id))
(save-pscheme)))
(defn get-partition-schema
"Return lsw partition scheme"
[id]
(get @lsw-pscheme (keyword id) nil))
(defn end-setup
"Send event Update inventory when setup is ended"
[server-name]
(when-not (ro?)
(.put lsw-queue [server-name "end-setup" nil])))
(defn start-saver!
[]
(chime-at (chime/periodic-seq (chime/now) (Duration/ofSeconds 5))
(fn [_]
(when (u/save? last-save items-not-saved)
(save-inventory)))))
(defn start!
[]
(if-not (or (nil? @lsw-conf) (nil? (:refresh-period @lsw-conf)) (:read-only @lsw-conf))
[{:stop (start-lsw-loop)} (start-op-consumer!) (start-saver!)]
(do
(if-not (:read-only @lsw-conf)
(log/info "[LSW] missing parameters can't load refresh loop")
(log/info "[LSW] mode set to READ_ONLY, API actions are limited"))
[])))
(defn configure!
[conf]
(reset! lsw-conf conf)
(log/info "[LSW]" (:store @lsw-conf))
(when-not (nil? @lsw-conf)
(log/info "[LSW] installation disabled : " (get @lsw-conf :disable-install true))
(load-inventory!)
(load-pscheme!)
(reset! current-address (:offset (:net conf)))
(reset! lsw-api-client (lsw/mk-client (:token @lsw-conf)))))
|
0838695b3db780262c1b4a731eb7ea782c8782b5f9845fc3753cb715f8c3abf2 | karamellpelle/grid | OutputState.hs | grid is a game written in Haskell
Copyright ( C ) 2018
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
-- (at your option) any later version.
--
-- grid 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 grid. If not, see </>.
--
module Game.LevelPuzzleMode.LevelPuzzleWorld.OutputState
(
#ifdef GRID_FANCY
module Game.LevelPuzzleMode.LevelPuzzleWorld.OutputState.Fancy,
#else
module Game.LevelPuzzleMode.LevelPuzzleWorld.OutputState.Plain,
#endif
) where
#ifdef GRID_FANCY
import Game.LevelPuzzleMode.LevelPuzzleWorld.OutputState.Fancy
#else
import Game.LevelPuzzleMode.LevelPuzzleWorld.OutputState.Plain
#endif
| null | https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/designer/source/Game/LevelPuzzleMode/LevelPuzzleWorld/OutputState.hs | haskell |
This file is part of grid.
grid is free software: you can redistribute it and/or modify
(at your option) any later version.
grid is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with grid. If not, see </>.
| grid is a game written in Haskell
Copyright ( C ) 2018
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
module Game.LevelPuzzleMode.LevelPuzzleWorld.OutputState
(
#ifdef GRID_FANCY
module Game.LevelPuzzleMode.LevelPuzzleWorld.OutputState.Fancy,
#else
module Game.LevelPuzzleMode.LevelPuzzleWorld.OutputState.Plain,
#endif
) where
#ifdef GRID_FANCY
import Game.LevelPuzzleMode.LevelPuzzleWorld.OutputState.Fancy
#else
import Game.LevelPuzzleMode.LevelPuzzleWorld.OutputState.Plain
#endif
|
24cf6f75285d10d32cb234e8d78bc69d41dcc85b19f5f55b67b18f602d09cecf | mbj/stratosphere | PagerDutyIncidentConfigurationProperty.hs | module Stratosphere.SSMIncidents.ResponsePlan.PagerDutyIncidentConfigurationProperty (
PagerDutyIncidentConfigurationProperty(..),
mkPagerDutyIncidentConfigurationProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data PagerDutyIncidentConfigurationProperty
= PagerDutyIncidentConfigurationProperty {serviceId :: (Value Prelude.Text)}
mkPagerDutyIncidentConfigurationProperty ::
Value Prelude.Text -> PagerDutyIncidentConfigurationProperty
mkPagerDutyIncidentConfigurationProperty serviceId
= PagerDutyIncidentConfigurationProperty {serviceId = serviceId}
instance ToResourceProperties PagerDutyIncidentConfigurationProperty where
toResourceProperties PagerDutyIncidentConfigurationProperty {..}
= ResourceProperties
{awsType = "AWS::SSMIncidents::ResponsePlan.PagerDutyIncidentConfiguration",
supportsTags = Prelude.False,
properties = ["ServiceId" JSON..= serviceId]}
instance JSON.ToJSON PagerDutyIncidentConfigurationProperty where
toJSON PagerDutyIncidentConfigurationProperty {..}
= JSON.object ["ServiceId" JSON..= serviceId]
instance Property "ServiceId" PagerDutyIncidentConfigurationProperty where
type PropertyType "ServiceId" PagerDutyIncidentConfigurationProperty = Value Prelude.Text
set newValue PagerDutyIncidentConfigurationProperty {}
= PagerDutyIncidentConfigurationProperty {serviceId = newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/ssmincidents/gen/Stratosphere/SSMIncidents/ResponsePlan/PagerDutyIncidentConfigurationProperty.hs | haskell | module Stratosphere.SSMIncidents.ResponsePlan.PagerDutyIncidentConfigurationProperty (
PagerDutyIncidentConfigurationProperty(..),
mkPagerDutyIncidentConfigurationProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data PagerDutyIncidentConfigurationProperty
= PagerDutyIncidentConfigurationProperty {serviceId :: (Value Prelude.Text)}
mkPagerDutyIncidentConfigurationProperty ::
Value Prelude.Text -> PagerDutyIncidentConfigurationProperty
mkPagerDutyIncidentConfigurationProperty serviceId
= PagerDutyIncidentConfigurationProperty {serviceId = serviceId}
instance ToResourceProperties PagerDutyIncidentConfigurationProperty where
toResourceProperties PagerDutyIncidentConfigurationProperty {..}
= ResourceProperties
{awsType = "AWS::SSMIncidents::ResponsePlan.PagerDutyIncidentConfiguration",
supportsTags = Prelude.False,
properties = ["ServiceId" JSON..= serviceId]}
instance JSON.ToJSON PagerDutyIncidentConfigurationProperty where
toJSON PagerDutyIncidentConfigurationProperty {..}
= JSON.object ["ServiceId" JSON..= serviceId]
instance Property "ServiceId" PagerDutyIncidentConfigurationProperty where
type PropertyType "ServiceId" PagerDutyIncidentConfigurationProperty = Value Prelude.Text
set newValue PagerDutyIncidentConfigurationProperty {}
= PagerDutyIncidentConfigurationProperty {serviceId = newValue, ..} | |
ca5647db411daeaf93e4a418c49324f75af82a38f73c8402bfdb33fdf890a14d | input-output-hk/project-icarus-importer | Poll.hs | module Pos.Binary.Update.Poll
(
) where
import Universum
import Pos.Binary.Class (Bi (..), Cons (..), Field (..), decodeListLenCanonical,
deriveSimpleBi, encodeListLen)
import Pos.Binary.Infra ()
import Pos.Core (ApplicationName, BlockVersion, ChainDifficulty, Coin, EpochIndex,
HeaderHash, NumSoftwareVersion, SlotId,
SoftwareVersion, StakeholderId)
import qualified Pos.Core.Update as U
import Pos.Slotting.Types (SlottingData)
import qualified Pos.Update.Poll.Types as U
import Pos.Util.Util (cborError)
deriveSimpleBi ''U.VoteState [
Cons 'U.PositiveVote [],
Cons 'U.NegativeVote [],
Cons 'U.PositiveRevote [],
Cons 'U.NegativeRevote []]
instance Bi a => Bi (U.PrevValue a) where
encode (U.PrevValue a) = encodeListLen 1 <> encode a
encode U.NoExist = encodeListLen 0
decode = do
len <- decodeListLenCanonical
case len of
1 -> U.PrevValue <$> decode
0 -> pure U.NoExist
_ -> cborError $ "decode@PrevValue: invalid len: " <> show len
deriveSimpleBi ''U.USUndo [
Cons 'U.USUndo [
Field [| U.unChangedBV :: HashMap BlockVersion (U.PrevValue U.BlockVersionState) |],
Field [| U.unLastAdoptedBV :: Maybe BlockVersion |],
Field [| U.unChangedProps :: HashMap U.UpId (U.PrevValue U.ProposalState) |],
Field [| U.unChangedSV :: HashMap ApplicationName (U.PrevValue NumSoftwareVersion) |],
Field [| U.unChangedConfProps :: HashMap SoftwareVersion (U.PrevValue U.ConfirmedProposalState) |],
Field [| U.unPrevProposers :: Maybe (HashSet StakeholderId) |],
Field [| U.unSlottingData :: Maybe SlottingData |]
]]
deriveSimpleBi ''U.UpsExtra [
Cons 'U.UpsExtra [
Field [| U.ueProposedBlk :: HeaderHash |]
]]
deriveSimpleBi ''U.DpsExtra [
Cons 'U.DpsExtra [
Field [| U.deDecidedBlk :: HeaderHash |],
Field [| U.deImplicit :: Bool |]
]]
deriveSimpleBi ''U.UndecidedProposalState [
Cons 'U.UndecidedProposalState [
Field [| U.upsVotes :: U.StakeholderVotes |],
Field [| U.upsProposal :: U.UpdateProposal |],
Field [| U.upsSlot :: SlotId |],
Field [| U.upsPositiveStake :: Coin |],
Field [| U.upsNegativeStake :: Coin |],
Field [| U.upsExtra :: Maybe U.UpsExtra |]
]]
deriveSimpleBi ''U.DecidedProposalState [
Cons 'U.DecidedProposalState [
Field [| U.dpsDecision :: Bool |],
Field [| U.dpsUndecided :: U.UndecidedProposalState |],
Field [| U.dpsDifficulty :: Maybe ChainDifficulty |],
Field [| U.dpsExtra :: Maybe U.DpsExtra |]
]]
deriveSimpleBi ''U.ProposalState [
Cons 'U.PSUndecided [
Field [| U.unPSUndecided :: U.UndecidedProposalState |]
],
Cons 'U.PSDecided [
Field [| U.unPSDecided :: U.DecidedProposalState |]
]]
deriveSimpleBi ''U.ConfirmedProposalState [
Cons 'U.ConfirmedProposalState [
Field [| U.cpsUpdateProposal :: U.UpdateProposal |],
Field [| U.cpsImplicit :: Bool |],
Field [| U.cpsProposed :: HeaderHash |],
Field [| U.cpsDecided :: HeaderHash |],
Field [| U.cpsConfirmed :: HeaderHash |],
Field [| U.cpsAdopted :: Maybe HeaderHash |],
Field [| U.cpsVotes :: U.StakeholderVotes |],
Field [| U.cpsPositiveStake :: Coin |],
Field [| U.cpsNegativeStake :: Coin |]
]]
deriveSimpleBi ''U.BlockVersionState [
Cons 'U.BlockVersionState [
Field [| U.bvsModifier :: U.BlockVersionModifier |],
Field [| U.bvsConfirmedEpoch :: Maybe EpochIndex |],
Field [| U.bvsIssuersStable :: HashSet StakeholderId |],
Field [| U.bvsIssuersUnstable :: HashSet StakeholderId |],
Field [| U.bvsLastBlockStable :: Maybe HeaderHash |],
Field [| U.bvsLastBlockUnstable :: Maybe HeaderHash |]
]]
| null | https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/update/Pos/Binary/Update/Poll.hs | haskell | module Pos.Binary.Update.Poll
(
) where
import Universum
import Pos.Binary.Class (Bi (..), Cons (..), Field (..), decodeListLenCanonical,
deriveSimpleBi, encodeListLen)
import Pos.Binary.Infra ()
import Pos.Core (ApplicationName, BlockVersion, ChainDifficulty, Coin, EpochIndex,
HeaderHash, NumSoftwareVersion, SlotId,
SoftwareVersion, StakeholderId)
import qualified Pos.Core.Update as U
import Pos.Slotting.Types (SlottingData)
import qualified Pos.Update.Poll.Types as U
import Pos.Util.Util (cborError)
deriveSimpleBi ''U.VoteState [
Cons 'U.PositiveVote [],
Cons 'U.NegativeVote [],
Cons 'U.PositiveRevote [],
Cons 'U.NegativeRevote []]
instance Bi a => Bi (U.PrevValue a) where
encode (U.PrevValue a) = encodeListLen 1 <> encode a
encode U.NoExist = encodeListLen 0
decode = do
len <- decodeListLenCanonical
case len of
1 -> U.PrevValue <$> decode
0 -> pure U.NoExist
_ -> cborError $ "decode@PrevValue: invalid len: " <> show len
deriveSimpleBi ''U.USUndo [
Cons 'U.USUndo [
Field [| U.unChangedBV :: HashMap BlockVersion (U.PrevValue U.BlockVersionState) |],
Field [| U.unLastAdoptedBV :: Maybe BlockVersion |],
Field [| U.unChangedProps :: HashMap U.UpId (U.PrevValue U.ProposalState) |],
Field [| U.unChangedSV :: HashMap ApplicationName (U.PrevValue NumSoftwareVersion) |],
Field [| U.unChangedConfProps :: HashMap SoftwareVersion (U.PrevValue U.ConfirmedProposalState) |],
Field [| U.unPrevProposers :: Maybe (HashSet StakeholderId) |],
Field [| U.unSlottingData :: Maybe SlottingData |]
]]
deriveSimpleBi ''U.UpsExtra [
Cons 'U.UpsExtra [
Field [| U.ueProposedBlk :: HeaderHash |]
]]
deriveSimpleBi ''U.DpsExtra [
Cons 'U.DpsExtra [
Field [| U.deDecidedBlk :: HeaderHash |],
Field [| U.deImplicit :: Bool |]
]]
deriveSimpleBi ''U.UndecidedProposalState [
Cons 'U.UndecidedProposalState [
Field [| U.upsVotes :: U.StakeholderVotes |],
Field [| U.upsProposal :: U.UpdateProposal |],
Field [| U.upsSlot :: SlotId |],
Field [| U.upsPositiveStake :: Coin |],
Field [| U.upsNegativeStake :: Coin |],
Field [| U.upsExtra :: Maybe U.UpsExtra |]
]]
deriveSimpleBi ''U.DecidedProposalState [
Cons 'U.DecidedProposalState [
Field [| U.dpsDecision :: Bool |],
Field [| U.dpsUndecided :: U.UndecidedProposalState |],
Field [| U.dpsDifficulty :: Maybe ChainDifficulty |],
Field [| U.dpsExtra :: Maybe U.DpsExtra |]
]]
deriveSimpleBi ''U.ProposalState [
Cons 'U.PSUndecided [
Field [| U.unPSUndecided :: U.UndecidedProposalState |]
],
Cons 'U.PSDecided [
Field [| U.unPSDecided :: U.DecidedProposalState |]
]]
deriveSimpleBi ''U.ConfirmedProposalState [
Cons 'U.ConfirmedProposalState [
Field [| U.cpsUpdateProposal :: U.UpdateProposal |],
Field [| U.cpsImplicit :: Bool |],
Field [| U.cpsProposed :: HeaderHash |],
Field [| U.cpsDecided :: HeaderHash |],
Field [| U.cpsConfirmed :: HeaderHash |],
Field [| U.cpsAdopted :: Maybe HeaderHash |],
Field [| U.cpsVotes :: U.StakeholderVotes |],
Field [| U.cpsPositiveStake :: Coin |],
Field [| U.cpsNegativeStake :: Coin |]
]]
deriveSimpleBi ''U.BlockVersionState [
Cons 'U.BlockVersionState [
Field [| U.bvsModifier :: U.BlockVersionModifier |],
Field [| U.bvsConfirmedEpoch :: Maybe EpochIndex |],
Field [| U.bvsIssuersStable :: HashSet StakeholderId |],
Field [| U.bvsIssuersUnstable :: HashSet StakeholderId |],
Field [| U.bvsLastBlockStable :: Maybe HeaderHash |],
Field [| U.bvsLastBlockUnstable :: Maybe HeaderHash |]
]]
| |
901b257cbee2888473cf9a7784f5f757b974eb0049cb1603d30a378fdb622d1b | kutyel/haskell-book | Database.hs | module Database where
import Control.Applicative
import Data.Bool
import Data.Time
data DatabaseItem
= DbString String
| DbNumber Integer
| DbDate UTCTime
deriving (Eq, Ord, Show)
theDatabase :: [DatabaseItem]
theDatabase =
[ DbDate (UTCTime (fromGregorian 1911 5 1) (secondsToDiffTime 34123)),
DbNumber 9001,
DbString "Hello, world!",
DbDate (UTCTime (fromGregorian 1921 5 1) (secondsToDiffTime 34123))
]
1 )
filterDbDate :: [DatabaseItem] -> [UTCTime]
filterDbDate = foldr f []
where
f (DbDate x) xs = x : xs
f _ xs = xs
2 )
filterDbNumber :: [DatabaseItem] -> [Integer]
filterDbNumber = foldr f []
where
f (DbNumber x) xs = x : xs
f _ xs = xs
3 )
mostRecent :: [DatabaseItem] -> UTCTime
mostRecent = f . filterDbDate
where
f (x : xs) = foldr (\a b -> bool b a (a > b)) x xs
4 )
sumDb :: [DatabaseItem] -> Integer
sumDb = sum . filterDbNumber
5 )
avgDb :: [DatabaseItem] -> Double
avgDb = (/) <$> fromIntegral . sumDb <*> fromIntegral . length . filterDbNumber
| null | https://raw.githubusercontent.com/kutyel/haskell-book/fd4dc0332b67575cfaf5e3fb0e26687dc01772a0/src/Database.hs | haskell | module Database where
import Control.Applicative
import Data.Bool
import Data.Time
data DatabaseItem
= DbString String
| DbNumber Integer
| DbDate UTCTime
deriving (Eq, Ord, Show)
theDatabase :: [DatabaseItem]
theDatabase =
[ DbDate (UTCTime (fromGregorian 1911 5 1) (secondsToDiffTime 34123)),
DbNumber 9001,
DbString "Hello, world!",
DbDate (UTCTime (fromGregorian 1921 5 1) (secondsToDiffTime 34123))
]
1 )
filterDbDate :: [DatabaseItem] -> [UTCTime]
filterDbDate = foldr f []
where
f (DbDate x) xs = x : xs
f _ xs = xs
2 )
filterDbNumber :: [DatabaseItem] -> [Integer]
filterDbNumber = foldr f []
where
f (DbNumber x) xs = x : xs
f _ xs = xs
3 )
mostRecent :: [DatabaseItem] -> UTCTime
mostRecent = f . filterDbDate
where
f (x : xs) = foldr (\a b -> bool b a (a > b)) x xs
4 )
sumDb :: [DatabaseItem] -> Integer
sumDb = sum . filterDbNumber
5 )
avgDb :: [DatabaseItem] -> Double
avgDb = (/) <$> fromIntegral . sumDb <*> fromIntegral . length . filterDbNumber
| |
3fcbba6d9860b26437e6e55b62373a41c760cc6579b62be6579401ad7e76f39c | CodyReichert/qi | mop.lisp | ;; -*- lisp -*-
(in-package :it.bese.arnesi)
* Messing with the MOP
The code pre - dates closer - mop package . If
;;;; you're looking for a compatability layer you should probably look
;;;; there instead.
(defmacro with-class-slots ((object class-name &key except) &body body)
"Execute BODY as if in a with-slots form containig _all_ the
slots of (find-clas CLASS-NAME). This macro, which is something
of an ugly hack, inspects the class named by CLASS-NAME at
macro expansion time. Should the class CLASS-NAME change form
containing WITH-CLASS-SLOTS must be recompiled. Should the
class CLASS-NAME not be available at macro expansion time
WITH-CLASS-SLOTS will fail."
(declare (ignore object class-name except body))
(error "Not yet implemented."))
;;;; ** wrapping-standard method combination
(define-method-combination wrapping-standard
(&key (around-order :most-specific-first)
(before-order :most-specific-first)
(primary-order :most-specific-first)
(after-order :most-specific-last)
(wrapping-order :most-specific-last)
(wrap-around-order :most-specific-last))
((wrap-around (:wrap-around))
(around (:around))
(before (:before))
(wrapping (:wrapping))
(primary () :required t)
(after (:after)))
"Same semantics as standard method combination but allows
\"wrapping\" methods. Ordering of methods:
(wrap-around
(around
(before)
(wrapping
(primary))
(after)))
:warp-around, :around, :wrapping and :primary methods call the
next least/most specific method via call-next-method (as in
standard method combination).
The various WHATEVER-order keyword arguments set the order in
which the methods are called and be set to either
:most-specific-last or :most-specific-first."
(labels ((effective-order (methods order)
(ecase order
(:most-specific-first methods)
(:most-specific-last (reverse methods))))
(call-methods (methods)
(mapcar (lambda (meth) `(call-method ,meth))
methods)))
(let* (;; reorder the methods based on the -order arguments
(wrap-around (effective-order wrap-around wrap-around-order))
(around (effective-order around around-order))
(wrapping (effective-order wrapping wrapping-order))
(before (effective-order before before-order))
(primary (effective-order primary primary-order))
(after (effective-order after after-order))
;; inital value of the effective call is a call its primary
;; method(s)
(form (case (length primary)
(1 `(call-method ,(first primary)))
(t `(call-method ,(first primary) ,(rest primary))))))
(when wrapping
;; wrap form in call to the wrapping methods
(setf form `(call-method ,(first wrapping)
(,@(rest wrapping) (make-method ,form)))))
(when before
;; wrap FORM in calls to its before methods
(setf form `(progn
,@(call-methods before)
,form)))
(when after
;; wrap FORM in calls to its after methods
(setf form `(multiple-value-prog1
,form
,@(call-methods after))))
(when around
;; wrap FORM in calls to its around methods
(setf form `(call-method ,(first around)
(,@(rest around)
(make-method ,form)))))
(when wrap-around
(setf form `(call-method ,(first wrap-around)
(,@(rest wrap-around)
(make-method ,form)))))
form)))
Copyright ( c ) 2002 - 2006 ,
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are
;; met:
;;
;; - Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; - Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
- Neither the name of , nor , nor the names
;; of its contributors may be used to endorse or promote products
;; derived from this software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| null | https://raw.githubusercontent.com/CodyReichert/qi/9cf6d31f40e19f4a7f60891ef7c8c0381ccac66f/dependencies/arnesi-master/src/mop.lisp | lisp | -*- lisp -*-
you're looking for a compatability layer you should probably look
there instead.
** wrapping-standard method combination
reorder the methods based on the -order arguments
inital value of the effective call is a call its primary
method(s)
wrap form in call to the wrapping methods
wrap FORM in calls to its before methods
wrap FORM in calls to its after methods
wrap FORM in calls to its around methods
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
LOSS OF USE ,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
(in-package :it.bese.arnesi)
* Messing with the MOP
The code pre - dates closer - mop package . If
(defmacro with-class-slots ((object class-name &key except) &body body)
"Execute BODY as if in a with-slots form containig _all_ the
slots of (find-clas CLASS-NAME). This macro, which is something
of an ugly hack, inspects the class named by CLASS-NAME at
macro expansion time. Should the class CLASS-NAME change form
containing WITH-CLASS-SLOTS must be recompiled. Should the
class CLASS-NAME not be available at macro expansion time
WITH-CLASS-SLOTS will fail."
(declare (ignore object class-name except body))
(error "Not yet implemented."))
(define-method-combination wrapping-standard
(&key (around-order :most-specific-first)
(before-order :most-specific-first)
(primary-order :most-specific-first)
(after-order :most-specific-last)
(wrapping-order :most-specific-last)
(wrap-around-order :most-specific-last))
((wrap-around (:wrap-around))
(around (:around))
(before (:before))
(wrapping (:wrapping))
(primary () :required t)
(after (:after)))
"Same semantics as standard method combination but allows
\"wrapping\" methods. Ordering of methods:
(wrap-around
(around
(before)
(wrapping
(primary))
(after)))
:warp-around, :around, :wrapping and :primary methods call the
next least/most specific method via call-next-method (as in
standard method combination).
The various WHATEVER-order keyword arguments set the order in
which the methods are called and be set to either
:most-specific-last or :most-specific-first."
(labels ((effective-order (methods order)
(ecase order
(:most-specific-first methods)
(:most-specific-last (reverse methods))))
(call-methods (methods)
(mapcar (lambda (meth) `(call-method ,meth))
methods)))
(wrap-around (effective-order wrap-around wrap-around-order))
(around (effective-order around around-order))
(wrapping (effective-order wrapping wrapping-order))
(before (effective-order before before-order))
(primary (effective-order primary primary-order))
(after (effective-order after after-order))
(form (case (length primary)
(1 `(call-method ,(first primary)))
(t `(call-method ,(first primary) ,(rest primary))))))
(when wrapping
(setf form `(call-method ,(first wrapping)
(,@(rest wrapping) (make-method ,form)))))
(when before
(setf form `(progn
,@(call-methods before)
,form)))
(when after
(setf form `(multiple-value-prog1
,form
,@(call-methods after))))
(when around
(setf form `(call-method ,(first around)
(,@(rest around)
(make-method ,form)))))
(when wrap-around
(setf form `(call-method ,(first wrap-around)
(,@(rest wrap-around)
(make-method ,form)))))
form)))
Copyright ( c ) 2002 - 2006 ,
- Neither the name of , nor , nor the names
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.