_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 |
|---|---|---|---|---|---|---|---|---|
c5f02f971404e557154b8aa771c2229e9071ece2cd6dba45d93a8b6d2fdf4e5c | footprintanalytics/footprint-web | classify_test.clj | (ns metabase.sync.analyze.classify-test
(:require [clojure.test :refer :all]
[metabase.models.database :refer [Database]]
[metabase.models.field :as field :refer [Field]]
[metabase.models.field-values :as field-values]
[metabase.models.interface :as mi]
[metabase.models.table :refer [Table]]
[metabase.sync.analyze.classify :as classify]
[metabase.sync.interface :as i]
[metabase.util :as u]
[toucan.db :as db]
[toucan.util.test :as tt]))
(deftest fields-to-classify-test
(testing "Finds current fingerprinted versions that are not analyzed"
(tt/with-temp* [Table [table]
Field [_ {:table_id (u/the-id table)
:name "expected"
:description "Current fingerprint, not analyzed"
:fingerprint_version i/latest-fingerprint-version
:last_analyzed nil}]
Field [_ {:table_id (u/the-id table)
:name "not expected 1"
:description "Current fingerprint, already analzed"
:fingerprint_version i/latest-fingerprint-version
:last_analyzed #t "2017-08-09"}]
Field [_ {:table_id (u/the-id table)
:name "not expected 2"
:description "Old fingerprint, not analyzed"
:fingerprint_version (dec i/latest-fingerprint-version)
:last_analyzed nil}]
Field [_ {:table_id (u/the-id table)
:name "not expected 3"
:description "Old fingerprint, already analzed"
:fingerprint_version (dec i/latest-fingerprint-version)
:last_analyzed #t "2017-08-09"}]]
(is (= ["expected"]
(for [field (#'classify/fields-to-classify table)]
(:name field))))))
(testing "Finds previously marked :type/category fields for state"
(tt/with-temp* [Table [table]
Field [_ {:table_id (u/the-id table)
:name "expected"
:description "Current fingerprint, not analyzed"
:fingerprint_version i/latest-fingerprint-version
:last_analyzed nil}]
Field [_ {:table_id (u/the-id table)
:name "not expected 1"
:description "Current fingerprint, already analzed"
:fingerprint_version i/latest-fingerprint-version
:last_analyzed #t "2017-08-09"}]
Field [_ {:table_id (u/the-id table)
:name "not expected 2"
:description "Old fingerprint, not analyzed"
:fingerprint_version (dec i/latest-fingerprint-version)
:last_analyzed nil}]
Field [_ {:table_id (u/the-id table)
:name "not expected 3"
:description "Old fingerprint, already analzed"
:fingerprint_version (dec i/latest-fingerprint-version)
:last_analyzed #t "2017-08-09"}]])))
(deftest classify-fields-for-db!-test
(testing "We classify decimal fields that have specially handled NaN values"
(tt/with-temp* [Database [db]
Table [table {:db_id (u/the-id db)}]
Field [field {:table_id (u/the-id table)
:name "Income"
:base_type :type/Float
:semantic_type nil
:fingerprint_version i/latest-fingerprint-version
:fingerprint {:type {:type/Number {:min "NaN"
:max "NaN"
:avg "NaN"}}
:global {:distinct-count 3}}
:last_analyzed nil}]]
(is (nil? (:semantic_type (db/select-one Field :id (u/the-id field)))))
(classify/classify-fields-for-db! db [table] (constantly nil))
(is (= :type/Income (:semantic_type (db/select-one Field :id (u/the-id field)))))))
(testing "We can classify decimal fields that have specially handled infinity values"
(tt/with-temp* [Database [db]
Table [table {:db_id (u/the-id db)}]
Field [field {:table_id (u/the-id table)
:name "Income"
:base_type :type/Float
:semantic_type nil
:fingerprint_version i/latest-fingerprint-version
:fingerprint {:type {:type/Number {:min "-Infinity"
:max "Infinity"
:avg "Infinity"}}
:global {:distinct-count 3}}
:last_analyzed nil}]]
(is (nil? (:semantic_type (db/select-one Field :id (u/the-id field)))))
(classify/classify-fields-for-db! db [table] (constantly nil))
(is (= :type/Income (:semantic_type (db/select-one Field :id (u/the-id field))))))))
(defn- ->field [field]
(mi/instance
Field
(merge {:fingerprint_version i/latest-fingerprint-version
:semantic_type nil}
field)))
(deftest run-classifiers-test
(testing "Fields marked state are not overridden"
(let [field (->field {:name "state", :base_type :type/Text, :semantic_type :type/State})]
(is (= :type/State (:semantic_type (classify/run-classifiers field nil))))))
(testing "Fields with few values are marked as category and list"
(let [field (->field {:name "state", :base_type :type/Text})
classified (classify/run-classifiers field {:global
{:distinct-count
(dec field-values/category-cardinality-threshold)
:nil% 0.3}})]
(is (= {:has_field_values :auto-list, :semantic_type :type/Category}
(select-keys classified [:has_field_values :semantic_type])))))
(testing "Earlier classifiers prevent later classifiers"
(let [field (->field {:name "site_url" :base_type :type/Text})
fingerprint {:global {:distinct-count 4
:nil% 0}}
classified (classify/run-classifiers field fingerprint)]
(is (= {:has_field_values :auto-list, :semantic_type :type/URL}
(select-keys classified [:has_field_values :semantic_type])))))
(testing "Classififying using fingerprinters can override previous classifications"
(testing "Classify state fields on fingerprint rather than name"
(let [field (->field {:name "order_state" :base_type :type/Text})
fingerprint {:global {:distinct-count 4
:nil% 0}
:type {:type/Text {:percent-state 0.98}}}
classified (classify/run-classifiers field fingerprint)]
(is (= {:has_field_values :auto-list, :semantic_type :type/State}
(select-keys classified [:has_field_values :semantic_type])))))
(let [field (->field {:name "order_status" :base_type :type/Text})
fingerprint {:type {:type/Text {:percent-json 0.99}}}]
(is (= :type/SerializedJSON
;; this will be marked as :type/Category based on name, but fingerprinters should override
(:semantic_type (classify/run-classifiers field fingerprint)))))))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/sync/analyze/classify_test.clj | clojure | this will be marked as :type/Category based on name, but fingerprinters should override | (ns metabase.sync.analyze.classify-test
(:require [clojure.test :refer :all]
[metabase.models.database :refer [Database]]
[metabase.models.field :as field :refer [Field]]
[metabase.models.field-values :as field-values]
[metabase.models.interface :as mi]
[metabase.models.table :refer [Table]]
[metabase.sync.analyze.classify :as classify]
[metabase.sync.interface :as i]
[metabase.util :as u]
[toucan.db :as db]
[toucan.util.test :as tt]))
(deftest fields-to-classify-test
(testing "Finds current fingerprinted versions that are not analyzed"
(tt/with-temp* [Table [table]
Field [_ {:table_id (u/the-id table)
:name "expected"
:description "Current fingerprint, not analyzed"
:fingerprint_version i/latest-fingerprint-version
:last_analyzed nil}]
Field [_ {:table_id (u/the-id table)
:name "not expected 1"
:description "Current fingerprint, already analzed"
:fingerprint_version i/latest-fingerprint-version
:last_analyzed #t "2017-08-09"}]
Field [_ {:table_id (u/the-id table)
:name "not expected 2"
:description "Old fingerprint, not analyzed"
:fingerprint_version (dec i/latest-fingerprint-version)
:last_analyzed nil}]
Field [_ {:table_id (u/the-id table)
:name "not expected 3"
:description "Old fingerprint, already analzed"
:fingerprint_version (dec i/latest-fingerprint-version)
:last_analyzed #t "2017-08-09"}]]
(is (= ["expected"]
(for [field (#'classify/fields-to-classify table)]
(:name field))))))
(testing "Finds previously marked :type/category fields for state"
(tt/with-temp* [Table [table]
Field [_ {:table_id (u/the-id table)
:name "expected"
:description "Current fingerprint, not analyzed"
:fingerprint_version i/latest-fingerprint-version
:last_analyzed nil}]
Field [_ {:table_id (u/the-id table)
:name "not expected 1"
:description "Current fingerprint, already analzed"
:fingerprint_version i/latest-fingerprint-version
:last_analyzed #t "2017-08-09"}]
Field [_ {:table_id (u/the-id table)
:name "not expected 2"
:description "Old fingerprint, not analyzed"
:fingerprint_version (dec i/latest-fingerprint-version)
:last_analyzed nil}]
Field [_ {:table_id (u/the-id table)
:name "not expected 3"
:description "Old fingerprint, already analzed"
:fingerprint_version (dec i/latest-fingerprint-version)
:last_analyzed #t "2017-08-09"}]])))
(deftest classify-fields-for-db!-test
(testing "We classify decimal fields that have specially handled NaN values"
(tt/with-temp* [Database [db]
Table [table {:db_id (u/the-id db)}]
Field [field {:table_id (u/the-id table)
:name "Income"
:base_type :type/Float
:semantic_type nil
:fingerprint_version i/latest-fingerprint-version
:fingerprint {:type {:type/Number {:min "NaN"
:max "NaN"
:avg "NaN"}}
:global {:distinct-count 3}}
:last_analyzed nil}]]
(is (nil? (:semantic_type (db/select-one Field :id (u/the-id field)))))
(classify/classify-fields-for-db! db [table] (constantly nil))
(is (= :type/Income (:semantic_type (db/select-one Field :id (u/the-id field)))))))
(testing "We can classify decimal fields that have specially handled infinity values"
(tt/with-temp* [Database [db]
Table [table {:db_id (u/the-id db)}]
Field [field {:table_id (u/the-id table)
:name "Income"
:base_type :type/Float
:semantic_type nil
:fingerprint_version i/latest-fingerprint-version
:fingerprint {:type {:type/Number {:min "-Infinity"
:max "Infinity"
:avg "Infinity"}}
:global {:distinct-count 3}}
:last_analyzed nil}]]
(is (nil? (:semantic_type (db/select-one Field :id (u/the-id field)))))
(classify/classify-fields-for-db! db [table] (constantly nil))
(is (= :type/Income (:semantic_type (db/select-one Field :id (u/the-id field))))))))
(defn- ->field [field]
(mi/instance
Field
(merge {:fingerprint_version i/latest-fingerprint-version
:semantic_type nil}
field)))
(deftest run-classifiers-test
(testing "Fields marked state are not overridden"
(let [field (->field {:name "state", :base_type :type/Text, :semantic_type :type/State})]
(is (= :type/State (:semantic_type (classify/run-classifiers field nil))))))
(testing "Fields with few values are marked as category and list"
(let [field (->field {:name "state", :base_type :type/Text})
classified (classify/run-classifiers field {:global
{:distinct-count
(dec field-values/category-cardinality-threshold)
:nil% 0.3}})]
(is (= {:has_field_values :auto-list, :semantic_type :type/Category}
(select-keys classified [:has_field_values :semantic_type])))))
(testing "Earlier classifiers prevent later classifiers"
(let [field (->field {:name "site_url" :base_type :type/Text})
fingerprint {:global {:distinct-count 4
:nil% 0}}
classified (classify/run-classifiers field fingerprint)]
(is (= {:has_field_values :auto-list, :semantic_type :type/URL}
(select-keys classified [:has_field_values :semantic_type])))))
(testing "Classififying using fingerprinters can override previous classifications"
(testing "Classify state fields on fingerprint rather than name"
(let [field (->field {:name "order_state" :base_type :type/Text})
fingerprint {:global {:distinct-count 4
:nil% 0}
:type {:type/Text {:percent-state 0.98}}}
classified (classify/run-classifiers field fingerprint)]
(is (= {:has_field_values :auto-list, :semantic_type :type/State}
(select-keys classified [:has_field_values :semantic_type])))))
(let [field (->field {:name "order_status" :base_type :type/Text})
fingerprint {:type {:type/Text {:percent-json 0.99}}}]
(is (= :type/SerializedJSON
(:semantic_type (classify/run-classifiers field fingerprint)))))))
|
e6e7ff34d27dd5b799df9288a33de1baf1ef7f4b38507e478259cffe253ddfea | ertugrulcetin/konva-cljs | canvas_scrolling.cljs | (ns examples.canvas-scrolling
(:require [konva-cljs.components :as c]
[reagent.core :as r]
[goog.dom :as dom]
[goog.object :as ob]))
(def padding 500)
(def height 3000)
(def width 3000)
(def state (atom {}))
(defn- reposition-stage []
(let [scroll-container (dom/getElement "scroll-container")
dx (- (.-scrollLeft scroll-container) padding)
dy (- (.-scrollTop scroll-container) padding)
stage (:stage @state)]
(set! (.-transform (.-style (.container stage))) (str "translate(" dx "px, " dy "px)"))
(.x stage (- dx))
(.y stage (- dy))
(.batchDraw stage)))
(defn- canvas-scroll-comp []
(r/create-class
{:component-did-mount (fn []
(.addEventListener (dom/getElement "scroll-container") "scroll" reposition-stage)
(reposition-stage)
(doseq [c (vals (:circles @state))]
(.cache c)))
:reagent-render (fn []
[:div#scroll-container
[:div#large-container
[:div#container
[c/stage {:width (+ (.-innerWidth js/window) (* 2 padding))
:height (+ (.-innerHeight js/window) (* 2 padding))
:ref #(swap! state assoc :stage %)}
[c/layer
(for [n (range 200)]
^{:key n}
[c/circle {:x (* width (Math/random))
:y (* height (Math/random))
:ref #(swap! state assoc-in [:circles n] %)
:radius 50
:fill "red"
:draggable true
:stroke "black"}])]]]]])}))
| null | https://raw.githubusercontent.com/ertugrulcetin/konva-cljs/338e3e76a10857e12880ddf10ca05b0b4a2a653e/examples/src/cljs/examples/canvas_scrolling.cljs | clojure | (ns examples.canvas-scrolling
(:require [konva-cljs.components :as c]
[reagent.core :as r]
[goog.dom :as dom]
[goog.object :as ob]))
(def padding 500)
(def height 3000)
(def width 3000)
(def state (atom {}))
(defn- reposition-stage []
(let [scroll-container (dom/getElement "scroll-container")
dx (- (.-scrollLeft scroll-container) padding)
dy (- (.-scrollTop scroll-container) padding)
stage (:stage @state)]
(set! (.-transform (.-style (.container stage))) (str "translate(" dx "px, " dy "px)"))
(.x stage (- dx))
(.y stage (- dy))
(.batchDraw stage)))
(defn- canvas-scroll-comp []
(r/create-class
{:component-did-mount (fn []
(.addEventListener (dom/getElement "scroll-container") "scroll" reposition-stage)
(reposition-stage)
(doseq [c (vals (:circles @state))]
(.cache c)))
:reagent-render (fn []
[:div#scroll-container
[:div#large-container
[:div#container
[c/stage {:width (+ (.-innerWidth js/window) (* 2 padding))
:height (+ (.-innerHeight js/window) (* 2 padding))
:ref #(swap! state assoc :stage %)}
[c/layer
(for [n (range 200)]
^{:key n}
[c/circle {:x (* width (Math/random))
:y (* height (Math/random))
:ref #(swap! state assoc-in [:circles n] %)
:radius 50
:fill "red"
:draggable true
:stroke "black"}])]]]]])}))
| |
2ddd874706bdc4a886d87f8038c69e0114d6c742b440d14e76deeedefe2ae0bd | psholtz/MIT-SICP | exercise2-30.scm | ;;
;; Exercise 2.30
;;
;; Define a procedure "square-tree" analogous to the "square-list" procedure of Exercise
2.21 . That is , " square - tree " should behave as follows :
;;
( square - tree ( list 1 ( list 2 ( list 3 4 ) 5 ) ( list 6 7 ) ) )
= = > ( 1 ( 4 ( 9 16 ) 25 ) ( 36 49 ) )
;;
;;
;; Define supporting procedures:
;;
(define (square n) (* n n))
;;
;; Define "square-tree" directly:
;;
(define (square-tree tree)
(cond ((null? tree) '())
((not (pair? tree)) (square tree))
(else
(cons (square-tree (car tree))
(square-tree (cdr tree))))))
;;
;; Run some unit tests:
;;
(square-tree (list 1 (list 2 (list 3 4) 5) (list 6 7)))
= = > ( 1 ( 4 ( 9 16 ) 25 ) ( 36 49 ) )
;;
;; Define "square-tree" using map and lambda:
;;
(define (square-tree tree)
(map (lambda (sub-tree)
(if (pair? sub-tree)
(square-tree sub-tree)
(square sub-tree)))
tree))
;;
;; Run some unit tests:
;;
(square-tree (list 1 (list 2 (list 3 4) 5) (list 6 7)))
= = > ( 1 ( 4 ( 9 16 ) 25 ) ( 36 49 ) ) | null | https://raw.githubusercontent.com/psholtz/MIT-SICP/01e9b722ac5008e26f386624849117ca8fa80906/Section-2.2/mit-scheme/exercise2-30.scm | scheme |
Exercise 2.30
Define a procedure "square-tree" analogous to the "square-list" procedure of Exercise
Define supporting procedures:
Define "square-tree" directly:
Run some unit tests:
Define "square-tree" using map and lambda:
Run some unit tests:
| 2.21 . That is , " square - tree " should behave as follows :
( square - tree ( list 1 ( list 2 ( list 3 4 ) 5 ) ( list 6 7 ) ) )
= = > ( 1 ( 4 ( 9 16 ) 25 ) ( 36 49 ) )
(define (square n) (* n n))
(define (square-tree tree)
(cond ((null? tree) '())
((not (pair? tree)) (square tree))
(else
(cons (square-tree (car tree))
(square-tree (cdr tree))))))
(square-tree (list 1 (list 2 (list 3 4) 5) (list 6 7)))
= = > ( 1 ( 4 ( 9 16 ) 25 ) ( 36 49 ) )
(define (square-tree tree)
(map (lambda (sub-tree)
(if (pair? sub-tree)
(square-tree sub-tree)
(square sub-tree)))
tree))
(square-tree (list 1 (list 2 (list 3 4) 5) (list 6 7)))
= = > ( 1 ( 4 ( 9 16 ) 25 ) ( 36 49 ) ) |
801b91ba2dbb15385ad780632020efdfcd219718f04f2f0a9297ebcb26c101fb | glutamate/bugpan | Compiler.hs | module Compiler where
import Expr
import EvalM
import System.Random
import Data.HashTable as H
import Daq
import Numbers
import Control.Concurrent
import Statement
import BuiltIn
import PrettyPrint
import RandomSources
import OpenGL (setTexture)
compile :: [Declare] -> [Stmt]
compile ds = let c = concatMap compileDec (filter noDtSeconds (bivDecls++ds)) in
concat [constEnv c, initSigVals c, mainLoop c]
noDtSeconds :: Declare -> Bool
noDtSeconds (Let (PatVar "dt" _) _) = False
noDtSeconds (Let (PatVar "seconds" _) _) = False
noDtSeconds _ = True
compileDec :: Declare -> [Stmt]
compileDec (Let (PatVar nm _) (Sig se)) = [SigUpdateRule nm $ unVal se]
compileDec (Let (PatVar nm _) (SigLimited se lim)) = [SigUpdateRule nm $ unVal se]
compileDec (Let (PatVar nm _) (SigDelay (Var sn) v0)) = [SigUpdateRule nm (Var sn),
InitSig nm v0]
compileDec (Let (PatVar nm _) (Event ee)) = [EventAddRule nm $ unVal ee]
compileDec (Let (PatVar nm _) (Forget tm ee)) = [EventAddRule nm $ Forget tm $ unVal ee]
compileDec (Let (PatVar nm _) (Switch ses ser)) =
[SigUpdateRule nm (Switch (map noSig ses) $ unSig (unVal ser))]
where noSig (e,s) = (e, unVal $ mapE unSig s)
unSig (Sig se) = se
unSig e = e
compileDec rs@(ReadSource nm ("adc", _)) = compileAdcSrc rs
compileDec ( ReadSource nm ( " loadTexture " , ( Const fnm ) ) ) =
[ RunInGLThread $ \env - > do
setTexture $ (
print " HELLLOOOO ! ! ! ! ! ! ! ! ! ! ! ! "
update env nm $ BoxV ( p3 1 1 1 ) ( p3 ( -0.5 ) ( -0.5 ) 0 ) ( p3 1 1 1 )
return ( ) ]
[RunInGLThread $ \env -> do
setTexture $ (unsafeReify fnm)::String
print "HELLLOOOO!!!!!!!!!!!!"
update env nm $ BoxV (p3 1 1 1) (p3 (-0.5) (-0.5) 0) (p3 1 1 1)
return () ] -}
compileDec (ReadSource nm (srcNm, (Const arg))) = [ReadSrcAction nm $ genSrc srcNm arg]
compileDec (Let (PatVar nm _) e) = [Env nm $ unVal e]
compileDec (SinkConnect (Var nm) (snkNm,_)) = [SigSnkConn nm snkNm]
compileDec (Stage _ _) = []
compileDec (DeclareType _ _) = []
compileDec s = error $ "compileDec: unknown decl "++show s
unVal :: E -> E
unVal = mapE f
where f (SigVal (Var n)) = Var n
f e = e
inMainLoop (SigUpdateRule _ _) = True
inMainLoop (EventAddRule _ _) = True
inMainLoop (SigSnkConn _ _) = True
inMainLoop (ReadSrcAction _ _) = True
inMainLoop (RunPrepare _) = True
inMainLoop (RunInGLThread _) = True
inMainLoop (RunAfterDone _) = True
inMainLoop (RunAfterGo _) = True
inMainLoop (Trigger _) = True
inMainLoop (GLParams _ _) = True
--inMainLoop (ReadSrcAction _ _) = True
inMainLoop _ = False
ppStmt :: Stmt -> String
ppStmt (InitSig n e) = concat [n, "(0) = ", pp e]
ppStmt (Env n e) = concat [n, " = ", pp e]
ppStmt (SigUpdateRule n e) = concat [n, " = {: ", pp e, " :}"]
ppStmt (EventAddRule n e) = concat [n, " = [: ", pp e, " :]"]
ppStmt (SigSnkConn vn sn) = concat [vn, " *> ", sn]
ppStmt (ReadSrcAction nm _) = nm ++ " <- <signal source>"
ppStmt (RunPrepare _) = "prepare something"
ppStmt (RunInGLThread _) = "run something in GL throead"
ppStmt (RunAfterDone _) = "run something after done"
ppStmt (RunAfterGo _) = "run something after go"
ppStmt (Trigger _) = "trigger somehow"
ppStmt (GLParams _ _) = "gl parameters"
initSigVals stmts = [is | is@(InitSig nm v) <- stmts]
constEnv stmts = [en | en@(Env nm v) <- stmts]
mainLoop stmts = filter inMainLoop stmts
genSrc :: String -> V -> (RealNum -> RealNum -> IO V)
genSrc "bernoulli" rateS t dt =
do rnd <- randomRIO (0,1)
return . BoolV $ rnd < ( unsafeReify rateS)*dt
genSrc "uniform" (PairV lo hi) t dt =
do rnd <- randomRIO ( unsafeReify lo, unsafeReify hi)
return . NumV . NReal $ rnd
genSrc nms _ _ _ = error $ "unknown source: "++show nms
p3 x y z = (PairV (PairV x y) z)
{- note: Now,
Event :: [(T,a)] -> Event a
what if
Event :: ([(T,a)] -> [(T,a)]) -> Event a
or something like that
-}
| null | https://raw.githubusercontent.com/glutamate/bugpan/d0983152f5afce306049262cba296df00e52264b/Compiler.hs | haskell | inMainLoop (ReadSrcAction _ _) = True
note: Now,
Event :: [(T,a)] -> Event a
what if
Event :: ([(T,a)] -> [(T,a)]) -> Event a
or something like that
| module Compiler where
import Expr
import EvalM
import System.Random
import Data.HashTable as H
import Daq
import Numbers
import Control.Concurrent
import Statement
import BuiltIn
import PrettyPrint
import RandomSources
import OpenGL (setTexture)
compile :: [Declare] -> [Stmt]
compile ds = let c = concatMap compileDec (filter noDtSeconds (bivDecls++ds)) in
concat [constEnv c, initSigVals c, mainLoop c]
noDtSeconds :: Declare -> Bool
noDtSeconds (Let (PatVar "dt" _) _) = False
noDtSeconds (Let (PatVar "seconds" _) _) = False
noDtSeconds _ = True
compileDec :: Declare -> [Stmt]
compileDec (Let (PatVar nm _) (Sig se)) = [SigUpdateRule nm $ unVal se]
compileDec (Let (PatVar nm _) (SigLimited se lim)) = [SigUpdateRule nm $ unVal se]
compileDec (Let (PatVar nm _) (SigDelay (Var sn) v0)) = [SigUpdateRule nm (Var sn),
InitSig nm v0]
compileDec (Let (PatVar nm _) (Event ee)) = [EventAddRule nm $ unVal ee]
compileDec (Let (PatVar nm _) (Forget tm ee)) = [EventAddRule nm $ Forget tm $ unVal ee]
compileDec (Let (PatVar nm _) (Switch ses ser)) =
[SigUpdateRule nm (Switch (map noSig ses) $ unSig (unVal ser))]
where noSig (e,s) = (e, unVal $ mapE unSig s)
unSig (Sig se) = se
unSig e = e
compileDec rs@(ReadSource nm ("adc", _)) = compileAdcSrc rs
compileDec ( ReadSource nm ( " loadTexture " , ( Const fnm ) ) ) =
[ RunInGLThread $ \env - > do
setTexture $ (
print " HELLLOOOO ! ! ! ! ! ! ! ! ! ! ! ! "
update env nm $ BoxV ( p3 1 1 1 ) ( p3 ( -0.5 ) ( -0.5 ) 0 ) ( p3 1 1 1 )
return ( ) ]
[RunInGLThread $ \env -> do
setTexture $ (unsafeReify fnm)::String
print "HELLLOOOO!!!!!!!!!!!!"
update env nm $ BoxV (p3 1 1 1) (p3 (-0.5) (-0.5) 0) (p3 1 1 1)
return () ] -}
compileDec (ReadSource nm (srcNm, (Const arg))) = [ReadSrcAction nm $ genSrc srcNm arg]
compileDec (Let (PatVar nm _) e) = [Env nm $ unVal e]
compileDec (SinkConnect (Var nm) (snkNm,_)) = [SigSnkConn nm snkNm]
compileDec (Stage _ _) = []
compileDec (DeclareType _ _) = []
compileDec s = error $ "compileDec: unknown decl "++show s
unVal :: E -> E
unVal = mapE f
where f (SigVal (Var n)) = Var n
f e = e
inMainLoop (SigUpdateRule _ _) = True
inMainLoop (EventAddRule _ _) = True
inMainLoop (SigSnkConn _ _) = True
inMainLoop (ReadSrcAction _ _) = True
inMainLoop (RunPrepare _) = True
inMainLoop (RunInGLThread _) = True
inMainLoop (RunAfterDone _) = True
inMainLoop (RunAfterGo _) = True
inMainLoop (Trigger _) = True
inMainLoop (GLParams _ _) = True
inMainLoop _ = False
ppStmt :: Stmt -> String
ppStmt (InitSig n e) = concat [n, "(0) = ", pp e]
ppStmt (Env n e) = concat [n, " = ", pp e]
ppStmt (SigUpdateRule n e) = concat [n, " = {: ", pp e, " :}"]
ppStmt (EventAddRule n e) = concat [n, " = [: ", pp e, " :]"]
ppStmt (SigSnkConn vn sn) = concat [vn, " *> ", sn]
ppStmt (ReadSrcAction nm _) = nm ++ " <- <signal source>"
ppStmt (RunPrepare _) = "prepare something"
ppStmt (RunInGLThread _) = "run something in GL throead"
ppStmt (RunAfterDone _) = "run something after done"
ppStmt (RunAfterGo _) = "run something after go"
ppStmt (Trigger _) = "trigger somehow"
ppStmt (GLParams _ _) = "gl parameters"
initSigVals stmts = [is | is@(InitSig nm v) <- stmts]
constEnv stmts = [en | en@(Env nm v) <- stmts]
mainLoop stmts = filter inMainLoop stmts
genSrc :: String -> V -> (RealNum -> RealNum -> IO V)
genSrc "bernoulli" rateS t dt =
do rnd <- randomRIO (0,1)
return . BoolV $ rnd < ( unsafeReify rateS)*dt
genSrc "uniform" (PairV lo hi) t dt =
do rnd <- randomRIO ( unsafeReify lo, unsafeReify hi)
return . NumV . NReal $ rnd
genSrc nms _ _ _ = error $ "unknown source: "++show nms
p3 x y z = (PairV (PairV x y) z)
|
21df5566858ddc6ae5a25b95a3c32684a680a3b4f41c98f0d27dd91cd9bce5f8 | Liqwid-Labs/plutus-extra | Natural.hs | # LANGUAGE QuasiQuotes #
module Suites.Natural (tests) where
import PlutusTx.Natural (
Natural,
Parity (Even, Odd),
nat,
parity,
)
import PlutusTx.Numeric.Extra (powNat, rem, (^-))
import PlutusTx.Prelude qualified as Plutus
import Test.QuickCheck (
Property,
forAllShrink,
(===),
)
import Test.QuickCheck.Arbitrary (arbitrary, shrink)
import Test.Tasty (TestTree, localOption, testGroup)
import Test.Tasty.QuickCheck (QuickCheckTests, testProperty)
import Prelude hiding (divMod, product, rem)
tests :: [TestTree]
tests =
[ localOption go . testProperty "Parity" $ parityProp
, localOption go . testGroup "Exponentiation" $
[ testProperty "x `powNat` 0 = mempty" expProp1
, testProperty "x `powNat` 1 = x" expProp2
, testProperty "x `powNat` n = fold . repeat n $ x" expProp3
]
]
where
go :: QuickCheckTests
go = 1000000
expProp1 :: Property
expProp1 = forAllShrink arbitrary shrink go
where
go :: Natural -> Property
go x = x `powNat` Plutus.zero === Plutus.one
expProp2 :: Property
expProp2 = forAllShrink arbitrary shrink go
where
go :: Natural -> Property
go x = x `powNat` Plutus.one === x
expProp3 :: Property
expProp3 = forAllShrink arbitrary shrink go
where
go :: (Natural, Natural) -> Property
go (x, n) = x `powNat` n === (product . clone n $ x)
clone :: Natural -> Natural -> [Natural]
clone n x =
if n == Plutus.zero
then []
else x : clone (n ^- Plutus.one) x
product :: [Natural] -> Natural
product = \case
[] -> Plutus.one
(n : ns) -> n Plutus.* product ns
parityProp :: Property
parityProp = forAllShrink arbitrary shrink go
where
go :: Natural -> Property
go x = case x `rem` [nat| 2 |] of
[nat| 0 |] -> parity x === Even
_ -> parity x === Odd
| null | https://raw.githubusercontent.com/Liqwid-Labs/plutus-extra/592b4fbc6d0a66e6ca8f105224839783bbb0a387/plutus-numeric/test/property/Suites/Natural.hs | haskell | # LANGUAGE QuasiQuotes #
module Suites.Natural (tests) where
import PlutusTx.Natural (
Natural,
Parity (Even, Odd),
nat,
parity,
)
import PlutusTx.Numeric.Extra (powNat, rem, (^-))
import PlutusTx.Prelude qualified as Plutus
import Test.QuickCheck (
Property,
forAllShrink,
(===),
)
import Test.QuickCheck.Arbitrary (arbitrary, shrink)
import Test.Tasty (TestTree, localOption, testGroup)
import Test.Tasty.QuickCheck (QuickCheckTests, testProperty)
import Prelude hiding (divMod, product, rem)
tests :: [TestTree]
tests =
[ localOption go . testProperty "Parity" $ parityProp
, localOption go . testGroup "Exponentiation" $
[ testProperty "x `powNat` 0 = mempty" expProp1
, testProperty "x `powNat` 1 = x" expProp2
, testProperty "x `powNat` n = fold . repeat n $ x" expProp3
]
]
where
go :: QuickCheckTests
go = 1000000
expProp1 :: Property
expProp1 = forAllShrink arbitrary shrink go
where
go :: Natural -> Property
go x = x `powNat` Plutus.zero === Plutus.one
expProp2 :: Property
expProp2 = forAllShrink arbitrary shrink go
where
go :: Natural -> Property
go x = x `powNat` Plutus.one === x
expProp3 :: Property
expProp3 = forAllShrink arbitrary shrink go
where
go :: (Natural, Natural) -> Property
go (x, n) = x `powNat` n === (product . clone n $ x)
clone :: Natural -> Natural -> [Natural]
clone n x =
if n == Plutus.zero
then []
else x : clone (n ^- Plutus.one) x
product :: [Natural] -> Natural
product = \case
[] -> Plutus.one
(n : ns) -> n Plutus.* product ns
parityProp :: Property
parityProp = forAllShrink arbitrary shrink go
where
go :: Natural -> Property
go x = case x `rem` [nat| 2 |] of
[nat| 0 |] -> parity x === Even
_ -> parity x === Odd
| |
19629f1adc5b74b078719023b14e51feb83f6ae77914f96b297392862fa4c6e3 | robert-strandh/SICL | packages.lisp | (cl:in-package #:common-lisp-user)
(defpackage #:sicl-compiler
(:use #:common-lisp)
(:local-nicknames (#:env #:sicl-environment))
(:shadow #:undefined-function)
(:export #:debug-information
#:code-object
#:instructions
#:literals
#:call-sites
#:ensure-literal
#:establish-call-site
#:function-names
#:hir
#:compile-ast
#:tie-code-object
#:ast-from-file
#:ast-from-stream
#:undefined-function
#:undefined-variable
#:undefined-block
#:undefined-tagbody-tag
#:call-site
#:instruction
#:name
#:arguments
#:offset
#:instructions))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/a99a73f6285279c04859a2b4cedb059b1bb0f268/Code/Compiler/packages.lisp | lisp | (cl:in-package #:common-lisp-user)
(defpackage #:sicl-compiler
(:use #:common-lisp)
(:local-nicknames (#:env #:sicl-environment))
(:shadow #:undefined-function)
(:export #:debug-information
#:code-object
#:instructions
#:literals
#:call-sites
#:ensure-literal
#:establish-call-site
#:function-names
#:hir
#:compile-ast
#:tie-code-object
#:ast-from-file
#:ast-from-stream
#:undefined-function
#:undefined-variable
#:undefined-block
#:undefined-tagbody-tag
#:call-site
#:instruction
#:name
#:arguments
#:offset
#:instructions))
| |
5652859d21a05eb647a19c329fc330008db738c30b06f312c8463ecc1fb32f06 | randomseed-io/bankster | fs.clj | (ns io.randomseed.bankster.util.fs
^{:doc "Support functions and macros, filesystem operations."
:author "Paweł Wilk"
:added "1.0.0"}
(:require [clojure.string :as str]
[clojure.java.io :as io]
[clojure.java.classpath :as cp]
[clojure.data.csv :as csv]
[clojure.edn :as edn]
[io.randomseed.bankster.util :refer :all])
(:import [org.apache.commons.io.input BOMInputStream]
[org.apache.commons.io ByteOrderMark]
[java.nio.file Path Paths]))
(def ^String ^:const default-encoding
"Default encoding for input files."
"UTF-8")
(def ^"[Ljava.lang.String;"
empty-str-ary
(into-array [""]))
(defn ^Boolean absolute-path?
[pathname]
(.isAbsolute ^Path (Paths/get ^String (str pathname)
^"[Ljava.lang.String;" empty-str-ary)))
(def ^Boolean relative-path?
(complement absolute-path?))
(defn ^clojure.lang.LazySeq get-java-classpath-folders
"Lists all directories which exist in Java classpath as a sequence of
strings. Returns nil if there are none."
[]
(seq (map str (filter #(.isDirectory (io/file %)) (cp/classpath)))))
(defn prop-pathname
"For the given Java property name and optional path names creates a path name
expressed as a string by prefixing them with the directory obtained from a
property with all parts joined using pathname separator."
([prop] (some-> (System/getProperty (str prop)) str))
([prop paths] (some->> paths (remove nil?) seq
(apply io/file (System/getProperty (str prop)))
str)))
(defn user-dir-pathname
"For the given pathnames creates a pathname expressed as a string by prefixing them
with user's directory (typically a project directory) obtained from the Java
property `user.dir` with all parts joined using current path name separator."
([] (prop-pathname "user.dir"))
([& paths] (prop-pathname "user.dir" paths)))
(defn home-dir-pathname
"For the given pathnames creates a pathname expressed as a string by prefixing them
with user's home directory obtained from the Java property `user.dir` with all parts
joined using current path name separator."
([] (prop-pathname "user.home"))
([& paths] (prop-pathname "user.home" paths)))
(defn ^String resource-pathname
"For the given pathnames creates a pathname expressed as a string that resides within
one of the Java resource directories. The path must exist to be returned. WARNING:
it will only work for resources on a filesystem, giving you the regular pathname,
not URI."
([] (some-> (io/resource "") io/file str))
([& paths] (some->> paths (remove nil?) seq
(apply io/file) str
io/resource
io/file
str)))
(defn paths->resource
"For the given pathnames creates a resource object that resides within one of the
Java resource directories. The resource must exist for the URI to be returned."
{:tag java.net.URL :added "1.0.0"}
([] (when-some [r (io/resource "")] r))
([& paths] (some->> paths (remove nil?) seq
(apply io/file) str
io/resource)))
(defn get-resource
"For the given pathname, returns the resource URL if the path exists. If the path
does not exist, returns nil."
{:tag java.net.URL :added "1.2.4"}
[pname]
(.getResource
(.. Thread currentThread getContextClassLoader)
pname))
(defn ^Boolean integer-string?
"Returns true if string contains valid integer number."
[^String s]
(try
(boolean (and (some? s) (Integer/parseInt s)))
(catch NumberFormatException e false)))
(def ^:private bom-utf-ary
"Array of BOM encodings."
(into-array [ByteOrderMark/UTF_16LE
ByteOrderMark/UTF_16BE
ByteOrderMark/UTF_8
ByteOrderMark/UTF_32BE
ByteOrderMark/UTF_32LE]))
(defn read-preferences
"Reads the given preference file. If the path is relative it will be relative to
user's home directory. Optional options map will be passed to EDN reader."
([^String filename]
(read-preferences filename nil))
([^String filename opts]
(when (some? filename)
(when-some [abs-filename (if (relative-path? filename) (home-dir-pathname filename) filename)]
(with-open [r (io/reader abs-filename)]
(if (nil? opts)
(edn/read (java.io.PushbackReader. r))
(edn/read opts (java.io.PushbackReader. r))))))))
(defn rtrim-comments
[^String s]
(str/trimr
(str/join
(first (take 1 (partition-by #{\#} s))))))
(defn ^clojure.lang.LazySeq read-csv
"Reads CSV file and returns a lazy sequence of rows."
[resource]
(let [stream (io/input-stream resource)
bstream (BOMInputStream. stream true ^longs bom-utf-ary)
bomenc (.getBOM bstream)
encoding (if (some? bomenc) (.getCharsetName bomenc) default-encoding)]
(with-open [reader (io/reader bstream :encoding encoding)]
(doall
(->> reader line-seq
(map rtrim-comments)
(remove (comp #{\#} first))
(remove empty?)
(str/join "\n")
csv/read-csv)))))
| null | https://raw.githubusercontent.com/randomseed-io/bankster/a4e1c475e87b5d1824e6831771dfbb85da537d59/src/io/randomseed/bankster/util/fs.clj | clojure | (ns io.randomseed.bankster.util.fs
^{:doc "Support functions and macros, filesystem operations."
:author "Paweł Wilk"
:added "1.0.0"}
(:require [clojure.string :as str]
[clojure.java.io :as io]
[clojure.java.classpath :as cp]
[clojure.data.csv :as csv]
[clojure.edn :as edn]
[io.randomseed.bankster.util :refer :all])
(:import [org.apache.commons.io.input BOMInputStream]
[org.apache.commons.io ByteOrderMark]
[java.nio.file Path Paths]))
(def ^String ^:const default-encoding
"Default encoding for input files."
"UTF-8")
(def ^"[Ljava.lang.String;"
empty-str-ary
(into-array [""]))
(defn ^Boolean absolute-path?
[pathname]
(.isAbsolute ^Path (Paths/get ^String (str pathname)
^"[Ljava.lang.String;" empty-str-ary)))
(def ^Boolean relative-path?
(complement absolute-path?))
(defn ^clojure.lang.LazySeq get-java-classpath-folders
"Lists all directories which exist in Java classpath as a sequence of
strings. Returns nil if there are none."
[]
(seq (map str (filter #(.isDirectory (io/file %)) (cp/classpath)))))
(defn prop-pathname
"For the given Java property name and optional path names creates a path name
expressed as a string by prefixing them with the directory obtained from a
property with all parts joined using pathname separator."
([prop] (some-> (System/getProperty (str prop)) str))
([prop paths] (some->> paths (remove nil?) seq
(apply io/file (System/getProperty (str prop)))
str)))
(defn user-dir-pathname
"For the given pathnames creates a pathname expressed as a string by prefixing them
with user's directory (typically a project directory) obtained from the Java
property `user.dir` with all parts joined using current path name separator."
([] (prop-pathname "user.dir"))
([& paths] (prop-pathname "user.dir" paths)))
(defn home-dir-pathname
"For the given pathnames creates a pathname expressed as a string by prefixing them
with user's home directory obtained from the Java property `user.dir` with all parts
joined using current path name separator."
([] (prop-pathname "user.home"))
([& paths] (prop-pathname "user.home" paths)))
(defn ^String resource-pathname
"For the given pathnames creates a pathname expressed as a string that resides within
one of the Java resource directories. The path must exist to be returned. WARNING:
it will only work for resources on a filesystem, giving you the regular pathname,
not URI."
([] (some-> (io/resource "") io/file str))
([& paths] (some->> paths (remove nil?) seq
(apply io/file) str
io/resource
io/file
str)))
(defn paths->resource
"For the given pathnames creates a resource object that resides within one of the
Java resource directories. The resource must exist for the URI to be returned."
{:tag java.net.URL :added "1.0.0"}
([] (when-some [r (io/resource "")] r))
([& paths] (some->> paths (remove nil?) seq
(apply io/file) str
io/resource)))
(defn get-resource
"For the given pathname, returns the resource URL if the path exists. If the path
does not exist, returns nil."
{:tag java.net.URL :added "1.2.4"}
[pname]
(.getResource
(.. Thread currentThread getContextClassLoader)
pname))
(defn ^Boolean integer-string?
"Returns true if string contains valid integer number."
[^String s]
(try
(boolean (and (some? s) (Integer/parseInt s)))
(catch NumberFormatException e false)))
(def ^:private bom-utf-ary
"Array of BOM encodings."
(into-array [ByteOrderMark/UTF_16LE
ByteOrderMark/UTF_16BE
ByteOrderMark/UTF_8
ByteOrderMark/UTF_32BE
ByteOrderMark/UTF_32LE]))
(defn read-preferences
"Reads the given preference file. If the path is relative it will be relative to
user's home directory. Optional options map will be passed to EDN reader."
([^String filename]
(read-preferences filename nil))
([^String filename opts]
(when (some? filename)
(when-some [abs-filename (if (relative-path? filename) (home-dir-pathname filename) filename)]
(with-open [r (io/reader abs-filename)]
(if (nil? opts)
(edn/read (java.io.PushbackReader. r))
(edn/read opts (java.io.PushbackReader. r))))))))
(defn rtrim-comments
[^String s]
(str/trimr
(str/join
(first (take 1 (partition-by #{\#} s))))))
(defn ^clojure.lang.LazySeq read-csv
"Reads CSV file and returns a lazy sequence of rows."
[resource]
(let [stream (io/input-stream resource)
bstream (BOMInputStream. stream true ^longs bom-utf-ary)
bomenc (.getBOM bstream)
encoding (if (some? bomenc) (.getCharsetName bomenc) default-encoding)]
(with-open [reader (io/reader bstream :encoding encoding)]
(doall
(->> reader line-seq
(map rtrim-comments)
(remove (comp #{\#} first))
(remove empty?)
(str/join "\n")
csv/read-csv)))))
| |
17d96c0eb6d477c3ba9cd46eea8977ddf70f814dc490309a6a0ae8b879805fc4 | windymelt/cl-string-random | main.lisp | (defpackage cl-string-random/tests/main
(:use :cl
:cl-string-random
:rove
:iterate))
(in-package :cl-string-random/tests/main)
;; NOTE: To run this test file, execute `(asdf:test-system :cl-string-random)' in your Lisp.
(defparameter *regexes*
'("" "a" "ab" "[ab]" "a|b" "(ab)" "a*" "a+" "(ab)*" "(ab)+" "(ab){4,10}" "(日|本|語)*" "\\d" "\\d{3}-\\d{4}" "\\s\\s\\s\\s"))
(deftest test-target-1
(iter (for regex in *regexes*)
(testing regex
(ok (cl-ppcre:scan regex (string-random regex))))))
| null | https://raw.githubusercontent.com/windymelt/cl-string-random/c13bca32e8e7b04573e08f27581210f8b596966e/tests/main.lisp | lisp | NOTE: To run this test file, execute `(asdf:test-system :cl-string-random)' in your Lisp. | (defpackage cl-string-random/tests/main
(:use :cl
:cl-string-random
:rove
:iterate))
(in-package :cl-string-random/tests/main)
(defparameter *regexes*
'("" "a" "ab" "[ab]" "a|b" "(ab)" "a*" "a+" "(ab)*" "(ab)+" "(ab){4,10}" "(日|本|語)*" "\\d" "\\d{3}-\\d{4}" "\\s\\s\\s\\s"))
(deftest test-target-1
(iter (for regex in *regexes*)
(testing regex
(ok (cl-ppcre:scan regex (string-random regex))))))
|
ac0f15b1a3167b66bd0112d68f6b3179c87730c7830223513c309a0c541d71ea | softwarelanguageslab/maf | R5RS_ad_qstand-2.scm | ; Changes:
* removed : 1
* added : 1
* swaps : 1
; * negated predicates: 0
* swapped branches : 1
; * calls to id fun: 0
(letrec ((quick-sort (lambda (vector)
(letrec ((swap (lambda (vector index1 index2)
(let ((temp (vector-ref vector index1)))
(<change>
(vector-set! vector index1 (vector-ref vector index2))
())
(vector-set! vector index2 temp))))
(quick-sort-aux (lambda (low high)
(letrec ((quick-sort-aux-iter (lambda (mid-value from to)
(letrec ((quick-right (lambda (index1)
(if (< (vector-ref vector index1) mid-value)
(quick-right (+ index1 1))
index1)))
(quick-left (lambda (index2)
(if (> (vector-ref vector index2) mid-value)
(quick-left (- index2 1))
index2))))
(let ((index1 (quick-right (+ from 1)))
(index2 (quick-left to)))
(if (< index1 index2)
(begin
(swap vector index1 index2)
(quick-sort-aux-iter mid-value index1 index2))
index2))))))
(if (< low high)
(begin
(if (> (vector-ref vector low) (vector-ref vector high))
(<change>
(swap vector low high)
#f)
(<change>
#f
(swap vector low high)))
(<change>
()
vector)
(let ((mid-index (quick-sort-aux-iter (vector-ref vector low) low high)))
(swap vector mid-index low)
(quick-sort-aux low (- mid-index 1))
(quick-sort-aux (+ mid-index 1) high)))
#f)))))
(quick-sort-aux 0 (- (vector-length vector) 1)))))
(test1 (vector 7 2 4 6 0 8 5 3 1)))
(quick-sort test1)
(letrec ((test2 (vector 8 1 4 9 6 3 5 2 7 0)))
(quick-sort test2)
(letrec ((test3 (vector 8 3 6 6 1 5 4 2 9 6)))
(<change>
(quick-sort test3)
(if (equal? test1 (vector 0 1 2 3 4 5 6 7 8))
(if (equal? test2 (vector 0 1 2 3 4 5 6 7 8 9))
(equal? test3 (vector 1 2 3 4 5 6 6 6 8 9))
#f)
#f))
(<change>
(if (equal? test1 (vector 0 1 2 3 4 5 6 7 8))
(if (equal? test2 (vector 0 1 2 3 4 5 6 7 8 9))
(equal? test3 (vector 1 2 3 4 5 6 6 6 8 9))
#f)
#f)
(quick-sort test3))))) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_ad_qstand-2.scm | scheme | Changes:
* negated predicates: 0
* calls to id fun: 0 | * removed : 1
* added : 1
* swaps : 1
* swapped branches : 1
(letrec ((quick-sort (lambda (vector)
(letrec ((swap (lambda (vector index1 index2)
(let ((temp (vector-ref vector index1)))
(<change>
(vector-set! vector index1 (vector-ref vector index2))
())
(vector-set! vector index2 temp))))
(quick-sort-aux (lambda (low high)
(letrec ((quick-sort-aux-iter (lambda (mid-value from to)
(letrec ((quick-right (lambda (index1)
(if (< (vector-ref vector index1) mid-value)
(quick-right (+ index1 1))
index1)))
(quick-left (lambda (index2)
(if (> (vector-ref vector index2) mid-value)
(quick-left (- index2 1))
index2))))
(let ((index1 (quick-right (+ from 1)))
(index2 (quick-left to)))
(if (< index1 index2)
(begin
(swap vector index1 index2)
(quick-sort-aux-iter mid-value index1 index2))
index2))))))
(if (< low high)
(begin
(if (> (vector-ref vector low) (vector-ref vector high))
(<change>
(swap vector low high)
#f)
(<change>
#f
(swap vector low high)))
(<change>
()
vector)
(let ((mid-index (quick-sort-aux-iter (vector-ref vector low) low high)))
(swap vector mid-index low)
(quick-sort-aux low (- mid-index 1))
(quick-sort-aux (+ mid-index 1) high)))
#f)))))
(quick-sort-aux 0 (- (vector-length vector) 1)))))
(test1 (vector 7 2 4 6 0 8 5 3 1)))
(quick-sort test1)
(letrec ((test2 (vector 8 1 4 9 6 3 5 2 7 0)))
(quick-sort test2)
(letrec ((test3 (vector 8 3 6 6 1 5 4 2 9 6)))
(<change>
(quick-sort test3)
(if (equal? test1 (vector 0 1 2 3 4 5 6 7 8))
(if (equal? test2 (vector 0 1 2 3 4 5 6 7 8 9))
(equal? test3 (vector 1 2 3 4 5 6 6 6 8 9))
#f)
#f))
(<change>
(if (equal? test1 (vector 0 1 2 3 4 5 6 7 8))
(if (equal? test2 (vector 0 1 2 3 4 5 6 7 8 9))
(equal? test3 (vector 1 2 3 4 5 6 6 6 8 9))
#f)
#f)
(quick-sort test3))))) |
8fabf0602260c833a814dc683ccc542be85540e5cafe20efe86d7c6064418d1a | xclerc/ocamljava | javalink_startup.ml |
* This file is part of compiler .
* Copyright ( C ) 2007 - 2015 .
*
* compiler is free software ; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* ( with a change to choice of law ) .
*
* compiler 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
* Q Public License for more details .
*
* You should have received a copy of the Q Public License
* along with this program . If not , see
* < -1.0 > .
* This file is part of OCaml-Java compiler.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java compiler is free software; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* Trolltech (with a change to choice of law).
*
* OCaml-Java compiler 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
* Q Public License for more details.
*
* You should have received a copy of the Q Public License
* along with this program. If not, see
* <-1.0>.
*)
open Bytecodeutils
open BaristaLibrary
open Utils
let node = Instrtree.node
let leaf = Instrtree.leaf
let flatten = Instrtree.flatten
let compile_class ~name ~parent ~fields ~methods ~attributes =
let cd = { ClassDefinition.access_flags = [`Public; `Final; `Super];
name = name;
extends = Some parent;
implements = [];
fields = fields;
methods = methods;
attributes = attributes; } in
let buff = ByteBuffer.make_of_size 1024 in
let stream = OutputStream.make_of_buffer buff in
ClassFile.write (ClassDefinition.encode cd) stream;
OutputStream.close stream;
ByteBuffer.contents buff
let make_startup_class units_to_link execname =
let execname = Filename.basename execname in
let class_name = !Jclflags.java_package ^ "." ^ Jconfig.main_class in
let main_class = make_class class_name in
let classes =
List.flatten
(List.map
(fun (infos, _, _) ->
infos.Cmj_format.ui_additional_classes @ [infos.Cmj_format.ui_javaname])
units_to_link) in
let constructor_code =
node
[ leaf [ Instruction.ALOAD_0 ; Instruction.ALOAD_1 ] ;
cstr_AbstractNativeRunner ;
leaf [ Instruction.RETURN ] ] in
let constructor_method =
Method.Constructor
{ Method.cstr_flags = [`Private];
Method.cstr_descriptor = [`Class interface_NativeParameters];
Method.cstr_attributes = [`Code { Attribute.max_stack = u2 2;
Attribute.max_locals = u2 2;
Attribute.code = flatten constructor_code;
Attribute.exception_table = [];
Attribute.attributes = []; }]; } in
let copy_constructor_code =
node
[ leaf [ Instruction.ALOAD_0 ; Instruction.ALOAD_1 ] ;
cstr_copy_AbstractNativeRunner ;
leaf [ Instruction.RETURN ] ] in
let copy_constructor_method =
Method.Constructor
{ Method.cstr_flags = [`Private];
Method.cstr_descriptor = [`Class main_class];
Method.cstr_attributes = [`Code { Attribute.max_stack = u2 2;
Attribute.max_locals = u2 2;
Attribute.code = flatten copy_constructor_code;
Attribute.exception_table = [];
Attribute.attributes = []; }]; } in
let copy_code =
[ Instruction.NEW main_class ;
Instruction.DUP ;
Instruction.ALOAD_0 ;
Instruction.INVOKESPECIAL (main_class,
make_method "<init>",
([`Class main_class], `Void)) ;
Instruction.ARETURN ] in
let copy_method =
Method.Regular
{ Method.flags = [`Public];
Method.name = make_method "copy";
Method.descriptor = ([], `Class class_AbstractNativeRunner);
Method.attributes = [`Code { Attribute.max_stack = u2 3;
Attribute.max_locals = u2 1;
Attribute.code = copy_code;
Attribute.exception_table = [];
Attribute.attributes = []; }]; } in
let module_main_code =
List.concat
(List.map
(fun c ->
[ Instruction.ALOAD_0 ;
Instruction.DUP ;
Instruction.INVOKESTATIC
(make_class c,
make_method "entry",
([], `Class class_Value)) ;
Instruction.PUTFIELD (class_AbstractNativeRunner,
make_field "result",
`Class class_Value) ;
Instruction.INVOKEVIRTUAL
(`Class_or_interface class_AbstractNativeRunner,
make_method "incrGlobalsInited",
([], `Void)) ])
classes)
@ [ Instruction.RETURN ] in
let module_main_method =
Method.Regular
{ Method.flags = [`Protected];
Method.name = make_method "moduleMain";
Method.descriptor = ([], `Void);
Method.attributes = [`Code { Attribute.max_stack = u2 3;
Attribute.max_locals = u2 1;
Attribute.code = module_main_code;
Attribute.exception_table = [];
Attribute.attributes = []; }]; } in
let main_with_return_code =
let bare_canvas =
if !Jclflags.applet = Some Jclflags.Graphics then
Instruction.ICONST_1
else
Instruction.ICONST_0 in
let parameters =
node
[ leaf [ Instruction.LDC_W (`Class_or_interface main_class) ;
Instruction.LDC_W (`String (UTF8.of_string Jconfig.parameters_entry)) ] ;
meth_getResourceAsStream ;
leaf [ Instruction.ALOAD_0 ] ;
field_System_in ;
field_System_out ;
field_System_err ;
leaf [ bare_canvas ;
Instruction.LDC_W (`String (UTF8.of_string execname)) ;
Instruction.LDC_W (`Class_or_interface main_class) ] ;
meth_fromStream ] in
node
[ leaf [ Instruction.NEW main_class ;
Instruction.DUP ] ;
parameters ;
leaf [ Instruction.INVOKESPECIAL
(main_class,
make_method "<init>",
([`Class interface_NativeParameters], `Void)) ;
Instruction.ASTORE_1 ] ;
node (List.map
(fun c ->
let create =
Instruction.INVOKESTATIC
(make_class c,
make_method "createConstants",
([], `Class (Bytecodegen_constants.const_class_of_curr_class c))) in
node
[ leaf [ Instruction.ALOAD_1 ;
Instruction.LDC_W (`Class_or_interface (make_class c)) ;
create ] ;
meth_setConstant ])
classes) ;
leaf [ Instruction.ALOAD_1 ] ;
meth_execute ; (* calls moduleMain *)
leaf [ Instruction.ALOAD_1 ;
Instruction.ARETURN ] ] in
let main_with_return_method =
Method.Regular
{ Method.flags = [`Public; `Static];
Method.name = make_method "mainWithReturn";
Method.descriptor = ([`Array (`Class class_String)], `Class main_class);
Method.attributes = [`Code { Attribute.max_stack = u2 11;
Attribute.max_locals = u2 2;
Attribute.code = flatten main_with_return_code;
Attribute.exception_table = [];
Attribute.attributes = []; }]; } in
let main_scripting_code =
let parameters =
node
[ leaf [ Instruction.LDC_W (`Class_or_interface main_class) ;
Instruction.LDC_W (`String (UTF8.of_string Jconfig.parameters_entry)) ] ;
meth_getResourceAsStream ;
leaf [ Instruction.ALOAD_0 ;
Instruction.ALOAD_2 ;
Instruction.ALOAD_3 ;
Instruction.ALOAD (u1 4) ;
Instruction.ICONST_0 ;
Instruction.LDC_W (`String (UTF8.of_string execname)) ;
Instruction.LDC_W (`Class_or_interface main_class) ] ;
meth_fromStream ] in
node
[ leaf [ Instruction.NEW main_class ;
Instruction.DUP ] ;
parameters ;
leaf [ Instruction.INVOKESPECIAL
(main_class,
make_method "<init>",
([`Class interface_NativeParameters], `Void)) ;
Instruction.ASTORE (u1 5) ] ;
node (List.map
(fun c ->
let create =
Instruction.INVOKESTATIC
(make_class c,
make_method "createConstants",
([], `Class (Bytecodegen_constants.const_class_of_curr_class c))) in
node
[ leaf [ Instruction.ALOAD (u1 5) ;
Instruction.LDC_W (`Class_or_interface (make_class c)) ;
create ] ;
meth_setConstant ])
classes) ;
leaf [ Instruction.ALOAD (u1 5) ;
Instruction.ALOAD_1 ] ;
meth_executeWithBindings ; (* calls moduleMain *)
leaf [ Instruction.ALOAD (u1 5) ] ;
meth_getResult ;
leaf [ Instruction.ARETURN ] ] in
let main_scripting_method =
Method.Regular
{ Method.flags = [`Public; `Static];
Method.name = make_method "mainScripting";
Method.descriptor =
([`Array (`Class class_String);
`Class class_Map;
`Class class_InputStream;
`Class class_PrintStream;
`Class class_PrintStream], `Class class_Value);
Method.attributes = [`Code { Attribute.max_stack = u2 11;
Attribute.max_locals = u2 6;
Attribute.code = flatten main_scripting_code;
Attribute.exception_table = [];
Attribute.attributes = []; }]; } in
let main_code =
node
[ leaf
[ Instruction.ALOAD_0 ;
Instruction.INVOKESTATIC
(main_class,
make_method "mainWithReturn",
([`Array (`Class class_String)], `Class main_class)) ;
Instruction.POP ] ;
begin match !Jclflags.war with
| Some _ ->
leaf
[ Instruction.INVOKESTATIC
(make_class (!Jclflags.java_package ^ "." ^ Jconfig.main_servlet_class),
make_method "initialized",
([], `Void)) ]
| None ->
leaf []
end;
leaf [ Instruction.RETURN ] ] in
let main_method =
Method.Regular
{ Method.flags = [`Public; `Static];
Method.name = make_method "main";
Method.descriptor = ([`Array (`Class class_String)], `Void);
Method.attributes = [`Code { Attribute.max_stack = u2 1;
Attribute.max_locals = u2 1;
Attribute.code = flatten main_code;
Attribute.exception_table = [];
Attribute.attributes = []; }]; } in
let annotation =
class_EntryPoint,
[ UTF8.of_string "standalone",
Annotation.Boolean_value !Jclflags.standalone ;
UTF8.of_string "linkedClasses",
Annotation.Array_value
(List.map
(fun c -> Annotation.String_value (UTF8.of_string c))
classes) ] in
class_name,
(compile_class
~name:main_class
~parent:class_AbstractNativeRunner
~fields:[]
~methods:[ constructor_method ;
copy_constructor_method ;
copy_method ;
module_main_method ;
main_with_return_method ;
main_scripting_method ;
main_method ]
~attributes:[ `RuntimeVisibleAnnotations [ annotation ] ])
| null | https://raw.githubusercontent.com/xclerc/ocamljava/8330bfdfd01d0c348f2ba2f0f23d8f5a8f6015b1/compiler/javacomp/javalink_startup.ml | ocaml | calls moduleMain
calls moduleMain |
* This file is part of compiler .
* Copyright ( C ) 2007 - 2015 .
*
* compiler is free software ; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* ( with a change to choice of law ) .
*
* compiler 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
* Q Public License for more details .
*
* You should have received a copy of the Q Public License
* along with this program . If not , see
* < -1.0 > .
* This file is part of OCaml-Java compiler.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java compiler is free software; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* Trolltech (with a change to choice of law).
*
* OCaml-Java compiler 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
* Q Public License for more details.
*
* You should have received a copy of the Q Public License
* along with this program. If not, see
* <-1.0>.
*)
open Bytecodeutils
open BaristaLibrary
open Utils
let node = Instrtree.node
let leaf = Instrtree.leaf
let flatten = Instrtree.flatten
let compile_class ~name ~parent ~fields ~methods ~attributes =
let cd = { ClassDefinition.access_flags = [`Public; `Final; `Super];
name = name;
extends = Some parent;
implements = [];
fields = fields;
methods = methods;
attributes = attributes; } in
let buff = ByteBuffer.make_of_size 1024 in
let stream = OutputStream.make_of_buffer buff in
ClassFile.write (ClassDefinition.encode cd) stream;
OutputStream.close stream;
ByteBuffer.contents buff
let make_startup_class units_to_link execname =
let execname = Filename.basename execname in
let class_name = !Jclflags.java_package ^ "." ^ Jconfig.main_class in
let main_class = make_class class_name in
let classes =
List.flatten
(List.map
(fun (infos, _, _) ->
infos.Cmj_format.ui_additional_classes @ [infos.Cmj_format.ui_javaname])
units_to_link) in
let constructor_code =
node
[ leaf [ Instruction.ALOAD_0 ; Instruction.ALOAD_1 ] ;
cstr_AbstractNativeRunner ;
leaf [ Instruction.RETURN ] ] in
let constructor_method =
Method.Constructor
{ Method.cstr_flags = [`Private];
Method.cstr_descriptor = [`Class interface_NativeParameters];
Method.cstr_attributes = [`Code { Attribute.max_stack = u2 2;
Attribute.max_locals = u2 2;
Attribute.code = flatten constructor_code;
Attribute.exception_table = [];
Attribute.attributes = []; }]; } in
let copy_constructor_code =
node
[ leaf [ Instruction.ALOAD_0 ; Instruction.ALOAD_1 ] ;
cstr_copy_AbstractNativeRunner ;
leaf [ Instruction.RETURN ] ] in
let copy_constructor_method =
Method.Constructor
{ Method.cstr_flags = [`Private];
Method.cstr_descriptor = [`Class main_class];
Method.cstr_attributes = [`Code { Attribute.max_stack = u2 2;
Attribute.max_locals = u2 2;
Attribute.code = flatten copy_constructor_code;
Attribute.exception_table = [];
Attribute.attributes = []; }]; } in
let copy_code =
[ Instruction.NEW main_class ;
Instruction.DUP ;
Instruction.ALOAD_0 ;
Instruction.INVOKESPECIAL (main_class,
make_method "<init>",
([`Class main_class], `Void)) ;
Instruction.ARETURN ] in
let copy_method =
Method.Regular
{ Method.flags = [`Public];
Method.name = make_method "copy";
Method.descriptor = ([], `Class class_AbstractNativeRunner);
Method.attributes = [`Code { Attribute.max_stack = u2 3;
Attribute.max_locals = u2 1;
Attribute.code = copy_code;
Attribute.exception_table = [];
Attribute.attributes = []; }]; } in
let module_main_code =
List.concat
(List.map
(fun c ->
[ Instruction.ALOAD_0 ;
Instruction.DUP ;
Instruction.INVOKESTATIC
(make_class c,
make_method "entry",
([], `Class class_Value)) ;
Instruction.PUTFIELD (class_AbstractNativeRunner,
make_field "result",
`Class class_Value) ;
Instruction.INVOKEVIRTUAL
(`Class_or_interface class_AbstractNativeRunner,
make_method "incrGlobalsInited",
([], `Void)) ])
classes)
@ [ Instruction.RETURN ] in
let module_main_method =
Method.Regular
{ Method.flags = [`Protected];
Method.name = make_method "moduleMain";
Method.descriptor = ([], `Void);
Method.attributes = [`Code { Attribute.max_stack = u2 3;
Attribute.max_locals = u2 1;
Attribute.code = module_main_code;
Attribute.exception_table = [];
Attribute.attributes = []; }]; } in
let main_with_return_code =
let bare_canvas =
if !Jclflags.applet = Some Jclflags.Graphics then
Instruction.ICONST_1
else
Instruction.ICONST_0 in
let parameters =
node
[ leaf [ Instruction.LDC_W (`Class_or_interface main_class) ;
Instruction.LDC_W (`String (UTF8.of_string Jconfig.parameters_entry)) ] ;
meth_getResourceAsStream ;
leaf [ Instruction.ALOAD_0 ] ;
field_System_in ;
field_System_out ;
field_System_err ;
leaf [ bare_canvas ;
Instruction.LDC_W (`String (UTF8.of_string execname)) ;
Instruction.LDC_W (`Class_or_interface main_class) ] ;
meth_fromStream ] in
node
[ leaf [ Instruction.NEW main_class ;
Instruction.DUP ] ;
parameters ;
leaf [ Instruction.INVOKESPECIAL
(main_class,
make_method "<init>",
([`Class interface_NativeParameters], `Void)) ;
Instruction.ASTORE_1 ] ;
node (List.map
(fun c ->
let create =
Instruction.INVOKESTATIC
(make_class c,
make_method "createConstants",
([], `Class (Bytecodegen_constants.const_class_of_curr_class c))) in
node
[ leaf [ Instruction.ALOAD_1 ;
Instruction.LDC_W (`Class_or_interface (make_class c)) ;
create ] ;
meth_setConstant ])
classes) ;
leaf [ Instruction.ALOAD_1 ] ;
leaf [ Instruction.ALOAD_1 ;
Instruction.ARETURN ] ] in
let main_with_return_method =
Method.Regular
{ Method.flags = [`Public; `Static];
Method.name = make_method "mainWithReturn";
Method.descriptor = ([`Array (`Class class_String)], `Class main_class);
Method.attributes = [`Code { Attribute.max_stack = u2 11;
Attribute.max_locals = u2 2;
Attribute.code = flatten main_with_return_code;
Attribute.exception_table = [];
Attribute.attributes = []; }]; } in
let main_scripting_code =
let parameters =
node
[ leaf [ Instruction.LDC_W (`Class_or_interface main_class) ;
Instruction.LDC_W (`String (UTF8.of_string Jconfig.parameters_entry)) ] ;
meth_getResourceAsStream ;
leaf [ Instruction.ALOAD_0 ;
Instruction.ALOAD_2 ;
Instruction.ALOAD_3 ;
Instruction.ALOAD (u1 4) ;
Instruction.ICONST_0 ;
Instruction.LDC_W (`String (UTF8.of_string execname)) ;
Instruction.LDC_W (`Class_or_interface main_class) ] ;
meth_fromStream ] in
node
[ leaf [ Instruction.NEW main_class ;
Instruction.DUP ] ;
parameters ;
leaf [ Instruction.INVOKESPECIAL
(main_class,
make_method "<init>",
([`Class interface_NativeParameters], `Void)) ;
Instruction.ASTORE (u1 5) ] ;
node (List.map
(fun c ->
let create =
Instruction.INVOKESTATIC
(make_class c,
make_method "createConstants",
([], `Class (Bytecodegen_constants.const_class_of_curr_class c))) in
node
[ leaf [ Instruction.ALOAD (u1 5) ;
Instruction.LDC_W (`Class_or_interface (make_class c)) ;
create ] ;
meth_setConstant ])
classes) ;
leaf [ Instruction.ALOAD (u1 5) ;
Instruction.ALOAD_1 ] ;
leaf [ Instruction.ALOAD (u1 5) ] ;
meth_getResult ;
leaf [ Instruction.ARETURN ] ] in
let main_scripting_method =
Method.Regular
{ Method.flags = [`Public; `Static];
Method.name = make_method "mainScripting";
Method.descriptor =
([`Array (`Class class_String);
`Class class_Map;
`Class class_InputStream;
`Class class_PrintStream;
`Class class_PrintStream], `Class class_Value);
Method.attributes = [`Code { Attribute.max_stack = u2 11;
Attribute.max_locals = u2 6;
Attribute.code = flatten main_scripting_code;
Attribute.exception_table = [];
Attribute.attributes = []; }]; } in
let main_code =
node
[ leaf
[ Instruction.ALOAD_0 ;
Instruction.INVOKESTATIC
(main_class,
make_method "mainWithReturn",
([`Array (`Class class_String)], `Class main_class)) ;
Instruction.POP ] ;
begin match !Jclflags.war with
| Some _ ->
leaf
[ Instruction.INVOKESTATIC
(make_class (!Jclflags.java_package ^ "." ^ Jconfig.main_servlet_class),
make_method "initialized",
([], `Void)) ]
| None ->
leaf []
end;
leaf [ Instruction.RETURN ] ] in
let main_method =
Method.Regular
{ Method.flags = [`Public; `Static];
Method.name = make_method "main";
Method.descriptor = ([`Array (`Class class_String)], `Void);
Method.attributes = [`Code { Attribute.max_stack = u2 1;
Attribute.max_locals = u2 1;
Attribute.code = flatten main_code;
Attribute.exception_table = [];
Attribute.attributes = []; }]; } in
let annotation =
class_EntryPoint,
[ UTF8.of_string "standalone",
Annotation.Boolean_value !Jclflags.standalone ;
UTF8.of_string "linkedClasses",
Annotation.Array_value
(List.map
(fun c -> Annotation.String_value (UTF8.of_string c))
classes) ] in
class_name,
(compile_class
~name:main_class
~parent:class_AbstractNativeRunner
~fields:[]
~methods:[ constructor_method ;
copy_constructor_method ;
copy_method ;
module_main_method ;
main_with_return_method ;
main_scripting_method ;
main_method ]
~attributes:[ `RuntimeVisibleAnnotations [ annotation ] ])
|
83813cc1bdb43fe222a14361ab2f18cdd73a255a033aa523262c595c27f13c12 | racket/redex | threads.rkt | #lang racket
(require redex)
(reduction-steps-cutoff 100)
(define-language threads
(p ((store (x v) ...) (threads e ...)))
(e (set! x e)
(let ((x e)) e)
(e e)
x
v
(+ e e))
(v (lambda (x) e)
number)
(x variable)
(pc ((store (x v) ...) tc))
(tc (threads e ... ec e ...))
(ec (ec e) (v ec) (set! variable ec) (let ((x ec)) e) (+ ec e) (+ v ec) hole))
(define reductions
(reduction-relation
threads
(--> (in-hole pc_1 (+ number_1 number_2))
(in-hole pc_1 ,(+ (term number_1) (term number_2)))
sum)
(--> ((store
(name befores (x_0 v_0)) ...
(x_i v_i)
(name afters (x_i+1 v_i+1)) ...)
(in-hole tc_1 x_i))
((store
befores ...
(x_i v_i)
afters ...)
(in-hole tc_1 v_i))
deref)
(--> ((store (x_1 v_1) ... (x_i v) (x_2 v_2) ...)
(in-hole tc_1 (set! x_i v_new)))
((store (x_1 v_1) ... (x_i v_new) (x_2 v_2) ...)
(in-hole tc_1 v_new))
set!)
(--> (in-hole pc_1 ((lambda (x_1) e_1) v_1))
(in-hole pc_1 ,(substitute (term x_1) (term v_1) (term e_1)))
app)
(--> ((store (name the-store any) ...)
(in-hole tc_1 (let ((x_1 v_1)) e_1)))
(term-let ((new-x (variable-not-in (term (the-store ...)) (term x_1))))
(term
((store the-store ... (new-x v_1))
(in-hole tc_1 ,(substitute (term x_1) (term new-x) (term e_1))))))
let)))
(define (substitute . x) (error 'substitute "~s" x))
(define (run es) (traces reductions `((store) (threads ,@es))))
(provide run)
(define (count x)
(match x
[`(set! ,x ,e) (+ 1 (count e))]
[(? symbol?) 1]
[(? number?) 0]
[`(+ ,e1 ,e2) (+ 1 (count e1) (count e2))]))
;; use a pretty-printer that just summaizes the terms, showing the depth of each thread.
(traces reductions
'((store (x 1))
(threads
(set! x (+ x -1))
(set! x (+ x 1))))
#:pp
(lambda (exp)
(match exp
[`((store (x ,x)) (threads ,t1 ,t2))
(format "~a ~a ~a" x (count t1) (count t2))])))
(parameterize ([initial-char-width 16])
(stepper reductions '((store) (threads
(+ 1 1)
(+ 1 1)
(+ 1 1)))))
| null | https://raw.githubusercontent.com/racket/redex/4c2dc96d90cedeb08ec1850575079b952c5ad396/redex-examples/redex/examples/threads.rkt | racket | use a pretty-printer that just summaizes the terms, showing the depth of each thread. | #lang racket
(require redex)
(reduction-steps-cutoff 100)
(define-language threads
(p ((store (x v) ...) (threads e ...)))
(e (set! x e)
(let ((x e)) e)
(e e)
x
v
(+ e e))
(v (lambda (x) e)
number)
(x variable)
(pc ((store (x v) ...) tc))
(tc (threads e ... ec e ...))
(ec (ec e) (v ec) (set! variable ec) (let ((x ec)) e) (+ ec e) (+ v ec) hole))
(define reductions
(reduction-relation
threads
(--> (in-hole pc_1 (+ number_1 number_2))
(in-hole pc_1 ,(+ (term number_1) (term number_2)))
sum)
(--> ((store
(name befores (x_0 v_0)) ...
(x_i v_i)
(name afters (x_i+1 v_i+1)) ...)
(in-hole tc_1 x_i))
((store
befores ...
(x_i v_i)
afters ...)
(in-hole tc_1 v_i))
deref)
(--> ((store (x_1 v_1) ... (x_i v) (x_2 v_2) ...)
(in-hole tc_1 (set! x_i v_new)))
((store (x_1 v_1) ... (x_i v_new) (x_2 v_2) ...)
(in-hole tc_1 v_new))
set!)
(--> (in-hole pc_1 ((lambda (x_1) e_1) v_1))
(in-hole pc_1 ,(substitute (term x_1) (term v_1) (term e_1)))
app)
(--> ((store (name the-store any) ...)
(in-hole tc_1 (let ((x_1 v_1)) e_1)))
(term-let ((new-x (variable-not-in (term (the-store ...)) (term x_1))))
(term
((store the-store ... (new-x v_1))
(in-hole tc_1 ,(substitute (term x_1) (term new-x) (term e_1))))))
let)))
(define (substitute . x) (error 'substitute "~s" x))
(define (run es) (traces reductions `((store) (threads ,@es))))
(provide run)
(define (count x)
(match x
[`(set! ,x ,e) (+ 1 (count e))]
[(? symbol?) 1]
[(? number?) 0]
[`(+ ,e1 ,e2) (+ 1 (count e1) (count e2))]))
(traces reductions
'((store (x 1))
(threads
(set! x (+ x -1))
(set! x (+ x 1))))
#:pp
(lambda (exp)
(match exp
[`((store (x ,x)) (threads ,t1 ,t2))
(format "~a ~a ~a" x (count t1) (count t2))])))
(parameterize ([initial-char-width 16])
(stepper reductions '((store) (threads
(+ 1 1)
(+ 1 1)
(+ 1 1)))))
|
d0a8220f5a2d7dbec53c8c42baa3924dea8814a49a158ef6c36539f0e11c5451 | finnishtransportagency/harja | integraatioloki.cljs | (ns harja.tiedot.hallinta.integraatioloki
"Hallinnoi integraatiolokin tietoja"
(:require [reagent.core :refer [atom]]
[cljs.core.async :refer [<!] :as async]
[harja.asiakas.kommunikaatio :as k]
[harja.loki :refer [log tarkkaile!]]
[harja.pvm :as pvm]
[cljs-time.core :as time]
[harja.atom :refer [paivita!]]
[cljs-time.core :as t]
[harja.pvm :as pvm])
(:require-macros [harja.atom :refer [reaction<!]]
[cljs.core.async.macros :refer [go go-loop]]
[reagent.ratom :refer [reaction]]))
(defn hae-jarjestelmien-integraatiot []
(k/post! :hae-jarjestelmien-integraatiot nil))
(defn hae-integraatiotapahtumien-maarat [jarjestelma integraatio]
(k/post! :hae-integraatiotapahtumien-maarat {:jarjestelma jarjestelma
:integraatio integraatio}))
(defn hae-integraation-tapahtumat [jarjestelma integraatio aikavali hakuehdot]
(k/post! :hae-integraatiotapahtumat
(merge {:jarjestelma (:jarjestelma jarjestelma)
:integraatio integraatio
:hakuehdot hakuehdot}
(when aikavali
{:alkaen (first aikavali)
:paattyen (second aikavali)}))))
(defn hae-integraatiotapahtuman-viestit [tapahtuma-id]
(k/post! :hae-integraatiotapahtuman-viestit tapahtuma-id))
(def nakymassa? (atom false))
(defonce jarjestelmien-integraatiot (reaction<! [nakymassa? @nakymassa?]
(when nakymassa?
(hae-jarjestelmien-integraatiot))))
(defonce valittu-jarjestelma (atom nil))
(defonce valittu-integraatio (atom nil))
(defonce valittu-aikavali (atom (pvm/tanaan-aikavali)))
(defonce hakuehdot (atom {:tapahtumien-tila :kaikki}))
(defonce nayta-uusimmat-tilassa? (atom true))
Kun seurataan ulkoista urlia - näitä slackista
(defonce tapahtuma-id (atom nil))
(defonce tultiin-urlin-kautta (atom nil))
(defonce nayta-graafit? (atom false))
(defonce nayta-kutsutut-integraatiot? (atom false))
(defn nayta-graafit! []
(js/console.log "click" @nayta-graafit?)
(if @nayta-graafit?
(reset! nayta-graafit? false)
(reset! nayta-graafit? true)))
(defn nayta-kutsutut-integraatiot! []
(js/console.log "click" @nayta-kutsutut-integraatiot?)
(if @nayta-kutsutut-integraatiot?
(reset! nayta-kutsutut-integraatiot? false)
(reset! nayta-kutsutut-integraatiot? true)))
(def tapahtumien-maarat (atom []))
nil , [ ] jos tyhjä
(def hae-automaattisesti? (atom false))
(defn hae-tapahtumat! []
(let [valittu-jarjestelma @valittu-jarjestelma
valittu-integraatio @valittu-integraatio
valittu-aikavali @valittu-aikavali
nakymassa? @nakymassa?
hakuehdot @hakuehdot]
(when nakymassa?
(reset! haetut-tapahtumat nil)
(reset! tapahtumien-maarat nil)
Palvelimen päässä on määritelty , että maksimissaan 500 tulosta palautetaan
(go (let [tapahtumat (<! (hae-integraation-tapahtumat valittu-jarjestelma valittu-integraatio valittu-aikavali hakuehdot))
maarat (<! (hae-integraatiotapahtumien-maarat valittu-jarjestelma valittu-integraatio))
maarat-aikavalilla (filter #(pvm/valissa? (:pvm %)
(first valittu-aikavali)
(second valittu-aikavali))
maarat)]
(reset! haetut-tapahtumat tapahtumat)
(reset! tapahtumien-maarat maarat-aikavalilla)
(when @tultiin-urlin-kautta
(go-loop [aukinainen-vetolaatikko (aget (.getElementsByClassName js/document "vetolaatikko-auki") 0)
kertoja-loopattu 0]
(if (or (= kertoja-loopattu 10) aukinainen-vetolaatikko)
(try (.scrollIntoView aukinainen-vetolaatikko true)
(catch :default e
(log "VIRHE: Skrollaaminen avattuun vetolaatikkoon ei onnistunut" e)))
(do
(<! (async/timeout 1200))
(recur (aget (.getElementsByClassName js/document "vetolaatikko-auki") 0)
(inc kertoja-loopattu)))))
(reset! tultiin-urlin-kautta nil))
tapahtumat)))))
| null | https://raw.githubusercontent.com/finnishtransportagency/harja/e480f656f98182760f02fde199278fac0b7162c3/src/cljs/harja/tiedot/hallinta/integraatioloki.cljs | clojure | (ns harja.tiedot.hallinta.integraatioloki
"Hallinnoi integraatiolokin tietoja"
(:require [reagent.core :refer [atom]]
[cljs.core.async :refer [<!] :as async]
[harja.asiakas.kommunikaatio :as k]
[harja.loki :refer [log tarkkaile!]]
[harja.pvm :as pvm]
[cljs-time.core :as time]
[harja.atom :refer [paivita!]]
[cljs-time.core :as t]
[harja.pvm :as pvm])
(:require-macros [harja.atom :refer [reaction<!]]
[cljs.core.async.macros :refer [go go-loop]]
[reagent.ratom :refer [reaction]]))
(defn hae-jarjestelmien-integraatiot []
(k/post! :hae-jarjestelmien-integraatiot nil))
(defn hae-integraatiotapahtumien-maarat [jarjestelma integraatio]
(k/post! :hae-integraatiotapahtumien-maarat {:jarjestelma jarjestelma
:integraatio integraatio}))
(defn hae-integraation-tapahtumat [jarjestelma integraatio aikavali hakuehdot]
(k/post! :hae-integraatiotapahtumat
(merge {:jarjestelma (:jarjestelma jarjestelma)
:integraatio integraatio
:hakuehdot hakuehdot}
(when aikavali
{:alkaen (first aikavali)
:paattyen (second aikavali)}))))
(defn hae-integraatiotapahtuman-viestit [tapahtuma-id]
(k/post! :hae-integraatiotapahtuman-viestit tapahtuma-id))
(def nakymassa? (atom false))
(defonce jarjestelmien-integraatiot (reaction<! [nakymassa? @nakymassa?]
(when nakymassa?
(hae-jarjestelmien-integraatiot))))
(defonce valittu-jarjestelma (atom nil))
(defonce valittu-integraatio (atom nil))
(defonce valittu-aikavali (atom (pvm/tanaan-aikavali)))
(defonce hakuehdot (atom {:tapahtumien-tila :kaikki}))
(defonce nayta-uusimmat-tilassa? (atom true))
Kun seurataan ulkoista urlia - näitä slackista
(defonce tapahtuma-id (atom nil))
(defonce tultiin-urlin-kautta (atom nil))
(defonce nayta-graafit? (atom false))
(defonce nayta-kutsutut-integraatiot? (atom false))
(defn nayta-graafit! []
(js/console.log "click" @nayta-graafit?)
(if @nayta-graafit?
(reset! nayta-graafit? false)
(reset! nayta-graafit? true)))
(defn nayta-kutsutut-integraatiot! []
(js/console.log "click" @nayta-kutsutut-integraatiot?)
(if @nayta-kutsutut-integraatiot?
(reset! nayta-kutsutut-integraatiot? false)
(reset! nayta-kutsutut-integraatiot? true)))
(def tapahtumien-maarat (atom []))
nil , [ ] jos tyhjä
(def hae-automaattisesti? (atom false))
(defn hae-tapahtumat! []
(let [valittu-jarjestelma @valittu-jarjestelma
valittu-integraatio @valittu-integraatio
valittu-aikavali @valittu-aikavali
nakymassa? @nakymassa?
hakuehdot @hakuehdot]
(when nakymassa?
(reset! haetut-tapahtumat nil)
(reset! tapahtumien-maarat nil)
Palvelimen päässä on määritelty , että maksimissaan 500 tulosta palautetaan
(go (let [tapahtumat (<! (hae-integraation-tapahtumat valittu-jarjestelma valittu-integraatio valittu-aikavali hakuehdot))
maarat (<! (hae-integraatiotapahtumien-maarat valittu-jarjestelma valittu-integraatio))
maarat-aikavalilla (filter #(pvm/valissa? (:pvm %)
(first valittu-aikavali)
(second valittu-aikavali))
maarat)]
(reset! haetut-tapahtumat tapahtumat)
(reset! tapahtumien-maarat maarat-aikavalilla)
(when @tultiin-urlin-kautta
(go-loop [aukinainen-vetolaatikko (aget (.getElementsByClassName js/document "vetolaatikko-auki") 0)
kertoja-loopattu 0]
(if (or (= kertoja-loopattu 10) aukinainen-vetolaatikko)
(try (.scrollIntoView aukinainen-vetolaatikko true)
(catch :default e
(log "VIRHE: Skrollaaminen avattuun vetolaatikkoon ei onnistunut" e)))
(do
(<! (async/timeout 1200))
(recur (aget (.getElementsByClassName js/document "vetolaatikko-auki") 0)
(inc kertoja-loopattu)))))
(reset! tultiin-urlin-kautta nil))
tapahtumat)))))
| |
4d668a4d663c34faaee2f4c5706585176cce746319d6c94a0d25418d269b1cba | elastic/eui-cljs | deps.cljs | {:npm-deps
{"@elastic/eui" "64.0.0",
"@elastic/datemath" "^5.0.3",
"classnames" "^2.2.6",
"moment" "^2.27.0",
"prop-types" "^15.6.0",
"typescript" "4.0.5"}}
| null | https://raw.githubusercontent.com/elastic/eui-cljs/88737a49699cdd2fd578acff3ad32e97b2b2e798/src/deps.cljs | clojure | {:npm-deps
{"@elastic/eui" "64.0.0",
"@elastic/datemath" "^5.0.3",
"classnames" "^2.2.6",
"moment" "^2.27.0",
"prop-types" "^15.6.0",
"typescript" "4.0.5"}}
| |
ba5dff66bc9989deab8b51bf52151c7f68050a9a69b3c141de9bf433e1db661b | mzp/coq-ide-for-ios | libnames.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
i $ I d : libnames.mli 13323 2010 - 07 - 24 15:57:30Z herbelin $ i
(*i*)
open Pp
open Util
open Names
open Term
open Mod_subst
(*i*)
(*s Global reference is a kernel side type for all references together *)
type global_reference =
| VarRef of variable
| ConstRef of constant
| IndRef of inductive
| ConstructRef of constructor
val isVarRef : global_reference -> bool
val isConstRef : global_reference -> bool
val isIndRef : global_reference -> bool
val isConstructRef : global_reference -> bool
val eq_gr : global_reference -> global_reference -> bool
val canonical_gr : global_reference -> global_reference
val destVarRef : global_reference -> variable
val destConstRef : global_reference -> constant
val destIndRef : global_reference -> inductive
val destConstructRef : global_reference -> constructor
val subst_constructor : substitution -> constructor -> constructor * constr
val subst_global : substitution -> global_reference -> global_reference * constr
(* Turn a global reference into a construction *)
val constr_of_global : global_reference -> constr
(* Turn a construction denoting a global reference into a global reference;
raise [Not_found] if not a global reference *)
val global_of_constr : constr -> global_reference
Obsolete synonyms for constr_of_global and global_of_constr
val constr_of_reference : global_reference -> constr
val reference_of_constr : constr -> global_reference
module RefOrdered : sig
type t = global_reference
val compare : global_reference -> global_reference -> int
end
module Refset : Set.S with type elt = global_reference
module Refmap : Map.S with type key = global_reference
(*s Extended global references *)
type syndef_name = kernel_name
type extended_global_reference =
| TrueGlobal of global_reference
| SynDef of syndef_name
(*s Dirpaths *)
val pr_dirpath : dir_path -> Pp.std_ppcmds
val dirpath_of_string : string -> dir_path
val string_of_dirpath : dir_path -> string
(* Pop the suffix of a [dir_path] *)
val pop_dirpath : dir_path -> dir_path
(* Pop the suffix n times *)
val pop_dirpath_n : int -> dir_path -> dir_path
(* Give the immediate prefix and basename of a [dir_path] *)
val split_dirpath : dir_path -> dir_path * identifier
val add_dirpath_suffix : dir_path -> module_ident -> dir_path
val add_dirpath_prefix : module_ident -> dir_path -> dir_path
val chop_dirpath : int -> dir_path -> dir_path * dir_path
val append_dirpath : dir_path -> dir_path -> dir_path
val drop_dirpath_prefix : dir_path -> dir_path -> dir_path
val is_dirpath_prefix_of : dir_path -> dir_path -> bool
module Dirset : Set.S with type elt = dir_path
module Dirmap : Map.S with type key = dir_path
(*s Full paths are {\em absolute} paths of declarations *)
type full_path
(* Constructors of [full_path] *)
val make_path : dir_path -> identifier -> full_path
(* Destructors of [full_path] *)
val repr_path : full_path -> dir_path * identifier
val dirpath : full_path -> dir_path
val basename : full_path -> identifier
(* Parsing and printing of section path as ["coq_root.module.id"] *)
val path_of_string : string -> full_path
val string_of_path : full_path -> string
val pr_path : full_path -> std_ppcmds
module Sppred : Predicate.S with type elt = full_path
module Spmap : Map.S with type key = full_path
val restrict_path : int -> full_path -> full_path
(*s Temporary function to brutally form kernel names from section paths *)
val encode_mind : dir_path -> identifier -> mutual_inductive
val decode_mind : mutual_inductive -> dir_path * identifier
val encode_con : dir_path -> identifier -> constant
val decode_con : constant -> dir_path * identifier
(*s A [qualid] is a partially qualified ident; it includes fully
qualified names (= absolute names) and all intermediate partial
qualifications of absolute names, including single identifiers.
The [qualid] are used to access the name table. *)
type qualid
val make_qualid : dir_path -> identifier -> qualid
val repr_qualid : qualid -> dir_path * identifier
val pr_qualid : qualid -> std_ppcmds
val string_of_qualid : qualid -> string
val qualid_of_string : string -> qualid
(* Turns an absolute name, a dirpath, or an identifier into a
qualified name denoting the same name *)
val qualid_of_path : full_path -> qualid
val qualid_of_dirpath : dir_path -> qualid
val qualid_of_ident : identifier -> qualid
(* Both names are passed to objects: a "semantic" [kernel_name], which
can be substituted and a "syntactic" [full_path] which can be printed
*)
type object_name = full_path * kernel_name
type object_prefix = dir_path * (module_path * dir_path)
val make_oname : object_prefix -> identifier -> object_name
to this type are mapped [ dir_path ] 's in the nametab
type global_dir_reference =
| DirOpenModule of object_prefix
| DirOpenModtype of object_prefix
| DirOpenSection of object_prefix
| DirModule of object_prefix
| DirClosedSection of dir_path
(* this won't last long I hope! *)
(*s A [reference] is the user-level notion of name. It denotes either a
global name (referred either by a qualified name or by a single
name) or a variable *)
type reference =
| Qualid of qualid located
| Ident of identifier located
val qualid_of_reference : reference -> qualid located
val string_of_reference : reference -> string
val pr_reference : reference -> std_ppcmds
val loc_of_reference : reference -> loc
s Popping one level of section in global names
val pop_con : constant -> constant
val pop_kn : mutual_inductive-> mutual_inductive
val pop_global_reference : global_reference -> global_reference
(* Deprecated synonyms *)
val make_short_qualid : identifier -> qualid (* = qualid_of_ident *)
val qualid_of_sp : full_path -> qualid (* = qualid_of_path *)
| null | https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/library/libnames.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i
i
s Global reference is a kernel side type for all references together
Turn a global reference into a construction
Turn a construction denoting a global reference into a global reference;
raise [Not_found] if not a global reference
s Extended global references
s Dirpaths
Pop the suffix of a [dir_path]
Pop the suffix n times
Give the immediate prefix and basename of a [dir_path]
s Full paths are {\em absolute} paths of declarations
Constructors of [full_path]
Destructors of [full_path]
Parsing and printing of section path as ["coq_root.module.id"]
s Temporary function to brutally form kernel names from section paths
s A [qualid] is a partially qualified ident; it includes fully
qualified names (= absolute names) and all intermediate partial
qualifications of absolute names, including single identifiers.
The [qualid] are used to access the name table.
Turns an absolute name, a dirpath, or an identifier into a
qualified name denoting the same name
Both names are passed to objects: a "semantic" [kernel_name], which
can be substituted and a "syntactic" [full_path] which can be printed
this won't last long I hope!
s A [reference] is the user-level notion of name. It denotes either a
global name (referred either by a qualified name or by a single
name) or a variable
Deprecated synonyms
= qualid_of_ident
= qualid_of_path | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
i $ I d : libnames.mli 13323 2010 - 07 - 24 15:57:30Z herbelin $ i
open Pp
open Util
open Names
open Term
open Mod_subst
type global_reference =
| VarRef of variable
| ConstRef of constant
| IndRef of inductive
| ConstructRef of constructor
val isVarRef : global_reference -> bool
val isConstRef : global_reference -> bool
val isIndRef : global_reference -> bool
val isConstructRef : global_reference -> bool
val eq_gr : global_reference -> global_reference -> bool
val canonical_gr : global_reference -> global_reference
val destVarRef : global_reference -> variable
val destConstRef : global_reference -> constant
val destIndRef : global_reference -> inductive
val destConstructRef : global_reference -> constructor
val subst_constructor : substitution -> constructor -> constructor * constr
val subst_global : substitution -> global_reference -> global_reference * constr
val constr_of_global : global_reference -> constr
val global_of_constr : constr -> global_reference
Obsolete synonyms for constr_of_global and global_of_constr
val constr_of_reference : global_reference -> constr
val reference_of_constr : constr -> global_reference
module RefOrdered : sig
type t = global_reference
val compare : global_reference -> global_reference -> int
end
module Refset : Set.S with type elt = global_reference
module Refmap : Map.S with type key = global_reference
type syndef_name = kernel_name
type extended_global_reference =
| TrueGlobal of global_reference
| SynDef of syndef_name
val pr_dirpath : dir_path -> Pp.std_ppcmds
val dirpath_of_string : string -> dir_path
val string_of_dirpath : dir_path -> string
val pop_dirpath : dir_path -> dir_path
val pop_dirpath_n : int -> dir_path -> dir_path
val split_dirpath : dir_path -> dir_path * identifier
val add_dirpath_suffix : dir_path -> module_ident -> dir_path
val add_dirpath_prefix : module_ident -> dir_path -> dir_path
val chop_dirpath : int -> dir_path -> dir_path * dir_path
val append_dirpath : dir_path -> dir_path -> dir_path
val drop_dirpath_prefix : dir_path -> dir_path -> dir_path
val is_dirpath_prefix_of : dir_path -> dir_path -> bool
module Dirset : Set.S with type elt = dir_path
module Dirmap : Map.S with type key = dir_path
type full_path
val make_path : dir_path -> identifier -> full_path
val repr_path : full_path -> dir_path * identifier
val dirpath : full_path -> dir_path
val basename : full_path -> identifier
val path_of_string : string -> full_path
val string_of_path : full_path -> string
val pr_path : full_path -> std_ppcmds
module Sppred : Predicate.S with type elt = full_path
module Spmap : Map.S with type key = full_path
val restrict_path : int -> full_path -> full_path
val encode_mind : dir_path -> identifier -> mutual_inductive
val decode_mind : mutual_inductive -> dir_path * identifier
val encode_con : dir_path -> identifier -> constant
val decode_con : constant -> dir_path * identifier
type qualid
val make_qualid : dir_path -> identifier -> qualid
val repr_qualid : qualid -> dir_path * identifier
val pr_qualid : qualid -> std_ppcmds
val string_of_qualid : qualid -> string
val qualid_of_string : string -> qualid
val qualid_of_path : full_path -> qualid
val qualid_of_dirpath : dir_path -> qualid
val qualid_of_ident : identifier -> qualid
type object_name = full_path * kernel_name
type object_prefix = dir_path * (module_path * dir_path)
val make_oname : object_prefix -> identifier -> object_name
to this type are mapped [ dir_path ] 's in the nametab
type global_dir_reference =
| DirOpenModule of object_prefix
| DirOpenModtype of object_prefix
| DirOpenSection of object_prefix
| DirModule of object_prefix
| DirClosedSection of dir_path
type reference =
| Qualid of qualid located
| Ident of identifier located
val qualid_of_reference : reference -> qualid located
val string_of_reference : reference -> string
val pr_reference : reference -> std_ppcmds
val loc_of_reference : reference -> loc
s Popping one level of section in global names
val pop_con : constant -> constant
val pop_kn : mutual_inductive-> mutual_inductive
val pop_global_reference : global_reference -> global_reference
|
1ccd04d8de38a6c1adbd744dc171051f0c713096f417d028b27b2c263e2f44f1 | gsakkas/rite | 2949.ml |
let pipe fs =
let f a x y = a (y x) in let base b = b in List.fold_left f base fs;;
fix
let pipe fs =
let f a x y = a ( x y ) in let base b = b in List.fold_left f base fs ; ;
let pipe fs =
let f a x y = a (x y) in let base b = b in List.fold_left f base fs;;
*)
changed spans
( 3,19)-(3,24 )
x y
AppG [ VarG ]
(3,19)-(3,24)
x y
AppG [VarG]
*)
type error slice
( 3,3)-(3,70 )
( 3,9)-(3,24 )
( 3,11)-(3,24 )
( 3,13)-(3,24 )
( 3,17)-(3,18 )
( 3,17)-(3,24 )
( 3,19)-(3,24 )
( 3,20)-(3,21 )
( 3,46)-(3,60 )
( 3,46)-(3,70 )
( 3,61)-(3,62 )
(3,3)-(3,70)
(3,9)-(3,24)
(3,11)-(3,24)
(3,13)-(3,24)
(3,17)-(3,18)
(3,17)-(3,24)
(3,19)-(3,24)
(3,20)-(3,21)
(3,46)-(3,60)
(3,46)-(3,70)
(3,61)-(3,62)
*)
| null | https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/data/sp14_min/2949.ml | ocaml |
let pipe fs =
let f a x y = a (y x) in let base b = b in List.fold_left f base fs;;
fix
let pipe fs =
let f a x y = a ( x y ) in let base b = b in List.fold_left f base fs ; ;
let pipe fs =
let f a x y = a (x y) in let base b = b in List.fold_left f base fs;;
*)
changed spans
( 3,19)-(3,24 )
x y
AppG [ VarG ]
(3,19)-(3,24)
x y
AppG [VarG]
*)
type error slice
( 3,3)-(3,70 )
( 3,9)-(3,24 )
( 3,11)-(3,24 )
( 3,13)-(3,24 )
( 3,17)-(3,18 )
( 3,17)-(3,24 )
( 3,19)-(3,24 )
( 3,20)-(3,21 )
( 3,46)-(3,60 )
( 3,46)-(3,70 )
( 3,61)-(3,62 )
(3,3)-(3,70)
(3,9)-(3,24)
(3,11)-(3,24)
(3,13)-(3,24)
(3,17)-(3,18)
(3,17)-(3,24)
(3,19)-(3,24)
(3,20)-(3,21)
(3,46)-(3,60)
(3,46)-(3,70)
(3,61)-(3,62)
*)
| |
8bda91ff7796e0d2f829505ec4d7cb768202d49cbfc279f0e55af7931e9280ab | ocaml/ocaml | main.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* The lexer generator. Command-line parsing. *)
open Syntax
let ml_automata = ref false
let source_name = ref None
let output_name = ref None
let usage = "usage: ocamllex [options] sourcefile"
let print_version_string () =
print_string "The OCaml lexer generator, version ";
print_string Sys.ocaml_version ; print_newline();
exit 0
let print_version_num () =
print_endline Sys.ocaml_version;
exit 0
let specs =
["-ml", Arg.Set ml_automata,
" Output code that does not use the Lexing module built-in automata \
interpreter";
"-o", Arg.String (fun x -> output_name := Some x),
" <file> Set output file name to <file>";
"-q", Arg.Set Common.quiet_mode, " Do not display informational messages";
"-v", Arg.Unit print_version_string, " Print version and exit";
"-version", Arg.Unit print_version_string, " Print version and exit";
"-vnum", Arg.Unit print_version_num, " Print version number and exit";
]
let _ =
Arg.parse
specs
(fun name -> source_name := Some name)
usage
let main () =
let source_name = match !source_name with
| None -> Arg.usage specs usage ; exit 2
| Some name -> name in
let dest_name = match !output_name with
| Some name -> name
| None ->
if Filename.check_suffix source_name ".mll" then
Filename.chop_suffix source_name ".mll" ^ ".ml"
else
source_name ^ ".ml" in
let ic = open_in_bin source_name in
let oc = open_out dest_name in
let tr = Common.open_tracker dest_name oc in
let lexbuf = Lexing.from_channel ic in
lexbuf.Lexing.lex_curr_p <-
{Lexing.pos_fname = source_name; Lexing.pos_lnum = 1;
Lexing.pos_bol = 0; Lexing.pos_cnum = 0};
try
let def = Parser.lexer_definition Lexer.main lexbuf in
let (entries, transitions) = Lexgen.make_dfa def.entrypoints in
if !ml_automata then begin
Outputbis.output_lexdef
ic oc tr
def.header def.refill_handler entries transitions def.trailer
end else begin
let tables = Compact.compact_tables transitions in
Output.output_lexdef ic oc tr
def.header def.refill_handler tables entries def.trailer
end;
close_in ic;
close_out oc;
Common.close_tracker tr;
with exn ->
let bt = Printexc.get_raw_backtrace () in
close_in ic;
close_out oc;
Common.close_tracker tr;
Sys.remove dest_name;
begin match exn with
| Cset.Bad ->
let p = Lexing.lexeme_start_p lexbuf in
Printf.fprintf stderr
"File \"%s\", line %d, character %d: character set expected.\n"
p.Lexing.pos_fname p.Lexing.pos_lnum
(p.Lexing.pos_cnum - p.Lexing.pos_bol)
| Parsing.Parse_error ->
let p = Lexing.lexeme_start_p lexbuf in
Printf.fprintf stderr
"File \"%s\", line %d, character %d: syntax error.\n"
p.Lexing.pos_fname p.Lexing.pos_lnum
(p.Lexing.pos_cnum - p.Lexing.pos_bol)
| Lexer.Lexical_error(msg, file, line, col) ->
Printf.fprintf stderr
"File \"%s\", line %d, character %d: %s.\n"
file line col msg
| Lexgen.Memory_overflow ->
Printf.fprintf stderr
"File \"%s\":\n Position memory overflow, too many bindings\n"
source_name
| Output.Table_overflow ->
Printf.fprintf stderr
"File \"%s\":\ntransition table overflow, automaton is too big\n"
source_name
| _ ->
Printexc.raise_with_backtrace exn bt
end;
exit 3
let _ = main (); exit 0
| null | https://raw.githubusercontent.com/ocaml/ocaml/04ddddd0e1d2bf2acb5091f434b93387243d4624/lex/main.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
The lexer generator. Command-line parsing. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Syntax
let ml_automata = ref false
let source_name = ref None
let output_name = ref None
let usage = "usage: ocamllex [options] sourcefile"
let print_version_string () =
print_string "The OCaml lexer generator, version ";
print_string Sys.ocaml_version ; print_newline();
exit 0
let print_version_num () =
print_endline Sys.ocaml_version;
exit 0
let specs =
["-ml", Arg.Set ml_automata,
" Output code that does not use the Lexing module built-in automata \
interpreter";
"-o", Arg.String (fun x -> output_name := Some x),
" <file> Set output file name to <file>";
"-q", Arg.Set Common.quiet_mode, " Do not display informational messages";
"-v", Arg.Unit print_version_string, " Print version and exit";
"-version", Arg.Unit print_version_string, " Print version and exit";
"-vnum", Arg.Unit print_version_num, " Print version number and exit";
]
let _ =
Arg.parse
specs
(fun name -> source_name := Some name)
usage
let main () =
let source_name = match !source_name with
| None -> Arg.usage specs usage ; exit 2
| Some name -> name in
let dest_name = match !output_name with
| Some name -> name
| None ->
if Filename.check_suffix source_name ".mll" then
Filename.chop_suffix source_name ".mll" ^ ".ml"
else
source_name ^ ".ml" in
let ic = open_in_bin source_name in
let oc = open_out dest_name in
let tr = Common.open_tracker dest_name oc in
let lexbuf = Lexing.from_channel ic in
lexbuf.Lexing.lex_curr_p <-
{Lexing.pos_fname = source_name; Lexing.pos_lnum = 1;
Lexing.pos_bol = 0; Lexing.pos_cnum = 0};
try
let def = Parser.lexer_definition Lexer.main lexbuf in
let (entries, transitions) = Lexgen.make_dfa def.entrypoints in
if !ml_automata then begin
Outputbis.output_lexdef
ic oc tr
def.header def.refill_handler entries transitions def.trailer
end else begin
let tables = Compact.compact_tables transitions in
Output.output_lexdef ic oc tr
def.header def.refill_handler tables entries def.trailer
end;
close_in ic;
close_out oc;
Common.close_tracker tr;
with exn ->
let bt = Printexc.get_raw_backtrace () in
close_in ic;
close_out oc;
Common.close_tracker tr;
Sys.remove dest_name;
begin match exn with
| Cset.Bad ->
let p = Lexing.lexeme_start_p lexbuf in
Printf.fprintf stderr
"File \"%s\", line %d, character %d: character set expected.\n"
p.Lexing.pos_fname p.Lexing.pos_lnum
(p.Lexing.pos_cnum - p.Lexing.pos_bol)
| Parsing.Parse_error ->
let p = Lexing.lexeme_start_p lexbuf in
Printf.fprintf stderr
"File \"%s\", line %d, character %d: syntax error.\n"
p.Lexing.pos_fname p.Lexing.pos_lnum
(p.Lexing.pos_cnum - p.Lexing.pos_bol)
| Lexer.Lexical_error(msg, file, line, col) ->
Printf.fprintf stderr
"File \"%s\", line %d, character %d: %s.\n"
file line col msg
| Lexgen.Memory_overflow ->
Printf.fprintf stderr
"File \"%s\":\n Position memory overflow, too many bindings\n"
source_name
| Output.Table_overflow ->
Printf.fprintf stderr
"File \"%s\":\ntransition table overflow, automaton is too big\n"
source_name
| _ ->
Printexc.raise_with_backtrace exn bt
end;
exit 3
let _ = main (); exit 0
|
78e21c79ba49e6222640ac886c15c15ccd34f0c34f34bf0b6cf6527fa406bd54 | fgalassi/cs61a-sp11 | test-reckless.scm | (load "load-simply")
(load "reckless")
(load "assert")
(define (always-hit hand dealer-card) #t)
(define (always-stand hand dealer-card) #f)
(define (hit-on-empty-hand hand dealer-card) (empty? hand))
(assert equal? ((reckless always-hit) '() 'as) #t "hit if the original strategy hits (empty hand)")
(assert equal? ((reckless always-hit) '(10s 10c 10h) 'as) #t "hit if the original strategy hits (busting hand)")
(assert equal? ((reckless always-stand) '() 'as) #f "stand if the original strategy stands and there was no previous turn")
(assert equal? ((reckless hit-on-empty-hand) '(10c) 'as) #t "hit if the original strategy stands and previous turn it hit")
(assert equal? ((reckless always-stand) '(10c) 'as) #f "stand if the original strategy stands and previous turn it didnt hit")
(display "done.\n")
(quit)
| null | https://raw.githubusercontent.com/fgalassi/cs61a-sp11/66df3b54b03ee27f368c716ae314fd7ed85c4dba/projects/blackjack/normal/test-reckless.scm | scheme | (load "load-simply")
(load "reckless")
(load "assert")
(define (always-hit hand dealer-card) #t)
(define (always-stand hand dealer-card) #f)
(define (hit-on-empty-hand hand dealer-card) (empty? hand))
(assert equal? ((reckless always-hit) '() 'as) #t "hit if the original strategy hits (empty hand)")
(assert equal? ((reckless always-hit) '(10s 10c 10h) 'as) #t "hit if the original strategy hits (busting hand)")
(assert equal? ((reckless always-stand) '() 'as) #f "stand if the original strategy stands and there was no previous turn")
(assert equal? ((reckless hit-on-empty-hand) '(10c) 'as) #t "hit if the original strategy stands and previous turn it hit")
(assert equal? ((reckless always-stand) '(10c) 'as) #f "stand if the original strategy stands and previous turn it didnt hit")
(display "done.\n")
(quit)
| |
60d31fbdda4be75d4e357a6571159b5896d53c25b00c00215686f91bdb4f8d15 | joonazan/regex-equivalence | RegexEquality.hs | module RegexEquality where
import Data.Text
import DFA
import qualified NFA
import qualified Regex
counterexample :: Text -> Text -> Either String (Maybe (String, Bool))
counterexample a b = do
a' <- Regex.parse a
b' <- Regex.parse b
return $
recognizedByOne (toDfa a') (toDfa b')
toDfa =
NFA.toDFA . NFA.fromRegex | null | https://raw.githubusercontent.com/joonazan/regex-equivalence/d050c942734883c702400a1fd3abb5e45f6b6874/src/RegexEquality.hs | haskell | module RegexEquality where
import Data.Text
import DFA
import qualified NFA
import qualified Regex
counterexample :: Text -> Text -> Either String (Maybe (String, Bool))
counterexample a b = do
a' <- Regex.parse a
b' <- Regex.parse b
return $
recognizedByOne (toDfa a') (toDfa b')
toDfa =
NFA.toDFA . NFA.fromRegex | |
ede59cef25fd53d8c0f94a9fadb1b6953764cd7f3586116ac97455a0adfa4213 | input-output-hk/cardano-base | Class.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
-- | Abstract Verifiable Random Functions.
module Cardano.Crypto.VRF.Class
(
-- * VRF algorithm class
VRFAlgorithm (..)
-- ** VRF output
, OutputVRF(..)
, getOutputVRFNatural
, mkTestOutputVRF
-- * 'CertifiedVRF' wrapper
, CertifiedVRF (..)
, evalCertified
, verifyCertified
-- * CBOR encoding and decoding
, encodeVerKeyVRF
, decodeVerKeyVRF
, encodeSignKeyVRF
, decodeSignKeyVRF
, encodeCertVRF
, decodeCertVRF
-- * Encoded 'Size' expressions
, encodedVerKeyVRFSizeExpr
, encodedSignKeyVRFSizeExpr
, encodedCertVRFSizeExpr
)
where
import Control.DeepSeq (NFData)
import Data.ByteString (ByteString)
import Data.Kind (Type)
import Data.Proxy (Proxy(..))
import Data.Typeable (Typeable)
import GHC.Exts (Constraint)
import GHC.Generics (Generic)
import GHC.Stack
import GHC.TypeLits (TypeError, ErrorMessage (..))
import NoThunks.Class (NoThunks)
import Numeric.Natural (Natural)
import qualified Data.ByteString as BS
import Cardano.Binary
(Decoder, Encoding, FromCBOR (..), ToCBOR (..), Size,
encodeListLen, enforceSize, decodeBytes, encodeBytes,
withWordSize)
import Cardano.Crypto.Util (Empty, bytesToNatural, naturalToBytes)
import Cardano.Crypto.Seed (Seed)
import Cardano.Crypto.Hash.Class (HashAlgorithm, Hash, hashWith)
class ( Typeable v
, Show (VerKeyVRF v)
, Eq (VerKeyVRF v)
, Show (SignKeyVRF v)
, Show (CertVRF v)
, Eq (CertVRF v)
, NoThunks (CertVRF v)
, NoThunks (VerKeyVRF v)
, NoThunks (SignKeyVRF v)
)
=> VRFAlgorithm v where
--
-- Key and signature types
--
data VerKeyVRF v :: Type
data SignKeyVRF v :: Type
data CertVRF v :: Type
--
Metadata and basic key operations
--
algorithmNameVRF :: proxy v -> String
deriveVerKeyVRF :: SignKeyVRF v -> VerKeyVRF v
hashVerKeyVRF :: HashAlgorithm h => VerKeyVRF v -> Hash h (VerKeyVRF v)
hashVerKeyVRF = hashWith rawSerialiseVerKeyVRF
--
Core algorithm operations
--
| Context required to run the VRF algorithm
--
-- Unit by default (no context required)
type ContextVRF v :: Type
type ContextVRF v = ()
type Signable v :: Type -> Constraint
type Signable c = Empty
evalVRF
:: (HasCallStack, Signable v a)
=> ContextVRF v
-> a
-> SignKeyVRF v
-> (OutputVRF v, CertVRF v)
verifyVRF
:: (HasCallStack, Signable v a)
=> ContextVRF v
-> VerKeyVRF v
-> a
-> (OutputVRF v, CertVRF v)
-> Bool
--
-- Key generation
--
genKeyVRF :: Seed -> SignKeyVRF v
genKeyPairVRF :: Seed -> (SignKeyVRF v, VerKeyVRF v)
genKeyVRF =
fst . genKeyPairVRF
genKeyPairVRF = \seed ->
let sk = genKeyVRF seed
in (sk, deriveVerKeyVRF sk)
-- | The upper bound on the 'Seed' size needed by 'genKeyVRF', in bytes.
seedSizeVRF :: proxy v -> Word
--
-- Serialisation/(de)serialisation in fixed-size raw format
--
sizeVerKeyVRF :: proxy v -> Word
sizeSignKeyVRF :: proxy v -> Word
sizeCertVRF :: proxy v -> Word
sizeOutputVRF :: proxy v -> Word
rawSerialiseVerKeyVRF :: VerKeyVRF v -> ByteString
rawSerialiseSignKeyVRF :: SignKeyVRF v -> ByteString
rawSerialiseCertVRF :: CertVRF v -> ByteString
rawDeserialiseVerKeyVRF :: ByteString -> Maybe (VerKeyVRF v)
rawDeserialiseSignKeyVRF :: ByteString -> Maybe (SignKeyVRF v)
rawDeserialiseCertVRF :: ByteString -> Maybe (CertVRF v)
# MINIMAL
algorithmNameVRF
, deriveVerKeyVRF
, evalVRF
, verifyVRF
, seedSizeVRF
, ( genKeyVRF | genKeyPairVRF )
, rawSerialiseVerKeyVRF
, rawSerialiseSignKeyVRF
, rawSerialiseCertVRF
, rawDeserialiseVerKeyVRF
, rawDeserialiseSignKeyVRF
, rawDeserialiseCertVRF
, sizeVerKeyVRF
, sizeSignKeyVRF
, sizeCertVRF
, sizeOutputVRF
#
algorithmNameVRF
, deriveVerKeyVRF
, evalVRF
, verifyVRF
, seedSizeVRF
, (genKeyVRF | genKeyPairVRF)
, rawSerialiseVerKeyVRF
, rawSerialiseSignKeyVRF
, rawSerialiseCertVRF
, rawDeserialiseVerKeyVRF
, rawDeserialiseSignKeyVRF
, rawDeserialiseCertVRF
, sizeVerKeyVRF
, sizeSignKeyVRF
, sizeCertVRF
, sizeOutputVRF
#-}
--
Do not provide instances for keys , see # 38
--
instance ( TypeError ('Text "Ord not supported for signing keys, use the hash instead")
, Eq (SignKeyVRF v)
)
=> Ord (SignKeyVRF v) where
compare = error "unsupported"
instance ( TypeError ('Text "Ord not supported for verification keys, use the hash instead")
, Eq (VerKeyVRF v)
)
=> Ord (VerKeyVRF v) where
compare = error "unsupported"
| The output bytes of the VRF .
--
-- The output size is a fixed number of bytes and is given by 'sizeOutputVRF'.
--
newtype OutputVRF v = OutputVRF { getOutputVRFBytes :: ByteString }
deriving (Eq, Ord, Show, ToCBOR, FromCBOR, NoThunks)
deriving newtype NFData
| The output bytes of the VRF interpreted as a big endian natural number .
--
-- The range of this number is determined by the size of the VRF output bytes.
It is thus in the range @0 .. 2 ^ ( 8 * sizeOutputVRF proxy ) - 1@.
--
getOutputVRFNatural :: OutputVRF v -> Natural
getOutputVRFNatural = bytesToNatural . getOutputVRFBytes
-- | For testing purposes, make an 'OutputVRF' from a 'Natural'.
--
-- The 'OutputVRF' will be of the appropriate size for the 'VRFAlgorithm'.
--
mkTestOutputVRF :: forall v. VRFAlgorithm v => Natural -> OutputVRF v
mkTestOutputVRF = OutputVRF . naturalToBytes sz
where
sz = fromIntegral (sizeOutputVRF (Proxy :: Proxy v))
--
-- Convenient CBOR encoding/decoding
--
-- Implementations in terms of the raw (de)serialise
--
encodeVerKeyVRF :: VRFAlgorithm v => VerKeyVRF v -> Encoding
encodeVerKeyVRF = encodeBytes . rawSerialiseVerKeyVRF
encodeSignKeyVRF :: VRFAlgorithm v => SignKeyVRF v -> Encoding
encodeSignKeyVRF = encodeBytes . rawSerialiseSignKeyVRF
encodeCertVRF :: VRFAlgorithm v => CertVRF v -> Encoding
encodeCertVRF = encodeBytes . rawSerialiseCertVRF
decodeVerKeyVRF :: forall v s. VRFAlgorithm v => Decoder s (VerKeyVRF v)
decodeVerKeyVRF = do
bs <- decodeBytes
case rawDeserialiseVerKeyVRF bs of
Just vk -> return vk
Nothing
| actual /= expected
-> fail ("decodeVerKeyVRF: wrong length, expected " ++
show expected ++ " bytes but got " ++ show actual)
| otherwise -> fail "decodeVerKeyVRF: cannot decode key"
where
expected = fromIntegral (sizeVerKeyVRF (Proxy :: Proxy v))
actual = BS.length bs
decodeSignKeyVRF :: forall v s. VRFAlgorithm v => Decoder s (SignKeyVRF v)
decodeSignKeyVRF = do
bs <- decodeBytes
case rawDeserialiseSignKeyVRF bs of
Just sk -> return sk
Nothing
| actual /= expected
-> fail ("decodeSignKeyVRF: wrong length, expected " ++
show expected ++ " bytes but got " ++ show actual)
| otherwise -> fail "decodeSignKeyVRF: cannot decode key"
where
expected = fromIntegral (sizeSignKeyVRF (Proxy :: Proxy v))
actual = BS.length bs
decodeCertVRF :: forall v s. VRFAlgorithm v => Decoder s (CertVRF v)
decodeCertVRF = do
bs <- decodeBytes
case rawDeserialiseCertVRF bs of
Just crt -> return crt
Nothing
| actual /= expected
-> fail ("decodeCertVRF: wrong length, expected " ++
show expected ++ " bytes but got " ++ show actual)
| otherwise -> fail "decodeCertVRF: cannot decode key"
where
expected = fromIntegral (sizeCertVRF (Proxy :: Proxy v))
actual = BS.length bs
data CertifiedVRF v a
= CertifiedVRF
{ certifiedOutput :: !(OutputVRF v)
, certifiedProof :: !(CertVRF v)
}
deriving Generic
deriving instance VRFAlgorithm v => Show (CertifiedVRF v a)
deriving instance VRFAlgorithm v => Eq (CertifiedVRF v a)
instance VRFAlgorithm v => NoThunks (CertifiedVRF v a)
-- use generic instance
instance (VRFAlgorithm v, Typeable a) => ToCBOR (CertifiedVRF v a) where
toCBOR cvrf =
encodeListLen 2 <>
toCBOR (certifiedOutput cvrf) <>
encodeCertVRF (certifiedProof cvrf)
encodedSizeExpr _size proxy =
1
+ certifiedOutputSize (certifiedOutput <$> proxy)
+ fromIntegral (sizeCertVRF (Proxy :: Proxy v))
where
certifiedOutputSize :: Proxy (OutputVRF v) -> Size
certifiedOutputSize _proxy =
fromIntegral $ sizeOutputVRF (Proxy :: Proxy v)
instance (VRFAlgorithm v, Typeable a) => FromCBOR (CertifiedVRF v a) where
fromCBOR =
CertifiedVRF <$
enforceSize "CertifiedVRF" 2 <*>
fromCBOR <*>
decodeCertVRF
evalCertified
:: (VRFAlgorithm v, Signable v a)
=> ContextVRF v
-> a
-> SignKeyVRF v
-> CertifiedVRF v a
evalCertified ctxt a key = uncurry CertifiedVRF $ evalVRF ctxt a key
verifyCertified
:: (VRFAlgorithm v, Signable v a)
=> ContextVRF v
-> VerKeyVRF v
-> a
-> CertifiedVRF v a
-> Bool
verifyCertified ctxt vk a CertifiedVRF {..} = verifyVRF ctxt vk a (certifiedOutput, certifiedProof)
--
' ' expressions for ' ToCBOR ' instances
--
| ' Size ' expression for ' VerKeyVRF ' which is using ' sizeVerKeyVRF ' encoded as
' ' .
--
encodedVerKeyVRFSizeExpr :: forall v. VRFAlgorithm v => Proxy (VerKeyVRF v) -> Size
encodedVerKeyVRFSizeExpr _proxy =
-- 'encodeBytes' envelope
fromIntegral ((withWordSize :: Word -> Integer) (sizeVerKeyVRF (Proxy :: Proxy v)))
-- payload
+ fromIntegral (sizeVerKeyVRF (Proxy :: Proxy v))
-- | 'Size' expression for 'SignKeyVRF' which is using 'sizeSignKeyVRF' encoded
-- as 'Size'
--
encodedSignKeyVRFSizeExpr :: forall v. VRFAlgorithm v => Proxy (SignKeyVRF v) -> Size
encodedSignKeyVRFSizeExpr _proxy =
-- 'encodeBytes' envelope
fromIntegral ((withWordSize :: Word -> Integer) (sizeSignKeyVRF (Proxy :: Proxy v)))
-- payload
+ fromIntegral (sizeSignKeyVRF (Proxy :: Proxy v))
| ' Size ' expression for ' CertVRF ' which is using ' sizeCertVRF ' encoded as
' ' .
--
encodedCertVRFSizeExpr :: forall v. VRFAlgorithm v => Proxy (CertVRF v) -> Size
encodedCertVRFSizeExpr _proxy =
-- 'encodeBytes' envelope
fromIntegral ((withWordSize :: Word -> Integer) (sizeCertVRF (Proxy :: Proxy v)))
-- payload
+ fromIntegral (sizeCertVRF (Proxy :: Proxy v))
| null | https://raw.githubusercontent.com/input-output-hk/cardano-base/1ea947d123981193a6055a193bc2b0e5fd5001ba/cardano-crypto-class/src/Cardano/Crypto/VRF/Class.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
| Abstract Verifiable Random Functions.
* VRF algorithm class
** VRF output
* 'CertifiedVRF' wrapper
* CBOR encoding and decoding
* Encoded 'Size' expressions
Key and signature types
Unit by default (no context required)
Key generation
| The upper bound on the 'Seed' size needed by 'genKeyVRF', in bytes.
Serialisation/(de)serialisation in fixed-size raw format
The output size is a fixed number of bytes and is given by 'sizeOutputVRF'.
The range of this number is determined by the size of the VRF output bytes.
| For testing purposes, make an 'OutputVRF' from a 'Natural'.
The 'OutputVRF' will be of the appropriate size for the 'VRFAlgorithm'.
Convenient CBOR encoding/decoding
Implementations in terms of the raw (de)serialise
use generic instance
'encodeBytes' envelope
payload
| 'Size' expression for 'SignKeyVRF' which is using 'sizeSignKeyVRF' encoded
as 'Size'
'encodeBytes' envelope
payload
'encodeBytes' envelope
payload | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Cardano.Crypto.VRF.Class
(
VRFAlgorithm (..)
, OutputVRF(..)
, getOutputVRFNatural
, mkTestOutputVRF
, CertifiedVRF (..)
, evalCertified
, verifyCertified
, encodeVerKeyVRF
, decodeVerKeyVRF
, encodeSignKeyVRF
, decodeSignKeyVRF
, encodeCertVRF
, decodeCertVRF
, encodedVerKeyVRFSizeExpr
, encodedSignKeyVRFSizeExpr
, encodedCertVRFSizeExpr
)
where
import Control.DeepSeq (NFData)
import Data.ByteString (ByteString)
import Data.Kind (Type)
import Data.Proxy (Proxy(..))
import Data.Typeable (Typeable)
import GHC.Exts (Constraint)
import GHC.Generics (Generic)
import GHC.Stack
import GHC.TypeLits (TypeError, ErrorMessage (..))
import NoThunks.Class (NoThunks)
import Numeric.Natural (Natural)
import qualified Data.ByteString as BS
import Cardano.Binary
(Decoder, Encoding, FromCBOR (..), ToCBOR (..), Size,
encodeListLen, enforceSize, decodeBytes, encodeBytes,
withWordSize)
import Cardano.Crypto.Util (Empty, bytesToNatural, naturalToBytes)
import Cardano.Crypto.Seed (Seed)
import Cardano.Crypto.Hash.Class (HashAlgorithm, Hash, hashWith)
class ( Typeable v
, Show (VerKeyVRF v)
, Eq (VerKeyVRF v)
, Show (SignKeyVRF v)
, Show (CertVRF v)
, Eq (CertVRF v)
, NoThunks (CertVRF v)
, NoThunks (VerKeyVRF v)
, NoThunks (SignKeyVRF v)
)
=> VRFAlgorithm v where
data VerKeyVRF v :: Type
data SignKeyVRF v :: Type
data CertVRF v :: Type
Metadata and basic key operations
algorithmNameVRF :: proxy v -> String
deriveVerKeyVRF :: SignKeyVRF v -> VerKeyVRF v
hashVerKeyVRF :: HashAlgorithm h => VerKeyVRF v -> Hash h (VerKeyVRF v)
hashVerKeyVRF = hashWith rawSerialiseVerKeyVRF
Core algorithm operations
| Context required to run the VRF algorithm
type ContextVRF v :: Type
type ContextVRF v = ()
type Signable v :: Type -> Constraint
type Signable c = Empty
evalVRF
:: (HasCallStack, Signable v a)
=> ContextVRF v
-> a
-> SignKeyVRF v
-> (OutputVRF v, CertVRF v)
verifyVRF
:: (HasCallStack, Signable v a)
=> ContextVRF v
-> VerKeyVRF v
-> a
-> (OutputVRF v, CertVRF v)
-> Bool
genKeyVRF :: Seed -> SignKeyVRF v
genKeyPairVRF :: Seed -> (SignKeyVRF v, VerKeyVRF v)
genKeyVRF =
fst . genKeyPairVRF
genKeyPairVRF = \seed ->
let sk = genKeyVRF seed
in (sk, deriveVerKeyVRF sk)
seedSizeVRF :: proxy v -> Word
sizeVerKeyVRF :: proxy v -> Word
sizeSignKeyVRF :: proxy v -> Word
sizeCertVRF :: proxy v -> Word
sizeOutputVRF :: proxy v -> Word
rawSerialiseVerKeyVRF :: VerKeyVRF v -> ByteString
rawSerialiseSignKeyVRF :: SignKeyVRF v -> ByteString
rawSerialiseCertVRF :: CertVRF v -> ByteString
rawDeserialiseVerKeyVRF :: ByteString -> Maybe (VerKeyVRF v)
rawDeserialiseSignKeyVRF :: ByteString -> Maybe (SignKeyVRF v)
rawDeserialiseCertVRF :: ByteString -> Maybe (CertVRF v)
# MINIMAL
algorithmNameVRF
, deriveVerKeyVRF
, evalVRF
, verifyVRF
, seedSizeVRF
, ( genKeyVRF | genKeyPairVRF )
, rawSerialiseVerKeyVRF
, rawSerialiseSignKeyVRF
, rawSerialiseCertVRF
, rawDeserialiseVerKeyVRF
, rawDeserialiseSignKeyVRF
, rawDeserialiseCertVRF
, sizeVerKeyVRF
, sizeSignKeyVRF
, sizeCertVRF
, sizeOutputVRF
#
algorithmNameVRF
, deriveVerKeyVRF
, evalVRF
, verifyVRF
, seedSizeVRF
, (genKeyVRF | genKeyPairVRF)
, rawSerialiseVerKeyVRF
, rawSerialiseSignKeyVRF
, rawSerialiseCertVRF
, rawDeserialiseVerKeyVRF
, rawDeserialiseSignKeyVRF
, rawDeserialiseCertVRF
, sizeVerKeyVRF
, sizeSignKeyVRF
, sizeCertVRF
, sizeOutputVRF
#-}
Do not provide instances for keys , see # 38
instance ( TypeError ('Text "Ord not supported for signing keys, use the hash instead")
, Eq (SignKeyVRF v)
)
=> Ord (SignKeyVRF v) where
compare = error "unsupported"
instance ( TypeError ('Text "Ord not supported for verification keys, use the hash instead")
, Eq (VerKeyVRF v)
)
=> Ord (VerKeyVRF v) where
compare = error "unsupported"
| The output bytes of the VRF .
newtype OutputVRF v = OutputVRF { getOutputVRFBytes :: ByteString }
deriving (Eq, Ord, Show, ToCBOR, FromCBOR, NoThunks)
deriving newtype NFData
| The output bytes of the VRF interpreted as a big endian natural number .
It is thus in the range @0 .. 2 ^ ( 8 * sizeOutputVRF proxy ) - 1@.
getOutputVRFNatural :: OutputVRF v -> Natural
getOutputVRFNatural = bytesToNatural . getOutputVRFBytes
mkTestOutputVRF :: forall v. VRFAlgorithm v => Natural -> OutputVRF v
mkTestOutputVRF = OutputVRF . naturalToBytes sz
where
sz = fromIntegral (sizeOutputVRF (Proxy :: Proxy v))
encodeVerKeyVRF :: VRFAlgorithm v => VerKeyVRF v -> Encoding
encodeVerKeyVRF = encodeBytes . rawSerialiseVerKeyVRF
encodeSignKeyVRF :: VRFAlgorithm v => SignKeyVRF v -> Encoding
encodeSignKeyVRF = encodeBytes . rawSerialiseSignKeyVRF
encodeCertVRF :: VRFAlgorithm v => CertVRF v -> Encoding
encodeCertVRF = encodeBytes . rawSerialiseCertVRF
decodeVerKeyVRF :: forall v s. VRFAlgorithm v => Decoder s (VerKeyVRF v)
decodeVerKeyVRF = do
bs <- decodeBytes
case rawDeserialiseVerKeyVRF bs of
Just vk -> return vk
Nothing
| actual /= expected
-> fail ("decodeVerKeyVRF: wrong length, expected " ++
show expected ++ " bytes but got " ++ show actual)
| otherwise -> fail "decodeVerKeyVRF: cannot decode key"
where
expected = fromIntegral (sizeVerKeyVRF (Proxy :: Proxy v))
actual = BS.length bs
decodeSignKeyVRF :: forall v s. VRFAlgorithm v => Decoder s (SignKeyVRF v)
decodeSignKeyVRF = do
bs <- decodeBytes
case rawDeserialiseSignKeyVRF bs of
Just sk -> return sk
Nothing
| actual /= expected
-> fail ("decodeSignKeyVRF: wrong length, expected " ++
show expected ++ " bytes but got " ++ show actual)
| otherwise -> fail "decodeSignKeyVRF: cannot decode key"
where
expected = fromIntegral (sizeSignKeyVRF (Proxy :: Proxy v))
actual = BS.length bs
decodeCertVRF :: forall v s. VRFAlgorithm v => Decoder s (CertVRF v)
decodeCertVRF = do
bs <- decodeBytes
case rawDeserialiseCertVRF bs of
Just crt -> return crt
Nothing
| actual /= expected
-> fail ("decodeCertVRF: wrong length, expected " ++
show expected ++ " bytes but got " ++ show actual)
| otherwise -> fail "decodeCertVRF: cannot decode key"
where
expected = fromIntegral (sizeCertVRF (Proxy :: Proxy v))
actual = BS.length bs
data CertifiedVRF v a
= CertifiedVRF
{ certifiedOutput :: !(OutputVRF v)
, certifiedProof :: !(CertVRF v)
}
deriving Generic
deriving instance VRFAlgorithm v => Show (CertifiedVRF v a)
deriving instance VRFAlgorithm v => Eq (CertifiedVRF v a)
instance VRFAlgorithm v => NoThunks (CertifiedVRF v a)
instance (VRFAlgorithm v, Typeable a) => ToCBOR (CertifiedVRF v a) where
toCBOR cvrf =
encodeListLen 2 <>
toCBOR (certifiedOutput cvrf) <>
encodeCertVRF (certifiedProof cvrf)
encodedSizeExpr _size proxy =
1
+ certifiedOutputSize (certifiedOutput <$> proxy)
+ fromIntegral (sizeCertVRF (Proxy :: Proxy v))
where
certifiedOutputSize :: Proxy (OutputVRF v) -> Size
certifiedOutputSize _proxy =
fromIntegral $ sizeOutputVRF (Proxy :: Proxy v)
instance (VRFAlgorithm v, Typeable a) => FromCBOR (CertifiedVRF v a) where
fromCBOR =
CertifiedVRF <$
enforceSize "CertifiedVRF" 2 <*>
fromCBOR <*>
decodeCertVRF
evalCertified
:: (VRFAlgorithm v, Signable v a)
=> ContextVRF v
-> a
-> SignKeyVRF v
-> CertifiedVRF v a
evalCertified ctxt a key = uncurry CertifiedVRF $ evalVRF ctxt a key
verifyCertified
:: (VRFAlgorithm v, Signable v a)
=> ContextVRF v
-> VerKeyVRF v
-> a
-> CertifiedVRF v a
-> Bool
verifyCertified ctxt vk a CertifiedVRF {..} = verifyVRF ctxt vk a (certifiedOutput, certifiedProof)
' ' expressions for ' ToCBOR ' instances
| ' Size ' expression for ' VerKeyVRF ' which is using ' sizeVerKeyVRF ' encoded as
' ' .
encodedVerKeyVRFSizeExpr :: forall v. VRFAlgorithm v => Proxy (VerKeyVRF v) -> Size
encodedVerKeyVRFSizeExpr _proxy =
fromIntegral ((withWordSize :: Word -> Integer) (sizeVerKeyVRF (Proxy :: Proxy v)))
+ fromIntegral (sizeVerKeyVRF (Proxy :: Proxy v))
encodedSignKeyVRFSizeExpr :: forall v. VRFAlgorithm v => Proxy (SignKeyVRF v) -> Size
encodedSignKeyVRFSizeExpr _proxy =
fromIntegral ((withWordSize :: Word -> Integer) (sizeSignKeyVRF (Proxy :: Proxy v)))
+ fromIntegral (sizeSignKeyVRF (Proxy :: Proxy v))
| ' Size ' expression for ' CertVRF ' which is using ' sizeCertVRF ' encoded as
' ' .
encodedCertVRFSizeExpr :: forall v. VRFAlgorithm v => Proxy (CertVRF v) -> Size
encodedCertVRFSizeExpr _proxy =
fromIntegral ((withWordSize :: Word -> Integer) (sizeCertVRF (Proxy :: Proxy v)))
+ fromIntegral (sizeCertVRF (Proxy :: Proxy v))
|
b36e5eb6dd5c6328bcc7d3346f5d761a3b751124e2e2cd88d3a9d950d272b36d | exercism/common-lisp | grade-school-test.lisp | ;; Ensures that grade-school.lisp and the testing library are always loaded
(eval-when (:compile-toplevel :load-toplevel :execute)
(load "grade-school")
(quicklisp-client:quickload :fiveam))
;; Defines the testing package with symbols from grade-school and FiveAM in scope
;; The `run-tests` function is exported for use by both the user and test-runner
(defpackage :grade-school-test
(:use :cl :fiveam)
(:export :run-tests))
;; Enter the testing package
(in-package :grade-school-test)
;; Define and enter a new FiveAM test-suite
(def-suite* grade-school-suite)
(test roster-is-empty-when-no-students-added
(let ((school (grade-school:make-school)))
(is (equalp '() (grade-school:roster school)))))
(test add-a-student
(let ((school (grade-school:make-school)))
(is (grade-school:add school "Aimee" 2))))
(test student-is-added-to-roster
(let ((school (grade-school:make-school)))
(grade-school:add school "Aimee" 2)
(is (equalp '("Aimee")
(grade-school:roster school)))))
(test adding-multiple-students-in-the-same-grade-in-the-roster
(let ((school (grade-school:make-school)))
(is (grade-school:add school "Blair" 2))
(is (grade-school:add school "James" 2))
(is (grade-school:add school "Paul" 2))))
(test multiple-students-in-the-same-grade-are-added-to-the-roster
(let ((school (grade-school:make-school)))
(grade-school:add school "Blair" 2)
(grade-school:add school "James" 2)
(grade-school:add school "Paul" 2)
(is (equal '("Blair" "James" "Paul") (grade-school:roster school)))))
(test cannot-add-student-to-same-grade-in-the-roster-more-than-once
(let ((school (grade-school:make-school)))
(is (grade-school:add school "Blair" 2))
(is (grade-school:add school "James" 2))
(is (not (grade-school:add school "James" 2)))
(is (grade-school:add school "Paul" 2))))
(test student-not-added-to-same-grade-in-the-roster-more-than-once
(let ((school (grade-school:make-school)))
(grade-school:add school "Blair" 2)
(grade-school:add school "James" 2)
(grade-school:add school "James" 2)
(grade-school:add school "Paul" 2)
(is (equal '("Blair" "James" "Paul") (grade-school:roster school)))))
(test adding-student-in-multiple-grades
(let ((school (grade-school:make-school)))
(is (grade-school:add school "Chelsea" 3))
(is (grade-school:add school "Logan" 7))))
(test students-in-multiple-grades-are-added-to-the-roster
(let ((school (grade-school:make-school)))
(grade-school:add school "Chelsea" 3)
(grade-school:add school "Logan" 7)
(is (equal '("Chelsea" "Logan") (grade-school:roster school)))))
(test cannot-add-same-student-to-multiple-grades-in-the-roster
(let ((school (grade-school:make-school)))
(is (grade-school:add school "Blair" 2))
(is (grade-school:add school "James" 2))
(is (not (grade-school:add school "James" 3)))
(is (grade-school:add school "Paul" 2))))
(test student-not-added-to-multiple-grades-in-the-roster
(let ((school (grade-school:make-school)))
(grade-school:add school "Blair" 2)
(grade-school:add school "James" 2)
(grade-school:add school "James" 3)
(grade-school:add school "Paul" 2)
(is (equal '("Blair" "James" "Paul") (grade-school:roster school)))))
(test students-are-sorted-by-grades-in-the-roster
(let ((school (grade-school:make-school)))
(grade-school:add school "Jim" 3)
(grade-school:add school "Peter" 2)
(grade-school:add school "Anna" 1)
(is (equal '("Anna" "Peter" "Jim") (grade-school:roster school)))))
(test students-are-sorted-by-name-in-the-roster
(let ((school (grade-school:make-school)))
(grade-school:add school "Peter" 2)
(grade-school:add school "Zoe" 2)
(grade-school:add school "Alex" 2)
(is (equal '("Alex" "Peter" "Zoe") (grade-school:roster school)))))
(test students-are-sorted-by-grade-then-by-name-in-the-roster
(let ((school (grade-school:make-school)))
(grade-school:add school "Peter" 2)
(grade-school:add school "Anna" 1)
(grade-school:add school "Barb" 1)
(grade-school:add school "Zoe" 2)
(grade-school:add school "Alex" 2)
(grade-school:add school "Jim" 3)
(grade-school:add school "Charlie" 1)
(is (equal '("Anna" "Barb" "Charlie" "Alex" "Peter" "Zoe" "Jim")
(grade-school:roster school)))))
(test grade-is-empty-if-no-students-in-the-roster
(let ((school (grade-school:make-school)))
(is (equal '() (grade-school:grade school 1)))))
(test grade-is-empty-if-no-students-in-that-grade
(let ((school (grade-school:make-school)))
(grade-school:add school "Peter" 2)
(grade-school:add school "Zoe" 2)
(grade-school:add school "Alex" 2)
(grade-school:add school "Jim" 3)
(is (equal '() (grade-school:grade school 1)))))
(test student-not-added-to-same-grade-more-than-once
(let ((school (grade-school:make-school)))
(grade-school:add school "Blair" 2)
(grade-school:add school "James" 2)
(grade-school:add school "James" 2)
(grade-school:add school "Paul" 2)
(is (equal '("Blair" "James" "Paul") (grade-school:grade school 2)))))
(test student-not-added-to-multiple-grades
(let ((school (grade-school:make-school)))
(grade-school:add school "Blair" 2)
(grade-school:add school "James" 2)
(grade-school:add school "James" 3)
(grade-school:add school "Paul" 3)
(is (equal '("Blair" "James") (grade-school:grade school 2)))))
(test student-not-added-to-other-grade-for-multiple-grades
(let ((school (grade-school:make-school)))
(grade-school:add school "Blair" 2)
(grade-school:add school "James" 2)
(grade-school:add school "James" 3)
(grade-school:add school "Paul" 3)
(is (equal '("Paul") (grade-school:grade school 3)))))
(test students-are-sorted-by-name-in-a-grade
(let ((school (grade-school:make-school)))
(grade-school:add school "Franklin" 5)
(grade-school:add school "Bradley" 5)
(grade-school:add school "Jeff" 1)
(is (equal '("Bradley" "Franklin") (grade-school:grade school 5)))))
(defun run-tests (&optional (test-or-suite 'grade-school-suite))
"Provides human readable results of test run. Default to entire suite."
(run! test-or-suite))
| null | https://raw.githubusercontent.com/exercism/common-lisp/b5d1a3d7bbf755c789d42e692a7ea795a5ce0938/exercises/practice/grade-school/grade-school-test.lisp | lisp | Ensures that grade-school.lisp and the testing library are always loaded
Defines the testing package with symbols from grade-school and FiveAM in scope
The `run-tests` function is exported for use by both the user and test-runner
Enter the testing package
Define and enter a new FiveAM test-suite | (eval-when (:compile-toplevel :load-toplevel :execute)
(load "grade-school")
(quicklisp-client:quickload :fiveam))
(defpackage :grade-school-test
(:use :cl :fiveam)
(:export :run-tests))
(in-package :grade-school-test)
(def-suite* grade-school-suite)
(test roster-is-empty-when-no-students-added
(let ((school (grade-school:make-school)))
(is (equalp '() (grade-school:roster school)))))
(test add-a-student
(let ((school (grade-school:make-school)))
(is (grade-school:add school "Aimee" 2))))
(test student-is-added-to-roster
(let ((school (grade-school:make-school)))
(grade-school:add school "Aimee" 2)
(is (equalp '("Aimee")
(grade-school:roster school)))))
(test adding-multiple-students-in-the-same-grade-in-the-roster
(let ((school (grade-school:make-school)))
(is (grade-school:add school "Blair" 2))
(is (grade-school:add school "James" 2))
(is (grade-school:add school "Paul" 2))))
(test multiple-students-in-the-same-grade-are-added-to-the-roster
(let ((school (grade-school:make-school)))
(grade-school:add school "Blair" 2)
(grade-school:add school "James" 2)
(grade-school:add school "Paul" 2)
(is (equal '("Blair" "James" "Paul") (grade-school:roster school)))))
(test cannot-add-student-to-same-grade-in-the-roster-more-than-once
(let ((school (grade-school:make-school)))
(is (grade-school:add school "Blair" 2))
(is (grade-school:add school "James" 2))
(is (not (grade-school:add school "James" 2)))
(is (grade-school:add school "Paul" 2))))
(test student-not-added-to-same-grade-in-the-roster-more-than-once
(let ((school (grade-school:make-school)))
(grade-school:add school "Blair" 2)
(grade-school:add school "James" 2)
(grade-school:add school "James" 2)
(grade-school:add school "Paul" 2)
(is (equal '("Blair" "James" "Paul") (grade-school:roster school)))))
(test adding-student-in-multiple-grades
(let ((school (grade-school:make-school)))
(is (grade-school:add school "Chelsea" 3))
(is (grade-school:add school "Logan" 7))))
(test students-in-multiple-grades-are-added-to-the-roster
(let ((school (grade-school:make-school)))
(grade-school:add school "Chelsea" 3)
(grade-school:add school "Logan" 7)
(is (equal '("Chelsea" "Logan") (grade-school:roster school)))))
(test cannot-add-same-student-to-multiple-grades-in-the-roster
(let ((school (grade-school:make-school)))
(is (grade-school:add school "Blair" 2))
(is (grade-school:add school "James" 2))
(is (not (grade-school:add school "James" 3)))
(is (grade-school:add school "Paul" 2))))
(test student-not-added-to-multiple-grades-in-the-roster
(let ((school (grade-school:make-school)))
(grade-school:add school "Blair" 2)
(grade-school:add school "James" 2)
(grade-school:add school "James" 3)
(grade-school:add school "Paul" 2)
(is (equal '("Blair" "James" "Paul") (grade-school:roster school)))))
(test students-are-sorted-by-grades-in-the-roster
(let ((school (grade-school:make-school)))
(grade-school:add school "Jim" 3)
(grade-school:add school "Peter" 2)
(grade-school:add school "Anna" 1)
(is (equal '("Anna" "Peter" "Jim") (grade-school:roster school)))))
(test students-are-sorted-by-name-in-the-roster
(let ((school (grade-school:make-school)))
(grade-school:add school "Peter" 2)
(grade-school:add school "Zoe" 2)
(grade-school:add school "Alex" 2)
(is (equal '("Alex" "Peter" "Zoe") (grade-school:roster school)))))
(test students-are-sorted-by-grade-then-by-name-in-the-roster
(let ((school (grade-school:make-school)))
(grade-school:add school "Peter" 2)
(grade-school:add school "Anna" 1)
(grade-school:add school "Barb" 1)
(grade-school:add school "Zoe" 2)
(grade-school:add school "Alex" 2)
(grade-school:add school "Jim" 3)
(grade-school:add school "Charlie" 1)
(is (equal '("Anna" "Barb" "Charlie" "Alex" "Peter" "Zoe" "Jim")
(grade-school:roster school)))))
(test grade-is-empty-if-no-students-in-the-roster
(let ((school (grade-school:make-school)))
(is (equal '() (grade-school:grade school 1)))))
(test grade-is-empty-if-no-students-in-that-grade
(let ((school (grade-school:make-school)))
(grade-school:add school "Peter" 2)
(grade-school:add school "Zoe" 2)
(grade-school:add school "Alex" 2)
(grade-school:add school "Jim" 3)
(is (equal '() (grade-school:grade school 1)))))
(test student-not-added-to-same-grade-more-than-once
(let ((school (grade-school:make-school)))
(grade-school:add school "Blair" 2)
(grade-school:add school "James" 2)
(grade-school:add school "James" 2)
(grade-school:add school "Paul" 2)
(is (equal '("Blair" "James" "Paul") (grade-school:grade school 2)))))
(test student-not-added-to-multiple-grades
(let ((school (grade-school:make-school)))
(grade-school:add school "Blair" 2)
(grade-school:add school "James" 2)
(grade-school:add school "James" 3)
(grade-school:add school "Paul" 3)
(is (equal '("Blair" "James") (grade-school:grade school 2)))))
(test student-not-added-to-other-grade-for-multiple-grades
(let ((school (grade-school:make-school)))
(grade-school:add school "Blair" 2)
(grade-school:add school "James" 2)
(grade-school:add school "James" 3)
(grade-school:add school "Paul" 3)
(is (equal '("Paul") (grade-school:grade school 3)))))
(test students-are-sorted-by-name-in-a-grade
(let ((school (grade-school:make-school)))
(grade-school:add school "Franklin" 5)
(grade-school:add school "Bradley" 5)
(grade-school:add school "Jeff" 1)
(is (equal '("Bradley" "Franklin") (grade-school:grade school 5)))))
(defun run-tests (&optional (test-or-suite 'grade-school-suite))
"Provides human readable results of test run. Default to entire suite."
(run! test-or-suite))
|
071ed812dbf5b6372181ea3e8b3c6ff32df62d74db3face491e2137e3fef0168 | expipiplus1/vulkan | VK_EXT_pipeline_robustness.hs | {-# language CPP #-}
-- | = Name
--
-- VK_EXT_pipeline_robustness - device extension
--
-- == VK_EXT_pipeline_robustness
--
-- [__Name String__]
@VK_EXT_pipeline_robustness@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
69
--
-- [__Revision__]
1
--
-- [__Extension and Version Dependencies__]
--
- Requires support for Vulkan 1.0
--
-- - Requires @VK_KHR_get_physical_device_properties2@ to be enabled
-- for any device-level functionality
--
-- [__Contact__]
--
-- - Jarred Davies
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
2022 - 07 - 12
--
-- [__Interactions and External Dependencies__]
--
-- - Interacts with @VK_EXT_robustness2@
--
- Interacts with @VK_EXT_image_robustness@
--
-- - Interacts with @VK_KHR_ray_tracing_pipeline@
--
-- [__Contributors__]
--
- Jarred Davies , Imagination Technologies
--
- , Imagination Technologies
--
- , NVIDIA
--
- , Broadcom Corporation
--
- , Qualcomm Technologies , Inc.
--
- , Intel
--
- , Intel
--
- , Google , Inc.
--
-- == Description
--
-- This extension allows users to request robustness on a per-pipeline
-- stage basis.
--
-- As
-- <-extensions/html/vkspec.html#features-robustBufferAccess robustBufferAccess>
-- and other robustness features may have an adverse effect on performance,
-- this extension is designed to allow users to request robust behavior
-- only where it may be needed.
--
-- == New Structures
--
- Extending ' Vulkan . Core10.Pipeline . ' ,
' Vulkan . Core10.Pipeline . ComputePipelineCreateInfo ' ,
' Vulkan . Core10.Pipeline . PipelineShaderStageCreateInfo ' ,
' Vulkan . Extensions . VK_KHR_ray_tracing_pipeline . RayTracingPipelineCreateInfoKHR ' :
--
-- - 'PipelineRobustnessCreateInfoEXT'
--
-- - Extending
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2 ' ,
' Vulkan . Core10.Device . DeviceCreateInfo ' :
--
-- - 'PhysicalDevicePipelineRobustnessFeaturesEXT'
--
-- - Extending
' Vulkan . ' :
--
-- - 'PhysicalDevicePipelineRobustnessPropertiesEXT'
--
-- == New Enums
--
-- - 'PipelineRobustnessBufferBehaviorEXT'
--
-- - 'PipelineRobustnessImageBehaviorEXT'
--
-- == New Enum Constants
--
-- - 'EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME'
--
- ' '
--
- Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' :
--
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT '
--
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_PROPERTIES_EXT '
--
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PIPELINE_ROBUSTNESS_CREATE_INFO_EXT '
--
-- == Version History
--
- Revision 1 , 2022 - 07 - 12 ( Jarred Davies )
--
-- - Initial version
--
-- == See Also
--
-- 'PhysicalDevicePipelineRobustnessFeaturesEXT',
-- 'PhysicalDevicePipelineRobustnessPropertiesEXT',
-- 'PipelineRobustnessBufferBehaviorEXT',
-- 'PipelineRobustnessCreateInfoEXT', 'PipelineRobustnessImageBehaviorEXT'
--
-- == Document Notes
--
-- For more information, see the
-- <-extensions/html/vkspec.html#VK_EXT_pipeline_robustness Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_EXT_pipeline_robustness ( PhysicalDevicePipelineRobustnessFeaturesEXT(..)
, PipelineRobustnessCreateInfoEXT(..)
, PhysicalDevicePipelineRobustnessPropertiesEXT(..)
, PipelineRobustnessBufferBehaviorEXT( PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT
, PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT
, PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT
, PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT
, ..
)
, PipelineRobustnessImageBehaviorEXT( PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DEVICE_DEFAULT_EXT
, PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DISABLED_EXT
, PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_EXT
, PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT
, ..
)
, EXT_PIPELINE_ROBUSTNESS_SPEC_VERSION
, pattern EXT_PIPELINE_ROBUSTNESS_SPEC_VERSION
, EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME
, pattern EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME
) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import GHC.Show (showsPrec)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero)
import Vulkan.Zero (Zero(..))
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import Data.Int (Int32)
import Foreign.Ptr (Ptr)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Data.Kind (Type)
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_PROPERTIES_EXT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PIPELINE_ROBUSTNESS_CREATE_INFO_EXT))
-- | VkPhysicalDevicePipelineRobustnessFeaturesEXT - Structure describing
-- whether an implementation supports robustness requests on a per-pipeline
-- stage granularity
--
-- = Members
--
-- This structure describes the following feature:
--
-- = Description
--
-- Note
--
-- Enabling
< -extensions/html/vkspec.html#features-pipelineRobustness pipelineRobustness >
-- may, on some platforms, incur a minor performance cost when
-- <-extensions/html/vkspec.html#features-robustBufferAccess robustBufferAccess>
-- is disabled, even for pipelines which do not make use of any robustness
-- features. If robustness is not needed,
< -extensions/html/vkspec.html#features-pipelineRobustness pipelineRobustness >
-- should not be enabled by an application.
--
-- If the 'PhysicalDevicePipelineRobustnessFeaturesEXT' structure is
-- included in the @pNext@ chain of the
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2 '
-- structure passed to
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2 ' ,
-- it is filled in to indicate whether each corresponding feature is
supported . ' PhysicalDevicePipelineRobustnessFeaturesEXT ' also be
used in the @pNext@ chain of ' Vulkan . Core10.Device . DeviceCreateInfo ' to
-- selectively enable these features.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_EXT_pipeline_robustness VK_EXT_pipeline_robustness>,
' Vulkan . Core10.FundamentalTypes . Bool32 ' ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data PhysicalDevicePipelineRobustnessFeaturesEXT = PhysicalDevicePipelineRobustnessFeaturesEXT
{ -- | #features-pipelineRobustness# @pipelineRobustness@ indicates that
robustness be requested on a per - pipeline - stage granularity .
pipelineRobustness :: Bool }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PhysicalDevicePipelineRobustnessFeaturesEXT)
#endif
deriving instance Show PhysicalDevicePipelineRobustnessFeaturesEXT
instance ToCStruct PhysicalDevicePipelineRobustnessFeaturesEXT where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PhysicalDevicePipelineRobustnessFeaturesEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (pipelineRobustness))
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
f
instance FromCStruct PhysicalDevicePipelineRobustnessFeaturesEXT where
peekCStruct p = do
pipelineRobustness <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
pure $ PhysicalDevicePipelineRobustnessFeaturesEXT
(bool32ToBool pipelineRobustness)
instance Storable PhysicalDevicePipelineRobustnessFeaturesEXT where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PhysicalDevicePipelineRobustnessFeaturesEXT where
zero = PhysicalDevicePipelineRobustnessFeaturesEXT
zero
-- | VkPipelineRobustnessCreateInfoEXT - Structure controlling the robustness
-- of a newly created pipeline shader stage
--
-- = Description
--
-- Resources bound as
' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_MUTABLE_EXT ' will
-- have the robustness behavior that covers its active descriptor type.
--
-- The scope of the effect of 'PipelineRobustnessCreateInfoEXT' depends on
-- which structure’s @pNext@ chain it is included in.
--
- ' Vulkan . Core10.Pipeline . ' ,
' Vulkan . Extensions . VK_KHR_ray_tracing_pipeline . RayTracingPipelineCreateInfoKHR ' ,
' Vulkan . Core10.Pipeline . ComputePipelineCreateInfo ' :
-- The robustness behavior described by
-- 'PipelineRobustnessCreateInfoEXT' applies to all accesses through
-- this pipeline
--
- ' Vulkan . Core10.Pipeline . ' :
-- The robustness behavior described by
-- 'PipelineRobustnessCreateInfoEXT' applies to all accesses emanating
-- from the shader code of this shader stage
--
-- If 'PipelineRobustnessCreateInfoEXT' is specified for both a pipeline
-- and a pipeline stage, the 'PipelineRobustnessCreateInfoEXT' specified
-- for the pipeline stage will take precedence.
--
-- When 'PipelineRobustnessCreateInfoEXT' is specified for a pipeline, it
-- only affects the subset of the pipeline that is specified by the create
-- info, as opposed to subsets linked from pipeline libraries. For
' Vulkan . Core10.Pipeline . ' , that subset is
-- specified by
' Vulkan . Extensions . VK_EXT_graphics_pipeline_library .
-- For
' Vulkan . Extensions . VK_KHR_ray_tracing_pipeline . RayTracingPipelineCreateInfoKHR ' ,
-- that subset is specified by the specific stages in
' Vulkan . Extensions . VK_KHR_ray_tracing_pipeline . RayTracingPipelineCreateInfoKHR'::@pStages@.
--
-- == Valid Usage
--
-- - #VUID-VkPipelineRobustnessCreateInfoEXT-pipelineRobustness-06926# If
-- the
< -extensions/html/vkspec.html#features-pipelineRobustness pipelineRobustness >
-- feature is not enabled, @storageBuffers@ /must/ be
-- 'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT'
--
-- - #VUID-VkPipelineRobustnessCreateInfoEXT-pipelineRobustness-06927# If
-- the
< -extensions/html/vkspec.html#features-pipelineRobustness pipelineRobustness >
-- feature is not enabled, @uniformBuffers@ /must/ be
-- 'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT'
--
-- - #VUID-VkPipelineRobustnessCreateInfoEXT-pipelineRobustness-06928# If
-- the
< -extensions/html/vkspec.html#features-pipelineRobustness pipelineRobustness >
-- feature is not enabled, @vertexInputs@ /must/ be
-- 'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT'
--
-- - #VUID-VkPipelineRobustnessCreateInfoEXT-pipelineRobustness-06929# If
-- the
< -extensions/html/vkspec.html#features-pipelineRobustness pipelineRobustness >
-- feature is not enabled, @images@ /must/ be
-- 'PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DEVICE_DEFAULT_EXT'
--
- # VUID - VkPipelineRobustnessCreateInfoEXT - robustImageAccess-06930 # If
-- the
-- <-extensions/html/vkspec.html#features-robustImageAccess robustImageAccess>
-- feature is not supported, @images@ /must/ not be
-- 'PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_EXT'
--
-- - #VUID-VkPipelineRobustnessCreateInfoEXT-robustBufferAccess2-06931#
-- If the
-- <-extensions/html/vkspec.html#features-robustBufferAccess2 robustBufferAccess2>
-- feature is not supported, @storageBuffers@ /must/ not be
-- 'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT'
--
-- - #VUID-VkPipelineRobustnessCreateInfoEXT-robustBufferAccess2-06932#
-- If the
-- <-extensions/html/vkspec.html#features-robustBufferAccess2 robustBufferAccess2>
-- feature is not supported, @uniformBuffers@ /must/ not be
-- 'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT'
--
-- - #VUID-VkPipelineRobustnessCreateInfoEXT-robustBufferAccess2-06933#
-- If the
-- <-extensions/html/vkspec.html#features-robustBufferAccess2 robustBufferAccess2>
-- feature is not supported, @vertexInputs@ /must/ not be
-- 'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT'
--
-- - #VUID-VkPipelineRobustnessCreateInfoEXT-robustImageAccess2-06934# If
-- the
< -extensions/html/vkspec.html#features-robustImageAccess2 robustImageAccess2 >
-- feature is not supported, @images@ /must/ not be
' PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT '
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkPipelineRobustnessCreateInfoEXT-sType-sType# @sType@ /must/
-- be
' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PIPELINE_ROBUSTNESS_CREATE_INFO_EXT '
--
-- - #VUID-VkPipelineRobustnessCreateInfoEXT-storageBuffers-parameter#
-- @storageBuffers@ /must/ be a valid
-- 'PipelineRobustnessBufferBehaviorEXT' value
--
-- - #VUID-VkPipelineRobustnessCreateInfoEXT-uniformBuffers-parameter#
-- @uniformBuffers@ /must/ be a valid
-- 'PipelineRobustnessBufferBehaviorEXT' value
--
-- - #VUID-VkPipelineRobustnessCreateInfoEXT-vertexInputs-parameter#
-- @vertexInputs@ /must/ be a valid
-- 'PipelineRobustnessBufferBehaviorEXT' value
--
-- - #VUID-VkPipelineRobustnessCreateInfoEXT-images-parameter# @images@
-- /must/ be a valid 'PipelineRobustnessImageBehaviorEXT' value
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_EXT_pipeline_robustness VK_EXT_pipeline_robustness>,
-- 'PipelineRobustnessBufferBehaviorEXT',
-- 'PipelineRobustnessImageBehaviorEXT',
' Vulkan . Core10.Enums . StructureType . StructureType '
data PipelineRobustnessCreateInfoEXT = PipelineRobustnessCreateInfoEXT
{ -- | @storageBuffers@ sets the behaviour of out of bounds accesses made to
-- resources bound as:
--
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_STORAGE_BUFFER '
--
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER '
--
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC '
storageBuffers :: PipelineRobustnessBufferBehaviorEXT
, -- | @uniformBuffers@ describes the behaviour of out of bounds accesses made
-- to resources bound as:
--
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER '
--
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_UNIFORM_BUFFER '
--
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC '
--
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK '
uniformBuffers :: PipelineRobustnessBufferBehaviorEXT
, -- | @vertexInputs@ describes the behaviour of out of bounds accesses made to
-- vertex input attributes
vertexInputs :: PipelineRobustnessBufferBehaviorEXT
, -- | @images@ describes the behaviour of out of bounds accesses made to
-- resources bound as:
--
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_SAMPLED_IMAGE '
--
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_STORAGE_IMAGE '
images :: PipelineRobustnessImageBehaviorEXT
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PipelineRobustnessCreateInfoEXT)
#endif
deriving instance Show PipelineRobustnessCreateInfoEXT
instance ToCStruct PipelineRobustnessCreateInfoEXT where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PipelineRobustnessCreateInfoEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_ROBUSTNESS_CREATE_INFO_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (storageBuffers)
poke ((p `plusPtr` 20 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (uniformBuffers)
poke ((p `plusPtr` 24 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (vertexInputs)
poke ((p `plusPtr` 28 :: Ptr PipelineRobustnessImageBehaviorEXT)) (images)
f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_ROBUSTNESS_CREATE_INFO_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (zero)
poke ((p `plusPtr` 20 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (zero)
poke ((p `plusPtr` 24 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (zero)
poke ((p `plusPtr` 28 :: Ptr PipelineRobustnessImageBehaviorEXT)) (zero)
f
instance FromCStruct PipelineRobustnessCreateInfoEXT where
peekCStruct p = do
storageBuffers <- peek @PipelineRobustnessBufferBehaviorEXT ((p `plusPtr` 16 :: Ptr PipelineRobustnessBufferBehaviorEXT))
uniformBuffers <- peek @PipelineRobustnessBufferBehaviorEXT ((p `plusPtr` 20 :: Ptr PipelineRobustnessBufferBehaviorEXT))
vertexInputs <- peek @PipelineRobustnessBufferBehaviorEXT ((p `plusPtr` 24 :: Ptr PipelineRobustnessBufferBehaviorEXT))
images <- peek @PipelineRobustnessImageBehaviorEXT ((p `plusPtr` 28 :: Ptr PipelineRobustnessImageBehaviorEXT))
pure $ PipelineRobustnessCreateInfoEXT
storageBuffers uniformBuffers vertexInputs images
instance Storable PipelineRobustnessCreateInfoEXT where
sizeOf ~_ = 32
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PipelineRobustnessCreateInfoEXT where
zero = PipelineRobustnessCreateInfoEXT
zero
zero
zero
zero
-- | VkPhysicalDevicePipelineRobustnessPropertiesEXT - Structure describing
-- the default robustness behavior of a physical device
--
-- = Description
--
Some implementations of Vulkan may be able to guarantee that certain
-- types of accesses are always performed with robustness even when the
Vulkan API ’s robustness features are not explicitly enabled .
--
-- Even when an implementation reports that accesses to a given resource
-- type are robust by default, it remains invalid to make an out of bounds
-- access without requesting the appropriate robustness feature.
--
-- If the 'PhysicalDevicePipelineRobustnessPropertiesEXT' structure is
-- included in the @pNext@ chain of the
' Vulkan . '
-- structure passed to
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceProperties2 ' ,
-- it is filled in with each corresponding implementation-dependent
-- property.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_EXT_pipeline_robustness VK_EXT_pipeline_robustness>,
-- 'PipelineRobustnessBufferBehaviorEXT',
-- 'PipelineRobustnessImageBehaviorEXT',
' Vulkan . Core10.Enums . StructureType . StructureType '
data PhysicalDevicePipelineRobustnessPropertiesEXT = PhysicalDevicePipelineRobustnessPropertiesEXT
{ -- | @defaultRobustnessStorageBuffers@ describes the behaviour of out of
-- bounds accesses made to storage buffers when no robustness features are
-- enabled
defaultRobustnessStorageBuffers :: PipelineRobustnessBufferBehaviorEXT
, -- | @defaultRobustnessUniformBuffers@ describes the behaviour of out of
-- bounds accesses made to uniform buffers when no robustness features are
-- enabled
defaultRobustnessUniformBuffers :: PipelineRobustnessBufferBehaviorEXT
, -- | @defaultRobustnessVertexInputs@ describes the behaviour of out of bounds
-- accesses made to vertex input attributes when no robustness features are
-- enabled
defaultRobustnessVertexInputs :: PipelineRobustnessBufferBehaviorEXT
, -- | @defaultRobustnessImages@ describes the behaviour of out of bounds
-- accesses made to images when no robustness features are enabled
defaultRobustnessImages :: PipelineRobustnessImageBehaviorEXT
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PhysicalDevicePipelineRobustnessPropertiesEXT)
#endif
deriving instance Show PhysicalDevicePipelineRobustnessPropertiesEXT
instance ToCStruct PhysicalDevicePipelineRobustnessPropertiesEXT where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PhysicalDevicePipelineRobustnessPropertiesEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_PROPERTIES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (defaultRobustnessStorageBuffers)
poke ((p `plusPtr` 20 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (defaultRobustnessUniformBuffers)
poke ((p `plusPtr` 24 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (defaultRobustnessVertexInputs)
poke ((p `plusPtr` 28 :: Ptr PipelineRobustnessImageBehaviorEXT)) (defaultRobustnessImages)
f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_PROPERTIES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (zero)
poke ((p `plusPtr` 20 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (zero)
poke ((p `plusPtr` 24 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (zero)
poke ((p `plusPtr` 28 :: Ptr PipelineRobustnessImageBehaviorEXT)) (zero)
f
instance FromCStruct PhysicalDevicePipelineRobustnessPropertiesEXT where
peekCStruct p = do
defaultRobustnessStorageBuffers <- peek @PipelineRobustnessBufferBehaviorEXT ((p `plusPtr` 16 :: Ptr PipelineRobustnessBufferBehaviorEXT))
defaultRobustnessUniformBuffers <- peek @PipelineRobustnessBufferBehaviorEXT ((p `plusPtr` 20 :: Ptr PipelineRobustnessBufferBehaviorEXT))
defaultRobustnessVertexInputs <- peek @PipelineRobustnessBufferBehaviorEXT ((p `plusPtr` 24 :: Ptr PipelineRobustnessBufferBehaviorEXT))
defaultRobustnessImages <- peek @PipelineRobustnessImageBehaviorEXT ((p `plusPtr` 28 :: Ptr PipelineRobustnessImageBehaviorEXT))
pure $ PhysicalDevicePipelineRobustnessPropertiesEXT
defaultRobustnessStorageBuffers
defaultRobustnessUniformBuffers
defaultRobustnessVertexInputs
defaultRobustnessImages
instance Storable PhysicalDevicePipelineRobustnessPropertiesEXT where
sizeOf ~_ = 32
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PhysicalDevicePipelineRobustnessPropertiesEXT where
zero = PhysicalDevicePipelineRobustnessPropertiesEXT
zero
zero
zero
zero
-- | VkPipelineRobustnessBufferBehaviorEXT - Enum controlling the robustness
-- of buffer accesses in a pipeline stage
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_EXT_pipeline_robustness VK_EXT_pipeline_robustness>,
-- 'PhysicalDevicePipelineRobustnessPropertiesEXT',
-- 'PipelineRobustnessCreateInfoEXT'
newtype PipelineRobustnessBufferBehaviorEXT = PipelineRobustnessBufferBehaviorEXT Int32
deriving newtype (Eq, Ord, Storable, Zero)
-- | 'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT' specifies that
-- this pipeline stage follows the behavior of robustness features that are
-- enabled on the device that created this pipeline
pattern PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT = PipelineRobustnessBufferBehaviorEXT 0
-- | 'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT' specifies that buffer
-- accesses by this pipeline stage to the relevant resource types /must/
-- not be out of bounds
pattern PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT = PipelineRobustnessBufferBehaviorEXT 1
-- | 'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT' specifies
-- that out of bounds accesses by this pipeline stage to the relevant
-- resource types behave as if the
-- <-extensions/html/vkspec.html#features-robustBufferAccess robustBufferAccess>
-- feature is enabled
pattern PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT = PipelineRobustnessBufferBehaviorEXT 2
-- | 'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT'
-- specifies that out of bounds accesses by this pipeline stage to the
-- relevant resource types behave as if the
-- <-extensions/html/vkspec.html#features-robustBufferAccess2 robustBufferAccess2>
-- feature is enabled
pattern PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT = PipelineRobustnessBufferBehaviorEXT 3
# COMPLETE
PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT
, PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT
, , PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT : :
PipelineRobustnessBufferBehaviorEXT
#
PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT
, PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT
, PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT
, PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT ::
PipelineRobustnessBufferBehaviorEXT
#-}
conNamePipelineRobustnessBufferBehaviorEXT :: String
conNamePipelineRobustnessBufferBehaviorEXT = "PipelineRobustnessBufferBehaviorEXT"
enumPrefixPipelineRobustnessBufferBehaviorEXT :: String
enumPrefixPipelineRobustnessBufferBehaviorEXT = "PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_"
showTablePipelineRobustnessBufferBehaviorEXT :: [(PipelineRobustnessBufferBehaviorEXT, String)]
showTablePipelineRobustnessBufferBehaviorEXT =
[
( PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT
, "DEVICE_DEFAULT_EXT"
)
,
( PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT
, "DISABLED_EXT"
)
,
( PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT
, "ROBUST_BUFFER_ACCESS_EXT"
)
,
( PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT
, "ROBUST_BUFFER_ACCESS_2_EXT"
)
]
instance Show PipelineRobustnessBufferBehaviorEXT where
showsPrec =
enumShowsPrec
enumPrefixPipelineRobustnessBufferBehaviorEXT
showTablePipelineRobustnessBufferBehaviorEXT
conNamePipelineRobustnessBufferBehaviorEXT
(\(PipelineRobustnessBufferBehaviorEXT x) -> x)
(showsPrec 11)
instance Read PipelineRobustnessBufferBehaviorEXT where
readPrec =
enumReadPrec
enumPrefixPipelineRobustnessBufferBehaviorEXT
showTablePipelineRobustnessBufferBehaviorEXT
conNamePipelineRobustnessBufferBehaviorEXT
PipelineRobustnessBufferBehaviorEXT
-- | VkPipelineRobustnessImageBehaviorEXT - Enum controlling the robustness
-- of image accesses in a pipeline stage
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_EXT_pipeline_robustness VK_EXT_pipeline_robustness>,
-- 'PhysicalDevicePipelineRobustnessPropertiesEXT',
-- 'PipelineRobustnessCreateInfoEXT'
newtype PipelineRobustnessImageBehaviorEXT = PipelineRobustnessImageBehaviorEXT Int32
deriving newtype (Eq, Ord, Storable, Zero)
-- | 'PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DEVICE_DEFAULT_EXT' specifies that
-- this pipeline stage follows the behavior of robustness features that are
-- enabled on the device that created this pipeline
pattern PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DEVICE_DEFAULT_EXT = PipelineRobustnessImageBehaviorEXT 0
-- | 'PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DISABLED_EXT' specifies that image
-- accesses by this pipeline stage to the relevant resource types /must/
-- not be out of bounds
pattern PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DISABLED_EXT = PipelineRobustnessImageBehaviorEXT 1
-- | 'PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_EXT' specifies
-- that out of bounds accesses by this pipeline stage to images behave as
-- if the
-- <-extensions/html/vkspec.html#features-robustImageAccess robustImageAccess>
-- feature is enabled
pattern PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_EXT = PipelineRobustnessImageBehaviorEXT 2
| ' PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT ' specifies
-- that out of bounds accesses by this pipeline stage to images behave as
-- if the
-- <-extensions/html/vkspec.html#features-robustImageAccess2 robustImageAccess2>
-- feature is enabled
pattern PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT = PipelineRobustnessImageBehaviorEXT 3
{-# COMPLETE
PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DEVICE_DEFAULT_EXT
, PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DISABLED_EXT
, PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_EXT
, PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT ::
PipelineRobustnessImageBehaviorEXT
#-}
conNamePipelineRobustnessImageBehaviorEXT :: String
conNamePipelineRobustnessImageBehaviorEXT = "PipelineRobustnessImageBehaviorEXT"
enumPrefixPipelineRobustnessImageBehaviorEXT :: String
enumPrefixPipelineRobustnessImageBehaviorEXT = "PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_"
showTablePipelineRobustnessImageBehaviorEXT :: [(PipelineRobustnessImageBehaviorEXT, String)]
showTablePipelineRobustnessImageBehaviorEXT =
[
( PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DEVICE_DEFAULT_EXT
, "DEVICE_DEFAULT_EXT"
)
,
( PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DISABLED_EXT
, "DISABLED_EXT"
)
,
( PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_EXT
, "ROBUST_IMAGE_ACCESS_EXT"
)
,
( PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT
, "ROBUST_IMAGE_ACCESS_2_EXT"
)
]
instance Show PipelineRobustnessImageBehaviorEXT where
showsPrec =
enumShowsPrec
enumPrefixPipelineRobustnessImageBehaviorEXT
showTablePipelineRobustnessImageBehaviorEXT
conNamePipelineRobustnessImageBehaviorEXT
(\(PipelineRobustnessImageBehaviorEXT x) -> x)
(showsPrec 11)
instance Read PipelineRobustnessImageBehaviorEXT where
readPrec =
enumReadPrec
enumPrefixPipelineRobustnessImageBehaviorEXT
showTablePipelineRobustnessImageBehaviorEXT
conNamePipelineRobustnessImageBehaviorEXT
PipelineRobustnessImageBehaviorEXT
type EXT_PIPELINE_ROBUSTNESS_SPEC_VERSION = 1
No documentation found for TopLevel " VK_EXT_PIPELINE_ROBUSTNESS_SPEC_VERSION "
pattern EXT_PIPELINE_ROBUSTNESS_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_PIPELINE_ROBUSTNESS_SPEC_VERSION = 1
type EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME = "VK_EXT_pipeline_robustness"
No documentation found for TopLevel " VK_EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME "
pattern EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME = "VK_EXT_pipeline_robustness"
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/d765efafb2ea2965ceba268e9e4e54cbd415aa33/src/Vulkan/Extensions/VK_EXT_pipeline_robustness.hs | haskell | # language CPP #
| = Name
VK_EXT_pipeline_robustness - device extension
== VK_EXT_pipeline_robustness
[__Name String__]
[__Extension Type__]
Device extension
[__Registered Extension Number__]
[__Revision__]
[__Extension and Version Dependencies__]
- Requires @VK_KHR_get_physical_device_properties2@ to be enabled
for any device-level functionality
[__Contact__]
- Jarred Davies
== Other Extension Metadata
[__Last Modified Date__]
[__Interactions and External Dependencies__]
- Interacts with @VK_EXT_robustness2@
- Interacts with @VK_KHR_ray_tracing_pipeline@
[__Contributors__]
== Description
This extension allows users to request robustness on a per-pipeline
stage basis.
As
<-extensions/html/vkspec.html#features-robustBufferAccess robustBufferAccess>
and other robustness features may have an adverse effect on performance,
this extension is designed to allow users to request robust behavior
only where it may be needed.
== New Structures
- 'PipelineRobustnessCreateInfoEXT'
- Extending
- 'PhysicalDevicePipelineRobustnessFeaturesEXT'
- Extending
- 'PhysicalDevicePipelineRobustnessPropertiesEXT'
== New Enums
- 'PipelineRobustnessBufferBehaviorEXT'
- 'PipelineRobustnessImageBehaviorEXT'
== New Enum Constants
- 'EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME'
== Version History
- Initial version
== See Also
'PhysicalDevicePipelineRobustnessFeaturesEXT',
'PhysicalDevicePipelineRobustnessPropertiesEXT',
'PipelineRobustnessBufferBehaviorEXT',
'PipelineRobustnessCreateInfoEXT', 'PipelineRobustnessImageBehaviorEXT'
== Document Notes
For more information, see the
<-extensions/html/vkspec.html#VK_EXT_pipeline_robustness Vulkan Specification>
This page is a generated document. Fixes and changes should be made to
the generator scripts, not directly.
| VkPhysicalDevicePipelineRobustnessFeaturesEXT - Structure describing
whether an implementation supports robustness requests on a per-pipeline
stage granularity
= Members
This structure describes the following feature:
= Description
Note
Enabling
may, on some platforms, incur a minor performance cost when
<-extensions/html/vkspec.html#features-robustBufferAccess robustBufferAccess>
is disabled, even for pipelines which do not make use of any robustness
features. If robustness is not needed,
should not be enabled by an application.
If the 'PhysicalDevicePipelineRobustnessFeaturesEXT' structure is
included in the @pNext@ chain of the
structure passed to
it is filled in to indicate whether each corresponding feature is
selectively enable these features.
== Valid Usage (Implicit)
= See Also
<-extensions/html/vkspec.html#VK_EXT_pipeline_robustness VK_EXT_pipeline_robustness>,
| #features-pipelineRobustness# @pipelineRobustness@ indicates that
| VkPipelineRobustnessCreateInfoEXT - Structure controlling the robustness
of a newly created pipeline shader stage
= Description
Resources bound as
have the robustness behavior that covers its active descriptor type.
The scope of the effect of 'PipelineRobustnessCreateInfoEXT' depends on
which structure’s @pNext@ chain it is included in.
The robustness behavior described by
'PipelineRobustnessCreateInfoEXT' applies to all accesses through
this pipeline
The robustness behavior described by
'PipelineRobustnessCreateInfoEXT' applies to all accesses emanating
from the shader code of this shader stage
If 'PipelineRobustnessCreateInfoEXT' is specified for both a pipeline
and a pipeline stage, the 'PipelineRobustnessCreateInfoEXT' specified
for the pipeline stage will take precedence.
When 'PipelineRobustnessCreateInfoEXT' is specified for a pipeline, it
only affects the subset of the pipeline that is specified by the create
info, as opposed to subsets linked from pipeline libraries. For
specified by
For
that subset is specified by the specific stages in
== Valid Usage
- #VUID-VkPipelineRobustnessCreateInfoEXT-pipelineRobustness-06926# If
the
feature is not enabled, @storageBuffers@ /must/ be
'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT'
- #VUID-VkPipelineRobustnessCreateInfoEXT-pipelineRobustness-06927# If
the
feature is not enabled, @uniformBuffers@ /must/ be
'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT'
- #VUID-VkPipelineRobustnessCreateInfoEXT-pipelineRobustness-06928# If
the
feature is not enabled, @vertexInputs@ /must/ be
'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT'
- #VUID-VkPipelineRobustnessCreateInfoEXT-pipelineRobustness-06929# If
the
feature is not enabled, @images@ /must/ be
'PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DEVICE_DEFAULT_EXT'
the
<-extensions/html/vkspec.html#features-robustImageAccess robustImageAccess>
feature is not supported, @images@ /must/ not be
'PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_EXT'
- #VUID-VkPipelineRobustnessCreateInfoEXT-robustBufferAccess2-06931#
If the
<-extensions/html/vkspec.html#features-robustBufferAccess2 robustBufferAccess2>
feature is not supported, @storageBuffers@ /must/ not be
'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT'
- #VUID-VkPipelineRobustnessCreateInfoEXT-robustBufferAccess2-06932#
If the
<-extensions/html/vkspec.html#features-robustBufferAccess2 robustBufferAccess2>
feature is not supported, @uniformBuffers@ /must/ not be
'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT'
- #VUID-VkPipelineRobustnessCreateInfoEXT-robustBufferAccess2-06933#
If the
<-extensions/html/vkspec.html#features-robustBufferAccess2 robustBufferAccess2>
feature is not supported, @vertexInputs@ /must/ not be
'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT'
- #VUID-VkPipelineRobustnessCreateInfoEXT-robustImageAccess2-06934# If
the
feature is not supported, @images@ /must/ not be
== Valid Usage (Implicit)
- #VUID-VkPipelineRobustnessCreateInfoEXT-sType-sType# @sType@ /must/
be
- #VUID-VkPipelineRobustnessCreateInfoEXT-storageBuffers-parameter#
@storageBuffers@ /must/ be a valid
'PipelineRobustnessBufferBehaviorEXT' value
- #VUID-VkPipelineRobustnessCreateInfoEXT-uniformBuffers-parameter#
@uniformBuffers@ /must/ be a valid
'PipelineRobustnessBufferBehaviorEXT' value
- #VUID-VkPipelineRobustnessCreateInfoEXT-vertexInputs-parameter#
@vertexInputs@ /must/ be a valid
'PipelineRobustnessBufferBehaviorEXT' value
- #VUID-VkPipelineRobustnessCreateInfoEXT-images-parameter# @images@
/must/ be a valid 'PipelineRobustnessImageBehaviorEXT' value
= See Also
<-extensions/html/vkspec.html#VK_EXT_pipeline_robustness VK_EXT_pipeline_robustness>,
'PipelineRobustnessBufferBehaviorEXT',
'PipelineRobustnessImageBehaviorEXT',
| @storageBuffers@ sets the behaviour of out of bounds accesses made to
resources bound as:
| @uniformBuffers@ describes the behaviour of out of bounds accesses made
to resources bound as:
| @vertexInputs@ describes the behaviour of out of bounds accesses made to
vertex input attributes
| @images@ describes the behaviour of out of bounds accesses made to
resources bound as:
| VkPhysicalDevicePipelineRobustnessPropertiesEXT - Structure describing
the default robustness behavior of a physical device
= Description
types of accesses are always performed with robustness even when the
Even when an implementation reports that accesses to a given resource
type are robust by default, it remains invalid to make an out of bounds
access without requesting the appropriate robustness feature.
If the 'PhysicalDevicePipelineRobustnessPropertiesEXT' structure is
included in the @pNext@ chain of the
structure passed to
it is filled in with each corresponding implementation-dependent
property.
== Valid Usage (Implicit)
= See Also
<-extensions/html/vkspec.html#VK_EXT_pipeline_robustness VK_EXT_pipeline_robustness>,
'PipelineRobustnessBufferBehaviorEXT',
'PipelineRobustnessImageBehaviorEXT',
| @defaultRobustnessStorageBuffers@ describes the behaviour of out of
bounds accesses made to storage buffers when no robustness features are
enabled
| @defaultRobustnessUniformBuffers@ describes the behaviour of out of
bounds accesses made to uniform buffers when no robustness features are
enabled
| @defaultRobustnessVertexInputs@ describes the behaviour of out of bounds
accesses made to vertex input attributes when no robustness features are
enabled
| @defaultRobustnessImages@ describes the behaviour of out of bounds
accesses made to images when no robustness features are enabled
| VkPipelineRobustnessBufferBehaviorEXT - Enum controlling the robustness
of buffer accesses in a pipeline stage
= See Also
<-extensions/html/vkspec.html#VK_EXT_pipeline_robustness VK_EXT_pipeline_robustness>,
'PhysicalDevicePipelineRobustnessPropertiesEXT',
'PipelineRobustnessCreateInfoEXT'
| 'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT' specifies that
this pipeline stage follows the behavior of robustness features that are
enabled on the device that created this pipeline
| 'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT' specifies that buffer
accesses by this pipeline stage to the relevant resource types /must/
not be out of bounds
| 'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT' specifies
that out of bounds accesses by this pipeline stage to the relevant
resource types behave as if the
<-extensions/html/vkspec.html#features-robustBufferAccess robustBufferAccess>
feature is enabled
| 'PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT'
specifies that out of bounds accesses by this pipeline stage to the
relevant resource types behave as if the
<-extensions/html/vkspec.html#features-robustBufferAccess2 robustBufferAccess2>
feature is enabled
| VkPipelineRobustnessImageBehaviorEXT - Enum controlling the robustness
of image accesses in a pipeline stage
= See Also
<-extensions/html/vkspec.html#VK_EXT_pipeline_robustness VK_EXT_pipeline_robustness>,
'PhysicalDevicePipelineRobustnessPropertiesEXT',
'PipelineRobustnessCreateInfoEXT'
| 'PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DEVICE_DEFAULT_EXT' specifies that
this pipeline stage follows the behavior of robustness features that are
enabled on the device that created this pipeline
| 'PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DISABLED_EXT' specifies that image
accesses by this pipeline stage to the relevant resource types /must/
not be out of bounds
| 'PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_EXT' specifies
that out of bounds accesses by this pipeline stage to images behave as
if the
<-extensions/html/vkspec.html#features-robustImageAccess robustImageAccess>
feature is enabled
that out of bounds accesses by this pipeline stage to images behave as
if the
<-extensions/html/vkspec.html#features-robustImageAccess2 robustImageAccess2>
feature is enabled
# COMPLETE
PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DEVICE_DEFAULT_EXT
, PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DISABLED_EXT
, PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_EXT
, PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT ::
PipelineRobustnessImageBehaviorEXT
# | @VK_EXT_pipeline_robustness@
69
1
- Requires support for Vulkan 1.0
2022 - 07 - 12
- Interacts with @VK_EXT_image_robustness@
- Jarred Davies , Imagination Technologies
- , Imagination Technologies
- , NVIDIA
- , Broadcom Corporation
- , Qualcomm Technologies , Inc.
- , Intel
- , Intel
- , Google , Inc.
- Extending ' Vulkan . Core10.Pipeline . ' ,
' Vulkan . Core10.Pipeline . ComputePipelineCreateInfo ' ,
' Vulkan . Core10.Pipeline . PipelineShaderStageCreateInfo ' ,
' Vulkan . Extensions . VK_KHR_ray_tracing_pipeline . RayTracingPipelineCreateInfoKHR ' :
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2 ' ,
' Vulkan . Core10.Device . DeviceCreateInfo ' :
' Vulkan . ' :
- ' '
- Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' :
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT '
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_PROPERTIES_EXT '
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PIPELINE_ROBUSTNESS_CREATE_INFO_EXT '
- Revision 1 , 2022 - 07 - 12 ( Jarred Davies )
module Vulkan.Extensions.VK_EXT_pipeline_robustness ( PhysicalDevicePipelineRobustnessFeaturesEXT(..)
, PipelineRobustnessCreateInfoEXT(..)
, PhysicalDevicePipelineRobustnessPropertiesEXT(..)
, PipelineRobustnessBufferBehaviorEXT( PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT
, PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT
, PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT
, PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT
, ..
)
, PipelineRobustnessImageBehaviorEXT( PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DEVICE_DEFAULT_EXT
, PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DISABLED_EXT
, PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_EXT
, PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT
, ..
)
, EXT_PIPELINE_ROBUSTNESS_SPEC_VERSION
, pattern EXT_PIPELINE_ROBUSTNESS_SPEC_VERSION
, EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME
, pattern EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME
) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import GHC.Show (showsPrec)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero)
import Vulkan.Zero (Zero(..))
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import Data.Int (Int32)
import Foreign.Ptr (Ptr)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Data.Kind (Type)
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_PROPERTIES_EXT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PIPELINE_ROBUSTNESS_CREATE_INFO_EXT))
< -extensions/html/vkspec.html#features-pipelineRobustness pipelineRobustness >
< -extensions/html/vkspec.html#features-pipelineRobustness pipelineRobustness >
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2 '
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2 ' ,
supported . ' PhysicalDevicePipelineRobustnessFeaturesEXT ' also be
used in the @pNext@ chain of ' Vulkan . Core10.Device . DeviceCreateInfo ' to
' Vulkan . Core10.FundamentalTypes . Bool32 ' ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data PhysicalDevicePipelineRobustnessFeaturesEXT = PhysicalDevicePipelineRobustnessFeaturesEXT
robustness be requested on a per - pipeline - stage granularity .
pipelineRobustness :: Bool }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PhysicalDevicePipelineRobustnessFeaturesEXT)
#endif
deriving instance Show PhysicalDevicePipelineRobustnessFeaturesEXT
instance ToCStruct PhysicalDevicePipelineRobustnessFeaturesEXT where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PhysicalDevicePipelineRobustnessFeaturesEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (pipelineRobustness))
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
f
instance FromCStruct PhysicalDevicePipelineRobustnessFeaturesEXT where
peekCStruct p = do
pipelineRobustness <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
pure $ PhysicalDevicePipelineRobustnessFeaturesEXT
(bool32ToBool pipelineRobustness)
instance Storable PhysicalDevicePipelineRobustnessFeaturesEXT where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PhysicalDevicePipelineRobustnessFeaturesEXT where
zero = PhysicalDevicePipelineRobustnessFeaturesEXT
zero
' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_MUTABLE_EXT ' will
- ' Vulkan . Core10.Pipeline . ' ,
' Vulkan . Extensions . VK_KHR_ray_tracing_pipeline . RayTracingPipelineCreateInfoKHR ' ,
' Vulkan . Core10.Pipeline . ComputePipelineCreateInfo ' :
- ' Vulkan . Core10.Pipeline . ' :
' Vulkan . Core10.Pipeline . ' , that subset is
' Vulkan . Extensions . VK_EXT_graphics_pipeline_library .
' Vulkan . Extensions . VK_KHR_ray_tracing_pipeline . RayTracingPipelineCreateInfoKHR ' ,
' Vulkan . Extensions . VK_KHR_ray_tracing_pipeline . RayTracingPipelineCreateInfoKHR'::@pStages@.
< -extensions/html/vkspec.html#features-pipelineRobustness pipelineRobustness >
< -extensions/html/vkspec.html#features-pipelineRobustness pipelineRobustness >
< -extensions/html/vkspec.html#features-pipelineRobustness pipelineRobustness >
< -extensions/html/vkspec.html#features-pipelineRobustness pipelineRobustness >
- # VUID - VkPipelineRobustnessCreateInfoEXT - robustImageAccess-06930 # If
< -extensions/html/vkspec.html#features-robustImageAccess2 robustImageAccess2 >
' PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT '
' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PIPELINE_ROBUSTNESS_CREATE_INFO_EXT '
' Vulkan . Core10.Enums . StructureType . StructureType '
data PipelineRobustnessCreateInfoEXT = PipelineRobustnessCreateInfoEXT
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_STORAGE_BUFFER '
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER '
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC '
storageBuffers :: PipelineRobustnessBufferBehaviorEXT
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER '
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_UNIFORM_BUFFER '
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC '
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK '
uniformBuffers :: PipelineRobustnessBufferBehaviorEXT
vertexInputs :: PipelineRobustnessBufferBehaviorEXT
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_SAMPLED_IMAGE '
- ' Vulkan . Core10.Enums . DescriptorType . DESCRIPTOR_TYPE_STORAGE_IMAGE '
images :: PipelineRobustnessImageBehaviorEXT
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PipelineRobustnessCreateInfoEXT)
#endif
deriving instance Show PipelineRobustnessCreateInfoEXT
instance ToCStruct PipelineRobustnessCreateInfoEXT where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PipelineRobustnessCreateInfoEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_ROBUSTNESS_CREATE_INFO_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (storageBuffers)
poke ((p `plusPtr` 20 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (uniformBuffers)
poke ((p `plusPtr` 24 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (vertexInputs)
poke ((p `plusPtr` 28 :: Ptr PipelineRobustnessImageBehaviorEXT)) (images)
f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_ROBUSTNESS_CREATE_INFO_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (zero)
poke ((p `plusPtr` 20 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (zero)
poke ((p `plusPtr` 24 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (zero)
poke ((p `plusPtr` 28 :: Ptr PipelineRobustnessImageBehaviorEXT)) (zero)
f
instance FromCStruct PipelineRobustnessCreateInfoEXT where
peekCStruct p = do
storageBuffers <- peek @PipelineRobustnessBufferBehaviorEXT ((p `plusPtr` 16 :: Ptr PipelineRobustnessBufferBehaviorEXT))
uniformBuffers <- peek @PipelineRobustnessBufferBehaviorEXT ((p `plusPtr` 20 :: Ptr PipelineRobustnessBufferBehaviorEXT))
vertexInputs <- peek @PipelineRobustnessBufferBehaviorEXT ((p `plusPtr` 24 :: Ptr PipelineRobustnessBufferBehaviorEXT))
images <- peek @PipelineRobustnessImageBehaviorEXT ((p `plusPtr` 28 :: Ptr PipelineRobustnessImageBehaviorEXT))
pure $ PipelineRobustnessCreateInfoEXT
storageBuffers uniformBuffers vertexInputs images
instance Storable PipelineRobustnessCreateInfoEXT where
sizeOf ~_ = 32
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PipelineRobustnessCreateInfoEXT where
zero = PipelineRobustnessCreateInfoEXT
zero
zero
zero
zero
Some implementations of Vulkan may be able to guarantee that certain
Vulkan API ’s robustness features are not explicitly enabled .
' Vulkan . '
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceProperties2 ' ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data PhysicalDevicePipelineRobustnessPropertiesEXT = PhysicalDevicePipelineRobustnessPropertiesEXT
defaultRobustnessStorageBuffers :: PipelineRobustnessBufferBehaviorEXT
defaultRobustnessUniformBuffers :: PipelineRobustnessBufferBehaviorEXT
defaultRobustnessVertexInputs :: PipelineRobustnessBufferBehaviorEXT
defaultRobustnessImages :: PipelineRobustnessImageBehaviorEXT
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PhysicalDevicePipelineRobustnessPropertiesEXT)
#endif
deriving instance Show PhysicalDevicePipelineRobustnessPropertiesEXT
instance ToCStruct PhysicalDevicePipelineRobustnessPropertiesEXT where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PhysicalDevicePipelineRobustnessPropertiesEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_PROPERTIES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (defaultRobustnessStorageBuffers)
poke ((p `plusPtr` 20 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (defaultRobustnessUniformBuffers)
poke ((p `plusPtr` 24 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (defaultRobustnessVertexInputs)
poke ((p `plusPtr` 28 :: Ptr PipelineRobustnessImageBehaviorEXT)) (defaultRobustnessImages)
f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_PROPERTIES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (zero)
poke ((p `plusPtr` 20 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (zero)
poke ((p `plusPtr` 24 :: Ptr PipelineRobustnessBufferBehaviorEXT)) (zero)
poke ((p `plusPtr` 28 :: Ptr PipelineRobustnessImageBehaviorEXT)) (zero)
f
instance FromCStruct PhysicalDevicePipelineRobustnessPropertiesEXT where
peekCStruct p = do
defaultRobustnessStorageBuffers <- peek @PipelineRobustnessBufferBehaviorEXT ((p `plusPtr` 16 :: Ptr PipelineRobustnessBufferBehaviorEXT))
defaultRobustnessUniformBuffers <- peek @PipelineRobustnessBufferBehaviorEXT ((p `plusPtr` 20 :: Ptr PipelineRobustnessBufferBehaviorEXT))
defaultRobustnessVertexInputs <- peek @PipelineRobustnessBufferBehaviorEXT ((p `plusPtr` 24 :: Ptr PipelineRobustnessBufferBehaviorEXT))
defaultRobustnessImages <- peek @PipelineRobustnessImageBehaviorEXT ((p `plusPtr` 28 :: Ptr PipelineRobustnessImageBehaviorEXT))
pure $ PhysicalDevicePipelineRobustnessPropertiesEXT
defaultRobustnessStorageBuffers
defaultRobustnessUniformBuffers
defaultRobustnessVertexInputs
defaultRobustnessImages
instance Storable PhysicalDevicePipelineRobustnessPropertiesEXT where
sizeOf ~_ = 32
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PhysicalDevicePipelineRobustnessPropertiesEXT where
zero = PhysicalDevicePipelineRobustnessPropertiesEXT
zero
zero
zero
zero
newtype PipelineRobustnessBufferBehaviorEXT = PipelineRobustnessBufferBehaviorEXT Int32
deriving newtype (Eq, Ord, Storable, Zero)
pattern PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT = PipelineRobustnessBufferBehaviorEXT 0
pattern PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT = PipelineRobustnessBufferBehaviorEXT 1
pattern PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT = PipelineRobustnessBufferBehaviorEXT 2
pattern PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT = PipelineRobustnessBufferBehaviorEXT 3
# COMPLETE
PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT
, PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT
, , PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT : :
PipelineRobustnessBufferBehaviorEXT
#
PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT
, PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT
, PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT
, PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT ::
PipelineRobustnessBufferBehaviorEXT
#-}
conNamePipelineRobustnessBufferBehaviorEXT :: String
conNamePipelineRobustnessBufferBehaviorEXT = "PipelineRobustnessBufferBehaviorEXT"
enumPrefixPipelineRobustnessBufferBehaviorEXT :: String
enumPrefixPipelineRobustnessBufferBehaviorEXT = "PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_"
showTablePipelineRobustnessBufferBehaviorEXT :: [(PipelineRobustnessBufferBehaviorEXT, String)]
showTablePipelineRobustnessBufferBehaviorEXT =
[
( PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT
, "DEVICE_DEFAULT_EXT"
)
,
( PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT
, "DISABLED_EXT"
)
,
( PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT
, "ROBUST_BUFFER_ACCESS_EXT"
)
,
( PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT
, "ROBUST_BUFFER_ACCESS_2_EXT"
)
]
instance Show PipelineRobustnessBufferBehaviorEXT where
showsPrec =
enumShowsPrec
enumPrefixPipelineRobustnessBufferBehaviorEXT
showTablePipelineRobustnessBufferBehaviorEXT
conNamePipelineRobustnessBufferBehaviorEXT
(\(PipelineRobustnessBufferBehaviorEXT x) -> x)
(showsPrec 11)
instance Read PipelineRobustnessBufferBehaviorEXT where
readPrec =
enumReadPrec
enumPrefixPipelineRobustnessBufferBehaviorEXT
showTablePipelineRobustnessBufferBehaviorEXT
conNamePipelineRobustnessBufferBehaviorEXT
PipelineRobustnessBufferBehaviorEXT
newtype PipelineRobustnessImageBehaviorEXT = PipelineRobustnessImageBehaviorEXT Int32
deriving newtype (Eq, Ord, Storable, Zero)
pattern PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DEVICE_DEFAULT_EXT = PipelineRobustnessImageBehaviorEXT 0
pattern PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DISABLED_EXT = PipelineRobustnessImageBehaviorEXT 1
pattern PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_EXT = PipelineRobustnessImageBehaviorEXT 2
| ' PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT ' specifies
pattern PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT = PipelineRobustnessImageBehaviorEXT 3
conNamePipelineRobustnessImageBehaviorEXT :: String
conNamePipelineRobustnessImageBehaviorEXT = "PipelineRobustnessImageBehaviorEXT"
enumPrefixPipelineRobustnessImageBehaviorEXT :: String
enumPrefixPipelineRobustnessImageBehaviorEXT = "PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_"
showTablePipelineRobustnessImageBehaviorEXT :: [(PipelineRobustnessImageBehaviorEXT, String)]
showTablePipelineRobustnessImageBehaviorEXT =
[
( PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DEVICE_DEFAULT_EXT
, "DEVICE_DEFAULT_EXT"
)
,
( PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DISABLED_EXT
, "DISABLED_EXT"
)
,
( PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_EXT
, "ROBUST_IMAGE_ACCESS_EXT"
)
,
( PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT
, "ROBUST_IMAGE_ACCESS_2_EXT"
)
]
instance Show PipelineRobustnessImageBehaviorEXT where
showsPrec =
enumShowsPrec
enumPrefixPipelineRobustnessImageBehaviorEXT
showTablePipelineRobustnessImageBehaviorEXT
conNamePipelineRobustnessImageBehaviorEXT
(\(PipelineRobustnessImageBehaviorEXT x) -> x)
(showsPrec 11)
instance Read PipelineRobustnessImageBehaviorEXT where
readPrec =
enumReadPrec
enumPrefixPipelineRobustnessImageBehaviorEXT
showTablePipelineRobustnessImageBehaviorEXT
conNamePipelineRobustnessImageBehaviorEXT
PipelineRobustnessImageBehaviorEXT
type EXT_PIPELINE_ROBUSTNESS_SPEC_VERSION = 1
No documentation found for TopLevel " VK_EXT_PIPELINE_ROBUSTNESS_SPEC_VERSION "
pattern EXT_PIPELINE_ROBUSTNESS_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_PIPELINE_ROBUSTNESS_SPEC_VERSION = 1
type EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME = "VK_EXT_pipeline_robustness"
No documentation found for TopLevel " VK_EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME "
pattern EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME = "VK_EXT_pipeline_robustness"
|
afb552a38b7b9f467eddbb5943cad29e8f87f286d5b389dd74367ae488f43026 | exercism/ocaml | test.ml | (* binary-search-tree - 1.0.0 *)
open Base
open OUnit2
open Binary_search_tree
let result_to_string f = function
| Error m -> Printf.sprintf "Error \"%s\"" m
| Ok x -> f x |> Printf.sprintf "Some %s"
let ae exp got _test_ctxt =
assert_equal ~printer:(result_to_string Int.to_string) exp got
let intlist_to_string l =
List.map l ~f:Int.to_string
|> List.intersperse ~sep:"; "
|> List.fold ~init:"" ~f:(^)
|> fun s -> "[" ^ s ^ "]"
let ael exp got _test_ctxt =
assert_equal ~printer:intlist_to_string exp got
let tests =
let t4 = empty |> insert 4 in
let t42 = t4 |> insert 2 in
let l2 = t42 |> left in
let t44 = t4 |> insert 4 in
let l4 = t44 |> left in
let t45 = t4 |> insert 5 in
let r5 = t45 |> right in
let t4261357 = t42 |> insert 6 |> insert 1 |> insert 3 |> insert 5 |> insert 7 in
let t2 = empty |> insert 2 in
let t21 = t2 |> insert 1 in
let t22 = t2 |> insert 2 in
let t23 = t2 |> insert 3 in
let t213675 = t21 |> insert 3 |> insert 6 |> insert 7 |> insert 5 in
[
"data is retained" >:: ae (Ok 4) (value t4);
"smaller number at left node 1" >:: ae (Ok 4) (value t42);
"smaller number at left node 2" >:: ae (Ok 2) (Result.bind l2 ~f:value);
"same number at left node 1" >:: ae (Ok 4) (value t44);
"same number at left node 2" >:: ae (Ok 4) (Result.bind l4 ~f:value);
"greater number at right node 1" >:: ae (Ok 4) (value t45);
"greater number at right node 2" >:: ae (Ok 5) (Result.bind r5 ~f:value);
"can create complex tree 1" >:: ae (Ok 4) (value t4261357);
"can create complex tree 2" >:: ae (Ok 2) (Result.bind (t4261357 |> left) ~f:value);
"can create complex tree 3" >:: ae (Ok 1) (Result.bind (Result.bind (t4261357 |> left) ~f:left) ~f:value);
"can create complex tree 4" >:: ae (Ok 3) (Result.bind (Result.bind (t4261357 |> left) ~f:right) ~f:value);
"can create complex tree 5" >:: ae (Ok 6) (Result.bind (t4261357 |> right) ~f:value);
"can create complex tree 6" >:: ae (Ok 5) (Result.bind (Result.bind (t4261357 |> right) ~f:left) ~f:value);
"can create complex tree 7" >:: ae (Ok 7) (Result.bind (Result.bind (t4261357 |> right) ~f:right) ~f:value);
"can sort single number" >:: ael [2] (to_list t2);
"can sort if second number is smaller than first" >:: ael [1;2] (to_list t21);
"can sort if second number is same as first" >:: ael [2;2] (to_list t22);
"can sort if second number is greater than first" >:: ael [2;3] (to_list t23);
"can sort complex tree" >:: ael [1; 2; 3; 5; 6; 7] (to_list t213675);
]
let () =
run_test_tt_main ("binary-search-tree tests" >::: tests)
| null | https://raw.githubusercontent.com/exercism/ocaml/bfd6121f757817865a34db06c3188b5e0ccab518/exercises/practice/binary-search-tree/test.ml | ocaml | binary-search-tree - 1.0.0 | open Base
open OUnit2
open Binary_search_tree
let result_to_string f = function
| Error m -> Printf.sprintf "Error \"%s\"" m
| Ok x -> f x |> Printf.sprintf "Some %s"
let ae exp got _test_ctxt =
assert_equal ~printer:(result_to_string Int.to_string) exp got
let intlist_to_string l =
List.map l ~f:Int.to_string
|> List.intersperse ~sep:"; "
|> List.fold ~init:"" ~f:(^)
|> fun s -> "[" ^ s ^ "]"
let ael exp got _test_ctxt =
assert_equal ~printer:intlist_to_string exp got
let tests =
let t4 = empty |> insert 4 in
let t42 = t4 |> insert 2 in
let l2 = t42 |> left in
let t44 = t4 |> insert 4 in
let l4 = t44 |> left in
let t45 = t4 |> insert 5 in
let r5 = t45 |> right in
let t4261357 = t42 |> insert 6 |> insert 1 |> insert 3 |> insert 5 |> insert 7 in
let t2 = empty |> insert 2 in
let t21 = t2 |> insert 1 in
let t22 = t2 |> insert 2 in
let t23 = t2 |> insert 3 in
let t213675 = t21 |> insert 3 |> insert 6 |> insert 7 |> insert 5 in
[
"data is retained" >:: ae (Ok 4) (value t4);
"smaller number at left node 1" >:: ae (Ok 4) (value t42);
"smaller number at left node 2" >:: ae (Ok 2) (Result.bind l2 ~f:value);
"same number at left node 1" >:: ae (Ok 4) (value t44);
"same number at left node 2" >:: ae (Ok 4) (Result.bind l4 ~f:value);
"greater number at right node 1" >:: ae (Ok 4) (value t45);
"greater number at right node 2" >:: ae (Ok 5) (Result.bind r5 ~f:value);
"can create complex tree 1" >:: ae (Ok 4) (value t4261357);
"can create complex tree 2" >:: ae (Ok 2) (Result.bind (t4261357 |> left) ~f:value);
"can create complex tree 3" >:: ae (Ok 1) (Result.bind (Result.bind (t4261357 |> left) ~f:left) ~f:value);
"can create complex tree 4" >:: ae (Ok 3) (Result.bind (Result.bind (t4261357 |> left) ~f:right) ~f:value);
"can create complex tree 5" >:: ae (Ok 6) (Result.bind (t4261357 |> right) ~f:value);
"can create complex tree 6" >:: ae (Ok 5) (Result.bind (Result.bind (t4261357 |> right) ~f:left) ~f:value);
"can create complex tree 7" >:: ae (Ok 7) (Result.bind (Result.bind (t4261357 |> right) ~f:right) ~f:value);
"can sort single number" >:: ael [2] (to_list t2);
"can sort if second number is smaller than first" >:: ael [1;2] (to_list t21);
"can sort if second number is same as first" >:: ael [2;2] (to_list t22);
"can sort if second number is greater than first" >:: ael [2;3] (to_list t23);
"can sort complex tree" >:: ael [1; 2; 3; 5; 6; 7] (to_list t213675);
]
let () =
run_test_tt_main ("binary-search-tree tests" >::: tests)
|
bd5df9de48f16c63efc2bfb59c807a2c5bdef0e2d1974a2932c663dba9a9d35e | softwarelanguageslab/maf | R5RS_scp1_lightbulb-4.scm | ; Changes:
* removed : 1
* added : 1
* swaps : 0
* negated predicates : 1
; * swapped branches: 0
* calls to i d fun : 3
(letrec ((MaakLampje (lambda (aantal)
(<change>
(letrec ((state 'off)
(on! (lambda ()
(set! state 'on)))
(off! (lambda ()
(set! state 'off)))
(broken! (lambda ()
(set! state 'broken)))
(on? (lambda ()
(eq? state 'on)))
(off? (lambda ()
(eq? state 'off)))
(broken? (lambda ()
(eq? state 'broken)))
(switch! (lambda ()
(set! aantal (- aantal 1))
(if (< aantal 0)
(broken!)
(if (off?) (on!) (if (on?) (off!) #f)))
(not (broken?))))
(change! (lambda (nieuw)
(off!)
(set! aantal nieuw)
'changed))
(dispatch (lambda (msg)
(if (eq? msg 'switch!)
(switch!)
(if (eq? msg 'on?)
(on?)
(if (eq? msg 'off?)
(off?)
(if (eq? msg 'test?)
(broken?)
(if (eq? msg 'change!)
change!
(error "Message not understood.")))))))))
dispatch)
((lambda (x) x)
(letrec ((state 'off)
(on! (lambda ()
(<change>
(set! state 'on)
((lambda (x) x) (set! state 'on)))))
(off! (lambda ()
(set! state 'off)))
(broken! (lambda ()
(set! state 'broken)))
(on? (lambda ()
(eq? state 'on)))
(off? (lambda ()
(eq? state 'off)))
(broken? (lambda ()
(eq? state 'broken)))
(switch! (lambda ()
(<change>
(set! aantal (- aantal 1))
())
(if (< aantal 0)
(broken!)
(if (off?) (on!) (if (on?) (off!) #f)))
(not (broken?))))
(change! (lambda (nieuw)
(off!)
(set! aantal nieuw)
'changed))
(dispatch (lambda (msg)
(if (eq? msg 'switch!)
(switch!)
(if (eq? msg 'on?)
(on?)
(if (eq? msg 'off?)
(off?)
(if (eq? msg 'test?)
(broken?)
(if (eq? msg 'change!)
change!
(error "Message not understood.")))))))))
(<change>
dispatch
((lambda (x) x) dispatch)))))))
(philips (MaakLampje 5)))
(if (not (philips 'test?))
(if (not (philips 'on?))
(if (philips 'off?)
(if (philips 'switch!)
(if (philips 'switch!)
(if (philips 'switch!)
(if (philips 'switch!)
(if (<change> (philips 'switch!) (not (philips 'switch!)))
(if (not (philips 'switch!))
(if (philips 'test?)
(if (begin ((philips 'change!) 10) (<change> () (philips 'test?)) (not (philips 'test?)))
(philips 'off?)
#f)
#f)
#f)
#f)
#f)
#f)
#f)
#f)
#f)
#f)
#f)) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_scp1_lightbulb-4.scm | scheme | Changes:
* swapped branches: 0 | * removed : 1
* added : 1
* swaps : 0
* negated predicates : 1
* calls to i d fun : 3
(letrec ((MaakLampje (lambda (aantal)
(<change>
(letrec ((state 'off)
(on! (lambda ()
(set! state 'on)))
(off! (lambda ()
(set! state 'off)))
(broken! (lambda ()
(set! state 'broken)))
(on? (lambda ()
(eq? state 'on)))
(off? (lambda ()
(eq? state 'off)))
(broken? (lambda ()
(eq? state 'broken)))
(switch! (lambda ()
(set! aantal (- aantal 1))
(if (< aantal 0)
(broken!)
(if (off?) (on!) (if (on?) (off!) #f)))
(not (broken?))))
(change! (lambda (nieuw)
(off!)
(set! aantal nieuw)
'changed))
(dispatch (lambda (msg)
(if (eq? msg 'switch!)
(switch!)
(if (eq? msg 'on?)
(on?)
(if (eq? msg 'off?)
(off?)
(if (eq? msg 'test?)
(broken?)
(if (eq? msg 'change!)
change!
(error "Message not understood.")))))))))
dispatch)
((lambda (x) x)
(letrec ((state 'off)
(on! (lambda ()
(<change>
(set! state 'on)
((lambda (x) x) (set! state 'on)))))
(off! (lambda ()
(set! state 'off)))
(broken! (lambda ()
(set! state 'broken)))
(on? (lambda ()
(eq? state 'on)))
(off? (lambda ()
(eq? state 'off)))
(broken? (lambda ()
(eq? state 'broken)))
(switch! (lambda ()
(<change>
(set! aantal (- aantal 1))
())
(if (< aantal 0)
(broken!)
(if (off?) (on!) (if (on?) (off!) #f)))
(not (broken?))))
(change! (lambda (nieuw)
(off!)
(set! aantal nieuw)
'changed))
(dispatch (lambda (msg)
(if (eq? msg 'switch!)
(switch!)
(if (eq? msg 'on?)
(on?)
(if (eq? msg 'off?)
(off?)
(if (eq? msg 'test?)
(broken?)
(if (eq? msg 'change!)
change!
(error "Message not understood.")))))))))
(<change>
dispatch
((lambda (x) x) dispatch)))))))
(philips (MaakLampje 5)))
(if (not (philips 'test?))
(if (not (philips 'on?))
(if (philips 'off?)
(if (philips 'switch!)
(if (philips 'switch!)
(if (philips 'switch!)
(if (philips 'switch!)
(if (<change> (philips 'switch!) (not (philips 'switch!)))
(if (not (philips 'switch!))
(if (philips 'test?)
(if (begin ((philips 'change!) 10) (<change> () (philips 'test?)) (not (philips 'test?)))
(philips 'off?)
#f)
#f)
#f)
#f)
#f)
#f)
#f)
#f)
#f)
#f)
#f)) |
f20731cc451f5fe3aa11c6f6e98319423d967bbfc85a39303dfdb3a8ead9306c | cojna/iota | SCC.hs | # LANGUAGE LambdaCase #
module Data.Graph.Sparse.SCC where
import Control.Monad
import Control.Monad.ST
import Data.Function
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import Data.Buffer
import Data.Graph.Sparse
import My.Prelude (rep)
type ComponentId = Int
stronglyConnectedComponents :: SparseGraph w -> U.Vector ComponentId
stronglyConnectedComponents gr = runST $ do
let numV = numVerticesCSR gr
low <- UM.replicate numV nothing
preord <- UM.replicate numV nothing
stack <- newBufferAsStack numV
component <- UM.replicate numV nothing
vars <- UM.replicate 2 0
rep numV $ \root -> do
rootOrd <- UM.unsafeRead preord root
when (rootOrd == nothing) $ do
flip fix root $ \dfs v -> do
preordId <- UM.unsafeRead vars _preordId
UM.unsafeWrite vars _preordId (preordId + 1)
UM.unsafeWrite preord v preordId
UM.unsafeWrite low v preordId
pushBack v stack
U.forM_ (adj gr v) $ \u -> do
ordU <- UM.unsafeRead preord u
if ordU == nothing
then do
dfs u
lowU <- UM.unsafeRead low u
UM.unsafeModify low (min lowU) v
else UM.unsafeModify low (min ordU) v
lowV <- UM.unsafeRead low v
ordV <- UM.unsafeRead preord v
when (lowV == ordV) $ do
compId <- UM.unsafeRead vars _compId
fix $ \loop -> do
popBack stack >>= \case
Just x -> do
UM.unsafeWrite preord x numV
UM.unsafeWrite component x compId
when (x /= v) loop
Nothing -> undefined
UM.unsafeWrite vars _compId (compId + 1)
maxCompId <- subtract 1 <$!> UM.unsafeRead vars _compId
U.map (maxCompId -) <$> U.unsafeFreeze component
where
nothing = -1
_preordId = 0
_compId = 1
| null | https://raw.githubusercontent.com/cojna/iota/9acaa765ad685d466d889229d97b5a1c852a00dd/src/Data/Graph/Sparse/SCC.hs | haskell | # LANGUAGE LambdaCase #
module Data.Graph.Sparse.SCC where
import Control.Monad
import Control.Monad.ST
import Data.Function
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import Data.Buffer
import Data.Graph.Sparse
import My.Prelude (rep)
type ComponentId = Int
stronglyConnectedComponents :: SparseGraph w -> U.Vector ComponentId
stronglyConnectedComponents gr = runST $ do
let numV = numVerticesCSR gr
low <- UM.replicate numV nothing
preord <- UM.replicate numV nothing
stack <- newBufferAsStack numV
component <- UM.replicate numV nothing
vars <- UM.replicate 2 0
rep numV $ \root -> do
rootOrd <- UM.unsafeRead preord root
when (rootOrd == nothing) $ do
flip fix root $ \dfs v -> do
preordId <- UM.unsafeRead vars _preordId
UM.unsafeWrite vars _preordId (preordId + 1)
UM.unsafeWrite preord v preordId
UM.unsafeWrite low v preordId
pushBack v stack
U.forM_ (adj gr v) $ \u -> do
ordU <- UM.unsafeRead preord u
if ordU == nothing
then do
dfs u
lowU <- UM.unsafeRead low u
UM.unsafeModify low (min lowU) v
else UM.unsafeModify low (min ordU) v
lowV <- UM.unsafeRead low v
ordV <- UM.unsafeRead preord v
when (lowV == ordV) $ do
compId <- UM.unsafeRead vars _compId
fix $ \loop -> do
popBack stack >>= \case
Just x -> do
UM.unsafeWrite preord x numV
UM.unsafeWrite component x compId
when (x /= v) loop
Nothing -> undefined
UM.unsafeWrite vars _compId (compId + 1)
maxCompId <- subtract 1 <$!> UM.unsafeRead vars _compId
U.map (maxCompId -) <$> U.unsafeFreeze component
where
nothing = -1
_preordId = 0
_compId = 1
| |
55340f91d55006f2a409b09f0f4d20eb33d2a41a0e235070cc3330f9e26837d1 | tarides/current-albatross-deployer | main.ml | open Lwt.Syntax
let socket_path =
"/var/run/current-iptables-daemon/current-iptables-daemon.sock"
let db_path = "/var/lib/current-iptables-daemon/db"
module Config = struct
type t = { network : Ipaddr.V4.Prefix.t }
end
module Types = Iptables_daemon_api.Types
module Ipmap = struct
module Map = Map.Make (Ipaddr.V4)
module Set = Set.Make (Ipaddr.V4)
type 'a t = { content : 'a Map.t }
let mem ip { content; _ } = Map.mem ip content
let obtain ~blacklist ~prefix t name =
(* assumption: name don't exist *)
let blacklist = Set.of_list blacklist in
let start = Ipaddr.V4.Prefix.first prefix in
let stop = Ipaddr.V4.Prefix.last prefix in
let rec test ip =
match Map.mem ip t.content || Set.mem ip blacklist with
| false -> Some ({ content = Map.add ip name t.content }, ip)
| true when ip <> stop -> test (Ipaddr.V4.succ ip |> Result.get_ok)
| true -> None
in
test start
let remove t name =
let content, removed_ip =
Map.fold
(fun ip name' (new_map, removed_ip) ->
if name' <> name then (Map.add ip name' new_map, removed_ip)
else (new_map, Some ip))
t.content (Map.empty, None)
in
({ content }, removed_ip)
let bindings t =
Map.bindings t.content |> List.map (fun (ip, tag) -> { Types.Ip.ip; tag })
let make () = { content = Map.empty }
end
module State = struct
type t = {
mutable ips : string Ipmap.t;
mutable deployments :
(Iptables.Nat.Rule.handle list * Types.DeploymentInfo.t) list;
mutable iptables : Iptables.Nat.t;
}
let empty () =
{
ips = Ipmap.make ();
deployments = [];
iptables = Iptables.Nat.init ~name:"CURRENT-DEPLOYER" [];
}
let list_ips t = Ipmap.bindings t.ips
let remove_ip t name =
let ips, removed_element = Ipmap.remove t.ips name in
t.ips <- ips;
match removed_element with
| None -> Error `Not_found
| Some ip -> Ok { Types.Ip.ip; tag = name }
let obtain_ip ~blacklist ~prefix t name =
let existing_ip =
Ipmap.bindings t.ips
|> List.find_map (fun (ip : Types.Ip.t) ->
if ip.tag = name then Some ip else None)
in
let obtain () =
match Ipmap.obtain ~blacklist ~prefix t.ips name with
| None -> Error `Full
| Some (ips, new_ip) ->
t.ips <- ips;
Ok { Types.Ip.ip = new_ip; tag = name }
in
match existing_ip with
| Some ip when not (List.exists (fun ip' -> ip.ip = ip') blacklist) -> Ok ip
| Some _ ->
let _ = remove_ip t name |> Result.get_ok in
obtain ()
| None -> obtain ()
let list_deployments t = t.deployments |> List.map snd
let remove_deployment t name =
let remaining_deployments, removed_deployment =
List.fold_left
(fun (remaining_deployments, removed_deployment) ((_, info) as entry) ->
if info.Types.DeploymentInfo.name = name then
(remaining_deployments, Some entry)
else (entry :: remaining_deployments, removed_deployment))
([], None) t.deployments
in
t.deployments <- remaining_deployments;
match removed_deployment with
| Some (removed_rules, removed_deployment) ->
List.iter (Iptables.Nat.remove_rule t.iptables) removed_rules;
Ok removed_deployment
| None -> Error `Not_found
let nat_redirection ~to_ip ~source ~target =
let module Nat = Iptables.Nat in
let match_tcp =
Nat.Match.(
protocol (`Tcp (Tcp.v ~dport:(Nat.Negatable.V [ Port source ]) ())))
in
let match_udp =
Nat.Match.(
protocol (`Udp (Udp.v ~dport:(Nat.Negatable.V [ Port source ]) ())))
in
let action = Nat.Action.destination_nat ~port:(Nat.Port target) to_ip in
[ Nat.Rule.v [ match_tcp ] action; Nat.Rule.v [ match_udp ] action ]
let add_new_deployment t (deployment : Types.DeploymentInfo.t) =
let existing_deployment =
List.exists
(fun (_, d) -> d.Types.DeploymentInfo.name = deployment.name)
t.deployments
in
if existing_deployment then remove_deployment t deployment.name |> ignore;
let module PortSet = Set.Make (Int) in
let ports =
List.map
(fun ((_, deployment) : _ * Types.DeploymentInfo.t) ->
List.map
(function { Types.PortRedirection.source; _ } -> source)
deployment.ports)
t.deployments
|> List.concat |> PortSet.of_list
in
let exception Port_conflict of int in
try
let new_rules =
List.map
(fun { Types.PortRedirection.source; target } ->
if PortSet.mem source ports then raise (Port_conflict source);
nat_redirection ~to_ip:deployment.ip.ip ~source ~target)
deployment.ports
|> List.concat
in
let handles = Iptables.Nat.add_rules t.iptables new_rules in
t.deployments <- (handles, deployment) :: t.deployments;
Ok ()
with Port_conflict v -> Error (`Port_already_allocated v)
module Db = struct
type state = t
type t = { ips : string Ipmap.t; deployments : Types.DeploymentInfo.t list }
let of_file () : t Lwt.t =
Lwt_io.with_file ~mode:Input db_path (fun channel ->
Lwt_io.read_value channel)
let mutex = Lwt_mutex.create ()
let to_file t =
let _ =
Bos.OS.Dir.create ~mode:0o700
(Fpath.of_string db_path |> Result.get_ok |> Fpath.parent)
in
Lwt_mutex.with_lock mutex @@ fun () ->
Lwt_io.with_file ~mode:Output db_path (fun channel ->
Lwt_io.write_value channel t)
let of_state (t : state) =
{ ips = t.ips; deployments = t.deployments |> List.map snd }
let to_state (t : t) =
let state = empty () in
state.ips <- t.ips;
List.iter
(fun x -> add_new_deployment state x |> Result.get_ok)
t.deployments;
state
end
let v () =
Lwt.catch
(fun () ->
let+ v = Db.of_file () in
Db.to_state v)
(function
| Unix.Unix_error (Unix.ENOENT, _, _) -> Lwt.return (empty ())
| exn -> Lwt.fail exn)
end
let safe_close fd =
Lwt.catch (fun () -> Lwt_unix.close fd) (fun _ -> Lwt.return_unit)
module Wire = struct
let respond ~socket data =
let open Lwt.Infix in
let write_raw buf =
let rec w off l =
Lwt.catch
(fun () ->
Lwt_unix.send socket buf off l [] >>= fun n ->
if n = l then Lwt.return (Ok ()) else w (off + n) (l - n))
(fun e ->
Logs.err (fun m ->
m "exception %s while writing" (Printexc.to_string e));
safe_close socket >|= fun () -> Error `Exception)
in
w 0 (Bytes.length buf)
in
let dlen = Cstruct.create 4 in
Cstruct.BE.set_uint32 dlen 0 (Int32.of_int (Cstruct.length data));
let bytes = Cstruct.(to_bytes (append dlen data)) in
write_raw bytes
let read s =
let open Lwt.Infix in
let buf = Bytes.create 4 in
let rec r b i l =
Lwt.catch
(fun () ->
Lwt_unix.read s b i l >>= function
| 0 ->
Logs.debug (fun m -> m "end of file while reading");
Lwt.return (Error `Eof)
| n when n == l -> Lwt.return (Ok ())
| n when n < l -> r b (i + n) (l - n)
| _ ->
Logs.err (fun m -> m "read too much, shouldn't happen)");
Lwt.return (Error `Toomuch))
(fun e ->
let err = Printexc.to_string e in
Logs.err (fun m -> m "exception %s while reading" err);
safe_close s >|= fun () -> Error `Exception)
in
r buf 0 4 >>= function
| Error e -> Lwt.return (Error e)
| Ok () ->
let len = Cstruct.BE.get_uint32 (Cstruct.of_bytes buf) 0 in
if len > 0l then
let b = Bytes.create (Int32.to_int len) in
r b 0 (Int32.to_int len) >|= function
| Error e -> Error e
| Ok () -> Ok (Cstruct.of_bytes b)
else Lwt.return (Error `Eof)
let create_socket =
let open Lwt.Infix in
(Lwt_unix.file_exists socket_path >>= function
| true -> Lwt_unix.unlink socket_path
| false ->
Bos.OS.Dir.create
(Fpath.of_string socket_path |> Result.get_ok |> Fpath.parent)
|> Result.get_ok |> ignore;
Lwt.return_unit)
>>= fun () ->
let s = Lwt_unix.(socket PF_UNIX SOCK_STREAM 0) in
Lwt_unix.set_close_on_exec s;
let old_umask = Unix.umask 0 in
Lwt_unix.(bind s (ADDR_UNIX socket_path)) >|= fun () ->
Logs.app (fun m -> m "listening on %s" socket_path);
let _ = Unix.umask old_umask in
Lwt_unix.listen s 1;
s
end
module Handler = struct
module Rpc = Iptables_daemon_api.Rpc
type t = {
tag : Rpc.Tag.t;
handle :
Rpc.untagged_buffer ->
(Rpc.untagged_buffer, Iptables_daemon_api.Rpc.error) result;
}
let implement rpc f =
let inj, proj = Rpc.get_server rpc in
{
tag = Rpc.Tag.v rpc;
handle =
(fun request ->
let ( let* ) = Result.bind in
let* request = inj request in
let response = f request in
Ok (proj response));
}
let handle handlers tagged_query =
let tag, query = Rpc.Tag.strip tagged_query in
let handler = Rpc.Tag.Map.find tag handlers in
handler.handle query |> Result.map (Rpc.Tag.add tag)
end
let handle ~handlers socket =
let open Lwt.Syntax in
Logs.app (fun f -> f "New client!");
let rec loop () =
let* v = Wire.read socket in
match v with
| Ok command ->
Logs.info (fun f -> f "Request !");
let* _ =
match Handler.handle handlers command with
| Ok response -> Wire.respond ~socket response
| Error _ ->
Logs.app (fun f -> f "Error while executing command");
Lwt.return_error (`Msg "TODO")
| exception _ ->
Logs.app (fun f -> f "Got exception while executing command. ");
Lwt.return_error (`Msg "TODO")
in
loop ()
| Error _ ->
Logs.err (fun m -> m "error while reading");
Lwt.return_unit
in
let+ () = loop () in
Logs.app (fun f -> f "Client left.")
let handlers ~state =
let module Spec = Iptables_daemon_api.Spec in
Handler.
[
(* IPs *)
implement Spec.IpManager.list (fun () -> State.list_ips state);
implement Spec.IpManager.request (fun (tag, prefix, blacklist) ->
State.obtain_ip ~blacklist ~prefix state tag);
implement Spec.IpManager.free (fun tag -> State.remove_ip state tag);
(* Port publishing *)
implement Spec.Deployments.list (fun () -> State.list_deployments state);
implement Spec.Deployments.create (fun dpl ->
State.add_new_deployment state dpl);
implement Spec.Deployments.delete (fun service ->
State.remove_deployment state service);
]
|> List.to_seq
|> Seq.map (fun ({ Handler.tag; _ } as v) -> (tag, v))
|> Handler.Rpc.Tag.Map.of_seq
let job =
let* state = State.v () in
let handlers = handlers ~state in
let open Lwt.Syntax in
let* socket = Wire.create_socket in
let rec loop () =
let* client_socket, _ = Lwt_unix.accept socket in
Lwt.async (fun () ->
let* () = handle ~handlers client_socket in
State.Db.of_state state |> State.Db.to_file);
loop ()
in
loop ()
let () =
Logs.set_reporter (Logs_fmt.reporter ());
Lwt_main.run job
| null | https://raw.githubusercontent.com/tarides/current-albatross-deployer/f4e7b88edf2c2d71a571178466d34048dad57bf7/lib/iptables-daemon/main.ml | ocaml | assumption: name don't exist
IPs
Port publishing | open Lwt.Syntax
let socket_path =
"/var/run/current-iptables-daemon/current-iptables-daemon.sock"
let db_path = "/var/lib/current-iptables-daemon/db"
module Config = struct
type t = { network : Ipaddr.V4.Prefix.t }
end
module Types = Iptables_daemon_api.Types
module Ipmap = struct
module Map = Map.Make (Ipaddr.V4)
module Set = Set.Make (Ipaddr.V4)
type 'a t = { content : 'a Map.t }
let mem ip { content; _ } = Map.mem ip content
let obtain ~blacklist ~prefix t name =
let blacklist = Set.of_list blacklist in
let start = Ipaddr.V4.Prefix.first prefix in
let stop = Ipaddr.V4.Prefix.last prefix in
let rec test ip =
match Map.mem ip t.content || Set.mem ip blacklist with
| false -> Some ({ content = Map.add ip name t.content }, ip)
| true when ip <> stop -> test (Ipaddr.V4.succ ip |> Result.get_ok)
| true -> None
in
test start
let remove t name =
let content, removed_ip =
Map.fold
(fun ip name' (new_map, removed_ip) ->
if name' <> name then (Map.add ip name' new_map, removed_ip)
else (new_map, Some ip))
t.content (Map.empty, None)
in
({ content }, removed_ip)
let bindings t =
Map.bindings t.content |> List.map (fun (ip, tag) -> { Types.Ip.ip; tag })
let make () = { content = Map.empty }
end
module State = struct
type t = {
mutable ips : string Ipmap.t;
mutable deployments :
(Iptables.Nat.Rule.handle list * Types.DeploymentInfo.t) list;
mutable iptables : Iptables.Nat.t;
}
let empty () =
{
ips = Ipmap.make ();
deployments = [];
iptables = Iptables.Nat.init ~name:"CURRENT-DEPLOYER" [];
}
let list_ips t = Ipmap.bindings t.ips
let remove_ip t name =
let ips, removed_element = Ipmap.remove t.ips name in
t.ips <- ips;
match removed_element with
| None -> Error `Not_found
| Some ip -> Ok { Types.Ip.ip; tag = name }
let obtain_ip ~blacklist ~prefix t name =
let existing_ip =
Ipmap.bindings t.ips
|> List.find_map (fun (ip : Types.Ip.t) ->
if ip.tag = name then Some ip else None)
in
let obtain () =
match Ipmap.obtain ~blacklist ~prefix t.ips name with
| None -> Error `Full
| Some (ips, new_ip) ->
t.ips <- ips;
Ok { Types.Ip.ip = new_ip; tag = name }
in
match existing_ip with
| Some ip when not (List.exists (fun ip' -> ip.ip = ip') blacklist) -> Ok ip
| Some _ ->
let _ = remove_ip t name |> Result.get_ok in
obtain ()
| None -> obtain ()
let list_deployments t = t.deployments |> List.map snd
let remove_deployment t name =
let remaining_deployments, removed_deployment =
List.fold_left
(fun (remaining_deployments, removed_deployment) ((_, info) as entry) ->
if info.Types.DeploymentInfo.name = name then
(remaining_deployments, Some entry)
else (entry :: remaining_deployments, removed_deployment))
([], None) t.deployments
in
t.deployments <- remaining_deployments;
match removed_deployment with
| Some (removed_rules, removed_deployment) ->
List.iter (Iptables.Nat.remove_rule t.iptables) removed_rules;
Ok removed_deployment
| None -> Error `Not_found
let nat_redirection ~to_ip ~source ~target =
let module Nat = Iptables.Nat in
let match_tcp =
Nat.Match.(
protocol (`Tcp (Tcp.v ~dport:(Nat.Negatable.V [ Port source ]) ())))
in
let match_udp =
Nat.Match.(
protocol (`Udp (Udp.v ~dport:(Nat.Negatable.V [ Port source ]) ())))
in
let action = Nat.Action.destination_nat ~port:(Nat.Port target) to_ip in
[ Nat.Rule.v [ match_tcp ] action; Nat.Rule.v [ match_udp ] action ]
let add_new_deployment t (deployment : Types.DeploymentInfo.t) =
let existing_deployment =
List.exists
(fun (_, d) -> d.Types.DeploymentInfo.name = deployment.name)
t.deployments
in
if existing_deployment then remove_deployment t deployment.name |> ignore;
let module PortSet = Set.Make (Int) in
let ports =
List.map
(fun ((_, deployment) : _ * Types.DeploymentInfo.t) ->
List.map
(function { Types.PortRedirection.source; _ } -> source)
deployment.ports)
t.deployments
|> List.concat |> PortSet.of_list
in
let exception Port_conflict of int in
try
let new_rules =
List.map
(fun { Types.PortRedirection.source; target } ->
if PortSet.mem source ports then raise (Port_conflict source);
nat_redirection ~to_ip:deployment.ip.ip ~source ~target)
deployment.ports
|> List.concat
in
let handles = Iptables.Nat.add_rules t.iptables new_rules in
t.deployments <- (handles, deployment) :: t.deployments;
Ok ()
with Port_conflict v -> Error (`Port_already_allocated v)
module Db = struct
type state = t
type t = { ips : string Ipmap.t; deployments : Types.DeploymentInfo.t list }
let of_file () : t Lwt.t =
Lwt_io.with_file ~mode:Input db_path (fun channel ->
Lwt_io.read_value channel)
let mutex = Lwt_mutex.create ()
let to_file t =
let _ =
Bos.OS.Dir.create ~mode:0o700
(Fpath.of_string db_path |> Result.get_ok |> Fpath.parent)
in
Lwt_mutex.with_lock mutex @@ fun () ->
Lwt_io.with_file ~mode:Output db_path (fun channel ->
Lwt_io.write_value channel t)
let of_state (t : state) =
{ ips = t.ips; deployments = t.deployments |> List.map snd }
let to_state (t : t) =
let state = empty () in
state.ips <- t.ips;
List.iter
(fun x -> add_new_deployment state x |> Result.get_ok)
t.deployments;
state
end
let v () =
Lwt.catch
(fun () ->
let+ v = Db.of_file () in
Db.to_state v)
(function
| Unix.Unix_error (Unix.ENOENT, _, _) -> Lwt.return (empty ())
| exn -> Lwt.fail exn)
end
let safe_close fd =
Lwt.catch (fun () -> Lwt_unix.close fd) (fun _ -> Lwt.return_unit)
module Wire = struct
let respond ~socket data =
let open Lwt.Infix in
let write_raw buf =
let rec w off l =
Lwt.catch
(fun () ->
Lwt_unix.send socket buf off l [] >>= fun n ->
if n = l then Lwt.return (Ok ()) else w (off + n) (l - n))
(fun e ->
Logs.err (fun m ->
m "exception %s while writing" (Printexc.to_string e));
safe_close socket >|= fun () -> Error `Exception)
in
w 0 (Bytes.length buf)
in
let dlen = Cstruct.create 4 in
Cstruct.BE.set_uint32 dlen 0 (Int32.of_int (Cstruct.length data));
let bytes = Cstruct.(to_bytes (append dlen data)) in
write_raw bytes
let read s =
let open Lwt.Infix in
let buf = Bytes.create 4 in
let rec r b i l =
Lwt.catch
(fun () ->
Lwt_unix.read s b i l >>= function
| 0 ->
Logs.debug (fun m -> m "end of file while reading");
Lwt.return (Error `Eof)
| n when n == l -> Lwt.return (Ok ())
| n when n < l -> r b (i + n) (l - n)
| _ ->
Logs.err (fun m -> m "read too much, shouldn't happen)");
Lwt.return (Error `Toomuch))
(fun e ->
let err = Printexc.to_string e in
Logs.err (fun m -> m "exception %s while reading" err);
safe_close s >|= fun () -> Error `Exception)
in
r buf 0 4 >>= function
| Error e -> Lwt.return (Error e)
| Ok () ->
let len = Cstruct.BE.get_uint32 (Cstruct.of_bytes buf) 0 in
if len > 0l then
let b = Bytes.create (Int32.to_int len) in
r b 0 (Int32.to_int len) >|= function
| Error e -> Error e
| Ok () -> Ok (Cstruct.of_bytes b)
else Lwt.return (Error `Eof)
let create_socket =
let open Lwt.Infix in
(Lwt_unix.file_exists socket_path >>= function
| true -> Lwt_unix.unlink socket_path
| false ->
Bos.OS.Dir.create
(Fpath.of_string socket_path |> Result.get_ok |> Fpath.parent)
|> Result.get_ok |> ignore;
Lwt.return_unit)
>>= fun () ->
let s = Lwt_unix.(socket PF_UNIX SOCK_STREAM 0) in
Lwt_unix.set_close_on_exec s;
let old_umask = Unix.umask 0 in
Lwt_unix.(bind s (ADDR_UNIX socket_path)) >|= fun () ->
Logs.app (fun m -> m "listening on %s" socket_path);
let _ = Unix.umask old_umask in
Lwt_unix.listen s 1;
s
end
module Handler = struct
module Rpc = Iptables_daemon_api.Rpc
type t = {
tag : Rpc.Tag.t;
handle :
Rpc.untagged_buffer ->
(Rpc.untagged_buffer, Iptables_daemon_api.Rpc.error) result;
}
let implement rpc f =
let inj, proj = Rpc.get_server rpc in
{
tag = Rpc.Tag.v rpc;
handle =
(fun request ->
let ( let* ) = Result.bind in
let* request = inj request in
let response = f request in
Ok (proj response));
}
let handle handlers tagged_query =
let tag, query = Rpc.Tag.strip tagged_query in
let handler = Rpc.Tag.Map.find tag handlers in
handler.handle query |> Result.map (Rpc.Tag.add tag)
end
let handle ~handlers socket =
let open Lwt.Syntax in
Logs.app (fun f -> f "New client!");
let rec loop () =
let* v = Wire.read socket in
match v with
| Ok command ->
Logs.info (fun f -> f "Request !");
let* _ =
match Handler.handle handlers command with
| Ok response -> Wire.respond ~socket response
| Error _ ->
Logs.app (fun f -> f "Error while executing command");
Lwt.return_error (`Msg "TODO")
| exception _ ->
Logs.app (fun f -> f "Got exception while executing command. ");
Lwt.return_error (`Msg "TODO")
in
loop ()
| Error _ ->
Logs.err (fun m -> m "error while reading");
Lwt.return_unit
in
let+ () = loop () in
Logs.app (fun f -> f "Client left.")
let handlers ~state =
let module Spec = Iptables_daemon_api.Spec in
Handler.
[
implement Spec.IpManager.list (fun () -> State.list_ips state);
implement Spec.IpManager.request (fun (tag, prefix, blacklist) ->
State.obtain_ip ~blacklist ~prefix state tag);
implement Spec.IpManager.free (fun tag -> State.remove_ip state tag);
implement Spec.Deployments.list (fun () -> State.list_deployments state);
implement Spec.Deployments.create (fun dpl ->
State.add_new_deployment state dpl);
implement Spec.Deployments.delete (fun service ->
State.remove_deployment state service);
]
|> List.to_seq
|> Seq.map (fun ({ Handler.tag; _ } as v) -> (tag, v))
|> Handler.Rpc.Tag.Map.of_seq
let job =
let* state = State.v () in
let handlers = handlers ~state in
let open Lwt.Syntax in
let* socket = Wire.create_socket in
let rec loop () =
let* client_socket, _ = Lwt_unix.accept socket in
Lwt.async (fun () ->
let* () = handle ~handlers client_socket in
State.Db.of_state state |> State.Db.to_file);
loop ()
in
loop ()
let () =
Logs.set_reporter (Logs_fmt.reporter ());
Lwt_main.run job
|
19e0ddbecf86b5c912393e30a833d1be4d7dea40b4021546c75116cda5d93913 | Frama-C/Frama-C-snapshot | region_analysis.mli | (**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 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 ) .
(* *)
(**************************************************************************)
An algorithm for region analysis , similar to the one in the
dragon book ( " Compilers : Principles , Techniques , and Tools ( 2nd
Edition ) " , by Aho , Lam , and ) .
The main difference compared to dataflow analysis is the handling
of loops : the " mu " construction for handling loops allows to
perform different computations , especially they can perform actions
when first entering the loop or after the fixpoint has been
reached .
: The algorithm does not handle non - natural loops for now .
dragon book ("Compilers: Principles, Techniques, and Tools (2nd
Edition)", by Aho, Lam, Sethi and Ullman).
The main difference compared to dataflow analysis is the handling
of loops: the "mu" construction for handling loops allows to
perform different computations, especially they can perform actions
when first entering the loop or after the fixpoint has been
reached.
TODO: The algorithm does not handle non-natural loops for now. *)
include module type of Region_analysis_sig;;
module Make(N:Node):sig
(* Function computing from an entry abstract value the "after"
state, which is a map from each outgoing edge to its respective
value. *)
val after: N.abstract_value -> N.abstract_value N.Edge_Dict.t
end
| null | https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/loop_analysis/region_analysis.mli | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
Function computing from an entry abstract value the "after"
state, which is a map from each outgoing edge to its respective
value. | This file is part of Frama - C.
Copyright ( C ) 2007 - 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 ) .
An algorithm for region analysis , similar to the one in the
dragon book ( " Compilers : Principles , Techniques , and Tools ( 2nd
Edition ) " , by Aho , Lam , and ) .
The main difference compared to dataflow analysis is the handling
of loops : the " mu " construction for handling loops allows to
perform different computations , especially they can perform actions
when first entering the loop or after the fixpoint has been
reached .
: The algorithm does not handle non - natural loops for now .
dragon book ("Compilers: Principles, Techniques, and Tools (2nd
Edition)", by Aho, Lam, Sethi and Ullman).
The main difference compared to dataflow analysis is the handling
of loops: the "mu" construction for handling loops allows to
perform different computations, especially they can perform actions
when first entering the loop or after the fixpoint has been
reached.
TODO: The algorithm does not handle non-natural loops for now. *)
include module type of Region_analysis_sig;;
module Make(N:Node):sig
val after: N.abstract_value -> N.abstract_value N.Edge_Dict.t
end
|
b3053ffb74878903a60de853d695385d3b4b000c41e273faa7a542d3d7dc4205 | Kakadu/fp2022 | parser.ml | * Copyright 2022 - 2023 , and contributors
* SPDX - License - Identifier : LGPL-3.0 - or - later
open Angstrom
open Parsetree
(* -------------------- Basic syntax -------------------- *)
(** A subset of OCaml keywords, that are used in our mini language *)
let keywords = [ "else"; "false"; "fun"; "if"; "in"; "let"; "mod"; "rec"; "then"; "true" ]
let is_keyword s = List.mem s keywords
let is_ignored = function
| '\x20' | '\x09' | '\x0d' | '\x0a' | '\x0c' -> true
| _ -> false
;;
let ignored = skip_while is_ignored
let required_ws = take_while1 is_ignored
(* Plain combinators for convenient spaces removal *)
let ( *~> ) a b = a *> ignored *> b
let ( <~* ) a b = a <* ignored <* b
let lift2' f a b = lift2 f (a <* ignored) b
let lift3' f a b c = lift3 f (a <* ignored) (b <* ignored) c
(* Combinator used for parsing binary operations *)
let chainl1 e op =
let rec go acc = lift2' (fun f x -> f acc x) op e >>= go <|> return acc in
e >>= fun init -> go init
;;
(* Plain combinators for parentheses parsing *)
let between a b p = a *> p <* b
let pstring s = between ignored ignored (string s)
let parens p = between (pstring "(") (pstring ")") p
let brackets p = between (pstring "[") (pstring "]") p
(* Primitive syntax recognition *)
let is_identifier_char = function
| 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '\'' | '_' -> true
| _ -> false
;;
let is_number_char = function
| '0' .. '9' -> true
| _ -> false
;;
let number_chars = take_while1 is_number_char
let keyword s =
ignored *> string s *> peek_char_fail
>>= fun c -> if is_identifier_char c then fail "Error parsing keyword" else return s
;;
(* ----------------- Variable names ------------------ *)
let identifier =
let is_valid_first_char = function
| 'a' .. 'z' | 'A' .. 'Z' | '_' -> true
| _ -> false
in
peek_char
>>= function
| Some c when is_valid_first_char c ->
take_while is_identifier_char
>>= fun s -> if is_keyword s then fail "Invalid variable name" else return s
| _ -> fail "Invalid variable name"
;;
(* -------------------- Constant -------------------- *)
let boolean =
string "true" *> return (Bool true) <|> string "false" *> return (Bool false)
;;
let integer =
option "" (string "+" <|> string "-")
>>= fun sign ->
number_chars >>= fun whole -> return (Int (int_of_string (sign ^ whole)))
;;
let unit = parens ignored *> return Unit
(* ------------------- Operators -------------------- *)
let plus = ignored *> string "+" *> return (fun x y -> Binop (Plus, x, y))
let minus = ignored *> string "-" *> return (fun x y -> Binop (Minus, x, y))
let mult = ignored *> string "*" *> return (fun x y -> Binop (Mult, x, y))
let divide = ignored *> string "/" *> return (fun x y -> Binop (Divide, x, y))
let mod_ = ignored *> string "mod" *> return (fun x y -> Binop (Mod, x, y))
let eq = ignored *> string "=" *> return (fun x y -> Binop (Eq, x, y))
let neq = ignored *> string "<>" *> return (fun x y -> Binop (Neq, x, y))
let lt = ignored *> string "<" *> return (fun x y -> Binop (Lt, x, y))
let ltq = ignored *> string "<=" *> return (fun x y -> Binop (Ltq, x, y))
let gt = ignored *> string ">" *> return (fun x y -> Binop (Gt, x, y))
let gtq = ignored *> string ">=" *> return (fun x y -> Binop (Gtq, x, y))
let and_ = ignored *> string "&&" *> return (fun x y -> Binop (Gt, x, y))
let or_ = ignored *> string "||" *> return (fun x y -> Binop (Gtq, x, y))
(* ----------------- Function arguments ---------------- *)
(* Helper type for representing the function arguments *)
type fun_argument =
{ label : arg_label
; name : id
; default_value : expr option
}
let label_parser =
let label =
string "~"
<|> string "?"
>>= fun parsed_arg_type ->
identifier
<* option ":" (string ":")
>>= fun name ->
match parsed_arg_type with
| "~" -> return (ArgLabeled name)
| "?" -> return (ArgOptional name)
| _ -> fail "Error parsing the label of the argument"
in
option ArgNoLabel label
;;
(* -------------------- Expressions -------------------- *)
(* Helper functions for desugaring syntactic sugar *)
For transforming " Fun x y - > e " into Fun ( x , Fun ( y , e ) )
let rec desugar_lambda exp = function
| [] -> exp
| a :: args -> Fun (a.label, a.default_value, a.name, desugar_lambda exp args)
;;
let desugar_let exp in_exp names include_rec =
let desugar_to_tuple exp in_exp = function
| [] -> fail "Error desugaring let"
| [ a ] -> return (a, exp, in_exp)
| a :: args -> return (a, desugar_lambda exp args, in_exp)
in
desugar_to_tuple exp in_exp names
>>= fun res ->
let a, new_exp, new_in_exp = res in
if include_rec
then return (LetRec (a.name, new_exp, new_in_exp))
else return (Let (a.name, new_exp, new_in_exp))
;;
let desugar_def args exp include_rec =
let inner =
match args with
| [] -> fail "Error desugaring let"
| [ a ] -> return (a, exp)
| _a :: _args -> return (_a, desugar_lambda exp _args)
in
inner
>>= fun res ->
let a, exp = res in
if include_rec
then return (a.name, LetRec (a.name, exp, Var a.name))
else return (a.name, exp)
;;
(* Helper type for representing application arguments, that might be labeled *)
type app_argument =
{ label : arg_label
; expr : expr
}
let rec desugar_app exp = function
| [] -> exp
| a :: args -> App (desugar_app exp args, a.label, a.expr)
;;
(* Dispatch table for mutually recursive parsers *)
type type_dispatch =
{ expr : type_dispatch -> expr t
; definition : type_dispatch -> definition t
}
(* Main parsers *)
let type_d =
let var_parser =
let var_expr x = Var x in
lift var_expr identifier <?> "var_parser"
in
let const_parser =
let const_expr x = Const x in
lift const_expr (choice [ boolean; integer; unit ]) <?> "const_parser"
in
let fun_argument_parser d =
ignored *> label_parser
>>= fun label ->
(* If there is no label then parse the argument name *)
If there is a label then parse the argument name or just the label :
let f ~name1 : name1 ~name2 : = name1 +
let f ~name1 ~name2 = name1 +
are equivalent
let f ~name1:name1 ~name2:name2 = name1 + name2
let f ~name1 ~name2 = name1 + name2
are equivalent *)
If there is an optional label then parse the argument label ,
name and the ( optional ) default value in parentheses :
let f ? arg:(arg = expr1 ) - > expr2
where expr1 is the default value or just
let f ? arg - > expr2
name and the (optional) default value in parentheses:
let f ?arg:(arg = expr1) -> expr2
where expr1 is the default value or just
let f ?arg -> expr2 *)
match label with
| ArgNoLabel ->
identifier
<|> parens identifier
<|> parens (string "" <|> required_ws)
>>= fun name -> return { label; name; default_value = None }
| ArgLabeled id ->
option id identifier
<|> parens identifier
>>= fun name -> return { label; name; default_value = None }
| ArgOptional _ ->
required_ws
>>= (fun _ -> return { label; name = ""; default_value = None })
<|> parens
(identifier
>>= fun name ->
ignored *> string "=" *~> d.expr d
>>= fun e -> return { label; name; default_value = Some e })
<?> "fun_argument_parser"
in
let fun_parser d =
fix
@@ fun self ->
choice
[ parens self
; (keyword "fun" *~> many_till (fun_argument_parser d) (pstring "->")
>>= fun fun_args -> d.expr d >>= fun e -> return (desugar_lambda e fun_args))
]
<?> "fun_parser"
in
let app_parser d =
let app_argument_parser =
ignored *> label_parser
>>= fun label ->
var_parser
<|> d.expr d
>>= fun expr ->
match label with
| ArgNoLabel | ArgLabeled _ -> return { label; expr }
| ArgOptional _ -> fail "You can not make a funcall with optional argument syntax"
in
fix
@@ fun self ->
choice
[ parens self
; (ignored *> var_parser
<* required_ws
>>= fun n ->
many1 app_argument_parser >>= fun args -> return (desugar_app n (List.rev args)))
]
<?> "app_parser"
in
let if_then_else_parser d =
let if_expr cond tbody fbody = IfThenElse (cond, tbody, fbody) in
fix
@@ fun self ->
choice
[ parens self
; (let cond = keyword "if" *~> d.expr d in
let tbody = keyword "then" *~> d.expr d in
let fbody = option (Const Unit) (keyword "else" *~> d.expr d) in
lift3' if_expr cond tbody fbody)
]
<?> "if_then_else_parser"
in
let list_parser d =
let rec fold_expr_list = function
| [] -> Const Nil
| h :: tl -> Cons (h, fold_expr_list tl)
in
fix
@@ fun self ->
choice
[ parens self
; (fun exprs -> fold_expr_list exprs) <$> brackets (sep_by (pstring ";") (d.expr d))
]
<?> "list_parser"
in
(* 'and' is not supported *)
let let_parser d =
fix
@@ fun self ->
choice
[ parens self
; (keyword "let" *~> option "" (keyword "rec")
>>= fun _rec ->
ignored *> many1 (fun_argument_parser d)
>>= fun var_list ->
ignored *> string "=" *~> d.expr d
>>= fun exp ->
ignored *> keyword "in" *~> d.expr d
>>= fun in_exp ->
match _rec with
| "" -> desugar_let exp in_exp var_list false
| "rec" -> desugar_let exp in_exp var_list true
| _ -> fail "Error in parsing let")
]
<?> "let_parser"
in
let def_parser d =
fix
@@ fun self ->
choice
[ parens self
; (keyword "let" *~> option "" (keyword "rec")
>>= fun _rec ->
ignored *> many1 (fun_argument_parser d)
>>= fun var_list ->
ignored *> string "=" *~> d.expr d
>>= fun exp ->
match _rec with
| "" -> desugar_def var_list exp false
| "rec" -> desugar_def var_list exp true
| _ -> fail "Error in parsing letdef")
]
<?> "def_parser"
in
let binop_parser d =
fix
@@ fun binop_expr ->
let factor d =
parens binop_expr <|> app_parser d <|> let_parser d <|> const_parser <|> var_parser
in
let term_mult = chainl1 (factor d) (mult <|> divide <|> mod_) in
let term_add = chainl1 term_mult (plus <|> minus) in
let term_bool = chainl1 term_add (and_ <|> or_) in
chainl1 term_bool (eq <|> neq <|> ltq <|> lt <|> gtq <|> gt) <?> "binop_parser"
in
let expr d =
app_parser d
<|> binop_parser d
<|> let_parser d
<|> fun_parser d
<|> list_parser d
<|> if_then_else_parser d
<|> const_parser
<|> var_parser
in
let definition d = def_parser d in
{ expr; definition }
;;
let expr_parser = type_d.expr type_d
let definition_parser = type_d.definition type_d
(* ------------------ Top-level parsing ------------------ *)
(** Should be called with specific parser *)
let parse p s = parse_string ~consume:All p s
TODO : filename parser
let toplevel_command_parser () =
string "#help" *> return (Command Help)
<|> string "#quit" *> return (Command Quit)
<|> (string "#use" *> identifier >>= fun filename -> return (Command (Use filename)))
;;
let toplevel_expr_parser () =
ignored *> expr_parser >>= fun expr -> return (Expression expr)
;;
let toplevel_defininition_parser () =
ignored *> definition_parser >>= fun definition -> return (Definition definition)
;;
let toplevel_parser () =
ignored
*> many1
(choice
[ return () >>= toplevel_command_parser
; return () >>= toplevel_expr_parser
; return () >>= toplevel_defininition_parser
]
<* option "" (pstring ";;"))
<|> return []
;;
(** Should only be called on top-level ast type *)
let parse_toplevel s =
match parse_string ~consume:All (toplevel_parser ()) s with
| Result.Ok x -> Ok x
| Error e ->
Format.printf "%s" e;
Error e
;;
| null | https://raw.githubusercontent.com/Kakadu/fp2022/5365f2f52e3e173cdb052abcfdbfb66fc70fe799/OCamlLabeledArgs/lib/parser.ml | ocaml | -------------------- Basic syntax --------------------
* A subset of OCaml keywords, that are used in our mini language
Plain combinators for convenient spaces removal
Combinator used for parsing binary operations
Plain combinators for parentheses parsing
Primitive syntax recognition
----------------- Variable names ------------------
-------------------- Constant --------------------
------------------- Operators --------------------
----------------- Function arguments ----------------
Helper type for representing the function arguments
-------------------- Expressions --------------------
Helper functions for desugaring syntactic sugar
Helper type for representing application arguments, that might be labeled
Dispatch table for mutually recursive parsers
Main parsers
If there is no label then parse the argument name
'and' is not supported
------------------ Top-level parsing ------------------
* Should be called with specific parser
* Should only be called on top-level ast type | * Copyright 2022 - 2023 , and contributors
* SPDX - License - Identifier : LGPL-3.0 - or - later
open Angstrom
open Parsetree
let keywords = [ "else"; "false"; "fun"; "if"; "in"; "let"; "mod"; "rec"; "then"; "true" ]
let is_keyword s = List.mem s keywords
let is_ignored = function
| '\x20' | '\x09' | '\x0d' | '\x0a' | '\x0c' -> true
| _ -> false
;;
let ignored = skip_while is_ignored
let required_ws = take_while1 is_ignored
let ( *~> ) a b = a *> ignored *> b
let ( <~* ) a b = a <* ignored <* b
let lift2' f a b = lift2 f (a <* ignored) b
let lift3' f a b c = lift3 f (a <* ignored) (b <* ignored) c
let chainl1 e op =
let rec go acc = lift2' (fun f x -> f acc x) op e >>= go <|> return acc in
e >>= fun init -> go init
;;
let between a b p = a *> p <* b
let pstring s = between ignored ignored (string s)
let parens p = between (pstring "(") (pstring ")") p
let brackets p = between (pstring "[") (pstring "]") p
let is_identifier_char = function
| 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '\'' | '_' -> true
| _ -> false
;;
let is_number_char = function
| '0' .. '9' -> true
| _ -> false
;;
let number_chars = take_while1 is_number_char
let keyword s =
ignored *> string s *> peek_char_fail
>>= fun c -> if is_identifier_char c then fail "Error parsing keyword" else return s
;;
let identifier =
let is_valid_first_char = function
| 'a' .. 'z' | 'A' .. 'Z' | '_' -> true
| _ -> false
in
peek_char
>>= function
| Some c when is_valid_first_char c ->
take_while is_identifier_char
>>= fun s -> if is_keyword s then fail "Invalid variable name" else return s
| _ -> fail "Invalid variable name"
;;
let boolean =
string "true" *> return (Bool true) <|> string "false" *> return (Bool false)
;;
let integer =
option "" (string "+" <|> string "-")
>>= fun sign ->
number_chars >>= fun whole -> return (Int (int_of_string (sign ^ whole)))
;;
let unit = parens ignored *> return Unit
let plus = ignored *> string "+" *> return (fun x y -> Binop (Plus, x, y))
let minus = ignored *> string "-" *> return (fun x y -> Binop (Minus, x, y))
let mult = ignored *> string "*" *> return (fun x y -> Binop (Mult, x, y))
let divide = ignored *> string "/" *> return (fun x y -> Binop (Divide, x, y))
let mod_ = ignored *> string "mod" *> return (fun x y -> Binop (Mod, x, y))
let eq = ignored *> string "=" *> return (fun x y -> Binop (Eq, x, y))
let neq = ignored *> string "<>" *> return (fun x y -> Binop (Neq, x, y))
let lt = ignored *> string "<" *> return (fun x y -> Binop (Lt, x, y))
let ltq = ignored *> string "<=" *> return (fun x y -> Binop (Ltq, x, y))
let gt = ignored *> string ">" *> return (fun x y -> Binop (Gt, x, y))
let gtq = ignored *> string ">=" *> return (fun x y -> Binop (Gtq, x, y))
let and_ = ignored *> string "&&" *> return (fun x y -> Binop (Gt, x, y))
let or_ = ignored *> string "||" *> return (fun x y -> Binop (Gtq, x, y))
type fun_argument =
{ label : arg_label
; name : id
; default_value : expr option
}
let label_parser =
let label =
string "~"
<|> string "?"
>>= fun parsed_arg_type ->
identifier
<* option ":" (string ":")
>>= fun name ->
match parsed_arg_type with
| "~" -> return (ArgLabeled name)
| "?" -> return (ArgOptional name)
| _ -> fail "Error parsing the label of the argument"
in
option ArgNoLabel label
;;
For transforming " Fun x y - > e " into Fun ( x , Fun ( y , e ) )
let rec desugar_lambda exp = function
| [] -> exp
| a :: args -> Fun (a.label, a.default_value, a.name, desugar_lambda exp args)
;;
let desugar_let exp in_exp names include_rec =
let desugar_to_tuple exp in_exp = function
| [] -> fail "Error desugaring let"
| [ a ] -> return (a, exp, in_exp)
| a :: args -> return (a, desugar_lambda exp args, in_exp)
in
desugar_to_tuple exp in_exp names
>>= fun res ->
let a, new_exp, new_in_exp = res in
if include_rec
then return (LetRec (a.name, new_exp, new_in_exp))
else return (Let (a.name, new_exp, new_in_exp))
;;
let desugar_def args exp include_rec =
let inner =
match args with
| [] -> fail "Error desugaring let"
| [ a ] -> return (a, exp)
| _a :: _args -> return (_a, desugar_lambda exp _args)
in
inner
>>= fun res ->
let a, exp = res in
if include_rec
then return (a.name, LetRec (a.name, exp, Var a.name))
else return (a.name, exp)
;;
type app_argument =
{ label : arg_label
; expr : expr
}
let rec desugar_app exp = function
| [] -> exp
| a :: args -> App (desugar_app exp args, a.label, a.expr)
;;
type type_dispatch =
{ expr : type_dispatch -> expr t
; definition : type_dispatch -> definition t
}
let type_d =
let var_parser =
let var_expr x = Var x in
lift var_expr identifier <?> "var_parser"
in
let const_parser =
let const_expr x = Const x in
lift const_expr (choice [ boolean; integer; unit ]) <?> "const_parser"
in
let fun_argument_parser d =
ignored *> label_parser
>>= fun label ->
If there is a label then parse the argument name or just the label :
let f ~name1 : name1 ~name2 : = name1 +
let f ~name1 ~name2 = name1 +
are equivalent
let f ~name1:name1 ~name2:name2 = name1 + name2
let f ~name1 ~name2 = name1 + name2
are equivalent *)
If there is an optional label then parse the argument label ,
name and the ( optional ) default value in parentheses :
let f ? arg:(arg = expr1 ) - > expr2
where expr1 is the default value or just
let f ? arg - > expr2
name and the (optional) default value in parentheses:
let f ?arg:(arg = expr1) -> expr2
where expr1 is the default value or just
let f ?arg -> expr2 *)
match label with
| ArgNoLabel ->
identifier
<|> parens identifier
<|> parens (string "" <|> required_ws)
>>= fun name -> return { label; name; default_value = None }
| ArgLabeled id ->
option id identifier
<|> parens identifier
>>= fun name -> return { label; name; default_value = None }
| ArgOptional _ ->
required_ws
>>= (fun _ -> return { label; name = ""; default_value = None })
<|> parens
(identifier
>>= fun name ->
ignored *> string "=" *~> d.expr d
>>= fun e -> return { label; name; default_value = Some e })
<?> "fun_argument_parser"
in
let fun_parser d =
fix
@@ fun self ->
choice
[ parens self
; (keyword "fun" *~> many_till (fun_argument_parser d) (pstring "->")
>>= fun fun_args -> d.expr d >>= fun e -> return (desugar_lambda e fun_args))
]
<?> "fun_parser"
in
let app_parser d =
let app_argument_parser =
ignored *> label_parser
>>= fun label ->
var_parser
<|> d.expr d
>>= fun expr ->
match label with
| ArgNoLabel | ArgLabeled _ -> return { label; expr }
| ArgOptional _ -> fail "You can not make a funcall with optional argument syntax"
in
fix
@@ fun self ->
choice
[ parens self
; (ignored *> var_parser
<* required_ws
>>= fun n ->
many1 app_argument_parser >>= fun args -> return (desugar_app n (List.rev args)))
]
<?> "app_parser"
in
let if_then_else_parser d =
let if_expr cond tbody fbody = IfThenElse (cond, tbody, fbody) in
fix
@@ fun self ->
choice
[ parens self
; (let cond = keyword "if" *~> d.expr d in
let tbody = keyword "then" *~> d.expr d in
let fbody = option (Const Unit) (keyword "else" *~> d.expr d) in
lift3' if_expr cond tbody fbody)
]
<?> "if_then_else_parser"
in
let list_parser d =
let rec fold_expr_list = function
| [] -> Const Nil
| h :: tl -> Cons (h, fold_expr_list tl)
in
fix
@@ fun self ->
choice
[ parens self
; (fun exprs -> fold_expr_list exprs) <$> brackets (sep_by (pstring ";") (d.expr d))
]
<?> "list_parser"
in
let let_parser d =
fix
@@ fun self ->
choice
[ parens self
; (keyword "let" *~> option "" (keyword "rec")
>>= fun _rec ->
ignored *> many1 (fun_argument_parser d)
>>= fun var_list ->
ignored *> string "=" *~> d.expr d
>>= fun exp ->
ignored *> keyword "in" *~> d.expr d
>>= fun in_exp ->
match _rec with
| "" -> desugar_let exp in_exp var_list false
| "rec" -> desugar_let exp in_exp var_list true
| _ -> fail "Error in parsing let")
]
<?> "let_parser"
in
let def_parser d =
fix
@@ fun self ->
choice
[ parens self
; (keyword "let" *~> option "" (keyword "rec")
>>= fun _rec ->
ignored *> many1 (fun_argument_parser d)
>>= fun var_list ->
ignored *> string "=" *~> d.expr d
>>= fun exp ->
match _rec with
| "" -> desugar_def var_list exp false
| "rec" -> desugar_def var_list exp true
| _ -> fail "Error in parsing letdef")
]
<?> "def_parser"
in
let binop_parser d =
fix
@@ fun binop_expr ->
let factor d =
parens binop_expr <|> app_parser d <|> let_parser d <|> const_parser <|> var_parser
in
let term_mult = chainl1 (factor d) (mult <|> divide <|> mod_) in
let term_add = chainl1 term_mult (plus <|> minus) in
let term_bool = chainl1 term_add (and_ <|> or_) in
chainl1 term_bool (eq <|> neq <|> ltq <|> lt <|> gtq <|> gt) <?> "binop_parser"
in
let expr d =
app_parser d
<|> binop_parser d
<|> let_parser d
<|> fun_parser d
<|> list_parser d
<|> if_then_else_parser d
<|> const_parser
<|> var_parser
in
let definition d = def_parser d in
{ expr; definition }
;;
let expr_parser = type_d.expr type_d
let definition_parser = type_d.definition type_d
let parse p s = parse_string ~consume:All p s
TODO : filename parser
let toplevel_command_parser () =
string "#help" *> return (Command Help)
<|> string "#quit" *> return (Command Quit)
<|> (string "#use" *> identifier >>= fun filename -> return (Command (Use filename)))
;;
let toplevel_expr_parser () =
ignored *> expr_parser >>= fun expr -> return (Expression expr)
;;
let toplevel_defininition_parser () =
ignored *> definition_parser >>= fun definition -> return (Definition definition)
;;
let toplevel_parser () =
ignored
*> many1
(choice
[ return () >>= toplevel_command_parser
; return () >>= toplevel_expr_parser
; return () >>= toplevel_defininition_parser
]
<* option "" (pstring ";;"))
<|> return []
;;
let parse_toplevel s =
match parse_string ~consume:All (toplevel_parser ()) s with
| Result.Ok x -> Ok x
| Error e ->
Format.printf "%s" e;
Error e
;;
|
5aa0e6b503522acd5c4ca5456fd914eab989a9d80e84065fd470406e45cae823 | dmvianna/haskellbook | Ch24-ipv6.hs |
module IPv6 where
import Data.List (elemIndex)
import Data.Maybe
import Data.Word
import Numeric
import Test.Hspec
import Text.Trifecta
import IPv4 hiding (main)
data IPAddress6 =
IPAddress6 Word64 Word64
deriving (Eq, Ord)
instance Show IPAddress6 where
show = show <$> ip6ToInteger
ip6ToInteger :: IPAddress6 -> Integer
ip6ToInteger (IPAddress6 q r) =
(toInteger q)
* (toInteger (maxBound :: Word))
+ (toInteger r)
hex :: [Char]
hex = ['0'..'9'] ++ ['A'..'F'] ++ ['a'..'f']
parseBlock :: Parser [Char]
parseBlock = many $ oneOf hex
parseBlocks :: Parser [String]
parseBlocks = sepBy1 parseBlock (char ':')
fillAbbrev :: [String] -> [String]
fillAbbrev xs = -- I'm sure this can be shortened
if "" `elem` xs
then
if length xs > 8
then catMaybes $ (\a -> if a == "" then Nothing else Just a) <$> xs
else let i = fromJust $ elemIndex "" xs
t = splitAt i xs
in fillAbbrev (fst t ++ ["0"] ++ snd t)
else xs
parseIPv6 :: Parser IPAddress6
parseIPv6 = do
xs <- parseBlocks
let xs' = concat $ spewPart
<$> initState 16
<$> fst
<$> (catMaybes $ listToMaybe
<$> readHex
<$> fillAbbrev xs)
x = bitToIntegral (0, xs')
ip = quotRem x (fromIntegral (maxBound :: Word))
return $ IPAddress6 (fromIntegral $ fst ip) (fromIntegral $ snd ip)
main :: IO ()
main = hspec $ do
describe "Test some IP values" $ do
let ip1 = "FE80::0202:B3FF:FE1E:8329"
ip2 = "0:0:0:0:0:ffff:cc78:f"
it ("can parse " ++ ip1) $ do
Nonexhaustive , I know
let (Success x) = parseString parseIPv6 mempty ip1
r = ip6ToInteger x
r `shouldBe` 338288524927261089654163772891438416681
it ("can parse " ++ ip2) $ do
let (Success x) = parseString parseIPv6 mempty ip2
r = ip6ToInteger x
r `shouldBe` 281474112159759
| null | https://raw.githubusercontent.com/dmvianna/haskellbook/b1fdce66283ccf3e740db0bb1ad9730a7669d1fc/src/Ch24-ipv6.hs | haskell | I'm sure this can be shortened |
module IPv6 where
import Data.List (elemIndex)
import Data.Maybe
import Data.Word
import Numeric
import Test.Hspec
import Text.Trifecta
import IPv4 hiding (main)
data IPAddress6 =
IPAddress6 Word64 Word64
deriving (Eq, Ord)
instance Show IPAddress6 where
show = show <$> ip6ToInteger
ip6ToInteger :: IPAddress6 -> Integer
ip6ToInteger (IPAddress6 q r) =
(toInteger q)
* (toInteger (maxBound :: Word))
+ (toInteger r)
hex :: [Char]
hex = ['0'..'9'] ++ ['A'..'F'] ++ ['a'..'f']
parseBlock :: Parser [Char]
parseBlock = many $ oneOf hex
parseBlocks :: Parser [String]
parseBlocks = sepBy1 parseBlock (char ':')
fillAbbrev :: [String] -> [String]
if "" `elem` xs
then
if length xs > 8
then catMaybes $ (\a -> if a == "" then Nothing else Just a) <$> xs
else let i = fromJust $ elemIndex "" xs
t = splitAt i xs
in fillAbbrev (fst t ++ ["0"] ++ snd t)
else xs
parseIPv6 :: Parser IPAddress6
parseIPv6 = do
xs <- parseBlocks
let xs' = concat $ spewPart
<$> initState 16
<$> fst
<$> (catMaybes $ listToMaybe
<$> readHex
<$> fillAbbrev xs)
x = bitToIntegral (0, xs')
ip = quotRem x (fromIntegral (maxBound :: Word))
return $ IPAddress6 (fromIntegral $ fst ip) (fromIntegral $ snd ip)
main :: IO ()
main = hspec $ do
describe "Test some IP values" $ do
let ip1 = "FE80::0202:B3FF:FE1E:8329"
ip2 = "0:0:0:0:0:ffff:cc78:f"
it ("can parse " ++ ip1) $ do
Nonexhaustive , I know
let (Success x) = parseString parseIPv6 mempty ip1
r = ip6ToInteger x
r `shouldBe` 338288524927261089654163772891438416681
it ("can parse " ++ ip2) $ do
let (Success x) = parseString parseIPv6 mempty ip2
r = ip6ToInteger x
r `shouldBe` 281474112159759
|
6396210e6de19b48771ae44b3697277ea684ea34f83d1b1b8ec22c7b43798a5d | dlesl/erqwest | erqwest_async.erl | -module(erqwest_async).
-export([ req/4
, send/2
, finish_send/1
, read/2
, cancel/1
]).
-export_type([handle/0]).
-opaque handle() :: erlang:nif_resource().
%% @doc Make an asynchronous request.
%%
A Response will be sent to ` Pid ' as follows :
%%
%% * If `body' is `stream', and the request was successfully initated,
` { erqwest_response , Ref , next } ' . See { @link send/2 } and { @link finish_send/1 }
for how to respond . Alternatively ` { erqwest_response , Ref , error ,
%% erqwest:err()}'.
%%
* If ` body ' is omitted or is of type ` iodata ( ) ' , ` { erqwest_response , Ref ,
reply , erqwest : resp ( ) } ' or ` { erqwest_response , Ref , error , erqwest : err ( ) } ' .
%%
%% * If `response_body' is `stream', `erqwest:resp()' will contain a handle
%% which should be passed to {@link read/2}. Alternatively, call {@link
%% cancel/1} if you do not intend to consume the body.
%%
%% An `error' response is _always_ the final response. If streaming is not used,
%% a single reply is guaranteed.
%%
%% Fails with reason badarg if any argument is invalid or if the client has
%% already been closed.
-spec req(erqwest:client() | atom(), pid(), any(), erqwest:req_opts()) -> handle().
req(Client, Pid, Ref, Req) ->
erqwest_nif:req(erqwest:get_client(Client), Pid, Ref, Req).
%% @doc Asynchronously stream a chunk of the request body. Replies with
` { erqwest_response , Ref , next } ' when the connection is ready to receive more
data . Replies with ` { erqwest_response , Ref , error , erqwest : err ( ) } ' if
something goes wrong , or ` { erqwest_response , Ref , reply , erqwest : resp ( ) } ' if
%% the server has already decided to reply. Call {@link finish_send/1} when the
%% request body is complete.
-spec send(handle(), iodata()) -> ok.
send(Handle, Data) ->
erqwest_nif:send(Handle, Data).
%% @doc Complete sending the request body. The message flow continues as
described for { @link } , ie . the next message will be ` reply ' or ` error ' .
-spec finish_send(handle()) -> ok.
finish_send(Handle) ->
erqwest_nif:finish_send(Handle).
%% @doc Read a chunk of the response body, waiting for at most `period' ms or
%% until at least `length' bytes have been read. Note that more than `length'
bytes can be returned . ` length ' defaults to 8 MB if omitted , and ` period ' to
%% `infinity'. Note that more than `length' bytes can be returned. Replies with
` { erqwest_response , Ref , chunk , Data } ' , ` { erqwest_response , Ref , fin , Data } '
or ` { erqwest_response , Ref , error , erqwest : err ( ) } ` . A ` fin ' or ` error '
%% response will be the final message.
-spec read(handle(), erqwest:read_opts()) -> ok.
read(Handle, Opts) ->
erqwest_nif:read(Handle, Opts).
%% @doc Cancel an asynchronous request at any stage. A reply will always still
%% be sent, either `{error, #{code := cancelled}}', another `error' or a `reply'
%% depending on the state of the connection. Has no effect if the request has
%% already completed or was already cancelled.
-spec cancel(handle()) -> ok.
cancel(Handle) ->
erqwest_nif:cancel(Handle).
| null | https://raw.githubusercontent.com/dlesl/erqwest/58b5166c039f8276e5cab629421d0b4609e6caba/src/erqwest_async.erl | erlang | @doc Make an asynchronous request.
* If `body' is `stream', and the request was successfully initated,
erqwest:err()}'.
* If `response_body' is `stream', `erqwest:resp()' will contain a handle
which should be passed to {@link read/2}. Alternatively, call {@link
cancel/1} if you do not intend to consume the body.
An `error' response is _always_ the final response. If streaming is not used,
a single reply is guaranteed.
Fails with reason badarg if any argument is invalid or if the client has
already been closed.
@doc Asynchronously stream a chunk of the request body. Replies with
the server has already decided to reply. Call {@link finish_send/1} when the
request body is complete.
@doc Complete sending the request body. The message flow continues as
@doc Read a chunk of the response body, waiting for at most `period' ms or
until at least `length' bytes have been read. Note that more than `length'
`infinity'. Note that more than `length' bytes can be returned. Replies with
response will be the final message.
@doc Cancel an asynchronous request at any stage. A reply will always still
be sent, either `{error, #{code := cancelled}}', another `error' or a `reply'
depending on the state of the connection. Has no effect if the request has
already completed or was already cancelled. | -module(erqwest_async).
-export([ req/4
, send/2
, finish_send/1
, read/2
, cancel/1
]).
-export_type([handle/0]).
-opaque handle() :: erlang:nif_resource().
A Response will be sent to ` Pid ' as follows :
` { erqwest_response , Ref , next } ' . See { @link send/2 } and { @link finish_send/1 }
for how to respond . Alternatively ` { erqwest_response , Ref , error ,
* If ` body ' is omitted or is of type ` iodata ( ) ' , ` { erqwest_response , Ref ,
reply , erqwest : resp ( ) } ' or ` { erqwest_response , Ref , error , erqwest : err ( ) } ' .
-spec req(erqwest:client() | atom(), pid(), any(), erqwest:req_opts()) -> handle().
req(Client, Pid, Ref, Req) ->
erqwest_nif:req(erqwest:get_client(Client), Pid, Ref, Req).
` { erqwest_response , Ref , next } ' when the connection is ready to receive more
data . Replies with ` { erqwest_response , Ref , error , erqwest : err ( ) } ' if
something goes wrong , or ` { erqwest_response , Ref , reply , erqwest : resp ( ) } ' if
-spec send(handle(), iodata()) -> ok.
send(Handle, Data) ->
erqwest_nif:send(Handle, Data).
described for { @link } , ie . the next message will be ` reply ' or ` error ' .
-spec finish_send(handle()) -> ok.
finish_send(Handle) ->
erqwest_nif:finish_send(Handle).
bytes can be returned . ` length ' defaults to 8 MB if omitted , and ` period ' to
` { erqwest_response , Ref , chunk , Data } ' , ` { erqwest_response , Ref , fin , Data } '
or ` { erqwest_response , Ref , error , erqwest : err ( ) } ` . A ` fin ' or ` error '
-spec read(handle(), erqwest:read_opts()) -> ok.
read(Handle, Opts) ->
erqwest_nif:read(Handle, Opts).
-spec cancel(handle()) -> ok.
cancel(Handle) ->
erqwest_nif:cancel(Handle).
|
0ecca9c26acb712798f26768059b23c5658ba1e046d75049ea0645b5dd08fa62 | charlieg/Sparser | denominations-of-money.lisp | ;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*-
copyright ( c ) 1993 - 1996 -- all rights reserved
;;;
;;; File: "denominations of money"
;;; Module: "grammar;model:dossiers:"
version : 0.1 January 1996
initiated 10/22/93 v2.3 from treatment of 11/91 .
0.1 ( 1/16/96 ) redid " cents " and " pence "
(in-package :sparser)
(define-individual 'denomination/money :name "$")
(define-individual 'denomination/money :name "dollar")
(define-fractional-denomination-of-money "cent"
:reference-denomination "dollar"
:fraction .01 )
(define-individual 'denomination/money :name "pound")
(define-fractional-denomination-of-money "pence"
:reference-denomination "pound"
:fraction .01 )
| null | https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/grammar/model/dossiers/denominations-of-money.lisp | lisp | -*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*-
File: "denominations of money"
Module: "grammar;model:dossiers:" | copyright ( c ) 1993 - 1996 -- all rights reserved
version : 0.1 January 1996
initiated 10/22/93 v2.3 from treatment of 11/91 .
0.1 ( 1/16/96 ) redid " cents " and " pence "
(in-package :sparser)
(define-individual 'denomination/money :name "$")
(define-individual 'denomination/money :name "dollar")
(define-fractional-denomination-of-money "cent"
:reference-denomination "dollar"
:fraction .01 )
(define-individual 'denomination/money :name "pound")
(define-fractional-denomination-of-money "pence"
:reference-denomination "pound"
:fraction .01 )
|
4eccb22fb10801d25653a97cd96e6ce9dbc698a2b16df3198455e2c21c9ef784 | ghcjs/ghcjs | MonadTrans.hs | -- This file is understood to be in the public domain.
module MonadTrans where
{-
- This provides a way of accessing a monad that is inside
- another monad.
-}
class MonadTrans t where
lift :: Monad m => m a -> t m a
liftTrans : : ( MonadTrans t ) = > ( a - > t m b ) - > ( t m a - > t m b )
liftTrans f m = do { a < - m ; f a }
| null | https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/nofib/spectral/cryptarithm2/MonadTrans.hs | haskell | This file is understood to be in the public domain.
- This provides a way of accessing a monad that is inside
- another monad.
|
module MonadTrans where
class MonadTrans t where
lift :: Monad m => m a -> t m a
liftTrans : : ( MonadTrans t ) = > ( a - > t m b ) - > ( t m a - > t m b )
liftTrans f m = do { a < - m ; f a }
|
911ec0182f09b6802e385fcbe37ad8f0444fefcf4e071c04e97d2c6f5830fcbc | davidarkemp/swiftp | server.erl | -module(swiftp_proxy.server).
-export([start/0, start/1, ping/0, listener/4]).
-import(swiftp_proxy.log, [log/3]).
-import(swiftp_proxy.db, [create_master_schema/0, join_db/1]).
-define(DEVICE_PORT, 2222).
-define(CLIENT_PORT, 2221).
Called when we are the first node of a cluster ( create a new db schema )
start() ->
case create_master_schema() of
ok ->
log(info, "Master schema created~n", []),
start_listeners();
_X ->
log(error, "Master schema create failed, stopping.~n", [])
end,
init:stop().
% Called when we are to join an existing cluster. The argument comes from
% the command line (e.g. erl -s server start 'name@host' -detached)
start([ConnectTo]) ->
case join_db(ConnectTo) of
ok ->
log(info, "Connected to mnesia cluster ok", []),
start_listeners();
X ->
log(error, "Mnesia join failed: ~p~n", [X])
end,
init:stop().
start_listeners() ->
log(info, "Running!~n", []),
process_flag(trap_exit, true),
LogPid = spawn_link_logger(),
register(random_thread, spawn_link(rand, start, [])),
_Registry = spawn_link(session_registry, start, []),
_DeviceThreadSpawner = spawn_link(?MODULE, listener, [?DEVICE_PORT,
"SessionListener",
device_session,
start]),
_ClientThreadSpawner = spawn_link(?MODULE, listener, [?CLIENT_PORT,
"MatcherListener",
connection_matcher,
start]),
% Loop until we receive a quit request or exception/error occurs
ReceiveLoop = fun(F, InLogPid) ->
receive
{quit, Why} ->
log(info, "Got quit request with: ~p~n", [Why]);
{'EXIT', LogPid, normal} ->
io:format("Logger exited normally, not respawning~n", []),
F(F, none);
{'EXIT', LogPid, Reason} ->
io:format("Logger exited, restarting. Reason: ~p~n", [Reason]),
NewLogPid = spawn_link_logger(),
F(F, NewLogPid);
X ->
log(debug, "Main thread got message: ~p~n", [X]),
F(F, InLogPid)
end
end,
ReceiveLoop(ReceiveLoop, LogPid),
log(info, "Server stopping.~n", []).
spawn_link_logger() ->
spawn_link(log, start, ["/swiftp_proxy/logs", "proxy.log", debug, 10]).
listener(Port, Name, Mod, Func) ->
case util:tcp_listen(Port) of
{ok, TcpListener} -> listener(Port, Name, Mod, Func, TcpListener);
X -> log(error, "~p listener TCP listen error: ~p~n", [Name, X])
end.
listener(Port, Name, Mod, Func, TcpListener) ->
case gen_tcp:accept(TcpListener) of
{ok, Socket} ->
Child = spawn(Mod, Func, [Socket]),
gen_tcp:controlling_process(Socket, Child),
listener(Port, Name, Mod, Func, TcpListener);
X ->
log(error, "Accept error: ~p~n", [X]),
gen_tcp:close(TcpListener)
end.
% Called via RPC from remote nodes to test communication.
ping() ->
ok.
| null | https://raw.githubusercontent.com/davidarkemp/swiftp/1e02e19606daa11c4b41763b7d95c202f60410e2/cloud_server/swiftp_proxy_packaged/server.erl | erlang | Called when we are to join an existing cluster. The argument comes from
the command line (e.g. erl -s server start 'name@host' -detached)
Loop until we receive a quit request or exception/error occurs
Called via RPC from remote nodes to test communication. | -module(swiftp_proxy.server).
-export([start/0, start/1, ping/0, listener/4]).
-import(swiftp_proxy.log, [log/3]).
-import(swiftp_proxy.db, [create_master_schema/0, join_db/1]).
-define(DEVICE_PORT, 2222).
-define(CLIENT_PORT, 2221).
Called when we are the first node of a cluster ( create a new db schema )
start() ->
case create_master_schema() of
ok ->
log(info, "Master schema created~n", []),
start_listeners();
_X ->
log(error, "Master schema create failed, stopping.~n", [])
end,
init:stop().
start([ConnectTo]) ->
case join_db(ConnectTo) of
ok ->
log(info, "Connected to mnesia cluster ok", []),
start_listeners();
X ->
log(error, "Mnesia join failed: ~p~n", [X])
end,
init:stop().
start_listeners() ->
log(info, "Running!~n", []),
process_flag(trap_exit, true),
LogPid = spawn_link_logger(),
register(random_thread, spawn_link(rand, start, [])),
_Registry = spawn_link(session_registry, start, []),
_DeviceThreadSpawner = spawn_link(?MODULE, listener, [?DEVICE_PORT,
"SessionListener",
device_session,
start]),
_ClientThreadSpawner = spawn_link(?MODULE, listener, [?CLIENT_PORT,
"MatcherListener",
connection_matcher,
start]),
ReceiveLoop = fun(F, InLogPid) ->
receive
{quit, Why} ->
log(info, "Got quit request with: ~p~n", [Why]);
{'EXIT', LogPid, normal} ->
io:format("Logger exited normally, not respawning~n", []),
F(F, none);
{'EXIT', LogPid, Reason} ->
io:format("Logger exited, restarting. Reason: ~p~n", [Reason]),
NewLogPid = spawn_link_logger(),
F(F, NewLogPid);
X ->
log(debug, "Main thread got message: ~p~n", [X]),
F(F, InLogPid)
end
end,
ReceiveLoop(ReceiveLoop, LogPid),
log(info, "Server stopping.~n", []).
spawn_link_logger() ->
spawn_link(log, start, ["/swiftp_proxy/logs", "proxy.log", debug, 10]).
listener(Port, Name, Mod, Func) ->
case util:tcp_listen(Port) of
{ok, TcpListener} -> listener(Port, Name, Mod, Func, TcpListener);
X -> log(error, "~p listener TCP listen error: ~p~n", [Name, X])
end.
listener(Port, Name, Mod, Func, TcpListener) ->
case gen_tcp:accept(TcpListener) of
{ok, Socket} ->
Child = spawn(Mod, Func, [Socket]),
gen_tcp:controlling_process(Socket, Child),
listener(Port, Name, Mod, Func, TcpListener);
X ->
log(error, "Accept error: ~p~n", [X]),
gen_tcp:close(TcpListener)
end.
ping() ->
ok.
|
727773257380a3bc8829cadcf699022a8d2b868c8151fa09125fdc27a32020df | snoyberg/http-client | Lookup.hs | {-# LANGUAGE OverloadedStrings #-}
module Network.PublicSuffixList.Lookup (effectiveTLDPlusOne, effectiveTLDPlusOne', isSuffix, isSuffix') where
import qualified Data.Map as M
import Data.Maybe (isNothing)
import qualified Data.Text as T
import qualified Network.PublicSuffixList.DataStructure as DS
import Network.PublicSuffixList.Types
|
OffEnd 's argument represents whether we fell off a
leaf or whether we fell off a non - leaf . True means that
we fell off a leaf . Its Text argument is the component
that pushed us off the end , along with all the components
to the right of that one , interspersed with "
OffEnd's Bool argument represents whether we fell off a
leaf or whether we fell off a non-leaf. True means that
we fell off a leaf. Its Text argument is the component
that pushed us off the end, along with all the components
to the right of that one, interspersed with "."s
-}
data LookupResult = Inside | AtLeaf | OffEnd Bool T.Text
deriving (Eq)
|
This function returns whether or not this domain is owned by a
registrar or a regular person . ' Nothing ' means that this is a registrar
domain ; ' Just x ' means it 's owned by a person . This is used to determine
if a cookie is allowed to bet set for a particular domain . For
example , you should n't be able to set a cookie for " .
If the value is ' Just x ' , then the x value is what is known as the
effective TLD plus one . This is one segment more than the suffix of the
domain . For example , the eTLD+1 for " this.is.a.subdom.com " is Just
" subdom.com "
Note that this function expects lowercase ASCII strings . These strings
should be gotten from the toASCII algorithm as described in RFC 3490 .
These strings should not start or end with the \'.\ ' character , and should
not have two \'.\ ' characters next to each other .
( The toASCII algorithm is implemented in the \'idna\ ' hackage package ,
though that package does n't always map strings to lowercase )
This function returns whether or not this domain is owned by a
registrar or a regular person. 'Nothing' means that this is a registrar
domain; 'Just x' means it's owned by a person. This is used to determine
if a cookie is allowed to bet set for a particular domain. For
example, you shouldn't be able to set a cookie for \"com\".
If the value is 'Just x', then the x value is what is known as the
effective TLD plus one. This is one segment more than the suffix of the
domain. For example, the eTLD+1 for "this.is.a.subdom.com" is Just
"subdom.com"
Note that this function expects lowercase ASCII strings. These strings
should be gotten from the toASCII algorithm as described in RFC 3490.
These strings should not start or end with the \'.\' character, and should
not have two \'.\' characters next to each other.
(The toASCII algorithm is implemented in the \'idna\' hackage package,
though that package doesn't always map strings to lowercase)
-}
effectiveTLDPlusOne' :: DataStructure -> T.Text -> Maybe T.Text
effectiveTLDPlusOne' dataStructure s
Any TLD is a suffix
| length ss == 1 = Nothing
| otherwise = output rulesResult exceptionResult
where ss = T.splitOn "." s
ps = reverse ss
exceptionResult = recurse ps [] $ snd dataStructure
rulesResult = recurse ps [] $ fst dataStructure
-- If we fell off, did we do it at a leaf? Otherwise, what's the
-- subtree that we're at
getNext :: Tree T.Text -> T.Text -> Either Bool (Tree T.Text)
getNext t s' = case M.lookup s' $ children t of
Nothing -> Left (M.null $ children t)
Just t' -> Right t'
-- Look up the component we're looking for...
getNextWithStar t s' = case getNext t s' of
-- and if that fails, look up "*"
Left _ -> getNext t "*"
r -> r
recurse :: [T.Text] -> [T.Text] -> Tree T.Text -> LookupResult
recurse [] _ t
| M.null $ children t = AtLeaf
| otherwise = Inside
recurse (c : cs) prev t = case getNextWithStar t c of
Left b -> OffEnd b $ T.intercalate "." (c : prev)
Right t' -> recurse cs (c : prev) t'
-- Only match against the exception rules if we have a full match
output _ AtLeaf = Just s
output _ (OffEnd True x) = Just $ T.intercalate "." $ tail $ T.splitOn "." x
-- If we have a subdomain on an existing rule, we're not a suffix
output (OffEnd _ x) _
-- A single level domain can never be a eTLD+1
| isNothing $ T.find (== '.') x = Just $ T.intercalate "." $ drop (length ss - 2) ss
| otherwise = Just x
-- Otherwise, we're a suffix of a suffix, which is a suffix
output _ _ = Nothing
| > > > effectiveTLDPlusOne = effectiveTLDPlusOne ' Network . PublicSuffixList . DataStructure.dataStructure
effectiveTLDPlusOne :: T.Text -> Maybe T.Text
effectiveTLDPlusOne = effectiveTLDPlusOne' DS.dataStructure
| > > > isSuffix ' dataStructure = isNothing . effectiveTLDPlusOne ' dataStructure
isSuffix' :: DataStructure -> T.Text -> Bool
isSuffix' dataStructure = isNothing . effectiveTLDPlusOne' dataStructure
-- | >>> isSuffix = isSuffix' Network.PublicSuffixList.DataStructure.dataStructure
isSuffix :: T.Text -> Bool
isSuffix = isNothing . effectiveTLDPlusOne
| null | https://raw.githubusercontent.com/snoyberg/http-client/106951809b3e1c796ffd6cccefc4c1fad16df7c9/http-client/publicsuffixlist/Network/PublicSuffixList/Lookup.hs | haskell | # LANGUAGE OverloadedStrings #
If we fell off, did we do it at a leaf? Otherwise, what's the
subtree that we're at
Look up the component we're looking for...
and if that fails, look up "*"
Only match against the exception rules if we have a full match
If we have a subdomain on an existing rule, we're not a suffix
A single level domain can never be a eTLD+1
Otherwise, we're a suffix of a suffix, which is a suffix
| >>> isSuffix = isSuffix' Network.PublicSuffixList.DataStructure.dataStructure | module Network.PublicSuffixList.Lookup (effectiveTLDPlusOne, effectiveTLDPlusOne', isSuffix, isSuffix') where
import qualified Data.Map as M
import Data.Maybe (isNothing)
import qualified Data.Text as T
import qualified Network.PublicSuffixList.DataStructure as DS
import Network.PublicSuffixList.Types
|
OffEnd 's argument represents whether we fell off a
leaf or whether we fell off a non - leaf . True means that
we fell off a leaf . Its Text argument is the component
that pushed us off the end , along with all the components
to the right of that one , interspersed with "
OffEnd's Bool argument represents whether we fell off a
leaf or whether we fell off a non-leaf. True means that
we fell off a leaf. Its Text argument is the component
that pushed us off the end, along with all the components
to the right of that one, interspersed with "."s
-}
data LookupResult = Inside | AtLeaf | OffEnd Bool T.Text
deriving (Eq)
|
This function returns whether or not this domain is owned by a
registrar or a regular person . ' Nothing ' means that this is a registrar
domain ; ' Just x ' means it 's owned by a person . This is used to determine
if a cookie is allowed to bet set for a particular domain . For
example , you should n't be able to set a cookie for " .
If the value is ' Just x ' , then the x value is what is known as the
effective TLD plus one . This is one segment more than the suffix of the
domain . For example , the eTLD+1 for " this.is.a.subdom.com " is Just
" subdom.com "
Note that this function expects lowercase ASCII strings . These strings
should be gotten from the toASCII algorithm as described in RFC 3490 .
These strings should not start or end with the \'.\ ' character , and should
not have two \'.\ ' characters next to each other .
( The toASCII algorithm is implemented in the \'idna\ ' hackage package ,
though that package does n't always map strings to lowercase )
This function returns whether or not this domain is owned by a
registrar or a regular person. 'Nothing' means that this is a registrar
domain; 'Just x' means it's owned by a person. This is used to determine
if a cookie is allowed to bet set for a particular domain. For
example, you shouldn't be able to set a cookie for \"com\".
If the value is 'Just x', then the x value is what is known as the
effective TLD plus one. This is one segment more than the suffix of the
domain. For example, the eTLD+1 for "this.is.a.subdom.com" is Just
"subdom.com"
Note that this function expects lowercase ASCII strings. These strings
should be gotten from the toASCII algorithm as described in RFC 3490.
These strings should not start or end with the \'.\' character, and should
not have two \'.\' characters next to each other.
(The toASCII algorithm is implemented in the \'idna\' hackage package,
though that package doesn't always map strings to lowercase)
-}
effectiveTLDPlusOne' :: DataStructure -> T.Text -> Maybe T.Text
effectiveTLDPlusOne' dataStructure s
Any TLD is a suffix
| length ss == 1 = Nothing
| otherwise = output rulesResult exceptionResult
where ss = T.splitOn "." s
ps = reverse ss
exceptionResult = recurse ps [] $ snd dataStructure
rulesResult = recurse ps [] $ fst dataStructure
getNext :: Tree T.Text -> T.Text -> Either Bool (Tree T.Text)
getNext t s' = case M.lookup s' $ children t of
Nothing -> Left (M.null $ children t)
Just t' -> Right t'
getNextWithStar t s' = case getNext t s' of
Left _ -> getNext t "*"
r -> r
recurse :: [T.Text] -> [T.Text] -> Tree T.Text -> LookupResult
recurse [] _ t
| M.null $ children t = AtLeaf
| otherwise = Inside
recurse (c : cs) prev t = case getNextWithStar t c of
Left b -> OffEnd b $ T.intercalate "." (c : prev)
Right t' -> recurse cs (c : prev) t'
output _ AtLeaf = Just s
output _ (OffEnd True x) = Just $ T.intercalate "." $ tail $ T.splitOn "." x
output (OffEnd _ x) _
| isNothing $ T.find (== '.') x = Just $ T.intercalate "." $ drop (length ss - 2) ss
| otherwise = Just x
output _ _ = Nothing
| > > > effectiveTLDPlusOne = effectiveTLDPlusOne ' Network . PublicSuffixList . DataStructure.dataStructure
effectiveTLDPlusOne :: T.Text -> Maybe T.Text
effectiveTLDPlusOne = effectiveTLDPlusOne' DS.dataStructure
| > > > isSuffix ' dataStructure = isNothing . effectiveTLDPlusOne ' dataStructure
isSuffix' :: DataStructure -> T.Text -> Bool
isSuffix' dataStructure = isNothing . effectiveTLDPlusOne' dataStructure
isSuffix :: T.Text -> Bool
isSuffix = isNothing . effectiveTLDPlusOne
|
4b05314c94d9a77e9bc4161ad2ff51051adde591888309e39ebc3753655744e0 | aprolog-lang/aprolog | printer.ml | Alpha Prolog
(* Device-independent printers *)
type out_interface = {out : string -> unit;
in_space : bool;
indent_level : int};;
type doc = out_interface -> out_interface;;
type 'a printer = 'a -> doc;;
let set_in_space b oi =
{out=oi.out;
in_space=b;
indent_level=oi.indent_level}
;;
let set_indent_level i oi =
{out = oi.out;
in_space=oi.in_space;
indent_level=i}
;;
let escaped_text s oi =
oi.out (String.escaped s);
set_in_space false oi
;;
let text s oi =
oi.out s;
set_in_space false oi
;;
let escaped_char c oi =
oi.out (Char.escaped c);
set_in_space false oi
;;
(* Common symbols *)
let arrow = text "->";;
let dot = text ".";;
let eq = text "=";;
let eqeq = text "==";;
let defeq = text ":=";;
let bar = text "|";;
let comma = text ",";;
let darrow = text "=>";;
let larrow = text ":-";;
let question = text "?";;
let cut = text "!";;
let amp = text "@";;
let colon = text ":";;
let semi = text ";";;
let star = text "*";;
let hash = text "#";;
let slash = text "/";;
let backslash = text "\\";;
let underscore = text "_";;
let space = text " ";;
let tilde = text "~";;
let num i = text (string_of_int i);;
let (<+>) d1 d2 oi =
let oi = d1 oi in
if oi.in_space
then
d2 (set_in_space false oi)
else (oi.out " ";
d2 (set_in_space true oi))
;;
let (<:>) d1 d2 oi =
d2(d1(oi))
;;
let indent i d oi =
set_indent_level oi.indent_level (d (set_indent_level (oi.indent_level+i) oi))
;;
let newline oi = (text "\n" <:> text (String.make oi.indent_level ' ')) oi;;
let emp oi = oi;;
let paren d =
text "(" <:>
d <:>
text ")"
;;
let angle d =
text "<" <:>
d <:>
text ">"
;;
let bracket d =
text "[" <:>
d <:>
text "]"
;;
let braces d =
text "{" <:>
d <:>
text "}"
;;
let quotes d =
text "\"" <:>
d <:>
text "\""
;;
let squotes d =
text "\'" <:>
d <:>
text "\'"
;;
let comment d =
text "(*" <:>
d <:>
text "*)"
;;
let rec sep d ds =
match ds with
[] -> emp
| [d1] -> d1
| d'::ds' -> d' <:> d <:> (sep d ds')
;;
let rec hcat ds =
match ds with
[] -> emp
| d'::ds' -> d' <:> (hcat ds')
;;
let rec vcat ds =
match ds with
[] -> emp
| d'::ds' -> d' <:> newline <:> (vcat ds')
;;
let doc_to_channel oc doc =
doc {out = output_string oc;
in_space = false;
indent_level = 0};
()
;;
let doc_to_string doc =
let s = ref "" in
doc {out = (fun t -> s := !s^t);
in_space = false;
indent_level = 0};
!s
;;
let print_to_channel pr a oc = doc_to_channel oc (pr a);;
let print_to_string pr a = doc_to_string (pr a);;
let pp = print_to_string;;
| null | https://raw.githubusercontent.com/aprolog-lang/aprolog/410327a615919eb6827d71661e69de14279b8c50/src/printer.ml | ocaml | Device-independent printers
Common symbols | Alpha Prolog
type out_interface = {out : string -> unit;
in_space : bool;
indent_level : int};;
type doc = out_interface -> out_interface;;
type 'a printer = 'a -> doc;;
let set_in_space b oi =
{out=oi.out;
in_space=b;
indent_level=oi.indent_level}
;;
let set_indent_level i oi =
{out = oi.out;
in_space=oi.in_space;
indent_level=i}
;;
let escaped_text s oi =
oi.out (String.escaped s);
set_in_space false oi
;;
let text s oi =
oi.out s;
set_in_space false oi
;;
let escaped_char c oi =
oi.out (Char.escaped c);
set_in_space false oi
;;
let arrow = text "->";;
let dot = text ".";;
let eq = text "=";;
let eqeq = text "==";;
let defeq = text ":=";;
let bar = text "|";;
let comma = text ",";;
let darrow = text "=>";;
let larrow = text ":-";;
let question = text "?";;
let cut = text "!";;
let amp = text "@";;
let colon = text ":";;
let semi = text ";";;
let star = text "*";;
let hash = text "#";;
let slash = text "/";;
let backslash = text "\\";;
let underscore = text "_";;
let space = text " ";;
let tilde = text "~";;
let num i = text (string_of_int i);;
let (<+>) d1 d2 oi =
let oi = d1 oi in
if oi.in_space
then
d2 (set_in_space false oi)
else (oi.out " ";
d2 (set_in_space true oi))
;;
let (<:>) d1 d2 oi =
d2(d1(oi))
;;
let indent i d oi =
set_indent_level oi.indent_level (d (set_indent_level (oi.indent_level+i) oi))
;;
let newline oi = (text "\n" <:> text (String.make oi.indent_level ' ')) oi;;
let emp oi = oi;;
let paren d =
text "(" <:>
d <:>
text ")"
;;
let angle d =
text "<" <:>
d <:>
text ">"
;;
let bracket d =
text "[" <:>
d <:>
text "]"
;;
let braces d =
text "{" <:>
d <:>
text "}"
;;
let quotes d =
text "\"" <:>
d <:>
text "\""
;;
let squotes d =
text "\'" <:>
d <:>
text "\'"
;;
let comment d =
text "(*" <:>
d <:>
text "*)"
;;
let rec sep d ds =
match ds with
[] -> emp
| [d1] -> d1
| d'::ds' -> d' <:> d <:> (sep d ds')
;;
let rec hcat ds =
match ds with
[] -> emp
| d'::ds' -> d' <:> (hcat ds')
;;
let rec vcat ds =
match ds with
[] -> emp
| d'::ds' -> d' <:> newline <:> (vcat ds')
;;
let doc_to_channel oc doc =
doc {out = output_string oc;
in_space = false;
indent_level = 0};
()
;;
let doc_to_string doc =
let s = ref "" in
doc {out = (fun t -> s := !s^t);
in_space = false;
indent_level = 0};
!s
;;
let print_to_channel pr a oc = doc_to_channel oc (pr a);;
let print_to_string pr a = doc_to_string (pr a);;
let pp = print_to_string;;
|
920d6eef7b118ef07ada509233680b2738117e8c807cac105c7d99acff3b6f3e | cracauer/sbcl-ita | cell.lisp | ;;;; the VM definition of various primitive memory access VOPs for
MIPS
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB!VM")
;;;; Data object ref/set stuff.
(define-vop (slot)
(:args (object :scs (descriptor-reg)))
(:info name offset lowtag)
(:ignore name)
(:results (result :scs (descriptor-reg any-reg)))
(:generator 1
(loadw result object offset lowtag)))
(define-vop (set-slot)
(:args (object :scs (descriptor-reg))
(value :scs (descriptor-reg any-reg null zero)))
(:info name offset lowtag)
(:ignore name)
(:results)
(:generator 1
(storew value object offset lowtag)))
(define-vop (init-slot set-slot))
;;;; Symbol hacking VOPs:
;;; The compiler likes to be able to directly SET symbols.
;;;
(define-vop (set cell-set)
(:variant symbol-value-slot other-pointer-lowtag))
;;; Do a cell ref with an error check for being unbound.
;;;
(define-vop (checked-cell-ref)
(:args (object :scs (descriptor-reg) :target obj-temp))
(:results (value :scs (descriptor-reg any-reg)))
(:policy :fast-safe)
(:vop-var vop)
(:save-p :compute-only)
(:temporary (:scs (non-descriptor-reg)) temp)
(:temporary (:scs (descriptor-reg) :from (:argument 0)) obj-temp))
With Symbol - Value , we check that the value is n't the trap object . So
Symbol - Value of NIL is NIL .
;;;
(define-vop (symbol-value checked-cell-ref)
(:translate symbol-value)
(:generator 9
(move obj-temp object)
(loadw value obj-temp symbol-value-slot other-pointer-lowtag)
(let ((err-lab (generate-error-code vop 'unbound-symbol-error obj-temp)))
(inst xor temp value unbound-marker-widetag)
(inst beq temp err-lab)
(inst nop))))
;;; Like CHECKED-CELL-REF, only we are a predicate to see if the cell is bound.
(define-vop (boundp-frob)
(:args (object :scs (descriptor-reg)))
(:conditional)
(:info target not-p)
(:policy :fast-safe)
(:temporary (:scs (descriptor-reg)) value)
(:temporary (:scs (non-descriptor-reg)) temp))
(define-vop (boundp boundp-frob)
(:translate boundp)
(:generator 9
(loadw value object symbol-value-slot other-pointer-lowtag)
(inst xor temp value unbound-marker-widetag)
(if not-p
(inst beq temp target)
(inst bne temp target))
(inst nop)))
(define-vop (fast-symbol-value cell-ref)
(:variant symbol-value-slot other-pointer-lowtag)
(:policy :fast)
(:translate symbol-value))
(define-vop (symbol-hash)
(:policy :fast-safe)
(:translate symbol-hash)
(:args (symbol :scs (descriptor-reg)))
(:temporary (:scs (non-descriptor-reg)) temp)
(:results (res :scs (any-reg)))
(:result-types positive-fixnum)
(:generator 2
The symbol - hash slot of NIL holds NIL because it is also the
cdr slot , so we have to strip off the two low bits to make sure
;; it is a fixnum. The lowtag selection magic that is required to
ensure this is explained in the comment in objdef.lisp
(loadw temp symbol symbol-hash-slot other-pointer-lowtag)
(inst srl temp n-fixnum-tag-bits)
(inst sll res temp n-fixnum-tag-bits)))
;;; On unithreaded builds these are just copies of the non-global versions.
(define-vop (%set-symbol-global-value set))
(define-vop (symbol-global-value symbol-value)
(:translate symbol-global-value))
(define-vop (fast-symbol-global-value fast-symbol-value)
(:translate symbol-global-value))
;;;; Fdefinition (fdefn) objects.
(define-vop (fdefn-fun cell-ref)
(:variant fdefn-fun-slot other-pointer-lowtag))
(define-vop (safe-fdefn-fun)
(:translate safe-fdefn-fun)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg) :target obj-temp))
(:results (value :scs (descriptor-reg any-reg)))
(:vop-var vop)
(:save-p :compute-only)
(:temporary (:scs (descriptor-reg) :from (:argument 0)) obj-temp)
(:generator 10
(move obj-temp object)
(loadw value obj-temp fdefn-fun-slot other-pointer-lowtag)
(let ((err-lab (generate-error-code vop 'undefined-fun-error obj-temp)))
(inst beq value null-tn err-lab))
(inst nop)))
(define-vop (set-fdefn-fun)
(:policy :fast-safe)
(:translate (setf fdefn-fun))
(:args (function :scs (descriptor-reg) :target result)
(fdefn :scs (descriptor-reg)))
(:temporary (:scs (interior-reg)) lip)
(:temporary (:scs (non-descriptor-reg)) type)
(:results (result :scs (descriptor-reg)))
(:generator 38
(let ((normal-fn (gen-label)))
(load-type type function (- fun-pointer-lowtag))
(inst nop)
(inst xor type simple-fun-header-widetag)
(inst beq type normal-fn)
(inst addu lip function
(- (ash simple-fun-code-offset word-shift)
fun-pointer-lowtag))
(inst li lip (make-fixup "closure_tramp" :foreign))
(emit-label normal-fn)
(storew lip fdefn fdefn-raw-addr-slot other-pointer-lowtag)
(storew function fdefn fdefn-fun-slot other-pointer-lowtag)
(move result function))))
(define-vop (fdefn-makunbound)
(:policy :fast-safe)
(:translate fdefn-makunbound)
(:args (fdefn :scs (descriptor-reg) :target result))
(:temporary (:scs (non-descriptor-reg)) temp)
(:results (result :scs (descriptor-reg)))
(:generator 38
(storew null-tn fdefn fdefn-fun-slot other-pointer-lowtag)
(inst li temp (make-fixup "undefined_tramp" :foreign))
(storew temp fdefn fdefn-raw-addr-slot other-pointer-lowtag)
(move result fdefn)))
;;;; Binding and Unbinding.
BIND -- Establish VAL as a binding for SYMBOL . Save the old value and
;;; the symbol on the binding stack and stuff the new value into the
;;; symbol.
See the " Chapter 9 : Specials " of the SBCL Internals Manual .
(define-vop (dynbind)
(:args (val :scs (any-reg descriptor-reg))
(symbol :scs (descriptor-reg)))
(:temporary (:scs (descriptor-reg)) temp)
(:generator 5
(loadw temp symbol symbol-value-slot other-pointer-lowtag)
(inst addu bsp-tn bsp-tn (* 2 n-word-bytes))
(storew temp bsp-tn (- binding-value-slot binding-size))
(storew symbol bsp-tn (- binding-symbol-slot binding-size))
(storew val symbol symbol-value-slot other-pointer-lowtag)))
(define-vop (unbind)
(:temporary (:scs (descriptor-reg)) symbol value)
(:generator 0
(loadw symbol bsp-tn (- binding-symbol-slot binding-size))
(loadw value bsp-tn (- binding-value-slot binding-size))
(storew value symbol symbol-value-slot other-pointer-lowtag)
(storew zero-tn bsp-tn (- binding-symbol-slot binding-size))
(storew zero-tn bsp-tn (- binding-value-slot binding-size))
(inst addu bsp-tn bsp-tn (* -2 n-word-bytes))))
(define-vop (unbind-to-here)
(:args (arg :scs (descriptor-reg any-reg) :target where))
(:temporary (:scs (any-reg) :from (:argument 0)) where)
(:temporary (:scs (descriptor-reg)) symbol value)
(:generator 0
(let ((loop (gen-label))
(skip (gen-label))
(done (gen-label)))
(move where arg)
(inst beq where bsp-tn done)
(inst nop)
(emit-label loop)
(loadw symbol bsp-tn (- binding-symbol-slot binding-size))
(inst beq symbol skip)
(loadw value bsp-tn (- binding-value-slot binding-size))
(storew value symbol symbol-value-slot other-pointer-lowtag)
(storew zero-tn bsp-tn (- binding-symbol-slot binding-size))
(emit-label skip)
(storew zero-tn bsp-tn (- binding-value-slot binding-size))
(inst addu bsp-tn bsp-tn (* -2 n-word-bytes))
(inst bne where bsp-tn loop)
(inst nop)
(emit-label done))))
;;;; Closure indexing.
(define-full-reffer closure-index-ref *
closure-info-offset fun-pointer-lowtag
(descriptor-reg any-reg) * %closure-index-ref)
(define-full-setter set-funcallable-instance-info *
funcallable-instance-info-offset fun-pointer-lowtag
(descriptor-reg any-reg null zero) * %set-funcallable-instance-info)
(define-full-reffer funcallable-instance-info *
funcallable-instance-info-offset fun-pointer-lowtag
(descriptor-reg any-reg) * %funcallable-instance-info)
(define-vop (closure-ref slot-ref)
(:variant closure-info-offset fun-pointer-lowtag))
(define-vop (closure-init slot-set)
(:variant closure-info-offset fun-pointer-lowtag))
(define-vop (closure-init-from-fp)
(:args (object :scs (descriptor-reg)))
(:info offset)
(:generator 4
(storew cfp-tn object (+ closure-info-offset offset) fun-pointer-lowtag)))
;;;; Value Cell hackery.
(define-vop (value-cell-ref cell-ref)
(:variant value-cell-value-slot other-pointer-lowtag))
(define-vop (value-cell-set cell-set)
(:variant value-cell-value-slot other-pointer-lowtag))
;;;; Instance hackery:
(define-vop (instance-length)
(:policy :fast-safe)
(:translate %instance-length)
(:args (struct :scs (descriptor-reg)))
(:temporary (:scs (non-descriptor-reg)) temp)
(:results (res :scs (unsigned-reg)))
(:result-types positive-fixnum)
(:generator 4
(loadw temp struct 0 instance-pointer-lowtag)
(inst srl res temp n-widetag-bits)))
(define-full-reffer instance-index-ref * instance-slots-offset
instance-pointer-lowtag (descriptor-reg any-reg) * %instance-ref)
(define-full-setter instance-index-set * instance-slots-offset
instance-pointer-lowtag (descriptor-reg any-reg null zero) * %instance-set)
;;;; Code object frobbing.
(define-full-reffer code-header-ref * 0 other-pointer-lowtag
(descriptor-reg any-reg) * code-header-ref)
(define-full-setter code-header-set * 0 other-pointer-lowtag
(descriptor-reg any-reg null zero) * code-header-set)
;;;; raw instance slot accessors
(define-vop (raw-instance-ref/word)
(:translate %raw-instance-ref/word)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg)))
(:arg-types * positive-fixnum)
(:results (value :scs (unsigned-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types unsigned-num)
(:generator 5
(inst addu lip object index)
(loadw value lip instance-slots-offset instance-pointer-lowtag)))
(define-vop (raw-instance-set/word)
(:translate %raw-instance-set/word)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg))
(value :scs (unsigned-reg) :target result))
(:arg-types * positive-fixnum unsigned-num)
(:results (result :scs (unsigned-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types unsigned-num)
(:generator 5
(inst addu lip object index)
(storew value lip instance-slots-offset instance-pointer-lowtag)
(move result value)))
(define-vop (raw-instance-ref/single)
(:translate %raw-instance-ref/single)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg)))
(:arg-types * positive-fixnum)
(:results (value :scs (single-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types single-float)
(:generator 5
(inst addu lip object index)
(inst lwc1 value lip (- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag))))
(define-vop (raw-instance-set/single)
(:translate %raw-instance-set/single)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg))
(value :scs (single-reg) :target result))
(:arg-types * positive-fixnum single-float)
(:results (result :scs (single-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types single-float)
(:generator 5
(inst addu lip object index)
(inst swc1 value lip (- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag))
(unless (location= result value)
(inst fmove :single result value))))
(define-vop (raw-instance-ref/double)
(:translate %raw-instance-ref/double)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg)))
(:arg-types * positive-fixnum)
(:results (value :scs (double-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types double-float)
(:generator 5
(inst addu lip object index)
(let ((immediate-offset (- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst lwc1-odd value lip immediate-offset))
(:little-endian (inst lwc1 value lip immediate-offset))))
(let ((immediate-offset (- (* (1+ instance-slots-offset) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst lwc1 value lip immediate-offset))
(:little-endian (inst lwc1-odd value lip immediate-offset))))))
(define-vop (raw-instance-set/double)
(:translate %raw-instance-set/double)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg))
(value :scs (double-reg) :target result))
(:arg-types * positive-fixnum double-float)
(:results (result :scs (double-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types double-float)
(:generator 5
(inst addu lip object index)
(let ((immediate-offset (- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst swc1-odd value lip immediate-offset))
(:little-endian (inst swc1 value lip immediate-offset))))
(let ((immediate-offset (- (* (1+ instance-slots-offset) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst swc1 value lip immediate-offset))
(:little-endian (inst swc1-odd value lip immediate-offset))))
(unless (location= result value)
(inst fmove :double result value))))
(define-vop (raw-instance-ref/complex-single)
(:translate %raw-instance-ref/complex-single)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg)))
(:arg-types * positive-fixnum)
(:results (value :scs (complex-single-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types complex-single-float)
(:generator 5
(inst addu lip object index)
(inst lwc1
(complex-single-reg-real-tn value)
lip
(- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag))
(inst lwc1
(complex-single-reg-imag-tn value)
lip
(- (* (1+ instance-slots-offset) n-word-bytes)
instance-pointer-lowtag))))
(define-vop (raw-instance-set/complex-single)
(:translate %raw-instance-set/complex-single)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg))
(value :scs (complex-single-reg) :target result))
(:arg-types * positive-fixnum complex-single-float)
(:results (result :scs (complex-single-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types complex-single-float)
(:generator 5
(inst addu lip object index)
(let ((value-real (complex-single-reg-real-tn value))
(result-real (complex-single-reg-real-tn result)))
(inst swc1
value-real
lip
(- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag))
(unless (location= result-real value-real)
(inst fmove :single result-real value-real)))
(let ((value-imag (complex-single-reg-imag-tn value))
(result-imag (complex-single-reg-imag-tn result)))
(inst swc1
value-imag
lip
(- (* (1+ instance-slots-offset) n-word-bytes)
instance-pointer-lowtag))
(unless (location= result-imag value-imag)
(inst fmove :single result-imag value-imag)))))
(define-vop (raw-instance-ref/complex-double)
(:translate %raw-instance-ref/complex-double)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg)))
(:arg-types * positive-fixnum)
(:results (value :scs (complex-double-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types complex-double-float)
(:generator 5
(inst addu lip object index)
(let ((immediate-offset (- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst lwc1-odd
(complex-double-reg-real-tn value)
lip
immediate-offset))
(:little-endian (inst lwc1
(complex-double-reg-real-tn value)
lip
immediate-offset))))
(let ((immediate-offset (- (* (1+ instance-slots-offset) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst lwc1
(complex-double-reg-real-tn value)
lip
immediate-offset))
(:little-endian (inst lwc1-odd
(complex-double-reg-real-tn value)
lip
immediate-offset))))
(let ((immediate-offset (- (* (+ instance-slots-offset 2) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst lwc1-odd
(complex-double-reg-imag-tn value)
lip
immediate-offset))
(:little-endian (inst lwc1
(complex-double-reg-imag-tn value)
lip
immediate-offset))))
(let ((immediate-offset (- (* (+ instance-slots-offset 3) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst lwc1
(complex-double-reg-imag-tn value)
lip
immediate-offset))
(:little-endian (inst lwc1-odd
(complex-double-reg-imag-tn value)
lip
immediate-offset))))))
(define-vop (raw-instance-set/complex-double)
(:translate %raw-instance-set/complex-double)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg))
(value :scs (complex-double-reg) :target result))
(:arg-types * positive-fixnum complex-double-float)
(:results (result :scs (complex-double-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types complex-double-float)
(:generator 5
(inst addu lip object index)
(let ((value-real (complex-double-reg-real-tn value))
(result-real (complex-double-reg-real-tn result)))
(let ((immediate-offset (- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst swc1-odd
value-real
lip
immediate-offset))
(:little-endian (inst swc1
value-real
lip
immediate-offset))))
(let ((immediate-offset (- (* (1+ instance-slots-offset) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst swc1
value-real
lip
immediate-offset))
(:little-endian (inst swc1-odd
value-real
lip
immediate-offset))))
(unless (location= result-real value-real)
(inst fmove :double result-real value-real)))
(let ((value-imag (complex-double-reg-imag-tn value))
(result-imag (complex-double-reg-imag-tn result)))
(let ((immediate-offset (- (* (+ instance-slots-offset 2) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst swc1-odd
value-imag
lip
immediate-offset))
(:little-endian (inst swc1
value-imag
lip
immediate-offset))))
(let ((immediate-offset (- (* (+ instance-slots-offset 3) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst swc1
value-imag
lip
immediate-offset))
(:little-endian (inst swc1-odd
value-imag
lip
immediate-offset))))
(unless (location= result-imag value-imag)
(inst fmove :double result-imag value-imag)))))
| null | https://raw.githubusercontent.com/cracauer/sbcl-ita/f85a8cf0d1fb6e8c7b258e898b7af3233713e0b9/src/compiler/mips/cell.lisp | lisp | the VM definition of various primitive memory access VOPs for
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
Data object ref/set stuff.
Symbol hacking VOPs:
The compiler likes to be able to directly SET symbols.
Do a cell ref with an error check for being unbound.
Like CHECKED-CELL-REF, only we are a predicate to see if the cell is bound.
it is a fixnum. The lowtag selection magic that is required to
On unithreaded builds these are just copies of the non-global versions.
Fdefinition (fdefn) objects.
Binding and Unbinding.
the symbol on the binding stack and stuff the new value into the
symbol.
Closure indexing.
Value Cell hackery.
Instance hackery:
Code object frobbing.
raw instance slot accessors | MIPS
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package "SB!VM")
(define-vop (slot)
(:args (object :scs (descriptor-reg)))
(:info name offset lowtag)
(:ignore name)
(:results (result :scs (descriptor-reg any-reg)))
(:generator 1
(loadw result object offset lowtag)))
(define-vop (set-slot)
(:args (object :scs (descriptor-reg))
(value :scs (descriptor-reg any-reg null zero)))
(:info name offset lowtag)
(:ignore name)
(:results)
(:generator 1
(storew value object offset lowtag)))
(define-vop (init-slot set-slot))
(define-vop (set cell-set)
(:variant symbol-value-slot other-pointer-lowtag))
(define-vop (checked-cell-ref)
(:args (object :scs (descriptor-reg) :target obj-temp))
(:results (value :scs (descriptor-reg any-reg)))
(:policy :fast-safe)
(:vop-var vop)
(:save-p :compute-only)
(:temporary (:scs (non-descriptor-reg)) temp)
(:temporary (:scs (descriptor-reg) :from (:argument 0)) obj-temp))
With Symbol - Value , we check that the value is n't the trap object . So
Symbol - Value of NIL is NIL .
(define-vop (symbol-value checked-cell-ref)
(:translate symbol-value)
(:generator 9
(move obj-temp object)
(loadw value obj-temp symbol-value-slot other-pointer-lowtag)
(let ((err-lab (generate-error-code vop 'unbound-symbol-error obj-temp)))
(inst xor temp value unbound-marker-widetag)
(inst beq temp err-lab)
(inst nop))))
(define-vop (boundp-frob)
(:args (object :scs (descriptor-reg)))
(:conditional)
(:info target not-p)
(:policy :fast-safe)
(:temporary (:scs (descriptor-reg)) value)
(:temporary (:scs (non-descriptor-reg)) temp))
(define-vop (boundp boundp-frob)
(:translate boundp)
(:generator 9
(loadw value object symbol-value-slot other-pointer-lowtag)
(inst xor temp value unbound-marker-widetag)
(if not-p
(inst beq temp target)
(inst bne temp target))
(inst nop)))
(define-vop (fast-symbol-value cell-ref)
(:variant symbol-value-slot other-pointer-lowtag)
(:policy :fast)
(:translate symbol-value))
(define-vop (symbol-hash)
(:policy :fast-safe)
(:translate symbol-hash)
(:args (symbol :scs (descriptor-reg)))
(:temporary (:scs (non-descriptor-reg)) temp)
(:results (res :scs (any-reg)))
(:result-types positive-fixnum)
(:generator 2
The symbol - hash slot of NIL holds NIL because it is also the
cdr slot , so we have to strip off the two low bits to make sure
ensure this is explained in the comment in objdef.lisp
(loadw temp symbol symbol-hash-slot other-pointer-lowtag)
(inst srl temp n-fixnum-tag-bits)
(inst sll res temp n-fixnum-tag-bits)))
(define-vop (%set-symbol-global-value set))
(define-vop (symbol-global-value symbol-value)
(:translate symbol-global-value))
(define-vop (fast-symbol-global-value fast-symbol-value)
(:translate symbol-global-value))
(define-vop (fdefn-fun cell-ref)
(:variant fdefn-fun-slot other-pointer-lowtag))
(define-vop (safe-fdefn-fun)
(:translate safe-fdefn-fun)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg) :target obj-temp))
(:results (value :scs (descriptor-reg any-reg)))
(:vop-var vop)
(:save-p :compute-only)
(:temporary (:scs (descriptor-reg) :from (:argument 0)) obj-temp)
(:generator 10
(move obj-temp object)
(loadw value obj-temp fdefn-fun-slot other-pointer-lowtag)
(let ((err-lab (generate-error-code vop 'undefined-fun-error obj-temp)))
(inst beq value null-tn err-lab))
(inst nop)))
(define-vop (set-fdefn-fun)
(:policy :fast-safe)
(:translate (setf fdefn-fun))
(:args (function :scs (descriptor-reg) :target result)
(fdefn :scs (descriptor-reg)))
(:temporary (:scs (interior-reg)) lip)
(:temporary (:scs (non-descriptor-reg)) type)
(:results (result :scs (descriptor-reg)))
(:generator 38
(let ((normal-fn (gen-label)))
(load-type type function (- fun-pointer-lowtag))
(inst nop)
(inst xor type simple-fun-header-widetag)
(inst beq type normal-fn)
(inst addu lip function
(- (ash simple-fun-code-offset word-shift)
fun-pointer-lowtag))
(inst li lip (make-fixup "closure_tramp" :foreign))
(emit-label normal-fn)
(storew lip fdefn fdefn-raw-addr-slot other-pointer-lowtag)
(storew function fdefn fdefn-fun-slot other-pointer-lowtag)
(move result function))))
(define-vop (fdefn-makunbound)
(:policy :fast-safe)
(:translate fdefn-makunbound)
(:args (fdefn :scs (descriptor-reg) :target result))
(:temporary (:scs (non-descriptor-reg)) temp)
(:results (result :scs (descriptor-reg)))
(:generator 38
(storew null-tn fdefn fdefn-fun-slot other-pointer-lowtag)
(inst li temp (make-fixup "undefined_tramp" :foreign))
(storew temp fdefn fdefn-raw-addr-slot other-pointer-lowtag)
(move result fdefn)))
BIND -- Establish VAL as a binding for SYMBOL . Save the old value and
See the " Chapter 9 : Specials " of the SBCL Internals Manual .
(define-vop (dynbind)
(:args (val :scs (any-reg descriptor-reg))
(symbol :scs (descriptor-reg)))
(:temporary (:scs (descriptor-reg)) temp)
(:generator 5
(loadw temp symbol symbol-value-slot other-pointer-lowtag)
(inst addu bsp-tn bsp-tn (* 2 n-word-bytes))
(storew temp bsp-tn (- binding-value-slot binding-size))
(storew symbol bsp-tn (- binding-symbol-slot binding-size))
(storew val symbol symbol-value-slot other-pointer-lowtag)))
(define-vop (unbind)
(:temporary (:scs (descriptor-reg)) symbol value)
(:generator 0
(loadw symbol bsp-tn (- binding-symbol-slot binding-size))
(loadw value bsp-tn (- binding-value-slot binding-size))
(storew value symbol symbol-value-slot other-pointer-lowtag)
(storew zero-tn bsp-tn (- binding-symbol-slot binding-size))
(storew zero-tn bsp-tn (- binding-value-slot binding-size))
(inst addu bsp-tn bsp-tn (* -2 n-word-bytes))))
(define-vop (unbind-to-here)
(:args (arg :scs (descriptor-reg any-reg) :target where))
(:temporary (:scs (any-reg) :from (:argument 0)) where)
(:temporary (:scs (descriptor-reg)) symbol value)
(:generator 0
(let ((loop (gen-label))
(skip (gen-label))
(done (gen-label)))
(move where arg)
(inst beq where bsp-tn done)
(inst nop)
(emit-label loop)
(loadw symbol bsp-tn (- binding-symbol-slot binding-size))
(inst beq symbol skip)
(loadw value bsp-tn (- binding-value-slot binding-size))
(storew value symbol symbol-value-slot other-pointer-lowtag)
(storew zero-tn bsp-tn (- binding-symbol-slot binding-size))
(emit-label skip)
(storew zero-tn bsp-tn (- binding-value-slot binding-size))
(inst addu bsp-tn bsp-tn (* -2 n-word-bytes))
(inst bne where bsp-tn loop)
(inst nop)
(emit-label done))))
(define-full-reffer closure-index-ref *
closure-info-offset fun-pointer-lowtag
(descriptor-reg any-reg) * %closure-index-ref)
(define-full-setter set-funcallable-instance-info *
funcallable-instance-info-offset fun-pointer-lowtag
(descriptor-reg any-reg null zero) * %set-funcallable-instance-info)
(define-full-reffer funcallable-instance-info *
funcallable-instance-info-offset fun-pointer-lowtag
(descriptor-reg any-reg) * %funcallable-instance-info)
(define-vop (closure-ref slot-ref)
(:variant closure-info-offset fun-pointer-lowtag))
(define-vop (closure-init slot-set)
(:variant closure-info-offset fun-pointer-lowtag))
(define-vop (closure-init-from-fp)
(:args (object :scs (descriptor-reg)))
(:info offset)
(:generator 4
(storew cfp-tn object (+ closure-info-offset offset) fun-pointer-lowtag)))
(define-vop (value-cell-ref cell-ref)
(:variant value-cell-value-slot other-pointer-lowtag))
(define-vop (value-cell-set cell-set)
(:variant value-cell-value-slot other-pointer-lowtag))
(define-vop (instance-length)
(:policy :fast-safe)
(:translate %instance-length)
(:args (struct :scs (descriptor-reg)))
(:temporary (:scs (non-descriptor-reg)) temp)
(:results (res :scs (unsigned-reg)))
(:result-types positive-fixnum)
(:generator 4
(loadw temp struct 0 instance-pointer-lowtag)
(inst srl res temp n-widetag-bits)))
(define-full-reffer instance-index-ref * instance-slots-offset
instance-pointer-lowtag (descriptor-reg any-reg) * %instance-ref)
(define-full-setter instance-index-set * instance-slots-offset
instance-pointer-lowtag (descriptor-reg any-reg null zero) * %instance-set)
(define-full-reffer code-header-ref * 0 other-pointer-lowtag
(descriptor-reg any-reg) * code-header-ref)
(define-full-setter code-header-set * 0 other-pointer-lowtag
(descriptor-reg any-reg null zero) * code-header-set)
(define-vop (raw-instance-ref/word)
(:translate %raw-instance-ref/word)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg)))
(:arg-types * positive-fixnum)
(:results (value :scs (unsigned-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types unsigned-num)
(:generator 5
(inst addu lip object index)
(loadw value lip instance-slots-offset instance-pointer-lowtag)))
(define-vop (raw-instance-set/word)
(:translate %raw-instance-set/word)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg))
(value :scs (unsigned-reg) :target result))
(:arg-types * positive-fixnum unsigned-num)
(:results (result :scs (unsigned-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types unsigned-num)
(:generator 5
(inst addu lip object index)
(storew value lip instance-slots-offset instance-pointer-lowtag)
(move result value)))
(define-vop (raw-instance-ref/single)
(:translate %raw-instance-ref/single)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg)))
(:arg-types * positive-fixnum)
(:results (value :scs (single-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types single-float)
(:generator 5
(inst addu lip object index)
(inst lwc1 value lip (- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag))))
(define-vop (raw-instance-set/single)
(:translate %raw-instance-set/single)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg))
(value :scs (single-reg) :target result))
(:arg-types * positive-fixnum single-float)
(:results (result :scs (single-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types single-float)
(:generator 5
(inst addu lip object index)
(inst swc1 value lip (- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag))
(unless (location= result value)
(inst fmove :single result value))))
(define-vop (raw-instance-ref/double)
(:translate %raw-instance-ref/double)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg)))
(:arg-types * positive-fixnum)
(:results (value :scs (double-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types double-float)
(:generator 5
(inst addu lip object index)
(let ((immediate-offset (- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst lwc1-odd value lip immediate-offset))
(:little-endian (inst lwc1 value lip immediate-offset))))
(let ((immediate-offset (- (* (1+ instance-slots-offset) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst lwc1 value lip immediate-offset))
(:little-endian (inst lwc1-odd value lip immediate-offset))))))
(define-vop (raw-instance-set/double)
(:translate %raw-instance-set/double)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg))
(value :scs (double-reg) :target result))
(:arg-types * positive-fixnum double-float)
(:results (result :scs (double-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types double-float)
(:generator 5
(inst addu lip object index)
(let ((immediate-offset (- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst swc1-odd value lip immediate-offset))
(:little-endian (inst swc1 value lip immediate-offset))))
(let ((immediate-offset (- (* (1+ instance-slots-offset) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst swc1 value lip immediate-offset))
(:little-endian (inst swc1-odd value lip immediate-offset))))
(unless (location= result value)
(inst fmove :double result value))))
(define-vop (raw-instance-ref/complex-single)
(:translate %raw-instance-ref/complex-single)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg)))
(:arg-types * positive-fixnum)
(:results (value :scs (complex-single-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types complex-single-float)
(:generator 5
(inst addu lip object index)
(inst lwc1
(complex-single-reg-real-tn value)
lip
(- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag))
(inst lwc1
(complex-single-reg-imag-tn value)
lip
(- (* (1+ instance-slots-offset) n-word-bytes)
instance-pointer-lowtag))))
(define-vop (raw-instance-set/complex-single)
(:translate %raw-instance-set/complex-single)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg))
(value :scs (complex-single-reg) :target result))
(:arg-types * positive-fixnum complex-single-float)
(:results (result :scs (complex-single-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types complex-single-float)
(:generator 5
(inst addu lip object index)
(let ((value-real (complex-single-reg-real-tn value))
(result-real (complex-single-reg-real-tn result)))
(inst swc1
value-real
lip
(- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag))
(unless (location= result-real value-real)
(inst fmove :single result-real value-real)))
(let ((value-imag (complex-single-reg-imag-tn value))
(result-imag (complex-single-reg-imag-tn result)))
(inst swc1
value-imag
lip
(- (* (1+ instance-slots-offset) n-word-bytes)
instance-pointer-lowtag))
(unless (location= result-imag value-imag)
(inst fmove :single result-imag value-imag)))))
(define-vop (raw-instance-ref/complex-double)
(:translate %raw-instance-ref/complex-double)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg)))
(:arg-types * positive-fixnum)
(:results (value :scs (complex-double-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types complex-double-float)
(:generator 5
(inst addu lip object index)
(let ((immediate-offset (- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst lwc1-odd
(complex-double-reg-real-tn value)
lip
immediate-offset))
(:little-endian (inst lwc1
(complex-double-reg-real-tn value)
lip
immediate-offset))))
(let ((immediate-offset (- (* (1+ instance-slots-offset) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst lwc1
(complex-double-reg-real-tn value)
lip
immediate-offset))
(:little-endian (inst lwc1-odd
(complex-double-reg-real-tn value)
lip
immediate-offset))))
(let ((immediate-offset (- (* (+ instance-slots-offset 2) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst lwc1-odd
(complex-double-reg-imag-tn value)
lip
immediate-offset))
(:little-endian (inst lwc1
(complex-double-reg-imag-tn value)
lip
immediate-offset))))
(let ((immediate-offset (- (* (+ instance-slots-offset 3) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst lwc1
(complex-double-reg-imag-tn value)
lip
immediate-offset))
(:little-endian (inst lwc1-odd
(complex-double-reg-imag-tn value)
lip
immediate-offset))))))
(define-vop (raw-instance-set/complex-double)
(:translate %raw-instance-set/complex-double)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg))
(index :scs (any-reg))
(value :scs (complex-double-reg) :target result))
(:arg-types * positive-fixnum complex-double-float)
(:results (result :scs (complex-double-reg)))
(:temporary (:scs (interior-reg)) lip)
(:result-types complex-double-float)
(:generator 5
(inst addu lip object index)
(let ((value-real (complex-double-reg-real-tn value))
(result-real (complex-double-reg-real-tn result)))
(let ((immediate-offset (- (* instance-slots-offset n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst swc1-odd
value-real
lip
immediate-offset))
(:little-endian (inst swc1
value-real
lip
immediate-offset))))
(let ((immediate-offset (- (* (1+ instance-slots-offset) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst swc1
value-real
lip
immediate-offset))
(:little-endian (inst swc1-odd
value-real
lip
immediate-offset))))
(unless (location= result-real value-real)
(inst fmove :double result-real value-real)))
(let ((value-imag (complex-double-reg-imag-tn value))
(result-imag (complex-double-reg-imag-tn result)))
(let ((immediate-offset (- (* (+ instance-slots-offset 2) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst swc1-odd
value-imag
lip
immediate-offset))
(:little-endian (inst swc1
value-imag
lip
immediate-offset))))
(let ((immediate-offset (- (* (+ instance-slots-offset 3) n-word-bytes)
instance-pointer-lowtag)))
(ecase *backend-byte-order*
(:big-endian (inst swc1
value-imag
lip
immediate-offset))
(:little-endian (inst swc1-odd
value-imag
lip
immediate-offset))))
(unless (location= result-imag value-imag)
(inst fmove :double result-imag value-imag)))))
|
8a7a41f1511cbbb225f2a50cd882ff2aaeb3b7abea0336cd06588aed788a26b3 | WormBase/wormbase_rest | molecular_details.clj | (ns rest-api.classes.variation.widgets.molecular-details
(:require
[datomic.api :as d]
[clojure.string :as str]
[rest-api.db.sequence :as seqdb]
[rest-api.classes.sequence.core :as sequence-fns]
[rest-api.classes.generic-fields :as generic]
[rest-api.classes.generic-functions :as generic-functions]
[pseudoace.utils :as pace-utils]
[rest-api.formatters.object :as obj :refer [pack-obj]]))
(defn- str-insert
"Insert c in string s at index i."
[s c i]
(str (subs s 0 i) c (subs s i)))
(defn- get-deletion-str [variation]
(or
(when-let [deletion (:variation.deletion/text
(:variation/deletion variation))]
(str/lower-case deletion))
(if-let [refseqobj (sequence-fns/genomic-obj variation)] ;WBVar00145789
(sequence-fns/get-sequence refseqobj))))
(defn- fetch-coords-in-feature [varrefseqobj object]
(when-let [refseqobj (sequence-fns/genomic-obj object)]
(if (and
(or (contains? object :cds/id)
(contains? object :pseudogene/id))
(= :locatable.strand/negative
(:locatable/strand object)))
{:fstart (:start refseqobj)
:fstop (:stop refseqobj)
:start (+ 1
(- (:stop refseqobj)
(:stop varrefseqobj)))
:stop (+ 1
(- (:stop refseqobj)
(:start varrefseqobj)))
:abs_start (:start varrefseqobj)
:abs_stop (:stop varrefseqobj)
:item (pack-obj object)}
{:fstart (:start refseqobj)
:fstop (:stop refseqobj)
:start (+ 1
(- (:start varrefseqobj)
(:start refseqobj)))
:stop (+ 1
(- (:stop varrefseqobj)
(:start refseqobj)))
:abs_start (:start varrefseqobj)
:abs_stop (:stop varrefseqobj)
:item (pack-obj object)})))
(defn- get-cgh-deleted-probes [variation]
(when-let [dp (:variation/cgh-deleted-probes variation)]
{:left_flank (:variation.cgh-deleted-probes/text-a dp)
:right_flank (:variation.cgh-deleted-probes/text-b dp)}))
(defn- get-cgh-flanking-probes [variation]
(when-let [fp (:variation/cgh-flanking-probes variation)]
{:left_flank (:variation.cgh-flanking-probes/text-a fp)
:right_flank (:variation.cgh-flanking-probes/text-b fp)}))
(defn- get-feature-affected-evidence [feature]
(if-let [rt (some (fn [[k v]] (if (= (name k) "text") v)) feature)]
(pace-utils/vmap
:evidence_type
(when-let [evidence-str (str/replace rt "*" "STOP")] evidence-str)
:evidence
(when (contains? feature :evidence/inferred-automatically)
"Inferred Automatically"))
(let [ev (obj/get-evidence feature)]
(not-empty
(pace-utils/vmap
:evidence_type
(some->> ev vals flatten first)
:evidence
(some->> ev keys first))))))
(defn- mutant-conceptual-translation [pseq position from to]
(str
(subs
pseq
0
(- (Integer/parseInt position) 1))
to
(subs
pseq
(- (+
(Integer/parseInt position)
(count from))
1))))
(defn- remove-from-end [s end]
(if (and (and (some? s) (some? end))
(.endsWith s end))
(.substring s 0 (- (count s)
(count end)))
s))
(defn- get-readthrough-obj [predicted-cds-holder cds]
(when (contains? (:molecular-change/vep-consequence predicted-cds-holder)
"stop_lost")
(let [description (when-let [t (some->> (:molecular-change/amino-acid-change predicted-cds-holder)
(map :molecular-change.amino-acid-change/text)
(first))]
(str/replace t "*" "STOP"))
[tmp-txt removed-aa added-aa] (re-matches #"(.*)/(.*)" description)
protein (:cds.corresponding-protein/protein
(:cds/corresponding-protein cds))
peptide (:protein.peptide/peptide
(:protein/peptide protein))
pseq (:peptide/sequence peptide)]
(conj
{:aa_change description
:mutant_start (str (- (count pseq)
(count removed-aa)))
:mutant_stop (str (- (+ (count pseq)
(count added-aa))
(count removed-aa)))
:wildtype_start (str (- (count pseq) (count removed-aa)))
:wildtype_stop (str (count pseq))
:description description
:protein (pack-obj protein)
:peptide (pack-obj peptide)
:wildtype_conceptual_translation pseq ;eg. WBVar00466445
:mutant_conceptual_translation (str (remove-from-end pseq removed-aa) added-aa)}
(get-feature-affected-evidence predicted-cds-holder)))))
(defn- get-nonsense-obj [predicted-cds-holder cds]
(when (contains? (:molecular-change/vep-consequence predicted-cds-holder)
"stop_gained")
(let [aa_change (when-let [t (some->> (:molecular-change/amino-acid-change predicted-cds-holder)
(map :molecular-change.amino-acid-change/text)
(first))]
(str/replace t "*" "STOP"))
from (last (re-matches #"(.*)/STOP" aa_change))
position (some->> (:molecular-change/protein-position predicted-cds-holder)
(map :molecular-change.protein-position/text)
(first))
protein (:cds.corresponding-protein/protein
(:cds/corresponding-protein cds))
peptide (:protein.peptide/peptide
(:protein/peptide protein))
pseq (:peptide/sequence peptide)]
(conj
{:aa_change (str from " to STOP")
:mutant_start position
:mutant_stop position
:wildtype_start position
:wildtype_stop (str (count pseq))
:description (str from " to stop (" position ")")
:protein (pack-obj protein)
:peptide (pack-obj peptide)
:wildtype_conceptual_translation pseq ;eg. WBVar00466445
:mutant_conceptual_translation (->> (Integer/parseInt position)
(dec)
(subs pseq 0)
(format "%s*"))}
(get-feature-affected-evidence predicted-cds-holder)))))
(defn- get-missense-obj [predicted-cds-holder cds]
(when (contains? (:molecular-change/vep-consequence predicted-cds-holder)
"missense_variant")
(let [description (some->> (:molecular-change/amino-acid-change predicted-cds-holder)
(map :molecular-change.amino-acid-change/text)
(first))
position (some->> (:molecular-change/protein-position predicted-cds-holder)
(map :molecular-change.protein-position/text)
(first))
[_ from to] (re-matches #"(.*)/(.*)" description)
protein (:cds.corresponding-protein/protein
(:cds/corresponding-protein cds))
peptide (:protein.peptide/peptide
(:protein/peptide protein))
pseq (:peptide/sequence peptide)]
(conj
{:aa_change (str from position to)
:position position
:from from
:to to
:mutant_start position
:mutant_stop position
:wildtype_start position
:wildtype_stop position
:description description
:protein (pack-obj protein)
:peptide (pack-obj peptide)
:wildtype_conceptual_translation pseq ; eg. WBVar01684110
:mutant_conceptual_translation (mutant-conceptual-translation pseq position from to)}
(get-feature-affected-evidence predicted-cds-holder)))))
(defn polymorphism-type [variation]
{:data (if (contains? variation :variation/snp)
(if (contains? variation :variation/reference-strain-digest)
"SNP and RFLP"
"SNP")
(when-let [insertion-str (:transposon-family/id
(first
(:variation/transposon-insertion variation)))]
(str insertion-str " transposon insertion" )))
:description "the general class of this polymorphism"})
(defn amino-acid-change [variation] ; e.g. WBVar00271007
{:data (some->> (:variation/transcript variation)
(map (fn [h]
(when-let [cds (some->> (:variation.transcript/transcript h)
(:transcript/corresponding-cds)
(:transcript.corresponding-cds/cds)
(pack-obj))]
{(:id cds)
{:amino_acid_change
(some->> (:molecular-change/amino-acid-change h)
(first)
(:molecular-change.amino-acid-change/text))
:transcript
cds}})))
(into {})
(vals))
:description "amino acid changes for this variation, if appropriate"})
(defn detection-method [variation] ; WBVar00601206
{:data (first (:variation/detection-method variation))
:description "detection method for polymorphism, typically via sequencing or restriction digest."})
e.g. WBVar00278357
{:data (some->> (:variation/deletion-verification variation)
(map (fn [h]
{:text (:variation.deletion-verification/text h)
:evidence (obj/get-evidence h)})))
:description "the method used to verify deletion alleles"})
;tested with: WBVar00750883,
(defn sequence-context [variation]
{:data (when-let [refseqobj (sequence-fns/genomic-obj variation)]
(let [max-seqlen 1000000
padding 500
flank-length 25
strand (if (= (:locatable/strand variation) :locatable.strand/negative) "-" "+")
seq-length (+ 1
(- (:stop refseqobj)
(:start refseqobj)))
refseqobj (if (and (= seq-length 1)
(and (contains? variation :variation/insertion)
(not (contains? variation :variation/deletion))))
(conj
refseqobj
{:start (+ 1 (:start refseqobj))
:stop (:stop refseqobj)})
refseqobj)
placeholder (when (> seq-length 1000000)
seq-length)
wildtype-sequence (when (nil? placeholder)
(sequence-fns/get-sequence
(conj
refseqobj
{:start (- (:start refseqobj) padding)
:stop (+ padding (:stop refseqobj))})))
wildtype-full-length (+ (* 2 padding)
seq-length)
length-change (if-let [insertion (:variation/insertion variation)]
(or (if-let [insertion-str (let [insertion (or (:variation.insertion/text insertion)
(or
(:transposon-family/id
(first
(:variation/transposon-insertion variation)))
"-"))]
(if (= insertion "Mos") "<Mos>" insertion))]
(if (contains? variation :variation/deletion)
(- (count insertion-str)
(count (get-deletion-str variation)))
(count insertion-str))
(if (contains? variation :variation/deletion)
(- 1 (count (get-deletion-str variation)))
(when (contains? variation :variation/transposon-insertion)
(- (count (:transposon-family/id
(first (:variation.transpon-insertion variation))))
1)))))
(if (contains? variation :variation/deletion)
(- 1 (count (get-deletion-str variation)))
(if-let [substitution (:variation/substitution variation)]
(- (count (:variation.substitution/alt substitution))
(count (:variation.substitution/ref substitution)))
(when (contains? variation :variation/tandem-duplication)
(- 1 seq-length)))))
cgh-deleted-probes (get-cgh-deleted-probes variation)
wildtype-positive (when (nil? placeholder)
{:sequence (if (and
(not (contains? variation :variation/deletion))
(or
(contains? variation :variation/insertion)
(contains? variation :variation/transpson-insertion)))
(str-insert wildtype-sequence
"-"
padding)
(apply str (map-indexed (fn [index val]
(if (and (>= index padding)
(<= index (- (+ padding
seq-length)
1)))
(str/upper-case val)
val))
wildtype-sequence)))
:features
(pace-utils/vmap
:variation {:type "variation"
:start (+ padding 1)
:stop (+ padding
seq-length)}
:left_cgh_deleted_flank (when cgh-deleted-probes
{:type "cgh_deleted_probe"
:start (+ padding 1)
:stop (+ padding
(count (:left_flank cgh-deleted-probes)))})
:left_flank {:type "flank"
:start (- (+ padding 1) flank-length)
:stop padding}
:right_flank {:type "flank"
:start (+ padding 1 seq-length)
:stop (+
padding
seq-length
flank-length)}
:right_cgh_deleted_flank (when cgh-deleted-probes
{:type "cgh_deleted_probe"
:start (- (+ padding 1 seq-length)
(count (:right_flank cgh-deleted-probes)))
:stop (+ padding seq-length)}))})
wildtype-negative (when (nil? placeholder)
{:sequence
(generic-functions/dna-reverse-complement (:sequence wildtype-positive))
:features
(:features wildtype-positive)})
mutant-positive (when (nil? placeholder)
{:sequence
(cond
(contains? variation :variation/substitution)
(let [substitution (:variation/substitution variation)
varseq (str/upper-case
(sequence-fns/get-sequence
(conj
refseqobj
{:start (:start refseqobj)
:stop (:stop refseqobj)})))
refseq (str/upper-case
(:variation.substitution/ref substitution))
altseq (str/upper-case
(:variation.substitution/alt substitution))
wildtype-seq (:sequence wildtype-positive)]
(str
(subs wildtype-seq 0 padding)
(cond
(= varseq refseq)
(str/upper-case altseq)
(= varseq (generic-functions/dna-reverse-complement refseq))
(str/upper-case (generic-functions/dna-reverse-complement altseq))
:else
(throw (Exception. "substitution/ref does not match either + or - strand")))
(subs wildtype-seq (+ padding (count varseq)))))
(and (contains? variation :variation/insertion)
(contains? variation :variation/deletion))
(let [insertion (:variation/insertion variation)
insert-str (or
(:variation.insertion/text insertion)
(or (:transposon-family/id
(first
(:variation/transposon-insertion variation))))
"-")]
(str/replace
(:sequence wildtype-positive)
#"[A-Z]+"
(if (str/includes? (:sequence wildtype-positive)
(str/upper-case (get-deletion-str variation)))
(str/upper-case insert-str)
(generic-functions/dna-reverse-complement
(str/upper-case
insert-str)))))
(contains? variation :variation/insertion)
(let [insertion (:variation/insertion variation)
insert-str (or (if-let [insert-value (:variation.insertion/text insertion)]
(if (= strand "+")
insert-value
(generic-functions/dna-reverse-complement insert-value)))
(or
(:transposon-family/id
(first
(:variation/transposon-insertion variation)))
"-"))]
(str/replace
(:sequence wildtype-positive)
#"\-+"
(if (= insert-str "Mos") "<Mos>" (str/upper-case insert-str))))
(or
(contains? variation :variation/deletion)
(contains? variation :variation/tandem-duplication))
(str/replace
(:sequence wildtype-positive)
#"[A-Z]+"
"-"))
:features
{:variation
{:type "variation"
:start (:start (:variation (:features wildtype-positive)))
:stop (if (and (contains? variation :variation/insertion)
(not (contains? variation :variation/deletion)))
(- (+ (:stop (:variation (:features wildtype-positive)))
length-change) 1)
(+ (:stop (:variation (:features wildtype-positive)))
length-change))}
:left_flank
(:left_flank (:features wildtype-positive))
:right_flank
{:type "flank"
:start (if (and (contains? variation :variation/insertion)
(not (contains? variation :variation/deletion)))
(- (+ (:start (:right_flank (:features wildtype-positive)))
length-change) 1)
(+ (:start (:right_flank (:features wildtype-positive)))
length-change))
:stop (if (and (contains? variation :variation/insertion)
(not (contains? variation :variation/deletion)))
(+ 1 (+ (:stop (:right_flank (:features wildtype-positive)))
length-change))
(+ (:stop (:right_flank (:features wildtype-positive)))
length-change))}}})
mutant-negative (when (nil? placeholder)
{:sequence
(if-let [transposon-family-str (let [transposon-family (:transposon-family/id
(first
(:variation/transposon-insertion variation)))]
(if (= transposon-family "Mos") "<Mos>" transposon-family))]
(str/replace
(generic-functions/dna-reverse-complement (:sequence mutant-positive))
(re-pattern (generic-functions/dna-reverse-complement transposon-family-str))
transposon-family-str)
(generic-functions/dna-reverse-complement (:sequence mutant-positive)))
:features
(:features mutant-positive)})
wildtype-positive-flattened (when (nil? placeholder)
{:sequence (:sequence wildtype-positive)
:features (sort-by
:start
(vals (:features wildtype-positive)))})
wildtype-negative-flattened (when (nil? placeholder)
{:sequence (:sequence wildtype-negative)
:features (sort-by
:start
(vals (:features wildtype-negative)))})
mutant-positive-flattened (when (nil? placeholder)
{:sequence (:sequence mutant-positive)
:features (sort-by
:start
(vals (:features mutant-positive)))})
mutant-negative-flattened (when (nil? placeholder)
{:sequence (:sequence mutant-negative)
:features (sort-by
:start
(vals (:features mutant-negative)))})
species (some->> (:species/assembly (:variation/species variation))
(map (fn [assembly]
(:strain/id (first (:sequence-collection/strain assembly))))))]
(when-not (every? nil? [wildtype-positive placeholder])
(pace-utils/vmap
:wildtype (not-empty
(pace-utils/vmap
:positive_strand wildtype-positive-flattened
:negative_strand wildtype-negative-flattened))
:mutant (not-empty
(pace-utils/vmap
:positive_strand mutant-positive-flattened
:negative_strand mutant-negative-flattened))
:public_name (:variation/public-name variation)
:placeholder placeholder))))
:description "wild type and variant sequences in genomic context"})
(defn flanking-pcr-products [variation] ; tested with WBVar00145789
{:data (some->> (:variation/pcr-product variation)
(map (fn [p]
{(:pcr-product/id p) (pack-obj p)}))
(apply merge))
:description "PCR products that flank the variation"})
test WBVar01112111
(defn variation-type [variation]
(let [variation-type-map {:variation/engineeered-allele "Engineered allele"
:variation/allele"Allele"
:variation/snp "SNP"
:variation/confirmed-snp "Confirmed SNP"
:variation/reference-strain-digest "RFLP"
:variation/predicted-snp "Predicted SNP"
:variation/transposon-insertion "Transposon Insertion"
:variation/natural-variant "Natural Variant"}
type-of-mutation-map {:variation/substitution "Substitution"
:variation/insertion "Insertion"
:variation/deletion "Deletion"
:variation/tandem-duplication "Tandem Duplication"}]
{:data {:physical_class (cond
(contains? variation :variation/transposon-insertion)
"Transposon insertion"
(contains? variation :variation/transposon-excision)
"Transposon excision"
:else
(->> type-of-mutation-map
(map
#(str (if
(contains? variation (first %))
(second %))))
(filter #(not= % ""))
(str/join "/")))
:general_class (->> variation-type-map
(map
#(str (if
(contains? variation (first %))
(second %))))
(filter #(not= % "")))}
:description "the general type of the variation"}))
test WBVar01112111 WBVar00601206
(defn features-affected [variation]
{:data (let [varrefseqobj (sequence-fns/genomic-obj variation)]
(pace-utils/vmap
checked with WBVar00274017
(when-let [s (:variation/mapping-target variation)]
[(conj
(pack-obj s)
(when (and (some? varrefseqobj)
(not= "MTCE" (:sequence/id s)))
(fetch-coords-in-feature varrefseqobj s)))])
"Chromosome"
(some->> (:variation/gene variation)
(map :variation.gene/gene)
(map (fn [g]
WBVar00274017
:gene/interpolated-map-position
:gene.interpolated-map-position/map)
(-> g ; WBVar00145789
:gene/map
:gene.map/map))))
(remove nil?)
(distinct)
(map (fn [chromosome-map]
(conj
(pack-obj chromosome-map)
{:item (pack-obj chromosome-map)})))
(not-empty))
tested with WBVar00274017
(some->> (:variation/gene variation)
(map-indexed
(fn [idx gh]
(let [gene (:variation.gene/gene gh)
obj (pack-obj gene)]
{:entry (+ idx 1)
:item obj
:id (:gene/id gene)
:label (:label obj)
:class "gene"
:taxonomy (:taxonomy obj)}))))
tested with WBVar01112111
(some->> (:variation/transcript variation)
(map (fn [predicted-cds-holder]
(when-let [cds (some->> (:variation.transcript/transcript predicted-cds-holder)
(:transcript/corresponding-cds)
(:transcript.corresponding-cds/cds))]
(let [missense-obj (get-missense-obj predicted-cds-holder cds)
nonsense-obj (get-nonsense-obj predicted-cds-holder cds)
readthrough-obj (get-readthrough-obj predicted-cds-holder cds)
cds-obj (or missense-obj
(or nonsense-obj
(select-keys readthrough-obj
[:from :to])))]
(conj
(pack-obj cds)
(when (some? varrefseqobj)
appears to a discreptency . This code gives 2945
(select-keys cds-obj [:wildtype_conceptual_translation
:mutant_conceptual_translation
:from
:to])
(pace-utils/vmap
:protein_effects
(not-empty
(pace-utils/vmap
tested with WBVar01112111
(when (= (first (:molecular-change/vep-consequence predicted-cds-holder) )
"synonymous_variant")
(when-let [aac (some->> (:molecular-change/amino-acid-change predicted-cds-holder)
(map :molecular-change.amino-acid-change/text)
(first))]
(let [position (some->> (:molecular-change/protein-position predicted-cds-holder)
(map :molecular-change.protein-position/text)
(first))]
{:description (str aac " (" position ")")})))
"Missense" ; eg. WBVar01684110
(when (some? missense-obj)
(select-keys missense-obj [:aa_change :evidence :evidence_type :from :to :wildtype_start :wildtype_stop :mutant_start :mutant_stop :position :description]))
"Nonsense" ; eg. WBVar00466445
(when (some? nonsense-obj)
(select-keys nonsense-obj [:aa_change :evidence :evidence_type :wildtype_start :wildtype_stop :mutant_start :mutant_stop :description]))
"Readthrough" ; eg. WBVar00215920
(when (some? readthrough-obj)
(select-keys readthrough-obj [:aa_change :evidence :evidence_type :wildtype_start :wildtype_stop :mutant_start :mutant_stop :description]))
e.g. WBVar00273213
(when-let [fs (first (:molecular-change/frameshift predicted-cds-holder))]
(conj
{:description (:molecular-change.frameshift/text fs)}
(get-feature-affected-evidence fs)))))
:location_effects
(not-empty
(pace-utils/vmap
tested with WBVar01112111
(when-let [ce (:molecular-change/coding-exon predicted-cds-holder)]
(get-feature-affected-evidence ce))
"Intron" ;tested with WBVar00271172
(when-let [i (:molecular-change/intron predicted-cds-holder)]
(get-feature-affected-evidence i))))))))))
(remove nil?))
"Transcript"
(some->> (:variation/transcript variation)
(map (fn [h]
(let [t (:variation.transcript/transcript h)]
(conj
(pack-obj t)
(when (some? varrefseqobj)
(fetch-coords-in-feature varrefseqobj t))
{:item
(pack-obj t)
:vep_consequence
(some-> (:molecular-change/vep-consequence h)
(first)
(str/replace "_" " "))
:vep_impact
(some->> (:molecular-change/vep-impact h)
(first)
(:molecular-change.vep-impact/text)
(str/lower-case))
:polyphen
(some->> (:molecular-change/polyphen h)
(first)
((fn [polyphen]
{:text (some-> (:molecular-change.polyphen/text polyphen)
(str/replace "_" " "))
:evidence {:PolyPhen_score (:molecular-change.polyphen/float polyphen)}})))
:sift
(some->> (:molecular-change/sift h)
(first)
((fn [sift]
{:text (some-> (:molecular-change.sift/text sift)
(str/replace "_" " "))
:evidence {:SIFT_score (:molecular-change.sift/float sift)}})))
:cds
(when (:molecular-change/cds-position h)
(some->> (:variation.transcript/transcript h)
(:transcript/corresponding-cds)
(:transcript.corresponding-cds/cds)
(pack-obj)))
:cds_position
(some->> (:molecular-change/cds-position h)
(first)
(:molecular-change.cds-position/text))
:cdna_position
(some->> (:molecular-change/cdna-position h)
(first)
(:molecular-change.cdna-position/text))
:protein_position
(some->> (:molecular-change/protein-position h)
(first)
(:molecular-change.protein-position/text))
:codon_change
(some->> (:molecular-change/codon-change h)
(first)
(:molecular-change.codon-change/text))
:amino_acid_change
(some->> (:molecular-change/amino-acid-change h)
(first)
(:molecular-change.amino-acid-change/text))
:exon_number
(some->> (:molecular-change/exon-number h)
(first)
(:molecular-change.exon-number/text))
:intron_number
(some->> (:molecular-change/intron-number h)
(first)
(:molecular-change.intron-number/text))
:hgvsc
(some->> (:molecular-change/hgvsc h)
(first)
(:molecular-change.hgvsc/text))
:hgvsp
(some->> (:molecular-change/hgvsp h)
(first)
(:molecular-change.hgvsp/text))
:location_effects
(not-empty
(pace-utils/vmap
:UTR_5
(get-feature-affected-evidence
(:molecular-change/five-prime-utr h))
:UTR_3
(get-feature-affected-evidence
(:molecular-change/three-prime-utr h))))})))))
"Pseudogene" ;tested with WBVar00601206
(some->> (:variation/pseudogene variation)
(map :variation.pseudogene/pseudogene)
(map (fn [pseudogene]
(when-let [refseqobj (sequence-fns/genomic-obj pseudogene)]
(conj
(pack-obj pseudogene)
(when (some? varrefseqobj)
(fetch-coords-in-feature varrefseqobj pseudogene))
{:item (pack-obj pseudogene)})))))
"Interactor"
(some->> (:interaction.variation-interactor/_variation variation)
(map :interaction/_variation-interactor)
(map (fn [i]
(let [obj (pack-obj i)]
(conj
obj
{:item obj})))))))
:description "genomic features affected by this variation"})
(defn cgh-deleted-probes [variation] ; tested with WBVar00601206
{:data (get-cgh-deleted-probes variation)
:description "probes used for CGH of deletion alleles"})
(defn cgh-flanking-probes [variation] ; WBVar00601206
{:data (get-cgh-flanking-probes variation)
:desciption "probes used for CGH of deletion alleles"})
(defn polymorphism-assays [variation]; WBVar00597552
{:data (some->> (:variation/pcr-product variation)
(map (fn [pcr]
{(:pcr-product/id pcr)
(let [ohs (:pcr-product/oligo pcr)
first-ohs-id (:id (pack-obj (:pcr-product.oligo/oligo (first ohs))))
[left-oh right-oh] (if (nil? first-ohs-id)
[nil nil]
(if (str/ends-with? first-ohs-id "_b")
[(second ohs) (first ohs)]
[(first ohs) (second ohs)]))]
{:pcr_product
(conj
(pack-obj pcr)
{:pcr_conditions nil ; from pcr-product/assay-conditions non found
:dna nil ;non found
:left_oligo (-> left-oh :pcr-product.oligo/oligo :oligo/sequence)
:right_oligo (-> right-oh :pcr-product.oligo/oligo :oligo/sequence)})
:assay_type (if (contains? (-> ohs first :pcr-product.oligo/oligo) :oligo/sequence)
"sequence")})}))
(apply merge))
:description "experimental assays for detecting this polymorphism"})
(defn affects-splice-site [variation] ; made from WBVar00750883
{:data (some->> (:variation/transcript variation)
(map (fn [h]
(let [t (:variation.transcript/transcript h)
consequence (some-> (:molecular-change/vep-consequence h)
(first)
(str/replace "_" " "))
hgvsc (some->> (:molecular-change/hgvsc h)
(first)
(:molecular-change.hgvsc/text))]
(not-empty
(pace-utils/vmap
:donor
(when (= consequence "splice donor variant") hgvsc)
:acceptor
(when (= consequence "splice acceptor variant")
hgvsc))))))
(remove nil?)
(first)
(not-empty))
:description "Affects splice site"})
WBVar00116162 is predicted
{:data (if (contains? variation :variation/confirmed-snp)
"confirmed"
(if (or (contains? variation :variation/snp)
(or (contains? variation :variation/reference-strain-digest)
(contains? variation :variation/transposon-insertion)))
"predicted"))
:description "experimental status of this polymorphism"})
(defn- pack-nulcleotide-change-obj [type-str wildtype mutant]
{:type type-str
:wildtype wildtype
:mutant mutant
:wildtype-label "wildtype"
:mutant-label "variant"})
(defn- variation-features [variation]
(if-let [species-name (->> variation :variation/species :species/id)]
(let [g-species (generic-functions/xform-species-name species-name)
sequence-database (seqdb/get-default-sequence-database g-species)
db-spec ((keyword sequence-database) seqdb/sequence-dbs)
variation-id (:variation/id variation)]
(if sequence-database
(seqdb/variation-features db-spec variation-id)))))
WBVar00116162 substitution
(remove nil?
[(when-let [insertion (or (:variation/insertion variation)
(:variation/transposon-insertion variation))] ; tested with WBVar00269113
{:mutant (or (:variation.insertion/text
(:variation/insertion variation))
(:transposon-family/id
(first
(:variation/transposon-insertion variation))))
:mutant_label "variant"
:wildtype_label "wild type"
:type "Insertion"
:wildtype ""})
(when-let [deletion (:variation/deletion variation)] ;eg WBVar00601206
(if (contains? variation :variation/cgh-deleted-probes)
{:type "Definition Deletion" ; eg WBVar00601206
:mutant ""
:wildtype (if-let [refseqobj (sequence-fns/genomic-obj variation)]
(sequence-fns/get-sequence refseqobj))}
eg
:mutant_label "variant"
:mutant ""
:wildtype_label "wild type"
:wildtype (get-deletion-str variation)}))
e.g. tested with WBVar00274017
(if-let [refseqobj (sequence-fns/genomic-obj variation)]
(let [varseq (str/lower-case (sequence-fns/get-sequence
(conj
refseqobj
{:start (:start refseqobj)
:stop (:stop refseqobj)})))]
(cond
(= varseq (str/lower-case
(:variation.substitution/ref substitution)))
{:mutant (:variation.substitution/alt substitution)
:wildtype (:variation.substitution/ref substitution)
:mutant_label "variant"
:wildtype_label "wild type"
:type "Substitution"}
(= varseq (str/lower-case
(generic-functions/dna-reverse-complement
(:variation.substitution/ref substitution))))
{:mutant (generic-functions/dna-reverse-complement (:variation.substitution/alt substitution))
:wildtype (generic-functions/dna-reverse-complement (:variation.substitution/ref substitution))
:mutant_label "variant"
:wildtype_label "wild type"
:type "Substitution"}
:else
(throw (Exception. "substution/ref does not match either + or - strand"))))))]))
(defn nucleotide-change [variation]
{:data (compile-nucleotide-changes variation)
:description "raw nucleotide changes for this variation"})
;tested with WBVar00101112
(defn reference-strain [variation]
{:data (some->> (:variation/strain variation)
(map :variation.strain/strain)
(map pack-obj)
(sort-by :label))
:description "strains that this variant has been observed in"})
e.g. WBVar01943248 this does not work on Ace version
{:data (some->> (:variation/transcript variation)
(map (fn [h]
(let [consequence (some-> (:molecular-change/vep-consequence h)
(first)
(str/replace "_" " "))]
(not-empty
(when (= consequence "frameshift variant")
(some->> (:molecular-change/amino-acid-change h)
(first)
(:molecular-change.amino-acid-change/text)))))))
(remove nil?)
(first)
(not-empty))
:description "A variation that alters the reading frame"})
(defn sequencing-status [variation]
{:data (when-let [seqstatus (:variation/seqstatus variation)]
(obj/humanize-ident (name seqstatus)))
:description "sequencing status of the variation"})
(def widget
{:name generic/name-field
:polymorphism_type polymorphism-type
:amino_acid_change amino-acid-change
:detection_method detection-method
:deletion_verification deletion-verification
:sequence_context sequence-context
:flanking_pcr_products flanking-pcr-products
:variation_type variation-type
:features_affected features-affected
:cgh_deleted_probes cgh-deleted-probes
:cgh_flanking_probes cgh-flanking-probes
:polymorphism_assays polymorphism-assays
:affects_splice_site affects-splice-site
:polymorphism_status polymorphism-status
:nucleotide_change nucleotide-change
:reference_strain reference-strain
:causes_frameshift causes-frameshift
:sequencing_status sequencing-status})
| null | https://raw.githubusercontent.com/WormBase/wormbase_rest/32120f597b9493ddd9786d7c89b442478e98b07e/src/rest_api/classes/variation/widgets/molecular_details.clj | clojure | WBVar00145789
eg. WBVar00466445
eg. WBVar00466445
eg. WBVar01684110
e.g. WBVar00271007
WBVar00601206
tested with: WBVar00750883,
tested with WBVar00145789
WBVar00145789
eg. WBVar01684110
eg. WBVar00466445
eg. WBVar00215920
tested with WBVar00271172
tested with WBVar00601206
tested with WBVar00601206
WBVar00601206
WBVar00597552
from pcr-product/assay-conditions non found
non found
made from WBVar00750883
tested with WBVar00269113
eg WBVar00601206
eg WBVar00601206
tested with WBVar00101112 | (ns rest-api.classes.variation.widgets.molecular-details
(:require
[datomic.api :as d]
[clojure.string :as str]
[rest-api.db.sequence :as seqdb]
[rest-api.classes.sequence.core :as sequence-fns]
[rest-api.classes.generic-fields :as generic]
[rest-api.classes.generic-functions :as generic-functions]
[pseudoace.utils :as pace-utils]
[rest-api.formatters.object :as obj :refer [pack-obj]]))
(defn- str-insert
"Insert c in string s at index i."
[s c i]
(str (subs s 0 i) c (subs s i)))
(defn- get-deletion-str [variation]
(or
(when-let [deletion (:variation.deletion/text
(:variation/deletion variation))]
(str/lower-case deletion))
(sequence-fns/get-sequence refseqobj))))
(defn- fetch-coords-in-feature [varrefseqobj object]
(when-let [refseqobj (sequence-fns/genomic-obj object)]
(if (and
(or (contains? object :cds/id)
(contains? object :pseudogene/id))
(= :locatable.strand/negative
(:locatable/strand object)))
{:fstart (:start refseqobj)
:fstop (:stop refseqobj)
:start (+ 1
(- (:stop refseqobj)
(:stop varrefseqobj)))
:stop (+ 1
(- (:stop refseqobj)
(:start varrefseqobj)))
:abs_start (:start varrefseqobj)
:abs_stop (:stop varrefseqobj)
:item (pack-obj object)}
{:fstart (:start refseqobj)
:fstop (:stop refseqobj)
:start (+ 1
(- (:start varrefseqobj)
(:start refseqobj)))
:stop (+ 1
(- (:stop varrefseqobj)
(:start refseqobj)))
:abs_start (:start varrefseqobj)
:abs_stop (:stop varrefseqobj)
:item (pack-obj object)})))
(defn- get-cgh-deleted-probes [variation]
(when-let [dp (:variation/cgh-deleted-probes variation)]
{:left_flank (:variation.cgh-deleted-probes/text-a dp)
:right_flank (:variation.cgh-deleted-probes/text-b dp)}))
(defn- get-cgh-flanking-probes [variation]
(when-let [fp (:variation/cgh-flanking-probes variation)]
{:left_flank (:variation.cgh-flanking-probes/text-a fp)
:right_flank (:variation.cgh-flanking-probes/text-b fp)}))
(defn- get-feature-affected-evidence [feature]
(if-let [rt (some (fn [[k v]] (if (= (name k) "text") v)) feature)]
(pace-utils/vmap
:evidence_type
(when-let [evidence-str (str/replace rt "*" "STOP")] evidence-str)
:evidence
(when (contains? feature :evidence/inferred-automatically)
"Inferred Automatically"))
(let [ev (obj/get-evidence feature)]
(not-empty
(pace-utils/vmap
:evidence_type
(some->> ev vals flatten first)
:evidence
(some->> ev keys first))))))
(defn- mutant-conceptual-translation [pseq position from to]
(str
(subs
pseq
0
(- (Integer/parseInt position) 1))
to
(subs
pseq
(- (+
(Integer/parseInt position)
(count from))
1))))
(defn- remove-from-end [s end]
(if (and (and (some? s) (some? end))
(.endsWith s end))
(.substring s 0 (- (count s)
(count end)))
s))
(defn- get-readthrough-obj [predicted-cds-holder cds]
(when (contains? (:molecular-change/vep-consequence predicted-cds-holder)
"stop_lost")
(let [description (when-let [t (some->> (:molecular-change/amino-acid-change predicted-cds-holder)
(map :molecular-change.amino-acid-change/text)
(first))]
(str/replace t "*" "STOP"))
[tmp-txt removed-aa added-aa] (re-matches #"(.*)/(.*)" description)
protein (:cds.corresponding-protein/protein
(:cds/corresponding-protein cds))
peptide (:protein.peptide/peptide
(:protein/peptide protein))
pseq (:peptide/sequence peptide)]
(conj
{:aa_change description
:mutant_start (str (- (count pseq)
(count removed-aa)))
:mutant_stop (str (- (+ (count pseq)
(count added-aa))
(count removed-aa)))
:wildtype_start (str (- (count pseq) (count removed-aa)))
:wildtype_stop (str (count pseq))
:description description
:protein (pack-obj protein)
:peptide (pack-obj peptide)
:mutant_conceptual_translation (str (remove-from-end pseq removed-aa) added-aa)}
(get-feature-affected-evidence predicted-cds-holder)))))
(defn- get-nonsense-obj [predicted-cds-holder cds]
(when (contains? (:molecular-change/vep-consequence predicted-cds-holder)
"stop_gained")
(let [aa_change (when-let [t (some->> (:molecular-change/amino-acid-change predicted-cds-holder)
(map :molecular-change.amino-acid-change/text)
(first))]
(str/replace t "*" "STOP"))
from (last (re-matches #"(.*)/STOP" aa_change))
position (some->> (:molecular-change/protein-position predicted-cds-holder)
(map :molecular-change.protein-position/text)
(first))
protein (:cds.corresponding-protein/protein
(:cds/corresponding-protein cds))
peptide (:protein.peptide/peptide
(:protein/peptide protein))
pseq (:peptide/sequence peptide)]
(conj
{:aa_change (str from " to STOP")
:mutant_start position
:mutant_stop position
:wildtype_start position
:wildtype_stop (str (count pseq))
:description (str from " to stop (" position ")")
:protein (pack-obj protein)
:peptide (pack-obj peptide)
:mutant_conceptual_translation (->> (Integer/parseInt position)
(dec)
(subs pseq 0)
(format "%s*"))}
(get-feature-affected-evidence predicted-cds-holder)))))
(defn- get-missense-obj [predicted-cds-holder cds]
(when (contains? (:molecular-change/vep-consequence predicted-cds-holder)
"missense_variant")
(let [description (some->> (:molecular-change/amino-acid-change predicted-cds-holder)
(map :molecular-change.amino-acid-change/text)
(first))
position (some->> (:molecular-change/protein-position predicted-cds-holder)
(map :molecular-change.protein-position/text)
(first))
[_ from to] (re-matches #"(.*)/(.*)" description)
protein (:cds.corresponding-protein/protein
(:cds/corresponding-protein cds))
peptide (:protein.peptide/peptide
(:protein/peptide protein))
pseq (:peptide/sequence peptide)]
(conj
{:aa_change (str from position to)
:position position
:from from
:to to
:mutant_start position
:mutant_stop position
:wildtype_start position
:wildtype_stop position
:description description
:protein (pack-obj protein)
:peptide (pack-obj peptide)
:mutant_conceptual_translation (mutant-conceptual-translation pseq position from to)}
(get-feature-affected-evidence predicted-cds-holder)))))
(defn polymorphism-type [variation]
{:data (if (contains? variation :variation/snp)
(if (contains? variation :variation/reference-strain-digest)
"SNP and RFLP"
"SNP")
(when-let [insertion-str (:transposon-family/id
(first
(:variation/transposon-insertion variation)))]
(str insertion-str " transposon insertion" )))
:description "the general class of this polymorphism"})
{:data (some->> (:variation/transcript variation)
(map (fn [h]
(when-let [cds (some->> (:variation.transcript/transcript h)
(:transcript/corresponding-cds)
(:transcript.corresponding-cds/cds)
(pack-obj))]
{(:id cds)
{:amino_acid_change
(some->> (:molecular-change/amino-acid-change h)
(first)
(:molecular-change.amino-acid-change/text))
:transcript
cds}})))
(into {})
(vals))
:description "amino acid changes for this variation, if appropriate"})
{:data (first (:variation/detection-method variation))
:description "detection method for polymorphism, typically via sequencing or restriction digest."})
e.g. WBVar00278357
{:data (some->> (:variation/deletion-verification variation)
(map (fn [h]
{:text (:variation.deletion-verification/text h)
:evidence (obj/get-evidence h)})))
:description "the method used to verify deletion alleles"})
(defn sequence-context [variation]
{:data (when-let [refseqobj (sequence-fns/genomic-obj variation)]
(let [max-seqlen 1000000
padding 500
flank-length 25
strand (if (= (:locatable/strand variation) :locatable.strand/negative) "-" "+")
seq-length (+ 1
(- (:stop refseqobj)
(:start refseqobj)))
refseqobj (if (and (= seq-length 1)
(and (contains? variation :variation/insertion)
(not (contains? variation :variation/deletion))))
(conj
refseqobj
{:start (+ 1 (:start refseqobj))
:stop (:stop refseqobj)})
refseqobj)
placeholder (when (> seq-length 1000000)
seq-length)
wildtype-sequence (when (nil? placeholder)
(sequence-fns/get-sequence
(conj
refseqobj
{:start (- (:start refseqobj) padding)
:stop (+ padding (:stop refseqobj))})))
wildtype-full-length (+ (* 2 padding)
seq-length)
length-change (if-let [insertion (:variation/insertion variation)]
(or (if-let [insertion-str (let [insertion (or (:variation.insertion/text insertion)
(or
(:transposon-family/id
(first
(:variation/transposon-insertion variation)))
"-"))]
(if (= insertion "Mos") "<Mos>" insertion))]
(if (contains? variation :variation/deletion)
(- (count insertion-str)
(count (get-deletion-str variation)))
(count insertion-str))
(if (contains? variation :variation/deletion)
(- 1 (count (get-deletion-str variation)))
(when (contains? variation :variation/transposon-insertion)
(- (count (:transposon-family/id
(first (:variation.transpon-insertion variation))))
1)))))
(if (contains? variation :variation/deletion)
(- 1 (count (get-deletion-str variation)))
(if-let [substitution (:variation/substitution variation)]
(- (count (:variation.substitution/alt substitution))
(count (:variation.substitution/ref substitution)))
(when (contains? variation :variation/tandem-duplication)
(- 1 seq-length)))))
cgh-deleted-probes (get-cgh-deleted-probes variation)
wildtype-positive (when (nil? placeholder)
{:sequence (if (and
(not (contains? variation :variation/deletion))
(or
(contains? variation :variation/insertion)
(contains? variation :variation/transpson-insertion)))
(str-insert wildtype-sequence
"-"
padding)
(apply str (map-indexed (fn [index val]
(if (and (>= index padding)
(<= index (- (+ padding
seq-length)
1)))
(str/upper-case val)
val))
wildtype-sequence)))
:features
(pace-utils/vmap
:variation {:type "variation"
:start (+ padding 1)
:stop (+ padding
seq-length)}
:left_cgh_deleted_flank (when cgh-deleted-probes
{:type "cgh_deleted_probe"
:start (+ padding 1)
:stop (+ padding
(count (:left_flank cgh-deleted-probes)))})
:left_flank {:type "flank"
:start (- (+ padding 1) flank-length)
:stop padding}
:right_flank {:type "flank"
:start (+ padding 1 seq-length)
:stop (+
padding
seq-length
flank-length)}
:right_cgh_deleted_flank (when cgh-deleted-probes
{:type "cgh_deleted_probe"
:start (- (+ padding 1 seq-length)
(count (:right_flank cgh-deleted-probes)))
:stop (+ padding seq-length)}))})
wildtype-negative (when (nil? placeholder)
{:sequence
(generic-functions/dna-reverse-complement (:sequence wildtype-positive))
:features
(:features wildtype-positive)})
mutant-positive (when (nil? placeholder)
{:sequence
(cond
(contains? variation :variation/substitution)
(let [substitution (:variation/substitution variation)
varseq (str/upper-case
(sequence-fns/get-sequence
(conj
refseqobj
{:start (:start refseqobj)
:stop (:stop refseqobj)})))
refseq (str/upper-case
(:variation.substitution/ref substitution))
altseq (str/upper-case
(:variation.substitution/alt substitution))
wildtype-seq (:sequence wildtype-positive)]
(str
(subs wildtype-seq 0 padding)
(cond
(= varseq refseq)
(str/upper-case altseq)
(= varseq (generic-functions/dna-reverse-complement refseq))
(str/upper-case (generic-functions/dna-reverse-complement altseq))
:else
(throw (Exception. "substitution/ref does not match either + or - strand")))
(subs wildtype-seq (+ padding (count varseq)))))
(and (contains? variation :variation/insertion)
(contains? variation :variation/deletion))
(let [insertion (:variation/insertion variation)
insert-str (or
(:variation.insertion/text insertion)
(or (:transposon-family/id
(first
(:variation/transposon-insertion variation))))
"-")]
(str/replace
(:sequence wildtype-positive)
#"[A-Z]+"
(if (str/includes? (:sequence wildtype-positive)
(str/upper-case (get-deletion-str variation)))
(str/upper-case insert-str)
(generic-functions/dna-reverse-complement
(str/upper-case
insert-str)))))
(contains? variation :variation/insertion)
(let [insertion (:variation/insertion variation)
insert-str (or (if-let [insert-value (:variation.insertion/text insertion)]
(if (= strand "+")
insert-value
(generic-functions/dna-reverse-complement insert-value)))
(or
(:transposon-family/id
(first
(:variation/transposon-insertion variation)))
"-"))]
(str/replace
(:sequence wildtype-positive)
#"\-+"
(if (= insert-str "Mos") "<Mos>" (str/upper-case insert-str))))
(or
(contains? variation :variation/deletion)
(contains? variation :variation/tandem-duplication))
(str/replace
(:sequence wildtype-positive)
#"[A-Z]+"
"-"))
:features
{:variation
{:type "variation"
:start (:start (:variation (:features wildtype-positive)))
:stop (if (and (contains? variation :variation/insertion)
(not (contains? variation :variation/deletion)))
(- (+ (:stop (:variation (:features wildtype-positive)))
length-change) 1)
(+ (:stop (:variation (:features wildtype-positive)))
length-change))}
:left_flank
(:left_flank (:features wildtype-positive))
:right_flank
{:type "flank"
:start (if (and (contains? variation :variation/insertion)
(not (contains? variation :variation/deletion)))
(- (+ (:start (:right_flank (:features wildtype-positive)))
length-change) 1)
(+ (:start (:right_flank (:features wildtype-positive)))
length-change))
:stop (if (and (contains? variation :variation/insertion)
(not (contains? variation :variation/deletion)))
(+ 1 (+ (:stop (:right_flank (:features wildtype-positive)))
length-change))
(+ (:stop (:right_flank (:features wildtype-positive)))
length-change))}}})
mutant-negative (when (nil? placeholder)
{:sequence
(if-let [transposon-family-str (let [transposon-family (:transposon-family/id
(first
(:variation/transposon-insertion variation)))]
(if (= transposon-family "Mos") "<Mos>" transposon-family))]
(str/replace
(generic-functions/dna-reverse-complement (:sequence mutant-positive))
(re-pattern (generic-functions/dna-reverse-complement transposon-family-str))
transposon-family-str)
(generic-functions/dna-reverse-complement (:sequence mutant-positive)))
:features
(:features mutant-positive)})
wildtype-positive-flattened (when (nil? placeholder)
{:sequence (:sequence wildtype-positive)
:features (sort-by
:start
(vals (:features wildtype-positive)))})
wildtype-negative-flattened (when (nil? placeholder)
{:sequence (:sequence wildtype-negative)
:features (sort-by
:start
(vals (:features wildtype-negative)))})
mutant-positive-flattened (when (nil? placeholder)
{:sequence (:sequence mutant-positive)
:features (sort-by
:start
(vals (:features mutant-positive)))})
mutant-negative-flattened (when (nil? placeholder)
{:sequence (:sequence mutant-negative)
:features (sort-by
:start
(vals (:features mutant-negative)))})
species (some->> (:species/assembly (:variation/species variation))
(map (fn [assembly]
(:strain/id (first (:sequence-collection/strain assembly))))))]
(when-not (every? nil? [wildtype-positive placeholder])
(pace-utils/vmap
:wildtype (not-empty
(pace-utils/vmap
:positive_strand wildtype-positive-flattened
:negative_strand wildtype-negative-flattened))
:mutant (not-empty
(pace-utils/vmap
:positive_strand mutant-positive-flattened
:negative_strand mutant-negative-flattened))
:public_name (:variation/public-name variation)
:placeholder placeholder))))
:description "wild type and variant sequences in genomic context"})
{:data (some->> (:variation/pcr-product variation)
(map (fn [p]
{(:pcr-product/id p) (pack-obj p)}))
(apply merge))
:description "PCR products that flank the variation"})
test WBVar01112111
(defn variation-type [variation]
(let [variation-type-map {:variation/engineeered-allele "Engineered allele"
:variation/allele"Allele"
:variation/snp "SNP"
:variation/confirmed-snp "Confirmed SNP"
:variation/reference-strain-digest "RFLP"
:variation/predicted-snp "Predicted SNP"
:variation/transposon-insertion "Transposon Insertion"
:variation/natural-variant "Natural Variant"}
type-of-mutation-map {:variation/substitution "Substitution"
:variation/insertion "Insertion"
:variation/deletion "Deletion"
:variation/tandem-duplication "Tandem Duplication"}]
{:data {:physical_class (cond
(contains? variation :variation/transposon-insertion)
"Transposon insertion"
(contains? variation :variation/transposon-excision)
"Transposon excision"
:else
(->> type-of-mutation-map
(map
#(str (if
(contains? variation (first %))
(second %))))
(filter #(not= % ""))
(str/join "/")))
:general_class (->> variation-type-map
(map
#(str (if
(contains? variation (first %))
(second %))))
(filter #(not= % "")))}
:description "the general type of the variation"}))
test WBVar01112111 WBVar00601206
(defn features-affected [variation]
{:data (let [varrefseqobj (sequence-fns/genomic-obj variation)]
(pace-utils/vmap
checked with WBVar00274017
(when-let [s (:variation/mapping-target variation)]
[(conj
(pack-obj s)
(when (and (some? varrefseqobj)
(not= "MTCE" (:sequence/id s)))
(fetch-coords-in-feature varrefseqobj s)))])
"Chromosome"
(some->> (:variation/gene variation)
(map :variation.gene/gene)
(map (fn [g]
WBVar00274017
:gene/interpolated-map-position
:gene.interpolated-map-position/map)
:gene/map
:gene.map/map))))
(remove nil?)
(distinct)
(map (fn [chromosome-map]
(conj
(pack-obj chromosome-map)
{:item (pack-obj chromosome-map)})))
(not-empty))
tested with WBVar00274017
(some->> (:variation/gene variation)
(map-indexed
(fn [idx gh]
(let [gene (:variation.gene/gene gh)
obj (pack-obj gene)]
{:entry (+ idx 1)
:item obj
:id (:gene/id gene)
:label (:label obj)
:class "gene"
:taxonomy (:taxonomy obj)}))))
tested with WBVar01112111
(some->> (:variation/transcript variation)
(map (fn [predicted-cds-holder]
(when-let [cds (some->> (:variation.transcript/transcript predicted-cds-holder)
(:transcript/corresponding-cds)
(:transcript.corresponding-cds/cds))]
(let [missense-obj (get-missense-obj predicted-cds-holder cds)
nonsense-obj (get-nonsense-obj predicted-cds-holder cds)
readthrough-obj (get-readthrough-obj predicted-cds-holder cds)
cds-obj (or missense-obj
(or nonsense-obj
(select-keys readthrough-obj
[:from :to])))]
(conj
(pack-obj cds)
(when (some? varrefseqobj)
appears to a discreptency . This code gives 2945
(select-keys cds-obj [:wildtype_conceptual_translation
:mutant_conceptual_translation
:from
:to])
(pace-utils/vmap
:protein_effects
(not-empty
(pace-utils/vmap
tested with WBVar01112111
(when (= (first (:molecular-change/vep-consequence predicted-cds-holder) )
"synonymous_variant")
(when-let [aac (some->> (:molecular-change/amino-acid-change predicted-cds-holder)
(map :molecular-change.amino-acid-change/text)
(first))]
(let [position (some->> (:molecular-change/protein-position predicted-cds-holder)
(map :molecular-change.protein-position/text)
(first))]
{:description (str aac " (" position ")")})))
(when (some? missense-obj)
(select-keys missense-obj [:aa_change :evidence :evidence_type :from :to :wildtype_start :wildtype_stop :mutant_start :mutant_stop :position :description]))
(when (some? nonsense-obj)
(select-keys nonsense-obj [:aa_change :evidence :evidence_type :wildtype_start :wildtype_stop :mutant_start :mutant_stop :description]))
(when (some? readthrough-obj)
(select-keys readthrough-obj [:aa_change :evidence :evidence_type :wildtype_start :wildtype_stop :mutant_start :mutant_stop :description]))
e.g. WBVar00273213
(when-let [fs (first (:molecular-change/frameshift predicted-cds-holder))]
(conj
{:description (:molecular-change.frameshift/text fs)}
(get-feature-affected-evidence fs)))))
:location_effects
(not-empty
(pace-utils/vmap
tested with WBVar01112111
(when-let [ce (:molecular-change/coding-exon predicted-cds-holder)]
(get-feature-affected-evidence ce))
(when-let [i (:molecular-change/intron predicted-cds-holder)]
(get-feature-affected-evidence i))))))))))
(remove nil?))
"Transcript"
(some->> (:variation/transcript variation)
(map (fn [h]
(let [t (:variation.transcript/transcript h)]
(conj
(pack-obj t)
(when (some? varrefseqobj)
(fetch-coords-in-feature varrefseqobj t))
{:item
(pack-obj t)
:vep_consequence
(some-> (:molecular-change/vep-consequence h)
(first)
(str/replace "_" " "))
:vep_impact
(some->> (:molecular-change/vep-impact h)
(first)
(:molecular-change.vep-impact/text)
(str/lower-case))
:polyphen
(some->> (:molecular-change/polyphen h)
(first)
((fn [polyphen]
{:text (some-> (:molecular-change.polyphen/text polyphen)
(str/replace "_" " "))
:evidence {:PolyPhen_score (:molecular-change.polyphen/float polyphen)}})))
:sift
(some->> (:molecular-change/sift h)
(first)
((fn [sift]
{:text (some-> (:molecular-change.sift/text sift)
(str/replace "_" " "))
:evidence {:SIFT_score (:molecular-change.sift/float sift)}})))
:cds
(when (:molecular-change/cds-position h)
(some->> (:variation.transcript/transcript h)
(:transcript/corresponding-cds)
(:transcript.corresponding-cds/cds)
(pack-obj)))
:cds_position
(some->> (:molecular-change/cds-position h)
(first)
(:molecular-change.cds-position/text))
:cdna_position
(some->> (:molecular-change/cdna-position h)
(first)
(:molecular-change.cdna-position/text))
:protein_position
(some->> (:molecular-change/protein-position h)
(first)
(:molecular-change.protein-position/text))
:codon_change
(some->> (:molecular-change/codon-change h)
(first)
(:molecular-change.codon-change/text))
:amino_acid_change
(some->> (:molecular-change/amino-acid-change h)
(first)
(:molecular-change.amino-acid-change/text))
:exon_number
(some->> (:molecular-change/exon-number h)
(first)
(:molecular-change.exon-number/text))
:intron_number
(some->> (:molecular-change/intron-number h)
(first)
(:molecular-change.intron-number/text))
:hgvsc
(some->> (:molecular-change/hgvsc h)
(first)
(:molecular-change.hgvsc/text))
:hgvsp
(some->> (:molecular-change/hgvsp h)
(first)
(:molecular-change.hgvsp/text))
:location_effects
(not-empty
(pace-utils/vmap
:UTR_5
(get-feature-affected-evidence
(:molecular-change/five-prime-utr h))
:UTR_3
(get-feature-affected-evidence
(:molecular-change/three-prime-utr h))))})))))
(some->> (:variation/pseudogene variation)
(map :variation.pseudogene/pseudogene)
(map (fn [pseudogene]
(when-let [refseqobj (sequence-fns/genomic-obj pseudogene)]
(conj
(pack-obj pseudogene)
(when (some? varrefseqobj)
(fetch-coords-in-feature varrefseqobj pseudogene))
{:item (pack-obj pseudogene)})))))
"Interactor"
(some->> (:interaction.variation-interactor/_variation variation)
(map :interaction/_variation-interactor)
(map (fn [i]
(let [obj (pack-obj i)]
(conj
obj
{:item obj})))))))
:description "genomic features affected by this variation"})
{:data (get-cgh-deleted-probes variation)
:description "probes used for CGH of deletion alleles"})
{:data (get-cgh-flanking-probes variation)
:desciption "probes used for CGH of deletion alleles"})
{:data (some->> (:variation/pcr-product variation)
(map (fn [pcr]
{(:pcr-product/id pcr)
(let [ohs (:pcr-product/oligo pcr)
first-ohs-id (:id (pack-obj (:pcr-product.oligo/oligo (first ohs))))
[left-oh right-oh] (if (nil? first-ohs-id)
[nil nil]
(if (str/ends-with? first-ohs-id "_b")
[(second ohs) (first ohs)]
[(first ohs) (second ohs)]))]
{:pcr_product
(conj
(pack-obj pcr)
:left_oligo (-> left-oh :pcr-product.oligo/oligo :oligo/sequence)
:right_oligo (-> right-oh :pcr-product.oligo/oligo :oligo/sequence)})
:assay_type (if (contains? (-> ohs first :pcr-product.oligo/oligo) :oligo/sequence)
"sequence")})}))
(apply merge))
:description "experimental assays for detecting this polymorphism"})
{:data (some->> (:variation/transcript variation)
(map (fn [h]
(let [t (:variation.transcript/transcript h)
consequence (some-> (:molecular-change/vep-consequence h)
(first)
(str/replace "_" " "))
hgvsc (some->> (:molecular-change/hgvsc h)
(first)
(:molecular-change.hgvsc/text))]
(not-empty
(pace-utils/vmap
:donor
(when (= consequence "splice donor variant") hgvsc)
:acceptor
(when (= consequence "splice acceptor variant")
hgvsc))))))
(remove nil?)
(first)
(not-empty))
:description "Affects splice site"})
WBVar00116162 is predicted
{:data (if (contains? variation :variation/confirmed-snp)
"confirmed"
(if (or (contains? variation :variation/snp)
(or (contains? variation :variation/reference-strain-digest)
(contains? variation :variation/transposon-insertion)))
"predicted"))
:description "experimental status of this polymorphism"})
(defn- pack-nulcleotide-change-obj [type-str wildtype mutant]
{:type type-str
:wildtype wildtype
:mutant mutant
:wildtype-label "wildtype"
:mutant-label "variant"})
(defn- variation-features [variation]
(if-let [species-name (->> variation :variation/species :species/id)]
(let [g-species (generic-functions/xform-species-name species-name)
sequence-database (seqdb/get-default-sequence-database g-species)
db-spec ((keyword sequence-database) seqdb/sequence-dbs)
variation-id (:variation/id variation)]
(if sequence-database
(seqdb/variation-features db-spec variation-id)))))
WBVar00116162 substitution
(remove nil?
[(when-let [insertion (or (:variation/insertion variation)
{:mutant (or (:variation.insertion/text
(:variation/insertion variation))
(:transposon-family/id
(first
(:variation/transposon-insertion variation))))
:mutant_label "variant"
:wildtype_label "wild type"
:type "Insertion"
:wildtype ""})
(if (contains? variation :variation/cgh-deleted-probes)
:mutant ""
:wildtype (if-let [refseqobj (sequence-fns/genomic-obj variation)]
(sequence-fns/get-sequence refseqobj))}
eg
:mutant_label "variant"
:mutant ""
:wildtype_label "wild type"
:wildtype (get-deletion-str variation)}))
e.g. tested with WBVar00274017
(if-let [refseqobj (sequence-fns/genomic-obj variation)]
(let [varseq (str/lower-case (sequence-fns/get-sequence
(conj
refseqobj
{:start (:start refseqobj)
:stop (:stop refseqobj)})))]
(cond
(= varseq (str/lower-case
(:variation.substitution/ref substitution)))
{:mutant (:variation.substitution/alt substitution)
:wildtype (:variation.substitution/ref substitution)
:mutant_label "variant"
:wildtype_label "wild type"
:type "Substitution"}
(= varseq (str/lower-case
(generic-functions/dna-reverse-complement
(:variation.substitution/ref substitution))))
{:mutant (generic-functions/dna-reverse-complement (:variation.substitution/alt substitution))
:wildtype (generic-functions/dna-reverse-complement (:variation.substitution/ref substitution))
:mutant_label "variant"
:wildtype_label "wild type"
:type "Substitution"}
:else
(throw (Exception. "substution/ref does not match either + or - strand"))))))]))
(defn nucleotide-change [variation]
{:data (compile-nucleotide-changes variation)
:description "raw nucleotide changes for this variation"})
(defn reference-strain [variation]
{:data (some->> (:variation/strain variation)
(map :variation.strain/strain)
(map pack-obj)
(sort-by :label))
:description "strains that this variant has been observed in"})
e.g. WBVar01943248 this does not work on Ace version
{:data (some->> (:variation/transcript variation)
(map (fn [h]
(let [consequence (some-> (:molecular-change/vep-consequence h)
(first)
(str/replace "_" " "))]
(not-empty
(when (= consequence "frameshift variant")
(some->> (:molecular-change/amino-acid-change h)
(first)
(:molecular-change.amino-acid-change/text)))))))
(remove nil?)
(first)
(not-empty))
:description "A variation that alters the reading frame"})
(defn sequencing-status [variation]
{:data (when-let [seqstatus (:variation/seqstatus variation)]
(obj/humanize-ident (name seqstatus)))
:description "sequencing status of the variation"})
(def widget
{:name generic/name-field
:polymorphism_type polymorphism-type
:amino_acid_change amino-acid-change
:detection_method detection-method
:deletion_verification deletion-verification
:sequence_context sequence-context
:flanking_pcr_products flanking-pcr-products
:variation_type variation-type
:features_affected features-affected
:cgh_deleted_probes cgh-deleted-probes
:cgh_flanking_probes cgh-flanking-probes
:polymorphism_assays polymorphism-assays
:affects_splice_site affects-splice-site
:polymorphism_status polymorphism-status
:nucleotide_change nucleotide-change
:reference_strain reference-strain
:causes_frameshift causes-frameshift
:sequencing_status sequencing-status})
|
c580af7df2db5dd2e3ce799a12fe034414b90736bf41378d973785f97e57e176 | vseloved/cl-nlp | misc.lisp | ( c ) 2013 - 2017 Vsevolod Dyomkin
(in-package #:nlp.util)
(named-readtables:in-readtable rutilsx-readtable)
(declaim (inline filler))
;;; Some aliasing
(rename-package "CL-PPCRE" "CL-PPCRE" '("PPCRE" "RE"))
(define-condition nlp-error (simple-error) ())
(define-condition not-implemented-error (simple-error) ())
(defun ending-word-p (word)
"Check if string WORD is some kind of a period char or a paragraph mark."
(or (every 'period-char-p word)
(string= "¶" word)))
(defun filler (n &optional (fill-char #\Space))
"Produce an N-element filler string of FILL-CHAR's."
(if (and (numberp n) (plusp n))
(make-string n :initial-element fill-char)
""))
(defun shorter? (list n)
"Tests if LIST has at least N elements."
(let ((tail list))
(loop :repeat (1- n) :do (setf tail (cdr tail)))
(null tail)))
(defun uniq (seq &key raw (test 'equal))
"Return only unique elements from SEQ either as a new list
or as hash-table if RAW is set.
TEST should be a hash-table test."
(let ((uniqs (make-hash-table :test test)))
(etypecase seq
(list (dolist (elt seq)
(:+ (get# elt uniqs 0))))
(vector (dovec (elt seq)
(:+ (get# elt uniqs 0)))))
(if raw uniqs (ht-keys uniqs))))
(defun bound-equal (obj specimen)
"Checks is OBJ has all the slots with values provided by SPECIMEN hash-table."
(maphash ^(unless (equal (slot-value obj %) %%)
(return-from bound-equal nil))
specimen))
(defun timestamp ()
"Return current timestamp as string."
(mv-bind (sec min hour day month year)
(decode-universal-time (get-universal-time))
(fmt "~A~2,'0D~2,'0D~2,'0D~2,'0D~2,'0D" year month day hour min sec)))
(defgeneric ss (obj)
(:documentation
"Get a short string from an object")
(:method (obj) (string obj)))
| null | https://raw.githubusercontent.com/vseloved/cl-nlp/f180b6c3c0b9a3614ae43f53a11bc500767307d0/src/util/misc.lisp | lisp | Some aliasing | ( c ) 2013 - 2017 Vsevolod Dyomkin
(in-package #:nlp.util)
(named-readtables:in-readtable rutilsx-readtable)
(declaim (inline filler))
(rename-package "CL-PPCRE" "CL-PPCRE" '("PPCRE" "RE"))
(define-condition nlp-error (simple-error) ())
(define-condition not-implemented-error (simple-error) ())
(defun ending-word-p (word)
"Check if string WORD is some kind of a period char or a paragraph mark."
(or (every 'period-char-p word)
(string= "¶" word)))
(defun filler (n &optional (fill-char #\Space))
"Produce an N-element filler string of FILL-CHAR's."
(if (and (numberp n) (plusp n))
(make-string n :initial-element fill-char)
""))
(defun shorter? (list n)
"Tests if LIST has at least N elements."
(let ((tail list))
(loop :repeat (1- n) :do (setf tail (cdr tail)))
(null tail)))
(defun uniq (seq &key raw (test 'equal))
"Return only unique elements from SEQ either as a new list
or as hash-table if RAW is set.
TEST should be a hash-table test."
(let ((uniqs (make-hash-table :test test)))
(etypecase seq
(list (dolist (elt seq)
(:+ (get# elt uniqs 0))))
(vector (dovec (elt seq)
(:+ (get# elt uniqs 0)))))
(if raw uniqs (ht-keys uniqs))))
(defun bound-equal (obj specimen)
"Checks is OBJ has all the slots with values provided by SPECIMEN hash-table."
(maphash ^(unless (equal (slot-value obj %) %%)
(return-from bound-equal nil))
specimen))
(defun timestamp ()
"Return current timestamp as string."
(mv-bind (sec min hour day month year)
(decode-universal-time (get-universal-time))
(fmt "~A~2,'0D~2,'0D~2,'0D~2,'0D~2,'0D" year month day hour min sec)))
(defgeneric ss (obj)
(:documentation
"Get a short string from an object")
(:method (obj) (string obj)))
|
87dd290fdd90c43742ce36ca6997180e5a88a5a93ce1f3bc346627335672a3b7 | art-w/mcavl | tests.ml | let () =
Alcotest.run "Mcavl"
[ "Sequential", Test_seq.tests
; "View", Test_view.tests
; "Domains", Test_mc.tests ]
| null | https://raw.githubusercontent.com/art-w/mcavl/bf7d3414dbb805a61ebbe809cbb3f2a7ec599c42/tests/tests.ml | ocaml | let () =
Alcotest.run "Mcavl"
[ "Sequential", Test_seq.tests
; "View", Test_view.tests
; "Domains", Test_mc.tests ]
| |
e5264b2564dd66c126936ad1df44bc2d4af1b5fe0f2d9729401fd1db812790f4 | input-output-hk/qeditas | ripemd160.ml | Copyright ( c ) 2015 The Qeditas developers
Distributed under the MIT software license , see the accompanying
file COPYING or -license.php .
file COPYING or -license.php. *)
open Hashaux
* * Following
Dobbertin , , . 1996
RIPEMD-160 : A Strengthened Version of RIPEMD .
With some constants taken from rosettacode.org/wiki/RIPEMD-160
* *
Dobbertin, Bosselaers, Preneel. 1996
RIPEMD-160: A Strengthened Version of RIPEMD.
With some constants taken from rosettacode.org/wiki/RIPEMD-160
***)
let ripemd160consts1 : int32 array = [| 0x00000000l; 0x5a827999l; 0x6ed9eba1l; 0x8f1bbcdcl; 0xa953fd4el |]
let ripemd160consts2 : int32 array = [| 0x50a28be6l; 0x5c4dd124l; 0x6d703ef3l; 0x7a6d76e9l; 0x00000000l |]
let r1 = [| 0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15;
7; 4; 13; 1; 10; 6; 15; 3; 12; 0; 9; 5; 2; 14; 11; 8;
3; 10; 14; 4; 9; 15; 8; 1; 2; 7; 0; 6; 13; 11; 5; 12;
1; 9; 11; 10; 0; 8; 12; 4; 13; 3; 7; 15; 14; 5; 6; 2;
4; 0; 5; 9; 7; 12; 2; 10; 14; 1; 3; 8; 11; 6; 15; 13 |]
let r2 = [| 5; 14; 7; 0; 9; 2; 11; 4; 13; 6; 15; 8; 1; 10; 3; 12;
6; 11; 3; 7; 0; 13; 5; 10; 14; 15; 8; 12; 4; 9; 1; 2;
15; 5; 1; 3; 7; 14; 6; 9; 11; 8; 12; 2; 10; 0; 4; 13;
8; 6; 4; 1; 3; 11; 15; 0; 5; 12; 2; 13; 9; 7; 10; 14;
12; 15; 10; 4; 1; 5; 8; 7; 6; 2; 13; 14; 0; 3; 9; 11 |]
let s1 = [| 11; 14; 15; 12; 5; 8; 7; 9; 11; 13; 14; 15; 6; 7; 9; 8;
7; 6; 8; 13; 11; 9; 7; 15; 7; 12; 15; 9; 11; 7; 13; 12;
11; 13; 6; 7; 14; 9; 13; 15; 14; 8; 13; 6; 5; 12; 7; 5;
11; 12; 14; 15; 14; 15; 9; 8; 9; 14; 5; 6; 8; 6; 5; 12;
9; 15; 5; 11; 6; 8; 13; 12; 5; 12; 13; 14; 11; 8; 5; 6 |]
let s2 = [| 8; 9; 9; 11; 13; 15; 15; 5; 7; 7; 8; 11; 14; 14; 12; 6;
9; 13; 15; 7; 12; 8; 9; 11; 7; 7; 12; 7; 6; 15; 13; 11;
9; 7; 15; 11; 8; 6; 6; 14; 12; 13; 5; 14; 13; 13; 7; 5;
15; 5; 8; 11; 14; 14; 6; 14; 6; 9; 12; 9; 12; 5; 15; 8;
8; 5; 12; 9; 12; 5; 14; 6; 8; 13; 6; 5; 15; 13; 11; 11 |]
let currmd : int32 array = [| 0x67452301l; 0xefcdab89l; 0x98badcfel; 0x10325476l; 0xc3d2e1f0l; |]
let currblock : int32 array = [|
0x0l; 0x0l; 0x0l; 0x0l; 0x0l; 0x0l; 0x0l; 0x0l;
0x0l; 0x0l; 0x0l; 0x0l; 0x0l; 0x0l; 0x0l; 0x0l |]
let a = ref 0l
let b = ref 0l
let c = ref 0l
let d = ref 0l
let e = ref 0l
let a2 = ref 0l
let b2 = ref 0l
let c2 = ref 0l
let d2 = ref 0l
let e2 = ref 0l
let int32_left_rotation x n =
Int32.logor (Int32.shift_right_logical x (32 - n)) (Int32.shift_left x n)
let ripemd160init () =
currmd.(0) <- 0x67452301l;
currmd.(1) <- 0xefcdab89l;
currmd.(2) <- 0x98badcfel;
currmd.(3) <- 0x10325476l;
currmd.(4) <- 0xc3d2e1f0l
* *
This implementation of ripemd160round is closely based on the description .
However , compiles it to something quite slow .
I attempted to write faster versions , but they were always slower .
* *
This implementation of ripemd160round is closely based on the description.
However, ocaml compiles it to something quite slow.
I attempted to write faster versions, but they were always slower.
***)
let ripemd160round () =
let f0 x y z = Int32.logxor x (Int32.logxor y z) in
let f1 x y z = Int32.logor (Int32.logand x y) (Int32.logand (Int32.lognot x) z) in
let f2 x y z = Int32.logxor (Int32.logor x (Int32.lognot y)) z in
let f3 x y z = Int32.logor (Int32.logand x z) (Int32.logand y (Int32.lognot z)) in
let f4 x y z = Int32.logxor x (Int32.logor y (Int32.lognot z)) in
a := currmd.(0);
b := currmd.(1);
c := currmd.(2);
d := currmd.(3);
e := currmd.(4);
a2 := currmd.(0);
b2 := currmd.(1);
c2 := currmd.(2);
d2 := currmd.(3);
e2 := currmd.(4);
for j = 0 to 79 do
let j2 = j lsr 4 in
let (fj,fnj) =
begin
match j2 with
| 0 -> (f0,f4)
| 1 -> (f1,f3)
| 2 -> (f2,f2)
| 3 -> (f3,f1)
| 4 -> (f4,f0)
| _ -> raise (Failure("Something impossible happened in ripemd160"))
end
in
let t = Int32.add
(int32_left_rotation (Int32.add !a (Int32.add (fj !b !c !d) (Int32.add currblock.(r1.(j)) ripemd160consts1.(j2)))) s1.(j))
!e
in
a := !e; e := !d; d := int32_left_rotation !c 10; c := !b; b := t;
let t = Int32.add
(int32_left_rotation (Int32.add !a2 (Int32.add (fnj !b2 !c2 !d2) (Int32.add currblock.(r2.(j)) ripemd160consts2.(j2)))) s2.(j))
!e2
in
a2 := !e2; e2 := !d2; d2 := int32_left_rotation !c2 10; c2 := !b2; b2 := t;
done;
let t = Int32.add (currmd.(1)) (Int32.add !c !d2) in
currmd.(1) <- Int32.add currmd.(2) (Int32.add !d !e2);
currmd.(2) <- Int32.add currmd.(3) (Int32.add !e !a2);
currmd.(3) <- Int32.add currmd.(4) (Int32.add !a !b2);
currmd.(4) <- Int32.add currmd.(0) (Int32.add !b !c2);
currmd.(0) <- t
type md = int32 * int32 * int32 * int32 * int32
let getcurrmd () : md =
(int32_rev currmd.(0),int32_rev currmd.(1),int32_rev currmd.(2),int32_rev currmd.(3),int32_rev currmd.(4))
let md_hexstring h =
let b = Buffer.create 64 in
let (h0,h1,h2,h3,h4) = h in
int32_hexstring b h0;
int32_hexstring b h1;
int32_hexstring b h2;
int32_hexstring b h3;
int32_hexstring b h4;
Buffer.contents b
let printmd h =
Printf.printf "%s" (md_hexstring h)
let hexstring_md h =
(hexsubstring_int32 h 0,hexsubstring_int32 h 8,hexsubstring_int32 h 16,hexsubstring_int32 h 24,hexsubstring_int32 h 32)
let ripemd160_md256 h =
let (h0,h1,h2,h3,h4,h5,h6,h7) = h in
currblock.(0) <- int32_rev h0;
currblock.(1) <- int32_rev h1;
currblock.(2) <- int32_rev h2;
currblock.(3) <- int32_rev h3;
currblock.(4) <- int32_rev h4;
currblock.(5) <- int32_rev h5;
currblock.(6) <- int32_rev h6;
currblock.(7) <- int32_rev h7;
currblock.(8) <- 0x80l;
currblock.(9) <- 0x0l;
currblock.(10) <- 0x0l;
currblock.(11) <- 0x0l;
currblock.(12) <- 0x0l;
currblock.(13) <- 0x0l;
currblock.(14) <- 256l;
currblock.(15) <- 0l;
ripemd160init();
ripemd160round();
getcurrmd ()
| null | https://raw.githubusercontent.com/input-output-hk/qeditas/f4871bd20833cd08a215f9d5fc9df2d362cba410/src/ripemd160.ml | ocaml | Copyright ( c ) 2015 The Qeditas developers
Distributed under the MIT software license , see the accompanying
file COPYING or -license.php .
file COPYING or -license.php. *)
open Hashaux
* * Following
Dobbertin , , . 1996
RIPEMD-160 : A Strengthened Version of RIPEMD .
With some constants taken from rosettacode.org/wiki/RIPEMD-160
* *
Dobbertin, Bosselaers, Preneel. 1996
RIPEMD-160: A Strengthened Version of RIPEMD.
With some constants taken from rosettacode.org/wiki/RIPEMD-160
***)
let ripemd160consts1 : int32 array = [| 0x00000000l; 0x5a827999l; 0x6ed9eba1l; 0x8f1bbcdcl; 0xa953fd4el |]
let ripemd160consts2 : int32 array = [| 0x50a28be6l; 0x5c4dd124l; 0x6d703ef3l; 0x7a6d76e9l; 0x00000000l |]
let r1 = [| 0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15;
7; 4; 13; 1; 10; 6; 15; 3; 12; 0; 9; 5; 2; 14; 11; 8;
3; 10; 14; 4; 9; 15; 8; 1; 2; 7; 0; 6; 13; 11; 5; 12;
1; 9; 11; 10; 0; 8; 12; 4; 13; 3; 7; 15; 14; 5; 6; 2;
4; 0; 5; 9; 7; 12; 2; 10; 14; 1; 3; 8; 11; 6; 15; 13 |]
let r2 = [| 5; 14; 7; 0; 9; 2; 11; 4; 13; 6; 15; 8; 1; 10; 3; 12;
6; 11; 3; 7; 0; 13; 5; 10; 14; 15; 8; 12; 4; 9; 1; 2;
15; 5; 1; 3; 7; 14; 6; 9; 11; 8; 12; 2; 10; 0; 4; 13;
8; 6; 4; 1; 3; 11; 15; 0; 5; 12; 2; 13; 9; 7; 10; 14;
12; 15; 10; 4; 1; 5; 8; 7; 6; 2; 13; 14; 0; 3; 9; 11 |]
let s1 = [| 11; 14; 15; 12; 5; 8; 7; 9; 11; 13; 14; 15; 6; 7; 9; 8;
7; 6; 8; 13; 11; 9; 7; 15; 7; 12; 15; 9; 11; 7; 13; 12;
11; 13; 6; 7; 14; 9; 13; 15; 14; 8; 13; 6; 5; 12; 7; 5;
11; 12; 14; 15; 14; 15; 9; 8; 9; 14; 5; 6; 8; 6; 5; 12;
9; 15; 5; 11; 6; 8; 13; 12; 5; 12; 13; 14; 11; 8; 5; 6 |]
let s2 = [| 8; 9; 9; 11; 13; 15; 15; 5; 7; 7; 8; 11; 14; 14; 12; 6;
9; 13; 15; 7; 12; 8; 9; 11; 7; 7; 12; 7; 6; 15; 13; 11;
9; 7; 15; 11; 8; 6; 6; 14; 12; 13; 5; 14; 13; 13; 7; 5;
15; 5; 8; 11; 14; 14; 6; 14; 6; 9; 12; 9; 12; 5; 15; 8;
8; 5; 12; 9; 12; 5; 14; 6; 8; 13; 6; 5; 15; 13; 11; 11 |]
let currmd : int32 array = [| 0x67452301l; 0xefcdab89l; 0x98badcfel; 0x10325476l; 0xc3d2e1f0l; |]
let currblock : int32 array = [|
0x0l; 0x0l; 0x0l; 0x0l; 0x0l; 0x0l; 0x0l; 0x0l;
0x0l; 0x0l; 0x0l; 0x0l; 0x0l; 0x0l; 0x0l; 0x0l |]
let a = ref 0l
let b = ref 0l
let c = ref 0l
let d = ref 0l
let e = ref 0l
let a2 = ref 0l
let b2 = ref 0l
let c2 = ref 0l
let d2 = ref 0l
let e2 = ref 0l
let int32_left_rotation x n =
Int32.logor (Int32.shift_right_logical x (32 - n)) (Int32.shift_left x n)
let ripemd160init () =
currmd.(0) <- 0x67452301l;
currmd.(1) <- 0xefcdab89l;
currmd.(2) <- 0x98badcfel;
currmd.(3) <- 0x10325476l;
currmd.(4) <- 0xc3d2e1f0l
* *
This implementation of ripemd160round is closely based on the description .
However , compiles it to something quite slow .
I attempted to write faster versions , but they were always slower .
* *
This implementation of ripemd160round is closely based on the description.
However, ocaml compiles it to something quite slow.
I attempted to write faster versions, but they were always slower.
***)
let ripemd160round () =
let f0 x y z = Int32.logxor x (Int32.logxor y z) in
let f1 x y z = Int32.logor (Int32.logand x y) (Int32.logand (Int32.lognot x) z) in
let f2 x y z = Int32.logxor (Int32.logor x (Int32.lognot y)) z in
let f3 x y z = Int32.logor (Int32.logand x z) (Int32.logand y (Int32.lognot z)) in
let f4 x y z = Int32.logxor x (Int32.logor y (Int32.lognot z)) in
a := currmd.(0);
b := currmd.(1);
c := currmd.(2);
d := currmd.(3);
e := currmd.(4);
a2 := currmd.(0);
b2 := currmd.(1);
c2 := currmd.(2);
d2 := currmd.(3);
e2 := currmd.(4);
for j = 0 to 79 do
let j2 = j lsr 4 in
let (fj,fnj) =
begin
match j2 with
| 0 -> (f0,f4)
| 1 -> (f1,f3)
| 2 -> (f2,f2)
| 3 -> (f3,f1)
| 4 -> (f4,f0)
| _ -> raise (Failure("Something impossible happened in ripemd160"))
end
in
let t = Int32.add
(int32_left_rotation (Int32.add !a (Int32.add (fj !b !c !d) (Int32.add currblock.(r1.(j)) ripemd160consts1.(j2)))) s1.(j))
!e
in
a := !e; e := !d; d := int32_left_rotation !c 10; c := !b; b := t;
let t = Int32.add
(int32_left_rotation (Int32.add !a2 (Int32.add (fnj !b2 !c2 !d2) (Int32.add currblock.(r2.(j)) ripemd160consts2.(j2)))) s2.(j))
!e2
in
a2 := !e2; e2 := !d2; d2 := int32_left_rotation !c2 10; c2 := !b2; b2 := t;
done;
let t = Int32.add (currmd.(1)) (Int32.add !c !d2) in
currmd.(1) <- Int32.add currmd.(2) (Int32.add !d !e2);
currmd.(2) <- Int32.add currmd.(3) (Int32.add !e !a2);
currmd.(3) <- Int32.add currmd.(4) (Int32.add !a !b2);
currmd.(4) <- Int32.add currmd.(0) (Int32.add !b !c2);
currmd.(0) <- t
type md = int32 * int32 * int32 * int32 * int32
let getcurrmd () : md =
(int32_rev currmd.(0),int32_rev currmd.(1),int32_rev currmd.(2),int32_rev currmd.(3),int32_rev currmd.(4))
let md_hexstring h =
let b = Buffer.create 64 in
let (h0,h1,h2,h3,h4) = h in
int32_hexstring b h0;
int32_hexstring b h1;
int32_hexstring b h2;
int32_hexstring b h3;
int32_hexstring b h4;
Buffer.contents b
let printmd h =
Printf.printf "%s" (md_hexstring h)
let hexstring_md h =
(hexsubstring_int32 h 0,hexsubstring_int32 h 8,hexsubstring_int32 h 16,hexsubstring_int32 h 24,hexsubstring_int32 h 32)
let ripemd160_md256 h =
let (h0,h1,h2,h3,h4,h5,h6,h7) = h in
currblock.(0) <- int32_rev h0;
currblock.(1) <- int32_rev h1;
currblock.(2) <- int32_rev h2;
currblock.(3) <- int32_rev h3;
currblock.(4) <- int32_rev h4;
currblock.(5) <- int32_rev h5;
currblock.(6) <- int32_rev h6;
currblock.(7) <- int32_rev h7;
currblock.(8) <- 0x80l;
currblock.(9) <- 0x0l;
currblock.(10) <- 0x0l;
currblock.(11) <- 0x0l;
currblock.(12) <- 0x0l;
currblock.(13) <- 0x0l;
currblock.(14) <- 256l;
currblock.(15) <- 0l;
ripemd160init();
ripemd160round();
getcurrmd ()
| |
eda48a605aeb7eaf063fc2ccbd76f8f1cbf3a900cae54e35e102f481e72da8ec | softwarelanguageslab/maf | R5RS_scp1_flip2-4.scm | ; Changes:
* removed : 0
* added : 0
* swaps : 0
* negated predicates : 1
; * swapped branches: 0
* calls to i d fun : 1
(letrec ((make-flip (lambda ()
(let ((state 0))
(lambda ()
(if (= state 0) (set! state 1) (set! state 0))
state))))
(flip (make-flip)))
(<change>
(if (= (flip) 1)
(if (= (flip) 0)
(if (= (flip) 1) (= (flip) 0) #f)
#f)
#f)
((lambda (x) x)
(if (= (flip) 1)
(if (<change> (= (flip) 0) (not (= (flip) 0)))
(if (= (flip) 1) (= (flip) 0) #f)
#f)
#f)))) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_scp1_flip2-4.scm | scheme | Changes:
* swapped branches: 0 | * removed : 0
* added : 0
* swaps : 0
* negated predicates : 1
* calls to i d fun : 1
(letrec ((make-flip (lambda ()
(let ((state 0))
(lambda ()
(if (= state 0) (set! state 1) (set! state 0))
state))))
(flip (make-flip)))
(<change>
(if (= (flip) 1)
(if (= (flip) 0)
(if (= (flip) 1) (= (flip) 0) #f)
#f)
#f)
((lambda (x) x)
(if (= (flip) 1)
(if (<change> (= (flip) 0) (not (= (flip) 0)))
(if (= (flip) 1) (= (flip) 0) #f)
#f)
#f)))) |
8736aac5ab32c9fec99efa325c73c29d2395e7ea61a6ea305db37cceebe2ad6a | sjl/chancery | package.test.lisp | (defpackage :chancery.test
(:use :cl :1am :chancery :chancery.quickutils)
(:export
:run-tests))
| null | https://raw.githubusercontent.com/sjl/chancery/87cb53cd791d4d60a6c41bc0b02345739b82abb0/package.test.lisp | lisp | (defpackage :chancery.test
(:use :cl :1am :chancery :chancery.quickutils)
(:export
:run-tests))
| |
3c2a70915f158aa12f767ea8581011e43096ab62a293a6f3c7922d68458232fb | lrascao/rebar3_scuttler | rebar3_scuttler_release.erl | %%-*- mode: erlang -*-
-module(rebar3_scuttler_release).
-behaviour(provider).
-export([init/1,
do/1,
format_error/1]).
-define(PROVIDER, release).
-define(NAMESPACE, default).
-define(DEPS, [{?NAMESPACE, compile}]).
-define(PRE_START_HOOK_TEMPLATE, "pre_start_cuttlefish.tpl").
-define(ERLANG_VM_ARGS_SCHEMA, "erlang.vm.args.schema").
%% ===================================================================
%% Public API
%% ===================================================================
-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
Provider = providers:create([
{name, ?PROVIDER}, % The 'user friendly' name of the task
{module, ?MODULE}, % The module implementation of the task
{namespace, ?NAMESPACE},
{bare, true}, % The task can be run by the user, always true
{deps, ?DEPS}, % The list of dependencies
{example, "rebar3 scuttler release"}, % How to use the plugin
{opts, []}, % list of options understood by the plugin
{short_desc, "Rebar3 scuttler release plugin"},
{desc, ""}
]),
{ok, rebar_state:add_provider(State, Provider)}.
-spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
do(State0) ->
rebar_api:info("Running cuttlefish schema generator", []),
ScuttlerConf = rebar_state:get(State0, scuttler, []),
Relx = rebar_state:get(State0, relx, []),
% find the release's name
{release, {Name, _Vsn}, _} = lists:keyfind(release, 1, Relx),
find and apps for this project
ReleaseDir = rebar_release_dir(State0),
TargetDir = filename:join([ReleaseDir, Name]),
Deps = rebar_state:all_deps(State0),
Apps = rebar_state:project_apps(State0),
find the cuttlefish escript executable
CuttlefishBin =
case filelib:is_regular(filename:join([rebar_dir:base_dir(State0), "bin", "cuttlefish"])) of
true ->
filename:join([rebar_dir:base_dir(State0), "bin", "cuttlefish"]);
false ->
it 's either in _ checkouts or some dep
case filelib:wildcard(filename:join(["_checkouts", "cuttlefish*", "cuttlefish"])) ++
filelib:wildcard(filename:join(["_build", "*", "bin", "cuttlefish"])) of
[C | _] ->
C;
[] ->
% unable to find, give up
throw({no_cuttlefish_escript, rebar_dir:base_dir(State0)})
end
end,
% find out the ebin dir for the plugin, we want to template our pre start
% script and need somewhere to write it to
PluginDeps = rebar_state:all_plugin_deps(State0),
{ok, AppInfo} = rebar_app_utils:find(<<"rebar3_scuttler">>, PluginDeps),
PluginEbinDir = rebar_app_info:ebin_dir(AppInfo),
% get the location of the plugin's extended start script hook,
% should be in priv/pre_start_cuttlefish.tpl
PreStartHookTemplate = filename:join([code:priv_dir(rebar3_scuttler), ?PRE_START_HOOK_TEMPLATE]),
% the conf filename will default the name of this release and the .conf suffix unless
% requested by the developer
ConfFile = proplists:get_value(conf_file, ScuttlerConf,
atom_to_list(Name) ++ ".conf"),
% get the list of configured schema transformation definitions
SchemaDefs = proplists:get_value(schemas, ScuttlerConf, []),
% get the name of the to be generated pre start hook
ReleasePreStartHook = proplists:get_value(pre_start_hook, ScuttlerConf,
"bin/hooks/pre_start_cuttlefish"),
get the projects overlays and apply the overlay that will copy over the cuttlefish
% and create the share/schema directory inside the release
Overlays0 = apply_bin_overlay(Name, CuttlefishBin, proplists:get_value(overlay, Relx, [])),
% go through each of the requested schema transformation definition
% and generate a file for each of them
{AllSchemas, Overlays1, PreStartHookBin} =
lists:foldl(fun(SchemaDef, {SchemasAcc0, OverlaysAcc0, PreStartHookBinAcc0}) ->
#{schemas := Schemas,
release_schema_dir := ReleaseSchemaDir,
output_file := OutputFile} = schemas(SchemaDef, Deps++Apps, State0),
% add template overlay entries that will copy all the cuttlefish schemas
% to the release
OverlaysAcc = apply_schema_overlays(Schemas, ReleaseSchemaDir, OverlaysAcc0),
OutputFilename = filename:basename(OutputFile),
OutputDir = filename:dirname(OutputFile),
% lastly inject the template directive that will copy the plugin
pre start hook that will invoke cuttlefish and generate the
% .config files of each schema
% before that we need to replace all mustache variables in the
% pre start script template
PreStartHookBin = template({file, PreStartHookTemplate},
[{"schema_dir", ReleaseSchemaDir},
{"output_dir", OutputDir},
{"output_filename", OutputFilename},
{"conf_file", ConfFile}]),
{Schemas ++ SchemasAcc0, OverlaysAcc, <<PreStartHookBinAcc0/binary, PreStartHookBin/binary>>}
end,
{[], Overlays0, <<"">>},
SchemaDefs),
% write the templated result file to the plugin's output dir
PreStartHookFile = filename:join([PluginEbinDir, ?PRE_START_HOOK_TEMPLATE]),
ok = file:write_file(PreStartHookFile, PreStartHookBin),
Overlays = [{template, PreStartHookFile, ReleasePreStartHook} | Overlays1],
% override the `overlay` relx project section with additional entries
% that will allow us to inject:
% - the cuttefish bin tool
% - the templated cuttefish schema files
% - the pre-start extended start script hook
State1 = rebar_state:set(State0, relx,
lists:keydelete(overlay, 1, Relx) ++
[{overlay, Overlays}]),
% generate the release, this will cause all schema files to be templated and copied
% over to the release dir
State2 = do_release(State1),
rebar_api:debug("all schemas: ~p", [AllSchemas]),
% % now that the schema files have been templated, we look them up
% % in order to generate a skeleton .conf file with all the defaults
ReleaseSchemas = find_release_schemas(TargetDir, AllSchemas),
rebar_api:debug("release schemas: ~p", [ReleaseSchemas]),
case filelib:is_regular(filename:join([TargetDir, ConfFile])) of
false ->
there is no .conf file present , we 'll just generate one out of
% the schema defaults
case cuttlefish_schema:files(ReleaseSchemas) of
{errorlist, Errors} ->
rebar_api:error("bad cuttlefish schemas: ~p (~p)",
[ReleaseSchemas, Errors]),
%% These errors were already printed
{error, "bad cuttlefish schemas"};
{_Translations, Mappings, _Validators} ->
make_default_file(ConfFile, TargetDir, Mappings),
now a bit of trickery that should be justified . Earlier we asked relx
% to create the release and gave it the schema overlays to copy over to the
% final release. Only after that did we ask cuttlefish to generate a default conf file
% based on these schema files, now we need to sneak a copy overlay of this generated
conf file into relx 's state in order for it to end up in a tarball that s a result of
% `rebar3 tar`.
{ok, rebar_state:set(State2, relx,
lists:keydelete(overlay, 1, Relx) ++
[{overlay, [
{copy, ConfFile, ConfFile} | Overlays]}])}
end;
true ->
rebar_api:debug("no need to generate a default .conf file, one already exists at ~p",
[filename:join([TargetDir, ConfFile])]),
{ok, rebar_state:set(State2, relx,
lists:keydelete(overlay, 1, Relx) ++
[{overlay, [
{copy, ConfFile, ConfFile} | Overlays]}])}
end.
-spec do_release(rebar_state:t()) -> rebar_state:t().
do_release(State0) ->
Vsn = rebar3_scuttler_utils:rebar_version(),
{ok, State} =
case Vsn of
#{minor := Minor} when Minor >= 14 ->
from 3.14 onwards , a relx refactor changed the interface
% of rebar_relx
rebar_relx:do(release, State0);
_ ->
rebar_relx:do(rlx_prv_release, "release", ?PROVIDER, State0)
end,
State.
find_release_schemas(Dir, Schemas) ->
SchemaFilenames = lists:map(fun filename:basename/1, Schemas),
%% Convert simple extension to proper regex
SchemaExtRe = "^[^._].*\\" ++ ".schema" ++ [$$],
% recursively look for all .schema files in the supplied dir
SchemasFound = rebar_utils:find_files(Dir, SchemaExtRe, true),
% now filter out all the files that were not provided in the configuration
lists:filter(fun(SchemaFound) ->
% ignore all .schema located beneath the `lib` dir since these
contain files that were templated by relx and might contain
% unprocessed overlay vars
case lists:prefix(filename:join([Dir, "lib"]), SchemaFound) of
true ->
false;
_ ->
lists:member(filename:basename(SchemaFound), SchemaFilenames)
end
end,
SchemasFound).
-spec format_error(any()) -> iolist().
format_error({no_cuttlefish_escript, ProfileDir}) ->
io_lib:format("No cuttlefish escript found under ~s or ~s", [filename:join(ProfileDir, "bin"),
"_build/default/bin"]);
format_error(Error) ->
io_lib:format("~p", [Error]).
make_default_file(File, TargetDir, Mappings) ->
rebar_api:debug("generating default file ~p in ~p",
[File, TargetDir]),
Filename = filename:join([TargetDir, File]),
filelib:ensure_dir(Filename),
cuttlefish_conf:generate_file(Mappings, Filename),
Filename.
schemas({vm_args, OutputFile}, _Apps, _State) ->
#{schemas => [filename:join([code:priv_dir(rebar3_scuttler), ?ERLANG_VM_ARGS_SCHEMA])],
release_schema_dir => "releases/{{release_version}}",
output_file => OutputFile};
schemas({auto_discover, ReleaseSchemaDir, OutputFile}, Apps, _State) ->
Schemas = lists:flatmap(fun(App) ->
AppDir = rebar_app_info:dir(App),
filelib:wildcard(filename:join(["{priv,schema,schemas}", "*.schema"]), AppDir) ++
filelib:wildcard(filename:join(["priv", "{schema,schemas}", "*.schema"]), AppDir)
end,
Apps) ++
filelib:wildcard(filename:join(["{priv,schema,schemas}", "*.schema"])),
#{schemas => Schemas,
release_schema_dir => ReleaseSchemaDir,
output_file => OutputFile};
schemas({Dir0, ReleaseSchemaDir, OutputFile}, _, State) when is_list(Dir0) ->
Dir = template(Dir0,
[{"deps_dir", rebar_dir:deps_dir(State)}]),
rebar_api:debug("looking for *.schemas in ~p",
[Dir]),
#{schemas => [filename:join([Dir, Schema]) || Schema <- filelib:wildcard("*.schema", Dir)],
release_schema_dir => ReleaseSchemaDir,
output_file => OutputFile}.
apply_bin_overlay(_Name, CuttlefishBin, Overlays0) ->
[{copy, CuttlefishBin, "bin/cuttlefish"}] ++ Overlays0.
apply_schema_overlays(Schemas, SchemasDir, Overlays0) ->
SchemaOverlays = [begin
{template, Schema, filename:join([SchemasDir, filename:basename(Schema)])}
end || Schema <- Schemas],
apply_mkdir_overlay(SchemasDir, SchemaOverlays ++ Overlays0).
apply_mkdir_overlay(undefined, Overlays0) ->
Overlays0;
apply_mkdir_overlay(Dir, Overlays0) ->
[{mkdir, Dir} | Overlays0].
%% Determine if --output-dir or -o has been passed, and if so, use
%% that path for the release directory. Otherwise, default to the
%% default directory.
rebar_release_dir(State) ->
DefaultRelDir = filename:join(rebar_dir:base_dir(State), "rel"),
{Options, _} = rebar_state:command_parsed_args(State),
case proplists:get_value(output_dir, Options) of
undefined ->
DefaultRelDir;
OutputDir ->
OutputDir
end.
template({file, Source}, Context) ->
{ok, Template} = file:read_file(Source),
case catch bbmustache:render(Template, Context) of
Bin when is_binary(Bin) ->
Bin;
Error ->
rebar_api:abort("failed generating due to ~p",
[Error]),
{error, Error}
end;
template(Template, Context) when is_list(Template) ->
binary_to_list(template(list_to_binary(Template), Context));
template(Template, Context) when is_binary(Template) ->
bbmustache:render(Template, Context).
| null | https://raw.githubusercontent.com/lrascao/rebar3_scuttler/98b3be5fe649192e18ed65cc09f2f8d92bbab195/src/rebar3_scuttler_release.erl | erlang | -*- mode: erlang -*-
===================================================================
Public API
===================================================================
The 'user friendly' name of the task
The module implementation of the task
The task can be run by the user, always true
The list of dependencies
How to use the plugin
list of options understood by the plugin
find the release's name
unable to find, give up
find out the ebin dir for the plugin, we want to template our pre start
script and need somewhere to write it to
get the location of the plugin's extended start script hook,
should be in priv/pre_start_cuttlefish.tpl
the conf filename will default the name of this release and the .conf suffix unless
requested by the developer
get the list of configured schema transformation definitions
get the name of the to be generated pre start hook
and create the share/schema directory inside the release
go through each of the requested schema transformation definition
and generate a file for each of them
add template overlay entries that will copy all the cuttlefish schemas
to the release
lastly inject the template directive that will copy the plugin
.config files of each schema
before that we need to replace all mustache variables in the
pre start script template
write the templated result file to the plugin's output dir
override the `overlay` relx project section with additional entries
that will allow us to inject:
- the cuttefish bin tool
- the templated cuttefish schema files
- the pre-start extended start script hook
generate the release, this will cause all schema files to be templated and copied
over to the release dir
% now that the schema files have been templated, we look them up
% in order to generate a skeleton .conf file with all the defaults
the schema defaults
These errors were already printed
to create the release and gave it the schema overlays to copy over to the
final release. Only after that did we ask cuttlefish to generate a default conf file
based on these schema files, now we need to sneak a copy overlay of this generated
`rebar3 tar`.
of rebar_relx
Convert simple extension to proper regex
recursively look for all .schema files in the supplied dir
now filter out all the files that were not provided in the configuration
ignore all .schema located beneath the `lib` dir since these
unprocessed overlay vars
Determine if --output-dir or -o has been passed, and if so, use
that path for the release directory. Otherwise, default to the
default directory. | -module(rebar3_scuttler_release).
-behaviour(provider).
-export([init/1,
do/1,
format_error/1]).
-define(PROVIDER, release).
-define(NAMESPACE, default).
-define(DEPS, [{?NAMESPACE, compile}]).
-define(PRE_START_HOOK_TEMPLATE, "pre_start_cuttlefish.tpl").
-define(ERLANG_VM_ARGS_SCHEMA, "erlang.vm.args.schema").
-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
Provider = providers:create([
{namespace, ?NAMESPACE},
{short_desc, "Rebar3 scuttler release plugin"},
{desc, ""}
]),
{ok, rebar_state:add_provider(State, Provider)}.
-spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
do(State0) ->
rebar_api:info("Running cuttlefish schema generator", []),
ScuttlerConf = rebar_state:get(State0, scuttler, []),
Relx = rebar_state:get(State0, relx, []),
{release, {Name, _Vsn}, _} = lists:keyfind(release, 1, Relx),
find and apps for this project
ReleaseDir = rebar_release_dir(State0),
TargetDir = filename:join([ReleaseDir, Name]),
Deps = rebar_state:all_deps(State0),
Apps = rebar_state:project_apps(State0),
find the cuttlefish escript executable
CuttlefishBin =
case filelib:is_regular(filename:join([rebar_dir:base_dir(State0), "bin", "cuttlefish"])) of
true ->
filename:join([rebar_dir:base_dir(State0), "bin", "cuttlefish"]);
false ->
it 's either in _ checkouts or some dep
case filelib:wildcard(filename:join(["_checkouts", "cuttlefish*", "cuttlefish"])) ++
filelib:wildcard(filename:join(["_build", "*", "bin", "cuttlefish"])) of
[C | _] ->
C;
[] ->
throw({no_cuttlefish_escript, rebar_dir:base_dir(State0)})
end
end,
PluginDeps = rebar_state:all_plugin_deps(State0),
{ok, AppInfo} = rebar_app_utils:find(<<"rebar3_scuttler">>, PluginDeps),
PluginEbinDir = rebar_app_info:ebin_dir(AppInfo),
PreStartHookTemplate = filename:join([code:priv_dir(rebar3_scuttler), ?PRE_START_HOOK_TEMPLATE]),
ConfFile = proplists:get_value(conf_file, ScuttlerConf,
atom_to_list(Name) ++ ".conf"),
SchemaDefs = proplists:get_value(schemas, ScuttlerConf, []),
ReleasePreStartHook = proplists:get_value(pre_start_hook, ScuttlerConf,
"bin/hooks/pre_start_cuttlefish"),
get the projects overlays and apply the overlay that will copy over the cuttlefish
Overlays0 = apply_bin_overlay(Name, CuttlefishBin, proplists:get_value(overlay, Relx, [])),
{AllSchemas, Overlays1, PreStartHookBin} =
lists:foldl(fun(SchemaDef, {SchemasAcc0, OverlaysAcc0, PreStartHookBinAcc0}) ->
#{schemas := Schemas,
release_schema_dir := ReleaseSchemaDir,
output_file := OutputFile} = schemas(SchemaDef, Deps++Apps, State0),
OverlaysAcc = apply_schema_overlays(Schemas, ReleaseSchemaDir, OverlaysAcc0),
OutputFilename = filename:basename(OutputFile),
OutputDir = filename:dirname(OutputFile),
pre start hook that will invoke cuttlefish and generate the
PreStartHookBin = template({file, PreStartHookTemplate},
[{"schema_dir", ReleaseSchemaDir},
{"output_dir", OutputDir},
{"output_filename", OutputFilename},
{"conf_file", ConfFile}]),
{Schemas ++ SchemasAcc0, OverlaysAcc, <<PreStartHookBinAcc0/binary, PreStartHookBin/binary>>}
end,
{[], Overlays0, <<"">>},
SchemaDefs),
PreStartHookFile = filename:join([PluginEbinDir, ?PRE_START_HOOK_TEMPLATE]),
ok = file:write_file(PreStartHookFile, PreStartHookBin),
Overlays = [{template, PreStartHookFile, ReleasePreStartHook} | Overlays1],
State1 = rebar_state:set(State0, relx,
lists:keydelete(overlay, 1, Relx) ++
[{overlay, Overlays}]),
State2 = do_release(State1),
rebar_api:debug("all schemas: ~p", [AllSchemas]),
ReleaseSchemas = find_release_schemas(TargetDir, AllSchemas),
rebar_api:debug("release schemas: ~p", [ReleaseSchemas]),
case filelib:is_regular(filename:join([TargetDir, ConfFile])) of
false ->
there is no .conf file present , we 'll just generate one out of
case cuttlefish_schema:files(ReleaseSchemas) of
{errorlist, Errors} ->
rebar_api:error("bad cuttlefish schemas: ~p (~p)",
[ReleaseSchemas, Errors]),
{error, "bad cuttlefish schemas"};
{_Translations, Mappings, _Validators} ->
make_default_file(ConfFile, TargetDir, Mappings),
now a bit of trickery that should be justified . Earlier we asked relx
conf file into relx 's state in order for it to end up in a tarball that s a result of
{ok, rebar_state:set(State2, relx,
lists:keydelete(overlay, 1, Relx) ++
[{overlay, [
{copy, ConfFile, ConfFile} | Overlays]}])}
end;
true ->
rebar_api:debug("no need to generate a default .conf file, one already exists at ~p",
[filename:join([TargetDir, ConfFile])]),
{ok, rebar_state:set(State2, relx,
lists:keydelete(overlay, 1, Relx) ++
[{overlay, [
{copy, ConfFile, ConfFile} | Overlays]}])}
end.
-spec do_release(rebar_state:t()) -> rebar_state:t().
do_release(State0) ->
Vsn = rebar3_scuttler_utils:rebar_version(),
{ok, State} =
case Vsn of
#{minor := Minor} when Minor >= 14 ->
from 3.14 onwards , a relx refactor changed the interface
rebar_relx:do(release, State0);
_ ->
rebar_relx:do(rlx_prv_release, "release", ?PROVIDER, State0)
end,
State.
find_release_schemas(Dir, Schemas) ->
SchemaFilenames = lists:map(fun filename:basename/1, Schemas),
SchemaExtRe = "^[^._].*\\" ++ ".schema" ++ [$$],
SchemasFound = rebar_utils:find_files(Dir, SchemaExtRe, true),
lists:filter(fun(SchemaFound) ->
contain files that were templated by relx and might contain
case lists:prefix(filename:join([Dir, "lib"]), SchemaFound) of
true ->
false;
_ ->
lists:member(filename:basename(SchemaFound), SchemaFilenames)
end
end,
SchemasFound).
-spec format_error(any()) -> iolist().
format_error({no_cuttlefish_escript, ProfileDir}) ->
io_lib:format("No cuttlefish escript found under ~s or ~s", [filename:join(ProfileDir, "bin"),
"_build/default/bin"]);
format_error(Error) ->
io_lib:format("~p", [Error]).
make_default_file(File, TargetDir, Mappings) ->
rebar_api:debug("generating default file ~p in ~p",
[File, TargetDir]),
Filename = filename:join([TargetDir, File]),
filelib:ensure_dir(Filename),
cuttlefish_conf:generate_file(Mappings, Filename),
Filename.
schemas({vm_args, OutputFile}, _Apps, _State) ->
#{schemas => [filename:join([code:priv_dir(rebar3_scuttler), ?ERLANG_VM_ARGS_SCHEMA])],
release_schema_dir => "releases/{{release_version}}",
output_file => OutputFile};
schemas({auto_discover, ReleaseSchemaDir, OutputFile}, Apps, _State) ->
Schemas = lists:flatmap(fun(App) ->
AppDir = rebar_app_info:dir(App),
filelib:wildcard(filename:join(["{priv,schema,schemas}", "*.schema"]), AppDir) ++
filelib:wildcard(filename:join(["priv", "{schema,schemas}", "*.schema"]), AppDir)
end,
Apps) ++
filelib:wildcard(filename:join(["{priv,schema,schemas}", "*.schema"])),
#{schemas => Schemas,
release_schema_dir => ReleaseSchemaDir,
output_file => OutputFile};
schemas({Dir0, ReleaseSchemaDir, OutputFile}, _, State) when is_list(Dir0) ->
Dir = template(Dir0,
[{"deps_dir", rebar_dir:deps_dir(State)}]),
rebar_api:debug("looking for *.schemas in ~p",
[Dir]),
#{schemas => [filename:join([Dir, Schema]) || Schema <- filelib:wildcard("*.schema", Dir)],
release_schema_dir => ReleaseSchemaDir,
output_file => OutputFile}.
apply_bin_overlay(_Name, CuttlefishBin, Overlays0) ->
[{copy, CuttlefishBin, "bin/cuttlefish"}] ++ Overlays0.
apply_schema_overlays(Schemas, SchemasDir, Overlays0) ->
SchemaOverlays = [begin
{template, Schema, filename:join([SchemasDir, filename:basename(Schema)])}
end || Schema <- Schemas],
apply_mkdir_overlay(SchemasDir, SchemaOverlays ++ Overlays0).
apply_mkdir_overlay(undefined, Overlays0) ->
Overlays0;
apply_mkdir_overlay(Dir, Overlays0) ->
[{mkdir, Dir} | Overlays0].
rebar_release_dir(State) ->
DefaultRelDir = filename:join(rebar_dir:base_dir(State), "rel"),
{Options, _} = rebar_state:command_parsed_args(State),
case proplists:get_value(output_dir, Options) of
undefined ->
DefaultRelDir;
OutputDir ->
OutputDir
end.
template({file, Source}, Context) ->
{ok, Template} = file:read_file(Source),
case catch bbmustache:render(Template, Context) of
Bin when is_binary(Bin) ->
Bin;
Error ->
rebar_api:abort("failed generating due to ~p",
[Error]),
{error, Error}
end;
template(Template, Context) when is_list(Template) ->
binary_to_list(template(list_to_binary(Template), Context));
template(Template, Context) when is_binary(Template) ->
bbmustache:render(Template, Context).
|
7bc2ea49b049ea520354c19ee4e19450bec94b5e26a696c3730c2400a38e5081 | phantomics/seed | package.lisp | package.lisp
(defpackage #:seed.sublimate
(:export #:meta #:fetch-meta #:instantiate-priority-macro-reader)
(:use #:cl #:prove))
| null | https://raw.githubusercontent.com/phantomics/seed/f128969c671c078543574395d6b23a1a5f2723f8/seed.sublimate/package.lisp | lisp | package.lisp
(defpackage #:seed.sublimate
(:export #:meta #:fetch-meta #:instantiate-priority-macro-reader)
(:use #:cl #:prove))
| |
ccf082c6c7614f41b20015382a75078fcf79d3e3b98c5771335a51f0fe7bbfbc | iu-parfunc/lvars | DeepFrz.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DataKinds #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE TypeFamilies #-}
|
The ` DeepFrz ` module provides a way to return arbitrarily complex data
structures containing LVars from ` Par ` computations .
The important thing to know is that to use ` runParThenFreeze ` to run a
` Par ` computation , you must make sure that all types you return from
the ` Par ` computation have ` DeepFrz ` instances . This means that , if
you wish to return a user - defined type , you will need to include a bit
of boilerplate to give it a ` DeepFrz ` instance . Here is a complete
example :
> { - # LANGUAGE TypeFamilies #
The `DeepFrz` module provides a way to return arbitrarily complex data
structures containing LVars from `Par` computations.
The important thing to know is that to use `runParThenFreeze` to run a
`Par` computation, you must make sure that all types you return from
the `Par` computation have `DeepFrz` instances. This means that, if
you wish to return a user-defined type, you will need to include a bit
of boilerplate to give it a `DeepFrz` instance. Here is a complete
example:
> {-# LANGUAGE TypeFamilies #-}
> import Control.LVish.DeepFrz
>
> data MyData = MyData Int deriving Show
>
> instance DeepFrz MyData where
> type FrzType MyData = MyData
>
> main = print (runParThenFreeze (return (MyData 3)))
-}
-- TODO: a more detailed (recursive?) DeepFrz instance example might
-- be really helpful here for people who want to implement their own
LVar types . -- LK
module Control.LVish.DeepFrz
(
-- * The functions you'll want to use
runParThenFreeze,
runParThenFreezeIO,
-- * Some supporting types
DeepFrz(), FrzType,
NonFrzn, Frzn, Trvrsbl,
) where
import Control . ( ( .. ) )
import Control.LVish.DeepFrz.Internal (DeepFrz (..), Frzn, NonFrzn,
Trvrsbl)
import Control.LVish.Internal (Par (WrapPar))
import Control.Par.EffectSigs
import Control.LVish.Internal.SchedIdempotent (runPar, runParIO)
--------------------------------------------------------------------------------
-- | Under normal conditions, calling a `freeze` operation inside a
` Par ` computation makes the ` Par ` computation quasi - deterministic .
However , if we freeze only after all LVar operations are completed
-- (after the implicit global barrier of `runPar`), then we've avoided
all data races , and freezing is therefore safe . Running a ` Par `
computation with ` runParThenFreeze ` accomplishes this , without our
-- having to call `freeze` explicitly.
--
In order to use ` runParThenFreeze ` , the type returned from the
` Par ` computation must be a member of the ` DeepFrz ` class . All the
@Data . libraries should provide instances of ` DeepFrz `
-- already. Further, you can create additional instances for custom,
-- pure datatypes. The result of a `runParThenFreeze` depends on the
type - level function ` FrzType ` , whose only purpose is to toggle the
-- `s` parameters of all IVars to the `Frzn` state.
--
Significantly , the freeze at the end of ` runParThenFreeze ` has /no/ runtime cost , in
-- spite of the fact that it enables a /deep/ (recursive) freeze of the value returned
by the ` Par ` computation .
runParThenFreeze :: (DeepFrz a, Deterministic e) => Par e NonFrzn a -> FrzType a
runParThenFreeze : : Deterministic e = > DeepFrz a = > Par e NonFrzn a - > FrzType a
runParThenFreeze (WrapPar p) = frz $ runPar p
-- | This version works for nondeterministic computations as well.
--
-- Of course, nondeterministic computations may also call `freeze`
-- internally, but this function has an advantage to doing your own
-- `freeze` at the end of a `runParIO`: there is an implicit barrier
-- before the final freeze. Further, `DeepFrz` has no runtime
-- overhead, whereas regular freezing has a cost.
runParThenFreezeIO :: DeepFrz a => Par e NonFrzn a -> IO (FrzType a)
runParThenFreezeIO (WrapPar p) = do
x <- runParIO p
return $ frz x
-- This wo n't work because it conflicts with other instances such as " Either " :
instance ( , a ) = > DeepFrz ( f s a ) where
type FrzType ( f s a ) = f Frzn ( FrzType a )
frz = unsafeCoerce #
-- This won't work because it conflicts with other instances such as "Either":
instance (LVarData1 f, DeepFrz a) => DeepFrz (f s a) where
type FrzType (f s a) = f Frzn (FrzType a)
frz = unsafeCoerce#
-}
| null | https://raw.githubusercontent.com/iu-parfunc/lvars/78e73c96a929aa75aa4f991d42b2f677849e433a/src/lvish/Control/LVish/DeepFrz.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE MagicHash #
# LANGUAGE RankNTypes #
# LANGUAGE Trustworthy #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeFamilies #
TODO: a more detailed (recursive?) DeepFrz instance example might
be really helpful here for people who want to implement their own
LK
* The functions you'll want to use
* Some supporting types
------------------------------------------------------------------------------
| Under normal conditions, calling a `freeze` operation inside a
(after the implicit global barrier of `runPar`), then we've avoided
having to call `freeze` explicitly.
already. Further, you can create additional instances for custom,
pure datatypes. The result of a `runParThenFreeze` depends on the
`s` parameters of all IVars to the `Frzn` state.
spite of the fact that it enables a /deep/ (recursive) freeze of the value returned
| This version works for nondeterministic computations as well.
Of course, nondeterministic computations may also call `freeze`
internally, but this function has an advantage to doing your own
`freeze` at the end of a `runParIO`: there is an implicit barrier
before the final freeze. Further, `DeepFrz` has no runtime
overhead, whereas regular freezing has a cost.
This wo n't work because it conflicts with other instances such as " Either " :
This won't work because it conflicts with other instances such as "Either": | # LANGUAGE DataKinds #
# LANGUAGE FlexibleInstances #
|
The ` DeepFrz ` module provides a way to return arbitrarily complex data
structures containing LVars from ` Par ` computations .
The important thing to know is that to use ` runParThenFreeze ` to run a
` Par ` computation , you must make sure that all types you return from
the ` Par ` computation have ` DeepFrz ` instances . This means that , if
you wish to return a user - defined type , you will need to include a bit
of boilerplate to give it a ` DeepFrz ` instance . Here is a complete
example :
> { - # LANGUAGE TypeFamilies #
The `DeepFrz` module provides a way to return arbitrarily complex data
structures containing LVars from `Par` computations.
The important thing to know is that to use `runParThenFreeze` to run a
`Par` computation, you must make sure that all types you return from
the `Par` computation have `DeepFrz` instances. This means that, if
you wish to return a user-defined type, you will need to include a bit
of boilerplate to give it a `DeepFrz` instance. Here is a complete
example:
> import Control.LVish.DeepFrz
>
> data MyData = MyData Int deriving Show
>
> instance DeepFrz MyData where
> type FrzType MyData = MyData
>
> main = print (runParThenFreeze (return (MyData 3)))
-}
module Control.LVish.DeepFrz
(
runParThenFreeze,
runParThenFreezeIO,
DeepFrz(), FrzType,
NonFrzn, Frzn, Trvrsbl,
) where
import Control . ( ( .. ) )
import Control.LVish.DeepFrz.Internal (DeepFrz (..), Frzn, NonFrzn,
Trvrsbl)
import Control.LVish.Internal (Par (WrapPar))
import Control.Par.EffectSigs
import Control.LVish.Internal.SchedIdempotent (runPar, runParIO)
` Par ` computation makes the ` Par ` computation quasi - deterministic .
However , if we freeze only after all LVar operations are completed
all data races , and freezing is therefore safe . Running a ` Par `
computation with ` runParThenFreeze ` accomplishes this , without our
In order to use ` runParThenFreeze ` , the type returned from the
` Par ` computation must be a member of the ` DeepFrz ` class . All the
@Data . libraries should provide instances of ` DeepFrz `
type - level function ` FrzType ` , whose only purpose is to toggle the
Significantly , the freeze at the end of ` runParThenFreeze ` has /no/ runtime cost , in
by the ` Par ` computation .
runParThenFreeze :: (DeepFrz a, Deterministic e) => Par e NonFrzn a -> FrzType a
runParThenFreeze : : Deterministic e = > DeepFrz a = > Par e NonFrzn a - > FrzType a
runParThenFreeze (WrapPar p) = frz $ runPar p
runParThenFreezeIO :: DeepFrz a => Par e NonFrzn a -> IO (FrzType a)
runParThenFreezeIO (WrapPar p) = do
x <- runParIO p
return $ frz x
instance ( , a ) = > DeepFrz ( f s a ) where
type FrzType ( f s a ) = f Frzn ( FrzType a )
frz = unsafeCoerce #
instance (LVarData1 f, DeepFrz a) => DeepFrz (f s a) where
type FrzType (f s a) = f Frzn (FrzType a)
frz = unsafeCoerce#
-}
|
b17bfd33c43234aedd5f9b17a3c38d22a52e061efde89afa11a56942843df68b | killme2008/cscheme | core.clj | (ns scheme.test.core
(:use [scheme.core] :reload)
(:use [clojure.test]))
(deftest replace-me ;; FIXME: write
(is false "No tests have been written."))
| null | https://raw.githubusercontent.com/killme2008/cscheme/b18b941e21f0779c247b166de1b1a1cfef7724d2/test/scheme/test/core.clj | clojure | FIXME: write | (ns scheme.test.core
(:use [scheme.core] :reload)
(:use [clojure.test]))
(is false "No tests have been written."))
|
f768265e2802e81a806b171be9b17636c82b3eae82c883afd9d93aa993a82be0 | spechub/Hets | WACocone.hs | |
Module : ./Static / WACocone.hs
Description : heterogeneous signatures colimits approximations
Copyright : ( c ) , and Uni Bremen 2002 - 2006
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non - portable
Heterogeneous version of weakly_amalgamable_cocones .
Needs some improvements ( see TO DO ) .
Module : ./Static/WACocone.hs
Description : heterogeneous signatures colimits approximations
Copyright : (c) Mihai Codescu, and Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non-portable
Heterogeneous version of weakly_amalgamable_cocones.
Needs some improvements (see TO DO).
-}
module Static.WACocone (isConnected,
isAcyclic,
isThin,
removeIdentities,
hetWeakAmalgCocone,
initDescList,
dijkstra,
buildStrMorphisms,
weakly_amalgamable_colimit
) where
import Control.Monad
import Data.List (nub)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Graph.Inductive.Graph as Graph
import Common.Lib.Graph as Tree
import Common.ExtSign
import Common.Result
import Common.LogicT
import qualified Control.Monad.Fail as Fail
import Logic.Logic
import Logic.Comorphism
import Logic.Modification
import Logic.Grothendieck
import Logic.Coerce
import Static.GTheory
import Comorphisms.LogicGraph
weakly_amalgamable_colimit :: StaticAnalysis lid
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol
=> lid -> Tree.Gr sign (Int, morphism)
-> Result (sign, Map.Map Int morphism)
weakly_amalgamable_colimit l diag = do
(sig, sink) <- signature_colimit l diag
return (sig, sink)
{- until amalgamability check is fixed, just return a colimit
get (commented out) code from rev:11881 -}
-- | checks whether a graph is connected
isConnected :: Gr a b -> Bool
isConnected graph = let
nodeList = nodes graph
root = head nodeList
availNodes = Map.fromList $ zip nodeList (repeat True)
bfs queue avail = case queue of
[] -> avail
n : ns -> let
avail1 = Map.insert n False avail
nbs = filter (\ x -> Map.findWithDefault (error "isconnected") x avail)
$ neighbors graph n
in bfs (ns ++ nbs) avail1
in not $ any (\ x -> Map.findWithDefault (error "iscon 2") x
(bfs [root] availNodes)) nodeList
-- | checks whether the graph is thin
isThin :: Gr a b -> Bool
isThin = checkThinness Map.empty . edges
checkThinness :: Map.Map Edge Int -> [Edge] -> Bool
checkThinness paths eList =
case eList of
[] -> True
(sn, tn) : eList' ->
(sn, tn) `notElem` Map.keys paths &&
multiple paths between ( sn , tn )
let pathsToS = filter (\ (_, y) -> y == sn) $ Map.keys paths
updatePaths pathF dest pList =
case pList of
[] -> Just pathF
(x, _) : pList' ->
if (x, dest) `elem` Map.keys pathF then Nothing
else updatePaths (Map.insert (x, dest) 1 pathF) dest pList'
in case updatePaths paths tn pathsToS of
Nothing -> False
Just paths' -> checkThinness (Map.insert (sn, tn) 1 paths') eList'
-- | checks whether a graph is acyclic
isAcyclic :: (Eq b) => Gr a b -> Bool
isAcyclic graph = let
filterIns gr = filter (\ x -> indeg gr x == 0)
queue = filterIns graph $ nodes graph
topologicalSort q gr = case q of
[] -> null $ edges gr
n : ns -> let
oEdges = lsuc gr n
graph1 = foldl (flip Graph.delLEdge) gr
$ map (\ (y, label) -> (n, y, label)) oEdges
succs = filterIns graph1 $ suc gr n
in topologicalSort (ns ++ succs) graph1
in topologicalSort queue graph
-- | auxiliary for removing the identity edges from a graph
removeIdentities :: Gr a b -> Gr a b
removeIdentities graph = let
addEdges gr eList = case eList of
[] -> gr
(sn, tn, label) : eList1 -> if sn == tn then addEdges gr eList1
else addEdges (insEdge (sn, tn, label) gr) eList1
in addEdges (insNodes (labNodes graph) Graph.empty) $ labEdges graph
-- assigns to a node all proper descendents
initDescList :: (Eq a, Eq b) => Gr a b -> Map.Map Node [(Node, a)]
initDescList graph = let
descsOf n = let
nodeList = filter (n /=) $ pre graph n
f = Map.fromList $ zip nodeList (repeat False)
precs nList nList' avail =
case nList of
[] -> nList'
_ -> let
nList'' = concatMap (\ y -> filter
(\ x -> x `notElem` Map.keys avail ||
Map.findWithDefault (error "iDL") x avail) $
filter (y /=) $ pre graph y) nList
avail' = Map.union avail $
Map.fromList $ zip nList'' (repeat False)
in precs (nub nList'') (nub $ nList' ++ nList'') avail'
in precs nodeList nodeList f
in Map.fromList $ map (\ node -> (node, filter (\ x -> fst x `elem`
descsOf node)
$ labNodes graph )) $ nodes graph
commonBounds :: (Eq a) => Map.Map Node [(Node, a)] -> Node -> Node -> [(Node, a)]
commonBounds funDesc n1 n2 = filter
(\ x -> x `elem` (Map.!) funDesc n1 && x `elem` (Map.!) funDesc n2 )
$ nub $ (Map.!) funDesc n1 ++ (Map.!) funDesc n2
returns the greatest lower bound of two maximal nodes , if it exists
glb :: (Eq a) => Map.Map Node [(Node, a)] -> Node -> Node -> Maybe (Node, a)
glb funDesc n1 n2 = let
cDescs = commonBounds funDesc n1 n2
subList [] _ = True
subList (x : xs) l2 = x `elem` l2 && subList xs l2
glbList = filter (\ (n, x) -> subList
(filter (\ (n0, x0) -> (n, x) /= (n0, x0)) cDescs) (funDesc Map.! n)
) cDescs
a node n is glb of n1 and n2 iff
all common bounds of n1 and n2 are also descendants of n
all common bounds of n1 and n2 are also descendants of n -}
in case glbList of
[] -> Nothing
because if it exists , there can be only one
-- if no greatest lower bound exists, compute all maximal bounds of the nodes
maxBounds :: (Eq a) => Map.Map Node [(Node, a)] -> Node -> Node -> [(Node, a)]
maxBounds funDesc n1 n2 = let
cDescs = commonBounds funDesc n1 n2
isDesc n0 (n, y) = (n, y) `elem` funDesc Map.! n0
noDescs (n, y) = not $ any (\ (n0, _) -> isDesc n0 (n, y)) cDescs
in filter noDescs cDescs
dijsktra algorithm for finding the the shortest path between two nodes
dijkstra :: GDiagram -> Node -> Node -> Result GMorphism
dijkstra graph source target = do
let
dist = Map.insert source 0 $ Map.fromList $
zip (nodes graph) $ repeat $ 2 * length (edges graph)
prev = if source == target then Map.insert source source Map.empty
else Map.empty
q = nodes graph
com = case lab graph source of
Nothing -> Map.empty -- shouldnt be the case
Just gt -> Map.insert source (ide $ signOf gt) Map.empty
extractMin queue dMap = let
u = head $
filter (\ x -> Map.findWithDefault (error "dijkstra") x dMap ==
minimum
(map (\ x1 -> Map.findWithDefault (error "dijkstra") x1 dMap)
queue))
queue
in ( Set.toList $ Set.difference (Set.fromList queue) (Set.fromList [u]) , u)
updateNeighbors d p c u gr = let
outEdges = out gr u
upNeighbor dMap pMap cMap uNode edgeList = case edgeList of
[] -> (dMap, pMap, cMap)
(_, v, (_, gmor)) : edgeL -> let
alt = Map.findWithDefault (error "dijkstra") uNode dMap + 1
in
if alt >= Map.findWithDefault (error "dijsktra") v dMap then
upNeighbor dMap pMap cMap uNode edgeL
else let
d1 = Map.insert v alt dMap
p1 = Map.insert v uNode pMap
c1 = Map.insert v gmor cMap
in upNeighbor d1 p1 c1 uNode edgeL
in upNeighbor d p c u outEdges
for each neighbor of u , if d(u)+1 < d(v ) , modify p(v ) = u , d(v ) = d(u)+1
mainloop gr sn tn qL d p c = let
(q1, u) = extractMin qL d
(d1, p1, c1) = updateNeighbors d p c u gr
in if u == tn then shortPath sn p1 c1 [] tn
else mainloop gr sn tn q1 d1 p1 c1
shortPath sn p1 c s u =
if u `notElem` Map.keys p1 then Fail.fail "path not found"
else let
x = Map.findWithDefault (error $ show u) u p1 in
if x == sn then return (u : s, c)
else shortPath sn p1 c (u : s) x
(nodeList, com1) <- mainloop graph source target q dist prev com
foldM comp ((Map.!) com1 source) . map ((Map.!) com1) $ nodeList
{- builds the arrows from the nodes of the original graph
to the unique maximal node of the obtained graph -}
buildStrMorphisms :: GDiagram -> GDiagram
-> Result (G_theory, Map.Map Node GMorphism)
buildStrMorphisms initGraph newGraph = do
let (maxNode, sigma) = head $ filter (\ (node, _) -> outdeg newGraph node == 0) $
labNodes newGraph
buildMor pairList solList =
case pairList of
(n, _) : pairs -> do nMor <- dijkstra newGraph n maxNode
buildMor pairs (solList ++ [(n, nMor)])
[] -> return solList
morList <- buildMor (labNodes initGraph) []
return (sigma, Map.fromList morList)
-- computes the colimit and inserts it into the graph
addNodeToGraph :: GDiagram -> G_theory -> G_theory -> G_theory -> Int -> Int
-> Int -> GMorphism -> GMorphism
-> Map.Map Node [(Node, G_theory)] -> [(Int, G_theory)]
-> Result (GDiagram, Map.Map Node [(Node, G_theory)])
addNodeToGraph oldGraph
(G_theory lid _ extSign _ _ _)
gt1@(G_theory lid1 _ extSign1 idx1 _ _)
gt2@(G_theory lid2 _ extSign2 idx2 _ _)
n
n1
n2
(GMorphism cid1 ss1 _ mor1 _)
(GMorphism cid2 ss2 _ mor2 _)
funDesc maxNodes = do
let newNode = 1 + maximum (nodes oldGraph) -- get a new node
s1 <- coerceSign lid1 lid "addToNodeGraph" extSign1
s2 <- coerceSign lid2 lid "addToNodeGraph" extSign2
m1 <- coerceMorphism (targetLogic cid1) lid "addToNodeGraph" mor1
m2 <- coerceMorphism (targetLogic cid2) lid "addToNodeGraph" mor2
let spanGr = Graph.mkGraph
[(n, plainSign extSign), (n1, plainSign s1), (n2, plainSign s2)]
[(n, n1, (1, m1)), (n, n2, (1, m2))]
(sig, morMap) <- weakly_amalgamable_colimit lid spanGr
-- must coerce here
m11 <- coerceMorphism lid (targetLogic cid1) "addToNodeGraph" $
morMap Map.! n1
m22 <- coerceMorphism lid (targetLogic cid2) "addToNodeGraph" $
morMap Map.! n2
let gth = noSensGTheory lid (mkExtSign sig) startSigId
gmor1 = GMorphism cid1 ss1 idx1 m11 startMorId
gmor2 = GMorphism cid2 ss2 idx2 m22 startMorId
case maxNodes of
[] -> do
let newGraph = insEdges [(n1, newNode, (1, gmor1)), (n2, newNode, (1, gmor2))] $
insNode (newNode, gth) oldGraph
funDesc1 = Map.insert newNode
(nub $ (Map.!) funDesc n1 ++ (Map.!) funDesc n2 ) funDesc
return (newGraph, funDesc1)
_ -> computeCoeqs oldGraph funDesc (n1, gt1) (n2, gt2)
(newNode, gth) gmor1 gmor2 maxNodes
{- for each node in the list, check whether the coequalizer can be computed
if so, modify the maximal node of graph and the edges to it from n1 and n2 -}
computeCoeqs :: GDiagram -> Map.Map Node [(Node, G_theory)]
-> (Node, G_theory) -> (Node, G_theory) -> (Node, G_theory)
-> GMorphism -> GMorphism -> [(Node, G_theory)] ->
Result (GDiagram, Map.Map Node [(Node, G_theory)])
computeCoeqs oldGraph funDesc (n1, _) (n2, _) (newN, newGt) gmor1 gmor2 [] = do
let newGraph = insEdges [(n1, newN, (1, gmor1)), (n2, newN, (1, gmor2))] $
insNode (newN, newGt) oldGraph
descFun1 = Map.insert newN
(nub $ (Map.!) funDesc n1 ++ (Map.!) funDesc n2 ) funDesc
return (newGraph, descFun1)
computeCoeqs graph funDesc (n1, gt1) (n2, gt2)
(newN, _newGt@(G_theory tlid _ tsign _ _ _))
_gmor1@(GMorphism cid1 sig1 idx1 mor1 _ )
_gmor2@(GMorphism cid2 sig2 idx2 mor2 _ ) ((n, gt) : descs) = do
_rho1@(GMorphism cid3 _ _ mor3 _) <- dijkstra graph n n1
_rho2@(GMorphism cid4 _ _ mor4 _) <- dijkstra graph n n2
com1 <- compComorphism (Comorphism cid1) (Comorphism cid3)
com2 <- compComorphism (Comorphism cid1) (Comorphism cid3)
if com1 /= com2 then Fail.fail "Unable to compute coequalizer" else do
_gtM@(G_theory lidM _ signM _idxM _ _) <- mapG_theory False com1 gt
s1 <- coerceSign lidM tlid "coequalizers" signM
mor3' <- coerceMorphism (targetLogic cid3) (sourceLogic cid1) "coeqs" mor3
mor4' <- coerceMorphism (targetLogic cid4) (sourceLogic cid2) "coeqs" mor4
m1 <- map_morphism cid1 mor3'
m2 <- map_morphism cid2 mor4'
phi1' <- comp m1 mor1
phi2' <- comp m2 mor2
phi1 <- coerceMorphism (targetLogic cid1) tlid "coeqs" phi1'
phi2 <- coerceMorphism (targetLogic cid2) tlid "coeqs" phi2'
-- build the double arrow for computing the coequalizers
let doubleArrow = Graph.mkGraph
[(n, plainSign s1), (newN, plainSign tsign)]
[(n, newN, (1, phi1)), (n, newN, (1, phi2))]
(colS, colM) <- weakly_amalgamable_colimit tlid doubleArrow
let newGt1 = noSensGTheory tlid (mkExtSign colS) startSigId
mor11' <- coerceMorphism tlid (targetLogic cid1) "coeqs" $ (Map.!) colM newN
mor11 <- comp mor1 mor11'
mor22' <- coerceMorphism tlid (targetLogic cid2) "coeqs" $ (Map.!) colM newN
mor22 <- comp mor2 mor22'
let gMor11 = GMorphism cid1 sig1 idx1 mor11 startMorId
let gMor22 = GMorphism cid2 sig2 idx2 mor22 startMorId
computeCoeqs graph funDesc (n1, gt1) (n2, gt2) (newN, newGt1)
gMor11 gMor22 descs
-- returns a maximal node available
pickMaxNode :: (MonadPlus t) => Gr a b -> t (Node, a)
pickMaxNode graph = msum $ map return $
filter (\ (node, _) -> outdeg graph node == 0) $
labNodes graph
returns a list of common descendants of two maximal nodes :
one node if a glb exists , or all maximal descendants otherwise
one node if a glb exists, or all maximal descendants otherwise -}
commonDesc :: Map.Map Node [(Node, G_theory)] -> Node -> Node
-> [(Node, G_theory)]
commonDesc funDesc n1 n2 = case glb funDesc n1 n2 of
Just x -> [x]
Nothing -> maxBounds funDesc n1 n2
-- returns a weakly amalgamable square of lax triangles
pickSquare :: (MonadPlus t, Fail.MonadFail t) => Result GMorphism -> Result GMorphism
-> t Square
pickSquare (Result _ (Just phi1@(GMorphism cid1 _ _ _ _)))
(Result _ (Just phi2@(GMorphism cid2 _ _ _ _))) =
if isHomogeneous phi1 && isHomogeneous phi2 then
return $ mkIdSquare $ Logic $ sourceLogic cid1
-- since they have the same target, both homogeneous implies same logic
else do
if one of them is homogeneous , build the square
with identity modification of the other comorphism
with identity modification of the other comorphism -}
let defaultSquare
| isHomogeneous phi1 = [mkDefSquare $ Comorphism cid2]
| isHomogeneous phi2 = [mirrorSquare $ mkDefSquare $ Comorphism cid1]
| otherwise = []
case maybeResult $ lookupSquare_in_LG (Comorphism cid1) (Comorphism cid2) of
Nothing -> msum $ map return defaultSquare
Just sqList -> msum $ map return $ sqList ++ defaultSquare
pickSquare (Result _ Nothing) _ = Fail.fail "Error computing comorphisms"
pickSquare _ (Result _ Nothing) = Fail.fail "Error computing comorphisms"
-- builds the span for which the colimit is computed
buildSpan :: GDiagram ->
Map.Map Node [(Node, G_theory)] ->
AnyComorphism ->
AnyComorphism ->
AnyComorphism ->
AnyComorphism ->
AnyComorphism ->
AnyModification ->
AnyModification ->
G_theory ->
G_theory ->
G_theory ->
GMorphism ->
GMorphism ->
Int -> Int -> Int ->
[(Int, G_theory)] ->
Result (GDiagram, Map.Map Node [(Node, G_theory)])
buildSpan graph
funDesc
d@(Comorphism _cidD)
e1@(Comorphism cidE1)
e2@(Comorphism cidE2)
_d1@(Comorphism _cidD1)
_d2@(Comorphism _cidD2)
_m1@(Modification cidM1)
_m2@(Modification cidM2)
gt@(G_theory lid _ sign _ _ _)
gt1@(G_theory lid1 _ sign1 _ _ _)
gt2@(G_theory lid2 _ sign2 _ _ _)
_phi1@(GMorphism cid1 _ _ mor1 _)
_phi2@(GMorphism cid2 _ _ mor2 _)
n n1 n2
maxNodes
= do
sig@(G_theory _lid0 _ _sign0 _ _ _) <- mapG_theory False d gt -- phi^d(Sigma)
sig1 <- mapG_theory False e1 gt1 -- phi^e1(Sigma1)
sig2 <- mapG_theory False e2 gt2 -- phi^e2(Sigma2)
mor1' <- coerceMorphism (targetLogic cid1) (sourceLogic cidE1) "buildSpan" mor1
eps1 <- map_morphism cidE1 mor1' -- phi^e1(sigma1)
sign' <- coerceSign lid (sourceLogic $ sourceComorphism cidM1) "buildSpan" sign
tau1 <- tauSigma cidM1 (plainSign sign') -- I^u1_Sigma
tau1' <- coerceMorphism (targetLogic $ sourceComorphism cidM1)
(targetLogic cidE1) "buildSpan" tau1
rho1 <- comp tau1' eps1
mor2' <- coerceMorphism (targetLogic cid2) (sourceLogic cidE2) "buildSpan" mor2
eps2 <- map_morphism cidE2 mor2' -- phi^e2(sigma2)
sign'' <- coerceSign lid (sourceLogic $ sourceComorphism cidM2) "buildSpan" sign
tau2 <- tauSigma cidM2 (plainSign sign'') -- I^u2_Sigma
tau2' <- coerceMorphism (targetLogic $ sourceComorphism cidM2)
(targetLogic cidE2) "buildSpan" tau2
rho2 <- comp tau2' eps2
signE1 <- coerceSign lid1 (sourceLogic cidE1) " " sign1
signE2 <- coerceSign lid2 (sourceLogic cidE2) " " sign2
(graph1, funDesc1) <- addNodeToGraph graph sig sig1 sig2 n n1 n2
(GMorphism cidE1 signE1 startSigId rho1 startMorId)
(GMorphism cidE2 signE2 startSigId rho2 startMorId)
funDesc maxNodes
return (graph1, funDesc1)
pickMaximalDesc :: (MonadPlus t) => [(Node, G_theory)] -> t (Node, G_theory)
pickMaximalDesc descList = msum $ map return descList
nrMaxNodes :: Gr a b -> Int
nrMaxNodes graph = length $ filter (\ n -> outdeg graph n == 0) $ nodes graph
-- | backtracking function for heterogeneous weak amalgamable cocones
hetWeakAmalgCocone :: (Fail.MonadFail m, LogicT t, MonadPlus (t m),
Fail.MonadFail (t m)) =>
GDiagram -> Map.Map Int [(Int, G_theory)] -> t m GDiagram
hetWeakAmalgCocone graph funDesc =
if nrMaxNodes graph == 1 then return graph
else once $ do
(n1, gt1) <- pickMaxNode graph
(n2, gt2) <- pickMaxNode graph
guard (n1 < n2) -- to consider each pair of maximal nodes only once
let descList = commonDesc funDesc n1 n2
case length descList of
0 -> mzero -- no common descendants for n1 and n2
_ -> do {- just one common descendant implies greatest lower bound
for several, the tail is not empty and we compute coequalizers -}
(n, gt) <- pickMaximalDesc descList
let phi1 = dijkstra graph n n1
phi2 = dijkstra graph n n2
square <- pickSquare phi1 phi2
let d = laxTarget $ leftTriangle square
e1 = laxFst $ leftTriangle square
d1 = laxSnd $ leftTriangle square
e2 = laxFst $ rightTriangle square
d2 = laxSnd $ rightTriangle square
m1 = laxModif $ leftTriangle square
m2 = laxModif $ rightTriangle square
case maybeResult phi1 of
Nothing -> mzero
Just phi1' -> case maybeResult phi2 of
Nothing -> mzero
Just phi2' -> do
let mGraph = buildSpan graph funDesc d e1 e2 d1 d2 m1 m2 gt gt1 gt2
phi1' phi2' n n1 n2 $ filter (\ (nx, _) -> nx /= n) descList
case maybeResult mGraph of
Nothing -> mzero
Just (graph1, funDesc1) -> hetWeakAmalgCocone graph1 funDesc1
| null | https://raw.githubusercontent.com/spechub/Hets/f582640a174df08d4c965d7c0a1ab24d1a31000d/Static/WACocone.hs | haskell | until amalgamability check is fixed, just return a colimit
get (commented out) code from rev:11881
| checks whether a graph is connected
| checks whether the graph is thin
| checks whether a graph is acyclic
| auxiliary for removing the identity edges from a graph
assigns to a node all proper descendents
if no greatest lower bound exists, compute all maximal bounds of the nodes
shouldnt be the case
builds the arrows from the nodes of the original graph
to the unique maximal node of the obtained graph
computes the colimit and inserts it into the graph
get a new node
must coerce here
for each node in the list, check whether the coequalizer can be computed
if so, modify the maximal node of graph and the edges to it from n1 and n2
build the double arrow for computing the coequalizers
returns a maximal node available
returns a weakly amalgamable square of lax triangles
since they have the same target, both homogeneous implies same logic
builds the span for which the colimit is computed
phi^d(Sigma)
phi^e1(Sigma1)
phi^e2(Sigma2)
phi^e1(sigma1)
I^u1_Sigma
phi^e2(sigma2)
I^u2_Sigma
| backtracking function for heterogeneous weak amalgamable cocones
to consider each pair of maximal nodes only once
no common descendants for n1 and n2
just one common descendant implies greatest lower bound
for several, the tail is not empty and we compute coequalizers | |
Module : ./Static / WACocone.hs
Description : heterogeneous signatures colimits approximations
Copyright : ( c ) , and Uni Bremen 2002 - 2006
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non - portable
Heterogeneous version of weakly_amalgamable_cocones .
Needs some improvements ( see TO DO ) .
Module : ./Static/WACocone.hs
Description : heterogeneous signatures colimits approximations
Copyright : (c) Mihai Codescu, and Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non-portable
Heterogeneous version of weakly_amalgamable_cocones.
Needs some improvements (see TO DO).
-}
module Static.WACocone (isConnected,
isAcyclic,
isThin,
removeIdentities,
hetWeakAmalgCocone,
initDescList,
dijkstra,
buildStrMorphisms,
weakly_amalgamable_colimit
) where
import Control.Monad
import Data.List (nub)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Graph.Inductive.Graph as Graph
import Common.Lib.Graph as Tree
import Common.ExtSign
import Common.Result
import Common.LogicT
import qualified Control.Monad.Fail as Fail
import Logic.Logic
import Logic.Comorphism
import Logic.Modification
import Logic.Grothendieck
import Logic.Coerce
import Static.GTheory
import Comorphisms.LogicGraph
weakly_amalgamable_colimit :: StaticAnalysis lid
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol
=> lid -> Tree.Gr sign (Int, morphism)
-> Result (sign, Map.Map Int morphism)
weakly_amalgamable_colimit l diag = do
(sig, sink) <- signature_colimit l diag
return (sig, sink)
isConnected :: Gr a b -> Bool
isConnected graph = let
nodeList = nodes graph
root = head nodeList
availNodes = Map.fromList $ zip nodeList (repeat True)
bfs queue avail = case queue of
[] -> avail
n : ns -> let
avail1 = Map.insert n False avail
nbs = filter (\ x -> Map.findWithDefault (error "isconnected") x avail)
$ neighbors graph n
in bfs (ns ++ nbs) avail1
in not $ any (\ x -> Map.findWithDefault (error "iscon 2") x
(bfs [root] availNodes)) nodeList
isThin :: Gr a b -> Bool
isThin = checkThinness Map.empty . edges
checkThinness :: Map.Map Edge Int -> [Edge] -> Bool
checkThinness paths eList =
case eList of
[] -> True
(sn, tn) : eList' ->
(sn, tn) `notElem` Map.keys paths &&
multiple paths between ( sn , tn )
let pathsToS = filter (\ (_, y) -> y == sn) $ Map.keys paths
updatePaths pathF dest pList =
case pList of
[] -> Just pathF
(x, _) : pList' ->
if (x, dest) `elem` Map.keys pathF then Nothing
else updatePaths (Map.insert (x, dest) 1 pathF) dest pList'
in case updatePaths paths tn pathsToS of
Nothing -> False
Just paths' -> checkThinness (Map.insert (sn, tn) 1 paths') eList'
isAcyclic :: (Eq b) => Gr a b -> Bool
isAcyclic graph = let
filterIns gr = filter (\ x -> indeg gr x == 0)
queue = filterIns graph $ nodes graph
topologicalSort q gr = case q of
[] -> null $ edges gr
n : ns -> let
oEdges = lsuc gr n
graph1 = foldl (flip Graph.delLEdge) gr
$ map (\ (y, label) -> (n, y, label)) oEdges
succs = filterIns graph1 $ suc gr n
in topologicalSort (ns ++ succs) graph1
in topologicalSort queue graph
removeIdentities :: Gr a b -> Gr a b
removeIdentities graph = let
addEdges gr eList = case eList of
[] -> gr
(sn, tn, label) : eList1 -> if sn == tn then addEdges gr eList1
else addEdges (insEdge (sn, tn, label) gr) eList1
in addEdges (insNodes (labNodes graph) Graph.empty) $ labEdges graph
initDescList :: (Eq a, Eq b) => Gr a b -> Map.Map Node [(Node, a)]
initDescList graph = let
descsOf n = let
nodeList = filter (n /=) $ pre graph n
f = Map.fromList $ zip nodeList (repeat False)
precs nList nList' avail =
case nList of
[] -> nList'
_ -> let
nList'' = concatMap (\ y -> filter
(\ x -> x `notElem` Map.keys avail ||
Map.findWithDefault (error "iDL") x avail) $
filter (y /=) $ pre graph y) nList
avail' = Map.union avail $
Map.fromList $ zip nList'' (repeat False)
in precs (nub nList'') (nub $ nList' ++ nList'') avail'
in precs nodeList nodeList f
in Map.fromList $ map (\ node -> (node, filter (\ x -> fst x `elem`
descsOf node)
$ labNodes graph )) $ nodes graph
commonBounds :: (Eq a) => Map.Map Node [(Node, a)] -> Node -> Node -> [(Node, a)]
commonBounds funDesc n1 n2 = filter
(\ x -> x `elem` (Map.!) funDesc n1 && x `elem` (Map.!) funDesc n2 )
$ nub $ (Map.!) funDesc n1 ++ (Map.!) funDesc n2
returns the greatest lower bound of two maximal nodes , if it exists
glb :: (Eq a) => Map.Map Node [(Node, a)] -> Node -> Node -> Maybe (Node, a)
glb funDesc n1 n2 = let
cDescs = commonBounds funDesc n1 n2
subList [] _ = True
subList (x : xs) l2 = x `elem` l2 && subList xs l2
glbList = filter (\ (n, x) -> subList
(filter (\ (n0, x0) -> (n, x) /= (n0, x0)) cDescs) (funDesc Map.! n)
) cDescs
a node n is glb of n1 and n2 iff
all common bounds of n1 and n2 are also descendants of n
all common bounds of n1 and n2 are also descendants of n -}
in case glbList of
[] -> Nothing
because if it exists , there can be only one
maxBounds :: (Eq a) => Map.Map Node [(Node, a)] -> Node -> Node -> [(Node, a)]
maxBounds funDesc n1 n2 = let
cDescs = commonBounds funDesc n1 n2
isDesc n0 (n, y) = (n, y) `elem` funDesc Map.! n0
noDescs (n, y) = not $ any (\ (n0, _) -> isDesc n0 (n, y)) cDescs
in filter noDescs cDescs
dijsktra algorithm for finding the the shortest path between two nodes
dijkstra :: GDiagram -> Node -> Node -> Result GMorphism
dijkstra graph source target = do
let
dist = Map.insert source 0 $ Map.fromList $
zip (nodes graph) $ repeat $ 2 * length (edges graph)
prev = if source == target then Map.insert source source Map.empty
else Map.empty
q = nodes graph
com = case lab graph source of
Just gt -> Map.insert source (ide $ signOf gt) Map.empty
extractMin queue dMap = let
u = head $
filter (\ x -> Map.findWithDefault (error "dijkstra") x dMap ==
minimum
(map (\ x1 -> Map.findWithDefault (error "dijkstra") x1 dMap)
queue))
queue
in ( Set.toList $ Set.difference (Set.fromList queue) (Set.fromList [u]) , u)
updateNeighbors d p c u gr = let
outEdges = out gr u
upNeighbor dMap pMap cMap uNode edgeList = case edgeList of
[] -> (dMap, pMap, cMap)
(_, v, (_, gmor)) : edgeL -> let
alt = Map.findWithDefault (error "dijkstra") uNode dMap + 1
in
if alt >= Map.findWithDefault (error "dijsktra") v dMap then
upNeighbor dMap pMap cMap uNode edgeL
else let
d1 = Map.insert v alt dMap
p1 = Map.insert v uNode pMap
c1 = Map.insert v gmor cMap
in upNeighbor d1 p1 c1 uNode edgeL
in upNeighbor d p c u outEdges
for each neighbor of u , if d(u)+1 < d(v ) , modify p(v ) = u , d(v ) = d(u)+1
mainloop gr sn tn qL d p c = let
(q1, u) = extractMin qL d
(d1, p1, c1) = updateNeighbors d p c u gr
in if u == tn then shortPath sn p1 c1 [] tn
else mainloop gr sn tn q1 d1 p1 c1
shortPath sn p1 c s u =
if u `notElem` Map.keys p1 then Fail.fail "path not found"
else let
x = Map.findWithDefault (error $ show u) u p1 in
if x == sn then return (u : s, c)
else shortPath sn p1 c (u : s) x
(nodeList, com1) <- mainloop graph source target q dist prev com
foldM comp ((Map.!) com1 source) . map ((Map.!) com1) $ nodeList
buildStrMorphisms :: GDiagram -> GDiagram
-> Result (G_theory, Map.Map Node GMorphism)
buildStrMorphisms initGraph newGraph = do
let (maxNode, sigma) = head $ filter (\ (node, _) -> outdeg newGraph node == 0) $
labNodes newGraph
buildMor pairList solList =
case pairList of
(n, _) : pairs -> do nMor <- dijkstra newGraph n maxNode
buildMor pairs (solList ++ [(n, nMor)])
[] -> return solList
morList <- buildMor (labNodes initGraph) []
return (sigma, Map.fromList morList)
addNodeToGraph :: GDiagram -> G_theory -> G_theory -> G_theory -> Int -> Int
-> Int -> GMorphism -> GMorphism
-> Map.Map Node [(Node, G_theory)] -> [(Int, G_theory)]
-> Result (GDiagram, Map.Map Node [(Node, G_theory)])
addNodeToGraph oldGraph
(G_theory lid _ extSign _ _ _)
gt1@(G_theory lid1 _ extSign1 idx1 _ _)
gt2@(G_theory lid2 _ extSign2 idx2 _ _)
n
n1
n2
(GMorphism cid1 ss1 _ mor1 _)
(GMorphism cid2 ss2 _ mor2 _)
funDesc maxNodes = do
s1 <- coerceSign lid1 lid "addToNodeGraph" extSign1
s2 <- coerceSign lid2 lid "addToNodeGraph" extSign2
m1 <- coerceMorphism (targetLogic cid1) lid "addToNodeGraph" mor1
m2 <- coerceMorphism (targetLogic cid2) lid "addToNodeGraph" mor2
let spanGr = Graph.mkGraph
[(n, plainSign extSign), (n1, plainSign s1), (n2, plainSign s2)]
[(n, n1, (1, m1)), (n, n2, (1, m2))]
(sig, morMap) <- weakly_amalgamable_colimit lid spanGr
m11 <- coerceMorphism lid (targetLogic cid1) "addToNodeGraph" $
morMap Map.! n1
m22 <- coerceMorphism lid (targetLogic cid2) "addToNodeGraph" $
morMap Map.! n2
let gth = noSensGTheory lid (mkExtSign sig) startSigId
gmor1 = GMorphism cid1 ss1 idx1 m11 startMorId
gmor2 = GMorphism cid2 ss2 idx2 m22 startMorId
case maxNodes of
[] -> do
let newGraph = insEdges [(n1, newNode, (1, gmor1)), (n2, newNode, (1, gmor2))] $
insNode (newNode, gth) oldGraph
funDesc1 = Map.insert newNode
(nub $ (Map.!) funDesc n1 ++ (Map.!) funDesc n2 ) funDesc
return (newGraph, funDesc1)
_ -> computeCoeqs oldGraph funDesc (n1, gt1) (n2, gt2)
(newNode, gth) gmor1 gmor2 maxNodes
computeCoeqs :: GDiagram -> Map.Map Node [(Node, G_theory)]
-> (Node, G_theory) -> (Node, G_theory) -> (Node, G_theory)
-> GMorphism -> GMorphism -> [(Node, G_theory)] ->
Result (GDiagram, Map.Map Node [(Node, G_theory)])
computeCoeqs oldGraph funDesc (n1, _) (n2, _) (newN, newGt) gmor1 gmor2 [] = do
let newGraph = insEdges [(n1, newN, (1, gmor1)), (n2, newN, (1, gmor2))] $
insNode (newN, newGt) oldGraph
descFun1 = Map.insert newN
(nub $ (Map.!) funDesc n1 ++ (Map.!) funDesc n2 ) funDesc
return (newGraph, descFun1)
computeCoeqs graph funDesc (n1, gt1) (n2, gt2)
(newN, _newGt@(G_theory tlid _ tsign _ _ _))
_gmor1@(GMorphism cid1 sig1 idx1 mor1 _ )
_gmor2@(GMorphism cid2 sig2 idx2 mor2 _ ) ((n, gt) : descs) = do
_rho1@(GMorphism cid3 _ _ mor3 _) <- dijkstra graph n n1
_rho2@(GMorphism cid4 _ _ mor4 _) <- dijkstra graph n n2
com1 <- compComorphism (Comorphism cid1) (Comorphism cid3)
com2 <- compComorphism (Comorphism cid1) (Comorphism cid3)
if com1 /= com2 then Fail.fail "Unable to compute coequalizer" else do
_gtM@(G_theory lidM _ signM _idxM _ _) <- mapG_theory False com1 gt
s1 <- coerceSign lidM tlid "coequalizers" signM
mor3' <- coerceMorphism (targetLogic cid3) (sourceLogic cid1) "coeqs" mor3
mor4' <- coerceMorphism (targetLogic cid4) (sourceLogic cid2) "coeqs" mor4
m1 <- map_morphism cid1 mor3'
m2 <- map_morphism cid2 mor4'
phi1' <- comp m1 mor1
phi2' <- comp m2 mor2
phi1 <- coerceMorphism (targetLogic cid1) tlid "coeqs" phi1'
phi2 <- coerceMorphism (targetLogic cid2) tlid "coeqs" phi2'
let doubleArrow = Graph.mkGraph
[(n, plainSign s1), (newN, plainSign tsign)]
[(n, newN, (1, phi1)), (n, newN, (1, phi2))]
(colS, colM) <- weakly_amalgamable_colimit tlid doubleArrow
let newGt1 = noSensGTheory tlid (mkExtSign colS) startSigId
mor11' <- coerceMorphism tlid (targetLogic cid1) "coeqs" $ (Map.!) colM newN
mor11 <- comp mor1 mor11'
mor22' <- coerceMorphism tlid (targetLogic cid2) "coeqs" $ (Map.!) colM newN
mor22 <- comp mor2 mor22'
let gMor11 = GMorphism cid1 sig1 idx1 mor11 startMorId
let gMor22 = GMorphism cid2 sig2 idx2 mor22 startMorId
computeCoeqs graph funDesc (n1, gt1) (n2, gt2) (newN, newGt1)
gMor11 gMor22 descs
pickMaxNode :: (MonadPlus t) => Gr a b -> t (Node, a)
pickMaxNode graph = msum $ map return $
filter (\ (node, _) -> outdeg graph node == 0) $
labNodes graph
returns a list of common descendants of two maximal nodes :
one node if a glb exists , or all maximal descendants otherwise
one node if a glb exists, or all maximal descendants otherwise -}
commonDesc :: Map.Map Node [(Node, G_theory)] -> Node -> Node
-> [(Node, G_theory)]
commonDesc funDesc n1 n2 = case glb funDesc n1 n2 of
Just x -> [x]
Nothing -> maxBounds funDesc n1 n2
pickSquare :: (MonadPlus t, Fail.MonadFail t) => Result GMorphism -> Result GMorphism
-> t Square
pickSquare (Result _ (Just phi1@(GMorphism cid1 _ _ _ _)))
(Result _ (Just phi2@(GMorphism cid2 _ _ _ _))) =
if isHomogeneous phi1 && isHomogeneous phi2 then
return $ mkIdSquare $ Logic $ sourceLogic cid1
else do
if one of them is homogeneous , build the square
with identity modification of the other comorphism
with identity modification of the other comorphism -}
let defaultSquare
| isHomogeneous phi1 = [mkDefSquare $ Comorphism cid2]
| isHomogeneous phi2 = [mirrorSquare $ mkDefSquare $ Comorphism cid1]
| otherwise = []
case maybeResult $ lookupSquare_in_LG (Comorphism cid1) (Comorphism cid2) of
Nothing -> msum $ map return defaultSquare
Just sqList -> msum $ map return $ sqList ++ defaultSquare
pickSquare (Result _ Nothing) _ = Fail.fail "Error computing comorphisms"
pickSquare _ (Result _ Nothing) = Fail.fail "Error computing comorphisms"
buildSpan :: GDiagram ->
Map.Map Node [(Node, G_theory)] ->
AnyComorphism ->
AnyComorphism ->
AnyComorphism ->
AnyComorphism ->
AnyComorphism ->
AnyModification ->
AnyModification ->
G_theory ->
G_theory ->
G_theory ->
GMorphism ->
GMorphism ->
Int -> Int -> Int ->
[(Int, G_theory)] ->
Result (GDiagram, Map.Map Node [(Node, G_theory)])
buildSpan graph
funDesc
d@(Comorphism _cidD)
e1@(Comorphism cidE1)
e2@(Comorphism cidE2)
_d1@(Comorphism _cidD1)
_d2@(Comorphism _cidD2)
_m1@(Modification cidM1)
_m2@(Modification cidM2)
gt@(G_theory lid _ sign _ _ _)
gt1@(G_theory lid1 _ sign1 _ _ _)
gt2@(G_theory lid2 _ sign2 _ _ _)
_phi1@(GMorphism cid1 _ _ mor1 _)
_phi2@(GMorphism cid2 _ _ mor2 _)
n n1 n2
maxNodes
= do
mor1' <- coerceMorphism (targetLogic cid1) (sourceLogic cidE1) "buildSpan" mor1
sign' <- coerceSign lid (sourceLogic $ sourceComorphism cidM1) "buildSpan" sign
tau1' <- coerceMorphism (targetLogic $ sourceComorphism cidM1)
(targetLogic cidE1) "buildSpan" tau1
rho1 <- comp tau1' eps1
mor2' <- coerceMorphism (targetLogic cid2) (sourceLogic cidE2) "buildSpan" mor2
sign'' <- coerceSign lid (sourceLogic $ sourceComorphism cidM2) "buildSpan" sign
tau2' <- coerceMorphism (targetLogic $ sourceComorphism cidM2)
(targetLogic cidE2) "buildSpan" tau2
rho2 <- comp tau2' eps2
signE1 <- coerceSign lid1 (sourceLogic cidE1) " " sign1
signE2 <- coerceSign lid2 (sourceLogic cidE2) " " sign2
(graph1, funDesc1) <- addNodeToGraph graph sig sig1 sig2 n n1 n2
(GMorphism cidE1 signE1 startSigId rho1 startMorId)
(GMorphism cidE2 signE2 startSigId rho2 startMorId)
funDesc maxNodes
return (graph1, funDesc1)
pickMaximalDesc :: (MonadPlus t) => [(Node, G_theory)] -> t (Node, G_theory)
pickMaximalDesc descList = msum $ map return descList
nrMaxNodes :: Gr a b -> Int
nrMaxNodes graph = length $ filter (\ n -> outdeg graph n == 0) $ nodes graph
hetWeakAmalgCocone :: (Fail.MonadFail m, LogicT t, MonadPlus (t m),
Fail.MonadFail (t m)) =>
GDiagram -> Map.Map Int [(Int, G_theory)] -> t m GDiagram
hetWeakAmalgCocone graph funDesc =
if nrMaxNodes graph == 1 then return graph
else once $ do
(n1, gt1) <- pickMaxNode graph
(n2, gt2) <- pickMaxNode graph
let descList = commonDesc funDesc n1 n2
case length descList of
(n, gt) <- pickMaximalDesc descList
let phi1 = dijkstra graph n n1
phi2 = dijkstra graph n n2
square <- pickSquare phi1 phi2
let d = laxTarget $ leftTriangle square
e1 = laxFst $ leftTriangle square
d1 = laxSnd $ leftTriangle square
e2 = laxFst $ rightTriangle square
d2 = laxSnd $ rightTriangle square
m1 = laxModif $ leftTriangle square
m2 = laxModif $ rightTriangle square
case maybeResult phi1 of
Nothing -> mzero
Just phi1' -> case maybeResult phi2 of
Nothing -> mzero
Just phi2' -> do
let mGraph = buildSpan graph funDesc d e1 e2 d1 d2 m1 m2 gt gt1 gt2
phi1' phi2' n n1 n2 $ filter (\ (nx, _) -> nx /= n) descList
case maybeResult mGraph of
Nothing -> mzero
Just (graph1, funDesc1) -> hetWeakAmalgCocone graph1 funDesc1
|
ab285556c033024b8b9d97e536bba1260ccf89d8b8e7c410de6fe347384d7d81 | facebookincubator/hsthrift | OptParse.hs | Copyright ( c ) Facebook , Inc. and its affiliates .
module Util.OptParse
( -- * Options
intOption
, doubleOption
, textOption
, maybeStrOption
, maybeTextOption
, maybeIntOption
, textCommaSplit
, testCommaSplitAndStrip
, stringCommaSplit
, readCommaSplit
, absFilePathOption
, relativeFilePathOption
, maybeAbsFilePathOption
, maybeRelativeFilePathOption
, jsonOption
-- * Commands
, commandParser
-- * Pure Parser
, runParserOnString
-- * Dragons and stuff
, partialParse
) where
import Data.Aeson (FromJSON(..), eitherDecodeStrict')
import Data.Bifunctor (second)
import Data.Char (isSpace)
import qualified Data.List.Split as List
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Text.Encoding (encodeUtf8)
import Options.Applicative
import Options.Applicative.Types
import Util.FilePath
import Util.String
intOption :: Mod OptionFields Int -> Parser Int
intOption = option auto
doubleOption :: Mod OptionFields Double -> Parser Double
doubleOption = option auto
textOption :: Mod OptionFields Text -> Parser Text
textOption = option (Text.pack <$> str)
maybeStrOption :: Mod OptionFields String -> Parser (Maybe String)
maybeStrOption = optional . option str
maybeTextOption :: Mod OptionFields Text -> Parser (Maybe Text)
maybeTextOption = optional . option (Text.pack <$> str)
maybeIntOption :: Mod OptionFields Int -> Parser (Maybe Int)
maybeIntOption = optional . option (read <$> str)
textCommaSplit :: ReadM [Text]
textCommaSplit = Text.splitOn "," . Text.pack <$> str
testCommaSplitAndStrip :: ReadM [Text]
testCommaSplitAndStrip = map Text.strip <$> textCommaSplit
stringCommaSplit :: ReadM [String]
stringCommaSplit = List.splitOn "," <$> str
readCommaSplit :: Read a => ReadM [a]
readCommaSplit = map (read . strip) <$> stringCommaSplit
jsonOption :: FromJSON a => Mod OptionFields a -> Parser a
jsonOption =
option (eitherReader $ eitherDecodeStrict' . encodeUtf8 . Text.pack)
-- | Returns an absolute file path, while handling relative paths and ~
absFilePathOption :: DirEnv -> Mod OptionFields FilePath -> Parser FilePath
absFilePathOption e = option (absolutiseWith e <$> str)
-- | Returns a relative file path
relativeFilePathOption :: Mod OptionFields FilePath -> Parser FilePath
relativeFilePathOption = option str
-- | Returns an absolute file path, while handling relative paths and ~
maybeAbsFilePathOption
:: DirEnv
-> Mod OptionFields FilePath
-> Parser (Maybe FilePath)
maybeAbsFilePathOption e = optional . option (absolutiseWith e <$> str)
-- | Returns a relative file path
maybeRelativeFilePathOption
:: Mod OptionFields FilePath
-> Parser (Maybe FilePath)
maybeRelativeFilePathOption = optional . option str
-- | Build a command subparser from a name, description, and parser.
--
Example : " foo " ( progDesc " does bar . " ) ( ... parser ... )
commandParser
:: String -- ^ command name (the 'cmd' in 'prog cmd --cmdflag1')
-> InfoMod a -- ^ command description in --help output
-> Parser a -- ^ parser of command's flags
-> Parser a
commandParser cmd desc p =
subparser $ metavar cmd <> command cmd (info (helper <*> p) desc)
-- | Run given parser on a string.
runParserOnString :: String -> Parser a -> String -> Either String a
runParserOnString cmdName p args =
case parse of
Success x -> Right x
Failure f -> Left $ fst $ renderFailure f cmdName
CompletionInvoked _ -> Left "Completion Invoked"
where
parse = execParserPure
(prefs mempty) (info (p <**> helper) fullDesc) (quotedWords args)
recurse (w,s) = w : quotedWords s
Mimic shell 's ability to group tokens with double quotes .
quotedWords s =
case dropWhile isSpace s of
"" -> []
('"':cs) -> recurse . second tail $ break (=='"') cs
s' -> recurse $ break isSpace s'
-- -----------------------------------------------------------------------------
-- Things from Options.Applicative that have changed
-- | Attempts to parse across *all* arguments, returning ones that were
-- unrecognized. Fails if a required argument is missing.
partialParse :: ParserPrefs -> ParserInfo a -> [String] -> IO (a, [String])
partialParse pprefs pinfo args = handleParseResult res
where
pinfo' = pinfo
{ infoParser = (,) <$> infoParser pinfo <*> many (strArgument mempty)
, infoPolicy = ForwardOptions
}
res = execParserPure pprefs pinfo' args
| null | https://raw.githubusercontent.com/facebookincubator/hsthrift/d3ff75d487e9d0c2904d18327373b603456e7a01/common/util/Util/OptParse.hs | haskell | * Options
* Commands
* Pure Parser
* Dragons and stuff
| Returns an absolute file path, while handling relative paths and ~
| Returns a relative file path
| Returns an absolute file path, while handling relative paths and ~
| Returns a relative file path
| Build a command subparser from a name, description, and parser.
^ command name (the 'cmd' in 'prog cmd --cmdflag1')
^ command description in --help output
^ parser of command's flags
| Run given parser on a string.
-----------------------------------------------------------------------------
Things from Options.Applicative that have changed
| Attempts to parse across *all* arguments, returning ones that were
unrecognized. Fails if a required argument is missing. | Copyright ( c ) Facebook , Inc. and its affiliates .
module Util.OptParse
intOption
, doubleOption
, textOption
, maybeStrOption
, maybeTextOption
, maybeIntOption
, textCommaSplit
, testCommaSplitAndStrip
, stringCommaSplit
, readCommaSplit
, absFilePathOption
, relativeFilePathOption
, maybeAbsFilePathOption
, maybeRelativeFilePathOption
, jsonOption
, commandParser
, runParserOnString
, partialParse
) where
import Data.Aeson (FromJSON(..), eitherDecodeStrict')
import Data.Bifunctor (second)
import Data.Char (isSpace)
import qualified Data.List.Split as List
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Text.Encoding (encodeUtf8)
import Options.Applicative
import Options.Applicative.Types
import Util.FilePath
import Util.String
intOption :: Mod OptionFields Int -> Parser Int
intOption = option auto
doubleOption :: Mod OptionFields Double -> Parser Double
doubleOption = option auto
textOption :: Mod OptionFields Text -> Parser Text
textOption = option (Text.pack <$> str)
maybeStrOption :: Mod OptionFields String -> Parser (Maybe String)
maybeStrOption = optional . option str
maybeTextOption :: Mod OptionFields Text -> Parser (Maybe Text)
maybeTextOption = optional . option (Text.pack <$> str)
maybeIntOption :: Mod OptionFields Int -> Parser (Maybe Int)
maybeIntOption = optional . option (read <$> str)
textCommaSplit :: ReadM [Text]
textCommaSplit = Text.splitOn "," . Text.pack <$> str
testCommaSplitAndStrip :: ReadM [Text]
testCommaSplitAndStrip = map Text.strip <$> textCommaSplit
stringCommaSplit :: ReadM [String]
stringCommaSplit = List.splitOn "," <$> str
readCommaSplit :: Read a => ReadM [a]
readCommaSplit = map (read . strip) <$> stringCommaSplit
jsonOption :: FromJSON a => Mod OptionFields a -> Parser a
jsonOption =
option (eitherReader $ eitherDecodeStrict' . encodeUtf8 . Text.pack)
absFilePathOption :: DirEnv -> Mod OptionFields FilePath -> Parser FilePath
absFilePathOption e = option (absolutiseWith e <$> str)
relativeFilePathOption :: Mod OptionFields FilePath -> Parser FilePath
relativeFilePathOption = option str
maybeAbsFilePathOption
:: DirEnv
-> Mod OptionFields FilePath
-> Parser (Maybe FilePath)
maybeAbsFilePathOption e = optional . option (absolutiseWith e <$> str)
maybeRelativeFilePathOption
:: Mod OptionFields FilePath
-> Parser (Maybe FilePath)
maybeRelativeFilePathOption = optional . option str
Example : " foo " ( progDesc " does bar . " ) ( ... parser ... )
commandParser
-> Parser a
commandParser cmd desc p =
subparser $ metavar cmd <> command cmd (info (helper <*> p) desc)
runParserOnString :: String -> Parser a -> String -> Either String a
runParserOnString cmdName p args =
case parse of
Success x -> Right x
Failure f -> Left $ fst $ renderFailure f cmdName
CompletionInvoked _ -> Left "Completion Invoked"
where
parse = execParserPure
(prefs mempty) (info (p <**> helper) fullDesc) (quotedWords args)
recurse (w,s) = w : quotedWords s
Mimic shell 's ability to group tokens with double quotes .
quotedWords s =
case dropWhile isSpace s of
"" -> []
('"':cs) -> recurse . second tail $ break (=='"') cs
s' -> recurse $ break isSpace s'
partialParse :: ParserPrefs -> ParserInfo a -> [String] -> IO (a, [String])
partialParse pprefs pinfo args = handleParseResult res
where
pinfo' = pinfo
{ infoParser = (,) <$> infoParser pinfo <*> many (strArgument mempty)
, infoPolicy = ForwardOptions
}
res = execParserPure pprefs pinfo' args
|
12eaf88594847d71c78f47ae14fda18caddad5b36ae6650c358c756a54eab936 | input-output-hk/cardano-ledger | Api.hs | -- | This module provides a library interface for working with types that will allow a user to
-- interact with Cardano ledger.
--
-- It is intended to be the complete API covering everything but without exposing constructors that
-- reveal any lower level types.
--
-- In the interest of simplicity it glosses over some details of the system.
-- Most tools should be able to work just using this interface, however you can go deeper and
-- experiment with internal modules if necessary, such as "Cardano.Ledger.Core",
" Cardano . . " , " Cardano . . Babbage " , etc .
module Cardano.Ledger.Api (
| Definition of era types .
module Cardano.Ledger.Api.Era,
-- | Building and inspecting transactions.
module Cardano.Ledger.Api.Tx,
-- | Protocol parameters.
module Cardano.Ledger.Api.PParams,
-- | Scripts
module Cardano.Ledger.Api.Scripts,
)
where
import Cardano.Ledger.Api.Era
import Cardano.Ledger.Api.PParams
import Cardano.Ledger.Api.Scripts
import Cardano.Ledger.Api.Tx
| null | https://raw.githubusercontent.com/input-output-hk/cardano-ledger/31c0bb1f5e78e40b83adfd1a916e69f47fdc9835/libs/cardano-ledger-api/src/Cardano/Ledger/Api.hs | haskell | | This module provides a library interface for working with types that will allow a user to
interact with Cardano ledger.
It is intended to be the complete API covering everything but without exposing constructors that
reveal any lower level types.
In the interest of simplicity it glosses over some details of the system.
Most tools should be able to work just using this interface, however you can go deeper and
experiment with internal modules if necessary, such as "Cardano.Ledger.Core",
| Building and inspecting transactions.
| Protocol parameters.
| Scripts | " Cardano . . " , " Cardano . . Babbage " , etc .
module Cardano.Ledger.Api (
| Definition of era types .
module Cardano.Ledger.Api.Era,
module Cardano.Ledger.Api.Tx,
module Cardano.Ledger.Api.PParams,
module Cardano.Ledger.Api.Scripts,
)
where
import Cardano.Ledger.Api.Era
import Cardano.Ledger.Api.PParams
import Cardano.Ledger.Api.Scripts
import Cardano.Ledger.Api.Tx
|
b45c7543967ecc95b313f902a96fcf44ba4db1f6873ac0d6bd68ee7b8d412445 | hasktorch/hasktorch | Typed.hs | module Torch.Typed
( module Torch.HList,
module Torch.Typed,
module Torch.Data,
module Torch.Typed.Auxiliary,
module Torch.Typed.Autograd,
module Torch.Typed.Device,
module Torch.Typed.DType,
module Torch.Typed.Factories,
module Torch.Typed.Functional,
module Torch.Typed.NN,
module Torch.Typed.Optim,
module Torch.Typed.Parameter,
module Torch.Typed.Serialize,
module Torch.Typed.Tensor,
module Torch.Typed.Vision,
Torch.Device.Device (..),
Torch.Device.DeviceType (..),
Torch.DType.DType (..),
Torch.Scalar.Scalar (..),
Torch.Functional.Reduction (..),
Torch.Functional.Tri (..),
)
where
import Torch.DType (DType (..))
import Torch.Data
import Torch.Device (Device (..), DeviceType (..))
import Torch.Functional (Reduction (..), Tri (..))
import Torch.HList
import Torch.Scalar (Scalar (..))
import Torch.Typed.Autograd
import Torch.Typed.Auxiliary
import Torch.Typed.DType
import Torch.Typed.Device
import Torch.Typed.Factories
import Torch.Typed.Functional
import Torch.Typed.NN
import Torch.Typed.Optim
import Torch.Typed.Parameter hiding (parameterToDType, parameterToDevice)
import Torch.Typed.Serialize
import Torch.Typed.Tensor hiding (toDType, toDevice)
import Torch.Typed.Vision
| null | https://raw.githubusercontent.com/hasktorch/hasktorch/9560d149b06af17e2d4e73d1e116afd2b0baff86/hasktorch/src/Torch/Typed.hs | haskell | module Torch.Typed
( module Torch.HList,
module Torch.Typed,
module Torch.Data,
module Torch.Typed.Auxiliary,
module Torch.Typed.Autograd,
module Torch.Typed.Device,
module Torch.Typed.DType,
module Torch.Typed.Factories,
module Torch.Typed.Functional,
module Torch.Typed.NN,
module Torch.Typed.Optim,
module Torch.Typed.Parameter,
module Torch.Typed.Serialize,
module Torch.Typed.Tensor,
module Torch.Typed.Vision,
Torch.Device.Device (..),
Torch.Device.DeviceType (..),
Torch.DType.DType (..),
Torch.Scalar.Scalar (..),
Torch.Functional.Reduction (..),
Torch.Functional.Tri (..),
)
where
import Torch.DType (DType (..))
import Torch.Data
import Torch.Device (Device (..), DeviceType (..))
import Torch.Functional (Reduction (..), Tri (..))
import Torch.HList
import Torch.Scalar (Scalar (..))
import Torch.Typed.Autograd
import Torch.Typed.Auxiliary
import Torch.Typed.DType
import Torch.Typed.Device
import Torch.Typed.Factories
import Torch.Typed.Functional
import Torch.Typed.NN
import Torch.Typed.Optim
import Torch.Typed.Parameter hiding (parameterToDType, parameterToDevice)
import Torch.Typed.Serialize
import Torch.Typed.Tensor hiding (toDType, toDevice)
import Torch.Typed.Vision
| |
8cb933bc4b3fc64dcc259f5ba1fa3c33afcc79a311c343c869cf0da2d41c94ab | simmone/racket-simple-xlsx | write-and-read-content-type-test.rkt | #lang racket
(require simple-xml)
(require "../../xlsx/xlsx.rkt")
(require "../../sheet/sheet.rkt")
(require "../../lib/lib.rkt")
(require rackunit/text-ui rackunit)
(require"../../content-type.rkt")
(require racket/runtime-path)
(define-runtime-path content_type_file "[Content_Types].xml")
(define test-content-type
(test-suite
"test-content-type"
(test-case
"test-content-type"
(with-xlsx
(lambda ()
(add-data-sheet "Sheet1" '(("1")))
(add-data-sheet "Sheet2" '((1)))
(add-data-sheet "Sheet3" '((1)))
(add-chart-sheet "Chart1" 'LINE "Chart1" '())
(add-chart-sheet "Chart2" 'LINE "Chart2" '())
(add-chart-sheet "Chart3" 'LINE "Chart3" '())
(dynamic-wind
(lambda ()
(write-content-type (apply build-path (drop-right (explode-path content_type_file) 1))))
(lambda ()
(call-with-input-file content_type_file
(lambda (expected)
(call-with-input-string
(lists->xml (to-content-type))
(lambda (actual)
(check-lines? expected actual)))))
(with-xlsx
(lambda ()
(read-content-type (apply build-path (drop-right (explode-path content_type_file) 1)))
(let ([sheet_list (XLSX-sheet_list (*XLSX*))])
(check-equal? (length sheet_list) 6)
(check-true (DATA-SHEET? (list-ref sheet_list 0)))
(check-true (DATA-SHEET? (list-ref sheet_list 1)))
(check-true (DATA-SHEET? (list-ref sheet_list 2)))
(check-true (CHART-SHEET? (list-ref sheet_list 3)))
(check-true (CHART-SHEET? (list-ref sheet_list 4)))
(check-true (CHART-SHEET? (list-ref sheet_list 5)))
)))
)
(lambda ()
(when (file-exists? content_type_file) (delete-file content_type_file))))
)))
))
(run-tests test-content-type)
| null | https://raw.githubusercontent.com/simmone/racket-simple-xlsx/e0ac3190b6700b0ee1dd80ed91a8f4318533d012/simple-xlsx/tests/content-type/write-and-read-content-type-test.rkt | racket | #lang racket
(require simple-xml)
(require "../../xlsx/xlsx.rkt")
(require "../../sheet/sheet.rkt")
(require "../../lib/lib.rkt")
(require rackunit/text-ui rackunit)
(require"../../content-type.rkt")
(require racket/runtime-path)
(define-runtime-path content_type_file "[Content_Types].xml")
(define test-content-type
(test-suite
"test-content-type"
(test-case
"test-content-type"
(with-xlsx
(lambda ()
(add-data-sheet "Sheet1" '(("1")))
(add-data-sheet "Sheet2" '((1)))
(add-data-sheet "Sheet3" '((1)))
(add-chart-sheet "Chart1" 'LINE "Chart1" '())
(add-chart-sheet "Chart2" 'LINE "Chart2" '())
(add-chart-sheet "Chart3" 'LINE "Chart3" '())
(dynamic-wind
(lambda ()
(write-content-type (apply build-path (drop-right (explode-path content_type_file) 1))))
(lambda ()
(call-with-input-file content_type_file
(lambda (expected)
(call-with-input-string
(lists->xml (to-content-type))
(lambda (actual)
(check-lines? expected actual)))))
(with-xlsx
(lambda ()
(read-content-type (apply build-path (drop-right (explode-path content_type_file) 1)))
(let ([sheet_list (XLSX-sheet_list (*XLSX*))])
(check-equal? (length sheet_list) 6)
(check-true (DATA-SHEET? (list-ref sheet_list 0)))
(check-true (DATA-SHEET? (list-ref sheet_list 1)))
(check-true (DATA-SHEET? (list-ref sheet_list 2)))
(check-true (CHART-SHEET? (list-ref sheet_list 3)))
(check-true (CHART-SHEET? (list-ref sheet_list 4)))
(check-true (CHART-SHEET? (list-ref sheet_list 5)))
)))
)
(lambda ()
(when (file-exists? content_type_file) (delete-file content_type_file))))
)))
))
(run-tests test-content-type)
| |
b6b107096d035a5cb9bb4ff82e289fe6df14a3681b9b051dbd68fe1174917338 | manuel-serrano/hop | transform_util.scm | ;*=====================================================================*/
* Author : * /
* Copyright : 2007 - 11 , see LICENSE file * /
;* ------------------------------------------------------------- */
* This file is part of Scheme2Js . * /
;* */
* Scheme2Js 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 */
;* LICENSE file for more details. */
;*=====================================================================*/
(module transform-util
(import nodes
error
export-desc
symbol)
(export (parameter-assig-mapping where call operands formals vaarg)))
;; needed for inlining, ...
;; if vaarg? is #t then the last element is a vaarg.
;;
;; given a call to a function with signature (formals . vaarg)
;; this function returns a list of pairs (formal . value).
Ex : ( parameter - assig - mapping ( ( + 1 1 ) 2 3 4 ) ( x y ) ( z )
= > ( ( x ( + 1 1 ) ) ( y 2 ) ( z ( list 3 4 ) ) )
;; The formals/vaarg are *not* referenced.
;;
;; Ensures that the order of assignment is that of formals
(define (parameter-assig-mapping where call operands formals vaarg?)
(let loop ((opnds operands)
(formals formals)
(rev-res '()))
(cond
;; nothing left to do.
((and (null? opnds)
(null? formals))
(reverse! rev-res))
;; no formals, but opnds
((and (not (null? opnds))
(null? formals))
(scheme2js-error where
"too many arguments"
'()
call))
;; the last element is a vaarg
;; and no operands left
((and (null? (cdr formals))
vaarg?
(null? opnds))
;; just map vaarg to '(), and return the
;; whole assig-list
(reverse (cons (cons (car formals) (instantiate::Const (value '())))
rev-res)))
;; the last element is a vaarg, and there are still operands
((and (null? (cdr formals))
vaarg?)
;; create a list, and map vaarg to it.
;; then return the whole list of pairs.
(let ((rvalue (instantiate::Call
(location (if (and (pair? operands)
(isa? (car operands) Node))
(with-access::Node (car operands) (location)
location)
#f))
(operator (runtime-reference 'list))
(operands opnds))))
(reverse (cons (cons (car formals) rvalue)
rev-res))))
;; no opnds, but formals
((and (null? opnds)
(not (null? formals)))
(scheme2js-error where
"not enough arguments"
(if (isa? (car formals) Ref)
(with-access::Ref (car formals) (var)
(with-access::Var var (id)
id))
'())
call))
;; still (non-vaarg)-formals and operands left.
(else
(loop (cdr opnds)
(cdr formals)
(cons (cons (car formals) (car opnds))
rev-res))))))
| null | https://raw.githubusercontent.com/manuel-serrano/hop/481cb10478286796addd2ec9ee29c95db27aa390/scheme2js/transform_util.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* */
* but WITHOUT ANY WARRANTY; without even the implied warranty of */
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
* LICENSE file for more details. */
*=====================================================================*/
needed for inlining, ...
if vaarg? is #t then the last element is a vaarg.
given a call to a function with signature (formals . vaarg)
this function returns a list of pairs (formal . value).
The formals/vaarg are *not* referenced.
Ensures that the order of assignment is that of formals
nothing left to do.
no formals, but opnds
the last element is a vaarg
and no operands left
just map vaarg to '(), and return the
whole assig-list
the last element is a vaarg, and there are still operands
create a list, and map vaarg to it.
then return the whole list of pairs.
no opnds, but formals
still (non-vaarg)-formals and operands left. | * Author : * /
* Copyright : 2007 - 11 , see LICENSE file * /
* This file is part of Scheme2Js . * /
* Scheme2Js is distributed in the hope that it will be useful , * /
(module transform-util
(import nodes
error
export-desc
symbol)
(export (parameter-assig-mapping where call operands formals vaarg)))
Ex : ( parameter - assig - mapping ( ( + 1 1 ) 2 3 4 ) ( x y ) ( z )
= > ( ( x ( + 1 1 ) ) ( y 2 ) ( z ( list 3 4 ) ) )
(define (parameter-assig-mapping where call operands formals vaarg?)
(let loop ((opnds operands)
(formals formals)
(rev-res '()))
(cond
((and (null? opnds)
(null? formals))
(reverse! rev-res))
((and (not (null? opnds))
(null? formals))
(scheme2js-error where
"too many arguments"
'()
call))
((and (null? (cdr formals))
vaarg?
(null? opnds))
(reverse (cons (cons (car formals) (instantiate::Const (value '())))
rev-res)))
((and (null? (cdr formals))
vaarg?)
(let ((rvalue (instantiate::Call
(location (if (and (pair? operands)
(isa? (car operands) Node))
(with-access::Node (car operands) (location)
location)
#f))
(operator (runtime-reference 'list))
(operands opnds))))
(reverse (cons (cons (car formals) rvalue)
rev-res))))
((and (null? opnds)
(not (null? formals)))
(scheme2js-error where
"not enough arguments"
(if (isa? (car formals) Ref)
(with-access::Ref (car formals) (var)
(with-access::Var var (id)
id))
'())
call))
(else
(loop (cdr opnds)
(cdr formals)
(cons (cons (car formals) (car opnds))
rev-res))))))
|
189d9b50fd1fd8c7fcc9d5d810e74f074321b0aff7971d490ee2aac46223f7bb | FlowForwarding/loom | tap_ne.erl | %%------------------------------------------------------------------------------
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%%-----------------------------------------------------------------------------
%%
@author Infoblox Inc < >
2013 Infoblox Inc
%% @doc tap module for loom
-module(tap_ne).
-copyright("2013, Infoblox Inc.").
-include_lib("ofs_handler/include/ofs_handler.hrl").
-include_lib("of_protocol/include/of_protocol.hrl").
-include_lib("of_protocol/include/ofp_v4.hrl").
-export([config/0]).
-define(L_PRIORITY, 100).
-define(H_PRIORITY, 101).
config() ->
[{IP, DatapathId, Version, _, _}] = simple_ne_logic:switches(),
ofs_handler:send(DatapathId, remove_all_flows_mod(Version)),
ofs_handler:send(DatapathId, tap_dns_response(Version, 1,2,controller, IP)),
ofs_handler:send(DatapathId, forward_mod(Version, 1, [2])),
ofs_handler:send(DatapathId, forward_mod(Version, 2, [1])).
%tap packets to controller for udp traffic from DNS server IP address
tap_dns_response(Version, Port1, Port2, Port3, IPv4Src) ->
Matches = [ { in_port , < < Port1:32 > > } , , < < 16#800:16 > > } , { ip_proto , < < 17:8 > > } , { ipv4_src , IPv4Src } ] ,
Matches = [{in_port, <<Port1:32>>}, {eth_type, 2048}, {ip_proto, <<17:8>>}, {ipv4_src, IPv4Src} ],
Instructions = [{apply_actions, [{output, Port2, no_buffer}, {output, Port3, no_buffer}] }],
Opts = [{table_id,0}, {priority, ?H_PRIORITY}, {idle_timeout, 0}, {idle_timeout, 0},
{cookie, <<0,0,0,0,0,0,0,10>>}, {cookie_mask, <<0,0,0,0,0,0,0,0>>}],
of_msg_lib:flow_add(Version, Matches, Instructions, Opts).
forward packet on InPort to OutPorts using apply_actions
forward_mod(Version,InPort,OutPorts)->
Matches = [{in_port, <<InPort:32>>}],
Instructions = [{apply_actions, [{output, OutPort, no_buffer} || OutPort <- OutPorts] } ],
io:format("Instructions=~p~n", [Instructions]),
Opts = [{table_id,0}, {priority,?L_PRIORITY}, {idle_timeout, 0}, {idle_timeout, 0},
{cookie, <<0,0,0,0,0,0,0,10>>}, {cookie_mask, <<0,0,0,0,0,0,0,0>>}],
of_msg_lib:flow_add(Version, Matches, Instructions, Opts).
% delete all flows in table 0
remove_all_flows_mod(Version) ->
of_msg_lib:flow_delete(Version, [], [{table_id, 0}]).
| null | https://raw.githubusercontent.com/FlowForwarding/loom/86a9c5aa8b7d4776062365716c9a3dbbf3330bc5/simple_ne/apps/simple_ne/src/tap_ne.erl | erlang | ------------------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-----------------------------------------------------------------------------
@doc tap module for loom
tap packets to controller for udp traffic from DNS server IP address
delete all flows in table 0 | Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author Infoblox Inc < >
2013 Infoblox Inc
-module(tap_ne).
-copyright("2013, Infoblox Inc.").
-include_lib("ofs_handler/include/ofs_handler.hrl").
-include_lib("of_protocol/include/of_protocol.hrl").
-include_lib("of_protocol/include/ofp_v4.hrl").
-export([config/0]).
-define(L_PRIORITY, 100).
-define(H_PRIORITY, 101).
config() ->
[{IP, DatapathId, Version, _, _}] = simple_ne_logic:switches(),
ofs_handler:send(DatapathId, remove_all_flows_mod(Version)),
ofs_handler:send(DatapathId, tap_dns_response(Version, 1,2,controller, IP)),
ofs_handler:send(DatapathId, forward_mod(Version, 1, [2])),
ofs_handler:send(DatapathId, forward_mod(Version, 2, [1])).
tap_dns_response(Version, Port1, Port2, Port3, IPv4Src) ->
Matches = [ { in_port , < < Port1:32 > > } , , < < 16#800:16 > > } , { ip_proto , < < 17:8 > > } , { ipv4_src , IPv4Src } ] ,
Matches = [{in_port, <<Port1:32>>}, {eth_type, 2048}, {ip_proto, <<17:8>>}, {ipv4_src, IPv4Src} ],
Instructions = [{apply_actions, [{output, Port2, no_buffer}, {output, Port3, no_buffer}] }],
Opts = [{table_id,0}, {priority, ?H_PRIORITY}, {idle_timeout, 0}, {idle_timeout, 0},
{cookie, <<0,0,0,0,0,0,0,10>>}, {cookie_mask, <<0,0,0,0,0,0,0,0>>}],
of_msg_lib:flow_add(Version, Matches, Instructions, Opts).
forward packet on InPort to OutPorts using apply_actions
forward_mod(Version,InPort,OutPorts)->
Matches = [{in_port, <<InPort:32>>}],
Instructions = [{apply_actions, [{output, OutPort, no_buffer} || OutPort <- OutPorts] } ],
io:format("Instructions=~p~n", [Instructions]),
Opts = [{table_id,0}, {priority,?L_PRIORITY}, {idle_timeout, 0}, {idle_timeout, 0},
{cookie, <<0,0,0,0,0,0,0,10>>}, {cookie_mask, <<0,0,0,0,0,0,0,0>>}],
of_msg_lib:flow_add(Version, Matches, Instructions, Opts).
remove_all_flows_mod(Version) ->
of_msg_lib:flow_delete(Version, [], [{table_id, 0}]).
|
f3aec6d315ca3924af85aeba8c4c6a5061378026a73ccbea4b5056624ac44ce5 | keigoi/ocaml-mpst | linState.ml | type 'a t = 'a Lin.gen PowState.t
let lin_op (type b) (module D : State.Op with type a = b) : b Lin.lin State.op =
let module M = struct
type nonrec a = b Lin.lin
let determinise ctx s = Lin.map_lin (D.determinise ctx) s
let merge ctx (s1 : b Lin.lin) (s2 : b Lin.lin) =
Lin.merge_lin (D.merge ctx) s1 s2
let force ctx s =
let s = Lin.raw_lin s in
D.force ctx s
let to_string ctx s = D.to_string ctx (Lin.raw_lin s)
end in
(module M)
let gen_op (type b) (module D : State.Op with type a = b) : b Lin.gen State.op =
let module M = struct
type nonrec a = b Lin.gen
let determinise ctx s = Lin.map_gen (D.determinise ctx) s
let merge ctx (s1 : b Lin.gen) (s2 : b Lin.gen) =
Lin.merge_gen (D.merge ctx) s1 s2
let force ctx s =
let s = Lin.raw_gen s in
D.force ctx s
let to_string ctx s = D.to_string ctx (Lin.raw_gen s)
end in
(module M)
let unit =
PowState.make (gen_op (module State.Unit)) @@ Lin.declare_unlimited ()
| null | https://raw.githubusercontent.com/keigoi/ocaml-mpst/96f7896cc119a754b453b59054723f505642210d/lib/lin_dyn/linState.ml | ocaml | type 'a t = 'a Lin.gen PowState.t
let lin_op (type b) (module D : State.Op with type a = b) : b Lin.lin State.op =
let module M = struct
type nonrec a = b Lin.lin
let determinise ctx s = Lin.map_lin (D.determinise ctx) s
let merge ctx (s1 : b Lin.lin) (s2 : b Lin.lin) =
Lin.merge_lin (D.merge ctx) s1 s2
let force ctx s =
let s = Lin.raw_lin s in
D.force ctx s
let to_string ctx s = D.to_string ctx (Lin.raw_lin s)
end in
(module M)
let gen_op (type b) (module D : State.Op with type a = b) : b Lin.gen State.op =
let module M = struct
type nonrec a = b Lin.gen
let determinise ctx s = Lin.map_gen (D.determinise ctx) s
let merge ctx (s1 : b Lin.gen) (s2 : b Lin.gen) =
Lin.merge_gen (D.merge ctx) s1 s2
let force ctx s =
let s = Lin.raw_gen s in
D.force ctx s
let to_string ctx s = D.to_string ctx (Lin.raw_gen s)
end in
(module M)
let unit =
PowState.make (gen_op (module State.Unit)) @@ Lin.declare_unlimited ()
| |
9791a74754eb96b6f71eb526db007c1998a31f1dde95c7783c931ad5e4dca70f | TomMD/network-data | IP.hs | # LANGUAGE DisambiguateRecordFields , FlexibleInstances , MultiParamTypeClasses , DeriveDataTypeable #
|The Data . IP library exports IPv4 address and header structures .
FIXME :
There is currently no support for options fields of the IP header .
FIXME:
There is currently no support for options fields of the IP header.
-}
module Data.IP
( IPv4(..)
, IPv4Header(..)
, IPv4Flag(..)
, IP
, IPHeader
, dummyIPv4Header
) where
import Control.Monad (sequence, when, liftM)
import qualified Data.ByteString as B
import Data.Serialize
import Data.Serialize.Put
import Data.Serialize.Get
import Data.CSum
import Data.Data
import Data.List
import Data.IPv6
import Data.Header
import Data.Bits
import Text.PrettyPrint
import Text.PrettyPrint.HughesPJClass
import Data.Word
type IP = Either IPv4 IPv6
type IPHeader = Either IPv4Header IPv6Header
-- |For IPv4 addresses.
data IPv4 = IPv4 Word32 deriving (Eq, Ord, Show, Read, Data, Typeable)
instance Serialize IPv4 where
put (IPv4 b) = putWord32be b
get = liftM IPv4 getWord32be
-- |Don't fragment, more fragment and reserved flags
data IPv4Flag = DF | MF | Res deriving (Eq, Ord, Show, Read, Data, Typeable)
instance Enum [IPv4Flag] where
fromEnum xs = foldl' (.|.) 0 $ map fromEnum1 xs
toEnum f = map snd $ filter fst [(testBit f 0, Res), (testBit f 1, MF), (testBit f 2, DF)]
fromEnum1 MF = 1
fromEnum1 DF = 2
fromEnum1 Res = 4
|This IPv4 header structure lacks support for options . Ints are used
-- for most integral data types and the binary instance hands the bit packing.
--
-- No warning is provided if a value is trunkated when packed!
data IPv4Header =
IPv4Hdr { hdrLength :: Int
, version :: Int
, tos :: Int
, totalLength :: Int
, ipID :: Int
, flags :: [IPv4Flag]
, fragmentOffset :: Int
, ttl :: Int
, protocol :: Int
, checksum :: CSum
, source :: IPv4
, destination :: IPv4
} deriving (Eq, Ord, Show, Read, Data, Typeable)
|A dummy header with zeroed fields except version , header length and ( 255 ) .
dummyIPv4Header = IPv4Hdr 5 4 0 0 0 [] 0 255 0 0 ipv4zero ipv4zero
ipv4zero = IPv4 0
instance Serialize IPv4Header where
put (IPv4Hdr ihl ver tos len id flags off ttl prot csum src dst) = do
pW8 $ (ihl .&. 0xF) .|. (ver `shiftL` 4 .&. 0xF0)
pW8 tos
pW16 len
pW16 id
let offFlags = (off .&. 0x1FFF) .|. fromIntegral (fromEnum flags `shiftL` 13)
pW16 offFlags
pW8 ttl
pW8 prot
put csum
put src
put dst
get = do
ihlVer <- gW8
let ihl = (ihlVer .&. 0xF)
ver = (ihlVer `shiftR` 4) .&. 0xF
tos <- gW8
len <- gW16
id <- gW16
offFlags <- gW16
let off = offFlags .&. 0x1FFF
flags = toEnum $ offFlags `shiftR` 13
ttl <- gW8
prot <- gW8
csum <- get
src <- get
dst <- get
return $ IPv4Hdr ihl ver tos len id flags off ttl prot csum src dst
gW8 = getWord8 >>= return . fromIntegral
gW16 = getWord16be >>= return . fromIntegral
pW8 = putWord8 . fromIntegral
pW16 = putWord16be . fromIntegral
pW32 = putWord32be . fromIntegral
-- L3Header and L3Address instances (see Data.Header)
instance L3Header IPv4Header IPv4 CSum where
getChecksum = checksum
setChecksum h c = h { checksum = c }
src = Data.IP.source
dst = Data.IP.destination
pseudoHeader h = runPut (do
put (src h)
put (dst h)
putWord8 0
pW8 $ fromIntegral (protocol h)
pW16 (totalLength h))
computeChecksum h = csum16 (encode (zeroChecksum h))
instance L3Address IPv4 IPv4Header where
localBroadcast (IPv4 a) = IPv4 (0xFFFFFF00 .|. (0x000000FF .&. a))
globalBroadcast = IPv4 0xFFFFFFFF
-- Pretty Printing and parsing instances
instance Pretty IPv4 where
pPrint (IPv4 i) = text . concat . intersperse "." . map show $ unfoldr (\(i,v) -> if i /= 0 then Just (v .&. 0xFF, (i-1, v `shiftR` 8)) else Nothing) (4,i)
| null | https://raw.githubusercontent.com/TomMD/network-data/90da1a30ef8f6a0c6cad246c23acd2a46b5d8d19/Data/IP.hs | haskell | |For IPv4 addresses.
|Don't fragment, more fragment and reserved flags
for most integral data types and the binary instance hands the bit packing.
No warning is provided if a value is trunkated when packed!
L3Header and L3Address instances (see Data.Header)
Pretty Printing and parsing instances | # LANGUAGE DisambiguateRecordFields , FlexibleInstances , MultiParamTypeClasses , DeriveDataTypeable #
|The Data . IP library exports IPv4 address and header structures .
FIXME :
There is currently no support for options fields of the IP header .
FIXME:
There is currently no support for options fields of the IP header.
-}
module Data.IP
( IPv4(..)
, IPv4Header(..)
, IPv4Flag(..)
, IP
, IPHeader
, dummyIPv4Header
) where
import Control.Monad (sequence, when, liftM)
import qualified Data.ByteString as B
import Data.Serialize
import Data.Serialize.Put
import Data.Serialize.Get
import Data.CSum
import Data.Data
import Data.List
import Data.IPv6
import Data.Header
import Data.Bits
import Text.PrettyPrint
import Text.PrettyPrint.HughesPJClass
import Data.Word
type IP = Either IPv4 IPv6
type IPHeader = Either IPv4Header IPv6Header
data IPv4 = IPv4 Word32 deriving (Eq, Ord, Show, Read, Data, Typeable)
instance Serialize IPv4 where
put (IPv4 b) = putWord32be b
get = liftM IPv4 getWord32be
data IPv4Flag = DF | MF | Res deriving (Eq, Ord, Show, Read, Data, Typeable)
instance Enum [IPv4Flag] where
fromEnum xs = foldl' (.|.) 0 $ map fromEnum1 xs
toEnum f = map snd $ filter fst [(testBit f 0, Res), (testBit f 1, MF), (testBit f 2, DF)]
fromEnum1 MF = 1
fromEnum1 DF = 2
fromEnum1 Res = 4
|This IPv4 header structure lacks support for options . Ints are used
data IPv4Header =
IPv4Hdr { hdrLength :: Int
, version :: Int
, tos :: Int
, totalLength :: Int
, ipID :: Int
, flags :: [IPv4Flag]
, fragmentOffset :: Int
, ttl :: Int
, protocol :: Int
, checksum :: CSum
, source :: IPv4
, destination :: IPv4
} deriving (Eq, Ord, Show, Read, Data, Typeable)
|A dummy header with zeroed fields except version , header length and ( 255 ) .
dummyIPv4Header = IPv4Hdr 5 4 0 0 0 [] 0 255 0 0 ipv4zero ipv4zero
ipv4zero = IPv4 0
instance Serialize IPv4Header where
put (IPv4Hdr ihl ver tos len id flags off ttl prot csum src dst) = do
pW8 $ (ihl .&. 0xF) .|. (ver `shiftL` 4 .&. 0xF0)
pW8 tos
pW16 len
pW16 id
let offFlags = (off .&. 0x1FFF) .|. fromIntegral (fromEnum flags `shiftL` 13)
pW16 offFlags
pW8 ttl
pW8 prot
put csum
put src
put dst
get = do
ihlVer <- gW8
let ihl = (ihlVer .&. 0xF)
ver = (ihlVer `shiftR` 4) .&. 0xF
tos <- gW8
len <- gW16
id <- gW16
offFlags <- gW16
let off = offFlags .&. 0x1FFF
flags = toEnum $ offFlags `shiftR` 13
ttl <- gW8
prot <- gW8
csum <- get
src <- get
dst <- get
return $ IPv4Hdr ihl ver tos len id flags off ttl prot csum src dst
gW8 = getWord8 >>= return . fromIntegral
gW16 = getWord16be >>= return . fromIntegral
pW8 = putWord8 . fromIntegral
pW16 = putWord16be . fromIntegral
pW32 = putWord32be . fromIntegral
instance L3Header IPv4Header IPv4 CSum where
getChecksum = checksum
setChecksum h c = h { checksum = c }
src = Data.IP.source
dst = Data.IP.destination
pseudoHeader h = runPut (do
put (src h)
put (dst h)
putWord8 0
pW8 $ fromIntegral (protocol h)
pW16 (totalLength h))
computeChecksum h = csum16 (encode (zeroChecksum h))
instance L3Address IPv4 IPv4Header where
localBroadcast (IPv4 a) = IPv4 (0xFFFFFF00 .|. (0x000000FF .&. a))
globalBroadcast = IPv4 0xFFFFFFFF
instance Pretty IPv4 where
pPrint (IPv4 i) = text . concat . intersperse "." . map show $ unfoldr (\(i,v) -> if i /= 0 then Just (v .&. 0xFF, (i-1, v `shiftR` 8)) else Nothing) (4,i)
|
39ebe9faba621a611d7a3535ac3529f3b5acf7aeb3d1378f7748870fa7994968 | KestrelInstitute/Specware | BuildDistribution.lisp | ;; This file builds a distribution directory for Window/Allegro Runtime Specware.
(defpackage :Specware)
(defvar Specware4-dir (Specware::getenv "SPECWARE4"))
(defun in-specware-dir (file) (concatenate 'string Specware4-dir "/" file))
;;; Get version information from canonical source...
(let ((version-file (in-specware-dir "Applications/Specware/Handwritten/Lisp/SpecwareVersion.lisp")))
(if (probe-file version-file)
(load version-file)
(error "in BuildDistribution.lisp: Cannot find ~A" version-file)))
;; dist-dir-name is the sub-directory to receive this particular distribution.
;; In particular, this is where generate-application puts all its stuff.
(defvar dist-dir-name "distribution/")
(defparameter distribution-directory
(in-specware-dir (concatenate 'string dist-dir-name *Specware-Name* "/")))
(defun in-distribution-dir (file) (concatenate 'string distribution-directory file))
;; in-lisp-dir is used to get some emacs files used by allegro runtime
(defun in-lisp-dir (file) (concatenate 'string (sys:getenv "ALLEGRO") "/" file))
For Windows , we use the Allegro Enterprise gen - app facility
;; If the application directory already exists, then we delete it.
;; generate-application complains and dies if the directory exists.
;; (when (probe-file (make-pathname :directory distribution-directory))
;; (excl::delete-directory-and-files
;; (make-pathname :directory distribution-directory)))
(excl:generate-application
;; this is the name of the application
*Specware-Name*
;; this is the directory where the application is to go
;; (plus accompanying files)
distribution-directory
;; a list of files to load
'("BuildPreamble.lisp" "Specware4.lisp")
;; a list of files to copy to the distribution directory
:application-files
(list (in-specware-dir "Release/Windows/Specware4.cmd")
(in-specware-dir "Release/Windows/Specware4 Shell.cmd")
(in-specware-dir "Applications/Specware/Handwritten/Lisp/StartShell.lisp"))
;; Possible option instead of excl::delete-directory-and-files call
:allow-existing-directory t
;; the image does not have a compiler neither during the build nor after.
;; The application has the interpreter only.
:include-compiler t
;; which runtime? the other option is :dynamic which includes the compiler
:runtime :dynamic
)
(load (in-specware-dir "Applications/Specware/Handwritten/Lisp/copy-files-for-distribution.lisp"))
(Specware::copy-directory (in-lisp-dir "xeli/") (in-distribution-dir "Library/IO/Emacs/xeli/"))
| null | https://raw.githubusercontent.com/KestrelInstitute/Specware/2be6411c55f26432bf5c9e2f7778128898220c24/Applications/Specware/Handwritten/Lisp/BuildDistribution.lisp | lisp | This file builds a distribution directory for Window/Allegro Runtime Specware.
Get version information from canonical source...
dist-dir-name is the sub-directory to receive this particular distribution.
In particular, this is where generate-application puts all its stuff.
in-lisp-dir is used to get some emacs files used by allegro runtime
If the application directory already exists, then we delete it.
generate-application complains and dies if the directory exists.
(when (probe-file (make-pathname :directory distribution-directory))
(excl::delete-directory-and-files
(make-pathname :directory distribution-directory)))
this is the name of the application
this is the directory where the application is to go
(plus accompanying files)
a list of files to load
a list of files to copy to the distribution directory
Possible option instead of excl::delete-directory-and-files call
the image does not have a compiler neither during the build nor after.
The application has the interpreter only.
which runtime? the other option is :dynamic which includes the compiler |
(defpackage :Specware)
(defvar Specware4-dir (Specware::getenv "SPECWARE4"))
(defun in-specware-dir (file) (concatenate 'string Specware4-dir "/" file))
(let ((version-file (in-specware-dir "Applications/Specware/Handwritten/Lisp/SpecwareVersion.lisp")))
(if (probe-file version-file)
(load version-file)
(error "in BuildDistribution.lisp: Cannot find ~A" version-file)))
(defvar dist-dir-name "distribution/")
(defparameter distribution-directory
(in-specware-dir (concatenate 'string dist-dir-name *Specware-Name* "/")))
(defun in-distribution-dir (file) (concatenate 'string distribution-directory file))
(defun in-lisp-dir (file) (concatenate 'string (sys:getenv "ALLEGRO") "/" file))
For Windows , we use the Allegro Enterprise gen - app facility
(excl:generate-application
*Specware-Name*
distribution-directory
'("BuildPreamble.lisp" "Specware4.lisp")
:application-files
(list (in-specware-dir "Release/Windows/Specware4.cmd")
(in-specware-dir "Release/Windows/Specware4 Shell.cmd")
(in-specware-dir "Applications/Specware/Handwritten/Lisp/StartShell.lisp"))
:allow-existing-directory t
:include-compiler t
:runtime :dynamic
)
(load (in-specware-dir "Applications/Specware/Handwritten/Lisp/copy-files-for-distribution.lisp"))
(Specware::copy-directory (in-lisp-dir "xeli/") (in-distribution-dir "Library/IO/Emacs/xeli/"))
|
cd2f95f525d40871e8a84586d5c08f941516e69d7a835b3d880913f86a348530 | kupl/LearnML | original.ml | type formula =
| True
| False
| Not of formula
| AndAlso of (formula * formula)
| OrElse of (formula * formula)
| Imply of (formula * formula)
| Equal of (exp * exp)
and exp = Num of int | Plus of (exp * exp) | Minus of (exp * exp)
let rec eval (f : formula) : bool =
let rec calculate (f2 : exp) : int =
match f2 with
| Num i -> i
| Plus (e1, e2) -> calculate e1 + calculate e2
| Minus (e1, e2) -> calculate e1 - calculate e2
in
match f with
| True -> true
| False -> false
| Not f -> if f = True then false else true
| AndAlso (f1, f2) -> if f1 = True && f2 = True then true else false
| OrElse (f1, f2) -> if f1 = True || f2 = True then true else false
| Imply (f1, f2) -> if f1 = True && f2 = False then false else true
| Equal (e1, e2) -> if calculate e1 = calculate e2 then true else false
| null | https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/formula/sub52/original.ml | ocaml | type formula =
| True
| False
| Not of formula
| AndAlso of (formula * formula)
| OrElse of (formula * formula)
| Imply of (formula * formula)
| Equal of (exp * exp)
and exp = Num of int | Plus of (exp * exp) | Minus of (exp * exp)
let rec eval (f : formula) : bool =
let rec calculate (f2 : exp) : int =
match f2 with
| Num i -> i
| Plus (e1, e2) -> calculate e1 + calculate e2
| Minus (e1, e2) -> calculate e1 - calculate e2
in
match f with
| True -> true
| False -> false
| Not f -> if f = True then false else true
| AndAlso (f1, f2) -> if f1 = True && f2 = True then true else false
| OrElse (f1, f2) -> if f1 = True || f2 = True then true else false
| Imply (f1, f2) -> if f1 = True && f2 = False then false else true
| Equal (e1, e2) -> if calculate e1 = calculate e2 then true else false
| |
ceb98e2ee6cd75db78e93a5dea9fca3b57868115938d3bf836be1c35e5168a27 | janestreet/learn-ocaml-workshop | game_tests.ml | open! Base
open! Snake_lib
open Game
open For_testing
type nonrec t = Game.t [@@deriving sexp_of]
let%expect_test "Testing [Game.set_direction]..." =
let t =
create_game_with_apple_exn
~height:10
~width:10
~initial_snake_length:3
~amount_to_grow:3
~apple_location:{ Position.row = 8; col = 1 }
in
set_direction t Direction.Down;
Stdio.printf !"%{sexp: t}\n%!" t;
[%expect
{|
((snake
((direction Down) (extensions_remaining 0)
(locations (((col 2) (row 0)) ((col 1) (row 0)) ((col 0) (row 0))))))
(apple ((location ((col 1) (row 8))))) (game_state In_progress) (height 10)
(width 10) (amount_to_grow 3)) |}]
;;
| null | https://raw.githubusercontent.com/janestreet/learn-ocaml-workshop/1ba9576b48b48a892644eb20c201c2c4aa643c32/03-snake/tests/phase2/game_tests.ml | ocaml | open! Base
open! Snake_lib
open Game
open For_testing
type nonrec t = Game.t [@@deriving sexp_of]
let%expect_test "Testing [Game.set_direction]..." =
let t =
create_game_with_apple_exn
~height:10
~width:10
~initial_snake_length:3
~amount_to_grow:3
~apple_location:{ Position.row = 8; col = 1 }
in
set_direction t Direction.Down;
Stdio.printf !"%{sexp: t}\n%!" t;
[%expect
{|
((snake
((direction Down) (extensions_remaining 0)
(locations (((col 2) (row 0)) ((col 1) (row 0)) ((col 0) (row 0))))))
(apple ((location ((col 1) (row 8))))) (game_state In_progress) (height 10)
(width 10) (amount_to_grow 3)) |}]
;;
| |
07085703cd76a96a3d75ce9c153a569426829f97641be4ed8c51bb40322eef65 | emqx/emqx | emqx_dashboard_bad_api.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. 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.
%%--------------------------------------------------------------------
-module(emqx_dashboard_bad_api).
-include_lib("emqx/include/logger.hrl").
-export([init/2]).
init(Req0, State) ->
?SLOG(warning, #{msg => "unexpected_api_access", request => Req0}),
Req = cowboy_req:reply(
404,
#{<<"content-type">> => <<"application/json">>},
<<"{\"code\": \"API_NOT_EXIST\", \"message\": \"Request Path Not Found\"}">>,
Req0
),
{ok, Req, State}.
| null | https://raw.githubusercontent.com/emqx/emqx/dbc10c2eed3df314586c7b9ac6292083204f1f68/apps/emqx_dashboard/src/emqx_dashboard_bad_api.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------------------------------- | Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_dashboard_bad_api).
-include_lib("emqx/include/logger.hrl").
-export([init/2]).
init(Req0, State) ->
?SLOG(warning, #{msg => "unexpected_api_access", request => Req0}),
Req = cowboy_req:reply(
404,
#{<<"content-type">> => <<"application/json">>},
<<"{\"code\": \"API_NOT_EXIST\", \"message\": \"Request Path Not Found\"}">>,
Req0
),
{ok, Req, State}.
|
bc24dd414369c296601b3e7f4302c98f91c04e5a78d35c368c24ccc93e9b981c | nikodemus/SBCL | misc.lisp | (in-package :sb-bsd-sockets)
;;; Miscellaneous things, placed here until I can find a logically more
;;; coherent place to put them
;;; I don't want to provide a complete interface to unix file
;;; operations, for example, but being about to set O_NONBLOCK on a
;;; socket is a necessary operation.
XXX bad ( sizeof ( int ) = = 4 ) assumptions
(defgeneric non-blocking-mode (socket)
(:documentation "Is SOCKET in non-blocking mode?"))
#-win32
(defmethod non-blocking-mode ((socket socket))
(let ((fd (socket-file-descriptor socket)))
(sb-alien:with-alien ((arg integer))
(> (logand
(sockint::fcntl fd sockint::f-getfl arg)
sockint::o-nonblock)
0))))
#+win32
(defmethod non-blocking-mode ((socket socket))
(slot-value socket 'non-blocking-p))
(defgeneric (setf non-blocking-mode) (non-blocking-p socket)
(:documentation "Put SOCKET in non-blocking mode - or not, according to NON-BLOCKING-P"))
#-win32
(defmethod (setf non-blocking-mode) (non-blocking-p (socket socket))
(declare (optimize (speed 3)))
(let* ((fd (socket-file-descriptor socket))
(arg1 (the (signed-byte 32) (sockint::fcntl fd sockint::f-getfl 0)))
(arg2
(if non-blocking-p
(logior arg1 sockint::o-nonblock)
(logand (lognot sockint::o-nonblock) arg1))))
(when (= (the (signed-byte 32) -1)
(the (signed-byte 32)
(sockint::fcntl fd sockint::f-setfl arg2)))
(socket-error "fcntl"))
non-blocking-p))
#+win32
(defmethod (setf non-blocking-mode)
(non-blocking-p (socket socket))
(declare (optimize (speed 3)))
(setf (slot-value socket 'non-blocking-p)
(when non-blocking-p t))
(let ((fd (socket-file-descriptor socket)))
(when (= (the (signed-byte 32) -1)
(the (signed-byte 32)
(sockint::ioctl fd sockint::FIONBIO (if non-blocking-p 1 0))))
(socket-error "ioctl(FIONBIO)"))
(when non-blocking-p t)))
| null | https://raw.githubusercontent.com/nikodemus/SBCL/3c11847d1e12db89b24a7887b18a137c45ed4661/contrib/sb-bsd-sockets/misc.lisp | lisp | Miscellaneous things, placed here until I can find a logically more
coherent place to put them
I don't want to provide a complete interface to unix file
operations, for example, but being about to set O_NONBLOCK on a
socket is a necessary operation. | (in-package :sb-bsd-sockets)
XXX bad ( sizeof ( int ) = = 4 ) assumptions
(defgeneric non-blocking-mode (socket)
(:documentation "Is SOCKET in non-blocking mode?"))
#-win32
(defmethod non-blocking-mode ((socket socket))
(let ((fd (socket-file-descriptor socket)))
(sb-alien:with-alien ((arg integer))
(> (logand
(sockint::fcntl fd sockint::f-getfl arg)
sockint::o-nonblock)
0))))
#+win32
(defmethod non-blocking-mode ((socket socket))
(slot-value socket 'non-blocking-p))
(defgeneric (setf non-blocking-mode) (non-blocking-p socket)
(:documentation "Put SOCKET in non-blocking mode - or not, according to NON-BLOCKING-P"))
#-win32
(defmethod (setf non-blocking-mode) (non-blocking-p (socket socket))
(declare (optimize (speed 3)))
(let* ((fd (socket-file-descriptor socket))
(arg1 (the (signed-byte 32) (sockint::fcntl fd sockint::f-getfl 0)))
(arg2
(if non-blocking-p
(logior arg1 sockint::o-nonblock)
(logand (lognot sockint::o-nonblock) arg1))))
(when (= (the (signed-byte 32) -1)
(the (signed-byte 32)
(sockint::fcntl fd sockint::f-setfl arg2)))
(socket-error "fcntl"))
non-blocking-p))
#+win32
(defmethod (setf non-blocking-mode)
(non-blocking-p (socket socket))
(declare (optimize (speed 3)))
(setf (slot-value socket 'non-blocking-p)
(when non-blocking-p t))
(let ((fd (socket-file-descriptor socket)))
(when (= (the (signed-byte 32) -1)
(the (signed-byte 32)
(sockint::ioctl fd sockint::FIONBIO (if non-blocking-p 1 0))))
(socket-error "ioctl(FIONBIO)"))
(when non-blocking-p t)))
|
bf82db8277b065794541e7108f536548e872a0eaa7fa8b246ea02f3f7f93fc5f | wedesoft/aiscm | roberts_cross.scm | (use-modules (aiscm magick) (aiscm image) (aiscm core))
(define (to-gray img) (from-image (convert-image (to-image img) 'GRAY)))
(define (norm x y) (/ (+ (abs x) (abs y)) 2))
(define (roberts-cross img) (/ (norm (convolve img (arr (+1 0) ( 0 -1))) (convolve img (arr ( 0 +1) (-1 0)))) 2))
(write-image (to-type <ubyte> (roberts-cross (to-gray (read-image "star-ferry.jpg")))) "roberts-cross.jpg")
| null | https://raw.githubusercontent.com/wedesoft/aiscm/2c3db8d00cad6e042150714ada85da19cf4338ad/tests/integration/roberts_cross.scm | scheme | (use-modules (aiscm magick) (aiscm image) (aiscm core))
(define (to-gray img) (from-image (convert-image (to-image img) 'GRAY)))
(define (norm x y) (/ (+ (abs x) (abs y)) 2))
(define (roberts-cross img) (/ (norm (convolve img (arr (+1 0) ( 0 -1))) (convolve img (arr ( 0 +1) (-1 0)))) 2))
(write-image (to-type <ubyte> (roberts-cross (to-gray (read-image "star-ferry.jpg")))) "roberts-cross.jpg")
| |
3714df1a68c6c65b9875db356a4d53e958f4e219ac58666dfba1ad694992b6c0 | tonatona-project/tonatona | Logger.hs | # OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE UndecidableInstances #
module Tonatona.Logger
( Config(..)
, DeployMode(..)
, Verbose(..)
, defaultVerbosity
-- * Standard logging functions
, Tonatona.Logger.logDebug
, Tonatona.Logger.logInfo
, Tonatona.Logger.logWarn
, Tonatona.Logger.logError
, Tonatona.Logger.logOther
-- * Advanced logging functions
-- ** Sticky logging
, Tonatona.Logger.logSticky
, Tonatona.Logger.logStickyDone
-- ** With source
, Tonatona.Logger.logDebugS
, Tonatona.Logger.logInfoS
, Tonatona.Logger.logWarnS
, Tonatona.Logger.logErrorS
, Tonatona.Logger.logOtherS
-- ** Generic log function
, Tonatona.Logger.logGeneric
-- * Data types
, LogLevel (..)
, LogSource
) where
import RIO
import Tonatona (HasConfig(..), HasParser(..))
import TonaParser
( Var(..)
, (.||)
, argLong
, envVar
, liftWith
, optionalEnum
)
-- Standard logging functions
{- | Log a debug level message with no source.
-}
logDebug :: (HasConfig env Config) => Utf8Builder -> RIO env ()
logDebug = unwrap . RIO.logDebug
{- | Log an info level message with no source.
-}
logInfo :: (HasConfig env Config) => Utf8Builder -> RIO env ()
logInfo = unwrap . RIO.logInfo
{- | Log a warn level message with no source.
-}
logWarn :: (HasConfig env Config) => Utf8Builder -> RIO env ()
logWarn = unwrap . RIO.logWarn
{- | Log an error level message with no source.
-}
logError :: (HasConfig env Config) => Utf8Builder -> RIO env ()
logError = unwrap . RIO.logError
{- | Log a message with the specified textual level and no source.
-}
logOther :: (HasConfig env Config)
=> Text -- ^ level
-> Utf8Builder -> RIO env ()
logOther level = unwrap . RIO.logOther level
-- With source
{- | Log a debug level message with the given source.
-}
logDebugS
:: (HasConfig env Config)
=> LogSource
-> Utf8Builder
-> RIO env ()
logDebugS src = unwrap . RIO.logDebugS src
{- | Log an info level message with the given source.
-}
logInfoS
:: (HasConfig env Config)
=> LogSource
-> Utf8Builder
-> RIO env ()
logInfoS src = unwrap . RIO.logInfoS src
{- | Log a warn level message with the given source.
-}
logWarnS
:: (HasConfig env Config)
=> LogSource
-> Utf8Builder
-> RIO env ()
logWarnS src = unwrap . RIO.logWarnS src
{- | Log an error level message with the given source.
-}
logErrorS
:: (HasConfig env Config)
=> LogSource
-> Utf8Builder
-> RIO env ()
logErrorS src = unwrap . RIO.logErrorS src
{- | Log a message with the specified textual level and the given source.
-}
logOtherS
:: (HasConfig env Config)
=> Text -- ^ level
-> LogSource
-> Utf8Builder
-> RIO env ()
logOtherS level src = unwrap . RIO.logOtherS level src
| Write a " sticky " line to the terminal . Any subsequent lines will
overwrite this one , and that same line will be repeated below
again . In other words , the line sticks at the bottom of the output
forever . Running this function again will replace the sticky line
with a new sticky line . When you want to get rid of the sticky
line , run ' logStickyDone ' .
Note that not all ' LogFunc ' implementations will support sticky
messages as described . However , the ' withLogFunc ' implementation
provided by this module does .
overwrite this one, and that same line will be repeated below
again. In other words, the line sticks at the bottom of the output
forever. Running this function again will replace the sticky line
with a new sticky line. When you want to get rid of the sticky
line, run 'logStickyDone'.
Note that not all 'LogFunc' implementations will support sticky
messages as described. However, the 'withLogFunc' implementation
provided by this module does.
-}
logSticky :: (HasConfig env Config) => Utf8Builder -> RIO env ()
logSticky = unwrap . RIO.logSticky
{- | This will print out the given message with a newline and disable
any further stickiness of the line until a new call to 'logSticky'
happens.
-}
logStickyDone :: (HasConfig env Config) => Utf8Builder -> RIO env ()
logStickyDone = unwrap . RIO.logStickyDone
Generic log function
{- | Generic, basic function for creating other logging functions.
-}
logGeneric ::
(HasConfig env Config)
=> LogSource
-> LogLevel
-> Utf8Builder
-> RIO env ()
logGeneric src level str = unwrap $ RIO.logGeneric src level str
unwrap :: RIO (InnerEnv env) () -> RIO env ()
unwrap action = do
env <- ask
runRIO (InnerEnv env) action
newtype InnerEnv env = InnerEnv { unInnerEnv :: env }
instance (HasConfig env Config) => HasLogFunc (InnerEnv env) where
logFuncL = lens (logFunc . config . unInnerEnv) $
error "Setter for logFuncL is not defined"
-- Config
data Config = Config
{ mode :: DeployMode
, verbose :: Verbose
, logOptions :: LogOptions
, logFunc :: LogFunc
}
instance HasParser Config where
parser = do
mode <- parser
verbose <- parser
liftWith $ \action -> do
options <- defaultLogOptions mode verbose
withLogFunc options $ \lf ->
action $ Config mode verbose options lf
Verbose
newtype Verbose = Verbose { unVerbose :: Bool }
deriving (Show, Read, Eq)
instance HasParser Verbose where
parser = Verbose <$>
optionalEnum
"Make the operation more talkative"
(argLong "verbose" .|| envVar "VERBOSE")
False
data DeployMode
= Development
| Production
| Staging
| Test
deriving (Eq, Generic, Show, Read, Bounded, Enum)
instance Var DeployMode where
toVar = show
fromVar = readMaybe
instance HasParser DeployMode where
parser =
optionalEnum
"Application deployment mode to run"
(argLong "env" .|| envVar "ENV")
Development
-- Logger options
| Default way to create ' LogOptions ' .
-}
defaultLogOptions :: (MonadIO m) => DeployMode -> Verbose -> m LogOptions
defaultLogOptions env verbose = do
logOptionsHandle stderr $ defaultVerbosity env verbose
{-| Default setting for verbosity.
-}
defaultVerbosity :: DeployMode -> Verbose -> Bool
defaultVerbosity env (Verbose v) =
case (v, env) of
(False, Development) -> True
_ -> v
| null | https://raw.githubusercontent.com/tonatona-project/tonatona/b6b67bf0f14d345c01dcf9ea7870b657891f032c/tonatona-logger/src/Tonatona/Logger.hs | haskell | * Standard logging functions
* Advanced logging functions
** Sticky logging
** With source
** Generic log function
* Data types
Standard logging functions
| Log a debug level message with no source.
| Log an info level message with no source.
| Log a warn level message with no source.
| Log an error level message with no source.
| Log a message with the specified textual level and no source.
^ level
With source
| Log a debug level message with the given source.
| Log an info level message with the given source.
| Log a warn level message with the given source.
| Log an error level message with the given source.
| Log a message with the specified textual level and the given source.
^ level
| This will print out the given message with a newline and disable
any further stickiness of the line until a new call to 'logSticky'
happens.
| Generic, basic function for creating other logging functions.
Config
Logger options
| Default setting for verbosity.
| # OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE UndecidableInstances #
module Tonatona.Logger
( Config(..)
, DeployMode(..)
, Verbose(..)
, defaultVerbosity
, Tonatona.Logger.logDebug
, Tonatona.Logger.logInfo
, Tonatona.Logger.logWarn
, Tonatona.Logger.logError
, Tonatona.Logger.logOther
, Tonatona.Logger.logSticky
, Tonatona.Logger.logStickyDone
, Tonatona.Logger.logDebugS
, Tonatona.Logger.logInfoS
, Tonatona.Logger.logWarnS
, Tonatona.Logger.logErrorS
, Tonatona.Logger.logOtherS
, Tonatona.Logger.logGeneric
, LogLevel (..)
, LogSource
) where
import RIO
import Tonatona (HasConfig(..), HasParser(..))
import TonaParser
( Var(..)
, (.||)
, argLong
, envVar
, liftWith
, optionalEnum
)
logDebug :: (HasConfig env Config) => Utf8Builder -> RIO env ()
logDebug = unwrap . RIO.logDebug
logInfo :: (HasConfig env Config) => Utf8Builder -> RIO env ()
logInfo = unwrap . RIO.logInfo
logWarn :: (HasConfig env Config) => Utf8Builder -> RIO env ()
logWarn = unwrap . RIO.logWarn
logError :: (HasConfig env Config) => Utf8Builder -> RIO env ()
logError = unwrap . RIO.logError
logOther :: (HasConfig env Config)
-> Utf8Builder -> RIO env ()
logOther level = unwrap . RIO.logOther level
logDebugS
:: (HasConfig env Config)
=> LogSource
-> Utf8Builder
-> RIO env ()
logDebugS src = unwrap . RIO.logDebugS src
logInfoS
:: (HasConfig env Config)
=> LogSource
-> Utf8Builder
-> RIO env ()
logInfoS src = unwrap . RIO.logInfoS src
logWarnS
:: (HasConfig env Config)
=> LogSource
-> Utf8Builder
-> RIO env ()
logWarnS src = unwrap . RIO.logWarnS src
logErrorS
:: (HasConfig env Config)
=> LogSource
-> Utf8Builder
-> RIO env ()
logErrorS src = unwrap . RIO.logErrorS src
logOtherS
:: (HasConfig env Config)
-> LogSource
-> Utf8Builder
-> RIO env ()
logOtherS level src = unwrap . RIO.logOtherS level src
| Write a " sticky " line to the terminal . Any subsequent lines will
overwrite this one , and that same line will be repeated below
again . In other words , the line sticks at the bottom of the output
forever . Running this function again will replace the sticky line
with a new sticky line . When you want to get rid of the sticky
line , run ' logStickyDone ' .
Note that not all ' LogFunc ' implementations will support sticky
messages as described . However , the ' withLogFunc ' implementation
provided by this module does .
overwrite this one, and that same line will be repeated below
again. In other words, the line sticks at the bottom of the output
forever. Running this function again will replace the sticky line
with a new sticky line. When you want to get rid of the sticky
line, run 'logStickyDone'.
Note that not all 'LogFunc' implementations will support sticky
messages as described. However, the 'withLogFunc' implementation
provided by this module does.
-}
logSticky :: (HasConfig env Config) => Utf8Builder -> RIO env ()
logSticky = unwrap . RIO.logSticky
logStickyDone :: (HasConfig env Config) => Utf8Builder -> RIO env ()
logStickyDone = unwrap . RIO.logStickyDone
Generic log function
logGeneric ::
(HasConfig env Config)
=> LogSource
-> LogLevel
-> Utf8Builder
-> RIO env ()
logGeneric src level str = unwrap $ RIO.logGeneric src level str
unwrap :: RIO (InnerEnv env) () -> RIO env ()
unwrap action = do
env <- ask
runRIO (InnerEnv env) action
newtype InnerEnv env = InnerEnv { unInnerEnv :: env }
instance (HasConfig env Config) => HasLogFunc (InnerEnv env) where
logFuncL = lens (logFunc . config . unInnerEnv) $
error "Setter for logFuncL is not defined"
data Config = Config
{ mode :: DeployMode
, verbose :: Verbose
, logOptions :: LogOptions
, logFunc :: LogFunc
}
instance HasParser Config where
parser = do
mode <- parser
verbose <- parser
liftWith $ \action -> do
options <- defaultLogOptions mode verbose
withLogFunc options $ \lf ->
action $ Config mode verbose options lf
Verbose
newtype Verbose = Verbose { unVerbose :: Bool }
deriving (Show, Read, Eq)
instance HasParser Verbose where
parser = Verbose <$>
optionalEnum
"Make the operation more talkative"
(argLong "verbose" .|| envVar "VERBOSE")
False
data DeployMode
= Development
| Production
| Staging
| Test
deriving (Eq, Generic, Show, Read, Bounded, Enum)
instance Var DeployMode where
toVar = show
fromVar = readMaybe
instance HasParser DeployMode where
parser =
optionalEnum
"Application deployment mode to run"
(argLong "env" .|| envVar "ENV")
Development
| Default way to create ' LogOptions ' .
-}
defaultLogOptions :: (MonadIO m) => DeployMode -> Verbose -> m LogOptions
defaultLogOptions env verbose = do
logOptionsHandle stderr $ defaultVerbosity env verbose
defaultVerbosity :: DeployMode -> Verbose -> Bool
defaultVerbosity env (Verbose v) =
case (v, env) of
(False, Development) -> True
_ -> v
|
657cea7397317f53038f2a7ce6be30399dfbae02ec5962d25bec0bf4dc21ba0c | russell/cl-git | object.lisp | -*- Mode : Lisp ; Syntax : COMMON - LISP ; Base : 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
Copyright ( C ) 2011 - 2022 < >
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation , either version 3 of
the License , or ( at your option ) any later version .
;;
;; This program is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; Lesser General Public License for more details.
;;
You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; </>.
(in-package #:cl-git)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Low-level interface
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar object-type-mapping
(list 'commit :commit
'tree :tree
'blob :blob
'tag :tag))
(defmethod pointer ((object git-object))
"Try and resolve the pointer if it isn't set."
(when (and (null-pointer-p (slot-value object 'libgit2-pointer))
(not (slot-value object 'libgit2-disposed)))
(cond
Resolve by
((slot-value object 'libgit2-oid)
(setf (slot-value object 'libgit2-pointer)
(git-object-lookup-ptr (slot-value object 'libgit2-oid)
(getf object-type-mapping (type-of object))
(facilitator object)))
(enable-garbage-collection object)
(setf (slot-value object 'libgit2-oid) nil))
;; Resolve by name
((slot-value object 'libgit2-name)
(setf (slot-value object 'libgit2-pointer)
(%git-lookup-by-name (type-of object)
(slot-value object 'libgit2-name)
(facilitator object)))
(enable-garbage-collection object)
(setf (slot-value object 'libgit2-name) nil))
(t (error "Unable to lookup object in git repository."))))
(slot-value object 'libgit2-pointer))
(defmethod initialize-instance :after ((instance git-object) &rest r)
"Setup the finalizer to call internal-dispose with the right arguments."
(when (getf r :pointer)
(enable-garbage-collection instance)))
(defmethod print-object ((object git-object) stream)
(print-unreadable-object (object stream :type t :identity t)
(cond
((not (null-pointer-p (slot-value object 'libgit2-pointer)))
(format stream "~X" (pointer-address (pointer object))))
((or (slot-value object 'libgit2-oid) (slot-value object 'libgit2-name))
(princ "(weak)" stream))
((slot-value object 'libgit2-disposed)
(princ "(disposed)" stream)))))
(defmethod translate-to-foreign (value (type git-object))
(if (pointerp value)
value
(pointer value)))
(defcfun ("git_object_id" git-object-id)
%oid
"Returns the oid identifying OBJECT"
(object %object))
(defcfun ("git_object_type" git-object-type)
git-object-t
"Returns the type of the git object."
(object %object))
(defcfun ("git_object_lookup" %git-object-lookup)
%return-value
(object %object)
(repo %repository)
(oid %oid)
(type git-object-t))
(defcfun ("git_object_free" git-object-free)
:void
"Free the git object."
(object :pointer))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Highlevel Interface
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun make-instance-object (&key pointer facilitator type)
"Creates an object wrapping OBJECT-PTR.
OBJECT-PTR needs to point to one of the git storage types, such as:
:commit :tag :tree or :blob. This function is not suitable to
wrap git pointers to repositories, config, index etc."
(let ((obj-type
(if (eq type :any)
(case (git-object-type pointer)
(:commit 'commit)
(:tag 'tag)
(:tree 'tree)
(:blob 'blob)
(:config 'config)
(t type))
type)))
(make-instance obj-type
:pointer pointer
:facilitator facilitator
:free-function #'git-object-free)))
(defmethod dispose ((object git-object))
"Dispose of the object and association to the facilitator. Mark
the pointer as disposed."
(setf (facilitator object) nil)
(when (car (finalizer-data object))
(internal-dispose (finalizer-data object)
(pointer object)
(free-function object))
(setf (slot-value object 'libgit2-pointer) nil)
(setf (slot-value object 'libgit2-disposed) t)))
(defun git-object-lookup-ptr (oid type repository)
(assert (not (null-or-nullpointer repository)))
(let ((type
(case type
(commit :commit)
(tag :tag)
(tree :tree)
(blob :blob)
(tree-tree :tree)
(tree-blob :blob)
(config :config)
(t type))))
(with-foreign-object (obj-ptr :pointer)
(%git-object-lookup obj-ptr repository oid type)
(mem-ref obj-ptr :pointer))))
(defun git-object-lookup (oid type repository)
"Returns a git object which is identified by the OID.
The type argument specifies which type is expected. If the found
object is not of the right type, an error will be signalled."
(assert (not (null-or-nullpointer repository)))
(make-instance-object :pointer (git-object-lookup-ptr oid type repository)
:facilitator repository
:type type))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Some generic functions
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod oid ((object git-object))
(git-object-id object))
(defmethod full-name ((object git-object))
(format nil "~x" (oid object)))
(defmethod short-name ((object git-object))
(subseq (format nil "~x" (oid object)) 0 7))
(defmethod print-object ((object git-object) stream)
(print-unreadable-object (object stream :type t :identity t)
(cond
((and (slot-value object 'libgit2-pointer)
(not (null-pointer-p (slot-value object 'libgit2-pointer))))
(format stream "~a" (full-name object)))
((or (slot-value object 'libgit2-oid) (slot-value object 'libgit2-name))
(format stream "~a (weak)" (full-name object)))
((slot-value object 'libgit2-disposed)
(format stream "(disposed)")))))
(defmethod get-object ((class (eql 'object)) oid repository)
(git-object-lookup oid :any repository))
(defgeneric object-type (object)
(:method ((object git-object))
(git-object-type object)))
| null | https://raw.githubusercontent.com/russell/cl-git/ab58b1dcf34649899085e9df95962ef1c9d902c3/src/object.lisp | lisp | Syntax : COMMON - LISP ; Base : 10 -*-
cl-git is a Common Lisp interface to git repositories.
This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
License along with this program. If not, see
</>.
Low-level interface
Resolve by name
Some generic functions
|
Copyright ( C ) 2011 - 2022 < >
as published by the Free Software Foundation , either version 3 of
the License , or ( at your option ) any later version .
You should have received a copy of the GNU Lesser General Public
(in-package #:cl-git)
(defvar object-type-mapping
(list 'commit :commit
'tree :tree
'blob :blob
'tag :tag))
(defmethod pointer ((object git-object))
"Try and resolve the pointer if it isn't set."
(when (and (null-pointer-p (slot-value object 'libgit2-pointer))
(not (slot-value object 'libgit2-disposed)))
(cond
Resolve by
((slot-value object 'libgit2-oid)
(setf (slot-value object 'libgit2-pointer)
(git-object-lookup-ptr (slot-value object 'libgit2-oid)
(getf object-type-mapping (type-of object))
(facilitator object)))
(enable-garbage-collection object)
(setf (slot-value object 'libgit2-oid) nil))
((slot-value object 'libgit2-name)
(setf (slot-value object 'libgit2-pointer)
(%git-lookup-by-name (type-of object)
(slot-value object 'libgit2-name)
(facilitator object)))
(enable-garbage-collection object)
(setf (slot-value object 'libgit2-name) nil))
(t (error "Unable to lookup object in git repository."))))
(slot-value object 'libgit2-pointer))
(defmethod initialize-instance :after ((instance git-object) &rest r)
"Setup the finalizer to call internal-dispose with the right arguments."
(when (getf r :pointer)
(enable-garbage-collection instance)))
(defmethod print-object ((object git-object) stream)
(print-unreadable-object (object stream :type t :identity t)
(cond
((not (null-pointer-p (slot-value object 'libgit2-pointer)))
(format stream "~X" (pointer-address (pointer object))))
((or (slot-value object 'libgit2-oid) (slot-value object 'libgit2-name))
(princ "(weak)" stream))
((slot-value object 'libgit2-disposed)
(princ "(disposed)" stream)))))
(defmethod translate-to-foreign (value (type git-object))
(if (pointerp value)
value
(pointer value)))
(defcfun ("git_object_id" git-object-id)
%oid
"Returns the oid identifying OBJECT"
(object %object))
(defcfun ("git_object_type" git-object-type)
git-object-t
"Returns the type of the git object."
(object %object))
(defcfun ("git_object_lookup" %git-object-lookup)
%return-value
(object %object)
(repo %repository)
(oid %oid)
(type git-object-t))
(defcfun ("git_object_free" git-object-free)
:void
"Free the git object."
(object :pointer))
Highlevel Interface
(defun make-instance-object (&key pointer facilitator type)
"Creates an object wrapping OBJECT-PTR.
OBJECT-PTR needs to point to one of the git storage types, such as:
:commit :tag :tree or :blob. This function is not suitable to
wrap git pointers to repositories, config, index etc."
(let ((obj-type
(if (eq type :any)
(case (git-object-type pointer)
(:commit 'commit)
(:tag 'tag)
(:tree 'tree)
(:blob 'blob)
(:config 'config)
(t type))
type)))
(make-instance obj-type
:pointer pointer
:facilitator facilitator
:free-function #'git-object-free)))
(defmethod dispose ((object git-object))
"Dispose of the object and association to the facilitator. Mark
the pointer as disposed."
(setf (facilitator object) nil)
(when (car (finalizer-data object))
(internal-dispose (finalizer-data object)
(pointer object)
(free-function object))
(setf (slot-value object 'libgit2-pointer) nil)
(setf (slot-value object 'libgit2-disposed) t)))
(defun git-object-lookup-ptr (oid type repository)
(assert (not (null-or-nullpointer repository)))
(let ((type
(case type
(commit :commit)
(tag :tag)
(tree :tree)
(blob :blob)
(tree-tree :tree)
(tree-blob :blob)
(config :config)
(t type))))
(with-foreign-object (obj-ptr :pointer)
(%git-object-lookup obj-ptr repository oid type)
(mem-ref obj-ptr :pointer))))
(defun git-object-lookup (oid type repository)
"Returns a git object which is identified by the OID.
The type argument specifies which type is expected. If the found
object is not of the right type, an error will be signalled."
(assert (not (null-or-nullpointer repository)))
(make-instance-object :pointer (git-object-lookup-ptr oid type repository)
:facilitator repository
:type type))
(defmethod oid ((object git-object))
(git-object-id object))
(defmethod full-name ((object git-object))
(format nil "~x" (oid object)))
(defmethod short-name ((object git-object))
(subseq (format nil "~x" (oid object)) 0 7))
(defmethod print-object ((object git-object) stream)
(print-unreadable-object (object stream :type t :identity t)
(cond
((and (slot-value object 'libgit2-pointer)
(not (null-pointer-p (slot-value object 'libgit2-pointer))))
(format stream "~a" (full-name object)))
((or (slot-value object 'libgit2-oid) (slot-value object 'libgit2-name))
(format stream "~a (weak)" (full-name object)))
((slot-value object 'libgit2-disposed)
(format stream "(disposed)")))))
(defmethod get-object ((class (eql 'object)) oid repository)
(git-object-lookup oid :any repository))
(defgeneric object-type (object)
(:method ((object git-object))
(git-object-type object)))
|
8b37086393c94c18d71b0251f4f63bf3dbbcdad1a783b7179dc7325e8eb94c99 | ghcjs/ghcjs-boot | Conc.hs | # LANGUAGE Unsafe #
# LANGUAGE CPP , NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - missing - signatures #
# OPTIONS_HADDOCK not - home #
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Conc
Copyright : ( c ) The University of Glasgow , 1994 - 2002
-- License : see libraries/base/LICENSE
--
-- Maintainer :
-- Stability : internal
Portability : non - portable ( GHC extensions )
--
-- Basic concurrency stuff.
--
-----------------------------------------------------------------------------
-- No: #hide, because bits of this module are exposed by the stm package.
-- However, we don't want this module to be the home location for the
-- bits it exports, we'd rather have Control.Concurrent and the other
-- higher level modules be the home. Hence: #not-home
module GHC.Conc
( ThreadId(..)
-- * Forking and suchlike
, forkIO
, forkIOWithUnmask
, forkOn
, forkOnWithUnmask
, numCapabilities
, getNumCapabilities
, setNumCapabilities
, getNumProcessors
, numSparks
, childHandler
, myThreadId
, killThread
, throwTo
, par
, pseq
, runSparks
, yield
, labelThread
, mkWeakThreadId
, ThreadStatus(..), BlockReason(..)
, threadStatus
, threadCapability
-- * Waiting
, threadDelay
, registerDelay
, threadWaitRead
, threadWaitWrite
, threadWaitReadSTM
, threadWaitWriteSTM
, closeFdWith
-- * Allocation counter and limit
, setAllocationCounter
, getAllocationCounter
, enableAllocationLimit
, disableAllocationLimit
* TVars
, STM(..)
, atomically
, retry
, orElse
, throwSTM
, catchSTM
, alwaysSucceeds
, always
, TVar(..)
, newTVar
, newTVarIO
, readTVar
, readTVarIO
, writeTVar
, unsafeIOToSTM
-- * Miscellaneous
, withMVar
#ifdef mingw32_HOST_OS
, asyncRead
, asyncWrite
, asyncDoProc
, asyncReadBA
, asyncWriteBA
#endif
#ifndef mingw32_HOST_OS
, Signal, HandlerFun, setHandler, runHandlers
#endif
, ensureIOManagerIsRunning
, ioManagerCapabilitiesChanged
#ifdef mingw32_HOST_OS
, ConsoleEvent(..)
, win32ConsoleHandler
, toWin32ConsoleEvent
#endif
, setUncaughtExceptionHandler
, getUncaughtExceptionHandler
, reportError, reportStackOverflow
) where
import GHC.Conc.IO
import GHC.Conc.Sync
#ifndef mingw32_HOST_OS
import GHC.Conc.Signal
#endif
| null | https://raw.githubusercontent.com/ghcjs/ghcjs-boot/8c549931da27ba9e607f77195208ec156c840c8a/boot/base/GHC/Conc.hs | haskell | ---------------------------------------------------------------------------
|
Module : GHC.Conc
License : see libraries/base/LICENSE
Maintainer :
Stability : internal
Basic concurrency stuff.
---------------------------------------------------------------------------
No: #hide, because bits of this module are exposed by the stm package.
However, we don't want this module to be the home location for the
bits it exports, we'd rather have Control.Concurrent and the other
higher level modules be the home. Hence: #not-home
* Forking and suchlike
* Waiting
* Allocation counter and limit
* Miscellaneous | # LANGUAGE Unsafe #
# LANGUAGE CPP , NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - missing - signatures #
# OPTIONS_HADDOCK not - home #
Copyright : ( c ) The University of Glasgow , 1994 - 2002
Portability : non - portable ( GHC extensions )
module GHC.Conc
( ThreadId(..)
, forkIO
, forkIOWithUnmask
, forkOn
, forkOnWithUnmask
, numCapabilities
, getNumCapabilities
, setNumCapabilities
, getNumProcessors
, numSparks
, childHandler
, myThreadId
, killThread
, throwTo
, par
, pseq
, runSparks
, yield
, labelThread
, mkWeakThreadId
, ThreadStatus(..), BlockReason(..)
, threadStatus
, threadCapability
, threadDelay
, registerDelay
, threadWaitRead
, threadWaitWrite
, threadWaitReadSTM
, threadWaitWriteSTM
, closeFdWith
, setAllocationCounter
, getAllocationCounter
, enableAllocationLimit
, disableAllocationLimit
* TVars
, STM(..)
, atomically
, retry
, orElse
, throwSTM
, catchSTM
, alwaysSucceeds
, always
, TVar(..)
, newTVar
, newTVarIO
, readTVar
, readTVarIO
, writeTVar
, unsafeIOToSTM
, withMVar
#ifdef mingw32_HOST_OS
, asyncRead
, asyncWrite
, asyncDoProc
, asyncReadBA
, asyncWriteBA
#endif
#ifndef mingw32_HOST_OS
, Signal, HandlerFun, setHandler, runHandlers
#endif
, ensureIOManagerIsRunning
, ioManagerCapabilitiesChanged
#ifdef mingw32_HOST_OS
, ConsoleEvent(..)
, win32ConsoleHandler
, toWin32ConsoleEvent
#endif
, setUncaughtExceptionHandler
, getUncaughtExceptionHandler
, reportError, reportStackOverflow
) where
import GHC.Conc.IO
import GHC.Conc.Sync
#ifndef mingw32_HOST_OS
import GHC.Conc.Signal
#endif
|
42c55c86c8e6007d1bcde474ea3da61f4a3c7c2810fc118459677c18ccf770bd | fukamachi/webapi | response.lisp | (defpackage #:webapi/response
(:use #:cl)
(:export #:response
#:response-status
#:response-headers
#:response-body
#:response-uri))
(in-package #:webapi/response)
(defclass response ()
((status :initarg :status
:reader response-status)
(headers :initarg :headers
:reader response-headers)
(body :initarg :body
:reader response-body)
(uri :initarg :uri
:reader response-uri)))
| null | https://raw.githubusercontent.com/fukamachi/webapi/99e64a22566946a937973b3994a28ae9535c9a63/response.lisp | lisp | (defpackage #:webapi/response
(:use #:cl)
(:export #:response
#:response-status
#:response-headers
#:response-body
#:response-uri))
(in-package #:webapi/response)
(defclass response ()
((status :initarg :status
:reader response-status)
(headers :initarg :headers
:reader response-headers)
(body :initarg :body
:reader response-body)
(uri :initarg :uri
:reader response-uri)))
| |
666599dcc42fdf9267cddf4068ad58e006e6eece8afde8eb212ee9633e597ab0 | clojerl/clojerl | clj_reader_SUITE.erl | -module(clj_reader_SUITE).
-include("clojerl.hrl").
-include("clojerl_int.hrl").
-include("clj_test_utils.hrl").
-include_lib("common_test/include/ct.hrl").
-export([ all/0
, groups/0
, init_per_group/2
, end_per_group/2
, init_per_suite/1
, end_per_suite/1
]).
-export([ eof/1
, number/1
, string/1
, keyword/1
, symbol/1
, comment/1
, quote/1
, deref/1
, meta/1
, syntax_quote/1
, unquote/1
, list/1
, vector/1
, map/1
, set/1
, unmatched_delim/1
, char/1
, arg/1
, fn/1
, eval/1
, var/1
, regex/1
, unreadable_form/1
, discard/1
, 'cond'/1
, unsupported_reader/1
, erl_literals/1
, erl_binary/1
, erl_alias/1
, tagged/1
, reader_resolver/1
, namespaced_map/1
]).
-spec all() -> [atom()].
all() -> [{group, read}, {group, read_io}].
-spec groups() -> [atom()].
groups() ->
[ {read, [], clj_test_utils:all(?MODULE)}
, {read_io, [], clj_test_utils:all(?MODULE)}
].
-spec init_per_group(atom(), config()) -> config().
init_per_group(read, Config) ->
[ {read_fun, fun read/1}
, {read_fun2, fun read/2}
, {read_all_fun, fun read_all/1}
| Config
];
init_per_group(read_io, Config) ->
[ {read_fun, fun read_io/1}
, {read_fun2, fun read_io/2}
, {read_all_fun, fun read_all_io/1}
| Config
].
-spec end_per_group(atom(), config()) -> ok.
end_per_group(_, _Config) -> ok.
-spec init_per_suite(config()) -> config().
init_per_suite(Config) -> clj_test_utils:init_per_suite(Config).
-spec end_per_suite(config()) -> config().
end_per_suite(Config) -> Config.
%%------------------------------------------------------------------------------
%% Test Cases
%%------------------------------------------------------------------------------
eof(Config) ->
ReadFun = ?config(read_fun, Config),
ct:comment("Read empty binary"),
ok = try ReadFun(<<"">>)
catch _:_ -> ok end,
ok = try ReadFun(<<" , , , , ">>)
catch _:_ -> ok end,
ok = try ReadFun(<<", , , \t \n ,, ">>)
catch _:_ -> ok end,
{comments, ""}.
number(Config) ->
ReadFun = ?config(read_fun, Config),
ReadAllFun = ?config(read_all_fun, Config),
0 = ReadFun(<<"0">>),
0.0 = ReadFun(<<"0.0">>),
1 = ReadFun(<<"1">>),
1 = ReadFun(<<"+1">>),
-1 = ReadFun(<<"-1">>),
1.0 = ReadFun(<<"1.0">>),
1.0 = ReadFun(<<"10E-1">>),
1.0 = ReadFun(<<"10.0e-1">>),
1.0 = ReadFun(<<"10.e-1">>),
1.0 = ReadFun(<<"10e-1">>),
1.0 = ReadFun(<<"+10e-1">>),
-1.0 = ReadFun(<<"-10e-1">>),
42 = ReadFun(<<"0x2A">>),
42 = ReadFun(<<"052">>),
42 = ReadFun(<<"36r16">>),
42 = ReadFun(<<"36R16">>),
ok = try ReadFun(<<"1/2">>), error
catch _:_ -> ok
end,
ok = try ReadFun(<<"12A">>), error
catch _:_ -> ok
end,
[0, 1, 2.0, 3.0e-10] = ReadAllFun(<<"0N 1 2.0 3e-10">>),
{comments, ""}.
string(Config) ->
ReadFun = ?config(read_fun, Config),
<<"">> = ReadFun(<<"\"\"">>),
<<"hello">> = ReadFun(<<"\"hello\"">>),
<<"hello \t world!">> = ReadFun(<<"\"hello \\t world!\"">>),
<<"hello \n world!">> = ReadFun(<<"\"hello \\n world!\"">>),
<<"hello \r world!">> = ReadFun(<<"\"hello \\r world!\"">>),
<<"hello \" world!">> = ReadFun(<<"\"hello \\\" world!\"">>),
<<"hello \f world!">> = ReadFun(<<"\"hello \\f world!\"">>),
<<"hello \b world!">> = ReadFun(<<"\"hello \\b world!\"">>),
<<"hello \\ world!">> = ReadFun(<<"\"hello \\\\ world!\"">>),
<<"hello © world!"/utf8>> =
ReadFun(<<"\"hello \\u00A9 world!\"">>),
ok = try ReadFun(<<"\"hello \\u00A world!\"">>)
catch _:_ -> ok
end,
ok = try ReadFun(<<"\"hello \\u00Z world!\"">>)
catch _:_ -> ok
end,
<<"hello © world!"/utf8>> =
ReadFun(<<"\"hello \\251 world!\"">>),
ct:comment("EOF"),
ok = try ReadFun(<<"\"hello world!">>)
catch _:_ -> ok
end,
ct:comment("Octal not in range"),
ok = try ReadFun(<<"\"hello \\400 world!">>)
catch _:_ -> ok
end,
ct:comment("Number not in base"),
ok = try ReadFun(<<"\"hello \\u000Z world!">>)
catch _:_ -> ok
end,
ct:comment("Unsupported escaped char"),
ok = try ReadFun(<<"\"hello \\z world!">>)
catch _:_ -> ok
end,
{comments, ""}.
keyword(Config) ->
ReadFun = ?config(read_fun, Config),
FooSym = clj_rt:symbol(<<"foo">>),
FooNs = 'clojerl.Namespace':find_or_create(FooSym),
SomeSym = clj_rt:symbol(<<"some">>),
SomeNs = 'clojerl.Namespace':find_or_create(SomeSym),
Keyword1 = clj_rt:keyword(<<"hello-world">>),
Keyword1 = ReadFun(<<":hello-world">>),
Keyword2 = clj_rt:keyword(<<"some">>, <<"hello-world">>),
Keyword2 = ReadFun(<<"::hello-world">>),
Keyword3 = clj_rt:keyword(<<"another-ns">>, <<"hello-world">>),
Keyword3 = ReadFun(<<":another-ns/hello-world">>),
Keyword4 = clj_rt:keyword(<<"/">>),
Keyword4 = ReadFun(<<":/">>),
Keyword5 = clj_rt:keyword(<<"some">>, <<"/">>),
Keyword5 = ReadFun(<<":some//">>),
FSym = clj_rt:symbol(<<"f">>),
SomeNs = 'clojerl.Namespace':add_alias(SomeNs, FSym, FooNs),
Keyword6 = clj_rt:keyword(<<"foo">>, <<"hello-world">>),
Keyword6 = ReadFun(<<"::f/hello-world">>),
Keyword7 = clj_rt:keyword(<<"42hello-world">>),
Keyword7 = ReadFun(<<":42hello-world">>),
ct:comment("Error: triple colon :::"),
ok = try ReadFun(<<":::hello-world">>)
catch _:_ -> ok
end,
ct:comment("Error: empty name after namespace"),
ok = try ReadFun(<<":some-ns/">>)
catch _:_ -> ok
end,
ct:comment("Error: colon as last char"),
ok = try ReadFun(<<":hello-world:">>)
catch _:_ -> ok
end,
ct:comment("Error: single colon"),
ok = try ReadFun(<<":">>)
catch _:_ -> ok
end,
{comments, ""}.
symbol(Config) ->
ReadFun = ?config(read_fun, Config),
Symbol1 = clj_rt:symbol(<<"hello-world">>),
?assertEquiv(ReadFun(<<"hello-world">>), Symbol1),
Symbol2 = clj_rt:symbol(<<"some-ns">>, <<"hello-world">>),
?assertEquiv(ReadFun(<<"some-ns/hello-world">>), Symbol2),
Symbol3 = clj_rt:symbol(<<"another-ns">>, <<"hello-world">>),
?assertEquiv( ReadFun(<<"another-ns/hello-world">>)
, Symbol3
),
Symbol4 = clj_rt:symbol(<<"some-ns">>, <<"/">>),
?assertEquiv(ReadFun(<<"some-ns//">>), Symbol4),
ct:comment("nil, true & false"),
?NIL = ReadFun(<<"nil">>),
true = ReadFun(<<"true">>),
false = ReadFun(<<"false">>),
ct:comment("Error: empty name after namespace"),
ok = try ReadFun(<<"some-ns/">>)
catch _:_ -> ok
end,
ct:comment("Error: colon as last char"),
ok = try ReadFun(<<"hello-world:">>)
catch _:_ -> ok
end,
ct:comment("Error: numeric first char in name"),
ok = try ReadFun(<<"42hello-world">>)
catch _:_ -> ok
end,
{comments, ""}.
comment(Config) ->
ReadAllFun = ?config(read_all_fun, Config),
BlaKeyword = clj_rt:keyword(<<"bla">>),
ct:comment("Single semi-colon"),
[1, BlaKeyword] = ReadAllFun(<<"1 ; comment\n :bla ">>),
ct:comment("Two semi-colon"),
[1, BlaKeyword] = ReadAllFun(<<"1 ;; comment\n :bla ">>),
ct:comment("A bunch of semi-colons"),
[1, BlaKeyword] = ReadAllFun(<<"1 ;;;; comment\n :bla ">>),
ct:comment("Comment reader"),
[1, BlaKeyword] = ReadAllFun(<<"1 #! comment\n :bla ">>),
ct:comment("Comment after meta"),
[BarSym1] = ReadAllFun(<<"^:foo ;; comment\n bar">>),
<<"bar">> = clj_rt:name(BarSym1),
true = clj_rt:get(clj_rt:meta(BarSym1), foo),
[_, BarSym2] = ReadAllFun(<<"hello ^:foo ;; comment\n bar">>),
<<"bar">> = clj_rt:name(BarSym2),
true = clj_rt:get(clj_rt:meta(BarSym2), foo),
{comments, ""}.
quote(Config) ->
ReadFun = ?config(read_fun, Config),
QuoteSymbol = clj_rt:symbol(<<"quote">>),
ListSymbol = clj_rt:symbol(<<"list">>),
ct:comment("Quote number"),
ListQuote1 = clj_rt:list([QuoteSymbol, 1]),
ListQuote1 = ReadFun(<<"'1">>),
ct:comment("Quote symbol"),
ListQuote2 = clj_rt:list([QuoteSymbol, ListSymbol]),
?assertEquiv(ReadFun(<<"'list">>), ListQuote2),
ct:comment("Quote space symbol"),
?assertEquiv(ReadFun(<<"' list">>), ListQuote2),
ct:comment("Error: only provide ' "),
ok = try ReadFun(<<"'">>)
catch _:_ -> ok
end,
{comments, ""}.
deref(Config) ->
ReadFun = ?config(read_fun, Config),
ReadAllFun = ?config(read_all_fun, Config),
DerefSymbol = clj_rt:symbol(<<"clojure.core">>, <<"deref">>),
ListSymbol = clj_rt:symbol(<<"list">>),
ct:comment("Deref number :P"),
ListDeref1 = clj_rt:list([DerefSymbol, 1]),
ListDeref1= ReadFun(<<"@1">>),
ct:comment("Deref symbol :P"),
ListDeref2 = clj_rt:list([DerefSymbol, ListSymbol]),
?assertEquiv(ReadFun(<<"@list">>), ListDeref2),
ct:comment("Deref symbol :P and read other stuff"),
[ListDeref3, 42.0] = ReadAllFun(<<"@list 42.0">>),
?assertEquiv(ListDeref3, ListDeref2),
ct:comment("Error: only provide @ "),
ok = try ReadFun(<<"@">>)
catch _:_ -> ok
end,
{comments, ""}.
meta(Config) ->
ReadFun = ?config(read_fun, Config),
MetadataKw = ReadFun(<<"{:private true}">>),
MetadataSym = ReadFun(<<"{:tag private}">>),
ct:comment("Keyword doesn't support metadata"),
ok = try ReadFun(<<"^:private :hello">>), error
catch _:_ -> ok
end,
%% Compare metadata after removing the location information.
AssertMetaEquiv =
fun(Value, ExpectedMeta) ->
Meta = clj_rt:meta(Value),
MetaNoLocation = clj_reader:remove_location(Meta),
?assertEquiv(MetaNoLocation, ExpectedMeta)
end,
ct:comment("Keyword meta to symbol"),
SymbolWithMetaKw = ReadFun(<<"^:private hello">>),
AssertMetaEquiv(SymbolWithMetaKw, MetadataKw),
ct:comment("Symbol meta to symbol"),
SymbolWithMetaSym = ReadFun(<<"^private hello">>),
AssertMetaEquiv(SymbolWithMetaSym, MetadataSym),
ct:comment("Map meta to symbol"),
MapWithMetaKw = ReadFun(<<"^:private {}">>),
AssertMetaEquiv(MapWithMetaKw, MetadataKw),
ct:comment("Map meta to symbol"),
MapWithMetaSym = ReadFun(<<"^private {}">>),
AssertMetaEquiv(MapWithMetaSym, MetadataSym),
ct:comment("List meta to symbol"),
ListWithMetaKw = ReadFun(<<"^:private ()">>),
AssertMetaEquiv(ListWithMetaKw, MetadataKw),
ct:comment("List meta to symbol"),
ListWithMetaSym = ReadFun(<<"^private ()">>),
AssertMetaEquiv(ListWithMetaSym, MetadataSym),
ct:comment("Vector meta to symbol"),
VectorWithMetaKw = ReadFun(<<"^:private []">>),
AssertMetaEquiv(VectorWithMetaKw, MetadataKw),
ct:comment("Vector meta to symbol"),
VectorWithMetaSym = ReadFun(<<"^private []">>),
AssertMetaEquiv(VectorWithMetaSym, MetadataSym),
ct:comment("Set meta to symbol"),
SetWithMetaKw = ReadFun(<<"^:private #{}">>),
AssertMetaEquiv(SetWithMetaKw, MetadataKw),
ct:comment("Set meta to symbol"),
SetWithMetaSym = ReadFun(<<"^private #{}">>),
AssertMetaEquiv(SetWithMetaSym, MetadataSym),
ct:comment("Meta number"),
ok = try ReadFun(<<"^1 1">>)
catch _:_ -> ok
end,
ct:comment("Reader meta number"),
ok = try ReadFun(<<"#^1 1">>)
catch _:_ -> ok
end,
ct:comment("Meta without form"),
ok = try ReadFun(<<"^:private">>)
catch _:_ -> ok
end,
{comments, ""}.
syntax_quote(Config) ->
ReadFun = ?config(read_fun, Config),
QuoteSym = clj_rt:symbol(<<"quote">>),
QuoteFun = fun(X) -> clj_rt:list([QuoteSym, X]) end,
ct:comment("Read special form"),
DoSym = clj_rt:symbol(<<"do">>),
QuoteDoList = QuoteFun(DoSym),
DoSyntaxQuote = ReadFun(<<"`do">>),
?assertEquiv(DoSyntaxQuote, QuoteDoList),
ct:comment("Form with meta info other than location keeps meta"),
WithMetaSym = clj_rt:symbol(<<"clojure.core">>, <<"with-meta">>),
DoWithMetaSyntaxQuote = ReadFun(<<"`^:foo do">>),
?assertEquiv(clj_rt:first(DoWithMetaSyntaxQuote), WithMetaSym),
?assertEquiv(clj_rt:second(DoWithMetaSyntaxQuote), QuoteDoList),
DefSym = clj_rt:symbol(<<"def">>),
QuoteDefList = clj_rt:list([QuoteSym, DefSym]),
DefSyntaxQuote = ReadFun(<<"`def">>),
?assertEquiv(DefSyntaxQuote, QuoteDefList),
ct:comment("Read literals"),
1 = ReadFun(<<"`1">>),
42.0 = ReadFun(<<"`42.0">>),
<<"something!">> = ReadFun(<<"`\"something!\"">>),
ct:comment("Keywords can't have metadata"),
HelloKeyword = clj_rt:keyword(<<"hello">>),
HelloKeyword = ReadFun(<<"`:hello">>),
ct:comment("Read values that can have metadata"),
ct:comment("Read unqualified symbol"),
UserHelloSym = clj_rt:symbol(<<"clojure.core">>, <<"hello">>),
HelloSyntaxQuote = ReadFun(<<"`hello">>),
?assertEquiv(HelloSyntaxQuote, QuoteFun(UserHelloSym)),
ct:comment("Read qualified symbol"),
SomeNsHelloSym = clj_rt:symbol(<<"some-ns">>, <<"hello">>),
SomeNsHelloSyntaxQuote = ReadFun(<<"`some-ns/hello">>),
?assertEquiv( SomeNsHelloSyntaxQuote, QuoteFun(SomeNsHelloSym)),
ct:comment("Read qualified symbol mapping to existing var"),
ResolverSym = clj_rt:symbol(<<"clojure.core">>, <<"*reader-resolver*">>),
ResolverSymSyntaxQuote = ReadFun(<<"`clojure.core/*reader-resolver*">>),
?assertEquiv(ResolverSymSyntaxQuote, QuoteFun(ResolverSym)),
ct:comment("Read constructor type symbol"),
ConstructorTypeSym = clj_rt:symbol(<<"clojerl.String.">>),
ConstructorTypeSyntaxQuote = ReadFun(<<"`clojerl.String.">>),
?assertEquiv(ConstructorTypeSyntaxQuote, QuoteFun(ConstructorTypeSym)),
ct:comment("Read type function name symbol"),
FunctionNameSym = clj_rt:symbol(<<".str">>),
FunctionNameSyntaxQuote = ReadFun(<<"`.str">>),
?assertEquiv(FunctionNameSyntaxQuote, QuoteFun(FunctionNameSym)),
ct:comment("Read auto-gen symbol"),
ListGenSym = ReadFun(<<"`hello#">>),
QuotedGenSym = clj_rt:second(ListGenSym),
GenSymName = clj_rt:name(QuotedGenSym),
{match, _} = re:run(GenSymName, "hello__\\d+__auto__"),
ct:comment("Read auto-gen symbol, "
"check generated symbols have the same name"),
ListApply = ReadFun(<<"`(hello# hello# world#)">>),
ListConcat = clj_rt:third(ListApply),
ListSecond = clj_rt:second(ListConcat),
ListThird = clj_rt:third(ListConcat),
?assertEquiv(clj_rt:second(ListSecond), clj_rt:second(ListThird)),
ct:comment("Read unquote"),
HelloSym = clj_rt:symbol(<<"hello">>),
ListWithMetaHelloSym = ReadFun(<<"`~hello">>),
?assertEquiv(ListWithMetaHelloSym, HelloSym),
ct:comment("Use unquote splice not in list"),
ok = try ReadFun(<<"`~@(hello)">>)
catch _:_ -> ok end,
ct:comment("Read list and empty list"),
ListHello = ReadFun(<<"`(hello :world)">>),
ListHelloCheck = ReadFun(<<"(clojure.core/concat"
" (clojure.core/list 'clojure.core/hello)"
" (clojure.core/list :world))">>),
?assertEquiv( clj_rt:third(ListHello), ListHelloCheck),
EmptyList = ReadFun(<<"`()">>),
EmptyListCheck = ReadFun(<<"(clojure.core/list)">>),
?assertEquiv(clj_rt:third(EmptyList), EmptyListCheck),
ct:comment("Read map"),
Map = ReadFun(<<"`{hello :world}">>),
MapCheck = ReadFun(<<"(clojure.core/apply"
" clojure.core/hash-map"
" (clojure.core/concat"
" (clojure.core/list 'clojure.core/hello)"
" (clojure.core/list :world)))">>),
?assertEquiv(Map, MapCheck),
ct:comment("Read vector"),
Vector = ReadFun(<<"`[hello :world]">>),
VectorCheck = ReadFun(<<"(clojure.core/apply"
" clojure.core/vector"
" (clojure.core/concat"
" (clojure.core/list 'clojure.core/hello)"
" (clojure.core/list :world)))">>),
?assertEquiv(Vector, VectorCheck),
ct:comment("Read set"),
Set = ReadFun(<<"`#{hello :world}">>),
SetCheck = ReadFun(<<"(clojure.core/apply"
" clojure.core/hash-set"
" (clojure.core/concat"
" (clojure.core/list 'clojure.core/hello)"
" (clojure.core/list :world)))">>),
?assertEquiv(Set, SetCheck),
ct:comment("Read unquote-splice inside list"),
HelloWorldSup = ReadFun(<<"`(~@(hello world) :sup?)">>),
HelloWorldSupCheck = ReadFun(<<"(clojure.core/concat"
" (hello world)"
" (clojure.core/list :sup?))">>),
?assertEquiv(clj_rt:third(HelloWorldSup), HelloWorldSupCheck),
ct:comment("Read unquote inside list"),
ListHelloWorld = ReadFun(<<"`(~hello :world)">>),
ListHelloWorldCheck = ReadFun(<<"(clojure.core/concat"
" (clojure.core/list hello)"
" (clojure.core/list :world))">>),
?assertEquiv(clj_rt:third(ListHelloWorld), ListHelloWorldCheck),
ct:comment("Syntax quote a symbol with dots"),
HelloWorldWithDot = ReadFun(<<"`hello.world">>),
HelloWorldWithDotCheck = ReadFun(<<"(quote hello.world)">>),
?assertEquiv(HelloWorldWithDot, HelloWorldWithDotCheck),
ct:comment("Generated symbol in nested structure keeps meta"),
SymbolWithMeta = ReadFun(<<"`(^foo bar)">>),
SymbolWithMetaCheck =
ReadFun(<<"(clojure.core/concat"
" (clojure.core/list"
" (clojure.core/with-meta"
" (quote clojure.core/bar)"
" (clojure.core/apply clojure.core/hash-map"
" (clojure.core/concat"
" (clojure.core/list :tag)"
" (clojure.core/list (quote clojure.core/foo)))))))">>),
?assertEquiv(clj_rt:third(SymbolWithMeta), SymbolWithMetaCheck),
ct:comment("Read Erlang tuple"),
ClojureCoreTuple = ReadFun(<<"clojure.core/tuple">>),
ErlTupleHello = ReadFun(<<"`#erl[hello :world]">>),
ErlTupleHelloCheck = ReadFun(<<"(clojure.core/concat"
" (clojure.core/list 'clojure.core/hello)"
" (clojure.core/list :world))">>),
?assertEquiv(clj_rt:second(ErlTupleHello), ClojureCoreTuple),
?assertEquiv(clj_rt:third(ErlTupleHello), ErlTupleHelloCheck),
ct:comment("Read Erlang map"),
ClojureCoreErlMap = ReadFun(<<"clojure.core/erl-map">>),
ErlMapHello = ReadFun(<<"`#erl{hello :world}">>),
ErlMapHelloCheck = ReadFun(<<"(clojure.core/concat"
" (clojure.core/list 'clojure.core/hello)"
" (clojure.core/list :world))">>),
?assertEquiv(clj_rt:second(ErlMapHello), ClojureCoreErlMap),
?assertEquiv(clj_rt:third(ErlMapHello), ErlMapHelloCheck),
{comments, ""}.
unquote(Config) ->
ReadFun = ?config(read_fun, Config),
UnquoteSymbol = clj_rt:symbol(<<"clojure.core">>, <<"unquote">>),
UnquoteSplicingSymbol = clj_rt:symbol(<<"clojure.core">>,
<<"unquote-splicing">>),
HelloWorldSymbol = clj_rt:symbol(<<"hello-world">>),
ct:comment("Unquote"),
ListUnquote = clj_rt:list([UnquoteSymbol, HelloWorldSymbol]),
?assertEquiv(ReadFun(<<"~hello-world">>), ListUnquote),
ct:comment("Unquote splicing"),
ListUnquoteSplicing = clj_rt:list([UnquoteSplicingSymbol,
HelloWorldSymbol]),
?assertEquiv(ReadFun(<<"~@hello-world">>), ListUnquoteSplicing),
ct:comment("Unquote nothing"),
ok = try ReadFun(<<"~">>)
catch _:_ -> ok
end,
{comments, ""}.
list(Config) ->
ReadFun = ?config(read_fun, Config),
HelloWorldKeyword = clj_rt:keyword(<<"hello-world">>),
HelloWorldSymbol = clj_rt:symbol(<<"hello-world">>),
ct:comment("Empty List"),
EmptyList = clj_rt:list([]),
?assertEquiv(ReadFun(<<"()">>), EmptyList),
ct:comment("List"),
List = clj_rt:list([HelloWorldKeyword, HelloWorldSymbol]),
?assertEquiv( ReadFun(<<"(:hello-world hello-world)">>)
, List
),
ct:comment("List & space"),
?assertEquiv( ReadFun(<<"(:hello-world hello-world )">>)
, List
),
ct:comment("List without closing paren"),
ok = try ReadFun(<<"(1 42.0">>)
catch _:_ -> ok
end,
{comments, ""}.
vector(Config) ->
ReadFun = ?config(read_fun, Config),
HelloWorldKeyword = clj_rt:keyword(<<"hello-world">>),
HelloWorldSymbol = clj_rt:symbol(<<"hello-world">>),
ct:comment("Vector"),
Vector = 'clojerl.Vector':?CONSTRUCTOR([HelloWorldKeyword, HelloWorldSymbol]),
?assertEquiv( ReadFun(<<"[:hello-world hello-world]">>)
, Vector
),
ct:comment("Vector without closing bracket"),
ok = try ReadFun(<<"[1 42.0">>)
catch _:_ -> ok
end,
{comments, ""}.
map(Config) ->
ReadFun = ?config(read_fun, Config),
HelloWorldKeyword = clj_rt:keyword(<<"hello-world">>),
HelloWorldSymbol = clj_rt:symbol(<<"hello-world">>),
ct:comment("Map"),
Map = 'clojerl.Map':?CONSTRUCTOR([ HelloWorldKeyword
, HelloWorldSymbol
, HelloWorldSymbol
, HelloWorldKeyword
]
),
MapResult = ReadFun(<<"{:hello-world hello-world,"
" hello-world :hello-world}">>),
?assertEquiv(Map, MapResult),
ct:comment("Map without closing braces"),
ok = try ReadFun(<<"{1 42.0">>)
catch _:_ -> ok
end,
ct:comment("Literal map with odd number of expressions"),
ok = try ReadFun(<<"{1 42.0 :a}">>)
catch _:_ -> ok
end,
{comments, ""}.
set(Config) ->
ReadFun = ?config(read_fun, Config),
HelloWorldKeyword = clj_rt:keyword(<<"hello-world">>),
HelloWorldSymbol = clj_rt:symbol(<<"hello-world">>),
ct:comment("Set"),
Set = 'clojerl.Set':?CONSTRUCTOR([HelloWorldKeyword, HelloWorldSymbol]),
SetResult = ReadFun(<<"#{:hello-world hello-world}">>),
?assertEquiv(Set, SetResult),
ct:comment("Set without closing braces"),
ok = try ReadFun(<<"#{1 42.0">>)
catch _:_ -> ok
end,
{comments, ""}.
unmatched_delim(Config) ->
ReadAllFun = ?config(read_all_fun, Config),
ct:comment("Single closing paren"),
ok = try ReadAllFun(<<"{1 42.0} )">>)
catch _:_ -> ok
end,
ct:comment("Single closing bracket"),
ok = try ReadAllFun(<<"{1 42.0} ]">>)
catch _:_ -> ok
end,
ct:comment("Single closing braces"),
ok = try ReadAllFun(<<"{1 42.0} } ">>)
catch _:_ -> ok
end,
{comments, ""}.
char(Config) ->
ReadFun = ?config(read_fun, Config),
ReadAllFun = ?config(read_all_fun, Config),
ct:comment("Read single char"),
<<"a">> = ReadFun(<<"\\a">>),
<<"\n">> = ReadFun(<<"\\newline">>),
<<" ">> = ReadFun(<<"\\space">>),
<<"\t">> = ReadFun(<<"\\tab">>),
<<"\b">> = ReadFun(<<"\\backspace">>),
<<"\f">> = ReadFun(<<"\\formfeed">>),
<<"\r">> = ReadFun(<<"\\return">>),
<<"©"/utf8>> = ReadFun(<<"\\u00A9">>),
<<"ß"/utf8>> = ReadFun(<<"\\o337">>),
<<" "/utf8>> = ReadFun(<<"\\ ">>),
<<"\""/utf8>> = ReadFun(<<"\\\"">>),
ct:comment("Char EOF"),
ok = try ReadAllFun(<<"12 \\">>)
catch _:_ -> ok
end,
ct:comment("Octal char wrong length"),
ok = try ReadAllFun(<<"12 \\o0337">>)
catch _:_ -> ok
end,
ct:comment("Octal char wrong range"),
ok = try ReadAllFun(<<"12 \\o477">>)
catch _:_ -> ok
end,
ct:comment("Unsupported char"),
ok = try ReadAllFun(<<"42.0 \\ab">>)
catch _:_ -> ok
end,
{comments, ""}.
fn(Config) ->
ReadFun = ?config(read_fun, Config),
FnSymbol = clj_rt:symbol(<<"fn*">>),
EmptyVector = clj_rt:vector([]),
EmptyList = clj_rt:list([]),
ct:comment("Read empty anonymous fn"),
EmptyFn = ReadFun(<<"#()">>),
FnSymbol = clj_rt:first(EmptyFn),
EmptyVector = clj_rt:second(EmptyFn),
?assertEquiv(clj_rt:third(EmptyFn), EmptyList),
ct:comment("Read anonymous fn with %"),
OneArgFn = ReadFun(<<"#(%)">>),
FnSymbol = clj_rt:first(OneArgFn),
ArgVector1 = clj_rt:second(OneArgFn),
1 = clj_rt:count(ArgVector1),
BodyList1 = clj_rt:third(OneArgFn),
1 = clj_rt:count(BodyList1),
true = clj_rt:first(ArgVector1) == clj_rt:first(ArgVector1),
ct:comment("Read anonymous fn with %4 and %42"),
FortyTwoArgFn = ReadFun(<<"#(do %42 %4)">>),
FnSymbol = clj_rt:first(FortyTwoArgFn),
ArgVector42 = clj_rt:second(FortyTwoArgFn),
42 = clj_rt:count(ArgVector42),
BodyList42 = clj_rt:third(FortyTwoArgFn),
3 = clj_rt:count(BodyList42),
Arg42Sym = clj_rt:second(BodyList42),
{match, _} = re:run(clj_rt:name(Arg42Sym), "p42__\\d+#"),
ct:comment("Read anonymous fn with %3 and %&"),
RestArgFn = ReadFun(<<"#(do %& %3)">>),
FnSymbol = clj_rt:first(RestArgFn),
ArgVectorRest = clj_rt:second(RestArgFn),
1 - 3 , & and rest
BodyListRest = clj_rt:third(RestArgFn),
3 = clj_rt:count(BodyListRest),
ArgRestSym = clj_rt:second(BodyListRest),
{match, _} = re:run(clj_rt:name(ArgRestSym), "rest__\\d+#"),
ct:comment("Nested #()"),
ok = try ReadFun(<<"#(do #(%))">>)
catch error:Error1 ->
Msg1 = 'clojerl.IError':message(Error1),
<<?NO_SOURCE, ":1:7: Nested #()s are not allowed">> = Msg1,
ok
end,
{comments, ""}.
arg(Config) ->
ReadFun = ?config(read_fun, Config),
ReadAllFun = ?config(read_all_fun, Config),
ct:comment("Read % as a symbol"),
ArgSymbol = clj_rt:symbol(<<"%">>),
?assertEquiv(ReadFun(<<"%">>), ArgSymbol),
ct:comment("Read %1 as a symbol"),
ArgOneSymbol = clj_rt:symbol(<<"%1">>),
?assertEquiv(ReadFun(<<"%1">>), ArgOneSymbol),
erlang:put(arg_env, #{}),
ct:comment("Read % as an argument"),
ArgGenSymbol = ReadFun(<<"%">>),
ArgGenName = clj_rt:name(ArgGenSymbol),
{match, _} = re:run(ArgGenName, "p1__\\d+#"),
ArgGenSymbol2 = ReadFun(<<"% ">>),
ArgGenName2 = clj_rt:name(ArgGenSymbol2),
{match, _} = re:run(ArgGenName2, "p1__\\d+#"),
ct:comment("Read %1 as an argument"),
ArgOneGenSymbol = ReadFun(<<"%1">>),
ArgOneGenName = clj_rt:name(ArgOneGenSymbol),
{match, _} = re:run(ArgOneGenName, "p1__\\d+#"),
ct:comment("Read %42 as an argument"),
ArgFortyTwoGenSymbol = ReadFun(<<"%42">>),
ArgFortyTwoGenName = clj_rt:name(ArgFortyTwoGenSymbol),
{match, _} = re:run(ArgFortyTwoGenName, "p42__\\d+#"),
ct:comment("Read %& as an argument"),
[ArgRestGenSymbol] = ReadAllFun(<<"%&">>),
ArgRestGenName = clj_rt:name(ArgRestGenSymbol),
{match, _} = re:run(ArgRestGenName, "rest__\\d+#"),
ct:comment("Invalid char after %"),
ok = try ReadFun(<<"%a">>)
catch error:Error1 ->
Msg1 = 'clojerl.IError':message(Error1),
<<?NO_SOURCE, ":1:2: Arg literal must be %, %& or %integer">> = Msg1,
ok
end,
erlang:erase(arg_env),
{comments, ""}.
eval(Config) ->
ReadFun = ?config(read_fun, Config),
ct:comment("Read eval 1"),
1 = ReadFun(<<"#=1">>),
ct:comment("Read eval (do 1)"),
1 = ReadFun(<<"#=(do 1)">>),
ct:comment("Read eval (str 1)"),
<<"1">> = ReadFun(<<"#=(clj_rt/str 1)">>),
{comments, ""}.
var(Config) ->
ReadFun = ?config(read_fun, Config),
VarSymbol = clj_rt:symbol(<<"var">>),
ListSymbol = clj_rt:symbol(<<"list">>),
ct:comment(""),
List = clj_rt:list([VarSymbol, ListSymbol]),
?assertEquiv(ReadFun(<<"#'list">>), List),
{comments, ""}.
regex(Config) ->
ReadFun = ?config(read_fun, Config),
ReadAllFun = ?config(read_all_fun, Config),
Regex1 = 'erlang.util.Regex':?CONSTRUCTOR(<<".?el\\.lo">>),
Regex1 = ReadFun(<<"#\".?el\\.lo\"">>),
Regex2 = 'erlang.util.Regex':?CONSTRUCTOR(<<"">>),
Regex2 = ReadFun(<<"#\"\"">>),
Regex3 = 'erlang.util.Regex':?CONSTRUCTOR(<<"foo\\\"">>),
Regex3 = ReadFun(<<"#\"foo\\\"\"">>),
ct:comment("EOF: unterminated regex"),
ok = try ReadAllFun(<<"#\"a*">>)
catch _:_ -> ok
end,
ct:comment("EOF: unterminated regex"),
ok = try ReadAllFun(<<"#\"foo\\">>)
catch _:_ -> ok
end,
{comments, ""}.
unreadable_form(Config) ->
ReadFun = ?config(read_fun, Config),
ct:comment("Read unreadable"),
ok = try ReadFun(<<"#<1>">>)
catch error:Error1 ->
Msg1 = 'clojerl.IError':message(Error1),
<<?NO_SOURCE, ":1:1: Unreadable form">> = Msg1,
ok
end,
{comments, ""}.
discard(Config) ->
ReadFun = ?config(read_fun, Config),
ReadAllFun = ?config(read_all_fun, Config),
[1] = ReadAllFun(<<"#_ :hello 1">>),
1 = ReadFun(<<"#_ :hello 1">>),
1 = ReadFun(<<"1 #_ :hello">>),
1 = ReadFun(<<"#_ #_ :hello :world 1">>),
[1, 2] = clj_rt:to_list(ReadFun(<<"(1 2 #_ #_ #_ #_ 3 4 5 6)">>)),
StrSym = clj_rt:symbol(<<"str">>),
ByeKeyword = clj_rt:keyword(<<"bye">>),
List = clj_rt:list([StrSym, ByeKeyword]),
?assertEquiv(ReadFun(<<"(str #_ :hello :bye)">>), List),
{comments, ""}.
'cond'(Config) when is_list(Config) ->
ReadFun = ?config(read_fun, Config),
ReadFun2 = ?config(read_fun2, Config),
AllowOpts = #{'read-cond' => allow},
AllowCljFeatureOpts = #{'read-cond' => allow,
features => ReadFun(<<"#{:clj}">>)},
AllowClrFeatureOpts = #{'read-cond' => allow,
features => ReadFun(<<"#{:clr}">>)},
HelloKeyword = clj_rt:keyword(<<"hello">>),
ct:comment("Allow with no features"),
HelloKeyword = ReadFun2(<<"#?(:one 2) :hello">>, AllowOpts),
ct:comment("Allow with feature match"),
2 = ReadFun2(<<"#?(:clj 2) :hello">>, AllowCljFeatureOpts),
ct:comment("Allow with no feature match"),
HelloKeyword = ReadFun2( <<"#?(:clj 2 :cljs [3]) :hello">>
, AllowClrFeatureOpts
),
ct:comment("Cond splice vector"),
OneTwoThreeVector = ReadFun(<<"[:one :two :three]">>),
OneTwoThreeVector = ReadFun2( <<"[:one #?@(:clj :three"
" :clr [:two]) :three]">>
, AllowClrFeatureOpts
),
OneTwoThreeVector = ReadFun2( <<"[:one #? @ (:clj :three"
" :clr [:two]) :three]">>
, AllowClrFeatureOpts
),
OneTwoThreeFourVector = ReadFun(<<"[:one :two :three :four]">>),
OneTwoThreeFourVector =
ReadFun2( <<"[:one #?@(:clj :three :clr"
" [:two :three] :cljs :five) :four]">>
, AllowClrFeatureOpts
),
ct:comment("Cond splice list"),
OneTwoThreeVector = ReadFun2( <<"[:one #?@(:clj :three"
" :clr (:two)) :three]">>
, AllowClrFeatureOpts
),
OneTwoThreeFourVector = ReadFun2( <<"[:one #?@(:clj :three :clr"
" (:two :three) :cljs :five) :four]">>
, AllowClrFeatureOpts
),
ct:comment("Preserve read"),
PreserveOpts = #{'read-cond' => preserve},
ReaderCond =
'clojerl.reader.ReaderConditional':?CONSTRUCTOR(
ReadFun(<<"(1 2)">>), false
),
[ReaderCondCheck, HelloKeyword] =
read_all(<<"#?(1 2) :hello">>, PreserveOpts),
?assertEquiv(ReaderCond, ReaderCondCheck),
ReaderCondSplice =
'clojerl.reader.ReaderConditional':?CONSTRUCTOR(
ReadFun(<<"(1 2)">>), true
),
ReaderCondSpliceVector = clj_rt:vector([ReaderCondSplice, HelloKeyword]),
ReaderCondSpliceVectorCheck = ReadFun2(<<"[#?@(1 2) :hello]">>, PreserveOpts),
?assertEquiv(ReaderCondSpliceVector, ReaderCondSpliceVectorCheck),
false = clj_rt:equiv(ReaderCond, ReaderCondSpliceVector),
ct:comment("EOF while reading cond"),
ok = try ReadFun2(<<"#?">>, AllowOpts)
catch error:Error1 ->
Msg1 = 'clojerl.IError':message(Error1),
<<?NO_SOURCE, ":1:3: EOF while reading cond">> = Msg1,
ok
end,
ct:comment("Reader conditional not allowed"),
ok = try ReadFun(<<"#?(:clj :whatever :clr :whateverrrr)">>)
catch error:Error2 ->
Msg2 = 'clojerl.IError':message(Error2),
<<?NO_SOURCE, ":1:3: Conditional read not allowed">> = Msg2,
ok
end,
ct:comment("No list"),
ok = try ReadFun2(<<"#?:clj">>, AllowOpts)
catch error:Error3 ->
Msg3 = 'clojerl.IError':message(Error3),
<<?NO_SOURCE, ":1:3: read-cond body must be a list">> = Msg3,
ok
end,
ct:comment("EOF: no feature matched"),
ok = try ReadFun2(<<"#?(:clj :whatever :clr :whateverrrr)">>, AllowOpts)
catch error:Error4 ->
Msg4 = 'clojerl.IError':message(Error4),
<<?NO_SOURCE, ":1:37: EOF">> = Msg4,
ok
end,
ct:comment("Uneven number of forms"),
ok = try ReadFun2(<<"#?(:one :two :three)">>, AllowOpts)
catch error:Error5 ->
Msg5 = 'clojerl.IError':message(Error5),
<<?NO_SOURCE, ":1:21: read-cond requires an "
"even number of forms">> = Msg5,
ok
end,
ct:comment("Splice at the top level"),
ok = try ReadFun2(<<"#?@(:clje [:two])">>, AllowOpts)
catch error:Error6 ->
Msg6 = 'clojerl.IError':message(Error6),
<<?NO_SOURCE, ":1:5: Reader conditional splicing not allowed "
"at the top level">> = Msg6,
ok
end,
ct:comment("Splice in list but not sequential"),
ok = try ReadFun2(<<"[#?@(:clr :a :cljs :b) :c :d]">>,
AllowClrFeatureOpts)
catch error:Error7 ->
Msg7 = 'clojerl.IError':message(Error7),
<<?NO_SOURCE, ":1:13: Spliced form list in read-cond-splicing "
"must extend clojerl.ISequential">> = Msg7,
ok
end,
ct:comment("Feature is not a keyword"),
ok = try ReadFun2(<<"#?(1 2) :hello">>, AllowOpts)
catch error:Error8 ->
Msg8 = 'clojerl.IError':message(Error8),
<<?NO_SOURCE, ":1:4: Feature should be a keyword">> = Msg8,
ok
end,
{comments, ""}.
unsupported_reader(Config) ->
ReadFun = ?config(read_fun, Config),
ct:comment("Try unsupported reader"),
ok = try ReadFun(<<"#-:something">>)
catch _:_ -> ok
end,
{comments, ""}.
erl_literals(Config) ->
ReadFun = ?config(read_fun, Config),
%% Tuple
ct:comment("Read an empty tuple"),
{} = ReadFun(<<"#erl []">>),
ct:comment("Read a tuple with a single element"),
{42} = ReadFun(<<"#erl [42]">>),
ct:comment("Read a tuple with many elements"),
HelloKeyword = clj_rt:keyword(<<"hello">>),
WorldSymbol = clj_rt:symbol(<<"world">>),
{ 42
, HelloKeywordCheck
, 2.5
, WorldSymbolCheck
} = ReadFun(<<"#erl [42, :hello, 2.5, world]">>),
?assertEquiv(HelloKeyword, HelloKeywordCheck),
?assertEquiv(WorldSymbol, WorldSymbolCheck),
ct:comment("Read a tuple whose first element is an keyword"),
T = ReadFun(<<"#erl [:random, :hello, 2.5, 'world]">>),
'erlang.Tuple' = clj_rt:type_module(T),
%% List
ct:comment("Read an empty list"),
ErlListSym = clj_rt:symbol(<<"erl-list*">>),
[ErlListSymCheck] = clj_rt:to_list(ReadFun(<<"#erl()">>)),
?assertEquiv(ErlListSym, ErlListSymCheck),
ct:comment("Read a list with a single element"),
[ErlListSymCheck, 42] = clj_rt:to_list(ReadFun(<<"#erl (42)">>)),
ct:comment("Read a tuple with many elements"),
[ ErlListSymCheck
, 42
, HelloKeywordCheckList
, 2.5
, WorldSymbolCheckList
] = clj_rt:to_list(ReadFun(<<"#erl (42, :hello, 2.5, world)">>)),
?assertEquiv(HelloKeyword, HelloKeywordCheckList),
?assertEquiv(WorldSymbol, WorldSymbolCheckList),
%% Map
ct:comment("Read an empty map"),
#{} = ReadFun(<<"#erl {}">>),
ct:comment("Read a map with a single entry"),
#{42 := 'forty-two'} = ReadFun(<<"#erl {42 :forty-two}">>),
ct:comment("Read a map with many entries"),
#{ 42 := HelloKeywordCheckMap
, 2.5 := WorldSymbolCheckMap
} = ReadFun(<<"#erl {42, :hello, 2.5, world}">>),
?assertEquiv(HelloKeyword, HelloKeywordCheckMap),
?assertEquiv(WorldSymbol, WorldSymbolCheckMap),
%% String
ct:comment("Read a string"),
[ErlListSymCheck] = clj_rt:to_list(ReadFun(<<"#erl\"\"">>)),
ct:comment("Read a non-empty string"),
[ ErlListSymCheck
| "Hello there!"
] = clj_rt:to_list(ReadFun(<<"#erl \"Hello there!\"">>)),
ct:comment("Try to read an integer"),
ok = try ReadFun(<<"#erl 1">>), error
catch _:_ -> ok
end,
ct:comment("Read an Erlang function"),
DisplayFun = ReadFun(<<"#erl erlang/display.1">>),
DisplayFunCheck = ReadFun(<<"(erl-fun* :erlang :display 1)">>),
?assertEquiv(DisplayFun, DisplayFunCheck),
{comments, ""}.
erl_binary(Config) ->
ReadFun = ?config(read_fun, Config),
ErlBinarySym = clj_rt:symbol(<<"erl-binary*">>),
EmptyBinary = clj_rt:list([ErlBinarySym]),
ct:comment("Read an empty binary"),
?assertEquiv(ReadFun(<<"#bin[]">>), EmptyBinary),
ct:comment("Read a single integer"),
SingleIntBinary = clj_rt:list([ErlBinarySym, 64]),
?assertEquiv(ReadFun(<<"#bin[64]">>), SingleIntBinary),
{comments, ""}.
erl_alias(Config) ->
ReadFun = ?config(read_fun, Config),
ErlAliasSym = clj_rt:symbol(<<"erl-alias*">>),
XSym = clj_rt:symbol(<<"x">>),
AliasList = clj_rt:list([ErlAliasSym, XSym, 1]),
ct:comment("Read the tagged literal alias"),
?assertEquiv(ReadFun(<<"#as(x 1)">>), AliasList),
{comments, ""}.
tagged(Config) ->
ReadFun = ?config(read_fun, Config),
UUIDBin = <<"de305d54-75b4-431b-adb2-eb6b9e546014">>,
ct:comment("Use bootstraped default readers implementation"),
{inst, <<"2016">>} = ReadFun(<<"#inst \"2016\"">>),
{uuid, UUIDBin} = ReadFun(<<"#uuid \"", UUIDBin/binary, "\"">>),
ct:comment("Use *default-data-reader-fn*"),
DefaultReaderFunVar =
'clojerl.Var':?CONSTRUCTOR( <<"clojure.core">>
, <<"*default-data-reader-fn*">>
),
DefaultReaderFun = fun(_, _) -> default end,
ok = 'clojerl.Var':push_bindings(#{DefaultReaderFunVar => DefaultReaderFun}),
default = ReadFun(<<"#whatever :tag">>),
default = ReadFun(<<"#we use">>),
ok = 'clojerl.Var':pop_bindings(),
ct:comment("Provide additional reader"),
DataReadersVar = 'clojerl.Var':?CONSTRUCTOR( <<"clojure.core">>
, <<"*data-readers*">>
),
BlaSymbol = clj_rt:symbol(<<"bla">>),
DataReaders = #{BlaSymbol => fun(_) -> bla end},
ok = 'clojerl.Var':push_bindings(#{DataReadersVar => DataReaders}),
bla = ReadFun(<<"#bla 1">>),
ok = 'clojerl.Var':pop_bindings(),
ct:comment("Don't provide a symbol"),
try
ReadFun(<<"#1">>),
?ERROR(<<"Expected an error">>)
catch error:Error1 ->
assert_error_message(Error1, ":1:2: Reader tag must be a symbol")
end,
ct:comment("Provide a missing reader"),
try
ReadFun(<<"#bla 1">>),
?ERROR(<<"Expected an error">>)
catch error:Error2 ->
assert_error_message(Error2, ":1:2: No reader function for tag bla")
end,
{comments, ""}.
reader_resolver(Config) ->
ReadFun = ?config(read_fun, Config),
Resolver = 'clojerl.DummyResolver':?CONSTRUCTOR(),
Bindings = #{<<"#'clojure.core/*reader-resolver*">> => Resolver},
ct:comment("Reading auto-resolved keyword"),
'clojerl.Var':push_bindings(Bindings),
'dummy/foo' = try ReadFun(<<"::foo">>)
after 'clojerl.Var':pop_bindings()
end,
ct:comment("Reading auto-resolved keyword with namespace"),
%% Without resolver
try ReadFun(<<"::foo/bar">>)
catch error:Error1 ->
assert_error_message(Error1, "Invalid token")
end,
%% With resolver
'clojerl.Var':push_bindings(Bindings),
'foo/bar' = try ReadFun(<<"::foo/bar">>)
after 'clojerl.Var':pop_bindings()
end,
ct:comment("Reading constructor type symbol in syntax quote"),
QuoteSym = clj_rt:symbol(<<"quote">>),
QuoteFun = fun(X) -> clj_rt:list([QuoteSym, X]) end,
StringTypeSym = clj_rt:symbol(<<"clojerl.String.">>),
QuotedStringTypeSym = QuoteFun(StringTypeSym),
'clojerl.Var':push_bindings(Bindings),
QuotedStringTypeSym = try ReadFun(<<"`clojerl.String.">>)
after 'clojerl.Var':pop_bindings()
end,
ct:comment("Syntax quote unqualified symbol"),
FooSym = clj_rt:symbol(<<"foo">>),
QuoteFooSym = QuoteFun(FooSym),
'clojerl.Var':push_bindings(Bindings),
QuoteFooSym = try ReadFun(<<"`foo">>)
after 'clojerl.Var':pop_bindings()
end,
ct:comment("Syntax quote qualified symbol"),
FooBarSym = clj_rt:symbol(<<"foo/bar">>),
QuoteFooBarSym = QuoteFun(FooBarSym),
'clojerl.Var':push_bindings(Bindings),
QuoteFooBarSym = try ReadFun(<<"`foo/bar">>)
after 'clojerl.Var':pop_bindings()
end,
ct:comment("Namespaced map auto-resolved"),
NamespacedMap1 = #{'dummy/a' => 1},
'clojerl.Var':push_bindings(Bindings),
NamespacedMap1Check = try ReadFun(<<"#::{:a 1}">>)
after 'clojerl.Var':pop_bindings()
end,
?assertEquiv(NamespacedMap1, NamespacedMap1Check),
ct:comment("Namespaced map auto-resolved"),
NamespacedMap2 = #{'foo/a' => 1},
'clojerl.Var':push_bindings(Bindings),
NamespacedMap2Check = try ReadFun(<<"#::foo{:a 1}">>)
after 'clojerl.Var':pop_bindings()
end,
?assertEquiv(NamespacedMap2, NamespacedMap2Check),
{comments, ""}.
namespaced_map(Config) ->
ReadFun = ?config(read_fun, Config),
ct:comment("Simple keyword"),
Map1 = #{'foo/a' => 1},
?assertEquiv(Map1, ReadFun(<<"#:foo{:a 1}">>)),
ct:comment("Auto-resolved map"),
Map2 = #{'clojure.core/a' => 1},
?assertEquiv(Map2, ReadFun(<<"#::{:a 1}">>)),
{comments, ""}.
%%------------------------------------------------------------------------------
%% Helper functions
%%------------------------------------------------------------------------------
-spec assert_error_message('clojerl.IError':type(), binary()) -> ok.
assert_error_message(Error, MessageRegex) ->
Msg = 'clojerl.IError':message(Error),
{match, _} = re:run(Msg, MessageRegex).
-spec read_io(binary()) -> any().
read_io(Src) ->
read_io(Src, #{}).
-spec read_io(binary(), clj_reader:opts()) -> any().
read_io(Src, Opts) ->
Reader = 'erlang.io.StringReader':?CONSTRUCTOR(Src),
PushbackReader = 'erlang.io.PushbackReader':?CONSTRUCTOR(Reader),
clj_reader:read(<<>>, Opts#{?OPT_IO_READER => PushbackReader}).
-spec read(binary()) -> any().
read(Src) ->
clj_reader:read(Src).
-spec read(binary(), clj_reader:opts()) -> any().
read(Src, Opts) ->
clj_reader:read(Src, Opts).
-spec read_all_io(binary()) -> any().
read_all_io(Src) ->
Reader = 'erlang.io.StringReader':?CONSTRUCTOR(Src),
PushbackReader = 'erlang.io.PushbackReader':?CONSTRUCTOR(Reader),
read_all(<<>>, #{?OPT_IO_READER => PushbackReader}).
%% @doc Read all forms.
-spec read_all(binary()) -> [any()].
read_all(Src) ->
read_all(Src, #{eof => ok}).
-spec read_all(binary(), clj_reader:opts()) -> [any()].
read_all(Src, Opts) ->
Fun = fun(Form, Acc) -> [Form | Acc] end,
lists:reverse(clj_reader:read_fold(Fun, Src, Opts, [])).
| null | https://raw.githubusercontent.com/clojerl/clojerl/2eae5c57ad3339336f7e90b4d822ec07388e166a/test/clj_reader_SUITE.erl | erlang | ------------------------------------------------------------------------------
Test Cases
------------------------------------------------------------------------------
Compare metadata after removing the location information.
Tuple
List
Map
String
Without resolver
With resolver
------------------------------------------------------------------------------
Helper functions
------------------------------------------------------------------------------
@doc Read all forms. | -module(clj_reader_SUITE).
-include("clojerl.hrl").
-include("clojerl_int.hrl").
-include("clj_test_utils.hrl").
-include_lib("common_test/include/ct.hrl").
-export([ all/0
, groups/0
, init_per_group/2
, end_per_group/2
, init_per_suite/1
, end_per_suite/1
]).
-export([ eof/1
, number/1
, string/1
, keyword/1
, symbol/1
, comment/1
, quote/1
, deref/1
, meta/1
, syntax_quote/1
, unquote/1
, list/1
, vector/1
, map/1
, set/1
, unmatched_delim/1
, char/1
, arg/1
, fn/1
, eval/1
, var/1
, regex/1
, unreadable_form/1
, discard/1
, 'cond'/1
, unsupported_reader/1
, erl_literals/1
, erl_binary/1
, erl_alias/1
, tagged/1
, reader_resolver/1
, namespaced_map/1
]).
-spec all() -> [atom()].
all() -> [{group, read}, {group, read_io}].
-spec groups() -> [atom()].
groups() ->
[ {read, [], clj_test_utils:all(?MODULE)}
, {read_io, [], clj_test_utils:all(?MODULE)}
].
-spec init_per_group(atom(), config()) -> config().
init_per_group(read, Config) ->
[ {read_fun, fun read/1}
, {read_fun2, fun read/2}
, {read_all_fun, fun read_all/1}
| Config
];
init_per_group(read_io, Config) ->
[ {read_fun, fun read_io/1}
, {read_fun2, fun read_io/2}
, {read_all_fun, fun read_all_io/1}
| Config
].
-spec end_per_group(atom(), config()) -> ok.
end_per_group(_, _Config) -> ok.
-spec init_per_suite(config()) -> config().
init_per_suite(Config) -> clj_test_utils:init_per_suite(Config).
-spec end_per_suite(config()) -> config().
end_per_suite(Config) -> Config.
eof(Config) ->
ReadFun = ?config(read_fun, Config),
ct:comment("Read empty binary"),
ok = try ReadFun(<<"">>)
catch _:_ -> ok end,
ok = try ReadFun(<<" , , , , ">>)
catch _:_ -> ok end,
ok = try ReadFun(<<", , , \t \n ,, ">>)
catch _:_ -> ok end,
{comments, ""}.
number(Config) ->
ReadFun = ?config(read_fun, Config),
ReadAllFun = ?config(read_all_fun, Config),
0 = ReadFun(<<"0">>),
0.0 = ReadFun(<<"0.0">>),
1 = ReadFun(<<"1">>),
1 = ReadFun(<<"+1">>),
-1 = ReadFun(<<"-1">>),
1.0 = ReadFun(<<"1.0">>),
1.0 = ReadFun(<<"10E-1">>),
1.0 = ReadFun(<<"10.0e-1">>),
1.0 = ReadFun(<<"10.e-1">>),
1.0 = ReadFun(<<"10e-1">>),
1.0 = ReadFun(<<"+10e-1">>),
-1.0 = ReadFun(<<"-10e-1">>),
42 = ReadFun(<<"0x2A">>),
42 = ReadFun(<<"052">>),
42 = ReadFun(<<"36r16">>),
42 = ReadFun(<<"36R16">>),
ok = try ReadFun(<<"1/2">>), error
catch _:_ -> ok
end,
ok = try ReadFun(<<"12A">>), error
catch _:_ -> ok
end,
[0, 1, 2.0, 3.0e-10] = ReadAllFun(<<"0N 1 2.0 3e-10">>),
{comments, ""}.
string(Config) ->
ReadFun = ?config(read_fun, Config),
<<"">> = ReadFun(<<"\"\"">>),
<<"hello">> = ReadFun(<<"\"hello\"">>),
<<"hello \t world!">> = ReadFun(<<"\"hello \\t world!\"">>),
<<"hello \n world!">> = ReadFun(<<"\"hello \\n world!\"">>),
<<"hello \r world!">> = ReadFun(<<"\"hello \\r world!\"">>),
<<"hello \" world!">> = ReadFun(<<"\"hello \\\" world!\"">>),
<<"hello \f world!">> = ReadFun(<<"\"hello \\f world!\"">>),
<<"hello \b world!">> = ReadFun(<<"\"hello \\b world!\"">>),
<<"hello \\ world!">> = ReadFun(<<"\"hello \\\\ world!\"">>),
<<"hello © world!"/utf8>> =
ReadFun(<<"\"hello \\u00A9 world!\"">>),
ok = try ReadFun(<<"\"hello \\u00A world!\"">>)
catch _:_ -> ok
end,
ok = try ReadFun(<<"\"hello \\u00Z world!\"">>)
catch _:_ -> ok
end,
<<"hello © world!"/utf8>> =
ReadFun(<<"\"hello \\251 world!\"">>),
ct:comment("EOF"),
ok = try ReadFun(<<"\"hello world!">>)
catch _:_ -> ok
end,
ct:comment("Octal not in range"),
ok = try ReadFun(<<"\"hello \\400 world!">>)
catch _:_ -> ok
end,
ct:comment("Number not in base"),
ok = try ReadFun(<<"\"hello \\u000Z world!">>)
catch _:_ -> ok
end,
ct:comment("Unsupported escaped char"),
ok = try ReadFun(<<"\"hello \\z world!">>)
catch _:_ -> ok
end,
{comments, ""}.
keyword(Config) ->
ReadFun = ?config(read_fun, Config),
FooSym = clj_rt:symbol(<<"foo">>),
FooNs = 'clojerl.Namespace':find_or_create(FooSym),
SomeSym = clj_rt:symbol(<<"some">>),
SomeNs = 'clojerl.Namespace':find_or_create(SomeSym),
Keyword1 = clj_rt:keyword(<<"hello-world">>),
Keyword1 = ReadFun(<<":hello-world">>),
Keyword2 = clj_rt:keyword(<<"some">>, <<"hello-world">>),
Keyword2 = ReadFun(<<"::hello-world">>),
Keyword3 = clj_rt:keyword(<<"another-ns">>, <<"hello-world">>),
Keyword3 = ReadFun(<<":another-ns/hello-world">>),
Keyword4 = clj_rt:keyword(<<"/">>),
Keyword4 = ReadFun(<<":/">>),
Keyword5 = clj_rt:keyword(<<"some">>, <<"/">>),
Keyword5 = ReadFun(<<":some//">>),
FSym = clj_rt:symbol(<<"f">>),
SomeNs = 'clojerl.Namespace':add_alias(SomeNs, FSym, FooNs),
Keyword6 = clj_rt:keyword(<<"foo">>, <<"hello-world">>),
Keyword6 = ReadFun(<<"::f/hello-world">>),
Keyword7 = clj_rt:keyword(<<"42hello-world">>),
Keyword7 = ReadFun(<<":42hello-world">>),
ct:comment("Error: triple colon :::"),
ok = try ReadFun(<<":::hello-world">>)
catch _:_ -> ok
end,
ct:comment("Error: empty name after namespace"),
ok = try ReadFun(<<":some-ns/">>)
catch _:_ -> ok
end,
ct:comment("Error: colon as last char"),
ok = try ReadFun(<<":hello-world:">>)
catch _:_ -> ok
end,
ct:comment("Error: single colon"),
ok = try ReadFun(<<":">>)
catch _:_ -> ok
end,
{comments, ""}.
symbol(Config) ->
ReadFun = ?config(read_fun, Config),
Symbol1 = clj_rt:symbol(<<"hello-world">>),
?assertEquiv(ReadFun(<<"hello-world">>), Symbol1),
Symbol2 = clj_rt:symbol(<<"some-ns">>, <<"hello-world">>),
?assertEquiv(ReadFun(<<"some-ns/hello-world">>), Symbol2),
Symbol3 = clj_rt:symbol(<<"another-ns">>, <<"hello-world">>),
?assertEquiv( ReadFun(<<"another-ns/hello-world">>)
, Symbol3
),
Symbol4 = clj_rt:symbol(<<"some-ns">>, <<"/">>),
?assertEquiv(ReadFun(<<"some-ns//">>), Symbol4),
ct:comment("nil, true & false"),
?NIL = ReadFun(<<"nil">>),
true = ReadFun(<<"true">>),
false = ReadFun(<<"false">>),
ct:comment("Error: empty name after namespace"),
ok = try ReadFun(<<"some-ns/">>)
catch _:_ -> ok
end,
ct:comment("Error: colon as last char"),
ok = try ReadFun(<<"hello-world:">>)
catch _:_ -> ok
end,
ct:comment("Error: numeric first char in name"),
ok = try ReadFun(<<"42hello-world">>)
catch _:_ -> ok
end,
{comments, ""}.
comment(Config) ->
ReadAllFun = ?config(read_all_fun, Config),
BlaKeyword = clj_rt:keyword(<<"bla">>),
ct:comment("Single semi-colon"),
[1, BlaKeyword] = ReadAllFun(<<"1 ; comment\n :bla ">>),
ct:comment("Two semi-colon"),
[1, BlaKeyword] = ReadAllFun(<<"1 ;; comment\n :bla ">>),
ct:comment("A bunch of semi-colons"),
[1, BlaKeyword] = ReadAllFun(<<"1 ;;;; comment\n :bla ">>),
ct:comment("Comment reader"),
[1, BlaKeyword] = ReadAllFun(<<"1 #! comment\n :bla ">>),
ct:comment("Comment after meta"),
[BarSym1] = ReadAllFun(<<"^:foo ;; comment\n bar">>),
<<"bar">> = clj_rt:name(BarSym1),
true = clj_rt:get(clj_rt:meta(BarSym1), foo),
[_, BarSym2] = ReadAllFun(<<"hello ^:foo ;; comment\n bar">>),
<<"bar">> = clj_rt:name(BarSym2),
true = clj_rt:get(clj_rt:meta(BarSym2), foo),
{comments, ""}.
quote(Config) ->
ReadFun = ?config(read_fun, Config),
QuoteSymbol = clj_rt:symbol(<<"quote">>),
ListSymbol = clj_rt:symbol(<<"list">>),
ct:comment("Quote number"),
ListQuote1 = clj_rt:list([QuoteSymbol, 1]),
ListQuote1 = ReadFun(<<"'1">>),
ct:comment("Quote symbol"),
ListQuote2 = clj_rt:list([QuoteSymbol, ListSymbol]),
?assertEquiv(ReadFun(<<"'list">>), ListQuote2),
ct:comment("Quote space symbol"),
?assertEquiv(ReadFun(<<"' list">>), ListQuote2),
ct:comment("Error: only provide ' "),
ok = try ReadFun(<<"'">>)
catch _:_ -> ok
end,
{comments, ""}.
deref(Config) ->
ReadFun = ?config(read_fun, Config),
ReadAllFun = ?config(read_all_fun, Config),
DerefSymbol = clj_rt:symbol(<<"clojure.core">>, <<"deref">>),
ListSymbol = clj_rt:symbol(<<"list">>),
ct:comment("Deref number :P"),
ListDeref1 = clj_rt:list([DerefSymbol, 1]),
ListDeref1= ReadFun(<<"@1">>),
ct:comment("Deref symbol :P"),
ListDeref2 = clj_rt:list([DerefSymbol, ListSymbol]),
?assertEquiv(ReadFun(<<"@list">>), ListDeref2),
ct:comment("Deref symbol :P and read other stuff"),
[ListDeref3, 42.0] = ReadAllFun(<<"@list 42.0">>),
?assertEquiv(ListDeref3, ListDeref2),
ct:comment("Error: only provide @ "),
ok = try ReadFun(<<"@">>)
catch _:_ -> ok
end,
{comments, ""}.
meta(Config) ->
ReadFun = ?config(read_fun, Config),
MetadataKw = ReadFun(<<"{:private true}">>),
MetadataSym = ReadFun(<<"{:tag private}">>),
ct:comment("Keyword doesn't support metadata"),
ok = try ReadFun(<<"^:private :hello">>), error
catch _:_ -> ok
end,
AssertMetaEquiv =
fun(Value, ExpectedMeta) ->
Meta = clj_rt:meta(Value),
MetaNoLocation = clj_reader:remove_location(Meta),
?assertEquiv(MetaNoLocation, ExpectedMeta)
end,
ct:comment("Keyword meta to symbol"),
SymbolWithMetaKw = ReadFun(<<"^:private hello">>),
AssertMetaEquiv(SymbolWithMetaKw, MetadataKw),
ct:comment("Symbol meta to symbol"),
SymbolWithMetaSym = ReadFun(<<"^private hello">>),
AssertMetaEquiv(SymbolWithMetaSym, MetadataSym),
ct:comment("Map meta to symbol"),
MapWithMetaKw = ReadFun(<<"^:private {}">>),
AssertMetaEquiv(MapWithMetaKw, MetadataKw),
ct:comment("Map meta to symbol"),
MapWithMetaSym = ReadFun(<<"^private {}">>),
AssertMetaEquiv(MapWithMetaSym, MetadataSym),
ct:comment("List meta to symbol"),
ListWithMetaKw = ReadFun(<<"^:private ()">>),
AssertMetaEquiv(ListWithMetaKw, MetadataKw),
ct:comment("List meta to symbol"),
ListWithMetaSym = ReadFun(<<"^private ()">>),
AssertMetaEquiv(ListWithMetaSym, MetadataSym),
ct:comment("Vector meta to symbol"),
VectorWithMetaKw = ReadFun(<<"^:private []">>),
AssertMetaEquiv(VectorWithMetaKw, MetadataKw),
ct:comment("Vector meta to symbol"),
VectorWithMetaSym = ReadFun(<<"^private []">>),
AssertMetaEquiv(VectorWithMetaSym, MetadataSym),
ct:comment("Set meta to symbol"),
SetWithMetaKw = ReadFun(<<"^:private #{}">>),
AssertMetaEquiv(SetWithMetaKw, MetadataKw),
ct:comment("Set meta to symbol"),
SetWithMetaSym = ReadFun(<<"^private #{}">>),
AssertMetaEquiv(SetWithMetaSym, MetadataSym),
ct:comment("Meta number"),
ok = try ReadFun(<<"^1 1">>)
catch _:_ -> ok
end,
ct:comment("Reader meta number"),
ok = try ReadFun(<<"#^1 1">>)
catch _:_ -> ok
end,
ct:comment("Meta without form"),
ok = try ReadFun(<<"^:private">>)
catch _:_ -> ok
end,
{comments, ""}.
syntax_quote(Config) ->
ReadFun = ?config(read_fun, Config),
QuoteSym = clj_rt:symbol(<<"quote">>),
QuoteFun = fun(X) -> clj_rt:list([QuoteSym, X]) end,
ct:comment("Read special form"),
DoSym = clj_rt:symbol(<<"do">>),
QuoteDoList = QuoteFun(DoSym),
DoSyntaxQuote = ReadFun(<<"`do">>),
?assertEquiv(DoSyntaxQuote, QuoteDoList),
ct:comment("Form with meta info other than location keeps meta"),
WithMetaSym = clj_rt:symbol(<<"clojure.core">>, <<"with-meta">>),
DoWithMetaSyntaxQuote = ReadFun(<<"`^:foo do">>),
?assertEquiv(clj_rt:first(DoWithMetaSyntaxQuote), WithMetaSym),
?assertEquiv(clj_rt:second(DoWithMetaSyntaxQuote), QuoteDoList),
DefSym = clj_rt:symbol(<<"def">>),
QuoteDefList = clj_rt:list([QuoteSym, DefSym]),
DefSyntaxQuote = ReadFun(<<"`def">>),
?assertEquiv(DefSyntaxQuote, QuoteDefList),
ct:comment("Read literals"),
1 = ReadFun(<<"`1">>),
42.0 = ReadFun(<<"`42.0">>),
<<"something!">> = ReadFun(<<"`\"something!\"">>),
ct:comment("Keywords can't have metadata"),
HelloKeyword = clj_rt:keyword(<<"hello">>),
HelloKeyword = ReadFun(<<"`:hello">>),
ct:comment("Read values that can have metadata"),
ct:comment("Read unqualified symbol"),
UserHelloSym = clj_rt:symbol(<<"clojure.core">>, <<"hello">>),
HelloSyntaxQuote = ReadFun(<<"`hello">>),
?assertEquiv(HelloSyntaxQuote, QuoteFun(UserHelloSym)),
ct:comment("Read qualified symbol"),
SomeNsHelloSym = clj_rt:symbol(<<"some-ns">>, <<"hello">>),
SomeNsHelloSyntaxQuote = ReadFun(<<"`some-ns/hello">>),
?assertEquiv( SomeNsHelloSyntaxQuote, QuoteFun(SomeNsHelloSym)),
ct:comment("Read qualified symbol mapping to existing var"),
ResolverSym = clj_rt:symbol(<<"clojure.core">>, <<"*reader-resolver*">>),
ResolverSymSyntaxQuote = ReadFun(<<"`clojure.core/*reader-resolver*">>),
?assertEquiv(ResolverSymSyntaxQuote, QuoteFun(ResolverSym)),
ct:comment("Read constructor type symbol"),
ConstructorTypeSym = clj_rt:symbol(<<"clojerl.String.">>),
ConstructorTypeSyntaxQuote = ReadFun(<<"`clojerl.String.">>),
?assertEquiv(ConstructorTypeSyntaxQuote, QuoteFun(ConstructorTypeSym)),
ct:comment("Read type function name symbol"),
FunctionNameSym = clj_rt:symbol(<<".str">>),
FunctionNameSyntaxQuote = ReadFun(<<"`.str">>),
?assertEquiv(FunctionNameSyntaxQuote, QuoteFun(FunctionNameSym)),
ct:comment("Read auto-gen symbol"),
ListGenSym = ReadFun(<<"`hello#">>),
QuotedGenSym = clj_rt:second(ListGenSym),
GenSymName = clj_rt:name(QuotedGenSym),
{match, _} = re:run(GenSymName, "hello__\\d+__auto__"),
ct:comment("Read auto-gen symbol, "
"check generated symbols have the same name"),
ListApply = ReadFun(<<"`(hello# hello# world#)">>),
ListConcat = clj_rt:third(ListApply),
ListSecond = clj_rt:second(ListConcat),
ListThird = clj_rt:third(ListConcat),
?assertEquiv(clj_rt:second(ListSecond), clj_rt:second(ListThird)),
ct:comment("Read unquote"),
HelloSym = clj_rt:symbol(<<"hello">>),
ListWithMetaHelloSym = ReadFun(<<"`~hello">>),
?assertEquiv(ListWithMetaHelloSym, HelloSym),
ct:comment("Use unquote splice not in list"),
ok = try ReadFun(<<"`~@(hello)">>)
catch _:_ -> ok end,
ct:comment("Read list and empty list"),
ListHello = ReadFun(<<"`(hello :world)">>),
ListHelloCheck = ReadFun(<<"(clojure.core/concat"
" (clojure.core/list 'clojure.core/hello)"
" (clojure.core/list :world))">>),
?assertEquiv( clj_rt:third(ListHello), ListHelloCheck),
EmptyList = ReadFun(<<"`()">>),
EmptyListCheck = ReadFun(<<"(clojure.core/list)">>),
?assertEquiv(clj_rt:third(EmptyList), EmptyListCheck),
ct:comment("Read map"),
Map = ReadFun(<<"`{hello :world}">>),
MapCheck = ReadFun(<<"(clojure.core/apply"
" clojure.core/hash-map"
" (clojure.core/concat"
" (clojure.core/list 'clojure.core/hello)"
" (clojure.core/list :world)))">>),
?assertEquiv(Map, MapCheck),
ct:comment("Read vector"),
Vector = ReadFun(<<"`[hello :world]">>),
VectorCheck = ReadFun(<<"(clojure.core/apply"
" clojure.core/vector"
" (clojure.core/concat"
" (clojure.core/list 'clojure.core/hello)"
" (clojure.core/list :world)))">>),
?assertEquiv(Vector, VectorCheck),
ct:comment("Read set"),
Set = ReadFun(<<"`#{hello :world}">>),
SetCheck = ReadFun(<<"(clojure.core/apply"
" clojure.core/hash-set"
" (clojure.core/concat"
" (clojure.core/list 'clojure.core/hello)"
" (clojure.core/list :world)))">>),
?assertEquiv(Set, SetCheck),
ct:comment("Read unquote-splice inside list"),
HelloWorldSup = ReadFun(<<"`(~@(hello world) :sup?)">>),
HelloWorldSupCheck = ReadFun(<<"(clojure.core/concat"
" (hello world)"
" (clojure.core/list :sup?))">>),
?assertEquiv(clj_rt:third(HelloWorldSup), HelloWorldSupCheck),
ct:comment("Read unquote inside list"),
ListHelloWorld = ReadFun(<<"`(~hello :world)">>),
ListHelloWorldCheck = ReadFun(<<"(clojure.core/concat"
" (clojure.core/list hello)"
" (clojure.core/list :world))">>),
?assertEquiv(clj_rt:third(ListHelloWorld), ListHelloWorldCheck),
ct:comment("Syntax quote a symbol with dots"),
HelloWorldWithDot = ReadFun(<<"`hello.world">>),
HelloWorldWithDotCheck = ReadFun(<<"(quote hello.world)">>),
?assertEquiv(HelloWorldWithDot, HelloWorldWithDotCheck),
ct:comment("Generated symbol in nested structure keeps meta"),
SymbolWithMeta = ReadFun(<<"`(^foo bar)">>),
SymbolWithMetaCheck =
ReadFun(<<"(clojure.core/concat"
" (clojure.core/list"
" (clojure.core/with-meta"
" (quote clojure.core/bar)"
" (clojure.core/apply clojure.core/hash-map"
" (clojure.core/concat"
" (clojure.core/list :tag)"
" (clojure.core/list (quote clojure.core/foo)))))))">>),
?assertEquiv(clj_rt:third(SymbolWithMeta), SymbolWithMetaCheck),
ct:comment("Read Erlang tuple"),
ClojureCoreTuple = ReadFun(<<"clojure.core/tuple">>),
ErlTupleHello = ReadFun(<<"`#erl[hello :world]">>),
ErlTupleHelloCheck = ReadFun(<<"(clojure.core/concat"
" (clojure.core/list 'clojure.core/hello)"
" (clojure.core/list :world))">>),
?assertEquiv(clj_rt:second(ErlTupleHello), ClojureCoreTuple),
?assertEquiv(clj_rt:third(ErlTupleHello), ErlTupleHelloCheck),
ct:comment("Read Erlang map"),
ClojureCoreErlMap = ReadFun(<<"clojure.core/erl-map">>),
ErlMapHello = ReadFun(<<"`#erl{hello :world}">>),
ErlMapHelloCheck = ReadFun(<<"(clojure.core/concat"
" (clojure.core/list 'clojure.core/hello)"
" (clojure.core/list :world))">>),
?assertEquiv(clj_rt:second(ErlMapHello), ClojureCoreErlMap),
?assertEquiv(clj_rt:third(ErlMapHello), ErlMapHelloCheck),
{comments, ""}.
unquote(Config) ->
ReadFun = ?config(read_fun, Config),
UnquoteSymbol = clj_rt:symbol(<<"clojure.core">>, <<"unquote">>),
UnquoteSplicingSymbol = clj_rt:symbol(<<"clojure.core">>,
<<"unquote-splicing">>),
HelloWorldSymbol = clj_rt:symbol(<<"hello-world">>),
ct:comment("Unquote"),
ListUnquote = clj_rt:list([UnquoteSymbol, HelloWorldSymbol]),
?assertEquiv(ReadFun(<<"~hello-world">>), ListUnquote),
ct:comment("Unquote splicing"),
ListUnquoteSplicing = clj_rt:list([UnquoteSplicingSymbol,
HelloWorldSymbol]),
?assertEquiv(ReadFun(<<"~@hello-world">>), ListUnquoteSplicing),
ct:comment("Unquote nothing"),
ok = try ReadFun(<<"~">>)
catch _:_ -> ok
end,
{comments, ""}.
list(Config) ->
ReadFun = ?config(read_fun, Config),
HelloWorldKeyword = clj_rt:keyword(<<"hello-world">>),
HelloWorldSymbol = clj_rt:symbol(<<"hello-world">>),
ct:comment("Empty List"),
EmptyList = clj_rt:list([]),
?assertEquiv(ReadFun(<<"()">>), EmptyList),
ct:comment("List"),
List = clj_rt:list([HelloWorldKeyword, HelloWorldSymbol]),
?assertEquiv( ReadFun(<<"(:hello-world hello-world)">>)
, List
),
ct:comment("List & space"),
?assertEquiv( ReadFun(<<"(:hello-world hello-world )">>)
, List
),
ct:comment("List without closing paren"),
ok = try ReadFun(<<"(1 42.0">>)
catch _:_ -> ok
end,
{comments, ""}.
vector(Config) ->
ReadFun = ?config(read_fun, Config),
HelloWorldKeyword = clj_rt:keyword(<<"hello-world">>),
HelloWorldSymbol = clj_rt:symbol(<<"hello-world">>),
ct:comment("Vector"),
Vector = 'clojerl.Vector':?CONSTRUCTOR([HelloWorldKeyword, HelloWorldSymbol]),
?assertEquiv( ReadFun(<<"[:hello-world hello-world]">>)
, Vector
),
ct:comment("Vector without closing bracket"),
ok = try ReadFun(<<"[1 42.0">>)
catch _:_ -> ok
end,
{comments, ""}.
map(Config) ->
ReadFun = ?config(read_fun, Config),
HelloWorldKeyword = clj_rt:keyword(<<"hello-world">>),
HelloWorldSymbol = clj_rt:symbol(<<"hello-world">>),
ct:comment("Map"),
Map = 'clojerl.Map':?CONSTRUCTOR([ HelloWorldKeyword
, HelloWorldSymbol
, HelloWorldSymbol
, HelloWorldKeyword
]
),
MapResult = ReadFun(<<"{:hello-world hello-world,"
" hello-world :hello-world}">>),
?assertEquiv(Map, MapResult),
ct:comment("Map without closing braces"),
ok = try ReadFun(<<"{1 42.0">>)
catch _:_ -> ok
end,
ct:comment("Literal map with odd number of expressions"),
ok = try ReadFun(<<"{1 42.0 :a}">>)
catch _:_ -> ok
end,
{comments, ""}.
set(Config) ->
ReadFun = ?config(read_fun, Config),
HelloWorldKeyword = clj_rt:keyword(<<"hello-world">>),
HelloWorldSymbol = clj_rt:symbol(<<"hello-world">>),
ct:comment("Set"),
Set = 'clojerl.Set':?CONSTRUCTOR([HelloWorldKeyword, HelloWorldSymbol]),
SetResult = ReadFun(<<"#{:hello-world hello-world}">>),
?assertEquiv(Set, SetResult),
ct:comment("Set without closing braces"),
ok = try ReadFun(<<"#{1 42.0">>)
catch _:_ -> ok
end,
{comments, ""}.
unmatched_delim(Config) ->
ReadAllFun = ?config(read_all_fun, Config),
ct:comment("Single closing paren"),
ok = try ReadAllFun(<<"{1 42.0} )">>)
catch _:_ -> ok
end,
ct:comment("Single closing bracket"),
ok = try ReadAllFun(<<"{1 42.0} ]">>)
catch _:_ -> ok
end,
ct:comment("Single closing braces"),
ok = try ReadAllFun(<<"{1 42.0} } ">>)
catch _:_ -> ok
end,
{comments, ""}.
char(Config) ->
ReadFun = ?config(read_fun, Config),
ReadAllFun = ?config(read_all_fun, Config),
ct:comment("Read single char"),
<<"a">> = ReadFun(<<"\\a">>),
<<"\n">> = ReadFun(<<"\\newline">>),
<<" ">> = ReadFun(<<"\\space">>),
<<"\t">> = ReadFun(<<"\\tab">>),
<<"\b">> = ReadFun(<<"\\backspace">>),
<<"\f">> = ReadFun(<<"\\formfeed">>),
<<"\r">> = ReadFun(<<"\\return">>),
<<"©"/utf8>> = ReadFun(<<"\\u00A9">>),
<<"ß"/utf8>> = ReadFun(<<"\\o337">>),
<<" "/utf8>> = ReadFun(<<"\\ ">>),
<<"\""/utf8>> = ReadFun(<<"\\\"">>),
ct:comment("Char EOF"),
ok = try ReadAllFun(<<"12 \\">>)
catch _:_ -> ok
end,
ct:comment("Octal char wrong length"),
ok = try ReadAllFun(<<"12 \\o0337">>)
catch _:_ -> ok
end,
ct:comment("Octal char wrong range"),
ok = try ReadAllFun(<<"12 \\o477">>)
catch _:_ -> ok
end,
ct:comment("Unsupported char"),
ok = try ReadAllFun(<<"42.0 \\ab">>)
catch _:_ -> ok
end,
{comments, ""}.
fn(Config) ->
ReadFun = ?config(read_fun, Config),
FnSymbol = clj_rt:symbol(<<"fn*">>),
EmptyVector = clj_rt:vector([]),
EmptyList = clj_rt:list([]),
ct:comment("Read empty anonymous fn"),
EmptyFn = ReadFun(<<"#()">>),
FnSymbol = clj_rt:first(EmptyFn),
EmptyVector = clj_rt:second(EmptyFn),
?assertEquiv(clj_rt:third(EmptyFn), EmptyList),
ct:comment("Read anonymous fn with %"),
OneArgFn = ReadFun(<<"#(%)">>),
FnSymbol = clj_rt:first(OneArgFn),
ArgVector1 = clj_rt:second(OneArgFn),
1 = clj_rt:count(ArgVector1),
BodyList1 = clj_rt:third(OneArgFn),
1 = clj_rt:count(BodyList1),
true = clj_rt:first(ArgVector1) == clj_rt:first(ArgVector1),
ct:comment("Read anonymous fn with %4 and %42"),
FortyTwoArgFn = ReadFun(<<"#(do %42 %4)">>),
FnSymbol = clj_rt:first(FortyTwoArgFn),
ArgVector42 = clj_rt:second(FortyTwoArgFn),
42 = clj_rt:count(ArgVector42),
BodyList42 = clj_rt:third(FortyTwoArgFn),
3 = clj_rt:count(BodyList42),
Arg42Sym = clj_rt:second(BodyList42),
{match, _} = re:run(clj_rt:name(Arg42Sym), "p42__\\d+#"),
ct:comment("Read anonymous fn with %3 and %&"),
RestArgFn = ReadFun(<<"#(do %& %3)">>),
FnSymbol = clj_rt:first(RestArgFn),
ArgVectorRest = clj_rt:second(RestArgFn),
1 - 3 , & and rest
BodyListRest = clj_rt:third(RestArgFn),
3 = clj_rt:count(BodyListRest),
ArgRestSym = clj_rt:second(BodyListRest),
{match, _} = re:run(clj_rt:name(ArgRestSym), "rest__\\d+#"),
ct:comment("Nested #()"),
ok = try ReadFun(<<"#(do #(%))">>)
catch error:Error1 ->
Msg1 = 'clojerl.IError':message(Error1),
<<?NO_SOURCE, ":1:7: Nested #()s are not allowed">> = Msg1,
ok
end,
{comments, ""}.
arg(Config) ->
ReadFun = ?config(read_fun, Config),
ReadAllFun = ?config(read_all_fun, Config),
ct:comment("Read % as a symbol"),
ArgSymbol = clj_rt:symbol(<<"%">>),
?assertEquiv(ReadFun(<<"%">>), ArgSymbol),
ct:comment("Read %1 as a symbol"),
ArgOneSymbol = clj_rt:symbol(<<"%1">>),
?assertEquiv(ReadFun(<<"%1">>), ArgOneSymbol),
erlang:put(arg_env, #{}),
ct:comment("Read % as an argument"),
ArgGenSymbol = ReadFun(<<"%">>),
ArgGenName = clj_rt:name(ArgGenSymbol),
{match, _} = re:run(ArgGenName, "p1__\\d+#"),
ArgGenSymbol2 = ReadFun(<<"% ">>),
ArgGenName2 = clj_rt:name(ArgGenSymbol2),
{match, _} = re:run(ArgGenName2, "p1__\\d+#"),
ct:comment("Read %1 as an argument"),
ArgOneGenSymbol = ReadFun(<<"%1">>),
ArgOneGenName = clj_rt:name(ArgOneGenSymbol),
{match, _} = re:run(ArgOneGenName, "p1__\\d+#"),
ct:comment("Read %42 as an argument"),
ArgFortyTwoGenSymbol = ReadFun(<<"%42">>),
ArgFortyTwoGenName = clj_rt:name(ArgFortyTwoGenSymbol),
{match, _} = re:run(ArgFortyTwoGenName, "p42__\\d+#"),
ct:comment("Read %& as an argument"),
[ArgRestGenSymbol] = ReadAllFun(<<"%&">>),
ArgRestGenName = clj_rt:name(ArgRestGenSymbol),
{match, _} = re:run(ArgRestGenName, "rest__\\d+#"),
ct:comment("Invalid char after %"),
ok = try ReadFun(<<"%a">>)
catch error:Error1 ->
Msg1 = 'clojerl.IError':message(Error1),
<<?NO_SOURCE, ":1:2: Arg literal must be %, %& or %integer">> = Msg1,
ok
end,
erlang:erase(arg_env),
{comments, ""}.
eval(Config) ->
ReadFun = ?config(read_fun, Config),
ct:comment("Read eval 1"),
1 = ReadFun(<<"#=1">>),
ct:comment("Read eval (do 1)"),
1 = ReadFun(<<"#=(do 1)">>),
ct:comment("Read eval (str 1)"),
<<"1">> = ReadFun(<<"#=(clj_rt/str 1)">>),
{comments, ""}.
var(Config) ->
ReadFun = ?config(read_fun, Config),
VarSymbol = clj_rt:symbol(<<"var">>),
ListSymbol = clj_rt:symbol(<<"list">>),
ct:comment(""),
List = clj_rt:list([VarSymbol, ListSymbol]),
?assertEquiv(ReadFun(<<"#'list">>), List),
{comments, ""}.
regex(Config) ->
ReadFun = ?config(read_fun, Config),
ReadAllFun = ?config(read_all_fun, Config),
Regex1 = 'erlang.util.Regex':?CONSTRUCTOR(<<".?el\\.lo">>),
Regex1 = ReadFun(<<"#\".?el\\.lo\"">>),
Regex2 = 'erlang.util.Regex':?CONSTRUCTOR(<<"">>),
Regex2 = ReadFun(<<"#\"\"">>),
Regex3 = 'erlang.util.Regex':?CONSTRUCTOR(<<"foo\\\"">>),
Regex3 = ReadFun(<<"#\"foo\\\"\"">>),
ct:comment("EOF: unterminated regex"),
ok = try ReadAllFun(<<"#\"a*">>)
catch _:_ -> ok
end,
ct:comment("EOF: unterminated regex"),
ok = try ReadAllFun(<<"#\"foo\\">>)
catch _:_ -> ok
end,
{comments, ""}.
unreadable_form(Config) ->
ReadFun = ?config(read_fun, Config),
ct:comment("Read unreadable"),
ok = try ReadFun(<<"#<1>">>)
catch error:Error1 ->
Msg1 = 'clojerl.IError':message(Error1),
<<?NO_SOURCE, ":1:1: Unreadable form">> = Msg1,
ok
end,
{comments, ""}.
discard(Config) ->
ReadFun = ?config(read_fun, Config),
ReadAllFun = ?config(read_all_fun, Config),
[1] = ReadAllFun(<<"#_ :hello 1">>),
1 = ReadFun(<<"#_ :hello 1">>),
1 = ReadFun(<<"1 #_ :hello">>),
1 = ReadFun(<<"#_ #_ :hello :world 1">>),
[1, 2] = clj_rt:to_list(ReadFun(<<"(1 2 #_ #_ #_ #_ 3 4 5 6)">>)),
StrSym = clj_rt:symbol(<<"str">>),
ByeKeyword = clj_rt:keyword(<<"bye">>),
List = clj_rt:list([StrSym, ByeKeyword]),
?assertEquiv(ReadFun(<<"(str #_ :hello :bye)">>), List),
{comments, ""}.
'cond'(Config) when is_list(Config) ->
ReadFun = ?config(read_fun, Config),
ReadFun2 = ?config(read_fun2, Config),
AllowOpts = #{'read-cond' => allow},
AllowCljFeatureOpts = #{'read-cond' => allow,
features => ReadFun(<<"#{:clj}">>)},
AllowClrFeatureOpts = #{'read-cond' => allow,
features => ReadFun(<<"#{:clr}">>)},
HelloKeyword = clj_rt:keyword(<<"hello">>),
ct:comment("Allow with no features"),
HelloKeyword = ReadFun2(<<"#?(:one 2) :hello">>, AllowOpts),
ct:comment("Allow with feature match"),
2 = ReadFun2(<<"#?(:clj 2) :hello">>, AllowCljFeatureOpts),
ct:comment("Allow with no feature match"),
HelloKeyword = ReadFun2( <<"#?(:clj 2 :cljs [3]) :hello">>
, AllowClrFeatureOpts
),
ct:comment("Cond splice vector"),
OneTwoThreeVector = ReadFun(<<"[:one :two :three]">>),
OneTwoThreeVector = ReadFun2( <<"[:one #?@(:clj :three"
" :clr [:two]) :three]">>
, AllowClrFeatureOpts
),
OneTwoThreeVector = ReadFun2( <<"[:one #? @ (:clj :three"
" :clr [:two]) :three]">>
, AllowClrFeatureOpts
),
OneTwoThreeFourVector = ReadFun(<<"[:one :two :three :four]">>),
OneTwoThreeFourVector =
ReadFun2( <<"[:one #?@(:clj :three :clr"
" [:two :three] :cljs :five) :four]">>
, AllowClrFeatureOpts
),
ct:comment("Cond splice list"),
OneTwoThreeVector = ReadFun2( <<"[:one #?@(:clj :three"
" :clr (:two)) :three]">>
, AllowClrFeatureOpts
),
OneTwoThreeFourVector = ReadFun2( <<"[:one #?@(:clj :three :clr"
" (:two :three) :cljs :five) :four]">>
, AllowClrFeatureOpts
),
ct:comment("Preserve read"),
PreserveOpts = #{'read-cond' => preserve},
ReaderCond =
'clojerl.reader.ReaderConditional':?CONSTRUCTOR(
ReadFun(<<"(1 2)">>), false
),
[ReaderCondCheck, HelloKeyword] =
read_all(<<"#?(1 2) :hello">>, PreserveOpts),
?assertEquiv(ReaderCond, ReaderCondCheck),
ReaderCondSplice =
'clojerl.reader.ReaderConditional':?CONSTRUCTOR(
ReadFun(<<"(1 2)">>), true
),
ReaderCondSpliceVector = clj_rt:vector([ReaderCondSplice, HelloKeyword]),
ReaderCondSpliceVectorCheck = ReadFun2(<<"[#?@(1 2) :hello]">>, PreserveOpts),
?assertEquiv(ReaderCondSpliceVector, ReaderCondSpliceVectorCheck),
false = clj_rt:equiv(ReaderCond, ReaderCondSpliceVector),
ct:comment("EOF while reading cond"),
ok = try ReadFun2(<<"#?">>, AllowOpts)
catch error:Error1 ->
Msg1 = 'clojerl.IError':message(Error1),
<<?NO_SOURCE, ":1:3: EOF while reading cond">> = Msg1,
ok
end,
ct:comment("Reader conditional not allowed"),
ok = try ReadFun(<<"#?(:clj :whatever :clr :whateverrrr)">>)
catch error:Error2 ->
Msg2 = 'clojerl.IError':message(Error2),
<<?NO_SOURCE, ":1:3: Conditional read not allowed">> = Msg2,
ok
end,
ct:comment("No list"),
ok = try ReadFun2(<<"#?:clj">>, AllowOpts)
catch error:Error3 ->
Msg3 = 'clojerl.IError':message(Error3),
<<?NO_SOURCE, ":1:3: read-cond body must be a list">> = Msg3,
ok
end,
ct:comment("EOF: no feature matched"),
ok = try ReadFun2(<<"#?(:clj :whatever :clr :whateverrrr)">>, AllowOpts)
catch error:Error4 ->
Msg4 = 'clojerl.IError':message(Error4),
<<?NO_SOURCE, ":1:37: EOF">> = Msg4,
ok
end,
ct:comment("Uneven number of forms"),
ok = try ReadFun2(<<"#?(:one :two :three)">>, AllowOpts)
catch error:Error5 ->
Msg5 = 'clojerl.IError':message(Error5),
<<?NO_SOURCE, ":1:21: read-cond requires an "
"even number of forms">> = Msg5,
ok
end,
ct:comment("Splice at the top level"),
ok = try ReadFun2(<<"#?@(:clje [:two])">>, AllowOpts)
catch error:Error6 ->
Msg6 = 'clojerl.IError':message(Error6),
<<?NO_SOURCE, ":1:5: Reader conditional splicing not allowed "
"at the top level">> = Msg6,
ok
end,
ct:comment("Splice in list but not sequential"),
ok = try ReadFun2(<<"[#?@(:clr :a :cljs :b) :c :d]">>,
AllowClrFeatureOpts)
catch error:Error7 ->
Msg7 = 'clojerl.IError':message(Error7),
<<?NO_SOURCE, ":1:13: Spliced form list in read-cond-splicing "
"must extend clojerl.ISequential">> = Msg7,
ok
end,
ct:comment("Feature is not a keyword"),
ok = try ReadFun2(<<"#?(1 2) :hello">>, AllowOpts)
catch error:Error8 ->
Msg8 = 'clojerl.IError':message(Error8),
<<?NO_SOURCE, ":1:4: Feature should be a keyword">> = Msg8,
ok
end,
{comments, ""}.
unsupported_reader(Config) ->
ReadFun = ?config(read_fun, Config),
ct:comment("Try unsupported reader"),
ok = try ReadFun(<<"#-:something">>)
catch _:_ -> ok
end,
{comments, ""}.
erl_literals(Config) ->
ReadFun = ?config(read_fun, Config),
ct:comment("Read an empty tuple"),
{} = ReadFun(<<"#erl []">>),
ct:comment("Read a tuple with a single element"),
{42} = ReadFun(<<"#erl [42]">>),
ct:comment("Read a tuple with many elements"),
HelloKeyword = clj_rt:keyword(<<"hello">>),
WorldSymbol = clj_rt:symbol(<<"world">>),
{ 42
, HelloKeywordCheck
, 2.5
, WorldSymbolCheck
} = ReadFun(<<"#erl [42, :hello, 2.5, world]">>),
?assertEquiv(HelloKeyword, HelloKeywordCheck),
?assertEquiv(WorldSymbol, WorldSymbolCheck),
ct:comment("Read a tuple whose first element is an keyword"),
T = ReadFun(<<"#erl [:random, :hello, 2.5, 'world]">>),
'erlang.Tuple' = clj_rt:type_module(T),
ct:comment("Read an empty list"),
ErlListSym = clj_rt:symbol(<<"erl-list*">>),
[ErlListSymCheck] = clj_rt:to_list(ReadFun(<<"#erl()">>)),
?assertEquiv(ErlListSym, ErlListSymCheck),
ct:comment("Read a list with a single element"),
[ErlListSymCheck, 42] = clj_rt:to_list(ReadFun(<<"#erl (42)">>)),
ct:comment("Read a tuple with many elements"),
[ ErlListSymCheck
, 42
, HelloKeywordCheckList
, 2.5
, WorldSymbolCheckList
] = clj_rt:to_list(ReadFun(<<"#erl (42, :hello, 2.5, world)">>)),
?assertEquiv(HelloKeyword, HelloKeywordCheckList),
?assertEquiv(WorldSymbol, WorldSymbolCheckList),
ct:comment("Read an empty map"),
#{} = ReadFun(<<"#erl {}">>),
ct:comment("Read a map with a single entry"),
#{42 := 'forty-two'} = ReadFun(<<"#erl {42 :forty-two}">>),
ct:comment("Read a map with many entries"),
#{ 42 := HelloKeywordCheckMap
, 2.5 := WorldSymbolCheckMap
} = ReadFun(<<"#erl {42, :hello, 2.5, world}">>),
?assertEquiv(HelloKeyword, HelloKeywordCheckMap),
?assertEquiv(WorldSymbol, WorldSymbolCheckMap),
ct:comment("Read a string"),
[ErlListSymCheck] = clj_rt:to_list(ReadFun(<<"#erl\"\"">>)),
ct:comment("Read a non-empty string"),
[ ErlListSymCheck
| "Hello there!"
] = clj_rt:to_list(ReadFun(<<"#erl \"Hello there!\"">>)),
ct:comment("Try to read an integer"),
ok = try ReadFun(<<"#erl 1">>), error
catch _:_ -> ok
end,
ct:comment("Read an Erlang function"),
DisplayFun = ReadFun(<<"#erl erlang/display.1">>),
DisplayFunCheck = ReadFun(<<"(erl-fun* :erlang :display 1)">>),
?assertEquiv(DisplayFun, DisplayFunCheck),
{comments, ""}.
erl_binary(Config) ->
ReadFun = ?config(read_fun, Config),
ErlBinarySym = clj_rt:symbol(<<"erl-binary*">>),
EmptyBinary = clj_rt:list([ErlBinarySym]),
ct:comment("Read an empty binary"),
?assertEquiv(ReadFun(<<"#bin[]">>), EmptyBinary),
ct:comment("Read a single integer"),
SingleIntBinary = clj_rt:list([ErlBinarySym, 64]),
?assertEquiv(ReadFun(<<"#bin[64]">>), SingleIntBinary),
{comments, ""}.
erl_alias(Config) ->
ReadFun = ?config(read_fun, Config),
ErlAliasSym = clj_rt:symbol(<<"erl-alias*">>),
XSym = clj_rt:symbol(<<"x">>),
AliasList = clj_rt:list([ErlAliasSym, XSym, 1]),
ct:comment("Read the tagged literal alias"),
?assertEquiv(ReadFun(<<"#as(x 1)">>), AliasList),
{comments, ""}.
tagged(Config) ->
ReadFun = ?config(read_fun, Config),
UUIDBin = <<"de305d54-75b4-431b-adb2-eb6b9e546014">>,
ct:comment("Use bootstraped default readers implementation"),
{inst, <<"2016">>} = ReadFun(<<"#inst \"2016\"">>),
{uuid, UUIDBin} = ReadFun(<<"#uuid \"", UUIDBin/binary, "\"">>),
ct:comment("Use *default-data-reader-fn*"),
DefaultReaderFunVar =
'clojerl.Var':?CONSTRUCTOR( <<"clojure.core">>
, <<"*default-data-reader-fn*">>
),
DefaultReaderFun = fun(_, _) -> default end,
ok = 'clojerl.Var':push_bindings(#{DefaultReaderFunVar => DefaultReaderFun}),
default = ReadFun(<<"#whatever :tag">>),
default = ReadFun(<<"#we use">>),
ok = 'clojerl.Var':pop_bindings(),
ct:comment("Provide additional reader"),
DataReadersVar = 'clojerl.Var':?CONSTRUCTOR( <<"clojure.core">>
, <<"*data-readers*">>
),
BlaSymbol = clj_rt:symbol(<<"bla">>),
DataReaders = #{BlaSymbol => fun(_) -> bla end},
ok = 'clojerl.Var':push_bindings(#{DataReadersVar => DataReaders}),
bla = ReadFun(<<"#bla 1">>),
ok = 'clojerl.Var':pop_bindings(),
ct:comment("Don't provide a symbol"),
try
ReadFun(<<"#1">>),
?ERROR(<<"Expected an error">>)
catch error:Error1 ->
assert_error_message(Error1, ":1:2: Reader tag must be a symbol")
end,
ct:comment("Provide a missing reader"),
try
ReadFun(<<"#bla 1">>),
?ERROR(<<"Expected an error">>)
catch error:Error2 ->
assert_error_message(Error2, ":1:2: No reader function for tag bla")
end,
{comments, ""}.
reader_resolver(Config) ->
ReadFun = ?config(read_fun, Config),
Resolver = 'clojerl.DummyResolver':?CONSTRUCTOR(),
Bindings = #{<<"#'clojure.core/*reader-resolver*">> => Resolver},
ct:comment("Reading auto-resolved keyword"),
'clojerl.Var':push_bindings(Bindings),
'dummy/foo' = try ReadFun(<<"::foo">>)
after 'clojerl.Var':pop_bindings()
end,
ct:comment("Reading auto-resolved keyword with namespace"),
try ReadFun(<<"::foo/bar">>)
catch error:Error1 ->
assert_error_message(Error1, "Invalid token")
end,
'clojerl.Var':push_bindings(Bindings),
'foo/bar' = try ReadFun(<<"::foo/bar">>)
after 'clojerl.Var':pop_bindings()
end,
ct:comment("Reading constructor type symbol in syntax quote"),
QuoteSym = clj_rt:symbol(<<"quote">>),
QuoteFun = fun(X) -> clj_rt:list([QuoteSym, X]) end,
StringTypeSym = clj_rt:symbol(<<"clojerl.String.">>),
QuotedStringTypeSym = QuoteFun(StringTypeSym),
'clojerl.Var':push_bindings(Bindings),
QuotedStringTypeSym = try ReadFun(<<"`clojerl.String.">>)
after 'clojerl.Var':pop_bindings()
end,
ct:comment("Syntax quote unqualified symbol"),
FooSym = clj_rt:symbol(<<"foo">>),
QuoteFooSym = QuoteFun(FooSym),
'clojerl.Var':push_bindings(Bindings),
QuoteFooSym = try ReadFun(<<"`foo">>)
after 'clojerl.Var':pop_bindings()
end,
ct:comment("Syntax quote qualified symbol"),
FooBarSym = clj_rt:symbol(<<"foo/bar">>),
QuoteFooBarSym = QuoteFun(FooBarSym),
'clojerl.Var':push_bindings(Bindings),
QuoteFooBarSym = try ReadFun(<<"`foo/bar">>)
after 'clojerl.Var':pop_bindings()
end,
ct:comment("Namespaced map auto-resolved"),
NamespacedMap1 = #{'dummy/a' => 1},
'clojerl.Var':push_bindings(Bindings),
NamespacedMap1Check = try ReadFun(<<"#::{:a 1}">>)
after 'clojerl.Var':pop_bindings()
end,
?assertEquiv(NamespacedMap1, NamespacedMap1Check),
ct:comment("Namespaced map auto-resolved"),
NamespacedMap2 = #{'foo/a' => 1},
'clojerl.Var':push_bindings(Bindings),
NamespacedMap2Check = try ReadFun(<<"#::foo{:a 1}">>)
after 'clojerl.Var':pop_bindings()
end,
?assertEquiv(NamespacedMap2, NamespacedMap2Check),
{comments, ""}.
namespaced_map(Config) ->
ReadFun = ?config(read_fun, Config),
ct:comment("Simple keyword"),
Map1 = #{'foo/a' => 1},
?assertEquiv(Map1, ReadFun(<<"#:foo{:a 1}">>)),
ct:comment("Auto-resolved map"),
Map2 = #{'clojure.core/a' => 1},
?assertEquiv(Map2, ReadFun(<<"#::{:a 1}">>)),
{comments, ""}.
-spec assert_error_message('clojerl.IError':type(), binary()) -> ok.
assert_error_message(Error, MessageRegex) ->
Msg = 'clojerl.IError':message(Error),
{match, _} = re:run(Msg, MessageRegex).
-spec read_io(binary()) -> any().
read_io(Src) ->
read_io(Src, #{}).
-spec read_io(binary(), clj_reader:opts()) -> any().
read_io(Src, Opts) ->
Reader = 'erlang.io.StringReader':?CONSTRUCTOR(Src),
PushbackReader = 'erlang.io.PushbackReader':?CONSTRUCTOR(Reader),
clj_reader:read(<<>>, Opts#{?OPT_IO_READER => PushbackReader}).
-spec read(binary()) -> any().
read(Src) ->
clj_reader:read(Src).
-spec read(binary(), clj_reader:opts()) -> any().
read(Src, Opts) ->
clj_reader:read(Src, Opts).
-spec read_all_io(binary()) -> any().
read_all_io(Src) ->
Reader = 'erlang.io.StringReader':?CONSTRUCTOR(Src),
PushbackReader = 'erlang.io.PushbackReader':?CONSTRUCTOR(Reader),
read_all(<<>>, #{?OPT_IO_READER => PushbackReader}).
-spec read_all(binary()) -> [any()].
read_all(Src) ->
read_all(Src, #{eof => ok}).
-spec read_all(binary(), clj_reader:opts()) -> [any()].
read_all(Src, Opts) ->
Fun = fun(Form, Acc) -> [Form | Acc] end,
lists:reverse(clj_reader:read_fold(Fun, Src, Opts, [])).
|
ba8bf635d9d5c12cb1245a4bdeae0c5d6f80a565a254dba07d093fe284cac271 | typelead/eta | ExtsCompat46.hs | # LANGUAGE BangPatterns , CPP , MagicHash #
-----------------------------------------------------------------------------
-- |
Module : ExtsCompat46
Copyright : ( c ) Lodz University of Technology 2013
-- License : see LICENSE
--
Maintainer :
-- Stability : internal
Portability : non - portable ( GHC internal )
--
Compatibility module to encapsulate primops API change between GHC 7.6
GHC 7.8 .
--
In GHC we use comparison primops in a couple of modules , but that
have different type signature in GHC 7.6 ( where they return ) than
in GHC 7.8 ( where they return Int # ) . As long as we allow bootstrapping
with GHC 7.6 or earlier we need to have this compatibility module , so that
we can compile stage1 compiler using the old API and then continue with
stage2 using the new API . When we set GHC 7.8 as the minimum version
-- required for bootstrapping, we should remove this module.
--
-----------------------------------------------------------------------------
module Eta.Utils.ExtsCompat46 (
module GHC.Exts,
gtChar#, geChar#, eqChar#,
neChar#, ltChar#, leChar#,
(>#), (>=#), (==#), (/=#), (<#), (<=#),
gtWord#, geWord#, eqWord#,
neWord#, ltWord#, leWord#,
(>##), (>=##), (==##), (/=##), (<##), (<=##),
gtFloat#, geFloat#, eqFloat#,
neFloat#, ltFloat#, leFloat#,
gtAddr#, geAddr#, eqAddr#,
neAddr#, ltAddr#, leAddr#,
sameMutableArray#, sameMutableByteArray#, sameMutableArrayArray#,
sameMutVar#, sameTVar#, sameMVar#
) where
import GHC.Exts hiding (
gtChar#, geChar#, eqChar#,
neChar#, ltChar#, leChar#,
(>#), (>=#), (==#), (/=#), (<#), (<=#),
gtWord#, geWord#, eqWord#,
neWord#, ltWord#, leWord#,
(>##), (>=##), (==##), (/=##), (<##), (<=##),
gtFloat#, geFloat#, eqFloat#,
neFloat#, ltFloat#, leFloat#,
gtAddr#, geAddr#, eqAddr#,
neAddr#, ltAddr#, leAddr#,
sameMutableArray#, sameMutableByteArray#, sameMutableArrayArray#,
sameMutVar#, sameTVar#, sameMVar#
)
import qualified GHC.Exts as E (
gtChar#, geChar#, eqChar#,
neChar#, ltChar#, leChar#,
(>#), (>=#), (==#), (/=#), (<#), (<=#),
gtWord#, geWord#, eqWord#,
neWord#, ltWord#, leWord#,
(>##), (>=##), (==##), (/=##), (<##), (<=##),
gtFloat#, geFloat#, eqFloat#,
neFloat#, ltFloat#, leFloat#,
gtAddr#, geAddr#, eqAddr#,
neAddr#, ltAddr#, leAddr#,
sameMutableArray#, sameMutableByteArray#, sameMutableArrayArray#,
sameMutVar#, sameTVar#, sameMVar#
)
See # 8330
#if __GLASGOW_HASKELL__ > 706
gtChar# :: Char# -> Char# -> Bool
gtChar# a b = isTrue# (a `E.gtChar#` b)
geChar# :: Char# -> Char# -> Bool
geChar# a b = isTrue# (a `E.geChar#` b)
eqChar# :: Char# -> Char# -> Bool
eqChar# a b = isTrue# (a `E.eqChar#` b)
neChar# :: Char# -> Char# -> Bool
neChar# a b = isTrue# (a `E.neChar#` b)
ltChar# :: Char# -> Char# -> Bool
ltChar# a b = isTrue# (a `E.ltChar#` b)
leChar# :: Char# -> Char# -> Bool
leChar# a b = isTrue# (a `E.leChar#` b)
infix 4 >#, >=#, ==#, /=#, <#, <=#
(>#) :: Int# -> Int# -> Bool
(>#) a b = isTrue# (a E.># b)
(>=#) :: Int# -> Int# -> Bool
(>=#) a b = isTrue# (a E.>=# b)
(==#) :: Int# -> Int# -> Bool
(==#) a b = isTrue# (a E.==# b)
(/=#) :: Int# -> Int# -> Bool
(/=#) a b = isTrue# (a E./=# b)
(<#) :: Int# -> Int# -> Bool
(<#) a b = isTrue# (a E.<# b)
(<=#) :: Int# -> Int# -> Bool
(<=#) a b = isTrue# (a E.<=# b)
gtWord# :: Word# -> Word# -> Bool
gtWord# a b = isTrue# (a `E.gtWord#` b)
geWord# :: Word# -> Word# -> Bool
geWord# a b = isTrue# (a `E.geWord#` b)
eqWord# :: Word# -> Word# -> Bool
eqWord# a b = isTrue# (a `E.eqWord#` b)
neWord# :: Word# -> Word# -> Bool
neWord# a b = isTrue# (a `E.neWord#` b)
ltWord# :: Word# -> Word# -> Bool
ltWord# a b = isTrue# (a `E.ltWord#` b)
leWord# :: Word# -> Word# -> Bool
leWord# a b = isTrue# (a `E.leWord#` b)
infix 4 >##, >=##, ==##, /=##, <##, <=##
(>##) :: Double# -> Double# -> Bool
(>##) a b = isTrue# (a E.>## b)
(>=##) :: Double# -> Double# -> Bool
(>=##) a b = isTrue# (a E.>=## b)
(==##) :: Double# -> Double# -> Bool
(==##) a b = isTrue# (a E.==## b)
(/=##) :: Double# -> Double# -> Bool
(/=##) a b = isTrue# (a E./=## b)
(<##) :: Double# -> Double# -> Bool
(<##) a b = isTrue# (a E.<## b)
(<=##) :: Double# -> Double# -> Bool
(<=##) a b = isTrue# (a E.<=## b)
gtFloat# :: Float# -> Float# -> Bool
gtFloat# a b = isTrue# (a `E.gtFloat#` b)
geFloat# :: Float# -> Float# -> Bool
geFloat# a b = isTrue# (a `E.geFloat#` b)
eqFloat# :: Float# -> Float# -> Bool
eqFloat# a b = isTrue# (a `E.eqFloat#` b)
neFloat# :: Float# -> Float# -> Bool
neFloat# a b = isTrue# (a `E.neFloat#` b)
ltFloat# :: Float# -> Float# -> Bool
ltFloat# a b = isTrue# (a `E.ltFloat#` b)
leFloat# :: Float# -> Float# -> Bool
leFloat# a b = isTrue# (a `E.leFloat#` b)
gtAddr# :: Addr# -> Addr# -> Bool
gtAddr# a b = isTrue# (a `E.gtAddr#` b)
geAddr# :: Addr# -> Addr# -> Bool
geAddr# a b = isTrue# (a `E.geAddr#` b)
eqAddr# :: Addr# -> Addr# -> Bool
eqAddr# a b = isTrue# (a `E.eqAddr#` b)
neAddr# :: Addr# -> Addr# -> Bool
neAddr# a b = isTrue# (a `E.neAddr#` b)
ltAddr# :: Addr# -> Addr# -> Bool
ltAddr# a b = isTrue# (a `E.ltAddr#` b)
leAddr# :: Addr# -> Addr# -> Bool
leAddr# a b = isTrue# (a `E.leAddr#` b)
sameMutableArray# :: MutableArray# s a -> MutableArray# s a -> Bool
sameMutableArray# a b = isTrue# (E.sameMutableArray# a b)
sameMutableByteArray# :: MutableByteArray# s -> MutableByteArray# s -> Bool
sameMutableByteArray# a b = isTrue# (E.sameMutableByteArray# a b)
sameMutableArrayArray# :: MutableArrayArray# s -> MutableArrayArray# s -> Bool
sameMutableArrayArray# a b = isTrue# (E.sameMutableArrayArray# a b)
sameMutVar# :: MutVar# s a -> MutVar# s a -> Bool
sameMutVar# a b = isTrue# (E.sameMutVar# a b)
sameTVar# :: TVar# s a -> TVar# s a -> Bool
sameTVar# a b = isTrue# (E.sameTVar# a b)
sameMVar# :: MVar# s a -> MVar# s a -> Bool
sameMVar# a b = isTrue# (E.sameMVar# a b)
#else
gtChar# :: Char# -> Char# -> Bool
gtChar# a b = a `E.gtChar#` b
geChar# :: Char# -> Char# -> Bool
geChar# a b = a `E.geChar#` b
eqChar# :: Char# -> Char# -> Bool
eqChar# a b = a `E.eqChar#` b
neChar# :: Char# -> Char# -> Bool
neChar# a b = a `E.neChar#` b
ltChar# :: Char# -> Char# -> Bool
ltChar# a b = a `E.ltChar#` b
leChar# :: Char# -> Char# -> Bool
leChar# a b = a `E.leChar#` b
infix 4 >#, >=#, ==#, /=#, <#, <=#
(>#) :: Int# -> Int# -> Bool
(>#) a b = a E.># b
(>=#) :: Int# -> Int# -> Bool
(>=#) a b = a E.>=# b
(==#) :: Int# -> Int# -> Bool
(==#) a b = a E.==# b
(/=#) :: Int# -> Int# -> Bool
(/=#) a b = a E./=# b
(<#) :: Int# -> Int# -> Bool
(<#) a b = a E.<# b
(<=#) :: Int# -> Int# -> Bool
(<=#) a b = a E.<=# b
gtWord# :: Word# -> Word# -> Bool
gtWord# a b = a `E.gtWord#` b
geWord# :: Word# -> Word# -> Bool
geWord# a b = a `E.geWord#` b
eqWord# :: Word# -> Word# -> Bool
eqWord# a b = a `E.eqWord#` b
neWord# :: Word# -> Word# -> Bool
neWord# a b = a `E.neWord#` b
ltWord# :: Word# -> Word# -> Bool
ltWord# a b = a `E.ltWord#` b
leWord# :: Word# -> Word# -> Bool
leWord# a b = a `E.leWord#` b
infix 4 >##, >=##, ==##, /=##, <##, <=##
(>##) :: Double# -> Double# -> Bool
(>##) a b = a E.>## b
(>=##) :: Double# -> Double# -> Bool
(>=##) a b = a E.>=## b
(==##) :: Double# -> Double# -> Bool
(==##) a b = a E.==## b
(/=##) :: Double# -> Double# -> Bool
(/=##) a b = a E./=## b
(<##) :: Double# -> Double# -> Bool
(<##) a b = a E.<## b
(<=##) :: Double# -> Double# -> Bool
(<=##) a b = a E.<=## b
gtFloat# :: Float# -> Float# -> Bool
gtFloat# a b = a `E.gtFloat#` b
geFloat# :: Float# -> Float# -> Bool
geFloat# a b = a `E.geFloat#` b
eqFloat# :: Float# -> Float# -> Bool
eqFloat# a b = a `E.eqFloat#` b
neFloat# :: Float# -> Float# -> Bool
neFloat# a b = a `E.neFloat#` b
ltFloat# :: Float# -> Float# -> Bool
ltFloat# a b = a `E.ltFloat#` b
leFloat# :: Float# -> Float# -> Bool
leFloat# a b = a `E.leFloat#` b
gtAddr# :: Addr# -> Addr# -> Bool
gtAddr# a b = a `E.gtAddr#` b
geAddr# :: Addr# -> Addr# -> Bool
geAddr# a b = a `E.geAddr#` b
eqAddr# :: Addr# -> Addr# -> Bool
eqAddr# a b = a `E.eqAddr#` b
neAddr# :: Addr# -> Addr# -> Bool
neAddr# a b = a `E.neAddr#` b
ltAddr# :: Addr# -> Addr# -> Bool
ltAddr# a b = a `E.ltAddr#` b
leAddr# :: Addr# -> Addr# -> Bool
leAddr# a b = a `E.leAddr#` b
sameMutableArray# :: MutableArray# s a -> MutableArray# s a -> Bool
sameMutableArray# a b = E.sameMutableArray# a b
sameMutableByteArray# :: MutableByteArray# s -> MutableByteArray# s -> Bool
sameMutableByteArray# a b = E.sameMutableByteArray# a b
sameMutableArrayArray# :: MutableArrayArray# s -> MutableArrayArray# s -> Bool
sameMutableArrayArray# a b = E.sameMutableArrayArray# a b
sameMutVar# :: MutVar# s a -> MutVar# s a -> Bool
sameMutVar# a b = E.sameMutVar# a b
sameTVar# :: TVar# s a -> TVar# s a -> Bool
sameTVar# a b = E.sameTVar# a b
sameMVar# :: MVar# s a -> MVar# s a -> Bool
sameMVar# a b = E.sameMVar# a b
#endif
| null | https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/compiler/Eta/Utils/ExtsCompat46.hs | haskell | ---------------------------------------------------------------------------
|
License : see LICENSE
Stability : internal
required for bootstrapping, we should remove this module.
--------------------------------------------------------------------------- | # LANGUAGE BangPatterns , CPP , MagicHash #
Module : ExtsCompat46
Copyright : ( c ) Lodz University of Technology 2013
Maintainer :
Portability : non - portable ( GHC internal )
Compatibility module to encapsulate primops API change between GHC 7.6
GHC 7.8 .
In GHC we use comparison primops in a couple of modules , but that
have different type signature in GHC 7.6 ( where they return ) than
in GHC 7.8 ( where they return Int # ) . As long as we allow bootstrapping
with GHC 7.6 or earlier we need to have this compatibility module , so that
we can compile stage1 compiler using the old API and then continue with
stage2 using the new API . When we set GHC 7.8 as the minimum version
module Eta.Utils.ExtsCompat46 (
module GHC.Exts,
gtChar#, geChar#, eqChar#,
neChar#, ltChar#, leChar#,
(>#), (>=#), (==#), (/=#), (<#), (<=#),
gtWord#, geWord#, eqWord#,
neWord#, ltWord#, leWord#,
(>##), (>=##), (==##), (/=##), (<##), (<=##),
gtFloat#, geFloat#, eqFloat#,
neFloat#, ltFloat#, leFloat#,
gtAddr#, geAddr#, eqAddr#,
neAddr#, ltAddr#, leAddr#,
sameMutableArray#, sameMutableByteArray#, sameMutableArrayArray#,
sameMutVar#, sameTVar#, sameMVar#
) where
import GHC.Exts hiding (
gtChar#, geChar#, eqChar#,
neChar#, ltChar#, leChar#,
(>#), (>=#), (==#), (/=#), (<#), (<=#),
gtWord#, geWord#, eqWord#,
neWord#, ltWord#, leWord#,
(>##), (>=##), (==##), (/=##), (<##), (<=##),
gtFloat#, geFloat#, eqFloat#,
neFloat#, ltFloat#, leFloat#,
gtAddr#, geAddr#, eqAddr#,
neAddr#, ltAddr#, leAddr#,
sameMutableArray#, sameMutableByteArray#, sameMutableArrayArray#,
sameMutVar#, sameTVar#, sameMVar#
)
import qualified GHC.Exts as E (
gtChar#, geChar#, eqChar#,
neChar#, ltChar#, leChar#,
(>#), (>=#), (==#), (/=#), (<#), (<=#),
gtWord#, geWord#, eqWord#,
neWord#, ltWord#, leWord#,
(>##), (>=##), (==##), (/=##), (<##), (<=##),
gtFloat#, geFloat#, eqFloat#,
neFloat#, ltFloat#, leFloat#,
gtAddr#, geAddr#, eqAddr#,
neAddr#, ltAddr#, leAddr#,
sameMutableArray#, sameMutableByteArray#, sameMutableArrayArray#,
sameMutVar#, sameTVar#, sameMVar#
)
See # 8330
#if __GLASGOW_HASKELL__ > 706
gtChar# :: Char# -> Char# -> Bool
gtChar# a b = isTrue# (a `E.gtChar#` b)
geChar# :: Char# -> Char# -> Bool
geChar# a b = isTrue# (a `E.geChar#` b)
eqChar# :: Char# -> Char# -> Bool
eqChar# a b = isTrue# (a `E.eqChar#` b)
neChar# :: Char# -> Char# -> Bool
neChar# a b = isTrue# (a `E.neChar#` b)
ltChar# :: Char# -> Char# -> Bool
ltChar# a b = isTrue# (a `E.ltChar#` b)
leChar# :: Char# -> Char# -> Bool
leChar# a b = isTrue# (a `E.leChar#` b)
infix 4 >#, >=#, ==#, /=#, <#, <=#
(>#) :: Int# -> Int# -> Bool
(>#) a b = isTrue# (a E.># b)
(>=#) :: Int# -> Int# -> Bool
(>=#) a b = isTrue# (a E.>=# b)
(==#) :: Int# -> Int# -> Bool
(==#) a b = isTrue# (a E.==# b)
(/=#) :: Int# -> Int# -> Bool
(/=#) a b = isTrue# (a E./=# b)
(<#) :: Int# -> Int# -> Bool
(<#) a b = isTrue# (a E.<# b)
(<=#) :: Int# -> Int# -> Bool
(<=#) a b = isTrue# (a E.<=# b)
gtWord# :: Word# -> Word# -> Bool
gtWord# a b = isTrue# (a `E.gtWord#` b)
geWord# :: Word# -> Word# -> Bool
geWord# a b = isTrue# (a `E.geWord#` b)
eqWord# :: Word# -> Word# -> Bool
eqWord# a b = isTrue# (a `E.eqWord#` b)
neWord# :: Word# -> Word# -> Bool
neWord# a b = isTrue# (a `E.neWord#` b)
ltWord# :: Word# -> Word# -> Bool
ltWord# a b = isTrue# (a `E.ltWord#` b)
leWord# :: Word# -> Word# -> Bool
leWord# a b = isTrue# (a `E.leWord#` b)
infix 4 >##, >=##, ==##, /=##, <##, <=##
(>##) :: Double# -> Double# -> Bool
(>##) a b = isTrue# (a E.>## b)
(>=##) :: Double# -> Double# -> Bool
(>=##) a b = isTrue# (a E.>=## b)
(==##) :: Double# -> Double# -> Bool
(==##) a b = isTrue# (a E.==## b)
(/=##) :: Double# -> Double# -> Bool
(/=##) a b = isTrue# (a E./=## b)
(<##) :: Double# -> Double# -> Bool
(<##) a b = isTrue# (a E.<## b)
(<=##) :: Double# -> Double# -> Bool
(<=##) a b = isTrue# (a E.<=## b)
gtFloat# :: Float# -> Float# -> Bool
gtFloat# a b = isTrue# (a `E.gtFloat#` b)
geFloat# :: Float# -> Float# -> Bool
geFloat# a b = isTrue# (a `E.geFloat#` b)
eqFloat# :: Float# -> Float# -> Bool
eqFloat# a b = isTrue# (a `E.eqFloat#` b)
neFloat# :: Float# -> Float# -> Bool
neFloat# a b = isTrue# (a `E.neFloat#` b)
ltFloat# :: Float# -> Float# -> Bool
ltFloat# a b = isTrue# (a `E.ltFloat#` b)
leFloat# :: Float# -> Float# -> Bool
leFloat# a b = isTrue# (a `E.leFloat#` b)
gtAddr# :: Addr# -> Addr# -> Bool
gtAddr# a b = isTrue# (a `E.gtAddr#` b)
geAddr# :: Addr# -> Addr# -> Bool
geAddr# a b = isTrue# (a `E.geAddr#` b)
eqAddr# :: Addr# -> Addr# -> Bool
eqAddr# a b = isTrue# (a `E.eqAddr#` b)
neAddr# :: Addr# -> Addr# -> Bool
neAddr# a b = isTrue# (a `E.neAddr#` b)
ltAddr# :: Addr# -> Addr# -> Bool
ltAddr# a b = isTrue# (a `E.ltAddr#` b)
leAddr# :: Addr# -> Addr# -> Bool
leAddr# a b = isTrue# (a `E.leAddr#` b)
sameMutableArray# :: MutableArray# s a -> MutableArray# s a -> Bool
sameMutableArray# a b = isTrue# (E.sameMutableArray# a b)
sameMutableByteArray# :: MutableByteArray# s -> MutableByteArray# s -> Bool
sameMutableByteArray# a b = isTrue# (E.sameMutableByteArray# a b)
sameMutableArrayArray# :: MutableArrayArray# s -> MutableArrayArray# s -> Bool
sameMutableArrayArray# a b = isTrue# (E.sameMutableArrayArray# a b)
sameMutVar# :: MutVar# s a -> MutVar# s a -> Bool
sameMutVar# a b = isTrue# (E.sameMutVar# a b)
sameTVar# :: TVar# s a -> TVar# s a -> Bool
sameTVar# a b = isTrue# (E.sameTVar# a b)
sameMVar# :: MVar# s a -> MVar# s a -> Bool
sameMVar# a b = isTrue# (E.sameMVar# a b)
#else
gtChar# :: Char# -> Char# -> Bool
gtChar# a b = a `E.gtChar#` b
geChar# :: Char# -> Char# -> Bool
geChar# a b = a `E.geChar#` b
eqChar# :: Char# -> Char# -> Bool
eqChar# a b = a `E.eqChar#` b
neChar# :: Char# -> Char# -> Bool
neChar# a b = a `E.neChar#` b
ltChar# :: Char# -> Char# -> Bool
ltChar# a b = a `E.ltChar#` b
leChar# :: Char# -> Char# -> Bool
leChar# a b = a `E.leChar#` b
infix 4 >#, >=#, ==#, /=#, <#, <=#
(>#) :: Int# -> Int# -> Bool
(>#) a b = a E.># b
(>=#) :: Int# -> Int# -> Bool
(>=#) a b = a E.>=# b
(==#) :: Int# -> Int# -> Bool
(==#) a b = a E.==# b
(/=#) :: Int# -> Int# -> Bool
(/=#) a b = a E./=# b
(<#) :: Int# -> Int# -> Bool
(<#) a b = a E.<# b
(<=#) :: Int# -> Int# -> Bool
(<=#) a b = a E.<=# b
gtWord# :: Word# -> Word# -> Bool
gtWord# a b = a `E.gtWord#` b
geWord# :: Word# -> Word# -> Bool
geWord# a b = a `E.geWord#` b
eqWord# :: Word# -> Word# -> Bool
eqWord# a b = a `E.eqWord#` b
neWord# :: Word# -> Word# -> Bool
neWord# a b = a `E.neWord#` b
ltWord# :: Word# -> Word# -> Bool
ltWord# a b = a `E.ltWord#` b
leWord# :: Word# -> Word# -> Bool
leWord# a b = a `E.leWord#` b
infix 4 >##, >=##, ==##, /=##, <##, <=##
(>##) :: Double# -> Double# -> Bool
(>##) a b = a E.>## b
(>=##) :: Double# -> Double# -> Bool
(>=##) a b = a E.>=## b
(==##) :: Double# -> Double# -> Bool
(==##) a b = a E.==## b
(/=##) :: Double# -> Double# -> Bool
(/=##) a b = a E./=## b
(<##) :: Double# -> Double# -> Bool
(<##) a b = a E.<## b
(<=##) :: Double# -> Double# -> Bool
(<=##) a b = a E.<=## b
gtFloat# :: Float# -> Float# -> Bool
gtFloat# a b = a `E.gtFloat#` b
geFloat# :: Float# -> Float# -> Bool
geFloat# a b = a `E.geFloat#` b
eqFloat# :: Float# -> Float# -> Bool
eqFloat# a b = a `E.eqFloat#` b
neFloat# :: Float# -> Float# -> Bool
neFloat# a b = a `E.neFloat#` b
ltFloat# :: Float# -> Float# -> Bool
ltFloat# a b = a `E.ltFloat#` b
leFloat# :: Float# -> Float# -> Bool
leFloat# a b = a `E.leFloat#` b
gtAddr# :: Addr# -> Addr# -> Bool
gtAddr# a b = a `E.gtAddr#` b
geAddr# :: Addr# -> Addr# -> Bool
geAddr# a b = a `E.geAddr#` b
eqAddr# :: Addr# -> Addr# -> Bool
eqAddr# a b = a `E.eqAddr#` b
neAddr# :: Addr# -> Addr# -> Bool
neAddr# a b = a `E.neAddr#` b
ltAddr# :: Addr# -> Addr# -> Bool
ltAddr# a b = a `E.ltAddr#` b
leAddr# :: Addr# -> Addr# -> Bool
leAddr# a b = a `E.leAddr#` b
sameMutableArray# :: MutableArray# s a -> MutableArray# s a -> Bool
sameMutableArray# a b = E.sameMutableArray# a b
sameMutableByteArray# :: MutableByteArray# s -> MutableByteArray# s -> Bool
sameMutableByteArray# a b = E.sameMutableByteArray# a b
sameMutableArrayArray# :: MutableArrayArray# s -> MutableArrayArray# s -> Bool
sameMutableArrayArray# a b = E.sameMutableArrayArray# a b
sameMutVar# :: MutVar# s a -> MutVar# s a -> Bool
sameMutVar# a b = E.sameMutVar# a b
sameTVar# :: TVar# s a -> TVar# s a -> Bool
sameTVar# a b = E.sameTVar# a b
sameMVar# :: MVar# s a -> MVar# s a -> Bool
sameMVar# a b = E.sameMVar# a b
#endif
|
2e909a3b63525096d5e6c43bc739675322008d70ab3a3ab03447577df0c4e1f9 | xach/buildapp | utils.lisp | ;;;;
Copyright ( c ) 2010 , All Rights Reserved
;;;;
;;;; Redistribution and use in source and binary forms, with or without
;;;; modification, are permitted provided that the following conditions
;;;; are met:
;;;;
;;;; * 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.
;;;;
;;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;;
;;;; utils.lisp
(in-package #:buildapp)
;;; interoperability
(defun get-args ()
#+sbcl 'sb-ext:*posix-argv*
#+ccl '(ccl::command-line-arguments))
(defmacro backtrace-as-list ()
#+sbcl '(sb-debug:backtrace-as-list)
#+ccl '(ccl::backtrace-as-list))
(defmacro quit (&optional (errno 0))
#+sbcl `(sb-ext:exit :code ,errno)
#+ccl `(ccl:quit ,errno))
(defmacro run-program (program args)
(let ((func #+sbcl 'sb-ext:run-program
#+ccl 'ccl:run-program)
(search #+sbcl '(:search t)))
`(,func ,program ,args
:input nil
:output *standard-output*
,@search)))
(defun native-namestring (namestring)
(let ((p (pathname namestring)))
#+sbcl (sb-ext:native-namestring p)
#+ccl (ccl:native-translated-namestring p)))
(defparameter *alphabet*
(concatenate 'string
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
(defun random-string (length)
"Return a random string with LENGTH characters."
(let ((string (make-string length)))
(map-into string (lambda (char)
(declare (ignore char))
(aref *alphabet* (random (length *alphabet*))))
string)))
(defun call-with-temporary-open-file (template fun &rest open-args
&key element-type external-format)
"Call FUN with two arguments: an open output stream and a file
name. When it returns, the file is deleted. TEMPLATE should be a
pathname that can be used as a basis for the temporary file's
location."
(declare (ignorable element-type external-format))
(flet ((new-name ()
(make-pathname :name (concatenate 'string
(pathname-name template)
"-"
(random-string 8))
:defaults template)))
(let (try stream)
(tagbody
:retry
(setf try (new-name))
(unwind-protect
(progn
(setf stream (apply #'open try
:if-exists nil
:direction :output
open-args))
(unless stream
(go :retry))
(funcall fun stream try))
(when stream
(close stream)
(ignore-errors (delete-file try))))))))
(defmacro with-tempfile ((stream (template file) &rest open-args) &body body)
`(call-with-temporary-open-file ,template
(lambda (,stream ,file)
,@body)
,@open-args))
(defclass pseudosymbol ()
((package-string
:initarg :package-string
:accessor package-string)
(symbol-string
:initarg :symbol-string
:accessor symbol-string)))
(defmethod print-object ((pseudosymbol pseudosymbol) stream)
(format stream "~A::~A"
(package-string pseudosymbol)
(symbol-string pseudosymbol)))
(defun make-pseudosymbol (string)
(let* ((package-start 0)
(package-end (position #\: string))
(symbol-start (and package-end (position #\: string
:start package-end
:test-not #'eql)))
(package (if package-end
(subseq string package-start package-end)
"cl-user"))
(symbol (if symbol-start
(subseq string symbol-start)
string)))
(make-instance 'pseudosymbol
:package-string package
:symbol-string symbol)))
(defclass dispatched-entry ()
((binary-name
:initarg :binary-name
:accessor binary-name
:initform nil)
(entry
:initarg :entry
:accessor entry
:initform ""))
(:documentation "A dispatched entry is used to select an entry point
depending on the name of the binary that invoked the application. If
the binary name is empty, it is considered the default entry if no
match is found."))
(defmethod print-object ((dispatched-entry dispatched-entry) stream)
(print-unreadable-object (dispatched-entry stream :type t)
(format stream "~A/~A"
(binary-name dispatched-entry)
(entry dispatched-entry))))
(define-condition malformed-dispatch-entry (error) ())
(defun make-dispatched-entry (string)
(let ((slash (position #\/ string)))
(unless slash
(error 'malformed-dispatch-entry))
(let ((binary-name (subseq string 0 slash))
(entry (make-pseudosymbol (subseq string (1+ slash)))))
(make-instance 'dispatched-entry
:binary-name binary-name
:entry entry))))
(defun default-entry-p (dispatch-entry)
(zerop (length (binary-name dispatch-entry))))
(defun directorize (namestring)
(concatenate 'string (string-right-trim "/" namestring) "/"))
(defun all-asdf-directories (root)
"Return a list of all ASDF files in the directory tree at ROOT."
(remove-duplicates
(mapcar #'directory-namestring
(directory (merge-pathnames "**/*.asd"
(pathname (directorize root)))))
:test #'string=))
(defun copy-file (input output &key (if-exists :supersede))
(with-open-file (input-stream input)
(with-open-file (output-stream output :direction :output
:if-exists if-exists)
(loop for char = (read-char input-stream nil)
while char do (write-char char output-stream)))))
(defun file-lines (file)
(with-open-file (stream file)
(loop for line = (read-line stream nil)
while line collect line)))
Cribbed from alexandria
(defun flatten (tree)
"Traverses the tree in order, collecting non-null leaves into a list."
(let (list)
(labels ((traverse (subtree)
(when subtree
(if (consp subtree)
(progn
(traverse (car subtree))
(traverse (cdr subtree)))
(push subtree list)))))
(traverse tree))
(nreverse list)))
| null | https://raw.githubusercontent.com/xach/buildapp/dd00f18938ccae0a9b406bfcfd882ad32abeb757/utils.lisp | lisp |
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
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.
utils.lisp
interoperability | Copyright ( c ) 2010 , All Rights Reserved
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package #:buildapp)
(defun get-args ()
#+sbcl 'sb-ext:*posix-argv*
#+ccl '(ccl::command-line-arguments))
(defmacro backtrace-as-list ()
#+sbcl '(sb-debug:backtrace-as-list)
#+ccl '(ccl::backtrace-as-list))
(defmacro quit (&optional (errno 0))
#+sbcl `(sb-ext:exit :code ,errno)
#+ccl `(ccl:quit ,errno))
(defmacro run-program (program args)
(let ((func #+sbcl 'sb-ext:run-program
#+ccl 'ccl:run-program)
(search #+sbcl '(:search t)))
`(,func ,program ,args
:input nil
:output *standard-output*
,@search)))
(defun native-namestring (namestring)
(let ((p (pathname namestring)))
#+sbcl (sb-ext:native-namestring p)
#+ccl (ccl:native-translated-namestring p)))
(defparameter *alphabet*
(concatenate 'string
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
(defun random-string (length)
"Return a random string with LENGTH characters."
(let ((string (make-string length)))
(map-into string (lambda (char)
(declare (ignore char))
(aref *alphabet* (random (length *alphabet*))))
string)))
(defun call-with-temporary-open-file (template fun &rest open-args
&key element-type external-format)
"Call FUN with two arguments: an open output stream and a file
name. When it returns, the file is deleted. TEMPLATE should be a
pathname that can be used as a basis for the temporary file's
location."
(declare (ignorable element-type external-format))
(flet ((new-name ()
(make-pathname :name (concatenate 'string
(pathname-name template)
"-"
(random-string 8))
:defaults template)))
(let (try stream)
(tagbody
:retry
(setf try (new-name))
(unwind-protect
(progn
(setf stream (apply #'open try
:if-exists nil
:direction :output
open-args))
(unless stream
(go :retry))
(funcall fun stream try))
(when stream
(close stream)
(ignore-errors (delete-file try))))))))
(defmacro with-tempfile ((stream (template file) &rest open-args) &body body)
`(call-with-temporary-open-file ,template
(lambda (,stream ,file)
,@body)
,@open-args))
(defclass pseudosymbol ()
((package-string
:initarg :package-string
:accessor package-string)
(symbol-string
:initarg :symbol-string
:accessor symbol-string)))
(defmethod print-object ((pseudosymbol pseudosymbol) stream)
(format stream "~A::~A"
(package-string pseudosymbol)
(symbol-string pseudosymbol)))
(defun make-pseudosymbol (string)
(let* ((package-start 0)
(package-end (position #\: string))
(symbol-start (and package-end (position #\: string
:start package-end
:test-not #'eql)))
(package (if package-end
(subseq string package-start package-end)
"cl-user"))
(symbol (if symbol-start
(subseq string symbol-start)
string)))
(make-instance 'pseudosymbol
:package-string package
:symbol-string symbol)))
(defclass dispatched-entry ()
((binary-name
:initarg :binary-name
:accessor binary-name
:initform nil)
(entry
:initarg :entry
:accessor entry
:initform ""))
(:documentation "A dispatched entry is used to select an entry point
depending on the name of the binary that invoked the application. If
the binary name is empty, it is considered the default entry if no
match is found."))
(defmethod print-object ((dispatched-entry dispatched-entry) stream)
(print-unreadable-object (dispatched-entry stream :type t)
(format stream "~A/~A"
(binary-name dispatched-entry)
(entry dispatched-entry))))
(define-condition malformed-dispatch-entry (error) ())
(defun make-dispatched-entry (string)
(let ((slash (position #\/ string)))
(unless slash
(error 'malformed-dispatch-entry))
(let ((binary-name (subseq string 0 slash))
(entry (make-pseudosymbol (subseq string (1+ slash)))))
(make-instance 'dispatched-entry
:binary-name binary-name
:entry entry))))
(defun default-entry-p (dispatch-entry)
(zerop (length (binary-name dispatch-entry))))
(defun directorize (namestring)
(concatenate 'string (string-right-trim "/" namestring) "/"))
(defun all-asdf-directories (root)
"Return a list of all ASDF files in the directory tree at ROOT."
(remove-duplicates
(mapcar #'directory-namestring
(directory (merge-pathnames "**/*.asd"
(pathname (directorize root)))))
:test #'string=))
(defun copy-file (input output &key (if-exists :supersede))
(with-open-file (input-stream input)
(with-open-file (output-stream output :direction :output
:if-exists if-exists)
(loop for char = (read-char input-stream nil)
while char do (write-char char output-stream)))))
(defun file-lines (file)
(with-open-file (stream file)
(loop for line = (read-line stream nil)
while line collect line)))
Cribbed from alexandria
(defun flatten (tree)
"Traverses the tree in order, collecting non-null leaves into a list."
(let (list)
(labels ((traverse (subtree)
(when subtree
(if (consp subtree)
(progn
(traverse (car subtree))
(traverse (cdr subtree)))
(push subtree list)))))
(traverse tree))
(nreverse list)))
|
9a1fc5945c41af0f582d677e964303f7f167df37a8449a3584863c70cbb5a391 | mrphlip/aoc | 11.hs | # OPTIONS_GHC -Wno - tabs #
import Data.Array
import Data.Ix
import Data.List
import Control.Exception
import Utils
data Cell = Floor | Empty | Filled deriving (Eq, Show, Read)
type Point = (Integer, Integer)
type FloorPlan = Array Point Cell
getInput :: IO FloorPlan
getInput = do
dat <- readFile "11.txt"
return $ readMaze dat
readCell :: Char -> Cell
readCell '.' = Floor
readCell 'L' = Empty
readCell '#' = Filled
readMaze :: String -> FloorPlan
readMaze s = array bounds cells
where
width = genericLength $ head rows
height = genericLength rows
bounds = ((0, 0), (width-1, height-1))
rows = lines s
cells = [ ((x,y), readCell c) | (y, row) <- enumerate $ rows, (x, c) <- enumerate row ]
neighboursA :: FloorPlan -> Point -> [Point]
neighboursA plan (x, y) = [ (x + dx, y + dy) |
dx <- [-1, 0, 1],
dy <- [-1, 0, 1],
dx /= 0 || dy /= 0,
inRange mapbounds (x + dx, y + dy)]
where
mapbounds = bounds plan
neighboursB :: FloorPlan -> Point -> [Point]
neighboursB plan p = [ p' |
dx <- [-1, 0, 1],
dy <- [-1, 0, 1],
dx /= 0 || dy /= 0,
p' <- findNeighbour p dx dy]
where
mapbounds = bounds plan
findNeighbour (x, y) dx dy
| not $ inRange mapbounds p' = []
| plan ! p' == Floor = findNeighbour p' dx dy
| otherwise = [p']
where p' = (x + dx, y + dy)
iterateFunc :: (FloorPlan -> Point -> [Point]) -> (Int -> Bool) -> (Int -> Bool) -> FloorPlan -> FloorPlan
iterateFunc neighbours becomeFilled becomeEmpty fromstate = listArray mapbounds $ map newState $ range mapbounds
where
mapbounds = bounds fromstate
countNeighbours p = length $ filter (==Filled) $ map (fromstate!) $ neighbours fromstate p
newState p = case fromstate ! p of
Floor -> Floor
Empty -> if becomeFilled $ countNeighbours p then Filled else Empty
Filled -> if becomeEmpty $ countNeighbours p then Empty else Filled
iterateA :: FloorPlan -> FloorPlan
iterateA = iterateFunc neighboursA (==0) (>=4)
iterateB :: FloorPlan -> FloorPlan
iterateB = iterateFunc neighboursB (==0) (>=5)
findStable :: (Eq a) => (a -> a) -> a -> a
findStable f x
| x == x' = x
| otherwise = findStable f x'
where x' = f x
findStableA :: FloorPlan -> FloorPlan
findStableA = findStable iterateA
findStableB :: FloorPlan -> FloorPlan
findStableB = findStable iterateB
countFilled :: FloorPlan -> Integer
countFilled = genericLength . filter (==Filled) . elems
tests = do
check $ countFilled (findStableA testdat) == 37
check $ countFilled (findStableB testdat) == 26
where
testdat = readMaze "L.LL.LL.LL\nLLLLLLL.LL\nL.L.L..L..\nLLLL.LL.LL\nL.LL.LL.LL\nL.LLLLL.LL\n..L.L.....\nLLLLLLLLLL\nL.LLLLLL.L\nL.LLLLL.LL"
check True = return ()
check False = throwIO $ AssertionFailed "test failed"
main = do
plan <- getInput
print $ countFilled $ findStableA plan
print $ countFilled $ findStableB plan
| null | https://raw.githubusercontent.com/mrphlip/aoc/06395681eb6b50b838cd4561b2e0aa772aca570a/2020/11.hs | haskell | # OPTIONS_GHC -Wno - tabs #
import Data.Array
import Data.Ix
import Data.List
import Control.Exception
import Utils
data Cell = Floor | Empty | Filled deriving (Eq, Show, Read)
type Point = (Integer, Integer)
type FloorPlan = Array Point Cell
getInput :: IO FloorPlan
getInput = do
dat <- readFile "11.txt"
return $ readMaze dat
readCell :: Char -> Cell
readCell '.' = Floor
readCell 'L' = Empty
readCell '#' = Filled
readMaze :: String -> FloorPlan
readMaze s = array bounds cells
where
width = genericLength $ head rows
height = genericLength rows
bounds = ((0, 0), (width-1, height-1))
rows = lines s
cells = [ ((x,y), readCell c) | (y, row) <- enumerate $ rows, (x, c) <- enumerate row ]
neighboursA :: FloorPlan -> Point -> [Point]
neighboursA plan (x, y) = [ (x + dx, y + dy) |
dx <- [-1, 0, 1],
dy <- [-1, 0, 1],
dx /= 0 || dy /= 0,
inRange mapbounds (x + dx, y + dy)]
where
mapbounds = bounds plan
neighboursB :: FloorPlan -> Point -> [Point]
neighboursB plan p = [ p' |
dx <- [-1, 0, 1],
dy <- [-1, 0, 1],
dx /= 0 || dy /= 0,
p' <- findNeighbour p dx dy]
where
mapbounds = bounds plan
findNeighbour (x, y) dx dy
| not $ inRange mapbounds p' = []
| plan ! p' == Floor = findNeighbour p' dx dy
| otherwise = [p']
where p' = (x + dx, y + dy)
iterateFunc :: (FloorPlan -> Point -> [Point]) -> (Int -> Bool) -> (Int -> Bool) -> FloorPlan -> FloorPlan
iterateFunc neighbours becomeFilled becomeEmpty fromstate = listArray mapbounds $ map newState $ range mapbounds
where
mapbounds = bounds fromstate
countNeighbours p = length $ filter (==Filled) $ map (fromstate!) $ neighbours fromstate p
newState p = case fromstate ! p of
Floor -> Floor
Empty -> if becomeFilled $ countNeighbours p then Filled else Empty
Filled -> if becomeEmpty $ countNeighbours p then Empty else Filled
iterateA :: FloorPlan -> FloorPlan
iterateA = iterateFunc neighboursA (==0) (>=4)
iterateB :: FloorPlan -> FloorPlan
iterateB = iterateFunc neighboursB (==0) (>=5)
findStable :: (Eq a) => (a -> a) -> a -> a
findStable f x
| x == x' = x
| otherwise = findStable f x'
where x' = f x
findStableA :: FloorPlan -> FloorPlan
findStableA = findStable iterateA
findStableB :: FloorPlan -> FloorPlan
findStableB = findStable iterateB
countFilled :: FloorPlan -> Integer
countFilled = genericLength . filter (==Filled) . elems
tests = do
check $ countFilled (findStableA testdat) == 37
check $ countFilled (findStableB testdat) == 26
where
testdat = readMaze "L.LL.LL.LL\nLLLLLLL.LL\nL.L.L..L..\nLLLL.LL.LL\nL.LL.LL.LL\nL.LLLLL.LL\n..L.L.....\nLLLLLLLLLL\nL.LLLLLL.L\nL.LLLLL.LL"
check True = return ()
check False = throwIO $ AssertionFailed "test failed"
main = do
plan <- getInput
print $ countFilled $ findStableA plan
print $ countFilled $ findStableB plan
| |
530617a9a77116d1a35fe96e3ccc986a3b7fa606b456b011bad06264df58be96 | MastodonC/kixi.hecuba | download.clj | (ns kixi.hecuba.data.measurements.download
(:require [clj-time.coerce :as tc]
[clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojure.tools.logging :as log]
[kixi.hecuba.data.calculate :as calculate]
[kixi.hecuba.data.measurements :as measurements]
[kixi.hecuba.data.measurements.core :refer (headers-in-order extract-columns-in-order)]
[kixi.hecuba.storage.db :as db]
[kixi.hecuba.storage.uuid :refer (uuid)]
[kixi.hecuba.time :as time]
[kixi.hecuba.api :as api]
[kixipipe.ioplus :as ioplus]
[kixipipe.storage.s3 :as s3]
[qbits.hayt :as hayt]
[clj-time.core :as t]
[clj-time.coerce :as tc]
[kixi.hecuba.data.measurements.core :refer (write-status)]))
(defn- relocate-customer-ref [m]
(-> m
(dissoc :metadata)
(assoc :customer_ref (get-in m [:metadata :customer_ref]))))
(defn- relocate-location [m]
(assoc m :location (get-in m [:location :name])))
(defn mk-temp-directory! [prefix & [attrs]]
(java.nio.file.Files/createTempDirectory
prefix
(into-array java.nio.file.attribute.FileAttribute attrs)))
(defn- join-to-device [devices x]
(let [device_id (:device_id x)]
(merge (get devices device_id) x)))
(defn min-date-time [& ts]
TODO a Y3 K problem ?
(defn max-date-time [& ts]
(reduce (fn [t1 t2] (if (t/after? t1 t2) t1 t2)) (map (fnil tc/to-date-time (t/date-time 1970) ) ts)))
(defn- find-ts-range [xs]
(when (seq xs)
(let [tss (map (juxt :lower_ts :upper_ts) xs)]
(reduce (fn [[l1 u1] [l2 u2]] [(min-date-time l1 l2)
(max-date-time u1 u2)])
tss))))
(defn- get-devices-and-sensors-for [session entity_id]
(let [devices (->> (db/execute session (hayt/select :devices (hayt/where [[= :entity_id entity_id]])))
(map (fn [x] [(:id x) x]))
(into {}))
sensors (if (seq devices)
(db/execute session (hayt/select :sensors (hayt/where [[:in :device_id (keys devices)]])))
[])
sensor-metadata (if (seq sensors)
(db/execute session (hayt/select :sensor_metadata
(hayt/columns :lower_ts :upper_ts)
(hayt/where [[:in :device_id (keys devices)]]))))
device-and-type #(str (:device_id %) "-" (:type %))]
(with-meta (if (seq sensors)
(->> sensors
(map (partial join-to-device devices))
(sort-by device-and-type))
[])
{:ts-range (find-ts-range sensor-metadata)})))
(defn format-header [devices-and-sensors]
(->> devices-and-sensors
(map relocate-customer-ref)
(map relocate-location)
(map extract-columns-in-order)
(apply map vector)
(map #(apply vector %1 %2) headers-in-order)))
(defn get-header [store entity_id]
(db/with-session [session (:hecuba-session store)]
(->> entity_id
(get-devices-and-sensors-for session)
(format-header))))
(defn indexes-of [v xs]
(set (keep-indexed (fn [i x] (when (= x v) i)) xs)))
(defn measurements->columns [[{:keys [timestamp value]} & more]]
(apply vector timestamp value (map :value more)))
(defn filled-measurements [measurements out]
(let [sentinel (Object.)
is-sentinel? #(identical? % sentinel)
next-or-sentinel #(if-let [n (next %)] n [sentinel])
replace-empty (partial map (fn [x] (if (seq x) x [sentinel])))
next-row (fn [xs]
(when-let [row (first (apply map vector (replace-empty xs)))]
(when (not-every? is-sentinel? row)
row)))]
(loop [ms measurements]
(let [row (next-row ms)]
(when row
(let [row-timestamps (mapv #(time/db-to-iso (:timestamp %)) row)
row-timestamp (first (sort (remove nil? row-timestamps)))
data-indexes (indexes-of row-timestamp row-timestamps)
has-data? #(contains? data-indexes %)
out-row (map-indexed (fn [i x] (if (has-data? i)
(assoc x :timestamp row-timestamp)
(hash-map :timestamp row-timestamp :value nil))) row)
fns (map-indexed (fn [i _] (if (has-data? i) next-or-sentinel identity)) row)
step (fn [xs] (map (fn [f v] (f v)) fns xs))
cols (measurements->columns out-row)]
(csv/write-csv out [cols])
(recur (step ms))))))))
(defn generate-file [store item]
(let [{:keys [header data entity_id]} item
item (dissoc item :header :data)
tmpfile (ioplus/mk-temp-file! "hecuba" ".csv-download")
filename (str entity_id "_measurements.csv")
metadata {:timestamp (t/now)
:filename filename
:content-type "text/csv"
:content-disposition (str "attachment; filename=\"" filename "\"")}]
(try
(with-open [out (io/writer tmpfile)]
(csv/write-csv out header)
(filled-measurements data out))
(s3/store-file (:s3 store) (-> item
(assoc :dir (.getParent tmpfile)
:filename (.getName tmpfile)
:metadata metadata)))
(write-status store (assoc (-> item
(assoc :metadata metadata)) :status "SUCCESS"))
(catch Throwable t
(log/error t "failed")
(write-status store (assoc :status "FAILURE" :data (ex-data t))))
(finally (.delete tmpfile)))))
(defn download-item [store item]
(db/with-session [session (:hecuba-session store)]
(let [devices-and-sensors (get-devices-and-sensors-for session (:entity_id item))
formatted-header (format-header devices-and-sensors)
[lower upper] (:ts-range (meta devices-and-sensors))
{:keys [start-date
end-date] :or {start-date lower end-date upper}} item
measurements (map (fn [m]
(measurements/retrieve-measurements session
start-date
end-date
(:device_id m)
(:sensor_id m)))
devices-and-sensors)
uuid (uuid)]
(generate-file store
(-> item
(assoc :header formatted-header
:data measurements)))
item)))
| null | https://raw.githubusercontent.com/MastodonC/kixi.hecuba/467400bbe670e74420a2711f7d49e869ab2b3e21/src/clj/kixi/hecuba/data/measurements/download.clj | clojure | (ns kixi.hecuba.data.measurements.download
(:require [clj-time.coerce :as tc]
[clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojure.tools.logging :as log]
[kixi.hecuba.data.calculate :as calculate]
[kixi.hecuba.data.measurements :as measurements]
[kixi.hecuba.data.measurements.core :refer (headers-in-order extract-columns-in-order)]
[kixi.hecuba.storage.db :as db]
[kixi.hecuba.storage.uuid :refer (uuid)]
[kixi.hecuba.time :as time]
[kixi.hecuba.api :as api]
[kixipipe.ioplus :as ioplus]
[kixipipe.storage.s3 :as s3]
[qbits.hayt :as hayt]
[clj-time.core :as t]
[clj-time.coerce :as tc]
[kixi.hecuba.data.measurements.core :refer (write-status)]))
(defn- relocate-customer-ref [m]
(-> m
(dissoc :metadata)
(assoc :customer_ref (get-in m [:metadata :customer_ref]))))
(defn- relocate-location [m]
(assoc m :location (get-in m [:location :name])))
(defn mk-temp-directory! [prefix & [attrs]]
(java.nio.file.Files/createTempDirectory
prefix
(into-array java.nio.file.attribute.FileAttribute attrs)))
(defn- join-to-device [devices x]
(let [device_id (:device_id x)]
(merge (get devices device_id) x)))
(defn min-date-time [& ts]
TODO a Y3 K problem ?
(defn max-date-time [& ts]
(reduce (fn [t1 t2] (if (t/after? t1 t2) t1 t2)) (map (fnil tc/to-date-time (t/date-time 1970) ) ts)))
(defn- find-ts-range [xs]
(when (seq xs)
(let [tss (map (juxt :lower_ts :upper_ts) xs)]
(reduce (fn [[l1 u1] [l2 u2]] [(min-date-time l1 l2)
(max-date-time u1 u2)])
tss))))
(defn- get-devices-and-sensors-for [session entity_id]
(let [devices (->> (db/execute session (hayt/select :devices (hayt/where [[= :entity_id entity_id]])))
(map (fn [x] [(:id x) x]))
(into {}))
sensors (if (seq devices)
(db/execute session (hayt/select :sensors (hayt/where [[:in :device_id (keys devices)]])))
[])
sensor-metadata (if (seq sensors)
(db/execute session (hayt/select :sensor_metadata
(hayt/columns :lower_ts :upper_ts)
(hayt/where [[:in :device_id (keys devices)]]))))
device-and-type #(str (:device_id %) "-" (:type %))]
(with-meta (if (seq sensors)
(->> sensors
(map (partial join-to-device devices))
(sort-by device-and-type))
[])
{:ts-range (find-ts-range sensor-metadata)})))
(defn format-header [devices-and-sensors]
(->> devices-and-sensors
(map relocate-customer-ref)
(map relocate-location)
(map extract-columns-in-order)
(apply map vector)
(map #(apply vector %1 %2) headers-in-order)))
(defn get-header [store entity_id]
(db/with-session [session (:hecuba-session store)]
(->> entity_id
(get-devices-and-sensors-for session)
(format-header))))
(defn indexes-of [v xs]
(set (keep-indexed (fn [i x] (when (= x v) i)) xs)))
(defn measurements->columns [[{:keys [timestamp value]} & more]]
(apply vector timestamp value (map :value more)))
(defn filled-measurements [measurements out]
(let [sentinel (Object.)
is-sentinel? #(identical? % sentinel)
next-or-sentinel #(if-let [n (next %)] n [sentinel])
replace-empty (partial map (fn [x] (if (seq x) x [sentinel])))
next-row (fn [xs]
(when-let [row (first (apply map vector (replace-empty xs)))]
(when (not-every? is-sentinel? row)
row)))]
(loop [ms measurements]
(let [row (next-row ms)]
(when row
(let [row-timestamps (mapv #(time/db-to-iso (:timestamp %)) row)
row-timestamp (first (sort (remove nil? row-timestamps)))
data-indexes (indexes-of row-timestamp row-timestamps)
has-data? #(contains? data-indexes %)
out-row (map-indexed (fn [i x] (if (has-data? i)
(assoc x :timestamp row-timestamp)
(hash-map :timestamp row-timestamp :value nil))) row)
fns (map-indexed (fn [i _] (if (has-data? i) next-or-sentinel identity)) row)
step (fn [xs] (map (fn [f v] (f v)) fns xs))
cols (measurements->columns out-row)]
(csv/write-csv out [cols])
(recur (step ms))))))))
(defn generate-file [store item]
(let [{:keys [header data entity_id]} item
item (dissoc item :header :data)
tmpfile (ioplus/mk-temp-file! "hecuba" ".csv-download")
filename (str entity_id "_measurements.csv")
metadata {:timestamp (t/now)
:filename filename
:content-type "text/csv"
:content-disposition (str "attachment; filename=\"" filename "\"")}]
(try
(with-open [out (io/writer tmpfile)]
(csv/write-csv out header)
(filled-measurements data out))
(s3/store-file (:s3 store) (-> item
(assoc :dir (.getParent tmpfile)
:filename (.getName tmpfile)
:metadata metadata)))
(write-status store (assoc (-> item
(assoc :metadata metadata)) :status "SUCCESS"))
(catch Throwable t
(log/error t "failed")
(write-status store (assoc :status "FAILURE" :data (ex-data t))))
(finally (.delete tmpfile)))))
(defn download-item [store item]
(db/with-session [session (:hecuba-session store)]
(let [devices-and-sensors (get-devices-and-sensors-for session (:entity_id item))
formatted-header (format-header devices-and-sensors)
[lower upper] (:ts-range (meta devices-and-sensors))
{:keys [start-date
end-date] :or {start-date lower end-date upper}} item
measurements (map (fn [m]
(measurements/retrieve-measurements session
start-date
end-date
(:device_id m)
(:sensor_id m)))
devices-and-sensors)
uuid (uuid)]
(generate-file store
(-> item
(assoc :header formatted-header
:data measurements)))
item)))
| |
fd4b42d373335e9c79432b2941217002bedb4f579ea804aeb3689c5df44684cd | patricoferris/ocaml-multicore-monorepo | caqti_driver_mariadb.mli | Copyright ( C ) 2017 < >
*
* This library is free software ; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or ( at your
* option ) any later version , with the OCaml static compilation exception .
*
* This library is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public
* License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library . If not , see < / > .
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version, with the OCaml static compilation exception.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see </>.
*)
* Caqti driver for MariaDB ( bindings ) .
This driver is implemented in terms of the mariadb OPAM package .
It handles URIs of the form
{ [
mariadb://<user>:<password>@<host>:<port>/?socket=<socket >
] }
where components are optional and present ones are passed on to the
correspondingly named arguments to the [ connect ] function of MariaDB .
This driver is implemented in terms of the mariadb OPAM package.
It handles URIs of the form
{[
mariadb://<user>:<password>@<host>:<port>/?socket=<socket>
]}
where components are optional and present ones are passed on to the
correspondingly named arguments to the [connect] function of MariaDB. *)
| null | https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/22b441e6727bc303950b3b37c8fbc024c748fe55/duniverse/ocaml-caqti/lib-driver/caqti_driver_mariadb.mli | ocaml | Copyright ( C ) 2017 < >
*
* This library is free software ; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or ( at your
* option ) any later version , with the OCaml static compilation exception .
*
* This library is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public
* License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library . If not , see < / > .
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version, with the OCaml static compilation exception.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see </>.
*)
* Caqti driver for MariaDB ( bindings ) .
This driver is implemented in terms of the mariadb OPAM package .
It handles URIs of the form
{ [
mariadb://<user>:<password>@<host>:<port>/?socket=<socket >
] }
where components are optional and present ones are passed on to the
correspondingly named arguments to the [ connect ] function of MariaDB .
This driver is implemented in terms of the mariadb OPAM package.
It handles URIs of the form
{[
mariadb://<user>:<password>@<host>:<port>/?socket=<socket>
]}
where components are optional and present ones are passed on to the
correspondingly named arguments to the [connect] function of MariaDB. *)
| |
4108efd52874b8f41ab61f0163aca1c2f07f9d81d30dcb22c70fecd73150ebce | coq/coq | tac2quote.mli | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
open Names
open Tac2dyn
open Tac2qexpr
open Tac2expr
* Syntactic quoting of expressions .
* Contrarily to Tac2ffi , which lives on the semantic level , this module
manipulates pure syntax of Ltac2 . Its main purpose is to write notations .
manipulates pure syntax of Ltac2. Its main purpose is to write notations. *)
val constructor : ?loc:Loc.t -> ltac_constructor -> raw_tacexpr list -> raw_tacexpr
val thunk : raw_tacexpr -> raw_tacexpr
val of_anti : ('a -> raw_tacexpr) -> 'a or_anti -> raw_tacexpr
val of_int : int CAst.t -> raw_tacexpr
val of_pair : ('a -> raw_tacexpr) -> ('b -> raw_tacexpr) -> ('a * 'b) CAst.t -> raw_tacexpr
val of_tuple : ?loc:Loc.t -> raw_tacexpr list -> raw_tacexpr
val of_variable : Id.t CAst.t -> raw_tacexpr
val of_ident : Id.t CAst.t -> raw_tacexpr
val of_constr : ?delimiters:Id.t list -> Constrexpr.constr_expr -> raw_tacexpr
val of_open_constr : ?delimiters:Id.t list -> Constrexpr.constr_expr -> raw_tacexpr
val of_preterm : ?delimiters:Id.t list -> Constrexpr.constr_expr -> raw_tacexpr
val of_list : ?loc:Loc.t -> ('a -> raw_tacexpr) -> 'a list -> raw_tacexpr
val array_of_list : ?loc:Loc.t -> raw_tacexpr -> raw_tacexpr
val of_bindings : bindings -> raw_tacexpr
val of_intro_pattern : intro_pattern -> raw_tacexpr
val of_intro_patterns : intro_pattern list CAst.t -> raw_tacexpr
val of_clause : clause -> raw_tacexpr
val of_destruction_arg : destruction_arg -> raw_tacexpr
val of_induction_clause : induction_clause -> raw_tacexpr
val of_conversion : conversion -> raw_tacexpr
val of_rewriting : rewriting -> raw_tacexpr
val of_occurrences : occurrences -> raw_tacexpr
val of_hintdb : hintdb -> raw_tacexpr
val of_move_location : move_location -> raw_tacexpr
val of_reference : reference or_anti -> raw_tacexpr
val of_hyp : ?loc:Loc.t -> Id.t CAst.t -> raw_tacexpr
(** id ↦ 'Control.hyp @id' *)
val of_exact_hyp : ?loc:Loc.t -> Id.t CAst.t -> raw_tacexpr
(** id ↦ 'Control.refine (fun () => Control.hyp @id') *)
val of_exact_var : ?loc:Loc.t -> Id.t CAst.t -> raw_tacexpr
(** id ↦ 'Control.refine (fun () => Control.hyp @id') *)
val of_dispatch : dispatch -> raw_tacexpr
val of_strategy_flag : strategy_flag -> raw_tacexpr
val of_pose : pose -> raw_tacexpr
val of_assertion : assertion -> raw_tacexpr
val of_constr_matching : constr_matching -> raw_tacexpr
val of_goal_matching : goal_matching -> raw_tacexpr
val of_format : lstring -> raw_tacexpr
* { 5 Generic arguments }
val wit_pattern : (Constrexpr.constr_expr, Pattern.constr_pattern) Arg.tag
val wit_ident : (Id.t, Id.t) Arg.tag
val wit_reference : (reference, GlobRef.t) Arg.tag
val wit_constr : (Constrexpr.constr_expr, Glob_term.glob_constr) Arg.tag
val wit_open_constr : (Constrexpr.constr_expr, Glob_term.glob_constr) Arg.tag
val wit_preterm : (Constrexpr.constr_expr, Id.Set.t * Glob_term.glob_constr) Arg.tag
val wit_ltac1 : (Id.t CAst.t list * Ltac_plugin.Tacexpr.raw_tactic_expr, Id.t list * Ltac_plugin.Tacexpr.glob_tactic_expr) Arg.tag
* Ltac1 AST quotation , seen as a ' tactic ' . Its type is unit in Ltac2 .
val wit_ltac1val : (Id.t CAst.t list * Ltac_plugin.Tacexpr.raw_tactic_expr, Id.t list * Ltac_plugin.Tacexpr.glob_tactic_expr) Arg.tag
* Ltac1 AST quotation , seen as a value - returning expression , with type Ltac1.t .
| null | https://raw.githubusercontent.com/coq/coq/e2952d535b9391fd37340aad5188b28cf83308d8/plugins/ltac2/tac2quote.mli | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
**********************************************************************
* id ↦ 'Control.hyp @id'
* id ↦ 'Control.refine (fun () => Control.hyp @id')
* id ↦ 'Control.refine (fun () => Control.hyp @id') | v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
open Names
open Tac2dyn
open Tac2qexpr
open Tac2expr
* Syntactic quoting of expressions .
* Contrarily to Tac2ffi , which lives on the semantic level , this module
manipulates pure syntax of Ltac2 . Its main purpose is to write notations .
manipulates pure syntax of Ltac2. Its main purpose is to write notations. *)
val constructor : ?loc:Loc.t -> ltac_constructor -> raw_tacexpr list -> raw_tacexpr
val thunk : raw_tacexpr -> raw_tacexpr
val of_anti : ('a -> raw_tacexpr) -> 'a or_anti -> raw_tacexpr
val of_int : int CAst.t -> raw_tacexpr
val of_pair : ('a -> raw_tacexpr) -> ('b -> raw_tacexpr) -> ('a * 'b) CAst.t -> raw_tacexpr
val of_tuple : ?loc:Loc.t -> raw_tacexpr list -> raw_tacexpr
val of_variable : Id.t CAst.t -> raw_tacexpr
val of_ident : Id.t CAst.t -> raw_tacexpr
val of_constr : ?delimiters:Id.t list -> Constrexpr.constr_expr -> raw_tacexpr
val of_open_constr : ?delimiters:Id.t list -> Constrexpr.constr_expr -> raw_tacexpr
val of_preterm : ?delimiters:Id.t list -> Constrexpr.constr_expr -> raw_tacexpr
val of_list : ?loc:Loc.t -> ('a -> raw_tacexpr) -> 'a list -> raw_tacexpr
val array_of_list : ?loc:Loc.t -> raw_tacexpr -> raw_tacexpr
val of_bindings : bindings -> raw_tacexpr
val of_intro_pattern : intro_pattern -> raw_tacexpr
val of_intro_patterns : intro_pattern list CAst.t -> raw_tacexpr
val of_clause : clause -> raw_tacexpr
val of_destruction_arg : destruction_arg -> raw_tacexpr
val of_induction_clause : induction_clause -> raw_tacexpr
val of_conversion : conversion -> raw_tacexpr
val of_rewriting : rewriting -> raw_tacexpr
val of_occurrences : occurrences -> raw_tacexpr
val of_hintdb : hintdb -> raw_tacexpr
val of_move_location : move_location -> raw_tacexpr
val of_reference : reference or_anti -> raw_tacexpr
val of_hyp : ?loc:Loc.t -> Id.t CAst.t -> raw_tacexpr
val of_exact_hyp : ?loc:Loc.t -> Id.t CAst.t -> raw_tacexpr
val of_exact_var : ?loc:Loc.t -> Id.t CAst.t -> raw_tacexpr
val of_dispatch : dispatch -> raw_tacexpr
val of_strategy_flag : strategy_flag -> raw_tacexpr
val of_pose : pose -> raw_tacexpr
val of_assertion : assertion -> raw_tacexpr
val of_constr_matching : constr_matching -> raw_tacexpr
val of_goal_matching : goal_matching -> raw_tacexpr
val of_format : lstring -> raw_tacexpr
* { 5 Generic arguments }
val wit_pattern : (Constrexpr.constr_expr, Pattern.constr_pattern) Arg.tag
val wit_ident : (Id.t, Id.t) Arg.tag
val wit_reference : (reference, GlobRef.t) Arg.tag
val wit_constr : (Constrexpr.constr_expr, Glob_term.glob_constr) Arg.tag
val wit_open_constr : (Constrexpr.constr_expr, Glob_term.glob_constr) Arg.tag
val wit_preterm : (Constrexpr.constr_expr, Id.Set.t * Glob_term.glob_constr) Arg.tag
val wit_ltac1 : (Id.t CAst.t list * Ltac_plugin.Tacexpr.raw_tactic_expr, Id.t list * Ltac_plugin.Tacexpr.glob_tactic_expr) Arg.tag
* Ltac1 AST quotation , seen as a ' tactic ' . Its type is unit in Ltac2 .
val wit_ltac1val : (Id.t CAst.t list * Ltac_plugin.Tacexpr.raw_tactic_expr, Id.t list * Ltac_plugin.Tacexpr.glob_tactic_expr) Arg.tag
* Ltac1 AST quotation , seen as a value - returning expression , with type Ltac1.t .
|
0fc70aca6a0b8cd42007f14482f05d08f17e64083ca74634853918cd16771147 | vernemq/vernemq_dev | on_subscribe_m5_hook.erl | %% @hidden
-module(on_subscribe_m5_hook).
-include("vernemq_dev.hrl").
%% called as an 'all'-hook, return value is ignored
-callback on_subscribe_m5(UserName :: username(),
SubscriberId :: subscriber_id(),
Topics :: [{Topic :: topic(), SubInfo :: subinfo()}],
Props :: properties()) -> any().
| null | https://raw.githubusercontent.com/vernemq/vernemq_dev/6d622aa8c901ae7777433aef2bd049e380c474a6/src/on_subscribe_m5_hook.erl | erlang | @hidden
called as an 'all'-hook, return value is ignored | -module(on_subscribe_m5_hook).
-include("vernemq_dev.hrl").
-callback on_subscribe_m5(UserName :: username(),
SubscriberId :: subscriber_id(),
Topics :: [{Topic :: topic(), SubInfo :: subinfo()}],
Props :: properties()) -> any().
|
bd507cab98ea62b028e712981edc3732e2b87c80284a852bfaa5303d9085703a | incoherentsoftware/defect-process | Id.hs | module Id
( HashedId(..)
, Id(NullId)
, newId
, hashId
) where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Unique (Unique, hashUnique, newUnique)
newtype HashedId = HashedId {_int :: Int}
deriving (Eq, Ord, Show)
data Id a
= Id Unique
| NullId
deriving (Eq, Ord)
instance Show (Id a) where
show :: Id a -> String
show (Id u) = show $ hashUnique u
show NullId = "null"
newId :: MonadIO m => m (Id a)
newId = Id <$> liftIO newUnique
implementation specific for Data . Unique , assumes newUnique starts at 1
hashId :: Id a -> HashedId
hashId (Id uniq) = HashedId $ hashUnique uniq
hashId NullId = HashedId 0
| null | https://raw.githubusercontent.com/incoherentsoftware/defect-process/15f2569e7d0e481c2e28c0ca3a5e72d2c049b667/src/Id.hs | haskell | module Id
( HashedId(..)
, Id(NullId)
, newId
, hashId
) where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Unique (Unique, hashUnique, newUnique)
newtype HashedId = HashedId {_int :: Int}
deriving (Eq, Ord, Show)
data Id a
= Id Unique
| NullId
deriving (Eq, Ord)
instance Show (Id a) where
show :: Id a -> String
show (Id u) = show $ hashUnique u
show NullId = "null"
newId :: MonadIO m => m (Id a)
newId = Id <$> liftIO newUnique
implementation specific for Data . Unique , assumes newUnique starts at 1
hashId :: Id a -> HashedId
hashId (Id uniq) = HashedId $ hashUnique uniq
hashId NullId = HashedId 0
| |
e8205dbab8354cf73eaa7f954d3fd91e72b0c2c45b89f820be6177612bd651cf | OCamlPro/ocamlexc | printmod.mli | (***********************************************************************)
(* *)
(* Ocamlexc *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1998 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
val pp_module_type: Format.formatter -> Typedtree.module_type -> unit
val pp_signature: Format.formatter -> Typedtree.signature_item list -> unit
val pp_toplevel_toplevel: Format.formatter ->
Typedtree.toplevel_phrase * Typedtree.signature_item list -> unit
| null | https://raw.githubusercontent.com/OCamlPro/ocamlexc/a9ddcfff6f376f5dd6c5fcc3211b8f89e36f79fe/typing/printmod.mli | ocaml | *********************************************************************
Ocamlexc
********************************************************************* | , projet Cristal , INRIA Rocquencourt
Copyright 1998 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
val pp_module_type: Format.formatter -> Typedtree.module_type -> unit
val pp_signature: Format.formatter -> Typedtree.signature_item list -> unit
val pp_toplevel_toplevel: Format.formatter ->
Typedtree.toplevel_phrase * Typedtree.signature_item list -> unit
|
72b131275b9231f3387d358b3059d1d164aa1d4e8faef19a45ba1f78b50049c8 | gadfly361/rid3 | b03_add_element_on_top.cljs | (ns rid3.b03-add-element-on-top
(:require
[reagent.core :as reagent]
[rid3.core :as rid3 :refer [rid3->]]
[rid3.basics-util :as util]
))
(def cursor-key :b03-add-element-on-top)
(def height 100)
(def width 100)
(defn example [app-state]
(let [viz-ratom (reagent/cursor app-state [cursor-key])]
(fn [app-state]
[:div
[:h4 "3) Add an element on top of another element: a circle on a rect"]
[util/link-source (name cursor-key)]
[rid3/viz
{:id "b03"
:ratom viz-ratom
:svg {:did-mount (fn [node ratom]
(rid3-> node
{:height height
:width width}))}
:pieces
[{:kind :elem
:class "some-element"
:tag "rect"
:did-mount (fn [node ratom]
(rid3-> node
{:x 0
:y 0
:height height
:width width
:fill "lightgrey"}))}
;; You can add any number of elements. They are added in
;; order, which means this circle overlaid on top of the
;; rect above."
{:kind :elem
:class "some-element-on-top"
:tag "circle"
:did-mount (fn [node ratom]
(rid3-> node
{:cx (/ width 2)
:cy (/ height 2)
:r 20
:fill "green"}))}
]}]])))
| null | https://raw.githubusercontent.com/gadfly361/rid3/cae79fdbee3b5aba45e29b589425f9a17ef8613b/src/basics/rid3/b03_add_element_on_top.cljs | clojure | You can add any number of elements. They are added in
order, which means this circle overlaid on top of the
rect above." | (ns rid3.b03-add-element-on-top
(:require
[reagent.core :as reagent]
[rid3.core :as rid3 :refer [rid3->]]
[rid3.basics-util :as util]
))
(def cursor-key :b03-add-element-on-top)
(def height 100)
(def width 100)
(defn example [app-state]
(let [viz-ratom (reagent/cursor app-state [cursor-key])]
(fn [app-state]
[:div
[:h4 "3) Add an element on top of another element: a circle on a rect"]
[util/link-source (name cursor-key)]
[rid3/viz
{:id "b03"
:ratom viz-ratom
:svg {:did-mount (fn [node ratom]
(rid3-> node
{:height height
:width width}))}
:pieces
[{:kind :elem
:class "some-element"
:tag "rect"
:did-mount (fn [node ratom]
(rid3-> node
{:x 0
:y 0
:height height
:width width
:fill "lightgrey"}))}
{:kind :elem
:class "some-element-on-top"
:tag "circle"
:did-mount (fn [node ratom]
(rid3-> node
{:cx (/ width 2)
:cy (/ height 2)
:r 20
:fill "green"}))}
]}]])))
|
fc8987aad4e57ae664412b519ef750c1dd6a6d08caead8d2b9192fea9f3155f3 | modular-macros/ocaml-macros | t101-poptrap.ml | open Lib;;
try ()
with _ -> ()
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 PUSHTRAP 15
11 CONST0
12 POPTRAP
13 BRANCH 18
15 PUSHCONST0
16 POP 1
18 ATOM0
19 SETGLOBAL T101 - poptrap
21 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 PUSHTRAP 15
11 CONST0
12 POPTRAP
13 BRANCH 18
15 PUSHCONST0
16 POP 1
18 ATOM0
19 SETGLOBAL T101-poptrap
21 STOP
**)
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/testsuite/tests/tool-ocaml/t101-poptrap.ml | ocaml | open Lib;;
try ()
with _ -> ()
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 PUSHTRAP 15
11 CONST0
12 POPTRAP
13 BRANCH 18
15 PUSHCONST0
16 POP 1
18 ATOM0
19 SETGLOBAL T101 - poptrap
21 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 PUSHTRAP 15
11 CONST0
12 POPTRAP
13 BRANCH 18
15 PUSHCONST0
16 POP 1
18 ATOM0
19 SETGLOBAL T101-poptrap
21 STOP
**)
| |
56c77030b016ed47972f25794e8498f14cecf1b25544bce92eb44ad82a58bc22 | threatgrid/ctia | data_table_test.clj | (ns ctia.entity.data-table-test
(:require [clj-momo.test-helpers.core :as mth]
[ctia.entity.data-table :as sut]
[clojure.test :refer [deftest join-fixtures use-fixtures]]
[ctia.test-helpers
[auth :refer [all-capabilities]]
[core :as helpers]
[crud :refer [entity-crud-test]]
[fake-whoami-service :as whoami-helpers]
[store :refer [test-for-each-store-with-app]]]
[ctim.schemas.common :as c]))
(use-fixtures :once (join-fixtures [mth/fixture-schema-validation
whoami-helpers/fixture-server]))
(def new-data-table
{:type "data-table"
:row_count 1
:external_ids ["-table/data-table-123"
"-table/data-table-456"]
:schema_version c/ctim-schema-version
:tlp "green"
:timestamp #inst "2016-02-11T00:40:48.212-00:00"
:columns [{:name "Column1"
:type "string"}
{:name "Column2"
:type "string"}]
:rows [["foo"] ["bar"]]
:valid_time {:start_time #inst "2016-02-11T00:40:48.212-00:00"
:end_time #inst "2016-07-11T00:40:48.212-00:00"}})
(deftest test-data-table-routes
(test-for-each-store-with-app
(fn [app]
(helpers/set-capabilities! app "foouser" ["foogroup"] "user" all-capabilities)
(whoami-helpers/set-whoami-response app
"45c1f5e3f05d0"
"foouser"
"foogroup"
"user")
(entity-crud-test
(into sut/data-table-entity
{:app app
:example new-data-table
:invalid-tests? false
:update-tests? false
:search-tests? false
:delete-search-tests? false
:headers {:Authorization "45c1f5e3f05d0"}})))))
| null | https://raw.githubusercontent.com/threatgrid/ctia/32857663cdd7ac385161103dbafa8dc4f98febf0/test/ctia/entity/data_table_test.clj | clojure | (ns ctia.entity.data-table-test
(:require [clj-momo.test-helpers.core :as mth]
[ctia.entity.data-table :as sut]
[clojure.test :refer [deftest join-fixtures use-fixtures]]
[ctia.test-helpers
[auth :refer [all-capabilities]]
[core :as helpers]
[crud :refer [entity-crud-test]]
[fake-whoami-service :as whoami-helpers]
[store :refer [test-for-each-store-with-app]]]
[ctim.schemas.common :as c]))
(use-fixtures :once (join-fixtures [mth/fixture-schema-validation
whoami-helpers/fixture-server]))
(def new-data-table
{:type "data-table"
:row_count 1
:external_ids ["-table/data-table-123"
"-table/data-table-456"]
:schema_version c/ctim-schema-version
:tlp "green"
:timestamp #inst "2016-02-11T00:40:48.212-00:00"
:columns [{:name "Column1"
:type "string"}
{:name "Column2"
:type "string"}]
:rows [["foo"] ["bar"]]
:valid_time {:start_time #inst "2016-02-11T00:40:48.212-00:00"
:end_time #inst "2016-07-11T00:40:48.212-00:00"}})
(deftest test-data-table-routes
(test-for-each-store-with-app
(fn [app]
(helpers/set-capabilities! app "foouser" ["foogroup"] "user" all-capabilities)
(whoami-helpers/set-whoami-response app
"45c1f5e3f05d0"
"foouser"
"foogroup"
"user")
(entity-crud-test
(into sut/data-table-entity
{:app app
:example new-data-table
:invalid-tests? false
:update-tests? false
:search-tests? false
:delete-search-tests? false
:headers {:Authorization "45c1f5e3f05d0"}})))))
| |
1c54d497a478821920366cc0764b88c507db76fef1f464ec4d61d6ff21ede841 | RefactoringTools/HaRe | Constructor.hs | module Constructor where
Should be able to rename AType to MyType , as they are in different name
-- spaces
data MyType = AType Int | YourType Bool
foo :: MyType -> Bool
foo (AType i) = i > 0
foo (YourType b) = b
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/testdata/Renaming/Constructor.hs | haskell | spaces | module Constructor where
Should be able to rename AType to MyType , as they are in different name
data MyType = AType Int | YourType Bool
foo :: MyType -> Bool
foo (AType i) = i > 0
foo (YourType b) = b
|
ea23b917c92642a2b0e085bdcf55db3eb5d5b992070df4960c4598420d9ecf4f | blacktaxi/inversion | Print.hs | {-# LANGUAGE GADTs #-}
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FlexibleInstances #
module Print
(ShowFingering (..)) where
import Data.List (delete, genericReplicate, sortBy)
import qualified Data.Map as M
import Text.Printf (printf, PrintfArg)
import Instrument
import Fingering
class ShowFingering b a where
showFingering :: Instrument b -> a -> String
showFingeredString :: (PrintfArg a) => GuitarString -> a -> FretNumber -> Maybe Fret -> String
showFingeredString string stringName fretCount fingering =
printf "%5s %s%s" stringName nut fretBoard
where
emptyBoard = concat $ genericReplicate fretCount "---|"
(nut, fretBoard) =
case fingering of
Nothing -> ("x", emptyBoard)
Just (Fret 0) -> ("O", emptyBoard)
Just (Fret fret) -> ("|", concat [if f == fret then "-O-|" else "---|" |
f <- [1 .. fretCount]])
showFretNumbers fretCount =
concat $ map (printf "%4d") [1 .. fretCount]
showNumberedBoard board fretCount =
unlines (board ++ [fretNumbers])
where fretNumbers = " " ++ (showFretNumbers fretCount)
instance (PrintfArg a) => ShowFingering a (StringFingering a) where
showFingering (Instrument strings fretCount) (StringFingering name fingering) =
showNumberedBoard ss fretCount
where
mutedString s n = showFingeredString s n fretCount Nothing
ss = [if n == name then showFingeredString s n fretCount (Just fingering)
else mutedString s n | (n, s) <- M.assocs strings]
instance (PrintfArg a) => ShowFingering a (ChordFingering a) where
showFingering (Instrument strings fretCount) (ChordFingering fingerings) =
showNumberedBoard ss fretCount
where
allMute = M.map (\_ -> Nothing :: Maybe (StringFingering a)) strings
chord = M.fromList $ map (\f@(StringFingering n _) -> (n, Just f)) fingerings
stringMap = chord `M.union` allMute
ss = [showFingeredString string n fretCount maybeFret |
(n, f) <- M.assocs stringMap,
let string = strings M.! n,
let maybeFret = fmap (\(StringFingering _ fret) -> fret) f] | null | https://raw.githubusercontent.com/blacktaxi/inversion/f11aa90d6fe6ab7a1f7fa3c3b19bfcf5c1fca451/src/Print.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE ConstraintKinds # | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE FlexibleInstances #
module Print
(ShowFingering (..)) where
import Data.List (delete, genericReplicate, sortBy)
import qualified Data.Map as M
import Text.Printf (printf, PrintfArg)
import Instrument
import Fingering
class ShowFingering b a where
showFingering :: Instrument b -> a -> String
showFingeredString :: (PrintfArg a) => GuitarString -> a -> FretNumber -> Maybe Fret -> String
showFingeredString string stringName fretCount fingering =
printf "%5s %s%s" stringName nut fretBoard
where
emptyBoard = concat $ genericReplicate fretCount "---|"
(nut, fretBoard) =
case fingering of
Nothing -> ("x", emptyBoard)
Just (Fret 0) -> ("O", emptyBoard)
Just (Fret fret) -> ("|", concat [if f == fret then "-O-|" else "---|" |
f <- [1 .. fretCount]])
showFretNumbers fretCount =
concat $ map (printf "%4d") [1 .. fretCount]
showNumberedBoard board fretCount =
unlines (board ++ [fretNumbers])
where fretNumbers = " " ++ (showFretNumbers fretCount)
instance (PrintfArg a) => ShowFingering a (StringFingering a) where
showFingering (Instrument strings fretCount) (StringFingering name fingering) =
showNumberedBoard ss fretCount
where
mutedString s n = showFingeredString s n fretCount Nothing
ss = [if n == name then showFingeredString s n fretCount (Just fingering)
else mutedString s n | (n, s) <- M.assocs strings]
instance (PrintfArg a) => ShowFingering a (ChordFingering a) where
showFingering (Instrument strings fretCount) (ChordFingering fingerings) =
showNumberedBoard ss fretCount
where
allMute = M.map (\_ -> Nothing :: Maybe (StringFingering a)) strings
chord = M.fromList $ map (\f@(StringFingering n _) -> (n, Just f)) fingerings
stringMap = chord `M.union` allMute
ss = [showFingeredString string n fretCount maybeFret |
(n, f) <- M.assocs stringMap,
let string = strings M.! n,
let maybeFret = fmap (\(StringFingering _ fret) -> fret) f] |
e2821fd1c08784c439ad6c3fd8acbcd0505cc6c3350549c6fabe7c7464f11b09 | Deep-Symmetry/afterglow | chauvet.clj | (ns afterglow.fixtures.chauvet
"Models for fixtures provided by [Chauvet Lighting]()."
{:author "James Elliott"}
(:require [afterglow.channels :as chan]
[afterglow.effects.channel :as chan-fx]
[afterglow.fixtures.qxf :refer [sanitize-name]]))
(defn- build-gobo-entries
"Build a list of gobo wheel function entries. If `shake?` is `true`,
they are a variable range which sets the shake speed. The individual
gobo names are in `names`."
[shake? names]
(map (fn [entry]
(let [label (str "Gobo " entry (when shake? " shake"))
type-key (keyword (sanitize-name label))]
(merge {:type type-key
:label label
:range (if shake? :variable :fixed)}
(when shake? {:var-label "Shake Speed"}))))
names))
(defn color-strip
"[ColorStrip](/) LED fixture.
Also works with the ColorStrip Mini.
This was created by Afterglow from the QLC+ Fixture Definintion
(.qxf) file, and revised by James Elliott.
The original fixture defintition was created by JL Griffin
using Q Light Controller version 3.1.0.
QLC+ Fixture Type: Color Changer."
[]
{:channels [(chan/functions :control 1
0 "Blackout"
10 "Red"
20 "Green"
30 "Blue"
40 "Yellow"
50 "Magenta"
60 "Cyan"
70 "White"
(range 80 139 10) "Auto Change"
(range 140 209 10) "Color Chase"
210 "RGB Control"
220 "Chase Fade"
230 "Auto Run")
(chan/color 2 :red)
(chan/color 3 :green)
(chan/color 4 :blue)]
:name "Chauvet ColorStrip"})
(defn geyser-rgb
"[Geyser RGB](-rgb/)
illuminated effect fogger."
[]
{:channels [(chan/functions :fog 1
0 nil
10 "Fog")
(chan/color 2 :red)
(chan/color 3 :green)
(chan/color 4 :blue)
(chan/functions :control 5
0 nil
10 :color-mixing)
(chan/functions :control 6
0 nil
10 :auto-speed)
(chan/functions :strobe 7
0 nil
10 :strobe)
(chan/dimmer 8)]
:name "Chauvet Geyser RGB"})
(defn gig-bar-2
"[GigBAR 2](-2/) mobile DJ
lighting system. Even though this fixture does not move, if you want
to have its RGB pars participate in spatial effects, it is important
to patch it at the correct location and orientation, so Afterglow
can properly reason about the spatial relationships between the
heads. If you have rearranged the pods from their default
configuration, you will want to edit the head definitions
appropriately.
The fixture origin is in between the two center (par) pods, at the
center of the support pole, and centered vertically with the lenses
of the Par lights. The default orientation is with the pod mounting
bar parallel to the X axis, and the LED display and sockets all
facing away from the audience.
This fixture can be patched to use 3, 11, or 23 DMX channels. If you
do not specify a mode when patching it, `:23-channel` is assumed;
you can pass a value of `:3-channel` or `:11-channel` for `mode` if
you are using it that way.
This was created by Afterglow from the QLC+ Fixture Definintion
(.qxf) file, and revised by James Elliott.
The original fixture defintition was created by Freasy using Q Light
Controller Plus version 4.11.0. QLC+ Fixture Type: Effect.
When you pass a mode, you can also control whether the UV channels
are mixed in when creating colors by passing a boolean value with
`:mix-uv`. The default is `true`."
([]
(gig-bar-2 :23-channels))
([mode & {:keys [mix-uv] :or {mix-uv true}}]
(merge {:name "GigBAR 2"
:mode mode}
(case mode
:3-channels
{:channels [(chan/functions :led-operation 1
0 nil
10 {:type :led-auto-mixed-mode-1
:label "Auto 1 fast>slow"
:range :variable}
120 {:type :led-auto-mixed-mode-2
:label "Auto 2 fast>slow"
:range :variable}
230 {:type :led-sound-mixed-mode-1
:label "Sound 1"
:range :fixed}
235 {:type :led-sound-active
:label "Sound 2"
:range :fixed}
240 {:type :led-show-setting
:label "Show, chan 2+3"
:range :fixed})
(chan/functions :operation 2
0 {:type :blackout
:label "Blackout"
:range :fixed}
10 {:type :pars-only
:label "Pars only"
:range :fixed}
20 {:type :derby-only
:label "Derby only"
:range :fixed}
30 {:type :laser-only
:label "Laser only"
:range :fixed}
40 {:type :strobes-only
:label "Strobes only"
:range :fixed}
50 {:type :auto-pars-derby
:label "Auto pars derby"
:range :fixed}
60 {:type :operation-pars-laser
:label "Auto pars laser"
:range :fixed}
70 {:type :operation-auto-pars-and-strobes-only
:label "Auto pars strobes"
:range :fixed}
80 {:type :auto-derby-laser
:label "Auto derby laser only"
:range :fixed}
90 {:type :auto-strobes-derby
:label "Auto strobes derby only"
:range :fixed}
100 {:type :pars-derby-laser
:label "Pars, derby, laser"
:range :fixed}
110 {:type :pars-derby-strobes
:label "Pars, derby, strobes"
:range :fixed}
120 {:type :pars-laser-strobes
:label "Pars, laser, strobes"
:range :fixed}
130 {:type :derby-laser-strobes
:label "Derby, laser, strobes"
:range :fixed}
140 {:type :par-sound-active
:label "Par Sound"
:range :fixed}
150 {:type :derby-sound-active
:label "Derby Sound"
:range :fixed}
160 {:type :laser-sound-active
:label "Laser Sound"
:range :fixed}
170 {:type :strobe-sound-active
:label "Strobe Sound"
:range :fixed}
180 {:type :par-derby-sound-active
:label "Par, Derby Sound"
:range :fixed}
190 {:type :par-laser-sound-active
:label "Par, Laser Sound"
:range :fixed}
200 {:type :par-strobe-sound-active
:label "Par, Strobe Sound"
:range :fixed}
210 {:type :derby-laser-sound-active
:label "Derby, Laser Sound"
:range :fixed}
220 {:type :derby-strobe-sound-active
:label "Derby, Strobe Sound"
:range :fixed}
230 {:type :pars-derby-laser-sound-active
:label "Par, Derby, Laser Sound"
:range :fixed}
240 {:type :pars-derby-strobes-sound-active
:label "Par, Derby, Strobe Sound"
:range :fixed}
245 {:type :pars-laser-strobes-sound-active
:label "Par, Laser, Strobe Sound"
:range :fixed}
250 {:type :derby-laser-strobes-sound-active
:label "Derby, Laser, Strobe Sound"
:range :fixed})
(chan/fine-channel :auto-speed 3
:function-name "Auto Speed"
:var-label "Auto Speed")]}
:11-channels
{:channels [(chan/color 1 :red)
(chan/color 2 :green)
(chan/color 3 :blue)
(chan/color 4 :uv :label "UV" :hue (when mix-uv 270))
(chan/functions :pars-and-derby-strobe-controls 5
0 {:type :dimmer
:label "Pars+Derbys Dimmer"
:range :variable}
128 {:type :pars-derby-strobe-speed
:label "Pars+Derbys Strobe Speed"
:range :variable}
240 {:type :pars-derby-sound-strobe
:label "Pars+Derbys Sound Strobe"
:range :variable}
250 {:type :pars-derby-full-strobe
:label "Pars+Derbys Full Strobe"
:range :fixed})
(chan/functions :derby-motor-rotation 6
0 nil
5 {:type :derby-clockwise
:label "Derby CW, slow>fast"
:range :variable}
128 nil
134 {:type :derby-counter-clockwise
:label "Derby CCW, slow>fast"
:range :variable})
(chan/functions :red-laser-controls 7
0 nil
5 {:type :red-laser-on
:label "Red laser on"
:range :fixed}
55 {:type :red-laser-strobe-speed
:label "Red laser strobe speed"
:range :variable})
(chan/functions :green-laser-controls 8
0 nil
5 {:type :green-laser-on
:label "Green laser on"
:range :fixed}
55 {:type :green-laser-strobe-speed
:label "Green laser strobe speed"
:range :variable})
(chan/functions :laser-movement-speed 9
0 nil
5 {:type :laser-clockwise
:label "Laser CW, slow>fast"
:range :variable}
128 nil
134 {:type :laser-counter-clockwise
:label "Laser CCW, slow>fast"
:range :variable})
Can not be used at the same time as 11
0 {:type :dimmer
:label "White strobe dimmer"
:range :variable}
55 {:type :white-strobe-speed
:label "White strobe speed"
:range :variable})
Can not be used at the same time as 10
0 {:type :dimmer
:label "UV strobe dimmer"
:range :variable}
55 {:type :uv-strobe-speed
:label "UV strobe speed"
:range :variable})]}
TODO : Split 23 - channels into individual heads , to be patched separately , for better semantic fit .
:23-channels
{:channels [(chan/functions :strobe-patterns 20
0 {:type :strobe-auto-1
:label "Strobe Auto 1"
:range :fixed}
10 {:type :strobe-auto-2
:label "Strobe Auto 2"
:range :fixed}
30 {:type :strobe-auto-3
:label "Strobe Auto 3"
:range :fixed}
50 {:type :strobe-auto-4
:label "Strobe Auto 4"
:range :fixed}
70 {:type :strobe-auto-5
:label "Strobe Auto 5"
:range :fixed}
90 {:type :strobe-auto-6
:label "Strobe Auto 6"
:range :fixed}
110 {:type :strobe-auto-7
:label "Strobe Auto 7"
:range :fixed}
130 {:type :strobe-auto-8
:label "Strobe Auto 8"
:range :fixed}
150 {:type :strobe-auto-9
:label "Strobe Auto 9"
:range :fixed}
170 {:type :strobe-auto-10
:label "Strobe Auto 10"
:range :fixed}
190 {:type :strobe-speed
:label "Strobe Speed"
:range :variable}
210 {:type :strobe-sound-active
:label "Strobe Sound"
:range :variable})
(chan/fine-channel :strobe-speed 23
:function-name "Strobe Speed Slow to Fast"
:var-label "Strobe Slow>Fast")]
:heads [{:x 0.5 :y -0.05 :z 0 ; TODO: Measure and fine-tune location
:channels [(chan/functions :derby-control 11
0 nil
25 {:type :derby-red
:label "Derby 1 Red"
:range :variable}
50 {:type :derby-green
:label "Derby 1 Green"
:range :variable}
75 {:type :derby-blue
:label "Derby 1 Blue"
:range :variable}
100 {:type :derby-red-green
:label "Derby 1 RG"
:range :variable}
125 {:type :derby-red-blue
:label "Derby 1 RB"
:range :variable}
150 {:type :derby-green-blue
:label "Derby 1 GB"
:range :variable}
175 {:type :derby-red-green-blue
:label "Derby 1 RGB"
:range :variable}
200 {:type :derby-auto-single-colors
:label "Derby 1 Auto (1 color)"
:range :variable}
225 {:type :derby--auto-two-colors
:label "Derby 1 Auto (2 colors)"
:range :variable})
(chan/functions :derby-strobe-speed 12
0 nil
10 {:type :strobe
:label "Derby 1 Strobe, 0-30Hz"
:range :variable} ; TODO: add scale-fn?
240 {:type :strobe-sound
:label "Derby 1 Strobe Sound"
:range :variable})
(chan/functions :derby-rotation 13
0 nil
5 {:type :derby-clockwise-slow-to-fast
:label "Derby 1 CW Slow>Fast"
:range :variable}
128 nil
134 {:type :derby-counter-clockwise-slow-to-fast
:label "Derby 1 CCW Slow>Fast"
:range :variable})]}
{:x 0.2 :y 0 :z 0 ; TODO: Measure and fine-tune location
:channels [(chan/color 1 :red)
(chan/color 2 :green)
(chan/color 3 :blue)
(chan/color 4 :uv :label "UV" :hue (when mix-uv 270))
(chan/functions :par-dimmer-strobe 5
0 {:type :dimmer
:label "Par 1 Dimmer"
:range :variable}
128 {:type :strobe
:label "Par 1 Strobe Slow>Fast"
:range :variable}
240 {:type :strobe-sound
:label "Par 1 Strobe Sound"
:range :variable}
250 {:type :full-on
:label "Par 1 RGB 100%"
:range :fixed})]}
{:x -0.2 :y 0 :z 0 ; TODO: Measure and fine-tune location
:channels [(chan/color 6 :red)
(chan/color 7 :green)
(chan/color 8 :blue)
(chan/color 9 :uv :label "UV" :hue (when mix-uv 270))
(chan/functions :par-dimmer-strobe 10
0 {:type :dimmer
:label "Par 2 Dimmer"
:range :variable}
128 {:type :strobe
:label "Par 2 Strobe Slow>Fast"
:range :variable}
240 {:type :strobe-sound
:label "Par 2 Strobe sound"
:range :variable}
250 {:type :full-on
:label "Par 2 RGB 100%"
:range :fixed})]}
{:x -0.5 :y -0.05 :z 0 ; TODO: Measure and fine-tune location
:channels [(chan/functions :derby-control 14
0 nil
25 {:type :derby-red
:label "Derby 2 Red"
:range :variable}
50 {:type :derby-green
:label "Derby 2 Green"
:range :variable}
75 {:type :derby-blue
:label "Derby 2 Blue"
:range :variable}
100 {:type :derby-red-green
:label "Derby 2 RG"
:range :variable}
125 {:type :derby-red-blue
:label "Derby 2 RB"
:range :variable}
150 {:type :derby-green-blue
:label "Derby 2 GB"
:range :variable}
175 {:type :derby-red-green-blue
:label "Derby 2 RGB"
:range :variable}
200 {:type :derby-auto-single-colors
:label "Derby 2 Auto (1 color)"
:range :variable}
225 {:type :derby-auto-tfwo-colors
:label "Derby 2 Auto (2 colors)"
:range :variable})
(chan/functions :derby-strobe-speed 15
0 nil
10 {:type :derby-strobe-rate-strobe-0-30-hz
:label "Derby 2 Strobe, 0-30Hz"
:range :variablepar-2-rgb-100}
240 {:type :derby-strobe-rate-strobe-to-sound
:label "Derby 2 Strobe Sound"
:range :variable})
(chan/functions :derby-rotation 16
0 nil
5 {:type :derby-rotation-rotate-clockwise-slow-to-fast
:label "Derby 2 CW Slow>Fast"
:range :variable}
128 nil
134 {:type :derby-rotation-rotate-counter-clockwise-slow-to-fast
:label "Derby 2 CCW Slow>Fast"
:range :variable})]}
{:x 0.0 :y 0.25 :z 0 ; TODO: Measure and fine-tune location
:channels [(chan/functions :laser-color 17
0 nil
40 {:type :laser-red-on
:label "Laser Red"
:range :variable}
80 {:type :laser-green-on
:label "Laser Green"
:range :variable}
120 {:type :laser-red-green-on
:label "Laser RG"
:range :variable}
160 {:type :laser-red-on-green-strobe
:label "Laser RGs"
:range :variable}
200 {:type :laser-green-on-red-strobe
:label "Laser RsG"
:range :variable}
240 {:type :laser-red-green-alternate-strobe
:label "Laser RsGs"
:range :variable})
(chan/functions :laser-strobe 18
0 nil
10 {:type :laser-strobe-strobe-speed-slow-to-fast
:label "Laser Strobe Slow>Fast"
:range :variable}
240 {:type :laser-strobe-strobe-to-sound
:label "Laser Strobe Sound"
:range :variable})
(chan/functions :laser-pattern 19
0 nil
5 {:type :laser-clockwise-slow-to-fast
:label "Laser CW Slow>Fast"
:range :variable}
128 nil
134 {:type :laser-counter-clockwise-slow-to-fast
:label "Laser CCW Slow>Fast"
:range :variable})]}
{:x 0 :y 0.2 :z 0 ; TODO: Measure and fine-tune height?
White strobe , can not be used with channel 22
{:x 0 :y 0.0 :z 0 ; TODO: Measure and fine-tune height?
UV strobe , can not be used with channel 21 ` `
(defn hurricane-1800-flex
"[Hurricane 1800
Flex](-1800-flex/)
fogger."
[]
{:channels [(chan/functions :fog 1
0 nil
6 "Fog")]
:name "Chauvet Hurricane 1800 Flex"})
(defn intimidator-scan-led-300
"[Intimidator Scan LED
300](-scan-led-300/)
compact scanner.
This fixture can be configured to use either 8 or 11 DMX channels.
If you do not specify a mode when patching it, `:11-channel` is
you can pass a value of ` : 8 - channel ` for ` mode ` if you are
using it that way.
The standard orientation to hang this fixture is with the Chauvet
logo and LED upright and facing the audience, but tilted up and away
from them at a 45 degree angle.
This was created by Afterglow from the QLC+ Fixture Definintion
(.qxf) file, and heavily revised by James Elliott.
The original fixture defintition was created by Craig Cudmore
using Q Light Controller Plus version 4.7.0 GIT.
QLC+ Fixture Type: Scanner."
([]
(intimidator-scan-led-300 :11-channel))
([mode]
(let [gobo-names ["Pink Dots" "Purple Bubbles" "45 Adapter" "Nested Rings" "Rose" "Triangles" "Galaxy"]]
(letfn [(build-color-wheel [channel]
(chan/functions :color channel
0 "Color Wheel Open"
7 (chan/color-wheel-hue "yellow")
14 "Color Wheel Pink"
21 (chan/color-wheel-hue "green")
28 "Color Wheel Peachblow"
35 "Color Wheel Light Blue"
42 "Color Wheel Kelly"
49 (chan/color-wheel-hue "red")
56 (chan/color-wheel-hue "blue")
64 "Color Wheel White + Yellow"
71 "Color Wheel Yellow + Pink"
78 "Color Wheel Pink + Green"
85 "Color Wheel Green + Peachblow"
92 "Color Wheel Peachblow + Blue"
99 "Color Wheel Blue + Kelly"
106 "Color Wheel Kelly + Red"
113 "Color Wheel Red + Blue"
120 "Color Wheel Blue + White"
128 {:type :color-clockwise
:label "Color Wheel Clockwise (slow->fast)"
:var-label "CW (slow->fast)"
:range :variable}
192 {:type :color-counterclockwise
:label "Color Wheel Counterclockwise (slow->fast)"
:var-label "CCW (slow->fast)"
:range :variable}))
(build-shutter [channel]
(chan/functions :shutter channel
0 "Shutter Closed"
4 "Shutter Open"
8 {:type :strobe
:label "Strobe"
:range :variable}
216 "Shutter Open 2"))
(build-gobo-wheel [channel]
(chan/functions :gobo channel
(range 0 63 8) (build-gobo-entries false (concat ["Open"] gobo-names))
(range 64 119 8) (build-gobo-entries true (reverse gobo-names))
120 "Gobo Open 2"
128 {:type :gobo-clockwise
:label "Gobo Clockwise Speed"
:var-label "CW Speed"
:range :variable}
192 {:type :gobo-counterclockwise
:label "Gobo Counterclockwise Speed"
:var-label "CCW Speed"
:range :variable}))
(build-gobo-rotation [channel]
(chan/functions :gobo-rotation channel
0 nil
16 {:type :gobo-rotation-counterclockwise
:label "Gobo Rotation Counterlockwise (slow->fast)"
:var-label "CCW (slow->fast)"
:range :variable}
128 {:type :gobo-rotation-clockwise
:label "Gobo Rotation Clockwise (slow->fast)"
:var-label "CW (slow->fast)"
:range :variable}
240 :gobo-bounce))]
(merge {:name "Chauvet Intimidator Scan LED 300"
:pan-center 128 :pan-half-circle -256
:tilt-center 0 :tilt-half-circle -1024
:mode mode}
(case mode
:11-channel
{:channels [(chan/pan 1)
(chan/tilt 2)
(build-color-wheel 3)
(build-shutter 4)
(chan/dimmer 5)
(build-gobo-wheel 6)
(build-gobo-rotation 7)
(chan/functions :prism 8
0 "Prism Out"
4 "Prism In")
(chan/focus 9)
(chan/functions :control 10
8 "Blackout while moving Pan/Tilt"
16 "Disable Blackout while moving Pan/Tilt"
24 "Blackout while moving Color Wheel"
32 "Disable Blackout while moving Color Wheel"
40 "Blackout while moving Gobo Wheel"
48 "Disable Blackout while moving Gobo Wheel"
56 "Fast Movement"
64 "Disable Fast Movement"
88 "Disable all Blackout while moving"
96 "Reset Pan/Tilt"
104 nil
112 "Reset Color Wheel"
120 "Reset Gobo Wheel"
128 nil
136 "Reset Prism"
144 "Reset Focus"
152 "Reset All"
160 nil)
(chan/functions :control 11
0 nil
(range 8 135 16) "Program"
(range 136 255 16) :sound-active)]}
:8-channel
{:channels [(chan/pan 1)
(chan/tilt 2)
(build-color-wheel 3)
(build-shutter 4)
(build-gobo-wheel 5)
(build-gobo-rotation 6)
(chan/functions :prism 7
0 "Prism Out"
4 "Prism In")
(chan/focus 8)]}))))))
(defn intimidator-spot-led-150
"[Intimidator Spot LED
150](-spot-led-150/)
moving yoke.
This fixture can be configured to use either 6 or 11 DMX channels.
If you do not specify a mode when patching it, `:11-channel` is
you can pass a value of ` : 6 - channel ` for ` mode ` if you are
using it that way.
The standard orientation for this fixture is hung with the Chauvet
label and LED indicator upside-down and facing towards the audience.
This was created by Afterglow from the QLC+ Fixture Definintion
(.qxf) file, and heavily revised by James Elliott.
The original fixture defintition was created by Tavon Markov
using Q Light Controller Plus version 4.8.3 GIT.
QLC+ Fixture Type: Moving Head."
([]
(intimidator-spot-led-150 :11-channel))
([mode]
(let [gobo-names ["Quotes" "Warp Spots" "4 Dots" "Sail Swirl" "Starburst" "Star Field" "Optical Tube"
"Sun Swirl" "Star Echo"]]
(letfn [(build-color-wheel [channel]
(chan/functions :color channel
0 "Color Wheel Open"
(range 6 47 6) (chan/color-wheel-hue ["yellow" "magenta" "green" "red"
"cyan" "orange" "blue"])
48 "Color Wheel Light Green"
54 (chan/color-wheel-hue 45 :label "Color Wheel Amber")
64 "Color Wheel White + Yellow"
70 "Color Wheel Yellow + Magenta"
76 "Color Wheel Magenta + Green"
82 "Color Wheel Green + Red"
88 "Color Wheel Red + Cyan"
94 "Color Wheel Cyan + Orange"
100 "Color Wheel Orange + Blue"
106 "Color Wheel Blue + Light Green"
112 "Color Wheel Light Green + Amber"
118 "Color Wheel Amber + White"
128 {:type :color-clockwise
:label "Color Wheel Clockwise (fast->slow)"
:var-label "CW (fast->slow)"
:range :variable}
192 {:type :color-counterclockwise
:label "Color Wheel Counterclockwise (slow->fast)"
:var-label "CCW (fast->slow)"
:range :variable}))
(build-shutter [channel]
(chan/functions :shutter channel
0 "Shutter Closed"
4 "Shutter Open"
8 {:type :strobe
:label "Strobe (0-20Hz)"
:scale-fn (partial chan-fx/function-value-scaler 0 200)
:range :variable}
216 "Shutter Open 2"))
(build-gobo-wheel [channel]
(chan/functions :gobo channel
(range 0 63 6) (build-gobo-entries false (concat ["Open"] gobo-names))
(range 64 121 6) (build-gobo-entries true (reverse gobo-names))
122 "Gobo Open 2"
128 {:type :gobo-clockwise
:label "Gobo Clockwise Speed"
:var-label "CW Speed"
:range :variable}
192 {:type :gobo-counterclockwise
:label "Gobo Counterclockwise Speed"
:var-label "CCW Speed"
:range :variable}))]
(merge {:name "Chauvet Intimidator Spot LED 150"
:pan-center 170 :pan-half-circle -85
:tilt-center 42 :tilt-half-circle 192
:mode mode}
(case mode
:11-channel
{:channels [(chan/pan 1 3)
(chan/tilt 2 4)
(chan/fine-channel :pan-tilt-speed 5
:function-name "Pan / Tilt Speed"
:var-label "P/T fast->slow")
(build-color-wheel 6)
(build-shutter 7)
(chan/dimmer 8)
(build-gobo-wheel 9)
(chan/functions :control-functions 10
0 nil
8 "Blackout while moving Pan/Tilt"
28 "Blackout while moving Gobo Wheel"
48 "Disable blackout while Pan/Tilt / moving Gobo Wheel"
68 "Blackout while moving Color Wheel"
88 "Disable blackout while Pan/Tilt / moving Color Wheel"
108 "Disable blackout while moving Gobo/Color Wheel"
128 "Diable blackout while moving all options"
148 "Reset Pan"
168 "Reset Tilt"
188 "Reset Color Wheel"
208 "Reset Gobo Wheel"
228 "Reset All Channels"
248 nil)
(chan/functions :movement-macros 11
0 nil
(range 8 135 16) "Program"
(range 136 255 16) "Sound Active")]}
:6-channel
{:channels [(chan/pan 1)
(chan/tilt 2)
(build-color-wheel 3)
(build-shutter 4)
(chan/dimmer 5)
(build-gobo-wheel 6)]}))))))
(defn kinta-x
"[Kinta
X](-x-becomes-an-led-powerhouse/)
derby effect."
[]
{:channels [(chan/functions :control 1
0 "LEDs off"
15 "LEDs on"
101 "Auto")
(chan/functions :rotation 2
0 nil
1 :counter-clockwise
86 :clockwise
171 :back-and-forth)]
:name "Chauvet Kinta X"})
(defn led-techno-strobe
"[LED Techno Strobe](-techno-strobe/)
strobe light."
[]
{:channels [(chan/functions :control 1
0 "Intensity Control"
(range 30 209 30) "Program"
210 :sound-active)
(chan/functions :strobe 2 0 nil
1 :strobe) ; TODO: Measure speed, add scale-fn
(chan/dimmer 3 :inverted-from 1)]
:name "Chauvet LED Techno Strobe"})
(defn led-techno-strobe-rgb
"[LED Techno Strobe RGB](-techno-strobe-rgb/)
color mixing strobe light.
This was created by Afterglow from the QLC+ Fixture Definintion
(.qxf) file, and revised by James Elliott.
The original fixture defintition was created by Davey D
using Q Light Controller Plus version 4.6.0.
QLC+ Fixture Type: Color Changer."
[]
{:channels [(chan/functions :control 1
0 "RGB Control"
(range 25 224 25) "Program"
225 :sound-active)
(chan/color 2 :red)
(chan/color 3 :green)
(chan/color 4 :blue)
(chan/functions :strobe 5 0 nil
1 :strobe) ; TODO: Measure speed, add scale-fn
(chan/dimmer 6 :inverted-from 0)]
:name "Chauvet LED Techno Strobe RGB"})
(defn scorpion-storm-fx-rgb
"[Scorpion Storm FX RGB](-storm-fx-rgb/)
grid effect laser.
This fixture can be patched to use either 7 or 2 DMX channels. If
you do not specify a mode when patching it, `:7-channel` is assumed;
you can pass a value of `:2-channel` for `mode` if you are using it
that way. Although there are two different modes in which you can
patch it, its behavior is controlled by the value you send in
channel 1: If that value is between `0` and `50`, the laser responds
if channel 1 is
set to `51` or higher, it looks only at the first two channels, as
described by `:2-channel` mode.
This was created by Afterglow from the QLC+ Fixture Definintion
(.qxf) file, and revised by James Elliott.
The original fixture defintition was created by Frédéric Combe
using Q Light Controller Plus version 5.0.0 GIT.
QLC+ Fixture Type: Laser."
([]
(scorpion-storm-fx-rgb :7-channel))
([mode]
(merge {:name "Chauvet Scorpion Storm FX RGB"
:mode mode}
(case mode
:7-channel
{:channels [(chan/functions :control 1
0 "DMX Mode"
51 nil)
(chan/functions :control 2
0 "Blackout"
5 "Beam Red"
16 "Beam Green"
26 "Beam Blue"
36 "Beam Red Green"
46 "Beam Blue Green"
56 "Beam Red Blue"
66 "Beam Red Green Blue"
76 "Beam Red, Strobe Green"
86 "Beam Green, Strobe Blue"
96 "Beam Blue, Strobe Red"
106 "Alternate Red/Green"
116 "Alternate Green/Blue"
126 "Alternate Red/Blue"
136 "Beam Red Green, Strobe Blue"
146 "Beam Green Blue, Strobe Red"
156 "Beam Red Blue, Strobe Green"
166 "Beam Blue, Strobe Red Green"
176 "Beam Red, Strobe Green Blue"
186 "Beam Green, Strobe Red Blue"
196 "Beam Blue, Alternate Red/Green"
206 "Beam Red, Alternate Green/Blue"
216 "Beam Green, Alternate Red/Blue"
226 "Alternate Red/Green/Blue")
(chan/functions :strobe 3
0 nil
5 :strobe
255 "Strobe Sound Active")
(chan/functions :control 4
0 "Motor 1 Stop"
5 :motor-1-clockwise
128 "Motor 1 Stop 2"
134 :motor-1-counterclockwise)
(chan/functions :control 5
0 nil
5 :stutter-motor-1-mode-1
57 :stutter-motor-1-mode-2
113 :stutter-motor-1-mode-3
169 :stutter-motor-1-mode-4)
(chan/functions :control 6
0 "Motor 2 Stop"
5 :motor-2-clockwise
128 "Motor 2 Stop 2"
134 :motor-2-counterclockwise)
(chan/functions :control 7
0 nil
5 :stutter-motor-2-mode-1
57 :stutter-motor-2-mode-2
113 :stutter-motor-2-mode-3
169 :stutter-motor-2-mode-4)]}
:2-channel
{:channels [(chan/functions :control 1
0 nil
51 "Auto fast"
101 "Auto slow"
151 :sound-active
201 "Random program")
(chan/functions :control 2
0 "Beam Red"
37 "Beam Green"
73 "Beam Blue"
109 "Beam Red Green"
145 "Beam Green Blue"
181 "Beam Red Blue"
217 "Beam Red Green Blue")]}))))
(defn scorpion-storm-rgx
"[Scorpion Storm RGX](-x-stands-for-extras-in-the-new-scorpion-storm-rgx/)
grid effect laser."
[]
{:channels [(chan/functions :control 1
0 "DMX Mode"
20 "Auto Fast Red"
40 "Auto Slow Red"
60 "Auto Fast Green"
80 "Auto Slow Green"
100 "Auto Fast Red Green"
120 "Auto Slow Red Green"
140 :sound-active-red
160 :sound-active-green
180 :sound-active
200 "Random")
(chan/functions :control 2
0 "Blackout"
5 "Beam Red"
29 "Beam Green"
57 "Beam Red Green"
85 "Strobe Green"
113 "Strobe Red"
141 "Beam Red, Strobe Green"
169 "Beam Green, Strobe Red"
198 "Strobe Red Green"
225 "Alternate Red/Green")
(chan/functions :strobe 3
0 nil
5 :strobe
255 "Strobe Sound Active")
(chan/functions :control 4
0 "Stop"
5 :beams-clockwise
128 "Stop 2"
134 :beams-counterclockwise)]
:name "Chauvet Scorpion Storm RGX"})
(defn q-spot-160
"Q Spot 160 moving yoke.
This fixture can be configured to use either 9 or 12 DMX channels.
If you do not specify a mode when patching it, `:12-channel` is
you can pass a value of ` : 9 - channel ` for ` mode ` if you are
using it that way.
The standard hanging orientation is with the Chauvet label and LED
panel upside-down and facing the house-right wall (the positive X
axis direction)."
([]
(q-spot-160 :12-channel))
([mode]
(let [gobo-names ["Splat" "Spot Sphere" "Fanned Squares" "Box" "Bar" "Blue Starburst" "Perforated Pink"]]
(letfn [(build-color-wheel [channel]
(chan/functions :color channel
0 "Color Wheel Open"
(range 15 59 15) (chan/color-wheel-hue ["red" "yellow" "green"])
60 "Color Wheel pink"
(range 75 119 15) (chan/color-wheel-hue ["blue" "orange" "magenta"])
120 "Color Wheel Light Blue"
135 "Color Wheel Light Green"
150 {:type :color-clockwise
:label "Color Wheel Clockwise (slow->fast)"
:var-label "CW (slow->fast)"
:range :variable}))
(build-shutter [channel]
(chan/functions :shutter channel
0 "Shutter Closed"
32 "Shutter Open"
64 :strobe
96 "Shutter Open 2"
128 :pulse-strobe
160 "Shutter Open 3"
192 :random-strobe
224 "Shutter Open 4"))
(build-gobo-wheel [channel]
(chan/functions :gobo channel
(range 0 79 10) (build-gobo-entries false (concat ["Open"] gobo-names))
(range 80 219 20) (build-gobo-entries true (reverse gobo-names))
220 {:type :gobo-scroll
:label "Gobo Scroll"
:var-label "Scroll Speed"
:range :variable}))
(build-gobo-rotation [channel]
(chan/functions :gobo-rotation channel
0 nil
3 {:type :gobo-rotation-clockwise
:label "Gobo Rotation Clockwise (slow->fast)"
:var-label "CW (slow->fast)"
:range :variable}
129 "Gobo Rotation Stop"
133 {:type :gobo-rotation-counterclockwise
:label "Gobo Rotation Counterlockwise (slow->fast)"
:var-label "CCW (slow->fast)"
:range :variable}))
(build-control-channel [channel]
(chan/functions :control channel
0 nil
20 "Blackout while moving Pan/Tilt"
40 "Disable Blackout while moving Pan/Tilt"
60 "Auto 1"
80 "Auto 2"
100 "Sound Active 1"
120 "Sound Active 2"
140 "Custom"
160 "Test"
180 nil
200 "Reset"
220 nil))]
(merge {:name "Chauvet Q Spot 160"
:pan-center 85 :pan-half-circle 85
:tilt-center 218 :tilt-half-circle -180
:mode mode}
(case mode
:12-channel
{:channels [(chan/pan 1 2)
(chan/tilt 3 4)
(chan/fine-channel :pan-tilt-speed 5
:function-name "Pan / Tilt Speed"
:var-label "P/T fast->slow")
(build-color-wheel 6)
(build-gobo-wheel 7)
(build-gobo-rotation 8)
(chan/functions :prism 9 0 "Prism Out" 128 "Prism In")
(chan/dimmer 10)
(build-shutter 11)
(build-control-channel 12)]}
:9-channel
{:channels [(chan/pan 1)
(chan/tilt 2)
(build-color-wheel 3)
(build-gobo-wheel 4)
(build-gobo-rotation 5)
(chan/functions :prism 6 0 "Prism Out" 128 "Prism In")
(chan/dimmer 7)
(build-shutter 8)
(build-control-channel 9)]}))))))
(defn slimpar-hex3-irc
"[SlimPAR HEX 3 IRC](-hex-3-irc/)
six-color low-profile LED PAR.
This fixture can be configured to use either 6, 8 or 12 DMX
channels. If you do not specify a mode when patching it,
you can pass a value of ` : 6 - channel ` or
`:8-channel` for `mode` if you are using it that way.
When you pass a mode, you can also control whether the amber and UV
channels are mixed in when creating colors by passing a boolean
value with `:mix-amber` and `:mix-uv`. The default for each is
`true`."
([]
(slimpar-hex3-irc :12-channel))
([mode & {:keys [mix-amber mix-uv] :or {mix-amber true mix-uv true}}]
(assoc (case mode
:12-channel {:channels [(chan/dimmer 1) (chan/color 2 :red) (chan/color 3 :green) (chan/color 4 :blue)
(chan/color 5 :amber :hue (when mix-amber 45)) (chan/color 6 :white)
(chan/color 7 :uv :label "UV" :hue (when mix-uv 270))
(chan/functions :strobe 8 0 nil
11 {:type :strobe
:scale-fn (partial chan-fx/function-value-scaler 0.87 25)
:label "Strobe (0.87Hz->25Hz)"})
(chan/functions :color-macros 9 0 nil 16 :color-macros)
(chan/functions :control 10 0 nil (range 11 200 50) "Program"
201 :sound-active-6-color 226 :sound-active)
(chan/functions :program-speed 11 0 :program-speed)
(chan/functions :dimmer-mode 12 0 "Dimmer Mode Manual" 52 "Dimmer Mode Off"
102 "Dimmer Mode Fast" 153 "Dimmer Mode Medium"
204 "Dimmer Mode Slow")]}
:8-channel {:channels [(chan/dimmer 1) (chan/color 2 :red) (chan/color 3 :green) (chan/color 4 :blue)
(chan/color 5 :amber :hue (when mix-amber 45)) (chan/color 6 :white)
(chan/color 7 :uv :label "UV" :hue (when mix-uv 270))
(chan/functions :strobe 8 0 nil
11 {:type :strobe
:scale-fn (partial chan-fx/function-value-scaler 0.87 25)
:label "Strobe (0.87Hz->25Hz)"})]}
:6-channel {:channels [(chan/color 1 :red) (chan/color 2 :green) (chan/color 3 :blue)
(chan/color 4 :amber :hue (when mix-amber 45)) (chan/color 5 :white)
(chan/color 6 :uv :label "UV" :hue (when mix-uv 270))]})
:name "Chauvet SlimPAR Hex 3 IRC"
:mode mode)))
| null | https://raw.githubusercontent.com/Deep-Symmetry/afterglow/cee930dab27274b350a6123a93590f05edca00c3/src/afterglow/fixtures/chauvet.clj | clojure |
TODO: Measure and fine-tune location
TODO: add scale-fn?
TODO: Measure and fine-tune location
TODO: Measure and fine-tune location
TODO: Measure and fine-tune location
TODO: Measure and fine-tune location
TODO: Measure and fine-tune height?
TODO: Measure and fine-tune height?
TODO: Measure speed, add scale-fn
TODO: Measure speed, add scale-fn
| (ns afterglow.fixtures.chauvet
"Models for fixtures provided by [Chauvet Lighting]()."
{:author "James Elliott"}
(:require [afterglow.channels :as chan]
[afterglow.effects.channel :as chan-fx]
[afterglow.fixtures.qxf :refer [sanitize-name]]))
(defn- build-gobo-entries
"Build a list of gobo wheel function entries. If `shake?` is `true`,
they are a variable range which sets the shake speed. The individual
gobo names are in `names`."
[shake? names]
(map (fn [entry]
(let [label (str "Gobo " entry (when shake? " shake"))
type-key (keyword (sanitize-name label))]
(merge {:type type-key
:label label
:range (if shake? :variable :fixed)}
(when shake? {:var-label "Shake Speed"}))))
names))
(defn color-strip
"[ColorStrip](/) LED fixture.
Also works with the ColorStrip Mini.
This was created by Afterglow from the QLC+ Fixture Definintion
(.qxf) file, and revised by James Elliott.
The original fixture defintition was created by JL Griffin
using Q Light Controller version 3.1.0.
QLC+ Fixture Type: Color Changer."
[]
{:channels [(chan/functions :control 1
0 "Blackout"
10 "Red"
20 "Green"
30 "Blue"
40 "Yellow"
50 "Magenta"
60 "Cyan"
70 "White"
(range 80 139 10) "Auto Change"
(range 140 209 10) "Color Chase"
210 "RGB Control"
220 "Chase Fade"
230 "Auto Run")
(chan/color 2 :red)
(chan/color 3 :green)
(chan/color 4 :blue)]
:name "Chauvet ColorStrip"})
(defn geyser-rgb
"[Geyser RGB](-rgb/)
illuminated effect fogger."
[]
{:channels [(chan/functions :fog 1
0 nil
10 "Fog")
(chan/color 2 :red)
(chan/color 3 :green)
(chan/color 4 :blue)
(chan/functions :control 5
0 nil
10 :color-mixing)
(chan/functions :control 6
0 nil
10 :auto-speed)
(chan/functions :strobe 7
0 nil
10 :strobe)
(chan/dimmer 8)]
:name "Chauvet Geyser RGB"})
(defn gig-bar-2
"[GigBAR 2](-2/) mobile DJ
lighting system. Even though this fixture does not move, if you want
to have its RGB pars participate in spatial effects, it is important
to patch it at the correct location and orientation, so Afterglow
can properly reason about the spatial relationships between the
heads. If you have rearranged the pods from their default
configuration, you will want to edit the head definitions
appropriately.
The fixture origin is in between the two center (par) pods, at the
center of the support pole, and centered vertically with the lenses
of the Par lights. The default orientation is with the pod mounting
bar parallel to the X axis, and the LED display and sockets all
facing away from the audience.
This fixture can be patched to use 3, 11, or 23 DMX channels. If you
you can pass a value of `:3-channel` or `:11-channel` for `mode` if
you are using it that way.
This was created by Afterglow from the QLC+ Fixture Definintion
(.qxf) file, and revised by James Elliott.
The original fixture defintition was created by Freasy using Q Light
Controller Plus version 4.11.0. QLC+ Fixture Type: Effect.
When you pass a mode, you can also control whether the UV channels
are mixed in when creating colors by passing a boolean value with
`:mix-uv`. The default is `true`."
([]
(gig-bar-2 :23-channels))
([mode & {:keys [mix-uv] :or {mix-uv true}}]
(merge {:name "GigBAR 2"
:mode mode}
(case mode
:3-channels
{:channels [(chan/functions :led-operation 1
0 nil
10 {:type :led-auto-mixed-mode-1
:label "Auto 1 fast>slow"
:range :variable}
120 {:type :led-auto-mixed-mode-2
:label "Auto 2 fast>slow"
:range :variable}
230 {:type :led-sound-mixed-mode-1
:label "Sound 1"
:range :fixed}
235 {:type :led-sound-active
:label "Sound 2"
:range :fixed}
240 {:type :led-show-setting
:label "Show, chan 2+3"
:range :fixed})
(chan/functions :operation 2
0 {:type :blackout
:label "Blackout"
:range :fixed}
10 {:type :pars-only
:label "Pars only"
:range :fixed}
20 {:type :derby-only
:label "Derby only"
:range :fixed}
30 {:type :laser-only
:label "Laser only"
:range :fixed}
40 {:type :strobes-only
:label "Strobes only"
:range :fixed}
50 {:type :auto-pars-derby
:label "Auto pars derby"
:range :fixed}
60 {:type :operation-pars-laser
:label "Auto pars laser"
:range :fixed}
70 {:type :operation-auto-pars-and-strobes-only
:label "Auto pars strobes"
:range :fixed}
80 {:type :auto-derby-laser
:label "Auto derby laser only"
:range :fixed}
90 {:type :auto-strobes-derby
:label "Auto strobes derby only"
:range :fixed}
100 {:type :pars-derby-laser
:label "Pars, derby, laser"
:range :fixed}
110 {:type :pars-derby-strobes
:label "Pars, derby, strobes"
:range :fixed}
120 {:type :pars-laser-strobes
:label "Pars, laser, strobes"
:range :fixed}
130 {:type :derby-laser-strobes
:label "Derby, laser, strobes"
:range :fixed}
140 {:type :par-sound-active
:label "Par Sound"
:range :fixed}
150 {:type :derby-sound-active
:label "Derby Sound"
:range :fixed}
160 {:type :laser-sound-active
:label "Laser Sound"
:range :fixed}
170 {:type :strobe-sound-active
:label "Strobe Sound"
:range :fixed}
180 {:type :par-derby-sound-active
:label "Par, Derby Sound"
:range :fixed}
190 {:type :par-laser-sound-active
:label "Par, Laser Sound"
:range :fixed}
200 {:type :par-strobe-sound-active
:label "Par, Strobe Sound"
:range :fixed}
210 {:type :derby-laser-sound-active
:label "Derby, Laser Sound"
:range :fixed}
220 {:type :derby-strobe-sound-active
:label "Derby, Strobe Sound"
:range :fixed}
230 {:type :pars-derby-laser-sound-active
:label "Par, Derby, Laser Sound"
:range :fixed}
240 {:type :pars-derby-strobes-sound-active
:label "Par, Derby, Strobe Sound"
:range :fixed}
245 {:type :pars-laser-strobes-sound-active
:label "Par, Laser, Strobe Sound"
:range :fixed}
250 {:type :derby-laser-strobes-sound-active
:label "Derby, Laser, Strobe Sound"
:range :fixed})
(chan/fine-channel :auto-speed 3
:function-name "Auto Speed"
:var-label "Auto Speed")]}
:11-channels
{:channels [(chan/color 1 :red)
(chan/color 2 :green)
(chan/color 3 :blue)
(chan/color 4 :uv :label "UV" :hue (when mix-uv 270))
(chan/functions :pars-and-derby-strobe-controls 5
0 {:type :dimmer
:label "Pars+Derbys Dimmer"
:range :variable}
128 {:type :pars-derby-strobe-speed
:label "Pars+Derbys Strobe Speed"
:range :variable}
240 {:type :pars-derby-sound-strobe
:label "Pars+Derbys Sound Strobe"
:range :variable}
250 {:type :pars-derby-full-strobe
:label "Pars+Derbys Full Strobe"
:range :fixed})
(chan/functions :derby-motor-rotation 6
0 nil
5 {:type :derby-clockwise
:label "Derby CW, slow>fast"
:range :variable}
128 nil
134 {:type :derby-counter-clockwise
:label "Derby CCW, slow>fast"
:range :variable})
(chan/functions :red-laser-controls 7
0 nil
5 {:type :red-laser-on
:label "Red laser on"
:range :fixed}
55 {:type :red-laser-strobe-speed
:label "Red laser strobe speed"
:range :variable})
(chan/functions :green-laser-controls 8
0 nil
5 {:type :green-laser-on
:label "Green laser on"
:range :fixed}
55 {:type :green-laser-strobe-speed
:label "Green laser strobe speed"
:range :variable})
(chan/functions :laser-movement-speed 9
0 nil
5 {:type :laser-clockwise
:label "Laser CW, slow>fast"
:range :variable}
128 nil
134 {:type :laser-counter-clockwise
:label "Laser CCW, slow>fast"
:range :variable})
Can not be used at the same time as 11
0 {:type :dimmer
:label "White strobe dimmer"
:range :variable}
55 {:type :white-strobe-speed
:label "White strobe speed"
:range :variable})
Can not be used at the same time as 10
0 {:type :dimmer
:label "UV strobe dimmer"
:range :variable}
55 {:type :uv-strobe-speed
:label "UV strobe speed"
:range :variable})]}
TODO : Split 23 - channels into individual heads , to be patched separately , for better semantic fit .
:23-channels
{:channels [(chan/functions :strobe-patterns 20
0 {:type :strobe-auto-1
:label "Strobe Auto 1"
:range :fixed}
10 {:type :strobe-auto-2
:label "Strobe Auto 2"
:range :fixed}
30 {:type :strobe-auto-3
:label "Strobe Auto 3"
:range :fixed}
50 {:type :strobe-auto-4
:label "Strobe Auto 4"
:range :fixed}
70 {:type :strobe-auto-5
:label "Strobe Auto 5"
:range :fixed}
90 {:type :strobe-auto-6
:label "Strobe Auto 6"
:range :fixed}
110 {:type :strobe-auto-7
:label "Strobe Auto 7"
:range :fixed}
130 {:type :strobe-auto-8
:label "Strobe Auto 8"
:range :fixed}
150 {:type :strobe-auto-9
:label "Strobe Auto 9"
:range :fixed}
170 {:type :strobe-auto-10
:label "Strobe Auto 10"
:range :fixed}
190 {:type :strobe-speed
:label "Strobe Speed"
:range :variable}
210 {:type :strobe-sound-active
:label "Strobe Sound"
:range :variable})
(chan/fine-channel :strobe-speed 23
:function-name "Strobe Speed Slow to Fast"
:var-label "Strobe Slow>Fast")]
:channels [(chan/functions :derby-control 11
0 nil
25 {:type :derby-red
:label "Derby 1 Red"
:range :variable}
50 {:type :derby-green
:label "Derby 1 Green"
:range :variable}
75 {:type :derby-blue
:label "Derby 1 Blue"
:range :variable}
100 {:type :derby-red-green
:label "Derby 1 RG"
:range :variable}
125 {:type :derby-red-blue
:label "Derby 1 RB"
:range :variable}
150 {:type :derby-green-blue
:label "Derby 1 GB"
:range :variable}
175 {:type :derby-red-green-blue
:label "Derby 1 RGB"
:range :variable}
200 {:type :derby-auto-single-colors
:label "Derby 1 Auto (1 color)"
:range :variable}
225 {:type :derby--auto-two-colors
:label "Derby 1 Auto (2 colors)"
:range :variable})
(chan/functions :derby-strobe-speed 12
0 nil
10 {:type :strobe
:label "Derby 1 Strobe, 0-30Hz"
240 {:type :strobe-sound
:label "Derby 1 Strobe Sound"
:range :variable})
(chan/functions :derby-rotation 13
0 nil
5 {:type :derby-clockwise-slow-to-fast
:label "Derby 1 CW Slow>Fast"
:range :variable}
128 nil
134 {:type :derby-counter-clockwise-slow-to-fast
:label "Derby 1 CCW Slow>Fast"
:range :variable})]}
:channels [(chan/color 1 :red)
(chan/color 2 :green)
(chan/color 3 :blue)
(chan/color 4 :uv :label "UV" :hue (when mix-uv 270))
(chan/functions :par-dimmer-strobe 5
0 {:type :dimmer
:label "Par 1 Dimmer"
:range :variable}
128 {:type :strobe
:label "Par 1 Strobe Slow>Fast"
:range :variable}
240 {:type :strobe-sound
:label "Par 1 Strobe Sound"
:range :variable}
250 {:type :full-on
:label "Par 1 RGB 100%"
:range :fixed})]}
:channels [(chan/color 6 :red)
(chan/color 7 :green)
(chan/color 8 :blue)
(chan/color 9 :uv :label "UV" :hue (when mix-uv 270))
(chan/functions :par-dimmer-strobe 10
0 {:type :dimmer
:label "Par 2 Dimmer"
:range :variable}
128 {:type :strobe
:label "Par 2 Strobe Slow>Fast"
:range :variable}
240 {:type :strobe-sound
:label "Par 2 Strobe sound"
:range :variable}
250 {:type :full-on
:label "Par 2 RGB 100%"
:range :fixed})]}
:channels [(chan/functions :derby-control 14
0 nil
25 {:type :derby-red
:label "Derby 2 Red"
:range :variable}
50 {:type :derby-green
:label "Derby 2 Green"
:range :variable}
75 {:type :derby-blue
:label "Derby 2 Blue"
:range :variable}
100 {:type :derby-red-green
:label "Derby 2 RG"
:range :variable}
125 {:type :derby-red-blue
:label "Derby 2 RB"
:range :variable}
150 {:type :derby-green-blue
:label "Derby 2 GB"
:range :variable}
175 {:type :derby-red-green-blue
:label "Derby 2 RGB"
:range :variable}
200 {:type :derby-auto-single-colors
:label "Derby 2 Auto (1 color)"
:range :variable}
225 {:type :derby-auto-tfwo-colors
:label "Derby 2 Auto (2 colors)"
:range :variable})
(chan/functions :derby-strobe-speed 15
0 nil
10 {:type :derby-strobe-rate-strobe-0-30-hz
:label "Derby 2 Strobe, 0-30Hz"
:range :variablepar-2-rgb-100}
240 {:type :derby-strobe-rate-strobe-to-sound
:label "Derby 2 Strobe Sound"
:range :variable})
(chan/functions :derby-rotation 16
0 nil
5 {:type :derby-rotation-rotate-clockwise-slow-to-fast
:label "Derby 2 CW Slow>Fast"
:range :variable}
128 nil
134 {:type :derby-rotation-rotate-counter-clockwise-slow-to-fast
:label "Derby 2 CCW Slow>Fast"
:range :variable})]}
:channels [(chan/functions :laser-color 17
0 nil
40 {:type :laser-red-on
:label "Laser Red"
:range :variable}
80 {:type :laser-green-on
:label "Laser Green"
:range :variable}
120 {:type :laser-red-green-on
:label "Laser RG"
:range :variable}
160 {:type :laser-red-on-green-strobe
:label "Laser RGs"
:range :variable}
200 {:type :laser-green-on-red-strobe
:label "Laser RsG"
:range :variable}
240 {:type :laser-red-green-alternate-strobe
:label "Laser RsGs"
:range :variable})
(chan/functions :laser-strobe 18
0 nil
10 {:type :laser-strobe-strobe-speed-slow-to-fast
:label "Laser Strobe Slow>Fast"
:range :variable}
240 {:type :laser-strobe-strobe-to-sound
:label "Laser Strobe Sound"
:range :variable})
(chan/functions :laser-pattern 19
0 nil
5 {:type :laser-clockwise-slow-to-fast
:label "Laser CW Slow>Fast"
:range :variable}
128 nil
134 {:type :laser-counter-clockwise-slow-to-fast
:label "Laser CCW Slow>Fast"
:range :variable})]}
White strobe , can not be used with channel 22
UV strobe , can not be used with channel 21 ` `
(defn hurricane-1800-flex
"[Hurricane 1800
Flex](-1800-flex/)
fogger."
[]
{:channels [(chan/functions :fog 1
0 nil
6 "Fog")]
:name "Chauvet Hurricane 1800 Flex"})
(defn intimidator-scan-led-300
"[Intimidator Scan LED
300](-scan-led-300/)
compact scanner.
This fixture can be configured to use either 8 or 11 DMX channels.
If you do not specify a mode when patching it, `:11-channel` is
you can pass a value of ` : 8 - channel ` for ` mode ` if you are
using it that way.
The standard orientation to hang this fixture is with the Chauvet
logo and LED upright and facing the audience, but tilted up and away
from them at a 45 degree angle.
This was created by Afterglow from the QLC+ Fixture Definintion
(.qxf) file, and heavily revised by James Elliott.
The original fixture defintition was created by Craig Cudmore
using Q Light Controller Plus version 4.7.0 GIT.
QLC+ Fixture Type: Scanner."
([]
(intimidator-scan-led-300 :11-channel))
([mode]
(let [gobo-names ["Pink Dots" "Purple Bubbles" "45 Adapter" "Nested Rings" "Rose" "Triangles" "Galaxy"]]
(letfn [(build-color-wheel [channel]
(chan/functions :color channel
0 "Color Wheel Open"
7 (chan/color-wheel-hue "yellow")
14 "Color Wheel Pink"
21 (chan/color-wheel-hue "green")
28 "Color Wheel Peachblow"
35 "Color Wheel Light Blue"
42 "Color Wheel Kelly"
49 (chan/color-wheel-hue "red")
56 (chan/color-wheel-hue "blue")
64 "Color Wheel White + Yellow"
71 "Color Wheel Yellow + Pink"
78 "Color Wheel Pink + Green"
85 "Color Wheel Green + Peachblow"
92 "Color Wheel Peachblow + Blue"
99 "Color Wheel Blue + Kelly"
106 "Color Wheel Kelly + Red"
113 "Color Wheel Red + Blue"
120 "Color Wheel Blue + White"
128 {:type :color-clockwise
:label "Color Wheel Clockwise (slow->fast)"
:var-label "CW (slow->fast)"
:range :variable}
192 {:type :color-counterclockwise
:label "Color Wheel Counterclockwise (slow->fast)"
:var-label "CCW (slow->fast)"
:range :variable}))
(build-shutter [channel]
(chan/functions :shutter channel
0 "Shutter Closed"
4 "Shutter Open"
8 {:type :strobe
:label "Strobe"
:range :variable}
216 "Shutter Open 2"))
(build-gobo-wheel [channel]
(chan/functions :gobo channel
(range 0 63 8) (build-gobo-entries false (concat ["Open"] gobo-names))
(range 64 119 8) (build-gobo-entries true (reverse gobo-names))
120 "Gobo Open 2"
128 {:type :gobo-clockwise
:label "Gobo Clockwise Speed"
:var-label "CW Speed"
:range :variable}
192 {:type :gobo-counterclockwise
:label "Gobo Counterclockwise Speed"
:var-label "CCW Speed"
:range :variable}))
(build-gobo-rotation [channel]
(chan/functions :gobo-rotation channel
0 nil
16 {:type :gobo-rotation-counterclockwise
:label "Gobo Rotation Counterlockwise (slow->fast)"
:var-label "CCW (slow->fast)"
:range :variable}
128 {:type :gobo-rotation-clockwise
:label "Gobo Rotation Clockwise (slow->fast)"
:var-label "CW (slow->fast)"
:range :variable}
240 :gobo-bounce))]
(merge {:name "Chauvet Intimidator Scan LED 300"
:pan-center 128 :pan-half-circle -256
:tilt-center 0 :tilt-half-circle -1024
:mode mode}
(case mode
:11-channel
{:channels [(chan/pan 1)
(chan/tilt 2)
(build-color-wheel 3)
(build-shutter 4)
(chan/dimmer 5)
(build-gobo-wheel 6)
(build-gobo-rotation 7)
(chan/functions :prism 8
0 "Prism Out"
4 "Prism In")
(chan/focus 9)
(chan/functions :control 10
8 "Blackout while moving Pan/Tilt"
16 "Disable Blackout while moving Pan/Tilt"
24 "Blackout while moving Color Wheel"
32 "Disable Blackout while moving Color Wheel"
40 "Blackout while moving Gobo Wheel"
48 "Disable Blackout while moving Gobo Wheel"
56 "Fast Movement"
64 "Disable Fast Movement"
88 "Disable all Blackout while moving"
96 "Reset Pan/Tilt"
104 nil
112 "Reset Color Wheel"
120 "Reset Gobo Wheel"
128 nil
136 "Reset Prism"
144 "Reset Focus"
152 "Reset All"
160 nil)
(chan/functions :control 11
0 nil
(range 8 135 16) "Program"
(range 136 255 16) :sound-active)]}
:8-channel
{:channels [(chan/pan 1)
(chan/tilt 2)
(build-color-wheel 3)
(build-shutter 4)
(build-gobo-wheel 5)
(build-gobo-rotation 6)
(chan/functions :prism 7
0 "Prism Out"
4 "Prism In")
(chan/focus 8)]}))))))
(defn intimidator-spot-led-150
"[Intimidator Spot LED
150](-spot-led-150/)
moving yoke.
This fixture can be configured to use either 6 or 11 DMX channels.
If you do not specify a mode when patching it, `:11-channel` is
you can pass a value of ` : 6 - channel ` for ` mode ` if you are
using it that way.
The standard orientation for this fixture is hung with the Chauvet
label and LED indicator upside-down and facing towards the audience.
This was created by Afterglow from the QLC+ Fixture Definintion
(.qxf) file, and heavily revised by James Elliott.
The original fixture defintition was created by Tavon Markov
using Q Light Controller Plus version 4.8.3 GIT.
QLC+ Fixture Type: Moving Head."
([]
(intimidator-spot-led-150 :11-channel))
([mode]
(let [gobo-names ["Quotes" "Warp Spots" "4 Dots" "Sail Swirl" "Starburst" "Star Field" "Optical Tube"
"Sun Swirl" "Star Echo"]]
(letfn [(build-color-wheel [channel]
(chan/functions :color channel
0 "Color Wheel Open"
(range 6 47 6) (chan/color-wheel-hue ["yellow" "magenta" "green" "red"
"cyan" "orange" "blue"])
48 "Color Wheel Light Green"
54 (chan/color-wheel-hue 45 :label "Color Wheel Amber")
64 "Color Wheel White + Yellow"
70 "Color Wheel Yellow + Magenta"
76 "Color Wheel Magenta + Green"
82 "Color Wheel Green + Red"
88 "Color Wheel Red + Cyan"
94 "Color Wheel Cyan + Orange"
100 "Color Wheel Orange + Blue"
106 "Color Wheel Blue + Light Green"
112 "Color Wheel Light Green + Amber"
118 "Color Wheel Amber + White"
128 {:type :color-clockwise
:label "Color Wheel Clockwise (fast->slow)"
:var-label "CW (fast->slow)"
:range :variable}
192 {:type :color-counterclockwise
:label "Color Wheel Counterclockwise (slow->fast)"
:var-label "CCW (fast->slow)"
:range :variable}))
(build-shutter [channel]
(chan/functions :shutter channel
0 "Shutter Closed"
4 "Shutter Open"
8 {:type :strobe
:label "Strobe (0-20Hz)"
:scale-fn (partial chan-fx/function-value-scaler 0 200)
:range :variable}
216 "Shutter Open 2"))
(build-gobo-wheel [channel]
(chan/functions :gobo channel
(range 0 63 6) (build-gobo-entries false (concat ["Open"] gobo-names))
(range 64 121 6) (build-gobo-entries true (reverse gobo-names))
122 "Gobo Open 2"
128 {:type :gobo-clockwise
:label "Gobo Clockwise Speed"
:var-label "CW Speed"
:range :variable}
192 {:type :gobo-counterclockwise
:label "Gobo Counterclockwise Speed"
:var-label "CCW Speed"
:range :variable}))]
(merge {:name "Chauvet Intimidator Spot LED 150"
:pan-center 170 :pan-half-circle -85
:tilt-center 42 :tilt-half-circle 192
:mode mode}
(case mode
:11-channel
{:channels [(chan/pan 1 3)
(chan/tilt 2 4)
(chan/fine-channel :pan-tilt-speed 5
:function-name "Pan / Tilt Speed"
:var-label "P/T fast->slow")
(build-color-wheel 6)
(build-shutter 7)
(chan/dimmer 8)
(build-gobo-wheel 9)
(chan/functions :control-functions 10
0 nil
8 "Blackout while moving Pan/Tilt"
28 "Blackout while moving Gobo Wheel"
48 "Disable blackout while Pan/Tilt / moving Gobo Wheel"
68 "Blackout while moving Color Wheel"
88 "Disable blackout while Pan/Tilt / moving Color Wheel"
108 "Disable blackout while moving Gobo/Color Wheel"
128 "Diable blackout while moving all options"
148 "Reset Pan"
168 "Reset Tilt"
188 "Reset Color Wheel"
208 "Reset Gobo Wheel"
228 "Reset All Channels"
248 nil)
(chan/functions :movement-macros 11
0 nil
(range 8 135 16) "Program"
(range 136 255 16) "Sound Active")]}
:6-channel
{:channels [(chan/pan 1)
(chan/tilt 2)
(build-color-wheel 3)
(build-shutter 4)
(chan/dimmer 5)
(build-gobo-wheel 6)]}))))))
(defn kinta-x
"[Kinta
X](-x-becomes-an-led-powerhouse/)
derby effect."
[]
{:channels [(chan/functions :control 1
0 "LEDs off"
15 "LEDs on"
101 "Auto")
(chan/functions :rotation 2
0 nil
1 :counter-clockwise
86 :clockwise
171 :back-and-forth)]
:name "Chauvet Kinta X"})
(defn led-techno-strobe
"[LED Techno Strobe](-techno-strobe/)
strobe light."
[]
{:channels [(chan/functions :control 1
0 "Intensity Control"
(range 30 209 30) "Program"
210 :sound-active)
(chan/functions :strobe 2 0 nil
(chan/dimmer 3 :inverted-from 1)]
:name "Chauvet LED Techno Strobe"})
(defn led-techno-strobe-rgb
"[LED Techno Strobe RGB](-techno-strobe-rgb/)
color mixing strobe light.
This was created by Afterglow from the QLC+ Fixture Definintion
(.qxf) file, and revised by James Elliott.
The original fixture defintition was created by Davey D
using Q Light Controller Plus version 4.6.0.
QLC+ Fixture Type: Color Changer."
[]
{:channels [(chan/functions :control 1
0 "RGB Control"
(range 25 224 25) "Program"
225 :sound-active)
(chan/color 2 :red)
(chan/color 3 :green)
(chan/color 4 :blue)
(chan/functions :strobe 5 0 nil
(chan/dimmer 6 :inverted-from 0)]
:name "Chauvet LED Techno Strobe RGB"})
(defn scorpion-storm-fx-rgb
"[Scorpion Storm FX RGB](-storm-fx-rgb/)
grid effect laser.
This fixture can be patched to use either 7 or 2 DMX channels. If
you can pass a value of `:2-channel` for `mode` if you are using it
that way. Although there are two different modes in which you can
patch it, its behavior is controlled by the value you send in
channel 1: If that value is between `0` and `50`, the laser responds
if channel 1 is
set to `51` or higher, it looks only at the first two channels, as
described by `:2-channel` mode.
This was created by Afterglow from the QLC+ Fixture Definintion
(.qxf) file, and revised by James Elliott.
The original fixture defintition was created by Frédéric Combe
using Q Light Controller Plus version 5.0.0 GIT.
QLC+ Fixture Type: Laser."
([]
(scorpion-storm-fx-rgb :7-channel))
([mode]
(merge {:name "Chauvet Scorpion Storm FX RGB"
:mode mode}
(case mode
:7-channel
{:channels [(chan/functions :control 1
0 "DMX Mode"
51 nil)
(chan/functions :control 2
0 "Blackout"
5 "Beam Red"
16 "Beam Green"
26 "Beam Blue"
36 "Beam Red Green"
46 "Beam Blue Green"
56 "Beam Red Blue"
66 "Beam Red Green Blue"
76 "Beam Red, Strobe Green"
86 "Beam Green, Strobe Blue"
96 "Beam Blue, Strobe Red"
106 "Alternate Red/Green"
116 "Alternate Green/Blue"
126 "Alternate Red/Blue"
136 "Beam Red Green, Strobe Blue"
146 "Beam Green Blue, Strobe Red"
156 "Beam Red Blue, Strobe Green"
166 "Beam Blue, Strobe Red Green"
176 "Beam Red, Strobe Green Blue"
186 "Beam Green, Strobe Red Blue"
196 "Beam Blue, Alternate Red/Green"
206 "Beam Red, Alternate Green/Blue"
216 "Beam Green, Alternate Red/Blue"
226 "Alternate Red/Green/Blue")
(chan/functions :strobe 3
0 nil
5 :strobe
255 "Strobe Sound Active")
(chan/functions :control 4
0 "Motor 1 Stop"
5 :motor-1-clockwise
128 "Motor 1 Stop 2"
134 :motor-1-counterclockwise)
(chan/functions :control 5
0 nil
5 :stutter-motor-1-mode-1
57 :stutter-motor-1-mode-2
113 :stutter-motor-1-mode-3
169 :stutter-motor-1-mode-4)
(chan/functions :control 6
0 "Motor 2 Stop"
5 :motor-2-clockwise
128 "Motor 2 Stop 2"
134 :motor-2-counterclockwise)
(chan/functions :control 7
0 nil
5 :stutter-motor-2-mode-1
57 :stutter-motor-2-mode-2
113 :stutter-motor-2-mode-3
169 :stutter-motor-2-mode-4)]}
:2-channel
{:channels [(chan/functions :control 1
0 nil
51 "Auto fast"
101 "Auto slow"
151 :sound-active
201 "Random program")
(chan/functions :control 2
0 "Beam Red"
37 "Beam Green"
73 "Beam Blue"
109 "Beam Red Green"
145 "Beam Green Blue"
181 "Beam Red Blue"
217 "Beam Red Green Blue")]}))))
(defn scorpion-storm-rgx
"[Scorpion Storm RGX](-x-stands-for-extras-in-the-new-scorpion-storm-rgx/)
grid effect laser."
[]
{:channels [(chan/functions :control 1
0 "DMX Mode"
20 "Auto Fast Red"
40 "Auto Slow Red"
60 "Auto Fast Green"
80 "Auto Slow Green"
100 "Auto Fast Red Green"
120 "Auto Slow Red Green"
140 :sound-active-red
160 :sound-active-green
180 :sound-active
200 "Random")
(chan/functions :control 2
0 "Blackout"
5 "Beam Red"
29 "Beam Green"
57 "Beam Red Green"
85 "Strobe Green"
113 "Strobe Red"
141 "Beam Red, Strobe Green"
169 "Beam Green, Strobe Red"
198 "Strobe Red Green"
225 "Alternate Red/Green")
(chan/functions :strobe 3
0 nil
5 :strobe
255 "Strobe Sound Active")
(chan/functions :control 4
0 "Stop"
5 :beams-clockwise
128 "Stop 2"
134 :beams-counterclockwise)]
:name "Chauvet Scorpion Storm RGX"})
(defn q-spot-160
"Q Spot 160 moving yoke.
This fixture can be configured to use either 9 or 12 DMX channels.
If you do not specify a mode when patching it, `:12-channel` is
you can pass a value of ` : 9 - channel ` for ` mode ` if you are
using it that way.
The standard hanging orientation is with the Chauvet label and LED
panel upside-down and facing the house-right wall (the positive X
axis direction)."
([]
(q-spot-160 :12-channel))
([mode]
(let [gobo-names ["Splat" "Spot Sphere" "Fanned Squares" "Box" "Bar" "Blue Starburst" "Perforated Pink"]]
(letfn [(build-color-wheel [channel]
(chan/functions :color channel
0 "Color Wheel Open"
(range 15 59 15) (chan/color-wheel-hue ["red" "yellow" "green"])
60 "Color Wheel pink"
(range 75 119 15) (chan/color-wheel-hue ["blue" "orange" "magenta"])
120 "Color Wheel Light Blue"
135 "Color Wheel Light Green"
150 {:type :color-clockwise
:label "Color Wheel Clockwise (slow->fast)"
:var-label "CW (slow->fast)"
:range :variable}))
(build-shutter [channel]
(chan/functions :shutter channel
0 "Shutter Closed"
32 "Shutter Open"
64 :strobe
96 "Shutter Open 2"
128 :pulse-strobe
160 "Shutter Open 3"
192 :random-strobe
224 "Shutter Open 4"))
(build-gobo-wheel [channel]
(chan/functions :gobo channel
(range 0 79 10) (build-gobo-entries false (concat ["Open"] gobo-names))
(range 80 219 20) (build-gobo-entries true (reverse gobo-names))
220 {:type :gobo-scroll
:label "Gobo Scroll"
:var-label "Scroll Speed"
:range :variable}))
(build-gobo-rotation [channel]
(chan/functions :gobo-rotation channel
0 nil
3 {:type :gobo-rotation-clockwise
:label "Gobo Rotation Clockwise (slow->fast)"
:var-label "CW (slow->fast)"
:range :variable}
129 "Gobo Rotation Stop"
133 {:type :gobo-rotation-counterclockwise
:label "Gobo Rotation Counterlockwise (slow->fast)"
:var-label "CCW (slow->fast)"
:range :variable}))
(build-control-channel [channel]
(chan/functions :control channel
0 nil
20 "Blackout while moving Pan/Tilt"
40 "Disable Blackout while moving Pan/Tilt"
60 "Auto 1"
80 "Auto 2"
100 "Sound Active 1"
120 "Sound Active 2"
140 "Custom"
160 "Test"
180 nil
200 "Reset"
220 nil))]
(merge {:name "Chauvet Q Spot 160"
:pan-center 85 :pan-half-circle 85
:tilt-center 218 :tilt-half-circle -180
:mode mode}
(case mode
:12-channel
{:channels [(chan/pan 1 2)
(chan/tilt 3 4)
(chan/fine-channel :pan-tilt-speed 5
:function-name "Pan / Tilt Speed"
:var-label "P/T fast->slow")
(build-color-wheel 6)
(build-gobo-wheel 7)
(build-gobo-rotation 8)
(chan/functions :prism 9 0 "Prism Out" 128 "Prism In")
(chan/dimmer 10)
(build-shutter 11)
(build-control-channel 12)]}
:9-channel
{:channels [(chan/pan 1)
(chan/tilt 2)
(build-color-wheel 3)
(build-gobo-wheel 4)
(build-gobo-rotation 5)
(chan/functions :prism 6 0 "Prism Out" 128 "Prism In")
(chan/dimmer 7)
(build-shutter 8)
(build-control-channel 9)]}))))))
(defn slimpar-hex3-irc
"[SlimPAR HEX 3 IRC](-hex-3-irc/)
six-color low-profile LED PAR.
This fixture can be configured to use either 6, 8 or 12 DMX
channels. If you do not specify a mode when patching it,
you can pass a value of ` : 6 - channel ` or
`:8-channel` for `mode` if you are using it that way.
When you pass a mode, you can also control whether the amber and UV
channels are mixed in when creating colors by passing a boolean
value with `:mix-amber` and `:mix-uv`. The default for each is
`true`."
([]
(slimpar-hex3-irc :12-channel))
([mode & {:keys [mix-amber mix-uv] :or {mix-amber true mix-uv true}}]
(assoc (case mode
:12-channel {:channels [(chan/dimmer 1) (chan/color 2 :red) (chan/color 3 :green) (chan/color 4 :blue)
(chan/color 5 :amber :hue (when mix-amber 45)) (chan/color 6 :white)
(chan/color 7 :uv :label "UV" :hue (when mix-uv 270))
(chan/functions :strobe 8 0 nil
11 {:type :strobe
:scale-fn (partial chan-fx/function-value-scaler 0.87 25)
:label "Strobe (0.87Hz->25Hz)"})
(chan/functions :color-macros 9 0 nil 16 :color-macros)
(chan/functions :control 10 0 nil (range 11 200 50) "Program"
201 :sound-active-6-color 226 :sound-active)
(chan/functions :program-speed 11 0 :program-speed)
(chan/functions :dimmer-mode 12 0 "Dimmer Mode Manual" 52 "Dimmer Mode Off"
102 "Dimmer Mode Fast" 153 "Dimmer Mode Medium"
204 "Dimmer Mode Slow")]}
:8-channel {:channels [(chan/dimmer 1) (chan/color 2 :red) (chan/color 3 :green) (chan/color 4 :blue)
(chan/color 5 :amber :hue (when mix-amber 45)) (chan/color 6 :white)
(chan/color 7 :uv :label "UV" :hue (when mix-uv 270))
(chan/functions :strobe 8 0 nil
11 {:type :strobe
:scale-fn (partial chan-fx/function-value-scaler 0.87 25)
:label "Strobe (0.87Hz->25Hz)"})]}
:6-channel {:channels [(chan/color 1 :red) (chan/color 2 :green) (chan/color 3 :blue)
(chan/color 4 :amber :hue (when mix-amber 45)) (chan/color 5 :white)
(chan/color 6 :uv :label "UV" :hue (when mix-uv 270))]})
:name "Chauvet SlimPAR Hex 3 IRC"
:mode mode)))
|
1022855315f7b9d3c1ac220b12e7176be89ddc707315325cd0bf9d50fcbba1d4 | tokenmill/docx-utils | core.clj | (ns docx-utils.core
(:require [clojure.java.io :as io]
[clojure.tools.logging :as log]
[docx-utils.io :as docx-io]
[docx-utils.append :as append]
[docx-utils.replace :as replace])
(:import (org.apache.poi.xwpf.usermodel XWPFDocument)))
(defn decorate-placeholder [undecorated-placeholder]
(str "%{" undecorated-placeholder "}"))
(defn apply-transformation [^XWPFDocument document {:keys [type placeholder replacement]}]
(let [decorated-placeholder (decorate-placeholder placeholder)]
(log/infof "Applying transformation of type '%s' for placeholder '%s' with replacement '%s'"
type decorated-placeholder replacement)
(try
(cond
(= :append-text type) (append/text document replacement)
(= :append-text-inline type) (append/text-inline document replacement)
(= :append-image type) (append/image document replacement)
(= :append-table type) (append/table document replacement)
(= :append-bullet-list type) (append/bullet-list document replacement)
(= :append-numbered-list type) (append/numbered-list document replacement)
(= :replace-text type) (replace/with-text document decorated-placeholder replacement)
(= :replace-text-inline type) (replace/with-text-inline document decorated-placeholder replacement)
(= :replace-table type) (replace/with-table document decorated-placeholder replacement)
(= :replace-image type) (replace/with-image document decorated-placeholder replacement)
(= :replace-bullet-list type) (replace/with-bullet-list document decorated-placeholder replacement)
(= :replace-numbered-list type) (replace/with-numbered-list document decorated-placeholder replacement)
:else (log/warnf "Unknown transformation type '%s'" type))
(catch Exception e
(log/errorf "Failed transformation with type '%s' decorated-placeholder '%s' and replacement '%s' with exception: %s"
type decorated-placeholder replacement (.printStackTrace e))))))
(defn apply-transformations [^XWPFDocument document transformations]
(doseq [transformation transformations]
(apply-transformation document transformation)))
(defn transform
([transformations]
(transform nil transformations))
([template-file-path transformations]
(transform template-file-path (docx-utils.io/temp-output-file) transformations))
([template-file-path output-file-path transformations]
(when (nil? output-file-path) (throw (Exception. "Output file path is nil.")))
(let [^XWPFDocument document (docx-io/load-template template-file-path)]
(log/infof "Applying transformations %s on template '%s' for output '%s'"
transformations template-file-path output-file-path)
(apply-transformations document transformations)
(docx-io/store document output-file-path)
output-file-path)))
(defn transform-input-stream
"Retrieves document from given InputStream.
Transforms the stream data and returns a new InputStream."
([transformations ^java.io.InputStream doc-input-stream]
(with-open [^XWPFDocument document (docx-io/load-template-from-memory doc-input-stream)]
(apply-transformations document transformations)
(with-open [output-stream (java.io.ByteArrayOutputStream.)]
(.write document output-stream)
(io/input-stream (.toByteArray output-stream))))))
| null | https://raw.githubusercontent.com/tokenmill/docx-utils/f9cb077df2360c11376e0f2d9c8daf8b5062179a/src/docx_utils/core.clj | clojure | (ns docx-utils.core
(:require [clojure.java.io :as io]
[clojure.tools.logging :as log]
[docx-utils.io :as docx-io]
[docx-utils.append :as append]
[docx-utils.replace :as replace])
(:import (org.apache.poi.xwpf.usermodel XWPFDocument)))
(defn decorate-placeholder [undecorated-placeholder]
(str "%{" undecorated-placeholder "}"))
(defn apply-transformation [^XWPFDocument document {:keys [type placeholder replacement]}]
(let [decorated-placeholder (decorate-placeholder placeholder)]
(log/infof "Applying transformation of type '%s' for placeholder '%s' with replacement '%s'"
type decorated-placeholder replacement)
(try
(cond
(= :append-text type) (append/text document replacement)
(= :append-text-inline type) (append/text-inline document replacement)
(= :append-image type) (append/image document replacement)
(= :append-table type) (append/table document replacement)
(= :append-bullet-list type) (append/bullet-list document replacement)
(= :append-numbered-list type) (append/numbered-list document replacement)
(= :replace-text type) (replace/with-text document decorated-placeholder replacement)
(= :replace-text-inline type) (replace/with-text-inline document decorated-placeholder replacement)
(= :replace-table type) (replace/with-table document decorated-placeholder replacement)
(= :replace-image type) (replace/with-image document decorated-placeholder replacement)
(= :replace-bullet-list type) (replace/with-bullet-list document decorated-placeholder replacement)
(= :replace-numbered-list type) (replace/with-numbered-list document decorated-placeholder replacement)
:else (log/warnf "Unknown transformation type '%s'" type))
(catch Exception e
(log/errorf "Failed transformation with type '%s' decorated-placeholder '%s' and replacement '%s' with exception: %s"
type decorated-placeholder replacement (.printStackTrace e))))))
(defn apply-transformations [^XWPFDocument document transformations]
(doseq [transformation transformations]
(apply-transformation document transformation)))
(defn transform
([transformations]
(transform nil transformations))
([template-file-path transformations]
(transform template-file-path (docx-utils.io/temp-output-file) transformations))
([template-file-path output-file-path transformations]
(when (nil? output-file-path) (throw (Exception. "Output file path is nil.")))
(let [^XWPFDocument document (docx-io/load-template template-file-path)]
(log/infof "Applying transformations %s on template '%s' for output '%s'"
transformations template-file-path output-file-path)
(apply-transformations document transformations)
(docx-io/store document output-file-path)
output-file-path)))
(defn transform-input-stream
"Retrieves document from given InputStream.
Transforms the stream data and returns a new InputStream."
([transformations ^java.io.InputStream doc-input-stream]
(with-open [^XWPFDocument document (docx-io/load-template-from-memory doc-input-stream)]
(apply-transformations document transformations)
(with-open [output-stream (java.io.ByteArrayOutputStream.)]
(.write document output-stream)
(io/input-stream (.toByteArray output-stream))))))
| |
14da76487d3706219d38f986f3d11967b49fa68f652d64fde5070fb76eee1ea2 | ghc/packages-Cabal | setup.test.hs | import Test.Cabal.Prelude
main = setupAndCabalTest $ do
skipUnless =<< ghcVersionIs (>= mkVersion [8,1])
r <- fails $ setup' "configure" []
assertOutputContains "non-existent" r
return ()
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-testsuite/PackageTests/Backpack/Fail2/setup.test.hs | haskell | import Test.Cabal.Prelude
main = setupAndCabalTest $ do
skipUnless =<< ghcVersionIs (>= mkVersion [8,1])
r <- fails $ setup' "configure" []
assertOutputContains "non-existent" r
return ()
| |
2e528278c510d127bd09632dd82471011f99b7256c32dcfd03531609c993b218 | qfpl/reflex-tutorial | Solution.hs | # LANGUAGE CPP #
{-# LANGUAGE OverloadedStrings #-}
module Ex05.Solution (
attachEx05
) where
import Language.Javascript.JSaddle (JSM)
import qualified Data.Map as Map
import Reflex
import Util.Attach
#ifndef ghcjs_HOST_OS
import Util.Run
#endif
import Ex05.Common
import Ex05.Run
ex05 ::
Reflex t =>
Inputs t ->
Outputs t
ex05 (Inputs dMoney dCarrot dCelery dCucumber dSelected eBuy eRefund) =
let
-- The typeclass instances that we are using here are available
for both ` Behavior`s and ` Dynamic`s , so this is mostly a change
-- of variable names
dStocks =
[dCarrot, dCelery, dCucumber]
stockSingleton s =
Map.singleton (pName . sProduct $ s) s
dmStock =
foldMap (fmap stockSingleton) dStocks
-- We use `current` to get hold of the `Behavior` here
emStock =
Map.lookup <$> current dSelected <*> current dmStock <@ eBuy
eStock =
fmapMaybe id emStock
checkItemOutOfStock s =
sQuantity s == 0
eItemOutOfStock =
ItemOutOfStock <$ ffilter checkItemOutOfStock eStock
checkNotEnoughMoney money s =
money < (pCost . sProduct $ s)
-- We use `current` to get hold of the `Behavior` here
eNotEnoughMoney =
NotEnoughMoney <$ ffilter id (checkNotEnoughMoney <$> current dMoney <@> eStock)
eError =
leftmost [
eItemOutOfStock
, eNotEnoughMoney
]
eSale =
sProduct <$> difference eStock eError
eVend =
pName <$> eSale
eSpend =
pCost <$> eSale
eChange =
current dMoney <@ eRefund
in
Outputs eVend eSpend eChange eError
attachEx05 ::
JSM ()
attachEx05 =
attachId_ "ex05" $
host ex05
#ifndef ghcjs_HOST_OS
go ::
IO ()
go =
run $
host ex05
#endif
| null | https://raw.githubusercontent.com/qfpl/reflex-tutorial/07c1e6fab387cbeedd031630ba6a5cd946cc612e/code/exercises/src/Ex05/Solution.hs | haskell | # LANGUAGE OverloadedStrings #
The typeclass instances that we are using here are available
of variable names
We use `current` to get hold of the `Behavior` here
We use `current` to get hold of the `Behavior` here | # LANGUAGE CPP #
module Ex05.Solution (
attachEx05
) where
import Language.Javascript.JSaddle (JSM)
import qualified Data.Map as Map
import Reflex
import Util.Attach
#ifndef ghcjs_HOST_OS
import Util.Run
#endif
import Ex05.Common
import Ex05.Run
ex05 ::
Reflex t =>
Inputs t ->
Outputs t
ex05 (Inputs dMoney dCarrot dCelery dCucumber dSelected eBuy eRefund) =
let
for both ` Behavior`s and ` Dynamic`s , so this is mostly a change
dStocks =
[dCarrot, dCelery, dCucumber]
stockSingleton s =
Map.singleton (pName . sProduct $ s) s
dmStock =
foldMap (fmap stockSingleton) dStocks
emStock =
Map.lookup <$> current dSelected <*> current dmStock <@ eBuy
eStock =
fmapMaybe id emStock
checkItemOutOfStock s =
sQuantity s == 0
eItemOutOfStock =
ItemOutOfStock <$ ffilter checkItemOutOfStock eStock
checkNotEnoughMoney money s =
money < (pCost . sProduct $ s)
eNotEnoughMoney =
NotEnoughMoney <$ ffilter id (checkNotEnoughMoney <$> current dMoney <@> eStock)
eError =
leftmost [
eItemOutOfStock
, eNotEnoughMoney
]
eSale =
sProduct <$> difference eStock eError
eVend =
pName <$> eSale
eSpend =
pCost <$> eSale
eChange =
current dMoney <@ eRefund
in
Outputs eVend eSpend eChange eError
attachEx05 ::
JSM ()
attachEx05 =
attachId_ "ex05" $
host ex05
#ifndef ghcjs_HOST_OS
go ::
IO ()
go =
run $
host ex05
#endif
|
e33a1e92ad2feed61b8e2959ea319caf867dab4cec311baf220a7258052d94a6 | pveber/bistro | FastQC.ml | open Bistro
open Bistro.Shell_dsl
type report = [`fastQC] directory
let img = [ docker_image ~account:"pveber" ~name:"fastqc" ~tag:"0.11.8" () ]
module Cmd = struct
let fastqc x = [
mkdir_p dest ;
cmd "fastqc" [
seq ~sep:"" [ string "--outdir=" ; dest ] ;
(
match x with
| `fq fq -> dep fq
| `fq_gz fq_gz -> Bistro_unix.Cmd.gzdep fq_gz
)
] ;
and_list [
cd dest ;
cmd "unzip" [ string "*_fastqc.zip" ] ;
cmd "mv" [ string "*_fastqc/*" ; string "." ]
] ;
]
end
let fastqc fq = Workflow.shell ~descr:"fastQC" ~img (Cmd.fastqc (`fq fq))
let fastqc_gz fq_gz = Workflow.shell ~descr:"fastQC" ~img (Cmd.fastqc (`fq_gz fq_gz))
let html_report x = Workflow.select x ["fastqc_report.html"]
let per_base_quality x =
Workflow.select x ["Images" ; "per_base_quality.png"]
let per_base_sequence_content x =
Workflow.select x ["Images" ; "per_base_sequence_content.png"]
| null | https://raw.githubusercontent.com/pveber/bistro/da0ebc969c8c5ca091905366875cbf8366622280/lib/bio/FastQC.ml | ocaml | open Bistro
open Bistro.Shell_dsl
type report = [`fastQC] directory
let img = [ docker_image ~account:"pveber" ~name:"fastqc" ~tag:"0.11.8" () ]
module Cmd = struct
let fastqc x = [
mkdir_p dest ;
cmd "fastqc" [
seq ~sep:"" [ string "--outdir=" ; dest ] ;
(
match x with
| `fq fq -> dep fq
| `fq_gz fq_gz -> Bistro_unix.Cmd.gzdep fq_gz
)
] ;
and_list [
cd dest ;
cmd "unzip" [ string "*_fastqc.zip" ] ;
cmd "mv" [ string "*_fastqc/*" ; string "." ]
] ;
]
end
let fastqc fq = Workflow.shell ~descr:"fastQC" ~img (Cmd.fastqc (`fq fq))
let fastqc_gz fq_gz = Workflow.shell ~descr:"fastQC" ~img (Cmd.fastqc (`fq_gz fq_gz))
let html_report x = Workflow.select x ["fastqc_report.html"]
let per_base_quality x =
Workflow.select x ["Images" ; "per_base_quality.png"]
let per_base_sequence_content x =
Workflow.select x ["Images" ; "per_base_sequence_content.png"]
| |
060595dd5671eb775610c4d42322f3d946b87837c1b637c4199f20acc2500402 | nick8325/jukebox | AnalyseMonotonicity.hs | # LANGUAGE TypeOperators , CPP #
module Jukebox.Tools.AnalyseMonotonicity where
import Prelude hiding (lookup)
import Jukebox.Name
import Jukebox.Form hiding (Form, clause, true, false, And, Or)
import Control.Monad
import qualified Data.Map.Strict as Map
import Data.Map(Map)
#ifndef NO_MINISAT
import Jukebox.Sat.Easy
#endif
import qualified Data.Set as Set
import Data.Set(Set)
import Data.Maybe
data Extension = TrueExtend | FalseExtend | CopyExtend deriving Show
data Var = FalseExtended Function | TrueExtended Function deriving (Eq, Ord)
analyseMonotonicity :: Problem Clause -> IO (Set Type)
analyseMonotonicity prob = do
m <- monotone (map what prob)
return (Set.fromList (Map.keys (Map.filter isJust m)))
monotone :: [Clause] -> IO (Map Type (Maybe (Map Function Extension)))
#ifdef NO_MINISAT
monotone _ = return Map.empty
#else
monotone cs = runSat watch tys $ do
let fs = functions cs
mapM_ (clause . toLiterals) cs
fmap Map.fromList . forM tys $ \ty -> atIndex ty $ do
r <- solve []
case r of
False -> return (ty, Nothing)
True -> do
m <- model
return (ty, Just (fromModel fs ty m))
where watch (FalseExtended f) =
addForm (Or [Lit (Neg (FalseExtended f)),
Lit (Neg (TrueExtended f))])
watch _ = return ()
tys = types' cs
fromModel :: [Function] -> Type -> (Var -> Bool) -> Map Function Extension
fromModel fs ty m = Map.fromList [ (f, extension f m) | f <- fs, typ f == O, ty `elem` args (rhs f) ]
extension :: Function -> (Var -> Bool) -> Extension
extension f m =
case (m (FalseExtended f), m (TrueExtended f)) of
(False, False) -> CopyExtend
(True, False) -> FalseExtend
(False, True) -> TrueExtend
clause :: [Literal] -> Sat Var Type ()
clause ls = mapM_ (literal ls) ls
literal :: [Literal] -> Literal -> Sat Var Type ()
literal ls (Pos (t :=: u)) = atIndex (typ t) $ do
addForm (safe ls t)
addForm (safe ls u)
literal _ls (Neg (_ :=: _)) = return ()
literal ls (Pos (Tru (p :@: ts))) =
forM_ ts $ \t -> atIndex (typ t) $ addForm (Or [safe ls t, Lit (Neg (FalseExtended p))])
literal ls (Neg (Tru (p :@: ts))) =
forM_ ts $ \t -> atIndex (typ t) $ addForm (Or [safe ls t, Lit (Neg (TrueExtended p))])
safe :: [Literal] -> Term -> Form Var
safe ls (Var x) = Or [ guards l x | l <- ls ]
safe _ _ = true
guards :: Literal -> Variable -> Form Var
guards (Neg (Var _ :=: Var _)) _ = error "Monotonicity.guards: found a variable inequality X!=Y after clausification"
guards (Neg (Var x :=: _)) y | x == y = true
guards (Neg (_ :=: Var x)) y | x == y = true
guards (Pos (Tru (p :@: ts))) x | Var x `elem` ts = Lit (Pos (TrueExtended p))
guards (Neg (Tru (p :@: ts))) x | Var x `elem` ts = Lit (Pos (FalseExtended p))
guards _ _ = false
#endif
| null | https://raw.githubusercontent.com/nick8325/jukebox/52c3206d7def50c8ebcc0128c442fa6c2bd4e074/src/Jukebox/Tools/AnalyseMonotonicity.hs | haskell | # LANGUAGE TypeOperators , CPP #
module Jukebox.Tools.AnalyseMonotonicity where
import Prelude hiding (lookup)
import Jukebox.Name
import Jukebox.Form hiding (Form, clause, true, false, And, Or)
import Control.Monad
import qualified Data.Map.Strict as Map
import Data.Map(Map)
#ifndef NO_MINISAT
import Jukebox.Sat.Easy
#endif
import qualified Data.Set as Set
import Data.Set(Set)
import Data.Maybe
data Extension = TrueExtend | FalseExtend | CopyExtend deriving Show
data Var = FalseExtended Function | TrueExtended Function deriving (Eq, Ord)
analyseMonotonicity :: Problem Clause -> IO (Set Type)
analyseMonotonicity prob = do
m <- monotone (map what prob)
return (Set.fromList (Map.keys (Map.filter isJust m)))
monotone :: [Clause] -> IO (Map Type (Maybe (Map Function Extension)))
#ifdef NO_MINISAT
monotone _ = return Map.empty
#else
monotone cs = runSat watch tys $ do
let fs = functions cs
mapM_ (clause . toLiterals) cs
fmap Map.fromList . forM tys $ \ty -> atIndex ty $ do
r <- solve []
case r of
False -> return (ty, Nothing)
True -> do
m <- model
return (ty, Just (fromModel fs ty m))
where watch (FalseExtended f) =
addForm (Or [Lit (Neg (FalseExtended f)),
Lit (Neg (TrueExtended f))])
watch _ = return ()
tys = types' cs
fromModel :: [Function] -> Type -> (Var -> Bool) -> Map Function Extension
fromModel fs ty m = Map.fromList [ (f, extension f m) | f <- fs, typ f == O, ty `elem` args (rhs f) ]
extension :: Function -> (Var -> Bool) -> Extension
extension f m =
case (m (FalseExtended f), m (TrueExtended f)) of
(False, False) -> CopyExtend
(True, False) -> FalseExtend
(False, True) -> TrueExtend
clause :: [Literal] -> Sat Var Type ()
clause ls = mapM_ (literal ls) ls
literal :: [Literal] -> Literal -> Sat Var Type ()
literal ls (Pos (t :=: u)) = atIndex (typ t) $ do
addForm (safe ls t)
addForm (safe ls u)
literal _ls (Neg (_ :=: _)) = return ()
literal ls (Pos (Tru (p :@: ts))) =
forM_ ts $ \t -> atIndex (typ t) $ addForm (Or [safe ls t, Lit (Neg (FalseExtended p))])
literal ls (Neg (Tru (p :@: ts))) =
forM_ ts $ \t -> atIndex (typ t) $ addForm (Or [safe ls t, Lit (Neg (TrueExtended p))])
safe :: [Literal] -> Term -> Form Var
safe ls (Var x) = Or [ guards l x | l <- ls ]
safe _ _ = true
guards :: Literal -> Variable -> Form Var
guards (Neg (Var _ :=: Var _)) _ = error "Monotonicity.guards: found a variable inequality X!=Y after clausification"
guards (Neg (Var x :=: _)) y | x == y = true
guards (Neg (_ :=: Var x)) y | x == y = true
guards (Pos (Tru (p :@: ts))) x | Var x `elem` ts = Lit (Pos (TrueExtended p))
guards (Neg (Tru (p :@: ts))) x | Var x `elem` ts = Lit (Pos (FalseExtended p))
guards _ _ = false
#endif
| |
56f203e497a19d3020aa3d4478a466979b20d766deddb1d9576b97c6fb11e9e5 | AlacrisIO/legicash-facts | side_chain_server.ml | (* side_chain_server -- TCP/IP server to receive client requests *)
open Legilogic_lib
open Action
open Lwt_exn
open Marshaling
open Types
open Alacris_lib
open Side_chain
open Side_chain_operator
open Side_chain_server_config
let _ =
Config.set_application_name "alacris"
let _init_random =
Random.self_init
let side_chain_server_log = true
(* TODO: pass request id, so we can send a JSON RPC style reply? *)
(* TODO: have some try ... finally construct handle the closing of the channels *)
let process_request_exn _client_address (in_channel,out_channel) =
if side_chain_server_log then
Logging.log "process_request_exn, running 1";
let (iter : int ref) = ref 0 in
let encode_response marshaler =
iter := !iter + 1;
marshaler |> Tag.marshal_result_or_exn |> marshal_string_of_marshal |> arr in
read_string_from_lwt_io_channel in_channel
>>= fun x ->
" After read_string_from_lwt_io_channel x=%s " x ;
if side_chain_server_log then
Logging.log "After read_string_from_lwt_io_channel x=(omit)";
trying (catching_arr ExternalRequest.unmarshal_string) x
>>= (function
| Ok (`UserQuery request) ->
if side_chain_server_log then
Logging.log "process_request_exn : UserQuery";
(oper_post_user_query_request request |> Lwt.bind) (encode_response yojson_marshaling.marshal)
| Ok (`UserTransaction signed_request) ->
if side_chain_server_log then
Logging.log "process_request_exn : UserTransaction";
(oper_post_user_transaction_request signed_request |> Lwt.bind) (encode_response TransactionCommitment.marshal)
| Ok (`AdminQuery request) ->
if side_chain_server_log then
Logging.log "process_request_exn : AdminQuery";
(oper_post_admin_query_request request |> Lwt.bind) (encode_response yojson_marshaling.marshal)
| Error e ->
if side_chain_server_log then
Logging.log "process_request_exn : Error case";
Error e |> encode_response Unit.marshal)
(* TODO: We need to always close, and thus exit the Lwt_exn monad and properly handle the Result
(e.g. by turning it into a yojson that fulfills the JSON RPC interface) before we close.
*)
>>= fun x ->
if side_chain_server_log then
Logging.log "Before writing to write_string_to_lwt_io_channel x=(omit)";
catching (write_string_to_lwt_io_channel out_channel) x
>>= fun () -> catching_lwt Lwt_io.close in_channel
>>= fun () -> catching_lwt Lwt_io.close out_channel
(* squeeze Lwt_exn into Lwt *)
let process_request client_address channels =
if side_chain_server_log then
Logging.log "process_request, running 1";
run_lwt (trying (catching (process_request_exn client_address))
>>> handling (fun e ->
if side_chain_server_log then
Logging.log "Exception while processing server request: %s" (Printexc.to_string e);
return ()))
channels
let sockaddr = Unix.(ADDR_INET (inet_addr_any, Side_chain_server_config.config.port))
let _ =
Lwt_exn.run
(fun () ->
if side_chain_server_log then
Logging.log "Beginning of side_chain_server";
Mkb_json_rpc.init_mkb_server ()
>>= fun () -> Side_chain_vigilantism.start_vigilantism_state_update_daemon Side_chain_server_config.operator_address
>>= fun () -> State_update.start_state_update_periodic_daemon Side_chain_server_config.operator_address
>>= fun () ->
if side_chain_server_log then
Logging.log "Before the Db.open_connection";
of_lwt Db.open_connection "alacris_server_db"
>>= fun () -> load_operator_state Side_chain_server_config.operator_address
>>= fun _operator_state ->
let%lwt _server = Lwt_io.establish_server_with_client_address sockaddr process_request in
start_operator Side_chain_server_config.operator_address
>>= fun () ->
if side_chain_server_log then
Logging.log "*** SIDE CHAIN SERVER STARTED ***";
(* NEVER RETURN *)
of_lwt (fun () -> Lwt.wait () |> fst) ())
()
| null | https://raw.githubusercontent.com/AlacrisIO/legicash-facts/5d3663bade68c09bed47b3f58fa12580f38fdb46/src/alacris_lib/side_chain_server.ml | ocaml | side_chain_server -- TCP/IP server to receive client requests
TODO: pass request id, so we can send a JSON RPC style reply?
TODO: have some try ... finally construct handle the closing of the channels
TODO: We need to always close, and thus exit the Lwt_exn monad and properly handle the Result
(e.g. by turning it into a yojson that fulfills the JSON RPC interface) before we close.
squeeze Lwt_exn into Lwt
NEVER RETURN |
open Legilogic_lib
open Action
open Lwt_exn
open Marshaling
open Types
open Alacris_lib
open Side_chain
open Side_chain_operator
open Side_chain_server_config
let _ =
Config.set_application_name "alacris"
let _init_random =
Random.self_init
let side_chain_server_log = true
let process_request_exn _client_address (in_channel,out_channel) =
if side_chain_server_log then
Logging.log "process_request_exn, running 1";
let (iter : int ref) = ref 0 in
let encode_response marshaler =
iter := !iter + 1;
marshaler |> Tag.marshal_result_or_exn |> marshal_string_of_marshal |> arr in
read_string_from_lwt_io_channel in_channel
>>= fun x ->
" After read_string_from_lwt_io_channel x=%s " x ;
if side_chain_server_log then
Logging.log "After read_string_from_lwt_io_channel x=(omit)";
trying (catching_arr ExternalRequest.unmarshal_string) x
>>= (function
| Ok (`UserQuery request) ->
if side_chain_server_log then
Logging.log "process_request_exn : UserQuery";
(oper_post_user_query_request request |> Lwt.bind) (encode_response yojson_marshaling.marshal)
| Ok (`UserTransaction signed_request) ->
if side_chain_server_log then
Logging.log "process_request_exn : UserTransaction";
(oper_post_user_transaction_request signed_request |> Lwt.bind) (encode_response TransactionCommitment.marshal)
| Ok (`AdminQuery request) ->
if side_chain_server_log then
Logging.log "process_request_exn : AdminQuery";
(oper_post_admin_query_request request |> Lwt.bind) (encode_response yojson_marshaling.marshal)
| Error e ->
if side_chain_server_log then
Logging.log "process_request_exn : Error case";
Error e |> encode_response Unit.marshal)
>>= fun x ->
if side_chain_server_log then
Logging.log "Before writing to write_string_to_lwt_io_channel x=(omit)";
catching (write_string_to_lwt_io_channel out_channel) x
>>= fun () -> catching_lwt Lwt_io.close in_channel
>>= fun () -> catching_lwt Lwt_io.close out_channel
let process_request client_address channels =
if side_chain_server_log then
Logging.log "process_request, running 1";
run_lwt (trying (catching (process_request_exn client_address))
>>> handling (fun e ->
if side_chain_server_log then
Logging.log "Exception while processing server request: %s" (Printexc.to_string e);
return ()))
channels
let sockaddr = Unix.(ADDR_INET (inet_addr_any, Side_chain_server_config.config.port))
let _ =
Lwt_exn.run
(fun () ->
if side_chain_server_log then
Logging.log "Beginning of side_chain_server";
Mkb_json_rpc.init_mkb_server ()
>>= fun () -> Side_chain_vigilantism.start_vigilantism_state_update_daemon Side_chain_server_config.operator_address
>>= fun () -> State_update.start_state_update_periodic_daemon Side_chain_server_config.operator_address
>>= fun () ->
if side_chain_server_log then
Logging.log "Before the Db.open_connection";
of_lwt Db.open_connection "alacris_server_db"
>>= fun () -> load_operator_state Side_chain_server_config.operator_address
>>= fun _operator_state ->
let%lwt _server = Lwt_io.establish_server_with_client_address sockaddr process_request in
start_operator Side_chain_server_config.operator_address
>>= fun () ->
if side_chain_server_log then
Logging.log "*** SIDE CHAIN SERVER STARTED ***";
of_lwt (fun () -> Lwt.wait () |> fst) ())
()
|
129c3ef56070eae8317dbe19745de47dd6fe22d903b97b742d5437d90ac986d6 | ekmett/graphs | AdjacencyList.hs | # LANGUAGE CPP , TypeFamilies , FlexibleContexts #
-----------------------------------------------------------------------------
-- |
-- Module : Data.Graph.Adjacency.List
Copyright : ( C ) 2011
-- License : BSD-style (see the file LICENSE)
--
Maintainer : < >
-- Stability : experimental
-- Portability : type families
--
----------------------------------------------------------------------------
module Data.Graph.AdjacencyList
( AdjacencyList(..)
, AdjacencyListGraph
, ask
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Data.Ix
import Data.Array
import Data.Graph.PropertyMap
import Data.Graph.Class
import Data.Graph.Class.AdjacencyList
newtype AdjacencyList i a = AdjacencyList { runAdjacencyList :: Array i [i] -> a }
ask :: AdjacencyList i (Array i [i])
ask = AdjacencyList id
instance Functor (AdjacencyList i) where
fmap f (AdjacencyList g) = AdjacencyList (f . g)
b <$ _ = pure b
instance Applicative (AdjacencyList i) where
pure = AdjacencyList . const
AdjacencyList f <*> AdjacencyList a = AdjacencyList $ \t -> f t (a t)
instance Monad (AdjacencyList i) where
#if !(MIN_VERSION_base(4,11,0))
return = AdjacencyList . const
#endif
AdjacencyList f >>= k = AdjacencyList $ \t -> runAdjacencyList (k (f t)) t
instance Ord i => Graph (AdjacencyList i) where
type Vertex (AdjacencyList i) = i
type Edge (AdjacencyList i) = (i, i)
vertexMap = pure . propertyMap
edgeMap = pure . propertyMap
instance Ix i => AdjacencyListGraph (AdjacencyList i) where
adjacentVertices v = AdjacencyList $ \g -> if inRange (bounds g) v
then g ! v
else []
source (a, _) = pure a
target (_, b) = pure b
outEdges = defaultOutEdges
| null | https://raw.githubusercontent.com/ekmett/graphs/dd26e6c3c49ace64fc05f53ef4e389910f852ef1/src/Data/Graph/AdjacencyList.hs | haskell | ---------------------------------------------------------------------------
|
Module : Data.Graph.Adjacency.List
License : BSD-style (see the file LICENSE)
Stability : experimental
Portability : type families
-------------------------------------------------------------------------- | # LANGUAGE CPP , TypeFamilies , FlexibleContexts #
Copyright : ( C ) 2011
Maintainer : < >
module Data.Graph.AdjacencyList
( AdjacencyList(..)
, AdjacencyListGraph
, ask
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Data.Ix
import Data.Array
import Data.Graph.PropertyMap
import Data.Graph.Class
import Data.Graph.Class.AdjacencyList
newtype AdjacencyList i a = AdjacencyList { runAdjacencyList :: Array i [i] -> a }
ask :: AdjacencyList i (Array i [i])
ask = AdjacencyList id
instance Functor (AdjacencyList i) where
fmap f (AdjacencyList g) = AdjacencyList (f . g)
b <$ _ = pure b
instance Applicative (AdjacencyList i) where
pure = AdjacencyList . const
AdjacencyList f <*> AdjacencyList a = AdjacencyList $ \t -> f t (a t)
instance Monad (AdjacencyList i) where
#if !(MIN_VERSION_base(4,11,0))
return = AdjacencyList . const
#endif
AdjacencyList f >>= k = AdjacencyList $ \t -> runAdjacencyList (k (f t)) t
instance Ord i => Graph (AdjacencyList i) where
type Vertex (AdjacencyList i) = i
type Edge (AdjacencyList i) = (i, i)
vertexMap = pure . propertyMap
edgeMap = pure . propertyMap
instance Ix i => AdjacencyListGraph (AdjacencyList i) where
adjacentVertices v = AdjacencyList $ \g -> if inRange (bounds g) v
then g ! v
else []
source (a, _) = pure a
target (_, b) = pure b
outEdges = defaultOutEdges
|
f17c39340312c549823d61e77639c44454e1f772af6f01e8b03e23d48e8fb47d | klange/cs421 | mp6-skeleton.ml | (*
* File: mp6-skeleton.ml
*)
open Mp6common
Problem 1
let asMonoTy1 () = failwith "Not implemented"
let asMonoTy2 () = failwith "Not implemented"
let asMonoTy3 () = failwith "Not implemented"
let asMonoTy4 () = failwith "Not implemented"
Problem 2
let rec subst_fun subst m = failwith "Not implemented"
Problem 3
let rec monoTy_lift_subst subst monoTy = failwith "Not implemented"
Problem 4
let rec occurs x ty = failwith "Not implemented"
Problem 5
let rec unify eqlst = failwith "Not implemented"
Extra Credit
let equiv_types ty1 ty2 = failwith "Not implemented"
| null | https://raw.githubusercontent.com/klange/cs421/8db4619db63169bbc2ca7e1998fa4e95f002a5c4/mp6grader/mp6-skeleton.ml | ocaml |
* File: mp6-skeleton.ml
|
open Mp6common
Problem 1
let asMonoTy1 () = failwith "Not implemented"
let asMonoTy2 () = failwith "Not implemented"
let asMonoTy3 () = failwith "Not implemented"
let asMonoTy4 () = failwith "Not implemented"
Problem 2
let rec subst_fun subst m = failwith "Not implemented"
Problem 3
let rec monoTy_lift_subst subst monoTy = failwith "Not implemented"
Problem 4
let rec occurs x ty = failwith "Not implemented"
Problem 5
let rec unify eqlst = failwith "Not implemented"
Extra Credit
let equiv_types ty1 ty2 = failwith "Not implemented"
|
fbb23055bd466cb34e52ab04af0b90567c5b0fc9ef2fc24dc13aee376740d721 | liquidz/cuma | core.clj | (ns cuma.core
(:require
[cuma.util.string :refer [index-of dotted-get get-paired-section-index]]
[cuma.extension :refer [collect-extension-functions-memo]]
[clojure.string :as str]))
(def read-string* (memoize read-string))
; =escape
(defn escape
"Escape string."
[s]
{:pre [(string? s)]}
(-> s (str/replace #"&" "&")
(str/replace #"\"" """)
(str/replace #"<" "<")
(str/replace #">" ">")))
; =render-variable
(defn- render-variable
[s data]
(str/replace
s #"\$(\(\s*.+?\s*\))"
(fn [[all x]]
(let [[a & b] (read-string* x)
b? (seq b)
f (if b? (dotted-get data (str a)))
args (map #(if (symbol? %) (dotted-get data (str %)) %) (if b? b [a]))
res (if b?
(if f (apply f data args) all)
(first args))]
(if (and (map? res) (contains? res :body))
(if (:raw? res)
(-> res :body str)
(-> res :body str escape))
(-> res str escape))))))
; =parse-section
(defn- parse-section
[s data ^long from]
(if-let [body-start (index-of s ")" from)]
(let [start-str (str/trim (subs s (inc from) (inc body-start)))
[f & args] (read-string* start-str)
" @(end ) " = > 6
(if-let [body-end (get-paired-section-index s from)]
{:f f
:args args
:body (str/replace (subs s (inc body-start) body-end) #"^[\r\n]+" "")
:all (subs s from (+ body-end end-len))}
s))
s))
; =render-section
(defn- render-section
[s data from]
(if-let [sec-start (index-of s "@(" from)]
(let [{:keys [f args body all]} (parse-section s data sec-start)
f (dotted-get data (str f))
args (map #(if (symbol? %) (dotted-get data (str %)) %) args)]
(if f
(let [res (str (apply f (concat (list data body) args)))]
(recur
(str/replace-first s all res)
data
(+ sec-start (count res))))
s))
s))
; =render
(defn render
[s data]
{:pre [(string? s) (map? data)] :post [(string? %)]}
(let [m (merge {:render render}
(collect-extension-functions-memo)
data)]
(-> s
(render-section m 0)
(render-variable m))))
| null | https://raw.githubusercontent.com/liquidz/cuma/120ff58a8601e0911591696622ad385e0616f1ff/src/cuma/core.clj | clojure | =escape
")
=render-variable
=parse-section
=render-section
=render | (ns cuma.core
(:require
[cuma.util.string :refer [index-of dotted-get get-paired-section-index]]
[cuma.extension :refer [collect-extension-functions-memo]]
[clojure.string :as str]))
(def read-string* (memoize read-string))
(defn escape
"Escape string."
[s]
{:pre [(string? s)]}
(-> s (str/replace #"&" "&")
(str/replace #"<" "<")
(str/replace #">" ">")))
(defn- render-variable
[s data]
(str/replace
s #"\$(\(\s*.+?\s*\))"
(fn [[all x]]
(let [[a & b] (read-string* x)
b? (seq b)
f (if b? (dotted-get data (str a)))
args (map #(if (symbol? %) (dotted-get data (str %)) %) (if b? b [a]))
res (if b?
(if f (apply f data args) all)
(first args))]
(if (and (map? res) (contains? res :body))
(if (:raw? res)
(-> res :body str)
(-> res :body str escape))
(-> res str escape))))))
(defn- parse-section
[s data ^long from]
(if-let [body-start (index-of s ")" from)]
(let [start-str (str/trim (subs s (inc from) (inc body-start)))
[f & args] (read-string* start-str)
" @(end ) " = > 6
(if-let [body-end (get-paired-section-index s from)]
{:f f
:args args
:body (str/replace (subs s (inc body-start) body-end) #"^[\r\n]+" "")
:all (subs s from (+ body-end end-len))}
s))
s))
(defn- render-section
[s data from]
(if-let [sec-start (index-of s "@(" from)]
(let [{:keys [f args body all]} (parse-section s data sec-start)
f (dotted-get data (str f))
args (map #(if (symbol? %) (dotted-get data (str %)) %) args)]
(if f
(let [res (str (apply f (concat (list data body) args)))]
(recur
(str/replace-first s all res)
data
(+ sec-start (count res))))
s))
s))
(defn render
[s data]
{:pre [(string? s) (map? data)] :post [(string? %)]}
(let [m (merge {:render render}
(collect-extension-functions-memo)
data)]
(-> s
(render-section m 0)
(render-variable m))))
|
6a4ee02bbfdde3f10c318bcde190b60a74b9cc2e528bbdac7bca5b473a540a58 | openmusic-project/openmusic | tests.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; tests.lisp --- Unit and regression tests for Babel.
;;;
Copyright ( C ) 2007 - 2009 ,
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
files ( the " Software " ) , to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software , and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software .
;;;
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
(in-package #:cl-user)
(defpackage #:babel-tests
(:use #:common-lisp #:babel #:babel-encodings #:hu.dwim.stefil)
(:export #:run))
(in-package #:babel-tests)
(defun run ()
(funcall-test-with-feedback-message 'babel-tests))
(defsuite* (babel-tests :in root-suite))
(defun ub8v (&rest contents)
(make-array (length contents) :element-type '(unsigned-byte 8)
:initial-contents contents))
(defun make-ub8-vector (size)
(make-array size :element-type '(unsigned-byte 8)
:initial-element 0))
(defmacro returns (form &rest values)
"Asserts, through EQUALP, that FORM returns VALUES."
`(is (equalp (multiple-value-list ,form) (list ,@values))))
(defmacro defstest (name form &body return-values)
"Similar to RT's DEFTEST."
`(deftest ,name ()
(returns ,form ,@(mapcar (lambda (x) `',x) return-values))))
(defun fail (control-string &rest arguments)
(hu.dwim.stefil::record-failure 'hu.dwim.stefil::failed-assertion
:format-control control-string
:format-arguments arguments))
(defun expected (expected &key got)
(fail "expected ~A, got ~A instead" expected got))
(enable-sharp-backslash-syntax)
;;;; Simple tests using ASCII
(defstest enc.ascii.1
(string-to-octets "abc" :encoding :ascii)
#(97 98 99))
(defstest enc.ascii.2
(string-to-octets (string #\uED) :encoding :ascii :errorp nil)
#(#x1a))
(deftest enc.ascii.3 ()
(handler-case
(string-to-octets (string #\uED) :encoding :ascii :errorp t)
(character-encoding-error (c)
(is (eql 0 (character-coding-error-position c)))
(is (eq :ascii (character-coding-error-encoding c)))
(is (eql #xed (character-encoding-error-code c))))
(:no-error (result)
(expected 'character-encoding-error :got result))))
(defstest dec.ascii.1
(octets-to-string (ub8v 97 98 99) :encoding :ascii)
"abc")
(deftest dec.ascii.2 ()
(handler-case
(octets-to-string (ub8v 97 128 99) :encoding :ascii :errorp t)
(character-decoding-error (c)
(is (equalp #(128) (character-decoding-error-octets c)))
(is (eql 1 (character-coding-error-position c)))
(is (eq :ascii (character-coding-error-encoding c))))
(:no-error (result)
(expected 'character-decoding-error :got result))))
(defstest dec.ascii.3
(octets-to-string (ub8v 97 255 98 99) :encoding :ascii :errorp nil)
#(#\a #\Sub #\b #\c))
(defstest oct-count.ascii.1
(string-size-in-octets "abc" :encoding :ascii)
3 3)
(defstest char-count.ascii.1
(vector-size-in-chars (ub8v 97 98 99) :encoding :ascii)
3 3)
UTF-8
(defstest char-count.utf-8.1
" ni hao " in with the last octet missing
(vector-size-in-chars (ub8v 228 189 160 229 165) :errorp nil)
2 5)
(deftest char-count.utf-8.2 ()
same as above with the last 2 octets missing
(handler-case
(vector-size-in-chars (ub8v 228 189 160 229) :errorp t)
(end-of-input-in-character (c)
(is (equalp #(229) (character-decoding-error-octets c)))
(is (eql 3 (character-coding-error-position c)))
(is (eq :utf-8 (character-coding-error-encoding c))))
(:no-error (result)
(expected 'end-of-input-in-character :got result))))
Lispworks bug ?
# + lispworks
( pushnew ' dec.utf-8.1 rtest::*expected - failures * )
(defstest dec.utf-8.1
(octets-to-string (ub8v 228 189 160 229) :errorp nil)
#(#\u4f60 #\ufffd))
(deftest dec.utf-8.2 ()
(handler-case
(octets-to-string (ub8v 228 189 160 229) :errorp t)
(end-of-input-in-character (c)
(is (equalp #(229) (character-decoding-error-octets c)))
(is (eql 3 (character-coding-error-position c)))
(is (eq :utf-8 (character-coding-error-encoding c))))
(:no-error (result)
(expected 'end-of-input-in-character :got result))))
;;;; UTF-16
Test that the BOM is not being counted as a character .
(deftest char-count.utf-16.bom ()
(is (eql (vector-size-in-chars (ub8v #xfe #xff #x00 #x55 #x00 #x54 #x00 #x46)
:encoding :utf-16)
3))
(is (eql (vector-size-in-chars (ub8v #xff #xfe #x00 #x55 #x00 #x54 #x00 #x46)
:encoding :utf-16)
3)))
;;;; UTF-32
RT : check that UTF-32 characters without a BOM are treated as
;;; little-endian.
(deftest endianness.utf-32.no-bom ()
(is (string= "a" (octets-to-string (ub8v 0 0 0 97) :encoding :utf-32))))
;;;; MORE TESTS
(defparameter *standard-characters*
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!$\"'(),_-./:;?+<=>#%&*@[\\]{|}`^~")
;;; Testing consistency by encoding and decoding a simple string for
;;; all character encodings.
(deftest rw-equiv.1 ()
(dolist (*default-character-encoding* (list-character-encodings))
(let ((octets (string-to-octets *standard-characters*)))
(is (string= (octets-to-string octets) *standard-characters*)))))
;;; FIXME: assumes little-endianness. Easily fixable when we
implement the BE and LE variants of : UTF-16 .
(deftest concatenate-strings-to-octets-equiv.1 ()
(let ((foo (octets-to-string (ub8v 102 195 186 195 186)
:encoding :utf-8))
(bar (octets-to-string (ub8v 98 195 161 114)
:encoding :utf-8)))
note : FOO and BAR are not ascii
(is (equalp (concatenate-strings-to-octets :utf-8 foo bar)
(ub8v 102 195 186 195 186 98 195 161 114)))
(is (equalp (concatenate-strings-to-octets :utf-16 foo bar)
(ub8v 102 0 250 0 250 0 98 0 225 0 114 0)))))
;;;; Testing against files generated by GNU iconv.
(defun test-file (name type)
(let ((sys-pn (truename
(asdf:system-definition-pathname
(asdf:find-system 'babel-tests)))))
(make-pathname :name name :type type
:directory (append (pathname-directory sys-pn)
'("tests"))
:defaults sys-pn)))
(defun read-test-file (name type)
(with-open-file (in (test-file name type) :element-type '(unsigned-byte 8))
(let* ((data (loop for byte = (read-byte in nil nil)
until (null byte) collect byte)))
(make-array (length data) :element-type '(unsigned-byte 8)
:initial-contents data))))
(deftest test-encoding (enc &optional input-enc-name)
(let* ((*default-character-encoding* enc)
(enc-name (string-downcase (symbol-name enc)))
(utf8-octets (read-test-file enc-name "txt-utf8"))
(foo-octets (read-test-file (or input-enc-name enc-name) "txt"))
(utf8-string (octets-to-string utf8-octets :encoding :utf-8 :errorp t))
(foo-string (octets-to-string foo-octets :errorp t)))
(is (string= utf8-string foo-string))
(is (= (length foo-string) (vector-size-in-chars foo-octets :errorp t)))
(unless (member enc '(:utf-16 :utf-32))
;; FIXME: skipping UTF-16 and UTF-32 because of the BOMs and
;; because the input might not be in native-endian order so the
;; comparison will fail there.
(let ((new-octets (string-to-octets foo-string :errorp t)))
(is (equalp new-octets foo-octets))
(is (eql (length foo-octets)
(string-size-in-octets foo-string :errorp t)))))))
(deftest iconv-test ()
(dolist (enc '(:ascii :ebcdic-us :utf-8 :utf-16 :utf-32))
(case enc
(:utf-16 (test-encoding :utf-16 "utf-16-with-le-bom"))
(:utf-32 (test-encoding :utf-32 "utf-32-with-le-bom")))
(test-encoding enc)))
RT : accept encoding objects in LOOKUP - MAPPING etc .
(defstest encoding-objects.1
(string-to-octets "abc" :encoding (get-character-encoding :ascii))
#(97 98 99))
(defmacro with-sharp-backslash-syntax (&body body)
`(let ((*readtable* (copy-readtable *readtable*)))
(set-sharp-backslash-syntax-in-readtable)
,@body))
(defstest sharp-backslash.1
(with-sharp-backslash-syntax
(loop for string in '("#\\a" "#\\u" "#\\ued")
collect (char-code (read-from-string string))))
(97 117 #xed))
(deftest sharp-backslash.2 ()
(signals reader-error (with-sharp-backslash-syntax
(read-from-string "#\\u12zz"))))
(deftest test-read-from-string (string object position)
"Test that (read-from-string STRING) returns values OBJECT and POSITION."
(multiple-value-bind (obj pos)
(read-from-string string)
(is (eql object obj))
(is (eql position pos))))
RT : our # \ reader did n't honor * READ - SUPPRESS * .
(deftest sharp-backslash.3 ()
(with-sharp-backslash-syntax
(let ((*read-suppress* t))
(test-read-from-string "#\\ujunk" nil 7)
(test-read-from-string "#\\u12zz" nil 7))))
RT : the slow implementation of with - simple - vector was buggy .
(defstest string-to-octets.1
(code-char (aref (string-to-octets "abc" :start 1 :end 2) 0))
#\b)
(defstest simple-base-string.1
(string-to-octets (coerce "abc" 'base-string) :encoding :ascii)
#(97 98 99))
For now , disable this tests for that are strict about
;;; non-character code points. In the future, simply mark them as
;;; expected failures.
#-(or abcl ccl)
(progn
(defstest utf-8b.1
(string-to-octets (coerce #(#\a #\b #\udcf0) 'unicode-string)
:encoding :utf-8b)
#(97 98 #xf0))
(defstest utf-8b.2
(octets-to-string (ub8v 97 98 #xcd) :encoding :utf-8b)
#(#\a #\b #\udccd))
(defstest utf-8b.3
(octets-to-string (ub8v 97 #xf0 #xf1 #xff #x01) :encoding :utf-8b)
#(#\a #\udcf0 #\udcf1 #\udcff #\udc01))
(deftest utf-8b.4 ()
(let* ((octets (coerce (loop repeat 8192 collect (random (+ #x82)))
'(array (unsigned-byte 8) (*))))
(string (octets-to-string octets :encoding :utf-8b)))
(is (equalp octets (string-to-octets string :encoding :utf-8b))))))
The following tests have been adapted from SBCL 's
;;; tests/octets.pure.lisp file.
(deftest ensure-roundtrip-ascii ()
(let ((octets (make-ub8-vector 128)))
(dotimes (i 128)
(setf (aref octets i) i))
(let* ((str (octets-to-string octets :encoding :ascii))
(oct2 (string-to-octets str :encoding :ascii)))
(is (= (length octets) (length oct2)))
(is (every #'= octets oct2)))))
(deftest test-8bit-roundtrip (enc)
(let ((octets (make-ub8-vector 256)))
(dotimes (i 256)
(setf (aref octets i) i))
(let* ((str (octets-to-string octets :encoding enc)))
;; remove the undefined code-points because they translate
to # xFFFD and string - to - octets raises an error when
;; encoding #xFFFD
(multiple-value-bind (filtered-str filtered-octets)
(let ((s (make-array 0 :element-type 'character
:adjustable t :fill-pointer 0))
(o (make-array 0 :element-type '(unsigned-byte 16)
:adjustable t :fill-pointer 0)))
(loop for i below 256
for c = (aref str i)
when (/= (char-code c) #xFFFD)
do (vector-push-extend c s)
(vector-push-extend (aref octets i) o))
(values s o))
(let ((oct2 (string-to-octets filtered-str :encoding enc)))
(is (eql (length filtered-octets) (length oct2)))
(is (every #'eql filtered-octets oct2)))))))
(defparameter *iso-8859-charsets*
'(:iso-8859-1 :iso-8859-2 :iso-8859-3 :iso-8859-4 :iso-8859-5 :iso-8859-6
:iso-8859-7 :iso-8859-8 :iso-8859-9 :iso-8859-10 :iso-8859-11 :iso-8859-13
:iso-8859-14 :iso-8859-15 :iso-8859-16))
;;; Don't actually see what comes out, but there shouldn't be any
;;; errors.
(deftest iso-8859-roundtrip-no-checking ()
(loop for enc in *iso-8859-charsets* do (test-8bit-roundtrip enc)))
(deftest ensure-roundtrip-latin ()
(loop for enc in '(:latin1 :latin9) do (test-8bit-roundtrip enc)))
Latin-9 chars ; the previous test checked roundtrip from
;;; octets->char and back, now test that the latin-9 characters did in
;;; fact appear during that trip.
(deftest ensure-roundtrip-latin9 ()
(let ((l9c (map 'string #'code-char '(8364 352 353 381 382 338 339 376))))
(is (string= (octets-to-string (string-to-octets l9c :encoding :latin9)
:encoding :latin9)
l9c))))
Expected to fail on that are strict about non - character code
points . this as an expected failure when Stefil supports such
;; a feature.
#-(or abcl ccl)
(deftest code-char-nilness ()
(is (loop for i below unicode-char-code-limit
never (null (code-char i)))))
(deftest test-unicode-roundtrip (enc)
(let ((string (make-string unicode-char-code-limit)))
(dotimes (i unicode-char-code-limit)
(setf (char string i)
(if (or (<= #xD800 i #xDFFF)
(<= #xFDD0 i #xFDEF)
(eql (logand i #xFFFF) #xFFFF)
(eql (logand i #xFFFF) #xFFFE))
#\? ; don't try to encode non-characters.
(code-char i))))
(let ((string2 (octets-to-string
(string-to-octets string :encoding enc :errorp t)
:encoding enc :errorp t)))
(is (eql (length string2) (length string)))
(is (string= string string2)))))
(deftest ensure-roundtrip.utf8 ()
(test-unicode-roundtrip :utf-8))
(deftest ensure-roundtrip.utf16 ()
(test-unicode-roundtrip :utf-16))
(deftest ensure-roundtrip.utf32 ()
(test-unicode-roundtrip :utf-32))
#+sbcl
(progn
(deftest test-encode-against-sbcl (enc)
(let ((string (make-string unicode-char-code-limit)))
(dotimes (i unicode-char-code-limit)
(setf (char string i) (code-char i)))
(loop for ch across string
for babel = (string-to-octets (string ch) :encoding enc)
for sbcl = (sb-ext:string-to-octets (string ch)
:external-format enc)
do (is (equalp babel sbcl)))))
not run automatically because it 's a bit slow ( 1114112 assertions )
(deftest (test-encode-against-sbcl.utf-8 :auto-call nil) ()
(test-encode-against-sbcl :utf-8)))
(deftest non-ascii-bytes ()
(let ((octets (make-array 128
:element-type '(unsigned-byte 8)
:initial-contents (loop for i from 128 below 256
collect i))))
(is (string= (octets-to-string octets :encoding :ascii :errorp nil)
(make-string 128 :initial-element #\Sub)))))
(deftest non-ascii-chars ()
(let ((string (make-array 128
:element-type 'character
:initial-contents (loop for i from 128 below 256
collect (code-char i)))))
(is (equalp (string-to-octets string :encoding :ascii :errorp nil)
(make-array 128 :initial-element (char-code #\Sub))))))
The following UTF-8 decoding tests are adapted from
;;;; </~mgk25/ucs/examples/UTF-8-test.txt>.
(deftest utf8-decode-test (octets expected-results expected-errors)
(let ((string (octets-to-string (coerce octets '(vector (unsigned-byte 8) *))
:encoding :utf-8 :errorp nil)))
(is (string= expected-results string))
(is (= (count #\ufffd string) expected-errors))))
(deftest utf8-decode-tests (octets expected-results)
(let ((expected-errors (count #\? expected-results))
(expected-results (substitute #\ufffd #\? expected-results)))
(utf8-decode-test octets expected-results expected-errors)
(utf8-decode-test (concatenate 'vector '(34) octets '(34))
(format nil "\"~A\"" expected-results)
expected-errors)))
(deftest utf8-too-big-characters ()
# x110000
# x1fffff
(utf8-decode-tests #(#xf8 #x88 #x80 #x80 #x80) "?") ; #x200000
(utf8-decode-tests #(#xfb #xbf #xbf #xbf #xbf) "?") ; #x3ffffff
(utf8-decode-tests #(#xfc #x84 #x80 #x80 #x80 #x80) "?") ; #x4000000e
(utf8-decode-tests #(#xfd #xbf #xbf #xbf #xbf #xbf) "?")) ; #x7fffffff
(deftest utf8-unexpected-continuation-bytes ()
(utf8-decode-tests #(#x80) "?")
(utf8-decode-tests #(#xbf) "?")
(utf8-decode-tests #(#x80 #xbf) "??")
(utf8-decode-tests #(#x80 #xbf #x80) "???")
(utf8-decode-tests #(#x80 #xbf #x80 #xbf) "????")
(utf8-decode-tests #(#x80 #xbf #x80 #xbf #x80) "?????")
(utf8-decode-tests #(#x80 #xbf #x80 #xbf #x80 #xbf) "??????")
(utf8-decode-tests #(#x80 #xbf #x80 #xbf #x80 #xbf #x80) "???????"))
All 64 continuation bytes in a row .
(deftest utf8-continuation-bytes ()
(apply #'utf8-decode-tests
(loop for i from #x80 to #xbf
collect i into bytes
collect #\? into chars
finally (return (list bytes
(coerce chars 'string))))))
(deftest utf8-lonely-start-characters ()
(flet ((lsc (first last)
(apply #'utf8-decode-tests
(loop for i from first to last
nconc (list i 32) into bytes
nconc (list #\? #\Space) into chars
finally (return (list bytes (coerce chars 'string)))))
(apply #'utf8-decode-tests
(loop for i from first to last
collect i into bytes
collect #\? into chars
finally (return
(list bytes (coerce chars 'string)))))))
2 - byte sequence start chars
3 - byte
4 - byte
5 - byte
6 - byte
;;; Otherwise incomplete sequences (last continuation byte missing)
(deftest utf8-incomplete-sequences ()
(utf8-decode-tests #0=#(#xc0) "?")
(utf8-decode-tests #1=#(#xe0 #x80) "?")
(utf8-decode-tests #2=#(#xf0 #x80 #x80) "?")
(utf8-decode-tests #3=#(#xf8 #x80 #x80 #x80) "?")
(utf8-decode-tests #4=#(#xfc #x80 #x80 #x80 #x80) "?")
(utf8-decode-tests #5=#(#xdf) "?")
(utf8-decode-tests #6=#(#xef #xbf) "?")
(utf8-decode-tests #7=#(#xf7 #xbf #xbf) "?")
(utf8-decode-tests #8=#(#xfb #xbf #xbf #xbf) "?")
(utf8-decode-tests #9=#(#xfd #xbf #xbf #xbf #xbf) "?")
All ten previous tests concatenated
(utf8-decode-tests (concatenate 'vector
#0# #1# #2# #3# #4# #5# #6# #7# #8# #9#)
"??????????"))
(deftest utf8-random-impossible-bytes ()
(utf8-decode-tests #(#xfe) "?")
(utf8-decode-tests #(#xff) "?")
(utf8-decode-tests #(#xfe #xfe #xff #xff) "????"))
(deftest utf8-overlong-sequences-/ ()
(utf8-decode-tests #(#xc0 #xaf) "?")
(utf8-decode-tests #(#xe0 #x80 #xaf) "?")
(utf8-decode-tests #(#xf0 #x80 #x80 #xaf) "?")
(utf8-decode-tests #(#xf8 #x80 #x80 #x80 #xaf) "?")
(utf8-decode-tests #(#xfc #x80 #x80 #x80 #x80 #xaf) "?"))
(deftest utf8-overlong-sequences-rubout ()
(utf8-decode-tests #(#xc1 #xbf) "?")
(utf8-decode-tests #(#xe0 #x9f #xbf) "?")
(utf8-decode-tests #(#xf0 #x8f #xbf #xbf) "?")
(utf8-decode-tests #(#xf8 #x87 #xbf #xbf #xbf) "?")
(utf8-decode-tests #(#xfc #x83 #xbf #xbf #xbf #xbf) "?"))
(deftest utf8-overlong-sequences-null ()
(utf8-decode-tests #(#xc0 #x80) "?")
(utf8-decode-tests #(#xe0 #x80 #x80) "?")
(utf8-decode-tests #(#xf0 #x80 #x80 #x80) "?")
(utf8-decode-tests #(#xf8 #x80 #x80 #x80 #x80) "?")
(utf8-decode-tests #(#xfc #x80 #x80 #x80 #x80 #x80) "?"))
End of adapted SBCL tests .
;;; Expected to fail, for now.
#+#:ignore
(deftest utf8-illegal-code-positions ()
;; single UTF-16 surrogates
(utf8-decode-tests #(#xed #xa0 #x80) "?")
(utf8-decode-tests #(#xed #xad #xbf) "?")
(utf8-decode-tests #(#xed #xae #x80) "?")
(utf8-decode-tests #(#xed #xaf #xbf) "?")
(utf8-decode-tests #(#xed #xb0 #x80) "?")
(utf8-decode-tests #(#xed #xbe #x80) "?")
(utf8-decode-tests #(#xed #xbf #xbf) "?")
;; paired UTF-16 surrogates
(utf8-decode-tests #(ed a0 80 ed b0 80) "??")
(utf8-decode-tests #(ed a0 80 ed bf bf) "??")
(utf8-decode-tests #(ed ad bf ed b0 80) "??")
(utf8-decode-tests #(ed ad bf ed bf bf) "??")
(utf8-decode-tests #(ed ae 80 ed b0 80) "??")
(utf8-decode-tests #(ed ae 80 ed bf bf) "??")
(utf8-decode-tests #(ed af bf ed b0 80) "??")
(utf8-decode-tests #(ed af bf ed bf bf) "??")
;; other illegal code positions
# \uFFFE
(utf8-decode-tests #(#xef #xbf #xbf) "?")) ; #\uFFFF
;;; A list of the ISO-8859 encodings where each element is a cons with
;;; the car being a keyword denoting the encoding and the cdr being a
;;; vector enumerating the corresponding character codes.
;;;
;;; It was auto-generated from files which can be found at
;;; <ftp/>.
;;;
;;; Taken from flexi-streams.
(defparameter *iso-8859-tables*
'((:iso-8859-1 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
243 244 245 246 247 248 249 250 251 252 253 254 255))
(:iso-8859-2 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 260 728 321 164 317 346 167 168 352 350
356 377 173 381 379 176 261 731 322 180 318 347 711 184 353 351 357 378
733 382 380 340 193 194 258 196 313 262 199 268 201 280 203 282 205 206
270 272 323 327 211 212 336 214 215 344 366 218 368 220 221 354 223 341
225 226 259 228 314 263 231 269 233 281 235 283 237 238 271 273 324 328
243 244 337 246 247 345 367 250 369 252 253 355 729))
(:iso-8859-3 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 294 728 163 164 65533 292 167 168 304
350 286 308 173 65533 379 176 295 178 179 180 181 293 183 184 305 351
287 309 189 65533 380 192 193 194 65533 196 266 264 199 200 201 202 203
204 205 206 207 65533 209 210 211 212 288 214 215 284 217 218 219 220
364 348 223 224 225 226 65533 228 267 265 231 232 233 234 235 236 237
238 239 65533 241 242 243 244 289 246 247 285 249 250 251 252 365 349
729))
(:iso-8859-4 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 260 312 342 164 296 315 167 168 352 274
290 358 173 381 175 176 261 731 343 180 297 316 711 184 353 275 291 359
330 382 331 256 193 194 195 196 197 198 302 268 201 280 203 278 205 206
298 272 325 332 310 212 213 214 215 216 370 218 219 220 360 362 223 257
225 226 227 228 229 230 303 269 233 281 235 279 237 238 299 273 326 333
311 244 245 246 247 248 371 250 251 252 361 363 729))
(:iso-8859-5 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 1025 1026 1027 1028 1029 1030 1031 1032
1033 1034 1035 1036 173 1038 1039 1040 1041 1042 1043 1044 1045 1046
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
1103 8470 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
167 1118 1119))
(:iso-8859-6 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 65533 65533 65533 164 65533 65533 65533
65533 65533 65533 65533 1548 173 65533 65533 65533 65533 65533 65533
65533 65533 65533 65533 65533 65533 65533 1563 65533 65533 65533 1567
65533 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 65533
65533 65533 65533 65533 1600 1601 1602 1603 1604 1605 1606 1607 1608
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 65533 65533 65533
65533 65533 65533 65533 65533 65533 65533 65533 65533 65533))
(:iso-8859-7 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 8216 8217 163 8364 8367 166 167 168 169
890 171 172 173 65533 8213 176 177 178 179 900 901 902 183 904 905 906
187 908 189 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
925 926 927 928 929 65533 931 932 933 934 935 936 937 938 939 940 941
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 65533))
(:iso-8859-8 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 65533 162 163 164 165 166 167 168 169
215 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 247 187
188 189 190 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533
65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533
65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 8215 1488
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 65533 65533
8206 8207 65533))
(:iso-8859-9 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
207 286 209 210 211 212 213 214 215 216 217 218 219 220 304 350 223 224
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 287 241 242
243 244 245 246 247 248 249 250 251 252 305 351 255))
(:iso-8859-10 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 260 274 290 298 296 310 167 315 272 352
358 381 173 362 330 176 261 275 291 299 297 311 183 316 273 353 359 382
8213 363 331 256 193 194 195 196 197 198 302 268 201 280 203 278 205 206
207 208 325 332 211 212 213 214 360 216 370 218 219 220 221 222 223 257
225 226 227 228 229 230 303 269 233 281 235 279 237 238 239 240 326 333
243 244 245 246 361 248 371 250 251 252 253 254 312))
(:iso-8859-11 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 3585 3586 3587 3588 3589 3590 3591 3592
3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606
3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620
3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634
3635 3636 3637 3638 3639 3640 3641 3642 65533 65533 65533 65533 3647
3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661
3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675
65533 65533 65533 65533))
(:iso-8859-13 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 8221 162 163 164 8222 166 167 216 169
342 171 172 173 174 198 176 177 178 179 8220 181 182 183 248 185 343 187
188 189 190 230 260 302 256 262 196 197 280 274 268 201 377 278 290 310
298 315 352 323 325 211 332 213 214 215 370 321 346 362 220 379 381 223
261 303 257 263 228 229 281 275 269 233 378 279 291 311 299 316 353 324
326 243 333 245 246 247 371 322 347 363 252 380 382 8217))
(:iso-8859-14 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 7682 7683 163 266 267 7690 167 7808 169
7810 7691 7922 173 174 376 7710 7711 288 289 7744 7745 182 7766 7809
7767 7811 7776 7923 7812 7813 7777 192 193 194 195 196 197 198 199 200
201 202 203 204 205 206 207 372 209 210 211 212 213 214 7786 216 217 218
219 220 221 374 223 224 225 226 227 228 229 230 231 232 233 234 235 236
237 238 239 373 241 242 243 244 245 246 7787 248 249 250 251 252 253 375
255))
(:iso-8859-15 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 161 162 163 8364 165 352 167 353 169 170
171 172 173 174 175 176 177 178 179 381 181 182 183 382 185 186 187 338
339 376 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
243 244 245 246 247 248 249 250 251 252 253 254 255))
(:iso-8859-16 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 260 261 321 8364 8222 352 167 353 169
536 171 377 173 378 379 176 177 268 322 381 8221 182 183 382 269 537 187
338 339 376 380 192 193 194 258 196 262 198 199 200 201 202 203 204 205
206 207 272 323 210 211 212 336 214 346 368 217 218 219 220 280 538 223
224 225 226 259 228 263 230 231 232 233 234 235 236 237 238 239 273 324
242 243 244 337 246 347 369 249 250 251 252 281 539 255))))
(deftest iso-8859-decode-check ()
(loop for enc in *iso-8859-charsets*
for octets = (let ((octets (make-ub8-vector 256)))
(dotimes (i 256 octets)
(setf (aref octets i) i)))
for string = (octets-to-string octets :encoding enc)
do (is (equalp (map 'vector #'char-code string)
(cdr (assoc enc *iso-8859-tables*))))))
(deftest character-out-of-range.utf-32 ()
(signals character-out-of-range
(octets-to-string (ub8v 0 0 #xfe #xff 0 #x11 0 0)
:encoding :utf-32 :errorp t)))
RT : encoders and decoders were returning bogus values .
(deftest encoder/decoder-retvals (encoding &optional (test-string "abc"))
(let* ((mapping (lookup-mapping babel::*string-vector-mappings* encoding))
(strlen (length test-string))
;; encoding
(octet-precount (funcall (octet-counter mapping)
test-string 0 strlen -1))
(array (make-array octet-precount :element-type '(unsigned-byte 8)))
(encoded-octet-count (funcall (encoder mapping)
test-string 0 strlen array 0))
;; decoding
(string (make-string strlen))
(char-precount (funcall (code-point-counter mapping)
array 0 octet-precount -1))
(char-count (funcall (decoder mapping)
array 0 octet-precount string 0)))
(is (= octet-precount encoded-octet-count))
(is (= char-precount char-count))
(is (string= test-string string))))
(deftest encoder-and-decoder-return-values ()
(mapcar 'encoder/decoder-retvals
(remove-if 'ambiguous-encoding-p
(list-character-encodings))))
| null | https://raw.githubusercontent.com/openmusic-project/openmusic/9560c064512a1598cd57bcc9f0151c0815178e6f/OPENMUSIC/code/api/foreign-interface/ffi/babel/tests/tests.lisp | lisp | -*- Mode: lisp; indent-tabs-mode: nil -*-
tests.lisp --- Unit and regression tests for Babel.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
Simple tests using ASCII
UTF-16
UTF-32
little-endian.
MORE TESTS
?+<=>#%&*@[\\]{|}`^~")
Testing consistency by encoding and decoding a simple string for
all character encodings.
FIXME: assumes little-endianness. Easily fixable when we
Testing against files generated by GNU iconv.
FIXME: skipping UTF-16 and UTF-32 because of the BOMs and
because the input might not be in native-endian order so the
comparison will fail there.
non-character code points. In the future, simply mark them as
expected failures.
tests/octets.pure.lisp file.
remove the undefined code-points because they translate
encoding #xFFFD
Don't actually see what comes out, but there shouldn't be any
errors.
the previous test checked roundtrip from
octets->char and back, now test that the latin-9 characters did in
fact appear during that trip.
a feature.
don't try to encode non-characters.
</~mgk25/ucs/examples/UTF-8-test.txt>.
#x200000
#x3ffffff
#x4000000e
#x7fffffff
Otherwise incomplete sequences (last continuation byte missing)
Expected to fail, for now.
single UTF-16 surrogates
paired UTF-16 surrogates
other illegal code positions
#\uFFFF
A list of the ISO-8859 encodings where each element is a cons with
the car being a keyword denoting the encoding and the cdr being a
vector enumerating the corresponding character codes.
It was auto-generated from files which can be found at
<ftp/>.
Taken from flexi-streams.
encoding
decoding | Copyright ( C ) 2007 - 2009 ,
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
(in-package #:cl-user)
(defpackage #:babel-tests
(:use #:common-lisp #:babel #:babel-encodings #:hu.dwim.stefil)
(:export #:run))
(in-package #:babel-tests)
(defun run ()
(funcall-test-with-feedback-message 'babel-tests))
(defsuite* (babel-tests :in root-suite))
(defun ub8v (&rest contents)
(make-array (length contents) :element-type '(unsigned-byte 8)
:initial-contents contents))
(defun make-ub8-vector (size)
(make-array size :element-type '(unsigned-byte 8)
:initial-element 0))
(defmacro returns (form &rest values)
"Asserts, through EQUALP, that FORM returns VALUES."
`(is (equalp (multiple-value-list ,form) (list ,@values))))
(defmacro defstest (name form &body return-values)
"Similar to RT's DEFTEST."
`(deftest ,name ()
(returns ,form ,@(mapcar (lambda (x) `',x) return-values))))
(defun fail (control-string &rest arguments)
(hu.dwim.stefil::record-failure 'hu.dwim.stefil::failed-assertion
:format-control control-string
:format-arguments arguments))
(defun expected (expected &key got)
(fail "expected ~A, got ~A instead" expected got))
(enable-sharp-backslash-syntax)
(defstest enc.ascii.1
(string-to-octets "abc" :encoding :ascii)
#(97 98 99))
(defstest enc.ascii.2
(string-to-octets (string #\uED) :encoding :ascii :errorp nil)
#(#x1a))
(deftest enc.ascii.3 ()
(handler-case
(string-to-octets (string #\uED) :encoding :ascii :errorp t)
(character-encoding-error (c)
(is (eql 0 (character-coding-error-position c)))
(is (eq :ascii (character-coding-error-encoding c)))
(is (eql #xed (character-encoding-error-code c))))
(:no-error (result)
(expected 'character-encoding-error :got result))))
(defstest dec.ascii.1
(octets-to-string (ub8v 97 98 99) :encoding :ascii)
"abc")
(deftest dec.ascii.2 ()
(handler-case
(octets-to-string (ub8v 97 128 99) :encoding :ascii :errorp t)
(character-decoding-error (c)
(is (equalp #(128) (character-decoding-error-octets c)))
(is (eql 1 (character-coding-error-position c)))
(is (eq :ascii (character-coding-error-encoding c))))
(:no-error (result)
(expected 'character-decoding-error :got result))))
(defstest dec.ascii.3
(octets-to-string (ub8v 97 255 98 99) :encoding :ascii :errorp nil)
#(#\a #\Sub #\b #\c))
(defstest oct-count.ascii.1
(string-size-in-octets "abc" :encoding :ascii)
3 3)
(defstest char-count.ascii.1
(vector-size-in-chars (ub8v 97 98 99) :encoding :ascii)
3 3)
UTF-8
(defstest char-count.utf-8.1
" ni hao " in with the last octet missing
(vector-size-in-chars (ub8v 228 189 160 229 165) :errorp nil)
2 5)
(deftest char-count.utf-8.2 ()
same as above with the last 2 octets missing
(handler-case
(vector-size-in-chars (ub8v 228 189 160 229) :errorp t)
(end-of-input-in-character (c)
(is (equalp #(229) (character-decoding-error-octets c)))
(is (eql 3 (character-coding-error-position c)))
(is (eq :utf-8 (character-coding-error-encoding c))))
(:no-error (result)
(expected 'end-of-input-in-character :got result))))
Lispworks bug ?
# + lispworks
( pushnew ' dec.utf-8.1 rtest::*expected - failures * )
(defstest dec.utf-8.1
(octets-to-string (ub8v 228 189 160 229) :errorp nil)
#(#\u4f60 #\ufffd))
(deftest dec.utf-8.2 ()
(handler-case
(octets-to-string (ub8v 228 189 160 229) :errorp t)
(end-of-input-in-character (c)
(is (equalp #(229) (character-decoding-error-octets c)))
(is (eql 3 (character-coding-error-position c)))
(is (eq :utf-8 (character-coding-error-encoding c))))
(:no-error (result)
(expected 'end-of-input-in-character :got result))))
Test that the BOM is not being counted as a character .
(deftest char-count.utf-16.bom ()
(is (eql (vector-size-in-chars (ub8v #xfe #xff #x00 #x55 #x00 #x54 #x00 #x46)
:encoding :utf-16)
3))
(is (eql (vector-size-in-chars (ub8v #xff #xfe #x00 #x55 #x00 #x54 #x00 #x46)
:encoding :utf-16)
3)))
RT : check that UTF-32 characters without a BOM are treated as
(deftest endianness.utf-32.no-bom ()
(is (string= "a" (octets-to-string (ub8v 0 0 0 97) :encoding :utf-32))))
(defparameter *standard-characters*
(deftest rw-equiv.1 ()
(dolist (*default-character-encoding* (list-character-encodings))
(let ((octets (string-to-octets *standard-characters*)))
(is (string= (octets-to-string octets) *standard-characters*)))))
implement the BE and LE variants of : UTF-16 .
(deftest concatenate-strings-to-octets-equiv.1 ()
(let ((foo (octets-to-string (ub8v 102 195 186 195 186)
:encoding :utf-8))
(bar (octets-to-string (ub8v 98 195 161 114)
:encoding :utf-8)))
note : FOO and BAR are not ascii
(is (equalp (concatenate-strings-to-octets :utf-8 foo bar)
(ub8v 102 195 186 195 186 98 195 161 114)))
(is (equalp (concatenate-strings-to-octets :utf-16 foo bar)
(ub8v 102 0 250 0 250 0 98 0 225 0 114 0)))))
(defun test-file (name type)
(let ((sys-pn (truename
(asdf:system-definition-pathname
(asdf:find-system 'babel-tests)))))
(make-pathname :name name :type type
:directory (append (pathname-directory sys-pn)
'("tests"))
:defaults sys-pn)))
(defun read-test-file (name type)
(with-open-file (in (test-file name type) :element-type '(unsigned-byte 8))
(let* ((data (loop for byte = (read-byte in nil nil)
until (null byte) collect byte)))
(make-array (length data) :element-type '(unsigned-byte 8)
:initial-contents data))))
(deftest test-encoding (enc &optional input-enc-name)
(let* ((*default-character-encoding* enc)
(enc-name (string-downcase (symbol-name enc)))
(utf8-octets (read-test-file enc-name "txt-utf8"))
(foo-octets (read-test-file (or input-enc-name enc-name) "txt"))
(utf8-string (octets-to-string utf8-octets :encoding :utf-8 :errorp t))
(foo-string (octets-to-string foo-octets :errorp t)))
(is (string= utf8-string foo-string))
(is (= (length foo-string) (vector-size-in-chars foo-octets :errorp t)))
(unless (member enc '(:utf-16 :utf-32))
(let ((new-octets (string-to-octets foo-string :errorp t)))
(is (equalp new-octets foo-octets))
(is (eql (length foo-octets)
(string-size-in-octets foo-string :errorp t)))))))
(deftest iconv-test ()
(dolist (enc '(:ascii :ebcdic-us :utf-8 :utf-16 :utf-32))
(case enc
(:utf-16 (test-encoding :utf-16 "utf-16-with-le-bom"))
(:utf-32 (test-encoding :utf-32 "utf-32-with-le-bom")))
(test-encoding enc)))
RT : accept encoding objects in LOOKUP - MAPPING etc .
(defstest encoding-objects.1
(string-to-octets "abc" :encoding (get-character-encoding :ascii))
#(97 98 99))
(defmacro with-sharp-backslash-syntax (&body body)
`(let ((*readtable* (copy-readtable *readtable*)))
(set-sharp-backslash-syntax-in-readtable)
,@body))
(defstest sharp-backslash.1
(with-sharp-backslash-syntax
(loop for string in '("#\\a" "#\\u" "#\\ued")
collect (char-code (read-from-string string))))
(97 117 #xed))
(deftest sharp-backslash.2 ()
(signals reader-error (with-sharp-backslash-syntax
(read-from-string "#\\u12zz"))))
(deftest test-read-from-string (string object position)
"Test that (read-from-string STRING) returns values OBJECT and POSITION."
(multiple-value-bind (obj pos)
(read-from-string string)
(is (eql object obj))
(is (eql position pos))))
RT : our # \ reader did n't honor * READ - SUPPRESS * .
(deftest sharp-backslash.3 ()
(with-sharp-backslash-syntax
(let ((*read-suppress* t))
(test-read-from-string "#\\ujunk" nil 7)
(test-read-from-string "#\\u12zz" nil 7))))
RT : the slow implementation of with - simple - vector was buggy .
(defstest string-to-octets.1
(code-char (aref (string-to-octets "abc" :start 1 :end 2) 0))
#\b)
(defstest simple-base-string.1
(string-to-octets (coerce "abc" 'base-string) :encoding :ascii)
#(97 98 99))
For now , disable this tests for that are strict about
#-(or abcl ccl)
(progn
(defstest utf-8b.1
(string-to-octets (coerce #(#\a #\b #\udcf0) 'unicode-string)
:encoding :utf-8b)
#(97 98 #xf0))
(defstest utf-8b.2
(octets-to-string (ub8v 97 98 #xcd) :encoding :utf-8b)
#(#\a #\b #\udccd))
(defstest utf-8b.3
(octets-to-string (ub8v 97 #xf0 #xf1 #xff #x01) :encoding :utf-8b)
#(#\a #\udcf0 #\udcf1 #\udcff #\udc01))
(deftest utf-8b.4 ()
(let* ((octets (coerce (loop repeat 8192 collect (random (+ #x82)))
'(array (unsigned-byte 8) (*))))
(string (octets-to-string octets :encoding :utf-8b)))
(is (equalp octets (string-to-octets string :encoding :utf-8b))))))
The following tests have been adapted from SBCL 's
(deftest ensure-roundtrip-ascii ()
(let ((octets (make-ub8-vector 128)))
(dotimes (i 128)
(setf (aref octets i) i))
(let* ((str (octets-to-string octets :encoding :ascii))
(oct2 (string-to-octets str :encoding :ascii)))
(is (= (length octets) (length oct2)))
(is (every #'= octets oct2)))))
(deftest test-8bit-roundtrip (enc)
(let ((octets (make-ub8-vector 256)))
(dotimes (i 256)
(setf (aref octets i) i))
(let* ((str (octets-to-string octets :encoding enc)))
to # xFFFD and string - to - octets raises an error when
(multiple-value-bind (filtered-str filtered-octets)
(let ((s (make-array 0 :element-type 'character
:adjustable t :fill-pointer 0))
(o (make-array 0 :element-type '(unsigned-byte 16)
:adjustable t :fill-pointer 0)))
(loop for i below 256
for c = (aref str i)
when (/= (char-code c) #xFFFD)
do (vector-push-extend c s)
(vector-push-extend (aref octets i) o))
(values s o))
(let ((oct2 (string-to-octets filtered-str :encoding enc)))
(is (eql (length filtered-octets) (length oct2)))
(is (every #'eql filtered-octets oct2)))))))
(defparameter *iso-8859-charsets*
'(:iso-8859-1 :iso-8859-2 :iso-8859-3 :iso-8859-4 :iso-8859-5 :iso-8859-6
:iso-8859-7 :iso-8859-8 :iso-8859-9 :iso-8859-10 :iso-8859-11 :iso-8859-13
:iso-8859-14 :iso-8859-15 :iso-8859-16))
(deftest iso-8859-roundtrip-no-checking ()
(loop for enc in *iso-8859-charsets* do (test-8bit-roundtrip enc)))
(deftest ensure-roundtrip-latin ()
(loop for enc in '(:latin1 :latin9) do (test-8bit-roundtrip enc)))
(deftest ensure-roundtrip-latin9 ()
(let ((l9c (map 'string #'code-char '(8364 352 353 381 382 338 339 376))))
(is (string= (octets-to-string (string-to-octets l9c :encoding :latin9)
:encoding :latin9)
l9c))))
Expected to fail on that are strict about non - character code
points . this as an expected failure when Stefil supports such
#-(or abcl ccl)
(deftest code-char-nilness ()
(is (loop for i below unicode-char-code-limit
never (null (code-char i)))))
(deftest test-unicode-roundtrip (enc)
(let ((string (make-string unicode-char-code-limit)))
(dotimes (i unicode-char-code-limit)
(setf (char string i)
(if (or (<= #xD800 i #xDFFF)
(<= #xFDD0 i #xFDEF)
(eql (logand i #xFFFF) #xFFFF)
(eql (logand i #xFFFF) #xFFFE))
(code-char i))))
(let ((string2 (octets-to-string
(string-to-octets string :encoding enc :errorp t)
:encoding enc :errorp t)))
(is (eql (length string2) (length string)))
(is (string= string string2)))))
(deftest ensure-roundtrip.utf8 ()
(test-unicode-roundtrip :utf-8))
(deftest ensure-roundtrip.utf16 ()
(test-unicode-roundtrip :utf-16))
(deftest ensure-roundtrip.utf32 ()
(test-unicode-roundtrip :utf-32))
#+sbcl
(progn
(deftest test-encode-against-sbcl (enc)
(let ((string (make-string unicode-char-code-limit)))
(dotimes (i unicode-char-code-limit)
(setf (char string i) (code-char i)))
(loop for ch across string
for babel = (string-to-octets (string ch) :encoding enc)
for sbcl = (sb-ext:string-to-octets (string ch)
:external-format enc)
do (is (equalp babel sbcl)))))
not run automatically because it 's a bit slow ( 1114112 assertions )
(deftest (test-encode-against-sbcl.utf-8 :auto-call nil) ()
(test-encode-against-sbcl :utf-8)))
(deftest non-ascii-bytes ()
(let ((octets (make-array 128
:element-type '(unsigned-byte 8)
:initial-contents (loop for i from 128 below 256
collect i))))
(is (string= (octets-to-string octets :encoding :ascii :errorp nil)
(make-string 128 :initial-element #\Sub)))))
(deftest non-ascii-chars ()
(let ((string (make-array 128
:element-type 'character
:initial-contents (loop for i from 128 below 256
collect (code-char i)))))
(is (equalp (string-to-octets string :encoding :ascii :errorp nil)
(make-array 128 :initial-element (char-code #\Sub))))))
The following UTF-8 decoding tests are adapted from
(deftest utf8-decode-test (octets expected-results expected-errors)
(let ((string (octets-to-string (coerce octets '(vector (unsigned-byte 8) *))
:encoding :utf-8 :errorp nil)))
(is (string= expected-results string))
(is (= (count #\ufffd string) expected-errors))))
(deftest utf8-decode-tests (octets expected-results)
(let ((expected-errors (count #\? expected-results))
(expected-results (substitute #\ufffd #\? expected-results)))
(utf8-decode-test octets expected-results expected-errors)
(utf8-decode-test (concatenate 'vector '(34) octets '(34))
(format nil "\"~A\"" expected-results)
expected-errors)))
(deftest utf8-too-big-characters ()
# x110000
# x1fffff
(deftest utf8-unexpected-continuation-bytes ()
(utf8-decode-tests #(#x80) "?")
(utf8-decode-tests #(#xbf) "?")
(utf8-decode-tests #(#x80 #xbf) "??")
(utf8-decode-tests #(#x80 #xbf #x80) "???")
(utf8-decode-tests #(#x80 #xbf #x80 #xbf) "????")
(utf8-decode-tests #(#x80 #xbf #x80 #xbf #x80) "?????")
(utf8-decode-tests #(#x80 #xbf #x80 #xbf #x80 #xbf) "??????")
(utf8-decode-tests #(#x80 #xbf #x80 #xbf #x80 #xbf #x80) "???????"))
All 64 continuation bytes in a row .
(deftest utf8-continuation-bytes ()
(apply #'utf8-decode-tests
(loop for i from #x80 to #xbf
collect i into bytes
collect #\? into chars
finally (return (list bytes
(coerce chars 'string))))))
(deftest utf8-lonely-start-characters ()
(flet ((lsc (first last)
(apply #'utf8-decode-tests
(loop for i from first to last
nconc (list i 32) into bytes
nconc (list #\? #\Space) into chars
finally (return (list bytes (coerce chars 'string)))))
(apply #'utf8-decode-tests
(loop for i from first to last
collect i into bytes
collect #\? into chars
finally (return
(list bytes (coerce chars 'string)))))))
2 - byte sequence start chars
3 - byte
4 - byte
5 - byte
6 - byte
(deftest utf8-incomplete-sequences ()
(utf8-decode-tests #0=#(#xc0) "?")
(utf8-decode-tests #1=#(#xe0 #x80) "?")
(utf8-decode-tests #2=#(#xf0 #x80 #x80) "?")
(utf8-decode-tests #3=#(#xf8 #x80 #x80 #x80) "?")
(utf8-decode-tests #4=#(#xfc #x80 #x80 #x80 #x80) "?")
(utf8-decode-tests #5=#(#xdf) "?")
(utf8-decode-tests #6=#(#xef #xbf) "?")
(utf8-decode-tests #7=#(#xf7 #xbf #xbf) "?")
(utf8-decode-tests #8=#(#xfb #xbf #xbf #xbf) "?")
(utf8-decode-tests #9=#(#xfd #xbf #xbf #xbf #xbf) "?")
All ten previous tests concatenated
(utf8-decode-tests (concatenate 'vector
#0# #1# #2# #3# #4# #5# #6# #7# #8# #9#)
"??????????"))
(deftest utf8-random-impossible-bytes ()
(utf8-decode-tests #(#xfe) "?")
(utf8-decode-tests #(#xff) "?")
(utf8-decode-tests #(#xfe #xfe #xff #xff) "????"))
(deftest utf8-overlong-sequences-/ ()
(utf8-decode-tests #(#xc0 #xaf) "?")
(utf8-decode-tests #(#xe0 #x80 #xaf) "?")
(utf8-decode-tests #(#xf0 #x80 #x80 #xaf) "?")
(utf8-decode-tests #(#xf8 #x80 #x80 #x80 #xaf) "?")
(utf8-decode-tests #(#xfc #x80 #x80 #x80 #x80 #xaf) "?"))
(deftest utf8-overlong-sequences-rubout ()
(utf8-decode-tests #(#xc1 #xbf) "?")
(utf8-decode-tests #(#xe0 #x9f #xbf) "?")
(utf8-decode-tests #(#xf0 #x8f #xbf #xbf) "?")
(utf8-decode-tests #(#xf8 #x87 #xbf #xbf #xbf) "?")
(utf8-decode-tests #(#xfc #x83 #xbf #xbf #xbf #xbf) "?"))
(deftest utf8-overlong-sequences-null ()
(utf8-decode-tests #(#xc0 #x80) "?")
(utf8-decode-tests #(#xe0 #x80 #x80) "?")
(utf8-decode-tests #(#xf0 #x80 #x80 #x80) "?")
(utf8-decode-tests #(#xf8 #x80 #x80 #x80 #x80) "?")
(utf8-decode-tests #(#xfc #x80 #x80 #x80 #x80 #x80) "?"))
End of adapted SBCL tests .
#+#:ignore
(deftest utf8-illegal-code-positions ()
(utf8-decode-tests #(#xed #xa0 #x80) "?")
(utf8-decode-tests #(#xed #xad #xbf) "?")
(utf8-decode-tests #(#xed #xae #x80) "?")
(utf8-decode-tests #(#xed #xaf #xbf) "?")
(utf8-decode-tests #(#xed #xb0 #x80) "?")
(utf8-decode-tests #(#xed #xbe #x80) "?")
(utf8-decode-tests #(#xed #xbf #xbf) "?")
(utf8-decode-tests #(ed a0 80 ed b0 80) "??")
(utf8-decode-tests #(ed a0 80 ed bf bf) "??")
(utf8-decode-tests #(ed ad bf ed b0 80) "??")
(utf8-decode-tests #(ed ad bf ed bf bf) "??")
(utf8-decode-tests #(ed ae 80 ed b0 80) "??")
(utf8-decode-tests #(ed ae 80 ed bf bf) "??")
(utf8-decode-tests #(ed af bf ed b0 80) "??")
(utf8-decode-tests #(ed af bf ed bf bf) "??")
# \uFFFE
(defparameter *iso-8859-tables*
'((:iso-8859-1 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
243 244 245 246 247 248 249 250 251 252 253 254 255))
(:iso-8859-2 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 260 728 321 164 317 346 167 168 352 350
356 377 173 381 379 176 261 731 322 180 318 347 711 184 353 351 357 378
733 382 380 340 193 194 258 196 313 262 199 268 201 280 203 282 205 206
270 272 323 327 211 212 336 214 215 344 366 218 368 220 221 354 223 341
225 226 259 228 314 263 231 269 233 281 235 283 237 238 271 273 324 328
243 244 337 246 247 345 367 250 369 252 253 355 729))
(:iso-8859-3 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 294 728 163 164 65533 292 167 168 304
350 286 308 173 65533 379 176 295 178 179 180 181 293 183 184 305 351
287 309 189 65533 380 192 193 194 65533 196 266 264 199 200 201 202 203
204 205 206 207 65533 209 210 211 212 288 214 215 284 217 218 219 220
364 348 223 224 225 226 65533 228 267 265 231 232 233 234 235 236 237
238 239 65533 241 242 243 244 289 246 247 285 249 250 251 252 365 349
729))
(:iso-8859-4 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 260 312 342 164 296 315 167 168 352 274
290 358 173 381 175 176 261 731 343 180 297 316 711 184 353 275 291 359
330 382 331 256 193 194 195 196 197 198 302 268 201 280 203 278 205 206
298 272 325 332 310 212 213 214 215 216 370 218 219 220 360 362 223 257
225 226 227 228 229 230 303 269 233 281 235 279 237 238 299 273 326 333
311 244 245 246 247 248 371 250 251 252 361 363 729))
(:iso-8859-5 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 1025 1026 1027 1028 1029 1030 1031 1032
1033 1034 1035 1036 173 1038 1039 1040 1041 1042 1043 1044 1045 1046
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
1103 8470 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
167 1118 1119))
(:iso-8859-6 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 65533 65533 65533 164 65533 65533 65533
65533 65533 65533 65533 1548 173 65533 65533 65533 65533 65533 65533
65533 65533 65533 65533 65533 65533 65533 1563 65533 65533 65533 1567
65533 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 65533
65533 65533 65533 65533 1600 1601 1602 1603 1604 1605 1606 1607 1608
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 65533 65533 65533
65533 65533 65533 65533 65533 65533 65533 65533 65533 65533))
(:iso-8859-7 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 8216 8217 163 8364 8367 166 167 168 169
890 171 172 173 65533 8213 176 177 178 179 900 901 902 183 904 905 906
187 908 189 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
925 926 927 928 929 65533 931 932 933 934 935 936 937 938 939 940 941
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 65533))
(:iso-8859-8 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 65533 162 163 164 165 166 167 168 169
215 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 247 187
188 189 190 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533
65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533
65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 8215 1488
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 65533 65533
8206 8207 65533))
(:iso-8859-9 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
207 286 209 210 211 212 213 214 215 216 217 218 219 220 304 350 223 224
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 287 241 242
243 244 245 246 247 248 249 250 251 252 305 351 255))
(:iso-8859-10 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 260 274 290 298 296 310 167 315 272 352
358 381 173 362 330 176 261 275 291 299 297 311 183 316 273 353 359 382
8213 363 331 256 193 194 195 196 197 198 302 268 201 280 203 278 205 206
207 208 325 332 211 212 213 214 360 216 370 218 219 220 221 222 223 257
225 226 227 228 229 230 303 269 233 281 235 279 237 238 239 240 326 333
243 244 245 246 361 248 371 250 251 252 253 254 312))
(:iso-8859-11 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 3585 3586 3587 3588 3589 3590 3591 3592
3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606
3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620
3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634
3635 3636 3637 3638 3639 3640 3641 3642 65533 65533 65533 65533 3647
3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661
3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675
65533 65533 65533 65533))
(:iso-8859-13 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 8221 162 163 164 8222 166 167 216 169
342 171 172 173 174 198 176 177 178 179 8220 181 182 183 248 185 343 187
188 189 190 230 260 302 256 262 196 197 280 274 268 201 377 278 290 310
298 315 352 323 325 211 332 213 214 215 370 321 346 362 220 379 381 223
261 303 257 263 228 229 281 275 269 233 378 279 291 311 299 316 353 324
326 243 333 245 246 247 371 322 347 363 252 380 382 8217))
(:iso-8859-14 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 7682 7683 163 266 267 7690 167 7808 169
7810 7691 7922 173 174 376 7710 7711 288 289 7744 7745 182 7766 7809
7767 7811 7776 7923 7812 7813 7777 192 193 194 195 196 197 198 199 200
201 202 203 204 205 206 207 372 209 210 211 212 213 214 7786 216 217 218
219 220 221 374 223 224 225 226 227 228 229 230 231 232 233 234 235 236
237 238 239 373 241 242 243 244 245 246 7787 248 249 250 251 252 253 375
255))
(:iso-8859-15 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 161 162 163 8364 165 352 167 353 169 170
171 172 173 174 175 176 177 178 179 381 181 182 183 382 185 186 187 338
339 376 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
243 244 245 246 247 248 249 250 251 252 253 254 255))
(:iso-8859-16 .
#(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 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 260 261 321 8364 8222 352 167 353 169
536 171 377 173 378 379 176 177 268 322 381 8221 182 183 382 269 537 187
338 339 376 380 192 193 194 258 196 262 198 199 200 201 202 203 204 205
206 207 272 323 210 211 212 336 214 346 368 217 218 219 220 280 538 223
224 225 226 259 228 263 230 231 232 233 234 235 236 237 238 239 273 324
242 243 244 337 246 347 369 249 250 251 252 281 539 255))))
(deftest iso-8859-decode-check ()
(loop for enc in *iso-8859-charsets*
for octets = (let ((octets (make-ub8-vector 256)))
(dotimes (i 256 octets)
(setf (aref octets i) i)))
for string = (octets-to-string octets :encoding enc)
do (is (equalp (map 'vector #'char-code string)
(cdr (assoc enc *iso-8859-tables*))))))
(deftest character-out-of-range.utf-32 ()
(signals character-out-of-range
(octets-to-string (ub8v 0 0 #xfe #xff 0 #x11 0 0)
:encoding :utf-32 :errorp t)))
RT : encoders and decoders were returning bogus values .
(deftest encoder/decoder-retvals (encoding &optional (test-string "abc"))
(let* ((mapping (lookup-mapping babel::*string-vector-mappings* encoding))
(strlen (length test-string))
(octet-precount (funcall (octet-counter mapping)
test-string 0 strlen -1))
(array (make-array octet-precount :element-type '(unsigned-byte 8)))
(encoded-octet-count (funcall (encoder mapping)
test-string 0 strlen array 0))
(string (make-string strlen))
(char-precount (funcall (code-point-counter mapping)
array 0 octet-precount -1))
(char-count (funcall (decoder mapping)
array 0 octet-precount string 0)))
(is (= octet-precount encoded-octet-count))
(is (= char-precount char-count))
(is (string= test-string string))))
(deftest encoder-and-decoder-return-values ()
(mapcar 'encoder/decoder-retvals
(remove-if 'ambiguous-encoding-p
(list-character-encodings))))
|
95981ef5daf62a123cbf0f09417f184c67991cf9296bed6fe4a0c4883f381f88 | witan-org/witan | context.mli | (*************************************************************************)
This file is part of Witan .
(* *)
Copyright ( C ) 2017
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
( Institut National de Recherche en Informatique et en
(* Automatique) *)
CNRS ( Centre national de la recherche scientifique )
(* *)
(* 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 ) .
(*************************************************************************)
(** Context and backtrack point management *)
type context
(** A context, with an history of backtrack point *)
type creator
(** Same than context, but only used for creating datastructure *)
val creator: context -> creator
type bp
(** A backtrack point associated to a context *)
val create: unit -> context
(** Create a new context, with a base backtrack point.
It is not possible to go below this backtrack point.
*)
val bp: context -> bp
(** Get the current backtrack point *)
val push : context -> unit
(** Push a new backtrack point *)
exception AlreadyPoped
val pop : bp -> unit
(** Pop the context associated to this backtrack point to this
backtrack point. All the backtrack point created since the given backtrack point are also poped.
raise AlreadyPoped if it already has been poped.
*)
module Ref: sig
type 'a t
(** A reference aware of a context *)
val create: creator -> 'a -> 'a t
(** Create a reference in this context with the given value *)
val set: 'a t -> 'a -> unit
(** Modify the reference *)
val get: 'a t -> 'a
(** Get the current value of the reference *)
val creator: 'a t -> creator
end
module Ref2: sig
type ('a,'b) t
(** A reference aware of a context *)
val create: creator -> 'a -> 'b -> ('a,'b) t
(** Create a reference in this context with the given value *)
val set: ('a,'b) t -> 'a -> 'b -> unit
(** Modify the reference *)
val get: ('a,'b) t -> 'a * 'b
(** Get the current value of the reference *)
val set1: ('a,'b) t -> 'a -> unit
(** Modify the reference *)
val get1: ('a,'b) t -> 'a
(** Get the current value of the reference *)
val set2: ('a,'b) t -> 'b -> unit
(** Modify the reference *)
val get2: ('a,'b) t -> 'b
(** Get the current value of the reference *)
val creator: ('a,'b) t -> creator
end
type 'a history
(** history of the values *)
module Make(S:sig
type t
(** a type to make context aware *)
type saved
(** The data to save at backtrack point *)
val save: t -> saved
(** Get the data to save from the original type *)
val restore: saved -> t -> unit
(** Restore the saved data after a pop (delayed at the next {!refresh}) *)
val get_history: t -> saved history
end): sig
val create: creator -> S.saved history
(** Create an history *)
val refresh: S.t -> unit
(** Function to call before accessing the value when a pop could have occured *)
val save: S.t -> unit
(** Function to call before modifying the value, it does also refresh *)
type hidden
(** To be used for enforcing the use of the previous function *)
val ro: hidden -> S.t
val rw: hidden -> S.t
val hide: S.t -> hidden
val creator: 'a history -> creator
end
| null | https://raw.githubusercontent.com/witan-org/witan/d26f9f810fc34bf44daccb91f71ad3258eb62037/src/stdlib/context.mli | ocaml | ***********************************************************************
alternatives)
Automatique)
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.
See the GNU Lesser General Public License version 2.1
***********************************************************************
* Context and backtrack point management
* A context, with an history of backtrack point
* Same than context, but only used for creating datastructure
* A backtrack point associated to a context
* Create a new context, with a base backtrack point.
It is not possible to go below this backtrack point.
* Get the current backtrack point
* Push a new backtrack point
* Pop the context associated to this backtrack point to this
backtrack point. All the backtrack point created since the given backtrack point are also poped.
raise AlreadyPoped if it already has been poped.
* A reference aware of a context
* Create a reference in this context with the given value
* Modify the reference
* Get the current value of the reference
* A reference aware of a context
* Create a reference in this context with the given value
* Modify the reference
* Get the current value of the reference
* Modify the reference
* Get the current value of the reference
* Modify the reference
* Get the current value of the reference
* history of the values
* a type to make context aware
* The data to save at backtrack point
* Get the data to save from the original type
* Restore the saved data after a pop (delayed at the next {!refresh})
* Create an history
* Function to call before accessing the value when a pop could have occured
* Function to call before modifying the value, it does also refresh
* To be used for enforcing the use of the previous function | This file is part of Witan .
Copyright ( C ) 2017
CEA ( Commissariat à l'énergie atomique et aux énergies
( Institut National de Recherche en Informatique et en
CNRS ( Centre national de la recherche scientifique )
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
type context
type creator
val creator: context -> creator
type bp
val create: unit -> context
val bp: context -> bp
val push : context -> unit
exception AlreadyPoped
val pop : bp -> unit
module Ref: sig
type 'a t
val create: creator -> 'a -> 'a t
val set: 'a t -> 'a -> unit
val get: 'a t -> 'a
val creator: 'a t -> creator
end
module Ref2: sig
type ('a,'b) t
val create: creator -> 'a -> 'b -> ('a,'b) t
val set: ('a,'b) t -> 'a -> 'b -> unit
val get: ('a,'b) t -> 'a * 'b
val set1: ('a,'b) t -> 'a -> unit
val get1: ('a,'b) t -> 'a
val set2: ('a,'b) t -> 'b -> unit
val get2: ('a,'b) t -> 'b
val creator: ('a,'b) t -> creator
end
type 'a history
module Make(S:sig
type t
type saved
val save: t -> saved
val restore: saved -> t -> unit
val get_history: t -> saved history
end): sig
val create: creator -> S.saved history
val refresh: S.t -> unit
val save: S.t -> unit
type hidden
val ro: hidden -> S.t
val rw: hidden -> S.t
val hide: S.t -> hidden
val creator: 'a history -> creator
end
|
c91dd944df26626e02aac0d9dd5b027c6e0af075bfbd6c8f2670f64f8badbf7f | tlaplus/tlapm | fotypes.mli | (* This code derives from a GPL'ed code and so is GPL'ed *)
type variable = string
type constant = string
type skolem = string
type varlist = variable list
type arg = Variable of variable
| Constant of constant
| Skolem of skolem * varlist
type arglist = arg list
type atom = string
type literal = Atom of atom * arglist | NotAtom of atom * arglist ;;
type formula = True (* constants *)
| False
| Literal of literal (* a literal *)
Booleans
| Or of formula * formula
| Implies of formula * formula
| Not of formula
| Forall of varlist * formula (* Quantification*)
| Exists of varlist * formula
| Always of formula (* Temporal operators*)
| AlwaysP of formula
| Sometime of formula
| SometimeP of formula
| Next of formula
| Until of formula * formula
| Unless of formula * formula
(*
type disjunct = True
| False
| Or of literal list
type cnf = True
| False
| And of disjunct list
type formulaList = True
| False
| Literal of literal
| And of formulaList list
| Or of formulaList list
*)
| null | https://raw.githubusercontent.com/tlaplus/tlapm/158386319f5b6cd299f95385a216ade2b85c9f72/translate/fotypes.mli | ocaml | This code derives from a GPL'ed code and so is GPL'ed
constants
a literal
Quantification
Temporal operators
type disjunct = True
| False
| Or of literal list
type cnf = True
| False
| And of disjunct list
type formulaList = True
| False
| Literal of literal
| And of formulaList list
| Or of formulaList list
| type variable = string
type constant = string
type skolem = string
type varlist = variable list
type arg = Variable of variable
| Constant of constant
| Skolem of skolem * varlist
type arglist = arg list
type atom = string
type literal = Atom of atom * arglist | NotAtom of atom * arglist ;;
| False
Booleans
| Or of formula * formula
| Implies of formula * formula
| Not of formula
| Exists of varlist * formula
| AlwaysP of formula
| Sometime of formula
| SometimeP of formula
| Next of formula
| Until of formula * formula
| Unless of formula * formula
|
1e0cbe4492c6575ef53577ee355d277b17b7b131c5a700ff0e3a7e51184078db | grin-compiler/grin | Pure.hs | # LANGUAGE LambdaCase , TupleSections , BangPatterns , OverloadedStrings , ConstraintKinds #
module Reducer.Pure
( EvalPlugin(..)
, reduceFun
) where
import Text.Printf
import Text.PrettyPrint.ANSI.Leijen
import Data.Foldable
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.List
import qualified Data.Text as Text
import Control.Monad.State
import Control.Monad.Reader
import Control.Monad.Except
import Foreign.C.String
import Foreign.C.Types
import Foreign.Ptr
import Foreign.LibFFI
import System.Posix.DynamicLinker
import qualified System.Info as Info
import Reducer.Base
import Reducer.PrimOps
import Grin.Grin
import Grin.Pretty
prettyDebug :: Pretty a => a -> String
prettyDebug = show . plain . pretty
-- models computer memory
data StoreMap
= StoreMap
{ storeMap :: !(IntMap RTVal)
, storeSize :: !Int
}
emptyStore = StoreMap mempty 0
newtype EvalPlugin = EvalPlugin
{ evalPluginPrimOp :: Map Name ([RTVal] -> IO RTVal)
}
type Prog = Map Name Def
data Context = Context
{ ctxProg :: Prog
, ctxExternals :: [External]
, ctxEvalPlugin :: EvalPlugin
, ctxForeign :: Map Name (FunPtr ())
}
type GrinM a = ReaderT Context (StateT (StoreMap, Statistics) IO) a
lookupStore :: Int -> StoreMap -> RTVal
lookupStore i s = IntMap.findWithDefault (error $ printf "missing location: %d" i) i $ storeMap s
debug :: Bool
debug = False
toFFIArg :: Ty -> RTVal -> GrinM Arg
toFFIArg (TySimple T_Int64) (RT_Lit (LInt64 x)) = pure $ argInt64 x
toFFIArg (TySimple T_Word64) (RT_Lit (LWord64 x)) = pure $ argWord64 x
toFFIArg (TySimple T_Float) (RT_Lit (LFloat x)) = pure $ argCFloat $ CFloat x
toFFIArg (TySimple T_Bool) (RT_Lit (LBool x)) = pure $ argInt $ if x then 1 else 0
toFFIArg (TySimple T_String) (RT_Lit (LString x)) = pure $ argString $ Text.unpack x
toFFIArg (TySimple T_Char) (RT_Lit (LChar x)) = pure $ argCChar $ castCharToCChar x
toFFIArg ty arg = throwError $ userError
$ printf "Unexpected argument type or value in FFI call: %s :: %s" (show arg) (show ty)
toFFIRet :: Ty -> GrinM (RetType RTVal)
toFFIRet (TySimple T_Int64) = pure $ withRetType (pure . RT_Lit . LInt64) retInt64
toFFIRet (TySimple T_Word64) = pure $ withRetType (pure . RT_Lit . LWord64) retWord64
toFFIRet (TySimple T_Float) = pure $ withRetType (pure . RT_Lit . LFloat . (\case CFloat x -> x)) retCFloat
toFFIRet (TySimple T_Bool) = pure $ withRetType (pure . RT_Lit . LBool . (/= 0)) retCInt
toFFIRet (TySimple T_String) = pure $ withRetType (pure . RT_Lit . LString . Text.pack) retString
toFFIRet (TySimple T_Char) = pure $ withRetType (pure . RT_Lit . LChar . castCCharToChar) retCChar
toFFIRet (TySimple T_Unit) = pure $ withRetType (const $ pure RT_Unit) retVoid
toFFIRet ty = throwError $ userError
$ printf "Unexpected return type in FFI call: %s" $ show ty
evalSimpleExp :: Env -> SimpleExp -> GrinM RTVal
evalSimpleExp env s = do
when debug $ do
liftIO $ print s
void $ liftIO getLine
case s of
SApp n a -> do
let args = map (evalVal env) a
go a [] [] = a
go a (x:xs) (y:ys) = go (Map.insert x y a) xs ys
go _ x y =
error $ printf
"invalid pattern for function: %s %s %s"
n
(prettyDebug x)
(prettyDebug y)
exts <- asks ctxExternals
evalPrimOpMap <- asks (evalPluginPrimOp . ctxEvalPlugin)
let extm = find (\e -> eName e == n) exts
case extm of
Just (External _ retTy argsTy _ FFI _) -> do
ffiArgs <- zipWithM toFFIArg argsTy args
ffiRet <- toFFIRet retTy
extFns <- asks ctxForeign
let fn = fromMaybe
(error $ printf "Missing foreign function: %s" n)
(Map.lookup n extFns)
liftIO $ callFFI fn ffiRet ffiArgs
Just _ -> do
let evalPrimOp = Map.findWithDefault
(error $ printf "undefined primop: %s" n)
n
evalPrimOpMap
liftIO $ evalPrimOp args
Nothing -> do
Def _ vars body <- reader
$ Map.findWithDefault (error $ printf "unknown function: %s" n) n . ctxProg
evalExp (go env vars args) body
SReturn v -> pure $ evalVal env v
SStore v -> do
l <- gets (storeSize . fst)
let v' = evalVal env v
modify' (\(StoreMap m s, Statistics f u) ->
( StoreMap (IntMap.insert l v' m) (s+1)
, Statistics (IntMap.insert l 0 f) (IntMap.insert l 0 u)
))
pure $ RT_Loc l
SFetchI n index -> case lookupEnv n env of
RT_Loc l -> do
modify' (\(heap, Statistics f u) ->
(heap, Statistics (IntMap.adjust (+1) l f) u))
gets $ (selectNodeItem index . lookupStore l . fst)
x -> error $ printf "evalSimpleExp - Fetch expected location, got: %s" (prettyDebug x)
-- | FetchI Name Int -- fetch node component
SUpdate n v -> do
let v' = evalVal env v
case lookupEnv n env of
RT_Loc l -> do
(StoreMap m _, _) <- get
case IntMap.member l m of
False -> error $ printf "evalSimpleExp - Update unknown location: %d" l
True -> do
modify' (\(StoreMap m s, Statistics f u) ->
(StoreMap (IntMap.insert l v' m) s, Statistics f (IntMap.adjust (+1) l u)))
pure RT_Unit
x -> error $ printf "evalSimpleExp - Update expected location, got: %s" (prettyDebug x)
SBlock a -> evalExp env a
e@ECase{} -> evalExp env e -- FIXME: this should not be here!!! please investigate.
x -> error $ printf "invalid simple expression %s" (prettyDebug x)
evalExp :: Env -> Exp -> GrinM RTVal
evalExp env = \case
EBind op pat exp -> do
v <- evalSimpleExp env op
when debug $ do
liftIO $ putStrLn $ unwords [show pat,":=",show v]
evalExp (bindPat env v pat) exp
ECase v alts -> do
let defaultAlts = [exp | Alt DefaultPat exp <- alts]
defaultAlt = if length defaultAlts > 1
then error "multiple default case alternative"
else take 1 defaultAlts
case evalVal env v of
RT_ConstTagNode t l ->
let (vars,exp) = head $ [(b,exp) | Alt (NodePat a b) exp <- alts, a == t] ++ map ([],) defaultAlt ++ error (printf "evalExp - missing Case Node alternative for: %s" (prettyDebug t))
go a [] [] = a
go a (x:xs) (y:ys) = go (Map.insert x y a) xs ys
go _ x y = error $ printf "invalid pattern and constructor: %s %s %s" (prettyDebug t) (prettyDebug x) (prettyDebug y)
in evalExp
(case vars of -- TODO: Better error check: If not default then parameters must match
_ -> go env vars l)
exp
RT_ValTag t -> evalExp env $ head $ [exp | Alt (TagPat a) exp <- alts, a == t] ++ defaultAlt ++ error (printf "evalExp - missing Case Tag alternative for: %s" (prettyDebug t))
RT_Lit l -> evalExp env $ head $ [exp | Alt (LitPat a) exp <- alts, a == l] ++ defaultAlt ++ error (printf "evalExp - missing Case Lit alternative for: %s" (show l))
x -> error $ printf "evalExp - invalid Case dispatch value: %s" (prettyDebug x)
exp -> evalSimpleExp env exp
createForeignFns :: [External] -> Map Name (FunPtr ()) -> IO (Map Name (FunPtr ()))
createForeignFns [] acc = pure acc
createForeignFns exts@(ext : _) acc
| eKind ext == PrimOp = createForeignFns (tail exts) acc
| otherwise = case find (\(os, _) -> toString os == Info.os) (eLibs ext) of
Nothing -> do
ptr <- dlsym Default $ Text.unpack $ unNM $ eName ext
createForeignFns (tail exts) $ Map.insert (eName ext) ptr acc
Just (os, lib) -> do
let (extWithLib, extNoLib) =
partition
(\e ->
find
(\(os, l) -> toString os == Info.os)
(eLibs e)
== Just (os, lib))
exts
acc' <- withDL
(Text.unpack lib)
[RTLD_LAZY]
(\dl -> foldlM (\a e -> do
ptr <- dlsym dl (Text.unpack $ unNM $ eName e)
pure $ Map.insert (eName e) ptr acc) acc extWithLib)
createForeignFns extNoLib acc'
where
toString :: OS -> String
toString = \case
Darwin -> "darwin"
FreeBSD -> "freebsd"
Linux -> "linux"
Android -> "linux-android"
MinGW -> "mingw32"
Win -> "mingw32"
NetBSD -> "netbsd"
OpenBSD -> "openbsd"
reduceFun :: EvalPlugin -> Program -> Name -> IO (RTVal, Maybe Statistics)
reduceFun evalPrimOp (Program exts l) n = do
ffiFns <- createForeignFns exts mempty
let context@(Context m _ _ _) = Context (Map.fromList [(n,d) | d@(Def n _ _) <- l]) exts evalPrimOp ffiFns
e = case Map.lookup n m of
Nothing -> error $ printf "missing function: %s" n
Just (Def _ [] a) -> a
_ -> error $ printf "function %s has arguments" n
(v, (_, s)) <- runStateT (runReaderT (evalExp mempty e) context) (emptyStore, emptyStatistics)
pure (v, Just s)
| null | https://raw.githubusercontent.com/grin-compiler/grin/4b68b848838d289573b59fae2272e6971fddb99f/grin/src/Reducer/Pure.hs | haskell | models computer memory
| FetchI Name Int -- fetch node component
FIXME: this should not be here!!! please investigate.
TODO: Better error check: If not default then parameters must match | # LANGUAGE LambdaCase , TupleSections , BangPatterns , OverloadedStrings , ConstraintKinds #
module Reducer.Pure
( EvalPlugin(..)
, reduceFun
) where
import Text.Printf
import Text.PrettyPrint.ANSI.Leijen
import Data.Foldable
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.List
import qualified Data.Text as Text
import Control.Monad.State
import Control.Monad.Reader
import Control.Monad.Except
import Foreign.C.String
import Foreign.C.Types
import Foreign.Ptr
import Foreign.LibFFI
import System.Posix.DynamicLinker
import qualified System.Info as Info
import Reducer.Base
import Reducer.PrimOps
import Grin.Grin
import Grin.Pretty
prettyDebug :: Pretty a => a -> String
prettyDebug = show . plain . pretty
data StoreMap
= StoreMap
{ storeMap :: !(IntMap RTVal)
, storeSize :: !Int
}
emptyStore = StoreMap mempty 0
newtype EvalPlugin = EvalPlugin
{ evalPluginPrimOp :: Map Name ([RTVal] -> IO RTVal)
}
type Prog = Map Name Def
data Context = Context
{ ctxProg :: Prog
, ctxExternals :: [External]
, ctxEvalPlugin :: EvalPlugin
, ctxForeign :: Map Name (FunPtr ())
}
type GrinM a = ReaderT Context (StateT (StoreMap, Statistics) IO) a
lookupStore :: Int -> StoreMap -> RTVal
lookupStore i s = IntMap.findWithDefault (error $ printf "missing location: %d" i) i $ storeMap s
debug :: Bool
debug = False
toFFIArg :: Ty -> RTVal -> GrinM Arg
toFFIArg (TySimple T_Int64) (RT_Lit (LInt64 x)) = pure $ argInt64 x
toFFIArg (TySimple T_Word64) (RT_Lit (LWord64 x)) = pure $ argWord64 x
toFFIArg (TySimple T_Float) (RT_Lit (LFloat x)) = pure $ argCFloat $ CFloat x
toFFIArg (TySimple T_Bool) (RT_Lit (LBool x)) = pure $ argInt $ if x then 1 else 0
toFFIArg (TySimple T_String) (RT_Lit (LString x)) = pure $ argString $ Text.unpack x
toFFIArg (TySimple T_Char) (RT_Lit (LChar x)) = pure $ argCChar $ castCharToCChar x
toFFIArg ty arg = throwError $ userError
$ printf "Unexpected argument type or value in FFI call: %s :: %s" (show arg) (show ty)
toFFIRet :: Ty -> GrinM (RetType RTVal)
toFFIRet (TySimple T_Int64) = pure $ withRetType (pure . RT_Lit . LInt64) retInt64
toFFIRet (TySimple T_Word64) = pure $ withRetType (pure . RT_Lit . LWord64) retWord64
toFFIRet (TySimple T_Float) = pure $ withRetType (pure . RT_Lit . LFloat . (\case CFloat x -> x)) retCFloat
toFFIRet (TySimple T_Bool) = pure $ withRetType (pure . RT_Lit . LBool . (/= 0)) retCInt
toFFIRet (TySimple T_String) = pure $ withRetType (pure . RT_Lit . LString . Text.pack) retString
toFFIRet (TySimple T_Char) = pure $ withRetType (pure . RT_Lit . LChar . castCCharToChar) retCChar
toFFIRet (TySimple T_Unit) = pure $ withRetType (const $ pure RT_Unit) retVoid
toFFIRet ty = throwError $ userError
$ printf "Unexpected return type in FFI call: %s" $ show ty
evalSimpleExp :: Env -> SimpleExp -> GrinM RTVal
evalSimpleExp env s = do
when debug $ do
liftIO $ print s
void $ liftIO getLine
case s of
SApp n a -> do
let args = map (evalVal env) a
go a [] [] = a
go a (x:xs) (y:ys) = go (Map.insert x y a) xs ys
go _ x y =
error $ printf
"invalid pattern for function: %s %s %s"
n
(prettyDebug x)
(prettyDebug y)
exts <- asks ctxExternals
evalPrimOpMap <- asks (evalPluginPrimOp . ctxEvalPlugin)
let extm = find (\e -> eName e == n) exts
case extm of
Just (External _ retTy argsTy _ FFI _) -> do
ffiArgs <- zipWithM toFFIArg argsTy args
ffiRet <- toFFIRet retTy
extFns <- asks ctxForeign
let fn = fromMaybe
(error $ printf "Missing foreign function: %s" n)
(Map.lookup n extFns)
liftIO $ callFFI fn ffiRet ffiArgs
Just _ -> do
let evalPrimOp = Map.findWithDefault
(error $ printf "undefined primop: %s" n)
n
evalPrimOpMap
liftIO $ evalPrimOp args
Nothing -> do
Def _ vars body <- reader
$ Map.findWithDefault (error $ printf "unknown function: %s" n) n . ctxProg
evalExp (go env vars args) body
SReturn v -> pure $ evalVal env v
SStore v -> do
l <- gets (storeSize . fst)
let v' = evalVal env v
modify' (\(StoreMap m s, Statistics f u) ->
( StoreMap (IntMap.insert l v' m) (s+1)
, Statistics (IntMap.insert l 0 f) (IntMap.insert l 0 u)
))
pure $ RT_Loc l
SFetchI n index -> case lookupEnv n env of
RT_Loc l -> do
modify' (\(heap, Statistics f u) ->
(heap, Statistics (IntMap.adjust (+1) l f) u))
gets $ (selectNodeItem index . lookupStore l . fst)
x -> error $ printf "evalSimpleExp - Fetch expected location, got: %s" (prettyDebug x)
SUpdate n v -> do
let v' = evalVal env v
case lookupEnv n env of
RT_Loc l -> do
(StoreMap m _, _) <- get
case IntMap.member l m of
False -> error $ printf "evalSimpleExp - Update unknown location: %d" l
True -> do
modify' (\(StoreMap m s, Statistics f u) ->
(StoreMap (IntMap.insert l v' m) s, Statistics f (IntMap.adjust (+1) l u)))
pure RT_Unit
x -> error $ printf "evalSimpleExp - Update expected location, got: %s" (prettyDebug x)
SBlock a -> evalExp env a
x -> error $ printf "invalid simple expression %s" (prettyDebug x)
evalExp :: Env -> Exp -> GrinM RTVal
evalExp env = \case
EBind op pat exp -> do
v <- evalSimpleExp env op
when debug $ do
liftIO $ putStrLn $ unwords [show pat,":=",show v]
evalExp (bindPat env v pat) exp
ECase v alts -> do
let defaultAlts = [exp | Alt DefaultPat exp <- alts]
defaultAlt = if length defaultAlts > 1
then error "multiple default case alternative"
else take 1 defaultAlts
case evalVal env v of
RT_ConstTagNode t l ->
let (vars,exp) = head $ [(b,exp) | Alt (NodePat a b) exp <- alts, a == t] ++ map ([],) defaultAlt ++ error (printf "evalExp - missing Case Node alternative for: %s" (prettyDebug t))
go a [] [] = a
go a (x:xs) (y:ys) = go (Map.insert x y a) xs ys
go _ x y = error $ printf "invalid pattern and constructor: %s %s %s" (prettyDebug t) (prettyDebug x) (prettyDebug y)
in evalExp
_ -> go env vars l)
exp
RT_ValTag t -> evalExp env $ head $ [exp | Alt (TagPat a) exp <- alts, a == t] ++ defaultAlt ++ error (printf "evalExp - missing Case Tag alternative for: %s" (prettyDebug t))
RT_Lit l -> evalExp env $ head $ [exp | Alt (LitPat a) exp <- alts, a == l] ++ defaultAlt ++ error (printf "evalExp - missing Case Lit alternative for: %s" (show l))
x -> error $ printf "evalExp - invalid Case dispatch value: %s" (prettyDebug x)
exp -> evalSimpleExp env exp
createForeignFns :: [External] -> Map Name (FunPtr ()) -> IO (Map Name (FunPtr ()))
createForeignFns [] acc = pure acc
createForeignFns exts@(ext : _) acc
| eKind ext == PrimOp = createForeignFns (tail exts) acc
| otherwise = case find (\(os, _) -> toString os == Info.os) (eLibs ext) of
Nothing -> do
ptr <- dlsym Default $ Text.unpack $ unNM $ eName ext
createForeignFns (tail exts) $ Map.insert (eName ext) ptr acc
Just (os, lib) -> do
let (extWithLib, extNoLib) =
partition
(\e ->
find
(\(os, l) -> toString os == Info.os)
(eLibs e)
== Just (os, lib))
exts
acc' <- withDL
(Text.unpack lib)
[RTLD_LAZY]
(\dl -> foldlM (\a e -> do
ptr <- dlsym dl (Text.unpack $ unNM $ eName e)
pure $ Map.insert (eName e) ptr acc) acc extWithLib)
createForeignFns extNoLib acc'
where
toString :: OS -> String
toString = \case
Darwin -> "darwin"
FreeBSD -> "freebsd"
Linux -> "linux"
Android -> "linux-android"
MinGW -> "mingw32"
Win -> "mingw32"
NetBSD -> "netbsd"
OpenBSD -> "openbsd"
reduceFun :: EvalPlugin -> Program -> Name -> IO (RTVal, Maybe Statistics)
reduceFun evalPrimOp (Program exts l) n = do
ffiFns <- createForeignFns exts mempty
let context@(Context m _ _ _) = Context (Map.fromList [(n,d) | d@(Def n _ _) <- l]) exts evalPrimOp ffiFns
e = case Map.lookup n m of
Nothing -> error $ printf "missing function: %s" n
Just (Def _ [] a) -> a
_ -> error $ printf "function %s has arguments" n
(v, (_, s)) <- runStateT (runReaderT (evalExp mempty e) context) (emptyStore, emptyStatistics)
pure (v, Just s)
|
29291d631507b9ed4bcb36b6debb3b5a480baf5c135b0a1fb601d907dc723e21 | goodell/cppmem | main.ml | Js_of_ocaml compiler
* /
* Copyright ( C ) 2010
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser 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 .
* /
* Copyright (C) 2010 Jérôme Vouillon
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*)
let debug = Util.debug "main"
let times = Util.debug "times"
let f paths js_files input_file output_file =
let t = Util.Timer.make () in
List.iter Linker.add_file js_files;
let paths = List.rev_append paths [Findlib.package_directory "stdlib"] in
let t1 = Util.Timer.make () in
let p =
match input_file with
None ->
Parse.from_channel ~paths stdin
| Some f ->
let ch = open_in_bin f in
let p = Parse.from_channel ~paths ch in
close_in ch;
p
in
if times () then Format.eprintf " parsing: %a@." Util.Timer.print t1;
let output_program = Driver.f p in
begin match output_file with
None ->
output_program (Pretty_print.to_out_channel stdout)
| Some f ->
let ch = open_out_bin f in
output_program (Pretty_print.to_out_channel ch);
close_out ch
end;
if times () then Format.eprintf "compilation: %a@." Util.Timer.print t
let _ =
Findlib.init ();
Util.Timer.init Unix.gettimeofday;
let js_files = ref [] in
let output_file = ref None in
let input_file = ref None in
let no_runtime = ref false in
let paths = ref [] in
let options =
[("-debug", Arg.String Util.set_debug, "<name> debug module <name>");
("-disable",
Arg.String Util.set_disabled, "<name> disable optimization <name>");
("-pretty", Arg.Unit Driver.set_pretty, " pretty print the output");
("-noinline", Arg.Unit Inline.disable_inlining, " disable inlining");
("-noruntime", Arg.Unit (fun () -> no_runtime := true),
" do not include the standard runtime");
("-toplevel", Arg.Unit Parse.build_toplevel,
" compile a toplevel");
("-I", Arg.String (fun s -> paths := s :: !paths),
"<dir> Add <dir> to the list of include directories");
("-o", Arg.String (fun s -> output_file := Some s),
"<file> set output file name to <file>")]
in
Arg.parse (Arg.align options)
(fun s ->
if Filename.check_suffix s ".js" then
js_files := s :: !js_files
else
input_file := Some s)
(Format.sprintf "Usage: %s [options]" Sys.argv.(0));
let runtime =
if !no_runtime then [] else
try
[Filename.concat (Findlib.package_directory "js_of_ocaml") "runtime.js"]
with Findlib.No_such_package _ ->
Format.eprintf "%s: runtime file 'runtime.js' not found.@." Sys.argv.(0);
exit 1
in
let chop_extension s =
try Filename.chop_extension s with Invalid_argument _ -> s in
f !paths (runtime @ List.rev !js_files) !input_file
(match !output_file with
Some _ -> !output_file
| None -> Util.opt_map (fun s -> chop_extension s ^ ".js") !input_file)
| null | https://raw.githubusercontent.com/goodell/cppmem/eb3ce19b607a5d6ec81138cd8cacd236f9388e87/js_of_ocaml-1.2/compiler/main.ml | ocaml | Js_of_ocaml compiler
* /
* Copyright ( C ) 2010
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser 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 .
* /
* Copyright (C) 2010 Jérôme Vouillon
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*)
let debug = Util.debug "main"
let times = Util.debug "times"
let f paths js_files input_file output_file =
let t = Util.Timer.make () in
List.iter Linker.add_file js_files;
let paths = List.rev_append paths [Findlib.package_directory "stdlib"] in
let t1 = Util.Timer.make () in
let p =
match input_file with
None ->
Parse.from_channel ~paths stdin
| Some f ->
let ch = open_in_bin f in
let p = Parse.from_channel ~paths ch in
close_in ch;
p
in
if times () then Format.eprintf " parsing: %a@." Util.Timer.print t1;
let output_program = Driver.f p in
begin match output_file with
None ->
output_program (Pretty_print.to_out_channel stdout)
| Some f ->
let ch = open_out_bin f in
output_program (Pretty_print.to_out_channel ch);
close_out ch
end;
if times () then Format.eprintf "compilation: %a@." Util.Timer.print t
let _ =
Findlib.init ();
Util.Timer.init Unix.gettimeofday;
let js_files = ref [] in
let output_file = ref None in
let input_file = ref None in
let no_runtime = ref false in
let paths = ref [] in
let options =
[("-debug", Arg.String Util.set_debug, "<name> debug module <name>");
("-disable",
Arg.String Util.set_disabled, "<name> disable optimization <name>");
("-pretty", Arg.Unit Driver.set_pretty, " pretty print the output");
("-noinline", Arg.Unit Inline.disable_inlining, " disable inlining");
("-noruntime", Arg.Unit (fun () -> no_runtime := true),
" do not include the standard runtime");
("-toplevel", Arg.Unit Parse.build_toplevel,
" compile a toplevel");
("-I", Arg.String (fun s -> paths := s :: !paths),
"<dir> Add <dir> to the list of include directories");
("-o", Arg.String (fun s -> output_file := Some s),
"<file> set output file name to <file>")]
in
Arg.parse (Arg.align options)
(fun s ->
if Filename.check_suffix s ".js" then
js_files := s :: !js_files
else
input_file := Some s)
(Format.sprintf "Usage: %s [options]" Sys.argv.(0));
let runtime =
if !no_runtime then [] else
try
[Filename.concat (Findlib.package_directory "js_of_ocaml") "runtime.js"]
with Findlib.No_such_package _ ->
Format.eprintf "%s: runtime file 'runtime.js' not found.@." Sys.argv.(0);
exit 1
in
let chop_extension s =
try Filename.chop_extension s with Invalid_argument _ -> s in
f !paths (runtime @ List.rev !js_files) !input_file
(match !output_file with
Some _ -> !output_file
| None -> Util.opt_map (fun s -> chop_extension s ^ ".js") !input_file)
| |
25b70ab42534109bbccd130622e828b2dc918ff09d44a469b154f9dc8e544cf2 | dgiot/dgiot | emqx_telemetry_api.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2021 EMQ Technologies Co. , Ltd. 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.
%%--------------------------------------------------------------------
-module(emqx_telemetry_api).
-rest_api(#{name => enable_telemetry,
method => 'PUT',
path => "/telemetry/status",
func => enable,
descr => "Enable or disbale telemetry"}).
-rest_api(#{name => get_telemetry_status,
method => 'GET',
path => "/telemetry/status",
func => get_status,
descr => "Get telemetry status"}).
-rest_api(#{name => get_telemetry_data,
method => 'GET',
path => "/telemetry/data",
func => get_data,
descr => "Get reported telemetry data"}).
-export([ cli/1
, enable/2
, get_status/2
, get_data/2
, enable_telemetry/1
, disable_telemetry/1
, get_telemetry_status/0
, get_telemetry_data/0
]).
-import(minirest, [return/1]).
%%--------------------------------------------------------------------
%% CLI
%%--------------------------------------------------------------------
cli(["enable"]) ->
emqx_mgmt:enable_telemetry(),
emqx_ctl:print("Enable telemetry successfully~n");
cli(["disable"]) ->
emqx_mgmt:disable_telemetry(),
emqx_ctl:print("Disable telemetry successfully~n");
cli(["get", "status"]) ->
case emqx_mgmt:get_telemetry_status() of
[{enabled, true}] ->
emqx_ctl:print("Telemetry is enabled~n");
[{enabled, false}] ->
emqx_ctl:print("Telemetry is disabled~n")
end;
cli(["get", "data"]) ->
{ok, TelemetryData} = emqx_mgmt:get_telemetry_data(),
case emqx_json:safe_encode(TelemetryData, [pretty]) of
{ok, Bin} ->
emqx_ctl:print("~s~n", [Bin]);
{error, _Reason} ->
emqx_ctl:print("Failed to get telemetry data")
end;
cli(_) ->
emqx_ctl:usage([{"telemetry enable", "Enable telemetry"},
{"telemetry disable", "Disable telemetry"},
{"telemetry get data", "Get reported telemetry data"}]).
%%--------------------------------------------------------------------
%% HTTP API
%%--------------------------------------------------------------------
enable(_Bindings, Params) ->
case proplists:get_value(<<"enabled">>, Params) of
true ->
enable_telemetry(),
return(ok);
false ->
disable_telemetry(),
return(ok);
undefined ->
return({error, missing_required_params})
end.
get_status(_Bindings, _Params) ->
return(get_telemetry_status()).
get_data(_Bindings, _Params) ->
return(get_telemetry_data()).
enable_telemetry() ->
lists:foreach(fun enable_telemetry/1, ekka_mnesia:running_nodes()).
enable_telemetry(Node) when Node =:= node() ->
emqx_telemetry:enable();
enable_telemetry(Node) ->
rpc_call(Node, ?MODULE, enable_telemetry, [Node]).
disable_telemetry() ->
lists:foreach(fun disable_telemetry/1, ekka_mnesia:running_nodes()).
disable_telemetry(Node) when Node =:= node() ->
emqx_telemetry:disable();
disable_telemetry(Node) ->
rpc_call(Node, ?MODULE, disable_telemetry, [Node]).
get_telemetry_status() ->
{ok, [{enabled, emqx_telemetry:is_enabled()}]}.
get_telemetry_data() ->
emqx_telemetry:get_telemetry().
rpc_call(Node, Module, Fun, Args) ->
case rpc:call(Node, Module, Fun, Args) of
{badrpc, Reason} -> {error, Reason};
Result -> Result
end.
| null | https://raw.githubusercontent.com/dgiot/dgiot/c9f2f78af71692ba532e4806621b611db2afe0c9/lib-ce/emqx_telemetry/src/emqx_telemetry_api.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
--------------------------------------------------------------------
CLI
--------------------------------------------------------------------
--------------------------------------------------------------------
HTTP API
-------------------------------------------------------------------- | Copyright ( c ) 2020 - 2021 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_telemetry_api).
-rest_api(#{name => enable_telemetry,
method => 'PUT',
path => "/telemetry/status",
func => enable,
descr => "Enable or disbale telemetry"}).
-rest_api(#{name => get_telemetry_status,
method => 'GET',
path => "/telemetry/status",
func => get_status,
descr => "Get telemetry status"}).
-rest_api(#{name => get_telemetry_data,
method => 'GET',
path => "/telemetry/data",
func => get_data,
descr => "Get reported telemetry data"}).
-export([ cli/1
, enable/2
, get_status/2
, get_data/2
, enable_telemetry/1
, disable_telemetry/1
, get_telemetry_status/0
, get_telemetry_data/0
]).
-import(minirest, [return/1]).
cli(["enable"]) ->
emqx_mgmt:enable_telemetry(),
emqx_ctl:print("Enable telemetry successfully~n");
cli(["disable"]) ->
emqx_mgmt:disable_telemetry(),
emqx_ctl:print("Disable telemetry successfully~n");
cli(["get", "status"]) ->
case emqx_mgmt:get_telemetry_status() of
[{enabled, true}] ->
emqx_ctl:print("Telemetry is enabled~n");
[{enabled, false}] ->
emqx_ctl:print("Telemetry is disabled~n")
end;
cli(["get", "data"]) ->
{ok, TelemetryData} = emqx_mgmt:get_telemetry_data(),
case emqx_json:safe_encode(TelemetryData, [pretty]) of
{ok, Bin} ->
emqx_ctl:print("~s~n", [Bin]);
{error, _Reason} ->
emqx_ctl:print("Failed to get telemetry data")
end;
cli(_) ->
emqx_ctl:usage([{"telemetry enable", "Enable telemetry"},
{"telemetry disable", "Disable telemetry"},
{"telemetry get data", "Get reported telemetry data"}]).
enable(_Bindings, Params) ->
case proplists:get_value(<<"enabled">>, Params) of
true ->
enable_telemetry(),
return(ok);
false ->
disable_telemetry(),
return(ok);
undefined ->
return({error, missing_required_params})
end.
get_status(_Bindings, _Params) ->
return(get_telemetry_status()).
get_data(_Bindings, _Params) ->
return(get_telemetry_data()).
enable_telemetry() ->
lists:foreach(fun enable_telemetry/1, ekka_mnesia:running_nodes()).
enable_telemetry(Node) when Node =:= node() ->
emqx_telemetry:enable();
enable_telemetry(Node) ->
rpc_call(Node, ?MODULE, enable_telemetry, [Node]).
disable_telemetry() ->
lists:foreach(fun disable_telemetry/1, ekka_mnesia:running_nodes()).
disable_telemetry(Node) when Node =:= node() ->
emqx_telemetry:disable();
disable_telemetry(Node) ->
rpc_call(Node, ?MODULE, disable_telemetry, [Node]).
get_telemetry_status() ->
{ok, [{enabled, emqx_telemetry:is_enabled()}]}.
get_telemetry_data() ->
emqx_telemetry:get_telemetry().
rpc_call(Node, Module, Fun, Args) ->
case rpc:call(Node, Module, Fun, Args) of
{badrpc, Reason} -> {error, Reason};
Result -> Result
end.
|
005ab51ceccb0ab279cb2bac3871fa966180fb965d393d4fab5d76c768eb008f | ghc/nofib | Delay.hs | module Delay (delay,delaya) where
delay_time :: Int
#ifdef mc68020
delay_time = 18
#else
#ifdef sparc
delay_time = 48
#else /* Alpha */
delay_time = 200
delay_time = 1
#endif
#endif
ddelay :: Int -> Int -> Int
ddelay 0 0 = 0
ddelay m 0 = ddelay (m-1) delay_time
ddelay m n = ddelay m (n-1)
delay d = ddelay d 0
delaya :: Int -> Int -> Int
delaya a d = delay d
| null | https://raw.githubusercontent.com/ghc/nofib/f34b90b5a6ce46284693119a06d1133908b11856/parallel/dcbm/Delay.hs | haskell | module Delay (delay,delaya) where
delay_time :: Int
#ifdef mc68020
delay_time = 18
#else
#ifdef sparc
delay_time = 48
#else /* Alpha */
delay_time = 200
delay_time = 1
#endif
#endif
ddelay :: Int -> Int -> Int
ddelay 0 0 = 0
ddelay m 0 = ddelay (m-1) delay_time
ddelay m n = ddelay m (n-1)
delay d = ddelay d 0
delaya :: Int -> Int -> Int
delaya a d = delay d
| |
94a7dd455afa843681977f302521a1eed5e553aadba0654c9220626dd923888e | input-output-hk/cardano-sl | Api.hs | # LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
-- | Web API exposed by node.
module Pos.Web.Api
( NodeApi
, nodeApi
, HealthCheckApi
, healthCheckApi
) where
import Universum
import Servant.API ((:<|>), (:>), Get, JSON, PlainText)
import Pos.Chain.Txp (Utxo)
import Pos.Web.Types (CConfirmedProposalState)
----------------------------------------------------------------------------
-- Base
----------------------------------------------------------------------------
-- | Servant API which provides access to full node internals.
--
-- Implementations of these methods are in
-- 'Pos.Web.Server.nodeServantHandlers'.
type NodeApi =
"utxo"
:> Get '[JSON] Utxo
:<|>
"confirmed_proposals"
:> Get '[JSON] [CConfirmedProposalState]
-- | Helper Proxy.
nodeApi :: Proxy NodeApi
nodeApi = Proxy
----------------------------------------------------------------------------
-- HealthCheck
----------------------------------------------------------------------------
-- | Helper Proxy.
healthCheckApi :: Proxy HealthCheckApi
healthCheckApi = Proxy
type HealthCheckApi =
"healthcheck" :> "route53" :> Get '[PlainText] String
| null | https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/lib/src/Pos/Web/Api.hs | haskell | | Web API exposed by node.
--------------------------------------------------------------------------
Base
--------------------------------------------------------------------------
| Servant API which provides access to full node internals.
Implementations of these methods are in
'Pos.Web.Server.nodeServantHandlers'.
| Helper Proxy.
--------------------------------------------------------------------------
HealthCheck
--------------------------------------------------------------------------
| Helper Proxy. | # LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
module Pos.Web.Api
( NodeApi
, nodeApi
, HealthCheckApi
, healthCheckApi
) where
import Universum
import Servant.API ((:<|>), (:>), Get, JSON, PlainText)
import Pos.Chain.Txp (Utxo)
import Pos.Web.Types (CConfirmedProposalState)
type NodeApi =
"utxo"
:> Get '[JSON] Utxo
:<|>
"confirmed_proposals"
:> Get '[JSON] [CConfirmedProposalState]
nodeApi :: Proxy NodeApi
nodeApi = Proxy
healthCheckApi :: Proxy HealthCheckApi
healthCheckApi = Proxy
type HealthCheckApi =
"healthcheck" :> "route53" :> Get '[PlainText] String
|
832bdc917a1eb7bb70a7dfba1c6d9dc0cd901c30bf0fdda5863af1b75cec8414 | frasertweedale/notes-redhat | ACL.hs | {-# LANGUAGE OverloadedStrings #-}
module ACL where
import Data.Maybe (fromMaybe)
import Data.Monoid (First(First, getFirst))
import Data.Semigroup ((<>))
import Data.Text (Text, unpack)
| An authentication token ( simple placeholder for this POC ) .
--
data AuthenticationToken = AuthenticationToken
{ tokenUsername :: Username
, tokenGroups :: [Group]
, tokenIPAddress :: String -- FIXME better type
}
type Username = Text
type Group = Text
-- | An AccessEvaluator
data AccessEvaluator = AccessEvaluator
{ evaluateAccess :: AuthenticationToken -> Bool
, printAccessEvaluator :: Text -- ^ string representation
}
instance Show AccessEvaluator where
show = unpack . printAccessEvaluator
-- | An ACL expression is left-associative with no operator
-- precedence. In other words:
--
-- @
a || b & & c || d = = ( ( ( a || b ) & & c ) || d )
-- @
--
-- This can give different results from the "usual" precedence
of AND and OR . The old Java implementation has this semantics .
--
-- Note that the construction is right-associative to make parsing
-- easy, but 'evaluateExpression' evaluates the structure
-- left-associatively.
--
data ACLExpression
= End AccessEvaluator
| And AccessEvaluator ACLExpression
| Or AccessEvaluator ACLExpression
deriving (Show)
-- | Evaluate expression left-associatively.
-- (The implementation is a bit convoluted for this reason)
--
evaluateExpression :: AuthenticationToken -> ACLExpression -> Bool
use the first fragment as - is
where
go f (End l) = f (evaluateAccess l tok)
go f (Or l r) = go (f (evaluateAccess l tok) ||) r
go f (And l r) = go (f (evaluateAccess l tok) &&) r
type Permission = Text
data ACLRuleType = Allow | Deny
deriving (Eq, Show)
data ACLRule = ACLRule
{ aclRuleType :: ACLRuleType
, aclRulePermissions :: [Permission]
, aclRuleExpression :: ACLExpression
}
deriving (Show)
| Evaluate a rule . An @Allow@ rule will evaluate to
-- @Just Allowed@ if its expression evaluate to @True@s, else
@Nothing@. Similarly , a @Deny@ rule will evaluate to
@Just Denied@ or @Nothing@.
--
evaluateRule :: AuthenticationToken -> ACLRule -> Maybe ACLResult
evaluateRule tok (ACLRule ruleType _ expr) =
if evaluateExpression tok expr then Just (result ruleType) else Nothing
where
result Deny = Denied
result Allow = Allowed
| Specifies whether " allow " or " deny " rules will be processed first
data ACLRuleOrder = AllowDeny | DenyAllow
| Result of evaluating an ACL
data ACLResult = Allowed | Denied
data ACL = ACL
{ aclName :: Text
, aclPermissions :: [Permission]
-- ^ the union of the permissions of each acl entry (hypothetically)
, aclRules :: [ACLRule]
, aclDescription :: Text
}
deriving (Show)
-- | Evaluate an ACL for the given 'Permission'. The 'ACLRuleOrder'
-- controls whether 'Deny' rules will be processed before 'Allow'
rules or vice - versa . The first matching rule covering the given
-- 'Permission' wins. If no rule matches for the given permission,
-- access is 'Denied'.
--
evaluateACL
:: ACLRuleOrder
-> AuthenticationToken
-> Permission
-> ACL
-> ACLResult
evaluateACL order tok perm (ACL _ _ rules _ ) =
fromMaybe Denied result -- deny if no rules matched
where
-- rules for the given permissions
permRules = filter (elem perm . aclRulePermissions) rules
order rules by allow / deny according to ACLRuleOrder
orderedRules = case order of
DenyAllow -> denyRules <> allowRules
AllowDeny -> allowRules <> denyRules
denyRules = filter ((== Deny) . aclRuleType) permRules
allowRules = filter ((== Allow) . aclRuleType) permRules
the first matching rule wins
result = getFirst (foldMap (First . evaluateRule tok) orderedRules)
data EqCondition = Equal | NotEqual
deriving (Eq)
eq :: (Eq a) => EqCondition -> (a -> a -> Bool)
eq Equal = (==)
eq NotEqual = (/=)
printEq :: EqCondition -> Text
printEq Equal = "="
printEq NotEqual = "!="
-- | Constract a user access evaluator
--
userAccessEvaluator :: EqCondition -> Text -> AccessEvaluator
userAccessEvaluator eqCond s = AccessEvaluator f repr
where
f | eqCond == Equal && (s `elem` ["anybody", "everybody"]) = const True
| otherwise = eq eqCond s . tokenUsername
repr = "user" <> printEq eqCond <> "\"" <> s <> "\""
groupAccessEvaluator :: EqCondition -> Text -> AccessEvaluator
groupAccessEvaluator eqCond s = AccessEvaluator f repr
where
f = any (eq eqCond s) . tokenGroups
repr = "group" <> printEq eqCond <> "\"" <> s <> "\""
-- | extract IP address from auth token and perform regex match
ipaddressAccessEvaluator :: EqCondition -> Text -> AccessEvaluator
ipaddressAccessEvaluator eqCond pat = AccessEvaluator f repr
where
op = case eqCond of Equal -> id ; NotEqual -> not
TODO
f tok = op (regexMatch (tokenIPAddress tok))
repr = "ipaddress" <> printEq eqCond <> "\"" <> pat <> "\""
| null | https://raw.githubusercontent.com/frasertweedale/notes-redhat/48ed96ed0aa8efd4e486b9daf9a4e1516498b60f/fp-examples/acl/ACL.hs | haskell | # LANGUAGE OverloadedStrings #
FIXME better type
| An AccessEvaluator
^ string representation
| An ACL expression is left-associative with no operator
precedence. In other words:
@
@
This can give different results from the "usual" precedence
Note that the construction is right-associative to make parsing
easy, but 'evaluateExpression' evaluates the structure
left-associatively.
| Evaluate expression left-associatively.
(The implementation is a bit convoluted for this reason)
@Just Allowed@ if its expression evaluate to @True@s, else
^ the union of the permissions of each acl entry (hypothetically)
| Evaluate an ACL for the given 'Permission'. The 'ACLRuleOrder'
controls whether 'Deny' rules will be processed before 'Allow'
'Permission' wins. If no rule matches for the given permission,
access is 'Denied'.
deny if no rules matched
rules for the given permissions
| Constract a user access evaluator
| extract IP address from auth token and perform regex match |
module ACL where
import Data.Maybe (fromMaybe)
import Data.Monoid (First(First, getFirst))
import Data.Semigroup ((<>))
import Data.Text (Text, unpack)
| An authentication token ( simple placeholder for this POC ) .
data AuthenticationToken = AuthenticationToken
{ tokenUsername :: Username
, tokenGroups :: [Group]
}
type Username = Text
type Group = Text
data AccessEvaluator = AccessEvaluator
{ evaluateAccess :: AuthenticationToken -> Bool
}
instance Show AccessEvaluator where
show = unpack . printAccessEvaluator
a || b & & c || d = = ( ( ( a || b ) & & c ) || d )
of AND and OR . The old Java implementation has this semantics .
data ACLExpression
= End AccessEvaluator
| And AccessEvaluator ACLExpression
| Or AccessEvaluator ACLExpression
deriving (Show)
evaluateExpression :: AuthenticationToken -> ACLExpression -> Bool
use the first fragment as - is
where
go f (End l) = f (evaluateAccess l tok)
go f (Or l r) = go (f (evaluateAccess l tok) ||) r
go f (And l r) = go (f (evaluateAccess l tok) &&) r
type Permission = Text
data ACLRuleType = Allow | Deny
deriving (Eq, Show)
data ACLRule = ACLRule
{ aclRuleType :: ACLRuleType
, aclRulePermissions :: [Permission]
, aclRuleExpression :: ACLExpression
}
deriving (Show)
| Evaluate a rule . An @Allow@ rule will evaluate to
@Nothing@. Similarly , a @Deny@ rule will evaluate to
@Just Denied@ or @Nothing@.
evaluateRule :: AuthenticationToken -> ACLRule -> Maybe ACLResult
evaluateRule tok (ACLRule ruleType _ expr) =
if evaluateExpression tok expr then Just (result ruleType) else Nothing
where
result Deny = Denied
result Allow = Allowed
| Specifies whether " allow " or " deny " rules will be processed first
data ACLRuleOrder = AllowDeny | DenyAllow
| Result of evaluating an ACL
data ACLResult = Allowed | Denied
data ACL = ACL
{ aclName :: Text
, aclPermissions :: [Permission]
, aclRules :: [ACLRule]
, aclDescription :: Text
}
deriving (Show)
rules or vice - versa . The first matching rule covering the given
evaluateACL
:: ACLRuleOrder
-> AuthenticationToken
-> Permission
-> ACL
-> ACLResult
evaluateACL order tok perm (ACL _ _ rules _ ) =
where
permRules = filter (elem perm . aclRulePermissions) rules
order rules by allow / deny according to ACLRuleOrder
orderedRules = case order of
DenyAllow -> denyRules <> allowRules
AllowDeny -> allowRules <> denyRules
denyRules = filter ((== Deny) . aclRuleType) permRules
allowRules = filter ((== Allow) . aclRuleType) permRules
the first matching rule wins
result = getFirst (foldMap (First . evaluateRule tok) orderedRules)
data EqCondition = Equal | NotEqual
deriving (Eq)
eq :: (Eq a) => EqCondition -> (a -> a -> Bool)
eq Equal = (==)
eq NotEqual = (/=)
printEq :: EqCondition -> Text
printEq Equal = "="
printEq NotEqual = "!="
userAccessEvaluator :: EqCondition -> Text -> AccessEvaluator
userAccessEvaluator eqCond s = AccessEvaluator f repr
where
f | eqCond == Equal && (s `elem` ["anybody", "everybody"]) = const True
| otherwise = eq eqCond s . tokenUsername
repr = "user" <> printEq eqCond <> "\"" <> s <> "\""
groupAccessEvaluator :: EqCondition -> Text -> AccessEvaluator
groupAccessEvaluator eqCond s = AccessEvaluator f repr
where
f = any (eq eqCond s) . tokenGroups
repr = "group" <> printEq eqCond <> "\"" <> s <> "\""
ipaddressAccessEvaluator :: EqCondition -> Text -> AccessEvaluator
ipaddressAccessEvaluator eqCond pat = AccessEvaluator f repr
where
op = case eqCond of Equal -> id ; NotEqual -> not
TODO
f tok = op (regexMatch (tokenIPAddress tok))
repr = "ipaddress" <> printEq eqCond <> "\"" <> pat <> "\""
|
037cc4b6dd303c1aecae2872375c276070c3a7c661bb8be4dddcd7475585d306 | leepike/Copilot | VotingExamples.hs | --------------------------------------------------------------------------------
Copyright © 2011 National Institute of Aerospace / Galois , Inc.
--------------------------------------------------------------------------------
-- | Fault-tolerant voting examples.
# LANGUAGE RebindableSyntax #
module VotingExamples ( votingExamples ) where
import Language.Copilot
--------------------------------------------------------------------------------
vote :: Spec
vote = do
trigger "maj" true [ arg maj ]
trigger "aMaj" true
[ arg $ aMajority xs maj ]
where
maj = majority xs
xs = concat (replicate 1 ls)
ls = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]
a = [0] ++ a + 1 :: Stream Word32
b = [0] ++ b + 1
c = [0] ++ c + 1
d = [0] ++ d + 1
e = [1] ++ e + 1
f = [1] ++ f + 1
g = [1] ++ g + 1
h = [1] ++ h + 1
i = [1] ++ i + 1
j = [1] ++ j + 1
k = [1] ++ k + 1
l = [1] ++ l + 1
m = [1] ++ m + 1
n = [1] ++ n + 1
o = [1] ++ o + 1
p = [1] ++ p + 1
q = [1] ++ q + 1
r = [1] ++ r + 1
s = [1] ++ s + 1
t = [1] ++ t + 1
u = [1] ++ u + 1
v = [1] ++ v + 1
w = [1] ++ w + 1
x = [1] ++ x + 1
y = [1] ++ y + 1
z = [1] ++ z + 1
--------------------------------------------------------------------------------
votingExamples :: IO ()
votingExamples =
do
interpret 20 vote
-- prettyPrint vote
| null | https://raw.githubusercontent.com/leepike/Copilot/18a71502c5c9e7262f14bb8167f3b4a09c9c6a8b/Examples/VotingExamples.hs | haskell | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Fault-tolerant voting examples.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
prettyPrint vote | Copyright © 2011 National Institute of Aerospace / Galois , Inc.
# LANGUAGE RebindableSyntax #
module VotingExamples ( votingExamples ) where
import Language.Copilot
vote :: Spec
vote = do
trigger "maj" true [ arg maj ]
trigger "aMaj" true
[ arg $ aMajority xs maj ]
where
maj = majority xs
xs = concat (replicate 1 ls)
ls = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]
a = [0] ++ a + 1 :: Stream Word32
b = [0] ++ b + 1
c = [0] ++ c + 1
d = [0] ++ d + 1
e = [1] ++ e + 1
f = [1] ++ f + 1
g = [1] ++ g + 1
h = [1] ++ h + 1
i = [1] ++ i + 1
j = [1] ++ j + 1
k = [1] ++ k + 1
l = [1] ++ l + 1
m = [1] ++ m + 1
n = [1] ++ n + 1
o = [1] ++ o + 1
p = [1] ++ p + 1
q = [1] ++ q + 1
r = [1] ++ r + 1
s = [1] ++ s + 1
t = [1] ++ t + 1
u = [1] ++ u + 1
v = [1] ++ v + 1
w = [1] ++ w + 1
x = [1] ++ x + 1
y = [1] ++ y + 1
z = [1] ++ z + 1
votingExamples :: IO ()
votingExamples =
do
interpret 20 vote
|
3c90cd97c58881e6cf0346b37324db45ec409c1e8c6eb8cd931fa58a44bc3efa | caisah/sicp-exercises-and-examples | ex_2.20.scm | Write a procedure same - parity that takes one or more integers and returns a list
of all the arguments that have the same even - odd parity as the first argument . For
;; example:
( same - parity 1 2 3 4 5 6 7 )
;; (1 3 5 7)
( same - parity 2 3 4 5 6 7 )
( 2 4 6 )
(define (same-parity . w)
(define rem (remainder (car w) 2))
(define (sp-iter items res)
(if (null? items)
res
(if (= (remainder (car items) 2) rem)
(sp-iter (cdr items)
(append res (list (car items))))
(sp-iter (cdr items) res))))
(sp-iter w '()))
(same-parity 1 2 3 4 5 6 7)
(same-parity 2 3 4 5 6 7)
| null | https://raw.githubusercontent.com/caisah/sicp-exercises-and-examples/605c698d7495aa3474c2b6edcd1312cb16c5b5cb/2.2.1-representing_sequences/ex_2.20.scm | scheme | example:
(1 3 5 7) | Write a procedure same - parity that takes one or more integers and returns a list
of all the arguments that have the same even - odd parity as the first argument . For
( same - parity 1 2 3 4 5 6 7 )
( same - parity 2 3 4 5 6 7 )
( 2 4 6 )
(define (same-parity . w)
(define rem (remainder (car w) 2))
(define (sp-iter items res)
(if (null? items)
res
(if (= (remainder (car items) 2) rem)
(sp-iter (cdr items)
(append res (list (car items))))
(sp-iter (cdr items) res))))
(sp-iter w '()))
(same-parity 1 2 3 4 5 6 7)
(same-parity 2 3 4 5 6 7)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.