_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
|
---|---|---|---|---|---|---|---|---|
b0e56f78d1210e7cfdf30650b5622639a87366b4c273b3124bdd970969dcd7bf | cbaggers/varjo | traits.lisp | (in-package :varjo.internals)
;;------------------------------------------------------------
;;
;; - adding functions needs to check if the name is bound to a trait function
;; if so then fail
;; - defining a function that takes or return traits is fine. They will need to
;; be monomorphised though.
;; - For now dont allow parametized type names to implement traits (except
;; arrays which will be hacked in the implementation) HMMMMMM
(defclass trait-function (v-function)
((trait :initarg :trait)))
(defun trait-function-p (x) (typep x 'trait-function))
;;------------------------------------------------------------
(defvar *traits*
(make-hash-table))
(defclass trait-spec ()
((type-vars :initarg :type-vars)
(function-signatures :initarg :function-signatures)))
(defmacro define-vari-trait (name (&rest type-vars) &body func-signatures)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(define-v-type-class ,name (v-trait) ())
(register-trait
',name
(make-instance
'trait-spec
:type-vars ',type-vars
:function-signatures (parse-trait-specs
',name ',type-vars ',func-signatures)))))
(defun remove-redundent-trait-functions (trait-name new-trait)
(let ((old-trait (gethash trait-name *traits*)))
(when old-trait
(let ((old-funcs
(mapcar #'first (slot-value old-trait 'function-signatures)))
(new-funcs
(mapcar #'second (slot-value new-trait 'function-signatures))))
(loop :for name :in (set-difference old-funcs new-funcs) :do
(delete-external-function name :all))))))
(defun check-for-trait-function-collision (spec)
;; - adding a trait has to check for existing functions with that name
;; if they arent functions of that same trait then fail
(let ((funcs (slot-value spec 'function-signatures)))
(loop :for (func-name . nil) :in funcs :do
(let* ((bindings (get-global-form-binding func-name))
(functions (when bindings
(remove-if #'trait-function-p
(functions bindings)))))
(assert (null functions) ()
"Varjo: Trait function cannot be an overload of any existing function:~%Found:~{~%~a~}"
(mapcar (lambda (fn)
(cons func-name
(rest (type->type-spec (v-type-of fn)))))
functions))))))
(defun add-trait-functions (trait-name spec)
(check-for-trait-function-collision spec)
(remove-redundent-trait-functions trait-name spec)
(let ((top (type-spec->type t))
(top-set (make-type-set (type-spec->type t)))
(funcs (slot-value spec 'function-signatures)))
(flet ((finalize-type (x)
(etypecase x
(v-type x)
(symbol top))))
(loop
:for (func-name . arg-types) :in funcs
:for final-arg-types := (mapcar #'finalize-type arg-types)
:do (add-global-form-binding
(make-trait-function-obj (type-spec->type trait-name)
func-name
final-arg-types
top-set))))))
(defun register-trait (trait-name spec)
(add-trait-functions trait-name spec)
(setf (gethash trait-name *traits*) spec))
(defun get-trait (trait-name &key (errorp t))
(or (gethash trait-name *traits*)
(when errorp
(error "Varjo:No trait named ~a is currently known" trait-name))))
(defun parse-trait-specs (trait-name type-vars function-signatures)
(let ((name-map
(loop :for (name type) :in (cons (list :self trait-name) type-vars)
:collect (cons name (if (string= type "_")
name
(type-spec->type type))))))
(flet ((as-type (name)
(or (assocr name name-map)
(type-spec->type name))))
(loop :for (func-name . func-spec) :in function-signatures
:do
(assert (find :self func-spec) ()
"Trait function specs must have at least one :self argument")
:collect
(cons func-name (mapcar #'as-type func-spec))))))
;;------------------------------------------------------------
(defvar *trait-implementations*
(make-hash-table))
(defclass impl-spec ()
((function-signatures :initarg :function-signatures)))
(defun check-impl-spec (trait-name trait-args type-name spec)
(assert (vtype-existsp type-name))
(assert (vtype-existsp trait-name))
(let* ((trait (get-trait trait-name))
(required-funcs (slot-value trait 'function-signatures))
(provided-funcs (slot-value spec 'function-signatures))
(type-var-requirements (make-hash-table :test #'eq)))
(assert (= (length required-funcs) (length provided-funcs)))
;; We need to check that the types used are consistent in the implementation in cases
;; where type-vars were used.
Relies on Varjo producing new types for each call to type - spec->type
(flet ((get-var-req (type)
(gethash type type-var-requirements))
(set-var-req (req ours)
(setf (gethash req type-var-requirements)
ours)
t)
(complete-req-type (type)
(etypecase type
(v-type type)
(symbol (or (assocr type trait-args :test #'string=)
(error "Varjo: Could not find the '~a' trait arg required by ~a"
type trait-name))))))
(loop :for (name func) :in provided-funcs :do
(assert
(loop
:for (nil . req-types) :in required-funcs
:thereis
(let ((complete-req-types (mapcar #'complete-req-type req-types)))
(and (func-args-satisfy-p func complete-req-types)
(loop :for req-type :in complete-req-types
:for req-spec :in req-types
:for type :in (v-argument-spec func)
:for i :from 0
:always
(let ((strict (get-var-req req-type)))
(when (symbolp req-spec)
(assert (v-type-eq type req-type) ()
"Varjo: Trait argument states that argument ~a of ~a should be ~a"
i name (type->type-spec req-type)))
(if strict
(v-type-eq type strict)
(set-var-req req-type type)))))))
() "Varjo: No func in~%~a~%matched~%~a" required-funcs func)))))
(defun register-trait-implementation (trait-name trait-args type-name spec)
(let ((trait-table (or (gethash type-name *trait-implementations*)
(setf (gethash type-name *trait-implementations*)
(make-hash-table)))))
(unless (gethash trait-name trait-table)
(setf (gethash trait-name trait-table) t))
(unwind-protect
(check-impl-spec trait-name trait-args type-name spec)
(setf (gethash trait-name trait-table) nil))
(setf (gethash trait-name trait-table)
spec)))
(defun get-trait-implementation (trait type &key (errorp t))
(check-type trait v-type)
(check-type type v-type)
(let* ((trait-name (slot-value trait 'type-name))
(type-name (slot-value type 'type-name))
(impl-table (gethash type-name *trait-implementations*)))
(if impl-table
(or (gethash trait-name impl-table)
(when errorp
(error "Varjo: Type ~a does not satisfy the trait named ~a"
type-name trait-name)))
(when errorp
(error "Varjo: Type ~a currently satisfies no traits.~%Looking for: ~a"
type-name trait-name)))))
(defun parse-impl-specs (function-signatures)
(loop :for (trait-func-name impl-func) :in function-signatures
:for binding := (find-global-form-binding-by-literal impl-func t)
:collect
(list trait-func-name binding)))
(defmacro define-vari-trait-implementation
(impl-type-name (trait-name &rest trait-args &key &allow-other-keys)
&body implementations &key &allow-other-keys)
(let ((grouped
(loop :for (k v) :on implementations :by #'cddr :collect
(list k v)))
(trait-args
(loop :for (k v) :on trait-args :by #'cddr :collect
(cons k v))))
`(progn
(register-trait-implementation
',trait-name ',trait-args ',impl-type-name
(make-instance 'impl-spec :function-signatures
(parse-impl-specs ',grouped)))
',impl-type-name)))
;;------------------------------------------------------------
#+nil
(progn
(v-deftype blerp () :ivec2)
(v-def-glsl-template-fun blerp (x) "blerp(~a)" (:int) blerp)
(v-def-glsl-template-fun boop (x) "boop(~a)" (blerp) blerp)
(v-def-glsl-template-fun checker (x y) "check(~a, ~a)" (blerp blerp) :bool)
(v-def-glsl-template-fun splat (x y) "splat(~a,~a)" (blerp :int) :int)
(v-deftype narp () :ivec3)
(v-def-glsl-template-fun narp (x) "narp(~a)" (:int) narp)
(v-def-glsl-template-fun nboop (x) "nboop(~a)" (narp) narp)
(v-def-glsl-template-fun checker (x y) "check(~a, ~a)" (narp narp) :bool)
(v-def-glsl-template-fun splat (x y) "splat(~a,~a)" (narp :int) :int)
(define-vari-trait trat ()
(booper :self)
(checkerer :self :self)
(splatter :self t))
(define-vari-trait-implementation blerp (trat)
:booper (boop blerp)
:checkerer (checker blerp blerp)
:splatter (splat blerp :int))
(define-vari-trait-implementation narp (trat)
:booper (nboop narp)
:checkerer (checker narp narp)
:splatter (splat narp :int)))
;;------------------------------------------------------------
| null | https://raw.githubusercontent.com/cbaggers/varjo/9e77f30220053155d2ef8870ceba157f75e538d4/src/varjo.internals/traits.lisp | lisp | ------------------------------------------------------------
- adding functions needs to check if the name is bound to a trait function
if so then fail
- defining a function that takes or return traits is fine. They will need to
be monomorphised though.
- For now dont allow parametized type names to implement traits (except
arrays which will be hacked in the implementation) HMMMMMM
------------------------------------------------------------
- adding a trait has to check for existing functions with that name
if they arent functions of that same trait then fail
------------------------------------------------------------
We need to check that the types used are consistent in the implementation in cases
where type-vars were used.
------------------------------------------------------------
------------------------------------------------------------ | (in-package :varjo.internals)
(defclass trait-function (v-function)
((trait :initarg :trait)))
(defun trait-function-p (x) (typep x 'trait-function))
(defvar *traits*
(make-hash-table))
(defclass trait-spec ()
((type-vars :initarg :type-vars)
(function-signatures :initarg :function-signatures)))
(defmacro define-vari-trait (name (&rest type-vars) &body func-signatures)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(define-v-type-class ,name (v-trait) ())
(register-trait
',name
(make-instance
'trait-spec
:type-vars ',type-vars
:function-signatures (parse-trait-specs
',name ',type-vars ',func-signatures)))))
(defun remove-redundent-trait-functions (trait-name new-trait)
(let ((old-trait (gethash trait-name *traits*)))
(when old-trait
(let ((old-funcs
(mapcar #'first (slot-value old-trait 'function-signatures)))
(new-funcs
(mapcar #'second (slot-value new-trait 'function-signatures))))
(loop :for name :in (set-difference old-funcs new-funcs) :do
(delete-external-function name :all))))))
(defun check-for-trait-function-collision (spec)
(let ((funcs (slot-value spec 'function-signatures)))
(loop :for (func-name . nil) :in funcs :do
(let* ((bindings (get-global-form-binding func-name))
(functions (when bindings
(remove-if #'trait-function-p
(functions bindings)))))
(assert (null functions) ()
"Varjo: Trait function cannot be an overload of any existing function:~%Found:~{~%~a~}"
(mapcar (lambda (fn)
(cons func-name
(rest (type->type-spec (v-type-of fn)))))
functions))))))
(defun add-trait-functions (trait-name spec)
(check-for-trait-function-collision spec)
(remove-redundent-trait-functions trait-name spec)
(let ((top (type-spec->type t))
(top-set (make-type-set (type-spec->type t)))
(funcs (slot-value spec 'function-signatures)))
(flet ((finalize-type (x)
(etypecase x
(v-type x)
(symbol top))))
(loop
:for (func-name . arg-types) :in funcs
:for final-arg-types := (mapcar #'finalize-type arg-types)
:do (add-global-form-binding
(make-trait-function-obj (type-spec->type trait-name)
func-name
final-arg-types
top-set))))))
(defun register-trait (trait-name spec)
(add-trait-functions trait-name spec)
(setf (gethash trait-name *traits*) spec))
(defun get-trait (trait-name &key (errorp t))
(or (gethash trait-name *traits*)
(when errorp
(error "Varjo:No trait named ~a is currently known" trait-name))))
(defun parse-trait-specs (trait-name type-vars function-signatures)
(let ((name-map
(loop :for (name type) :in (cons (list :self trait-name) type-vars)
:collect (cons name (if (string= type "_")
name
(type-spec->type type))))))
(flet ((as-type (name)
(or (assocr name name-map)
(type-spec->type name))))
(loop :for (func-name . func-spec) :in function-signatures
:do
(assert (find :self func-spec) ()
"Trait function specs must have at least one :self argument")
:collect
(cons func-name (mapcar #'as-type func-spec))))))
(defvar *trait-implementations*
(make-hash-table))
(defclass impl-spec ()
((function-signatures :initarg :function-signatures)))
(defun check-impl-spec (trait-name trait-args type-name spec)
(assert (vtype-existsp type-name))
(assert (vtype-existsp trait-name))
(let* ((trait (get-trait trait-name))
(required-funcs (slot-value trait 'function-signatures))
(provided-funcs (slot-value spec 'function-signatures))
(type-var-requirements (make-hash-table :test #'eq)))
(assert (= (length required-funcs) (length provided-funcs)))
Relies on Varjo producing new types for each call to type - spec->type
(flet ((get-var-req (type)
(gethash type type-var-requirements))
(set-var-req (req ours)
(setf (gethash req type-var-requirements)
ours)
t)
(complete-req-type (type)
(etypecase type
(v-type type)
(symbol (or (assocr type trait-args :test #'string=)
(error "Varjo: Could not find the '~a' trait arg required by ~a"
type trait-name))))))
(loop :for (name func) :in provided-funcs :do
(assert
(loop
:for (nil . req-types) :in required-funcs
:thereis
(let ((complete-req-types (mapcar #'complete-req-type req-types)))
(and (func-args-satisfy-p func complete-req-types)
(loop :for req-type :in complete-req-types
:for req-spec :in req-types
:for type :in (v-argument-spec func)
:for i :from 0
:always
(let ((strict (get-var-req req-type)))
(when (symbolp req-spec)
(assert (v-type-eq type req-type) ()
"Varjo: Trait argument states that argument ~a of ~a should be ~a"
i name (type->type-spec req-type)))
(if strict
(v-type-eq type strict)
(set-var-req req-type type)))))))
() "Varjo: No func in~%~a~%matched~%~a" required-funcs func)))))
(defun register-trait-implementation (trait-name trait-args type-name spec)
(let ((trait-table (or (gethash type-name *trait-implementations*)
(setf (gethash type-name *trait-implementations*)
(make-hash-table)))))
(unless (gethash trait-name trait-table)
(setf (gethash trait-name trait-table) t))
(unwind-protect
(check-impl-spec trait-name trait-args type-name spec)
(setf (gethash trait-name trait-table) nil))
(setf (gethash trait-name trait-table)
spec)))
(defun get-trait-implementation (trait type &key (errorp t))
(check-type trait v-type)
(check-type type v-type)
(let* ((trait-name (slot-value trait 'type-name))
(type-name (slot-value type 'type-name))
(impl-table (gethash type-name *trait-implementations*)))
(if impl-table
(or (gethash trait-name impl-table)
(when errorp
(error "Varjo: Type ~a does not satisfy the trait named ~a"
type-name trait-name)))
(when errorp
(error "Varjo: Type ~a currently satisfies no traits.~%Looking for: ~a"
type-name trait-name)))))
(defun parse-impl-specs (function-signatures)
(loop :for (trait-func-name impl-func) :in function-signatures
:for binding := (find-global-form-binding-by-literal impl-func t)
:collect
(list trait-func-name binding)))
(defmacro define-vari-trait-implementation
(impl-type-name (trait-name &rest trait-args &key &allow-other-keys)
&body implementations &key &allow-other-keys)
(let ((grouped
(loop :for (k v) :on implementations :by #'cddr :collect
(list k v)))
(trait-args
(loop :for (k v) :on trait-args :by #'cddr :collect
(cons k v))))
`(progn
(register-trait-implementation
',trait-name ',trait-args ',impl-type-name
(make-instance 'impl-spec :function-signatures
(parse-impl-specs ',grouped)))
',impl-type-name)))
#+nil
(progn
(v-deftype blerp () :ivec2)
(v-def-glsl-template-fun blerp (x) "blerp(~a)" (:int) blerp)
(v-def-glsl-template-fun boop (x) "boop(~a)" (blerp) blerp)
(v-def-glsl-template-fun checker (x y) "check(~a, ~a)" (blerp blerp) :bool)
(v-def-glsl-template-fun splat (x y) "splat(~a,~a)" (blerp :int) :int)
(v-deftype narp () :ivec3)
(v-def-glsl-template-fun narp (x) "narp(~a)" (:int) narp)
(v-def-glsl-template-fun nboop (x) "nboop(~a)" (narp) narp)
(v-def-glsl-template-fun checker (x y) "check(~a, ~a)" (narp narp) :bool)
(v-def-glsl-template-fun splat (x y) "splat(~a,~a)" (narp :int) :int)
(define-vari-trait trat ()
(booper :self)
(checkerer :self :self)
(splatter :self t))
(define-vari-trait-implementation blerp (trat)
:booper (boop blerp)
:checkerer (checker blerp blerp)
:splatter (splat blerp :int))
(define-vari-trait-implementation narp (trat)
:booper (nboop narp)
:checkerer (checker narp narp)
:splatter (splat narp :int)))
|
083371b84cccd41a30b0e8e38e54967625b5c69470b51923865d4b56979b3ca2 | danr/hipspec | Properties.hs | {-
All properties from the article.
-}
module Properties where
import HipSpec
import Prelude(Bool(..))
import Definitions
-- Theorems
prop_T01 :: Nat -> Prop Nat
prop_T01 x = double x =:= x + x
prop_T02 :: [a] -> [a] -> Prop Nat
prop_T02 x y = length (x ++ y ) =:= length (y ++ x)
prop_T03 :: [a] -> [a] -> Prop Nat
prop_T03 x y = length (x ++ y ) =:= length (y ) + length x
prop_T04 :: [a] -> Prop Nat
prop_T04 x = length (x ++ x) =:= double (length x)
prop_T05 :: [a] -> Prop Nat
prop_T05 x = length (rev x) =:= length x
prop_T06 :: [a] -> [a] -> Prop Nat
prop_T06 x y = length (rev (x ++ y )) =:= length x + length y
prop_T07 :: [a] -> [a] -> Prop Nat
prop_T07 x y = length (qrev x y) =:= length x + length y
prop_T08 :: Nat -> Nat -> [a] -> Prop [a]
prop_T08 x y z = drop x (drop y z) =:= drop y (drop x z)
prop_T09 :: Nat -> Nat -> [a] -> Nat -> Prop [a]
prop_T09 x y z w = drop w (drop x (drop y z)) =:= drop y (drop x (drop w z))
prop_T10 :: [a] -> Prop [a]
prop_T10 x = rev (rev x) =:= x
prop_T11 :: [a] -> [a] -> Prop [a]
prop_T11 x y = rev (rev x ++ rev y) =:= y ++ x
prop_T12 :: [a] -> [a] -> Prop [a]
prop_T12 x y = qrev x y =:= rev x ++ y
prop_T13 :: Nat -> Prop Nat
prop_T13 x = half (x + x) =:= x
prop_T14 :: [Nat] -> Prop Bool
prop_T14 x = proveBool (sorted (isort x))
prop_T15 :: Nat -> Prop Nat
prop_T15 x = x + S x =:= S (x + x)
prop_T16 :: Nat -> Prop Bool
prop_T16 x = proveBool (even (x + x))
prop_T17 :: [a] -> [a] -> Prop [a]
prop_T17 x y = rev (rev (x ++ y)) =:= rev (rev x) ++ rev (rev y)
prop_T18 :: [a] -> [a] -> Prop [a]
prop_T18 x y = rev (rev x ++ y) =:= rev y ++ x
prop_T19 :: [a] -> [a] -> Prop [a]
prop_T19 x y = rev (rev x) ++ y =:= rev (rev (x ++ y))
prop_T20 :: [a] -> Prop Bool
prop_T20 x = proveBool (even (length (x ++ x)))
prop_T21 :: [a] -> [a] -> Prop [a]
prop_T21 x y = rotate (length x) (x ++ y) =:= y ++ x
prop_T22 :: [a] -> [a] -> Prop Bool
prop_T22 x y = even (length (x ++ y)) =:= even (length (y ++ x))
prop_T23 :: [a] -> [a] -> Prop Nat
prop_T23 x y = half (length (x ++ y)) =:= half (length (y ++ x))
prop_T24 :: Nat -> Nat -> Prop Bool
prop_T24 x y = even (x + y) =:= even (y + x)
prop_T25 :: [a] -> [a] -> Prop Bool
prop_T25 x y = even (length (x ++ y)) =:= even (length y + length x)
prop_T26 :: Nat -> Nat -> Prop Nat
prop_T26 x y = half (x + y) =:= half (y + x)
prop_T27 :: [a] -> Prop [a]
prop_T27 x = rev x =:= qrev x []
prop_T28 :: [[a]] -> Prop [a]
prop_T28 x = revflat x =:= qrevflat x []
prop_T29 :: [a] -> Prop [a]
prop_T29 x = rev (qrev x []) =:= x
prop_T30 :: [a] -> Prop [a]
prop_T30 x = rev (rev x ++ []) =:= x
prop_T31 :: [a] -> Prop [a]
prop_T31 x = qrev (qrev x []) [] =:= x
prop_T32 :: [a] -> Prop [a]
prop_T32 x = rotate (length x) x =:= x
prop_T33 :: Nat -> Prop Nat
prop_T33 x = fac x =:= qfac x one
prop_T34 :: Nat -> Nat -> Prop Nat
prop_T34 x y = x * y =:= mult x y zero
prop_T35 :: Nat -> Nat -> Prop Nat
prop_T35 x y = exp x y =:= qexp x y one
prop_T36 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T36 x y z = givenBool (x `elem` y) (proveBool (x `elem` (y ++ z)))
prop_T37 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T37 x y z = givenBool (x `elem` z) (proveBool (x `elem` (y ++ z)))
prop_T38 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T38 x y z = givenBool (x `elem` y)
( givenBool (x `elem` z)
( proveBool (x `elem` (y ++ z))))
prop_T39 :: Nat -> Nat -> [Nat] -> Prop Bool
prop_T39 x y z = givenBool (x `elem` drop y z) (proveBool (x `elem` z))
prop_T40 :: [Nat] -> [Nat] -> Prop [Nat]
prop_T40 x y = givenBool (x `subset` y) ((x `union` y) =:= y)
prop_T41 :: [Nat] -> [Nat] -> Prop [Nat]
prop_T41 x y = givenBool (x `subset` y) ((x `intersect` y) =:= x)
prop_T42 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T42 x y z = givenBool (x `elem` y) (proveBool (x `elem` (y `union` z)))
prop_T43 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T43 x y z = givenBool (x `elem` y) (proveBool (x `elem` (z `union` y)))
prop_T44 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T44 x y z = givenBool (x `elem` y)
( givenBool (x `elem` z)
( proveBool (x `elem` (y `intersect` z))))
prop_T45 :: Nat -> [Nat] -> Prop Bool
prop_T45 x y = proveBool (x `elem` insert x y)
prop_T46 :: Nat -> Nat -> [Nat] -> Prop Bool
prop_T46 x y z = x =:= y ==> proveBool (x `elem` insert y z)
prop_T47 :: Nat -> Nat -> [Nat] -> Prop Bool
prop_T47 x y z = givenBool (x /= y) ((x `elem` insert y z) =:= x `elem` z)
prop_T48 :: [Nat] -> Prop Nat
prop_T48 x = length (isort x) =:= length x
prop_T49 :: Nat -> [Nat] -> Prop Bool
prop_T49 x y = givenBool (x `elem` isort y) (proveBool (x `elem` y))
prop_T50 :: Nat -> [Nat] -> Prop Nat
prop_T50 x y = count x (isort y) =:= count x y
| null | https://raw.githubusercontent.com/danr/hipspec/a114db84abd5fee8ce0b026abc5380da11147aa9/testsuite/prod/Properties.hs | haskell |
All properties from the article.
Theorems | module Properties where
import HipSpec
import Prelude(Bool(..))
import Definitions
prop_T01 :: Nat -> Prop Nat
prop_T01 x = double x =:= x + x
prop_T02 :: [a] -> [a] -> Prop Nat
prop_T02 x y = length (x ++ y ) =:= length (y ++ x)
prop_T03 :: [a] -> [a] -> Prop Nat
prop_T03 x y = length (x ++ y ) =:= length (y ) + length x
prop_T04 :: [a] -> Prop Nat
prop_T04 x = length (x ++ x) =:= double (length x)
prop_T05 :: [a] -> Prop Nat
prop_T05 x = length (rev x) =:= length x
prop_T06 :: [a] -> [a] -> Prop Nat
prop_T06 x y = length (rev (x ++ y )) =:= length x + length y
prop_T07 :: [a] -> [a] -> Prop Nat
prop_T07 x y = length (qrev x y) =:= length x + length y
prop_T08 :: Nat -> Nat -> [a] -> Prop [a]
prop_T08 x y z = drop x (drop y z) =:= drop y (drop x z)
prop_T09 :: Nat -> Nat -> [a] -> Nat -> Prop [a]
prop_T09 x y z w = drop w (drop x (drop y z)) =:= drop y (drop x (drop w z))
prop_T10 :: [a] -> Prop [a]
prop_T10 x = rev (rev x) =:= x
prop_T11 :: [a] -> [a] -> Prop [a]
prop_T11 x y = rev (rev x ++ rev y) =:= y ++ x
prop_T12 :: [a] -> [a] -> Prop [a]
prop_T12 x y = qrev x y =:= rev x ++ y
prop_T13 :: Nat -> Prop Nat
prop_T13 x = half (x + x) =:= x
prop_T14 :: [Nat] -> Prop Bool
prop_T14 x = proveBool (sorted (isort x))
prop_T15 :: Nat -> Prop Nat
prop_T15 x = x + S x =:= S (x + x)
prop_T16 :: Nat -> Prop Bool
prop_T16 x = proveBool (even (x + x))
prop_T17 :: [a] -> [a] -> Prop [a]
prop_T17 x y = rev (rev (x ++ y)) =:= rev (rev x) ++ rev (rev y)
prop_T18 :: [a] -> [a] -> Prop [a]
prop_T18 x y = rev (rev x ++ y) =:= rev y ++ x
prop_T19 :: [a] -> [a] -> Prop [a]
prop_T19 x y = rev (rev x) ++ y =:= rev (rev (x ++ y))
prop_T20 :: [a] -> Prop Bool
prop_T20 x = proveBool (even (length (x ++ x)))
prop_T21 :: [a] -> [a] -> Prop [a]
prop_T21 x y = rotate (length x) (x ++ y) =:= y ++ x
prop_T22 :: [a] -> [a] -> Prop Bool
prop_T22 x y = even (length (x ++ y)) =:= even (length (y ++ x))
prop_T23 :: [a] -> [a] -> Prop Nat
prop_T23 x y = half (length (x ++ y)) =:= half (length (y ++ x))
prop_T24 :: Nat -> Nat -> Prop Bool
prop_T24 x y = even (x + y) =:= even (y + x)
prop_T25 :: [a] -> [a] -> Prop Bool
prop_T25 x y = even (length (x ++ y)) =:= even (length y + length x)
prop_T26 :: Nat -> Nat -> Prop Nat
prop_T26 x y = half (x + y) =:= half (y + x)
prop_T27 :: [a] -> Prop [a]
prop_T27 x = rev x =:= qrev x []
prop_T28 :: [[a]] -> Prop [a]
prop_T28 x = revflat x =:= qrevflat x []
prop_T29 :: [a] -> Prop [a]
prop_T29 x = rev (qrev x []) =:= x
prop_T30 :: [a] -> Prop [a]
prop_T30 x = rev (rev x ++ []) =:= x
prop_T31 :: [a] -> Prop [a]
prop_T31 x = qrev (qrev x []) [] =:= x
prop_T32 :: [a] -> Prop [a]
prop_T32 x = rotate (length x) x =:= x
prop_T33 :: Nat -> Prop Nat
prop_T33 x = fac x =:= qfac x one
prop_T34 :: Nat -> Nat -> Prop Nat
prop_T34 x y = x * y =:= mult x y zero
prop_T35 :: Nat -> Nat -> Prop Nat
prop_T35 x y = exp x y =:= qexp x y one
prop_T36 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T36 x y z = givenBool (x `elem` y) (proveBool (x `elem` (y ++ z)))
prop_T37 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T37 x y z = givenBool (x `elem` z) (proveBool (x `elem` (y ++ z)))
prop_T38 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T38 x y z = givenBool (x `elem` y)
( givenBool (x `elem` z)
( proveBool (x `elem` (y ++ z))))
prop_T39 :: Nat -> Nat -> [Nat] -> Prop Bool
prop_T39 x y z = givenBool (x `elem` drop y z) (proveBool (x `elem` z))
prop_T40 :: [Nat] -> [Nat] -> Prop [Nat]
prop_T40 x y = givenBool (x `subset` y) ((x `union` y) =:= y)
prop_T41 :: [Nat] -> [Nat] -> Prop [Nat]
prop_T41 x y = givenBool (x `subset` y) ((x `intersect` y) =:= x)
prop_T42 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T42 x y z = givenBool (x `elem` y) (proveBool (x `elem` (y `union` z)))
prop_T43 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T43 x y z = givenBool (x `elem` y) (proveBool (x `elem` (z `union` y)))
prop_T44 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T44 x y z = givenBool (x `elem` y)
( givenBool (x `elem` z)
( proveBool (x `elem` (y `intersect` z))))
prop_T45 :: Nat -> [Nat] -> Prop Bool
prop_T45 x y = proveBool (x `elem` insert x y)
prop_T46 :: Nat -> Nat -> [Nat] -> Prop Bool
prop_T46 x y z = x =:= y ==> proveBool (x `elem` insert y z)
prop_T47 :: Nat -> Nat -> [Nat] -> Prop Bool
prop_T47 x y z = givenBool (x /= y) ((x `elem` insert y z) =:= x `elem` z)
prop_T48 :: [Nat] -> Prop Nat
prop_T48 x = length (isort x) =:= length x
prop_T49 :: Nat -> [Nat] -> Prop Bool
prop_T49 x y = givenBool (x `elem` isort y) (proveBool (x `elem` y))
prop_T50 :: Nat -> [Nat] -> Prop Nat
prop_T50 x y = count x (isort y) =:= count x y
|
8d2d0ce9c1fd15a525aa984b6c91e875c4bb8b701a81ed66e896a41b839068dd | threatgrid/ctim | disposition_test.cljc | (ns ctim.domain.disposition-test
(:require #?(:clj [clojure.test :refer [deftest is testing]]
:cljs [cljs.test :refer-macros [deftest is testing]])
[ctim.domain.disposition :as sut]))
(deftest sort-by-importance-test
(testing "sorting disposition strings"
(is (= (sut/sort-by-importance
["Malicious" "Clean" "Unknown" "Foo"])
["Clean" "Malicious" "Unknown" "Foo"])))
(testing "sorting a map with disposition keys"
(is (= (sut/sort-by-importance
first
{"Malicious" 2
"Clean" 4
"Suspicious" 6
"Unknown" 10})
[["Clean" 4]
["Malicious" 2]
["Suspicious" 6]
["Unknown" 10]])))
(testing "sorting maps by :disposition key"
(is (= (sut/sort-by-importance
:disposition
[{:disposition "Unknown"}
{:disposition "Clean"}
{:disposition "Malicious"}])
[{:disposition "Clean"}
{:disposition "Malicious"}
{:disposition "Unknown"}]))))
| null | https://raw.githubusercontent.com/threatgrid/ctim/2ecae70682e69495cc3a12fd58a474d4ea57ae9c/test/ctim/domain/disposition_test.cljc | clojure | (ns ctim.domain.disposition-test
(:require #?(:clj [clojure.test :refer [deftest is testing]]
:cljs [cljs.test :refer-macros [deftest is testing]])
[ctim.domain.disposition :as sut]))
(deftest sort-by-importance-test
(testing "sorting disposition strings"
(is (= (sut/sort-by-importance
["Malicious" "Clean" "Unknown" "Foo"])
["Clean" "Malicious" "Unknown" "Foo"])))
(testing "sorting a map with disposition keys"
(is (= (sut/sort-by-importance
first
{"Malicious" 2
"Clean" 4
"Suspicious" 6
"Unknown" 10})
[["Clean" 4]
["Malicious" 2]
["Suspicious" 6]
["Unknown" 10]])))
(testing "sorting maps by :disposition key"
(is (= (sut/sort-by-importance
:disposition
[{:disposition "Unknown"}
{:disposition "Clean"}
{:disposition "Malicious"}])
[{:disposition "Clean"}
{:disposition "Malicious"}
{:disposition "Unknown"}]))))
|
|
c49035fd7ebf94f90845f97f8b01048a20e32cc3a4f871c8c4a95511f72dc810 | zendesk/clj-headlights | pardo.clj | (ns clj-headlights.pardo
(:require [schema.core :as s]
[clojure.tools.logging :as log]
[clojure.string :as string]
[clj-headlights.clj-fn-call :as clj-fn-call]
[clj-headlights.pcollections :as pcollections])
(:import (java.util List)
(clojure.lang Reflector)
(org.apache.beam.sdk.transforms.join CoGbkResult$CoGbkResultCoder CoGbkResult)
(org.apache.beam.sdk.coders Coder IterableCoder KvCoder StringUtf8Coder)
(org.apache.beam.sdk.transforms.windowing Window)
(org.apache.beam.sdk.transforms Create DoFn$ProcessContext ParDo ParDo$SingleOutput)
(org.apache.beam.sdk.values TupleTag KV TupleTagList PCollectionTuple PCollection)
(clj_headlights CljDoFn NippyCoder EdnCoder)))
(defn ^TupleTag get-tag [tag] (TupleTag. (name tag)))
(s/defn kv-value-restructurer :- s/Any
"If the output of the previous stage was a KV, then it may
have been the result of a GroupBy or CoGroupBy, which means
we need to transform the output of those operations into more idiomatic
clojure data structures.
For a GroupBy we wrap the list of results in a seq, so that it acts like a normal list.
For a CoGroupBy we create a positional vector, where the results for each pcoll that
was grouped are in the same position they were sent to co-group-by-key."
^:private
[coder :- Coder]
(cond
;; co-group-by-key just happened
(instance? CoGbkResult$CoGbkResultCoder coder)
(fn [^CoGbkResult val]
(let [tuple-tags (-> val .getSchema .getTupleTagList .getAll)]
(mapv (fn [tuple-tag] (seq (.getAll val tuple-tag))) tuple-tags)))
;; group-by-key just happened
(instance? IterableCoder coder)
seq
;; no aggregation yet happened
:else
identity))
(s/defn input-restructurer :- s/Any
"Given the coder of the input, create a function which pulls the input value
from the context and turns it into clojure data structures."
^:private
[coder :- Coder]
(cond
(instance? KvCoder coder)
(let [value-restructurer (kv-value-restructurer (.getValueCoder ^KvCoder coder))]
(fn [^DoFn$ProcessContext c]
(let [kv ^KV (.element c)]
[(.getKey kv) (value-restructurer (.getValue kv))])))
:else
(fn [^DoFn$ProcessContext c] (.element c))))
(defn setup [input-coder, serializable-clj-call]
The DoFn is a wrapper around a clojure function , to be executed
on compute nodes . The function is being executed on a new jvm , so
;; we find out what namespace that function came from, and require
;; it, so all its dependencies are met.
;; Only do that once per bundle (though no-op reqs are fast anyway).
(clj_headlights.System/ensureInitialized (:ns-name serializable-clj-call))
(input-restructurer input-coder))
(defn process-element [^DoFn$ProcessContext c
^Window window
serialized-clj-call
creation-stack
input-extractor
& states]
(clj_headlights.System/ensureInitialized (:ns-name serialized-clj-call))
(try
(apply clj-fn-call/clj-call-invoke serialized-clj-call c (input-extractor c) window states)
(catch IllegalStateException e
(log/error
"Illegal state exception in ParDo, probably because var-ns"
(:ns-name serialized-clj-call)
"stack during creation:" (apply str (interpose "\n" creation-stack)))
(throw e))))
(s/defn make-tags-list :- TupleTagList
[tags :- [s/Keyword]]
(TupleTagList/of ^List (map get-tag tags)))
(defn get-side-output ; TODO: is about pcollections, should be moved to pcollections ns
"Retrieve the pcollection associated with a given tag in the output of a df-map-with-side-outputs."
[^PCollectionTuple pcoll
tag]
(.get pcoll (get-tag tag)))
(defn get-side-outputs ; TODO: is about pcollections, should be moved to pcollections ns
"Retrieve the map of Tags to PCollections."
[^PCollectionTuple pcoll]
(.getAll pcoll))
(s/defn set-side-output-coder :- PCollection ; TODO: is about pcollections, should be moved to pcollections ns
"Sets the coder for the pcollection associated with a given tag in the output of a df-map-with-side-outputs."
[pcoll :- PCollectionTuple
tag :- s/Keyword
coder :- Coder]
(-> (get-side-output pcoll tag)
(.setCoder coder)))
(defn default-coder []
(NippyCoder.))
(s/defn create-and-apply :- pcollections/PCollectionType
"Create a ParDo operation from a DoFn class, and apply it to a PCollection.
It accepts an `options` map parameter that describes how the ParDo is created. You can specify the following keys:
:dofn-cls - which DoFn class is created for the ParDo. For now, it is required that the class inherits from
`clj_headlights.AbstractCljDoFn`, because the constructor invocation is hardcoded. Create a CljDoFn by
default.
:outputs - a map associating the (tagged) outputs of the ParDo with their respective coders. This map should always
contain at least a :main key, that is used for the main output coder.
:side-inputs - a collection of side-inputs the ParDo needs. As Beam requires, the given side-inputs need to extend
PCollectionView. Note: this only attaches the views to the ParDo; it is up to you to carry around the
same view object in your code to access the view data."
[pcoll :- pcollections/PCollectionType
name :- s/Str
clj-call :- clj-fn-call/CljCall
options :- {s/Keyword s/Any}] ; TODO: make me more precise, and optional
maybe rename to : dofn and accept either DoFn instance or class inheriting AbstractCljDoFn
:outputs {:main (default-coder)}
:side-inputs []}
options (merge default-options options)
input-coder (.getCoder pcoll)
pardo (cond-> (ParDo/of (Reflector/invokeConstructor (:dofn-cls options) (to-array [name input-coder (clj-fn-call/to-serializable-clj-call clj-call)])))
(not-empty (:side-inputs options)) (.withSideInputs ^Iterable (:side-inputs options)))]
(if (= 1 (count (:outputs options)))
(.setCoder (.apply pcoll name pardo) (get-in options [:outputs :main]))
(let [extra-tags (remove #{:main} (keys (:outputs options)))
applied-pcoll (.apply pcoll name (.withOutputTags pardo (get-tag :main) (make-tags-list extra-tags)))]
(doseq [[tag coder] (:outputs options)]
(set-side-output-coder applied-pcoll tag coder))
applied-pcoll))))
(defn emit-side-output
"Emit a value to a side output."
[^DoFn$ProcessContext context
tag
value]
(.output context (get-tag tag) value))
(defn emit-main-output
"Emit the main output value"
[^DoFn$ProcessContext context
value]
(.output context value))
; TODO: having that function is a smell. find a way to get rid of it.
(defn invoke-with-optional-state [& args]
(let [state (last args)]
(if (nil? state)
(apply clj-fn-call/clj-call-invoke (butlast args))
(apply clj-fn-call/clj-call-invoke args))))
| null | https://raw.githubusercontent.com/zendesk/clj-headlights/095ab05337c1a35583776a74137041ba9d783383/src/clj_headlights/pardo.clj | clojure | co-group-by-key just happened
group-by-key just happened
no aggregation yet happened
we find out what namespace that function came from, and require
it, so all its dependencies are met.
Only do that once per bundle (though no-op reqs are fast anyway).
TODO: is about pcollections, should be moved to pcollections ns
TODO: is about pcollections, should be moved to pcollections ns
TODO: is about pcollections, should be moved to pcollections ns
it is up to you to carry around the
TODO: make me more precise, and optional
TODO: having that function is a smell. find a way to get rid of it. | (ns clj-headlights.pardo
(:require [schema.core :as s]
[clojure.tools.logging :as log]
[clojure.string :as string]
[clj-headlights.clj-fn-call :as clj-fn-call]
[clj-headlights.pcollections :as pcollections])
(:import (java.util List)
(clojure.lang Reflector)
(org.apache.beam.sdk.transforms.join CoGbkResult$CoGbkResultCoder CoGbkResult)
(org.apache.beam.sdk.coders Coder IterableCoder KvCoder StringUtf8Coder)
(org.apache.beam.sdk.transforms.windowing Window)
(org.apache.beam.sdk.transforms Create DoFn$ProcessContext ParDo ParDo$SingleOutput)
(org.apache.beam.sdk.values TupleTag KV TupleTagList PCollectionTuple PCollection)
(clj_headlights CljDoFn NippyCoder EdnCoder)))
(defn ^TupleTag get-tag [tag] (TupleTag. (name tag)))
(s/defn kv-value-restructurer :- s/Any
"If the output of the previous stage was a KV, then it may
have been the result of a GroupBy or CoGroupBy, which means
we need to transform the output of those operations into more idiomatic
clojure data structures.
For a GroupBy we wrap the list of results in a seq, so that it acts like a normal list.
For a CoGroupBy we create a positional vector, where the results for each pcoll that
was grouped are in the same position they were sent to co-group-by-key."
^:private
[coder :- Coder]
(cond
(instance? CoGbkResult$CoGbkResultCoder coder)
(fn [^CoGbkResult val]
(let [tuple-tags (-> val .getSchema .getTupleTagList .getAll)]
(mapv (fn [tuple-tag] (seq (.getAll val tuple-tag))) tuple-tags)))
(instance? IterableCoder coder)
seq
:else
identity))
(s/defn input-restructurer :- s/Any
"Given the coder of the input, create a function which pulls the input value
from the context and turns it into clojure data structures."
^:private
[coder :- Coder]
(cond
(instance? KvCoder coder)
(let [value-restructurer (kv-value-restructurer (.getValueCoder ^KvCoder coder))]
(fn [^DoFn$ProcessContext c]
(let [kv ^KV (.element c)]
[(.getKey kv) (value-restructurer (.getValue kv))])))
:else
(fn [^DoFn$ProcessContext c] (.element c))))
(defn setup [input-coder, serializable-clj-call]
The DoFn is a wrapper around a clojure function , to be executed
on compute nodes . The function is being executed on a new jvm , so
(clj_headlights.System/ensureInitialized (:ns-name serializable-clj-call))
(input-restructurer input-coder))
(defn process-element [^DoFn$ProcessContext c
^Window window
serialized-clj-call
creation-stack
input-extractor
& states]
(clj_headlights.System/ensureInitialized (:ns-name serialized-clj-call))
(try
(apply clj-fn-call/clj-call-invoke serialized-clj-call c (input-extractor c) window states)
(catch IllegalStateException e
(log/error
"Illegal state exception in ParDo, probably because var-ns"
(:ns-name serialized-clj-call)
"stack during creation:" (apply str (interpose "\n" creation-stack)))
(throw e))))
(s/defn make-tags-list :- TupleTagList
[tags :- [s/Keyword]]
(TupleTagList/of ^List (map get-tag tags)))
"Retrieve the pcollection associated with a given tag in the output of a df-map-with-side-outputs."
[^PCollectionTuple pcoll
tag]
(.get pcoll (get-tag tag)))
"Retrieve the map of Tags to PCollections."
[^PCollectionTuple pcoll]
(.getAll pcoll))
"Sets the coder for the pcollection associated with a given tag in the output of a df-map-with-side-outputs."
[pcoll :- PCollectionTuple
tag :- s/Keyword
coder :- Coder]
(-> (get-side-output pcoll tag)
(.setCoder coder)))
(defn default-coder []
(NippyCoder.))
(s/defn create-and-apply :- pcollections/PCollectionType
"Create a ParDo operation from a DoFn class, and apply it to a PCollection.
It accepts an `options` map parameter that describes how the ParDo is created. You can specify the following keys:
:dofn-cls - which DoFn class is created for the ParDo. For now, it is required that the class inherits from
`clj_headlights.AbstractCljDoFn`, because the constructor invocation is hardcoded. Create a CljDoFn by
default.
:outputs - a map associating the (tagged) outputs of the ParDo with their respective coders. This map should always
contain at least a :main key, that is used for the main output coder.
:side-inputs - a collection of side-inputs the ParDo needs. As Beam requires, the given side-inputs need to extend
same view object in your code to access the view data."
[pcoll :- pcollections/PCollectionType
name :- s/Str
clj-call :- clj-fn-call/CljCall
maybe rename to : dofn and accept either DoFn instance or class inheriting AbstractCljDoFn
:outputs {:main (default-coder)}
:side-inputs []}
options (merge default-options options)
input-coder (.getCoder pcoll)
pardo (cond-> (ParDo/of (Reflector/invokeConstructor (:dofn-cls options) (to-array [name input-coder (clj-fn-call/to-serializable-clj-call clj-call)])))
(not-empty (:side-inputs options)) (.withSideInputs ^Iterable (:side-inputs options)))]
(if (= 1 (count (:outputs options)))
(.setCoder (.apply pcoll name pardo) (get-in options [:outputs :main]))
(let [extra-tags (remove #{:main} (keys (:outputs options)))
applied-pcoll (.apply pcoll name (.withOutputTags pardo (get-tag :main) (make-tags-list extra-tags)))]
(doseq [[tag coder] (:outputs options)]
(set-side-output-coder applied-pcoll tag coder))
applied-pcoll))))
(defn emit-side-output
"Emit a value to a side output."
[^DoFn$ProcessContext context
tag
value]
(.output context (get-tag tag) value))
(defn emit-main-output
"Emit the main output value"
[^DoFn$ProcessContext context
value]
(.output context value))
(defn invoke-with-optional-state [& args]
(let [state (last args)]
(if (nil? state)
(apply clj-fn-call/clj-call-invoke (butlast args))
(apply clj-fn-call/clj-call-invoke args))))
|
0a8b266a792627a61d219424bcedee1a03993a91d0f26c162adda3175a8c5725 | upgradingdave/cljs | dev.cljs | (ns up.reframe.dev
(:require
[devcards.core :as dc :include-macros true]
[reagent.core :as r]
[up.reframe.core :as c])
(:require-macros
[devcards.core :refer [defcard deftest defcard-doc]]
[cljs.test :refer [is testing]]))
(deftest unit-tests
(testing "Sanity"
(is (= false false))))
(defcard
"## Simple"
(dc/reagent
(fn [data _]
[:div
[c/greet-input]
[c/greet-btn]
[c/greet]]))
re-frame.db/app-db
{:inspect-data true})
(defn main []
(c/main))
(defn reload [])
| null | https://raw.githubusercontent.com/upgradingdave/cljs/1026b6db905214586fb7e04800df078da19b37cc/src/cljs/up/reframe/dev.cljs | clojure | (ns up.reframe.dev
(:require
[devcards.core :as dc :include-macros true]
[reagent.core :as r]
[up.reframe.core :as c])
(:require-macros
[devcards.core :refer [defcard deftest defcard-doc]]
[cljs.test :refer [is testing]]))
(deftest unit-tests
(testing "Sanity"
(is (= false false))))
(defcard
"## Simple"
(dc/reagent
(fn [data _]
[:div
[c/greet-input]
[c/greet-btn]
[c/greet]]))
re-frame.db/app-db
{:inspect-data true})
(defn main []
(c/main))
(defn reload [])
|
|
619b949400de32e08bd33ed86083302a7b9945cc6acafdf08dc572cb31b5166f | OCamlPro/ocp-build | metaConfig.mli | (**************************************************************************)
(* *)
(* Typerex Tools *)
(* *)
Copyright 2011 - 2017 OCamlPro SAS
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU General Public License version 3 described in the file
(* LICENSE. *)
(* *)
(**************************************************************************)
(* [load_config ()] calls "ocamlfind" to load its search path.
[load_config ~ocamlfind ()] can be used to specify a specific
ocamlfind executable. *)
val load_config : ?ocamlfind:string list -> unit -> string list
| null | https://raw.githubusercontent.com/OCamlPro/ocp-build/56aff560bb438c12b2929feaf8379bc6f31b9840/tools/ocp-build/meta/metaConfig.mli | ocaml | ************************************************************************
Typerex Tools
All rights reserved. This file is distributed under the terms of
LICENSE.
************************************************************************
[load_config ()] calls "ocamlfind" to load its search path.
[load_config ~ocamlfind ()] can be used to specify a specific
ocamlfind executable. | Copyright 2011 - 2017 OCamlPro SAS
the GNU General Public License version 3 described in the file
val load_config : ?ocamlfind:string list -> unit -> string list
|
cd23548eaeb09ac107b467718cc1b0708ec1364bf0014309e511b348cb6eca36 | huangjs/cl | code-mops.lisp | (in-package :cs325-user)
(eval-when (:compile-toplevel :load-toplevel :execute)
(require "mops")
)
(defmop programming-language)
(defmop lisp-language (programming-language)
:name "Lisp"
:run-time-types "yes")
(defmop common-lisp (lisp-language)
:name "Common Lisp"
:compile-time-types "optional")
(defmop allegro-lisp (common-lisp)
:name "Allegro")
(defmop allegro-windows (allegro-lisp windows-application)
:platform "windows")
(defmop application)
(defmop windows-application (application))
| null | https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/other-code/cs325/www.cs.northwestern.edu/academics/courses/325/programs/code-mops.lisp | lisp | (in-package :cs325-user)
(eval-when (:compile-toplevel :load-toplevel :execute)
(require "mops")
)
(defmop programming-language)
(defmop lisp-language (programming-language)
:name "Lisp"
:run-time-types "yes")
(defmop common-lisp (lisp-language)
:name "Common Lisp"
:compile-time-types "optional")
(defmop allegro-lisp (common-lisp)
:name "Allegro")
(defmop allegro-windows (allegro-lisp windows-application)
:platform "windows")
(defmop application)
(defmop windows-application (application))
|
|
a1e20f3cd1556f8afae0273d108b4a081eb8ef423c13a0ed983a25737efd24fe | tobias/progress | file.clj | (ns progress.file
(:use progress.bar
progress.util)
(:require [clojure.java.io :as io]))
(defn file-ratio
"Generates a file size ratio string based on the given sizes"
[current-size final-size]
(str (convert-unit current-size) " / " (convert-unit final-size)))
(defn display-file-progress
"Displays the progress of a file download using either a progress
bar or a simple final-size counter, depending on wether a final-size is given."
([current-size]
(display-file-progress current-size nil))
([current-size final-size]
(if (or (nil? final-size) (<= final-size 0))
(padded-printr (convert-unit current-size))
(padded-printr
(str
(progress-bar (if (> final-size 0)
(* 100 (/ current-size final-size))
0))
" "
(file-ratio current-size final-size))))))
(defn done?
"Returns true if the download is finished based on the file sizes."
[current-size final-size]
(= current-size final-size))
(defn check-progress
"Checks the progress of a download, displaying progress data."
[f options]
(Thread/sleep (get options :monitor-interval 100))
(let [file (io/file f)]
(if (.exists file)
(let [current-size (.length file)
final-size (:filesize options)]
(when-not (done? current-size (:filesize options))
(display-file-progress current-size final-size)
(recur f options)))
(recur f options))))
(defn monitor
"Starts a thread to handle check-progress"
[f options]
(let [out *out*]
(doto
(Thread. (fn [] (binding [*out* out]
(check-progress f options))))
(.start))))
(defmacro with-file-progress
"Monitors the size of a file for the duration of BODY.
Options are specified as part of the arg vector in keyword/value pairs.
Currently, the only two options available are :filesize and :monitor-interval.
:monitor-interval controls how often the monitor thread checks and updates
the progress, and defaults to 100ms.
Monitoring can be disabled entirely by setting the progress.monitor sytem property
to \"false\"."
[f & opts-and-body]
(let [[options# body#] (extract-options opts-and-body)]
`(let [monitor-thread# (if (monitor?) (monitor ~f ~options#))]
(try
~@body#
(done)
(finally (if monitor-thread#
(.stop monitor-thread#)))))))
| null | https://raw.githubusercontent.com/tobias/progress/35b6a72cff7b09b849d8170a80626690058a6bd3/src/progress/file.clj | clojure | (ns progress.file
(:use progress.bar
progress.util)
(:require [clojure.java.io :as io]))
(defn file-ratio
"Generates a file size ratio string based on the given sizes"
[current-size final-size]
(str (convert-unit current-size) " / " (convert-unit final-size)))
(defn display-file-progress
"Displays the progress of a file download using either a progress
bar or a simple final-size counter, depending on wether a final-size is given."
([current-size]
(display-file-progress current-size nil))
([current-size final-size]
(if (or (nil? final-size) (<= final-size 0))
(padded-printr (convert-unit current-size))
(padded-printr
(str
(progress-bar (if (> final-size 0)
(* 100 (/ current-size final-size))
0))
" "
(file-ratio current-size final-size))))))
(defn done?
"Returns true if the download is finished based on the file sizes."
[current-size final-size]
(= current-size final-size))
(defn check-progress
"Checks the progress of a download, displaying progress data."
[f options]
(Thread/sleep (get options :monitor-interval 100))
(let [file (io/file f)]
(if (.exists file)
(let [current-size (.length file)
final-size (:filesize options)]
(when-not (done? current-size (:filesize options))
(display-file-progress current-size final-size)
(recur f options)))
(recur f options))))
(defn monitor
"Starts a thread to handle check-progress"
[f options]
(let [out *out*]
(doto
(Thread. (fn [] (binding [*out* out]
(check-progress f options))))
(.start))))
(defmacro with-file-progress
"Monitors the size of a file for the duration of BODY.
Options are specified as part of the arg vector in keyword/value pairs.
Currently, the only two options available are :filesize and :monitor-interval.
:monitor-interval controls how often the monitor thread checks and updates
the progress, and defaults to 100ms.
Monitoring can be disabled entirely by setting the progress.monitor sytem property
to \"false\"."
[f & opts-and-body]
(let [[options# body#] (extract-options opts-and-body)]
`(let [monitor-thread# (if (monitor?) (monitor ~f ~options#))]
(try
~@body#
(done)
(finally (if monitor-thread#
(.stop monitor-thread#)))))))
|
|
24d1e047d0a5015f0e753560d154802c63911a07dbb9e2a5bf1b4a1a346a2c01 | collaborativetrust/WikiTrust | online_revision.ml |
Copyright ( c ) 2007 - 2009 The Regents of the University of California
All rights reserved .
Authors :
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
1 . Redistributions of source code must retain the above copyright notice ,
this list of conditions and the following disclaimer .
2 . Redistributions in binary form must reproduce the above copyright notice ,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution .
3 . The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
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 , IN
CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE )
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE .
Copyright (c) 2007-2009 The Regents of the University of California
All rights reserved.
Authors: Luca de Alfaro
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 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.
*)
open Online_types;;
open Mysql;;
open Eval_defs;;
type word = string;;
exception ReadTextError
(** This is the revision object used for the on-line author reputation and
text trust evaluation. The creation parameters correspond to the
information that can be found for standard = uncolored revisions. *)
class revision
(db: Online_db.db)
(rev_id: int) (* revision id *)
(page_id: int) (* page id *)
(text_id: int) (* text id (for uncolored text) *)
(time_string: string) (* time, as a string yyyymmddhhmmss *)
(user_id: int) (* user id *)
(username: string) (* name of the user *)
(is_minor: bool)
(quality_info_opt: qual_info_t option) (* Quality information, if known. *)
(blob_id_opt_init: int option) (* Blob id, if known. *)
=
let time = Timeconv.time_string_to_float time_string in
let timestamp = Timeconv.time_string_to_timestamp time_string in
let is_anon : bool = (user_id = 0) in
object (self : 'a)
(* These have to do with the revision text. There is nothing in this,
since we do not necessarily read the text of all the revisions we
may want to keep track: reading the text is expensive. *)
val mutable words : word array = [| |]
val mutable seps : Text.sep_t array = [| |]
val mutable sep_word_idx : int array = [| |]
val mutable sigs : Author_sig.packed_author_signature_t array = [| |]
val mutable trust : float array = [| |]
val mutable origin : int array = [| |]
val mutable author : string array = [| |]
(* These quantities keep track of the quality of a revision *)
First , I have a flag that says whether I have read the quantities
or not . They are not read by default ; they reside in a
separate table from standard revision data .
or not. They are not read by default; they reside in a
separate table from standard revision data. *)
val mutable quality_info : qual_info_t = {
n_edit_judges = 0;
judge_weight = 0.;
total_edit_quality = 0.;
min_edit_quality = 0.;
nix_bit = false;
delta = 0.;
reputation_gain = 0.;
overall_trust = 0.;
word_trust_histogram = Array.make 10 0;
}
(* As part of the quality info, we also keep the blob id. *)
val mutable blob_id_opt : int option = None
(* Dirty bits to avoid writing back unchanged stuff *)
val mutable modified_quality_info : bool = false
(** The initializer reads the information from the wikitrust_revision
table, to initialize things such as the quality, and the blob_id. *)
initializer begin
match quality_info_opt with
Some q -> begin
(* If the revision object has been created with a known quality info,
then takes this data and the blob_id from the initializer. *)
quality_info.n_edit_judges <- q.n_edit_judges;
quality_info.judge_weight <- q.judge_weight;
quality_info.total_edit_quality <- q.total_edit_quality;
quality_info.min_edit_quality <- q.min_edit_quality;
quality_info.nix_bit <- q.nix_bit;
quality_info.delta <- q.delta;
quality_info.reputation_gain <- q.reputation_gain;
quality_info.overall_trust <- q.overall_trust;
quality_info.word_trust_histogram <- q.word_trust_histogram;
blob_id_opt <- blob_id_opt_init;
end
| None -> begin
(* No quality information or blob_id is known at initialization.
Tries to get the information from the wikitrust_revision table. *)
try begin
let (q, b) = db#read_revision_quality rev_id in
quality_info <- q;
blob_id_opt <- b;
modified_quality_info <- false;
end with Online_db.DB_Not_Found -> begin
(* If we have not found the revision in the
wikitrust_revision table, leaves the fields initialized
with their default values, and notes that such defaults
will need to be written to the db. *)
modified_quality_info <- true
end
end
end (* Initializer *)
(** Checks if the revision needs coloring. If there is a blob id,
and (as a safety check) it is a valid one, then it does not
need coloring. *)
method needs_coloring : bool =
match blob_id_opt with
None -> true
| Some b -> b <> blob_locations.invalid_location
(* Basic access methods *)
method get_id : int = rev_id
method get_ip : string = if user_id = 0 then username else ""
method get_time : float = time
method get_page_id : int = page_id
method get_user_id : int = user_id
method get_user_name : string = username
method get_is_anon : bool = is_anon
method get_time_string : string = time_string
method get_timestamp : timestamp_t = timestamp
(** Reads the revision text from the db, and splits it appropriately *)
method read_text : unit =
try
We have to use Textbuf here to split text into smaller chunks ,
since otherwise Text chokes on it
since otherwise Text chokes on it *)
let buf = Textbuf.add (db#read_rev_text page_id rev_id text_id)
Textbuf.empty in
let (w, s_idx, s) =
Text.split_into_words_and_seps false false (Textbuf.get buf) in
words <- w;
seps <- s;
sep_word_idx <- s_idx;
with Online_db.DB_Not_Found -> ()
(** Reads the text, trust and sigs of text from the db.
This is useful in voting, where we need the seps, which cannot
be found in page_sigs. We get an optional text, that can save
us the task of reading it from the db. *)
method read_colored_text (raw_text_opt: string option) : unit =
let raw_text = match raw_text_opt with
None -> db#read_colored_markup page_id rev_id blob_id_opt
| Some t -> t
in
The use of Textbuf is to avoid the string routines in Text
from breaking on too long strings .
from breaking on too long strings. *)
let buf = Textbuf.add raw_text Textbuf.empty in
let (w, t, o, a, s_idx, s) = Text.split_into_words_seps_and_info
false false (Textbuf.get buf) in
words <- w;
trust <- t;
origin <- o;
author <- a;
seps <- s;
sep_word_idx <- s_idx;
Checks that the text and trust , sigs information have the
same length .
same length. *)
let trust_len = Array.length trust in
let origin_len = Array.length origin in
let author_len = Array.length author in
let text_len = Array.length words in
if trust_len <> text_len then begin
trust <- Array.create text_len 0.;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed trust for revision %d\n" rev_id);
end;
if origin_len <> text_len then begin
origin <- Array.create text_len rev_id;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed origin for revision %d\n" rev_id);
end;
if author_len <> text_len then begin
author <- Array.create text_len username;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed authors for revision %d\n" rev_id);
end
(** Reads the author signatures, making sure that they are of the
right length. Also replaces trust, sig, and origin info with
what found in the sigs, if of the correct length. *)
method read_author_sigs (page_sigs : Online_db.page_sig_t)
: unit =
begin
try
begin
let (_, t, o, a, s) = db#read_words_trust_origin_sigs
page_id rev_id page_sigs in
sigs <- s;
let text_len = Array.length words in
(* Replaces other fields with more precise version, if possible. *)
if Array.length t = text_len then trust <- t;
if Array.length o = text_len then origin <- o;
if Array.length a = text_len then author <- a
end
with Online_db.DB_Not_Found -> sigs <- [| |]
end;
Checks that the author are the right length .
let sigs_len = Array.length sigs in
let text_len = Array.length words in
if sigs_len <> text_len then begin
sigs <- Array.create text_len Author_sig.empty_sigs;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed sigs for revision %d\n" rev_id);
end
(** Reads the text, trust and sigs of text from the page_sigs is possible.
Note that the seps are not read, if the result is found
in page_sigs. *)
method read_words_trust_origin_sigs (page_sigs : Online_db.page_sig_t)
: unit =
For the older revisions , we do n't need the seps . So , we read
the words , trust , etc , from the sigs table , if we can . This
has two advantages . First , less parsing is needed , so it 's
faster . Second , the information is consistent . If this is
not found , then we parse the colored text .
the words, trust, etc, from the sigs table, if we can. This
has two advantages. First, less parsing is needed, so it's
faster. Second, the information is consistent. If this is
not found, then we parse the colored text. *)
try begin
let (w, t, o, a, s) = db#read_words_trust_origin_sigs
page_id rev_id page_sigs in
words <- w;
trust <- t;
origin <- o;
author <- a;
sigs <- s
end with Online_db.DB_Not_Found ->
begin
(* Not found: we parse the colored text. If this is also not found,
we let the error pop up, so that the caller knows that the revision
needs to be colored. *)
We have to use Textbuf here to split text into smaller chunks ,
since otherwise Text chokes on it .
since otherwise Text chokes on it. *)
let buf = Textbuf.add
(db#read_colored_markup page_id rev_id blob_id_opt) Textbuf.empty in
let (w, t, o, a, s_idx, s) = Text.split_into_words_seps_and_info
false false (Textbuf.get buf) in
words <- w;
trust <- t;
origin <- o;
author <- a;
sigs <- [| |];
seps <- s;
sep_word_idx <- s_idx;
!Online_log.online_logger#log
(Printf.sprintf "Warning: pre-parsed text of revision %d not found, reconstructed.\n" rev_id)
end;
Checks that the text and trust , sigs information have the
same length .
same length. *)
let sigs_len = Array.length sigs in
let trust_len = Array.length trust in
let origin_len = Array.length origin in
let author_len = Array.length author in
let text_len = Array.length words in
if sigs_len <> text_len then begin
sigs <- Array.create text_len Author_sig.empty_sigs;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed sigs for revision %d\n" rev_id);
end;
if trust_len <> text_len then begin
trust <- Array.create text_len 0.;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed trust for revision %d\n" rev_id);
end;
if origin_len <> text_len then begin
origin <- Array.create text_len rev_id;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed origin for revision %d\n" rev_id);
end;
if author_len <> text_len then begin
author <- Array.create text_len username;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed authors for revision %d\n" rev_id);
end
(** Gets the colored text. *)
method get_colored_text (trust_is_float: bool) (include_origin: bool)
(include_author: bool): string =
let buf = Revision.produce_annotated_markup
seps trust origin author
trust_is_float include_origin include_author in
Buffer.contents buf
* Writes the colored text to the db , as a compressed blob .
It takes as first parameter the open blob i d for the page ,
and it returns the updated information , if any . Note
that the write method takes care already of updating the
open blob in the page , so the return value is used only
to help additional writes .
It takes as first parameter the open blob id for the page,
and it returns the updated information, if any. Note
that the write method takes care already of updating the
open blob in the page, so the return value is used only
to help additional writes. *)
method write_colored_text (page_open_blob: int)
(trust_is_float: bool) (include_origin: bool) (include_author: bool)
: int =
(* Writes the colored information, updating as required the blob id.
Note that blob_id_opt can be None, in case the colored data is not
already in the db. For that reason, we let the database
tell us back what the new blob id is. *)
let (new_bid, new_page_open_blob) = db#write_colored_markup
page_id rev_id blob_id_opt page_open_blob
(self#get_colored_text trust_is_float include_origin include_author) in
if Some new_bid <> blob_id_opt then begin
blob_id_opt <- Some new_bid;
modified_quality_info <- true
end;
new_page_open_blob
(** Writes the colored text to the db, as a compressed blob,
using a revision writer object to accomplish that. *)
method write_running_text (writer: Revision_writer.writer)
(trust_is_float: bool) (include_origin: bool) (include_author: bool)
: unit =
(* Writes the colored text using the writer. *)
let new_bid = writer#write_revision rev_id
(self#get_colored_text trust_is_float include_origin include_author) in
if Some new_bid <> blob_id_opt then begin
blob_id_opt <- Some new_bid;
modified_quality_info <- true
end
(** Writes the trust, origin, and sigs to the db, as a signature. *)
method write_words_trust_origin_sigs page_sigs =
db#write_words_trust_origin_sigs
page_id rev_id page_sigs words trust origin author sigs
method get_words : word array = words
method get_seps : Text.sep_t array = seps
method get_sep_word_idx : int array = sep_word_idx
method get_trust : float array = trust
method set_trust (t: float array) = trust <- t
method get_origin : int array = origin
method set_origin (o: int array) = origin <- o
method get_author : string array = author
method set_author (a: string array) = author <- a
method get_sigs : Author_sig.packed_author_signature_t array = sigs
method set_sigs (s: Author_sig.packed_author_signature_t array) = sigs <- s
(** Adds edit quality information *)
method add_edit_quality_info
(delta: float) (jw: float) (new_q: float) : unit =
If there are no judges yet , sets the information for the first time .
if quality_info.n_edit_judges = 0 then begin
Sets the quality info for the first time .
quality_info.delta <- delta;
quality_info.judge_weight <- jw;
quality_info.total_edit_quality <- new_q *. jw;
quality_info.min_edit_quality <- new_q;
quality_info.n_edit_judges <- 1;
end else begin
(* Updates the quality info. *)
quality_info.delta <- min quality_info.delta delta;
quality_info.judge_weight <- quality_info.judge_weight +. jw;
quality_info.total_edit_quality <- quality_info.total_edit_quality +. new_q *. jw;
quality_info.min_edit_quality <- min new_q quality_info.min_edit_quality;
quality_info.n_edit_judges <- quality_info.n_edit_judges + 1;
end;
(* flags the change *)
modified_quality_info <- true
method note_reputation_inc (rep_gain: float) : unit =
quality_info.reputation_gain <- quality_info.reputation_gain +. rep_gain;
modified_quality_info <- true
method set_overall_trust (t: float) : unit =
quality_info.overall_trust <- t;
modified_quality_info <- true
method get_overall_trust : float = quality_info.overall_trust
method set_trust_histogram (a: int array) : unit =
quality_info.word_trust_histogram <- a;
modified_quality_info <- true
method get_trust_histogram : int array = quality_info.word_trust_histogram
method get_nix : bool = quality_info.nix_bit
method set_nix_bit : unit =
quality_info.nix_bit <- true;
modified_quality_info <- true
(** [write_quality_to_db n_attempts] writes all revision quality information to the db. *)
method write_quality_to_db : unit =
if modified_quality_info then
db#write_wikitrust_revision {
Online_db.rev_id = rev_id;
Online_db.rev_page = page_id;
Online_db.rev_text_id = text_id;
Online_db.rev_timestamp = time_string;
Online_db.rev_user = user_id;
Online_db.rev_user_text = username;
Online_db.rev_is_minor = is_minor;
} quality_info blob_id_opt
end (* revision class *)
(** Makes a revision from a revision_t record *)
let make_revision (rev : Online_db.revision_t) db: revision =
new revision db
rev.Online_db.rev_id
rev.Online_db.rev_page
rev.Online_db.rev_text_id
rev.Online_db.rev_timestamp
rev.Online_db.rev_user
rev.Online_db.rev_user_text
rev.Online_db.rev_is_minor
None (* No quality information known *)
None (* No blob_id known *)
(** Makes a revision from a database row *)
let make_revision_from_cursor row db: revision =
let set_is_minor ism = match ism with
| 0 -> false
| 1 -> true
| _ -> assert false in
new revision db
(not_null int2ml row.(0)) (* rev id *)
(not_null int2ml row.(1)) (* page id *)
(not_null int2ml row.(2)) (* text id *)
(not_null str2ml row.(3)) (* timestamp *)
(not_null int2ml row.(4)) (* user id *)
(not_null str2ml row.(5)) (* user name *)
(set_is_minor (not_null int2ml row.(6))) (* is_minor *)
None (* No quality information known *)
None (* No blob_id known *)
(** Reads a revision from the wikitrust_revision table given its
revision id. *)
let read_wikitrust_revision (db: Online_db.db) (id: int) : revision =
begin
let (r_data, q_data, bid_opt) = db#read_wikitrust_revision id in
let rev = new revision db
id
r_data.Online_db.rev_page
r_data.Online_db.rev_text_id
r_data.Online_db.rev_timestamp
r_data.Online_db.rev_user
r_data.Online_db.rev_user_text
r_data.Online_db.rev_is_minor
(Some q_data)
bid_opt
in rev
end
| null | https://raw.githubusercontent.com/collaborativetrust/WikiTrust/9dd056e65c37a22f67d600dd1e87753aa0ec9e2c/analysis/online_revision.ml | ocaml | * This is the revision object used for the on-line author reputation and
text trust evaluation. The creation parameters correspond to the
information that can be found for standard = uncolored revisions.
revision id
page id
text id (for uncolored text)
time, as a string yyyymmddhhmmss
user id
name of the user
Quality information, if known.
Blob id, if known.
These have to do with the revision text. There is nothing in this,
since we do not necessarily read the text of all the revisions we
may want to keep track: reading the text is expensive.
These quantities keep track of the quality of a revision
As part of the quality info, we also keep the blob id.
Dirty bits to avoid writing back unchanged stuff
* The initializer reads the information from the wikitrust_revision
table, to initialize things such as the quality, and the blob_id.
If the revision object has been created with a known quality info,
then takes this data and the blob_id from the initializer.
No quality information or blob_id is known at initialization.
Tries to get the information from the wikitrust_revision table.
If we have not found the revision in the
wikitrust_revision table, leaves the fields initialized
with their default values, and notes that such defaults
will need to be written to the db.
Initializer
* Checks if the revision needs coloring. If there is a blob id,
and (as a safety check) it is a valid one, then it does not
need coloring.
Basic access methods
* Reads the revision text from the db, and splits it appropriately
* Reads the text, trust and sigs of text from the db.
This is useful in voting, where we need the seps, which cannot
be found in page_sigs. We get an optional text, that can save
us the task of reading it from the db.
* Reads the author signatures, making sure that they are of the
right length. Also replaces trust, sig, and origin info with
what found in the sigs, if of the correct length.
Replaces other fields with more precise version, if possible.
* Reads the text, trust and sigs of text from the page_sigs is possible.
Note that the seps are not read, if the result is found
in page_sigs.
Not found: we parse the colored text. If this is also not found,
we let the error pop up, so that the caller knows that the revision
needs to be colored.
* Gets the colored text.
Writes the colored information, updating as required the blob id.
Note that blob_id_opt can be None, in case the colored data is not
already in the db. For that reason, we let the database
tell us back what the new blob id is.
* Writes the colored text to the db, as a compressed blob,
using a revision writer object to accomplish that.
Writes the colored text using the writer.
* Writes the trust, origin, and sigs to the db, as a signature.
* Adds edit quality information
Updates the quality info.
flags the change
* [write_quality_to_db n_attempts] writes all revision quality information to the db.
revision class
* Makes a revision from a revision_t record
No quality information known
No blob_id known
* Makes a revision from a database row
rev id
page id
text id
timestamp
user id
user name
is_minor
No quality information known
No blob_id known
* Reads a revision from the wikitrust_revision table given its
revision id. |
Copyright ( c ) 2007 - 2009 The Regents of the University of California
All rights reserved .
Authors :
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
1 . Redistributions of source code must retain the above copyright notice ,
this list of conditions and the following disclaimer .
2 . Redistributions in binary form must reproduce the above copyright notice ,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution .
3 . The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
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 , IN
CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE )
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE .
Copyright (c) 2007-2009 The Regents of the University of California
All rights reserved.
Authors: Luca de Alfaro
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 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.
*)
open Online_types;;
open Mysql;;
open Eval_defs;;
type word = string;;
exception ReadTextError
class revision
(db: Online_db.db)
(is_minor: bool)
=
let time = Timeconv.time_string_to_float time_string in
let timestamp = Timeconv.time_string_to_timestamp time_string in
let is_anon : bool = (user_id = 0) in
object (self : 'a)
val mutable words : word array = [| |]
val mutable seps : Text.sep_t array = [| |]
val mutable sep_word_idx : int array = [| |]
val mutable sigs : Author_sig.packed_author_signature_t array = [| |]
val mutable trust : float array = [| |]
val mutable origin : int array = [| |]
val mutable author : string array = [| |]
First , I have a flag that says whether I have read the quantities
or not . They are not read by default ; they reside in a
separate table from standard revision data .
or not. They are not read by default; they reside in a
separate table from standard revision data. *)
val mutable quality_info : qual_info_t = {
n_edit_judges = 0;
judge_weight = 0.;
total_edit_quality = 0.;
min_edit_quality = 0.;
nix_bit = false;
delta = 0.;
reputation_gain = 0.;
overall_trust = 0.;
word_trust_histogram = Array.make 10 0;
}
val mutable blob_id_opt : int option = None
val mutable modified_quality_info : bool = false
initializer begin
match quality_info_opt with
Some q -> begin
quality_info.n_edit_judges <- q.n_edit_judges;
quality_info.judge_weight <- q.judge_weight;
quality_info.total_edit_quality <- q.total_edit_quality;
quality_info.min_edit_quality <- q.min_edit_quality;
quality_info.nix_bit <- q.nix_bit;
quality_info.delta <- q.delta;
quality_info.reputation_gain <- q.reputation_gain;
quality_info.overall_trust <- q.overall_trust;
quality_info.word_trust_histogram <- q.word_trust_histogram;
blob_id_opt <- blob_id_opt_init;
end
| None -> begin
try begin
let (q, b) = db#read_revision_quality rev_id in
quality_info <- q;
blob_id_opt <- b;
modified_quality_info <- false;
end with Online_db.DB_Not_Found -> begin
modified_quality_info <- true
end
end
method needs_coloring : bool =
match blob_id_opt with
None -> true
| Some b -> b <> blob_locations.invalid_location
method get_id : int = rev_id
method get_ip : string = if user_id = 0 then username else ""
method get_time : float = time
method get_page_id : int = page_id
method get_user_id : int = user_id
method get_user_name : string = username
method get_is_anon : bool = is_anon
method get_time_string : string = time_string
method get_timestamp : timestamp_t = timestamp
method read_text : unit =
try
We have to use Textbuf here to split text into smaller chunks ,
since otherwise Text chokes on it
since otherwise Text chokes on it *)
let buf = Textbuf.add (db#read_rev_text page_id rev_id text_id)
Textbuf.empty in
let (w, s_idx, s) =
Text.split_into_words_and_seps false false (Textbuf.get buf) in
words <- w;
seps <- s;
sep_word_idx <- s_idx;
with Online_db.DB_Not_Found -> ()
method read_colored_text (raw_text_opt: string option) : unit =
let raw_text = match raw_text_opt with
None -> db#read_colored_markup page_id rev_id blob_id_opt
| Some t -> t
in
The use of Textbuf is to avoid the string routines in Text
from breaking on too long strings .
from breaking on too long strings. *)
let buf = Textbuf.add raw_text Textbuf.empty in
let (w, t, o, a, s_idx, s) = Text.split_into_words_seps_and_info
false false (Textbuf.get buf) in
words <- w;
trust <- t;
origin <- o;
author <- a;
seps <- s;
sep_word_idx <- s_idx;
Checks that the text and trust , sigs information have the
same length .
same length. *)
let trust_len = Array.length trust in
let origin_len = Array.length origin in
let author_len = Array.length author in
let text_len = Array.length words in
if trust_len <> text_len then begin
trust <- Array.create text_len 0.;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed trust for revision %d\n" rev_id);
end;
if origin_len <> text_len then begin
origin <- Array.create text_len rev_id;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed origin for revision %d\n" rev_id);
end;
if author_len <> text_len then begin
author <- Array.create text_len username;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed authors for revision %d\n" rev_id);
end
method read_author_sigs (page_sigs : Online_db.page_sig_t)
: unit =
begin
try
begin
let (_, t, o, a, s) = db#read_words_trust_origin_sigs
page_id rev_id page_sigs in
sigs <- s;
let text_len = Array.length words in
if Array.length t = text_len then trust <- t;
if Array.length o = text_len then origin <- o;
if Array.length a = text_len then author <- a
end
with Online_db.DB_Not_Found -> sigs <- [| |]
end;
Checks that the author are the right length .
let sigs_len = Array.length sigs in
let text_len = Array.length words in
if sigs_len <> text_len then begin
sigs <- Array.create text_len Author_sig.empty_sigs;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed sigs for revision %d\n" rev_id);
end
method read_words_trust_origin_sigs (page_sigs : Online_db.page_sig_t)
: unit =
For the older revisions , we do n't need the seps . So , we read
the words , trust , etc , from the sigs table , if we can . This
has two advantages . First , less parsing is needed , so it 's
faster . Second , the information is consistent . If this is
not found , then we parse the colored text .
the words, trust, etc, from the sigs table, if we can. This
has two advantages. First, less parsing is needed, so it's
faster. Second, the information is consistent. If this is
not found, then we parse the colored text. *)
try begin
let (w, t, o, a, s) = db#read_words_trust_origin_sigs
page_id rev_id page_sigs in
words <- w;
trust <- t;
origin <- o;
author <- a;
sigs <- s
end with Online_db.DB_Not_Found ->
begin
We have to use Textbuf here to split text into smaller chunks ,
since otherwise Text chokes on it .
since otherwise Text chokes on it. *)
let buf = Textbuf.add
(db#read_colored_markup page_id rev_id blob_id_opt) Textbuf.empty in
let (w, t, o, a, s_idx, s) = Text.split_into_words_seps_and_info
false false (Textbuf.get buf) in
words <- w;
trust <- t;
origin <- o;
author <- a;
sigs <- [| |];
seps <- s;
sep_word_idx <- s_idx;
!Online_log.online_logger#log
(Printf.sprintf "Warning: pre-parsed text of revision %d not found, reconstructed.\n" rev_id)
end;
Checks that the text and trust , sigs information have the
same length .
same length. *)
let sigs_len = Array.length sigs in
let trust_len = Array.length trust in
let origin_len = Array.length origin in
let author_len = Array.length author in
let text_len = Array.length words in
if sigs_len <> text_len then begin
sigs <- Array.create text_len Author_sig.empty_sigs;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed sigs for revision %d\n" rev_id);
end;
if trust_len <> text_len then begin
trust <- Array.create text_len 0.;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed trust for revision %d\n" rev_id);
end;
if origin_len <> text_len then begin
origin <- Array.create text_len rev_id;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed origin for revision %d\n" rev_id);
end;
if author_len <> text_len then begin
author <- Array.create text_len username;
!Online_log.online_logger#log (Printf.sprintf "Warning: reconstructed authors for revision %d\n" rev_id);
end
method get_colored_text (trust_is_float: bool) (include_origin: bool)
(include_author: bool): string =
let buf = Revision.produce_annotated_markup
seps trust origin author
trust_is_float include_origin include_author in
Buffer.contents buf
* Writes the colored text to the db , as a compressed blob .
It takes as first parameter the open blob i d for the page ,
and it returns the updated information , if any . Note
that the write method takes care already of updating the
open blob in the page , so the return value is used only
to help additional writes .
It takes as first parameter the open blob id for the page,
and it returns the updated information, if any. Note
that the write method takes care already of updating the
open blob in the page, so the return value is used only
to help additional writes. *)
method write_colored_text (page_open_blob: int)
(trust_is_float: bool) (include_origin: bool) (include_author: bool)
: int =
let (new_bid, new_page_open_blob) = db#write_colored_markup
page_id rev_id blob_id_opt page_open_blob
(self#get_colored_text trust_is_float include_origin include_author) in
if Some new_bid <> blob_id_opt then begin
blob_id_opt <- Some new_bid;
modified_quality_info <- true
end;
new_page_open_blob
method write_running_text (writer: Revision_writer.writer)
(trust_is_float: bool) (include_origin: bool) (include_author: bool)
: unit =
let new_bid = writer#write_revision rev_id
(self#get_colored_text trust_is_float include_origin include_author) in
if Some new_bid <> blob_id_opt then begin
blob_id_opt <- Some new_bid;
modified_quality_info <- true
end
method write_words_trust_origin_sigs page_sigs =
db#write_words_trust_origin_sigs
page_id rev_id page_sigs words trust origin author sigs
method get_words : word array = words
method get_seps : Text.sep_t array = seps
method get_sep_word_idx : int array = sep_word_idx
method get_trust : float array = trust
method set_trust (t: float array) = trust <- t
method get_origin : int array = origin
method set_origin (o: int array) = origin <- o
method get_author : string array = author
method set_author (a: string array) = author <- a
method get_sigs : Author_sig.packed_author_signature_t array = sigs
method set_sigs (s: Author_sig.packed_author_signature_t array) = sigs <- s
method add_edit_quality_info
(delta: float) (jw: float) (new_q: float) : unit =
If there are no judges yet , sets the information for the first time .
if quality_info.n_edit_judges = 0 then begin
Sets the quality info for the first time .
quality_info.delta <- delta;
quality_info.judge_weight <- jw;
quality_info.total_edit_quality <- new_q *. jw;
quality_info.min_edit_quality <- new_q;
quality_info.n_edit_judges <- 1;
end else begin
quality_info.delta <- min quality_info.delta delta;
quality_info.judge_weight <- quality_info.judge_weight +. jw;
quality_info.total_edit_quality <- quality_info.total_edit_quality +. new_q *. jw;
quality_info.min_edit_quality <- min new_q quality_info.min_edit_quality;
quality_info.n_edit_judges <- quality_info.n_edit_judges + 1;
end;
modified_quality_info <- true
method note_reputation_inc (rep_gain: float) : unit =
quality_info.reputation_gain <- quality_info.reputation_gain +. rep_gain;
modified_quality_info <- true
method set_overall_trust (t: float) : unit =
quality_info.overall_trust <- t;
modified_quality_info <- true
method get_overall_trust : float = quality_info.overall_trust
method set_trust_histogram (a: int array) : unit =
quality_info.word_trust_histogram <- a;
modified_quality_info <- true
method get_trust_histogram : int array = quality_info.word_trust_histogram
method get_nix : bool = quality_info.nix_bit
method set_nix_bit : unit =
quality_info.nix_bit <- true;
modified_quality_info <- true
method write_quality_to_db : unit =
if modified_quality_info then
db#write_wikitrust_revision {
Online_db.rev_id = rev_id;
Online_db.rev_page = page_id;
Online_db.rev_text_id = text_id;
Online_db.rev_timestamp = time_string;
Online_db.rev_user = user_id;
Online_db.rev_user_text = username;
Online_db.rev_is_minor = is_minor;
} quality_info blob_id_opt
let make_revision (rev : Online_db.revision_t) db: revision =
new revision db
rev.Online_db.rev_id
rev.Online_db.rev_page
rev.Online_db.rev_text_id
rev.Online_db.rev_timestamp
rev.Online_db.rev_user
rev.Online_db.rev_user_text
rev.Online_db.rev_is_minor
let make_revision_from_cursor row db: revision =
let set_is_minor ism = match ism with
| 0 -> false
| 1 -> true
| _ -> assert false in
new revision db
let read_wikitrust_revision (db: Online_db.db) (id: int) : revision =
begin
let (r_data, q_data, bid_opt) = db#read_wikitrust_revision id in
let rev = new revision db
id
r_data.Online_db.rev_page
r_data.Online_db.rev_text_id
r_data.Online_db.rev_timestamp
r_data.Online_db.rev_user
r_data.Online_db.rev_user_text
r_data.Online_db.rev_is_minor
(Some q_data)
bid_opt
in rev
end
|
cfdc1752d0f683950c8e8bfbe60fcc0d6dcea5537858c4fcae7ac74785953ee2 | cs136/seashell | compiler.rkt | #lang typed/racket
Seashell 's compiler system .
Copyright ( C ) 2013 - 2015 The Seashell Maintainers .
;;
;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;; (at your option) any later version.
;;
;; See also 'ADDITIONAL TERMS' at the end of the included LICENSE file.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
You should have received a copy of the GNU General Public License
;; along with this program. If not, see </>.
(require seashell/compiler/compiler seashell/compiler/place)
(provide (all-from-out seashell/compiler/compiler seashell/compiler/place))
| null | https://raw.githubusercontent.com/cs136/seashell/17cc2b0a6d2cdac270d7168e03aa5fed88f9eb02/src/collects/seashell/compiler.rkt | racket |
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
See also 'ADDITIONAL TERMS' at the end of the included LICENSE file.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>. | #lang typed/racket
Seashell 's compiler system .
Copyright ( C ) 2013 - 2015 The Seashell Maintainers .
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(require seashell/compiler/compiler seashell/compiler/place)
(provide (all-from-out seashell/compiler/compiler seashell/compiler/place))
|
5b9bc49aa244494c1955dbe49d2565754be598a33bb71963724abe814a9a94db | mariachris/Concuerror | etsi_3.erl | -module(etsi_3).
-export([etsi_3/0]).
-export([scenarios/0]).
scenarios() -> [{?MODULE, inf, dpor}].
etsi_3() ->
ets:new(table, [public, named_table]),
ets:insert(table, {x, 0}),
ets:insert(table, {y, 0}),
ets:insert(table, {z, 0}),
spawn(fun() -> ets:insert(table, {y,1}) end),
spawn(fun() ->
[{z,_}] = ets:lookup(table,z),
[{x,X}] = ets:lookup(table,x),
case X of
0 -> [{y,_}] = ets:lookup(table,y);
1 -> ok
end
end),
spawn(fun() -> ets:insert(table, {x,1}) end),
block().
block() ->
receive
after
infinity -> ok
end.
| null | https://raw.githubusercontent.com/mariachris/Concuerror/87e63f10ac615bf2eeac5b0916ef54d11a933e0b/testsuite/suites/dpor/src/etsi_3.erl | erlang | -module(etsi_3).
-export([etsi_3/0]).
-export([scenarios/0]).
scenarios() -> [{?MODULE, inf, dpor}].
etsi_3() ->
ets:new(table, [public, named_table]),
ets:insert(table, {x, 0}),
ets:insert(table, {y, 0}),
ets:insert(table, {z, 0}),
spawn(fun() -> ets:insert(table, {y,1}) end),
spawn(fun() ->
[{z,_}] = ets:lookup(table,z),
[{x,X}] = ets:lookup(table,x),
case X of
0 -> [{y,_}] = ets:lookup(table,y);
1 -> ok
end
end),
spawn(fun() -> ets:insert(table, {x,1}) end),
block().
block() ->
receive
after
infinity -> ok
end.
|
|
87250f10f95283f14134831574a9086035d3f765ce5eaacbeed7c6e9d82ea9d6 | xoken/xoken-core | Crypto.hs | |
Module : Network . . Test . Crypto
Copyright : Xoken Labs
License : Open BSV License
Stability : experimental
Portability : POSIX
Module : Network.Xoken.Test.Crypto
Copyright : Xoken Labs
License : Open BSV License
Stability : experimental
Portability : POSIX
-}
module Network.Xoken.Test.Crypto where
import Network.Xoken.Crypto.Hash
import Network.Xoken.Test.Util
import Test.QuickCheck
| Arbitrary 160 - bit hash .
arbitraryHash160 :: Gen Hash160
arbitraryHash160 = ripemd160 <$> arbitraryBSn 20
| Arbitrary 256 - bit hash .
arbitraryHash256 :: Gen Hash256
arbitraryHash256 = sha256 <$> arbitraryBSn 32
| Arbitrary 512 - bit hash .
arbitraryHash512 :: Gen Hash512
arbitraryHash512 = sha512 <$> arbitraryBSn 64
| Arbitrary 32 - bit checksum .
arbitraryCheckSum32 :: Gen CheckSum32
arbitraryCheckSum32 = checkSum32 <$> arbitraryBSn 4
| null | https://raw.githubusercontent.com/xoken/xoken-core/34399655febdc8c0940da7983489f0c9d58c35d2/core/src/Network/Xoken/Test/Crypto.hs | haskell | |
Module : Network . . Test . Crypto
Copyright : Xoken Labs
License : Open BSV License
Stability : experimental
Portability : POSIX
Module : Network.Xoken.Test.Crypto
Copyright : Xoken Labs
License : Open BSV License
Stability : experimental
Portability : POSIX
-}
module Network.Xoken.Test.Crypto where
import Network.Xoken.Crypto.Hash
import Network.Xoken.Test.Util
import Test.QuickCheck
| Arbitrary 160 - bit hash .
arbitraryHash160 :: Gen Hash160
arbitraryHash160 = ripemd160 <$> arbitraryBSn 20
| Arbitrary 256 - bit hash .
arbitraryHash256 :: Gen Hash256
arbitraryHash256 = sha256 <$> arbitraryBSn 32
| Arbitrary 512 - bit hash .
arbitraryHash512 :: Gen Hash512
arbitraryHash512 = sha512 <$> arbitraryBSn 64
| Arbitrary 32 - bit checksum .
arbitraryCheckSum32 :: Gen CheckSum32
arbitraryCheckSum32 = checkSum32 <$> arbitraryBSn 4
|
|
bef831cc9bf292dbd7b26f5ed9682596d408a00e637a67f0ddb045cf6b3a34d3 | magthe/sandi | Base64Url.hs | -- |
-- Module: Data.Conduit.Codec.Base64Url
Copyright : ( c ) 2014
-- License: BSD3
module Data.Conduit.Codec.Base64Url where
import qualified Codec.Binary.Base64Url as B64U
import qualified Data.Conduit.Codec.Util as U
import Control.Monad.Catch (MonadThrow)
import Data.ByteString (ByteString, empty)
import Data.Conduit (ConduitT)
encode :: (Monad m) => ConduitT ByteString ByteString m ()
encode = U.encodeI B64U.b64uEncodePart B64U.b64uEncodeFinal empty
decode :: (Monad m, MonadThrow m) => ConduitT ByteString ByteString m ()
decode = U.decodeI B64U.b64uDecodePart B64U.b64uDecodeFinal empty
| null | https://raw.githubusercontent.com/magthe/sandi/a8ef86ec3798a640d86342421a7fa7fa97bdedd4/sandi/src/Data/Conduit/Codec/Base64Url.hs | haskell | |
Module: Data.Conduit.Codec.Base64Url
License: BSD3 | Copyright : ( c ) 2014
module Data.Conduit.Codec.Base64Url where
import qualified Codec.Binary.Base64Url as B64U
import qualified Data.Conduit.Codec.Util as U
import Control.Monad.Catch (MonadThrow)
import Data.ByteString (ByteString, empty)
import Data.Conduit (ConduitT)
encode :: (Monad m) => ConduitT ByteString ByteString m ()
encode = U.encodeI B64U.b64uEncodePart B64U.b64uEncodeFinal empty
decode :: (Monad m, MonadThrow m) => ConduitT ByteString ByteString m ()
decode = U.decodeI B64U.b64uDecodePart B64U.b64uDecodeFinal empty
|
7fdad65b4490c9f59de32ed4a52015486bf5db1224f09872f21d5d9b0f156c9f | Smart-Sql/smart-sql | my_smart_scenes.clj | (ns org.gridgain.plus.sql.my-smart-scenes
(:require
[org.gridgain.plus.dml.select-lexical :as my-lexical]
[org.gridgain.plus.dml.my-select-plus :as my-select-plus]
[org.gridgain.plus.dml.my-smart-token-clj :as my-smart-token-clj]
[org.gridgain.plus.dml.my-insert :as my-insert]
[org.gridgain.plus.dml.my-update :as my-update]
[org.gridgain.plus.dml.my-delete :as my-delete]
[clojure.core.reducers :as r]
[clojure.string :as str]
[clojure.walk :as w])
(:import (org.apache.ignite Ignite)
(org.gridgain.smart MyVar)
(org.tools MyPlusUtil)
(org.gridgain.dml.util MyCacheExUtil)
(cn.plus.model.db MyCallScenesPk MyCallScenes MyScenesCache ScenesType MyScenesParams MyScenesParamsPk MyScenesCachePk)
(org.apache.ignite.cache.query SqlFieldsQuery)
(java.math BigDecimal)
(java.util List ArrayList Hashtable Date Iterator)
)
(:gen-class
; 生成 class 的类名
:name org.gridgain.plus.dml.MySmartScenes
是否生成 class 的 main 方法
:main false
; init 构造函数
:init init
生成 java 静态的方法
;:methods [^:static [invokeScenes [org.apache.ignite.Ignite Long String java.util.List] Object]
; ^:static [myInvokeScenes [org.apache.ignite.Ignite Long Long] Object]
; ^:static [myInit [] void]
; ^:static [myShowCode [org.apache.ignite.Ignite Long String] String]
; ^:static [invokeScenesLink [org.apache.ignite.Ignite Long String java.util.List] Object]]
:methods [[invokeScenes [org.apache.ignite.Ignite Object String java.util.List] Object]
[myInvokeScenes [org.apache.ignite.Ignite Long Long] Object]
[myShowCode [org.apache.ignite.Ignite Long String] String]
[invokeScenesLink [org.apache.ignite.Ignite Object String java.util.List] Object]]
))
; 调用 func
(defn my-invoke-func [^Ignite ignite ^String method-name ps]
(MyPlusUtil/invokeFuncObj ignite (str/lower-case method-name) (to-array ps)))
(defn my-invoke-func-no-ps [^Ignite ignite ^String method-name]
(MyPlusUtil/invokeFuncNoPs ignite (str/lower-case method-name)))
; 获取输入参数和处理后的参数
(defn get-params [params]
(if (> (count params) 0)
(loop [[f & r] (MyPlusUtil/getParams params) ps-line [] ps-line-ex []]
(if (some? f)
(let [ps-name (str (gensym "c"))]
(recur r (conj ps-line ps-name) (conj ps-line-ex (MyPlusUtil/getValue ps-name (.getPs_type f)))))
[(str/join " " ps-line) (str/join " " ps-line-ex)])
)
))
; 获取真实的 clj
(defn get-code-by-scenes [m]
(let [sql-code (.getSql_code m) scenes_name (.getScenes_name m) [ps-line ps-line-ex] (get-params (.getParams m))]
[sql-code (format "(defn %s-ex [^Ignite ignite group_id %s]\n (%s ignite group_id %s))" scenes_name ps-line scenes_name ps-line-ex)]
))
(defn scenes-run [^Ignite ignite group_id ^String my-method-name ps]
(let [m (.get (.cache ignite "my_scenes") (MyScenesCachePk. (first group_id) my-method-name))]
(if-not (nil? m)
(let [sql-code (.getSql_code m)]
(eval (read-string sql-code))
(my-lexical/get-value (apply (eval (read-string my-method-name)) ignite group_id ps)))
)
(my-lexical/get-value (apply (eval (read-string my-method-name)) ignite group_id ps))))
(defn get-call-group-id [^Ignite ignite group_id my-method-name]
(.get (.cache ignite "call_scenes") (MyCallScenesPk. group_id my-method-name)))
; 调用 scenes
(defn my-invoke-scenes [^Ignite ignite group_id ^String method-name ps]
(let [my-method-name (str/lower-case method-name)]
(try
(my-lexical/get-value (apply (eval (read-string my-method-name)) ignite group_id ps))
(catch Exception e
(if-let [my-group (get-call-group-id ignite (first group_id) my-method-name)]
(my-invoke-scenes ignite (.getGroup_id_obj my-group) method-name ps)
(scenes-run ignite group_id my-method-name ps))
))))
(defn my-invoke-scenes-no-ps [^Ignite ignite group_id ^String method-name]
(my-invoke-scenes ignite group_id method-name []))
( defn my - invoke - scenes [ ^Ignite ignite ^Long group_id ^String method - name ps ]
; (let [my-method-name (str/lower-case method-name)]
; (try
; (my-lexical/get-value (apply (eval (read-string (format "%s-ex" my-method-name))) ignite group_id ps))
; (catch Exception e
( let [ m ( .get ( .cache ignite " my_scenes " ) ( MyScenesCachePk . group_id my - method - name ) ) ]
; (let [[sql-code sql-code-ex] (get-code-by-scenes m)]
; (eval (read-string sql-code))
; (my-lexical/get-value (apply (eval (read-string sql-code-ex)) ignite group_id ps)))
; (my-lexical/get-value (apply (eval (read-string (format "%s-ex" my-method-name))) ignite group_id ps)))))))
; 调用 scenes
( defn my - invoke - scenes - link [ ^Ignite ignite ^Long group_id ^String method - name & ps ]
; (let [my-method-name (str/lower-case method-name)]
; (my-lexical/get-value (apply (eval (read-string my-method-name)) ignite group_id ps))))
(defn my-invoke-scenes-link [^Ignite ignite group_id ^String method-code ps]
(let [[code args] (my-smart-token-clj/func-link-clj ignite group_id (my-select-plus/sql-to-ast (my-lexical/to-back method-code)))]
(apply (eval (read-string code)) ignite group_id ps)))
首先调用方法,如果不存在,在从 cache 中读取数据在执行
(defn -invokeScenes [^Ignite ignite group_id ^String method-name ^List ps]
(my-invoke-scenes ignite group_id method-name ps))
(defn -invokeScenesLink [^Ignite ignite group_id ^String method-name ^List ps]
(my-invoke-scenes-link ignite group_id method-name ps))
(defn -myInvokeScenes [this ^Ignite ignite ^Long a ^Long b]
(my-lexical/get-value (apply (eval (read-string "(defn add [ignite a b]\n (+ a b))")) [nil a b])))
(defn -myShowCode [this ^Ignite ignite ^Long group_id ^String method-name]
(do
( import ( cn.plus.model.db MyScenesCache ScenesType MyScenesParams MyScenesParamsPk MyScenesCachePk ) )
(my-lexical/get-value (apply (eval (read-string "(defn get-code [ignite group_id my-method-name]\n (let [m (.get (.cache ignite \"my_scenes\") (MyScenesCachePk. group_id my-method-name))]\n (.getSql_code m)))")) [ignite group_id method-name]))))
(defn -init []
(do
(import (org.apache.ignite Ignite IgniteCache)
(org.apache.ignite.internal IgnitionEx)
(org.gridgain.smart MyVar)
(com.google.common.base Strings)
(org.tools MyConvertUtil MyPlusUtil KvSql MyDbUtil MyGson MyTools MyFunction)
(cn.plus.model MyCacheEx MyKeyValue MyLogCache SqlType)
(cn.plus.model.ddl MyDataSet MyDeleteViews MyInsertViews MySelectViews MyTable MyTableIndex MyTableIndexItem MyTableItem MyTableItemPK MyUpdateViews)
(org.gridgain.dml.util MyCacheExUtil)
(cn.plus.model.db MyScenesCache MyScenesParams MyScenesParamsPk MyScenesCachePk)
(org.apache.ignite.configuration CacheConfiguration)
(org.apache.ignite.cache CacheMode CacheAtomicityMode)
(org.apache.ignite.cache.query FieldsQueryCursor SqlFieldsQuery)
(org.apache.ignite.binary BinaryObjectBuilder BinaryObject)
(java.util List ArrayList Date Iterator Hashtable)
(java.sql Timestamp)
(java.math BigDecimal)
)
(require
'[org.gridgain.plus.ddl.my-create-table :as my-create-table]
'[org.gridgain.plus.ddl.my-alter-table :as my-alter-table]
'[org.gridgain.plus.ddl.my-create-index :as my-create-index]
'[org.gridgain.plus.ddl.my-drop-index :as my-drop-index]
'[org.gridgain.plus.ddl.my-drop-table :as my-drop-table]
'[org.gridgain.plus.ddl.my-create-dataset :as my-create-dataset]
'[org.gridgain.plus.ddl.my-drop-dataset :as my-drop-dataset]
'[org.gridgain.plus.dml.my-delete :as my-delete]
'[org.gridgain.plus.dml.my-insert :as my-insert]
'[org.gridgain.plus.dml.my-load-smart-sql :as my-load-smart-sql]
'[org.gridgain.plus.dml.my-select-plus :as my-select-plus]
'[org.gridgain.plus.dml.my-select-plus-args :as my-select-plus-args]
'[org.gridgain.plus.dml.my-smart-clj :as my-smart-clj]
'[org.gridgain.plus.dml.my-smart-db :as my-smart-db]
'[org.gridgain.plus.dml.my-smart-db-line :as my-smart-db-line]
'[org.gridgain.plus.dml.my-smart-func-args-token-clj :as my-smart-func-args-token-clj]
'[org.gridgain.plus.dml.my-smart-sql :as my-smart-sql]
'[org.gridgain.plus.dml.my-smart-token-clj :as my-smart-token-clj]
'[org.gridgain.plus.dml.my-update :as my-update]
'[org.gridgain.plus.dml.select-lexical :as my-lexical]
'[org.gridgain.plus.init.plus-init :as plus-init]
'[org.gridgain.plus.sql.my-smart-scenes :as my-smart-scenes]
'[org.gridgain.plus.sql.my-super-sql :as my-super-sql]
'[org.gridgain.plus.tools.my-cache :as my-cache]
'[org.gridgain.plus.tools.my-date-util :as my-date-util]
'[org.gridgain.plus.tools.my-java-util :as my-java-util]
'[org.gridgain.plus.tools.my-util :as my-util]
'[org.gridgain.plus.user.my-user :as my-user]
'[org.gridgain.plus.smart-func :as smart-func]
'[org.gridgain.plus.ml.my-ml-train-data :as my-ml-train-data]
'[org.gridgain.plus.ml.my-ml-func :as my-ml-func]
'[clojure.core.reducers :as r]
'[clojure.string :as str]
'[clojure.walk :as w]
)
))
| null | https://raw.githubusercontent.com/Smart-Sql/smart-sql/d2f237f935472942a143816925221cdcf8246aff/src/main/clojure/org/gridgain/plus/sql/my_smart_scenes.clj | clojure | 生成 class 的类名
init 构造函数
:methods [^:static [invokeScenes [org.apache.ignite.Ignite Long String java.util.List] Object]
^:static [myInvokeScenes [org.apache.ignite.Ignite Long Long] Object]
^:static [myInit [] void]
^:static [myShowCode [org.apache.ignite.Ignite Long String] String]
^:static [invokeScenesLink [org.apache.ignite.Ignite Long String java.util.List] Object]]
调用 func
获取输入参数和处理后的参数
获取真实的 clj
调用 scenes
(let [my-method-name (str/lower-case method-name)]
(try
(my-lexical/get-value (apply (eval (read-string (format "%s-ex" my-method-name))) ignite group_id ps))
(catch Exception e
(let [[sql-code sql-code-ex] (get-code-by-scenes m)]
(eval (read-string sql-code))
(my-lexical/get-value (apply (eval (read-string sql-code-ex)) ignite group_id ps)))
(my-lexical/get-value (apply (eval (read-string (format "%s-ex" my-method-name))) ignite group_id ps)))))))
调用 scenes
(let [my-method-name (str/lower-case method-name)]
(my-lexical/get-value (apply (eval (read-string my-method-name)) ignite group_id ps)))) | (ns org.gridgain.plus.sql.my-smart-scenes
(:require
[org.gridgain.plus.dml.select-lexical :as my-lexical]
[org.gridgain.plus.dml.my-select-plus :as my-select-plus]
[org.gridgain.plus.dml.my-smart-token-clj :as my-smart-token-clj]
[org.gridgain.plus.dml.my-insert :as my-insert]
[org.gridgain.plus.dml.my-update :as my-update]
[org.gridgain.plus.dml.my-delete :as my-delete]
[clojure.core.reducers :as r]
[clojure.string :as str]
[clojure.walk :as w])
(:import (org.apache.ignite Ignite)
(org.gridgain.smart MyVar)
(org.tools MyPlusUtil)
(org.gridgain.dml.util MyCacheExUtil)
(cn.plus.model.db MyCallScenesPk MyCallScenes MyScenesCache ScenesType MyScenesParams MyScenesParamsPk MyScenesCachePk)
(org.apache.ignite.cache.query SqlFieldsQuery)
(java.math BigDecimal)
(java.util List ArrayList Hashtable Date Iterator)
)
(:gen-class
:name org.gridgain.plus.dml.MySmartScenes
是否生成 class 的 main 方法
:main false
:init init
生成 java 静态的方法
:methods [[invokeScenes [org.apache.ignite.Ignite Object String java.util.List] Object]
[myInvokeScenes [org.apache.ignite.Ignite Long Long] Object]
[myShowCode [org.apache.ignite.Ignite Long String] String]
[invokeScenesLink [org.apache.ignite.Ignite Object String java.util.List] Object]]
))
(defn my-invoke-func [^Ignite ignite ^String method-name ps]
(MyPlusUtil/invokeFuncObj ignite (str/lower-case method-name) (to-array ps)))
(defn my-invoke-func-no-ps [^Ignite ignite ^String method-name]
(MyPlusUtil/invokeFuncNoPs ignite (str/lower-case method-name)))
(defn get-params [params]
(if (> (count params) 0)
(loop [[f & r] (MyPlusUtil/getParams params) ps-line [] ps-line-ex []]
(if (some? f)
(let [ps-name (str (gensym "c"))]
(recur r (conj ps-line ps-name) (conj ps-line-ex (MyPlusUtil/getValue ps-name (.getPs_type f)))))
[(str/join " " ps-line) (str/join " " ps-line-ex)])
)
))
(defn get-code-by-scenes [m]
(let [sql-code (.getSql_code m) scenes_name (.getScenes_name m) [ps-line ps-line-ex] (get-params (.getParams m))]
[sql-code (format "(defn %s-ex [^Ignite ignite group_id %s]\n (%s ignite group_id %s))" scenes_name ps-line scenes_name ps-line-ex)]
))
(defn scenes-run [^Ignite ignite group_id ^String my-method-name ps]
(let [m (.get (.cache ignite "my_scenes") (MyScenesCachePk. (first group_id) my-method-name))]
(if-not (nil? m)
(let [sql-code (.getSql_code m)]
(eval (read-string sql-code))
(my-lexical/get-value (apply (eval (read-string my-method-name)) ignite group_id ps)))
)
(my-lexical/get-value (apply (eval (read-string my-method-name)) ignite group_id ps))))
(defn get-call-group-id [^Ignite ignite group_id my-method-name]
(.get (.cache ignite "call_scenes") (MyCallScenesPk. group_id my-method-name)))
(defn my-invoke-scenes [^Ignite ignite group_id ^String method-name ps]
(let [my-method-name (str/lower-case method-name)]
(try
(my-lexical/get-value (apply (eval (read-string my-method-name)) ignite group_id ps))
(catch Exception e
(if-let [my-group (get-call-group-id ignite (first group_id) my-method-name)]
(my-invoke-scenes ignite (.getGroup_id_obj my-group) method-name ps)
(scenes-run ignite group_id my-method-name ps))
))))
(defn my-invoke-scenes-no-ps [^Ignite ignite group_id ^String method-name]
(my-invoke-scenes ignite group_id method-name []))
( defn my - invoke - scenes [ ^Ignite ignite ^Long group_id ^String method - name ps ]
( let [ m ( .get ( .cache ignite " my_scenes " ) ( MyScenesCachePk . group_id my - method - name ) ) ]
( defn my - invoke - scenes - link [ ^Ignite ignite ^Long group_id ^String method - name & ps ]
(defn my-invoke-scenes-link [^Ignite ignite group_id ^String method-code ps]
(let [[code args] (my-smart-token-clj/func-link-clj ignite group_id (my-select-plus/sql-to-ast (my-lexical/to-back method-code)))]
(apply (eval (read-string code)) ignite group_id ps)))
首先调用方法,如果不存在,在从 cache 中读取数据在执行
(defn -invokeScenes [^Ignite ignite group_id ^String method-name ^List ps]
(my-invoke-scenes ignite group_id method-name ps))
(defn -invokeScenesLink [^Ignite ignite group_id ^String method-name ^List ps]
(my-invoke-scenes-link ignite group_id method-name ps))
(defn -myInvokeScenes [this ^Ignite ignite ^Long a ^Long b]
(my-lexical/get-value (apply (eval (read-string "(defn add [ignite a b]\n (+ a b))")) [nil a b])))
(defn -myShowCode [this ^Ignite ignite ^Long group_id ^String method-name]
(do
( import ( cn.plus.model.db MyScenesCache ScenesType MyScenesParams MyScenesParamsPk MyScenesCachePk ) )
(my-lexical/get-value (apply (eval (read-string "(defn get-code [ignite group_id my-method-name]\n (let [m (.get (.cache ignite \"my_scenes\") (MyScenesCachePk. group_id my-method-name))]\n (.getSql_code m)))")) [ignite group_id method-name]))))
(defn -init []
(do
(import (org.apache.ignite Ignite IgniteCache)
(org.apache.ignite.internal IgnitionEx)
(org.gridgain.smart MyVar)
(com.google.common.base Strings)
(org.tools MyConvertUtil MyPlusUtil KvSql MyDbUtil MyGson MyTools MyFunction)
(cn.plus.model MyCacheEx MyKeyValue MyLogCache SqlType)
(cn.plus.model.ddl MyDataSet MyDeleteViews MyInsertViews MySelectViews MyTable MyTableIndex MyTableIndexItem MyTableItem MyTableItemPK MyUpdateViews)
(org.gridgain.dml.util MyCacheExUtil)
(cn.plus.model.db MyScenesCache MyScenesParams MyScenesParamsPk MyScenesCachePk)
(org.apache.ignite.configuration CacheConfiguration)
(org.apache.ignite.cache CacheMode CacheAtomicityMode)
(org.apache.ignite.cache.query FieldsQueryCursor SqlFieldsQuery)
(org.apache.ignite.binary BinaryObjectBuilder BinaryObject)
(java.util List ArrayList Date Iterator Hashtable)
(java.sql Timestamp)
(java.math BigDecimal)
)
(require
'[org.gridgain.plus.ddl.my-create-table :as my-create-table]
'[org.gridgain.plus.ddl.my-alter-table :as my-alter-table]
'[org.gridgain.plus.ddl.my-create-index :as my-create-index]
'[org.gridgain.plus.ddl.my-drop-index :as my-drop-index]
'[org.gridgain.plus.ddl.my-drop-table :as my-drop-table]
'[org.gridgain.plus.ddl.my-create-dataset :as my-create-dataset]
'[org.gridgain.plus.ddl.my-drop-dataset :as my-drop-dataset]
'[org.gridgain.plus.dml.my-delete :as my-delete]
'[org.gridgain.plus.dml.my-insert :as my-insert]
'[org.gridgain.plus.dml.my-load-smart-sql :as my-load-smart-sql]
'[org.gridgain.plus.dml.my-select-plus :as my-select-plus]
'[org.gridgain.plus.dml.my-select-plus-args :as my-select-plus-args]
'[org.gridgain.plus.dml.my-smart-clj :as my-smart-clj]
'[org.gridgain.plus.dml.my-smart-db :as my-smart-db]
'[org.gridgain.plus.dml.my-smart-db-line :as my-smart-db-line]
'[org.gridgain.plus.dml.my-smart-func-args-token-clj :as my-smart-func-args-token-clj]
'[org.gridgain.plus.dml.my-smart-sql :as my-smart-sql]
'[org.gridgain.plus.dml.my-smart-token-clj :as my-smart-token-clj]
'[org.gridgain.plus.dml.my-update :as my-update]
'[org.gridgain.plus.dml.select-lexical :as my-lexical]
'[org.gridgain.plus.init.plus-init :as plus-init]
'[org.gridgain.plus.sql.my-smart-scenes :as my-smart-scenes]
'[org.gridgain.plus.sql.my-super-sql :as my-super-sql]
'[org.gridgain.plus.tools.my-cache :as my-cache]
'[org.gridgain.plus.tools.my-date-util :as my-date-util]
'[org.gridgain.plus.tools.my-java-util :as my-java-util]
'[org.gridgain.plus.tools.my-util :as my-util]
'[org.gridgain.plus.user.my-user :as my-user]
'[org.gridgain.plus.smart-func :as smart-func]
'[org.gridgain.plus.ml.my-ml-train-data :as my-ml-train-data]
'[org.gridgain.plus.ml.my-ml-func :as my-ml-func]
'[clojure.core.reducers :as r]
'[clojure.string :as str]
'[clojure.walk :as w]
)
))
|
5843cc0e157d59c9d9390db1762b46002f35a9fb021bb566f5a1177edd28b660 | weyrick/roadsend-php | core-builtins.scm | ;; ***** BEGIN LICENSE BLOCK *****
Roadsend PHP Compiler Runtime Libraries
Copyright ( C ) 2008 Roadsend , Inc.
;;
;; 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 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. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA
;; ***** END LICENSE BLOCK *****
(module core-builtins
(library profiler)
(include "php-runtime.sch")
(load
(php-macros "../php-macros.scm"))
(use
(signatures "signatures.scm")
(php-object "php-object.scm")
(php-runtime "php-runtime.scm")
(php-hash "php-hash.scm")
(php-errors "php-errors.scm"))
(export
(init-core-builtins)
(_default_error_handler errno errstr errfile errline vars)
(_default_exception_handler exception_obj)
(php-exit status)
))
(define (init-core-builtins)
(register-extension "runtime" "1.0.0" "php-runtime"))
(defbuiltin (_default_exception_handler exception_obj)
(php-error "Uncaught exception '" (php-object-class exception_obj) "'"))
(defbuiltin (_default_error_handler errno errstr (errfile "unknown file") (errline "unknown line") (vars 'unset))
(let ((etype (check-etype (mkfixnum (convert-to-number errno)))))
; if etype wasn't a string, we're not showing the message
; due to error reporting level
(when (string? etype)
(if *commandline?*
(begin
(echo (mkstr "\n" etype ": " errstr " in " errfile " on line " errline "\n"))
(when (or (equalp errno E_USER_ERROR)
(equalp errno E_RECOVERABLE_ERROR)) ;XXX any others?
(php-exit 255)))
(begin
(when (equalp errno E_USER_ERROR)
(print-stack-trace-html))
(echo (mkstr "<br />\n<b>" etype "</b>: " errstr " in <b>" errfile "</b> on line <b>" errline "</b><br />\n"))
(when (or (equalp errno E_USER_ERROR)
(equalp errno E_RECOVERABLE_ERROR)) ;XXX any others?
(php-exit 255)))))))
(defalias die php-exit)
(defalias exit php-exit)
(defbuiltin (php-exit (status 0))
(set! status (maybe-unbox status))
(if *commandline?*
(if (string? status)
(begin
(echo status)
(exit 0))
(exit (mkfixnum status)))
(begin
(when (string? status)
(echo status))
;special error that'll be filtered out.
(error 'php-exit "exiting" 'php-exit))))
; based on current error level return either #f if we shouldn't
; show this error, or a string detailing the error type
(define (check-etype errno)
;(print "errno is " errno " and level is " (mkstr *error-level*))
(if (or (php-= *error-level* E_ALL)
(php-> (bitwise-and *error-level* errno) 0))
(begin
(cond ((or (php-= errno E_USER_WARNING)
(php-= errno E_WARNING)) "Warning")
;((or (php-= errno E_USER_ERROR)
( php-= errno ) " Fatal error " )
((php-= errno E_USER_ERROR) "Fatal error")
((php-= errno E_RECOVERABLE_ERROR) "Catchable fatal error")
((or (php-= errno E_USER_NOTICE)
(php-= errno E_NOTICE)) "Notice")
(else "Unknown error")))
; they don't want to see this error
; based on error-level
#f))
| null | https://raw.githubusercontent.com/weyrick/roadsend-php/d6301a897b1a02d7a85bdb915bea91d0991eb158/runtime/core-builtins.scm | scheme | ***** BEGIN LICENSE BLOCK *****
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
either version 2.1
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program; if not, write to the Free Software
***** END LICENSE BLOCK *****
if etype wasn't a string, we're not showing the message
due to error reporting level
XXX any others?
XXX any others?
special error that'll be filtered out.
based on current error level return either #f if we shouldn't
show this error, or a string detailing the error type
(print "errno is " errno " and level is " (mkstr *error-level*))
((or (php-= errno E_USER_ERROR)
they don't want to see this error
based on error-level | Roadsend PHP Compiler Runtime Libraries
Copyright ( C ) 2008 Roadsend , Inc.
of the License , or ( at your option ) any later version .
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA
(module core-builtins
(library profiler)
(include "php-runtime.sch")
(load
(php-macros "../php-macros.scm"))
(use
(signatures "signatures.scm")
(php-object "php-object.scm")
(php-runtime "php-runtime.scm")
(php-hash "php-hash.scm")
(php-errors "php-errors.scm"))
(export
(init-core-builtins)
(_default_error_handler errno errstr errfile errline vars)
(_default_exception_handler exception_obj)
(php-exit status)
))
(define (init-core-builtins)
(register-extension "runtime" "1.0.0" "php-runtime"))
(defbuiltin (_default_exception_handler exception_obj)
(php-error "Uncaught exception '" (php-object-class exception_obj) "'"))
(defbuiltin (_default_error_handler errno errstr (errfile "unknown file") (errline "unknown line") (vars 'unset))
(let ((etype (check-etype (mkfixnum (convert-to-number errno)))))
(when (string? etype)
(if *commandline?*
(begin
(echo (mkstr "\n" etype ": " errstr " in " errfile " on line " errline "\n"))
(when (or (equalp errno E_USER_ERROR)
(php-exit 255)))
(begin
(when (equalp errno E_USER_ERROR)
(print-stack-trace-html))
(echo (mkstr "<br />\n<b>" etype "</b>: " errstr " in <b>" errfile "</b> on line <b>" errline "</b><br />\n"))
(when (or (equalp errno E_USER_ERROR)
(php-exit 255)))))))
(defalias die php-exit)
(defalias exit php-exit)
(defbuiltin (php-exit (status 0))
(set! status (maybe-unbox status))
(if *commandline?*
(if (string? status)
(begin
(echo status)
(exit 0))
(exit (mkfixnum status)))
(begin
(when (string? status)
(echo status))
(error 'php-exit "exiting" 'php-exit))))
(define (check-etype errno)
(if (or (php-= *error-level* E_ALL)
(php-> (bitwise-and *error-level* errno) 0))
(begin
(cond ((or (php-= errno E_USER_WARNING)
(php-= errno E_WARNING)) "Warning")
( php-= errno ) " Fatal error " )
((php-= errno E_USER_ERROR) "Fatal error")
((php-= errno E_RECOVERABLE_ERROR) "Catchable fatal error")
((or (php-= errno E_USER_NOTICE)
(php-= errno E_NOTICE)) "Notice")
(else "Unknown error")))
#f))
|
cac38ed344b3e3c7d65246e35891041eedb43978827a8a102c8cf7b0b09b0e34 | grin-compiler/grin | ConstantPropagation.hs | # LANGUAGE LambdaCase , TupleSections , ViewPatterns #
module Transformations.Optimising.ConstantPropagation where
import Text.Printf
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Functor.Foldable as Foldable
import Grin.Grin
import Transformations.Util
type Env = Map Val Val
{-
HINT:
propagates only tag values but not literals
GRIN is not a supercompiler
-}
constantPropagation :: Exp -> Exp
constantPropagation e = ana builder (mempty, e) where
builder :: (Env, Exp) -> ExpF (Env, Exp)
builder (env, exp) = case exp of
ECase val alts ->
let constVal = substValsVal env val
known = isKnown constVal || Map.member val env
matchingAlts = [alt | alt@(Alt cpat body) <- alts, match cpat constVal]
defaultAlts = [alt | alt@(Alt DefaultPat body) <- alts]
HINT : use cpat as known value in the alternative ; bind cpat to val
altEnv cpat = env `mappend` unify env (cpatToLPat cpat) val
in case (known, matchingAlts, defaultAlts) of
known scutinee , specific pattern
(True, [Alt cpat body], _) -> (env,) <$> SBlockF (EBind (SReturn constVal) (cpatToLPat cpat) body)
known scutinee , default pattern
(True, _, [Alt DefaultPat body]) -> (env,) <$> SBlockF body
unknown scutinee
-- HINT: in each alternative set val value like it was matched
_ -> ECaseF val [(altEnv cpat, alt) | alt@(Alt cpat _) <- alts]
-- track values
EBind (SReturn val) lpat rightExp -> (env `mappend` unify env val lpat,) <$> project exp
_ -> (env,) <$> project exp
unify :: Env -> Val -> LPat -> Env
unify env (substValsVal env -> val) lpat = case (lpat, val) of
(Var{}, ConstTagNode{}) -> Map.singleton lpat val
(Var{}, Unit) -> Map.singleton lpat val -- HINT: default pattern (minor hack)
LPat : unit , lit , tag
isKnown :: Val -> Bool
isKnown = \case
ConstTagNode{} -> True
ValTag{} -> True
_ -> False
match :: CPat -> Val -> Bool
match (NodePat tagA _) (ConstTagNode tagB _) = tagA == tagB
match (TagPat tagA) (ValTag tagB) = tagA == tagB
match _ _ = False
| null | https://raw.githubusercontent.com/grin-compiler/grin/44ac2958810ecee969c8028d2d2a082d47fba51b/grin/src/Transformations/Optimising/ConstantPropagation.hs | haskell |
HINT:
propagates only tag values but not literals
GRIN is not a supercompiler
HINT: in each alternative set val value like it was matched
track values
HINT: default pattern (minor hack) | # LANGUAGE LambdaCase , TupleSections , ViewPatterns #
module Transformations.Optimising.ConstantPropagation where
import Text.Printf
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Functor.Foldable as Foldable
import Grin.Grin
import Transformations.Util
type Env = Map Val Val
constantPropagation :: Exp -> Exp
constantPropagation e = ana builder (mempty, e) where
builder :: (Env, Exp) -> ExpF (Env, Exp)
builder (env, exp) = case exp of
ECase val alts ->
let constVal = substValsVal env val
known = isKnown constVal || Map.member val env
matchingAlts = [alt | alt@(Alt cpat body) <- alts, match cpat constVal]
defaultAlts = [alt | alt@(Alt DefaultPat body) <- alts]
HINT : use cpat as known value in the alternative ; bind cpat to val
altEnv cpat = env `mappend` unify env (cpatToLPat cpat) val
in case (known, matchingAlts, defaultAlts) of
known scutinee , specific pattern
(True, [Alt cpat body], _) -> (env,) <$> SBlockF (EBind (SReturn constVal) (cpatToLPat cpat) body)
known scutinee , default pattern
(True, _, [Alt DefaultPat body]) -> (env,) <$> SBlockF body
unknown scutinee
_ -> ECaseF val [(altEnv cpat, alt) | alt@(Alt cpat _) <- alts]
EBind (SReturn val) lpat rightExp -> (env `mappend` unify env val lpat,) <$> project exp
_ -> (env,) <$> project exp
unify :: Env -> Val -> LPat -> Env
unify env (substValsVal env -> val) lpat = case (lpat, val) of
(Var{}, ConstTagNode{}) -> Map.singleton lpat val
LPat : unit , lit , tag
isKnown :: Val -> Bool
isKnown = \case
ConstTagNode{} -> True
ValTag{} -> True
_ -> False
match :: CPat -> Val -> Bool
match (NodePat tagA _) (ConstTagNode tagB _) = tagA == tagB
match (TagPat tagA) (ValTag tagB) = tagA == tagB
match _ _ = False
|
0f8a890424fad775fc9e79b83acbefb479270e1780175fd616c7e27d98ed25be | gonzojive/sbcl | test-driver.lisp | 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.
(defpackage :sb-introspect-test
(:use "SB-INTROSPECT" "CL" "SB-RT"))
(in-package :sb-introspect-test)
(deftest function-lambda-list.1
(function-lambda-list 'cl-user::one)
(cl-user::a cl-user::b cl-user::c))
(deftest function-lambda-list.2
(function-lambda-list 'the)
(sb-c::value-type sb-c::form))
(deftest function-lambda-list.3
(function-lambda-list #'(sb-pcl::slow-method cl-user::j (t)))
(sb-pcl::method-args sb-pcl::next-methods))
(deftest definition-source-plist.1
(let* ((source (find-definition-source #'cl-user::one))
(plist (definition-source-plist source)))
(values (= (definition-source-file-write-date source)
(file-write-date "test.lisp"))
(or (equal (getf plist :test-outer)
"OUT")
plist)))
t t)
(deftest definition-source-plist.2
(let ((plist (definition-source-plist
(find-definition-source #'cl-user::four))))
(values (or (equal (getf plist :test-outer) "OUT")
plist)
(or (equal (getf plist :test-inner) "IN")
plist)))
t t)
(defun matchp (object form-number)
(let ((ds (sb-introspect:find-definition-source object)))
(and (pathnamep (sb-introspect:definition-source-pathname ds))
(= form-number
(first (sb-introspect:definition-source-form-path ds))))))
(defun matchp-name (type object form-number)
(let ((ds (car (sb-introspect:find-definition-sources-by-name object type))))
(and (pathnamep (sb-introspect:definition-source-pathname ds))
(= form-number
(first (sb-introspect:definition-source-form-path ds))))))
(defun matchp-length (type object form-numbers)
(let ((ds (sb-introspect:find-definition-sources-by-name object type)))
(= (length ds) form-numbers)))
(deftest find-source-stuff.1
(matchp-name :function 'cl-user::one 2)
t)
(deftest find-source-stuff.2
(matchp #'cl-user::one 2)
t)
(deftest find-source-stuff.3
(matchp-name :generic-function 'cl-user::two 3)
t)
(deftest find-source-stuff.4
(matchp (car (sb-pcl:generic-function-methods #'cl-user::two)) 4)
t)
(deftest find-source-stuff.5
(matchp-name :variable 'cl-user::*a* 8)
t)
(deftest find-source-stuff.6
(matchp-name :variable 'cl-user::*b* 9)
t)
(deftest find-source-stuff.7
(matchp-name :class 'cl-user::a 10)
t)
(deftest find-source-stuff.8
(matchp-name :condition 'cl-user::b 11)
t)
(deftest find-source-stuff.9
(matchp-name :structure 'cl-user::c 12)
t)
(deftest find-source-stuff.10
(matchp-name :function 'cl-user::make-c 12)
t)
(deftest find-source-stuff.11
(matchp-name :function 'cl-user::c-e 12)
t)
(deftest find-source-stuff.12
(matchp-name :structure 'cl-user::d 13)
t)
(deftest find-source-stuff.13
(matchp-name :function 'cl-user::make-d 13)
t)
(deftest find-source-stuff.14
(matchp-name :function 'cl-user::d-e 13)
t)
(deftest find-source-stuff.15
(matchp-name :package 'cl-user::e 14)
t)
(deftest find-source-stuff.16
(matchp-name :symbol-macro 'cl-user::f 15)
t)
(deftest find-source-stuff.17
(matchp-name :type 'cl-user::g 16)
t)
(deftest find-source-stuff.18
(matchp-name :constant 'cl-user::+h+ 17)
t)
(deftest find-source-stuff.19
(matchp-length :method 'cl-user::j 2)
t)
(deftest find-source-stuff.20
(matchp-name :macro 'cl-user::l 20)
t)
(deftest find-source-stuff.21
(matchp-name :compiler-macro 'cl-user::m 21)
t)
(deftest find-source-stuff.22
(matchp-name :setf-expander 'cl-user::n 22)
t)
(deftest find-source-stuff.23
(matchp-name :function '(setf cl-user::o) 23)
t)
(deftest find-source-stuff.24
(matchp-name :method '(setf cl-user::p) 24)
t)
(deftest find-source-stuff.25
(matchp-name :macro 'cl-user::q 25)
t)
(deftest find-source-stuff.26
(matchp-name :method-combination 'cl-user::r 26)
t)
(deftest find-source-stuff.27
(matchp-name :setf-expander 'cl-user::s 27)
t)
(deftest find-source-stuff.28
(let ((fin (make-instance 'sb-mop:funcallable-standard-object)))
(sb-mop:set-funcallable-instance-function fin #'cl-user::one)
(matchp fin 2))
t)
(deftest find-source-stuff.29
(unwind-protect
(progn
(sb-profile:profile cl-user::one)
(matchp-name :function 'cl-user::one 2))
(sb-profile:unprofile cl-user::one))
t)
(deftest find-source-stuff.30
Test finding a type that is n't one
(not (find-definition-sources-by-name 'fboundp :type))
t)
Check wrt . interplay of generic functions and their methods .
(defgeneric xuuq (gf.a gf.b &rest gf.rest &key gf.k-X))
(defmethod xuuq ((m1.a number) m1.b &rest m1.rest &key gf.k-X m1.k-Y m1.k-Z)
(declare (ignore m1.a m1.b m1.rest gf.k-X m1.k-Y m1.k-Z))
'm1)
(defmethod xuuq ((m2.a string) m2.b &rest m2.rest &key gf.k-X m1.k-Y m2.k-Q)
(declare (ignore m2.a m2.b m2.rest gf.k-X m1.k-Y m2.k-Q))
'm2)
;; XUUQ's lambda list should look similiar to
;;
( GF.A GF.B & REST GF.REST & KEY GF.K - X M1.K - Z M1.K - Y M2.K - Q )
;;
(deftest gf-interplay.1
(multiple-value-bind (required optional restp rest keyp keys allowp
auxp aux morep more-context more-count)
(sb-int:parse-lambda-list (function-lambda-list #'xuuq))
(and (equal required '(gf.a gf.b))
(null optional)
(and restp (eql rest 'gf.rest))
(and keyp
(member 'gf.k-X keys)
(member 'm1.k-Y keys)
(member 'm1.k-Z keys)
(member 'm2.k-Q keys))
(not allowp)
(and (not auxp) (null aux))
(and (not morep) (null more-context) (not more-count))))
t)
Check what happens when there 's no explicit .
(defmethod kroolz (r1 r2 &optional opt &aux aux)
(declare (ignore r1 r2 opt aux))
'kroolz)
(deftest gf-interplay.2
(equal (function-lambda-list #'kroolz) '(r1 r2 &optional opt))
t)
Check correctness of DEFTYPE - LAMBDA - LIST .
(deftype foobar-type
(&whole w &environment e r1 r2 &optional o &rest rest &key k1 k2 k3)
(declare (ignore w e r1 r2 o rest k1 k2 k3))
nil)
(deftest deftype-lambda-list.1
(deftype-lambda-list 'foobar-type)
(&whole w &environment e r1 r2 &optional o &rest rest &key k1 k2 k3)
t)
(deftest deftype-lambda-list.2
(deftype-lambda-list (gensym))
nil
nil)
;; ARRAY is a primitive type with associated translator function.
(deftest deftype-lambda-list.3
(deftype-lambda-list 'array)
(&optional (sb-kernel::element-type '*) (sb-kernel::dimensions '*))
t)
VECTOR is a primitive type that is defined by means of DEFTYPE .
(deftest deftype-lambda-list.4
(deftype-lambda-list 'vector)
(&optional sb-kernel::element-type sb-kernel::size)
t)
;;; Test allocation-information
(defun tai (x kind info &key ignore)
(multiple-value-bind (kind2 info2) (sb-introspect:allocation-information x)
(unless (eq kind kind2)
(error "wanted ~S, got ~S" kind kind2))
(when (not (null ignore))
(setf info2 (copy-list info2))
(dolist (key ignore)
(remf info2 key))
(setf info (copy-list info))
(dolist (key ignore)
(remf info key)))
(equal info info2)))
(deftest allocation-infromation.1
(tai nil :heap '(:space :static))
t)
(deftest allocation-information.2
(tai t :heap '(:space :static))
t)
(deftest allocation-information.3
(tai 42 :immediate nil)
t)
;;; Skip the whole damn test on GENCGC PPC -- the combination is just
;;; to flaky for this to make too much sense.
#-(and ppc gencgc)
(deftest allocation-information.4
#+gencgc
(tai #'cons :heap
;; FIXME: This is the canonical GENCGC result. On PPC we sometimes get
;; :LARGE T, which doesn't seem right -- but ignore that for now.
'(:space :dynamic :generation 6 :write-protected t :boxed t :pinned nil :large nil)
:ignore #+ppc '(:large) #-ppc nil)
#-gencgc
(tai :cons :heap
FIXME : Figure out what 's the right - result . SPARC at least
has exhibited both : READ - ONLY and : , which seems wrong .
'()
:ignore '(:space))
t)
#+sb-thread
(deftest allocation-information.thread.1
(let ((x (list 1 2 3)))
(declare (dynamic-extent x))
(tai x :stack sb-thread:*current-thread*))
t)
#+sb-thread
(progn
(defun thread-tai ()
(let ((x (list 1 2 3)))
(declare (dynamic-extent x))
(let ((child (sb-thread:make-thread
(lambda ()
(sb-introspect:allocation-information x)))))
(equal (list :stack sb-thread:*current-thread*)
(multiple-value-list (sb-thread:join-thread child))))))
(deftest allocation-information.thread.2
(thread-tai)
t)
(defun thread-tai2 ()
(let* ((sem (sb-thread:make-semaphore))
(obj nil)
(child (sb-thread:make-thread
(lambda ()
(let ((x (list 1 2 3)))
(declare (dynamic-extent x))
(setf obj x)
(sb-thread:wait-on-semaphore sem)))
:name "child")))
(loop until obj)
(unwind-protect
(equal (list :stack child)
(multiple-value-list
(sb-introspect:allocation-information obj)))
(sb-thread:signal-semaphore sem)
(sb-thread:join-thread child))))
(deftest allocation-information.thread.3
(thread-tai2)
t))
;;;; Test FUNCTION-TYPE
(defun type-equal (typespec1 typespec2)
TYPE= punts on & keywords in FTYPEs .
(sb-kernel:type= (sb-kernel:values-specifier-type typespec1)
(sb-kernel:values-specifier-type typespec2))))
(defmacro interpret (form)
`(let ((sb-ext:*evaluator-mode* :interpret))
(eval ',form)))
;; Functions
(declaim (ftype (function (integer &optional string) string) moon))
(defun moon (int &optional suffix)
(concatenate 'string (princ-to-string int) suffix))
(deftest function-type.1
(values (type-equal (function-type 'moon) (function-type #'moon))
(type-equal (function-type #'moon)
'(function (integer &optional string)
(values string &rest t))))
t t)
(defun sun (x y &key k1)
(declare (fixnum x y))
(declare (boolean k1))
(declare (ignore x y k1))
t)
(deftest function-type.2
(values (type-equal (function-type 'sun) (function-type #'sun))
Does not currently work due to Bug # 384892 . ( 1.0.31.26 )
#+nil
(type-equal (function-type #'sun)
'(function (fixnum fixnum &key (:k1 (member nil t)))
(values (member t) &optional))))
t #+nil t)
;; Local functions
(deftest function-type.5
(flet ((f (s)
(declare (symbol s))
(values (symbol-name s))))
(type-equal (function-type #'f)
'(function (symbol) (values simple-string &optional))))
t)
;; Closures
(deftest function-type.6
(let ((x 10))
(declare (fixnum x))
(flet ((closure (y)
(declare (fixnum y))
(setq x (+ x y))))
(type-equal (function-type #'closure)
'(function (fixnum) (values fixnum &optional)))))
t)
;; Anonymous functions
(deftest function-type.7
(type-equal (function-type #'(lambda (x) (declare (fixnum x)) x))
'(function (fixnum) (values fixnum &optional)))
t)
;; Interpreted functions
#+sb-eval
(deftest function-type.8
(type-equal (function-type (interpret (lambda (x) (declare (fixnum x)) x)))
'(function (&rest t) *))
t)
Generic functions
(defgeneric earth (x y))
(deftest function-type+gfs.1
(values (type-equal (function-type 'earth) (function-type #'earth))
(type-equal (function-type 'earth) '(function (t t) *)))
t t)
;; Implicitly created generic functions.
( FUNCTION - TYPE ' MARS ) = > FUNCTION at the moment . ( 1.0.31.26 )
See LP # 520695 .
(defmethod mars (x y) (+ x y))
#+ nil
(deftest function-type+gfs.2
(values (type-equal (function-type 'mars) (function-type #'mars))
(type-equal (function-type 'mars) '(function (t t) *)))
t t)
DEFSTRUCT created functions
;; These do not yet work because SB-KERNEL:%FUN-NAME does not work on
functions defined by DEFSTRUCT . ( 1.0.35.x )
See LP # 520692 .
#+nil
(progn
(defstruct (struct (:predicate our-struct-p)
(:copier copy-our-struct))
(a 42 :type fixnum))
(deftest function-type+defstruct.1
(values (type-equal (function-type 'struct-a)
(function-type #'struct-a))
(type-equal (function-type 'struct-a)
'(function (struct) (values fixnum &optional))))
t t)
(deftest function-type+defstruct.2
(values (type-equal (function-type 'our-struct-p)
(function-type #'our-struct-p))
(type-equal (function-type 'our-struct-p)
'(function (t) (values (member t nil) &optional))))
t t)
(deftest function-type+defstruct.3
(values (type-equal (function-type 'copy-our-struct)
(function-type #'copy-our-struct))
(type-equal (function-type 'copy-our-struct)
'(function (struct) (values struct &optional))))
t t)
(defstruct (typed-struct :named (:type list)
(:predicate typed-struct-p))
(a 42 :type fixnum))
(deftest function-type+defstruct.4
(values (type-equal (function-type 'typed-struct-a)
(function-type #'typed-struct-a))
(type-equal (function-type 'typed-struct-a)
'(function (list) (values fixnum &optional))))
t t)
(deftest function-type+defstruct.5
(values (type-equal (function-type 'typed-struct-p)
(function-type #'typed-struct-p))
(type-equal (function-type 'typed-struct-p)
'(function (t) (values (member t nil) &optional))))
t t)
# + nil ( progn ...
SETF functions
(defun (setf sun) (value x y &key k1)
(declare (boolean value))
(declare (fixnum x y))
(declare (boolean k1))
(declare (ignore x y k1))
value)
(deftest function-type+setf.1
(values (type-equal (function-type '(setf sun))
(function-type #'(setf sun)))
(type-equal (function-type '(setf sun))
'(function ((member nil t)
fixnum fixnum
&key (:k1 (member nil t)))
*)))
t t)
;; Misc
(deftest function-type+misc.1
(flet ((nullary ()))
(type-equal (function-type #'nullary)
'(function () (values null &optional))))
t)
| null | https://raw.githubusercontent.com/gonzojive/sbcl/3210d8ed721541d5bba85cbf51831238990e33f1/contrib/sb-introspect/test-driver.lisp | lisp | 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.
XUUQ's lambda list should look similiar to
ARRAY is a primitive type with associated translator function.
Test allocation-information
Skip the whole damn test on GENCGC PPC -- the combination is just
to flaky for this to make too much sense.
FIXME: This is the canonical GENCGC result. On PPC we sometimes get
:LARGE T, which doesn't seem right -- but ignore that for now.
Test FUNCTION-TYPE
Functions
Local functions
Closures
Anonymous functions
Interpreted functions
Implicitly created generic functions.
These do not yet work because SB-KERNEL:%FUN-NAME does not work on
Misc | 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
(defpackage :sb-introspect-test
(:use "SB-INTROSPECT" "CL" "SB-RT"))
(in-package :sb-introspect-test)
(deftest function-lambda-list.1
(function-lambda-list 'cl-user::one)
(cl-user::a cl-user::b cl-user::c))
(deftest function-lambda-list.2
(function-lambda-list 'the)
(sb-c::value-type sb-c::form))
(deftest function-lambda-list.3
(function-lambda-list #'(sb-pcl::slow-method cl-user::j (t)))
(sb-pcl::method-args sb-pcl::next-methods))
(deftest definition-source-plist.1
(let* ((source (find-definition-source #'cl-user::one))
(plist (definition-source-plist source)))
(values (= (definition-source-file-write-date source)
(file-write-date "test.lisp"))
(or (equal (getf plist :test-outer)
"OUT")
plist)))
t t)
(deftest definition-source-plist.2
(let ((plist (definition-source-plist
(find-definition-source #'cl-user::four))))
(values (or (equal (getf plist :test-outer) "OUT")
plist)
(or (equal (getf plist :test-inner) "IN")
plist)))
t t)
(defun matchp (object form-number)
(let ((ds (sb-introspect:find-definition-source object)))
(and (pathnamep (sb-introspect:definition-source-pathname ds))
(= form-number
(first (sb-introspect:definition-source-form-path ds))))))
(defun matchp-name (type object form-number)
(let ((ds (car (sb-introspect:find-definition-sources-by-name object type))))
(and (pathnamep (sb-introspect:definition-source-pathname ds))
(= form-number
(first (sb-introspect:definition-source-form-path ds))))))
(defun matchp-length (type object form-numbers)
(let ((ds (sb-introspect:find-definition-sources-by-name object type)))
(= (length ds) form-numbers)))
(deftest find-source-stuff.1
(matchp-name :function 'cl-user::one 2)
t)
(deftest find-source-stuff.2
(matchp #'cl-user::one 2)
t)
(deftest find-source-stuff.3
(matchp-name :generic-function 'cl-user::two 3)
t)
(deftest find-source-stuff.4
(matchp (car (sb-pcl:generic-function-methods #'cl-user::two)) 4)
t)
(deftest find-source-stuff.5
(matchp-name :variable 'cl-user::*a* 8)
t)
(deftest find-source-stuff.6
(matchp-name :variable 'cl-user::*b* 9)
t)
(deftest find-source-stuff.7
(matchp-name :class 'cl-user::a 10)
t)
(deftest find-source-stuff.8
(matchp-name :condition 'cl-user::b 11)
t)
(deftest find-source-stuff.9
(matchp-name :structure 'cl-user::c 12)
t)
(deftest find-source-stuff.10
(matchp-name :function 'cl-user::make-c 12)
t)
(deftest find-source-stuff.11
(matchp-name :function 'cl-user::c-e 12)
t)
(deftest find-source-stuff.12
(matchp-name :structure 'cl-user::d 13)
t)
(deftest find-source-stuff.13
(matchp-name :function 'cl-user::make-d 13)
t)
(deftest find-source-stuff.14
(matchp-name :function 'cl-user::d-e 13)
t)
(deftest find-source-stuff.15
(matchp-name :package 'cl-user::e 14)
t)
(deftest find-source-stuff.16
(matchp-name :symbol-macro 'cl-user::f 15)
t)
(deftest find-source-stuff.17
(matchp-name :type 'cl-user::g 16)
t)
(deftest find-source-stuff.18
(matchp-name :constant 'cl-user::+h+ 17)
t)
(deftest find-source-stuff.19
(matchp-length :method 'cl-user::j 2)
t)
(deftest find-source-stuff.20
(matchp-name :macro 'cl-user::l 20)
t)
(deftest find-source-stuff.21
(matchp-name :compiler-macro 'cl-user::m 21)
t)
(deftest find-source-stuff.22
(matchp-name :setf-expander 'cl-user::n 22)
t)
(deftest find-source-stuff.23
(matchp-name :function '(setf cl-user::o) 23)
t)
(deftest find-source-stuff.24
(matchp-name :method '(setf cl-user::p) 24)
t)
(deftest find-source-stuff.25
(matchp-name :macro 'cl-user::q 25)
t)
(deftest find-source-stuff.26
(matchp-name :method-combination 'cl-user::r 26)
t)
(deftest find-source-stuff.27
(matchp-name :setf-expander 'cl-user::s 27)
t)
(deftest find-source-stuff.28
(let ((fin (make-instance 'sb-mop:funcallable-standard-object)))
(sb-mop:set-funcallable-instance-function fin #'cl-user::one)
(matchp fin 2))
t)
(deftest find-source-stuff.29
(unwind-protect
(progn
(sb-profile:profile cl-user::one)
(matchp-name :function 'cl-user::one 2))
(sb-profile:unprofile cl-user::one))
t)
(deftest find-source-stuff.30
Test finding a type that is n't one
(not (find-definition-sources-by-name 'fboundp :type))
t)
Check wrt . interplay of generic functions and their methods .
(defgeneric xuuq (gf.a gf.b &rest gf.rest &key gf.k-X))
(defmethod xuuq ((m1.a number) m1.b &rest m1.rest &key gf.k-X m1.k-Y m1.k-Z)
(declare (ignore m1.a m1.b m1.rest gf.k-X m1.k-Y m1.k-Z))
'm1)
(defmethod xuuq ((m2.a string) m2.b &rest m2.rest &key gf.k-X m1.k-Y m2.k-Q)
(declare (ignore m2.a m2.b m2.rest gf.k-X m1.k-Y m2.k-Q))
'm2)
( GF.A GF.B & REST GF.REST & KEY GF.K - X M1.K - Z M1.K - Y M2.K - Q )
(deftest gf-interplay.1
(multiple-value-bind (required optional restp rest keyp keys allowp
auxp aux morep more-context more-count)
(sb-int:parse-lambda-list (function-lambda-list #'xuuq))
(and (equal required '(gf.a gf.b))
(null optional)
(and restp (eql rest 'gf.rest))
(and keyp
(member 'gf.k-X keys)
(member 'm1.k-Y keys)
(member 'm1.k-Z keys)
(member 'm2.k-Q keys))
(not allowp)
(and (not auxp) (null aux))
(and (not morep) (null more-context) (not more-count))))
t)
Check what happens when there 's no explicit .
(defmethod kroolz (r1 r2 &optional opt &aux aux)
(declare (ignore r1 r2 opt aux))
'kroolz)
(deftest gf-interplay.2
(equal (function-lambda-list #'kroolz) '(r1 r2 &optional opt))
t)
Check correctness of DEFTYPE - LAMBDA - LIST .
(deftype foobar-type
(&whole w &environment e r1 r2 &optional o &rest rest &key k1 k2 k3)
(declare (ignore w e r1 r2 o rest k1 k2 k3))
nil)
(deftest deftype-lambda-list.1
(deftype-lambda-list 'foobar-type)
(&whole w &environment e r1 r2 &optional o &rest rest &key k1 k2 k3)
t)
(deftest deftype-lambda-list.2
(deftype-lambda-list (gensym))
nil
nil)
(deftest deftype-lambda-list.3
(deftype-lambda-list 'array)
(&optional (sb-kernel::element-type '*) (sb-kernel::dimensions '*))
t)
VECTOR is a primitive type that is defined by means of DEFTYPE .
(deftest deftype-lambda-list.4
(deftype-lambda-list 'vector)
(&optional sb-kernel::element-type sb-kernel::size)
t)
(defun tai (x kind info &key ignore)
(multiple-value-bind (kind2 info2) (sb-introspect:allocation-information x)
(unless (eq kind kind2)
(error "wanted ~S, got ~S" kind kind2))
(when (not (null ignore))
(setf info2 (copy-list info2))
(dolist (key ignore)
(remf info2 key))
(setf info (copy-list info))
(dolist (key ignore)
(remf info key)))
(equal info info2)))
(deftest allocation-infromation.1
(tai nil :heap '(:space :static))
t)
(deftest allocation-information.2
(tai t :heap '(:space :static))
t)
(deftest allocation-information.3
(tai 42 :immediate nil)
t)
#-(and ppc gencgc)
(deftest allocation-information.4
#+gencgc
(tai #'cons :heap
'(:space :dynamic :generation 6 :write-protected t :boxed t :pinned nil :large nil)
:ignore #+ppc '(:large) #-ppc nil)
#-gencgc
(tai :cons :heap
FIXME : Figure out what 's the right - result . SPARC at least
has exhibited both : READ - ONLY and : , which seems wrong .
'()
:ignore '(:space))
t)
#+sb-thread
(deftest allocation-information.thread.1
(let ((x (list 1 2 3)))
(declare (dynamic-extent x))
(tai x :stack sb-thread:*current-thread*))
t)
#+sb-thread
(progn
(defun thread-tai ()
(let ((x (list 1 2 3)))
(declare (dynamic-extent x))
(let ((child (sb-thread:make-thread
(lambda ()
(sb-introspect:allocation-information x)))))
(equal (list :stack sb-thread:*current-thread*)
(multiple-value-list (sb-thread:join-thread child))))))
(deftest allocation-information.thread.2
(thread-tai)
t)
(defun thread-tai2 ()
(let* ((sem (sb-thread:make-semaphore))
(obj nil)
(child (sb-thread:make-thread
(lambda ()
(let ((x (list 1 2 3)))
(declare (dynamic-extent x))
(setf obj x)
(sb-thread:wait-on-semaphore sem)))
:name "child")))
(loop until obj)
(unwind-protect
(equal (list :stack child)
(multiple-value-list
(sb-introspect:allocation-information obj)))
(sb-thread:signal-semaphore sem)
(sb-thread:join-thread child))))
(deftest allocation-information.thread.3
(thread-tai2)
t))
(defun type-equal (typespec1 typespec2)
TYPE= punts on & keywords in FTYPEs .
(sb-kernel:type= (sb-kernel:values-specifier-type typespec1)
(sb-kernel:values-specifier-type typespec2))))
(defmacro interpret (form)
`(let ((sb-ext:*evaluator-mode* :interpret))
(eval ',form)))
(declaim (ftype (function (integer &optional string) string) moon))
(defun moon (int &optional suffix)
(concatenate 'string (princ-to-string int) suffix))
(deftest function-type.1
(values (type-equal (function-type 'moon) (function-type #'moon))
(type-equal (function-type #'moon)
'(function (integer &optional string)
(values string &rest t))))
t t)
(defun sun (x y &key k1)
(declare (fixnum x y))
(declare (boolean k1))
(declare (ignore x y k1))
t)
(deftest function-type.2
(values (type-equal (function-type 'sun) (function-type #'sun))
Does not currently work due to Bug # 384892 . ( 1.0.31.26 )
#+nil
(type-equal (function-type #'sun)
'(function (fixnum fixnum &key (:k1 (member nil t)))
(values (member t) &optional))))
t #+nil t)
(deftest function-type.5
(flet ((f (s)
(declare (symbol s))
(values (symbol-name s))))
(type-equal (function-type #'f)
'(function (symbol) (values simple-string &optional))))
t)
(deftest function-type.6
(let ((x 10))
(declare (fixnum x))
(flet ((closure (y)
(declare (fixnum y))
(setq x (+ x y))))
(type-equal (function-type #'closure)
'(function (fixnum) (values fixnum &optional)))))
t)
(deftest function-type.7
(type-equal (function-type #'(lambda (x) (declare (fixnum x)) x))
'(function (fixnum) (values fixnum &optional)))
t)
#+sb-eval
(deftest function-type.8
(type-equal (function-type (interpret (lambda (x) (declare (fixnum x)) x)))
'(function (&rest t) *))
t)
Generic functions
(defgeneric earth (x y))
(deftest function-type+gfs.1
(values (type-equal (function-type 'earth) (function-type #'earth))
(type-equal (function-type 'earth) '(function (t t) *)))
t t)
( FUNCTION - TYPE ' MARS ) = > FUNCTION at the moment . ( 1.0.31.26 )
See LP # 520695 .
(defmethod mars (x y) (+ x y))
#+ nil
(deftest function-type+gfs.2
(values (type-equal (function-type 'mars) (function-type #'mars))
(type-equal (function-type 'mars) '(function (t t) *)))
t t)
DEFSTRUCT created functions
functions defined by DEFSTRUCT . ( 1.0.35.x )
See LP # 520692 .
#+nil
(progn
(defstruct (struct (:predicate our-struct-p)
(:copier copy-our-struct))
(a 42 :type fixnum))
(deftest function-type+defstruct.1
(values (type-equal (function-type 'struct-a)
(function-type #'struct-a))
(type-equal (function-type 'struct-a)
'(function (struct) (values fixnum &optional))))
t t)
(deftest function-type+defstruct.2
(values (type-equal (function-type 'our-struct-p)
(function-type #'our-struct-p))
(type-equal (function-type 'our-struct-p)
'(function (t) (values (member t nil) &optional))))
t t)
(deftest function-type+defstruct.3
(values (type-equal (function-type 'copy-our-struct)
(function-type #'copy-our-struct))
(type-equal (function-type 'copy-our-struct)
'(function (struct) (values struct &optional))))
t t)
(defstruct (typed-struct :named (:type list)
(:predicate typed-struct-p))
(a 42 :type fixnum))
(deftest function-type+defstruct.4
(values (type-equal (function-type 'typed-struct-a)
(function-type #'typed-struct-a))
(type-equal (function-type 'typed-struct-a)
'(function (list) (values fixnum &optional))))
t t)
(deftest function-type+defstruct.5
(values (type-equal (function-type 'typed-struct-p)
(function-type #'typed-struct-p))
(type-equal (function-type 'typed-struct-p)
'(function (t) (values (member t nil) &optional))))
t t)
# + nil ( progn ...
SETF functions
(defun (setf sun) (value x y &key k1)
(declare (boolean value))
(declare (fixnum x y))
(declare (boolean k1))
(declare (ignore x y k1))
value)
(deftest function-type+setf.1
(values (type-equal (function-type '(setf sun))
(function-type #'(setf sun)))
(type-equal (function-type '(setf sun))
'(function ((member nil t)
fixnum fixnum
&key (:k1 (member nil t)))
*)))
t t)
(deftest function-type+misc.1
(flet ((nullary ()))
(type-equal (function-type #'nullary)
'(function () (values null &optional))))
t)
|
40c6d76c4da97f50a51321f45523b93e037bdfa31b4d128292cebd42e1e7026b | D00mch/PWA-clojure | middleware.clj | (ns pwa.middleware
(:require
[pwa.env :refer [defaults]]
[cheshire.generate :as cheshire]
[cognitect.transit :as transit]
[clojure.tools.logging :as log]
[pwa.layout :refer [error-page]]
[ring.middleware.anti-forgery :refer [wrap-anti-forgery]]
[pwa.middleware.formats :as formats]
[muuntaja.middleware :refer [wrap-format wrap-params]]
[pwa.config :refer [env]]
[ring-ttl-session.core :refer [ttl-memory-store]]
[ring.middleware.defaults :refer [site-defaults wrap-defaults]])
)
(defn wrap-internal-error [handler]
(fn [req]
(try
(handler req)
(catch Throwable t
(log/error t (.getMessage t))
(error-page {:status 500
:title "Something very bad has happened!"
:message "We've dispatched a team of highly trained gnomes to take care of the problem."})))))
(defn wrap-csrf [handler]
(wrap-anti-forgery
handler
{:error-response
(error-page
{:status 403
:title "Invalid anti-forgery token"})}))
(defn wrap-formats [handler]
(let [wrapped (-> handler wrap-params (wrap-format formats/instance))]
(fn [request]
disable wrap - formats for websockets
;; since they're not compatible with this middleware
((if (:websocket? request) handler wrapped) request))))
(defn wrap-base [handler]
(-> ((:middleware defaults) handler)
(wrap-defaults
(-> site-defaults
(assoc-in [:security :anti-forgery] false)
(assoc-in [:session :store] (ttl-memory-store (* 60 30)))))
wrap-internal-error))
| null | https://raw.githubusercontent.com/D00mch/PWA-clojure/39ab4d3690c7a8ddbdd8095d65a782961f92c183/src/clj/pwa/middleware.clj | clojure | since they're not compatible with this middleware | (ns pwa.middleware
(:require
[pwa.env :refer [defaults]]
[cheshire.generate :as cheshire]
[cognitect.transit :as transit]
[clojure.tools.logging :as log]
[pwa.layout :refer [error-page]]
[ring.middleware.anti-forgery :refer [wrap-anti-forgery]]
[pwa.middleware.formats :as formats]
[muuntaja.middleware :refer [wrap-format wrap-params]]
[pwa.config :refer [env]]
[ring-ttl-session.core :refer [ttl-memory-store]]
[ring.middleware.defaults :refer [site-defaults wrap-defaults]])
)
(defn wrap-internal-error [handler]
(fn [req]
(try
(handler req)
(catch Throwable t
(log/error t (.getMessage t))
(error-page {:status 500
:title "Something very bad has happened!"
:message "We've dispatched a team of highly trained gnomes to take care of the problem."})))))
(defn wrap-csrf [handler]
(wrap-anti-forgery
handler
{:error-response
(error-page
{:status 403
:title "Invalid anti-forgery token"})}))
(defn wrap-formats [handler]
(let [wrapped (-> handler wrap-params (wrap-format formats/instance))]
(fn [request]
disable wrap - formats for websockets
((if (:websocket? request) handler wrapped) request))))
(defn wrap-base [handler]
(-> ((:middleware defaults) handler)
(wrap-defaults
(-> site-defaults
(assoc-in [:security :anti-forgery] false)
(assoc-in [:session :store] (ttl-memory-store (* 60 30)))))
wrap-internal-error))
|
2811e7e718d98844dc22a1498fd85a689543c14c5a29cb37bc345e3a5e92e652 | CSCfi/rems | resource.cljs | (ns rems.administration.resource
(:require [re-frame.core :as rf]
[rems.administration.administration :as administration]
[rems.administration.blacklist :as blacklist]
[rems.administration.components :refer [inline-info-field]]
[rems.administration.license :refer [licenses-view]]
[rems.administration.duo :refer [duo-info-field]]
[rems.administration.status-flags :as status-flags]
[rems.atoms :as atoms :refer [readonly-checkbox document-title]]
[rems.collapsible :as collapsible]
[rems.common.util :refer [andstr]]
[rems.flash-message :as flash-message]
[rems.common.roles :as roles]
[rems.spinner :as spinner]
[rems.text :refer [text]]
[rems.util :refer [fetch]]))
(rf/reg-event-fx
::enter-page
(fn [{:keys [db]} [_ resource-id]]
{:dispatch [::fetch-resource resource-id]}))
(rf/reg-event-fx
::fetch-resource
(fn [{:keys [db]} [_ resource-id]]
(fetch (str "/api/resources/" resource-id)
{:handler #(rf/dispatch [::fetch-resource-result %])
:error-handler (flash-message/default-error-handler :top "Fetch resource")})
{:db (assoc db ::loading? true)}))
(rf/reg-event-fx
::fetch-resource-result
(fn [{:keys [db]} [_ resource]]
{:db (-> db
(assoc ::resource resource)
(dissoc ::loading?))
:dispatch-n [[::blacklist/fetch-blacklist {:resource (:resid resource)}]
[::blacklist/fetch-users]]}))
(rf/reg-sub ::resource (fn [db _] (::resource db)))
(rf/reg-sub ::loading? (fn [db _] (::loading? db)))
(defn resource-blacklist []
[collapsible/component
{:id "blacklist"
:title (text :t.administration/blacklist)
:always [:div
[blacklist/blacklist]
[blacklist/add-user-form {:resource/ext-id (:resid @(rf/subscribe [::resource]))}]]}])
(defn resource-duos [resource]
[collapsible/component
{:id "duos"
:title (text :t.duo/title)
:always (if-let [duos (seq (-> resource :resource/duo :duo/codes))]
(for [duo duos]
^{:key (:id duo)}
[duo-info-field {:id (str "resource-duo-" (:id duo))
:duo duo
:duo/more-infos (when (:more-info duo)
(list (merge (select-keys duo [:more-info])
{:resource/id (:id resource)})))}])
[:p (text :t.duo/no-duo-codes)])}])
(defn resource-view [resource language]
(let [config @(rf/subscribe [:rems.config/config])]
[:div.spaced-vertically-3
[collapsible/component
{:id "resource"
:title [:span (andstr (get-in resource [:organization :organization/short-name language]) "/") (:resid resource)]
:always [:div
[inline-info-field (text :t.administration/organization) (get-in resource [:organization :organization/name language])]
[inline-info-field (text :t.administration/resource) (:resid resource)]
[inline-info-field (text :t.administration/active) [readonly-checkbox {:value (status-flags/active? resource)}]]]}]
[licenses-view (:licenses resource) language]
(when (:enable-duo config)
[resource-duos resource])
[resource-blacklist]
(let [id (:id resource)]
[:div.col.commands
[administration/back-button "/administration/resources"]
[roles/show-when roles/+admin-write-roles+
[status-flags/enabled-toggle resource #(rf/dispatch [:rems.administration.resources/set-resource-enabled %1 %2 [::enter-page id]])]
[status-flags/archived-toggle resource #(rf/dispatch [:rems.administration.resources/set-resource-archived %1 %2 [::enter-page id]])]]])]))
(defn resource-page []
(let [resource (rf/subscribe [::resource])
language (rf/subscribe [:language])
loading? (rf/subscribe [::loading?])]
[:div
[administration/navigator]
[document-title (text :t.administration/resource)]
[flash-message/component :top]
(if @loading?
[spinner/big]
[resource-view @resource @language])]))
| null | https://raw.githubusercontent.com/CSCfi/rems/6c34d51199289c395b0cd0b9a3176bc5f0e83758/src/cljs/rems/administration/resource.cljs | clojure | (ns rems.administration.resource
(:require [re-frame.core :as rf]
[rems.administration.administration :as administration]
[rems.administration.blacklist :as blacklist]
[rems.administration.components :refer [inline-info-field]]
[rems.administration.license :refer [licenses-view]]
[rems.administration.duo :refer [duo-info-field]]
[rems.administration.status-flags :as status-flags]
[rems.atoms :as atoms :refer [readonly-checkbox document-title]]
[rems.collapsible :as collapsible]
[rems.common.util :refer [andstr]]
[rems.flash-message :as flash-message]
[rems.common.roles :as roles]
[rems.spinner :as spinner]
[rems.text :refer [text]]
[rems.util :refer [fetch]]))
(rf/reg-event-fx
::enter-page
(fn [{:keys [db]} [_ resource-id]]
{:dispatch [::fetch-resource resource-id]}))
(rf/reg-event-fx
::fetch-resource
(fn [{:keys [db]} [_ resource-id]]
(fetch (str "/api/resources/" resource-id)
{:handler #(rf/dispatch [::fetch-resource-result %])
:error-handler (flash-message/default-error-handler :top "Fetch resource")})
{:db (assoc db ::loading? true)}))
(rf/reg-event-fx
::fetch-resource-result
(fn [{:keys [db]} [_ resource]]
{:db (-> db
(assoc ::resource resource)
(dissoc ::loading?))
:dispatch-n [[::blacklist/fetch-blacklist {:resource (:resid resource)}]
[::blacklist/fetch-users]]}))
(rf/reg-sub ::resource (fn [db _] (::resource db)))
(rf/reg-sub ::loading? (fn [db _] (::loading? db)))
(defn resource-blacklist []
[collapsible/component
{:id "blacklist"
:title (text :t.administration/blacklist)
:always [:div
[blacklist/blacklist]
[blacklist/add-user-form {:resource/ext-id (:resid @(rf/subscribe [::resource]))}]]}])
(defn resource-duos [resource]
[collapsible/component
{:id "duos"
:title (text :t.duo/title)
:always (if-let [duos (seq (-> resource :resource/duo :duo/codes))]
(for [duo duos]
^{:key (:id duo)}
[duo-info-field {:id (str "resource-duo-" (:id duo))
:duo duo
:duo/more-infos (when (:more-info duo)
(list (merge (select-keys duo [:more-info])
{:resource/id (:id resource)})))}])
[:p (text :t.duo/no-duo-codes)])}])
(defn resource-view [resource language]
(let [config @(rf/subscribe [:rems.config/config])]
[:div.spaced-vertically-3
[collapsible/component
{:id "resource"
:title [:span (andstr (get-in resource [:organization :organization/short-name language]) "/") (:resid resource)]
:always [:div
[inline-info-field (text :t.administration/organization) (get-in resource [:organization :organization/name language])]
[inline-info-field (text :t.administration/resource) (:resid resource)]
[inline-info-field (text :t.administration/active) [readonly-checkbox {:value (status-flags/active? resource)}]]]}]
[licenses-view (:licenses resource) language]
(when (:enable-duo config)
[resource-duos resource])
[resource-blacklist]
(let [id (:id resource)]
[:div.col.commands
[administration/back-button "/administration/resources"]
[roles/show-when roles/+admin-write-roles+
[status-flags/enabled-toggle resource #(rf/dispatch [:rems.administration.resources/set-resource-enabled %1 %2 [::enter-page id]])]
[status-flags/archived-toggle resource #(rf/dispatch [:rems.administration.resources/set-resource-archived %1 %2 [::enter-page id]])]]])]))
(defn resource-page []
(let [resource (rf/subscribe [::resource])
language (rf/subscribe [:language])
loading? (rf/subscribe [::loading?])]
[:div
[administration/navigator]
[document-title (text :t.administration/resource)]
[flash-message/component :top]
(if @loading?
[spinner/big]
[resource-view @resource @language])]))
|
|
a36594a39e086d007361f45b740a767f0c5f92983f24b40ad48b423eaf922861 | ralsei/graphite | titles.rkt | #lang racket/base
(require pict
plot/no-gui
racket/format
racket/match
racket/math
"util.rkt"
"with-area.rkt")
(provide px->pt pt->px title add-title add-all-titles add-facet-label)
(define (px->pt px) (* px 3/4))
(define (pt->px pt) (* pt 4/3))
(define (->pict-font-style)
(or (plot-font-face) (plot-font-family) null))
(define (title content
#:style [style #f]
#:size [size (round (pt->px (plot-font-size)))]
#:angle [angle 0])
(cond [content
(define initial-title
(text (~a content)
(if style
(cons style (->pict-font-style))
(->pict-font-style))
size))
(define w (pict-height initial-title))
(rotate (inset initial-title 0 (/ (- (ceiling w) w) 2)) angle)]
[else (blank)]))
(define (add-title title-text side position pct #:v-offset [v-offset 0] #:h-offset [h-offset 0])
(define angle
(match side
['left (/ pi 2)]
['right (/ (* 3 pi) 2)]
[_ 0]))
(define ((flip fn) a b)
(fn b a))
(define combiner
(match* (side position)
[('top 'left) vl-append]
[('top 'center) vc-append]
[('top 'right) vr-append]
[('left 'top) ht-append]
[('left 'center) hc-append]
[('left 'bottom) hb-append]
[('right 'top) (flip ht-append)]
[('right 'center) (flip hc-append)]
[('right 'bottom) (flip hb-append)]
[('bottom 'left) (flip vl-append)]
[('bottom 'center) (flip vc-append)]
[('bottom 'right) (flip vr-append)]))
(combiner (inset (title title-text #:angle angle)
(if (negative? h-offset) (- h-offset) 0)
(if (not (negative? v-offset)) v-offset 0)
(if (not (negative? h-offset)) h-offset 0)
(if (negative? v-offset) (- v-offset) 0))
pct))
; NOTE on facet labels:
; when faceting, we want a common baseline to work on.
; the way facet labels are added, we account for the top-extras in order to _induce_ that baseline.
; this way we have something common to align on and can use lt-superimpose
;
; we also do not add a background because we want transparency for when bottom extras overlap with the
; facet title. the background gets added at the end of main/facet-plot
;
; we ALSO normalize the left and right extras, so we get a common baseline to work with for
; cc-superimpose.
(define (add-facet-label group plot-pict)
(match-define-values ((app inexact->exact left-extras)
(app inexact->exact right-extras)
_
(app inexact->exact top-extras))
(plot-extras-size plot-pict))
(define add-left-extras
(if (< left-extras right-extras)
(- right-extras left-extras)
0))
(define add-right-extras
(if (< right-extras left-extras)
(- left-extras right-extras)
0))
(define t (title group))
(cb-superimpose (inset plot-pict add-left-extras 0 add-right-extras 0)
(inset t 0 #;add-left-extras 0 0 #; add-right-extras
(- (pict-height plot-pict) top-extras))))
(define (add-all-titles regular-pict #:x-offset [x-offset 0] #:y-offset [y-offset 0])
; XXX: center x/y labels -- this requires metrics info which gets lost!!
(define titled
(add-title
(gr-title) 'top 'center
(add-title
(gr-x-label) 'bottom 'center #:h-offset x-offset
(add-title
(gr-y-label) 'left 'center #:v-offset y-offset
regular-pict))))
(define bg (background-rectangle (pict-width titled) (pict-height titled)))
(cc-superimpose bg titled))
| null | https://raw.githubusercontent.com/ralsei/graphite/06aca4a3f630ea589c2618eaa322243d2ea8315e/graphite-lib/titles.rkt | racket | NOTE on facet labels:
when faceting, we want a common baseline to work on.
the way facet labels are added, we account for the top-extras in order to _induce_ that baseline.
this way we have something common to align on and can use lt-superimpose
we also do not add a background because we want transparency for when bottom extras overlap with the
facet title. the background gets added at the end of main/facet-plot
we ALSO normalize the left and right extras, so we get a common baseline to work with for
cc-superimpose.
add-left-extras 0 0 #; add-right-extras
XXX: center x/y labels -- this requires metrics info which gets lost!! | #lang racket/base
(require pict
plot/no-gui
racket/format
racket/match
racket/math
"util.rkt"
"with-area.rkt")
(provide px->pt pt->px title add-title add-all-titles add-facet-label)
(define (px->pt px) (* px 3/4))
(define (pt->px pt) (* pt 4/3))
(define (->pict-font-style)
(or (plot-font-face) (plot-font-family) null))
(define (title content
#:style [style #f]
#:size [size (round (pt->px (plot-font-size)))]
#:angle [angle 0])
(cond [content
(define initial-title
(text (~a content)
(if style
(cons style (->pict-font-style))
(->pict-font-style))
size))
(define w (pict-height initial-title))
(rotate (inset initial-title 0 (/ (- (ceiling w) w) 2)) angle)]
[else (blank)]))
(define (add-title title-text side position pct #:v-offset [v-offset 0] #:h-offset [h-offset 0])
(define angle
(match side
['left (/ pi 2)]
['right (/ (* 3 pi) 2)]
[_ 0]))
(define ((flip fn) a b)
(fn b a))
(define combiner
(match* (side position)
[('top 'left) vl-append]
[('top 'center) vc-append]
[('top 'right) vr-append]
[('left 'top) ht-append]
[('left 'center) hc-append]
[('left 'bottom) hb-append]
[('right 'top) (flip ht-append)]
[('right 'center) (flip hc-append)]
[('right 'bottom) (flip hb-append)]
[('bottom 'left) (flip vl-append)]
[('bottom 'center) (flip vc-append)]
[('bottom 'right) (flip vr-append)]))
(combiner (inset (title title-text #:angle angle)
(if (negative? h-offset) (- h-offset) 0)
(if (not (negative? v-offset)) v-offset 0)
(if (not (negative? h-offset)) h-offset 0)
(if (negative? v-offset) (- v-offset) 0))
pct))
(define (add-facet-label group plot-pict)
(match-define-values ((app inexact->exact left-extras)
(app inexact->exact right-extras)
_
(app inexact->exact top-extras))
(plot-extras-size plot-pict))
(define add-left-extras
(if (< left-extras right-extras)
(- right-extras left-extras)
0))
(define add-right-extras
(if (< right-extras left-extras)
(- left-extras right-extras)
0))
(define t (title group))
(cb-superimpose (inset plot-pict add-left-extras 0 add-right-extras 0)
(- (pict-height plot-pict) top-extras))))
(define (add-all-titles regular-pict #:x-offset [x-offset 0] #:y-offset [y-offset 0])
(define titled
(add-title
(gr-title) 'top 'center
(add-title
(gr-x-label) 'bottom 'center #:h-offset x-offset
(add-title
(gr-y-label) 'left 'center #:v-offset y-offset
regular-pict))))
(define bg (background-rectangle (pict-width titled) (pict-height titled)))
(cc-superimpose bg titled))
|
111d8a4f3f21d439cde2ae8516e74c0f5cb3c24524131981cb078c6355b32a29 | GillianPlatform/Gillian | debugger_intf.ml | module type S = sig
type tl_ast
type debug_state
module Inspect : sig
type debug_state_view [@@deriving yojson]
val get_debug_state : debug_state -> debug_state_view
val get_unification :
Logging.Report_id.t -> debug_state -> Logging.Report_id.t * Unify_map.t
end
val launch : string -> string option -> (debug_state, string) result
val jump_to_id :
string -> Logging.Report_id.t -> debug_state -> (unit, string) result
val jump_to_start : debug_state -> unit
val step_in : ?reverse:bool -> debug_state -> stop_reason
val step : ?reverse:bool -> debug_state -> stop_reason
val step_specific :
string ->
Exec_map.Packaged.branch_case option ->
Logging.Report_id.t ->
debug_state ->
(stop_reason, string) result
val step_out : debug_state -> stop_reason
val run : ?reverse:bool -> ?launch:bool -> debug_state -> stop_reason
val start_proc : string -> debug_state -> (stop_reason, string) result
val terminate : debug_state -> unit
val get_frames : debug_state -> frame list
val get_scopes : debug_state -> Variable.scope list
val get_variables : int -> debug_state -> Variable.t list
val get_exception_info : debug_state -> exception_info
val set_breakpoints : string option -> int list -> debug_state -> unit
end
module type Make = functor
(ID : Init_data.S)
(PC : ParserAndCompiler.S with type init_data = ID.t)
(V : Verifier.S with type SPState.init_data = ID.t and type annot = PC.Annot.t)
(Lifter : Debugger_lifter.S
with type memory = V.SAInterpreter.heap_t
and type memory_error = V.SPState.m_err_t
and type tl_ast = PC.tl_ast
and type cmd_report = V.SAInterpreter.Logging.ConfigReport.t
and type annot = PC.Annot.t)
-> S
module type Intf = sig
* @canonical . Debugger . S
module type S = S
(**/**)
module type Make = Make
(**/**)
* @canonical . Debugger . Make
module Make : Make
end
| null | https://raw.githubusercontent.com/GillianPlatform/Gillian/c794de7417f29e3c23146f9958ead7e4ad0216ce/GillianCore/debugging/debugger/debugger_intf.ml | ocaml | */*
*/* | module type S = sig
type tl_ast
type debug_state
module Inspect : sig
type debug_state_view [@@deriving yojson]
val get_debug_state : debug_state -> debug_state_view
val get_unification :
Logging.Report_id.t -> debug_state -> Logging.Report_id.t * Unify_map.t
end
val launch : string -> string option -> (debug_state, string) result
val jump_to_id :
string -> Logging.Report_id.t -> debug_state -> (unit, string) result
val jump_to_start : debug_state -> unit
val step_in : ?reverse:bool -> debug_state -> stop_reason
val step : ?reverse:bool -> debug_state -> stop_reason
val step_specific :
string ->
Exec_map.Packaged.branch_case option ->
Logging.Report_id.t ->
debug_state ->
(stop_reason, string) result
val step_out : debug_state -> stop_reason
val run : ?reverse:bool -> ?launch:bool -> debug_state -> stop_reason
val start_proc : string -> debug_state -> (stop_reason, string) result
val terminate : debug_state -> unit
val get_frames : debug_state -> frame list
val get_scopes : debug_state -> Variable.scope list
val get_variables : int -> debug_state -> Variable.t list
val get_exception_info : debug_state -> exception_info
val set_breakpoints : string option -> int list -> debug_state -> unit
end
module type Make = functor
(ID : Init_data.S)
(PC : ParserAndCompiler.S with type init_data = ID.t)
(V : Verifier.S with type SPState.init_data = ID.t and type annot = PC.Annot.t)
(Lifter : Debugger_lifter.S
with type memory = V.SAInterpreter.heap_t
and type memory_error = V.SPState.m_err_t
and type tl_ast = PC.tl_ast
and type cmd_report = V.SAInterpreter.Logging.ConfigReport.t
and type annot = PC.Annot.t)
-> S
module type Intf = sig
* @canonical . Debugger . S
module type S = S
module type Make = Make
* @canonical . Debugger . Make
module Make : Make
end
|
1cff8e155b1a2f364acc39c813016c6c2708adf6405fcdd663695c763fb35082 | astrada/google-drive-ocamlfuse | keyValueStore.ml | exception File_not_found
module type FileStore = sig
type data
type t = { path : string; data : data }
val path : (t, string) GapiLens.t
val data : (t, data) GapiLens.t
val save : t -> unit
val load : string -> t
end
module type Data = sig
type t
val of_table : (string, string) Hashtbl.t -> t
val to_table : t -> (string, string) Hashtbl.t
end
module MakeFileStore (D : Data) = struct
type data = D.t
type t = { path : string; data : data }
let path =
{
GapiLens.get = (fun x -> x.path);
GapiLens.set = (fun v x -> { x with path = v });
}
let data =
{
GapiLens.get = (fun x -> x.data);
GapiLens.set = (fun v x -> { x with data = v });
}
let load filename =
if not (Sys.file_exists filename) then raise File_not_found;
let sb = Scanf.Scanning.from_file filename in
let table = Hashtbl.create 16 in
while not (Scanf.Scanning.end_of_input sb) do
let key, value = Scanf.bscanf sb "%s@=%s@\n" (fun k v -> (k, v)) in
Hashtbl.add table (String.trim key) (String.trim value)
done;
{ path = filename; data = D.of_table table }
let save store =
let table = D.to_table store.data in
let out_ch = open_out store.path in
let key_value_list =
Hashtbl.fold (fun key value kvs -> (key, value) :: kvs) table []
in
let sorted_table =
List.sort (fun (k, _) (k', _) -> compare k k') key_value_list
in
List.iter
(fun (key, value) -> Printf.fprintf out_ch "%s=%s\n" key value)
sorted_table;
close_out out_ch
end
| null | https://raw.githubusercontent.com/astrada/google-drive-ocamlfuse/9027602dbbaf7473cfacc8bd44865d2bef7c41c7/src/keyValueStore.ml | ocaml | exception File_not_found
module type FileStore = sig
type data
type t = { path : string; data : data }
val path : (t, string) GapiLens.t
val data : (t, data) GapiLens.t
val save : t -> unit
val load : string -> t
end
module type Data = sig
type t
val of_table : (string, string) Hashtbl.t -> t
val to_table : t -> (string, string) Hashtbl.t
end
module MakeFileStore (D : Data) = struct
type data = D.t
type t = { path : string; data : data }
let path =
{
GapiLens.get = (fun x -> x.path);
GapiLens.set = (fun v x -> { x with path = v });
}
let data =
{
GapiLens.get = (fun x -> x.data);
GapiLens.set = (fun v x -> { x with data = v });
}
let load filename =
if not (Sys.file_exists filename) then raise File_not_found;
let sb = Scanf.Scanning.from_file filename in
let table = Hashtbl.create 16 in
while not (Scanf.Scanning.end_of_input sb) do
let key, value = Scanf.bscanf sb "%s@=%s@\n" (fun k v -> (k, v)) in
Hashtbl.add table (String.trim key) (String.trim value)
done;
{ path = filename; data = D.of_table table }
let save store =
let table = D.to_table store.data in
let out_ch = open_out store.path in
let key_value_list =
Hashtbl.fold (fun key value kvs -> (key, value) :: kvs) table []
in
let sorted_table =
List.sort (fun (k, _) (k', _) -> compare k k') key_value_list
in
List.iter
(fun (key, value) -> Printf.fprintf out_ch "%s=%s\n" key value)
sorted_table;
close_out out_ch
end
|
|
ca379b30c8f909a73ce9cfd8ba6812806ee9c39761ae88550d107d008a9a56a0 | yogthos/reagent-example | project.clj | (defproject reagent-example "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:dependencies [[org.clojure/clojure "1.6.0"]
[lib-noir "0.8.4"]
[ring-server "0.3.1"]
[selmer "0.6.8"]
[com.taoensso/timbre "3.2.1"]
[com.taoensso/tower "2.0.2"]
[markdown-clj "0.9.44"]
[environ "0.5.0"]
[noir-exception "0.2.2"]
[org.clojure/clojurescript "0.0-2280"]
[reagent "0.4.2"]
[cljs-ajax "0.2.6"]]
:repl-options {:init-ns reagent-example.repl}
:plugins [[lein-ring "0.8.10"]
[lein-environ "0.5.0"]
[lein-cljsbuild "1.0.3"]]
:ring {:handler reagent-example.handler/app
:init reagent-example.handler/init
:destroy reagent-example.handler/destroy}
:cljsbuild
{:builds
[{:id "dev"
:source-paths ["src-cljs"]
:compiler
{:optimizations :none
:output-to "resources/public/js/app.js"
:output-dir "resources/public/js/"
:pretty-print true
:source-map true}}
{:id "release"
:source-paths ["src-cljs"]
:compiler
{:output-to "resources/public/js/app.js"
;:source-map "resources/public/js/app.js.map"
:optimizations :advanced
:pretty-print false
:output-wrapper false
:closure-warnings {:non-standard-jsdoc :off}}}]}
:profiles
{:uberjar {:aot :all}
:release {:ring {:open-browser? false
:stacktraces? false
:auto-reload? false}}
:dev {:dependencies [[ring-mock "0.1.5"]
[ring/ring-devel "1.3.0"]
[pjstadig/humane-test-output "0.6.0"]]
:injections [(require 'pjstadig.humane-test-output)
(pjstadig.humane-test-output/activate!)]
:env {:dev true}}}
:min-lein-version "2.0.0")
| null | https://raw.githubusercontent.com/yogthos/reagent-example/2512a61dfd8c00169af05fce253920567182095e/project.clj | clojure | :source-map "resources/public/js/app.js.map" | (defproject reagent-example "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:dependencies [[org.clojure/clojure "1.6.0"]
[lib-noir "0.8.4"]
[ring-server "0.3.1"]
[selmer "0.6.8"]
[com.taoensso/timbre "3.2.1"]
[com.taoensso/tower "2.0.2"]
[markdown-clj "0.9.44"]
[environ "0.5.0"]
[noir-exception "0.2.2"]
[org.clojure/clojurescript "0.0-2280"]
[reagent "0.4.2"]
[cljs-ajax "0.2.6"]]
:repl-options {:init-ns reagent-example.repl}
:plugins [[lein-ring "0.8.10"]
[lein-environ "0.5.0"]
[lein-cljsbuild "1.0.3"]]
:ring {:handler reagent-example.handler/app
:init reagent-example.handler/init
:destroy reagent-example.handler/destroy}
:cljsbuild
{:builds
[{:id "dev"
:source-paths ["src-cljs"]
:compiler
{:optimizations :none
:output-to "resources/public/js/app.js"
:output-dir "resources/public/js/"
:pretty-print true
:source-map true}}
{:id "release"
:source-paths ["src-cljs"]
:compiler
{:output-to "resources/public/js/app.js"
:optimizations :advanced
:pretty-print false
:output-wrapper false
:closure-warnings {:non-standard-jsdoc :off}}}]}
:profiles
{:uberjar {:aot :all}
:release {:ring {:open-browser? false
:stacktraces? false
:auto-reload? false}}
:dev {:dependencies [[ring-mock "0.1.5"]
[ring/ring-devel "1.3.0"]
[pjstadig/humane-test-output "0.6.0"]]
:injections [(require 'pjstadig.humane-test-output)
(pjstadig.humane-test-output/activate!)]
:env {:dev true}}}
:min-lein-version "2.0.0")
|
a583f1f35be21507e2357b4a16c4654533e2eda94ef4f4fdb2955295406720d4 | Javran/advent-of-code | Day16.hs | module Javran.AdventOfCode.Y2020.Day16 (
) where
import Control.Monad
import qualified Data.IntMap.Strict as IM
import qualified Data.IntSet as IS
import Data.List
import Javran.AdventOfCode.Prelude
import Text.ParserCombinators.ReadP
data Day16 deriving (Generic)
type Range = (Int, Int)
type FieldRangeInfo = (String, [Range])
rangeP :: ReadP Range
rangeP = (,) <$> decimal1P <*> (char '-' *> decimal1P)
fieldRangeInfoP :: ReadP FieldRangeInfo
fieldRangeInfoP =
(,)
<$> (munch1 (/= ':') <* string ": ")
<*> (rangeP `sepBy` string " or ")
solve :: IM.IntMap IS.IntSet -> [(Int, Int)] -> [] [(Int, Int)]
solve clues solution
| IM.null clues = [solution]
| otherwise = do
let (k, vs) = minimumBy (comparing (IS.size . snd)) $ IM.toList clues
v <- IS.toList vs
let clues' = fmap (IS.delete v) $ IM.delete k clues
guard $ not (any IS.null clues')
solve clues' ((k, v) : solution)
instance Solution Day16 where
solutionRun _ SolutionContext {getInputS, answerShow} = do
let parseInts :: String -> [Int]
parseInts = fmap read . splitOn ","
[ xs
, ["your ticket:", ys]
, "nearby tickets:" : zs
] <-
splitOn [""] . lines <$> getInputS
let rangeRules = fmap (fromJust . consumeAllWithReadP fieldRangeInfoP) xs
yourTicket = parseInts ys
nearbyTickets = fmap parseInts zs
allRanges = concatMap snd rangeRules
isInvalidVal v = not (any (\r -> inRange r v) allRanges)
invalidVals = filter isInvalidVal $ concat nearbyTickets
answerShow (sum invalidVals)
let invalids = IS.fromList invalidVals
validTickets =
yourTicket :
filter (all (`IS.notMember` invalids)) nearbyTickets
fieldVals = fmap IS.fromList $ transpose validTickets
-- collect possible relations:
-- key is field index and value is list of possible val sets.
possiblePairs = IM.fromListWith IS.union $ do
(indField, (_fName, ranges)) <- zip [0 :: Int ..] rangeRules
(indVal, vs) <- zip [0 :: Int ..] fieldVals
guard $ all (\v -> any (\r -> inRange r v) ranges) (IS.toList vs)
pure (indField, IS.singleton indVal)
solution =
just need one solution , probably the only one .
head $ solve possiblePairs []
answerShow $
product $ do
(indField, (fName, _)) <- zip [0 :: Int ..] rangeRules
guard $ "departure" `isPrefixOf` fName
let Just colInd = lookup indField solution
pure $ yourTicket !! colInd
| null | https://raw.githubusercontent.com/Javran/advent-of-code/676ef13c2f9d341cf7de0f383335a1cf577bd73d/src/Javran/AdventOfCode/Y2020/Day16.hs | haskell | collect possible relations:
key is field index and value is list of possible val sets. | module Javran.AdventOfCode.Y2020.Day16 (
) where
import Control.Monad
import qualified Data.IntMap.Strict as IM
import qualified Data.IntSet as IS
import Data.List
import Javran.AdventOfCode.Prelude
import Text.ParserCombinators.ReadP
data Day16 deriving (Generic)
type Range = (Int, Int)
type FieldRangeInfo = (String, [Range])
rangeP :: ReadP Range
rangeP = (,) <$> decimal1P <*> (char '-' *> decimal1P)
fieldRangeInfoP :: ReadP FieldRangeInfo
fieldRangeInfoP =
(,)
<$> (munch1 (/= ':') <* string ": ")
<*> (rangeP `sepBy` string " or ")
solve :: IM.IntMap IS.IntSet -> [(Int, Int)] -> [] [(Int, Int)]
solve clues solution
| IM.null clues = [solution]
| otherwise = do
let (k, vs) = minimumBy (comparing (IS.size . snd)) $ IM.toList clues
v <- IS.toList vs
let clues' = fmap (IS.delete v) $ IM.delete k clues
guard $ not (any IS.null clues')
solve clues' ((k, v) : solution)
instance Solution Day16 where
solutionRun _ SolutionContext {getInputS, answerShow} = do
let parseInts :: String -> [Int]
parseInts = fmap read . splitOn ","
[ xs
, ["your ticket:", ys]
, "nearby tickets:" : zs
] <-
splitOn [""] . lines <$> getInputS
let rangeRules = fmap (fromJust . consumeAllWithReadP fieldRangeInfoP) xs
yourTicket = parseInts ys
nearbyTickets = fmap parseInts zs
allRanges = concatMap snd rangeRules
isInvalidVal v = not (any (\r -> inRange r v) allRanges)
invalidVals = filter isInvalidVal $ concat nearbyTickets
answerShow (sum invalidVals)
let invalids = IS.fromList invalidVals
validTickets =
yourTicket :
filter (all (`IS.notMember` invalids)) nearbyTickets
fieldVals = fmap IS.fromList $ transpose validTickets
possiblePairs = IM.fromListWith IS.union $ do
(indField, (_fName, ranges)) <- zip [0 :: Int ..] rangeRules
(indVal, vs) <- zip [0 :: Int ..] fieldVals
guard $ all (\v -> any (\r -> inRange r v) ranges) (IS.toList vs)
pure (indField, IS.singleton indVal)
solution =
just need one solution , probably the only one .
head $ solve possiblePairs []
answerShow $
product $ do
(indField, (fName, _)) <- zip [0 :: Int ..] rangeRules
guard $ "departure" `isPrefixOf` fName
let Just colInd = lookup indField solution
pure $ yourTicket !! colInd
|
beb98fdb53d2c101a75c1b22921bfb4686942f5b004963268bf68da37a4609b4 | wooga/erlang_prelude | ep_code_tests.erl | -module(ep_code_tests).
-include_lib("eunit/include/eunit.hrl").
-define(IT, ep_code).
% just to test has_behaviour/2
-behaviour(ep_deploy).
-export([reload/1]).
reload(_) -> ok.
has_behaviour_test() ->
?assertEqual(true, ?IT:has_behaviour(ep_deploy, ?MODULE)),
?assertEqual(false, ?IT:has_behaviour(not_existing, ?MODULE)),
?assertEqual(false, ?IT:has_behaviour(ep_deploy, ?IT)).
| null | https://raw.githubusercontent.com/wooga/erlang_prelude/ce7e96ef58dee98e8f67232b21cd5aabc7963f2f/test/ep_code_tests.erl | erlang | just to test has_behaviour/2 | -module(ep_code_tests).
-include_lib("eunit/include/eunit.hrl").
-define(IT, ep_code).
-behaviour(ep_deploy).
-export([reload/1]).
reload(_) -> ok.
has_behaviour_test() ->
?assertEqual(true, ?IT:has_behaviour(ep_deploy, ?MODULE)),
?assertEqual(false, ?IT:has_behaviour(not_existing, ?MODULE)),
?assertEqual(false, ?IT:has_behaviour(ep_deploy, ?IT)).
|
cce4f5e8dda3c69b24c95faf39c83fe07c62d248984cacf7e528db9987a1f8e3 | kthielen/stlcc | CFG.hs | # LANGUAGE MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances , FlexibleContexts , TypeSynonymInstances , ImpredicativeTypes #
module Util.CFG where
import Util.String
import Util.Sequence
import Util.Pointed
import Util.State
import Util.Num
import Util.Graphviz
import Data.List
import Data.Char
import Control.Monad.State
{-
Basic block construction for generic instruction sequences
(plus definitions of assembly code statements and abstract machine statements as generic instructions)
-}
data CFlowTy = NoCFlow | LabelDef String | JumpSrc [String]
class (Eq i, Show i) => Instruction i where
inst_type :: i -> CFlowTy
label :: String -> i
jump :: String -> i
invert :: i -> i
data Instruction i => BBlock i = BBlock [i] Int Int Int deriving Show
type CFG i = [BBlock i]
mapCFG :: (Instruction i, Instruction j) => (i -> j) -> CFG i -> CFG j
mapCFG f bs = [BBlock (map f is) n m o | BBlock is n m o <- bs]
concatMapCFG :: (Instruction i, Instruction j) => (i -> [j]) -> CFG i -> CFG j
concatMapCFG f bs = [BBlock (concatMap f is) n m o | BBlock is n m o <- bs]
instance Instruction i => Eq (BBlock i) where
(BBlock _ n _ _) == (BBlock _ n' _ _) = n == n'
instance Instruction i => Ord (BBlock i) where
compare (BBlock _ _ m _) (BBlock _ _ m' _) = compare m m'
build_cfg :: Instruction i => [i] -> State Int (CFG i)
build_cfg insts = do { g <- accum 0 True [] insts; return $ orderTrace g } where
accum _ _ bs [] = return bs
accum n True bs (i:is) | is_label i = accum (n+1) False ((BBlock [i] n 0 0):bs) is
accum n True bs is = do
lbl <- fresh (label . prefix "bb");
accum (n+1) False ((BBlock [lbl] n 0 0):bs) is
accum n False (b:bs) (i:is) | is_label i = accum n False (b:bs) ((jump $ ex_lbl $ inst_type i):i:is)
accum n False (b:bs) (i:is) | is_jump i = accum n True ((append_inst i b):bs) is
accum n False (b:bs) (i:is) = accum n False ((append_inst i b):bs) is
orderTrace :: Instruction i => CFG i -> CFG i
orderTrace [] = []
orderTrace bs = concat $ unfold getTrace restBs endBs (0, [], [entry], bs') where
(entry:bs') = closePointedPfx $ findBy ((==0) . block_id) bs
getTrace (_, tr, _, _) = tr
restBs (n, _, lb, rb) = nextTrace n lb rb
endBs (_, _, lb, _) = lb == []
nextTrace :: Instruction i => Int -> CFG i -> CFG i -> (Int, CFG i, CFG i, CFG i)
nextTrace n [] _ = (n, [], [], [])
nextTrace n [b] [] = (n+block_length b, [set_block_order b n], [], [])
nextTrace n (b:bs) availBs = tryOrder (block_dests b) where
stepOrd = n + block_length b
tryOrder [lbl] | isDef lbl = ordStep id lbl []
tryOrder [flbl,tlbl] | isDef tlbl = ordStep id tlbl [flbl]
tryOrder [flbl,tlbl] | isDef flbl = ordStep block_invjump flbl []
tryOrder lbls = (stepOrd, [set_block_order b n], bs ++ bs', availBs') where
(bs', availBs') = extractRefBlocks lbls availBs
ordStep f lbl elbls = (n', (set_block_order (f b) n):bs''', lbs, availBs''') where
(bs', availBs') = reorder lbl
(bs'', availBs'') = extractRefBlocks elbls availBs'
(n', bs''', lbs, availBs''') = nextTrace stepOrd (bs' ++ bs'') availBs''
reorder lbl | isLiveDef lbl = (closePointedPfx (findNamedBlock lbl bs), availBs)
reorder lbl = (pointed i : bs, cutClose i) where
i = findNamedBlock lbl availBs
isBDef bs' lbl = any (== lbl) (map block_name bs')
isLiveDef = isBDef bs
isAvailDef = isBDef availBs
isDef lbl = isLiveDef lbl || isAvailDef lbl
findNamedBlock lbl bs = findBy ((== lbl) . block_name) bs
extractRefBlocks lbls bs = partition ((`elem` lbls) . block_name) bs
serialize_cfg :: Instruction i => CFG i -> [i]
serialize_cfg bbs = concat $ map block_insts $ fixup_blocks $ sort bbs where
fixup_blocks bs = zipWith fixup_block bs ((tail bs)++[null_block])
fixup_block b b' | falls_through (block_dests b) (block_name b') = strip_mjump b
fixup_block b b' = add_false_jump b (block_dests b)
falls_through [lbl] lbl' | lbl == lbl' = True
falls_through (_:lbl:_) lbl' | lbl == lbl' = True
falls_through _ _ = False
strip_mjump b | (length (block_dests b)) == 1 = block_cutjump b
strip_mjump b = b
add_false_jump b (_:lbl:_) = append_inst (jump lbl) b
add_false_jump b _ = b
null_block = BBlock [] (-1) (-1) (-1)
cfg_node :: Instruction i => CFG i -> Int -> i
cfg_node bs idx = (block_insts b') !! (idx - block_order b') where
b' = find_inst_block bs idx
node_count :: Instruction i => CFG i -> Int
node_count bs = sum (map (length . block_insts) bs)
node_succ :: Instruction i => CFG i -> Int -> [Int]
node_succ bs idx = find_succ b' idx' where
find_succ b i | (i+1) < block_length b = [block_order b+i+1]
find_succ b _ = [block_order (named_block lbl bs) | lbl <- block_dests b]
b' = find_inst_block bs idx
idx' = idx - block_order b'
node_pred :: Instruction i => CFG i -> Int -> [Int]
node_pred bs idx = find_pred b' idx' where
find_pred b i | i > 0 = [block_order b+i-1]
find_pred b _ = [block_order b' + block_length b' - 1| b' <- bs, (block_name b) `elem` (block_dests b')]
b' = find_inst_block bs idx
idx' = idx - block_order b'
find_inst_block :: Instruction i => CFG i -> Int -> BBlock i
find_inst_block (b:bs) idx | withinLen idx (block_order b) (block_length b) = b
find_inst_block (_:bs) idx = find_inst_block bs idx
find_inst_block _ idx = error ("Invalid instruction index: " ++ show idx)
append_inst :: Instruction i => i -> BBlock i -> BBlock i
append_inst i (BBlock is n m o) = BBlock (is++[i]) n m o
block_insts :: Instruction i => BBlock i -> [i]
block_insts (BBlock is _ _ _) = is
blockNumberedInsts :: Instruction i => BBlock i -> [(Int, i)]
blockNumberedInsts (BBlock is _ m _) = zip (iterate (+1) m) is
block_length :: Instruction i => BBlock i -> Int
block_length b = length $ block_insts b
block_name :: Instruction i => BBlock i -> String
block_name (BBlock (i:is) _ _ _) = ex_lbl (inst_type i)
block_name (BBlock [] _ _ _) = "empty"
renameBlock :: Instruction i => BBlock i -> String -> BBlock i
renameBlock (BBlock (_:is) n m o) s = BBlock (label s : is) n m o
renameBlock (BBlock [] n m o) s = BBlock [label s] n m o
renameNamedBlock :: Instruction i => String -> String -> BBlock i -> BBlock i
renameNamedBlock s s' bb | block_name bb == s = renameBlock bb s'
renameNamedBlock _ _ bb = bb
block_id :: Instruction i => BBlock i -> Int
block_id (BBlock _ n _ _) = n
block_order :: Instruction i => BBlock i -> Int
block_order (BBlock _ _ m _) = m
set_block_order :: Instruction i => BBlock i -> Int -> BBlock i
set_block_order (BBlock is n _ o) m = BBlock is n m o
block_offset :: Instruction i => BBlock i -> Int
block_offset (BBlock _ _ _ o) = o
block_dests :: Instruction i => BBlock i -> [String]
block_dests (BBlock [] _ _ _) = []
block_dests (BBlock is _ _ _) = ex_dsts (inst_type (last is)) where
ex_dsts (JumpSrc lbls) = lbls
ex_dsts _ = []
block_invjump :: Instruction i => BBlock i -> BBlock i
block_invjump (BBlock is n m o) = BBlock is' n m o where
(li:ris) = reverse is
is' = reverse ((invert li):ris)
block_cutjump :: Instruction i => BBlock i -> BBlock i
block_cutjump (BBlock is n m o) = BBlock is' n m o where
(_:ris) = reverse is
is' = reverse ris
named_block :: Instruction i => String -> CFG i -> BBlock i
named_block lbl bs = bs !! (at lbl $ map block_name bs)
block_by_id :: Instruction i => Int -> CFG i -> BBlock i
block_by_id n bs = bs !! (at n $ map block_id bs)
push_instruction :: Instruction i => BBlock i -> i -> BBlock i
push_instruction (BBlock is m n o) i = BBlock (insert is) m n o where
insert [] = [i]
insert (i':is) | is_label i' = i' : insert is
insert (i':is) = i : i' : is
first_inst :: Instruction i => BBlock i -> Maybe i
first_inst (BBlock is _ _ _) = find is where
find (i:is) | is_label i = find is
find (i:_) = Just i
find [] = Nothing
is_first_inst :: Instruction i => BBlock i -> i -> Bool
is_first_inst bb i = match (first_inst bb) where
match (Just i') = i' == i
match Nothing = False
rpush_instruction :: Instruction i => BBlock i -> i -> BBlock i
rpush_instruction (BBlock is m n o) i = BBlock (reverse (insert (reverse is))) m n o where
insert [] = [i]
insert (i':is) | is_jump i' = i' : insert is
insert (i':is) = i : i' : is
last_inst :: Instruction i => BBlock i -> Maybe i
last_inst (BBlock is _ _ _) = Just (last is)
last_inst_ord :: Instruction i => BBlock i -> (Int, i)
last_inst_ord bb = (block_order bb + length is - 1, last is) where
is = block_insts bb
is_label :: Instruction i => i -> Bool
is_label i = il (inst_type i) where
il (LabelDef _) = True
il _ = False
ex_lbl :: CFlowTy -> String
ex_lbl (LabelDef lbl) = lbl
is_jump :: Instruction i => i -> Bool
is_jump i = ij (inst_type i) where
ij (JumpSrc _) = True
ij _ = False
Graphviz serialization of control flow graphs
Graphviz serialization of control flow graphs
-}
cfgDiagram :: Instruction i => String -> CFG i -> String
cfgDiagram name bs =
" subgraph cluster_" ++ name' ++ " {\n" ++
" label=\"" ++ name' ++ "\";\n" ++
concat (map block_desc bs) ++
concat (map edge_desc edges) ++
" }\n"
where
name' = gvEsc name
block_desc b =
" \"" ++ name' ++ "_block" ++ show (block_id b) ++ "\" " ++
"[" ++
"style=\"filled, bold\" " ++
"penwidth=1 " ++
"fillcolor=\"white\" " ++
"fontname=\"Courier New\" " ++
"shape=\"Mrecord\" " ++
"label=<" ++ inst_table b ++ ">" ++
"];\n"
edge_desc (src, dst) =
" \"" ++ name' ++ "_block" ++ show src ++ "\" -> \"" ++ name' ++ "_block" ++ show dst ++ "\" " ++
"[" ++
"penwidth=1 " ++
"fontsize=28 " ++
"fontcolor=\"black\" " ++
"];\n"
edges = [(block_id b, block_id $ named_block d bs) | b <- bs, d <- block_dests b]
inst_table b =
"<table border=\"0\" cellborder=\"0\" cellpadding=\"3\" bgcolor=\"white\">" ++
concat ["<tr><td align=\"left\">" ++ show idx ++ ": " ++ gvEsc (show i) ++ "</td></tr>" | (i, idx) <- zip (block_insts b) (map (+(block_order b)) [0..])] ++
"</table>" | null | https://raw.githubusercontent.com/kthielen/stlcc/369492daad6498a93c00f5924a99ceb65b5f1062/Util/CFG.hs | haskell |
Basic block construction for generic instruction sequences
(plus definitions of assembly code statements and abstract machine statements as generic instructions)
| # LANGUAGE MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances , FlexibleContexts , TypeSynonymInstances , ImpredicativeTypes #
module Util.CFG where
import Util.String
import Util.Sequence
import Util.Pointed
import Util.State
import Util.Num
import Util.Graphviz
import Data.List
import Data.Char
import Control.Monad.State
data CFlowTy = NoCFlow | LabelDef String | JumpSrc [String]
class (Eq i, Show i) => Instruction i where
inst_type :: i -> CFlowTy
label :: String -> i
jump :: String -> i
invert :: i -> i
data Instruction i => BBlock i = BBlock [i] Int Int Int deriving Show
type CFG i = [BBlock i]
mapCFG :: (Instruction i, Instruction j) => (i -> j) -> CFG i -> CFG j
mapCFG f bs = [BBlock (map f is) n m o | BBlock is n m o <- bs]
concatMapCFG :: (Instruction i, Instruction j) => (i -> [j]) -> CFG i -> CFG j
concatMapCFG f bs = [BBlock (concatMap f is) n m o | BBlock is n m o <- bs]
instance Instruction i => Eq (BBlock i) where
(BBlock _ n _ _) == (BBlock _ n' _ _) = n == n'
instance Instruction i => Ord (BBlock i) where
compare (BBlock _ _ m _) (BBlock _ _ m' _) = compare m m'
build_cfg :: Instruction i => [i] -> State Int (CFG i)
build_cfg insts = do { g <- accum 0 True [] insts; return $ orderTrace g } where
accum _ _ bs [] = return bs
accum n True bs (i:is) | is_label i = accum (n+1) False ((BBlock [i] n 0 0):bs) is
accum n True bs is = do
lbl <- fresh (label . prefix "bb");
accum (n+1) False ((BBlock [lbl] n 0 0):bs) is
accum n False (b:bs) (i:is) | is_label i = accum n False (b:bs) ((jump $ ex_lbl $ inst_type i):i:is)
accum n False (b:bs) (i:is) | is_jump i = accum n True ((append_inst i b):bs) is
accum n False (b:bs) (i:is) = accum n False ((append_inst i b):bs) is
orderTrace :: Instruction i => CFG i -> CFG i
orderTrace [] = []
orderTrace bs = concat $ unfold getTrace restBs endBs (0, [], [entry], bs') where
(entry:bs') = closePointedPfx $ findBy ((==0) . block_id) bs
getTrace (_, tr, _, _) = tr
restBs (n, _, lb, rb) = nextTrace n lb rb
endBs (_, _, lb, _) = lb == []
nextTrace :: Instruction i => Int -> CFG i -> CFG i -> (Int, CFG i, CFG i, CFG i)
nextTrace n [] _ = (n, [], [], [])
nextTrace n [b] [] = (n+block_length b, [set_block_order b n], [], [])
nextTrace n (b:bs) availBs = tryOrder (block_dests b) where
stepOrd = n + block_length b
tryOrder [lbl] | isDef lbl = ordStep id lbl []
tryOrder [flbl,tlbl] | isDef tlbl = ordStep id tlbl [flbl]
tryOrder [flbl,tlbl] | isDef flbl = ordStep block_invjump flbl []
tryOrder lbls = (stepOrd, [set_block_order b n], bs ++ bs', availBs') where
(bs', availBs') = extractRefBlocks lbls availBs
ordStep f lbl elbls = (n', (set_block_order (f b) n):bs''', lbs, availBs''') where
(bs', availBs') = reorder lbl
(bs'', availBs'') = extractRefBlocks elbls availBs'
(n', bs''', lbs, availBs''') = nextTrace stepOrd (bs' ++ bs'') availBs''
reorder lbl | isLiveDef lbl = (closePointedPfx (findNamedBlock lbl bs), availBs)
reorder lbl = (pointed i : bs, cutClose i) where
i = findNamedBlock lbl availBs
isBDef bs' lbl = any (== lbl) (map block_name bs')
isLiveDef = isBDef bs
isAvailDef = isBDef availBs
isDef lbl = isLiveDef lbl || isAvailDef lbl
findNamedBlock lbl bs = findBy ((== lbl) . block_name) bs
extractRefBlocks lbls bs = partition ((`elem` lbls) . block_name) bs
serialize_cfg :: Instruction i => CFG i -> [i]
serialize_cfg bbs = concat $ map block_insts $ fixup_blocks $ sort bbs where
fixup_blocks bs = zipWith fixup_block bs ((tail bs)++[null_block])
fixup_block b b' | falls_through (block_dests b) (block_name b') = strip_mjump b
fixup_block b b' = add_false_jump b (block_dests b)
falls_through [lbl] lbl' | lbl == lbl' = True
falls_through (_:lbl:_) lbl' | lbl == lbl' = True
falls_through _ _ = False
strip_mjump b | (length (block_dests b)) == 1 = block_cutjump b
strip_mjump b = b
add_false_jump b (_:lbl:_) = append_inst (jump lbl) b
add_false_jump b _ = b
null_block = BBlock [] (-1) (-1) (-1)
cfg_node :: Instruction i => CFG i -> Int -> i
cfg_node bs idx = (block_insts b') !! (idx - block_order b') where
b' = find_inst_block bs idx
node_count :: Instruction i => CFG i -> Int
node_count bs = sum (map (length . block_insts) bs)
node_succ :: Instruction i => CFG i -> Int -> [Int]
node_succ bs idx = find_succ b' idx' where
find_succ b i | (i+1) < block_length b = [block_order b+i+1]
find_succ b _ = [block_order (named_block lbl bs) | lbl <- block_dests b]
b' = find_inst_block bs idx
idx' = idx - block_order b'
node_pred :: Instruction i => CFG i -> Int -> [Int]
node_pred bs idx = find_pred b' idx' where
find_pred b i | i > 0 = [block_order b+i-1]
find_pred b _ = [block_order b' + block_length b' - 1| b' <- bs, (block_name b) `elem` (block_dests b')]
b' = find_inst_block bs idx
idx' = idx - block_order b'
find_inst_block :: Instruction i => CFG i -> Int -> BBlock i
find_inst_block (b:bs) idx | withinLen idx (block_order b) (block_length b) = b
find_inst_block (_:bs) idx = find_inst_block bs idx
find_inst_block _ idx = error ("Invalid instruction index: " ++ show idx)
append_inst :: Instruction i => i -> BBlock i -> BBlock i
append_inst i (BBlock is n m o) = BBlock (is++[i]) n m o
block_insts :: Instruction i => BBlock i -> [i]
block_insts (BBlock is _ _ _) = is
blockNumberedInsts :: Instruction i => BBlock i -> [(Int, i)]
blockNumberedInsts (BBlock is _ m _) = zip (iterate (+1) m) is
block_length :: Instruction i => BBlock i -> Int
block_length b = length $ block_insts b
block_name :: Instruction i => BBlock i -> String
block_name (BBlock (i:is) _ _ _) = ex_lbl (inst_type i)
block_name (BBlock [] _ _ _) = "empty"
renameBlock :: Instruction i => BBlock i -> String -> BBlock i
renameBlock (BBlock (_:is) n m o) s = BBlock (label s : is) n m o
renameBlock (BBlock [] n m o) s = BBlock [label s] n m o
renameNamedBlock :: Instruction i => String -> String -> BBlock i -> BBlock i
renameNamedBlock s s' bb | block_name bb == s = renameBlock bb s'
renameNamedBlock _ _ bb = bb
block_id :: Instruction i => BBlock i -> Int
block_id (BBlock _ n _ _) = n
block_order :: Instruction i => BBlock i -> Int
block_order (BBlock _ _ m _) = m
set_block_order :: Instruction i => BBlock i -> Int -> BBlock i
set_block_order (BBlock is n _ o) m = BBlock is n m o
block_offset :: Instruction i => BBlock i -> Int
block_offset (BBlock _ _ _ o) = o
block_dests :: Instruction i => BBlock i -> [String]
block_dests (BBlock [] _ _ _) = []
block_dests (BBlock is _ _ _) = ex_dsts (inst_type (last is)) where
ex_dsts (JumpSrc lbls) = lbls
ex_dsts _ = []
block_invjump :: Instruction i => BBlock i -> BBlock i
block_invjump (BBlock is n m o) = BBlock is' n m o where
(li:ris) = reverse is
is' = reverse ((invert li):ris)
block_cutjump :: Instruction i => BBlock i -> BBlock i
block_cutjump (BBlock is n m o) = BBlock is' n m o where
(_:ris) = reverse is
is' = reverse ris
named_block :: Instruction i => String -> CFG i -> BBlock i
named_block lbl bs = bs !! (at lbl $ map block_name bs)
block_by_id :: Instruction i => Int -> CFG i -> BBlock i
block_by_id n bs = bs !! (at n $ map block_id bs)
push_instruction :: Instruction i => BBlock i -> i -> BBlock i
push_instruction (BBlock is m n o) i = BBlock (insert is) m n o where
insert [] = [i]
insert (i':is) | is_label i' = i' : insert is
insert (i':is) = i : i' : is
first_inst :: Instruction i => BBlock i -> Maybe i
first_inst (BBlock is _ _ _) = find is where
find (i:is) | is_label i = find is
find (i:_) = Just i
find [] = Nothing
is_first_inst :: Instruction i => BBlock i -> i -> Bool
is_first_inst bb i = match (first_inst bb) where
match (Just i') = i' == i
match Nothing = False
rpush_instruction :: Instruction i => BBlock i -> i -> BBlock i
rpush_instruction (BBlock is m n o) i = BBlock (reverse (insert (reverse is))) m n o where
insert [] = [i]
insert (i':is) | is_jump i' = i' : insert is
insert (i':is) = i : i' : is
last_inst :: Instruction i => BBlock i -> Maybe i
last_inst (BBlock is _ _ _) = Just (last is)
last_inst_ord :: Instruction i => BBlock i -> (Int, i)
last_inst_ord bb = (block_order bb + length is - 1, last is) where
is = block_insts bb
is_label :: Instruction i => i -> Bool
is_label i = il (inst_type i) where
il (LabelDef _) = True
il _ = False
ex_lbl :: CFlowTy -> String
ex_lbl (LabelDef lbl) = lbl
is_jump :: Instruction i => i -> Bool
is_jump i = ij (inst_type i) where
ij (JumpSrc _) = True
ij _ = False
Graphviz serialization of control flow graphs
Graphviz serialization of control flow graphs
-}
cfgDiagram :: Instruction i => String -> CFG i -> String
cfgDiagram name bs =
" subgraph cluster_" ++ name' ++ " {\n" ++
" label=\"" ++ name' ++ "\";\n" ++
concat (map block_desc bs) ++
concat (map edge_desc edges) ++
" }\n"
where
name' = gvEsc name
block_desc b =
" \"" ++ name' ++ "_block" ++ show (block_id b) ++ "\" " ++
"[" ++
"style=\"filled, bold\" " ++
"penwidth=1 " ++
"fillcolor=\"white\" " ++
"fontname=\"Courier New\" " ++
"shape=\"Mrecord\" " ++
"label=<" ++ inst_table b ++ ">" ++
"];\n"
edge_desc (src, dst) =
" \"" ++ name' ++ "_block" ++ show src ++ "\" -> \"" ++ name' ++ "_block" ++ show dst ++ "\" " ++
"[" ++
"penwidth=1 " ++
"fontsize=28 " ++
"fontcolor=\"black\" " ++
"];\n"
edges = [(block_id b, block_id $ named_block d bs) | b <- bs, d <- block_dests b]
inst_table b =
"<table border=\"0\" cellborder=\"0\" cellpadding=\"3\" bgcolor=\"white\">" ++
concat ["<tr><td align=\"left\">" ++ show idx ++ ": " ++ gvEsc (show i) ++ "</td></tr>" | (i, idx) <- zip (block_insts b) (map (+(block_order b)) [0..])] ++
"</table>" |
f1c8125dd33293b208d64609d0ee6b358b7c1b3209356ffc7c05b3c43b95573f | zachjs/sv2v | Inside.hs | sv2v
- Author : < >
-
- Conversion for ` inside ` expressions and cases
-
- The expressions are compared to each candidate using ` = = ? ` , the wildcard
- comparison . As required by the specification , the result of each comparison
- is combined using an OR reduction .
-
- ` case ... inside ` statements are converted to an equivalent if - else cascade .
-
- TODO : Add support for array value ranges .
- TODO : This conversion may cause an expression with side effects to be
- evaluated more than once .
- Author: Zachary Snow <>
-
- Conversion for `inside` expressions and cases
-
- The expressions are compared to each candidate using `==?`, the wildcard
- comparison. As required by the specification, the result of each comparison
- is combined using an OR reduction.
-
- `case ... inside` statements are converted to an equivalent if-else cascade.
-
- TODO: Add support for array value ranges.
- TODO: This conversion may cause an expression with side effects to be
- evaluated more than once.
-}
module Convert.Inside (convert) where
import Convert.Traverse
import Language.SystemVerilog.AST
import Control.Monad.Writer
import Data.Maybe (fromMaybe)
convert :: [AST] -> [AST]
convert = map $ traverseDescriptions $ traverseModuleItems convertModuleItem
convertModuleItem :: ModuleItem -> ModuleItem
convertModuleItem item =
traverseExprs (traverseNestedExprs convertExpr) $
traverseStmts (traverseNestedStmts convertStmt) $
item
convertExpr :: Expr -> Expr
convertExpr (Inside expr valueRanges) =
if length checks == 1
then head checks
else UniOp RedOr $ Concat checks
where
checks = map toCheck valueRanges
toCheck :: Expr -> Expr
toCheck (Range Nil NonIndexed (lo, hi)) =
BinOp LogAnd
(BinOp Le lo expr)
(BinOp Ge hi expr)
toCheck pattern =
BinOp WEq expr pattern
convertExpr other = other
convertStmt :: Stmt -> Stmt
convertStmt (Case u CaseInside expr items) =
if hasSideEffects expr then
Block Seq "" [decl] [stmt]
else
foldr ($) defaultStmt $
map (uncurry $ If NoCheck) $
zip comps stmts
where
-- evaluate expressions with side effects once
tmp = "sv2v_temp_" ++ shortHash expr
decl = Variable Local (TypeOf expr) tmp [] expr
stmt = convertStmt (Case u CaseInside (Ident tmp) items)
-- underlying inside case elaboration
itemsNonDefault = filter (not . null . fst) items
comps = map (Inside expr . fst) itemsNonDefault
stmts = map snd itemsNonDefault
defaultStmt = fromMaybe Null (lookup [] items)
convertStmt other = other
hasSideEffects :: Expr -> Bool
hasSideEffects expr =
getAny $ execWriter $ collectNestedExprsM write expr
where
write :: Expr -> Writer Any ()
write Call{} = tell $ Any True
write _ = return ()
| null | https://raw.githubusercontent.com/zachjs/sv2v/a2b99fa9ddec5af70020cba1668ac8b873ece27e/src/Convert/Inside.hs | haskell | evaluate expressions with side effects once
underlying inside case elaboration | sv2v
- Author : < >
-
- Conversion for ` inside ` expressions and cases
-
- The expressions are compared to each candidate using ` = = ? ` , the wildcard
- comparison . As required by the specification , the result of each comparison
- is combined using an OR reduction .
-
- ` case ... inside ` statements are converted to an equivalent if - else cascade .
-
- TODO : Add support for array value ranges .
- TODO : This conversion may cause an expression with side effects to be
- evaluated more than once .
- Author: Zachary Snow <>
-
- Conversion for `inside` expressions and cases
-
- The expressions are compared to each candidate using `==?`, the wildcard
- comparison. As required by the specification, the result of each comparison
- is combined using an OR reduction.
-
- `case ... inside` statements are converted to an equivalent if-else cascade.
-
- TODO: Add support for array value ranges.
- TODO: This conversion may cause an expression with side effects to be
- evaluated more than once.
-}
module Convert.Inside (convert) where
import Convert.Traverse
import Language.SystemVerilog.AST
import Control.Monad.Writer
import Data.Maybe (fromMaybe)
convert :: [AST] -> [AST]
convert = map $ traverseDescriptions $ traverseModuleItems convertModuleItem
convertModuleItem :: ModuleItem -> ModuleItem
convertModuleItem item =
traverseExprs (traverseNestedExprs convertExpr) $
traverseStmts (traverseNestedStmts convertStmt) $
item
convertExpr :: Expr -> Expr
convertExpr (Inside expr valueRanges) =
if length checks == 1
then head checks
else UniOp RedOr $ Concat checks
where
checks = map toCheck valueRanges
toCheck :: Expr -> Expr
toCheck (Range Nil NonIndexed (lo, hi)) =
BinOp LogAnd
(BinOp Le lo expr)
(BinOp Ge hi expr)
toCheck pattern =
BinOp WEq expr pattern
convertExpr other = other
convertStmt :: Stmt -> Stmt
convertStmt (Case u CaseInside expr items) =
if hasSideEffects expr then
Block Seq "" [decl] [stmt]
else
foldr ($) defaultStmt $
map (uncurry $ If NoCheck) $
zip comps stmts
where
tmp = "sv2v_temp_" ++ shortHash expr
decl = Variable Local (TypeOf expr) tmp [] expr
stmt = convertStmt (Case u CaseInside (Ident tmp) items)
itemsNonDefault = filter (not . null . fst) items
comps = map (Inside expr . fst) itemsNonDefault
stmts = map snd itemsNonDefault
defaultStmt = fromMaybe Null (lookup [] items)
convertStmt other = other
hasSideEffects :: Expr -> Bool
hasSideEffects expr =
getAny $ execWriter $ collectNestedExprsM write expr
where
write :: Expr -> Writer Any ()
write Call{} = tell $ Any True
write _ = return ()
|
9857e0cc0bea5e6bc8282e4d2846b4aff45fbc4e9914ac22530780f9e4e2a652 | kimwnasptd/YAAC-Yet-Another-Alan-Compiler | Emit.hs | {-# LANGUAGE OverloadedStrings #-}
module Emit where
import LLVM.AST
import LLVM.Module
import LLVM.Context
import LLVM.Prelude
import LLVM.AST.Type
import LLVM.PassManager
import LLVM.Analysis
import qualified LLVM.AST.IntegerPredicate as IPRD
import qualified LLVM.AST as AST
import qualified LLVM.AST.Constant as C
import qualified LLVM.AST.Float as F
import qualified LLVM.AST.FloatingPointPredicate as FP
import Data.Char
import Data.Word
import Data.Int
import Data.List
import Control.Monad.Except
import Control.Applicative
import Control.Monad.State
import Control.Monad
import qualified Data.ByteString.Char8 as BS8 (pack, unpack)
import qualified Data.Map as Map
import Codegen
import qualified ASTTypes as S
import SymbolTableTypes
import SemanticFunctions
import CodegenUtilities
import qualified LibraryFunctions as LIB
-------------------------------------------------------------------------------
-- Compilation
-------------------------------------------------------------------------------
passes :: Word -> PassSetSpec -- the optimizations we want to run
passes opt = defaultCuratedPassSetSpec { optLevel = Just opt }
codegen :: AST.Module -> S.Program -> Word -> IO AST.Module
codegen mod main opt = withContext $ \context ->
withModuleFromAST context newast $ \m -> do
withPassManager (passes opt) $ \pm -> do
runPassManager pm m
llstr <- moduleLLVMAssembly m
putStrLn $ BS8.unpack llstr -- Convert ByteString -> String
return newast
where
modn = codegenTop main
newast = runLLVM mod modn
codegenTop :: S.Program -> LLVM ()
codegenTop main = do
let codegen = execCodegen (cgen_ast main)
defs = definitions codegen
log = logger codegen
modify $ \s -> s { moduleDefinitions = defs }
-------------------------------------------------------------------------------
-- Codegeneration Functions
-------------------------------------------------------------------------------
cgen_ast :: S.Program -> Codegen String
cgen_ast (S.Prog main) = do
addLibraryFns LIB.lib_fns
cgen_main main
gets logger >>= return -- > return the logger of our codegeneration
cgen_main :: S.Func_Def -> Codegen ()
cgen_main main@(S.F_Def name args_lst f_type ldef_list cmp_stmt) = do
openScope "main"
fun <- addFunc "main" [] f_type
entry <- addBlock entryBlockName
setBlock entry
addLDefLst ldef_list -- > add the local definitions of that function, this is where the recursion happens
init_display (max_nesting (S.Loc_Def_Fun main)) -- Updates the stack frame
putframe
escapevars
> do the Semantic analysis of the function body
cgen_stmts cmp_stmt
endblock fun
closeScope -- > close the function' s scope
cgenFuncDef :: S.Func_Def -> Codegen ()
cgenFuncDef (S.F_Def name args_lst f_type ldef_list cmp_stmt) = do
fun <- addFunc name args_lst f_type -- we add the function to our CURRENT scope
openScope name -- every function creates a new scope
entry <- addBlock entryBlockName
setBlock entry -- change the current block to the new function
addFArgs args_lst -- add parameters to symtable
addFunc name args_lst f_type -- NOTE: add the function to the inside scope as well
addLDefLst ldef_list -- add the local definitions of that function, this is where the recursion happens
putframe
escapevars -- previous functions, Then, local escape our own variables
do the Semantic analysis of the function body
recover_vars cmp_stmt -- walk the function body , recovering all needed external variables from
once the Semantic analysis has passed , gen the body
If proc , put a ret as terminator
closeScope -- close the function' s scope
cgen_stmts :: S.Comp_Stmt -> Codegen [()]
cgen_stmts (S.C_Stmt stmts) = mapM cgen_stmt stmts
cgen_stmts ( S.C_Stmt stmts ) = forM stmts cgen_stmt -- because we like playing with monads ...
cgen_stmt :: S.Stmt -> Codegen ()
cgen_stmt S.Stmt_Ret = ret >> return ()
cgen_stmt S.Stmt_Semi = return ()
cgen_stmt (S.Stmt_Ret_Expr e1) = cgen_expr e1 >>= retval >> return ()
cgen_stmt (S.Stmt_Cmp cmp_stmt) = cgen_stmts cmp_stmt >> return ()
cgen_stmt (S.Stmt_Eq lval expr) = do
var <- cgen_lval lval
val <- cgen_expr expr
store var val
return ()
cgen_stmt (S.Stmt_FCall (S.Func_Call fn args)) = do
F fun_info <- getSymbol fn
refs <- forM (fn_args fun_info) (\(_,_,ref,_) -> return ref)
arg_operands <- mapM cgen_arg (zip args refs)
foo_operand <- getfun fn
disp <- getvar "display"
lbr_fns <- gets libraryfns
case fn `elem` lbr_fns of
True -> call_void foo_operand arg_operands
_ -> call_void foo_operand (arg_operands ++ [disp] )
return ()
-- call_void foo_operand arg_operands
-- return () NOTE: ASK SOMEONE
cgen_stmt (S.Stmt_IFE cond if_stmt else_stmt) = do
ifthen <- addBlock "if.then"
ifelse <- addBlock "if.else"
create the 3 blocks .
-- ENTRY
generate a 1 - bit condition
cbr cond_op ifthen ifelse -- branch based on condition
-- ifthen part
--------------
setBlock ifthen -- now instructions are added to the ifthen block
cgen_stmt if_stmt -- fill the block with the proper instructions
merge the block . NOTE : Fallthrough is not allowed !
get back the block for the phi node
-- ifelse part
--------------
setBlock ifelse -- same as ifthen block
cgen_stmt else_stmt
br ifexit
ifelse <- getBlock
-- exit part
------------
merge the 2 blocks
ret -- WARNING : JUST FOR TESTING , THIS IS WRONG AF
return ()
cgen_stmt (S.Stmt_If cond if_stmt ) = do
ifthen <- addBlock "if.then"
ifexit <- addBlock "if.exit"
-- ENTRY
generate a 1 - bit condition
cbr cond_op ifthen ifexit -- branch based on condition
-- ifthen part
--------------
setBlock ifthen
cgen_stmt if_stmt
br ifexit
-- ifthen <- getBlock
-- exit part
------------
setBlock ifexit
return ()
cgen_stmt (S.Stmt_Wh cond loop_stmt) = do
while_entry <- addBlock "while.entry" -- add a block to prep the loop body
while_loop <- addBlock "while.loop" -- add block for the loop body
while_exit <- addBlock "while.exit" -- add fall through loop
generate the condition for the FIRST time
cbr entry_cond while_loop while_exit -- if the condition is true, execute the body
-- while entry
setBlock while_entry
generate the condition for the FIRST time
cbr entry_cond while_loop while_exit -- if the condition is true, execute the body
-- while body
setBlock while_loop -- change block
cgen_stmt loop_stmt -- generate the loop's code
br while_entry -- go to the loop exit
-- while exit
setBlock while_exit
return()
cgen_expr :: S.Expr -> Codegen AST.Operand
cgen_expr (S.Expr_Brack exp) = cgen_expr exp
cgen_expr (S.Expr_Lval lval) = cgen_lval lval >>= load
cgen_expr (S.Expr_Int int) = return $ toInt int
cgen_expr (S.Expr_Add e1 e2) = do
ce1 <- cgen_expr e1
ce2 <- cgen_expr e2
add ce1 ce2
cgen_expr (S.Expr_Sub e1 e2) = do
ce1 <- cgen_expr e1
ce2 <- cgen_expr e2
sub ce1 ce2
cgen_expr (S.Expr_Tms e1 e2) = do
ce1 <- cgen_expr e1
ce2 <- cgen_expr e2
mul ce1 ce2
cgen_expr (S.Expr_Div e1 e2) = do
ce1 <- cgen_expr e1
ce2 <- cgen_expr e2
tp <- getExprType e1
case tp of
IntType -> sdiv ce1 ce2
ByteType -> udiv ce1 ce2
cgen_expr (S.Expr_Mod e1 e2) = do
ce1 <- cgen_expr e1
ce2 <- cgen_expr e2
tp <- getExprType e1
case tp of
IntType -> srem ce1 ce2
ByteType -> urem ce1 ce2
cgen_expr (S.Expr_Fcall (S.Func_Call fn args ) ) = do
F fun_info <- getSymbol fn
refs <- forM (fn_args fun_info) (\(_,_,ref,_) -> return ref)
arg_operands <- mapM cgen_arg (zip args refs)
foo_operand <- getfun fn
disp <- getvar "display"
lbr_fns <- gets libraryfns
case fn `elem` lbr_fns of
True -> call foo_operand arg_operands
_ -> call foo_operand (arg_operands ++ [disp] )
cgen_expr (S.Expr_Char ch_str) = do
return $ toChar (head ch_str)
cgen_expr (S.Expr_Pos expr ) = cgen_expr expr
cgen_expr(S.Expr_Neg expr ) = do
ce <- cgen_expr expr
sub zero ce
cgen_cond :: S.Cond -> Codegen AST.Operand
cgen_cond (S.Cond_Eq left right ) = do
left_op <- cgen_expr left -- generate the left operand
right_op <- cgen_expr right -- generate the right operand
cmp IPRD.EQ left_op right_op -- compare them accordingly
cgen_cond (S.Cond_Neq left right ) = do
left_op <- cgen_expr left
right_op <- cgen_expr right
cmp IPRD.NE left_op right_op
cgen_cond (S.Cond_G left right ) = do
left_op <- cgen_expr left
right_op <- cgen_expr right
cmp IPRD.SGT left_op right_op
cgen_cond (S.Cond_L left right ) = do
left_op <- cgen_expr left
right_op <- cgen_expr right
cmp IPRD.SLT left_op right_op
cgen_cond (S.Cond_GE left right ) = do
left_op <- cgen_expr left
right_op <- cgen_expr right
cmp IPRD.SGE left_op right_op
cgen_cond (S.Cond_LE left right ) = do
left_op <- cgen_expr left
right_op <- cgen_expr right
cmp IPRD.SLE left_op right_op
cgen_cond (S.Cond_True) = return true
cgen_cond (S.Cond_False) = return false
cgen_cond (S.Cond_Br br) = cgen_cond br -- just generate the inner condition
cgen_cond (S.Cond_And first second ) = do
fst_op <- cgen_cond first -- generate the left condition
snd_op <- cgen_cond second -- generate the right condition
and_instr fst_op snd_op -- logical AND them
cgen_cond (S.Cond_Or first second ) = do
fst_op <- cgen_cond first
snd_op <- cgen_cond second
or_instr fst_op snd_op
cgen_cond (S.Cond_Bang arg ) = do
generate the 1 bit boolean inside condition
bang op -- reverse it
-- cgen_lval always returns an address operand
cgen_lval :: S.L_Value -> Codegen AST.Operand
cgen_lval (S.LV_Var var) = getvar var
cgen_lval (S.LV_Tbl tbl_var offset_expr) = do
offset <- cgen_expr offset_expr --generate the expression for the offset
tbl_operand <- getvar tbl_var -- get the table operand
create_ptr tbl_operand [offset] tbl_var
cgen_lval (S.LV_Lit str) = do
globStrName <- freshStr
define $ globalStr globStrName str
let op = externstr (Name $ toShort globStrName) (str_type str)
bitcast op (ptr i8)
-- If an array without brackets we need to pass the pointer to the func
cgen_arg :: (S.Expr, Bool) -> Codegen Operand
cgen_arg ((S.Expr_Lval lval), False) = cgen_lval lval >>= load
cgen_arg ((S.Expr_Lval lval), True ) = cgen_lval lval
cgen_arg (expr, _) = cgen_expr expr
-------------------------------------------------------------------------------
-- Symbol Table and Scopes Handling
-------------------------------------------------------------------------------
getvar :: SymbolName -> Codegen Operand
getvar var = do
symbol <- getSymbol_enhanced var
case symbol of
(Left (F _ ) ) -> error $ "Var " ++ (show var) ++ " is also a function on the current scope!"
(Right ( _, F _ ) ) -> error $ "Var " ++ (show var) ++ " is a function on a previous scope!"
(Left ( V var_info ) ) -> case var_operand var_info of
Nothing -> error $ "Symbol " ++ (show var) ++ " has no operand"
Just op -> return op
(Right ( scp, V var_info) ) -> case var_operand var_info of
Nothing -> error $ "Symbol " ++ (show var) ++ " has no operand in the parent function!"
Just op -> putvar (scp_name scp) (nesting scp) var_info -- we need to put it in the scope
-- takes the nesting level in which a non local variable can be found
-- and the var_info of that function in order to add it to our own scope
putvar :: String -> Int -> VarInfo -> Codegen Operand
putvar fn_name level v_info = do
let (offset, v_name ) = (var_idx v_info, var_name v_info ) --calculate the offset for local rec
local_recover_operand <- getfun "llvm.localrecover"
func_operand <- getfun fn_name
bitcasted_func <- bitcast func_operand (ptr i8) -- bitcast the function operand to * i8 for localrecover
fp_op <- getframe level -- load the frame ptr we are looking for
recovered_op <- call local_recover_operand [bitcasted_func , fp_op ,(toInt offset) ]
op <- convert_op recovered_op v_info
addSymbol v_name (V v_info { var_operand = Just op })
return $ op
getfun :: SymbolName -> Codegen Operand
getfun fn = do
symbol <- getSymbol fn
case symbol of
V _ -> error $ "Fun " ++ (show fn) ++ " is also a variable"
F fun_info -> case fun_operand fun_info of
Nothing -> error $ "Symbol " ++ (show fn) ++ " has no operand"
Just op -> return op
init_display :: Int -> Codegen ()
init_display lvl = do
disp_info <- addVarOperand (display lvl)
addSymbol "display" (V disp_info)
putframe :: Codegen ()
putframe = do
curr_nst <- gets $ nesting . currentScope -- get current nesting level
fn_operand <- getfun "llvm.frameaddress" -- get the call opearand
frame_op <- call fn_operand [zero] -- call the function to get the frame pointer
curr_display <- getvar "display"
offseted_ptr <- create_ptr curr_display [toInt curr_nst] "display"
store offseted_ptr frame_op
return ()
getframe :: Int -> Codegen Operand
getframe idx = do
let offset = toInt idx
tbl_operand <- getvar "display"
display_pos <- create_ptr tbl_operand [offset] "display"
load display_pos
escapevars :: Codegen ()
escapevars = do
funs <- currfuns -- take all the functions in our scope
case funs of
[self] -> return () -- Leaf function
funs -> do
take the variables of the curret scope INCLUDING display
let vars = filter ( \x -> (var_type x) /= DisplayType ) vars_withdisp
let sortedVars = var_sort vars
operands < - forM sortedVars ( getvar . )
operands <- forM sortedVars escape_op
fn_operand <- getfun "llvm.localescape" -- localescape every variable in the function
call_void fn_operand operands
return ()
where
var_sort :: [VarInfo] -> [VarInfo]
var_sort = sortBy ( \a b -> compare (var_idx a) (var_idx b) )
-- recovers all function variables on the entry block of that function, using walkers
recover_vars :: S.Comp_Stmt -> Codegen ()
recover_vars (S.C_Stmt [] ) = return ()
recover_vars (S.C_Stmt stmt_list) = mapM walk_stmt stmt_list >> return ()
-- WALKERS: They traverse the whole body of a function, and only check for variable accesses
-- For every variable found, if it comes from a previous function, they make sure to use
-- local recover ON THE ENTRY BLOCK, so that the the variable is visible on every
-- function block, regarldess of control flow. They ignore everything else.
walk_stmt :: S.Stmt -> Codegen ()
walk_stmt S.Stmt_Ret = return ()
walk_stmt S.Stmt_Semi = return ()
walk_stmt (S.Stmt_Ret_Expr e1) = walk_expr e1
walk_stmt (S.Stmt_Cmp (S.C_Stmt list ) ) = mapM walk_stmt list >> return () -- THIS LINE IS WHAT REAL PAIN LOOKS LIKE
walk_stmt (S.Stmt_Eq lval expr) = walk_expr (S.Expr_Lval lval) >> walk_expr expr
walk_stmt (S.Stmt_FCall (S.Func_Call fn args)) = mapM walk_expr args >> return ()
walk_stmt (S.Stmt_If cond stmt) = walk_cond cond >> walk_stmt stmt
walk_stmt (S.Stmt_Wh cond stmt) = walk_cond cond >> walk_stmt stmt
walk_stmt (S.Stmt_IFE cond stmt1 stmt2) = do
walk_cond cond
walk_stmt stmt1
walk_stmt stmt2
walk_cond :: S.Cond -> Codegen ()
walk_cond S.Cond_True = return ()
walk_cond S.Cond_False = return ()
walk_cond (S.Cond_Br cond ) = walk_cond cond
walk_cond (S.Cond_Bang cond ) = walk_cond cond
walk_cond (S.Cond_Eq left right ) = walk_expr left>> walk_expr right
walk_cond (S.Cond_Neq left right ) = walk_expr left >> walk_expr right
walk_cond (S.Cond_L left right ) = walk_expr left >> walk_expr right
walk_cond (S.Cond_G left right ) = walk_expr left >> walk_expr right
walk_cond (S.Cond_LE left right ) = walk_expr left >> walk_expr right
walk_cond (S.Cond_GE left right ) = walk_expr left >> walk_expr right
walk_cond (S.Cond_And cond1 cond2 ) = walk_cond cond1 >> walk_cond cond2
walk_cond (S.Cond_Or cond1 cond2 ) = walk_cond cond1 >> walk_cond cond2
walk_expr :: S.Expr -> Codegen ()
walk_expr (S.Expr_Add left right) = walk_expr left >> walk_expr right
walk_expr (S.Expr_Sub left right) = walk_expr left >> walk_expr right
walk_expr (S.Expr_Tms left right) = walk_expr left>> walk_expr right
walk_expr (S.Expr_Div left right) = walk_expr left >> walk_expr right
walk_expr (S.Expr_Mod left right) = walk_expr left >> walk_expr right
walk_expr (S.Expr_Pos expr) = walk_expr expr
walk_expr (S.Expr_Neg expr) = walk_expr expr
walk_expr (S.Expr_Brack expr) = walk_expr expr
walk_expr (S.Expr_Fcall (S.Func_Call nm args) ) = mapM walk_expr args >> return ()
walk_expr (S.Expr_Lval (S.LV_Var var)) = getvar var >> return ()
walk_expr (S.Expr_Lval (S.LV_Tbl tbl_var offset_expr)) = do
walk_expr offset_expr
tbl_operand <- getvar tbl_var
-- create_ptr tbl_operand [offset] tbl_var -- WARNING MAYBE WE NEED IT?
return ()
walk_expr _ = return ()
In case of Tables , we ' alloca ' a Pointer Holder and escape that one
escape_op :: VarInfo -> Codegen Operand
escape_op vinfo
| (byreference vinfo) == False = getvar $ var_name vinfo
| otherwise = do
addr <- getvar $ var_name vinfo
ptr_holder <- allocavar (to_type tp ref) nm -- The holder of the pointer is what we escape
store ptr_holder addr >> return ptr_holder
where tp = var_type vinfo
nm = var_name vinfo
ref = byreference vinfo
Bitcasts the result of llvm.localrecover to the corect type
convert_op :: Operand -> VarInfo -> Codegen Operand
convert_op recovered_op vinfo
| ref == False = bitcast recovered_op (proper_type tp ref)
| otherwise = bitcast recovered_op (proper_type tp ref) >>= load >>= return
where tp = var_type vinfo
ref = byreference vinfo
proper_type IntType False = ptr i32
proper_type ByteType False = ptr i8
proper_type IntType True = ptr (ptr i32)
proper_type ByteType True = ptr (ptr i8)
proper_type tabletp _ = ptr $ type_to_ast tabletp
-------------------------------------------------------------------------------
-- Driver Functions for navigating the Tree
-------------------------------------------------------------------------------
-- Takes the necessary fields from a function defintion, and adds a fun_info struct to the current scope
addFunc :: SymbolName -> S.FPar_List -> S.R_Type -> Codegen FunInfo
addFunc name args_lst f_type = do
scpnm <- getScopeName
nest <- gets $ nesting . currentScope
let our_ret = getFunType f_type -- we format all of the function stuff properly
fun_args = (map createArgType args_lst) ++ (argdisplay nest name)
fn_info = createFunInfo name fun_args our_ret
fun <- addFunOperand fn_info
> add the function to our SymbolTable
return fun
addVar :: S.Var_Def -> Codegen () -- takes a VARIABLE DEFINITION , and adds the proper things, to the proper scopes
addVar vdef = do
scpnm <- getScopeName
create the new VarInfo filed to be inserted in the scope
var <- addVarOperand var_info -- NOTE: add the operand to the varinfo field
current_scope <- gets currentScope
get the current max index
update the index for
modify $ \s -> s { currentScope = (current_scope) { max_index = curr_index + 1 } }
addSymbol (var_name var_info) (V new_var)
-- Put the Function args to the function's scope, as variables
addFArgs :: S.FPar_List -> Codegen ()
addFArgs (arg:args) = do
param <- createVar_from_Arg arg
param_ready <- addArgOperand param
addSymbol (var_name param) (V param_ready)
addFArgs args
addFArgs [] = do
disp <- addArgOperand (display 0)
addSymbol "display" (V disp)
addLDef :: S.Local_Def -> Codegen ()
addLDef (S.Loc_Def_Fun fun) = cgenFuncDef fun
addLDef (S.Loc_Def_Var var) = addVar var
addLDefLst :: [S.Local_Def] -> Codegen ()
addLDefLst defs = mapM addLDef defs >> return ()
addLibraryFns :: [FunInfo] -> Codegen ()
addLibraryFns (fn:fns) = do
define $ externalFun retty label argtys vargs
addSymbol (fn_name fn) (F fn)
libfns <- gets libraryfns
modify $ \s -> s {libraryfns = label:libfns}
addLibraryFns fns
where
retty = type_to_ast (result_type fn)
label = fn_name fn
argtys = [(type_to_ast tp, Name $ toShort nm) | (nm, tp, _, _) <- (fn_args fn)]
vargs = varargs fn
addLibraryFns [] = return ()
| null | https://raw.githubusercontent.com/kimwnasptd/YAAC-Yet-Another-Alan-Compiler/73046cb21d29aaeb5ab3f83ae6ff6978d445afc8/Codegen/Emit.hs | haskell | # LANGUAGE OverloadedStrings #
-----------------------------------------------------------------------------
Compilation
-----------------------------------------------------------------------------
the optimizations we want to run
Convert ByteString -> String
-----------------------------------------------------------------------------
Codegeneration Functions
-----------------------------------------------------------------------------
> return the logger of our codegeneration
> add the local definitions of that function, this is where the recursion happens
Updates the stack frame
> close the function' s scope
we add the function to our CURRENT scope
every function creates a new scope
change the current block to the new function
add parameters to symtable
NOTE: add the function to the inside scope as well
add the local definitions of that function, this is where the recursion happens
previous functions, Then, local escape our own variables
walk the function body , recovering all needed external variables from
close the function' s scope
because we like playing with monads ...
call_void foo_operand arg_operands
return () NOTE: ASK SOMEONE
ENTRY
branch based on condition
ifthen part
------------
now instructions are added to the ifthen block
fill the block with the proper instructions
ifelse part
------------
same as ifthen block
exit part
----------
WARNING : JUST FOR TESTING , THIS IS WRONG AF
ENTRY
branch based on condition
ifthen part
------------
ifthen <- getBlock
exit part
----------
add a block to prep the loop body
add block for the loop body
add fall through loop
if the condition is true, execute the body
while entry
if the condition is true, execute the body
while body
change block
generate the loop's code
go to the loop exit
while exit
generate the left operand
generate the right operand
compare them accordingly
just generate the inner condition
generate the left condition
generate the right condition
logical AND them
reverse it
cgen_lval always returns an address operand
generate the expression for the offset
get the table operand
If an array without brackets we need to pass the pointer to the func
-----------------------------------------------------------------------------
Symbol Table and Scopes Handling
-----------------------------------------------------------------------------
we need to put it in the scope
takes the nesting level in which a non local variable can be found
and the var_info of that function in order to add it to our own scope
calculate the offset for local rec
bitcast the function operand to * i8 for localrecover
load the frame ptr we are looking for
get current nesting level
get the call opearand
call the function to get the frame pointer
take all the functions in our scope
Leaf function
localescape every variable in the function
recovers all function variables on the entry block of that function, using walkers
WALKERS: They traverse the whole body of a function, and only check for variable accesses
For every variable found, if it comes from a previous function, they make sure to use
local recover ON THE ENTRY BLOCK, so that the the variable is visible on every
function block, regarldess of control flow. They ignore everything else.
THIS LINE IS WHAT REAL PAIN LOOKS LIKE
create_ptr tbl_operand [offset] tbl_var -- WARNING MAYBE WE NEED IT?
The holder of the pointer is what we escape
-----------------------------------------------------------------------------
Driver Functions for navigating the Tree
-----------------------------------------------------------------------------
Takes the necessary fields from a function defintion, and adds a fun_info struct to the current scope
we format all of the function stuff properly
takes a VARIABLE DEFINITION , and adds the proper things, to the proper scopes
NOTE: add the operand to the varinfo field
Put the Function args to the function's scope, as variables |
module Emit where
import LLVM.AST
import LLVM.Module
import LLVM.Context
import LLVM.Prelude
import LLVM.AST.Type
import LLVM.PassManager
import LLVM.Analysis
import qualified LLVM.AST.IntegerPredicate as IPRD
import qualified LLVM.AST as AST
import qualified LLVM.AST.Constant as C
import qualified LLVM.AST.Float as F
import qualified LLVM.AST.FloatingPointPredicate as FP
import Data.Char
import Data.Word
import Data.Int
import Data.List
import Control.Monad.Except
import Control.Applicative
import Control.Monad.State
import Control.Monad
import qualified Data.ByteString.Char8 as BS8 (pack, unpack)
import qualified Data.Map as Map
import Codegen
import qualified ASTTypes as S
import SymbolTableTypes
import SemanticFunctions
import CodegenUtilities
import qualified LibraryFunctions as LIB
passes opt = defaultCuratedPassSetSpec { optLevel = Just opt }
codegen :: AST.Module -> S.Program -> Word -> IO AST.Module
codegen mod main opt = withContext $ \context ->
withModuleFromAST context newast $ \m -> do
withPassManager (passes opt) $ \pm -> do
runPassManager pm m
llstr <- moduleLLVMAssembly m
return newast
where
modn = codegenTop main
newast = runLLVM mod modn
codegenTop :: S.Program -> LLVM ()
codegenTop main = do
let codegen = execCodegen (cgen_ast main)
defs = definitions codegen
log = logger codegen
modify $ \s -> s { moduleDefinitions = defs }
cgen_ast :: S.Program -> Codegen String
cgen_ast (S.Prog main) = do
addLibraryFns LIB.lib_fns
cgen_main main
cgen_main :: S.Func_Def -> Codegen ()
cgen_main main@(S.F_Def name args_lst f_type ldef_list cmp_stmt) = do
openScope "main"
fun <- addFunc "main" [] f_type
entry <- addBlock entryBlockName
setBlock entry
putframe
escapevars
> do the Semantic analysis of the function body
cgen_stmts cmp_stmt
endblock fun
cgenFuncDef :: S.Func_Def -> Codegen ()
cgenFuncDef (S.F_Def name args_lst f_type ldef_list cmp_stmt) = do
entry <- addBlock entryBlockName
putframe
do the Semantic analysis of the function body
once the Semantic analysis has passed , gen the body
If proc , put a ret as terminator
cgen_stmts :: S.Comp_Stmt -> Codegen [()]
cgen_stmts (S.C_Stmt stmts) = mapM cgen_stmt stmts
cgen_stmt :: S.Stmt -> Codegen ()
cgen_stmt S.Stmt_Ret = ret >> return ()
cgen_stmt S.Stmt_Semi = return ()
cgen_stmt (S.Stmt_Ret_Expr e1) = cgen_expr e1 >>= retval >> return ()
cgen_stmt (S.Stmt_Cmp cmp_stmt) = cgen_stmts cmp_stmt >> return ()
cgen_stmt (S.Stmt_Eq lval expr) = do
var <- cgen_lval lval
val <- cgen_expr expr
store var val
return ()
cgen_stmt (S.Stmt_FCall (S.Func_Call fn args)) = do
F fun_info <- getSymbol fn
refs <- forM (fn_args fun_info) (\(_,_,ref,_) -> return ref)
arg_operands <- mapM cgen_arg (zip args refs)
foo_operand <- getfun fn
disp <- getvar "display"
lbr_fns <- gets libraryfns
case fn `elem` lbr_fns of
True -> call_void foo_operand arg_operands
_ -> call_void foo_operand (arg_operands ++ [disp] )
return ()
cgen_stmt (S.Stmt_IFE cond if_stmt else_stmt) = do
ifthen <- addBlock "if.then"
ifelse <- addBlock "if.else"
create the 3 blocks .
generate a 1 - bit condition
merge the block . NOTE : Fallthrough is not allowed !
get back the block for the phi node
cgen_stmt else_stmt
br ifexit
ifelse <- getBlock
merge the 2 blocks
return ()
cgen_stmt (S.Stmt_If cond if_stmt ) = do
ifthen <- addBlock "if.then"
ifexit <- addBlock "if.exit"
generate a 1 - bit condition
setBlock ifthen
cgen_stmt if_stmt
br ifexit
setBlock ifexit
return ()
cgen_stmt (S.Stmt_Wh cond loop_stmt) = do
generate the condition for the FIRST time
setBlock while_entry
generate the condition for the FIRST time
setBlock while_exit
return()
cgen_expr :: S.Expr -> Codegen AST.Operand
cgen_expr (S.Expr_Brack exp) = cgen_expr exp
cgen_expr (S.Expr_Lval lval) = cgen_lval lval >>= load
cgen_expr (S.Expr_Int int) = return $ toInt int
cgen_expr (S.Expr_Add e1 e2) = do
ce1 <- cgen_expr e1
ce2 <- cgen_expr e2
add ce1 ce2
cgen_expr (S.Expr_Sub e1 e2) = do
ce1 <- cgen_expr e1
ce2 <- cgen_expr e2
sub ce1 ce2
cgen_expr (S.Expr_Tms e1 e2) = do
ce1 <- cgen_expr e1
ce2 <- cgen_expr e2
mul ce1 ce2
cgen_expr (S.Expr_Div e1 e2) = do
ce1 <- cgen_expr e1
ce2 <- cgen_expr e2
tp <- getExprType e1
case tp of
IntType -> sdiv ce1 ce2
ByteType -> udiv ce1 ce2
cgen_expr (S.Expr_Mod e1 e2) = do
ce1 <- cgen_expr e1
ce2 <- cgen_expr e2
tp <- getExprType e1
case tp of
IntType -> srem ce1 ce2
ByteType -> urem ce1 ce2
cgen_expr (S.Expr_Fcall (S.Func_Call fn args ) ) = do
F fun_info <- getSymbol fn
refs <- forM (fn_args fun_info) (\(_,_,ref,_) -> return ref)
arg_operands <- mapM cgen_arg (zip args refs)
foo_operand <- getfun fn
disp <- getvar "display"
lbr_fns <- gets libraryfns
case fn `elem` lbr_fns of
True -> call foo_operand arg_operands
_ -> call foo_operand (arg_operands ++ [disp] )
cgen_expr (S.Expr_Char ch_str) = do
return $ toChar (head ch_str)
cgen_expr (S.Expr_Pos expr ) = cgen_expr expr
cgen_expr(S.Expr_Neg expr ) = do
ce <- cgen_expr expr
sub zero ce
cgen_cond :: S.Cond -> Codegen AST.Operand
cgen_cond (S.Cond_Eq left right ) = do
cgen_cond (S.Cond_Neq left right ) = do
left_op <- cgen_expr left
right_op <- cgen_expr right
cmp IPRD.NE left_op right_op
cgen_cond (S.Cond_G left right ) = do
left_op <- cgen_expr left
right_op <- cgen_expr right
cmp IPRD.SGT left_op right_op
cgen_cond (S.Cond_L left right ) = do
left_op <- cgen_expr left
right_op <- cgen_expr right
cmp IPRD.SLT left_op right_op
cgen_cond (S.Cond_GE left right ) = do
left_op <- cgen_expr left
right_op <- cgen_expr right
cmp IPRD.SGE left_op right_op
cgen_cond (S.Cond_LE left right ) = do
left_op <- cgen_expr left
right_op <- cgen_expr right
cmp IPRD.SLE left_op right_op
cgen_cond (S.Cond_True) = return true
cgen_cond (S.Cond_False) = return false
cgen_cond (S.Cond_And first second ) = do
cgen_cond (S.Cond_Or first second ) = do
fst_op <- cgen_cond first
snd_op <- cgen_cond second
or_instr fst_op snd_op
cgen_cond (S.Cond_Bang arg ) = do
generate the 1 bit boolean inside condition
cgen_lval :: S.L_Value -> Codegen AST.Operand
cgen_lval (S.LV_Var var) = getvar var
cgen_lval (S.LV_Tbl tbl_var offset_expr) = do
create_ptr tbl_operand [offset] tbl_var
cgen_lval (S.LV_Lit str) = do
globStrName <- freshStr
define $ globalStr globStrName str
let op = externstr (Name $ toShort globStrName) (str_type str)
bitcast op (ptr i8)
cgen_arg :: (S.Expr, Bool) -> Codegen Operand
cgen_arg ((S.Expr_Lval lval), False) = cgen_lval lval >>= load
cgen_arg ((S.Expr_Lval lval), True ) = cgen_lval lval
cgen_arg (expr, _) = cgen_expr expr
getvar :: SymbolName -> Codegen Operand
getvar var = do
symbol <- getSymbol_enhanced var
case symbol of
(Left (F _ ) ) -> error $ "Var " ++ (show var) ++ " is also a function on the current scope!"
(Right ( _, F _ ) ) -> error $ "Var " ++ (show var) ++ " is a function on a previous scope!"
(Left ( V var_info ) ) -> case var_operand var_info of
Nothing -> error $ "Symbol " ++ (show var) ++ " has no operand"
Just op -> return op
(Right ( scp, V var_info) ) -> case var_operand var_info of
Nothing -> error $ "Symbol " ++ (show var) ++ " has no operand in the parent function!"
putvar :: String -> Int -> VarInfo -> Codegen Operand
putvar fn_name level v_info = do
local_recover_operand <- getfun "llvm.localrecover"
func_operand <- getfun fn_name
recovered_op <- call local_recover_operand [bitcasted_func , fp_op ,(toInt offset) ]
op <- convert_op recovered_op v_info
addSymbol v_name (V v_info { var_operand = Just op })
return $ op
getfun :: SymbolName -> Codegen Operand
getfun fn = do
symbol <- getSymbol fn
case symbol of
V _ -> error $ "Fun " ++ (show fn) ++ " is also a variable"
F fun_info -> case fun_operand fun_info of
Nothing -> error $ "Symbol " ++ (show fn) ++ " has no operand"
Just op -> return op
init_display :: Int -> Codegen ()
init_display lvl = do
disp_info <- addVarOperand (display lvl)
addSymbol "display" (V disp_info)
putframe :: Codegen ()
putframe = do
curr_display <- getvar "display"
offseted_ptr <- create_ptr curr_display [toInt curr_nst] "display"
store offseted_ptr frame_op
return ()
getframe :: Int -> Codegen Operand
getframe idx = do
let offset = toInt idx
tbl_operand <- getvar "display"
display_pos <- create_ptr tbl_operand [offset] "display"
load display_pos
escapevars :: Codegen ()
escapevars = do
case funs of
funs -> do
take the variables of the curret scope INCLUDING display
let vars = filter ( \x -> (var_type x) /= DisplayType ) vars_withdisp
let sortedVars = var_sort vars
operands < - forM sortedVars ( getvar . )
operands <- forM sortedVars escape_op
call_void fn_operand operands
return ()
where
var_sort :: [VarInfo] -> [VarInfo]
var_sort = sortBy ( \a b -> compare (var_idx a) (var_idx b) )
recover_vars :: S.Comp_Stmt -> Codegen ()
recover_vars (S.C_Stmt [] ) = return ()
recover_vars (S.C_Stmt stmt_list) = mapM walk_stmt stmt_list >> return ()
walk_stmt :: S.Stmt -> Codegen ()
walk_stmt S.Stmt_Ret = return ()
walk_stmt S.Stmt_Semi = return ()
walk_stmt (S.Stmt_Ret_Expr e1) = walk_expr e1
walk_stmt (S.Stmt_Eq lval expr) = walk_expr (S.Expr_Lval lval) >> walk_expr expr
walk_stmt (S.Stmt_FCall (S.Func_Call fn args)) = mapM walk_expr args >> return ()
walk_stmt (S.Stmt_If cond stmt) = walk_cond cond >> walk_stmt stmt
walk_stmt (S.Stmt_Wh cond stmt) = walk_cond cond >> walk_stmt stmt
walk_stmt (S.Stmt_IFE cond stmt1 stmt2) = do
walk_cond cond
walk_stmt stmt1
walk_stmt stmt2
walk_cond :: S.Cond -> Codegen ()
walk_cond S.Cond_True = return ()
walk_cond S.Cond_False = return ()
walk_cond (S.Cond_Br cond ) = walk_cond cond
walk_cond (S.Cond_Bang cond ) = walk_cond cond
walk_cond (S.Cond_Eq left right ) = walk_expr left>> walk_expr right
walk_cond (S.Cond_Neq left right ) = walk_expr left >> walk_expr right
walk_cond (S.Cond_L left right ) = walk_expr left >> walk_expr right
walk_cond (S.Cond_G left right ) = walk_expr left >> walk_expr right
walk_cond (S.Cond_LE left right ) = walk_expr left >> walk_expr right
walk_cond (S.Cond_GE left right ) = walk_expr left >> walk_expr right
walk_cond (S.Cond_And cond1 cond2 ) = walk_cond cond1 >> walk_cond cond2
walk_cond (S.Cond_Or cond1 cond2 ) = walk_cond cond1 >> walk_cond cond2
walk_expr :: S.Expr -> Codegen ()
walk_expr (S.Expr_Add left right) = walk_expr left >> walk_expr right
walk_expr (S.Expr_Sub left right) = walk_expr left >> walk_expr right
walk_expr (S.Expr_Tms left right) = walk_expr left>> walk_expr right
walk_expr (S.Expr_Div left right) = walk_expr left >> walk_expr right
walk_expr (S.Expr_Mod left right) = walk_expr left >> walk_expr right
walk_expr (S.Expr_Pos expr) = walk_expr expr
walk_expr (S.Expr_Neg expr) = walk_expr expr
walk_expr (S.Expr_Brack expr) = walk_expr expr
walk_expr (S.Expr_Fcall (S.Func_Call nm args) ) = mapM walk_expr args >> return ()
walk_expr (S.Expr_Lval (S.LV_Var var)) = getvar var >> return ()
walk_expr (S.Expr_Lval (S.LV_Tbl tbl_var offset_expr)) = do
walk_expr offset_expr
tbl_operand <- getvar tbl_var
return ()
walk_expr _ = return ()
In case of Tables , we ' alloca ' a Pointer Holder and escape that one
escape_op :: VarInfo -> Codegen Operand
escape_op vinfo
| (byreference vinfo) == False = getvar $ var_name vinfo
| otherwise = do
addr <- getvar $ var_name vinfo
store ptr_holder addr >> return ptr_holder
where tp = var_type vinfo
nm = var_name vinfo
ref = byreference vinfo
Bitcasts the result of llvm.localrecover to the corect type
convert_op :: Operand -> VarInfo -> Codegen Operand
convert_op recovered_op vinfo
| ref == False = bitcast recovered_op (proper_type tp ref)
| otherwise = bitcast recovered_op (proper_type tp ref) >>= load >>= return
where tp = var_type vinfo
ref = byreference vinfo
proper_type IntType False = ptr i32
proper_type ByteType False = ptr i8
proper_type IntType True = ptr (ptr i32)
proper_type ByteType True = ptr (ptr i8)
proper_type tabletp _ = ptr $ type_to_ast tabletp
addFunc :: SymbolName -> S.FPar_List -> S.R_Type -> Codegen FunInfo
addFunc name args_lst f_type = do
scpnm <- getScopeName
nest <- gets $ nesting . currentScope
fun_args = (map createArgType args_lst) ++ (argdisplay nest name)
fn_info = createFunInfo name fun_args our_ret
fun <- addFunOperand fn_info
> add the function to our SymbolTable
return fun
addVar vdef = do
scpnm <- getScopeName
create the new VarInfo filed to be inserted in the scope
current_scope <- gets currentScope
get the current max index
update the index for
modify $ \s -> s { currentScope = (current_scope) { max_index = curr_index + 1 } }
addSymbol (var_name var_info) (V new_var)
addFArgs :: S.FPar_List -> Codegen ()
addFArgs (arg:args) = do
param <- createVar_from_Arg arg
param_ready <- addArgOperand param
addSymbol (var_name param) (V param_ready)
addFArgs args
addFArgs [] = do
disp <- addArgOperand (display 0)
addSymbol "display" (V disp)
addLDef :: S.Local_Def -> Codegen ()
addLDef (S.Loc_Def_Fun fun) = cgenFuncDef fun
addLDef (S.Loc_Def_Var var) = addVar var
addLDefLst :: [S.Local_Def] -> Codegen ()
addLDefLst defs = mapM addLDef defs >> return ()
addLibraryFns :: [FunInfo] -> Codegen ()
addLibraryFns (fn:fns) = do
define $ externalFun retty label argtys vargs
addSymbol (fn_name fn) (F fn)
libfns <- gets libraryfns
modify $ \s -> s {libraryfns = label:libfns}
addLibraryFns fns
where
retty = type_to_ast (result_type fn)
label = fn_name fn
argtys = [(type_to_ast tp, Name $ toShort nm) | (nm, tp, _, _) <- (fn_args fn)]
vargs = varargs fn
addLibraryFns [] = return ()
|
ee0f5ba5dd6509724ad3d320864c6591f660bd65ab4e4ba3ef3cb1337d249040 | RDTK/generator | protocol.lisp | ;;;; protocol.lisp --- Protocol provided by the project module.
;;;;
Copyright ( C ) 2012 - 2019 Jan Moringen
;;;;
Author : < >
(cl:in-package #:build-generator.model)
;;; Ancestors protocol
(defgeneric parent (thing)
(:documentation
"Return the parent of THING or NIL."))
(defgeneric ancestors (thing)
(:documentation
"Return a list of ancestors of THING, including THING."))
;;; Default behavior
(defmethod ancestors ((thing t))
(list* thing
(when-let ((parent (and (compute-applicable-methods
#'parent (list thing))
(parent thing))))
(ancestors parent))))
;;; Named and ancestors protocol
(defgeneric ancestor-names (thing)
(:documentation
"Return a list of the names of the ancestors of THING.
The firsts element of the returned list is the name of THING, the
second element (if any) is the name of the parent of THING,
etc."))
;;; Default behavior
(defmethod ancestor-names ((thing t))
(list* (let ((name (name thing)))
(if (emptyp name)
"<empty>"
name))
(when-let ((parent (and (compute-applicable-methods
#'parent (list thing))
(parent thing))))
(ancestor-names parent))))
;;; Dependencies protocol
(defgeneric direct-dependencies (thing)
(:documentation
"Return a list of direct (as opposed to transitive) dependencies of
THING."))
(defgeneric dependencies (thing)
(:documentation
"Return a duplicate-free list of transitive dependencies of
THING."))
(defgeneric minimal-dependencies (thing)
(:documentation
"Return a list of direct dependencies of THING that are not also
transitive dependencies of the direct dependencies of THING."))
;; Default behavior
(defmethod dependencies ((thing t))
(let+ ((result '())
((&labels one-thing (thing)
(dolist (dependency (direct-dependencies thing))
(unless (member dependency result :test #'eq)
(push dependency result)
(one-thing dependency))))))
(one-thing thing)
result))
(defmethod minimal-dependencies ((thing t))
(let* ((direct-dependencies (direct-dependencies thing))
(indirect (reduce #'union direct-dependencies
:key #'dependencies
:initial-value '())))
(set-difference direct-dependencies indirect)))
;;; Access protocol
(defgeneric access (object)
(:documentation
"Return the access specification for OBJECT, either :private
or :public."))
(defgeneric check-access (object lower-bound)
(:documentation
"Return true if OBJECT permits at least the level of access
indicates by LOWER-BOUND. If OBJECT does not permit the access,
return nil and a optionally a condition instance describing the
reason as a second value."))
(defmethod access ((object t))
(var:value/cast object :access :public))
(defmethod check-access ((object t) (lower-bound t))
t)
(defmethod check-access ((object t) (lower-bound (eql :public)))
(eq (access object) lower-bound))
;;; Instantiation protocol
(defgeneric instantiate? (spec parent)
(:documentation
"Return non-nil when SPEC should be instantiated."))
(defgeneric instantiate (spec &key parent specification-parent)
(:documentation
"Instantiate the specification SPEC and return the created
object.
Signal `instantiation-condition's such as `instantiation-error'
when conditions such as errors are encountered."))
(defgeneric add-dependencies! (thing &key providers)
(:documentation
"TODO(jmoringe): document"))
;; Default behavior
(defmethod instantiate? ((spec t) (parent t))
t)
(defmethod instantiate :around ((spec t) &key parent specification-parent)
(declare (ignore parent specification-parent))
(with-condition-translation
(((error instantiation-error)
:specification spec))
(with-simple-restart (continue "~@<Skip instantiation of ~A.~@:>" spec)
(let ((implementation (call-next-method)))
(unless (eq (specification implementation) spec)
(setf (%specification implementation) spec))
(push implementation (implementations spec))
(assert implementation)
implementation))))
(defmethod add-dependencies! :around ((thing t) &key providers)
(declare (ignore providers))
(with-condition-translation
(((error instantiation-error)
:specification (specification thing)))
(with-simple-restart (continue "~@<Skip adding dependencies to ~A.~@:>"
thing)
(call-next-method))))
;;; Implementation protocol
(defgeneric specification (implementation)
(:documentation
"Return the specification according to which IMPLEMENTATION has
been created."))
;;; Specification protocol
(defgeneric implementation (specification)
(:documentation
"Return the implementation that has been created according to
SPECIFICATION.
Asserts that there is exactly one implementation of
SPECIFICATION."))
(defgeneric implementations (specification)
(:documentation
"Return all implementations that have been created according to
SPECIFICATION."))
| null | https://raw.githubusercontent.com/RDTK/generator/8d9e6e47776f2ccb7b5ed934337d2db50ecbe2f5/src/model/protocol.lisp | lisp | protocol.lisp --- Protocol provided by the project module.
Ancestors protocol
Default behavior
Named and ancestors protocol
Default behavior
Dependencies protocol
Default behavior
Access protocol
Instantiation protocol
Default behavior
Implementation protocol
Specification protocol | Copyright ( C ) 2012 - 2019 Jan Moringen
Author : < >
(cl:in-package #:build-generator.model)
(defgeneric parent (thing)
(:documentation
"Return the parent of THING or NIL."))
(defgeneric ancestors (thing)
(:documentation
"Return a list of ancestors of THING, including THING."))
(defmethod ancestors ((thing t))
(list* thing
(when-let ((parent (and (compute-applicable-methods
#'parent (list thing))
(parent thing))))
(ancestors parent))))
(defgeneric ancestor-names (thing)
(:documentation
"Return a list of the names of the ancestors of THING.
The firsts element of the returned list is the name of THING, the
second element (if any) is the name of the parent of THING,
etc."))
(defmethod ancestor-names ((thing t))
(list* (let ((name (name thing)))
(if (emptyp name)
"<empty>"
name))
(when-let ((parent (and (compute-applicable-methods
#'parent (list thing))
(parent thing))))
(ancestor-names parent))))
(defgeneric direct-dependencies (thing)
(:documentation
"Return a list of direct (as opposed to transitive) dependencies of
THING."))
(defgeneric dependencies (thing)
(:documentation
"Return a duplicate-free list of transitive dependencies of
THING."))
(defgeneric minimal-dependencies (thing)
(:documentation
"Return a list of direct dependencies of THING that are not also
transitive dependencies of the direct dependencies of THING."))
(defmethod dependencies ((thing t))
(let+ ((result '())
((&labels one-thing (thing)
(dolist (dependency (direct-dependencies thing))
(unless (member dependency result :test #'eq)
(push dependency result)
(one-thing dependency))))))
(one-thing thing)
result))
(defmethod minimal-dependencies ((thing t))
(let* ((direct-dependencies (direct-dependencies thing))
(indirect (reduce #'union direct-dependencies
:key #'dependencies
:initial-value '())))
(set-difference direct-dependencies indirect)))
(defgeneric access (object)
(:documentation
"Return the access specification for OBJECT, either :private
or :public."))
(defgeneric check-access (object lower-bound)
(:documentation
"Return true if OBJECT permits at least the level of access
indicates by LOWER-BOUND. If OBJECT does not permit the access,
return nil and a optionally a condition instance describing the
reason as a second value."))
(defmethod access ((object t))
(var:value/cast object :access :public))
(defmethod check-access ((object t) (lower-bound t))
t)
(defmethod check-access ((object t) (lower-bound (eql :public)))
(eq (access object) lower-bound))
(defgeneric instantiate? (spec parent)
(:documentation
"Return non-nil when SPEC should be instantiated."))
(defgeneric instantiate (spec &key parent specification-parent)
(:documentation
"Instantiate the specification SPEC and return the created
object.
Signal `instantiation-condition's such as `instantiation-error'
when conditions such as errors are encountered."))
(defgeneric add-dependencies! (thing &key providers)
(:documentation
"TODO(jmoringe): document"))
(defmethod instantiate? ((spec t) (parent t))
t)
(defmethod instantiate :around ((spec t) &key parent specification-parent)
(declare (ignore parent specification-parent))
(with-condition-translation
(((error instantiation-error)
:specification spec))
(with-simple-restart (continue "~@<Skip instantiation of ~A.~@:>" spec)
(let ((implementation (call-next-method)))
(unless (eq (specification implementation) spec)
(setf (%specification implementation) spec))
(push implementation (implementations spec))
(assert implementation)
implementation))))
(defmethod add-dependencies! :around ((thing t) &key providers)
(declare (ignore providers))
(with-condition-translation
(((error instantiation-error)
:specification (specification thing)))
(with-simple-restart (continue "~@<Skip adding dependencies to ~A.~@:>"
thing)
(call-next-method))))
(defgeneric specification (implementation)
(:documentation
"Return the specification according to which IMPLEMENTATION has
been created."))
(defgeneric implementation (specification)
(:documentation
"Return the implementation that has been created according to
SPECIFICATION.
Asserts that there is exactly one implementation of
SPECIFICATION."))
(defgeneric implementations (specification)
(:documentation
"Return all implementations that have been created according to
SPECIFICATION."))
|
16f3725c83636a7e13b67b6bdc1687f1b42f4989479346cd1c7725dff0595f57 | ccfontes/eg | user.clj | (ns user
(:require [clojure.tools.namespace.repl :refer [refresh]]
[clojure.test :as test :refer [deftest is]]
[clojure.spec.alpha :as spec]
[eg :as eg :refer [eg ge ex]]
[eg.spec :as eg-spec]
[eg.test.fixtures :as fixtures]
[eg.test.pass.unit]
[eg.test.pass.integration]))
(defn run-tests []
(refresh)
(test/run-tests 'eg.test.pass.unit 'eg.test.pass.integration 'user))
(intern 'eg 'refresh refresh)
(intern 'eg.platform 'refresh refresh)
(intern 'eg 'run-tests run-tests)
(intern 'eg.platform 'run-tests run-tests)
| null | https://raw.githubusercontent.com/ccfontes/eg/b46796b3e1fc07d835673900dbed927fa51925cf/repl/user.clj | clojure | (ns user
(:require [clojure.tools.namespace.repl :refer [refresh]]
[clojure.test :as test :refer [deftest is]]
[clojure.spec.alpha :as spec]
[eg :as eg :refer [eg ge ex]]
[eg.spec :as eg-spec]
[eg.test.fixtures :as fixtures]
[eg.test.pass.unit]
[eg.test.pass.integration]))
(defn run-tests []
(refresh)
(test/run-tests 'eg.test.pass.unit 'eg.test.pass.integration 'user))
(intern 'eg 'refresh refresh)
(intern 'eg.platform 'refresh refresh)
(intern 'eg 'run-tests run-tests)
(intern 'eg.platform 'run-tests run-tests)
|
|
0689d63db11fac5ec7f79ff557dccdd00ea0387b34982119802a01fb2330795d | runeksvendsen/restful-payment-channel-server | Handler.hs | module AppPrelude.Types.Handler where
import qualified Control.Monad.Reader as Reader
import qualified Servant
-- |We use this monad for the handlers, which gives access to configuration data
-- of type 'conf'.
type AppM conf = Reader.ReaderT conf Servant.Handler
| null | https://raw.githubusercontent.com/runeksvendsen/restful-payment-channel-server/0fe65eadccad5ef2b840714623ec407e509ad00b/src/AppPrelude/Types/Handler.hs | haskell | |We use this monad for the handlers, which gives access to configuration data
of type 'conf'. | module AppPrelude.Types.Handler where
import qualified Control.Monad.Reader as Reader
import qualified Servant
type AppM conf = Reader.ReaderT conf Servant.Handler
|
175573168ce6230f9aee3afc30156c6d0730f4bc240fe19d4b2afb4f165af06c | ytomino/headmaster | c_lexical_output.ml | open C_lexical;;
open C_literals;;
module type LexicalOutputType = sig
module Literals: LiteralsType
module LexicalElement: LexicalElementType
with module Literals := Literals
val print_element: (string -> unit) -> LexicalElement.t -> unit
end;;
module LexicalOutput
(Literals: LiteralsType)
(LexicalElement: LexicalElementType
with module Literals := Literals)
: LexicalOutputType
with module Literals := Literals
with module LexicalElement := LexicalElement =
struct
open Literals;;
let print_element (print_string: string -> unit) (e: LexicalElement.t): unit = (
let image =
begin match e with
implies # extended_word
string_of_rw w
| #objc_directive as w ->
string_of_objcdirective w
| #preprocessor_word as w ->
string_of_ppw w
| #preprocessor_directive as w ->
"#" ^ string_of_ppdirective w
| `directive_parameter s ->
s
| `end_of_line ->
"\n"
| `ident w ->
w
| `numeric_literal (_, `int_literal (prec, value)) ->
Integer.to_based_string ~base:10 value ^
begin match prec with
| `signed_char -> ""
| `unsigned_char -> ""
| `signed_short -> ""
| `unsigned_short -> ""
| `signed_int -> ""
| `unsigned_int -> "U"
| `signed_long -> "L"
| `unsigned_long -> "UL"
| `signed_long_long -> "LL"
| `unsigned_long_long -> "ULL"
| `__int128_t | `__uint128_t -> assert false (* no suffix *)
end
| `numeric_literal (_, `float_literal (prec, value)) ->
let m, e = Real.frexp value in
"0x" ^
Real.to_based_string ~base:16 m ^
"P" ^
string_of_int e ^
begin match prec with
| `float -> "F"
| `double -> ""
| `long_double -> "L"
| `_Float32 -> "f32"
| `_Float64 -> "f64"
| `_Float128 -> "f128"
| `_Float32x -> "f32x"
| `_Float64x -> "f64x"
end
| `numeric_literal (_, `imaginary_literal (prec, value)) ->
let m, e = Real.frexp value in
"0x" ^
Real.to_based_string ~base:16 m ^
"P" ^
string_of_int e ^
begin match prec with
| `float -> "FI"
| `double -> "I"
| `long_double -> "LI"
end
| `numeric_literal (s, `decimal_literal _) ->
s
| `char_literal s ->
"\'" ^ Char.escaped s ^ "\'"
| `chars_literal s ->
"\"" ^ String.escaped s ^ "\""
| `wchar_literal s ->
"L\'\\x" ^ Hexadecimal.x4u (Int32.of_int (WideChar.to_int s)) ^ "\'"
| `wchars_literal s ->
let length = WideString.length s in
let buf = Buffer.create (length * 6 + 3) in
Buffer.add_string buf "L\"";
for i = 0 to length do
Buffer.add_string buf "\\x";
Buffer.add_string buf
(Hexadecimal.x4u (Int32.of_int (WideChar.to_int (WideString.get s i))))
done;
Buffer.add_char buf '\"';
Buffer.contents buf
| `objc_string_literal s ->
"@\"" ^ String.escaped s ^ "\""
| `l_paren ->
"("
| `r_paren ->
")"
| `l_bracket ->
"["
| `r_bracket ->
"]"
| `l_curly ->
"{"
| `r_curly ->
"}"
| `period ->
"."
| `arrow ->
"->"
| `increment ->
"++"
| `decrement ->
"--"
| `ampersand ->
"&"
| `asterisk ->
"*"
| `plus ->
"+"
| `minus ->
"-"
| `tilde ->
"~"
| `exclamation ->
"!"
| `slash ->
"/"
| `percent ->
"%"
| `l_shift ->
"<<"
| `r_shift ->
">>"
| `lt ->
"<"
| `gt ->
">"
| `le ->
"<="
| `ge ->
">="
| `eq ->
"=="
| `ne ->
"!="
| `caret ->
"^"
| `vertical ->
"|"
| `and_then ->
"&&"
| `or_else ->
"||"
| `question ->
"?"
| `colon ->
":"
| `semicolon ->
";"
| `varargs ->
"..."
| `assign ->
"="
| `mul_assign ->
"*="
| `div_assign ->
"/="
| `rem_assign ->
"%="
| `add_assign ->
"+="
| `sub_assign ->
"-="
| `l_shift_assign ->
"<<="
| `r_shift_assign ->
">>="
| `and_assign ->
"&="
| `xor_assign ->
"^="
| `or_assign ->
"|="
| `comma ->
","
| `backslash ->
"\\"
| `sharp ->
"#"
| `d_sharp ->
"##"
| `d_colon ->
"::"
| `period_ref ->
".*"
| `arrow_ref ->
"->*"
end
in
print_string image
);;
end;;
| null | https://raw.githubusercontent.com/ytomino/headmaster/11571992e480aa9fbc5821fe1be1b62edf5f924f/source/c_lexical_output.ml | ocaml | no suffix | open C_lexical;;
open C_literals;;
module type LexicalOutputType = sig
module Literals: LiteralsType
module LexicalElement: LexicalElementType
with module Literals := Literals
val print_element: (string -> unit) -> LexicalElement.t -> unit
end;;
module LexicalOutput
(Literals: LiteralsType)
(LexicalElement: LexicalElementType
with module Literals := Literals)
: LexicalOutputType
with module Literals := Literals
with module LexicalElement := LexicalElement =
struct
open Literals;;
let print_element (print_string: string -> unit) (e: LexicalElement.t): unit = (
let image =
begin match e with
implies # extended_word
string_of_rw w
| #objc_directive as w ->
string_of_objcdirective w
| #preprocessor_word as w ->
string_of_ppw w
| #preprocessor_directive as w ->
"#" ^ string_of_ppdirective w
| `directive_parameter s ->
s
| `end_of_line ->
"\n"
| `ident w ->
w
| `numeric_literal (_, `int_literal (prec, value)) ->
Integer.to_based_string ~base:10 value ^
begin match prec with
| `signed_char -> ""
| `unsigned_char -> ""
| `signed_short -> ""
| `unsigned_short -> ""
| `signed_int -> ""
| `unsigned_int -> "U"
| `signed_long -> "L"
| `unsigned_long -> "UL"
| `signed_long_long -> "LL"
| `unsigned_long_long -> "ULL"
end
| `numeric_literal (_, `float_literal (prec, value)) ->
let m, e = Real.frexp value in
"0x" ^
Real.to_based_string ~base:16 m ^
"P" ^
string_of_int e ^
begin match prec with
| `float -> "F"
| `double -> ""
| `long_double -> "L"
| `_Float32 -> "f32"
| `_Float64 -> "f64"
| `_Float128 -> "f128"
| `_Float32x -> "f32x"
| `_Float64x -> "f64x"
end
| `numeric_literal (_, `imaginary_literal (prec, value)) ->
let m, e = Real.frexp value in
"0x" ^
Real.to_based_string ~base:16 m ^
"P" ^
string_of_int e ^
begin match prec with
| `float -> "FI"
| `double -> "I"
| `long_double -> "LI"
end
| `numeric_literal (s, `decimal_literal _) ->
s
| `char_literal s ->
"\'" ^ Char.escaped s ^ "\'"
| `chars_literal s ->
"\"" ^ String.escaped s ^ "\""
| `wchar_literal s ->
"L\'\\x" ^ Hexadecimal.x4u (Int32.of_int (WideChar.to_int s)) ^ "\'"
| `wchars_literal s ->
let length = WideString.length s in
let buf = Buffer.create (length * 6 + 3) in
Buffer.add_string buf "L\"";
for i = 0 to length do
Buffer.add_string buf "\\x";
Buffer.add_string buf
(Hexadecimal.x4u (Int32.of_int (WideChar.to_int (WideString.get s i))))
done;
Buffer.add_char buf '\"';
Buffer.contents buf
| `objc_string_literal s ->
"@\"" ^ String.escaped s ^ "\""
| `l_paren ->
"("
| `r_paren ->
")"
| `l_bracket ->
"["
| `r_bracket ->
"]"
| `l_curly ->
"{"
| `r_curly ->
"}"
| `period ->
"."
| `arrow ->
"->"
| `increment ->
"++"
| `decrement ->
"--"
| `ampersand ->
"&"
| `asterisk ->
"*"
| `plus ->
"+"
| `minus ->
"-"
| `tilde ->
"~"
| `exclamation ->
"!"
| `slash ->
"/"
| `percent ->
"%"
| `l_shift ->
"<<"
| `r_shift ->
">>"
| `lt ->
"<"
| `gt ->
">"
| `le ->
"<="
| `ge ->
">="
| `eq ->
"=="
| `ne ->
"!="
| `caret ->
"^"
| `vertical ->
"|"
| `and_then ->
"&&"
| `or_else ->
"||"
| `question ->
"?"
| `colon ->
":"
| `semicolon ->
";"
| `varargs ->
"..."
| `assign ->
"="
| `mul_assign ->
"*="
| `div_assign ->
"/="
| `rem_assign ->
"%="
| `add_assign ->
"+="
| `sub_assign ->
"-="
| `l_shift_assign ->
"<<="
| `r_shift_assign ->
">>="
| `and_assign ->
"&="
| `xor_assign ->
"^="
| `or_assign ->
"|="
| `comma ->
","
| `backslash ->
"\\"
| `sharp ->
"#"
| `d_sharp ->
"##"
| `d_colon ->
"::"
| `period_ref ->
".*"
| `arrow_ref ->
"->*"
end
in
print_string image
);;
end;;
|
f0b3eee217e1893020d26e12a0b74272dacfef2086a842a8691212a1f26e8fbc | kappelmann/engaging-large-scale-functional-programming | Test.hs | # LANGUAGE CPP #
module Test where
import qualified Interface as Sub
import qualified Solution as Sol
import Test.Tasty
import Test.Tasty.Runners.AntXML
import Test.Tasty.QuickCheck as QC
import Control.Monad
import qualified Mock.System.IO.Internal as Mock
import System.Environment (setEnv)
getAverage s i j ps =
let filtered = [p | (n,t,p) <- ps, n == s, t >= i, t <= j]
in if null filtered then 0 else sum filtered `div` length filtered
genStock = elements ["BB","BBY","AMC","GME"]
genTicker = do
n <- genStock
t <- choose (0,100) :: Gen Int
p <- choose (0,100) :: Gen Int
return (n,t,p)
genTickers = listOf genTicker
-- We show the console dump if the test fails and fail the test if an error occurs
wrapConsoleProp io = do
hook <- Mock.hookConsole
r <- Mock.tryIO io
consoleDump <- fmap (\d -> "\n=== CONSOLE DUMP ===\n" ++ d ++ "\n=== END CONSOLE DUMP ===\n") (Mock.showConsoleHook hook)
let p' = case r of
Right p -> counterexample consoleDump p
Left e -> counterexample (showError e) $ counterexample consoleDump (property False)
return p'
where
showError e = if Mock.isUserError e
then "### " ++ Mock.ioeGetErrorString e ++ "\n"
else "\n### IO Exception thrown: " ++ show e ++ "\n"
prop_stocks' s i j ps = Mock.evalIO wrappedIo Mock.emptyWorld
where
wrappedIo = wrapConsoleProp $ Mock.setUser user >> Sub.main >> Mock.runUser
getContentS = do
b <- Mock.hIsEOF Mock.stdout
if b then return [] else liftM2 (:) (Mock.hGetLine Mock.stdout) getContentS
user = do
Mock.hPutStrLn Mock.stdin (unwords [s, show (i, j)])
mapM_ (Mock.hPutStrLn Mock.stdin) $ map (\(n,t,p) -> n ++ "," ++ show t ++ "," ++ show p) ps
Mock.hPutStrLn Mock.stdin "quit"
Mock.wait -- this transfers control to the submission code
output <- unlines <$> getContentS
let expected = getAverage s i j ps
when (read output /= expected)
(fail ("### Wrong result. \n### Expected output: " ++ show expected ++ "\n### Actual output: " ++ output))
prop_stocks =
QC.forAll genStock $ \s ->
QC.forAll (choose (0,20) :: Gen Int) $ \i ->
QC.forAll (choose (15,50) :: Gen Int) $ \j ->
QC.forAll genTickers $ \ps ->
prop_stocks' s i j ps
stonksProps :: TestTree
stonksProps = testGroup "Stonks" [
localOption (QC.QuickCheckMaxSize 100) $ QC.testProperty "testing stonks main against sample solution" prop_stocks
]
tests :: TestTree
tests = testGroup "Tests" [stonksProps]
main = do
-- set the default output file path as expected by bamboo
-- the path can be overwritten by passing --xml=<pathGoesHere>
setEnv "TASTY_XML" resultsPath
testRunner $ localOption timeoutOption tests
where
resultsPath = "test-reports/results.xml"
#ifdef PROD
-- on the server (production mode), run tests with xml output
testRunner = defaultMainWithIngredients [antXMLRunner]
#else
-- locally, run tests with terminal output
testRunner = defaultMain
#endif
by default , run for 1 second
timeoutOption = mkTimeout (10 * 10^6)
| null | https://raw.githubusercontent.com/kappelmann/engaging-large-scale-functional-programming/28905255605b55353de2d06239f79448c6fe4230/resources/io_mocking/stocks/test/Test.hs | haskell | We show the console dump if the test fails and fail the test if an error occurs
this transfers control to the submission code
set the default output file path as expected by bamboo
the path can be overwritten by passing --xml=<pathGoesHere>
on the server (production mode), run tests with xml output
locally, run tests with terminal output | # LANGUAGE CPP #
module Test where
import qualified Interface as Sub
import qualified Solution as Sol
import Test.Tasty
import Test.Tasty.Runners.AntXML
import Test.Tasty.QuickCheck as QC
import Control.Monad
import qualified Mock.System.IO.Internal as Mock
import System.Environment (setEnv)
getAverage s i j ps =
let filtered = [p | (n,t,p) <- ps, n == s, t >= i, t <= j]
in if null filtered then 0 else sum filtered `div` length filtered
genStock = elements ["BB","BBY","AMC","GME"]
genTicker = do
n <- genStock
t <- choose (0,100) :: Gen Int
p <- choose (0,100) :: Gen Int
return (n,t,p)
genTickers = listOf genTicker
wrapConsoleProp io = do
hook <- Mock.hookConsole
r <- Mock.tryIO io
consoleDump <- fmap (\d -> "\n=== CONSOLE DUMP ===\n" ++ d ++ "\n=== END CONSOLE DUMP ===\n") (Mock.showConsoleHook hook)
let p' = case r of
Right p -> counterexample consoleDump p
Left e -> counterexample (showError e) $ counterexample consoleDump (property False)
return p'
where
showError e = if Mock.isUserError e
then "### " ++ Mock.ioeGetErrorString e ++ "\n"
else "\n### IO Exception thrown: " ++ show e ++ "\n"
prop_stocks' s i j ps = Mock.evalIO wrappedIo Mock.emptyWorld
where
wrappedIo = wrapConsoleProp $ Mock.setUser user >> Sub.main >> Mock.runUser
getContentS = do
b <- Mock.hIsEOF Mock.stdout
if b then return [] else liftM2 (:) (Mock.hGetLine Mock.stdout) getContentS
user = do
Mock.hPutStrLn Mock.stdin (unwords [s, show (i, j)])
mapM_ (Mock.hPutStrLn Mock.stdin) $ map (\(n,t,p) -> n ++ "," ++ show t ++ "," ++ show p) ps
Mock.hPutStrLn Mock.stdin "quit"
output <- unlines <$> getContentS
let expected = getAverage s i j ps
when (read output /= expected)
(fail ("### Wrong result. \n### Expected output: " ++ show expected ++ "\n### Actual output: " ++ output))
prop_stocks =
QC.forAll genStock $ \s ->
QC.forAll (choose (0,20) :: Gen Int) $ \i ->
QC.forAll (choose (15,50) :: Gen Int) $ \j ->
QC.forAll genTickers $ \ps ->
prop_stocks' s i j ps
stonksProps :: TestTree
stonksProps = testGroup "Stonks" [
localOption (QC.QuickCheckMaxSize 100) $ QC.testProperty "testing stonks main against sample solution" prop_stocks
]
tests :: TestTree
tests = testGroup "Tests" [stonksProps]
main = do
setEnv "TASTY_XML" resultsPath
testRunner $ localOption timeoutOption tests
where
resultsPath = "test-reports/results.xml"
#ifdef PROD
testRunner = defaultMainWithIngredients [antXMLRunner]
#else
testRunner = defaultMain
#endif
by default , run for 1 second
timeoutOption = mkTimeout (10 * 10^6)
|
0ff54d8e38dc657cb37e874ff1e9218ad01f18c05ed9aaf9d307ff0dc52f9fb6 | parsonsmatt/gear-tracker | DB.hs | -- | This namespace contains all database access code for the project.
module GT.DB where
| null | https://raw.githubusercontent.com/parsonsmatt/gear-tracker/b7a597b32322e8938192a443572e6735219ce8ff/src/GT/DB.hs | haskell | | This namespace contains all database access code for the project. | module GT.DB where
|
e704ddc6d7e6a1c6eb0419064c3632ce0b06eab6a9e16388cc9a5073abbb2ff3 | uw-unsat/serval | bitfield-move.rkt | #lang racket/base
(require "lib.rkt")
(define tests
(test-suite+ "Bitfield move"
(arm64-case* [choose-sf choose-imm6 choose-imm6 choose-reg choose-reg]
sbfm
bfm
ubfm)
Shift ( immediate ) , aliases of sbfm / ubfm
(arm64-case* [choose-sf choose-imm6 choose-reg choose-reg]
; no ror yet
asr
lsl
lsr)
Sign - extend and Zero - extend , of sbfm / ubfm
(arm64-case* [choose-sf choose-reg choose-reg]
sxtb
sxth)
(arm64-case* [choose-reg choose-reg]
sxtw
uxtb
uxth)
))
(module+ test
(time (run-tests tests)))
| null | https://raw.githubusercontent.com/uw-unsat/serval/be11ecccf03f81b8bd0557acf8385a6a5d4f51ed/test/arm64/bitfield-move.rkt | racket | no ror yet | #lang racket/base
(require "lib.rkt")
(define tests
(test-suite+ "Bitfield move"
(arm64-case* [choose-sf choose-imm6 choose-imm6 choose-reg choose-reg]
sbfm
bfm
ubfm)
Shift ( immediate ) , aliases of sbfm / ubfm
(arm64-case* [choose-sf choose-imm6 choose-reg choose-reg]
asr
lsl
lsr)
Sign - extend and Zero - extend , of sbfm / ubfm
(arm64-case* [choose-sf choose-reg choose-reg]
sxtb
sxth)
(arm64-case* [choose-reg choose-reg]
sxtw
uxtb
uxth)
))
(module+ test
(time (run-tests tests)))
|
95703f538eb53755a43a09f3fa3321554d02fb578f9149537146a869cde9b500 | LambdaScientist/CLaSH-by-example | SimpleInOut.hs | # LANGUAGE DataKinds #
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
# LANGUAGE NoImplicitPrelude #
module InAndOut.Models.SimpleInOut where
import CLaSH.Prelude
import Control.Lens hiding ((:>))
import Control.Monad.Trans.State
import SAFE.TestingTools
import SAFE.CommonClash
import Text.PrettyPrint.HughesPJClass
import GHC.Generics (Generic)
import Control.DeepSeq
--inputs
data PIn = PIn { _in1 :: Bit
, _in2 :: Bit
, _in3 :: Bit
} deriving (Eq, Show)
instance NFData PIn where
rnf a = seq a ()
--Outputs and state data
data St = St { _out1 :: Bit
, _out2 :: Bit
} deriving (Eq, Show)
makeLenses ''St
instance NFData St where
rnf a = seq a ()
procSimple :: St -> PIn -> St
procSimple st@St{..} PIn{..} = flip execState st $ do
out1 .= (_in1 .&. _in2 .&. _in3)
out2 .= (_in1 .|. _in2 .|. _in3)
topEntity :: Signal PIn -> Signal St
topEntity = topEntity' st
where
st = St 0 0
topEntity' :: St -> Signal PIn -> Signal St--Signal st
topEntity' st pin = reg
where
reg = register st (procSimple <$> reg <*> pin)
- The following code is only for a custom testing framework , and PrettyPrinted output
instance PortIn PIn
instance Pretty PIn where
pPrint PIn {..} = text "PIn:"
$+$ text "_in1 =" <+> showT _in1
$+$ text "_in2 =" <+> showT _in2
$+$ text "_in3 =" <+> showT _in3
instance SysState St
instance Pretty St where
pPrint St {..} = text "St"
$+$ text "_out1 =" <+> showT _out1
$+$ text "_out2 =" <+> showT _out2
| null | https://raw.githubusercontent.com/LambdaScientist/CLaSH-by-example/e783cd2f2408e67baf7f36c10398c27036a78ef3/ConvertedClashExamples/src/InAndOut/Models/SimpleInOut.hs | haskell | inputs
Outputs and state data
Signal st | # LANGUAGE DataKinds #
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
# LANGUAGE NoImplicitPrelude #
module InAndOut.Models.SimpleInOut where
import CLaSH.Prelude
import Control.Lens hiding ((:>))
import Control.Monad.Trans.State
import SAFE.TestingTools
import SAFE.CommonClash
import Text.PrettyPrint.HughesPJClass
import GHC.Generics (Generic)
import Control.DeepSeq
data PIn = PIn { _in1 :: Bit
, _in2 :: Bit
, _in3 :: Bit
} deriving (Eq, Show)
instance NFData PIn where
rnf a = seq a ()
data St = St { _out1 :: Bit
, _out2 :: Bit
} deriving (Eq, Show)
makeLenses ''St
instance NFData St where
rnf a = seq a ()
procSimple :: St -> PIn -> St
procSimple st@St{..} PIn{..} = flip execState st $ do
out1 .= (_in1 .&. _in2 .&. _in3)
out2 .= (_in1 .|. _in2 .|. _in3)
topEntity :: Signal PIn -> Signal St
topEntity = topEntity' st
where
st = St 0 0
topEntity' st pin = reg
where
reg = register st (procSimple <$> reg <*> pin)
- The following code is only for a custom testing framework , and PrettyPrinted output
instance PortIn PIn
instance Pretty PIn where
pPrint PIn {..} = text "PIn:"
$+$ text "_in1 =" <+> showT _in1
$+$ text "_in2 =" <+> showT _in2
$+$ text "_in3 =" <+> showT _in3
instance SysState St
instance Pretty St where
pPrint St {..} = text "St"
$+$ text "_out1 =" <+> showT _out1
$+$ text "_out2 =" <+> showT _out2
|
ce668219565f8aad50a8aba9dc67378310dc5e75451ca16ccc29b2646a6a4fd9 | c4-project/c4f | common.mli | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
(** Common functionality for regress tests *)
open Core
val regress_on_files :
string
-> dir:Fpath.t
-> ext:string
-> f:(file:Fpath.t -> path:Fpath.t -> unit Or_error.t)
-> unit Or_error.t
val make_regress_command :
(Fpath.t -> unit Or_error.t) -> summary:string -> Command.t
| null | https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/regress_tests/common.mli | ocaml | * Common functionality for regress tests | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Core
val regress_on_files :
string
-> dir:Fpath.t
-> ext:string
-> f:(file:Fpath.t -> path:Fpath.t -> unit Or_error.t)
-> unit Or_error.t
val make_regress_command :
(Fpath.t -> unit Or_error.t) -> summary:string -> Command.t
|
8b3db0c27c2db3c2228365b2ac861fe296e36a4be8e8da4465fd1bb89aa14fdd | horie-t/iacc-riscv | compiler.scm | (import (srfi 1))
(import (rnrs hashtables))
(load "test_cases.scm")
;;;; ユーティリティ関数
;;; 書式と引数を取って表示し、改行を付け加えます。
例 : ( emit " addi t0 , t0 , ~s " 1 )
addi t0 , t0 , 1
;; が表示されます。
(define (emit . args)
(apply format #t args)
(newline))
;;; ユニーク・ラベル生成
;; 重複のない、ラベルを返します。
(define unique-label
(let ((count 0))
(lambda ()
(let ((L (string->symbol (format "L_~s" count)))) ; シンボルに変換する必要はある?
(set! count (+ count 1))
L))))
;;; ユニーク・ラベルのリストを生成します。
;; vars ラベルの一部を形成する文字のリスト
(define (unique-labels vars)
(map (lambda (var)
(format "~a_~s" (unique-label) var))
vars))
ユニーク変数生成
;; 重複のない、変数名を返します。
(define unique-name
既に出現した名前と、出現回数の連想リスト。例 : ( ( x . 1 ) ( a . 3 ) ( cnt . 2 ) )
(lambda (name)
(let ((entry (assv name counts)))
(cond
(entry
(let* ((count (cdr entry))
(new-name (string->symbol (format "~s_~s" name count))))
(set-cdr! entry (+ count 1))
new-name))
(else
(set! counts (cons (cons name 1) counts))
name))))))
;;; 値比較ユーティリティ
;; a0と値を比較し、booleanオブジェクトをa0に設定します。
;; args 比較する即値、省略時はt0と比較
(define (emit-cmp-bool . args)
(if (null? args)
(emit " sub a0, a0, t0")
(emit " addi a0, a0, ~s" (- (car args))))
(emit " seqz a0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
;;; 式の書式判定ユーティリティ
( tag .... )
(define (tagged-form? tag expr)
(and (list? expr) (not (null? expr)) (eq? (car expr) tag)))
;;;; スタック関連
;;; スタックに値を保存します。
;; si スタック・インデックス
(define (emit-stack-save si)
(emit " sw a0, ~s(sp)" si))
(define (emit-stack-load si)
(emit " lw a0, ~s(sp)" si))
(define (emit-stack-load-t0 si)
(emit " lw t0, ~s(sp)" si))
;;; 次のスタックインデックスを返します。
(define (next-stack-index si)
(- si wordsize))
;;; スタック・ポインタを移動させます。
(define (emit-adjust-base si)
(emit " addi sp, sp, ~s" si))
;;;; 環境関連
;;; 環境を生成します。
;; bindings 初期値。 '((a -8) (b -9))のような、シンボル、スタック・インデックスのリストのリスト。
(define (make-initial-env bindings)
bindings)
;;; binding部分を生成します。
(define (bind lhs rhs)
(list lhs rhs))
bindingの束縛されるシンボル(left hand side)を返します
(define (lhs expr)
(car expr))
bindingの値(right hand side)を返します
(define (rhs expr)
(cadr expr))
;;; 環境に変数を追加します。
var 変数のシンボル
;; si スタック・インデックス
;; env 変数を追加する環境
(define (extend-env var si env)
(cons (list var si) env))
;;; 環境に変数を追加します。
(define (bulk-extend-env vars vals env)
(append (map list vars vals) env))
;;; 環境から変数の値を検索します
(define (lookup var env)
(cond
((assv var env)
(cadr (assv var env)))
(else #f)))
;;;; オブジェクト型情報定義: タグ付きポインタ表現を使う
;;; 整数: 下位2ビットが00、上位30ビットが符号付き整数となっている
整数変換シフト量
(define fxmask #x03) ; 整数判定ビットマスク(ANDを取って0なら整数オブジェクト)
(define fxtag #0x0) ;
;;; boolean:
(define bool_f #x2f) ; #fの数値表現
(define bool_t #x6f) ; #t
(define boolmask #xbf) ; boolean判定ビットマスク(ANDを取ってis_boolならbooleanオブジェクト)
(define is_bool #x2f) ;
(define bool_bit 6) ; booleanの判定用ビット位置
;;; 空リスト:
(define empty_list #x3f) ;
(define emptymask #xff) ;
文字 :
(define charmask #xff) ; char判定ビットマスク(ANDを取って、chartagならchar)
(define chartag #x0f) ; charタグ
(define charshift 8) ; char変換シフト量
(define wordsize 4) ; 32bit(4バイト)
word数 - > バイト数
(define fixnum-bits (- (* wordsize 8) fxshift))
(define fxlower (- (expt 2 (- fixnum-bits 1))))
(define fxupper (- (expt 2 (- fixnum-bits 1))
1))
(define (fixnum? x)
(and (integer? x) (exact? x) (<= fxlower x fxupper)))
;;;; 即値関連関数
;;; 即値かどうかを返します。
(define (immediate? x)
(or (fixnum? x) (boolean? x) (char? x) (null? x)))
;;; Schemeの即値から、アセンブリ言語でのオブジェクト表現を返します。
(define (immediate-rep x)
(cond
((fixnum? x) (ash x fxshift))
((eq? x #f) bool_f)
((eq? x #t) bool_t)
((char? x) (logior (ash (char->integer x) charshift) chartag))
((null? x) empty_list)
(else (error "invalid immediate"))))
即値表現から、アセンブリ言語を出力します 。
(define (emit-immediate expr)
(let ((imm (immediate-rep expr)))
(when (>= imm 4096)
(emit " lui a0, ~s" (ash imm -12)))
(emit " li a0, ~s" imm)))
;;;; グローバル・プロバティ
(define *prop* (make-eq-hashtable))
(define (getprop x property)
(let ((prop (hashtable-ref *prop* x #f)))
(if prop
(hashtable-ref prop property #f)
#f)))
(define (putprop x property val)
(let ((entry (hashtable-ref *prop* x #f)))
(if entry
(hashtable-set! entry property val)
(hashtable-set! *prop*
x
(let ((entry (make-eq-hashtable)))
(hashtable-set! entry property val)
entry)))))
プリミティブ関連
;;; プリミティブ定義(*porp*にプリミティブ関連の情報を追加)
;; 例: (define-primitive (fxadd1 arg)
;; 出力内容 ...)
(define-syntax define-primitive
(syntax-rules ()
((_ (prime-name si env arg* ...) body body* ...)
(begin
(putprop 'prime-name '*is-prime* #t)
(putprop 'prime-name '*arg-count
(length '(arg* ...)))
(putprop 'prime-name '*emmiter*
(lambda (si env arg* ...)
body body* ...))))))
;;; 引数が基本演算かどうかを返します。
; xは、add1のようにシンボルで、*is-prime*が#tにセットされている必要がある
(define (primitive? x)
(and (symbol? x) (getprop x '*is-prime*)))
(define (primitive-emitter x)
(or (getprop x '*emmiter*) (error "primitive-emitter: not exist emmiter")))
;;;; 単項演算関連
;;; 単項演算呼び出し(単項演算処理)かどうかを返します。
;; 単項演算呼び出しは(op arg)の形式なので、最初はpairで、carがprimitive?がtrueを返すものでなければならない。
(define (primcall? expr)
(and (pair? expr) (primitive? (car expr))))
(define (emit-primcall si env expr)
(let ((prim (car expr))
(args (cdr expr)))
(apply (primitive-emitter prim) si env args)))
引数に1を加えた値を返します
(define-primitive (fxadd1 si env arg)
(emit-expr si env arg)
(emit " addi a0, a0, ~s" (immediate-rep 1)))
引数から1を引いた値を返します
(define-primitive (fxsub1 si env arg)
(emit-expr si env arg)
(emit " addi a0, a0, ~s" (immediate-rep -1)))
(define-primitive (fixnum->char si env arg)
(emit-expr si env arg)
(emit " slli a0, a0, ~s" (- charshift fxshift))
(emit " ori a0, a0, ~s" chartag))
;;; charからfixnumに変換します。
(define-primitive (char->fixnum si env arg)
(emit-expr si env arg)
(emit " srli a0, a0, ~s" (- charshift fxshift)))
;;; fixnumかどうかを返します
(define-primitive (fixnum? si env arg)
(emit-expr si env arg)
(emit " andi a0, a0, ~s" fxmask)
(emit-cmp-bool fxtag))
;;; 空リストかどうかを返します
(define-primitive (null? si env arg)
(emit-expr si env arg)
(emit " andi a0, a0, ~s" emptymask)
(emit-cmp-bool empty_list))
;;; booleanオブジェクトかどうかを返します
(define-primitive (boolean? si env arg)
(emit-expr si env arg)
(emit " andi a0, a0, ~s" boolmask)
(emit-cmp-bool is_bool))
;;; 文字オブジェクトかどうかを返します
(define-primitive (char? si env arg)
(emit-expr si env arg)
(emit " andi a0, a0, ~s" charmask)
(emit-cmp-bool chartag))
;;; #fなら#tを返し、それ以外は#fを返します。
(define-primitive (not si env arg)
(emit-expr si env arg)
(emit-cmp-bool bool_f))
;;;
(define-primitive (fxlognot si env arg)
(emit-expr si env arg)
(emit " xori a0, a0, ~s" (immediate-rep -1)))
;;;; 二項基本演算
;;; 二項基本演算ユーティリティ
arg1、arg2を評価し、結果をそれぞれt0、a0レジスタに代入します
(define (emit-binop si env arg1 arg2)
(emit-expr si env arg1)
(emit-stack-save si) ; 結果をスタックに一時退避
(emit-expr (next-stack-index si) env arg2)
(emit-stack-load-t0 si)) ; スタックに退避した値をt0に復元
;;; 整数加算
siは、stack indexの略。siが指す先は、空き領域にしてから呼び出す事
(emit-binop si env arg1 arg2)
(emit " add a0, a0, t0"))
;;; 整数減算
(define-primitive (fx- si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit " sub a0, t0, a0"))
;;; 整数積
(define-primitive (fx* si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit " sra a0, a0, ~s" fxshift)
(emit " mul a0, t0, a0"))
;;; 整数ビット論理積
(define-primitive (fxlogand si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit " and a0, a0, t0"))
;;; 整数ビット論理和
(define-primitive (fxlogor si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit " or a0, a0, t0"))
整数等号
(define-primitive (fx= si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit-cmp-bool))
整数小なり
(define-primitive (fx< si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit " slt a0, t0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
;;; 整数以下
(define-primitive (fx<= si env arg1 arg2)
(emit-expr si env (list 'fx< arg2 arg1)) ; 大なりを判定して、あとで否定する
(emit " xori a0, a0, ~s" (ash 1 bool_bit)))
;;; 整数大なり
(define-primitive (fx> si env arg1 arg2)
(emit-expr si env (list 'fx< arg2 arg1))) ; 引数を逆にして、小なりを使う
;;; 整数以上
(define-primitive (fx>= si env arg1 arg2)
(emit-expr si env (list 'fx< arg1 arg2)) ; 小なりを判定して、あとで否定する
(emit " xori a0, a0, ~s" (ash 1 bool_bit)))
;;; 文字等号
(define-primitive (char= si env arg1 arg2)
型判定をしていないので、fx = と同じ内容。eq?をこれにしてOKかも
(emit-cmp-bool))
整数小なり
(define-primitive (char< si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit " slt a0, t0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
;;; 整数以下
(define-primitive (char<= si env arg1 arg2)
(emit-expr si env (list 'char< arg2 arg1)) ; 大なりを判定して、あとで否定する
(emit " xori a0, a0, ~s" (ash 1 bool_bit)))
;;; 整数大なり
(define-primitive (char> si env arg1 arg2)
(emit-expr si env (list 'char< arg2 arg1))) ; 引数を逆にして、小なりを使う
;;; 整数以上
(define-primitive (char>= si env arg1 arg2)
(emit-expr si env (list 'char< arg1 arg2)) ; 小なりを判定して、あとで否定する
(emit " xori a0, a0, ~s" (ash 1 bool_bit)))
;;;; 特殊形式関連
;;; 特殊形式、プリミティブのシンボルかどうかを判定します。
(define (special? symbol)
(or (member symbol '(if begin let lambda closure set!))
(primitive? symbol)))
;;;; 条件式
if形式
;;; if形式かどうかを返します
(define (if? expr)
(and (tagged-form? 'if expr)
(or (= (length (cdr expr)) 3)
(error "if? " (format #t "malformed if ~s" expr)))))
;;; if形式の述部(predicate)を取り出します。
(define (if-test expr)
(cadr expr))
;;; if形式の帰結部(consequent)を取り出します。
(define (if-conseq expr)
(caddr expr))
;;; if形式の代替部(alternative)を取り出します。
(define (if-altern expr)
(cadddr expr))
;;; if形式の出力
(define (emit-if si env tail expr)
(let ((alt-label (unique-label))
(end-label (unique-label)))
(emit-expr si env (if-test expr))
(emit " addi a0, a0, ~s" (- bool_f))
(emit " beqz a0, ~a" alt-label)
(emit-any-expr si env tail (if-conseq expr))
(if (not tail) (emit " j ~a" end-label))
(emit "~a:" alt-label)
(emit-any-expr si env tail (if-altern expr))
(emit "~a:" end-label)))
;;; and形式
(define (and? expr)
(tagged-form? 'and expr))
(define (emit-and si env expr)
(let ((pred-len (length (cdr expr))))
(cond
((= pred-len 0)
引数なしなら常に真
((= pred-len 1)
(emit-primcall si env (list 'not (cadr expr))) ; まず、(not test)の式に変換して評価する
(emit " xori a0, a0, ~s" (ash 1 bool_bit))) ; a0は偽かどうかの値なので、ビット反転でnotを演算する
(else
;; (and test test* ...) => (if test (and test* ...) #f)と変換して処理
(emit-if si env #f (list 'if (cadr expr)
(cons 'and (cddr expr))
#f))))))
;;; or形式
(define (or? expr)
(tagged-form? 'or expr))
(define (emit-or si env expr)
(let ((pred-len (length (cdr expr))))
(cond
((= pred-len 0)
(emit " li a0, ~s" bool_f)) ;引数なしなら常に偽
((= pred-len 1)
(emit-primcall si env (list 'not (cadr expr))) ; まず、(not test)の式に変換して評価する
(emit " xori a0, a0, ~s" (ash 1 bool_bit))) ; a0は偽かどうかの値なので、ビット反転でnotを演算する
(else
;; (or test test* ...) => (if test #t (or test* ...))と変換して処理
(emit-if si env #f (list 'if (cadr expr)
#t
(cons 'or (cddr expr))))))))
let形式
;;; let形式かどうかを返します
(define (let? expr)
(tagged-form? 'let expr))
;;; letの形式の詳細を返します。
(define (let-kind expr)
(car expr))
(define (let-bindings expr)
(cadr expr))
(define make-let list)
;;; let形式のbody部分を返します。body部分が複数の式からなる時は、begin形式に変換します
(define (let-body expr)
(if (null? (cdddr expr))
(caddr expr)
(make-begin (cddr expr))))
(define (let-body-seq expr)
(cddr expr))
(define (emit-let si env tail expr)
(define (process-let bindings si new-env)
(cond
((null? bindings)
(emit-any-expr si new-env tail (let-body expr)))
(else
(let ((b (car bindings)))
(emit-expr si env (rhs b))
(emit-stack-save si)
(process-let (cdr bindings)
(next-stack-index si)
(extend-env (lhs b) si new-env))))))
(process-let (let-bindings expr) si env))
;;;; let*形式
;;; let*形式かどうかを返します。
(define (let*? expr)
(tagged-form? 'let* expr))
;;;
;; let*は、letの入れ子に書き換えてしまう。
;; 例)
( let * ( ( x 1 ) ) ( let ( ( x 1 ) )
( let * ( ( x ( fx+ x 1 ) ) = > ( let ( ( x ( fx+ x 1 ) ) )
( y ( fx+ x 1 ) ) ) ( let ( ( y ( fx+ x 1 ) ) )
;; y)) y)))
(define (emit-let* si env tail expr)
(emit-any-expr si env tail
(let ((bindings (let-bindings expr))
(body (let-body expr)))
(cond
((<= (length bindings) 1)
(list 'let bindings
body))
(else
(list 'let (list (car bindings))
(list 'let* (cdr bindings)
body)))))))
;;;; letrec形式
letrec形式かどうかを返します 。
(define (letrec? expr)
(or (tagged-form? 'letrec expr) (tagged-form? 'letrec* expr)))
;;; let系形式のどれかか、どうかを返します。
(define (any-let? expr)
(and (pair? expr)
(member (car expr) '(let let* letrec))))
begin形式
;;; begin形式かどうかを返します。
(define (begin? expr)
(tagged-form? 'begin expr))
(define (emit-begin si env tail expr)
(emit-seq si env tail (cdr expr)))
;; 連続した式を出力します
seq 連続した式。例 : ( ( set - car ! some - pair 7 ) ( set - cdr ! come - pair 5 ) some - pair )
(define (emit-seq si env tail seq)
(cond
((null? seq) (error "empty seq"))
((null? (cdr seq)) ; 連続式の末尾の場合
(emit-any-expr si env tail (car seq)))
連続式の途中の場合
(emit-expr si env (car seq))
(emit-seq si env tail (cdr seq)))))
(define (make-begin lst)
(if (null? (cdr lst))
(car lst)
(cons 'begin lst)))
(define (make-body lst)
(make-begin lst))
;;;; 変数参照関連
;; 変数の表現書式は以下の3通りあります。
;; 数値: スタック上の変数
;; ('free offset): 自由変数。offsetは、クロージャ・オブジェクト内でのオフセット
;; シンボル: クロージャを指している
;;; 変数かどうかを返します。
(define (variable? expr)
(symbol? expr))
;;; 自由変数を作成します。
;; offset クロージャ・オブジェクト内でのオフセット
(define (free-var offset)
(list 'free (- offset closuretag)))
;;; 変数が自由変数かどうかを判定します。
;; var 判定対象変数
(define (free-var? var)
(tagged-form? 'free var))
;;; 式の中から自由変数を取得します。
(define (get-free-vars expr)
(cond
((variable? expr)
(list expr))
((lambda? expr)
(filter (lambda (v)
(not (member v (cadr expr))))
(get-free-vars (caddr expr))))
((let? expr)
(append (append-map get-free-vars (map cadr (let-bindings expr)))
(filter (lambda (v)
(not (member v (map car (let-bindings expr)))))
(get-free-vars (let-body expr)))))
((list? expr)
(append-map get-free-vars (if (and (not (null? expr))
(special? (car expr)))
(cdr expr)
expr)))
(else '())))
;;;
(define (emit-variable-ref si env var)
(cond
((lookup var env)
(let ((v (lookup var env)))
(cond
((free-var? v)
(emit " lw a0, ~s(a1)" (cadr v)))
((number? v)
(emit-stack-load v))
(else (error "emit-variable-ref. "
(format #t "looked up unknown value ~s for var ~s" v var))))))
(else (error "emit-variable-ref. " (format "undefined variable ~s" var)))))
;;;; set!関連
;;; set!特殊形式かどうかを返します
(define (set? expr)
(tagged-form? 'set! expr))
;;; set!特殊形式を生成します。
lhs ( left hand side )
;; rhs (right hand side)
(define (make-set! lhs rhs)
(list 'set! lhs rhs))
;;; set!特殊形式の代入されるシンボルを返します
(define (set-lhs expr)
(cadr expr))
;;; set!特殊形式の代入する式を返します。
(define (set-rhs expr)
(caddr expr))
;;;; lambda特殊形式
;;; lamda特殊形式かどうかを返します。
(define (lambda? expr)
(tagged-form? 'lambda expr))
(define (lambda-formals expr)
(cadr expr))
;;; lambda特殊形式の本体部分を返します。
(define (lambda-body expr)
(make-body (cddr expr)))
;;; lambda特殊形式を生成します。
formals
;; body 本体
(define (make-lambda formals body)
(list 'lambda formals body))
;;;; code特殊形式
(define (make-code formals free-vars body)
(list 'code formals free-vars body))
(define (emit-code env)
(lambda (expr label)
(emit-function-header label)
(emit " addi sp, sp, ~s" (- wordsize))
(emit " sw ra, 0(sp)")
(let ((formals (cadr expr))
(free-vars (caddr expr))
(body (cadddr expr)))
(extend-env-with (- wordsize) env formals
(lambda (si env)
(close-env-with wordsize env free-vars
(lambda (env)
(emit-tail-expr si env body))))))))
;;; 手続き呼び出しの引数で環境を拡張して、kを実行します。
;; k 拡張された環境で実行したい手続き? thunk?
(define (extend-env-with si env lvars k)
(if (null? lvars)
(k si env)
(extend-env-with (next-stack-index si)
(extend-env (car lvars) si env)
(cdr lvars)
k)))
;;; 自由変数で環境を拡張して、kを実行します。 (closure対応に必要)
;; offset クロージャ・オブジェクトの開始アドレスからのオフセット
lvars 自由変数のリスト
(define (close-env-with offset env lvars k)
(if (null? lvars)
(k env)
(close-env-with (+ offset wordsize)
(extend-env (car lvars) (free-var offset) env)
(cdr lvars)
k)))
;;;; app関連
apply可能かどうか
(define (app? expr env)
(and (list? expr) (not (null? expr))))
;;; applyの出力
;; si スタック・インデックス(stack index)
;; env 環境(environment)。変数や関数の名前と、アクセスするための位置情報のリスト
tail
;; expr lambda式(expression)
(define (emit-app si env tail expr)
;;; 呼び出し先の引数をスタックに積む
(define (emit-arguments si args)
(unless (null? args)
(emit-expr si env (car args))
(emit-stack-save si)
(emit-arguments (- si wordsize) (cdr args))))
;;; 末尾呼び出しの場合は、引数を自分の関数のスタックに移動する
;; delta 移動量
(define (move-arguments si delta args)
(unless (or (= delta 0) (null? args))
(emit-stack-load si)
(emit-stack-save (+ si delta))
(move-arguments (- si wordsize) delta (cdr args))))
(cond
((not tail)
(emit-arguments (- si (* 2 wordsize)) (cdr expr))
(emit-expr si env (car expr))
(emit " sw a1, ~s(sp)" si)
(emit " mv a1, a0")
(emit-heap-load (- closuretag))
(emit-adjust-base si)
(emit-call)
(emit-adjust-base (- si))
(emit " lw a1, ~s(sp)" si))
(else ; tail
(emit-arguments si (cdr expr))
(emit-expr (- si (* wordsize (length (cdr expr)))) env (car expr))
(emit " mv a1, a0")
(move-arguments si (- (+ si wordsize)) (cdr expr))
(emit " mv a0, a1")
(emit-heap-load (- closuretag))
(emit-jmp-tail))))
;;; Scheme手続きに対応する、アセンブリ言語のラベルを返します。見つからなかった場合は#fを返します。
(define (proc expr env)
(and (variable? expr)
(let ((val (lookup expr env)))
(and (symbol? val) val))))
;;;; ヒープ領域オブジェクト関連
(define objshift 2)
(define objmask #x07)
;;; ヒープメモリ確保時の最低サイズ(バイト)
(define heap-cell-size (ash 1 objshift))
;;; ヒープメモリを確保します。確保したアドレスはa0に設定
size 確保するバイト数
(define (emit-heap-alloc size)
(let ((alloc-size (* (+ (div (- size 1) heap-cell-size) 1) heap-cell-size)))
(emit " mv a0, s0")
(emit " addi s0, s0, ~s" alloc-size)))
;;; 動的にヒープ・メモリを確保します。確保するバイト数はa0にセットして呼び出します。
(define (emit-heap-alloc-dynamic)
(emit " addi a0, a0, -1")
(emit " srai a0, a0, ~s" objshift)
(emit " addi a0, a0, 1")
(emit " slli a0, a0, ~s" objshift)
(emit " mv t0, a0")
(emit " mv a0, s0")
(emit " add s0, s0, t0"))
;;; スタックの値をヒープにコピーします。
;; si コピー元の値のスタックインデックス
;; offset a0+offset のアドレスに値をコピーします。
(define (emit-stack-to-heap si offset)
(emit " lw t0, ~s(sp)" si)
(emit " sw t0, ~s(a0)" offset))
;;; ヒープの値をa0に読み込みます。
;; offset a0+offset のアドレスの値を読み込みます
(define (emit-heap-load offset)
(emit " lw a0, ~s(a0)" offset))
;;; オブジェクトの型判定をします。
(define (emit-object? tag si env arg)
(emit-expr si env arg)
(emit " andi a0, a0, ~s" objmask)
(emit-cmp-bool tag))
;;;; eq?
(define-primitive (eq? si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit-cmp-bool))
;;;; ペア関連
(define pairtag #b001) ; ペアのタグ
(define pairsize 8) ; ペアのメモリサイズ(バイト)
(define paircar 0) ; ペア中のcar部分のオフセット
(define paircdr 4) ; ペア中のcdr部分のオフセット
;;; cons
(define-primitive (cons si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit-stack-save (next-stack-index si))
(emit-heap-alloc pairsize)
(emit " ori a0, a0, ~s" pairtag)
(emit-stack-to-heap si (- paircar pairtag))
(emit-stack-to-heap (next-stack-index si) (- paircdr pairtag)))
;;; pair?
(define-primitive (pair? si env arg)
(emit-object? pairtag si env arg))
;;; car
(define-primitive (car si env arg)
(emit-expr si env arg)
(emit-heap-load (- paircar pairtag)))
;;; cdr
(define-primitive (cdr si env arg)
(emit-expr si env arg)
(emit-heap-load (- paircdr pairtag)))
;;; set-car!
(define-primitive (set-car! si env cell val)
(emit-binop si env val cell)
(emit-stack-to-heap si (- paircar pairtag)))
;;; set-cdr!
(define-primitive (set-cdr! si env cell val)
(emit-binop si env val cell)
(emit-stack-to-heap si (- paircdr pairtag)))
;;;; ベクトル関連
(define vectortag #x05) ; ベクトルのタグ
length ベクトルの要素数
(define-primitive (make-vector si env length)
(emit-expr si env length)
(emit-stack-save si)
(emit " addi a0, a0, ~s" (ash 1 fxshift)) ; 要素数+1のセルを確保する。+1はlengthデータ保存用
(emit " slli a0, a0, ~s" wordshift) ; 要素数 -> バイト数へ変換
(emit-heap-alloc-dynamic)
(emit-stack-to-heap si 0)
(emit " ori a0, a0, ~s" vectortag))
;;; ベクトルかどうかを返します。
(define-primitive (vector? si env arg)
(emit-object? vectortag si env arg))
;;; ベクトルの要素数を返します。
(define-primitive (vector-length si env arg)
(emit-expr si env arg)
(emit-heap-load (- vectortag))) ; タグの値の分だけアドレスをずらす
;;; ベクトルに値をセットします。
;; vector セットされるベクトル
;; index セットする位置
;; value セットする値
(define-primitive (vector-set! si env vector index value)
(emit-expr si env index)
(emit " addi a0, a0, ~s" (ash 1 fxshift)) ; index=0の位置には長さが入っているのでずれる。
(emit " slli a0, a0, ~s" (- objshift fxshift))
(emit-stack-save si)
(emit-expr-save (next-stack-index si) env value)
(emit-expr si env vector)
(emit-stack-load-t0 si)
(emit " add a0, a0, t0")
(emit-stack-to-heap (next-stack-index si) (- vectortag)))
ベクトルの要素の値を取得します 。
(define-primitive (vector-ref si env vector index)
(emit-expr si env index)
(emit " addi a0, a0, ~s" (ash 1 fxshift)) ; index=0の位置には長さが入っているのでずれる。
(emit " slli a0, a0, ~s" (- objshift fxshift))
(emit-stack-save si)
(emit-expr si env vector)
(emit-stack-load-t0 si)
(emit " add a0, a0, t0")
(emit-heap-load (- vectortag)))
;;;; 文字列関連
(define stringtag #x06)
;;; 文字列を作成します。
(define-primitive (make-string si env length)
(emit-expr-save si env length)
(emit " srai a0, a0, ~s" fxshift)
(emit " addi a0, a0, ~s" wordsize)
(emit-heap-alloc-dynamic)
(emit-stack-to-heap si 0)
(emit " ori a0, a0, ~s" stringtag))
;;; 文字列かどうかを返します。
(define-primitive (string? si env arg)
(emit-object? stringtag si env arg))
;;; 文字列の長さを返します。
(define-primitive (string-length si env arg)
(emit-expr si env arg)
(emit-heap-load (- stringtag)))
;;; 文字列に文字をセットします。
(define-primitive (string-set! si env string index value)
(emit-expr si env index)
(emit " srai a0, a0, ~s" fxshift)
(emit " addi a0, a0, ~s" wordsize)
(emit-stack-save si)
(emit-expr (next-stack-index si) env value)
(emit " srai a0, a0, ~s" charshift)
(emit-stack-save (next-stack-index si))
(emit-expr si env string)
(emit-stack-load-t0 si)
(emit " add a0, a0, t0")
(emit-stack-load-t0 (next-stack-index si))
(emit " sb t0, ~s(a0)" (- stringtag)))
;;; 文字列の文字を参照します。
(define-primitive (string-ref si env string index)
(emit-expr si env index)
(emit " srai a0, a0, ~s" fxshift)
(emit " addi a0, a0, ~s" wordsize)
(emit-stack-save si)
(emit-expr si env string)
(emit-stack-load-t0 si)
(emit " add a0, a0, t0")
(emit " lb a0, ~s(a0)" (- stringtag))
(emit " slli a0, a0, ~s" charshift)
(emit " ori a0, a0, ~s" chartag))
クロージャ・オブジェクト関連
(define closuretag #x02) ; クロージャ・オブジェクトタグ
;;; クロージャ特殊形式を作成します。
(define (make-closure label free-vars)
(cons 'closure (cons label free-vars)))
;;; クロージャかどうかを返します
(define (closure? expr)
(tagged-form? 'closure expr))
;;;
(define (emit-closure si env expr)
(let ((label (cadr expr))
(free-vars (cddr expr)))
(emit-heap-alloc (* (+ (length free-vars) 1) wordsize))
(emit " la t0, ~s" label)
(emit " sw t0, 0(a0)")
(unless (null? free-vars)
しばらくは、t0がクロージャ・オブジェクトの開始アドレスを指す
(let loop ((free-vars free-vars)
(count 1))
(unless (null? free-vars) ; 自由変数があれば、評価してヒープに保存
(emit-variable-ref si env (car free-vars))
(emit " sw a0, ~s(t0)" (* count wordsize))
(loop (cdr free-vars) (+ count 1))))
(emit " mv a0, t0")) ; クロージャ・オブジェクトの開始アドレスを戻す
(emit " ori a0, a0, ~s" closuretag)))
;;;; 前処理の変換
;;; マクロ変換
(define (macro-expand expr)
(define (transform expr bound-vars)
(cond
((set? expr)
(make-set! (set-lhs expr) (transform (set-rhs expr) bound-vars)))
((lambda? expr)
(make-lambda
(lambda-formals expr)
(transform (lambda-body expr)
(append (lambda-formals expr) bound-vars))))
((let? expr)
(make-let
(let-kind expr)
(map (lambda (binding)
(bind (lhs binding) (transform (rhs binding) bound-vars)))
(let-bindings expr))
(transform (let-body expr)
(append (map lhs (let-bindings expr)) bound-vars))))
((let*? expr)
(transform
(if (null? (let-bindings expr))
(let-body expr)
(make-let
'let
(list (car (let-bindings expr)))
(make-let
'let*
(cdr (let-bindings expr))
(let-body expr))))
bound-vars))
((letrec? expr)
(transform
(make-let
'let
(map (lambda (binding)
(bind (lhs binding) '#f))
(let-bindings expr))
(make-body
(append
(map (lambda (binding)
(make-set! (lhs binding) (rhs binding)))
(let-bindings expr))
(let-body-seq expr))))
bound-vars))
((tagged-form? 'and expr)
(cond
((null? (cdr expr))
#t)
((null? (cddr expr))
(transform (cadr expr) bound-vars))
(else
(transform
(list 'if (cadr expr)
(cons 'and (cddr expr))
#f)
bound-vars))))
((tagged-form? 'or expr)
(cond
((null? (cdr expr))
#f)
((null? (cddr expr))
(transform (cadr expr) bound-vars))
(else
(transform
`(let ((one ,(cadr expr))
(thunk (lambda () (or ,@(cddr expr)))))
(if one
one
(thunk)))
bound-vars))))
((tagged-form? 'when expr)
(transform
(list 'if (cadr expr)
(make-begin cddr expr)
#f)
bound-vars))
((tagged-form? 'unless expr)
(transform
(append (list 'when ('not cadr expr))
(cddr expr))
bound-vars))
((tagged-form? 'cond expr)
(transform
(let* ((conditions (cdr expr))
(first-condition (car conditions))
(first-test (car first-condition))
(first-body (cdr first-condition))
(rest (if (null? (cdr conditions))
#f
(cons 'cond (cdr conditions)))))
(cond
((and (eq? first-test 'else) (not (member 'else bound-vars)))
(make-begin first-body))
((null? first-body)
(list 'or first-test rest))
(else
(list 'if first-test
(make-begin first-body)
rest))))
bound-vars))
((list? expr)
(map (lambda (e)
(transform e bound-vars))
expr))
(else
expr)))
(transform expr '()))
;;; α変換(変数をユニークにする)
(define (alpha-conversion expr)
(define (transform expr env)
(cond
((variable? expr)
(or (lookup expr env)
(error "alpha-conversion: " (format #t "undefined variable ~s" expr))))
((lambda? expr) ; lamdaの引数名をユニークにする
lambdaの引数に対応するユニークな名前を環境に追加
(lambda-formals expr)
(map unique-name (lambda-formals expr))
env)))
(make-lambda ; ユニークな名前を使って、lambda式を作り直す
(map (lambda (v)
(lookup v new-env))
(lambda-formals expr))
(transform (lambda-body expr) new-env))))
((let? expr) ; letのbindされる変数名をユニークにする
(let* ((lvars (map lhs (let-bindings expr)))
(new-env (bulk-extend-env
lvars
(map unique-name lvars)
env)))
(make-let
'let
(map (lambda (binding)
(bind (lookup (lhs binding) new-env)
(transform (rhs binding) env)))
(let-bindings expr))
(transform (let-body expr) new-env))))
((and (list? expr) (not (null? expr)) (special? (car expr)))
(cons (car expr) (map (lambda (e)
(transform e env))
(cdr expr))))
((list? expr)
(map (lambda (e)
(transform e env))
expr))
(else
expr)))
(transform expr (make-initial-env '())))
;;; 代入処理の変換
;;; (set!の対象になる自由変数はxを (x . #f) のようにペアに変え、ヒープ領域で各クロージャから共有する)
(define (assignment-conversion expr)
(let ((assigned '())) ; set!対象の変数名のリスト
;; set!対象リストに変数名を追加
(define (set-variable-assigned! v)
(unless (member v assigned)
(set! assigned (cons v assigned))))
(define (variable-assigned v)
(member v assigned))
式の中のset!対象の変数を、対象リストに追加します 。
(define (mark expr)
(when (set? expr)
(set-variable-assigned! (set-lhs expr)))
(when (list? expr) (for-each mark expr)))
(define (transform expr)
(cond
((set? expr)
(list 'set-car! (set-lhs expr) (transform (set-rhs expr))))
((lambda? expr)
(let ((vars (filter variable-assigned (lambda-formals expr))))
(make-lambda
(lambda-formals expr)
(if (null? vars)
(transform (lambda-body expr))
(make-let
'let
(map (lambda (v)
(bind v (list 'cons v #f)))
vars)
(transform (lambda-body expr)))))))
((let? expr)
(make-let
'let
(map (lambda (binding)
(let ((var (lhs binding))
(val (transform (rhs binding))))
(bind var
(if (variable-assigned var)
(list 'cons val #f)
val))))
(let-bindings expr))
(transform (let-body expr))))
((list? expr) (map transform expr))
((and (variable? expr) (variable-assigned expr))
(list 'car expr))
(else
expr)))
(mark expr)
(transform expr)))
;;; code特殊形式を使った式に変換して、クロージャに対応します
;;; labels特殊形式と、top-envとのリストを返します。
(define (closure-convertion expr)
(let ((labels '()))
(define (transform expr . label)
(cond
((lambda? expr)
labelが指定されていなかったらlabelを生成
(unique-label)))
(free-vars (get-free-vars expr)))
(set! labels
(cons (bind label (make-code (cadr expr)
free-vars
(transform (caddr expr))))
labels))
(make-closure label free-vars)))
((any-let? expr)
(list (car expr)
(map (lambda (binding)
(list (car binding) (transform (cadr binding))))
(let-bindings expr))
(transform (let-body expr))))
((list? expr)
(map transform expr))
(else
expr)))
(let* ((body (if (letrec? expr)
(transform-letrec expr)
(transform expr))))
(make-let 'labels labels body))))
;;; コンパイル前の変換処理
(define (all-conversions expr)
(closure-convertion (assignment-conversion (alpha-conversion (macro-expand expr)))))
コンパイラ・メイン処理
手続き内部の式のコンパイル
(define (emit-ret-if tail)
(when tail
(emit " lw ra, 0(sp)")
(emit " addi sp, sp, ~s" wordsize)
(emit " ret")))
(define (emit-expr si env expr)
(emit-any-expr si env #f expr))
;;; 式を評価して、siに保存します。
(define (emit-expr-save si env arg)
(emit-expr si env arg)
(emit-stack-save si))
;;; 手続き末尾の式のコンパイル
(define (emit-tail-expr si env expr)
(emit-any-expr si env #t expr))
;;; 式をコンパイルします。
;; si スタック・インデックス(stack index)
;; env 環境(environment)。変数や関数の名前と、アクセスするための位置情報のリスト
tail
;; expr コンパイルする式(expression)
(define (emit-any-expr si env tail expr)
(cond
((immediate? expr) (emit-immediate expr) (emit-ret-if tail)) ; 即値の場合は、si、envを必要としない。
((variable? expr) (emit-variable-ref si env expr) (emit-ret-if tail))
((closure? expr) (emit-closure si env expr) (emit-ret-if tail))
((if? expr) (emit-if si env tail expr))
((and? expr) (emit-and si env expr) (emit-ret-if tail))
((or? expr) (emit-or si env expr) (emit-ret-if tail))
((let? expr) (emit-let si env tail expr))
((begin? expr) (emit-begin si env tail expr))
((primcall? expr) (emit-primcall si env expr) (emit-ret-if tail))
((app? expr env) (emit-app si env tail expr))
(else (error "imvalid expr: " expr))))
(define (emit-label label)
(emit "~a:" label))
(define (emit-function-header f)
(emit "")
(emit " .text")
(emit " .globl ~a" f)
(emit " .type ~a, @function" f)
(emit-label f))
(define (emit-call . labels)
(cond
((null? labels)
(emit " jalr a0"))
(else
(emit " call ~a" (car labels)))))
;;; 末尾呼び出しの最後のジャンプ
(define (emit-jmp-tail . labels)
(emit " lw ra, 0(sp)")
(emit " addi sp, sp, ~s" wordsize)
(cond
((null? labels)
(emit " jr a0"))
(else
(emit " j ~a" (car labels)))))
;;;;
(define (emit-scheme-entry expr env)
(emit-function-header "L_scheme_entry")
(emit " addi sp, sp, ~s" (- wordsize))
(emit " sw ra, 0(sp)")
(emit-tail-expr (- wordsize) env expr))
;;;;
(define (emit-labels labels-expr)
(let* ((bindings (let-bindings labels-expr))
(labels (map car bindings))
(codes (map cadr bindings))
(env (make-initial-env '())))
(for-each (emit-code env) codes labels)
(emit-scheme-entry (caddr labels-expr) env)))
;;;;
(define (emit-top top)
(emit-labels (car top) (cadr top)))
(define (emit-program program)
(emit-function-header "scheme_entry")
(emit " addi sp, sp, ~s" (- (* wordsize 3)))
(emit " sw ra, 0(sp)")
(emit " sw s0, ~s(sp)" wordsize)
(emit " sw a1, ~s(sp)" (* wordsize 2))
(emit " mv s0, a0") ; heapの空きアドレスは、s0レジスタに保存する。
(emit " call L_scheme_entry")
(emit " lw ra, 0(sp)")
(emit " lw s0, ~s(sp)" wordsize)
(emit " lw a1, ~s(sp)" (* wordsize 2))
(emit " addi sp, sp, ~s" (* wordsize 3))
(emit " ret")
(emit-labels (all-conversions program)))
;;;; 自動テスト関連
Schemeプログラムのコンパイル
(define (compile-program expr)
(with-output-to-file (path "stst.s")
(lambda ()
(emit-program expr))))
実行ファイルの作成
(define (build)
(unless (zero? (process-exit-wait (run-process "make stst --quiet")))
(error "Could not build target.")))
;;; テスト・プログラムの実行
(define (execute)
(unless (zero? (process-exit-wait (run-process out-to: (path "./stst.out")
"spike pk ./stst > ./stst.out")))
(error "Produced program exited abnormally.")))
;;; テスト・プログラムの実行結果の検証
(define (validate expected-output)
(let ((executed-output (path-data (path "stst.out"))))
(unless (string=? expected-output executed-output)
(error "Output mismatch for expected ~s, got ~s."
expected-output executed-output))))
(define (test-one expr expected-output)
(compile-program expr)
(build)
(execute)
(validate expected-output))
;;; 全てのテストケースをテストします。
(define (test-all)
(for-each (lambda (test-case)
(format #t "TestCase: ~a ..." (car test-case))
(flush-output-port)
(test-one (cadr test-case) (caddr test-case))
(format #t " ok.\n"))
test-cases))
| null | https://raw.githubusercontent.com/horie-t/iacc-riscv/2aea0b27f712f4b9354ecf04a7a0cb08f5c2117e/12.13_AssignmentAndExtendingTheSyntax/compiler.scm | scheme | ユーティリティ関数
書式と引数を取って表示し、改行を付け加えます。
が表示されます。
ユニーク・ラベル生成
重複のない、ラベルを返します。
シンボルに変換する必要はある?
ユニーク・ラベルのリストを生成します。
vars ラベルの一部を形成する文字のリスト
重複のない、変数名を返します。
値比較ユーティリティ
a0と値を比較し、booleanオブジェクトをa0に設定します。
args 比較する即値、省略時はt0と比較
式の書式判定ユーティリティ
スタック関連
スタックに値を保存します。
si スタック・インデックス
次のスタックインデックスを返します。
スタック・ポインタを移動させます。
環境関連
環境を生成します。
bindings 初期値。 '((a -8) (b -9))のような、シンボル、スタック・インデックスのリストのリスト。
binding部分を生成します。
環境に変数を追加します。
si スタック・インデックス
env 変数を追加する環境
環境に変数を追加します。
環境から変数の値を検索します
オブジェクト型情報定義: タグ付きポインタ表現を使う
整数: 下位2ビットが00、上位30ビットが符号付き整数となっている
整数判定ビットマスク(ANDを取って0なら整数オブジェクト)
boolean:
#fの数値表現
#t
boolean判定ビットマスク(ANDを取ってis_boolならbooleanオブジェクト)
booleanの判定用ビット位置
空リスト:
char判定ビットマスク(ANDを取って、chartagならchar)
charタグ
char変換シフト量
32bit(4バイト)
即値関連関数
即値かどうかを返します。
Schemeの即値から、アセンブリ言語でのオブジェクト表現を返します。
グローバル・プロバティ
プリミティブ定義(*porp*にプリミティブ関連の情報を追加)
例: (define-primitive (fxadd1 arg)
出力内容 ...)
引数が基本演算かどうかを返します。
xは、add1のようにシンボルで、*is-prime*が#tにセットされている必要がある
単項演算関連
単項演算呼び出し(単項演算処理)かどうかを返します。
単項演算呼び出しは(op arg)の形式なので、最初はpairで、carがprimitive?がtrueを返すものでなければならない。
charからfixnumに変換します。
fixnumかどうかを返します
空リストかどうかを返します
booleanオブジェクトかどうかを返します
文字オブジェクトかどうかを返します
#fなら#tを返し、それ以外は#fを返します。
二項基本演算
二項基本演算ユーティリティ
結果をスタックに一時退避
スタックに退避した値をt0に復元
整数加算
整数減算
整数積
整数ビット論理積
整数ビット論理和
整数以下
大なりを判定して、あとで否定する
整数大なり
引数を逆にして、小なりを使う
整数以上
小なりを判定して、あとで否定する
文字等号
整数以下
大なりを判定して、あとで否定する
整数大なり
引数を逆にして、小なりを使う
整数以上
小なりを判定して、あとで否定する
特殊形式関連
特殊形式、プリミティブのシンボルかどうかを判定します。
条件式
if形式かどうかを返します
if形式の述部(predicate)を取り出します。
if形式の帰結部(consequent)を取り出します。
if形式の代替部(alternative)を取り出します。
if形式の出力
and形式
まず、(not test)の式に変換して評価する
a0は偽かどうかの値なので、ビット反転でnotを演算する
(and test test* ...) => (if test (and test* ...) #f)と変換して処理
or形式
引数なしなら常に偽
まず、(not test)の式に変換して評価する
a0は偽かどうかの値なので、ビット反転でnotを演算する
(or test test* ...) => (if test #t (or test* ...))と変換して処理
let形式かどうかを返します
letの形式の詳細を返します。
let形式のbody部分を返します。body部分が複数の式からなる時は、begin形式に変換します
let*形式
let*形式かどうかを返します。
let*は、letの入れ子に書き換えてしまう。
例)
y)) y)))
letrec形式
let系形式のどれかか、どうかを返します。
begin形式かどうかを返します。
連続した式を出力します
連続式の末尾の場合
変数参照関連
変数の表現書式は以下の3通りあります。
数値: スタック上の変数
('free offset): 自由変数。offsetは、クロージャ・オブジェクト内でのオフセット
シンボル: クロージャを指している
変数かどうかを返します。
自由変数を作成します。
offset クロージャ・オブジェクト内でのオフセット
変数が自由変数かどうかを判定します。
var 判定対象変数
式の中から自由変数を取得します。
set!関連
set!特殊形式かどうかを返します
set!特殊形式を生成します。
rhs (right hand side)
set!特殊形式の代入されるシンボルを返します
set!特殊形式の代入する式を返します。
lambda特殊形式
lamda特殊形式かどうかを返します。
lambda特殊形式の本体部分を返します。
lambda特殊形式を生成します。
body 本体
code特殊形式
手続き呼び出しの引数で環境を拡張して、kを実行します。
k 拡張された環境で実行したい手続き? thunk?
自由変数で環境を拡張して、kを実行します。 (closure対応に必要)
offset クロージャ・オブジェクトの開始アドレスからのオフセット
app関連
applyの出力
si スタック・インデックス(stack index)
env 環境(environment)。変数や関数の名前と、アクセスするための位置情報のリスト
expr lambda式(expression)
呼び出し先の引数をスタックに積む
末尾呼び出しの場合は、引数を自分の関数のスタックに移動する
delta 移動量
tail
Scheme手続きに対応する、アセンブリ言語のラベルを返します。見つからなかった場合は#fを返します。
ヒープ領域オブジェクト関連
ヒープメモリ確保時の最低サイズ(バイト)
ヒープメモリを確保します。確保したアドレスはa0に設定
動的にヒープ・メモリを確保します。確保するバイト数はa0にセットして呼び出します。
スタックの値をヒープにコピーします。
si コピー元の値のスタックインデックス
offset a0+offset のアドレスに値をコピーします。
ヒープの値をa0に読み込みます。
offset a0+offset のアドレスの値を読み込みます
オブジェクトの型判定をします。
eq?
ペア関連
ペアのタグ
ペアのメモリサイズ(バイト)
ペア中のcar部分のオフセット
ペア中のcdr部分のオフセット
cons
pair?
car
cdr
set-car!
set-cdr!
ベクトル関連
ベクトルのタグ
要素数+1のセルを確保する。+1はlengthデータ保存用
要素数 -> バイト数へ変換
ベクトルかどうかを返します。
ベクトルの要素数を返します。
タグの値の分だけアドレスをずらす
ベクトルに値をセットします。
vector セットされるベクトル
index セットする位置
value セットする値
index=0の位置には長さが入っているのでずれる。
index=0の位置には長さが入っているのでずれる。
文字列関連
文字列を作成します。
文字列かどうかを返します。
文字列の長さを返します。
文字列に文字をセットします。
文字列の文字を参照します。
クロージャ・オブジェクトタグ
クロージャ特殊形式を作成します。
クロージャかどうかを返します
自由変数があれば、評価してヒープに保存
クロージャ・オブジェクトの開始アドレスを戻す
前処理の変換
マクロ変換
α変換(変数をユニークにする)
lamdaの引数名をユニークにする
ユニークな名前を使って、lambda式を作り直す
letのbindされる変数名をユニークにする
代入処理の変換
(set!の対象になる自由変数はxを (x . #f) のようにペアに変え、ヒープ領域で各クロージャから共有する)
set!対象の変数名のリスト
set!対象リストに変数名を追加
code特殊形式を使った式に変換して、クロージャに対応します
labels特殊形式と、top-envとのリストを返します。
コンパイル前の変換処理
式を評価して、siに保存します。
手続き末尾の式のコンパイル
式をコンパイルします。
si スタック・インデックス(stack index)
env 環境(environment)。変数や関数の名前と、アクセスするための位置情報のリスト
expr コンパイルする式(expression)
即値の場合は、si、envを必要としない。
末尾呼び出しの最後のジャンプ
heapの空きアドレスは、s0レジスタに保存する。
自動テスト関連
テスト・プログラムの実行
テスト・プログラムの実行結果の検証
全てのテストケースをテストします。 | (import (srfi 1))
(import (rnrs hashtables))
(load "test_cases.scm")
例 : ( emit " addi t0 , t0 , ~s " 1 )
addi t0 , t0 , 1
(define (emit . args)
(apply format #t args)
(newline))
(define unique-label
(let ((count 0))
(lambda ()
(set! count (+ count 1))
L))))
(define (unique-labels vars)
(map (lambda (var)
(format "~a_~s" (unique-label) var))
vars))
ユニーク変数生成
(define unique-name
既に出現した名前と、出現回数の連想リスト。例 : ( ( x . 1 ) ( a . 3 ) ( cnt . 2 ) )
(lambda (name)
(let ((entry (assv name counts)))
(cond
(entry
(let* ((count (cdr entry))
(new-name (string->symbol (format "~s_~s" name count))))
(set-cdr! entry (+ count 1))
new-name))
(else
(set! counts (cons (cons name 1) counts))
name))))))
(define (emit-cmp-bool . args)
(if (null? args)
(emit " sub a0, a0, t0")
(emit " addi a0, a0, ~s" (- (car args))))
(emit " seqz a0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
( tag .... )
(define (tagged-form? tag expr)
(and (list? expr) (not (null? expr)) (eq? (car expr) tag)))
(define (emit-stack-save si)
(emit " sw a0, ~s(sp)" si))
(define (emit-stack-load si)
(emit " lw a0, ~s(sp)" si))
(define (emit-stack-load-t0 si)
(emit " lw t0, ~s(sp)" si))
(define (next-stack-index si)
(- si wordsize))
(define (emit-adjust-base si)
(emit " addi sp, sp, ~s" si))
(define (make-initial-env bindings)
bindings)
(define (bind lhs rhs)
(list lhs rhs))
bindingの束縛されるシンボル(left hand side)を返します
(define (lhs expr)
(car expr))
bindingの値(right hand side)を返します
(define (rhs expr)
(cadr expr))
var 変数のシンボル
(define (extend-env var si env)
(cons (list var si) env))
(define (bulk-extend-env vars vals env)
(append (map list vars vals) env))
(define (lookup var env)
(cond
((assv var env)
(cadr (assv var env)))
(else #f)))
整数変換シフト量
文字 :
word数 - > バイト数
(define fixnum-bits (- (* wordsize 8) fxshift))
(define fxlower (- (expt 2 (- fixnum-bits 1))))
(define fxupper (- (expt 2 (- fixnum-bits 1))
1))
(define (fixnum? x)
(and (integer? x) (exact? x) (<= fxlower x fxupper)))
(define (immediate? x)
(or (fixnum? x) (boolean? x) (char? x) (null? x)))
(define (immediate-rep x)
(cond
((fixnum? x) (ash x fxshift))
((eq? x #f) bool_f)
((eq? x #t) bool_t)
((char? x) (logior (ash (char->integer x) charshift) chartag))
((null? x) empty_list)
(else (error "invalid immediate"))))
即値表現から、アセンブリ言語を出力します 。
(define (emit-immediate expr)
(let ((imm (immediate-rep expr)))
(when (>= imm 4096)
(emit " lui a0, ~s" (ash imm -12)))
(emit " li a0, ~s" imm)))
(define *prop* (make-eq-hashtable))
(define (getprop x property)
(let ((prop (hashtable-ref *prop* x #f)))
(if prop
(hashtable-ref prop property #f)
#f)))
(define (putprop x property val)
(let ((entry (hashtable-ref *prop* x #f)))
(if entry
(hashtable-set! entry property val)
(hashtable-set! *prop*
x
(let ((entry (make-eq-hashtable)))
(hashtable-set! entry property val)
entry)))))
プリミティブ関連
(define-syntax define-primitive
(syntax-rules ()
((_ (prime-name si env arg* ...) body body* ...)
(begin
(putprop 'prime-name '*is-prime* #t)
(putprop 'prime-name '*arg-count
(length '(arg* ...)))
(putprop 'prime-name '*emmiter*
(lambda (si env arg* ...)
body body* ...))))))
(define (primitive? x)
(and (symbol? x) (getprop x '*is-prime*)))
(define (primitive-emitter x)
(or (getprop x '*emmiter*) (error "primitive-emitter: not exist emmiter")))
(define (primcall? expr)
(and (pair? expr) (primitive? (car expr))))
(define (emit-primcall si env expr)
(let ((prim (car expr))
(args (cdr expr)))
(apply (primitive-emitter prim) si env args)))
引数に1を加えた値を返します
(define-primitive (fxadd1 si env arg)
(emit-expr si env arg)
(emit " addi a0, a0, ~s" (immediate-rep 1)))
引数から1を引いた値を返します
(define-primitive (fxsub1 si env arg)
(emit-expr si env arg)
(emit " addi a0, a0, ~s" (immediate-rep -1)))
(define-primitive (fixnum->char si env arg)
(emit-expr si env arg)
(emit " slli a0, a0, ~s" (- charshift fxshift))
(emit " ori a0, a0, ~s" chartag))
(define-primitive (char->fixnum si env arg)
(emit-expr si env arg)
(emit " srli a0, a0, ~s" (- charshift fxshift)))
(define-primitive (fixnum? si env arg)
(emit-expr si env arg)
(emit " andi a0, a0, ~s" fxmask)
(emit-cmp-bool fxtag))
(define-primitive (null? si env arg)
(emit-expr si env arg)
(emit " andi a0, a0, ~s" emptymask)
(emit-cmp-bool empty_list))
(define-primitive (boolean? si env arg)
(emit-expr si env arg)
(emit " andi a0, a0, ~s" boolmask)
(emit-cmp-bool is_bool))
(define-primitive (char? si env arg)
(emit-expr si env arg)
(emit " andi a0, a0, ~s" charmask)
(emit-cmp-bool chartag))
(define-primitive (not si env arg)
(emit-expr si env arg)
(emit-cmp-bool bool_f))
(define-primitive (fxlognot si env arg)
(emit-expr si env arg)
(emit " xori a0, a0, ~s" (immediate-rep -1)))
arg1、arg2を評価し、結果をそれぞれt0、a0レジスタに代入します
(define (emit-binop si env arg1 arg2)
(emit-expr si env arg1)
(emit-expr (next-stack-index si) env arg2)
siは、stack indexの略。siが指す先は、空き領域にしてから呼び出す事
(emit-binop si env arg1 arg2)
(emit " add a0, a0, t0"))
(define-primitive (fx- si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit " sub a0, t0, a0"))
(define-primitive (fx* si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit " sra a0, a0, ~s" fxshift)
(emit " mul a0, t0, a0"))
(define-primitive (fxlogand si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit " and a0, a0, t0"))
(define-primitive (fxlogor si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit " or a0, a0, t0"))
整数等号
(define-primitive (fx= si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit-cmp-bool))
整数小なり
(define-primitive (fx< si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit " slt a0, t0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
(define-primitive (fx<= si env arg1 arg2)
(emit " xori a0, a0, ~s" (ash 1 bool_bit)))
(define-primitive (fx> si env arg1 arg2)
(define-primitive (fx>= si env arg1 arg2)
(emit " xori a0, a0, ~s" (ash 1 bool_bit)))
(define-primitive (char= si env arg1 arg2)
型判定をしていないので、fx = と同じ内容。eq?をこれにしてOKかも
(emit-cmp-bool))
整数小なり
(define-primitive (char< si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit " slt a0, t0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
(define-primitive (char<= si env arg1 arg2)
(emit " xori a0, a0, ~s" (ash 1 bool_bit)))
(define-primitive (char> si env arg1 arg2)
(define-primitive (char>= si env arg1 arg2)
(emit " xori a0, a0, ~s" (ash 1 bool_bit)))
(define (special? symbol)
(or (member symbol '(if begin let lambda closure set!))
(primitive? symbol)))
if形式
(define (if? expr)
(and (tagged-form? 'if expr)
(or (= (length (cdr expr)) 3)
(error "if? " (format #t "malformed if ~s" expr)))))
(define (if-test expr)
(cadr expr))
(define (if-conseq expr)
(caddr expr))
(define (if-altern expr)
(cadddr expr))
(define (emit-if si env tail expr)
(let ((alt-label (unique-label))
(end-label (unique-label)))
(emit-expr si env (if-test expr))
(emit " addi a0, a0, ~s" (- bool_f))
(emit " beqz a0, ~a" alt-label)
(emit-any-expr si env tail (if-conseq expr))
(if (not tail) (emit " j ~a" end-label))
(emit "~a:" alt-label)
(emit-any-expr si env tail (if-altern expr))
(emit "~a:" end-label)))
(define (and? expr)
(tagged-form? 'and expr))
(define (emit-and si env expr)
(let ((pred-len (length (cdr expr))))
(cond
((= pred-len 0)
引数なしなら常に真
((= pred-len 1)
(else
(emit-if si env #f (list 'if (cadr expr)
(cons 'and (cddr expr))
#f))))))
(define (or? expr)
(tagged-form? 'or expr))
(define (emit-or si env expr)
(let ((pred-len (length (cdr expr))))
(cond
((= pred-len 0)
((= pred-len 1)
(else
(emit-if si env #f (list 'if (cadr expr)
#t
(cons 'or (cddr expr))))))))
let形式
(define (let? expr)
(tagged-form? 'let expr))
(define (let-kind expr)
(car expr))
(define (let-bindings expr)
(cadr expr))
(define make-let list)
(define (let-body expr)
(if (null? (cdddr expr))
(caddr expr)
(make-begin (cddr expr))))
(define (let-body-seq expr)
(cddr expr))
(define (emit-let si env tail expr)
(define (process-let bindings si new-env)
(cond
((null? bindings)
(emit-any-expr si new-env tail (let-body expr)))
(else
(let ((b (car bindings)))
(emit-expr si env (rhs b))
(emit-stack-save si)
(process-let (cdr bindings)
(next-stack-index si)
(extend-env (lhs b) si new-env))))))
(process-let (let-bindings expr) si env))
(define (let*? expr)
(tagged-form? 'let* expr))
( let * ( ( x 1 ) ) ( let ( ( x 1 ) )
( let * ( ( x ( fx+ x 1 ) ) = > ( let ( ( x ( fx+ x 1 ) ) )
( y ( fx+ x 1 ) ) ) ( let ( ( y ( fx+ x 1 ) ) )
(define (emit-let* si env tail expr)
(emit-any-expr si env tail
(let ((bindings (let-bindings expr))
(body (let-body expr)))
(cond
((<= (length bindings) 1)
(list 'let bindings
body))
(else
(list 'let (list (car bindings))
(list 'let* (cdr bindings)
body)))))))
letrec形式かどうかを返します 。
(define (letrec? expr)
(or (tagged-form? 'letrec expr) (tagged-form? 'letrec* expr)))
(define (any-let? expr)
(and (pair? expr)
(member (car expr) '(let let* letrec))))
begin形式
(define (begin? expr)
(tagged-form? 'begin expr))
(define (emit-begin si env tail expr)
(emit-seq si env tail (cdr expr)))
seq 連続した式。例 : ( ( set - car ! some - pair 7 ) ( set - cdr ! come - pair 5 ) some - pair )
(define (emit-seq si env tail seq)
(cond
((null? seq) (error "empty seq"))
(emit-any-expr si env tail (car seq)))
連続式の途中の場合
(emit-expr si env (car seq))
(emit-seq si env tail (cdr seq)))))
(define (make-begin lst)
(if (null? (cdr lst))
(car lst)
(cons 'begin lst)))
(define (make-body lst)
(make-begin lst))
(define (variable? expr)
(symbol? expr))
(define (free-var offset)
(list 'free (- offset closuretag)))
(define (free-var? var)
(tagged-form? 'free var))
(define (get-free-vars expr)
(cond
((variable? expr)
(list expr))
((lambda? expr)
(filter (lambda (v)
(not (member v (cadr expr))))
(get-free-vars (caddr expr))))
((let? expr)
(append (append-map get-free-vars (map cadr (let-bindings expr)))
(filter (lambda (v)
(not (member v (map car (let-bindings expr)))))
(get-free-vars (let-body expr)))))
((list? expr)
(append-map get-free-vars (if (and (not (null? expr))
(special? (car expr)))
(cdr expr)
expr)))
(else '())))
(define (emit-variable-ref si env var)
(cond
((lookup var env)
(let ((v (lookup var env)))
(cond
((free-var? v)
(emit " lw a0, ~s(a1)" (cadr v)))
((number? v)
(emit-stack-load v))
(else (error "emit-variable-ref. "
(format #t "looked up unknown value ~s for var ~s" v var))))))
(else (error "emit-variable-ref. " (format "undefined variable ~s" var)))))
(define (set? expr)
(tagged-form? 'set! expr))
lhs ( left hand side )
(define (make-set! lhs rhs)
(list 'set! lhs rhs))
(define (set-lhs expr)
(cadr expr))
(define (set-rhs expr)
(caddr expr))
(define (lambda? expr)
(tagged-form? 'lambda expr))
(define (lambda-formals expr)
(cadr expr))
(define (lambda-body expr)
(make-body (cddr expr)))
formals
(define (make-lambda formals body)
(list 'lambda formals body))
(define (make-code formals free-vars body)
(list 'code formals free-vars body))
(define (emit-code env)
(lambda (expr label)
(emit-function-header label)
(emit " addi sp, sp, ~s" (- wordsize))
(emit " sw ra, 0(sp)")
(let ((formals (cadr expr))
(free-vars (caddr expr))
(body (cadddr expr)))
(extend-env-with (- wordsize) env formals
(lambda (si env)
(close-env-with wordsize env free-vars
(lambda (env)
(emit-tail-expr si env body))))))))
(define (extend-env-with si env lvars k)
(if (null? lvars)
(k si env)
(extend-env-with (next-stack-index si)
(extend-env (car lvars) si env)
(cdr lvars)
k)))
lvars 自由変数のリスト
(define (close-env-with offset env lvars k)
(if (null? lvars)
(k env)
(close-env-with (+ offset wordsize)
(extend-env (car lvars) (free-var offset) env)
(cdr lvars)
k)))
apply可能かどうか
(define (app? expr env)
(and (list? expr) (not (null? expr))))
tail
(define (emit-app si env tail expr)
(define (emit-arguments si args)
(unless (null? args)
(emit-expr si env (car args))
(emit-stack-save si)
(emit-arguments (- si wordsize) (cdr args))))
(define (move-arguments si delta args)
(unless (or (= delta 0) (null? args))
(emit-stack-load si)
(emit-stack-save (+ si delta))
(move-arguments (- si wordsize) delta (cdr args))))
(cond
((not tail)
(emit-arguments (- si (* 2 wordsize)) (cdr expr))
(emit-expr si env (car expr))
(emit " sw a1, ~s(sp)" si)
(emit " mv a1, a0")
(emit-heap-load (- closuretag))
(emit-adjust-base si)
(emit-call)
(emit-adjust-base (- si))
(emit " lw a1, ~s(sp)" si))
(emit-arguments si (cdr expr))
(emit-expr (- si (* wordsize (length (cdr expr)))) env (car expr))
(emit " mv a1, a0")
(move-arguments si (- (+ si wordsize)) (cdr expr))
(emit " mv a0, a1")
(emit-heap-load (- closuretag))
(emit-jmp-tail))))
(define (proc expr env)
(and (variable? expr)
(let ((val (lookup expr env)))
(and (symbol? val) val))))
(define objshift 2)
(define objmask #x07)
(define heap-cell-size (ash 1 objshift))
size 確保するバイト数
(define (emit-heap-alloc size)
(let ((alloc-size (* (+ (div (- size 1) heap-cell-size) 1) heap-cell-size)))
(emit " mv a0, s0")
(emit " addi s0, s0, ~s" alloc-size)))
(define (emit-heap-alloc-dynamic)
(emit " addi a0, a0, -1")
(emit " srai a0, a0, ~s" objshift)
(emit " addi a0, a0, 1")
(emit " slli a0, a0, ~s" objshift)
(emit " mv t0, a0")
(emit " mv a0, s0")
(emit " add s0, s0, t0"))
(define (emit-stack-to-heap si offset)
(emit " lw t0, ~s(sp)" si)
(emit " sw t0, ~s(a0)" offset))
(define (emit-heap-load offset)
(emit " lw a0, ~s(a0)" offset))
(define (emit-object? tag si env arg)
(emit-expr si env arg)
(emit " andi a0, a0, ~s" objmask)
(emit-cmp-bool tag))
(define-primitive (eq? si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit-cmp-bool))
(define-primitive (cons si env arg1 arg2)
(emit-binop si env arg1 arg2)
(emit-stack-save (next-stack-index si))
(emit-heap-alloc pairsize)
(emit " ori a0, a0, ~s" pairtag)
(emit-stack-to-heap si (- paircar pairtag))
(emit-stack-to-heap (next-stack-index si) (- paircdr pairtag)))
(define-primitive (pair? si env arg)
(emit-object? pairtag si env arg))
(define-primitive (car si env arg)
(emit-expr si env arg)
(emit-heap-load (- paircar pairtag)))
(define-primitive (cdr si env arg)
(emit-expr si env arg)
(emit-heap-load (- paircdr pairtag)))
(define-primitive (set-car! si env cell val)
(emit-binop si env val cell)
(emit-stack-to-heap si (- paircar pairtag)))
(define-primitive (set-cdr! si env cell val)
(emit-binop si env val cell)
(emit-stack-to-heap si (- paircdr pairtag)))
length ベクトルの要素数
(define-primitive (make-vector si env length)
(emit-expr si env length)
(emit-stack-save si)
(emit-heap-alloc-dynamic)
(emit-stack-to-heap si 0)
(emit " ori a0, a0, ~s" vectortag))
(define-primitive (vector? si env arg)
(emit-object? vectortag si env arg))
(define-primitive (vector-length si env arg)
(emit-expr si env arg)
(define-primitive (vector-set! si env vector index value)
(emit-expr si env index)
(emit " slli a0, a0, ~s" (- objshift fxshift))
(emit-stack-save si)
(emit-expr-save (next-stack-index si) env value)
(emit-expr si env vector)
(emit-stack-load-t0 si)
(emit " add a0, a0, t0")
(emit-stack-to-heap (next-stack-index si) (- vectortag)))
ベクトルの要素の値を取得します 。
(define-primitive (vector-ref si env vector index)
(emit-expr si env index)
(emit " slli a0, a0, ~s" (- objshift fxshift))
(emit-stack-save si)
(emit-expr si env vector)
(emit-stack-load-t0 si)
(emit " add a0, a0, t0")
(emit-heap-load (- vectortag)))
(define stringtag #x06)
(define-primitive (make-string si env length)
(emit-expr-save si env length)
(emit " srai a0, a0, ~s" fxshift)
(emit " addi a0, a0, ~s" wordsize)
(emit-heap-alloc-dynamic)
(emit-stack-to-heap si 0)
(emit " ori a0, a0, ~s" stringtag))
(define-primitive (string? si env arg)
(emit-object? stringtag si env arg))
(define-primitive (string-length si env arg)
(emit-expr si env arg)
(emit-heap-load (- stringtag)))
(define-primitive (string-set! si env string index value)
(emit-expr si env index)
(emit " srai a0, a0, ~s" fxshift)
(emit " addi a0, a0, ~s" wordsize)
(emit-stack-save si)
(emit-expr (next-stack-index si) env value)
(emit " srai a0, a0, ~s" charshift)
(emit-stack-save (next-stack-index si))
(emit-expr si env string)
(emit-stack-load-t0 si)
(emit " add a0, a0, t0")
(emit-stack-load-t0 (next-stack-index si))
(emit " sb t0, ~s(a0)" (- stringtag)))
(define-primitive (string-ref si env string index)
(emit-expr si env index)
(emit " srai a0, a0, ~s" fxshift)
(emit " addi a0, a0, ~s" wordsize)
(emit-stack-save si)
(emit-expr si env string)
(emit-stack-load-t0 si)
(emit " add a0, a0, t0")
(emit " lb a0, ~s(a0)" (- stringtag))
(emit " slli a0, a0, ~s" charshift)
(emit " ori a0, a0, ~s" chartag))
クロージャ・オブジェクト関連
(define (make-closure label free-vars)
(cons 'closure (cons label free-vars)))
(define (closure? expr)
(tagged-form? 'closure expr))
(define (emit-closure si env expr)
(let ((label (cadr expr))
(free-vars (cddr expr)))
(emit-heap-alloc (* (+ (length free-vars) 1) wordsize))
(emit " la t0, ~s" label)
(emit " sw t0, 0(a0)")
(unless (null? free-vars)
しばらくは、t0がクロージャ・オブジェクトの開始アドレスを指す
(let loop ((free-vars free-vars)
(count 1))
(emit-variable-ref si env (car free-vars))
(emit " sw a0, ~s(t0)" (* count wordsize))
(loop (cdr free-vars) (+ count 1))))
(emit " ori a0, a0, ~s" closuretag)))
(define (macro-expand expr)
(define (transform expr bound-vars)
(cond
((set? expr)
(make-set! (set-lhs expr) (transform (set-rhs expr) bound-vars)))
((lambda? expr)
(make-lambda
(lambda-formals expr)
(transform (lambda-body expr)
(append (lambda-formals expr) bound-vars))))
((let? expr)
(make-let
(let-kind expr)
(map (lambda (binding)
(bind (lhs binding) (transform (rhs binding) bound-vars)))
(let-bindings expr))
(transform (let-body expr)
(append (map lhs (let-bindings expr)) bound-vars))))
((let*? expr)
(transform
(if (null? (let-bindings expr))
(let-body expr)
(make-let
'let
(list (car (let-bindings expr)))
(make-let
'let*
(cdr (let-bindings expr))
(let-body expr))))
bound-vars))
((letrec? expr)
(transform
(make-let
'let
(map (lambda (binding)
(bind (lhs binding) '#f))
(let-bindings expr))
(make-body
(append
(map (lambda (binding)
(make-set! (lhs binding) (rhs binding)))
(let-bindings expr))
(let-body-seq expr))))
bound-vars))
((tagged-form? 'and expr)
(cond
((null? (cdr expr))
#t)
((null? (cddr expr))
(transform (cadr expr) bound-vars))
(else
(transform
(list 'if (cadr expr)
(cons 'and (cddr expr))
#f)
bound-vars))))
((tagged-form? 'or expr)
(cond
((null? (cdr expr))
#f)
((null? (cddr expr))
(transform (cadr expr) bound-vars))
(else
(transform
`(let ((one ,(cadr expr))
(thunk (lambda () (or ,@(cddr expr)))))
(if one
one
(thunk)))
bound-vars))))
((tagged-form? 'when expr)
(transform
(list 'if (cadr expr)
(make-begin cddr expr)
#f)
bound-vars))
((tagged-form? 'unless expr)
(transform
(append (list 'when ('not cadr expr))
(cddr expr))
bound-vars))
((tagged-form? 'cond expr)
(transform
(let* ((conditions (cdr expr))
(first-condition (car conditions))
(first-test (car first-condition))
(first-body (cdr first-condition))
(rest (if (null? (cdr conditions))
#f
(cons 'cond (cdr conditions)))))
(cond
((and (eq? first-test 'else) (not (member 'else bound-vars)))
(make-begin first-body))
((null? first-body)
(list 'or first-test rest))
(else
(list 'if first-test
(make-begin first-body)
rest))))
bound-vars))
((list? expr)
(map (lambda (e)
(transform e bound-vars))
expr))
(else
expr)))
(transform expr '()))
(define (alpha-conversion expr)
(define (transform expr env)
(cond
((variable? expr)
(or (lookup expr env)
(error "alpha-conversion: " (format #t "undefined variable ~s" expr))))
lambdaの引数に対応するユニークな名前を環境に追加
(lambda-formals expr)
(map unique-name (lambda-formals expr))
env)))
(map (lambda (v)
(lookup v new-env))
(lambda-formals expr))
(transform (lambda-body expr) new-env))))
(let* ((lvars (map lhs (let-bindings expr)))
(new-env (bulk-extend-env
lvars
(map unique-name lvars)
env)))
(make-let
'let
(map (lambda (binding)
(bind (lookup (lhs binding) new-env)
(transform (rhs binding) env)))
(let-bindings expr))
(transform (let-body expr) new-env))))
((and (list? expr) (not (null? expr)) (special? (car expr)))
(cons (car expr) (map (lambda (e)
(transform e env))
(cdr expr))))
((list? expr)
(map (lambda (e)
(transform e env))
expr))
(else
expr)))
(transform expr (make-initial-env '())))
(define (assignment-conversion expr)
(define (set-variable-assigned! v)
(unless (member v assigned)
(set! assigned (cons v assigned))))
(define (variable-assigned v)
(member v assigned))
式の中のset!対象の変数を、対象リストに追加します 。
(define (mark expr)
(when (set? expr)
(set-variable-assigned! (set-lhs expr)))
(when (list? expr) (for-each mark expr)))
(define (transform expr)
(cond
((set? expr)
(list 'set-car! (set-lhs expr) (transform (set-rhs expr))))
((lambda? expr)
(let ((vars (filter variable-assigned (lambda-formals expr))))
(make-lambda
(lambda-formals expr)
(if (null? vars)
(transform (lambda-body expr))
(make-let
'let
(map (lambda (v)
(bind v (list 'cons v #f)))
vars)
(transform (lambda-body expr)))))))
((let? expr)
(make-let
'let
(map (lambda (binding)
(let ((var (lhs binding))
(val (transform (rhs binding))))
(bind var
(if (variable-assigned var)
(list 'cons val #f)
val))))
(let-bindings expr))
(transform (let-body expr))))
((list? expr) (map transform expr))
((and (variable? expr) (variable-assigned expr))
(list 'car expr))
(else
expr)))
(mark expr)
(transform expr)))
(define (closure-convertion expr)
(let ((labels '()))
(define (transform expr . label)
(cond
((lambda? expr)
labelが指定されていなかったらlabelを生成
(unique-label)))
(free-vars (get-free-vars expr)))
(set! labels
(cons (bind label (make-code (cadr expr)
free-vars
(transform (caddr expr))))
labels))
(make-closure label free-vars)))
((any-let? expr)
(list (car expr)
(map (lambda (binding)
(list (car binding) (transform (cadr binding))))
(let-bindings expr))
(transform (let-body expr))))
((list? expr)
(map transform expr))
(else
expr)))
(let* ((body (if (letrec? expr)
(transform-letrec expr)
(transform expr))))
(make-let 'labels labels body))))
(define (all-conversions expr)
(closure-convertion (assignment-conversion (alpha-conversion (macro-expand expr)))))
コンパイラ・メイン処理
手続き内部の式のコンパイル
(define (emit-ret-if tail)
(when tail
(emit " lw ra, 0(sp)")
(emit " addi sp, sp, ~s" wordsize)
(emit " ret")))
(define (emit-expr si env expr)
(emit-any-expr si env #f expr))
(define (emit-expr-save si env arg)
(emit-expr si env arg)
(emit-stack-save si))
(define (emit-tail-expr si env expr)
(emit-any-expr si env #t expr))
tail
(define (emit-any-expr si env tail expr)
(cond
((variable? expr) (emit-variable-ref si env expr) (emit-ret-if tail))
((closure? expr) (emit-closure si env expr) (emit-ret-if tail))
((if? expr) (emit-if si env tail expr))
((and? expr) (emit-and si env expr) (emit-ret-if tail))
((or? expr) (emit-or si env expr) (emit-ret-if tail))
((let? expr) (emit-let si env tail expr))
((begin? expr) (emit-begin si env tail expr))
((primcall? expr) (emit-primcall si env expr) (emit-ret-if tail))
((app? expr env) (emit-app si env tail expr))
(else (error "imvalid expr: " expr))))
(define (emit-label label)
(emit "~a:" label))
(define (emit-function-header f)
(emit "")
(emit " .text")
(emit " .globl ~a" f)
(emit " .type ~a, @function" f)
(emit-label f))
(define (emit-call . labels)
(cond
((null? labels)
(emit " jalr a0"))
(else
(emit " call ~a" (car labels)))))
(define (emit-jmp-tail . labels)
(emit " lw ra, 0(sp)")
(emit " addi sp, sp, ~s" wordsize)
(cond
((null? labels)
(emit " jr a0"))
(else
(emit " j ~a" (car labels)))))
(define (emit-scheme-entry expr env)
(emit-function-header "L_scheme_entry")
(emit " addi sp, sp, ~s" (- wordsize))
(emit " sw ra, 0(sp)")
(emit-tail-expr (- wordsize) env expr))
(define (emit-labels labels-expr)
(let* ((bindings (let-bindings labels-expr))
(labels (map car bindings))
(codes (map cadr bindings))
(env (make-initial-env '())))
(for-each (emit-code env) codes labels)
(emit-scheme-entry (caddr labels-expr) env)))
(define (emit-top top)
(emit-labels (car top) (cadr top)))
(define (emit-program program)
(emit-function-header "scheme_entry")
(emit " addi sp, sp, ~s" (- (* wordsize 3)))
(emit " sw ra, 0(sp)")
(emit " sw s0, ~s(sp)" wordsize)
(emit " sw a1, ~s(sp)" (* wordsize 2))
(emit " call L_scheme_entry")
(emit " lw ra, 0(sp)")
(emit " lw s0, ~s(sp)" wordsize)
(emit " lw a1, ~s(sp)" (* wordsize 2))
(emit " addi sp, sp, ~s" (* wordsize 3))
(emit " ret")
(emit-labels (all-conversions program)))
Schemeプログラムのコンパイル
(define (compile-program expr)
(with-output-to-file (path "stst.s")
(lambda ()
(emit-program expr))))
実行ファイルの作成
(define (build)
(unless (zero? (process-exit-wait (run-process "make stst --quiet")))
(error "Could not build target.")))
(define (execute)
(unless (zero? (process-exit-wait (run-process out-to: (path "./stst.out")
"spike pk ./stst > ./stst.out")))
(error "Produced program exited abnormally.")))
(define (validate expected-output)
(let ((executed-output (path-data (path "stst.out"))))
(unless (string=? expected-output executed-output)
(error "Output mismatch for expected ~s, got ~s."
expected-output executed-output))))
(define (test-one expr expected-output)
(compile-program expr)
(build)
(execute)
(validate expected-output))
(define (test-all)
(for-each (lambda (test-case)
(format #t "TestCase: ~a ..." (car test-case))
(flush-output-port)
(test-one (cadr test-case) (caddr test-case))
(format #t " ok.\n"))
test-cases))
|
4e09ea6db4ae0a2286b0f6bd2eafa3b7670b9c91d2413f59e6750130e771d20e | jkk/formative-demo | project.clj | (defproject formative-demo "0.0.2-SNAPSHOT"
:description "Demo app for the Formative lib"
:url "-demo.herokuapp.com"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/clojurescript "0.0-2138"]
[compojure "1.1.5"]
[ring/ring-core "1.2.0"]
[ring/ring-jetty-adapter "1.2.0"]
[ring/ring-devel "1.2.0"]
[amalloy/ring-gzip-middleware "0.1.2"]
[environ "0.3.0"]
[formative "0.8.8"]
[hiccup "1.0.2"]
[prismatic/dommy "0.1.1"]]
:min-lein-version "2.0.0"
:plugins [[environ/environ.lein "0.3.0"]
[lein-cljsbuild "1.0.1"]]
:hooks [environ.leiningen.hooks]
:profiles {:production {:env {:production true}}}
:cljsbuild {:builds [{:source-paths ["src-cljs"]
:compiler {:output-to "resources/public/js/main.js"
:optimizations :advanced
:pretty-print false}
#_{:output-dir "resources/public/js"
:output-to "resources/public/js/main.js"
:source-map "resources/public/js/main.js.map"
:optimizations :none
:pretty-print false}}]}) | null | https://raw.githubusercontent.com/jkk/formative-demo/c379800c205c29ea46f08fba9ce4d1ff5b8acb42/project.clj | clojure | (defproject formative-demo "0.0.2-SNAPSHOT"
:description "Demo app for the Formative lib"
:url "-demo.herokuapp.com"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/clojurescript "0.0-2138"]
[compojure "1.1.5"]
[ring/ring-core "1.2.0"]
[ring/ring-jetty-adapter "1.2.0"]
[ring/ring-devel "1.2.0"]
[amalloy/ring-gzip-middleware "0.1.2"]
[environ "0.3.0"]
[formative "0.8.8"]
[hiccup "1.0.2"]
[prismatic/dommy "0.1.1"]]
:min-lein-version "2.0.0"
:plugins [[environ/environ.lein "0.3.0"]
[lein-cljsbuild "1.0.1"]]
:hooks [environ.leiningen.hooks]
:profiles {:production {:env {:production true}}}
:cljsbuild {:builds [{:source-paths ["src-cljs"]
:compiler {:output-to "resources/public/js/main.js"
:optimizations :advanced
:pretty-print false}
#_{:output-dir "resources/public/js"
:output-to "resources/public/js/main.js"
:source-map "resources/public/js/main.js.map"
:optimizations :none
:pretty-print false}}]}) |
|
5144814574d55785a32f1936e0da74199eafcde230c48f6d84d4ea0a02ff46af | input-output-hk/marlowe-cardano | ChainIndexer.hs | {-# LANGUAGE Arrows #-}
# LANGUAGE DataKinds #
# LANGUAGE DuplicateRecordFields #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
module Language.Marlowe.Runtime.ChainIndexer
( ChainIndexerDependencies(..)
, ChainIndexerSelector(..)
, chainIndexer
, getChainIndexerSelectorConfig
) where
import Cardano.Api (CardanoMode, ChainPoint(..), ChainTip(..), LocalNodeClientProtocolsInMode)
import Control.Concurrent.Component
import Data.Aeson (Value(..), object, (.=))
import Data.Time (NominalDiffTime)
import Language.Marlowe.Runtime.Cardano.Api
(fromCardanoBlockHeader, fromCardanoBlockHeaderHash, fromCardanoBlockNo, fromCardanoSlotNo)
import Language.Marlowe.Runtime.ChainIndexer.Database (DatabaseQueries(..))
import Language.Marlowe.Runtime.ChainIndexer.Genesis (GenesisBlock)
import Language.Marlowe.Runtime.ChainIndexer.NodeClient
( CostModel
, NodeClient(..)
, NodeClientDependencies(..)
, NodeClientSelector(..)
, RollBackwardField(..)
, RollForwardField(..)
, nodeClient
)
import Language.Marlowe.Runtime.ChainIndexer.Store
(ChainStoreDependencies(..), ChainStoreSelector(..), SaveField(..), chainStore)
import Observe.Event (EventBackend, narrowEventBackend)
import Observe.Event.Component
( FieldConfig(..)
, GetSelectorConfig
, SelectorConfig(..)
, SomeJSON(..)
, absurdFieldConfig
, prependKey
, singletonFieldConfig
, singletonFieldConfigWith
)
data ChainIndexerSelector f where
NodeClientEvent :: NodeClientSelector f -> ChainIndexerSelector f
ChainStoreEvent :: ChainStoreSelector f -> ChainIndexerSelector f
data ChainIndexerDependencies r = ChainIndexerDependencies
{ connectToLocalNode :: !(LocalNodeClientProtocolsInMode CardanoMode -> IO ())
, maxCost :: !Int
, costModel :: !CostModel
, databaseQueries :: !(DatabaseQueries IO)
, persistRateLimit :: !NominalDiffTime
, genesisBlock :: !GenesisBlock
, eventBackend :: !(EventBackend IO r ChainIndexerSelector)
}
chainIndexer :: Component IO (ChainIndexerDependencies r) ()
chainIndexer = proc ChainIndexerDependencies{..} -> do
let DatabaseQueries{..} = databaseQueries
NodeClient{..} <- nodeClient -< NodeClientDependencies
{ connectToLocalNode
, getIntersectionPoints
, maxCost
, costModel
, eventBackend = narrowEventBackend NodeClientEvent eventBackend
}
let rateLimit = persistRateLimit
chainStore -< ChainStoreDependencies
{ commitRollback
, commitBlocks
, rateLimit
, getChanges
, getGenesisBlock
, genesisBlock
, commitGenesisBlock
, eventBackend = narrowEventBackend ChainStoreEvent eventBackend
}
getChainIndexerSelectorConfig :: GetSelectorConfig ChainIndexerSelector
getChainIndexerSelectorConfig = \case
NodeClientEvent sel -> prependKey "node-client" $ getNodeClientSelectorConfig sel
ChainStoreEvent sel -> prependKey "chain-store" $ getChainStoreSelectorConfig sel
getNodeClientSelectorConfig :: GetSelectorConfig NodeClientSelector
getNodeClientSelectorConfig = \case
Connect -> SelectorConfig "connect" True absurdFieldConfig
Intersect -> SelectorConfig "intersect" True
$ singletonFieldConfigWith (SomeJSON . fmap pointToJSON) "points" False
IntersectFound -> SelectorConfig "intersect-found" True
$ singletonFieldConfigWith (SomeJSON . pointToJSON) "point" True
IntersectNotFound -> SelectorConfig "intersect-not-found" True absurdFieldConfig
RollForward -> SelectorConfig "roll-forward" False FieldConfig
{ fieldKey = \case
RollForwardBlock _ -> "block-header"
RollForwardTip _ -> "tip"
RollForwardNewCost _ -> "new-cost"
, fieldDefaultEnabled = \case
RollForwardBlock _ -> True
RollForwardTip _ -> True
RollForwardNewCost _ -> False
, toSomeJSON = \case
RollForwardBlock header -> SomeJSON $ fromCardanoBlockHeader header
RollForwardTip tip -> SomeJSON $ tipToJSON tip
RollForwardNewCost cost -> SomeJSON cost
}
RollBackward -> SelectorConfig "roll-backward" True FieldConfig
{ fieldKey = \case
RollBackwardPoint _ -> "point"
RollBackwardTip _ -> "tip"
RollBackwardNewCost _ -> "new-cost"
, fieldDefaultEnabled = \case
RollBackwardPoint _ -> True
RollBackwardTip _ -> True
RollBackwardNewCost _ -> False
, toSomeJSON = \case
RollBackwardPoint point -> SomeJSON $ pointToJSON point
RollBackwardTip tip -> SomeJSON $ tipToJSON tip
RollBackwardNewCost cost -> SomeJSON cost
}
getChainStoreSelectorConfig :: GetSelectorConfig ChainStoreSelector
getChainStoreSelectorConfig = \case
CheckGenesisBlock -> SelectorConfig "check-genesis-block" True
$ singletonFieldConfig "genesis-block-exists" True
Save -> SelectorConfig "save" True FieldConfig
{ fieldKey = \case
RollbackPoint _ -> "rollback-point"
BlockCount _ -> "block-count"
LocalTip _ -> "local-tip"
RemoteTip _ -> "remote-tip"
TxCount _ -> "tx-count"
, fieldDefaultEnabled = const True
, toSomeJSON = \case
RollbackPoint point -> SomeJSON $ pointToJSON point
BlockCount count -> SomeJSON count
LocalTip tip -> SomeJSON $ tipToJSON tip
RemoteTip tip -> SomeJSON $ tipToJSON tip
TxCount count -> SomeJSON count
}
pointToJSON :: ChainPoint -> Value
pointToJSON = \case
ChainPointAtGenesis -> String "genesis"
ChainPoint slotNo hash -> object
[ "slotNo" .= fromCardanoSlotNo slotNo
, "hash" .= fromCardanoBlockHeaderHash hash
]
tipToJSON :: ChainTip -> Value
tipToJSON = \case
ChainTipAtGenesis -> String "genesis"
ChainTip slotNo hash blockNo -> object
[ "slotNo" .= fromCardanoSlotNo slotNo
, "hash" .= fromCardanoBlockHeaderHash hash
, "blockNo" .= fromCardanoBlockNo blockNo
]
| null | https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/4b652fbaeafdea9a6b499a695db86e621813a23f/marlowe-chain-sync/chain-indexer/Language/Marlowe/Runtime/ChainIndexer.hs | haskell | # LANGUAGE Arrows #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes # | # LANGUAGE DataKinds #
# LANGUAGE DuplicateRecordFields #
module Language.Marlowe.Runtime.ChainIndexer
( ChainIndexerDependencies(..)
, ChainIndexerSelector(..)
, chainIndexer
, getChainIndexerSelectorConfig
) where
import Cardano.Api (CardanoMode, ChainPoint(..), ChainTip(..), LocalNodeClientProtocolsInMode)
import Control.Concurrent.Component
import Data.Aeson (Value(..), object, (.=))
import Data.Time (NominalDiffTime)
import Language.Marlowe.Runtime.Cardano.Api
(fromCardanoBlockHeader, fromCardanoBlockHeaderHash, fromCardanoBlockNo, fromCardanoSlotNo)
import Language.Marlowe.Runtime.ChainIndexer.Database (DatabaseQueries(..))
import Language.Marlowe.Runtime.ChainIndexer.Genesis (GenesisBlock)
import Language.Marlowe.Runtime.ChainIndexer.NodeClient
( CostModel
, NodeClient(..)
, NodeClientDependencies(..)
, NodeClientSelector(..)
, RollBackwardField(..)
, RollForwardField(..)
, nodeClient
)
import Language.Marlowe.Runtime.ChainIndexer.Store
(ChainStoreDependencies(..), ChainStoreSelector(..), SaveField(..), chainStore)
import Observe.Event (EventBackend, narrowEventBackend)
import Observe.Event.Component
( FieldConfig(..)
, GetSelectorConfig
, SelectorConfig(..)
, SomeJSON(..)
, absurdFieldConfig
, prependKey
, singletonFieldConfig
, singletonFieldConfigWith
)
data ChainIndexerSelector f where
NodeClientEvent :: NodeClientSelector f -> ChainIndexerSelector f
ChainStoreEvent :: ChainStoreSelector f -> ChainIndexerSelector f
data ChainIndexerDependencies r = ChainIndexerDependencies
{ connectToLocalNode :: !(LocalNodeClientProtocolsInMode CardanoMode -> IO ())
, maxCost :: !Int
, costModel :: !CostModel
, databaseQueries :: !(DatabaseQueries IO)
, persistRateLimit :: !NominalDiffTime
, genesisBlock :: !GenesisBlock
, eventBackend :: !(EventBackend IO r ChainIndexerSelector)
}
chainIndexer :: Component IO (ChainIndexerDependencies r) ()
chainIndexer = proc ChainIndexerDependencies{..} -> do
let DatabaseQueries{..} = databaseQueries
NodeClient{..} <- nodeClient -< NodeClientDependencies
{ connectToLocalNode
, getIntersectionPoints
, maxCost
, costModel
, eventBackend = narrowEventBackend NodeClientEvent eventBackend
}
let rateLimit = persistRateLimit
chainStore -< ChainStoreDependencies
{ commitRollback
, commitBlocks
, rateLimit
, getChanges
, getGenesisBlock
, genesisBlock
, commitGenesisBlock
, eventBackend = narrowEventBackend ChainStoreEvent eventBackend
}
getChainIndexerSelectorConfig :: GetSelectorConfig ChainIndexerSelector
getChainIndexerSelectorConfig = \case
NodeClientEvent sel -> prependKey "node-client" $ getNodeClientSelectorConfig sel
ChainStoreEvent sel -> prependKey "chain-store" $ getChainStoreSelectorConfig sel
getNodeClientSelectorConfig :: GetSelectorConfig NodeClientSelector
getNodeClientSelectorConfig = \case
Connect -> SelectorConfig "connect" True absurdFieldConfig
Intersect -> SelectorConfig "intersect" True
$ singletonFieldConfigWith (SomeJSON . fmap pointToJSON) "points" False
IntersectFound -> SelectorConfig "intersect-found" True
$ singletonFieldConfigWith (SomeJSON . pointToJSON) "point" True
IntersectNotFound -> SelectorConfig "intersect-not-found" True absurdFieldConfig
RollForward -> SelectorConfig "roll-forward" False FieldConfig
{ fieldKey = \case
RollForwardBlock _ -> "block-header"
RollForwardTip _ -> "tip"
RollForwardNewCost _ -> "new-cost"
, fieldDefaultEnabled = \case
RollForwardBlock _ -> True
RollForwardTip _ -> True
RollForwardNewCost _ -> False
, toSomeJSON = \case
RollForwardBlock header -> SomeJSON $ fromCardanoBlockHeader header
RollForwardTip tip -> SomeJSON $ tipToJSON tip
RollForwardNewCost cost -> SomeJSON cost
}
RollBackward -> SelectorConfig "roll-backward" True FieldConfig
{ fieldKey = \case
RollBackwardPoint _ -> "point"
RollBackwardTip _ -> "tip"
RollBackwardNewCost _ -> "new-cost"
, fieldDefaultEnabled = \case
RollBackwardPoint _ -> True
RollBackwardTip _ -> True
RollBackwardNewCost _ -> False
, toSomeJSON = \case
RollBackwardPoint point -> SomeJSON $ pointToJSON point
RollBackwardTip tip -> SomeJSON $ tipToJSON tip
RollBackwardNewCost cost -> SomeJSON cost
}
getChainStoreSelectorConfig :: GetSelectorConfig ChainStoreSelector
getChainStoreSelectorConfig = \case
CheckGenesisBlock -> SelectorConfig "check-genesis-block" True
$ singletonFieldConfig "genesis-block-exists" True
Save -> SelectorConfig "save" True FieldConfig
{ fieldKey = \case
RollbackPoint _ -> "rollback-point"
BlockCount _ -> "block-count"
LocalTip _ -> "local-tip"
RemoteTip _ -> "remote-tip"
TxCount _ -> "tx-count"
, fieldDefaultEnabled = const True
, toSomeJSON = \case
RollbackPoint point -> SomeJSON $ pointToJSON point
BlockCount count -> SomeJSON count
LocalTip tip -> SomeJSON $ tipToJSON tip
RemoteTip tip -> SomeJSON $ tipToJSON tip
TxCount count -> SomeJSON count
}
pointToJSON :: ChainPoint -> Value
pointToJSON = \case
ChainPointAtGenesis -> String "genesis"
ChainPoint slotNo hash -> object
[ "slotNo" .= fromCardanoSlotNo slotNo
, "hash" .= fromCardanoBlockHeaderHash hash
]
tipToJSON :: ChainTip -> Value
tipToJSON = \case
ChainTipAtGenesis -> String "genesis"
ChainTip slotNo hash blockNo -> object
[ "slotNo" .= fromCardanoSlotNo slotNo
, "hash" .= fromCardanoBlockHeaderHash hash
, "blockNo" .= fromCardanoBlockNo blockNo
]
|
cad925198f7f3b030a9b14e1d710b44500ec0eda4ce535855bce397b2ea26923 | caradoc-org/caradoc | console.ml | (*****************************************************************************)
(* Caradoc: a PDF parser and validator *)
Copyright ( C ) 2015 ANSSI
Copyright ( C ) 2015 - 2017
(* *)
(* This program is free software; you can redistribute it and/or modify *)
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation .
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
(*****************************************************************************)
module Console = struct
let highlight : string =
"\x1b[0;7m"
let reset : string =
"\x1b[0m"
end
| null | https://raw.githubusercontent.com/caradoc-org/caradoc/100f53bc55ef682049e10fabf24869bc019dc6ce/src/util/console.ml | ocaml | ***************************************************************************
Caradoc: a PDF parser and validator
This program is free software; you can redistribute it and/or modify
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*************************************************************************** | Copyright ( C ) 2015 ANSSI
Copyright ( C ) 2015 - 2017
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation .
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
module Console = struct
let highlight : string =
"\x1b[0;7m"
let reset : string =
"\x1b[0m"
end
|
664fafc4211b5e104acc8dc335918894dd88ff45578ca52ae4cc49877e6d3847 | peerdrive/peerdrive | peerdrive_servlet_sup.erl | PeerDrive
Copyright ( C ) 2011 < jan DOT kloetzke AT freenet DOT de >
%%
%% This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
%% (at your option) any later version.
%%
%% This program is distributed in the hope that it will be useful,
%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
%% GNU General Public License for more details.
%%
You should have received a copy of the GNU General Public License
%% along with this program. If not, see </>.
-module(peerdrive_servlet_sup).
-behaviour(supervisor).
-export([start_link/2]).
-export([spawn_servlet/3]).
-export([init/1]).
start_link(Module, ServletOpt) ->
supervisor:start_link(?MODULE, {Module, ServletOpt}).
init({Module, ServletOpt}) ->
{ok, {
{simple_one_for_one, 1000, 1},
[{
servlet,
{peerdrive_gen_servlet, start_link, [Module, ServletOpt]},
temporary,
brutal_kill,
worker,
[]
}]
}}.
spawn_servlet(SupervisorPid, ListenSock, ListenState) ->
supervisor:start_child(SupervisorPid, [self(), ListenSock, ListenState]).
| null | https://raw.githubusercontent.com/peerdrive/peerdrive/94389e2536cc9b1a0c168ec56ba3912910eb0c35/server/apps/peerdrive/src/peerdrive_servlet_sup.erl | erlang |
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>. | PeerDrive
Copyright ( C ) 2011 < jan DOT kloetzke AT freenet DOT de >
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
-module(peerdrive_servlet_sup).
-behaviour(supervisor).
-export([start_link/2]).
-export([spawn_servlet/3]).
-export([init/1]).
start_link(Module, ServletOpt) ->
supervisor:start_link(?MODULE, {Module, ServletOpt}).
init({Module, ServletOpt}) ->
{ok, {
{simple_one_for_one, 1000, 1},
[{
servlet,
{peerdrive_gen_servlet, start_link, [Module, ServletOpt]},
temporary,
brutal_kill,
worker,
[]
}]
}}.
spawn_servlet(SupervisorPid, ListenSock, ListenState) ->
supervisor:start_child(SupervisorPid, [self(), ListenSock, ListenState]).
|
db37f241b5f9e02177ef808e0e02baafbfc66acafb0e656ff816cbb486713294 | lambda-pi-plus/lambda-pi-plus | Main.hs | module Main where
import Common
import qualified ConstraintBased as CB
import System.Environment (getArgs)
import PatternUnify.Tm as Tm
import Constraint as Constraint
import PatternUnify.Kit
main :: IO ()
main = do
args <- getArgs
case args of
[] ->
repLP CB.checker True
(fileName:_) -> do
compileFile (lp CB.checker) (True, [], lpve, lpte) fileName
return ()
type LpInterp = Interpreter ITerm_ CTerm_ Tm.VAL Tm.VAL CTerm_ Tm.VAL
lp :: TypeChecker -> Interpreter ITerm_ CTerm_ Tm.VAL Tm.VAL CTerm_ Tm.VAL
lp checker = I { iname = "lambda-Pi",
iprompt = "LP> ",
iitype = \ v c -> checker (v, c),
iquote = error "TODO quote",
ieval = \e x -> Constraint.constrEval (lpte, e) x,
ihastype = id,
icprint = cPrint_ 0 0,
itprint = runPretty . pretty,
ivprint = runPretty . pretty,
iiparse = parseITerm_ 0 [],
isparse = parseStmt_ [],
iassume = \ s (x, t) -> lpassume checker s x t }
repLP :: TypeChecker -> Bool -> IO ()
repLP checker b = readevalprint (lp checker) (b, [], lpve, lpte)
lpassume checker state@(inter, out, ve, te) x t =
check (lp checker) state x (builtin $ Ann_ t (builtin $ Inf_ $ builtin $ Star_))
(\ (y, v, _) -> return ())
(\ (y, v) -> (inter, out, ve, (Global x, v) : te))
| null | https://raw.githubusercontent.com/lambda-pi-plus/lambda-pi-plus/78eba7ebb7b2ed94f7cb06f0d1aca4d07eb3626f/src/Main.hs | haskell | module Main where
import Common
import qualified ConstraintBased as CB
import System.Environment (getArgs)
import PatternUnify.Tm as Tm
import Constraint as Constraint
import PatternUnify.Kit
main :: IO ()
main = do
args <- getArgs
case args of
[] ->
repLP CB.checker True
(fileName:_) -> do
compileFile (lp CB.checker) (True, [], lpve, lpte) fileName
return ()
type LpInterp = Interpreter ITerm_ CTerm_ Tm.VAL Tm.VAL CTerm_ Tm.VAL
lp :: TypeChecker -> Interpreter ITerm_ CTerm_ Tm.VAL Tm.VAL CTerm_ Tm.VAL
lp checker = I { iname = "lambda-Pi",
iprompt = "LP> ",
iitype = \ v c -> checker (v, c),
iquote = error "TODO quote",
ieval = \e x -> Constraint.constrEval (lpte, e) x,
ihastype = id,
icprint = cPrint_ 0 0,
itprint = runPretty . pretty,
ivprint = runPretty . pretty,
iiparse = parseITerm_ 0 [],
isparse = parseStmt_ [],
iassume = \ s (x, t) -> lpassume checker s x t }
repLP :: TypeChecker -> Bool -> IO ()
repLP checker b = readevalprint (lp checker) (b, [], lpve, lpte)
lpassume checker state@(inter, out, ve, te) x t =
check (lp checker) state x (builtin $ Ann_ t (builtin $ Inf_ $ builtin $ Star_))
(\ (y, v, _) -> return ())
(\ (y, v) -> (inter, out, ve, (Global x, v) : te))
|
|
3f063855bd14650a369a86a95d98a0cde0a6509a2af0683487c19618e5ca5512 | alexkazik/qrcode | Special.hs | # LANGUAGE BinaryLiterals #
# LANGUAGE NoImplicitPrelude #
module Codec.QRCode.Intermediate.Special
( emptyNumericSegment
, emptyAlphanumericSegment
, emptyByteSegment
, emptyKanjiSegment
) where
import Codec.QRCode.Base
import Codec.QRCode.Data.QRSegment.Internal
emptyNumericSegment :: QRSegment
emptyNumericSegment =
encodeBits 4 0b0001 <> lengthSegment (10, 12, 14) 0
emptyAlphanumericSegment :: QRSegment
emptyAlphanumericSegment =
encodeBits 4 0b0010 <> lengthSegment (9, 11, 13) 0
emptyByteSegment :: QRSegment
emptyByteSegment =
encodeBits 4 0b0100 <> lengthSegment (8, 16, 16) 0
emptyKanjiSegment :: QRSegment
emptyKanjiSegment =
encodeBits 4 0b1000 <> lengthSegment (8, 10, 12) 0
| null | https://raw.githubusercontent.com/alexkazik/qrcode/7ee12de893c856a968dc1397602a7f81f8ea2c68/qrcode-core/src/Codec/QRCode/Intermediate/Special.hs | haskell | # LANGUAGE BinaryLiterals #
# LANGUAGE NoImplicitPrelude #
module Codec.QRCode.Intermediate.Special
( emptyNumericSegment
, emptyAlphanumericSegment
, emptyByteSegment
, emptyKanjiSegment
) where
import Codec.QRCode.Base
import Codec.QRCode.Data.QRSegment.Internal
emptyNumericSegment :: QRSegment
emptyNumericSegment =
encodeBits 4 0b0001 <> lengthSegment (10, 12, 14) 0
emptyAlphanumericSegment :: QRSegment
emptyAlphanumericSegment =
encodeBits 4 0b0010 <> lengthSegment (9, 11, 13) 0
emptyByteSegment :: QRSegment
emptyByteSegment =
encodeBits 4 0b0100 <> lengthSegment (8, 16, 16) 0
emptyKanjiSegment :: QRSegment
emptyKanjiSegment =
encodeBits 4 0b1000 <> lengthSegment (8, 10, 12) 0
|
|
fbd97102e15e1f4e1da41fa4605b3beafee30fca63da04b742aa9e74ebf5feb5 | tolysz/ghcjs-stack | System.hs | # OPTIONS_GHC -fno - warn - orphans #
module UnitTests.Distribution.System
( tests
) where
import Control.Monad (liftM2)
import Distribution.Text (Text(..), display, simpleParse)
import Distribution.System
import Test.Tasty
import Test.Tasty.QuickCheck
textRoundtrip :: (Show a, Eq a, Text a) => a -> Property
textRoundtrip x = simpleParse (display x) === Just x
tests :: [TestTree]
tests =
[ testProperty "Text OS round trip" (textRoundtrip :: OS -> Property)
, testProperty "Text Arch round trip" (textRoundtrip :: Arch -> Property)
, testProperty "Text Platform round trip" (textRoundtrip :: Platform -> Property)
]
instance Arbitrary OS where
arbitrary = elements knownOSs
instance Arbitrary Arch where
arbitrary = elements knownArches
instance Arbitrary Platform where
arbitrary = liftM2 Platform arbitrary arbitrary
| null | https://raw.githubusercontent.com/tolysz/ghcjs-stack/83d5be83e87286d984e89635d5926702c55b9f29/special/cabal/Cabal/tests/UnitTests/Distribution/System.hs | haskell | # OPTIONS_GHC -fno - warn - orphans #
module UnitTests.Distribution.System
( tests
) where
import Control.Monad (liftM2)
import Distribution.Text (Text(..), display, simpleParse)
import Distribution.System
import Test.Tasty
import Test.Tasty.QuickCheck
textRoundtrip :: (Show a, Eq a, Text a) => a -> Property
textRoundtrip x = simpleParse (display x) === Just x
tests :: [TestTree]
tests =
[ testProperty "Text OS round trip" (textRoundtrip :: OS -> Property)
, testProperty "Text Arch round trip" (textRoundtrip :: Arch -> Property)
, testProperty "Text Platform round trip" (textRoundtrip :: Platform -> Property)
]
instance Arbitrary OS where
arbitrary = elements knownOSs
instance Arbitrary Arch where
arbitrary = elements knownArches
instance Arbitrary Platform where
arbitrary = liftM2 Platform arbitrary arbitrary
|
|
9882a0f6b7e50f25fe0c7914979d1683d9d43f315a7262152771b76c68f92aeb | naveensundarg/prover | lisp.lisp | ;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: snark-lisp -*-
;;; File: lisp.lisp
The contents of this file are subject to the Mozilla Public License
;;; Version 1.1 (the "License"); you may not use this file except in
;;; compliance with the License. You may obtain a copy of the License at
;;; /
;;;
Software distributed under the License is distributed on an " AS IS "
;;; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
;;; License for the specific language governing rights and limitations
;;; under the License.
;;;
The Original Code is SNARK .
The Initial Developer of the Original Code is SRI International .
Portions created by the Initial Developer are Copyright ( C ) 1981 - 2011 .
All Rights Reserved .
;;;
Contributor(s ): < > .
(in-package :snark-lisp)
(defconstant none '$$none) ;special null value to use when NIL won't do
(defconstant true '$$true)
(defconstant false '$$false)
(defmacro definline (name lambda-list &body body)
#-clisp
`(progn
(defun ,name ,lambda-list ,@body)
(define-compiler-macro ,name (&rest arg-list)
(cons '(lambda ,lambda-list ,@body) arg-list)))
#+clisp
`(defun ,name ,lambda-list ,@body))
(definline neq (x y)
(not (eq x y)))
(definline neql (x y)
(not (eql x y)))
(definline nequal (x y)
(not (equal x y)))
(definline nequalp (x y)
(not (equalp x y)))
(definline iff (x y)
(eq (not x) (not y)))
(defmacro implies (x y)
;; implies is a macro so that y is not evaluated if x is false
`(if ,x ,y t))
(defmacro if-let (binding thenform elseform)
(let ((block (gensym)) (temp (gensym)))
`(block ,block
(let ((,temp ,(second binding)))
(when ,temp
(return-from ,block
(let ((,(first binding) ,temp))
,thenform))))
,elseform)))
(defmacro when-let (binding &rest forms)
`(if-let ,binding (progn ,@forms) nil))
(defun kwote (x &optional selectively)
(if (implies selectively (not (constantp x)))
(list 'quote x)
x))
(defun unquote (x)
(if (and (consp x) (eq 'quote (first x)))
(second x)
x))
(definline rrest (list)
(cddr list))
(definline rrrest (list)
(cdddr list))
(definline rrrrest (list)
(cddddr list))
(definline mklist (x)
(if (listp x) x (list x)))
(defun firstn (list num)
return a new list that contains the first num elements of list
(declare (type integer num))
(cond
((or (eql 0 num) (atom list))
nil)
(t
(cons (first list) (firstn (rest list) (- num 1))))))
(defun consn (x y num)
;; cons x and y n times
( cons ' a ' ( b ) 3 ) = ( a a a b )
(declare (type integer num))
(dotimes (dummy num)
(declare (type integer dummy) (ignorable dummy))
(push x y))
y)
(defun leafp (x y)
(if (atom y)
(eql x y)
(or (leafp x (car y)) (leafp x (cdr y)))))
(defun naturalp (x)
(and (integerp x) (not (minusp x))))
(defun ratiop (x)
(and (rationalp x) (not (integerp x))))
(defmacro carc (x)
`(car (the cons ,x)))
(defmacro cdrc (x)
`(cdr (the cons ,x)))
(defmacro caarcc (x)
`(carc (carc ,x)))
(defmacro cadrcc (x)
`(carc (cdrc ,x)))
(defmacro cdarcc (x)
`(cdrc (carc ,x)))
(defmacro cddrcc (x)
`(cdrc (cdrc ,x)))
(defmacro lcons (a* b* ab)
;; (lcons a* b* ab) does lazy cons of a* and b*
;; lcons does not evaluate a* or b* and returns nil if ab is nil
;; lcons does not evaluate b* and treats it as nil if (cdr ab) is nil
;; lcons returns ab if a* = (car ab) and b* = (cdr ab)
;; otherwise, lcons conses a* and b*
;;
;; lcons is useful for writing functions that map over lists
;; and return a modified list without unnecessary consing
;; for example, the following applies a substitution to a list of terms
;; (defun instantiate-list (terms subst)
( lcons ( instantiate - term ( first terms ) subst )
;; (instantiate-list (rest terms) subst)
;; terms))
(assert (symbolp ab))
(let ((tempa (gensym)) (tempb (gensym)) (tempa* (gensym)) (tempb* (gensym)))
(setf a* (sublis (list (cons `(car ,ab) tempa)
(cons `(carc ,ab) tempa)
(cons `(first ,ab) tempa)
(cons `(nth 0 ,ab) tempa))
a*
:test #'equal))
(setf b* (sublis (list (cons `(cdr ,ab) tempb)
(cons `(cdrc ,ab) tempb)
(cons `(rest ,ab) tempb)
(cons `(nthcdr 1 ,ab) tempb))
b*
:test #'equal))
`(if (null ,ab)
nil
(let* ((,tempa (car ,ab))
(,tempa* ,a*)
(,tempb (cdrc ,ab)))
(if (null ,tempb)
(if (eql ,tempa ,tempa*)
,ab
(cons ,tempa* nil))
(let ((,tempb* ,b*))
(if (and (eql ,tempb ,tempb*)
(eql ,tempa ,tempa*))
,ab
(cons ,tempa* ,tempb*))))))))
(definline cons-unless-nil (x &optional y)
;; returns y if x is nil, otherwise returns (cons x y)
;; if y is omitted: returns nil if x is nil, otherwise (list x)
(if (null x) y (cons x y)))
(defmacro push-unless-nil (item place)
;; doesn't evaluate place if item is nil
;; always returns nil
(let ((v (gensym)))
`(let ((,v ,item))
(unless (null ,v)
(push ,v ,place)
nil))))
(defmacro pushnew-unless-nil (item place &rest options)
;; doesn't evaluate place or options if item is nil
;; always returns nil
(let ((v (gensym)))
`(let ((,v ,item))
(unless (null ,v)
(pushnew ,v ,place ,@options)
nil))))
(defmacro dotails ((var listform &optional resultform) &body body)
dotails is just like dolist except the variable is bound
;; to successive tails instead of successive elements of the list
`(do ((,var ,listform (rest ,var)))
((endp ,var)
,resultform)
,@body))
(defmacro dopairs ((var1 var2 listform &optional resultform) &body body)
;; (dopairs (x y '(a b c)) (print (list x y))) prints (a b), (a c), and (b c)
;; doesn't handle declarations in body correctly
(let ((l1 (gensym)) (l2 (gensym)) (loop (gensym)))
`(do ((,l1 ,listform) ,var1 ,var2 ,l2)
((endp ,l1)
,resultform)
(setf ,var1 (pop ,l1))
(setf ,l2 ,l1)
,loop
(unless (endp ,l2)
(setf ,var2 (pop ,l2))
,@body
(go ,loop)))))
(defun choose (function list k)
;; apply function to lists of k items taken from list
(labels
((choose* (cc l k n)
(cond
((eql 0 k)
(funcall cc nil))
((eql n k)
(funcall cc l))
(t
(prog->
(decf n)
(pop l -> x)
(choose* l (- k 1) n ->* res)
(funcall cc (cons x res)))
(prog->
(choose* l k n ->* res)
(funcall cc res))))))
(let ((len (length list)))
(when (minusp k)
(incf k len))
(cl:assert (<= 0 k len))
(choose* function list k len)
nil)))
(defun integers-between (low high)
;; list of integers in [low,high]
(let ((i high)
(result nil))
(loop
(when (< i low)
(return result))
(push i result)
(decf i))))
(defun ints (low high)
;; list of integers in [low,high]
(integers-between low high))
(defun length= (x y)
;; if y is an integer then (= (length x) y)
;; if x is an integer then (= x (length y))
;; otherwise (= (length x) (length y))
(cond
((or (not (listp y)) (when (not (listp x)) (psetq x y y x) t))
(and (<= 0 y)
(loop
(cond
((endp x)
(return (eql 0 y)))
((eql 0 y)
(return nil))
(t
(setf x (rest x) y (- y 1)))))))
(t
(loop
(cond
((endp x)
(return (endp y)))
((endp y)
(return nil))
(t
(setf x (rest x) y (rest y))))))))
(defun length< (x y)
;; if y is an integer then (< (length x) y)
;; if x is an integer then (< x (length y))
;; otherwise (< (length x) (length y))
(cond
((not (listp y))
(and (<= 1 y)
(loop
(cond
((endp x)
(return t))
((eql 1 y)
(return nil))
(t
(setf x (rest x) y (- y 1)))))))
((not (listp x))
(or (> 0 x)
(loop
(cond
((endp y)
(return nil))
((eql 0 x)
(return t))
(t
(setf x (- x 1) y (rest y)))))))
(t
(loop
(cond
((endp x)
(return (not (endp y))))
((endp y)
(return nil))
(t
(setf x (rest x) y (rest y))))))))
(defun length<= (x y)
;; if y is an integer then (<= (length x) y)
;; if x is an integer then (<= x (length y))
;; otherwise (<= (length x) (length y))
(cond
((not (listp y))
(and (<= 0 y)
(loop
(cond
((endp x)
(return t))
((eql 0 y)
(return nil))
(t
(setf x (rest x) y (- y 1)))))))
((not (listp x))
(or (> 1 x)
(loop
(cond
((endp y)
(return nil))
((eql 1 x)
(return t))
(t
(setf x (- x 1) y (rest y)))))))
(t
(loop
(cond
((endp x)
(return t))
((endp y)
(return nil))
(t
(setf x (rest x) y (rest y))))))))
(definline length> (x y)
(length< y x))
(definline length>= (x y)
(length<= y x))
(defun acons+ (key delta alist &key test)
creates a new association list with datum associated with key adjusted up or down by delta
;; omits pairs with datum 0
(labels
((ac+ (alist)
(declare (type cons alist))
(let ((pair (first alist))
(alist1 (rest alist)))
(declare (type cons pair))
(cond
((if test (funcall test key (car pair)) (eql key (car pair)))
(let ((datum (+ (cdr pair) delta)))
(if (= 0 datum) alist1 (cons (cons key datum) alist1))))
((null alist1)
alist)
(t
(let ((alist1* (ac+ alist1)))
(if (eq alist1 alist1*) alist (cons pair alist1*))))))))
(cond
((= 0 delta)
alist)
((null alist)
(cons (cons key delta) nil))
(t
(let ((alist* (ac+ alist)))
(if (eq alist alist*) (cons (cons key delta) alist) alist*))))))
(defun alist-notany-plusp (alist)
(dolist (pair alist t)
(declare (type cons pair))
(when (plusp (cdr pair))
(return nil))))
(defun alist-notany-minusp (alist)
(dolist (pair alist t)
(declare (type cons pair))
(when (minusp (cdr pair))
(return nil))))
(defun cons-count (x)
(do ((n 0 (+ 1 (cons-count (carc x)) n))
(x x (cdrc x)))
((atom x)
n)))
(defun char-invert-case (ch)
(cond
((lower-case-p ch)
(char-upcase ch))
((upper-case-p ch)
(char-downcase ch))
(t
ch)))
(let ((case-preserved-readtable-cache nil))
(defun case-preserved-readtable (&optional (readtable *readtable*))
(cond
((eq :preserve (readtable-case readtable))
readtable)
((cdr (assoc readtable case-preserved-readtable-cache))
)
(t
(let ((new-readtable (copy-readtable readtable)))
(setf (readtable-case new-readtable) :preserve)
(setf case-preserved-readtable-cache (acons readtable new-readtable case-preserved-readtable-cache))
new-readtable)))))
(defun to-string (arg &rest more-args)
(declare (dynamic-extent more-args))
(flet ((string1 (x)
(cond
((stringp x)
x)
((symbolp x)
(symbol-name x))
((characterp x)
(string x))
(t
(let ((*print-radix* nil))
(cond
((numberp x)
(princ-to-string x))
(t
(let ((*readtable* (case-preserved-readtable)))
(princ-to-string x)))))))))
(if (null more-args)
(string1 arg)
(apply #'concatenate 'string (string1 arg) (mapcar #'string1 more-args)))))
(defun find-or-make-package (pkg)
(cond
((packagep pkg)
pkg)
((find-package pkg)
)
(t
(cerror "Make a package named ~A." "There is no package named ~A." (string pkg))
(make-package pkg :use '(:common-lisp)))))
(defun percentage (m n)
(values (round (* 100 m) n)))
(defun print-time (year month date hour minute second &optional (destination *standard-output*) (basic nil))
per the ISO 8601 standard
(format destination
(if basic
20020405T011216
2002 - 04 - 05T01:12:16
year month date hour minute second))
(defun print-universal-time (utime &optional (destination *standard-output*) (basic nil))
(mvlet (((values second minute hour date month year) (decode-universal-time utime)))
(print-time year month date hour minute second destination basic)))
(defun print-current-time (&optional (destination *standard-output*) (basic nil))
(print-universal-time (get-universal-time) destination basic))
(defun leap-year-p (year)
(and (eql 0 (mod year 4))
(implies (eql 0 (mod year 100))
(eql 0 (mod year 400)))))
(defun days-per-month (month year)
(let ((month (month-number month)))
(cl:assert month)
(case month
(2
(if (leap-year-p year) 29 28))
((4 6 9 11)
30)
(otherwise
31))))
(defun month-number (month)
(cond
((or (symbolp month) (stringp month))
(cdr (assoc (string month)
'(("JAN" . 1) ("JANUARY" . 1)
("FEB" . 2) ("FEBRUARY" . 2)
("MAR" . 3) ("MARCH" . 3)
("APR" . 4) ("APRIL" . 4)
("MAY" . 5)
("JUN" . 6) ("JUNE" . 6)
("JUL" . 7) ("JULY" . 7)
("AUG" . 8) ("AUGUST" . 8)
("SEP" . 9) ("SEPTEMBER" . 9)
("OCT" . 10) ("OCTOBER" . 10)
("NOV" . 11) ("NOVEMBER" . 11)
("DEC" . 12) ("DECEMBER" . 12))
:test #'string-equal)))
((and (integerp month) (<= 1 month 12))
month)
(t
nil)))
(defun print-args (&rest args)
(declare (dynamic-extent args))
(print args)
nil)
(defmacro define-plist-slot-accessor (type name)
(let ((fun (intern (to-string type "-" name) :snark))
(plist (intern (to-string type :-plist) :snark)))
`(progn
(#-(or allegro lispworks) definline #+(or allegro lispworks) defun ,fun (x)
(getf (,plist x) ',name))
(defun (setf ,fun) (value x)
(if (null value)
(progn (remf (,plist x) ',name) nil)
(setf (getf (,plist x) ',name) value))))))
(defvar *print-pretty2* nil)
#+ignore
(defmacro with-standard-io-syntax2 (&body forms)
(let ((pkg (gensym)))
`(let ((,pkg *package*))
(with-standard-io-syntax
(let ((*package* ,pkg)
(*print-case* :downcase)
(*print-pretty* *print-pretty2*)
# + ccl ( ccl:*print - abbreviate - quote * nil )
# + cmu ( pretty - print::*print - pprint - dispatch * ( pretty - print::make - pprint - dispatch - table ) )
# + sbcl ( sb - pretty::*print - pprint - dispatch * ( sb - pretty::make - pprint - dispatch - table ) )
stop clisp from printing decimal points , # 1= , etc
)
,@forms)))))
(defmacro with-standard-io-syntax2 (&body forms)
`(let ((*print-pretty* *print-pretty2*)
;; #+ccl (ccl:*print-abbreviate-quote* nil)
# + cmu ( pretty - print::*print - pprint - dispatch * ( pretty - print::make - pprint - dispatch - table ) )
# + sbcl ( sb - pretty::*print - pprint - dispatch * ( sb - pretty::make - pprint - dispatch - table ) )
stop clisp from printing decimal points , # 1= , etc
)
,@forms))
(defun quit ()
#+(or ccl cmu sbcl clisp lispworks) (common-lisp-user::quit)
#+allegro (excl::exit))
lisp.lisp EOF
| null | https://raw.githubusercontent.com/naveensundarg/prover/812baf098d8bf77e4d634cef4d12de94dcd1e113/snark-20120808r02/src/lisp.lisp | lisp | -*- Mode: Lisp; Syntax: Common-Lisp; Package: snark-lisp -*-
File: lisp.lisp
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
/
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
special null value to use when NIL won't do
implies is a macro so that y is not evaluated if x is false
cons x and y n times
(lcons a* b* ab) does lazy cons of a* and b*
lcons does not evaluate a* or b* and returns nil if ab is nil
lcons does not evaluate b* and treats it as nil if (cdr ab) is nil
lcons returns ab if a* = (car ab) and b* = (cdr ab)
otherwise, lcons conses a* and b*
lcons is useful for writing functions that map over lists
and return a modified list without unnecessary consing
for example, the following applies a substitution to a list of terms
(defun instantiate-list (terms subst)
(instantiate-list (rest terms) subst)
terms))
returns y if x is nil, otherwise returns (cons x y)
if y is omitted: returns nil if x is nil, otherwise (list x)
doesn't evaluate place if item is nil
always returns nil
doesn't evaluate place or options if item is nil
always returns nil
to successive tails instead of successive elements of the list
(dopairs (x y '(a b c)) (print (list x y))) prints (a b), (a c), and (b c)
doesn't handle declarations in body correctly
apply function to lists of k items taken from list
list of integers in [low,high]
list of integers in [low,high]
if y is an integer then (= (length x) y)
if x is an integer then (= x (length y))
otherwise (= (length x) (length y))
if y is an integer then (< (length x) y)
if x is an integer then (< x (length y))
otherwise (< (length x) (length y))
if y is an integer then (<= (length x) y)
if x is an integer then (<= x (length y))
otherwise (<= (length x) (length y))
omits pairs with datum 0
#+ccl (ccl:*print-abbreviate-quote* nil) | The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is SNARK .
The Initial Developer of the Original Code is SRI International .
Portions created by the Initial Developer are Copyright ( C ) 1981 - 2011 .
All Rights Reserved .
Contributor(s ): < > .
(in-package :snark-lisp)
(defconstant true '$$true)
(defconstant false '$$false)
(defmacro definline (name lambda-list &body body)
#-clisp
`(progn
(defun ,name ,lambda-list ,@body)
(define-compiler-macro ,name (&rest arg-list)
(cons '(lambda ,lambda-list ,@body) arg-list)))
#+clisp
`(defun ,name ,lambda-list ,@body))
(definline neq (x y)
(not (eq x y)))
(definline neql (x y)
(not (eql x y)))
(definline nequal (x y)
(not (equal x y)))
(definline nequalp (x y)
(not (equalp x y)))
(definline iff (x y)
(eq (not x) (not y)))
(defmacro implies (x y)
`(if ,x ,y t))
(defmacro if-let (binding thenform elseform)
(let ((block (gensym)) (temp (gensym)))
`(block ,block
(let ((,temp ,(second binding)))
(when ,temp
(return-from ,block
(let ((,(first binding) ,temp))
,thenform))))
,elseform)))
(defmacro when-let (binding &rest forms)
`(if-let ,binding (progn ,@forms) nil))
(defun kwote (x &optional selectively)
(if (implies selectively (not (constantp x)))
(list 'quote x)
x))
(defun unquote (x)
(if (and (consp x) (eq 'quote (first x)))
(second x)
x))
(definline rrest (list)
(cddr list))
(definline rrrest (list)
(cdddr list))
(definline rrrrest (list)
(cddddr list))
(definline mklist (x)
(if (listp x) x (list x)))
(defun firstn (list num)
return a new list that contains the first num elements of list
(declare (type integer num))
(cond
((or (eql 0 num) (atom list))
nil)
(t
(cons (first list) (firstn (rest list) (- num 1))))))
(defun consn (x y num)
( cons ' a ' ( b ) 3 ) = ( a a a b )
(declare (type integer num))
(dotimes (dummy num)
(declare (type integer dummy) (ignorable dummy))
(push x y))
y)
(defun leafp (x y)
(if (atom y)
(eql x y)
(or (leafp x (car y)) (leafp x (cdr y)))))
(defun naturalp (x)
(and (integerp x) (not (minusp x))))
(defun ratiop (x)
(and (rationalp x) (not (integerp x))))
(defmacro carc (x)
`(car (the cons ,x)))
(defmacro cdrc (x)
`(cdr (the cons ,x)))
(defmacro caarcc (x)
`(carc (carc ,x)))
(defmacro cadrcc (x)
`(carc (cdrc ,x)))
(defmacro cdarcc (x)
`(cdrc (carc ,x)))
(defmacro cddrcc (x)
`(cdrc (cdrc ,x)))
(defmacro lcons (a* b* ab)
( lcons ( instantiate - term ( first terms ) subst )
(assert (symbolp ab))
(let ((tempa (gensym)) (tempb (gensym)) (tempa* (gensym)) (tempb* (gensym)))
(setf a* (sublis (list (cons `(car ,ab) tempa)
(cons `(carc ,ab) tempa)
(cons `(first ,ab) tempa)
(cons `(nth 0 ,ab) tempa))
a*
:test #'equal))
(setf b* (sublis (list (cons `(cdr ,ab) tempb)
(cons `(cdrc ,ab) tempb)
(cons `(rest ,ab) tempb)
(cons `(nthcdr 1 ,ab) tempb))
b*
:test #'equal))
`(if (null ,ab)
nil
(let* ((,tempa (car ,ab))
(,tempa* ,a*)
(,tempb (cdrc ,ab)))
(if (null ,tempb)
(if (eql ,tempa ,tempa*)
,ab
(cons ,tempa* nil))
(let ((,tempb* ,b*))
(if (and (eql ,tempb ,tempb*)
(eql ,tempa ,tempa*))
,ab
(cons ,tempa* ,tempb*))))))))
(definline cons-unless-nil (x &optional y)
(if (null x) y (cons x y)))
(defmacro push-unless-nil (item place)
(let ((v (gensym)))
`(let ((,v ,item))
(unless (null ,v)
(push ,v ,place)
nil))))
(defmacro pushnew-unless-nil (item place &rest options)
(let ((v (gensym)))
`(let ((,v ,item))
(unless (null ,v)
(pushnew ,v ,place ,@options)
nil))))
(defmacro dotails ((var listform &optional resultform) &body body)
dotails is just like dolist except the variable is bound
`(do ((,var ,listform (rest ,var)))
((endp ,var)
,resultform)
,@body))
(defmacro dopairs ((var1 var2 listform &optional resultform) &body body)
(let ((l1 (gensym)) (l2 (gensym)) (loop (gensym)))
`(do ((,l1 ,listform) ,var1 ,var2 ,l2)
((endp ,l1)
,resultform)
(setf ,var1 (pop ,l1))
(setf ,l2 ,l1)
,loop
(unless (endp ,l2)
(setf ,var2 (pop ,l2))
,@body
(go ,loop)))))
(defun choose (function list k)
(labels
((choose* (cc l k n)
(cond
((eql 0 k)
(funcall cc nil))
((eql n k)
(funcall cc l))
(t
(prog->
(decf n)
(pop l -> x)
(choose* l (- k 1) n ->* res)
(funcall cc (cons x res)))
(prog->
(choose* l k n ->* res)
(funcall cc res))))))
(let ((len (length list)))
(when (minusp k)
(incf k len))
(cl:assert (<= 0 k len))
(choose* function list k len)
nil)))
(defun integers-between (low high)
(let ((i high)
(result nil))
(loop
(when (< i low)
(return result))
(push i result)
(decf i))))
(defun ints (low high)
(integers-between low high))
(defun length= (x y)
(cond
((or (not (listp y)) (when (not (listp x)) (psetq x y y x) t))
(and (<= 0 y)
(loop
(cond
((endp x)
(return (eql 0 y)))
((eql 0 y)
(return nil))
(t
(setf x (rest x) y (- y 1)))))))
(t
(loop
(cond
((endp x)
(return (endp y)))
((endp y)
(return nil))
(t
(setf x (rest x) y (rest y))))))))
(defun length< (x y)
(cond
((not (listp y))
(and (<= 1 y)
(loop
(cond
((endp x)
(return t))
((eql 1 y)
(return nil))
(t
(setf x (rest x) y (- y 1)))))))
((not (listp x))
(or (> 0 x)
(loop
(cond
((endp y)
(return nil))
((eql 0 x)
(return t))
(t
(setf x (- x 1) y (rest y)))))))
(t
(loop
(cond
((endp x)
(return (not (endp y))))
((endp y)
(return nil))
(t
(setf x (rest x) y (rest y))))))))
(defun length<= (x y)
(cond
((not (listp y))
(and (<= 0 y)
(loop
(cond
((endp x)
(return t))
((eql 0 y)
(return nil))
(t
(setf x (rest x) y (- y 1)))))))
((not (listp x))
(or (> 1 x)
(loop
(cond
((endp y)
(return nil))
((eql 1 x)
(return t))
(t
(setf x (- x 1) y (rest y)))))))
(t
(loop
(cond
((endp x)
(return t))
((endp y)
(return nil))
(t
(setf x (rest x) y (rest y))))))))
(definline length> (x y)
(length< y x))
(definline length>= (x y)
(length<= y x))
(defun acons+ (key delta alist &key test)
creates a new association list with datum associated with key adjusted up or down by delta
(labels
((ac+ (alist)
(declare (type cons alist))
(let ((pair (first alist))
(alist1 (rest alist)))
(declare (type cons pair))
(cond
((if test (funcall test key (car pair)) (eql key (car pair)))
(let ((datum (+ (cdr pair) delta)))
(if (= 0 datum) alist1 (cons (cons key datum) alist1))))
((null alist1)
alist)
(t
(let ((alist1* (ac+ alist1)))
(if (eq alist1 alist1*) alist (cons pair alist1*))))))))
(cond
((= 0 delta)
alist)
((null alist)
(cons (cons key delta) nil))
(t
(let ((alist* (ac+ alist)))
(if (eq alist alist*) (cons (cons key delta) alist) alist*))))))
(defun alist-notany-plusp (alist)
(dolist (pair alist t)
(declare (type cons pair))
(when (plusp (cdr pair))
(return nil))))
(defun alist-notany-minusp (alist)
(dolist (pair alist t)
(declare (type cons pair))
(when (minusp (cdr pair))
(return nil))))
(defun cons-count (x)
(do ((n 0 (+ 1 (cons-count (carc x)) n))
(x x (cdrc x)))
((atom x)
n)))
(defun char-invert-case (ch)
(cond
((lower-case-p ch)
(char-upcase ch))
((upper-case-p ch)
(char-downcase ch))
(t
ch)))
(let ((case-preserved-readtable-cache nil))
(defun case-preserved-readtable (&optional (readtable *readtable*))
(cond
((eq :preserve (readtable-case readtable))
readtable)
((cdr (assoc readtable case-preserved-readtable-cache))
)
(t
(let ((new-readtable (copy-readtable readtable)))
(setf (readtable-case new-readtable) :preserve)
(setf case-preserved-readtable-cache (acons readtable new-readtable case-preserved-readtable-cache))
new-readtable)))))
(defun to-string (arg &rest more-args)
(declare (dynamic-extent more-args))
(flet ((string1 (x)
(cond
((stringp x)
x)
((symbolp x)
(symbol-name x))
((characterp x)
(string x))
(t
(let ((*print-radix* nil))
(cond
((numberp x)
(princ-to-string x))
(t
(let ((*readtable* (case-preserved-readtable)))
(princ-to-string x)))))))))
(if (null more-args)
(string1 arg)
(apply #'concatenate 'string (string1 arg) (mapcar #'string1 more-args)))))
(defun find-or-make-package (pkg)
(cond
((packagep pkg)
pkg)
((find-package pkg)
)
(t
(cerror "Make a package named ~A." "There is no package named ~A." (string pkg))
(make-package pkg :use '(:common-lisp)))))
(defun percentage (m n)
(values (round (* 100 m) n)))
(defun print-time (year month date hour minute second &optional (destination *standard-output*) (basic nil))
per the ISO 8601 standard
(format destination
(if basic
20020405T011216
2002 - 04 - 05T01:12:16
year month date hour minute second))
(defun print-universal-time (utime &optional (destination *standard-output*) (basic nil))
(mvlet (((values second minute hour date month year) (decode-universal-time utime)))
(print-time year month date hour minute second destination basic)))
(defun print-current-time (&optional (destination *standard-output*) (basic nil))
(print-universal-time (get-universal-time) destination basic))
(defun leap-year-p (year)
(and (eql 0 (mod year 4))
(implies (eql 0 (mod year 100))
(eql 0 (mod year 400)))))
(defun days-per-month (month year)
(let ((month (month-number month)))
(cl:assert month)
(case month
(2
(if (leap-year-p year) 29 28))
((4 6 9 11)
30)
(otherwise
31))))
(defun month-number (month)
(cond
((or (symbolp month) (stringp month))
(cdr (assoc (string month)
'(("JAN" . 1) ("JANUARY" . 1)
("FEB" . 2) ("FEBRUARY" . 2)
("MAR" . 3) ("MARCH" . 3)
("APR" . 4) ("APRIL" . 4)
("MAY" . 5)
("JUN" . 6) ("JUNE" . 6)
("JUL" . 7) ("JULY" . 7)
("AUG" . 8) ("AUGUST" . 8)
("SEP" . 9) ("SEPTEMBER" . 9)
("OCT" . 10) ("OCTOBER" . 10)
("NOV" . 11) ("NOVEMBER" . 11)
("DEC" . 12) ("DECEMBER" . 12))
:test #'string-equal)))
((and (integerp month) (<= 1 month 12))
month)
(t
nil)))
(defun print-args (&rest args)
(declare (dynamic-extent args))
(print args)
nil)
(defmacro define-plist-slot-accessor (type name)
(let ((fun (intern (to-string type "-" name) :snark))
(plist (intern (to-string type :-plist) :snark)))
`(progn
(#-(or allegro lispworks) definline #+(or allegro lispworks) defun ,fun (x)
(getf (,plist x) ',name))
(defun (setf ,fun) (value x)
(if (null value)
(progn (remf (,plist x) ',name) nil)
(setf (getf (,plist x) ',name) value))))))
(defvar *print-pretty2* nil)
#+ignore
(defmacro with-standard-io-syntax2 (&body forms)
(let ((pkg (gensym)))
`(let ((,pkg *package*))
(with-standard-io-syntax
(let ((*package* ,pkg)
(*print-case* :downcase)
(*print-pretty* *print-pretty2*)
# + ccl ( ccl:*print - abbreviate - quote * nil )
# + cmu ( pretty - print::*print - pprint - dispatch * ( pretty - print::make - pprint - dispatch - table ) )
# + sbcl ( sb - pretty::*print - pprint - dispatch * ( sb - pretty::make - pprint - dispatch - table ) )
stop clisp from printing decimal points , # 1= , etc
)
,@forms)))))
(defmacro with-standard-io-syntax2 (&body forms)
`(let ((*print-pretty* *print-pretty2*)
# + cmu ( pretty - print::*print - pprint - dispatch * ( pretty - print::make - pprint - dispatch - table ) )
# + sbcl ( sb - pretty::*print - pprint - dispatch * ( sb - pretty::make - pprint - dispatch - table ) )
stop clisp from printing decimal points , # 1= , etc
)
,@forms))
(defun quit ()
#+(or ccl cmu sbcl clisp lispworks) (common-lisp-user::quit)
#+allegro (excl::exit))
lisp.lisp EOF
|
92c381ce63bedce369b27ed42e9b601e226a26545ead89e1be077ce8dd086fae | DrTom/clj-pg-types | uuid_test.clj | (ns pg-types.uuid-test
(:require
[pg-types.all]
[pg-types.connection :refer :all]
[clojure.java.jdbc :as jdbc]
[clojure.test :refer :all]))
(def db-spec (env-db-spec))
(deftest uuid
(jdbc/with-db-transaction [tx db-spec]
(jdbc/db-do-commands tx "CREATE TEMP TABLE test (id uuid)")
(let [str-uuid "65b85773-c935-439f-a3c0-6c538f84825d"
uuid (java.util.UUID/fromString str-uuid) ]
(testing "result of inserting a string value"
(let [result-value (:id (first (jdbc/insert! tx :test {:id str-uuid})))]
(testing "is the equivalent uuid type" (is (= result-value uuid)))))
(testing "result of querying with a string value"
(let [res (first (jdbc/query tx ["SELECT * FROM test WHERE id = ?" str-uuid]))]
(testing "yields the equivalent uuid type" (is (= res {:id uuid})))))
(testing "result of querying with a uuid value"
(let [res (first (jdbc/query tx ["SELECT * FROM test WHERE id = ?" uuid]))]
(testing "yields the equivalent uuid type" (is (= res {:id uuid}))))))
(let [ruuid (java.util.UUID/randomUUID)]
(testing "result of inserting a random uuid of type UUID"
(let [result-value (:id (first (jdbc/insert! tx :test {:id ruuid})))]
(testing "is the equivalent uuid type" (is (= result-value ruuid))))))))
| null | https://raw.githubusercontent.com/DrTom/clj-pg-types/d847735c46b2da173fd50a6ebe492bead0d75dd5/test/pg_types/uuid_test.clj | clojure | (ns pg-types.uuid-test
(:require
[pg-types.all]
[pg-types.connection :refer :all]
[clojure.java.jdbc :as jdbc]
[clojure.test :refer :all]))
(def db-spec (env-db-spec))
(deftest uuid
(jdbc/with-db-transaction [tx db-spec]
(jdbc/db-do-commands tx "CREATE TEMP TABLE test (id uuid)")
(let [str-uuid "65b85773-c935-439f-a3c0-6c538f84825d"
uuid (java.util.UUID/fromString str-uuid) ]
(testing "result of inserting a string value"
(let [result-value (:id (first (jdbc/insert! tx :test {:id str-uuid})))]
(testing "is the equivalent uuid type" (is (= result-value uuid)))))
(testing "result of querying with a string value"
(let [res (first (jdbc/query tx ["SELECT * FROM test WHERE id = ?" str-uuid]))]
(testing "yields the equivalent uuid type" (is (= res {:id uuid})))))
(testing "result of querying with a uuid value"
(let [res (first (jdbc/query tx ["SELECT * FROM test WHERE id = ?" uuid]))]
(testing "yields the equivalent uuid type" (is (= res {:id uuid}))))))
(let [ruuid (java.util.UUID/randomUUID)]
(testing "result of inserting a random uuid of type UUID"
(let [result-value (:id (first (jdbc/insert! tx :test {:id ruuid})))]
(testing "is the equivalent uuid type" (is (= result-value ruuid))))))))
|
|
d344014b66d4784f0f47dd5957c97c0d5789d583c8e479038ed5f5c7c4f7f5a0 | ku-fpg/hermit | GHC.hs | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
module HERMIT.Dictionary.GHC
* GHC - based Transformations
| This module contains transformations that are reflections of GHC functions , or derived from GHC functions .
externals
-- ** Dynamic Loading
, loadLemmaLibraryT
, LemmaLibrary
, injectDependencyT
-- ** Substitution
, substR
-- ** Utilities
, dynFlagsT
, arityOf
* * Lifted GHC capabilities
-- A zombie is an identifer that has 'OccInfo' 'IAmDead', but still has occurrences.
, lintExprT
, lintModuleT
, lintClauseT
, occurAnalyseR
, occurAnalyseChangedR
, occurAnalyseExprChangedR
, occurAnalyseAndDezombifyR
, occurrenceAnalysisR
, deShadowProgR
, dezombifyR
, buildDictionary
, buildDictionaryT
, buildTypeable
) where
import qualified Bag
import qualified CoreLint
#if __GLASGOW_HASKELL__ > 710
import TcRnMonad (getCtLocM)
import TcRnTypes (cc_ev)
#else
import TcRnMonad (getCtLoc)
#endif
import Control.Arrow
import Control.Monad
import Control.Monad.IO.Class
import Data.Char (isSpace)
import Data.List (mapAccumL, nub)
import qualified Data.Map as M
import Data.String
import HERMIT.Core
import HERMIT.Context
import HERMIT.External
import HERMIT.GHC
import HERMIT.Kure
import HERMIT.Lemma
import HERMIT.Monad
import HERMIT.Name
import HERMIT.PrettyPrinter.Common
import HERMIT.PrettyPrinter.Glyphs
import qualified HERMIT.PrettyPrinter.Clean as Clean
------------------------------------------------------------------------
| Externals that reflect GHC functions , or are derived from GHC functions .
externals :: [External]
externals =
[ external "deshadow-prog" (promoteProgR deShadowProgR :: RewriteH LCore)
[ "Deshadow a program." ] .+ Deep
, external "dezombify" (promoteExprR dezombifyR :: RewriteH LCore)
[ "Zap the occurrence information in the current identifer if it is a zombie."] .+ Shallow
, external "occurrence-analysis" (occurrenceAnalysisR :: RewriteH LCore)
[ "Perform dependency analysis on all sub-expressions; simplifying and updating identifer info."] .+ Deep
, external "lint-expr" (promoteExprT lintExprT :: TransformH LCoreTC String)
[ "Runs GHC's Core Lint, which typechecks the current expression."
, "Note: this can miss several things that a whole-module core lint will find."
, "For instance, running this on the RHS of a binding, the type of the RHS will"
, "not be checked against the type of the binding. Running on the whole let expression"
, "will catch that however."] .+ Deep .+ Debug .+ Query
, external "lint-module" (promoteModGutsT lintModuleT :: TransformH LCoreTC String)
[ "Runs GHC's Core Lint, which typechecks the current module."] .+ Deep .+ Debug .+ Query
, external "lint" (promoteT lintClauseT :: TransformH LCoreTC String)
[ "Lint check a clause." ]
, external "load-lemma-library" (flip loadLemmaLibraryT Nothing :: HermitName -> TransformH LCore String)
[ "Dynamically load a library of lemmas." ]
, external "load-lemma-library" ((\nm -> loadLemmaLibraryT nm . Just) :: HermitName -> LemmaName -> TransformH LCore String)
[ "Dynamically load a specific lemma from a library of lemmas." ]
, external "inject-dependency" (promoteModGutsT . injectDependencyT . mkModuleName :: String -> TransformH LCore ())
[ "Inject a dependency on the given module." ]
]
------------------------------------------------------------------------
-- | Substitute all occurrences of a variable with an expression, in either a program, an expression, or a case alternative.
substR :: MonadCatch m => Var -> CoreExpr -> Rewrite c m Core
substR v e = setFailMsg "Can only perform substitution on expressions, case alternatives or programs." $
promoteExprR (arr $ substCoreExpr v e) <+ promoteProgR (substTopBindR v e) <+ promoteAltR (arr $ substCoreAlt v e)
-- | Substitute all occurrences of a variable with an expression, in a program.
substTopBindR :: Monad m => Var -> CoreExpr -> Rewrite c m CoreProg
substTopBindR v e = contextfreeT $ \ p -> do
TODO . Do we need to initialize the emptySubst with bindFreeVars ?
mkEmptySubst ( mkInScopeSet ( exprFreeVars exp ) )
return $ bindsToProg $ snd (mapAccumL substBind (extendSubst emptySub v e) (progToBinds p))
------------------------------------------------------------------------
| [ from GHC documentation ] De - shadowing the program is sometimes a useful pre - pass .
-- It can be done simply by running over the bindings with an empty substitution,
-- becuase substitution returns a result that has no-shadowing guaranteed.
--
-- (Actually, within a single /type/ there might still be shadowing, because
-- 'substTy' is a no-op for the empty substitution, but that's probably OK.)
deShadowProgR :: Monad m => Rewrite c m CoreProg
deShadowProgR = arr (bindsToProg . deShadowBinds . progToBinds)
--------------------------------------------------------
-- | Try to figure out the arity of an identifier.
arityOf :: ReadBindings c => c -> Id -> Int
arityOf c i =
case lookupHermitBinding i c of
Nothing -> idArity i
-- Note: the exprArity will call idArity if
-- it hits an id; perhaps we should do the counting
The advantage of idArity is it will terminate , though .
Just b -> runKureM exprArity
(const 0) -- conservative estimate, as we don't know what the expression looks like
(hermitBindingExpr b)
-------------------------------------------
-- | Run the Core Lint typechecker.
-- Fails on errors, with error messages.
-- Succeeds returning warnings.
lintModuleT :: TransformH ModGuts String
lintModuleT =
do dynFlags <- dynFlagsT
bnds <- arr mg_binds
#if __GLASGOW_HASKELL__ <= 710
-- [] are vars to treat as in scope, used by GHCi
' CoreDesugar ' so we check for global ids , but not INLINE loop breakers , see notes in GHC 's CoreLint module .
let (warns, errs) = CoreLint.lintCoreBindings CoreDesugar [] bnds
#else
let (warns, errs) = CoreLint.lintCoreBindings dynFlags CoreDesugar [] bnds
#endif
dumpSDocs endMsg = Bag.foldBag (\ d r -> d ++ ('\n':r)) (showSDoc dynFlags) endMsg
if Bag.isEmptyBag errs
then return $ dumpSDocs "Core Lint Passed" warns
else fail $ "Core Lint Failed:\n" ++ dumpSDocs "" errs
-- | Note: this can miss several things that a whole-module core lint will find.
For instance , running this on the RHS of a binding , the type of the RHS will
-- not be checked against the type of the binding. Running on the whole let expression
-- will catch that however.
lintExprT :: (BoundVars c, Monad m, HasDynFlags m) => Transform c m CoreExpr String
lintExprT = transform $ \ c e -> do
dflags <- getDynFlags
case e of
Type _ -> fail "cannot core lint types."
_ -> maybe (return "Core Lint Passed") (fail . showSDoc dflags)
#if __GLASGOW_HASKELL__ <= 710
(CoreLint.lintExpr (varSetElems $ boundVars c) e)
#else
(CoreLint.lintExpr dflags (varSetElems $ boundVars c) e)
#endif
-------------------------------------------
-- | Lifted version of 'getDynFlags'.
dynFlagsT :: HasDynFlags m => Transform c m a DynFlags
dynFlagsT = constT getDynFlags
-------------------------------------------
----------------------------------------------------------------------
TODO : Ideally , occurAnalyseExprR would fail if nothing changed .
-- This is tricky though, as it's not just the structure of the expression, but also the meta-data.
-- | Zap the 'OccInfo' in a zombie identifier.
dezombifyR :: (ExtendPath c Crumb, Monad m) => Rewrite c m CoreExpr
dezombifyR = varR (acceptR isDeadBinder >>^ zapVarOccInfo)
-- | Apply 'occurAnalyseExprR' to all sub-expressions.
occurAnalyseR :: (Injection CoreExpr u, Walker c u, MonadCatch m) => Rewrite c m u
occurAnalyseR = let r = promoteExprR (arr occurAnalyseExpr_NoBinderSwap) -- See Note [No Binder Swap]
go = r <+ anyR go
in tryR go -- always succeed
Note [ No Binder Swap ]
The binder swap performed by occurrence analysis in GHC < = 7.8.3 is buggy
in that it can lead to unintended variable capture ( Trac # 9440 ) . Concretely ,
this will send bash into a loop , or cause core lint to fail . As this is an
un - expected change as far as HERMIT users are concerned anyway , we use the
version that does n't perform the binder swap .
Note [No Binder Swap]
The binder swap performed by occurrence analysis in GHC <= 7.8.3 is buggy
in that it can lead to unintended variable capture (Trac #9440). Concretely,
this will send bash into a loop, or cause core lint to fail. As this is an
un-expected change as far as HERMIT users are concerned anyway, we use the
version that doesn't perform the binder swap.
-}
-- | Occurrence analyse an expression, failing if the result is syntactically equal to the initial expression.
occurAnalyseExprChangedR :: MonadCatch m => Rewrite c m CoreExpr
occurAnalyseExprChangedR = changedByR exprSyntaxEq (arr occurAnalyseExpr_NoBinderSwap) -- See Note [No Binder Swap]
-- | Occurrence analyse all sub-expressions, failing if the result is syntactically equal to the initial expression.
occurAnalyseChangedR :: (AddBindings c, ExtendPath c Crumb, HasEmptyContext c, LemmaContext c, ReadPath c Crumb, MonadCatch m) => Rewrite c m LCore
occurAnalyseChangedR = changedByR lcoreSyntaxEq occurAnalyseR
| Run GHC 's occurrence analyser , and also eliminate any zombies .
occurAnalyseAndDezombifyR :: (ExtendPath c Crumb, MonadCatch m, Walker c u, Injection CoreExpr u) => Rewrite c m u
occurAnalyseAndDezombifyR = allbuR (tryR $ promoteExprR dezombifyR) >>> occurAnalyseR
occurrenceAnalysisR :: (ExtendPath c Crumb, MonadCatch m, Walker c LCore) => Rewrite c m LCore
occurrenceAnalysisR = occurAnalyseAndDezombifyR
----------------------------------------------------------------------
-- TODO: this is mostly an example, move somewhere?
buildTypeable :: (HasDynFlags m, HasHermitMEnv m, LiftCoreM m, MonadIO m) => Type -> m (Id, [CoreBind])
buildTypeable ty = do
evar <- runTcM $ do
cls <- tcLookupClass typeableClassName
recall that is now poly - kinded
newEvVar predTy
buildDictionary evar
-- | Build a dictionary for the given
buildDictionary :: (HasDynFlags m, HasHermitMEnv m, LiftCoreM m, MonadIO m) => Id -> m (Id, [CoreBind])
buildDictionary evar = do
(i, bs) <- runTcM $ do
#if __GLASGOW_HASKELL__ > 710
loc <- getCtLocM (GivenOrigin UnkSkol) Nothing
#else
loc <- getCtLoc $ GivenOrigin UnkSkol
#endif
let predTy = varType evar
#if __GLASGOW_HASKELL__ > 710
nonC = mkNonCanonical $ CtWanted { ctev_pred = predTy, ctev_dest = EvVarDest evar, ctev_loc = loc }
wCs = mkSimpleWC [cc_ev nonC]
-- TODO: Make sure solveWanteds is the right function to call.
(_wCs', bnds) <- second evBindMapBinds <$> runTcS (solveWanteds wCs)
#else
nonC = mkNonCanonical $ CtWanted { ctev_pred = predTy, ctev_evar = evar, ctev_loc = loc }
wCs = mkSimpleWC [nonC]
(_wCs', bnds) <- solveWantedsTcM wCs
#endif
-- reportAllUnsolved _wCs' -- this is causing a panic with dictionary instantiation
-- revist and fix!
return (evar, bnds)
bnds <- runDsM $ dsEvBinds bs
return (i,bnds)
buildDictionaryT :: (HasDynFlags m, HasHermitMEnv m, LiftCoreM m, MonadCatch m, MonadIO m, MonadUnique m)
=> Transform c m Type CoreExpr
buildDictionaryT = prefixFailMsg "buildDictionaryT failed: " $ contextfreeT $ \ ty -> do
dflags <- getDynFlags
binder <- newIdH ("$d" ++ zEncodeString (filter (not . isSpace) (showPpr dflags ty))) ty
(i,bnds) <- buildDictionary binder
guardMsg (notNull bnds) "no dictionary bindings generated."
return $ case bnds of
[NonRec v e] | i == v -> e -- the common case that we would have gotten a single non-recursive let
_ -> mkCoreLets bnds (varToCoreExpr i)
----------------------------------------------------------------------
lintClauseT :: forall c m.
( AddBindings c, BoundVars c, ExtendPath c Crumb, HasEmptyContext c, LemmaContext c, ReadPath c Crumb
, HasDynFlags m, MonadCatch m )
=> Transform c m Clause String
lintClauseT = do
strs <- extractT (collectPruneT (promoteExprT $ lintExprT `catchM` return) :: Transform c m LCore [String])
let strs' = nub $ filter notNull strs
guardMsg (null strs' || (strs' == ["Core Lint Passed"])) $ unlines strs'
return "Core Lint Passed"
----------------------------------------------------------------------
-- | A LemmaLibrary is a transformation that produces a set of lemmas,
-- which are then added to the lemma store. It is not allowed to insert
-- its own lemmas directly (if it tries they are throw away), but can
-- certainly read the existing store.
type LemmaLibrary = TransformH () Lemmas
loadLemmaLibraryT :: HermitName -> Maybe LemmaName -> TransformH x String
loadLemmaLibraryT nm mblnm = prefixFailMsg "Loading lemma library failed: " $
contextonlyT $ \ c -> do
hscEnv <- getHscEnv
comp <- liftAndCatchIO $ loadLemmaLibrary hscEnv nm
ls <- applyT comp c () -- TODO: discard side effects
nls <- maybe (return $ M.toList ls)
(\lnm -> maybe (fail $ show lnm ++ " not found in library.")
(\ l -> return [(lnm,l)])
(M.lookup lnm ls))
mblnm
nls' <- flip filterM nls $ \ (n, l) -> do
er <- attemptM $ applyT lintClauseT c $ lemmaC l
case er of
Left msg -> do
let pp = Clean.pretty { pOptions = (pOptions Clean.pretty) { po_exprTypes = Detailed } }
d <- applyT (liftPrettyH (pOptions pp) $ pLCoreTC pp) c $ inject $ lemmaC l
let Glyphs gs = renderCode (pOptions pp) d
liftIO $ do
putStr "\n" >> sequence_ [ withStyle s t | Glyph t s <- gs ] >> putStr "\n"
putStrLn $ "Not adding lemma " ++ show n ++ " because lint failed.\n" ++ msg
return False
Right _ -> return True
guardMsg (not (null nls')) "no lemmas to load."
m <- getLemmas
putLemmas $ (M.fromList nls') `M.union` m
return $ "Successfully loaded library " ++ show nm
loadLemmaLibrary :: HscEnv -> HermitName -> IO LemmaLibrary
loadLemmaLibrary hscEnv hnm = do
name <- lookupHermitNameForPlugins hscEnv varNS hnm
lib_tycon_name <- lookupHermitNameForPlugins hscEnv tyConClassNS $ fromString "HERMIT.Dictionary.GHC.LemmaLibrary"
lib_tycon <- forceLoadTyCon hscEnv lib_tycon_name
mb_v <- getValueSafely hscEnv name $ mkTyConTy lib_tycon
let dflags = hsc_dflags hscEnv
maybe (fail $ showSDoc dflags $ hsep
[ ptext (sLit "The value"), ppr name
, ptext (sLit "did not have the type")
, ppr lib_tycon, ptext (sLit "as required.")])
return mb_v
lookupHermitNameForPlugins :: HscEnv -> NameSpace -> HermitName -> IO Name
lookupHermitNameForPlugins hscEnv ns hnm = do
modName <- maybe (fail "name must be fully qualified with module name.") return (hnModuleName hnm)
let dflags = hsc_dflags hscEnv
rdrName = toRdrName ns hnm
mbName <- lookupRdrNameInModuleForPlugins hscEnv modName rdrName
maybe (fail $ showSDoc dflags $ hsep
[ ptext (sLit "The module"), ppr modName
, ptext (sLit "did not export the name")
, ppr rdrName ])
return mbName
injectDependencyT :: (LiftCoreM m, MonadIO m) => ModuleName -> Transform c m ModGuts ()
injectDependencyT mn = contextfreeT $ \ guts -> do
env <- getHscEnv
liftIO $ injectDependency env guts mn
| null | https://raw.githubusercontent.com/ku-fpg/hermit/3e7be430fae74a9e3860b8b574f36efbf9648dec/src/HERMIT/Dictionary/GHC.hs | haskell | ** Dynamic Loading
** Substitution
** Utilities
A zombie is an identifer that has 'OccInfo' 'IAmDead', but still has occurrences.
----------------------------------------------------------------------
----------------------------------------------------------------------
| Substitute all occurrences of a variable with an expression, in either a program, an expression, or a case alternative.
| Substitute all occurrences of a variable with an expression, in a program.
----------------------------------------------------------------------
It can be done simply by running over the bindings with an empty substitution,
becuase substitution returns a result that has no-shadowing guaranteed.
(Actually, within a single /type/ there might still be shadowing, because
'substTy' is a no-op for the empty substitution, but that's probably OK.)
------------------------------------------------------
| Try to figure out the arity of an identifier.
Note: the exprArity will call idArity if
it hits an id; perhaps we should do the counting
conservative estimate, as we don't know what the expression looks like
-----------------------------------------
| Run the Core Lint typechecker.
Fails on errors, with error messages.
Succeeds returning warnings.
[] are vars to treat as in scope, used by GHCi
| Note: this can miss several things that a whole-module core lint will find.
not be checked against the type of the binding. Running on the whole let expression
will catch that however.
-----------------------------------------
| Lifted version of 'getDynFlags'.
-----------------------------------------
--------------------------------------------------------------------
This is tricky though, as it's not just the structure of the expression, but also the meta-data.
| Zap the 'OccInfo' in a zombie identifier.
| Apply 'occurAnalyseExprR' to all sub-expressions.
See Note [No Binder Swap]
always succeed
| Occurrence analyse an expression, failing if the result is syntactically equal to the initial expression.
See Note [No Binder Swap]
| Occurrence analyse all sub-expressions, failing if the result is syntactically equal to the initial expression.
--------------------------------------------------------------------
TODO: this is mostly an example, move somewhere?
| Build a dictionary for the given
TODO: Make sure solveWanteds is the right function to call.
reportAllUnsolved _wCs' -- this is causing a panic with dictionary instantiation
revist and fix!
the common case that we would have gotten a single non-recursive let
--------------------------------------------------------------------
--------------------------------------------------------------------
| A LemmaLibrary is a transformation that produces a set of lemmas,
which are then added to the lemma store. It is not allowed to insert
its own lemmas directly (if it tries they are throw away), but can
certainly read the existing store.
TODO: discard side effects | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
module HERMIT.Dictionary.GHC
* GHC - based Transformations
| This module contains transformations that are reflections of GHC functions , or derived from GHC functions .
externals
, loadLemmaLibraryT
, LemmaLibrary
, injectDependencyT
, substR
, dynFlagsT
, arityOf
* * Lifted GHC capabilities
, lintExprT
, lintModuleT
, lintClauseT
, occurAnalyseR
, occurAnalyseChangedR
, occurAnalyseExprChangedR
, occurAnalyseAndDezombifyR
, occurrenceAnalysisR
, deShadowProgR
, dezombifyR
, buildDictionary
, buildDictionaryT
, buildTypeable
) where
import qualified Bag
import qualified CoreLint
#if __GLASGOW_HASKELL__ > 710
import TcRnMonad (getCtLocM)
import TcRnTypes (cc_ev)
#else
import TcRnMonad (getCtLoc)
#endif
import Control.Arrow
import Control.Monad
import Control.Monad.IO.Class
import Data.Char (isSpace)
import Data.List (mapAccumL, nub)
import qualified Data.Map as M
import Data.String
import HERMIT.Core
import HERMIT.Context
import HERMIT.External
import HERMIT.GHC
import HERMIT.Kure
import HERMIT.Lemma
import HERMIT.Monad
import HERMIT.Name
import HERMIT.PrettyPrinter.Common
import HERMIT.PrettyPrinter.Glyphs
import qualified HERMIT.PrettyPrinter.Clean as Clean
| Externals that reflect GHC functions , or are derived from GHC functions .
externals :: [External]
externals =
[ external "deshadow-prog" (promoteProgR deShadowProgR :: RewriteH LCore)
[ "Deshadow a program." ] .+ Deep
, external "dezombify" (promoteExprR dezombifyR :: RewriteH LCore)
[ "Zap the occurrence information in the current identifer if it is a zombie."] .+ Shallow
, external "occurrence-analysis" (occurrenceAnalysisR :: RewriteH LCore)
[ "Perform dependency analysis on all sub-expressions; simplifying and updating identifer info."] .+ Deep
, external "lint-expr" (promoteExprT lintExprT :: TransformH LCoreTC String)
[ "Runs GHC's Core Lint, which typechecks the current expression."
, "Note: this can miss several things that a whole-module core lint will find."
, "For instance, running this on the RHS of a binding, the type of the RHS will"
, "not be checked against the type of the binding. Running on the whole let expression"
, "will catch that however."] .+ Deep .+ Debug .+ Query
, external "lint-module" (promoteModGutsT lintModuleT :: TransformH LCoreTC String)
[ "Runs GHC's Core Lint, which typechecks the current module."] .+ Deep .+ Debug .+ Query
, external "lint" (promoteT lintClauseT :: TransformH LCoreTC String)
[ "Lint check a clause." ]
, external "load-lemma-library" (flip loadLemmaLibraryT Nothing :: HermitName -> TransformH LCore String)
[ "Dynamically load a library of lemmas." ]
, external "load-lemma-library" ((\nm -> loadLemmaLibraryT nm . Just) :: HermitName -> LemmaName -> TransformH LCore String)
[ "Dynamically load a specific lemma from a library of lemmas." ]
, external "inject-dependency" (promoteModGutsT . injectDependencyT . mkModuleName :: String -> TransformH LCore ())
[ "Inject a dependency on the given module." ]
]
substR :: MonadCatch m => Var -> CoreExpr -> Rewrite c m Core
substR v e = setFailMsg "Can only perform substitution on expressions, case alternatives or programs." $
promoteExprR (arr $ substCoreExpr v e) <+ promoteProgR (substTopBindR v e) <+ promoteAltR (arr $ substCoreAlt v e)
substTopBindR :: Monad m => Var -> CoreExpr -> Rewrite c m CoreProg
substTopBindR v e = contextfreeT $ \ p -> do
TODO . Do we need to initialize the emptySubst with bindFreeVars ?
mkEmptySubst ( mkInScopeSet ( exprFreeVars exp ) )
return $ bindsToProg $ snd (mapAccumL substBind (extendSubst emptySub v e) (progToBinds p))
| [ from GHC documentation ] De - shadowing the program is sometimes a useful pre - pass .
deShadowProgR :: Monad m => Rewrite c m CoreProg
deShadowProgR = arr (bindsToProg . deShadowBinds . progToBinds)
arityOf :: ReadBindings c => c -> Id -> Int
arityOf c i =
case lookupHermitBinding i c of
Nothing -> idArity i
The advantage of idArity is it will terminate , though .
Just b -> runKureM exprArity
(hermitBindingExpr b)
lintModuleT :: TransformH ModGuts String
lintModuleT =
do dynFlags <- dynFlagsT
bnds <- arr mg_binds
#if __GLASGOW_HASKELL__ <= 710
' CoreDesugar ' so we check for global ids , but not INLINE loop breakers , see notes in GHC 's CoreLint module .
let (warns, errs) = CoreLint.lintCoreBindings CoreDesugar [] bnds
#else
let (warns, errs) = CoreLint.lintCoreBindings dynFlags CoreDesugar [] bnds
#endif
dumpSDocs endMsg = Bag.foldBag (\ d r -> d ++ ('\n':r)) (showSDoc dynFlags) endMsg
if Bag.isEmptyBag errs
then return $ dumpSDocs "Core Lint Passed" warns
else fail $ "Core Lint Failed:\n" ++ dumpSDocs "" errs
For instance , running this on the RHS of a binding , the type of the RHS will
lintExprT :: (BoundVars c, Monad m, HasDynFlags m) => Transform c m CoreExpr String
lintExprT = transform $ \ c e -> do
dflags <- getDynFlags
case e of
Type _ -> fail "cannot core lint types."
_ -> maybe (return "Core Lint Passed") (fail . showSDoc dflags)
#if __GLASGOW_HASKELL__ <= 710
(CoreLint.lintExpr (varSetElems $ boundVars c) e)
#else
(CoreLint.lintExpr dflags (varSetElems $ boundVars c) e)
#endif
dynFlagsT :: HasDynFlags m => Transform c m a DynFlags
dynFlagsT = constT getDynFlags
TODO : Ideally , occurAnalyseExprR would fail if nothing changed .
dezombifyR :: (ExtendPath c Crumb, Monad m) => Rewrite c m CoreExpr
dezombifyR = varR (acceptR isDeadBinder >>^ zapVarOccInfo)
occurAnalyseR :: (Injection CoreExpr u, Walker c u, MonadCatch m) => Rewrite c m u
go = r <+ anyR go
Note [ No Binder Swap ]
The binder swap performed by occurrence analysis in GHC < = 7.8.3 is buggy
in that it can lead to unintended variable capture ( Trac # 9440 ) . Concretely ,
this will send bash into a loop , or cause core lint to fail . As this is an
un - expected change as far as HERMIT users are concerned anyway , we use the
version that does n't perform the binder swap .
Note [No Binder Swap]
The binder swap performed by occurrence analysis in GHC <= 7.8.3 is buggy
in that it can lead to unintended variable capture (Trac #9440). Concretely,
this will send bash into a loop, or cause core lint to fail. As this is an
un-expected change as far as HERMIT users are concerned anyway, we use the
version that doesn't perform the binder swap.
-}
occurAnalyseExprChangedR :: MonadCatch m => Rewrite c m CoreExpr
occurAnalyseChangedR :: (AddBindings c, ExtendPath c Crumb, HasEmptyContext c, LemmaContext c, ReadPath c Crumb, MonadCatch m) => Rewrite c m LCore
occurAnalyseChangedR = changedByR lcoreSyntaxEq occurAnalyseR
| Run GHC 's occurrence analyser , and also eliminate any zombies .
occurAnalyseAndDezombifyR :: (ExtendPath c Crumb, MonadCatch m, Walker c u, Injection CoreExpr u) => Rewrite c m u
occurAnalyseAndDezombifyR = allbuR (tryR $ promoteExprR dezombifyR) >>> occurAnalyseR
occurrenceAnalysisR :: (ExtendPath c Crumb, MonadCatch m, Walker c LCore) => Rewrite c m LCore
occurrenceAnalysisR = occurAnalyseAndDezombifyR
buildTypeable :: (HasDynFlags m, HasHermitMEnv m, LiftCoreM m, MonadIO m) => Type -> m (Id, [CoreBind])
buildTypeable ty = do
evar <- runTcM $ do
cls <- tcLookupClass typeableClassName
recall that is now poly - kinded
newEvVar predTy
buildDictionary evar
buildDictionary :: (HasDynFlags m, HasHermitMEnv m, LiftCoreM m, MonadIO m) => Id -> m (Id, [CoreBind])
buildDictionary evar = do
(i, bs) <- runTcM $ do
#if __GLASGOW_HASKELL__ > 710
loc <- getCtLocM (GivenOrigin UnkSkol) Nothing
#else
loc <- getCtLoc $ GivenOrigin UnkSkol
#endif
let predTy = varType evar
#if __GLASGOW_HASKELL__ > 710
nonC = mkNonCanonical $ CtWanted { ctev_pred = predTy, ctev_dest = EvVarDest evar, ctev_loc = loc }
wCs = mkSimpleWC [cc_ev nonC]
(_wCs', bnds) <- second evBindMapBinds <$> runTcS (solveWanteds wCs)
#else
nonC = mkNonCanonical $ CtWanted { ctev_pred = predTy, ctev_evar = evar, ctev_loc = loc }
wCs = mkSimpleWC [nonC]
(_wCs', bnds) <- solveWantedsTcM wCs
#endif
return (evar, bnds)
bnds <- runDsM $ dsEvBinds bs
return (i,bnds)
buildDictionaryT :: (HasDynFlags m, HasHermitMEnv m, LiftCoreM m, MonadCatch m, MonadIO m, MonadUnique m)
=> Transform c m Type CoreExpr
buildDictionaryT = prefixFailMsg "buildDictionaryT failed: " $ contextfreeT $ \ ty -> do
dflags <- getDynFlags
binder <- newIdH ("$d" ++ zEncodeString (filter (not . isSpace) (showPpr dflags ty))) ty
(i,bnds) <- buildDictionary binder
guardMsg (notNull bnds) "no dictionary bindings generated."
return $ case bnds of
_ -> mkCoreLets bnds (varToCoreExpr i)
lintClauseT :: forall c m.
( AddBindings c, BoundVars c, ExtendPath c Crumb, HasEmptyContext c, LemmaContext c, ReadPath c Crumb
, HasDynFlags m, MonadCatch m )
=> Transform c m Clause String
lintClauseT = do
strs <- extractT (collectPruneT (promoteExprT $ lintExprT `catchM` return) :: Transform c m LCore [String])
let strs' = nub $ filter notNull strs
guardMsg (null strs' || (strs' == ["Core Lint Passed"])) $ unlines strs'
return "Core Lint Passed"
type LemmaLibrary = TransformH () Lemmas
loadLemmaLibraryT :: HermitName -> Maybe LemmaName -> TransformH x String
loadLemmaLibraryT nm mblnm = prefixFailMsg "Loading lemma library failed: " $
contextonlyT $ \ c -> do
hscEnv <- getHscEnv
comp <- liftAndCatchIO $ loadLemmaLibrary hscEnv nm
nls <- maybe (return $ M.toList ls)
(\lnm -> maybe (fail $ show lnm ++ " not found in library.")
(\ l -> return [(lnm,l)])
(M.lookup lnm ls))
mblnm
nls' <- flip filterM nls $ \ (n, l) -> do
er <- attemptM $ applyT lintClauseT c $ lemmaC l
case er of
Left msg -> do
let pp = Clean.pretty { pOptions = (pOptions Clean.pretty) { po_exprTypes = Detailed } }
d <- applyT (liftPrettyH (pOptions pp) $ pLCoreTC pp) c $ inject $ lemmaC l
let Glyphs gs = renderCode (pOptions pp) d
liftIO $ do
putStr "\n" >> sequence_ [ withStyle s t | Glyph t s <- gs ] >> putStr "\n"
putStrLn $ "Not adding lemma " ++ show n ++ " because lint failed.\n" ++ msg
return False
Right _ -> return True
guardMsg (not (null nls')) "no lemmas to load."
m <- getLemmas
putLemmas $ (M.fromList nls') `M.union` m
return $ "Successfully loaded library " ++ show nm
loadLemmaLibrary :: HscEnv -> HermitName -> IO LemmaLibrary
loadLemmaLibrary hscEnv hnm = do
name <- lookupHermitNameForPlugins hscEnv varNS hnm
lib_tycon_name <- lookupHermitNameForPlugins hscEnv tyConClassNS $ fromString "HERMIT.Dictionary.GHC.LemmaLibrary"
lib_tycon <- forceLoadTyCon hscEnv lib_tycon_name
mb_v <- getValueSafely hscEnv name $ mkTyConTy lib_tycon
let dflags = hsc_dflags hscEnv
maybe (fail $ showSDoc dflags $ hsep
[ ptext (sLit "The value"), ppr name
, ptext (sLit "did not have the type")
, ppr lib_tycon, ptext (sLit "as required.")])
return mb_v
lookupHermitNameForPlugins :: HscEnv -> NameSpace -> HermitName -> IO Name
lookupHermitNameForPlugins hscEnv ns hnm = do
modName <- maybe (fail "name must be fully qualified with module name.") return (hnModuleName hnm)
let dflags = hsc_dflags hscEnv
rdrName = toRdrName ns hnm
mbName <- lookupRdrNameInModuleForPlugins hscEnv modName rdrName
maybe (fail $ showSDoc dflags $ hsep
[ ptext (sLit "The module"), ppr modName
, ptext (sLit "did not export the name")
, ppr rdrName ])
return mbName
injectDependencyT :: (LiftCoreM m, MonadIO m) => ModuleName -> Transform c m ModGuts ()
injectDependencyT mn = contextfreeT $ \ guts -> do
env <- getHscEnv
liftIO $ injectDependency env guts mn
|
40ae0d958638f172d82d69a07416c7a368902bd8046301e243af2c145ad62c2e | GlideAngle/flare-timing | Coincident.hs | module Ellipsoid.Coincident (coincidentUnits) where
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit ((@?=), testCase)
import Data.UnitsOfMeasure (u, convert, fromRational')
import Data.UnitsOfMeasure.Internal (Quantity(..))
import Flight.Distance (TaskDistance(..), PathDistance(..))
import Flight.Zone (QRadius, Radius(..))
import Flight.Zone.Path (distancePointToPoint)
import Zone (MkZone, QLL, showQ, describedZones)
import qualified Distance as D (DistanceEqual, toDistanceEqual)
import Flight.Earth.Ellipsoid (wgs84)
import Ellipsoid.Span (spanD, spanR)
coincidentUnits :: TestTree
coincidentUnits =
testGroup "Coincident zones unit tests"
$ emptyDistance
:
[ testGroup "With doubles" (uncurry f <$> describedZones)
, testGroup "With rationals" (uncurry g <$> describedZones)
]
where
f s =
distanceZero
("Distance between coincident " ++ s ++ " zones")
(D.toDistanceEqual $ spanD wgs84)
g s =
distanceZero
("Distance between coincident " ++ s ++ " zones")
(D.toDistanceEqual $ spanR wgs84)
emptyDistance :: TestTree
emptyDistance =
testGroup "Point-to-point distance"
[ testCase "No zones = zero point-to-point distance" $
edgesSum (distancePointToPoint (spanR wgs84) [])
@?= (TaskDistance $ MkQuantity 0)
]
pts :: (Enum a, Real a, Fractional a) => [(QLL a, QLL a)]
pts =
[ ((z, z), (z, z))
, ((m, z), (m, z))
, ((z, m), (z, m))
, ((m, m), (m, m))
]
where
z = [u| 0 rad |]
m = convert [u| 45 deg |]
distances :: (Real a, Fractional a) => [QRadius a [u| m |]]
distances =
repeat . Radius . fromRational' $ [u| 0 m |]
distanceZero
:: (Enum a, Real a, Fractional a)
=> String
-> D.DistanceEqual a
-> MkZone a a
-> TestTree
distanceZero s f g =
testGroup s
$ zipWith
(\r@(Radius r') (x, y) ->
f
r'
(showQ x ++ " " ++ showQ y)
(g r x, g r y))
distances
pts
| null | https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/earth/test-suite-zones/Ellipsoid/Coincident.hs | haskell | module Ellipsoid.Coincident (coincidentUnits) where
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit ((@?=), testCase)
import Data.UnitsOfMeasure (u, convert, fromRational')
import Data.UnitsOfMeasure.Internal (Quantity(..))
import Flight.Distance (TaskDistance(..), PathDistance(..))
import Flight.Zone (QRadius, Radius(..))
import Flight.Zone.Path (distancePointToPoint)
import Zone (MkZone, QLL, showQ, describedZones)
import qualified Distance as D (DistanceEqual, toDistanceEqual)
import Flight.Earth.Ellipsoid (wgs84)
import Ellipsoid.Span (spanD, spanR)
coincidentUnits :: TestTree
coincidentUnits =
testGroup "Coincident zones unit tests"
$ emptyDistance
:
[ testGroup "With doubles" (uncurry f <$> describedZones)
, testGroup "With rationals" (uncurry g <$> describedZones)
]
where
f s =
distanceZero
("Distance between coincident " ++ s ++ " zones")
(D.toDistanceEqual $ spanD wgs84)
g s =
distanceZero
("Distance between coincident " ++ s ++ " zones")
(D.toDistanceEqual $ spanR wgs84)
emptyDistance :: TestTree
emptyDistance =
testGroup "Point-to-point distance"
[ testCase "No zones = zero point-to-point distance" $
edgesSum (distancePointToPoint (spanR wgs84) [])
@?= (TaskDistance $ MkQuantity 0)
]
pts :: (Enum a, Real a, Fractional a) => [(QLL a, QLL a)]
pts =
[ ((z, z), (z, z))
, ((m, z), (m, z))
, ((z, m), (z, m))
, ((m, m), (m, m))
]
where
z = [u| 0 rad |]
m = convert [u| 45 deg |]
distances :: (Real a, Fractional a) => [QRadius a [u| m |]]
distances =
repeat . Radius . fromRational' $ [u| 0 m |]
distanceZero
:: (Enum a, Real a, Fractional a)
=> String
-> D.DistanceEqual a
-> MkZone a a
-> TestTree
distanceZero s f g =
testGroup s
$ zipWith
(\r@(Radius r') (x, y) ->
f
r'
(showQ x ++ " " ++ showQ y)
(g r x, g r y))
distances
pts
|
|
24790eb4cf63b4de821bdb66da42c4448313f31b17e47a2014f1864c8d19c7ba | dhleong/wish | gdrive.cljs | (ns ^{:author "Daniel Leong"
:doc "Google Drive powered Provider"}
wish.providers.gdrive
(:require-macros [cljs.core.async :refer [go]]
[wish.util.async :refer [call-with-cb->chan]]
[wish.util.log :as log :refer [log]])
(:require [clojure.core.async :refer [promise-chan close! put! to-chan! <!]]
[clojure.string :as str]
[goog.dom :as dom]
[wish.config :refer [gdrive-client-id]]
[wish.data :as data]
[wish.providers.core :refer [IProvider]]
[wish.providers.gdrive.api :as api :refer [->clj]]
[wish.sheets.util :refer [make-id]]
[wish.util :refer [>evt]]
[wish.util.async :refer [promise->chan]]))
;;
;; Constants
;;
;; Array of API discovery doc URLs for APIs used by the quickstart
(def ^:private discovery-docs #js [""])
(def ^:private drive-read-scope
"")
(def ^:private drive-full-scope
"")
;; Authorization scopes required by the API; multiple scopes can be
;; included, separated by spaces.
(def ^:private scopes (str/join
" "
[""
""]))
(def ^:private campaign-desc "WISH Campaign")
(def ^:private campaign-mime "application/edn")
(def ^:private campaign-props {:wish-type "wish-campaign"})
(def ^:private sheet-desc "WISH Character Sheet")
(def ^:private sheet-mime "application/edn")
(def ^:private sheet-props {:wish-type "wish-sheet"})
(def ^:private source-desc "WISH Data Source")
(def ^:private source-mime "application/edn")
(def ^:private source-props {:wish-type "data-source"})
;;
Internal util
;;
(defn- refresh-auth []
(call-with-cb->chan
(js/gapi.auth.authorize
#js {:client_id gdrive-client-id
:scope scopes
:immediate true})))
(defn- do-with-retry
[f & args]
(go (let [[error resp] (<! (apply f args))]
(cond
(and error
(= 401 (or (.-code error)
(.-status error))))
; refresh creds and retry
(let [_ (log/info "Refreshing auth before retrying " f "...")
[refresh-err refresh-resp] (<! (refresh-auth))]
(if refresh-err
(do
(log/warn "Auth refresh failed:" refresh-resp)
[refresh-err nil])
(let [_ (log/info "Auth refreshed! Retrying...")
[retry-err retry-resp] (<! (apply f args))]
(if retry-err
(do
(log/err "Even after auth refresh, " f " failed: " resp)
[retry-err nil])
; upload retry succeeded!
[nil retry-resp]))))
; network error
(and error
(str/includes?
(or (some-> error
(.-result)
(.-error)
(.-message))
(some-> error
(.-message))
(ex-message error)
(log/warn "No message on " error))
"network"))
[(ex-info
"A network error occured"
{:network? true}
error)
nil]
; unexpected error:
error (do
(log/err f " ERROR:" error)
[error nil])
; no problem; pass it along
:else [nil resp]))))
(defn- reliably
"Given a function `f`, return a new function that
applies its arguments to `f`, and auto-retries on
auth failure"
[f]
(partial do-with-retry f))
;;
gapi wrappers
;;
(def ^:private get-file (reliably api/get-file))
(def ^:private get-meta (reliably api/get-meta))
(def ^:private query-files (reliably api/query-files))
(def ^:private upload-data (reliably api/upload-data))
(defn- ensure-meta
([file-id metadata]
(ensure-meta file-id metadata false))
([file-id metadata force?]
(go (if force?
(<! (api/update-meta file-id metadata))
(let [[err resp] (<! (get-meta file-id))]
(when (or err
(not= (select-keys
resp
(keys metadata))
metadata))
(log "Updating " file-id "metadata <- " metadata)
(api/update-meta file-id metadata)))))))
(defn- do-query-files
"Convenience wrapper around query-files that provides a
callback-style interface"
[q & {:keys [on-error on-success]
:or {on-error (fn [e]
(log/err "ERROR listing files" e))}
:as opts}]
(go (let [[err resp] (<! (apply query-files
q
(dissoc opts :on-error :on-success)))]
(if err
(on-error err)
(on-success resp)))))
;;
State management and API interactions
;;
; gapi availability channel. it starts out as a channel,
so function calls depending on being available can
; wait on it to discover the state (see `when-gapi-available`).
Once gapi availability is determined , this atom is reset !
to one of the valid provider states (: ready , : unavailable , : signed - out )
(defonce ^:private gapi-state (atom (promise-chan)))
(defn- set-gapi-state! [new-state]
(swap! gapi-state
(fn [old-state]
(if (keyword? old-state)
; if it's not a channel then this is probably not
; part of init!, instead from config. Dispatch the event
(>evt [:put-provider-state! :gdrive new-state])
; if it is a channel, however, write to it!
(do (put! old-state new-state)
(close! old-state)))
new-state)))
(defn- when-gapi-available
"Apply `args` to `f` when gapi is available, or (if it's
unavailable) return an appropriate error"
[f & args]
(go (let [availability @gapi-state]
(log "when-gapi-available: " availability f args)
(cond
(= :unavailable availability)
[(ex-info
"GAPI unavailable"
{:network? true})
nil]
wait on the channel , if there is one
(not (keyword? availability))
(let [from-ch (<! availability)]
(if (= :ready from-ch)
; ready
(do
(log "got availability; then: " f args)
(<! (apply f args)))
; try again
(do
(log "Not ready: " from-ch)
[(js/Error. (str "Error? " from-ch))])))
; should be available! go ahead and load
:else
(<! (apply f args))))))
(defn- auth-instance
"Convenience to get the gapi auth instance:
gapi.auth2.getAuthInstance().
@return {gapi.AuthInstance}"
[]
(js/gapi.auth2.getAuthInstance))
(defn- current-user []
(some-> (auth-instance)
(.-currentUser)
(.get)))
(defn- auth-response []
(some-> ^js (current-user)
(.getAuthResponse)))
(defn- access-token
"When logged in, get the current user's access token"
[]
(some-> ^js (auth-response)
(.-access_token)))
(defn- update-signin-status!
[signed-in?]
(log/info "signed-in? <-" signed-in?)
(set-gapi-state! (if signed-in?
:ready
:signed-out)))
(defn- on-client-init []
(log "gapi client init!")
; listen for updates
(-> (auth-instance)
(.-isSignedIn)
(.listen update-signin-status!))
; set current status immediately
(update-signin-status!
(-> (auth-instance)
(.-isSignedIn)
(.get))))
(defn- on-client-init-error [e]
(log/warn "gapi client failed" e (js/JSON.stringify e))
(set-gapi-state! :unavailable)
TODO can we retry when network returns ?
)
(defn init-client! []
(log "init-client!")
(-> (js/gapi.client.init
#js {:discoveryDocs discovery-docs
:clientId gdrive-client-id
:scope scopes})
(.then on-client-init
on-client-init-error)))
(defn request-read!
"Starts the flow to request readonly scope. Returns a channel"
[]
(some-> ^js (current-user)
(.grant #js {:scope drive-read-scope})
(promise->chan)))
(defn has-global-read?
"Returns truthy if the active user should have read access
to any file shared with them, else nil"
[]
(when-let [^js user (current-user)]
(or (.hasGrantedScopes user drive-read-scope)
(.hasGrantedScopes user drive-full-scope))))
;;
;; NOTE: Exposed to index.html
(defn ^:export handle-client-load [success?]
(log "load")
(if success?
(js/gapi.load "client:auth2",
#js {:callback init-client!
:onerror on-client-init-error})
(on-client-init-error nil)))
(defn- retry-gapi-load! []
; NOTE we have to do a get off window, else cljs throws
; a reference error
(if js/window.gapi
we have , but I guess one of the libs failed to load ?
(handle-client-load true)
no gapi ; add a new copy of the script node
(do
(log "Add a new gapi <script> node")
(dom/appendChild
(aget (dom/getElementsByTagName "head") 0)
(dom/createDom dom/TagName.SCRIPT
#js {:onload (partial handle-client-load true)
:onerror (partial handle-client-load false)
:async true
:src ""
:type "text/javascript"})))))
;;
;; Public API
;;
(defn signin! []
(-> (auth-instance)
(.signIn)))
(defn signout! []
(doto (auth-instance)
(.disconnect)
(.signOut)))
(defn active-user []
(when-let [profile (some-> ^js (current-user)
(.getBasicProfile))]
{:name (.getName profile)
:email (.getEmail profile)}))
; ======= file picker ======================================
(defn- do-pick-file
[{:keys [description props]}]
; NOTE: I don't love using camel case in my clojure code,
; but since we're using it everywhere else for easier compat
; with google docs, let's just use it here for consistency.
(let [ch (promise-chan)]
(-> (js/google.picker.PickerBuilder.)
(.addView (doto (js/google.picker.View.
js/google.picker.ViewId.DOCS)
(.setMimeTypes "application/edn,application/json,text/plain")))
(.addView (js/google.picker.DocsUploadView.))
(.setAppId gdrive-client-id)
(.setOAuthToken (access-token))
(.setCallback
(fn [result]
(let [result (->clj result)
uploaded? (= "upload"
(-> result :viewToken first))]
(log "Picked: (wasUpload=" uploaded? ") " result)
(case (:action result)
"cancel" (put! ch [nil nil])
"picked" (let [file (-> result
:docs
first
(select-keys [:id :name]))
file-id (:id file)
wish-file (update file :id
(partial make-id :gdrive))]
; update mime type and annotate with :wish-type
(ensure-meta
file-id
{:appProperties props
:description description}
; force update when uploaded (skip a roundtrip)
uploaded?)
(put! ch [nil wish-file]))
(log "Other pick action")))))
(.build)
(.setVisible true))
; return the channel
ch))
(def pick-file (api/when-loaded "picker" do-pick-file))
; ======= Share dialog ====================================
(defn- do-share-file [id]
(doto (js/gapi.drive.share.ShareClient.)
(.setOAuthToken (access-token))
(.setItemIds #js [id])
(.showSettingsDialog))
; make sure we return nil
nil)
(def share! (api/when-loaded "drive-share" do-share-file))
; ======= file loading ====================================
(defn- do-load-raw [id]
(go (let [[err :as r] (<! (get-file id))]
(if err
(let [status (.-status err)]
(log/err "ERROR loading " id err)
(cond
; possibly caused by permissions
(= 404 status)
[(ex-info
(ex-message err)
{:permissions? true
:provider :gdrive
:id id}
err)
nil]
; signed out
(= 403 status)
[(ex-info
(ex-message err)
{:state :signed-out
:provider :gdrive
:id id}
err)
nil]
; some other error
:else
[err nil]))
; success; return unchanged
r))))
; ======= Provider def =====================================
(defn- meta-for [kind file-name]
(let [base (case kind
:campaign {:description campaign-desc
:mimeType campaign-mime
:appProperties campaign-props}
:sheet {:description sheet-desc
:mimeType sheet-mime
:appProperties sheet-props})]
(assoc base :name file-name)))
(deftype GDriveProvider []
IProvider
(id [_] :gdrive)
(create-file [_ kind file-name data]
(log/info "Create " kind ": " file-name)
(go (let [[err resp] (<! (upload-data
:create
(meta-for kind file-name)
(str data)))]
(if err
[err nil]
(let [pro-sheet-id (:id resp)]
(log/info "CREATED" resp)
[nil (make-id :gdrive pro-sheet-id)])))))
#_(delete-sheet [_ info]
(log/info "Delete " (:gapi-id info))
(-> js/gapi.client.drive.files
(.delete #js {:fileId (:gapi-id info)})
(.then (fn [resp]
(log/info "Deleted!" (:gapi-id info)))
(fn [e]
(log/warn "Failed to delete " (:gapi-id info))))))
(init! [_]
(go (let [state @gapi-state]
(cond
try to load again
(= :unavailable state)
(let [ch (promise-chan)]
(log "reloading gapi")
(reset! gapi-state ch)
; init a new load onto this promise-chan,
; and wait for the result
(retry-gapi-load!)
(<! ch))
; state is resolved; return directly
(keyword? state)
state
; wait on the channel for the state
:else
(<! state)))))
(connect! [_]
(signin!))
(disconnect! [_]
(signout!))
(load-raw
[_ id]
(when-gapi-available do-load-raw id))
(query-data-sources [_]
TODO indicate query state ?
(do-query-files
"appProperties has { key='wish-type' and value='data-source' }"
:on-success (fn [files]
(log "Found data sources: " files)
(>evt [:add-data-sources
(map (fn [[id file]]
(assoc file :id id))
files)]))))
(query-sheets [_]
(when-gapi-available
query-files
(str "(appProperties has { key='wish-type' and value='wish-sheet' }) "
"or (appProperties has { key='wish-type' and value='wish-campaign' })")))
(register-data-source [_]
TODO sanity checks galore
(pick-file {:mimeType source-mime
:description source-desc
:props source-props}))
(save-sheet [_ file-id data data-str]
(if (= :ready @gapi-state)
(do
(log/info "Save " file-id data)
(upload-data
:update
(cond-> {:fileId file-id
:mimeType sheet-mime
:description sheet-desc}
; update the :name if we can
data (assoc :name (when-let [n (:name data)]
(str n "." data/sheet-extension))))
data-str))
; not ready? don't try
(to-chan! [[(js/Error. "No network; unable to save sheet") nil]])))
(watch-auth [_]
(when-let [resp (auth-response)]
{:id_token (.-id_token resp)
:access_token (access-token)})))
(defn create-provider []
(->GDriveProvider))
| null | https://raw.githubusercontent.com/dhleong/wish/9036f9da3706bfcc1e4b4736558b6f7309f53b7b/src/cljs/wish/providers/gdrive.cljs | clojure |
Constants
Array of API discovery doc URLs for APIs used by the quickstart
Authorization scopes required by the API; multiple scopes can be
included, separated by spaces.
refresh creds and retry
upload retry succeeded!
network error
unexpected error:
no problem; pass it along
gapi availability channel. it starts out as a channel,
wait on it to discover the state (see `when-gapi-available`).
if it's not a channel then this is probably not
part of init!, instead from config. Dispatch the event
if it is a channel, however, write to it!
ready
try again
should be available! go ahead and load
listen for updates
set current status immediately
NOTE: Exposed to index.html
NOTE we have to do a get off window, else cljs throws
a reference error
add a new copy of the script node
Public API
======= file picker ======================================
NOTE: I don't love using camel case in my clojure code,
but since we're using it everywhere else for easier compat
with google docs, let's just use it here for consistency.
update mime type and annotate with :wish-type
force update when uploaded (skip a roundtrip)
return the channel
======= Share dialog ====================================
make sure we return nil
======= file loading ====================================
possibly caused by permissions
signed out
some other error
success; return unchanged
======= Provider def =====================================
init a new load onto this promise-chan,
and wait for the result
state is resolved; return directly
wait on the channel for the state
update the :name if we can
not ready? don't try | (ns ^{:author "Daniel Leong"
:doc "Google Drive powered Provider"}
wish.providers.gdrive
(:require-macros [cljs.core.async :refer [go]]
[wish.util.async :refer [call-with-cb->chan]]
[wish.util.log :as log :refer [log]])
(:require [clojure.core.async :refer [promise-chan close! put! to-chan! <!]]
[clojure.string :as str]
[goog.dom :as dom]
[wish.config :refer [gdrive-client-id]]
[wish.data :as data]
[wish.providers.core :refer [IProvider]]
[wish.providers.gdrive.api :as api :refer [->clj]]
[wish.sheets.util :refer [make-id]]
[wish.util :refer [>evt]]
[wish.util.async :refer [promise->chan]]))
(def ^:private discovery-docs #js [""])
(def ^:private drive-read-scope
"")
(def ^:private drive-full-scope
"")
(def ^:private scopes (str/join
" "
[""
""]))
(def ^:private campaign-desc "WISH Campaign")
(def ^:private campaign-mime "application/edn")
(def ^:private campaign-props {:wish-type "wish-campaign"})
(def ^:private sheet-desc "WISH Character Sheet")
(def ^:private sheet-mime "application/edn")
(def ^:private sheet-props {:wish-type "wish-sheet"})
(def ^:private source-desc "WISH Data Source")
(def ^:private source-mime "application/edn")
(def ^:private source-props {:wish-type "data-source"})
Internal util
(defn- refresh-auth []
(call-with-cb->chan
(js/gapi.auth.authorize
#js {:client_id gdrive-client-id
:scope scopes
:immediate true})))
(defn- do-with-retry
[f & args]
(go (let [[error resp] (<! (apply f args))]
(cond
(and error
(= 401 (or (.-code error)
(.-status error))))
(let [_ (log/info "Refreshing auth before retrying " f "...")
[refresh-err refresh-resp] (<! (refresh-auth))]
(if refresh-err
(do
(log/warn "Auth refresh failed:" refresh-resp)
[refresh-err nil])
(let [_ (log/info "Auth refreshed! Retrying...")
[retry-err retry-resp] (<! (apply f args))]
(if retry-err
(do
(log/err "Even after auth refresh, " f " failed: " resp)
[retry-err nil])
[nil retry-resp]))))
(and error
(str/includes?
(or (some-> error
(.-result)
(.-error)
(.-message))
(some-> error
(.-message))
(ex-message error)
(log/warn "No message on " error))
"network"))
[(ex-info
"A network error occured"
{:network? true}
error)
nil]
error (do
(log/err f " ERROR:" error)
[error nil])
:else [nil resp]))))
(defn- reliably
"Given a function `f`, return a new function that
applies its arguments to `f`, and auto-retries on
auth failure"
[f]
(partial do-with-retry f))
gapi wrappers
(def ^:private get-file (reliably api/get-file))
(def ^:private get-meta (reliably api/get-meta))
(def ^:private query-files (reliably api/query-files))
(def ^:private upload-data (reliably api/upload-data))
(defn- ensure-meta
([file-id metadata]
(ensure-meta file-id metadata false))
([file-id metadata force?]
(go (if force?
(<! (api/update-meta file-id metadata))
(let [[err resp] (<! (get-meta file-id))]
(when (or err
(not= (select-keys
resp
(keys metadata))
metadata))
(log "Updating " file-id "metadata <- " metadata)
(api/update-meta file-id metadata)))))))
(defn- do-query-files
"Convenience wrapper around query-files that provides a
callback-style interface"
[q & {:keys [on-error on-success]
:or {on-error (fn [e]
(log/err "ERROR listing files" e))}
:as opts}]
(go (let [[err resp] (<! (apply query-files
q
(dissoc opts :on-error :on-success)))]
(if err
(on-error err)
(on-success resp)))))
State management and API interactions
so function calls depending on being available can
Once gapi availability is determined , this atom is reset !
to one of the valid provider states (: ready , : unavailable , : signed - out )
(defonce ^:private gapi-state (atom (promise-chan)))
(defn- set-gapi-state! [new-state]
(swap! gapi-state
(fn [old-state]
(if (keyword? old-state)
(>evt [:put-provider-state! :gdrive new-state])
(do (put! old-state new-state)
(close! old-state)))
new-state)))
(defn- when-gapi-available
"Apply `args` to `f` when gapi is available, or (if it's
unavailable) return an appropriate error"
[f & args]
(go (let [availability @gapi-state]
(log "when-gapi-available: " availability f args)
(cond
(= :unavailable availability)
[(ex-info
"GAPI unavailable"
{:network? true})
nil]
wait on the channel , if there is one
(not (keyword? availability))
(let [from-ch (<! availability)]
(if (= :ready from-ch)
(do
(log "got availability; then: " f args)
(<! (apply f args)))
(do
(log "Not ready: " from-ch)
[(js/Error. (str "Error? " from-ch))])))
:else
(<! (apply f args))))))
(defn- auth-instance
"Convenience to get the gapi auth instance:
gapi.auth2.getAuthInstance().
@return {gapi.AuthInstance}"
[]
(js/gapi.auth2.getAuthInstance))
(defn- current-user []
(some-> (auth-instance)
(.-currentUser)
(.get)))
(defn- auth-response []
(some-> ^js (current-user)
(.getAuthResponse)))
(defn- access-token
"When logged in, get the current user's access token"
[]
(some-> ^js (auth-response)
(.-access_token)))
(defn- update-signin-status!
[signed-in?]
(log/info "signed-in? <-" signed-in?)
(set-gapi-state! (if signed-in?
:ready
:signed-out)))
(defn- on-client-init []
(log "gapi client init!")
(-> (auth-instance)
(.-isSignedIn)
(.listen update-signin-status!))
(update-signin-status!
(-> (auth-instance)
(.-isSignedIn)
(.get))))
(defn- on-client-init-error [e]
(log/warn "gapi client failed" e (js/JSON.stringify e))
(set-gapi-state! :unavailable)
TODO can we retry when network returns ?
)
(defn init-client! []
(log "init-client!")
(-> (js/gapi.client.init
#js {:discoveryDocs discovery-docs
:clientId gdrive-client-id
:scope scopes})
(.then on-client-init
on-client-init-error)))
(defn request-read!
"Starts the flow to request readonly scope. Returns a channel"
[]
(some-> ^js (current-user)
(.grant #js {:scope drive-read-scope})
(promise->chan)))
(defn has-global-read?
"Returns truthy if the active user should have read access
to any file shared with them, else nil"
[]
(when-let [^js user (current-user)]
(or (.hasGrantedScopes user drive-read-scope)
(.hasGrantedScopes user drive-full-scope))))
(defn ^:export handle-client-load [success?]
(log "load")
(if success?
(js/gapi.load "client:auth2",
#js {:callback init-client!
:onerror on-client-init-error})
(on-client-init-error nil)))
(defn- retry-gapi-load! []
(if js/window.gapi
we have , but I guess one of the libs failed to load ?
(handle-client-load true)
(do
(log "Add a new gapi <script> node")
(dom/appendChild
(aget (dom/getElementsByTagName "head") 0)
(dom/createDom dom/TagName.SCRIPT
#js {:onload (partial handle-client-load true)
:onerror (partial handle-client-load false)
:async true
:src ""
:type "text/javascript"})))))
(defn signin! []
(-> (auth-instance)
(.signIn)))
(defn signout! []
(doto (auth-instance)
(.disconnect)
(.signOut)))
(defn active-user []
(when-let [profile (some-> ^js (current-user)
(.getBasicProfile))]
{:name (.getName profile)
:email (.getEmail profile)}))
(defn- do-pick-file
[{:keys [description props]}]
(let [ch (promise-chan)]
(-> (js/google.picker.PickerBuilder.)
(.addView (doto (js/google.picker.View.
js/google.picker.ViewId.DOCS)
(.setMimeTypes "application/edn,application/json,text/plain")))
(.addView (js/google.picker.DocsUploadView.))
(.setAppId gdrive-client-id)
(.setOAuthToken (access-token))
(.setCallback
(fn [result]
(let [result (->clj result)
uploaded? (= "upload"
(-> result :viewToken first))]
(log "Picked: (wasUpload=" uploaded? ") " result)
(case (:action result)
"cancel" (put! ch [nil nil])
"picked" (let [file (-> result
:docs
first
(select-keys [:id :name]))
file-id (:id file)
wish-file (update file :id
(partial make-id :gdrive))]
(ensure-meta
file-id
{:appProperties props
:description description}
uploaded?)
(put! ch [nil wish-file]))
(log "Other pick action")))))
(.build)
(.setVisible true))
ch))
(def pick-file (api/when-loaded "picker" do-pick-file))
(defn- do-share-file [id]
(doto (js/gapi.drive.share.ShareClient.)
(.setOAuthToken (access-token))
(.setItemIds #js [id])
(.showSettingsDialog))
nil)
(def share! (api/when-loaded "drive-share" do-share-file))
(defn- do-load-raw [id]
(go (let [[err :as r] (<! (get-file id))]
(if err
(let [status (.-status err)]
(log/err "ERROR loading " id err)
(cond
(= 404 status)
[(ex-info
(ex-message err)
{:permissions? true
:provider :gdrive
:id id}
err)
nil]
(= 403 status)
[(ex-info
(ex-message err)
{:state :signed-out
:provider :gdrive
:id id}
err)
nil]
:else
[err nil]))
r))))
(defn- meta-for [kind file-name]
(let [base (case kind
:campaign {:description campaign-desc
:mimeType campaign-mime
:appProperties campaign-props}
:sheet {:description sheet-desc
:mimeType sheet-mime
:appProperties sheet-props})]
(assoc base :name file-name)))
(deftype GDriveProvider []
IProvider
(id [_] :gdrive)
(create-file [_ kind file-name data]
(log/info "Create " kind ": " file-name)
(go (let [[err resp] (<! (upload-data
:create
(meta-for kind file-name)
(str data)))]
(if err
[err nil]
(let [pro-sheet-id (:id resp)]
(log/info "CREATED" resp)
[nil (make-id :gdrive pro-sheet-id)])))))
#_(delete-sheet [_ info]
(log/info "Delete " (:gapi-id info))
(-> js/gapi.client.drive.files
(.delete #js {:fileId (:gapi-id info)})
(.then (fn [resp]
(log/info "Deleted!" (:gapi-id info)))
(fn [e]
(log/warn "Failed to delete " (:gapi-id info))))))
(init! [_]
(go (let [state @gapi-state]
(cond
try to load again
(= :unavailable state)
(let [ch (promise-chan)]
(log "reloading gapi")
(reset! gapi-state ch)
(retry-gapi-load!)
(<! ch))
(keyword? state)
state
:else
(<! state)))))
(connect! [_]
(signin!))
(disconnect! [_]
(signout!))
(load-raw
[_ id]
(when-gapi-available do-load-raw id))
(query-data-sources [_]
TODO indicate query state ?
(do-query-files
"appProperties has { key='wish-type' and value='data-source' }"
:on-success (fn [files]
(log "Found data sources: " files)
(>evt [:add-data-sources
(map (fn [[id file]]
(assoc file :id id))
files)]))))
(query-sheets [_]
(when-gapi-available
query-files
(str "(appProperties has { key='wish-type' and value='wish-sheet' }) "
"or (appProperties has { key='wish-type' and value='wish-campaign' })")))
(register-data-source [_]
TODO sanity checks galore
(pick-file {:mimeType source-mime
:description source-desc
:props source-props}))
(save-sheet [_ file-id data data-str]
(if (= :ready @gapi-state)
(do
(log/info "Save " file-id data)
(upload-data
:update
(cond-> {:fileId file-id
:mimeType sheet-mime
:description sheet-desc}
data (assoc :name (when-let [n (:name data)]
(str n "." data/sheet-extension))))
data-str))
(to-chan! [[(js/Error. "No network; unable to save sheet") nil]])))
(watch-auth [_]
(when-let [resp (auth-response)]
{:id_token (.-id_token resp)
:access_token (access-token)})))
(defn create-provider []
(->GDriveProvider))
|
f305cc960ba78ade73b1634840f1cb539f38cb3b61c8ea94fdcb84778dd5596a | ocaml/odoc | comment_desc.mli | val docs : Odoc_model.Comment.docs Type_desc.t
val docs_or_stop : Odoc_model.Comment.docs_or_stop Type_desc.t
| null | https://raw.githubusercontent.com/ocaml/odoc/2f639d7d661bc5397afce83dfaa71af53d2a8677/src/model_desc/comment_desc.mli | ocaml | val docs : Odoc_model.Comment.docs Type_desc.t
val docs_or_stop : Odoc_model.Comment.docs_or_stop Type_desc.t
|
|
a194e1bea738b24a0222b80b15f19b2debc972636dbc6b6a3b245613d3b0b2d6 | zcaudate-me/lein-repack | common.clj | (ns repack.common) | null | https://raw.githubusercontent.com/zcaudate-me/lein-repack/1eb542d66a77f55c4b5625783027c31fd2dddfe5/example/repack.advance/src/clj/repack/common.clj | clojure | (ns repack.common) |
|
ab690580b4341b255d60b2e35fdff3884ac27eb39b674d6fa5710f43badaed81 | ds-wizard/engine-backend | Detail_Bundle_GET.hs | module Registry.Specs.API.Locale.Detail_Bundle_GET (
detail_bundle_get,
) where
import Network.HTTP.Types
import Network.Wai (Application)
import Test.Hspec
import Test.Hspec.Wai hiding (shouldRespondWith)
import qualified Registry.Database.Migration.Development.Locale.LocaleMigration as LOC_Migration
import Registry.Model.Context.AppContext
import Registry.Specs.API.Common
import Registry.Specs.Common
import SharedTest.Specs.API.Common
-- ------------------------------------------------------------------------
-- GET /locales/{lclId}/bundle
-- ------------------------------------------------------------------------
detail_bundle_get :: AppContext -> SpecWith ((), Application)
detail_bundle_get appContext =
describe "GET /locales/{lclId}/bundle" $ do
test_200 appContext
test_401 appContext
test_404 appContext
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
reqMethod = methodGet
reqUrl = "/locales/global:dutch:1.0.0/bundle"
reqHeaders = [reqAdminAuthHeader, reqCtHeader]
reqBody = ""
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_200 appContext =
it "HTTP 200 OK" $
-- GIVEN: Prepare expectation
do
let expStatus = 200
let expHeaders = resCorsHeadersPlain
-- AND: Run migrations
runInContextIO LOC_Migration.runMigration appContext
runInContextIO LOC_Migration.runS3Migration appContext
-- WHEN: Call API
response <- request reqMethod reqUrl reqHeaders reqBody
-- THEN: Compare response with expectation
let (status, headers, resDto) = destructResponse response :: (Int, ResponseHeaders, String)
assertResStatus status expStatus
assertResHeaders headers expHeaders
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_401 appContext = createAuthTest reqMethod reqUrl [reqCtHeader] reqBody
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_404 appContext =
createNotFoundTest'
reqMethod
"/locales/global:non-existing-locale:1.0.0/bundle"
reqHeaders
reqBody
"locale"
[("id", "global:non-existing-locale:1.0.0")]
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/0ec94a4b0545f2de8a4e59686a4376023719d5e7/engine-registry/test/Registry/Specs/API/Locale/Detail_Bundle_GET.hs | haskell | ------------------------------------------------------------------------
GET /locales/{lclId}/bundle
------------------------------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
GIVEN: Prepare expectation
AND: Run migrations
WHEN: Call API
THEN: Compare response with expectation
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
---------------------------------------------------- | module Registry.Specs.API.Locale.Detail_Bundle_GET (
detail_bundle_get,
) where
import Network.HTTP.Types
import Network.Wai (Application)
import Test.Hspec
import Test.Hspec.Wai hiding (shouldRespondWith)
import qualified Registry.Database.Migration.Development.Locale.LocaleMigration as LOC_Migration
import Registry.Model.Context.AppContext
import Registry.Specs.API.Common
import Registry.Specs.Common
import SharedTest.Specs.API.Common
detail_bundle_get :: AppContext -> SpecWith ((), Application)
detail_bundle_get appContext =
describe "GET /locales/{lclId}/bundle" $ do
test_200 appContext
test_401 appContext
test_404 appContext
reqMethod = methodGet
reqUrl = "/locales/global:dutch:1.0.0/bundle"
reqHeaders = [reqAdminAuthHeader, reqCtHeader]
reqBody = ""
test_200 appContext =
it "HTTP 200 OK" $
do
let expStatus = 200
let expHeaders = resCorsHeadersPlain
runInContextIO LOC_Migration.runMigration appContext
runInContextIO LOC_Migration.runS3Migration appContext
response <- request reqMethod reqUrl reqHeaders reqBody
let (status, headers, resDto) = destructResponse response :: (Int, ResponseHeaders, String)
assertResStatus status expStatus
assertResHeaders headers expHeaders
test_401 appContext = createAuthTest reqMethod reqUrl [reqCtHeader] reqBody
test_404 appContext =
createNotFoundTest'
reqMethod
"/locales/global:non-existing-locale:1.0.0/bundle"
reqHeaders
reqBody
"locale"
[("id", "global:non-existing-locale:1.0.0")]
|
0a0c95cf1dac2ea1dffafe251edf98ec82e6cdbef053ad4894b7710d04ec8c91 | fccm/OCamlSDL2 | sdlquit.ml | OCamlSDL2 - An OCaml interface to the SDL2 library
Copyright ( C ) 2013
This software is provided " AS - IS " , without any express or implied warranty .
In no event will the authors be held liable for any damages arising from
the use of this software .
Permission is granted to anyone to use this software for any purpose ,
including commercial applications , and to alter it and redistribute it freely .
Copyright (C) 2013 Florent Monnier
This software is provided "AS-IS", without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely.
*)
(** Quit SDL *)
external quit : unit -> unit = "caml_SDL_Quit"
external quit_requested : unit -> bool
= "caml_SDL_QuitRequested"
| null | https://raw.githubusercontent.com/fccm/OCamlSDL2/01fa29187cab90052d2581eb509d1bca1a85418f/src/sdlquit.ml | ocaml | * Quit SDL | OCamlSDL2 - An OCaml interface to the SDL2 library
Copyright ( C ) 2013
This software is provided " AS - IS " , without any express or implied warranty .
In no event will the authors be held liable for any damages arising from
the use of this software .
Permission is granted to anyone to use this software for any purpose ,
including commercial applications , and to alter it and redistribute it freely .
Copyright (C) 2013 Florent Monnier
This software is provided "AS-IS", without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely.
*)
external quit : unit -> unit = "caml_SDL_Quit"
external quit_requested : unit -> bool
= "caml_SDL_QuitRequested"
|
b5f2fe3b0a1cfa346f8a6debf71c799670d869f7396dfdcb06fe845e856b1d15 | msakai/toysolver | Polynomial.hs | # OPTIONS_GHC -Wall #
-----------------------------------------------------------------------------
-- |
-- Module : ToySolver.Data.Polynomial
Copyright : ( c ) 2012 - 2013
-- License : BSD-style
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- Polynomials
--
-- References:
--
* Monomial order < >
--
* Polynomial class for < -u.ac.jp/~kodama/tips-RubyPoly.html >
--
-- * constructive-algebra package <-algebra>
--
-----------------------------------------------------------------------------
module ToySolver.Data.Polynomial
(
-- * Polynomial type
Polynomial
-- * Conversion
, Var (..)
, constant
, terms
, fromTerms
, coeffMap
, fromCoeffMap
, fromTerm
-- * Query
, Degree (..)
, Vars (..)
, lt
, lc
, lm
, coeff
, lookupCoeff
, isPrimitive
-- * Operations
, Factor (..)
, SQFree (..)
, ContPP (..)
, deriv
, integral
, eval
, subst
, mapCoeff
, toMonic
, toUPolynomialOf
, divModMP
, reduce
-- * Univariate polynomials
, UPolynomial
, X (..)
, UTerm
, UMonomial
, div
, mod
, divMod
, divides
, gcd
, lcm
, exgcd
, pdivMod
, pdiv
, pmod
, gcd'
, isRootOf
, isSquareFree
, nat
, eisensteinsCriterion
-- * Term
, Term
, tdeg
, tscale
, tmult
, tdivides
, tdiv
, tderiv
, tintegral
-- * Monic monomial
, Monomial
, mone
, mfromIndices
, mfromIndicesMap
, mindices
, mindicesMap
, mmult
, mpow
, mdivides
, mdiv
, mderiv
, mintegral
, mlcm
, mgcd
, mcoprime
-- * Monomial order
, MonomialOrder
, lex
, revlex
, grlex
, grevlex
-- * Pretty Printing
, PrintOptions (..)
, prettyPrint
, PrettyCoeff (..)
, PrettyVar (..)
) where
import Prelude hiding (lex, div, mod, divMod, gcd, lcm)
import ToySolver.Data.Polynomial.Base
import ToySolver.Data.Polynomial.Factorization.FiniteField ()
import ToySolver.Data.Polynomial.Factorization.Integer ()
import ToySolver.Data.Polynomial.Factorization.Rational ()
| null | https://raw.githubusercontent.com/msakai/toysolver/6233d130d3dcea32fa34c26feebd151f546dea85/src/ToySolver/Data/Polynomial.hs | haskell | ---------------------------------------------------------------------------
|
Module : ToySolver.Data.Polynomial
License : BSD-style
Maintainer :
Stability : provisional
Portability : portable
Polynomials
References:
* constructive-algebra package <-algebra>
---------------------------------------------------------------------------
* Polynomial type
* Conversion
* Query
* Operations
* Univariate polynomials
* Term
* Monic monomial
* Monomial order
* Pretty Printing | # OPTIONS_GHC -Wall #
Copyright : ( c ) 2012 - 2013
* Monomial order < >
* Polynomial class for < -u.ac.jp/~kodama/tips-RubyPoly.html >
module ToySolver.Data.Polynomial
(
Polynomial
, Var (..)
, constant
, terms
, fromTerms
, coeffMap
, fromCoeffMap
, fromTerm
, Degree (..)
, Vars (..)
, lt
, lc
, lm
, coeff
, lookupCoeff
, isPrimitive
, Factor (..)
, SQFree (..)
, ContPP (..)
, deriv
, integral
, eval
, subst
, mapCoeff
, toMonic
, toUPolynomialOf
, divModMP
, reduce
, UPolynomial
, X (..)
, UTerm
, UMonomial
, div
, mod
, divMod
, divides
, gcd
, lcm
, exgcd
, pdivMod
, pdiv
, pmod
, gcd'
, isRootOf
, isSquareFree
, nat
, eisensteinsCriterion
, Term
, tdeg
, tscale
, tmult
, tdivides
, tdiv
, tderiv
, tintegral
, Monomial
, mone
, mfromIndices
, mfromIndicesMap
, mindices
, mindicesMap
, mmult
, mpow
, mdivides
, mdiv
, mderiv
, mintegral
, mlcm
, mgcd
, mcoprime
, MonomialOrder
, lex
, revlex
, grlex
, grevlex
, PrintOptions (..)
, prettyPrint
, PrettyCoeff (..)
, PrettyVar (..)
) where
import Prelude hiding (lex, div, mod, divMod, gcd, lcm)
import ToySolver.Data.Polynomial.Base
import ToySolver.Data.Polynomial.Factorization.FiniteField ()
import ToySolver.Data.Polynomial.Factorization.Integer ()
import ToySolver.Data.Polynomial.Factorization.Rational ()
|
7a9cfb2478451097d1e84e16d0661bc7820f2706c9457dbac4d28d3f41ce6626 | gedge-platform/gedge-platform | cow_qs.erl | Copyright ( c ) 2013 - 2018 , < >
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-module(cow_qs).
-export([parse_qs/1]).
-export([qs/1]).
-export([urldecode/1]).
-export([urlencode/1]).
-type qs_vals() :: [{binary(), binary() | true}].
@doc an application / x - www - form - urlencoded string .
%%
%% The percent decoding is inlined to greatly improve the performance
%% by avoiding copying binaries twice (once for extracting, once for
%% decoding) instead of just extracting the proper representation.
-spec parse_qs(binary()) -> qs_vals().
parse_qs(B) ->
parse_qs_name(B, [], <<>>).
, H , L , Rest / bits > > , Acc , Name ) - >
C = (unhex(H) bsl 4 bor unhex(L)),
parse_qs_name(Rest, Acc, << Name/bits, C >>);
parse_qs_name(<< $+, Rest/bits >>, Acc, Name) ->
parse_qs_name(Rest, Acc, << Name/bits, " " >>);
parse_qs_name(<< $=, Rest/bits >>, Acc, Name) when Name =/= <<>> ->
parse_qs_value(Rest, Acc, Name, <<>>);
parse_qs_name(<< $&, Rest/bits >>, Acc, Name) ->
case Name of
<<>> -> parse_qs_name(Rest, Acc, <<>>);
_ -> parse_qs_name(Rest, [{Name, true}|Acc], <<>>)
end;
parse_qs_name(<< C, Rest/bits >>, Acc, Name) when C =/= $%, C =/= $= ->
parse_qs_name(Rest, Acc, << Name/bits, C >>);
parse_qs_name(<<>>, Acc, Name) ->
case Name of
<<>> -> lists:reverse(Acc);
_ -> lists:reverse([{Name, true}|Acc])
end.
, H , L , Rest / bits > > , Acc , Name , Value ) - >
C = (unhex(H) bsl 4 bor unhex(L)),
parse_qs_value(Rest, Acc, Name, << Value/bits, C >>);
parse_qs_value(<< $+, Rest/bits >>, Acc, Name, Value) ->
parse_qs_value(Rest, Acc, Name, << Value/bits, " " >>);
parse_qs_value(<< $&, Rest/bits >>, Acc, Name, Value) ->
parse_qs_name(Rest, [{Name, Value}|Acc], <<>>);
parse_qs_value(<< C, Rest/bits >>, Acc, Name, Value) when C =/= $% ->
parse_qs_value(Rest, Acc, Name, << Value/bits, C >>);
parse_qs_value(<<>>, Acc, Name, Value) ->
lists:reverse([{Name, Value}|Acc]).
-ifdef(TEST).
parse_qs_test_() ->
Tests = [
{<<>>, []},
{<<"&">>, []},
{<<"a">>, [{<<"a">>, true}]},
{<<"a&">>, [{<<"a">>, true}]},
{<<"&a">>, [{<<"a">>, true}]},
{<<"a&b">>, [{<<"a">>, true}, {<<"b">>, true}]},
{<<"a&&b">>, [{<<"a">>, true}, {<<"b">>, true}]},
{<<"a&b&">>, [{<<"a">>, true}, {<<"b">>, true}]},
{<<"=">>, error},
{<<"=b">>, error},
{<<"a=">>, [{<<"a">>, <<>>}]},
{<<"a=b">>, [{<<"a">>, <<"b">>}]},
{<<"a=&b=">>, [{<<"a">>, <<>>}, {<<"b">>, <<>>}]},
{<<"a=b&c&d=e">>, [{<<"a">>, <<"b">>},
{<<"c">>, true}, {<<"d">>, <<"e">>}]},
{<<"a=b=c&d=e=f&g=h=i">>, [{<<"a">>, <<"b=c">>},
{<<"d">>, <<"e=f">>}, {<<"g">>, <<"h=i">>}]},
{<<"+">>, [{<<" ">>, true}]},
{<<"+=+">>, [{<<" ">>, <<" ">>}]},
{<<"a+b=c+d">>, [{<<"a b">>, <<"c d">>}]},
{<<"+a+=+b+&+c+=+d+">>, [{<<" a ">>, <<" b ">>},
{<<" c ">>, <<" d ">>}]},
{<<"a%20b=c%20d">>, [{<<"a b">>, <<"c d">>}]},
{<<"%25%26%3D=%25%26%3D&_-.=.-_">>, [{<<"%&=">>, <<"%&=">>},
{<<"_-.">>, <<".-_">>}]},
{<<"for=extend%2Franch">>, [{<<"for">>, <<"extend/ranch">>}]}
],
[{Qs, fun() ->
E = try parse_qs(Qs) of
R -> R
catch _:_ ->
error
end
end} || {Qs, E} <- Tests].
parse_qs_identity_test_() ->
Tests = [
<<"+">>,
<<"hl=en&q=erlang+cowboy">>,
<<"direction=desc&for=extend%2Franch&sort=updated&state=open">>,
<<"i=EWiIXmPj5gl6&v=QowBp0oDLQXdd4x_GwiywA&ip=98.20.31.81&"
"la=en&pg=New8.undertonebrandsafe.com%2F698a2525065ee2"
"60c0b2f2aaad89ab82&re=&sz=1&fc=1&fr=140&br=3&bv=11.0."
"696.16&os=3&ov=&rs=vpl&k=cookies%7Csale%7Cbrowser%7Cm"
"ore%7Cprivacy%7Cstatistics%7Cactivities%7Cauction%7Ce"
"mail%7Cfree%7Cin...&t=112373&xt=5%7C61%7C0&tz=-1&ev=x"
"&tk=&za=1&ortb-za=1&zu=&zl=&ax=U&ay=U&ortb-pid=536454"
".55&ortb-sid=112373.8&seats=999&ortb-xt=IAB24&ortb-ugc=">>,
<<"i=9pQNskA&v=0ySQQd1F&ev=12345678&t=12345&sz=3&ip=67.58."
"236.89&la=en&pg=http%3A%2F%2Fwww.yahoo.com%2Fpage1.ht"
"m&re=http%3A%2F%2Fsearch.google.com&fc=1&fr=1&br=2&bv"
"=3.0.14&os=1&ov=XP&k=cars%2Cford&rs=js&xt=5%7C22%7C23"
"4&tz=%2B180&tk=key1%3Dvalue1%7Ckey2%3Dvalue2&zl=4%2C5"
"%2C6&za=4&zu=competitor.com&ua=Mozilla%2F5.0+%28Windo"
"ws%3B+U%3B+Windows+NT+6.1%3B+en-US%29+AppleWebKit%2F5"
"34.13+%28KHTML%2C+like+Gecko%29+Chrome%2F9.0.597.98+S"
"afari%2F534.13&ortb-za=1%2C6%2C13&ortb-pid=521732&ort"
"b-sid=521732&ortb-xt=IAB3&ortb-ugc=">>
],
[{V, fun() -> V = qs(parse_qs(V)) end} || V <- Tests].
horse_parse_qs_shorter() ->
horse:repeat(20000,
parse_qs(<<"hl=en&q=erlang%20cowboy">>)
).
horse_parse_qs_short() ->
horse:repeat(20000,
parse_qs(
<<"direction=desc&for=extend%2Franch&sort=updated&state=open">>)
).
horse_parse_qs_long() ->
horse:repeat(20000,
parse_qs(<<"i=EWiIXmPj5gl6&v=QowBp0oDLQXdd4x_GwiywA&ip=98.20.31.81&"
"la=en&pg=New8.undertonebrandsafe.com%2F698a2525065ee260c0b2f2a"
"aad89ab82&re=&sz=1&fc=1&fr=140&br=3&bv=11.0.696.16&os=3&ov=&rs"
"=vpl&k=cookies%7Csale%7Cbrowser%7Cmore%7Cprivacy%7Cstatistics%"
"7Cactivities%7Cauction%7Cemail%7Cfree%7Cin...&t=112373&xt=5%7C"
"61%7C0&tz=-1&ev=x&tk=&za=1&ortb-za=1&zu=&zl=&ax=U&ay=U&ortb-pi"
"d=536454.55&ortb-sid=112373.8&seats=999&ortb-xt=IAB24&ortb-ugc"
"=">>)
).
horse_parse_qs_longer() ->
horse:repeat(20000,
parse_qs(<<"i=9pQNskA&v=0ySQQd1F&ev=12345678&t=12345&sz=3&ip=67.58."
"236.89&la=en&pg=http%3A%2F%2Fwww.yahoo.com%2Fpage1.htm&re=http"
"%3A%2F%2Fsearch.google.com&fc=1&fr=1&br=2&bv=3.0.14&os=1&ov=XP"
"&k=cars%2cford&rs=js&xt=5%7c22%7c234&tz=%2b180&tk=key1%3Dvalue"
"1%7Ckey2%3Dvalue2&zl=4,5,6&za=4&zu=competitor.com&ua=Mozilla%2"
"F5.0%20(Windows%3B%20U%3B%20Windows%20NT%206.1%3B%20en-US)%20A"
"ppleWebKit%2F534.13%20(KHTML%2C%20like%20Gecko)%20Chrome%2F9.0"
".597.98%20Safari%2F534.13&ortb-za=1%2C6%2C13&ortb-pid=521732&o"
"rtb-sid=521732&ortb-xt=IAB3&ortb-ugc=">>)
).
-endif.
%% @doc Build an application/x-www-form-urlencoded string.
-spec qs(qs_vals()) -> binary().
qs([]) ->
<<>>;
qs(L) ->
qs(L, <<>>).
qs([], Acc) ->
<< $&, Qs/bits >> = Acc,
Qs;
qs([{Name, true}|Tail], Acc) ->
Acc2 = urlencode(Name, << Acc/bits, $& >>),
qs(Tail, Acc2);
qs([{Name, Value}|Tail], Acc) ->
Acc2 = urlencode(Name, << Acc/bits, $& >>),
Acc3 = urlencode(Value, << Acc2/bits, $= >>),
qs(Tail, Acc3).
-define(QS_SHORTER, [
{<<"hl">>, <<"en">>},
{<<"q">>, <<"erlang cowboy">>}
]).
-define(QS_SHORT, [
{<<"direction">>, <<"desc">>},
{<<"for">>, <<"extend/ranch">>},
{<<"sort">>, <<"updated">>},
{<<"state">>, <<"open">>}
]).
-define(QS_LONG, [
{<<"i">>, <<"EWiIXmPj5gl6">>},
{<<"v">>, <<"QowBp0oDLQXdd4x_GwiywA">>},
{<<"ip">>, <<"98.20.31.81">>},
{<<"la">>, <<"en">>},
{<<"pg">>, <<"New8.undertonebrandsafe.com/"
"698a2525065ee260c0b2f2aaad89ab82">>},
{<<"re">>, <<>>},
{<<"sz">>, <<"1">>},
{<<"fc">>, <<"1">>},
{<<"fr">>, <<"140">>},
{<<"br">>, <<"3">>},
{<<"bv">>, <<"11.0.696.16">>},
{<<"os">>, <<"3">>},
{<<"ov">>, <<>>},
{<<"rs">>, <<"vpl">>},
{<<"k">>, <<"cookies|sale|browser|more|privacy|statistics|"
"activities|auction|email|free|in...">>},
{<<"t">>, <<"112373">>},
{<<"xt">>, <<"5|61|0">>},
{<<"tz">>, <<"-1">>},
{<<"ev">>, <<"x">>},
{<<"tk">>, <<>>},
{<<"za">>, <<"1">>},
{<<"ortb-za">>, <<"1">>},
{<<"zu">>, <<>>},
{<<"zl">>, <<>>},
{<<"ax">>, <<"U">>},
{<<"ay">>, <<"U">>},
{<<"ortb-pid">>, <<"536454.55">>},
{<<"ortb-sid">>, <<"112373.8">>},
{<<"seats">>, <<"999">>},
{<<"ortb-xt">>, <<"IAB24">>},
{<<"ortb-ugc">>, <<>>}
]).
-define(QS_LONGER, [
{<<"i">>, <<"9pQNskA">>},
{<<"v">>, <<"0ySQQd1F">>},
{<<"ev">>, <<"12345678">>},
{<<"t">>, <<"12345">>},
{<<"sz">>, <<"3">>},
{<<"ip">>, <<"67.58.236.89">>},
{<<"la">>, <<"en">>},
{<<"pg">>, <<"">>},
{<<"re">>, <<"">>},
{<<"fc">>, <<"1">>},
{<<"fr">>, <<"1">>},
{<<"br">>, <<"2">>},
{<<"bv">>, <<"3.0.14">>},
{<<"os">>, <<"1">>},
{<<"ov">>, <<"XP">>},
{<<"k">>, <<"cars,ford">>},
{<<"rs">>, <<"js">>},
{<<"xt">>, <<"5|22|234">>},
{<<"tz">>, <<"+180">>},
{<<"tk">>, <<"key1=value1|key2=value2">>},
{<<"zl">>, <<"4,5,6">>},
{<<"za">>, <<"4">>},
{<<"zu">>, <<"competitor.com">>},
{<<"ua">>, <<"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) "
"AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.98 "
"Safari/534.13">>},
{<<"ortb-za">>, <<"1,6,13">>},
{<<"ortb-pid">>, <<"521732">>},
{<<"ortb-sid">>, <<"521732">>},
{<<"ortb-xt">>, <<"IAB3">>},
{<<"ortb-ugc">>, <<>>}
]).
-ifdef(TEST).
qs_test_() ->
Tests = [
{[<<"a">>], error},
{[{<<"a">>, <<"b">>, <<"c">>}], error},
{[], <<>>},
{[{<<"a">>, true}], <<"a">>},
{[{<<"a">>, true}, {<<"b">>, true}], <<"a&b">>},
{[{<<"a">>, <<>>}], <<"a=">>},
{[{<<"a">>, <<"b">>}], <<"a=b">>},
{[{<<"a">>, <<>>}, {<<"b">>, <<>>}], <<"a=&b=">>},
{[{<<"a">>, <<"b">>}, {<<"c">>, true}, {<<"d">>, <<"e">>}],
<<"a=b&c&d=e">>},
{[{<<"a">>, <<"b=c">>}, {<<"d">>, <<"e=f">>}, {<<"g">>, <<"h=i">>}],
<<"a=b%3Dc&d=e%3Df&g=h%3Di">>},
{[{<<" ">>, true}], <<"+">>},
{[{<<" ">>, <<" ">>}], <<"+=+">>},
{[{<<"a b">>, <<"c d">>}], <<"a+b=c+d">>},
{[{<<" a ">>, <<" b ">>}, {<<" c ">>, <<" d ">>}],
<<"+a+=+b+&+c+=+d+">>},
{[{<<"%&=">>, <<"%&=">>}, {<<"_-.">>, <<".-_">>}],
<<"%25%26%3D=%25%26%3D&_-.=.-_">>},
{[{<<"for">>, <<"extend/ranch">>}], <<"for=extend%2Franch">>}
],
[{lists:flatten(io_lib:format("~p", [Vals])), fun() ->
E = try qs(Vals) of
R -> R
catch _:_ ->
error
end
end} || {Vals, E} <- Tests].
qs_identity_test_() ->
Tests = [
[{<<"+">>, true}],
?QS_SHORTER,
?QS_SHORT,
?QS_LONG,
?QS_LONGER
],
[{lists:flatten(io_lib:format("~p", [V])), fun() ->
V = parse_qs(qs(V))
end} || V <- Tests].
horse_qs_shorter() ->
horse:repeat(20000, qs(?QS_SHORTER)).
horse_qs_short() ->
horse:repeat(20000, qs(?QS_SHORT)).
horse_qs_long() ->
horse:repeat(20000, qs(?QS_LONG)).
horse_qs_longer() ->
horse:repeat(20000, qs(?QS_LONGER)).
-endif.
%% @doc Decode a percent encoded string (x-www-form-urlencoded rules).
-spec urldecode(B) -> B when B::binary().
urldecode(B) ->
urldecode(B, <<>>).
, H , L , Rest / bits > > , Acc ) - >
C = (unhex(H) bsl 4 bor unhex(L)),
urldecode(Rest, << Acc/bits, C >>);
urldecode(<< $+, Rest/bits >>, Acc) ->
urldecode(Rest, << Acc/bits, " " >>);
urldecode(<< C, Rest/bits >>, Acc) when C =/= $% ->
urldecode(Rest, << Acc/bits, C >>);
urldecode(<<>>, Acc) ->
Acc.
unhex($0) -> 0;
unhex($1) -> 1;
unhex($2) -> 2;
unhex($3) -> 3;
unhex($4) -> 4;
unhex($5) -> 5;
unhex($6) -> 6;
unhex($7) -> 7;
unhex($8) -> 8;
unhex($9) -> 9;
unhex($A) -> 10;
unhex($B) -> 11;
unhex($C) -> 12;
unhex($D) -> 13;
unhex($E) -> 14;
unhex($F) -> 15;
unhex($a) -> 10;
unhex($b) -> 11;
unhex($c) -> 12;
unhex($d) -> 13;
unhex($e) -> 14;
unhex($f) -> 15.
-ifdef(TEST).
urldecode_test_() ->
Tests = [
{<<"%20">>, <<" ">>},
{<<"+">>, <<" ">>},
{<<"%00">>, <<0>>},
{<<"%fF">>, <<255>>},
{<<"123">>, <<"123">>},
{<<"%i5">>, error},
{<<"%5">>, error}
],
[{Qs, fun() ->
E = try urldecode(Qs) of
R -> R
catch _:_ ->
error
end
end} || {Qs, E} <- Tests].
urldecode_identity_test_() ->
Tests = [
<<"+">>,
<<"nothingnothingnothingnothing">>,
<<"Small+fast+modular+HTTP+server">>,
<<"Small%2C+fast%2C+modular+HTTP+server.">>,
<<"%E3%83%84%E3%82%A4%E3%83%B3%E3%82%BD%E3%82%A6%E3%83"
"%AB%E3%80%9C%E8%BC%AA%E5%BB%BB%E3%81%99%E3%82%8B%E6%97%8B%E5"
"%BE%8B%E3%80%9C">>
],
[{V, fun() -> V = urlencode(urldecode(V)) end} || V <- Tests].
horse_urldecode() ->
horse:repeat(100000,
urldecode(<<"nothingnothingnothingnothing">>)
).
horse_urldecode_plus() ->
horse:repeat(100000,
urldecode(<<"Small+fast+modular+HTTP+server">>)
).
horse_urldecode_hex() ->
horse:repeat(100000,
urldecode(<<"Small%2C%20fast%2C%20modular%20HTTP%20server.">>)
).
horse_urldecode_jp_hex() ->
horse:repeat(100000,
urldecode(<<"%E3%83%84%E3%82%A4%E3%83%B3%E3%82%BD%E3%82%A6%E3%83"
"%AB%E3%80%9C%E8%BC%AA%E5%BB%BB%E3%81%99%E3%82%8B%E6%97%8B%E5"
"%BE%8B%E3%80%9C">>)
).
horse_urldecode_mix() ->
horse:repeat(100000,
urldecode(<<"Small%2C+fast%2C+modular+HTTP+server.">>)
).
-endif.
%% @doc Percent encode a string (x-www-form-urlencoded rules).
-spec urlencode(B) -> B when B::binary().
urlencode(B) ->
urlencode(B, <<>>).
urlencode(<< $\s, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $+ >>);
urlencode(<< $-, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $- >>);
urlencode(<< $., Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $. >>);
urlencode(<< $0, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $0 >>);
urlencode(<< $1, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $1 >>);
urlencode(<< $2, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $2 >>);
urlencode(<< $3, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $3 >>);
urlencode(<< $4, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $4 >>);
urlencode(<< $5, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $5 >>);
urlencode(<< $6, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $6 >>);
urlencode(<< $7, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $7 >>);
urlencode(<< $8, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $8 >>);
urlencode(<< $9, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $9 >>);
urlencode(<< $A, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $A >>);
urlencode(<< $B, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $B >>);
urlencode(<< $C, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $C >>);
urlencode(<< $D, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $D >>);
urlencode(<< $E, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $E >>);
urlencode(<< $F, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $F >>);
urlencode(<< $G, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $G >>);
urlencode(<< $H, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $H >>);
urlencode(<< $I, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $I >>);
urlencode(<< $J, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $J >>);
urlencode(<< $K, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $K >>);
urlencode(<< $L, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $L >>);
urlencode(<< $M, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $M >>);
urlencode(<< $N, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $N >>);
urlencode(<< $O, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $O >>);
urlencode(<< $P, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $P >>);
urlencode(<< $Q, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $Q >>);
urlencode(<< $R, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $R >>);
urlencode(<< $S, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $S >>);
urlencode(<< $T, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $T >>);
urlencode(<< $U, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $U >>);
urlencode(<< $V, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $V >>);
urlencode(<< $W, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $W >>);
urlencode(<< $X, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $X >>);
urlencode(<< $Y, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $Y >>);
urlencode(<< $Z, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $Z >>);
urlencode(<< $_, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $_ >>);
urlencode(<< $a, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $a >>);
urlencode(<< $b, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $b >>);
urlencode(<< $c, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $c >>);
urlencode(<< $d, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $d >>);
urlencode(<< $e, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $e >>);
urlencode(<< $f, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $f >>);
urlencode(<< $g, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $g >>);
urlencode(<< $h, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $h >>);
urlencode(<< $i, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $i >>);
urlencode(<< $j, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $j >>);
urlencode(<< $k, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $k >>);
urlencode(<< $l, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $l >>);
urlencode(<< $m, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $m >>);
urlencode(<< $n, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $n >>);
urlencode(<< $o, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $o >>);
urlencode(<< $p, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $p >>);
urlencode(<< $q, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $q >>);
urlencode(<< $r, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $r >>);
urlencode(<< $s, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $s >>);
urlencode(<< $t, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $t >>);
urlencode(<< $u, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $u >>);
urlencode(<< $v, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $v >>);
urlencode(<< $w, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $w >>);
urlencode(<< $x, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $x >>);
urlencode(<< $y, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $y >>);
urlencode(<< $z, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $z >>);
urlencode(<< C, Rest/bits >>, Acc) ->
H = hex(C bsr 4),
L = hex(C band 16#0f),
urlencode(Rest, << Acc/bits, $%, H, L >>);
urlencode(<<>>, Acc) ->
Acc.
hex( 0) -> $0;
hex( 1) -> $1;
hex( 2) -> $2;
hex( 3) -> $3;
hex( 4) -> $4;
hex( 5) -> $5;
hex( 6) -> $6;
hex( 7) -> $7;
hex( 8) -> $8;
hex( 9) -> $9;
hex(10) -> $A;
hex(11) -> $B;
hex(12) -> $C;
hex(13) -> $D;
hex(14) -> $E;
hex(15) -> $F.
-ifdef(TEST).
urlencode_test_() ->
Tests = [
{<<255, 0>>, <<"%FF%00">>},
{<<255, " ">>, <<"%FF+">>},
{<<" ">>, <<"+">>},
{<<"aBc123">>, <<"aBc123">>},
{<<".-_">>, <<".-_">>}
],
[{V, fun() -> E = urlencode(V) end} || {V, E} <- Tests].
urlencode_identity_test_() ->
Tests = [
<<"+">>,
<<"nothingnothingnothingnothing">>,
<<"Small fast modular HTTP server">>,
<<"Small, fast, modular HTTP server.">>,
<<227,131,132,227,130,164,227,131,179,227,130,189,227,
130,166,227,131,171,227,128,156,232,188,170,229,187,187,227,
129,153,227,130,139,230,151,139,229,190,139,227,128,156>>
],
[{V, fun() -> V = urldecode(urlencode(V)) end} || V <- Tests].
horse_urlencode() ->
horse:repeat(100000,
urlencode(<<"nothingnothingnothingnothing">>)
).
horse_urlencode_plus() ->
horse:repeat(100000,
urlencode(<<"Small fast modular HTTP server">>)
).
horse_urlencode_jp() ->
horse:repeat(100000,
urlencode(<<227,131,132,227,130,164,227,131,179,227,130,189,227,
130,166,227,131,171,227,128,156,232,188,170,229,187,187,227,
129,153,227,130,139,230,151,139,229,190,139,227,128,156>>)
).
horse_urlencode_mix() ->
horse:repeat(100000,
urlencode(<<"Small, fast, modular HTTP server.">>)
).
-endif.
| null | https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/cowlib/src/cow_qs.erl | erlang |
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
The percent decoding is inlined to greatly improve the performance
by avoiding copying binaries twice (once for extracting, once for
decoding) instead of just extracting the proper representation.
, C =/= $= ->
->
@doc Build an application/x-www-form-urlencoded string.
@doc Decode a percent encoded string (x-www-form-urlencoded rules).
->
@doc Percent encode a string (x-www-form-urlencoded rules).
, H, L >>); | Copyright ( c ) 2013 - 2018 , < >
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
-module(cow_qs).
-export([parse_qs/1]).
-export([qs/1]).
-export([urldecode/1]).
-export([urlencode/1]).
-type qs_vals() :: [{binary(), binary() | true}].
@doc an application / x - www - form - urlencoded string .
-spec parse_qs(binary()) -> qs_vals().
parse_qs(B) ->
parse_qs_name(B, [], <<>>).
, H , L , Rest / bits > > , Acc , Name ) - >
C = (unhex(H) bsl 4 bor unhex(L)),
parse_qs_name(Rest, Acc, << Name/bits, C >>);
parse_qs_name(<< $+, Rest/bits >>, Acc, Name) ->
parse_qs_name(Rest, Acc, << Name/bits, " " >>);
parse_qs_name(<< $=, Rest/bits >>, Acc, Name) when Name =/= <<>> ->
parse_qs_value(Rest, Acc, Name, <<>>);
parse_qs_name(<< $&, Rest/bits >>, Acc, Name) ->
case Name of
<<>> -> parse_qs_name(Rest, Acc, <<>>);
_ -> parse_qs_name(Rest, [{Name, true}|Acc], <<>>)
end;
parse_qs_name(Rest, Acc, << Name/bits, C >>);
parse_qs_name(<<>>, Acc, Name) ->
case Name of
<<>> -> lists:reverse(Acc);
_ -> lists:reverse([{Name, true}|Acc])
end.
, H , L , Rest / bits > > , Acc , Name , Value ) - >
C = (unhex(H) bsl 4 bor unhex(L)),
parse_qs_value(Rest, Acc, Name, << Value/bits, C >>);
parse_qs_value(<< $+, Rest/bits >>, Acc, Name, Value) ->
parse_qs_value(Rest, Acc, Name, << Value/bits, " " >>);
parse_qs_value(<< $&, Rest/bits >>, Acc, Name, Value) ->
parse_qs_name(Rest, [{Name, Value}|Acc], <<>>);
parse_qs_value(Rest, Acc, Name, << Value/bits, C >>);
parse_qs_value(<<>>, Acc, Name, Value) ->
lists:reverse([{Name, Value}|Acc]).
-ifdef(TEST).
parse_qs_test_() ->
Tests = [
{<<>>, []},
{<<"&">>, []},
{<<"a">>, [{<<"a">>, true}]},
{<<"a&">>, [{<<"a">>, true}]},
{<<"&a">>, [{<<"a">>, true}]},
{<<"a&b">>, [{<<"a">>, true}, {<<"b">>, true}]},
{<<"a&&b">>, [{<<"a">>, true}, {<<"b">>, true}]},
{<<"a&b&">>, [{<<"a">>, true}, {<<"b">>, true}]},
{<<"=">>, error},
{<<"=b">>, error},
{<<"a=">>, [{<<"a">>, <<>>}]},
{<<"a=b">>, [{<<"a">>, <<"b">>}]},
{<<"a=&b=">>, [{<<"a">>, <<>>}, {<<"b">>, <<>>}]},
{<<"a=b&c&d=e">>, [{<<"a">>, <<"b">>},
{<<"c">>, true}, {<<"d">>, <<"e">>}]},
{<<"a=b=c&d=e=f&g=h=i">>, [{<<"a">>, <<"b=c">>},
{<<"d">>, <<"e=f">>}, {<<"g">>, <<"h=i">>}]},
{<<"+">>, [{<<" ">>, true}]},
{<<"+=+">>, [{<<" ">>, <<" ">>}]},
{<<"a+b=c+d">>, [{<<"a b">>, <<"c d">>}]},
{<<"+a+=+b+&+c+=+d+">>, [{<<" a ">>, <<" b ">>},
{<<" c ">>, <<" d ">>}]},
{<<"a%20b=c%20d">>, [{<<"a b">>, <<"c d">>}]},
{<<"%25%26%3D=%25%26%3D&_-.=.-_">>, [{<<"%&=">>, <<"%&=">>},
{<<"_-.">>, <<".-_">>}]},
{<<"for=extend%2Franch">>, [{<<"for">>, <<"extend/ranch">>}]}
],
[{Qs, fun() ->
E = try parse_qs(Qs) of
R -> R
catch _:_ ->
error
end
end} || {Qs, E} <- Tests].
parse_qs_identity_test_() ->
Tests = [
<<"+">>,
<<"hl=en&q=erlang+cowboy">>,
<<"direction=desc&for=extend%2Franch&sort=updated&state=open">>,
<<"i=EWiIXmPj5gl6&v=QowBp0oDLQXdd4x_GwiywA&ip=98.20.31.81&"
"la=en&pg=New8.undertonebrandsafe.com%2F698a2525065ee2"
"60c0b2f2aaad89ab82&re=&sz=1&fc=1&fr=140&br=3&bv=11.0."
"696.16&os=3&ov=&rs=vpl&k=cookies%7Csale%7Cbrowser%7Cm"
"ore%7Cprivacy%7Cstatistics%7Cactivities%7Cauction%7Ce"
"mail%7Cfree%7Cin...&t=112373&xt=5%7C61%7C0&tz=-1&ev=x"
"&tk=&za=1&ortb-za=1&zu=&zl=&ax=U&ay=U&ortb-pid=536454"
".55&ortb-sid=112373.8&seats=999&ortb-xt=IAB24&ortb-ugc=">>,
<<"i=9pQNskA&v=0ySQQd1F&ev=12345678&t=12345&sz=3&ip=67.58."
"236.89&la=en&pg=http%3A%2F%2Fwww.yahoo.com%2Fpage1.ht"
"m&re=http%3A%2F%2Fsearch.google.com&fc=1&fr=1&br=2&bv"
"=3.0.14&os=1&ov=XP&k=cars%2Cford&rs=js&xt=5%7C22%7C23"
"4&tz=%2B180&tk=key1%3Dvalue1%7Ckey2%3Dvalue2&zl=4%2C5"
"%2C6&za=4&zu=competitor.com&ua=Mozilla%2F5.0+%28Windo"
"ws%3B+U%3B+Windows+NT+6.1%3B+en-US%29+AppleWebKit%2F5"
"34.13+%28KHTML%2C+like+Gecko%29+Chrome%2F9.0.597.98+S"
"afari%2F534.13&ortb-za=1%2C6%2C13&ortb-pid=521732&ort"
"b-sid=521732&ortb-xt=IAB3&ortb-ugc=">>
],
[{V, fun() -> V = qs(parse_qs(V)) end} || V <- Tests].
horse_parse_qs_shorter() ->
horse:repeat(20000,
parse_qs(<<"hl=en&q=erlang%20cowboy">>)
).
horse_parse_qs_short() ->
horse:repeat(20000,
parse_qs(
<<"direction=desc&for=extend%2Franch&sort=updated&state=open">>)
).
horse_parse_qs_long() ->
horse:repeat(20000,
parse_qs(<<"i=EWiIXmPj5gl6&v=QowBp0oDLQXdd4x_GwiywA&ip=98.20.31.81&"
"la=en&pg=New8.undertonebrandsafe.com%2F698a2525065ee260c0b2f2a"
"aad89ab82&re=&sz=1&fc=1&fr=140&br=3&bv=11.0.696.16&os=3&ov=&rs"
"=vpl&k=cookies%7Csale%7Cbrowser%7Cmore%7Cprivacy%7Cstatistics%"
"7Cactivities%7Cauction%7Cemail%7Cfree%7Cin...&t=112373&xt=5%7C"
"61%7C0&tz=-1&ev=x&tk=&za=1&ortb-za=1&zu=&zl=&ax=U&ay=U&ortb-pi"
"d=536454.55&ortb-sid=112373.8&seats=999&ortb-xt=IAB24&ortb-ugc"
"=">>)
).
horse_parse_qs_longer() ->
horse:repeat(20000,
parse_qs(<<"i=9pQNskA&v=0ySQQd1F&ev=12345678&t=12345&sz=3&ip=67.58."
"236.89&la=en&pg=http%3A%2F%2Fwww.yahoo.com%2Fpage1.htm&re=http"
"%3A%2F%2Fsearch.google.com&fc=1&fr=1&br=2&bv=3.0.14&os=1&ov=XP"
"&k=cars%2cford&rs=js&xt=5%7c22%7c234&tz=%2b180&tk=key1%3Dvalue"
"1%7Ckey2%3Dvalue2&zl=4,5,6&za=4&zu=competitor.com&ua=Mozilla%2"
"F5.0%20(Windows%3B%20U%3B%20Windows%20NT%206.1%3B%20en-US)%20A"
"ppleWebKit%2F534.13%20(KHTML%2C%20like%20Gecko)%20Chrome%2F9.0"
".597.98%20Safari%2F534.13&ortb-za=1%2C6%2C13&ortb-pid=521732&o"
"rtb-sid=521732&ortb-xt=IAB3&ortb-ugc=">>)
).
-endif.
-spec qs(qs_vals()) -> binary().
qs([]) ->
<<>>;
qs(L) ->
qs(L, <<>>).
qs([], Acc) ->
<< $&, Qs/bits >> = Acc,
Qs;
qs([{Name, true}|Tail], Acc) ->
Acc2 = urlencode(Name, << Acc/bits, $& >>),
qs(Tail, Acc2);
qs([{Name, Value}|Tail], Acc) ->
Acc2 = urlencode(Name, << Acc/bits, $& >>),
Acc3 = urlencode(Value, << Acc2/bits, $= >>),
qs(Tail, Acc3).
-define(QS_SHORTER, [
{<<"hl">>, <<"en">>},
{<<"q">>, <<"erlang cowboy">>}
]).
-define(QS_SHORT, [
{<<"direction">>, <<"desc">>},
{<<"for">>, <<"extend/ranch">>},
{<<"sort">>, <<"updated">>},
{<<"state">>, <<"open">>}
]).
-define(QS_LONG, [
{<<"i">>, <<"EWiIXmPj5gl6">>},
{<<"v">>, <<"QowBp0oDLQXdd4x_GwiywA">>},
{<<"ip">>, <<"98.20.31.81">>},
{<<"la">>, <<"en">>},
{<<"pg">>, <<"New8.undertonebrandsafe.com/"
"698a2525065ee260c0b2f2aaad89ab82">>},
{<<"re">>, <<>>},
{<<"sz">>, <<"1">>},
{<<"fc">>, <<"1">>},
{<<"fr">>, <<"140">>},
{<<"br">>, <<"3">>},
{<<"bv">>, <<"11.0.696.16">>},
{<<"os">>, <<"3">>},
{<<"ov">>, <<>>},
{<<"rs">>, <<"vpl">>},
{<<"k">>, <<"cookies|sale|browser|more|privacy|statistics|"
"activities|auction|email|free|in...">>},
{<<"t">>, <<"112373">>},
{<<"xt">>, <<"5|61|0">>},
{<<"tz">>, <<"-1">>},
{<<"ev">>, <<"x">>},
{<<"tk">>, <<>>},
{<<"za">>, <<"1">>},
{<<"ortb-za">>, <<"1">>},
{<<"zu">>, <<>>},
{<<"zl">>, <<>>},
{<<"ax">>, <<"U">>},
{<<"ay">>, <<"U">>},
{<<"ortb-pid">>, <<"536454.55">>},
{<<"ortb-sid">>, <<"112373.8">>},
{<<"seats">>, <<"999">>},
{<<"ortb-xt">>, <<"IAB24">>},
{<<"ortb-ugc">>, <<>>}
]).
-define(QS_LONGER, [
{<<"i">>, <<"9pQNskA">>},
{<<"v">>, <<"0ySQQd1F">>},
{<<"ev">>, <<"12345678">>},
{<<"t">>, <<"12345">>},
{<<"sz">>, <<"3">>},
{<<"ip">>, <<"67.58.236.89">>},
{<<"la">>, <<"en">>},
{<<"pg">>, <<"">>},
{<<"re">>, <<"">>},
{<<"fc">>, <<"1">>},
{<<"fr">>, <<"1">>},
{<<"br">>, <<"2">>},
{<<"bv">>, <<"3.0.14">>},
{<<"os">>, <<"1">>},
{<<"ov">>, <<"XP">>},
{<<"k">>, <<"cars,ford">>},
{<<"rs">>, <<"js">>},
{<<"xt">>, <<"5|22|234">>},
{<<"tz">>, <<"+180">>},
{<<"tk">>, <<"key1=value1|key2=value2">>},
{<<"zl">>, <<"4,5,6">>},
{<<"za">>, <<"4">>},
{<<"zu">>, <<"competitor.com">>},
{<<"ua">>, <<"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) "
"AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.98 "
"Safari/534.13">>},
{<<"ortb-za">>, <<"1,6,13">>},
{<<"ortb-pid">>, <<"521732">>},
{<<"ortb-sid">>, <<"521732">>},
{<<"ortb-xt">>, <<"IAB3">>},
{<<"ortb-ugc">>, <<>>}
]).
-ifdef(TEST).
qs_test_() ->
Tests = [
{[<<"a">>], error},
{[{<<"a">>, <<"b">>, <<"c">>}], error},
{[], <<>>},
{[{<<"a">>, true}], <<"a">>},
{[{<<"a">>, true}, {<<"b">>, true}], <<"a&b">>},
{[{<<"a">>, <<>>}], <<"a=">>},
{[{<<"a">>, <<"b">>}], <<"a=b">>},
{[{<<"a">>, <<>>}, {<<"b">>, <<>>}], <<"a=&b=">>},
{[{<<"a">>, <<"b">>}, {<<"c">>, true}, {<<"d">>, <<"e">>}],
<<"a=b&c&d=e">>},
{[{<<"a">>, <<"b=c">>}, {<<"d">>, <<"e=f">>}, {<<"g">>, <<"h=i">>}],
<<"a=b%3Dc&d=e%3Df&g=h%3Di">>},
{[{<<" ">>, true}], <<"+">>},
{[{<<" ">>, <<" ">>}], <<"+=+">>},
{[{<<"a b">>, <<"c d">>}], <<"a+b=c+d">>},
{[{<<" a ">>, <<" b ">>}, {<<" c ">>, <<" d ">>}],
<<"+a+=+b+&+c+=+d+">>},
{[{<<"%&=">>, <<"%&=">>}, {<<"_-.">>, <<".-_">>}],
<<"%25%26%3D=%25%26%3D&_-.=.-_">>},
{[{<<"for">>, <<"extend/ranch">>}], <<"for=extend%2Franch">>}
],
[{lists:flatten(io_lib:format("~p", [Vals])), fun() ->
E = try qs(Vals) of
R -> R
catch _:_ ->
error
end
end} || {Vals, E} <- Tests].
qs_identity_test_() ->
Tests = [
[{<<"+">>, true}],
?QS_SHORTER,
?QS_SHORT,
?QS_LONG,
?QS_LONGER
],
[{lists:flatten(io_lib:format("~p", [V])), fun() ->
V = parse_qs(qs(V))
end} || V <- Tests].
horse_qs_shorter() ->
horse:repeat(20000, qs(?QS_SHORTER)).
horse_qs_short() ->
horse:repeat(20000, qs(?QS_SHORT)).
horse_qs_long() ->
horse:repeat(20000, qs(?QS_LONG)).
horse_qs_longer() ->
horse:repeat(20000, qs(?QS_LONGER)).
-endif.
-spec urldecode(B) -> B when B::binary().
urldecode(B) ->
urldecode(B, <<>>).
, H , L , Rest / bits > > , Acc ) - >
C = (unhex(H) bsl 4 bor unhex(L)),
urldecode(Rest, << Acc/bits, C >>);
urldecode(<< $+, Rest/bits >>, Acc) ->
urldecode(Rest, << Acc/bits, " " >>);
urldecode(Rest, << Acc/bits, C >>);
urldecode(<<>>, Acc) ->
Acc.
unhex($0) -> 0;
unhex($1) -> 1;
unhex($2) -> 2;
unhex($3) -> 3;
unhex($4) -> 4;
unhex($5) -> 5;
unhex($6) -> 6;
unhex($7) -> 7;
unhex($8) -> 8;
unhex($9) -> 9;
unhex($A) -> 10;
unhex($B) -> 11;
unhex($C) -> 12;
unhex($D) -> 13;
unhex($E) -> 14;
unhex($F) -> 15;
unhex($a) -> 10;
unhex($b) -> 11;
unhex($c) -> 12;
unhex($d) -> 13;
unhex($e) -> 14;
unhex($f) -> 15.
-ifdef(TEST).
urldecode_test_() ->
Tests = [
{<<"%20">>, <<" ">>},
{<<"+">>, <<" ">>},
{<<"%00">>, <<0>>},
{<<"%fF">>, <<255>>},
{<<"123">>, <<"123">>},
{<<"%i5">>, error},
{<<"%5">>, error}
],
[{Qs, fun() ->
E = try urldecode(Qs) of
R -> R
catch _:_ ->
error
end
end} || {Qs, E} <- Tests].
urldecode_identity_test_() ->
Tests = [
<<"+">>,
<<"nothingnothingnothingnothing">>,
<<"Small+fast+modular+HTTP+server">>,
<<"Small%2C+fast%2C+modular+HTTP+server.">>,
<<"%E3%83%84%E3%82%A4%E3%83%B3%E3%82%BD%E3%82%A6%E3%83"
"%AB%E3%80%9C%E8%BC%AA%E5%BB%BB%E3%81%99%E3%82%8B%E6%97%8B%E5"
"%BE%8B%E3%80%9C">>
],
[{V, fun() -> V = urlencode(urldecode(V)) end} || V <- Tests].
horse_urldecode() ->
horse:repeat(100000,
urldecode(<<"nothingnothingnothingnothing">>)
).
horse_urldecode_plus() ->
horse:repeat(100000,
urldecode(<<"Small+fast+modular+HTTP+server">>)
).
horse_urldecode_hex() ->
horse:repeat(100000,
urldecode(<<"Small%2C%20fast%2C%20modular%20HTTP%20server.">>)
).
horse_urldecode_jp_hex() ->
horse:repeat(100000,
urldecode(<<"%E3%83%84%E3%82%A4%E3%83%B3%E3%82%BD%E3%82%A6%E3%83"
"%AB%E3%80%9C%E8%BC%AA%E5%BB%BB%E3%81%99%E3%82%8B%E6%97%8B%E5"
"%BE%8B%E3%80%9C">>)
).
horse_urldecode_mix() ->
horse:repeat(100000,
urldecode(<<"Small%2C+fast%2C+modular+HTTP+server.">>)
).
-endif.
-spec urlencode(B) -> B when B::binary().
urlencode(B) ->
urlencode(B, <<>>).
urlencode(<< $\s, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $+ >>);
urlencode(<< $-, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $- >>);
urlencode(<< $., Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $. >>);
urlencode(<< $0, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $0 >>);
urlencode(<< $1, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $1 >>);
urlencode(<< $2, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $2 >>);
urlencode(<< $3, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $3 >>);
urlencode(<< $4, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $4 >>);
urlencode(<< $5, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $5 >>);
urlencode(<< $6, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $6 >>);
urlencode(<< $7, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $7 >>);
urlencode(<< $8, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $8 >>);
urlencode(<< $9, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $9 >>);
urlencode(<< $A, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $A >>);
urlencode(<< $B, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $B >>);
urlencode(<< $C, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $C >>);
urlencode(<< $D, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $D >>);
urlencode(<< $E, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $E >>);
urlencode(<< $F, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $F >>);
urlencode(<< $G, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $G >>);
urlencode(<< $H, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $H >>);
urlencode(<< $I, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $I >>);
urlencode(<< $J, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $J >>);
urlencode(<< $K, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $K >>);
urlencode(<< $L, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $L >>);
urlencode(<< $M, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $M >>);
urlencode(<< $N, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $N >>);
urlencode(<< $O, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $O >>);
urlencode(<< $P, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $P >>);
urlencode(<< $Q, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $Q >>);
urlencode(<< $R, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $R >>);
urlencode(<< $S, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $S >>);
urlencode(<< $T, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $T >>);
urlencode(<< $U, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $U >>);
urlencode(<< $V, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $V >>);
urlencode(<< $W, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $W >>);
urlencode(<< $X, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $X >>);
urlencode(<< $Y, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $Y >>);
urlencode(<< $Z, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $Z >>);
urlencode(<< $_, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $_ >>);
urlencode(<< $a, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $a >>);
urlencode(<< $b, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $b >>);
urlencode(<< $c, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $c >>);
urlencode(<< $d, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $d >>);
urlencode(<< $e, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $e >>);
urlencode(<< $f, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $f >>);
urlencode(<< $g, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $g >>);
urlencode(<< $h, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $h >>);
urlencode(<< $i, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $i >>);
urlencode(<< $j, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $j >>);
urlencode(<< $k, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $k >>);
urlencode(<< $l, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $l >>);
urlencode(<< $m, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $m >>);
urlencode(<< $n, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $n >>);
urlencode(<< $o, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $o >>);
urlencode(<< $p, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $p >>);
urlencode(<< $q, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $q >>);
urlencode(<< $r, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $r >>);
urlencode(<< $s, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $s >>);
urlencode(<< $t, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $t >>);
urlencode(<< $u, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $u >>);
urlencode(<< $v, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $v >>);
urlencode(<< $w, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $w >>);
urlencode(<< $x, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $x >>);
urlencode(<< $y, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $y >>);
urlencode(<< $z, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $z >>);
urlencode(<< C, Rest/bits >>, Acc) ->
H = hex(C bsr 4),
L = hex(C band 16#0f),
urlencode(<<>>, Acc) ->
Acc.
hex( 0) -> $0;
hex( 1) -> $1;
hex( 2) -> $2;
hex( 3) -> $3;
hex( 4) -> $4;
hex( 5) -> $5;
hex( 6) -> $6;
hex( 7) -> $7;
hex( 8) -> $8;
hex( 9) -> $9;
hex(10) -> $A;
hex(11) -> $B;
hex(12) -> $C;
hex(13) -> $D;
hex(14) -> $E;
hex(15) -> $F.
-ifdef(TEST).
urlencode_test_() ->
Tests = [
{<<255, 0>>, <<"%FF%00">>},
{<<255, " ">>, <<"%FF+">>},
{<<" ">>, <<"+">>},
{<<"aBc123">>, <<"aBc123">>},
{<<".-_">>, <<".-_">>}
],
[{V, fun() -> E = urlencode(V) end} || {V, E} <- Tests].
urlencode_identity_test_() ->
Tests = [
<<"+">>,
<<"nothingnothingnothingnothing">>,
<<"Small fast modular HTTP server">>,
<<"Small, fast, modular HTTP server.">>,
<<227,131,132,227,130,164,227,131,179,227,130,189,227,
130,166,227,131,171,227,128,156,232,188,170,229,187,187,227,
129,153,227,130,139,230,151,139,229,190,139,227,128,156>>
],
[{V, fun() -> V = urldecode(urlencode(V)) end} || V <- Tests].
horse_urlencode() ->
horse:repeat(100000,
urlencode(<<"nothingnothingnothingnothing">>)
).
horse_urlencode_plus() ->
horse:repeat(100000,
urlencode(<<"Small fast modular HTTP server">>)
).
horse_urlencode_jp() ->
horse:repeat(100000,
urlencode(<<227,131,132,227,130,164,227,131,179,227,130,189,227,
130,166,227,131,171,227,128,156,232,188,170,229,187,187,227,
129,153,227,130,139,230,151,139,229,190,139,227,128,156>>)
).
horse_urlencode_mix() ->
horse:repeat(100000,
urlencode(<<"Small, fast, modular HTTP server.">>)
).
-endif.
|
ae59d53fac80ba1db5fb792aa4748513e9d60e123ec02d5477481250ce3d13c9 | uhc/uhc | Random1.hs | ----------------------------------------------------------------------------------------
what : library System . Random
expected : ok
constraints : exclude - if - js
----------------------------------------------------------------------------------------
what : library System.Random
expected: ok
constraints: exclude-if-js
---------------------------------------------------------------------------------------- -}
module Main where
import System.Random
intRange :: (Int, Int)
intRange = (-100,100)
boolRange :: (Bool, Bool)
boolRange = (False,True)
floatRange :: (Float,Float)
floatRange = (-10,10)
doubleRange :: (Double, Double)
doubleRange = (1,20)
diceRange :: (Int, Int)
diceRange = (1,6)
main :: IO ()
main = do
r' <- rollDice
r <- rollDice
print (inRange diceRange r && inRange diceRange r')
g <- newStdGen
setStdGen g
g' <- getStdGen
print (show g == show g')
print ( show = = show ( read ( show g ) ) )
rd <- randomRIO doubleRange
print (inRange doubleRange rd)
let sg = mkStdGen 1
sg' = read "123" :: StdGen
ri = fst $ randomR intRange sg
rb = fst $ randomR boolRange sg'
rfs = randomRs floatRange g
print (inRange intRange ri)
print (inRange boolRange rb)
print (all (inRange floatRange) (take 10 rfs))
rollDice :: IO Int
rollDice = getStdRandom (randomR diceRange)
inRange :: Ord a => (a,a) -> a -> Bool
inRange (lo,hi) x = lo <= x && x <= hi
| null | https://raw.githubusercontent.com/uhc/uhc/8eb6914df3ba2ba43916a1a4956c6f25aa0e07c5/EHC/test/regress/99/Random1.hs | haskell | --------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------- -} | what : library System . Random
expected : ok
constraints : exclude - if - js
what : library System.Random
expected: ok
constraints: exclude-if-js
module Main where
import System.Random
intRange :: (Int, Int)
intRange = (-100,100)
boolRange :: (Bool, Bool)
boolRange = (False,True)
floatRange :: (Float,Float)
floatRange = (-10,10)
doubleRange :: (Double, Double)
doubleRange = (1,20)
diceRange :: (Int, Int)
diceRange = (1,6)
main :: IO ()
main = do
r' <- rollDice
r <- rollDice
print (inRange diceRange r && inRange diceRange r')
g <- newStdGen
setStdGen g
g' <- getStdGen
print (show g == show g')
print ( show = = show ( read ( show g ) ) )
rd <- randomRIO doubleRange
print (inRange doubleRange rd)
let sg = mkStdGen 1
sg' = read "123" :: StdGen
ri = fst $ randomR intRange sg
rb = fst $ randomR boolRange sg'
rfs = randomRs floatRange g
print (inRange intRange ri)
print (inRange boolRange rb)
print (all (inRange floatRange) (take 10 rfs))
rollDice :: IO Int
rollDice = getStdRandom (randomR diceRange)
inRange :: Ord a => (a,a) -> a -> Bool
inRange (lo,hi) x = lo <= x && x <= hi
|
3ca025024c31721037eb8c6c7da78266995ab2079fc82ea2371fa13418b39f9a | esl/MongooseIM | metrics_c2s_SUITE.erl | %%==============================================================================
Copyright 2013 Erlang Solutions Ltd.
%%
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(metrics_c2s_SUITE).
-compile([export_all, nowarn_export_all]).
-include_lib("escalus/include/escalus.hrl").
-include_lib("common_test/include/ct.hrl").
-define(WAIT_TIME, 100).
-import(metrics_helper, [get_counter_value/1,
wait_for_counter/2]).
%%--------------------------------------------------------------------
%% Suite configuration
%%--------------------------------------------------------------------
all() ->
[{group, single},
{group, multiple},
{group, drop},
{group, errors},
{group, count}].
groups() ->
[{single, [sequence], [message_one,
stanza_one,
presence_one,
presence_direct_one,
iq_one]},
{multiple, [sequence], [messages]},
{drop, [sequence], [bounced
]},
{errors, [sequence], [error_total,
error_mesg,
error_iq,
error_presence]},
{count, [sequence], [stanza_count]}].
suite() ->
[{require, ejabberd_node} | escalus:suite()].
%%--------------------------------------------------------------------
Init & teardown
%%--------------------------------------------------------------------
init_per_suite(Config) ->
HostType = domain_helper:host_type(),
Config1 = dynamic_modules:save_modules(HostType, Config),
dynamic_modules:ensure_stopped(HostType, [mod_offline]),
escalus:init_per_suite(Config1).
end_per_suite(Config) ->
dynamic_modules:restore_modules(Config),
escalus:end_per_suite(Config).
init_per_group(_GroupName, Config) ->
escalus:create_users(Config, escalus:get_users([alice, bob])).
end_per_group(_GroupName, Config) ->
escalus:delete_users(Config, escalus:get_users([alice, bob])).
init_per_testcase(CaseName, Config) ->
escalus:init_per_testcase(CaseName, Config).
end_per_testcase(CaseName, Config) ->
escalus:end_per_testcase(CaseName, Config).
%%--------------------------------------------------------------------
%% Message tests
%%--------------------------------------------------------------------
message_one(Config) ->
{value, MesgSent} = get_counter_value(xmppMessageSent),
{value, MesgReceived} = get_counter_value(xmppMessageReceived),
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
escalus_client:wait_for_stanza(Bob),
wait_for_counter(MesgSent + 1, xmppMessageSent),
wait_for_counter(MesgReceived + 1, xmppMessageReceived)
end).
stanza_one(Config) ->
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
{value, StanzaSent} = get_counter_value(xmppStanzaSent),
{value, StanzaReceived} = get_counter_value(xmppStanzaReceived),
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
escalus_client:wait_for_stanza(Bob),
wait_for_counter(StanzaSent + 1, xmppStanzaSent),
wait_for_counter(StanzaReceived + 1, xmppStanzaReceived)
end).
presence_one(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
{value, PresenceSent} = get_counter_value(xmppPresenceSent),
{value, PresenceReceived} = get_counter_value(xmppPresenceReceived),
{value, StanzaSent} = get_counter_value(xmppStanzaSent),
{value, StanzaReceived} = get_counter_value(xmppStanzaReceived),
escalus:send(Alice, escalus_stanza:presence(<<"available">>)),
escalus:wait_for_stanza(Alice),
wait_for_counter(PresenceSent + 1, xmppPresenceSent),
wait_for_counter(PresenceReceived + 1, xmppPresenceReceived),
wait_for_counter(StanzaSent + 1, xmppStanzaSent),
wait_for_counter(StanzaReceived + 1, xmppStanzaReceived)
end).
presence_direct_one(Config) ->
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
{value, PresenceSent} = get_counter_value(xmppPresenceSent),
{value, PresenceReceived} = get_counter_value(xmppPresenceReceived),
{value, StanzaSent} = get_counter_value(xmppStanzaSent),
{value, StanzaReceived} = get_counter_value(xmppStanzaReceived),
Presence = escalus_stanza:presence_direct(escalus_client:short_jid(Bob), <<"available">>),
escalus:send(Alice, Presence),
escalus:wait_for_stanza(Bob),
wait_for_counter(PresenceSent + 1, xmppPresenceSent),
wait_for_counter(PresenceReceived + 1, xmppPresenceReceived),
wait_for_counter(StanzaSent + 1, xmppStanzaSent),
wait_for_counter(StanzaReceived + 1, xmppStanzaReceived)
end).
iq_one(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
{value, IqSent} = get_counter_value(xmppIqSent),
{value, IqReceived} = get_counter_value(xmppIqReceived),
{value, StanzaSent} = get_counter_value(xmppStanzaSent),
{value, StanzaReceived} = get_counter_value(xmppStanzaReceived),
escalus_client:send(Alice,
escalus_stanza:roster_get()),
escalus_client:wait_for_stanza(Alice),
wait_for_counter(IqSent + 1, xmppIqSent),
wait_for_counter(StanzaSent + 1, xmppStanzaSent),
wait_for_counter(StanzaReceived + 1, xmppStanzaReceived),
wait_for_counter(IqReceived + 1, xmppIqReceived)
end).
messages(Config) ->
{value, MesgSent} = get_counter_value(xmppMessageSent),
{value, MesgReceived} = get_counter_value(xmppMessageReceived),
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
escalus_client:wait_for_stanza(Bob),
escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)),
escalus_client:wait_for_stanza(Alice),
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
escalus_client:wait_for_stanza(Bob),
escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)),
escalus_client:wait_for_stanza(Alice),
wait_for_counter(MesgSent + 4, xmppMessageSent),
wait_for_counter(MesgReceived + 4, xmppMessageReceived)
end).
bounced(Config) ->
{value, MesgBounced} = get_counter_value(xmppMessageBounced),
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
escalus_client:stop(Config, Bob),
timer:sleep(?WAIT_TIME),
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
wait_for_counter(MesgBounced + 1, xmppMessageBounced)
end).
stanza_count(Config) ->
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
{value, OldStanzaCount} = get_counter_value(xmppStanzaCount),
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
escalus_client:wait_for_stanza(Bob),
escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)),
escalus_client:wait_for_stanza(Alice),
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
escalus_client:wait_for_stanza(Bob),
escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)),
escalus_client:wait_for_stanza(Alice),
{value, StanzaCount} = get_counter_value(xmppStanzaCount),
true = StanzaCount >= OldStanzaCount + 4
end).
%%-----------------------------------------------------
%% Error tests
%%-----------------------------------------------------
error_total(Config) ->
{value, Errors} = get_counter_value(xmppErrorTotal),
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
escalus_client:stop(Config, Bob),
timer:sleep(?WAIT_TIME),
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
wait_for_counter(Errors + 1, xmppErrorTotal)
end).
error_mesg(Config) ->
{value, Errors} = get_counter_value(xmppErrorMessage),
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
escalus_client:stop(Config, Bob),
timer:sleep(?WAIT_TIME),
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
wait_for_counter(Errors + 1, xmppErrorMessage)
end).
error_presence(Config) ->
{value, Errors} = get_counter_value(xmppErrorPresence),
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
escalus:send(Alice, escalus_stanza:presence_direct(
escalus_client:short_jid(Bob), <<"available">>)),
escalus:wait_for_stanza(Bob),
ErrorElt = escalus_stanza:error_element(<<"cancel">>, <<"gone">>),
Presence = escalus_stanza:presence_direct(escalus_client:short_jid(Alice),
<<"error">>, [ErrorElt]),
escalus:send(Bob, Presence),
wait_for_counter(Errors + 1, xmppErrorPresence)
end).
error_iq(Config) ->
{value, Errors} = get_counter_value(xmppErrorIq),
Users = escalus_config:get_config(escalus_users, Config),
Alice = escalus_users:get_user_by_name(alice, Users),
escalus_users:create_user(Config, Alice),
wait_for_counter(Errors + 1, xmppErrorIq).
| null | https://raw.githubusercontent.com/esl/MongooseIM/997ce8cc01dacf8bf1f1f4e3a984ee10f0ce5dd6/big_tests/tests/metrics_c2s_SUITE.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.
==============================================================================
--------------------------------------------------------------------
Suite configuration
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Message tests
--------------------------------------------------------------------
-----------------------------------------------------
Error tests
----------------------------------------------------- | Copyright 2013 Erlang Solutions Ltd.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(metrics_c2s_SUITE).
-compile([export_all, nowarn_export_all]).
-include_lib("escalus/include/escalus.hrl").
-include_lib("common_test/include/ct.hrl").
-define(WAIT_TIME, 100).
-import(metrics_helper, [get_counter_value/1,
wait_for_counter/2]).
all() ->
[{group, single},
{group, multiple},
{group, drop},
{group, errors},
{group, count}].
groups() ->
[{single, [sequence], [message_one,
stanza_one,
presence_one,
presence_direct_one,
iq_one]},
{multiple, [sequence], [messages]},
{drop, [sequence], [bounced
]},
{errors, [sequence], [error_total,
error_mesg,
error_iq,
error_presence]},
{count, [sequence], [stanza_count]}].
suite() ->
[{require, ejabberd_node} | escalus:suite()].
Init & teardown
init_per_suite(Config) ->
HostType = domain_helper:host_type(),
Config1 = dynamic_modules:save_modules(HostType, Config),
dynamic_modules:ensure_stopped(HostType, [mod_offline]),
escalus:init_per_suite(Config1).
end_per_suite(Config) ->
dynamic_modules:restore_modules(Config),
escalus:end_per_suite(Config).
init_per_group(_GroupName, Config) ->
escalus:create_users(Config, escalus:get_users([alice, bob])).
end_per_group(_GroupName, Config) ->
escalus:delete_users(Config, escalus:get_users([alice, bob])).
init_per_testcase(CaseName, Config) ->
escalus:init_per_testcase(CaseName, Config).
end_per_testcase(CaseName, Config) ->
escalus:end_per_testcase(CaseName, Config).
message_one(Config) ->
{value, MesgSent} = get_counter_value(xmppMessageSent),
{value, MesgReceived} = get_counter_value(xmppMessageReceived),
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
escalus_client:wait_for_stanza(Bob),
wait_for_counter(MesgSent + 1, xmppMessageSent),
wait_for_counter(MesgReceived + 1, xmppMessageReceived)
end).
stanza_one(Config) ->
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
{value, StanzaSent} = get_counter_value(xmppStanzaSent),
{value, StanzaReceived} = get_counter_value(xmppStanzaReceived),
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
escalus_client:wait_for_stanza(Bob),
wait_for_counter(StanzaSent + 1, xmppStanzaSent),
wait_for_counter(StanzaReceived + 1, xmppStanzaReceived)
end).
presence_one(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
{value, PresenceSent} = get_counter_value(xmppPresenceSent),
{value, PresenceReceived} = get_counter_value(xmppPresenceReceived),
{value, StanzaSent} = get_counter_value(xmppStanzaSent),
{value, StanzaReceived} = get_counter_value(xmppStanzaReceived),
escalus:send(Alice, escalus_stanza:presence(<<"available">>)),
escalus:wait_for_stanza(Alice),
wait_for_counter(PresenceSent + 1, xmppPresenceSent),
wait_for_counter(PresenceReceived + 1, xmppPresenceReceived),
wait_for_counter(StanzaSent + 1, xmppStanzaSent),
wait_for_counter(StanzaReceived + 1, xmppStanzaReceived)
end).
presence_direct_one(Config) ->
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
{value, PresenceSent} = get_counter_value(xmppPresenceSent),
{value, PresenceReceived} = get_counter_value(xmppPresenceReceived),
{value, StanzaSent} = get_counter_value(xmppStanzaSent),
{value, StanzaReceived} = get_counter_value(xmppStanzaReceived),
Presence = escalus_stanza:presence_direct(escalus_client:short_jid(Bob), <<"available">>),
escalus:send(Alice, Presence),
escalus:wait_for_stanza(Bob),
wait_for_counter(PresenceSent + 1, xmppPresenceSent),
wait_for_counter(PresenceReceived + 1, xmppPresenceReceived),
wait_for_counter(StanzaSent + 1, xmppStanzaSent),
wait_for_counter(StanzaReceived + 1, xmppStanzaReceived)
end).
iq_one(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
{value, IqSent} = get_counter_value(xmppIqSent),
{value, IqReceived} = get_counter_value(xmppIqReceived),
{value, StanzaSent} = get_counter_value(xmppStanzaSent),
{value, StanzaReceived} = get_counter_value(xmppStanzaReceived),
escalus_client:send(Alice,
escalus_stanza:roster_get()),
escalus_client:wait_for_stanza(Alice),
wait_for_counter(IqSent + 1, xmppIqSent),
wait_for_counter(StanzaSent + 1, xmppStanzaSent),
wait_for_counter(StanzaReceived + 1, xmppStanzaReceived),
wait_for_counter(IqReceived + 1, xmppIqReceived)
end).
messages(Config) ->
{value, MesgSent} = get_counter_value(xmppMessageSent),
{value, MesgReceived} = get_counter_value(xmppMessageReceived),
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
escalus_client:wait_for_stanza(Bob),
escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)),
escalus_client:wait_for_stanza(Alice),
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
escalus_client:wait_for_stanza(Bob),
escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)),
escalus_client:wait_for_stanza(Alice),
wait_for_counter(MesgSent + 4, xmppMessageSent),
wait_for_counter(MesgReceived + 4, xmppMessageReceived)
end).
bounced(Config) ->
{value, MesgBounced} = get_counter_value(xmppMessageBounced),
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
escalus_client:stop(Config, Bob),
timer:sleep(?WAIT_TIME),
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
wait_for_counter(MesgBounced + 1, xmppMessageBounced)
end).
stanza_count(Config) ->
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
{value, OldStanzaCount} = get_counter_value(xmppStanzaCount),
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
escalus_client:wait_for_stanza(Bob),
escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)),
escalus_client:wait_for_stanza(Alice),
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
escalus_client:wait_for_stanza(Bob),
escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)),
escalus_client:wait_for_stanza(Alice),
{value, StanzaCount} = get_counter_value(xmppStanzaCount),
true = StanzaCount >= OldStanzaCount + 4
end).
error_total(Config) ->
{value, Errors} = get_counter_value(xmppErrorTotal),
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
escalus_client:stop(Config, Bob),
timer:sleep(?WAIT_TIME),
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
wait_for_counter(Errors + 1, xmppErrorTotal)
end).
error_mesg(Config) ->
{value, Errors} = get_counter_value(xmppErrorMessage),
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
escalus_client:stop(Config, Bob),
timer:sleep(?WAIT_TIME),
escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)),
wait_for_counter(Errors + 1, xmppErrorMessage)
end).
error_presence(Config) ->
{value, Errors} = get_counter_value(xmppErrorPresence),
escalus:story(Config, [{alice, 1}, {bob, 1}], fun(Alice, Bob) ->
escalus:send(Alice, escalus_stanza:presence_direct(
escalus_client:short_jid(Bob), <<"available">>)),
escalus:wait_for_stanza(Bob),
ErrorElt = escalus_stanza:error_element(<<"cancel">>, <<"gone">>),
Presence = escalus_stanza:presence_direct(escalus_client:short_jid(Alice),
<<"error">>, [ErrorElt]),
escalus:send(Bob, Presence),
wait_for_counter(Errors + 1, xmppErrorPresence)
end).
error_iq(Config) ->
{value, Errors} = get_counter_value(xmppErrorIq),
Users = escalus_config:get_config(escalus_users, Config),
Alice = escalus_users:get_user_by_name(alice, Users),
escalus_users:create_user(Config, Alice),
wait_for_counter(Errors + 1, xmppErrorIq).
|
851684f326906815bbd6e9108e1e733dd43e10579ae62f268ca4cf47ddf2720a | arsenm/Clutterhs | PathTest.hs | This tests Path and BehaviourPath
import Prelude
import qualified Prelude as P
import Graphics.UI.Clutter
import System.Glib.Signals
import Control.Monad (when)
import System.IO
testForeachFunc :: PathCallback
testForeachFunc pn = putStr "PathCallback: " >> print pn
-- example from docs
For example , to move an actor in a 100 by 100 pixel square
centered on the point 300,300 you could use the following path :
testPathStr = "M 250,350 l 0 -100 L 350,250 l 0 100 z"
testPathDescript :: IO Path
testPathDescript = do
path <- pathNew
ret <- pathAddString path testPathStr
putStrLn $ "pathAddString: " ++ if ret then "Success" else "Failure"
return path
testPathNewDescript :: IO Path
testPathNewDescript = pathNewWithDescription testPathStr
testPathAddMoves :: IO Path
testPathAddMoves = do
path <- pathNew
pathAddMoveTo path 15 15
pathAddRelMoveTo path 30 0
pathAddRelLineTo path 10 100
pathAddRelCurveTo path 10 10 40 40 90 90
pathAddRelCurveTo path 50 30 40 40 140 90
pathAddMoveTo path 300 350
pathAddRelCurveTo path 10 20 50 40 40 90
pathAddClose path
return path
main :: IO ()
main = do
clutterInit
stage <- stageGetDefault
Path1 tests adding moves
path1 <- testPathAddMoves
n1 <- pathGetNNodes path1
len1 <- pathGetLength path1
CHECKME : This list is supposed to be freed but I do n't remember if I made that happen
nodes1 <- pathGetNodes path1
putStrLn $ "Path1: Number of nodes: " ++ P.show n1
putStrLn $ "Path1: length: " ++ P.show len1
pos1 <- pathGetPosition path1 0.5
putStrLn $ "Path1: pathGetPosition: pos = " ++ P.show pos1
putStrLn "Path1 Nodes: "
mapM_ print nodes1
descr <- pathGetDescription path1 -- see if the string description is correct
putStrLn ("Path1 Description: " ++ descr)
--Path2 tests using string descriptions
path2 <- testPathDescript
n2 <- pathGetNNodes path2
len2 <- pathGetLength path2
putStrLn $ "Path2: Number of nodes: " ++ Prelude.show n2
putStrLn $ "Path2: length: " ++ Prelude.show len2
should be the same as , i.e. they should track
path3 <- testPathNewDescript
n3 <- pathGetNNodes path3
len3 <- pathGetLength path3
putStrLn $ "Path3: Number of nodes: " ++ Prelude.show n3
putStrLn $ "Path3: length: " ++ Prelude.show len3
when ( n2 /= n3 || len3 /= len2 ) (hPutStrLn stderr "Path2 /= Path3!")
pathForeach path1 testForeachFunc
tml <- timelineNew 3000
alph <- alphaNewFull tml EaseInSine
behav1 <- behaviourPathNew alph path1
behav2 <- behaviourPathNew alph path2
behav3 <- behaviourPathNew alph path3
behav4 <- behaviourPathNewWithDescription alph testPathStr
< - behaviourPathNewWithKnots alph [ ( 250,350 ) , ( 0,(-100 ) ) , ( 350,250 ) , ( 0,10 ) ]
behav5 <- behaviourPathNewWithKnots alph [ (100,100), (250, 250), (300, 300), (200, 200) ]
rect[1 .. 4 ] should all move together
rect1 <- rectangleNewWithColor (Color 0 0 255 200)
rect2 <- rectangleNewWithColor (Color 0 255 0 150)
rect3 <- rectangleNewWithColor (Color 255 0 0 150)
rect4 <- rectangleNewWithColor (Color 0 123 123 150)
rect5 <- rectangleNewWithColor (Color 123 200 123 150)
mapM_ (containerAddActor stage) [rect1, rect2, rect3, rect4, rect5]
actorSetSize rect1 50 50
actorSetSize rect2 20 60
actorSetSize rect3 60 20
actorSetSize rect4 40 40
actorSetSize rect5 50 50
actorSetPosition rect2 200 100
actorSetPosition rect3 150 100
actorSetPosition rect5 300 200
behaviourApply behav1 rect1
behaviourApply behav2 rect2
behaviourApply behav3 rect3
behaviourApply behav4 rect4
behaviourApply behav5 rect5
behav5 `on` knotReached $ \n -> putStrLn ("Path5: Knot " ++ P.show n ++ " reached")
actorShowAll stage
timelineStart tml
on tml completed mainQuit
clutterMain
| null | https://raw.githubusercontent.com/arsenm/Clutterhs/ad3390895264c46906b5d3d954c4b04b04d96b1d/clutter/demo/PathTest.hs | haskell | example from docs
see if the string description is correct
Path2 tests using string descriptions | This tests Path and BehaviourPath
import Prelude
import qualified Prelude as P
import Graphics.UI.Clutter
import System.Glib.Signals
import Control.Monad (when)
import System.IO
testForeachFunc :: PathCallback
testForeachFunc pn = putStr "PathCallback: " >> print pn
For example , to move an actor in a 100 by 100 pixel square
centered on the point 300,300 you could use the following path :
testPathStr = "M 250,350 l 0 -100 L 350,250 l 0 100 z"
testPathDescript :: IO Path
testPathDescript = do
path <- pathNew
ret <- pathAddString path testPathStr
putStrLn $ "pathAddString: " ++ if ret then "Success" else "Failure"
return path
testPathNewDescript :: IO Path
testPathNewDescript = pathNewWithDescription testPathStr
testPathAddMoves :: IO Path
testPathAddMoves = do
path <- pathNew
pathAddMoveTo path 15 15
pathAddRelMoveTo path 30 0
pathAddRelLineTo path 10 100
pathAddRelCurveTo path 10 10 40 40 90 90
pathAddRelCurveTo path 50 30 40 40 140 90
pathAddMoveTo path 300 350
pathAddRelCurveTo path 10 20 50 40 40 90
pathAddClose path
return path
main :: IO ()
main = do
clutterInit
stage <- stageGetDefault
Path1 tests adding moves
path1 <- testPathAddMoves
n1 <- pathGetNNodes path1
len1 <- pathGetLength path1
CHECKME : This list is supposed to be freed but I do n't remember if I made that happen
nodes1 <- pathGetNodes path1
putStrLn $ "Path1: Number of nodes: " ++ P.show n1
putStrLn $ "Path1: length: " ++ P.show len1
pos1 <- pathGetPosition path1 0.5
putStrLn $ "Path1: pathGetPosition: pos = " ++ P.show pos1
putStrLn "Path1 Nodes: "
mapM_ print nodes1
putStrLn ("Path1 Description: " ++ descr)
path2 <- testPathDescript
n2 <- pathGetNNodes path2
len2 <- pathGetLength path2
putStrLn $ "Path2: Number of nodes: " ++ Prelude.show n2
putStrLn $ "Path2: length: " ++ Prelude.show len2
should be the same as , i.e. they should track
path3 <- testPathNewDescript
n3 <- pathGetNNodes path3
len3 <- pathGetLength path3
putStrLn $ "Path3: Number of nodes: " ++ Prelude.show n3
putStrLn $ "Path3: length: " ++ Prelude.show len3
when ( n2 /= n3 || len3 /= len2 ) (hPutStrLn stderr "Path2 /= Path3!")
pathForeach path1 testForeachFunc
tml <- timelineNew 3000
alph <- alphaNewFull tml EaseInSine
behav1 <- behaviourPathNew alph path1
behav2 <- behaviourPathNew alph path2
behav3 <- behaviourPathNew alph path3
behav4 <- behaviourPathNewWithDescription alph testPathStr
< - behaviourPathNewWithKnots alph [ ( 250,350 ) , ( 0,(-100 ) ) , ( 350,250 ) , ( 0,10 ) ]
behav5 <- behaviourPathNewWithKnots alph [ (100,100), (250, 250), (300, 300), (200, 200) ]
rect[1 .. 4 ] should all move together
rect1 <- rectangleNewWithColor (Color 0 0 255 200)
rect2 <- rectangleNewWithColor (Color 0 255 0 150)
rect3 <- rectangleNewWithColor (Color 255 0 0 150)
rect4 <- rectangleNewWithColor (Color 0 123 123 150)
rect5 <- rectangleNewWithColor (Color 123 200 123 150)
mapM_ (containerAddActor stage) [rect1, rect2, rect3, rect4, rect5]
actorSetSize rect1 50 50
actorSetSize rect2 20 60
actorSetSize rect3 60 20
actorSetSize rect4 40 40
actorSetSize rect5 50 50
actorSetPosition rect2 200 100
actorSetPosition rect3 150 100
actorSetPosition rect5 300 200
behaviourApply behav1 rect1
behaviourApply behav2 rect2
behaviourApply behav3 rect3
behaviourApply behav4 rect4
behaviourApply behav5 rect5
behav5 `on` knotReached $ \n -> putStrLn ("Path5: Knot " ++ P.show n ++ " reached")
actorShowAll stage
timelineStart tml
on tml completed mainQuit
clutterMain
|
c0736360d98a8ac609fbf0d27777c53020564c37cf01310f33eda0405510d1ba | Ferdinand-vW/sessiontypes-distributed | Normalize.hs | # LANGUAGE DataKinds #
# OPTIONS_GHC -Wno - simplifiable - class - constraints #
| This module provides three functions for normalizing session typed programs .
--
-- With normalizing we mean that we apply rewrites to a session typed program until we can no longer do so
-- and that do not change the semantics of the program.
--
The motivation for this module is that for two session typed programs to run as a session they must be dual .
-- Sometimes, one of these programs might not have a session type that is dual to the session type of the other program,
--
-- but we can rewrite the program and therefore also its session type. It is of course important that we do not
-- alter the semantics of the program when rewriting it. For that reason, any rewrite that we may apply must be isomorphic.
--
A rewrite is isomorphic if we have two programs \p\ and \p'\ , we can do a rewrite from \p\ to \p'\ and from \p'\ to \p\.
--
For now two types of rewrites are applied : Elimination of recursive types and flattening of branches .
--
-- An additional benefit of normalizing is that it may lead to further optimizations.
--
In " Control . Distributed . Session . Eval " we send an integer for every ` Sel ` session type that we encounter . By flattening branching
we reduce the number of ` Sel ` constructors and therefore also the number of times one needs to communicate an integer .
module Control.Distributed.Session.Normalize (
normalize,
elimRec,
flatten
) where
import Control.SessionTypes
import Control.SessionTypes.Codensity (rep)
import qualified Control.SessionTypes.Normalize as S
import Control.Distributed.Session.Session
| Applies two types of rewrites to a ` Session ` .
--
-- * Elimination of unused recursion
-- * Rewrites non-right nested branchings to right nested branchings
normalize :: S.Normalize s s' => Session s ('Cap '[] Eps) a -> Session s' ('Cap '[] Eps) a
normalize sess = Session $ \si -> rep $ S.normalize (runSession sess si)
-- | Function for eliminating unused recursive types.
--
The function ` elimRec ` takes a ` Session ` and traverses the underlying ` STTerm ` . While doing so , it will attempt to remove ` STTerm ` constructors annotated with ` R ` or ` Wk ` from the program
-- if in doing so does not change the behavior of the program.
--
-- For example, in the following session type we may remove the inner `R` and the `Wk`.
--
-- > R (R (Wk V))
--
-- We have that the outer `R` matches the recursion variable because of the use of `Wk`.
--
-- That means the inner `R` does not match any recursion variable (the `R` is unused) and therefore may it and its corresponding constructor be removed from the session.
--
-- We also remove the `Wk`, because the session type pushed into the context by the inner `R` has also been removed.
--
-- The generated session type is
--
-- > R V
elimRec :: S.ElimRec s s' => Session s ('Cap '[] Eps) a -> Session s' ('Cap '[] Eps) a
elimRec sess = Session $ \si -> rep $ S.elimRec (runSession sess si)
-- | Flattening of branching
--
The function ` flatten ` takes a ` Session ` and traverses the underlying ` STTerm ` .
-- If it finds a branching session type that has a branch
-- starting with another branching of the same type, then it will extract the branches of the inner branching
-- and inserts these into the outer branching. This is similar to flattening a list of lists to a larger list.
--
-- For example:
--
> Sel ' [ a , b , Sel ' [ c , d ] , e ]
--
-- becomes
--
-- > Sel '[a,b,c,d,e]
--
This only works if the inner branching has the same type as the outer branch ( Sel in Sel or Off in Off ) .
--
-- Also, for now this rewrite only works if one of the branching of the outer branch starts with a new branching.
--
-- For example:
--
-- > Sel '[a,b, Int :!> Sel '[c,d],e]
--
-- does not become
--
-- > Sel '[a,b,Int :!> c, Int :!> d, e]
--
-- Although, this is something that will be added in the future.
flatten :: S.Flatten s s' => Session s ('Cap '[] Eps) a -> Session s' ('Cap '[] Eps) a
flatten sess = Session $ \si -> rep $ S.flatten (runSession sess si)
| null | https://raw.githubusercontent.com/Ferdinand-vW/sessiontypes-distributed/5b0889008f69b130355ee2887793774b49793844/src/Control/Distributed/Session/Normalize.hs | haskell |
With normalizing we mean that we apply rewrites to a session typed program until we can no longer do so
and that do not change the semantics of the program.
Sometimes, one of these programs might not have a session type that is dual to the session type of the other program,
but we can rewrite the program and therefore also its session type. It is of course important that we do not
alter the semantics of the program when rewriting it. For that reason, any rewrite that we may apply must be isomorphic.
An additional benefit of normalizing is that it may lead to further optimizations.
* Elimination of unused recursion
* Rewrites non-right nested branchings to right nested branchings
| Function for eliminating unused recursive types.
if in doing so does not change the behavior of the program.
For example, in the following session type we may remove the inner `R` and the `Wk`.
> R (R (Wk V))
We have that the outer `R` matches the recursion variable because of the use of `Wk`.
That means the inner `R` does not match any recursion variable (the `R` is unused) and therefore may it and its corresponding constructor be removed from the session.
We also remove the `Wk`, because the session type pushed into the context by the inner `R` has also been removed.
The generated session type is
> R V
| Flattening of branching
If it finds a branching session type that has a branch
starting with another branching of the same type, then it will extract the branches of the inner branching
and inserts these into the outer branching. This is similar to flattening a list of lists to a larger list.
For example:
becomes
> Sel '[a,b,c,d,e]
Also, for now this rewrite only works if one of the branching of the outer branch starts with a new branching.
For example:
> Sel '[a,b, Int :!> Sel '[c,d],e]
does not become
> Sel '[a,b,Int :!> c, Int :!> d, e]
Although, this is something that will be added in the future. | # LANGUAGE DataKinds #
# OPTIONS_GHC -Wno - simplifiable - class - constraints #
| This module provides three functions for normalizing session typed programs .
The motivation for this module is that for two session typed programs to run as a session they must be dual .
A rewrite is isomorphic if we have two programs \p\ and \p'\ , we can do a rewrite from \p\ to \p'\ and from \p'\ to \p\.
For now two types of rewrites are applied : Elimination of recursive types and flattening of branches .
In " Control . Distributed . Session . Eval " we send an integer for every ` Sel ` session type that we encounter . By flattening branching
we reduce the number of ` Sel ` constructors and therefore also the number of times one needs to communicate an integer .
module Control.Distributed.Session.Normalize (
normalize,
elimRec,
flatten
) where
import Control.SessionTypes
import Control.SessionTypes.Codensity (rep)
import qualified Control.SessionTypes.Normalize as S
import Control.Distributed.Session.Session
| Applies two types of rewrites to a ` Session ` .
normalize :: S.Normalize s s' => Session s ('Cap '[] Eps) a -> Session s' ('Cap '[] Eps) a
normalize sess = Session $ \si -> rep $ S.normalize (runSession sess si)
The function ` elimRec ` takes a ` Session ` and traverses the underlying ` STTerm ` . While doing so , it will attempt to remove ` STTerm ` constructors annotated with ` R ` or ` Wk ` from the program
elimRec :: S.ElimRec s s' => Session s ('Cap '[] Eps) a -> Session s' ('Cap '[] Eps) a
elimRec sess = Session $ \si -> rep $ S.elimRec (runSession sess si)
The function ` flatten ` takes a ` Session ` and traverses the underlying ` STTerm ` .
> Sel ' [ a , b , Sel ' [ c , d ] , e ]
This only works if the inner branching has the same type as the outer branch ( Sel in Sel or Off in Off ) .
flatten :: S.Flatten s s' => Session s ('Cap '[] Eps) a -> Session s' ('Cap '[] Eps) a
flatten sess = Session $ \si -> rep $ S.flatten (runSession sess si)
|
bd3c67c6dd896876e00da21c8442bbdb5a8d3938eac1019868a63d84d74bacae | IvanIvanov/fp2013 | digits-sum.scm | (define (digits-sum n)
(cond
( (= n 0) 0)
(else (+ (remainder n 10) (digits-sum (quotient n 10)))))) | null | https://raw.githubusercontent.com/IvanIvanov/fp2013/2ac1bb1102cb65e0ecbfa8d2fb3ca69953ae4ecf/lab2-and-3/homework1/digits-sum.scm | scheme | (define (digits-sum n)
(cond
( (= n 0) 0)
(else (+ (remainder n 10) (digits-sum (quotient n 10)))))) |
|
931eab42cb991fb7f2df22428d0fa4a045c79b477162aa78e8ab148d40c9a146 | tsoding/aoc-2019 | Intcode.hs | {-# LANGUAGE OverloadedStrings #-}
module Intcode where
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Array
import Text.Printf
import Data.List
type Address = Int
type Memory = Array Address Int
data Machine = Machine
{ getMemory :: !Memory
, getIp :: !Int
, isHalt :: !Bool
} deriving (Show)
memoryFromFile :: FilePath -> IO Memory
memoryFromFile filePath = do
xs <-
map (read . T.unpack . T.strip) . T.splitOn "," <$> T.readFile filePath
let n = length xs
return $ array (0, n - 1) (zip [0 ..] xs)
machineFromFile :: FilePath -> IO Machine
machineFromFile filePath = do
memory <- memoryFromFile filePath
return $ Machine memory 0 False
step :: Machine -> Machine
step machine@(Machine _ _ True) = machine
step machine@(Machine memory ip _) =
let opcode = memory ! getIp machine
in case opcode of
1 ->
let a1 = memory ! (memory ! (ip + 1))
a2 = memory ! (memory ! (ip + 2))
dst = memory ! (ip + 3)
in machine {getMemory = memory // [(dst, a1 + a2)], getIp = ip + 4}
2 ->
let a1 = memory ! (memory ! (ip + 1))
a2 = memory ! (memory ! (ip + 2))
dst = memory ! (ip + 3)
in machine {getMemory = memory // [(dst, a1 * a2)], getIp = ip + 4}
99 -> machine {isHalt = True}
_ -> error $ printf "Unknown opcode `%d` at position `%d`" opcode ip
execute :: Machine -> Machine
execute = head . dropWhile (not . isHalt) . iterate' step
| null | https://raw.githubusercontent.com/tsoding/aoc-2019/bd186aa96558676a4380a465351b877dbaae261d/02/Intcode.hs | haskell | # LANGUAGE OverloadedStrings # | module Intcode where
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Array
import Text.Printf
import Data.List
type Address = Int
type Memory = Array Address Int
data Machine = Machine
{ getMemory :: !Memory
, getIp :: !Int
, isHalt :: !Bool
} deriving (Show)
memoryFromFile :: FilePath -> IO Memory
memoryFromFile filePath = do
xs <-
map (read . T.unpack . T.strip) . T.splitOn "," <$> T.readFile filePath
let n = length xs
return $ array (0, n - 1) (zip [0 ..] xs)
machineFromFile :: FilePath -> IO Machine
machineFromFile filePath = do
memory <- memoryFromFile filePath
return $ Machine memory 0 False
step :: Machine -> Machine
step machine@(Machine _ _ True) = machine
step machine@(Machine memory ip _) =
let opcode = memory ! getIp machine
in case opcode of
1 ->
let a1 = memory ! (memory ! (ip + 1))
a2 = memory ! (memory ! (ip + 2))
dst = memory ! (ip + 3)
in machine {getMemory = memory // [(dst, a1 + a2)], getIp = ip + 4}
2 ->
let a1 = memory ! (memory ! (ip + 1))
a2 = memory ! (memory ! (ip + 2))
dst = memory ! (ip + 3)
in machine {getMemory = memory // [(dst, a1 * a2)], getIp = ip + 4}
99 -> machine {isHalt = True}
_ -> error $ printf "Unknown opcode `%d` at position `%d`" opcode ip
execute :: Machine -> Machine
execute = head . dropWhile (not . isHalt) . iterate' step
|
4ab199de27bd9c39d3766a3b24b8fd11c759143a0a77ce4eaabff88753df7423 | elsamuko/gimp-elsamuko | elsamuko-color-tint.scm | ; The GIMP -- an image manipulation program
Copyright ( C ) 1995 and
;
; This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 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 General Public License for more details.
;
You should have received a copy of the GNU General Public License
; along with this program; if not, write to the Free Software
Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
; -3.0.html
;
Copyright ( C ) 2008 elsamuko < >
;
(define (elsamuko-color-tint aimg adraw color opacity saturation blackwhite)
(let* ((img (car (gimp-item-get-image adraw)))
(owidth (car (gimp-image-width img)))
(oheight (car (gimp-image-height img)))
(tint-layer 0)
(tint-layer-mask 0)
(imgTMP 0)
first layer of imgTMP
(tmp-layer 0) ;tint layer of imgTMP
(tmp-layer-mask 0)
(imgHSV 0)
(layersHSV 0)
(layerS 0)
(red (/ (car color) 255))
(blue (/ (cadr color) 255))
(green (/ (caddr color) 255))
)
; init
(gimp-context-push)
(gimp-image-undo-group-start img)
(if (= (car (gimp-drawable-is-gray adraw )) TRUE)
(gimp-image-convert-rgb img)
)
;filter ops on new image
(gimp-edit-copy-visible img)
(set! imgTMP (car (gimp-edit-paste-as-new)))
;rise saturation
(set! copy-layer (car (gimp-image-get-active-layer imgTMP)))
(gimp-hue-saturation copy-layer ALL-HUES 0 0 saturation)
;add tint layer and filter color
(set! tmp-layer (car (gimp-layer-copy copy-layer FALSE)))
(gimp-item-set-name tmp-layer "Temp")
(gimp-image-insert-layer imgTMP tmp-layer 0 -1)
(plug-in-colors-channel-mixer 1 img tmp-layer TRUE
red blue green ;R
0 0 0 ;G
0 0 0 ;B
)
;add filter mask
(set! tmp-layer-mask (car (gimp-layer-create-mask tmp-layer ADD-COPY-MASK)))
(gimp-layer-add-mask tmp-layer tmp-layer-mask)
;colorize tint layer
(gimp-context-set-foreground color)
(gimp-selection-all imgTMP)
(gimp-edit-bucket-fill tmp-layer FG-BUCKET-FILL NORMAL-MODE 100 0 FALSE 0 0)
;get visible and add to original
(gimp-item-set-visible copy-layer FALSE)
(gimp-edit-copy-visible imgTMP)
(set! tint-layer (car (gimp-layer-new-from-visible imgTMP img "Tint") ))
(gimp-image-insert-layer img tint-layer 0 0)
;set modes
(gimp-layer-set-mode tint-layer SCREEN-MODE)
(gimp-layer-set-opacity tint-layer opacity)
;get saturation layer
(set! imgHSV (car (plug-in-decompose 1 imgTMP copy-layer "HSV" TRUE)))
(set! layersHSV (gimp-image-get-layers imgHSV))
(set! layerS (aref (cadr layersHSV) 1))
(gimp-edit-copy layerS)
;add saturation mask
(set! tint-layer-mask (car (gimp-layer-create-mask tint-layer ADD-WHITE-MASK )))
(gimp-layer-add-mask tint-layer tint-layer-mask)
(gimp-floating-sel-anchor (car (gimp-edit-paste tint-layer-mask TRUE)))
;desaturate original
(if (= blackwhite TRUE)
( begin
(gimp-desaturate-full adraw DESATURATE-LUMINOSITY)
)
)
; tidy up
(gimp-image-delete imgTMP)
(gimp-image-delete imgHSV)
(gimp-image-undo-group-end img)
(gimp-displays-flush)
(gimp-context-pop)
)
)
(script-fu-register "elsamuko-color-tint"
_"_Color Tint"
"Add color tint layer.
Latest version can be downloaded from /"
"elsamuko <>"
"elsamuko"
"16/04/10"
"*"
SF-IMAGE "Input image" 0
SF-DRAWABLE "Input drawable" 0
SF-COLOR "Color" '(0 0 255)
SF-ADJUSTMENT _"Opacity" '(100 0 100 5 10 0 0)
SF-ADJUSTMENT _"Saturation" '(100 0 100 5 10 0 0)
SF-TOGGLE _"Desaturate Image" FALSE
)
(script-fu-menu-register "elsamuko-color-tint" _"<Image>/Colors")
| null | https://raw.githubusercontent.com/elsamuko/gimp-elsamuko/d64e60321553ee4a621841eda5a3353f68a94fc1/scripts/elsamuko-color-tint.scm | scheme | The GIMP -- an image manipulation program
This program is free software; you can redistribute it and/or modify
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 General Public License for more details.
along with this program; if not, write to the Free Software
-3.0.html
tint layer of imgTMP
init
filter ops on new image
rise saturation
add tint layer and filter color
R
G
B
add filter mask
colorize tint layer
get visible and add to original
set modes
get saturation layer
add saturation mask
desaturate original
tidy up | Copyright ( C ) 1995 and
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
Copyright ( C ) 2008 elsamuko < >
(define (elsamuko-color-tint aimg adraw color opacity saturation blackwhite)
(let* ((img (car (gimp-item-get-image adraw)))
(owidth (car (gimp-image-width img)))
(oheight (car (gimp-image-height img)))
(tint-layer 0)
(tint-layer-mask 0)
(imgTMP 0)
first layer of imgTMP
(tmp-layer-mask 0)
(imgHSV 0)
(layersHSV 0)
(layerS 0)
(red (/ (car color) 255))
(blue (/ (cadr color) 255))
(green (/ (caddr color) 255))
)
(gimp-context-push)
(gimp-image-undo-group-start img)
(if (= (car (gimp-drawable-is-gray adraw )) TRUE)
(gimp-image-convert-rgb img)
)
(gimp-edit-copy-visible img)
(set! imgTMP (car (gimp-edit-paste-as-new)))
(set! copy-layer (car (gimp-image-get-active-layer imgTMP)))
(gimp-hue-saturation copy-layer ALL-HUES 0 0 saturation)
(set! tmp-layer (car (gimp-layer-copy copy-layer FALSE)))
(gimp-item-set-name tmp-layer "Temp")
(gimp-image-insert-layer imgTMP tmp-layer 0 -1)
(plug-in-colors-channel-mixer 1 img tmp-layer TRUE
)
(set! tmp-layer-mask (car (gimp-layer-create-mask tmp-layer ADD-COPY-MASK)))
(gimp-layer-add-mask tmp-layer tmp-layer-mask)
(gimp-context-set-foreground color)
(gimp-selection-all imgTMP)
(gimp-edit-bucket-fill tmp-layer FG-BUCKET-FILL NORMAL-MODE 100 0 FALSE 0 0)
(gimp-item-set-visible copy-layer FALSE)
(gimp-edit-copy-visible imgTMP)
(set! tint-layer (car (gimp-layer-new-from-visible imgTMP img "Tint") ))
(gimp-image-insert-layer img tint-layer 0 0)
(gimp-layer-set-mode tint-layer SCREEN-MODE)
(gimp-layer-set-opacity tint-layer opacity)
(set! imgHSV (car (plug-in-decompose 1 imgTMP copy-layer "HSV" TRUE)))
(set! layersHSV (gimp-image-get-layers imgHSV))
(set! layerS (aref (cadr layersHSV) 1))
(gimp-edit-copy layerS)
(set! tint-layer-mask (car (gimp-layer-create-mask tint-layer ADD-WHITE-MASK )))
(gimp-layer-add-mask tint-layer tint-layer-mask)
(gimp-floating-sel-anchor (car (gimp-edit-paste tint-layer-mask TRUE)))
(if (= blackwhite TRUE)
( begin
(gimp-desaturate-full adraw DESATURATE-LUMINOSITY)
)
)
(gimp-image-delete imgTMP)
(gimp-image-delete imgHSV)
(gimp-image-undo-group-end img)
(gimp-displays-flush)
(gimp-context-pop)
)
)
(script-fu-register "elsamuko-color-tint"
_"_Color Tint"
"Add color tint layer.
Latest version can be downloaded from /"
"elsamuko <>"
"elsamuko"
"16/04/10"
"*"
SF-IMAGE "Input image" 0
SF-DRAWABLE "Input drawable" 0
SF-COLOR "Color" '(0 0 255)
SF-ADJUSTMENT _"Opacity" '(100 0 100 5 10 0 0)
SF-ADJUSTMENT _"Saturation" '(100 0 100 5 10 0 0)
SF-TOGGLE _"Desaturate Image" FALSE
)
(script-fu-menu-register "elsamuko-color-tint" _"<Image>/Colors")
|
2e68e8763f0ccc2be0431c587bef8a44a40990a51f5607479cfe729b7fc6fd04 | yapsterapp/er-cassandra | edn_codec.cljc | (ns er-cassandra.model.callbacks.edn-codec
(:require
[taoensso.timbre #?(:clj :refer :cljs :refer-macros) [debug]]
#?(:clj [clojure.edn :as edn]
:cljs [cljs.reader :as edn])))
(defn edn-serialize-callback
[col]
(assert (keyword? col))
(fn [r]
(let [col? (contains? r col)
v (get r col)]
(cond
;; i would prefer not to set the value if the key
;; wasn't in the map, but it breaks a lot of tests
;;
UPDATE 20181018 mccraig - we got ta deal with the
test breakage 'cos this is causing : attrs and
;; :perms to get temporarily removed from :org_user
;; records during import with consequent perms failures
(not col?) r
(nil? v) (assoc r col nil)
(and (string? v) (empty? v)) (assoc r col nil)
(string? v) r
:else (binding [*print-length* -1]
(update r col pr-str))))))
(defn edn-deserialize-callback
([col] (edn-deserialize-callback col nil {}))
([col default-value] (edn-deserialize-callback col default-value {}))
([col default-value reader-opts]
(assert (keyword? col))
(fn [r]
(let [col? (contains? r col)
v (get r col)]
;;:completion_status [:started] nil
(try
(cond
;; i would prefer not to set the value if the key
;; wasn't in the map, but lots of test breakage results
;;
UPDATE 20181018 mccraig - we got ta deal with the
test breakage 'cos this is causing : attrs and
;; :perms to get temporarily removed from :org_user
;; records during import with consequent perms failures
(not col?) r
(nil? v) (assoc r col default-value)
(not (string? v)) r
:else (update r col #(edn/read-string reader-opts %)))
(catch #?(:clj Exception :cljs js/Error) err
(debug err (str "Failed to deserialize value:" v))
(throw err)))))))
| null | https://raw.githubusercontent.com/yapsterapp/er-cassandra/1d059f47bdf8654c7a4dd6f0759f1a114fdeba81/src/er_cassandra/model/callbacks/edn_codec.cljc | clojure | i would prefer not to set the value if the key
wasn't in the map, but it breaks a lot of tests
:perms to get temporarily removed from :org_user
records during import with consequent perms failures
:completion_status [:started] nil
i would prefer not to set the value if the key
wasn't in the map, but lots of test breakage results
:perms to get temporarily removed from :org_user
records during import with consequent perms failures | (ns er-cassandra.model.callbacks.edn-codec
(:require
[taoensso.timbre #?(:clj :refer :cljs :refer-macros) [debug]]
#?(:clj [clojure.edn :as edn]
:cljs [cljs.reader :as edn])))
(defn edn-serialize-callback
[col]
(assert (keyword? col))
(fn [r]
(let [col? (contains? r col)
v (get r col)]
(cond
UPDATE 20181018 mccraig - we got ta deal with the
test breakage 'cos this is causing : attrs and
(not col?) r
(nil? v) (assoc r col nil)
(and (string? v) (empty? v)) (assoc r col nil)
(string? v) r
:else (binding [*print-length* -1]
(update r col pr-str))))))
(defn edn-deserialize-callback
([col] (edn-deserialize-callback col nil {}))
([col default-value] (edn-deserialize-callback col default-value {}))
([col default-value reader-opts]
(assert (keyword? col))
(fn [r]
(let [col? (contains? r col)
v (get r col)]
(try
(cond
UPDATE 20181018 mccraig - we got ta deal with the
test breakage 'cos this is causing : attrs and
(not col?) r
(nil? v) (assoc r col default-value)
(not (string? v)) r
:else (update r col #(edn/read-string reader-opts %)))
(catch #?(:clj Exception :cljs js/Error) err
(debug err (str "Failed to deserialize value:" v))
(throw err)))))))
|
49316714dc3936d987583d81c184efa395582917abab5a5c7a075e288247eb67 | lambe-lang/nethra | term.ml | (* *)
type implicit = bool
type lit =
| Int of int
| Char of char
| String of string
type builtin =
| Fst
| Snd
| Inl
| Inr
| Fold
| Unfold
type 'a t =
(* Basic type, identifier and literals *)
| Type of int * 'a option
| Id of string * string option * 'a option
| Literal of lit * 'a option
(* Function type and data *)
| Pi of string * 'a t * 'a t * implicit * 'a option
| Lambda of string * 'a t * implicit * 'a option
| Apply of 'a t * 'a t * implicit * 'a option
| Let of string * 'a t * 'a t * 'a option
(* Pair type and data *)
| Sigma of string * 'a t * 'a t * 'a option
| Pair of 'a t * 'a t * 'a option
(* Sum type and data *)
| Sum of 'a t * 'a t * 'a option
| Case of 'a t * 'a t * 'a t * 'a option
(* Recursion *)
| Mu of string * 'a t * 'a t * 'a option
(* builtin *)
| BuiltIn of builtin * 'a t * 'a option
(* Type for inference *)
| Hole of string * 'a t option ref * 'a option
(* Type annotation *)
| Annotation of 'a t * 'a t * 'a option
(* Propositional equality *)
| Equals of 'a t * 'a t * 'a option
| Refl of 'a option
| Subst of 'a t * 'a t * 'a option
(* Record type and Access *)
| RecordSig of (string * 'a t) list * 'a option
| RecordVal of (string * 'a t) list * 'a option
| Access of 'a t * string * 'a option
module Construct = struct
let kind ?(c = None) i = Type (i, c)
let int ?(c = None) v = Literal (Int v, c)
let string ?(c = None) v = Literal (String v, c)
let char ?(c = None) v = Literal (Char v, c)
let id ?(c = None) ?(initial = None) name = Id (name, initial, c)
let pi ?(c = None) ?(implicit = false) n bound body =
Pi (n, bound, body, implicit, c)
let arrow ?(c = None) bound body = pi ~c "_" bound body
let lambda ?(c = None) ?(implicit = false) n body =
Lambda (n, body, implicit, c)
let apply ?(c = None) ?(implicit = false) abs arg =
Apply (abs, arg, implicit, c)
let let_binding ?(c = None) id arg body = Let (id, arg, body, c)
let sigma ?(c = None) n bound body = Sigma (n, bound, body, c)
let pair ?(c = None) left right = Pair (left, right, c)
let fst ?(c = None) term = BuiltIn (Fst, term, c)
let snd ?(c = None) term = BuiltIn (Snd, term, c)
let sum ?(c = None) left right = Sum (left, right, c)
let inl ?(c = None) term = BuiltIn (Inl, term, c)
let inr ?(c = None) term = BuiltIn (Inr, term, c)
let case ?(c = None) term left right = Case (term, left, right, c)
let mu ?(c = None) self kind body = Mu (self, kind, body, c)
let fold ?(c = None) term = BuiltIn (Fold, term, c)
let unfold ?(c = None) term = BuiltIn (Unfold, term, c)
let hole ?(c = None) ?(r = ref None) n = Hole (n, r, c)
let annotation ?(c = None) term kind = Annotation (term, kind, c)
let equals ?(c = None) lhd rhd = Equals (lhd, rhd, c)
let refl ?(c = None) _ = Refl c
let subst ?(c = None) lhd rhd = Subst (lhd, rhd, c)
let record_sig ?(c = None) l = RecordSig (l, c)
let record_val ?(c = None) l = RecordVal (l, c)
let access ?(c = None) t n = Access (t, n, c)
end
module Destruct = struct
let fold ~kind ~int ~char ~string ~id ~pi ~lambda ~apply ~let_binding ~sigma
~pair ~fst ~snd ~sum ~inl ~inr ~case ~mu ~fold ~unfold ~hole ~annotation
~equals ~refl ~subst ~record_sig ~record_val ~access = function
| Type (i, c) -> kind (i, c)
| Literal (Int i, c) -> int (i, c)
| Literal (Char i, c) -> char (i, c)
| Literal (String i, c) -> string (i, c)
| Id (name, initial, c) -> id (name, initial, c)
| Pi (n, bound, body, implicit, c) -> pi (n, bound, body, implicit, c)
| Lambda (n, body, implicit, c) -> lambda (n, body, implicit, c)
| Apply (abs, arg, implicit, c) -> apply (abs, arg, implicit, c)
| Let (n, arg, body, c) -> let_binding (n, arg, body, c)
| Sigma (n, bound, body, c) -> sigma (n, bound, body, c)
| Pair (first, second, c) -> pair (first, second, c)
| BuiltIn (Fst, term, c) -> fst (term, c)
| BuiltIn (Snd, term, c) -> snd (term, c)
| Sum (lhd, rhd, c) -> sum (lhd, rhd, c)
| BuiltIn (Inl, term, c) -> inl (term, c)
| BuiltIn (Inr, term, c) -> inr (term, c)
| Case (term, left, right, c) -> case (term, left, right, c)
| Mu (self, kind, body, c) -> mu (self, kind, body, c)
| BuiltIn (Fold, term, c) -> fold (term, c)
| BuiltIn (Unfold, term, c) -> unfold (term, c)
| Hole (n, body, c) -> hole (n, body, c)
| Annotation (term, kind, c) -> annotation (term, kind, c)
| Equals (lhd, rhd, c) -> equals (lhd, rhd, c)
| Refl c -> refl c
| Subst (lhd, rhd, c) -> subst (lhd, rhd, c)
| RecordSig (l, c) -> record_sig (l, c)
| RecordVal (l, c) -> record_val (l, c)
| Access (l, n, c) -> access (l, n, c)
let fold_opt =
let internal_fold = fold in
let none _ = None in
fun ?(kind = none) ?(int = none) ?(char = none) ?(string = none)
?(id = none) ?(pi = none) ?(lambda = none) ?(apply = none)
?(let_binding = none) ?(sigma = none) ?(pair = none) ?(fst = none)
?(snd = none) ?(sum = none) ?(inl = none) ?(inr = none) ?(case = none)
?(mu = none) ?(fold = none) ?(unfold = none) ?(hole = none)
?(annotation = none) ?(equals = none) ?(refl = none) ?(subst = none)
?(record_sig = none) ?(record_val = none) ?(access = none) term ->
internal_fold ~kind ~int ~char ~string ~id ~pi ~lambda ~apply ~let_binding
~sigma ~pair ~fst ~snd ~sum ~inl ~inr ~case ~mu ~fold ~unfold ~hole
~annotation ~equals ~refl ~subst ~record_sig ~record_val ~access term
end
| null | https://raw.githubusercontent.com/lambe-lang/nethra/c84871f475ef090653a87bf50bb416f7f6153fd8/lib/nethra/lang/ast/term.ml | ocaml |
Basic type, identifier and literals
Function type and data
Pair type and data
Sum type and data
Recursion
builtin
Type for inference
Type annotation
Propositional equality
Record type and Access |
type implicit = bool
type lit =
| Int of int
| Char of char
| String of string
type builtin =
| Fst
| Snd
| Inl
| Inr
| Fold
| Unfold
type 'a t =
| Type of int * 'a option
| Id of string * string option * 'a option
| Literal of lit * 'a option
| Pi of string * 'a t * 'a t * implicit * 'a option
| Lambda of string * 'a t * implicit * 'a option
| Apply of 'a t * 'a t * implicit * 'a option
| Let of string * 'a t * 'a t * 'a option
| Sigma of string * 'a t * 'a t * 'a option
| Pair of 'a t * 'a t * 'a option
| Sum of 'a t * 'a t * 'a option
| Case of 'a t * 'a t * 'a t * 'a option
| Mu of string * 'a t * 'a t * 'a option
| BuiltIn of builtin * 'a t * 'a option
| Hole of string * 'a t option ref * 'a option
| Annotation of 'a t * 'a t * 'a option
| Equals of 'a t * 'a t * 'a option
| Refl of 'a option
| Subst of 'a t * 'a t * 'a option
| RecordSig of (string * 'a t) list * 'a option
| RecordVal of (string * 'a t) list * 'a option
| Access of 'a t * string * 'a option
module Construct = struct
let kind ?(c = None) i = Type (i, c)
let int ?(c = None) v = Literal (Int v, c)
let string ?(c = None) v = Literal (String v, c)
let char ?(c = None) v = Literal (Char v, c)
let id ?(c = None) ?(initial = None) name = Id (name, initial, c)
let pi ?(c = None) ?(implicit = false) n bound body =
Pi (n, bound, body, implicit, c)
let arrow ?(c = None) bound body = pi ~c "_" bound body
let lambda ?(c = None) ?(implicit = false) n body =
Lambda (n, body, implicit, c)
let apply ?(c = None) ?(implicit = false) abs arg =
Apply (abs, arg, implicit, c)
let let_binding ?(c = None) id arg body = Let (id, arg, body, c)
let sigma ?(c = None) n bound body = Sigma (n, bound, body, c)
let pair ?(c = None) left right = Pair (left, right, c)
let fst ?(c = None) term = BuiltIn (Fst, term, c)
let snd ?(c = None) term = BuiltIn (Snd, term, c)
let sum ?(c = None) left right = Sum (left, right, c)
let inl ?(c = None) term = BuiltIn (Inl, term, c)
let inr ?(c = None) term = BuiltIn (Inr, term, c)
let case ?(c = None) term left right = Case (term, left, right, c)
let mu ?(c = None) self kind body = Mu (self, kind, body, c)
let fold ?(c = None) term = BuiltIn (Fold, term, c)
let unfold ?(c = None) term = BuiltIn (Unfold, term, c)
let hole ?(c = None) ?(r = ref None) n = Hole (n, r, c)
let annotation ?(c = None) term kind = Annotation (term, kind, c)
let equals ?(c = None) lhd rhd = Equals (lhd, rhd, c)
let refl ?(c = None) _ = Refl c
let subst ?(c = None) lhd rhd = Subst (lhd, rhd, c)
let record_sig ?(c = None) l = RecordSig (l, c)
let record_val ?(c = None) l = RecordVal (l, c)
let access ?(c = None) t n = Access (t, n, c)
end
module Destruct = struct
let fold ~kind ~int ~char ~string ~id ~pi ~lambda ~apply ~let_binding ~sigma
~pair ~fst ~snd ~sum ~inl ~inr ~case ~mu ~fold ~unfold ~hole ~annotation
~equals ~refl ~subst ~record_sig ~record_val ~access = function
| Type (i, c) -> kind (i, c)
| Literal (Int i, c) -> int (i, c)
| Literal (Char i, c) -> char (i, c)
| Literal (String i, c) -> string (i, c)
| Id (name, initial, c) -> id (name, initial, c)
| Pi (n, bound, body, implicit, c) -> pi (n, bound, body, implicit, c)
| Lambda (n, body, implicit, c) -> lambda (n, body, implicit, c)
| Apply (abs, arg, implicit, c) -> apply (abs, arg, implicit, c)
| Let (n, arg, body, c) -> let_binding (n, arg, body, c)
| Sigma (n, bound, body, c) -> sigma (n, bound, body, c)
| Pair (first, second, c) -> pair (first, second, c)
| BuiltIn (Fst, term, c) -> fst (term, c)
| BuiltIn (Snd, term, c) -> snd (term, c)
| Sum (lhd, rhd, c) -> sum (lhd, rhd, c)
| BuiltIn (Inl, term, c) -> inl (term, c)
| BuiltIn (Inr, term, c) -> inr (term, c)
| Case (term, left, right, c) -> case (term, left, right, c)
| Mu (self, kind, body, c) -> mu (self, kind, body, c)
| BuiltIn (Fold, term, c) -> fold (term, c)
| BuiltIn (Unfold, term, c) -> unfold (term, c)
| Hole (n, body, c) -> hole (n, body, c)
| Annotation (term, kind, c) -> annotation (term, kind, c)
| Equals (lhd, rhd, c) -> equals (lhd, rhd, c)
| Refl c -> refl c
| Subst (lhd, rhd, c) -> subst (lhd, rhd, c)
| RecordSig (l, c) -> record_sig (l, c)
| RecordVal (l, c) -> record_val (l, c)
| Access (l, n, c) -> access (l, n, c)
let fold_opt =
let internal_fold = fold in
let none _ = None in
fun ?(kind = none) ?(int = none) ?(char = none) ?(string = none)
?(id = none) ?(pi = none) ?(lambda = none) ?(apply = none)
?(let_binding = none) ?(sigma = none) ?(pair = none) ?(fst = none)
?(snd = none) ?(sum = none) ?(inl = none) ?(inr = none) ?(case = none)
?(mu = none) ?(fold = none) ?(unfold = none) ?(hole = none)
?(annotation = none) ?(equals = none) ?(refl = none) ?(subst = none)
?(record_sig = none) ?(record_val = none) ?(access = none) term ->
internal_fold ~kind ~int ~char ~string ~id ~pi ~lambda ~apply ~let_binding
~sigma ~pair ~fst ~snd ~sum ~inl ~inr ~case ~mu ~fold ~unfold ~hole
~annotation ~equals ~refl ~subst ~record_sig ~record_val ~access term
end
|
ce24c76e2854a78912473e5f16c91c65c05ef54bb9eece6c875b2807e89429e7 | barracudanetworks/lighthouse | project.clj | (defproject com.barracuda/lighthouse #=(clojure.string/trim #=(slurp "resources/VERSION"))
:description "A data-driven Kubernetes pre-processor"
:dependencies [[org.clojure/clojure "1.10.3"]
[borkdude/sci "0.2.5"]
[borkdude/edamame "0.0.11"]
[borkdude/rewrite-edn "0.0.2"]
[camel-snake-kebab "0.4.2"]
[cli-matic "0.4.3"]
[clj-commons/clj-yaml "0.7.1"]
[dorothy "0.0.7"]
[hiccup "1.0.5"]
[org.clojure/data.json "2.0.1"]]
:main lh.cli
:profiles {:test {:resource-paths ["test/resources"]}
:dev {:resource-paths ["test/resources"]}
:uberjar {:aot :all
:uberjar-name "lighthouse.jar"
:jvm-opts ["-Dclojure.compiler.direct-linking=true"]}})
| null | https://raw.githubusercontent.com/barracudanetworks/lighthouse/b66e5e431d407a3e7d5983d71b03806713b91df6/project.clj | clojure | (defproject com.barracuda/lighthouse #=(clojure.string/trim #=(slurp "resources/VERSION"))
:description "A data-driven Kubernetes pre-processor"
:dependencies [[org.clojure/clojure "1.10.3"]
[borkdude/sci "0.2.5"]
[borkdude/edamame "0.0.11"]
[borkdude/rewrite-edn "0.0.2"]
[camel-snake-kebab "0.4.2"]
[cli-matic "0.4.3"]
[clj-commons/clj-yaml "0.7.1"]
[dorothy "0.0.7"]
[hiccup "1.0.5"]
[org.clojure/data.json "2.0.1"]]
:main lh.cli
:profiles {:test {:resource-paths ["test/resources"]}
:dev {:resource-paths ["test/resources"]}
:uberjar {:aot :all
:uberjar-name "lighthouse.jar"
:jvm-opts ["-Dclojure.compiler.direct-linking=true"]}})
|
|
3ebf46b843327f9e88cf672bd864f0a4785c29a8e636103033df707ebc88b823 | robert-strandh/SICL | gui.lisp | (cl:in-package #:sicl-boot-backtrace-inspector)
(clim:define-application-frame inspector ()
((%stack :initarg :stack :reader stack)
(%current-entry :initform nil :accessor current-entry))
(:panes (arguments :application
:scroll-bars nil
:end-of-line-action :allow
:display-function 'display-arguments)
(backtrace :application
:scroll-bars nil
:incremental-redisplay t
:display-function 'display-backtrace)
(source :application
:scroll-bars nil
:display-function 'display-source)
(inter :interactor :scroll-bars nil))
(:layouts (default (clim:horizontally (:width 1200 :height 900)
(1/2 (clim:vertically ()
(3/10 (clim:scrolling () arguments))
(6/10 (clim:scrolling () backtrace))
(1/10 (clim:scrolling () inter))))
(1/2 (clim:scrolling () source))))))
(defclass argument () ())
(defun display-arguments (frame pane)
(let ((entry (current-entry frame)))
(unless (null entry)
(loop for argument in (sicl-hir-evaluator:arguments entry)
for i from 1
do (clim:with-drawing-options (pane :ink clim:+red+)
(format pane "~a:" i))
(multiple-value-bind (x y)
(clim:stream-cursor-position pane)
(declare (ignore x))
(setf (clim:stream-cursor-position pane)
(values 30 y)))
(clim:with-output-as-presentation
(pane argument 'argument)
(format pane "~s~%" argument))))))
(defun display-entry (pane entry)
(let ((origin (sicl-hir-evaluator:origin entry)))
(when (eq entry (current-entry clim:*application-frame*))
(format pane "+"))
(multiple-value-bind (x y)
(clim:stream-cursor-position pane)
(declare (ignore x))
(setf (clim:stream-cursor-position pane)
(values 20 y)))
(clim:with-output-as-presentation
(pane entry 'sicl-hir-evaluator:call-stack-entry)
(if (null origin)
(clim:with-drawing-options (pane :ink clim:+red+)
(format pane "entry with no source information~%"))
(clim:with-drawing-options (pane :ink clim:+dark-green+)
(let* ((start (car origin))
(line-index (sicl-source-tracking:line-index start))
(line (aref (sicl-source-tracking:lines start) line-index))
(char-index (sicl-source-tracking:character-index start)))
(multiple-value-bind (x y)
(clim:stream-cursor-position pane)
(declare (ignore x))
(setf (clim:stream-cursor-position pane)
(values 20 y)))
(format pane "~a~%" (subseq line char-index))))))))
(defun display-backtrace (frame pane)
(loop for entry in (stack frame)
do (display-entry pane entry)))
(defun display-source (frame pane)
(let ((entry (current-entry frame)))
(unless (or (null entry)
(null (sicl-hir-evaluator:origin entry)))
(let* ((origin (sicl-hir-evaluator:origin entry))
(start (car origin))
(start-line-index (sicl-source-tracking:line-index start))
(start-character-index (sicl-source-tracking:character-index start))
(end (cdr origin))
(end-line-index (sicl-source-tracking:line-index end))
(end-character-index (sicl-source-tracking:character-index end))
(lines (sicl-source-tracking:lines start)))
(setf (clim:stream-drawing-p pane) nil)
;; Display all the lines preceding the source location
(loop for i from 0 below start-line-index
do (format pane "~a~%" (aref lines i)))
(if (= start-line-index end-line-index)
(let ((line (aref lines start-line-index)))
(format pane "~a" (subseq line 0 start-character-index))
(clim:with-drawing-options (pane :ink clim:+red+)
(format pane "~a"
(subseq line start-character-index end-character-index)))
(format pane "~a~%" (subseq line end-character-index)))
(let ((start-line (aref lines start-line-index))
(end-line (aref lines end-line-index)))
(format pane "~a" (subseq start-line 0 start-character-index))
(clim:with-drawing-options (pane :ink clim:+red+)
(format pane "~a~%" (subseq start-line start-character-index))
(loop for i from (1+ start-line-index) below end-line-index
do (format pane "~a~%" (aref lines i)))
(format pane "~a" (subseq end-line 0 end-character-index)))
(format pane "~a~%" (subseq end-line end-character-index))))
(loop for i from (1+ end-line-index) below (length lines)
do (format pane "~a~%" (aref lines i)))
(setf (clim:stream-drawing-p pane) t)
(clim:replay (clim:stream-output-history pane) pane)))))
(defun inspect (stack &key new-process-p)
(let ((frame (clim:make-application-frame 'inspector
:stack stack)))
(flet ((run ()
(clim:run-frame-top-level frame)))
(if new-process-p
(clim-sys:make-process #'run)
(run)))))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/37752269e983495c89a4a5b49fd303d67910f810/Code/Boot/Backtrace-inspector/gui.lisp | lisp | Display all the lines preceding the source location | (cl:in-package #:sicl-boot-backtrace-inspector)
(clim:define-application-frame inspector ()
((%stack :initarg :stack :reader stack)
(%current-entry :initform nil :accessor current-entry))
(:panes (arguments :application
:scroll-bars nil
:end-of-line-action :allow
:display-function 'display-arguments)
(backtrace :application
:scroll-bars nil
:incremental-redisplay t
:display-function 'display-backtrace)
(source :application
:scroll-bars nil
:display-function 'display-source)
(inter :interactor :scroll-bars nil))
(:layouts (default (clim:horizontally (:width 1200 :height 900)
(1/2 (clim:vertically ()
(3/10 (clim:scrolling () arguments))
(6/10 (clim:scrolling () backtrace))
(1/10 (clim:scrolling () inter))))
(1/2 (clim:scrolling () source))))))
(defclass argument () ())
(defun display-arguments (frame pane)
(let ((entry (current-entry frame)))
(unless (null entry)
(loop for argument in (sicl-hir-evaluator:arguments entry)
for i from 1
do (clim:with-drawing-options (pane :ink clim:+red+)
(format pane "~a:" i))
(multiple-value-bind (x y)
(clim:stream-cursor-position pane)
(declare (ignore x))
(setf (clim:stream-cursor-position pane)
(values 30 y)))
(clim:with-output-as-presentation
(pane argument 'argument)
(format pane "~s~%" argument))))))
(defun display-entry (pane entry)
(let ((origin (sicl-hir-evaluator:origin entry)))
(when (eq entry (current-entry clim:*application-frame*))
(format pane "+"))
(multiple-value-bind (x y)
(clim:stream-cursor-position pane)
(declare (ignore x))
(setf (clim:stream-cursor-position pane)
(values 20 y)))
(clim:with-output-as-presentation
(pane entry 'sicl-hir-evaluator:call-stack-entry)
(if (null origin)
(clim:with-drawing-options (pane :ink clim:+red+)
(format pane "entry with no source information~%"))
(clim:with-drawing-options (pane :ink clim:+dark-green+)
(let* ((start (car origin))
(line-index (sicl-source-tracking:line-index start))
(line (aref (sicl-source-tracking:lines start) line-index))
(char-index (sicl-source-tracking:character-index start)))
(multiple-value-bind (x y)
(clim:stream-cursor-position pane)
(declare (ignore x))
(setf (clim:stream-cursor-position pane)
(values 20 y)))
(format pane "~a~%" (subseq line char-index))))))))
(defun display-backtrace (frame pane)
(loop for entry in (stack frame)
do (display-entry pane entry)))
(defun display-source (frame pane)
(let ((entry (current-entry frame)))
(unless (or (null entry)
(null (sicl-hir-evaluator:origin entry)))
(let* ((origin (sicl-hir-evaluator:origin entry))
(start (car origin))
(start-line-index (sicl-source-tracking:line-index start))
(start-character-index (sicl-source-tracking:character-index start))
(end (cdr origin))
(end-line-index (sicl-source-tracking:line-index end))
(end-character-index (sicl-source-tracking:character-index end))
(lines (sicl-source-tracking:lines start)))
(setf (clim:stream-drawing-p pane) nil)
(loop for i from 0 below start-line-index
do (format pane "~a~%" (aref lines i)))
(if (= start-line-index end-line-index)
(let ((line (aref lines start-line-index)))
(format pane "~a" (subseq line 0 start-character-index))
(clim:with-drawing-options (pane :ink clim:+red+)
(format pane "~a"
(subseq line start-character-index end-character-index)))
(format pane "~a~%" (subseq line end-character-index)))
(let ((start-line (aref lines start-line-index))
(end-line (aref lines end-line-index)))
(format pane "~a" (subseq start-line 0 start-character-index))
(clim:with-drawing-options (pane :ink clim:+red+)
(format pane "~a~%" (subseq start-line start-character-index))
(loop for i from (1+ start-line-index) below end-line-index
do (format pane "~a~%" (aref lines i)))
(format pane "~a" (subseq end-line 0 end-character-index)))
(format pane "~a~%" (subseq end-line end-character-index))))
(loop for i from (1+ end-line-index) below (length lines)
do (format pane "~a~%" (aref lines i)))
(setf (clim:stream-drawing-p pane) t)
(clim:replay (clim:stream-output-history pane) pane)))))
(defun inspect (stack &key new-process-p)
(let ((frame (clim:make-application-frame 'inspector
:stack stack)))
(flet ((run ()
(clim:run-frame-top-level frame)))
(if new-process-p
(clim-sys:make-process #'run)
(run)))))
|
eb0dfe159a51a541173a5b6ad5fdf3e46d388cdb792108edee74c033d7c7cd0b | tarides/dune-release | opam_file.mli | val upgrade :
filename:OpamTypes.filename ->
url:OpamFile.URL.t ->
id:string ->
version:[ `V1 of OpamFile.Descr.t | `V2 ] ->
OpamFile.OPAM.t ->
OpamFile.OPAM.t
(** [upgrade ~filename ~url ~id ~version opam_t] produces the content of the
opam file for the opam package, from the old [opam_t] content, migrating to
the most supported format if needed (depending on [version]), setting the
'url' field with [url], setting the 'x-commit-hash' to [id], and stripping
the 'version' and 'name' fields. *)
| null | https://raw.githubusercontent.com/tarides/dune-release/6bfed0f299b82c0931c78d4e216fd0efedff0673/lib/opam_file.mli | ocaml | * [upgrade ~filename ~url ~id ~version opam_t] produces the content of the
opam file for the opam package, from the old [opam_t] content, migrating to
the most supported format if needed (depending on [version]), setting the
'url' field with [url], setting the 'x-commit-hash' to [id], and stripping
the 'version' and 'name' fields. | val upgrade :
filename:OpamTypes.filename ->
url:OpamFile.URL.t ->
id:string ->
version:[ `V1 of OpamFile.Descr.t | `V2 ] ->
OpamFile.OPAM.t ->
OpamFile.OPAM.t
|
a4624983f9b0dd13e9bfa4a8cfc62d9a4334de24fbab614380cfc68fc54f0f73 | mirage/index | force_merge.ml | module Hook = Index.Private.Hook
module Semaphore = Semaphore_compat.Semaphore.Binary
open Common
let root = Filename.concat "_tests" "unix.force_merge"
module Context = Common.Make_context (struct
let root = root
end)
let after f = Hook.v (function `After -> f () | _ -> ())
let after_clear f = Hook.v (function `After_clear -> f () | _ -> ())
let before f = Hook.v (function `Before -> f () | _ -> ())
let before_offset_read f =
Hook.v (function `Before_offset_read -> f () | _ -> ())
let test_find_present t tbl =
Hashtbl.iter
(fun k v ->
match Index.find t k with
| res ->
if not (res = v) then Alcotest.fail "Replacing existing value failed."
| exception Not_found ->
Alcotest.failf "Inserted value is not present anymore: %s." k)
tbl
let test_one_entry r k v =
match Index.find r k with
| res ->
if not (res = v) then Alcotest.fail "Replacing existing value failed."
| exception Not_found ->
Alcotest.failf "Inserted value is not present anymore: %s." k
let test_fd () =
match Common.get_open_fd root with
| `Ok lines -> (
let contains sub s =
try
ignore (Re.Str.search_forward (Re.Str.regexp sub) s 0);
true
with Not_found -> false
in
let result =
let data, rs = List.partition (contains "data") lines in
if List.length data > 2 then
Alcotest.fail "Too many file descriptors opened for data files";
let log, rs = List.partition (contains "log") rs in
if List.length log > 2 then
Alcotest.fail "Too many file descriptors opened for log files";
let lock, rs = List.partition (contains "lock") rs in
if List.length lock > 2 then
Alcotest.fail "Too many file descriptors opened for lock files";
if List.length rs > 0 then
Alcotest.fail "Unknown file descriptors opened";
`Ok ()
in
match result with
| `Ok () -> ()
| `Skip err -> Log.warn (fun m -> m "`test_fd` was skipped: %s" err))
| `Skip err -> Log.warn (fun m -> m "`test_fd` was skipped: %s" err)
let readonly_s () =
let* { Context.tbl; clone; _ } = Context.with_full_index () in
let r1 = clone ~readonly:true () in
let r2 = clone ~readonly:true () in
let r3 = clone ~readonly:true () in
test_find_present r1 tbl;
test_find_present r2 tbl;
test_find_present r3 tbl;
test_fd ()
let readonly () =
let* { Context.tbl; clone; _ } = Context.with_full_index () in
let r1 = clone ~readonly:true () in
let r2 = clone ~readonly:true () in
let r3 = clone ~readonly:true () in
Hashtbl.iter
(fun k v ->
test_one_entry r1 k v;
test_one_entry r2 k v;
test_one_entry r3 k v)
tbl;
test_fd ()
let readonly_and_merge () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let w = rw in
let r1 = clone ~readonly:true () in
let r2 = clone ~readonly:true () in
let r3 = clone ~readonly:true () in
let interleave () =
let k1 = Key.v () in
let v1 = Value.v () in
Index.replace w k1 v1;
Index.flush w;
let t1 = Index.try_merge_aux ~force:true w in
Index.sync r1;
Index.sync r2;
Index.sync r3;
test_one_entry r1 k1 v1;
test_one_entry r2 k1 v1;
test_one_entry r3 k1 v1;
let k2 = Key.v () in
let v2 = Value.v () in
Index.replace w k2 v2;
Index.flush w;
Index.sync r1;
Index.sync r2;
Index.sync r3;
test_one_entry r1 k1 v1;
let t2 = Index.try_merge_aux ~force:true w in
test_one_entry r2 k2 v2;
test_one_entry r3 k1 v1;
let k2 = Key.v () in
let v2 = Value.v () in
let k3 = Key.v () in
let v3 = Value.v () in
test_one_entry r1 k1 v1;
Index.replace w k2 v2;
Index.flush w;
Index.sync r1;
let t3 = Index.try_merge_aux ~force:true w in
test_one_entry r1 k1 v1;
Index.replace w k3 v3;
Index.flush w;
Index.sync r3;
let t4 = Index.try_merge_aux ~force:true w in
test_one_entry r3 k3 v3;
let k2 = Key.v () in
let v2 = Value.v () in
Index.replace w k2 v2;
Index.flush w;
Index.sync r2;
Index.sync r3;
test_one_entry w k2 v2;
let t5 = Index.try_merge_aux ~force:true w in
test_one_entry w k2 v2;
test_one_entry r2 k2 v2;
test_one_entry r3 k1 v1;
let k2 = Key.v () in
let v2 = Value.v () in
Index.replace w k2 v2;
Index.flush w;
Index.sync r2;
Index.sync r3;
test_one_entry r2 k1 v1;
let t6 = Index.try_merge_aux ~force:true w in
test_one_entry w k2 v2;
test_one_entry r2 k2 v2;
test_one_entry r3 k2 v2;
Index.await t1 |> check_completed;
Index.await t2 |> check_completed;
Index.await t3 |> check_completed;
Index.await t4 |> check_completed;
Index.await t5 |> check_completed;
Index.await t6 |> check_completed
in
for _ = 1 to 10 do
interleave ()
done;
test_fd ()
(* A force merge has an implicit flush, however, if the replace occurs at the end of the merge, the value is not flushed *)
let write_after_merge () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let w = rw in
let r1 = clone ~readonly:true () in
let k1 = Key.v () in
let v1 = Value.v () in
let k2 = Key.v () in
let v2 = Value.v () in
Index.replace w k1 v1;
let hook = after (fun () -> Index.replace w k2 v2) in
let t = Index.try_merge_aux ~force:true ~hook w in
Index.await t |> check_completed;
Index.sync r1;
test_one_entry r1 k1 v1;
Alcotest.check_raises (Printf.sprintf "Absent value was found: %s." k2)
Not_found (fun () -> ignore_value (Index.find r1 k2))
let replace_while_merge () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let w = rw in
let r1 = clone ~readonly:true () in
let k1 = Key.v () in
let v1 = Value.v () in
let k2 = Key.v () in
let v2 = Value.v () in
Index.replace w k1 v1;
let hook =
before (fun () ->
Index.replace w k2 v2;
test_one_entry w k2 v2)
in
let t = Index.try_merge_aux ~force:true ~hook w in
Index.sync r1;
test_one_entry r1 k1 v1;
Index.await t |> check_completed
note that here we can not do
` test_one_entry r1 k2 v2 `
as there is no way to guarantee that the latests value
added by a RW instance is found by a RO instance
`test_one_entry r1 k2 v2`
as there is no way to guarantee that the latests value
added by a RW instance is found by a RO instance
*)
let find_while_merge () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let w = rw in
let k1 = Key.v () in
let v1 = Value.v () in
Index.replace w k1 v1;
let f () = test_one_entry w k1 v1 in
let t1 = Index.try_merge_aux ~force:true ~hook:(after f) w in
let t2 = Index.try_merge_aux ~force:true ~hook:(after f) w in
let r1 = clone ~readonly:true () in
let f () = test_one_entry r1 k1 v1 in
let t3 = Index.try_merge_aux ~force:true ~hook:(before f) w in
let t4 = Index.try_merge_aux ~force:true ~hook:(before f) w in
Index.await t1 |> check_completed;
Index.await t2 |> check_completed;
Index.await t3 |> check_completed;
Index.await t4 |> check_completed
let find_in_async_generation_change () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let w = rw in
let r1 = clone ~readonly:true () in
let k1 = Key.v () in
let v1 = Value.v () in
let f () =
Index.replace w k1 v1;
Index.flush w;
Index.sync r1;
test_one_entry r1 k1 v1
in
let t1 = Index.try_merge_aux ~force:true ~hook:(before f) w in
Index.await t1 |> check_completed
let find_in_async_same_generation () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let w = rw in
let r1 = clone ~readonly:true () in
let k1 = Key.v () in
let v1 = Value.v () in
let k2 = Key.v () in
let v2 = Value.v () in
let f () =
Index.replace w k1 v1;
Index.flush w;
Index.sync r1;
test_one_entry r1 k1 v1;
Index.replace w k2 v2;
Index.flush w;
Index.sync r1;
test_one_entry r1 k2 v2
in
let t1 = Index.try_merge_aux ~force:true ~hook:(before f) w in
Index.await t1 |> check_completed
let sync_before_and_after_clearing_async () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let w = rw in
let ro = clone ~readonly:true () in
let k1 = Key.v () in
let v1 = Value.v () in
let k2 = Key.v () in
let v2 = Value.v () in
let add_in_async () =
Index.replace w k1 v1;
Index.replace w k2 v2;
Index.flush w;
Log.debug (fun l -> l "RO updates async's offset");
Index.sync ro
in
let sync_before_clear_async () =
Log.debug (fun l -> l "RO updates instance's generation");
Index.sync ro
in
let hook =
Hook.v (function
| `Before -> add_in_async ()
| `After_clear -> sync_before_clear_async ()
| _ -> ())
in
let t1 = Index.try_merge_aux ~force:true ~hook w in
Index.await t1 |> check_completed;
Index.sync ro;
test_one_entry ro k1 v1;
test_one_entry ro k2 v2
(** RW adds a value in log and flushes it, so every subsequent RO sync should
find that value. But if the RO sync occurs during a merge, after a clear but
before a generation change, then the value is missed. Also test ro find at
this point. *)
let sync_after_clear_log () =
let* Context.{ rw; clone; _ } = Context.with_empty_index () in
let ro = clone ~readonly:true () in
let k1, v1 = (Key.v (), Value.v ()) in
Index.replace rw k1 v1;
Index.flush rw;
let hook = after_clear (fun () -> Index.sync ro) in
let t = Index.try_merge_aux ~force:true ~hook rw in
Index.await t |> check_completed;
test_one_entry ro k1 v1;
let k2, v2 = (Key.v (), Value.v ()) in
Index.replace rw k2 v2;
Index.flush rw;
Index.sync ro;
let hook = after_clear (fun () -> test_one_entry ro k1 v1) in
let t = Index.try_merge_aux ~force:true ~hook rw in
Index.await t |> check_completed
(** during a merge RO sync can miss a value if it reads the generation before
the generation is updated. *)
let merge_during_sync () =
let* Context.{ rw; clone; _ } = Context.with_empty_index () in
let ro = clone ~readonly:true () in
let k1, v1 = (Key.v (), Value.v ()) in
Index.replace rw k1 v1;
Index.flush rw;
let hook =
before_offset_read (fun () ->
let t = Index.try_merge_aux ~force:true rw in
Index.await t |> check_completed)
in
Index.sync' ~hook ro;
test_one_entry ro k1 v1
let test_is_merging () =
let* Context.{ rw; _ } = Context.with_empty_index () in
let add_binding_and_merge ~hook =
let k1, v1 = (Key.v (), Value.v ()) in
Index.replace rw k1 v1;
let t = Index.try_merge_aux ~force:true ~hook rw in
Index.await t |> check_completed
in
let f msg b () = Alcotest.(check bool) msg (Index.is_merging rw) b in
f "before merge" false ();
add_binding_and_merge ~hook:(before (f "before" true));
f "between merge" false ();
add_binding_and_merge ~hook:(after (f "after" true));
add_binding_and_merge ~hook:(after_clear (f "after clear" true))
let add_bindings index =
let k1, v1 = (Key.v (), Value.v ()) in
Index.replace index k1 v1
(** Test that a clear aborts the merge. *)
let test_non_blocking_clear () =
let* Context.{ rw; _ } = Context.with_empty_index () in
let merge_started = Semaphore.make false and merge = Semaphore.make false in
let merge_hook =
Hook.v @@ function
| `Before ->
Semaphore.release merge_started;
Semaphore.acquire merge
| `After -> Alcotest.fail "Merge should have been aborted by clear"
| _ -> ()
in
let clear_hook =
Hook.v @@ function
| `Abort_signalled -> Semaphore.release merge
| `IO_clear -> ()
in
add_bindings rw;
let thread = Index.try_merge_aux ~force:true ~hook:merge_hook rw in
Semaphore.acquire merge_started;
add_bindings rw;
Index.clear' ~hook:clear_hook rw;
match Index.await thread with
| Ok `Aborted -> ()
| _ -> Alcotest.fail "merge should have aborted"
* The test consists of aborting a first merge after one entry is added in the
./merge file and checking that a second merge succeeds . Regression test for
PR 211 in which the second merge was triggering an assert failure .
./merge file and checking that a second merge succeeds. Regression test for
PR 211 in which the second merge was triggering an assert failure. *)
let test_abort_merge ~abort_merge () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let merge_started = Semaphore.make false and merge = Semaphore.make false in
let merge_hook =
Hook.v @@ function
| `After_first_entry ->
Semaphore.release merge_started;
Semaphore.acquire merge
| `After | `After_clear ->
Alcotest.fail "Merge should have been aborted by clear"
| `Before -> ()
in
let abort_hook =
Hook.v @@ function
| `Abort_signalled -> Semaphore.release merge
| `IO_clear -> ()
in
let t = Index.try_merge_aux ~force:true ~hook:merge_hook rw in
Semaphore.acquire merge_started;
abort_merge ~hook:abort_hook rw;
(match Index.await t with
| Ok `Aborted -> ()
| _ -> Alcotest.fail "Merge should have aborted");
let rw = clone ~readonly:false ~fresh:false () in
add_bindings rw;
let t = Index.try_merge_aux ~force:true rw in
Index.await t |> check_completed
let test_clear_aborts_merge = test_abort_merge ~abort_merge:Index.clear'
let test_close_immediately_aborts_merge =
test_abort_merge ~abort_merge:(Index.close' ~immediately:())
let tests =
[
("readonly in sequence", `Quick, readonly_s);
("readonly interleaved", `Quick, readonly);
("interleaved merge", `Quick, readonly_and_merge);
("write at the end of merge", `Quick, write_after_merge);
("write in log_async", `Quick, replace_while_merge);
("find while merging", `Quick, find_while_merge);
("find in async without log", `Quick, find_in_async_generation_change);
("find in async with log", `Quick, find_in_async_same_generation);
( "sync before and after clearing the async",
`Quick,
sync_before_and_after_clearing_async );
("sync and find after log cleared", `Quick, sync_after_clear_log);
("merge during ro sync", `Quick, merge_during_sync);
("is_merging", `Quick, test_is_merging);
("clear is not blocking", `Quick, test_non_blocking_clear);
("`clear` aborts merge", `Quick, test_clear_aborts_merge);
( "`close ~immediately` aborts merge",
`Quick,
test_close_immediately_aborts_merge );
]
| null | https://raw.githubusercontent.com/mirage/index/fe5e962534d192389484ecc63a25e4ab4668a2f0/test/unix/force_merge.ml | ocaml | A force merge has an implicit flush, however, if the replace occurs at the end of the merge, the value is not flushed
* RW adds a value in log and flushes it, so every subsequent RO sync should
find that value. But if the RO sync occurs during a merge, after a clear but
before a generation change, then the value is missed. Also test ro find at
this point.
* during a merge RO sync can miss a value if it reads the generation before
the generation is updated.
* Test that a clear aborts the merge. | module Hook = Index.Private.Hook
module Semaphore = Semaphore_compat.Semaphore.Binary
open Common
let root = Filename.concat "_tests" "unix.force_merge"
module Context = Common.Make_context (struct
let root = root
end)
let after f = Hook.v (function `After -> f () | _ -> ())
let after_clear f = Hook.v (function `After_clear -> f () | _ -> ())
let before f = Hook.v (function `Before -> f () | _ -> ())
let before_offset_read f =
Hook.v (function `Before_offset_read -> f () | _ -> ())
let test_find_present t tbl =
Hashtbl.iter
(fun k v ->
match Index.find t k with
| res ->
if not (res = v) then Alcotest.fail "Replacing existing value failed."
| exception Not_found ->
Alcotest.failf "Inserted value is not present anymore: %s." k)
tbl
let test_one_entry r k v =
match Index.find r k with
| res ->
if not (res = v) then Alcotest.fail "Replacing existing value failed."
| exception Not_found ->
Alcotest.failf "Inserted value is not present anymore: %s." k
let test_fd () =
match Common.get_open_fd root with
| `Ok lines -> (
let contains sub s =
try
ignore (Re.Str.search_forward (Re.Str.regexp sub) s 0);
true
with Not_found -> false
in
let result =
let data, rs = List.partition (contains "data") lines in
if List.length data > 2 then
Alcotest.fail "Too many file descriptors opened for data files";
let log, rs = List.partition (contains "log") rs in
if List.length log > 2 then
Alcotest.fail "Too many file descriptors opened for log files";
let lock, rs = List.partition (contains "lock") rs in
if List.length lock > 2 then
Alcotest.fail "Too many file descriptors opened for lock files";
if List.length rs > 0 then
Alcotest.fail "Unknown file descriptors opened";
`Ok ()
in
match result with
| `Ok () -> ()
| `Skip err -> Log.warn (fun m -> m "`test_fd` was skipped: %s" err))
| `Skip err -> Log.warn (fun m -> m "`test_fd` was skipped: %s" err)
let readonly_s () =
let* { Context.tbl; clone; _ } = Context.with_full_index () in
let r1 = clone ~readonly:true () in
let r2 = clone ~readonly:true () in
let r3 = clone ~readonly:true () in
test_find_present r1 tbl;
test_find_present r2 tbl;
test_find_present r3 tbl;
test_fd ()
let readonly () =
let* { Context.tbl; clone; _ } = Context.with_full_index () in
let r1 = clone ~readonly:true () in
let r2 = clone ~readonly:true () in
let r3 = clone ~readonly:true () in
Hashtbl.iter
(fun k v ->
test_one_entry r1 k v;
test_one_entry r2 k v;
test_one_entry r3 k v)
tbl;
test_fd ()
let readonly_and_merge () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let w = rw in
let r1 = clone ~readonly:true () in
let r2 = clone ~readonly:true () in
let r3 = clone ~readonly:true () in
let interleave () =
let k1 = Key.v () in
let v1 = Value.v () in
Index.replace w k1 v1;
Index.flush w;
let t1 = Index.try_merge_aux ~force:true w in
Index.sync r1;
Index.sync r2;
Index.sync r3;
test_one_entry r1 k1 v1;
test_one_entry r2 k1 v1;
test_one_entry r3 k1 v1;
let k2 = Key.v () in
let v2 = Value.v () in
Index.replace w k2 v2;
Index.flush w;
Index.sync r1;
Index.sync r2;
Index.sync r3;
test_one_entry r1 k1 v1;
let t2 = Index.try_merge_aux ~force:true w in
test_one_entry r2 k2 v2;
test_one_entry r3 k1 v1;
let k2 = Key.v () in
let v2 = Value.v () in
let k3 = Key.v () in
let v3 = Value.v () in
test_one_entry r1 k1 v1;
Index.replace w k2 v2;
Index.flush w;
Index.sync r1;
let t3 = Index.try_merge_aux ~force:true w in
test_one_entry r1 k1 v1;
Index.replace w k3 v3;
Index.flush w;
Index.sync r3;
let t4 = Index.try_merge_aux ~force:true w in
test_one_entry r3 k3 v3;
let k2 = Key.v () in
let v2 = Value.v () in
Index.replace w k2 v2;
Index.flush w;
Index.sync r2;
Index.sync r3;
test_one_entry w k2 v2;
let t5 = Index.try_merge_aux ~force:true w in
test_one_entry w k2 v2;
test_one_entry r2 k2 v2;
test_one_entry r3 k1 v1;
let k2 = Key.v () in
let v2 = Value.v () in
Index.replace w k2 v2;
Index.flush w;
Index.sync r2;
Index.sync r3;
test_one_entry r2 k1 v1;
let t6 = Index.try_merge_aux ~force:true w in
test_one_entry w k2 v2;
test_one_entry r2 k2 v2;
test_one_entry r3 k2 v2;
Index.await t1 |> check_completed;
Index.await t2 |> check_completed;
Index.await t3 |> check_completed;
Index.await t4 |> check_completed;
Index.await t5 |> check_completed;
Index.await t6 |> check_completed
in
for _ = 1 to 10 do
interleave ()
done;
test_fd ()
let write_after_merge () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let w = rw in
let r1 = clone ~readonly:true () in
let k1 = Key.v () in
let v1 = Value.v () in
let k2 = Key.v () in
let v2 = Value.v () in
Index.replace w k1 v1;
let hook = after (fun () -> Index.replace w k2 v2) in
let t = Index.try_merge_aux ~force:true ~hook w in
Index.await t |> check_completed;
Index.sync r1;
test_one_entry r1 k1 v1;
Alcotest.check_raises (Printf.sprintf "Absent value was found: %s." k2)
Not_found (fun () -> ignore_value (Index.find r1 k2))
let replace_while_merge () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let w = rw in
let r1 = clone ~readonly:true () in
let k1 = Key.v () in
let v1 = Value.v () in
let k2 = Key.v () in
let v2 = Value.v () in
Index.replace w k1 v1;
let hook =
before (fun () ->
Index.replace w k2 v2;
test_one_entry w k2 v2)
in
let t = Index.try_merge_aux ~force:true ~hook w in
Index.sync r1;
test_one_entry r1 k1 v1;
Index.await t |> check_completed
note that here we can not do
` test_one_entry r1 k2 v2 `
as there is no way to guarantee that the latests value
added by a RW instance is found by a RO instance
`test_one_entry r1 k2 v2`
as there is no way to guarantee that the latests value
added by a RW instance is found by a RO instance
*)
let find_while_merge () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let w = rw in
let k1 = Key.v () in
let v1 = Value.v () in
Index.replace w k1 v1;
let f () = test_one_entry w k1 v1 in
let t1 = Index.try_merge_aux ~force:true ~hook:(after f) w in
let t2 = Index.try_merge_aux ~force:true ~hook:(after f) w in
let r1 = clone ~readonly:true () in
let f () = test_one_entry r1 k1 v1 in
let t3 = Index.try_merge_aux ~force:true ~hook:(before f) w in
let t4 = Index.try_merge_aux ~force:true ~hook:(before f) w in
Index.await t1 |> check_completed;
Index.await t2 |> check_completed;
Index.await t3 |> check_completed;
Index.await t4 |> check_completed
let find_in_async_generation_change () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let w = rw in
let r1 = clone ~readonly:true () in
let k1 = Key.v () in
let v1 = Value.v () in
let f () =
Index.replace w k1 v1;
Index.flush w;
Index.sync r1;
test_one_entry r1 k1 v1
in
let t1 = Index.try_merge_aux ~force:true ~hook:(before f) w in
Index.await t1 |> check_completed
let find_in_async_same_generation () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let w = rw in
let r1 = clone ~readonly:true () in
let k1 = Key.v () in
let v1 = Value.v () in
let k2 = Key.v () in
let v2 = Value.v () in
let f () =
Index.replace w k1 v1;
Index.flush w;
Index.sync r1;
test_one_entry r1 k1 v1;
Index.replace w k2 v2;
Index.flush w;
Index.sync r1;
test_one_entry r1 k2 v2
in
let t1 = Index.try_merge_aux ~force:true ~hook:(before f) w in
Index.await t1 |> check_completed
let sync_before_and_after_clearing_async () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let w = rw in
let ro = clone ~readonly:true () in
let k1 = Key.v () in
let v1 = Value.v () in
let k2 = Key.v () in
let v2 = Value.v () in
let add_in_async () =
Index.replace w k1 v1;
Index.replace w k2 v2;
Index.flush w;
Log.debug (fun l -> l "RO updates async's offset");
Index.sync ro
in
let sync_before_clear_async () =
Log.debug (fun l -> l "RO updates instance's generation");
Index.sync ro
in
let hook =
Hook.v (function
| `Before -> add_in_async ()
| `After_clear -> sync_before_clear_async ()
| _ -> ())
in
let t1 = Index.try_merge_aux ~force:true ~hook w in
Index.await t1 |> check_completed;
Index.sync ro;
test_one_entry ro k1 v1;
test_one_entry ro k2 v2
let sync_after_clear_log () =
let* Context.{ rw; clone; _ } = Context.with_empty_index () in
let ro = clone ~readonly:true () in
let k1, v1 = (Key.v (), Value.v ()) in
Index.replace rw k1 v1;
Index.flush rw;
let hook = after_clear (fun () -> Index.sync ro) in
let t = Index.try_merge_aux ~force:true ~hook rw in
Index.await t |> check_completed;
test_one_entry ro k1 v1;
let k2, v2 = (Key.v (), Value.v ()) in
Index.replace rw k2 v2;
Index.flush rw;
Index.sync ro;
let hook = after_clear (fun () -> test_one_entry ro k1 v1) in
let t = Index.try_merge_aux ~force:true ~hook rw in
Index.await t |> check_completed
let merge_during_sync () =
let* Context.{ rw; clone; _ } = Context.with_empty_index () in
let ro = clone ~readonly:true () in
let k1, v1 = (Key.v (), Value.v ()) in
Index.replace rw k1 v1;
Index.flush rw;
let hook =
before_offset_read (fun () ->
let t = Index.try_merge_aux ~force:true rw in
Index.await t |> check_completed)
in
Index.sync' ~hook ro;
test_one_entry ro k1 v1
let test_is_merging () =
let* Context.{ rw; _ } = Context.with_empty_index () in
let add_binding_and_merge ~hook =
let k1, v1 = (Key.v (), Value.v ()) in
Index.replace rw k1 v1;
let t = Index.try_merge_aux ~force:true ~hook rw in
Index.await t |> check_completed
in
let f msg b () = Alcotest.(check bool) msg (Index.is_merging rw) b in
f "before merge" false ();
add_binding_and_merge ~hook:(before (f "before" true));
f "between merge" false ();
add_binding_and_merge ~hook:(after (f "after" true));
add_binding_and_merge ~hook:(after_clear (f "after clear" true))
let add_bindings index =
let k1, v1 = (Key.v (), Value.v ()) in
Index.replace index k1 v1
let test_non_blocking_clear () =
let* Context.{ rw; _ } = Context.with_empty_index () in
let merge_started = Semaphore.make false and merge = Semaphore.make false in
let merge_hook =
Hook.v @@ function
| `Before ->
Semaphore.release merge_started;
Semaphore.acquire merge
| `After -> Alcotest.fail "Merge should have been aborted by clear"
| _ -> ()
in
let clear_hook =
Hook.v @@ function
| `Abort_signalled -> Semaphore.release merge
| `IO_clear -> ()
in
add_bindings rw;
let thread = Index.try_merge_aux ~force:true ~hook:merge_hook rw in
Semaphore.acquire merge_started;
add_bindings rw;
Index.clear' ~hook:clear_hook rw;
match Index.await thread with
| Ok `Aborted -> ()
| _ -> Alcotest.fail "merge should have aborted"
* The test consists of aborting a first merge after one entry is added in the
./merge file and checking that a second merge succeeds . Regression test for
PR 211 in which the second merge was triggering an assert failure .
./merge file and checking that a second merge succeeds. Regression test for
PR 211 in which the second merge was triggering an assert failure. *)
let test_abort_merge ~abort_merge () =
let* { Context.rw; clone; _ } = Context.with_full_index () in
let merge_started = Semaphore.make false and merge = Semaphore.make false in
let merge_hook =
Hook.v @@ function
| `After_first_entry ->
Semaphore.release merge_started;
Semaphore.acquire merge
| `After | `After_clear ->
Alcotest.fail "Merge should have been aborted by clear"
| `Before -> ()
in
let abort_hook =
Hook.v @@ function
| `Abort_signalled -> Semaphore.release merge
| `IO_clear -> ()
in
let t = Index.try_merge_aux ~force:true ~hook:merge_hook rw in
Semaphore.acquire merge_started;
abort_merge ~hook:abort_hook rw;
(match Index.await t with
| Ok `Aborted -> ()
| _ -> Alcotest.fail "Merge should have aborted");
let rw = clone ~readonly:false ~fresh:false () in
add_bindings rw;
let t = Index.try_merge_aux ~force:true rw in
Index.await t |> check_completed
let test_clear_aborts_merge = test_abort_merge ~abort_merge:Index.clear'
let test_close_immediately_aborts_merge =
test_abort_merge ~abort_merge:(Index.close' ~immediately:())
let tests =
[
("readonly in sequence", `Quick, readonly_s);
("readonly interleaved", `Quick, readonly);
("interleaved merge", `Quick, readonly_and_merge);
("write at the end of merge", `Quick, write_after_merge);
("write in log_async", `Quick, replace_while_merge);
("find while merging", `Quick, find_while_merge);
("find in async without log", `Quick, find_in_async_generation_change);
("find in async with log", `Quick, find_in_async_same_generation);
( "sync before and after clearing the async",
`Quick,
sync_before_and_after_clearing_async );
("sync and find after log cleared", `Quick, sync_after_clear_log);
("merge during ro sync", `Quick, merge_during_sync);
("is_merging", `Quick, test_is_merging);
("clear is not blocking", `Quick, test_non_blocking_clear);
("`clear` aborts merge", `Quick, test_clear_aborts_merge);
( "`close ~immediately` aborts merge",
`Quick,
test_close_immediately_aborts_merge );
]
|
04e53892d26a6bf08535f84e45408d134693522e1d144df767349ea7063d31d6 | chenyukang/eopl | lang.scm | ;;;;;;;;;;;;;;;; grammatical specification ;;;;;;;;;;;;;;;;
(define the-lexical-spec
'((whitespace (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier
(letter (arbno (or letter digit "_" "-" "?")))
symbol)
(number (digit (arbno digit)) number)
(number ("-" digit (arbno digit)) number)
))
(define the-grammar
'((program (expression) a-program)
(expression (number) const-exp)
(expression
("-" "(" expression "," expression ")")
diff-exp)
(expression
("zero?" "(" expression ")")
zero?-exp)
(expression
("if" expression "then" expression "else" expression)
if-exp)
(expression (identifier) var-exp)
(expression
("let" identifier "=" expression "in" expression)
let-exp)
))
;;;;;;;;;;;;;;;; sllgen boilerplate ;;;;;;;;;;;;;;;;
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define show-the-datatypes
(lambda () (sllgen:list-define-datatypes the-lexical-spec the-grammar)))
(define scan&parse
(sllgen:make-string-parser the-lexical-spec the-grammar))
(define just-scan
(sllgen:make-string-scanner the-lexical-spec the-grammar))
| null | https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/base/chapter3/let-lang/lang.scm | scheme | grammatical specification ;;;;;;;;;;;;;;;;
sllgen boilerplate ;;;;;;;;;;;;;;;;
|
(define the-lexical-spec
'((whitespace (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier
(letter (arbno (or letter digit "_" "-" "?")))
symbol)
(number (digit (arbno digit)) number)
(number ("-" digit (arbno digit)) number)
))
(define the-grammar
'((program (expression) a-program)
(expression (number) const-exp)
(expression
("-" "(" expression "," expression ")")
diff-exp)
(expression
("zero?" "(" expression ")")
zero?-exp)
(expression
("if" expression "then" expression "else" expression)
if-exp)
(expression (identifier) var-exp)
(expression
("let" identifier "=" expression "in" expression)
let-exp)
))
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define show-the-datatypes
(lambda () (sllgen:list-define-datatypes the-lexical-spec the-grammar)))
(define scan&parse
(sllgen:make-string-parser the-lexical-spec the-grammar))
(define just-scan
(sllgen:make-string-scanner the-lexical-spec the-grammar))
|
8f9503c16589512499be8a0e428850a8b36bb52185bda68c6335897000fbe7d9 | lukstafi/invargent | NumS.mli | * Numeric sort operations for InvarGenT.
Released under the GNU General Public Licence ( version 2 or
higher ) , NO WARRANTY of correctness etc . ( C ) 2013
@author ( AT ) gmail.com
@since Mar 2013
Released under the GNU General Public Licence (version 2 or
higher), NO WARRANTY of correctness etc. (C) Lukasz Stafiniak 2013
@author Lukasz Stafiniak lukstafi (AT) gmail.com
@since Mar 2013
*)
* Try four times as many linear combinations ( k,-k,1 / k,-1 / k ) .
val abd_rotations : int ref
(** Start abduction on all branches rather than only non-recursive. *)
val early_num_abduction : bool ref
* Keep less than N elements in abduction sums ( default < 6 ) .
val abd_prune_at : int ref
val abd_timeout_count : int ref
val abd_fail_timeout_count : int ref
(** Treat the numerical domain as integers when pruning
formulas. Default [true]. *)
val int_pruning : bool ref
(** When pruning, discard constraints that force a variable to a
single value. Default [false]. *)
val strong_int_pruning : bool ref
val passing_ineq_trs : bool ref
(** Do not create subopti atoms of the form [k<=max(C,..)] etc. where
[C] is a constant (default true). *)
val subopti_of_cst : [`No_sides | `Left_side | `Both_sides] ref
(** Replace variable=constant equations by variable=variable equations
in initial abduction candidates to promote generality of
answers. Default [true]. *)
val revert_csts : bool ref
* How much to penalize an abduction candidate inequality for
belonging to some formula in the discard list . Default [ 2 ] .
belonging to some formula in the discard list. Default [2]. *)
val discard_penalty : int ref
* How much to penalize an abduction candidate inequality for
containing a constant term . Default [ 4 ] .
containing a constant term. Default [4]. *)
val affine_penalty : int ref
* How much to reward introducing a constraint on so - far
unconstrained varialbe ( or penalize , if negative ) . Default [ 2 ] .
unconstrained varialbe (or penalize, if negative). Default [2]. *)
val reward_constrn : int ref
* How much to penalize for complexity ; the coefficient $ a$ in the
description of { ! complexity_scale } . Default [ 2.5 ] .
description of {!complexity_scale}. Default [2.5]. *)
val complexity_penalty : float ref
* How much to penalize for variables that are not parameters but
instead instances from use sites of existential types . Default [ 6 ] .
instead instances from use sites of existential types. Default [6]. *)
val nonparam_vars_penalty : int ref
* Prefer bound coming from outer scope , to inequality between two
local parameters . Default [ false ] .
local parameters. Default [false]. *)
val prefer_bound_to_local : bool ref
* Prefer a bound coming from outer scope , to inequality between two
outer scope parameters . Default [ false ] .
outer scope parameters. Default [false]. *)
val prefer_bound_to_outer : bool ref
* Limit the effect of [ prefer_bound_to_local ] and
[ ] to inequalities with a constant 1 . This
corresponds to an upper bound of zero - indexed array / matrix / etc .
[prefer_bound_to_outer] to inequalities with a constant 1. This
corresponds to an upper bound of zero-indexed array/matrix/etc. *)
val only_off_by_1 : bool ref
* Penalize abductive guess when the supporting argument comes from
the partial answer , instead of from the current premise . Default [ 4 ] .
the partial answer, instead of from the current premise. Default [4]. *)
val concl_abd_penalty : int ref
(** Filter out less general abduction candidate atoms (does not
guarantee overall more general answers). Default [false]. *)
val more_general : bool ref
* How to scale coefficients when computing complexity : either by
raising to the given power i.e. [ a*k^b ] , or by linear scaling with
a jump at the given threshold with the given height
i.e. $ a*k + a*1_{b<=k}$. Default [ ` LinThres ( 2 , 2.0 ) ] .
raising to the given power i.e. [a*k^b], or by linear scaling with
a jump at the given threshold with the given height
i.e. $a*k + a*1_{b<=k}$. Default [`LinThres (2, 2.0)]. *)
val complexity_scale : [`LinThres of float * float | `Pow of float] ref
(** Twice as many angles of rotation are tried out for *)
val disjelim_rotations : int ref
(** How many opti atoms: [x = min(a, b)], [x = max(a, b)] in a
postcondition. *)
val max_opti_postcond : int ref
(** How many subopti atoms: [min(a, b) <= x], [x <= max(a, b)] in a
postcondition. *)
val max_subopti_postcond : int ref
(* TODO: export more knobs, i.e. global reference variables; also add their
command-line interfaces in [InvarGenT.main]. *)
val num_of : Terms.typ -> NumDefs.term
val sort_formula : Terms.formula -> NumDefs.formula
val formula_of_sort : NumDefs.formula -> Terms.formula
val sort_of_assoc :
(Defs.var_name * (Terms.typ * Defs.loc)) list -> NumDefs.formula
val sort_of_subst : Terms.subst -> NumDefs.formula
type subst = (NumDefs.term * Defs.loc) Defs.VarMap.t
val subst_num_formula : subst -> NumDefs.formula -> NumDefs.formula
val subst_formula : Terms.subst -> NumDefs.formula -> NumDefs.formula
val abd_fail_flag : bool ref
val abd_timeout_flag : bool ref
(** For uniformity, return an empty list as introduced
variables. Raise [Contradiction] if constraints are contradictory
and [Suspect] if no answer can be found. *)
val abd :
Defs.quant_ops ->
bvs:Defs.VarSet.t ->
xbvs:(int * Defs.VarSet.t) list ->
?orig_ren:(Defs.var_name, Defs.var_name) Hashtbl.t ->
?b_of_v:(Defs.var_name -> Defs.var_name) ->
upward_of:(Defs.var_name -> Defs.var_name -> bool) ->
nonparam_vars:Defs.VarSet.t ->
discard:NumDefs.formula list ->
?iter_no:int ->
(bool * (int * Terms.hvsubst) list *
NumDefs.formula * NumDefs.formula) list ->
Defs.var_name list * NumDefs.formula
(** For uniformity, we return an empty list as introduced variables. *)
val disjelim :
Defs.quant_ops -> target_vs:Defs.VarSet.t -> preserve:Defs.VarSet.t ->
bvs:Defs.VarSet.t -> param_bvs:Defs.VarSet.t ->
guess:bool -> initstep:bool ->
(NumDefs.formula * NumDefs.formula) list ->
Defs.var_name list * NumDefs.formula * NumDefs.formula *
NumDefs.formula list
(** Eliminate provided variables from the substitution part of solved
form and generally simplify the formula, but do not perform
quantifier elimination -- preserve those variables that are not
equal to something else. *)
val simplify :
Defs.quant_ops ->
?keepvs:Defs.VarSet.t -> ?localvs:Defs.VarSet.t -> ?guard:NumDefs.formula ->
Defs.VarSet.t -> NumDefs.formula ->
Defs.var_name list * NumDefs.formula
(** Prune atoms implied by other atoms -- for efficiency, only single
other atoms, i.e. "atom-on-atom", are considered. Prefer other
atoms over opti atoms. *)
val prune_redundant :
Defs.quant_ops -> ?localvs:Defs.VarSet.t ->
?guard:NumDefs.formula ->
initstep:bool ->
NumDefs.formula -> NumDefs.formula
* Intersect atoms of the formulas , but only after generating
consequences via Fourier elimination and turning equations into
pairs of inequalities .
consequences via Fourier elimination and turning equations into
pairs of inequalities. *)
val converge :
Defs.quant_ops -> ?localvs:Defs.VarSet.t -> ?guard:NumDefs.formula ->
initstep:bool ->
NumDefs.formula -> NumDefs.formula -> NumDefs.formula
type state
val empty_state : state
val formula_of_state : state -> NumDefs.formula
val num_to_formula : NumDefs.formula -> Terms.formula
val pr_state : Format.formatter -> state -> unit
val satisfiable :
?state:state -> NumDefs.formula -> (exn, state) Aux.choice
val satisfiable_exn : ?state:state -> NumDefs.formula -> state
States computed by [ satisfiable ] should be used , to match the variable
ordering .
ordering. *)
val implies_cnj : state -> NumDefs.formula -> bool
* Incremental check whether |= Raises [ Contradiction ] .
val holds :
Defs.quant_ops -> Defs.VarSet.t ->
state -> NumDefs.formula -> state
* Incremental check whether |= Collects implied formulas that
would not hold if the given parameters were universally quantified .
Raises [ Contradiction ] .
would not hold if the given parameters were universally quantified.
Raises [Contradiction]. *)
val abductive_holds :
Defs.quant_ops -> bvs:Defs.VarSet.t ->
state -> NumDefs.formula -> state * NumDefs.formula
val negation_elim :
Defs.quant_ops -> bvs:Defs.VarSet.t ->
verif_cns:state list ->
(NumDefs.formula * Defs.loc) list ->
NumDefs.formula
val separate_subst :
Defs.quant_ops -> ?no_csts:bool -> ?keep:Defs.VarSet.t ->
?bvs:Defs.VarSet.t -> apply:bool -> NumDefs.formula ->
Terms.subst * NumDefs.term Defs.VarMap.t * NumDefs.formula
val transitive_cl : Defs.quant_ops -> NumDefs.formula -> NumDefs.formula
| null | https://raw.githubusercontent.com/lukstafi/invargent/e25d8b12d9f9a8e2d5269001dd14cf93abcb7549/src/NumS.mli | ocaml | * Start abduction on all branches rather than only non-recursive.
* Treat the numerical domain as integers when pruning
formulas. Default [true].
* When pruning, discard constraints that force a variable to a
single value. Default [false].
* Do not create subopti atoms of the form [k<=max(C,..)] etc. where
[C] is a constant (default true).
* Replace variable=constant equations by variable=variable equations
in initial abduction candidates to promote generality of
answers. Default [true].
* Filter out less general abduction candidate atoms (does not
guarantee overall more general answers). Default [false].
* Twice as many angles of rotation are tried out for
* How many opti atoms: [x = min(a, b)], [x = max(a, b)] in a
postcondition.
* How many subopti atoms: [min(a, b) <= x], [x <= max(a, b)] in a
postcondition.
TODO: export more knobs, i.e. global reference variables; also add their
command-line interfaces in [InvarGenT.main].
* For uniformity, return an empty list as introduced
variables. Raise [Contradiction] if constraints are contradictory
and [Suspect] if no answer can be found.
* For uniformity, we return an empty list as introduced variables.
* Eliminate provided variables from the substitution part of solved
form and generally simplify the formula, but do not perform
quantifier elimination -- preserve those variables that are not
equal to something else.
* Prune atoms implied by other atoms -- for efficiency, only single
other atoms, i.e. "atom-on-atom", are considered. Prefer other
atoms over opti atoms. | * Numeric sort operations for InvarGenT.
Released under the GNU General Public Licence ( version 2 or
higher ) , NO WARRANTY of correctness etc . ( C ) 2013
@author ( AT ) gmail.com
@since Mar 2013
Released under the GNU General Public Licence (version 2 or
higher), NO WARRANTY of correctness etc. (C) Lukasz Stafiniak 2013
@author Lukasz Stafiniak lukstafi (AT) gmail.com
@since Mar 2013
*)
* Try four times as many linear combinations ( k,-k,1 / k,-1 / k ) .
val abd_rotations : int ref
val early_num_abduction : bool ref
* Keep less than N elements in abduction sums ( default < 6 ) .
val abd_prune_at : int ref
val abd_timeout_count : int ref
val abd_fail_timeout_count : int ref
val int_pruning : bool ref
val strong_int_pruning : bool ref
val passing_ineq_trs : bool ref
val subopti_of_cst : [`No_sides | `Left_side | `Both_sides] ref
val revert_csts : bool ref
* How much to penalize an abduction candidate inequality for
belonging to some formula in the discard list . Default [ 2 ] .
belonging to some formula in the discard list. Default [2]. *)
val discard_penalty : int ref
* How much to penalize an abduction candidate inequality for
containing a constant term . Default [ 4 ] .
containing a constant term. Default [4]. *)
val affine_penalty : int ref
* How much to reward introducing a constraint on so - far
unconstrained varialbe ( or penalize , if negative ) . Default [ 2 ] .
unconstrained varialbe (or penalize, if negative). Default [2]. *)
val reward_constrn : int ref
* How much to penalize for complexity ; the coefficient $ a$ in the
description of { ! complexity_scale } . Default [ 2.5 ] .
description of {!complexity_scale}. Default [2.5]. *)
val complexity_penalty : float ref
* How much to penalize for variables that are not parameters but
instead instances from use sites of existential types . Default [ 6 ] .
instead instances from use sites of existential types. Default [6]. *)
val nonparam_vars_penalty : int ref
* Prefer bound coming from outer scope , to inequality between two
local parameters . Default [ false ] .
local parameters. Default [false]. *)
val prefer_bound_to_local : bool ref
* Prefer a bound coming from outer scope , to inequality between two
outer scope parameters . Default [ false ] .
outer scope parameters. Default [false]. *)
val prefer_bound_to_outer : bool ref
* Limit the effect of [ prefer_bound_to_local ] and
[ ] to inequalities with a constant 1 . This
corresponds to an upper bound of zero - indexed array / matrix / etc .
[prefer_bound_to_outer] to inequalities with a constant 1. This
corresponds to an upper bound of zero-indexed array/matrix/etc. *)
val only_off_by_1 : bool ref
* Penalize abductive guess when the supporting argument comes from
the partial answer , instead of from the current premise . Default [ 4 ] .
the partial answer, instead of from the current premise. Default [4]. *)
val concl_abd_penalty : int ref
val more_general : bool ref
* How to scale coefficients when computing complexity : either by
raising to the given power i.e. [ a*k^b ] , or by linear scaling with
a jump at the given threshold with the given height
i.e. $ a*k + a*1_{b<=k}$. Default [ ` LinThres ( 2 , 2.0 ) ] .
raising to the given power i.e. [a*k^b], or by linear scaling with
a jump at the given threshold with the given height
i.e. $a*k + a*1_{b<=k}$. Default [`LinThres (2, 2.0)]. *)
val complexity_scale : [`LinThres of float * float | `Pow of float] ref
val disjelim_rotations : int ref
val max_opti_postcond : int ref
val max_subopti_postcond : int ref
val num_of : Terms.typ -> NumDefs.term
val sort_formula : Terms.formula -> NumDefs.formula
val formula_of_sort : NumDefs.formula -> Terms.formula
val sort_of_assoc :
(Defs.var_name * (Terms.typ * Defs.loc)) list -> NumDefs.formula
val sort_of_subst : Terms.subst -> NumDefs.formula
type subst = (NumDefs.term * Defs.loc) Defs.VarMap.t
val subst_num_formula : subst -> NumDefs.formula -> NumDefs.formula
val subst_formula : Terms.subst -> NumDefs.formula -> NumDefs.formula
val abd_fail_flag : bool ref
val abd_timeout_flag : bool ref
val abd :
Defs.quant_ops ->
bvs:Defs.VarSet.t ->
xbvs:(int * Defs.VarSet.t) list ->
?orig_ren:(Defs.var_name, Defs.var_name) Hashtbl.t ->
?b_of_v:(Defs.var_name -> Defs.var_name) ->
upward_of:(Defs.var_name -> Defs.var_name -> bool) ->
nonparam_vars:Defs.VarSet.t ->
discard:NumDefs.formula list ->
?iter_no:int ->
(bool * (int * Terms.hvsubst) list *
NumDefs.formula * NumDefs.formula) list ->
Defs.var_name list * NumDefs.formula
val disjelim :
Defs.quant_ops -> target_vs:Defs.VarSet.t -> preserve:Defs.VarSet.t ->
bvs:Defs.VarSet.t -> param_bvs:Defs.VarSet.t ->
guess:bool -> initstep:bool ->
(NumDefs.formula * NumDefs.formula) list ->
Defs.var_name list * NumDefs.formula * NumDefs.formula *
NumDefs.formula list
val simplify :
Defs.quant_ops ->
?keepvs:Defs.VarSet.t -> ?localvs:Defs.VarSet.t -> ?guard:NumDefs.formula ->
Defs.VarSet.t -> NumDefs.formula ->
Defs.var_name list * NumDefs.formula
val prune_redundant :
Defs.quant_ops -> ?localvs:Defs.VarSet.t ->
?guard:NumDefs.formula ->
initstep:bool ->
NumDefs.formula -> NumDefs.formula
* Intersect atoms of the formulas , but only after generating
consequences via Fourier elimination and turning equations into
pairs of inequalities .
consequences via Fourier elimination and turning equations into
pairs of inequalities. *)
val converge :
Defs.quant_ops -> ?localvs:Defs.VarSet.t -> ?guard:NumDefs.formula ->
initstep:bool ->
NumDefs.formula -> NumDefs.formula -> NumDefs.formula
type state
val empty_state : state
val formula_of_state : state -> NumDefs.formula
val num_to_formula : NumDefs.formula -> Terms.formula
val pr_state : Format.formatter -> state -> unit
val satisfiable :
?state:state -> NumDefs.formula -> (exn, state) Aux.choice
val satisfiable_exn : ?state:state -> NumDefs.formula -> state
States computed by [ satisfiable ] should be used , to match the variable
ordering .
ordering. *)
val implies_cnj : state -> NumDefs.formula -> bool
* Incremental check whether |= Raises [ Contradiction ] .
val holds :
Defs.quant_ops -> Defs.VarSet.t ->
state -> NumDefs.formula -> state
* Incremental check whether |= Collects implied formulas that
would not hold if the given parameters were universally quantified .
Raises [ Contradiction ] .
would not hold if the given parameters were universally quantified.
Raises [Contradiction]. *)
val abductive_holds :
Defs.quant_ops -> bvs:Defs.VarSet.t ->
state -> NumDefs.formula -> state * NumDefs.formula
val negation_elim :
Defs.quant_ops -> bvs:Defs.VarSet.t ->
verif_cns:state list ->
(NumDefs.formula * Defs.loc) list ->
NumDefs.formula
val separate_subst :
Defs.quant_ops -> ?no_csts:bool -> ?keep:Defs.VarSet.t ->
?bvs:Defs.VarSet.t -> apply:bool -> NumDefs.formula ->
Terms.subst * NumDefs.term Defs.VarMap.t * NumDefs.formula
val transitive_cl : Defs.quant_ops -> NumDefs.formula -> NumDefs.formula
|
5bb6b35d4c97394a3b90e0746c6e7f13e23dbe5682bee672620c5f521b05d983 | plumatic/plumbing | lazymap.clj | ;-
Copyright 2008 - 2011 ( c ) Meikel Brandmeyer .
; All rights reserved.
;
; 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.
from
by JW on 11/17/2011 , and slightly modified to fix a bug in .entryAt and add a safety check .
;; Also replaced 'force' with 'deref' so this can be used with futures (with marginal utility).
;; (our pull request with these changes has been been ignored, so we've just included
;; this fixed file in plumbing for the time being).
;; Known Issues: LazyMapEntries are not equal to persistent vectors like ordinary map entries.
(ns plumbing.lazymap
"Lazymap is to maps what lazy-seq is to lists. It allows to store values
with evaluating them. This is only done in case the value is really accessed.
Lazymap works with any map type (hash-map, sorted-map, struct-map) and may
be used as a drop-in replacement everywhere where a normal map type may be
used.
Available macros:
lazy-hash-map, lazy-sorted-map, lazy-struct-map, lazy-struct, lazy-assoc
and their * counterpart functions."
(:import
clojure.lang.IObj
clojure.lang.IFn
clojure.lang.ILookup
clojure.lang.IMapEntry
clojure.lang.IPersistentMap
clojure.lang.IPersistentVector
clojure.lang.ASeq
clojure.lang.ISeq
clojure.lang.Seqable
clojure.lang.SeqIterator))
(defprotocol ILazyMapEntry
"ILazyMapEntry describes the behaviour of a lazy MapEntry. It provides
an additional method (over IMapEntry), which returns the raw delay object
and not the forced value."
(get-key [lazy-map-entry] "Return the key of the map entry.")
(get-raw-value [lazy-map-entry] "Return the underlying delay object."))
Extend the IMapEntry interface to act also like ILazyMapEntry .
For a IMapEntry get - raw - value just returns the given value as
wrapped in a delay . Similar a vector of two elements might be
used in place of a IMapEntry .
(extend-protocol ILazyMapEntry
IMapEntry
(get-key [#^IMapEntry this] (.getKey this))
(get-raw-value [#^IMapEntry this] (let [v (.getValue this)] (delay v)))
IPersistentVector
(get-key [this]
(when-not (= (count this) 2)
(throw (IllegalArgumentException.
"Vector used as IMapEntry must be a pair")))
(this 0))
(get-raw-value
[this]
(when-not (= (count this) 2)
(throw (IllegalArgumentException.
"Vector used as IMapEntry must be a pair")))
(let [v (this 1)]
(delay v))))
(defprotocol ILazyPersistentMap
"ILazyPersistentMap extends IPersistentMap with a method to allow
transportation of the underlying delay objects."
(delay-assoc [lazy-map key delay] "Associates the given delay in the map."))
(deftype LazyMapEntry [k v]
ILazyMapEntry
(get-key [_] k)
(get-raw-value [_] v)
IMapEntry
(key [_] k)
(getKey [_] k)
(val [_] (deref v))
(getValue [_] (deref v))
Object
(toString [_] (str \[ (pr-str k) \space (pr-str (deref v)) \])))
(defmethod print-method LazyMapEntry
[this #^java.io.Writer w]
(.write w (str this)))
(defn create-lazy-map-seq
([inner-seq]
(create-lazy-map-seq inner-seq nil))
([inner-seq metadata]
(proxy [ASeq] [metadata]
; ISeq
(first []
(let [first-val (first inner-seq)]
(LazyMapEntry. (key first-val) (val first-val))))
(next []
(when-let [inner-rest (next inner-seq)]
(create-lazy-map-seq inner-rest metadata)))
(more [] (lazy-seq (next this))))))
(declare create-lazy-map)
(deftype LazyPersistentMap
[base metadata]
ILazyPersistentMap
(delay-assoc [this k v] (create-lazy-map (assoc base k v) metadata))
IPersistentMap
(assoc [this k v] (create-lazy-map (assoc base k (delay v)) metadata))
(assocEx
[this k v]
(when (contains? base k)
(throw (Exception. (str "Key already present in map: " k))))
(.assoc this k v))
(without [this k] (create-lazy-map (dissoc base k) metadata))
Associative
(containsKey [this k] (contains? base k))
(entryAt [this k] (when-let [v (base k)] (LazyMapEntry. k v)))
; IPersistentCollection
(count [this] (count base))
(cons
[this o]
(if (satisfies? ILazyMapEntry o)
(delay-assoc this (get-key o) (get-raw-value o))
(into this o)))
(empty [this] (create-lazy-map (empty base) nil))
ILookup
(valAt [this k] (.valAt this k nil))
(valAt
[this k not-found]
(if (contains? base k)
(-> base (get k) deref)
not-found))
IFn
(invoke [this k] (.valAt this k nil))
(invoke [this k not-found] (.valAt this k not-found))
(applyTo
[this args]
(let [[k v & rest-args :as args] (seq args)]
(when (or (not args) rest-args)
(throw (Exception. "lazy map must be called with one or two arguments")))
(.valAt this k v)))
Seqable
(seq
[this]
(when-let [inner-seq (seq base)]
(create-lazy-map-seq inner-seq)))
IObj
(withMeta [this new-metadata] (create-lazy-map base new-metadata))
IMeta
(meta [this] metadata)
Iterable
(iterator [this] (-> this .seq SeqIterator.)))
(defn create-lazy-map
([base]
(create-lazy-map base nil))
([base metadata]
(LazyPersistentMap. base metadata)))
(defn- quote-values
[kvs]
(assert (even? (count kvs)))
(mapcat (fn [[k v]] [k `(delay ~v)]) (partition 2 kvs)))
(defn lazy-assoc*
"lazy-assoc* is like lazy-assoc but a function and takes values as delays
instead of expanding into a delay of val."
[m & kvs]
(assert (even? (count kvs)))
(reduce (fn [m [k v]] (delay-assoc m k v)) m (partition 2 kvs)))
(defmacro lazy-assoc
"lazy-assoc associates new values to the given keys in the given lazy map.
The values are not evaluated, before their first retrieval. They are
evaluated at most once."
[m & kvs]
`(lazy-assoc* ~m ~@(quote-values kvs)))
(defn lazy-hash-map*
"lazy-hash-map* is the same as lazy-hash-map except that its a function
and it takes a seq of keys-delayed-value pairs."
[& kvs]
(create-lazy-map (apply hash-map kvs)))
(defmacro lazy-hash-map
"lazy-hash-map creates a map. The values are not evaluated before their
first retrieval. Each value is evaluated at most once. The underlying map
is a hash map."
[& kvs]
`(lazy-hash-map* ~@(quote-values kvs)))
(defn lazy-sorted-map*
"lazy-sorted-map* is the same as lazy-sorted-map except that its a
function and it takes a seq of keys-delayed-value pairs."
[& kvs]
(create-lazy-map (apply sorted-map kvs)))
(defmacro lazy-sorted-map
"lazy-sorted-map creates a map. The values are not evaluated before their
first retrieval. Each value is evaluated at most once. The underlying map
is a sorted map."
[& kvs]
`(lazy-sorted-map* ~@(quote-values kvs)))
(defn lazy-struct-map*
"lazy-struct-map* is the same as lazy-struct-map except that its a
function and it takes a seq of keys-delayed-value pairs together with the
struct basis."
[s & kvs]
(create-lazy-map (apply struct-map s kvs)))
(defmacro lazy-struct-map
"lazy-struct-map creates a map. The values are not evaluated before their
first retrieval. Each value is evaluated at most once. The underlying map
is a struct map according to the provided structure s."
[s & kvs]
`(lazy-struct-map* ~s ~@(quote-values kvs)))
(defn lazy-struct*
"lazy-struct* is the same as lazy-struct except that its a function and
it takes a seq of delayed value together with the struct basis."
[s & vs]
(create-lazy-map (apply struct s vs)))
(defmacro lazy-struct
"lazy-struct creates a map. The values are not evaluated before their
first retrieval. Each value is evaluated at most once. The underlying map
is a struct map according to the provided structure s. As with Clojure's
struct the values have to appear in the order of the keys in the structure."
[s & vs]
(let [vs (map (fn [v] `(delay ~v)) vs)]
`(lazy-struct* ~s ~@vs))) | null | https://raw.githubusercontent.com/plumatic/plumbing/e6f99d8f50789633559eb637df3362ed5f129035/src/plumbing/lazymap.clj | clojure | -
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Also replaced 'force' with 'deref' so this can be used with futures (with marginal utility).
(our pull request with these changes has been been ignored, so we've just included
this fixed file in plumbing for the time being).
Known Issues: LazyMapEntries are not equal to persistent vectors like ordinary map entries.
ISeq
IPersistentCollection | Copyright 2008 - 2011 ( c ) Meikel Brandmeyer .
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
from
by JW on 11/17/2011 , and slightly modified to fix a bug in .entryAt and add a safety check .
(ns plumbing.lazymap
"Lazymap is to maps what lazy-seq is to lists. It allows to store values
with evaluating them. This is only done in case the value is really accessed.
Lazymap works with any map type (hash-map, sorted-map, struct-map) and may
be used as a drop-in replacement everywhere where a normal map type may be
used.
Available macros:
lazy-hash-map, lazy-sorted-map, lazy-struct-map, lazy-struct, lazy-assoc
and their * counterpart functions."
(:import
clojure.lang.IObj
clojure.lang.IFn
clojure.lang.ILookup
clojure.lang.IMapEntry
clojure.lang.IPersistentMap
clojure.lang.IPersistentVector
clojure.lang.ASeq
clojure.lang.ISeq
clojure.lang.Seqable
clojure.lang.SeqIterator))
(defprotocol ILazyMapEntry
"ILazyMapEntry describes the behaviour of a lazy MapEntry. It provides
an additional method (over IMapEntry), which returns the raw delay object
and not the forced value."
(get-key [lazy-map-entry] "Return the key of the map entry.")
(get-raw-value [lazy-map-entry] "Return the underlying delay object."))
Extend the IMapEntry interface to act also like ILazyMapEntry .
For a IMapEntry get - raw - value just returns the given value as
wrapped in a delay . Similar a vector of two elements might be
used in place of a IMapEntry .
(extend-protocol ILazyMapEntry
IMapEntry
(get-key [#^IMapEntry this] (.getKey this))
(get-raw-value [#^IMapEntry this] (let [v (.getValue this)] (delay v)))
IPersistentVector
(get-key [this]
(when-not (= (count this) 2)
(throw (IllegalArgumentException.
"Vector used as IMapEntry must be a pair")))
(this 0))
(get-raw-value
[this]
(when-not (= (count this) 2)
(throw (IllegalArgumentException.
"Vector used as IMapEntry must be a pair")))
(let [v (this 1)]
(delay v))))
(defprotocol ILazyPersistentMap
"ILazyPersistentMap extends IPersistentMap with a method to allow
transportation of the underlying delay objects."
(delay-assoc [lazy-map key delay] "Associates the given delay in the map."))
(deftype LazyMapEntry [k v]
ILazyMapEntry
(get-key [_] k)
(get-raw-value [_] v)
IMapEntry
(key [_] k)
(getKey [_] k)
(val [_] (deref v))
(getValue [_] (deref v))
Object
(toString [_] (str \[ (pr-str k) \space (pr-str (deref v)) \])))
(defmethod print-method LazyMapEntry
[this #^java.io.Writer w]
(.write w (str this)))
(defn create-lazy-map-seq
([inner-seq]
(create-lazy-map-seq inner-seq nil))
([inner-seq metadata]
(proxy [ASeq] [metadata]
(first []
(let [first-val (first inner-seq)]
(LazyMapEntry. (key first-val) (val first-val))))
(next []
(when-let [inner-rest (next inner-seq)]
(create-lazy-map-seq inner-rest metadata)))
(more [] (lazy-seq (next this))))))
(declare create-lazy-map)
(deftype LazyPersistentMap
[base metadata]
ILazyPersistentMap
(delay-assoc [this k v] (create-lazy-map (assoc base k v) metadata))
IPersistentMap
(assoc [this k v] (create-lazy-map (assoc base k (delay v)) metadata))
(assocEx
[this k v]
(when (contains? base k)
(throw (Exception. (str "Key already present in map: " k))))
(.assoc this k v))
(without [this k] (create-lazy-map (dissoc base k) metadata))
Associative
(containsKey [this k] (contains? base k))
(entryAt [this k] (when-let [v (base k)] (LazyMapEntry. k v)))
(count [this] (count base))
(cons
[this o]
(if (satisfies? ILazyMapEntry o)
(delay-assoc this (get-key o) (get-raw-value o))
(into this o)))
(empty [this] (create-lazy-map (empty base) nil))
ILookup
(valAt [this k] (.valAt this k nil))
(valAt
[this k not-found]
(if (contains? base k)
(-> base (get k) deref)
not-found))
IFn
(invoke [this k] (.valAt this k nil))
(invoke [this k not-found] (.valAt this k not-found))
(applyTo
[this args]
(let [[k v & rest-args :as args] (seq args)]
(when (or (not args) rest-args)
(throw (Exception. "lazy map must be called with one or two arguments")))
(.valAt this k v)))
Seqable
(seq
[this]
(when-let [inner-seq (seq base)]
(create-lazy-map-seq inner-seq)))
IObj
(withMeta [this new-metadata] (create-lazy-map base new-metadata))
IMeta
(meta [this] metadata)
Iterable
(iterator [this] (-> this .seq SeqIterator.)))
(defn create-lazy-map
([base]
(create-lazy-map base nil))
([base metadata]
(LazyPersistentMap. base metadata)))
(defn- quote-values
[kvs]
(assert (even? (count kvs)))
(mapcat (fn [[k v]] [k `(delay ~v)]) (partition 2 kvs)))
(defn lazy-assoc*
"lazy-assoc* is like lazy-assoc but a function and takes values as delays
instead of expanding into a delay of val."
[m & kvs]
(assert (even? (count kvs)))
(reduce (fn [m [k v]] (delay-assoc m k v)) m (partition 2 kvs)))
(defmacro lazy-assoc
"lazy-assoc associates new values to the given keys in the given lazy map.
The values are not evaluated, before their first retrieval. They are
evaluated at most once."
[m & kvs]
`(lazy-assoc* ~m ~@(quote-values kvs)))
(defn lazy-hash-map*
"lazy-hash-map* is the same as lazy-hash-map except that its a function
and it takes a seq of keys-delayed-value pairs."
[& kvs]
(create-lazy-map (apply hash-map kvs)))
(defmacro lazy-hash-map
"lazy-hash-map creates a map. The values are not evaluated before their
first retrieval. Each value is evaluated at most once. The underlying map
is a hash map."
[& kvs]
`(lazy-hash-map* ~@(quote-values kvs)))
(defn lazy-sorted-map*
"lazy-sorted-map* is the same as lazy-sorted-map except that its a
function and it takes a seq of keys-delayed-value pairs."
[& kvs]
(create-lazy-map (apply sorted-map kvs)))
(defmacro lazy-sorted-map
"lazy-sorted-map creates a map. The values are not evaluated before their
first retrieval. Each value is evaluated at most once. The underlying map
is a sorted map."
[& kvs]
`(lazy-sorted-map* ~@(quote-values kvs)))
(defn lazy-struct-map*
"lazy-struct-map* is the same as lazy-struct-map except that its a
function and it takes a seq of keys-delayed-value pairs together with the
struct basis."
[s & kvs]
(create-lazy-map (apply struct-map s kvs)))
(defmacro lazy-struct-map
"lazy-struct-map creates a map. The values are not evaluated before their
first retrieval. Each value is evaluated at most once. The underlying map
is a struct map according to the provided structure s."
[s & kvs]
`(lazy-struct-map* ~s ~@(quote-values kvs)))
(defn lazy-struct*
"lazy-struct* is the same as lazy-struct except that its a function and
it takes a seq of delayed value together with the struct basis."
[s & vs]
(create-lazy-map (apply struct s vs)))
(defmacro lazy-struct
"lazy-struct creates a map. The values are not evaluated before their
first retrieval. Each value is evaluated at most once. The underlying map
is a struct map according to the provided structure s. As with Clojure's
struct the values have to appear in the order of the keys in the structure."
[s & vs]
(let [vs (map (fn [v] `(delay ~v)) vs)]
`(lazy-struct* ~s ~@vs))) |
db12f52ae5cad319b5d5f707b379793a21e0f4ce8519b3033fd8a5da7a0f218b | lambdamikel/DLMAPS | timeout.lisp | ;;;-*- Mode: Lisp; Package: COMMON-LISP-USER -*-
(in-package :cl-user)
(defmacro with-timeout ((seconds . timeout-forms) &body body)
#+:ALLEGRO
`(mp:with-timeout (,seconds . ,timeout-forms)
,@body)
#+:MCL
`(with-timeout-1 ,seconds #'(lambda () ,@timeout-forms) #'(lambda () ,@body)))
(defmacro with-timeout ((seconds . timeout-forms) &body body)
#+:ALLEGRO
`(let ((timeout-fn #'(lambda () ,@timeout-forms)))
(unwind-protect
(restart-case
(mp:with-timeout (,seconds . (funcall timeout-fn))
,@body)
(abort-execution ()
:report
(lambda (stream)
(format stream "Abort execution as timeout"))
(funcall timeout-fn)))))
#+:MCL
`(with-timeout-1 ,seconds #'(lambda () ,@timeout-forms) #'(lambda () ,@body)))
#+:MCL
(defun with-timeout-1 (seconds timeout-fn body-fn)
(let* ((tag 'tag-1)
(current-process *current-process*)
(timeout-process
(process-run-function
(format nil "Timeout ~D" (round seconds))
#'(lambda ()
(sleep (round seconds))
(process-interrupt current-process
#'(lambda ()
(throw tag (funcall timeout-fn))))))))
(catch tag
(unwind-protect
(restart-case
(funcall body-fn)
(abort-execution ()
:report
(lambda (stream)
(format stream "Abort execution as timeout"))
(funcall timeout-fn)))
(process-kill timeout-process)))))
#+:ALLEGRO
(let ((elapsed-gc-time-user 0)
(elapsed-gc-time-system 0)
(elapsed-run-time-user 0)
(elapsed-run-time-system 0)
(elapsed-real-time 0)
(used-cons-cells 0)
(used-symbols 0)
(used-other-bytes 0))
(defun set-time-vars (pelapsed-gc-time-user
pelapsed-gc-time-system
pelapsed-run-time-user
pelapsed-run-time-system
pelapsed-real-time
pused-cons-cells
pused-symbols
pused-other-bytes)
(setf elapsed-gc-time-user pelapsed-gc-time-user)
(setf elapsed-gc-time-system pelapsed-gc-time-system)
(setf elapsed-run-time-user pelapsed-run-time-user)
(setf elapsed-run-time-system pelapsed-run-time-system)
(setf elapsed-real-time pelapsed-real-time)
(setf used-cons-cells pused-cons-cells)
(setf used-symbols pused-symbols)
(setf used-other-bytes pused-other-bytes))
(defun gctime ()
(+ elapsed-gc-time-user elapsed-gc-time-system))
(defun total-bytes-allocated ()
(+ (* 8 used-cons-cells) (* 64 used-symbols) used-other-bytes)))
#+:MCL
(defun total-bytes-allocated ()
(ccl::total-bytes-allocated))
(let (#+:mcl initial-gc-time #+:mcl initial-consed
initial-real-time initial-run-time)
#+:mcl
(defun with-timed-form (thunk)
(setf initial-gc-time (gctime))
(setf initial-consed (total-bytes-allocated))
(setf initial-real-time (get-internal-real-time))
(setf initial-run-time (get-internal-run-time))
(let* ((result (funcall thunk))
(elapsed-real-time (/ (- (get-internal-real-time) initial-real-time)
internal-time-units-per-second))
(elapsed-run-time (/ (- (get-internal-run-time) initial-run-time)
internal-time-units-per-second))
(elapsed-mf-time (max 0 (- elapsed-real-time elapsed-run-time)))
(elapsed-gc-time (/ (- (gctime) initial-gc-time)
internal-time-units-per-second))
(bytes-consed (- (total-bytes-allocated) initial-consed
(if (fixnump initial-consed) 0 16))))
(values result elapsed-run-time elapsed-real-time elapsed-mf-time
elapsed-gc-time bytes-consed)))
#+:ALLEGRO
(defun with-timed-form (thunk)
(setf initial-real-time (get-internal-real-time))
(setf initial-run-time (get-internal-run-time))
(let* ((result (excl::time-a-funcall thunk #'set-time-vars))
(elapsed-real-time (/ (- (get-internal-real-time) initial-real-time)
internal-time-units-per-second))
(elapsed-run-time (/ (- (get-internal-run-time) initial-run-time)
internal-time-units-per-second))
(elapsed-mf-time (max 0 (- elapsed-real-time elapsed-run-time)))
(elapsed-gc-time (/ (gctime) internal-time-units-per-second))
(bytes-consed (total-bytes-allocated)))
(values result elapsed-run-time elapsed-real-time elapsed-mf-time
elapsed-gc-time (abs bytes-consed))))
#+:mcl
(defun timed-out-handler ()
(let* ((elapsed-real-time (/ (- (get-internal-real-time) initial-real-time)
internal-time-units-per-second))
(elapsed-run-time (/ (- (get-internal-run-time) initial-run-time)
internal-time-units-per-second))
(elapsed-mf-time (max 0 (- elapsed-real-time elapsed-run-time)))
(elapsed-gc-time (/ (- (gctime) initial-gc-time)
internal-time-units-per-second))
(bytes-consed (- (total-bytes-allocated) initial-consed
(if (fixnump initial-consed) 0 16))))
(values '(?) elapsed-run-time elapsed-real-time elapsed-mf-time
elapsed-gc-time bytes-consed)))
#+:ALLEGRO
(defun timed-out-handler ()
(let* ((elapsed-real-time (/ (- (get-internal-real-time) initial-real-time)
internal-time-units-per-second))
(elapsed-run-time (/ (- (get-internal-run-time) initial-run-time)
internal-time-units-per-second))
(elapsed-mf-time (max 0 (- elapsed-real-time elapsed-run-time)))
(elapsed-gc-time (/ (gctime) internal-time-units-per-second))
(bytes-consed (total-bytes-allocated)))
(values '(?) elapsed-run-time elapsed-real-time elapsed-mf-time
elapsed-gc-time (abs bytes-consed)))))
| null | https://raw.githubusercontent.com/lambdamikel/DLMAPS/7f8dbb9432069d41e6a7d9c13dc5b25602ad35dc/src/prover/dl-benchmark-suite/timeout.lisp | lisp | -*- Mode: Lisp; Package: COMMON-LISP-USER -*- |
(in-package :cl-user)
(defmacro with-timeout ((seconds . timeout-forms) &body body)
#+:ALLEGRO
`(mp:with-timeout (,seconds . ,timeout-forms)
,@body)
#+:MCL
`(with-timeout-1 ,seconds #'(lambda () ,@timeout-forms) #'(lambda () ,@body)))
(defmacro with-timeout ((seconds . timeout-forms) &body body)
#+:ALLEGRO
`(let ((timeout-fn #'(lambda () ,@timeout-forms)))
(unwind-protect
(restart-case
(mp:with-timeout (,seconds . (funcall timeout-fn))
,@body)
(abort-execution ()
:report
(lambda (stream)
(format stream "Abort execution as timeout"))
(funcall timeout-fn)))))
#+:MCL
`(with-timeout-1 ,seconds #'(lambda () ,@timeout-forms) #'(lambda () ,@body)))
#+:MCL
(defun with-timeout-1 (seconds timeout-fn body-fn)
(let* ((tag 'tag-1)
(current-process *current-process*)
(timeout-process
(process-run-function
(format nil "Timeout ~D" (round seconds))
#'(lambda ()
(sleep (round seconds))
(process-interrupt current-process
#'(lambda ()
(throw tag (funcall timeout-fn))))))))
(catch tag
(unwind-protect
(restart-case
(funcall body-fn)
(abort-execution ()
:report
(lambda (stream)
(format stream "Abort execution as timeout"))
(funcall timeout-fn)))
(process-kill timeout-process)))))
#+:ALLEGRO
(let ((elapsed-gc-time-user 0)
(elapsed-gc-time-system 0)
(elapsed-run-time-user 0)
(elapsed-run-time-system 0)
(elapsed-real-time 0)
(used-cons-cells 0)
(used-symbols 0)
(used-other-bytes 0))
(defun set-time-vars (pelapsed-gc-time-user
pelapsed-gc-time-system
pelapsed-run-time-user
pelapsed-run-time-system
pelapsed-real-time
pused-cons-cells
pused-symbols
pused-other-bytes)
(setf elapsed-gc-time-user pelapsed-gc-time-user)
(setf elapsed-gc-time-system pelapsed-gc-time-system)
(setf elapsed-run-time-user pelapsed-run-time-user)
(setf elapsed-run-time-system pelapsed-run-time-system)
(setf elapsed-real-time pelapsed-real-time)
(setf used-cons-cells pused-cons-cells)
(setf used-symbols pused-symbols)
(setf used-other-bytes pused-other-bytes))
(defun gctime ()
(+ elapsed-gc-time-user elapsed-gc-time-system))
(defun total-bytes-allocated ()
(+ (* 8 used-cons-cells) (* 64 used-symbols) used-other-bytes)))
#+:MCL
(defun total-bytes-allocated ()
(ccl::total-bytes-allocated))
(let (#+:mcl initial-gc-time #+:mcl initial-consed
initial-real-time initial-run-time)
#+:mcl
(defun with-timed-form (thunk)
(setf initial-gc-time (gctime))
(setf initial-consed (total-bytes-allocated))
(setf initial-real-time (get-internal-real-time))
(setf initial-run-time (get-internal-run-time))
(let* ((result (funcall thunk))
(elapsed-real-time (/ (- (get-internal-real-time) initial-real-time)
internal-time-units-per-second))
(elapsed-run-time (/ (- (get-internal-run-time) initial-run-time)
internal-time-units-per-second))
(elapsed-mf-time (max 0 (- elapsed-real-time elapsed-run-time)))
(elapsed-gc-time (/ (- (gctime) initial-gc-time)
internal-time-units-per-second))
(bytes-consed (- (total-bytes-allocated) initial-consed
(if (fixnump initial-consed) 0 16))))
(values result elapsed-run-time elapsed-real-time elapsed-mf-time
elapsed-gc-time bytes-consed)))
#+:ALLEGRO
(defun with-timed-form (thunk)
(setf initial-real-time (get-internal-real-time))
(setf initial-run-time (get-internal-run-time))
(let* ((result (excl::time-a-funcall thunk #'set-time-vars))
(elapsed-real-time (/ (- (get-internal-real-time) initial-real-time)
internal-time-units-per-second))
(elapsed-run-time (/ (- (get-internal-run-time) initial-run-time)
internal-time-units-per-second))
(elapsed-mf-time (max 0 (- elapsed-real-time elapsed-run-time)))
(elapsed-gc-time (/ (gctime) internal-time-units-per-second))
(bytes-consed (total-bytes-allocated)))
(values result elapsed-run-time elapsed-real-time elapsed-mf-time
elapsed-gc-time (abs bytes-consed))))
#+:mcl
(defun timed-out-handler ()
(let* ((elapsed-real-time (/ (- (get-internal-real-time) initial-real-time)
internal-time-units-per-second))
(elapsed-run-time (/ (- (get-internal-run-time) initial-run-time)
internal-time-units-per-second))
(elapsed-mf-time (max 0 (- elapsed-real-time elapsed-run-time)))
(elapsed-gc-time (/ (- (gctime) initial-gc-time)
internal-time-units-per-second))
(bytes-consed (- (total-bytes-allocated) initial-consed
(if (fixnump initial-consed) 0 16))))
(values '(?) elapsed-run-time elapsed-real-time elapsed-mf-time
elapsed-gc-time bytes-consed)))
#+:ALLEGRO
(defun timed-out-handler ()
(let* ((elapsed-real-time (/ (- (get-internal-real-time) initial-real-time)
internal-time-units-per-second))
(elapsed-run-time (/ (- (get-internal-run-time) initial-run-time)
internal-time-units-per-second))
(elapsed-mf-time (max 0 (- elapsed-real-time elapsed-run-time)))
(elapsed-gc-time (/ (gctime) internal-time-units-per-second))
(bytes-consed (total-bytes-allocated)))
(values '(?) elapsed-run-time elapsed-real-time elapsed-mf-time
elapsed-gc-time (abs bytes-consed)))))
|
869ae45489791878c4070ea81950b7b15846d06ac0f430c447bafcf622baed62 | williamleferrand/accretio | ys_widgets.ml |
* Accretio is an API , a sandbox and a runtime for social playbooks
*
* Copyright ( C ) 2015
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation , either version 3 of the
* License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Affero General Public License for more details .
*
* You should have received a copy of the GNU Affero General Public License
* along with this program . If not , see < / > .
* Accretio is an API, a sandbox and a runtime for social playbooks
*
* Copyright (C) 2015 William Le Ferrand
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see </>.
*)
open Lwt
open React
open Eliom_content.Html5
open Eliom_content.Html5.D
open Ys_react
(* let's put some factored code in there .. *)
(* this widget displays a list of elements that can be created from a string *)
let appender extract init format builder =
let elements = RListUnique.init ~extract init in
let input = input ~input_type:`Text () in
let add _ =
match Ys_dom.get_value input with
"" -> ()
| _ as content ->
builder
content
(fun result ->
Ys_dom.set_value input "" ;
RListUnique.add elements result)
in
Ys_dom.register_on_return input add ;
[
RListUnique.map_in_div format elements ;
div ~a:[ a_class [ "ys-widgets-appender" ; "clearfix" ]] [
input ;
button
~button_type:`Button
~a:[ a_onclick add ]
[ pcdata "Add" ]
]
]
| null | https://raw.githubusercontent.com/williamleferrand/accretio/394f855e9c2a6a18f0c2da35058d5a01aacf6586/library/client/ys_widgets.ml | ocaml | let's put some factored code in there ..
this widget displays a list of elements that can be created from a string |
* Accretio is an API , a sandbox and a runtime for social playbooks
*
* Copyright ( C ) 2015
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation , either version 3 of the
* License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Affero General Public License for more details .
*
* You should have received a copy of the GNU Affero General Public License
* along with this program . If not , see < / > .
* Accretio is an API, a sandbox and a runtime for social playbooks
*
* Copyright (C) 2015 William Le Ferrand
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see </>.
*)
open Lwt
open React
open Eliom_content.Html5
open Eliom_content.Html5.D
open Ys_react
let appender extract init format builder =
let elements = RListUnique.init ~extract init in
let input = input ~input_type:`Text () in
let add _ =
match Ys_dom.get_value input with
"" -> ()
| _ as content ->
builder
content
(fun result ->
Ys_dom.set_value input "" ;
RListUnique.add elements result)
in
Ys_dom.register_on_return input add ;
[
RListUnique.map_in_div format elements ;
div ~a:[ a_class [ "ys-widgets-appender" ; "clearfix" ]] [
input ;
button
~button_type:`Button
~a:[ a_onclick add ]
[ pcdata "Add" ]
]
]
|
d97f6c45c132944de53a521c0e39563694c65b503b50389b4b5f3064a0930a81 | morazanm/fsm | state.rkt | FSM Library Version 1.0
Copyright ( C ) 2015 by and
Written by : and , 2015
;;; STATE
; A state is a symbol.
; A superstate is a (listof state)
(module state racket
(require "misc.rkt" "constants.rkt" "rules.rkt" "string.rkt")
(provide get-result minus-set empties get-final-super-states compute-P
compute-super-states extract-sstates extract-final-ss superstate->state
union-states)
(define union-states append)
(define (get-result s finals)
(cond [(member s finals) (list 'accept)]
[else (list 'reject)]))
( listof state ) ( listof state ) -- > ( listof state )
(define (minus-set L1 L2) (filter (lambda (s) (not (member s L2))) L1))
state ( listof rule ) -- > ( listof state )
(define (empties s rules)
(define (search visited to-visit result)
(cond [(null? to-visit) result]
[else
(let* ((next (car to-visit))
(rls (filter (lambda (r) (and (eq? (car r) next) (eq? (cadr r) EMP)))
rules))
(new-states (filter (lambda (s) (not (member s (append visited to-visit))))
(map (lambda (r) (caddr r)) rls)))
)
(search (cons next visited)
(append (cdr to-visit) new-states)
(append result new-states)))]))
(search '() (list s) (list s)))
( listof ( string ) ) ( listof state)-- > ( listof ( listof string ) )
(define (get-final-super-states K finals res)
(cond [(null? finals) (remove-duplicates res)] ; remove duplicates to keep res a set
[else
(let ((new-super-finals (filter (lambda (ss) (member (symbol->string (car finals)) ss)) K)))
(get-final-super-states K (cdr finals) (append new-super-finals res)))]))
( listof string ) symbol ( listof rules ) -- > state
(define (compute-P SS symb rules)
( listof state ) -- > ( listof state )
(define (helper S)
(cond [(null? S) '()]
[else
(let* ((current-state (car S))
(rls (filter-rules current-state symb rules))
(ps (remove-duplicates (append-map
(lambda (s) (empties s rules))
(map caddr rls))))
)
(append ps (helper (cdr S))))]))
(string->symbol
(lostr->string
(sort-strings
(remove-duplicates (map symbol->string (helper SS)))))))
state alphabet ( listof rules ) -- > ( listof ( listof string ) )
(define (compute-super-states start sigma rules)
( listof ( listof state ) ) ( listof ( listof state ) ) ( listof ( listof state ) ) -- > ( listof ( listof state ) )
(define (bfs visited tovisit SS)
(if (null? tovisit)
SS
(bfs (cons (car SS) visited)
(cdr tovisit)
(append (compute-supers (car SS) sigma (append visited tovisit)) SS))))
( listof state ) alphabet ( listof ( listof state ) ) -- > ( listof state )
(define (compute-supers SS sigma genSS)
(map (lambda (a) (compute-superS SS a genSS)) sigma))
( listof state ) symbol ( listof ( listof state ) ) -- > ( listof state )
(define (compute-superS SS a genSS)
(let ((superS (append-map (lambda (s) (reachable-states s a genSS)) SS)))
(begin
;(print superS) (newline)
(if (member superS genSS) null superS))) )
state symbol ( listof ( listof state ) ) -- > ( listof state )
(define (reachable-states s a genSS)
(let ((rls (filter (lambda (r) (and (eq? (car r) s) (eq? (cadr r) a)))
rules)))
(map (lambda (s) (empties s rules)) (map caddr rls))))
(bfs '() (list (empties start rules)) (list (empties start rules))))
;;; superstates
( listof ( superstate symbol superstate ) -- > ( list superstate )
(define (extract-sstates rls)
(remove-duplicates (append-map (lambda (r) (list (car r) (caddr r))) rls)))
( listof ( listof state ) ) -- > ( listof ( listof state ) )
(define (extract-final-ss sts finals)
(define (has-final-state? SS)
(ormap (lambda (s) (member s finals)) SS))
(filter (lambda (SS) (has-final-state? SS)) sts))
; superstate --> state
(define (superstate->state ss)
(string->symbol (lostr->string (los->lostr ss))))
) | null | https://raw.githubusercontent.com/morazanm/fsm/0a7e96e8d69cda7d22b8496375d5c792cd5d320d/fsm-core/private/state.rkt | racket | STATE
A state is a symbol.
A superstate is a (listof state)
remove duplicates to keep res a set
(print superS) (newline)
superstates
superstate --> state | FSM Library Version 1.0
Copyright ( C ) 2015 by and
Written by : and , 2015
(module state racket
(require "misc.rkt" "constants.rkt" "rules.rkt" "string.rkt")
(provide get-result minus-set empties get-final-super-states compute-P
compute-super-states extract-sstates extract-final-ss superstate->state
union-states)
(define union-states append)
(define (get-result s finals)
(cond [(member s finals) (list 'accept)]
[else (list 'reject)]))
( listof state ) ( listof state ) -- > ( listof state )
(define (minus-set L1 L2) (filter (lambda (s) (not (member s L2))) L1))
state ( listof rule ) -- > ( listof state )
(define (empties s rules)
(define (search visited to-visit result)
(cond [(null? to-visit) result]
[else
(let* ((next (car to-visit))
(rls (filter (lambda (r) (and (eq? (car r) next) (eq? (cadr r) EMP)))
rules))
(new-states (filter (lambda (s) (not (member s (append visited to-visit))))
(map (lambda (r) (caddr r)) rls)))
)
(search (cons next visited)
(append (cdr to-visit) new-states)
(append result new-states)))]))
(search '() (list s) (list s)))
( listof ( string ) ) ( listof state)-- > ( listof ( listof string ) )
(define (get-final-super-states K finals res)
[else
(let ((new-super-finals (filter (lambda (ss) (member (symbol->string (car finals)) ss)) K)))
(get-final-super-states K (cdr finals) (append new-super-finals res)))]))
( listof string ) symbol ( listof rules ) -- > state
(define (compute-P SS symb rules)
( listof state ) -- > ( listof state )
(define (helper S)
(cond [(null? S) '()]
[else
(let* ((current-state (car S))
(rls (filter-rules current-state symb rules))
(ps (remove-duplicates (append-map
(lambda (s) (empties s rules))
(map caddr rls))))
)
(append ps (helper (cdr S))))]))
(string->symbol
(lostr->string
(sort-strings
(remove-duplicates (map symbol->string (helper SS)))))))
state alphabet ( listof rules ) -- > ( listof ( listof string ) )
(define (compute-super-states start sigma rules)
( listof ( listof state ) ) ( listof ( listof state ) ) ( listof ( listof state ) ) -- > ( listof ( listof state ) )
(define (bfs visited tovisit SS)
(if (null? tovisit)
SS
(bfs (cons (car SS) visited)
(cdr tovisit)
(append (compute-supers (car SS) sigma (append visited tovisit)) SS))))
( listof state ) alphabet ( listof ( listof state ) ) -- > ( listof state )
(define (compute-supers SS sigma genSS)
(map (lambda (a) (compute-superS SS a genSS)) sigma))
( listof state ) symbol ( listof ( listof state ) ) -- > ( listof state )
(define (compute-superS SS a genSS)
(let ((superS (append-map (lambda (s) (reachable-states s a genSS)) SS)))
(begin
(if (member superS genSS) null superS))) )
state symbol ( listof ( listof state ) ) -- > ( listof state )
(define (reachable-states s a genSS)
(let ((rls (filter (lambda (r) (and (eq? (car r) s) (eq? (cadr r) a)))
rules)))
(map (lambda (s) (empties s rules)) (map caddr rls))))
(bfs '() (list (empties start rules)) (list (empties start rules))))
( listof ( superstate symbol superstate ) -- > ( list superstate )
(define (extract-sstates rls)
(remove-duplicates (append-map (lambda (r) (list (car r) (caddr r))) rls)))
( listof ( listof state ) ) -- > ( listof ( listof state ) )
(define (extract-final-ss sts finals)
(define (has-final-state? SS)
(ormap (lambda (s) (member s finals)) SS))
(filter (lambda (SS) (has-final-state? SS)) sts))
(define (superstate->state ss)
(string->symbol (lostr->string (los->lostr ss))))
) |
76425d45793fc60c01ab871404ee8ea02f67166ac1ef52a1b0e45747439c9e0b | emqx/emqx-exhook | emqx_extension_hook.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 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_extension_hook).
-include("emqx_extension_hook.hrl").
-include_lib("emqx/include/logger.hrl").
-logger_header("[ExHook]").
Mgmt APIs
-export([ enable/2
, disable/1
, disable_all/0
, list/0
]).
-export([ cast/2
, call_fold/4
]).
%%--------------------------------------------------------------------
Mgmt APIs
%%--------------------------------------------------------------------
-spec list() -> [emqx_extension_hook_driver:driver()].
list() ->
[state(Name) || Name <- running()].
-spec enable(atom(), list()) -> ok | {error, term()}.
enable(Name, Opts) ->
case lists:member(Name, running()) of
true ->
{error, already_started};
_ ->
case emqx_extension_hook_driver:load(Name, Opts) of
{ok, DriverState} ->
save(Name, DriverState);
{error, Reason} ->
?LOG(error, "Load driver ~p failed: ~p", [Name, Reason]),
{error, Reason}
end
end.
-spec disable(atom()) -> ok | {error, term()}.
disable(Name) ->
case state(Name) of
undefined -> {error, not_running};
Driver ->
ok = emqx_extension_hook_driver:unload(Driver),
unsave(Name)
end.
-spec disable_all() -> [atom()].
disable_all() ->
[begin disable(Name), Name end || Name <- running()].
%%----------------------------------------------------------
Dispatch APIs
%%----------------------------------------------------------
-spec cast(atom(), list()) -> ok.
cast(Name, Args) ->
cast(Name, Args, running()).
cast(_, _, []) ->
ok;
cast(Name, Args, [DriverName|More]) ->
emqx_extension_hook_driver:run_hook(Name, Args, state(DriverName)),
cast(Name, Args, More).
-spec call_fold(atom(), list(), term(), function()) -> ok | {stop, term()}.
call_fold(Name, InfoArgs, AccArg, Validator) ->
call_fold(Name, InfoArgs, AccArg, Validator, running()).
call_fold(_, _, _, _, []) ->
ok;
call_fold(Name, InfoArgs, AccArg, Validator, [NameDriver|More]) ->
Driver = state(NameDriver),
case emqx_extension_hook_driver:run_hook_fold(Name, InfoArgs, AccArg, Driver) of
ok -> call_fold(Name, InfoArgs, AccArg, Validator, More);
{error, _} -> call_fold(Name, InfoArgs, AccArg, Validator, More);
{ok, NAcc} ->
case Validator(NAcc) of
true ->
{stop, NAcc};
_ ->
?LOG(error, "Got invalid return type for calling ~p on ~p",
[Name, emqx_extension_hook_driver:name(Driver)]),
call_fold(Name, InfoArgs, AccArg, Validator, More)
end
end.
%%----------------------------------------------------------
%% Storage
-compile({inline, [save/2]}).
save(Name, DriverState) ->
Saved = persistent_term:get(?APP, []),
persistent_term:put(?APP, lists:reverse([Name | Saved])),
persistent_term:put({?APP, Name}, DriverState).
-compile({inline, [unsave/1]}).
unsave(Name) ->
case persistent_term:get(?APP, []) of
[] ->
persistent_term:erase(?APP);
Saved ->
persistent_term:put(?APP, lists:delete(Name, Saved))
end,
persistent_term:erase({?APP, Name}),
ok.
-compile({inline, [running/0]}).
running() ->
persistent_term:get(?APP, []).
-compile({inline, [state/1]}).
state(Name) ->
case catch persistent_term:get({?APP, Name}) of
{'EXIT', {badarg,_}} -> undefined;
State -> State
end.
| null | https://raw.githubusercontent.com/emqx/emqx-exhook/906ba8c0ac907414b85738c24c7dbef880da844e/src/emqx_extension_hook.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.
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
----------------------------------------------------------
----------------------------------------------------------
----------------------------------------------------------
Storage | Copyright ( c ) 2020 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_extension_hook).
-include("emqx_extension_hook.hrl").
-include_lib("emqx/include/logger.hrl").
-logger_header("[ExHook]").
Mgmt APIs
-export([ enable/2
, disable/1
, disable_all/0
, list/0
]).
-export([ cast/2
, call_fold/4
]).
Mgmt APIs
-spec list() -> [emqx_extension_hook_driver:driver()].
list() ->
[state(Name) || Name <- running()].
-spec enable(atom(), list()) -> ok | {error, term()}.
enable(Name, Opts) ->
case lists:member(Name, running()) of
true ->
{error, already_started};
_ ->
case emqx_extension_hook_driver:load(Name, Opts) of
{ok, DriverState} ->
save(Name, DriverState);
{error, Reason} ->
?LOG(error, "Load driver ~p failed: ~p", [Name, Reason]),
{error, Reason}
end
end.
-spec disable(atom()) -> ok | {error, term()}.
disable(Name) ->
case state(Name) of
undefined -> {error, not_running};
Driver ->
ok = emqx_extension_hook_driver:unload(Driver),
unsave(Name)
end.
-spec disable_all() -> [atom()].
disable_all() ->
[begin disable(Name), Name end || Name <- running()].
Dispatch APIs
-spec cast(atom(), list()) -> ok.
cast(Name, Args) ->
cast(Name, Args, running()).
cast(_, _, []) ->
ok;
cast(Name, Args, [DriverName|More]) ->
emqx_extension_hook_driver:run_hook(Name, Args, state(DriverName)),
cast(Name, Args, More).
-spec call_fold(atom(), list(), term(), function()) -> ok | {stop, term()}.
call_fold(Name, InfoArgs, AccArg, Validator) ->
call_fold(Name, InfoArgs, AccArg, Validator, running()).
call_fold(_, _, _, _, []) ->
ok;
call_fold(Name, InfoArgs, AccArg, Validator, [NameDriver|More]) ->
Driver = state(NameDriver),
case emqx_extension_hook_driver:run_hook_fold(Name, InfoArgs, AccArg, Driver) of
ok -> call_fold(Name, InfoArgs, AccArg, Validator, More);
{error, _} -> call_fold(Name, InfoArgs, AccArg, Validator, More);
{ok, NAcc} ->
case Validator(NAcc) of
true ->
{stop, NAcc};
_ ->
?LOG(error, "Got invalid return type for calling ~p on ~p",
[Name, emqx_extension_hook_driver:name(Driver)]),
call_fold(Name, InfoArgs, AccArg, Validator, More)
end
end.
-compile({inline, [save/2]}).
save(Name, DriverState) ->
Saved = persistent_term:get(?APP, []),
persistent_term:put(?APP, lists:reverse([Name | Saved])),
persistent_term:put({?APP, Name}, DriverState).
-compile({inline, [unsave/1]}).
unsave(Name) ->
case persistent_term:get(?APP, []) of
[] ->
persistent_term:erase(?APP);
Saved ->
persistent_term:put(?APP, lists:delete(Name, Saved))
end,
persistent_term:erase({?APP, Name}),
ok.
-compile({inline, [running/0]}).
running() ->
persistent_term:get(?APP, []).
-compile({inline, [state/1]}).
state(Name) ->
case catch persistent_term:get({?APP, Name}) of
{'EXIT', {badarg,_}} -> undefined;
State -> State
end.
|
147c10a1e047e07c0508a63a0776ebfb401554e466230a5ff91b9ae5716589ff | luc-tielen/llvm-codegen | Flag.hs | # LANGUAGE RoleAnnotations #
module LLVM.Codegen.Flag
( Flag(..)
) where
data Flag a
= On
| Off
deriving (Eq, Ord, Show)
type role Flag nominal
| null | https://raw.githubusercontent.com/luc-tielen/llvm-codegen/ee415723fecfb85525654394b61e77bb3e99a67a/lib/LLVM/Codegen/Flag.hs | haskell | # LANGUAGE RoleAnnotations #
module LLVM.Codegen.Flag
( Flag(..)
) where
data Flag a
= On
| Off
deriving (Eq, Ord, Show)
type role Flag nominal
|
|
b4f3580b279dec5a328fc269b65ec8f2568a14b2d06fa33005cf51feedf9a6ca | ralsei/sawzall | syntax.rkt | #lang racket/base
(require (for-syntax racket/base
racket/list)
data-frame
racket/contract/base
syntax/parse/define
"grouped-df.rkt")
(provide (struct-out column-proc)
(struct-out row-proc)
(for-syntax column-syntax-form
row-syntax-form))
(struct column-proc (columns bindings procs) #:transparent)
(begin-for-syntax
(define-syntax-class binder
#:attributes (var ty)
[pattern var:id #:attr ty (syntax #f)]
[pattern [var:id {~literal :} ty:id]
#:with quote-ty (quote ty)
#:declare quote-ty (expr/c #'(or/c 'element 'vector))]))
(define-for-syntax (column-syntax-form stx internal-function-stx faux-types?)
(syntax-parse stx
[(_ frame [col:id (binding:binder ...) body:expr ...] ...)
#:declare frame (expr/c #'(or/c data-frame? grouped-data-frame?))
#:with internal-function internal-function-stx
(when (and (not faux-types?)
(andmap (λ (x) (and (syntax->datum x) #t)) (flatten (attribute binding.ty))))
(raise-syntax-error (syntax->datum (attribute internal-function))
"types should not be specified here"))
#'(internal-function
frame.c
(column-proc (list (symbol->string 'col) ...)
(list (list (cons (symbol->string 'binding.var)
'binding.ty)
...) ...)
(list (λ (binding.var ...)
body ...)
...)))]))
(struct row-proc (bindings proc))
(define-for-syntax (row-syntax-form stx internal-function-stx)
(syntax-parse stx
[(_ frame (bound:id ...) body:expr ...)
#:declare frame (expr/c #'(or/c data-frame? grouped-data-frame?))
#:with internal-function internal-function-stx
#'(internal-function
frame.c
(row-proc (list (symbol->string 'bound) ...)
(λ (bound ...)
body ...)))]))
| null | https://raw.githubusercontent.com/ralsei/sawzall/61f147cd523466b74422c3990fd95cd6ead64559/sawzall-lib/syntax.rkt | racket | #lang racket/base
(require (for-syntax racket/base
racket/list)
data-frame
racket/contract/base
syntax/parse/define
"grouped-df.rkt")
(provide (struct-out column-proc)
(struct-out row-proc)
(for-syntax column-syntax-form
row-syntax-form))
(struct column-proc (columns bindings procs) #:transparent)
(begin-for-syntax
(define-syntax-class binder
#:attributes (var ty)
[pattern var:id #:attr ty (syntax #f)]
[pattern [var:id {~literal :} ty:id]
#:with quote-ty (quote ty)
#:declare quote-ty (expr/c #'(or/c 'element 'vector))]))
(define-for-syntax (column-syntax-form stx internal-function-stx faux-types?)
(syntax-parse stx
[(_ frame [col:id (binding:binder ...) body:expr ...] ...)
#:declare frame (expr/c #'(or/c data-frame? grouped-data-frame?))
#:with internal-function internal-function-stx
(when (and (not faux-types?)
(andmap (λ (x) (and (syntax->datum x) #t)) (flatten (attribute binding.ty))))
(raise-syntax-error (syntax->datum (attribute internal-function))
"types should not be specified here"))
#'(internal-function
frame.c
(column-proc (list (symbol->string 'col) ...)
(list (list (cons (symbol->string 'binding.var)
'binding.ty)
...) ...)
(list (λ (binding.var ...)
body ...)
...)))]))
(struct row-proc (bindings proc))
(define-for-syntax (row-syntax-form stx internal-function-stx)
(syntax-parse stx
[(_ frame (bound:id ...) body:expr ...)
#:declare frame (expr/c #'(or/c data-frame? grouped-data-frame?))
#:with internal-function internal-function-stx
#'(internal-function
frame.c
(row-proc (list (symbol->string 'bound) ...)
(λ (bound ...)
body ...)))]))
|
|
058f261f8d8a8a6eba0e0a4ec286667aafe2c8fe343110c387153d8df14427cf | kit-clj/kit | test_utils.clj | (ns <<ns-name>>.test-utils
(:require
[<<ns-name>>.core :as core]
[integrant.repl.state :as state]))
(defn system-state
[]
(or @core/system state/system))
(defn system-fixture
[]
(fn [f]
(when (nil? (system-state))
(core/start-app {:opts {:profile :test}}))
(f)))
| null | https://raw.githubusercontent.com/kit-clj/kit/9a38fbdfce072e056e6b0d79001f810e5deebe62/libs/deps-template/resources/io/github/kit_clj/kit/test/clj/test_utils.clj | clojure | (ns <<ns-name>>.test-utils
(:require
[<<ns-name>>.core :as core]
[integrant.repl.state :as state]))
(defn system-state
[]
(or @core/system state/system))
(defn system-fixture
[]
(fn [f]
(when (nil? (system-state))
(core/start-app {:opts {:profile :test}}))
(f)))
|
|
bdc8221390570990bda50e41d386fc0d51d78ac9eefd82e5ed885a972d269dca | antono/guix-debian | derivations.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2012 , 2013 , 2014 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (test-derivations)
#:use-module (guix derivations)
#:use-module (guix store)
#:use-module (guix utils)
#:use-module (guix hash)
#:use-module (guix base32)
#:use-module ((guix packages) #:select (package-derivation base32))
#:use-module ((guix build utils) #:select (executable-file?))
#:use-module ((gnu packages) #:select (search-bootstrap-binary))
#:use-module (gnu packages bootstrap)
#:use-module ((gnu packages guile) #:select (guile-1.8))
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-11)
#:use-module (srfi srfi-26)
#:use-module (srfi srfi-34)
#:use-module (srfi srfi-64)
#:use-module (rnrs io ports)
#:use-module (rnrs bytevectors)
#:use-module (web uri)
#:use-module (ice-9 rdelim)
#:use-module (ice-9 regex)
#:use-module (ice-9 ftw)
#:use-module (ice-9 match))
(define %store
(false-if-exception (open-connection)))
(when %store
;; Make sure we build everything by ourselves.
(set-build-options %store #:use-substitutes? #f)
By default , use % BOOTSTRAP - GUILE for the current system .
(let ((drv (package-derivation %store %bootstrap-guile)))
(%guile-for-build drv)))
(define (bootstrap-binary name)
(let ((bin (search-bootstrap-binary name (%current-system))))
(and %store
(add-to-store %store name #t "sha256" bin))))
(define %bash
(bootstrap-binary "bash"))
(define %mkdir
(bootstrap-binary "mkdir"))
(define* (directory-contents dir #:optional (slurp get-bytevector-all))
"Return an alist representing the contents of DIR."
(define prefix-len (string-length dir))
(sort (file-system-fold (const #t) ; enter?
(lambda (path stat result) ; leaf
(alist-cons (string-drop path prefix-len)
(call-with-input-file path slurp)
result))
(lambda (path stat result) result) ; down
(lambda (path stat result) result) ; up
(lambda (path stat result) result) ; skip
(lambda (path stat errno result) result) ; error
'()
dir)
(lambda (e1 e2)
(string<? (car e1) (car e2)))))
(test-begin "derivations")
(test-assert "parse & export"
(let* ((f (search-path %load-path "tests/test.drv"))
(b1 (call-with-input-file f get-bytevector-all))
(d1 (read-derivation (open-bytevector-input-port b1)))
(b2 (call-with-bytevector-output-port (cut write-derivation d1 <>)))
(d2 (read-derivation (open-bytevector-input-port b2))))
(and (equal? b1 b2)
(equal? d1 d2))))
(test-skip (if %store 0 12))
(test-assert "add-to-store, flat"
(let* ((file (search-path %load-path "language/tree-il/spec.scm"))
(drv (add-to-store %store "flat-test" #f "sha256" file)))
(and (eq? 'regular (stat:type (stat drv)))
(valid-path? %store drv)
(equal? (call-with-input-file file get-bytevector-all)
(call-with-input-file drv get-bytevector-all)))))
(test-assert "add-to-store, recursive"
(let* ((dir (dirname (search-path %load-path "language/tree-il/spec.scm")))
(drv (add-to-store %store "dir-tree-test" #t "sha256" dir)))
(and (eq? 'directory (stat:type (stat drv)))
(valid-path? %store drv)
(equal? (directory-contents dir)
(directory-contents drv)))))
(test-assert "derivation with no inputs"
(let* ((builder (add-text-to-store %store "my-builder.sh"
"echo hello, world\n"
'()))
(drv (derivation %store "foo"
%bash `("-e" ,builder)
#:env-vars '(("HOME" . "/homeless")))))
(and (store-path? (derivation-file-name drv))
(valid-path? %store (derivation-file-name drv)))))
(test-assert "build derivation with 1 source"
(let* ((builder (add-text-to-store %store "my-builder.sh"
"echo hello, world > \"$out\"\n"
'()))
(drv (derivation %store "foo"
%bash `(,builder)
#:env-vars '(("HOME" . "/homeless")
("zzz" . "Z!")
("AAA" . "A!"))
#:inputs `((,%bash) (,builder))))
(succeeded?
(build-derivations %store (list drv))))
(and succeeded?
(let ((path (derivation->output-path drv)))
(and (valid-path? %store path)
(string=? (call-with-input-file path read-line)
"hello, world"))))))
(test-assert "derivation with local file as input"
(let* ((builder (add-text-to-store
%store "my-builder.sh"
"(while read line ; do echo \"$line\" ; done) < $in > $out"
'()))
(input (search-path %load-path "ice-9/boot-9.scm"))
(input* (add-to-store %store (basename input)
#t "sha256" input))
(drv (derivation %store "derivation-with-input-file"
%bash `(,builder)
;; Cheat to pass the actual file name to the
;; builder.
#:env-vars `(("in" . ,input*))
#:inputs `((,%bash)
(,builder)
(,input))))) ; ← local file name
(and (build-derivations %store (list drv))
;; Note: we can't compare the files because the above trick alters
;; the contents.
(valid-path? %store (derivation->output-path drv)))))
(test-assert "fixed-output-derivation?"
(let* ((builder (add-text-to-store %store "my-fixed-builder.sh"
"echo -n hello > $out" '()))
(hash (sha256 (string->utf8 "hello")))
(drv (derivation %store "fixed"
%bash `(,builder)
#:inputs `((,builder))
#:hash hash #:hash-algo 'sha256)))
(fixed-output-derivation? drv)))
(test-assert "fixed-output derivation"
(let* ((builder (add-text-to-store %store "my-fixed-builder.sh"
"echo -n hello > $out" '()))
(hash (sha256 (string->utf8 "hello")))
(drv (derivation %store "fixed"
%bash `(,builder)
#:inputs `((,builder)) ; optional
#:hash hash #:hash-algo 'sha256))
(succeeded? (build-derivations %store (list drv))))
(and succeeded?
(let ((p (derivation->output-path drv)))
(and (equal? (string->utf8 "hello")
(call-with-input-file p get-bytevector-all))
(bytevector? (query-path-hash %store p)))))))
(test-assert "fixed-output derivation: output paths are equal"
(let* ((builder1 (add-text-to-store %store "fixed-builder1.sh"
"echo -n hello > $out" '()))
(builder2 (add-text-to-store %store "fixed-builder2.sh"
"echo hey; echo -n hello > $out" '()))
(hash (sha256 (string->utf8 "hello")))
(drv1 (derivation %store "fixed"
%bash `(,builder1)
#:hash hash #:hash-algo 'sha256))
(drv2 (derivation %store "fixed"
%bash `(,builder2)
#:hash hash #:hash-algo 'sha256))
(succeeded? (build-derivations %store (list drv1 drv2))))
(and succeeded?
(equal? (derivation->output-path drv1)
(derivation->output-path drv2)))))
(test-assert "fixed-output derivation, recursive"
(let* ((builder (add-text-to-store %store "my-fixed-builder.sh"
"echo -n hello > $out" '()))
(hash (sha256 (string->utf8 "hello")))
(drv (derivation %store "fixed-rec"
%bash `(,builder)
#:inputs `((,builder))
#:hash (base32 "0sg9f58l1jj88w6pdrfdpj5x9b1zrwszk84j81zvby36q9whhhqa")
#:hash-algo 'sha256
#:recursive? #t))
(succeeded? (build-derivations %store (list drv))))
(and succeeded?
(let ((p (derivation->output-path drv)))
(and (equal? (string->utf8 "hello")
(call-with-input-file p get-bytevector-all))
(bytevector? (query-path-hash %store p)))))))
(test-assert "derivation with a fixed-output input"
;; A derivation D using a fixed-output derivation F doesn't has the same
output path when passed F or F ' , as long as F and F ' have the same output
;; path.
(let* ((builder1 (add-text-to-store %store "fixed-builder1.sh"
"echo -n hello > $out" '()))
(builder2 (add-text-to-store %store "fixed-builder2.sh"
"echo hey; echo -n hello > $out" '()))
(hash (sha256 (string->utf8 "hello")))
(fixed1 (derivation %store "fixed"
%bash `(,builder1)
#:hash hash #:hash-algo 'sha256))
(fixed2 (derivation %store "fixed"
%bash `(,builder2)
#:hash hash #:hash-algo 'sha256))
(fixed-out (derivation->output-path fixed1))
(builder3 (add-text-to-store
%store "final-builder.sh"
Use Bash hackery to avoid Coreutils .
"echo $in ; (read -u 3 c; echo $c) 3< $in > $out" '()))
(final1 (derivation %store "final"
%bash `(,builder3)
#:env-vars `(("in" . ,fixed-out))
#:inputs `((,%bash) (,builder3) (,fixed1))))
(final2 (derivation %store "final"
%bash `(,builder3)
#:env-vars `(("in" . ,fixed-out))
#:inputs `((,%bash) (,builder3) (,fixed2))))
(succeeded? (build-derivations %store
(list final1 final2))))
(and succeeded?
(equal? (derivation->output-path final1)
(derivation->output-path final2)))))
(test-assert "multiple-output derivation"
(let* ((builder (add-text-to-store %store "my-fixed-builder.sh"
"echo one > $out ; echo two > $second"
'()))
(drv (derivation %store "fixed"
%bash `(,builder)
#:env-vars '(("HOME" . "/homeless")
("zzz" . "Z!")
("AAA" . "A!"))
#:inputs `((,%bash) (,builder))
#:outputs '("out" "second")))
(succeeded? (build-derivations %store (list drv))))
(and succeeded?
(let ((one (derivation->output-path drv "out"))
(two (derivation->output-path drv "second")))
(and (lset= equal?
(derivation->output-paths drv)
`(("out" . ,one) ("second" . ,two)))
(eq? 'one (call-with-input-file one read))
(eq? 'two (call-with-input-file two read)))))))
(test-assert "multiple-output derivation, non-alphabetic order"
;; Here, the outputs are not listed in alphabetic order. Yet, the store
path computation must reorder them first .
(let* ((builder (add-text-to-store %store "my-fixed-builder.sh"
"echo one > $out ; echo two > $AAA"
'()))
(drv (derivation %store "fixed"
%bash `(,builder)
#:inputs `((,%bash) (,builder))
#:outputs '("out" "AAA")))
(succeeded? (build-derivations %store (list drv))))
(and succeeded?
(let ((one (derivation->output-path drv "out"))
(two (derivation->output-path drv "AAA")))
(and (eq? 'one (call-with-input-file one read))
(eq? 'two (call-with-input-file two read)))))))
(test-assert "multiple-output derivation, derivation-path->output-path"
(let* ((builder (add-text-to-store %store "builder.sh"
"echo one > $out ; echo two > $second"
'()))
(drv (derivation %store "multiple"
%bash `(,builder)
#:outputs '("out" "second")))
(drv-file (derivation-file-name drv))
(one (derivation->output-path drv "out"))
(two (derivation->output-path drv "second"))
(first (derivation-path->output-path drv-file "out"))
(second (derivation-path->output-path drv-file "second")))
(and (not (string=? one two))
(string-suffix? "-second" two)
(string=? first one)
(string=? second two))))
(test-assert "user of multiple-output derivation"
;; Check whether specifying several inputs coming from the same
;; multiple-output derivation works.
(let* ((builder1 (add-text-to-store %store "my-mo-builder.sh"
"echo one > $out ; echo two > $two"
'()))
(mdrv (derivation %store "multiple-output"
%bash `(,builder1)
#:inputs `((,%bash) (,builder1))
#:outputs '("out" "two")))
(builder2 (add-text-to-store %store "my-mo-user-builder.sh"
"read x < $one;
read y < $two;
echo \"($x $y)\" > $out"
'()))
(udrv (derivation %store "multiple-output-user"
%bash `(,builder2)
#:env-vars `(("one"
. ,(derivation->output-path
mdrv "out"))
("two"
. ,(derivation->output-path
mdrv "two")))
#:inputs `((,%bash)
(,builder2)
two occurrences of MDRV :
(,mdrv)
(,mdrv "two")))))
(and (build-derivations %store (list (pk 'udrv udrv)))
(let ((p (derivation->output-path udrv)))
(and (valid-path? %store p)
(equal? '(one two) (call-with-input-file p read)))))))
(test-assert "derivation with #:references-graphs"
(let* ((input1 (add-text-to-store %store "foo" "hello"
(list %bash)))
(input2 (add-text-to-store %store "bar"
(number->string (random 7777))
(list input1)))
(builder (add-text-to-store %store "build-graph"
(format #f "
~a $out
(while read l ; do echo $l ; done) < bash > $out/bash
(while read l ; do echo $l ; done) < input1 > $out/input1
(while read l ; do echo $l ; done) < input2 > $out/input2"
%mkdir)
(list %mkdir)))
(drv (derivation %store "closure-graphs"
%bash `(,builder)
#:references-graphs
`(("bash" . ,%bash)
("input1" . ,input1)
("input2" . ,input2))
#:inputs `((,%bash) (,builder))))
(out (derivation->output-path drv)))
(define (deps path . deps)
(let ((count (length deps)))
(string-append path "\n\n" (number->string count) "\n"
(string-join (sort deps string<?) "\n")
(if (zero? count) "" "\n"))))
(and (build-derivations %store (list drv))
(equal? (directory-contents out get-string-all)
`(("/bash" . ,(string-append %bash "\n\n0\n"))
("/input1" . ,(if (string>? input1 %bash)
(string-append (deps %bash)
(deps input1 %bash))
(string-append (deps input1 %bash)
(deps %bash))))
("/input2" . ,(string-concatenate
(map cdr
(sort
(map (lambda (p d)
(cons p (apply deps p d)))
(list %bash input1 input2)
(list '() (list %bash) (list input1)))
(lambda (x y)
(match x
((p1 . _)
(match y
((p2 . _)
(string<? p1 p2)))))))))))))))
(test-assert "derivation #:allowed-references, ok"
(let ((drv (derivation %store "allowed" %bash
'("-c" "echo hello > $out")
#:inputs `((,%bash))
#:allowed-references '())))
(build-derivations %store (list drv))))
(test-assert "derivation #:allowed-references, not allowed"
(let* ((txt (add-text-to-store %store "foo" "Hello, world."))
(drv (derivation %store "disallowed" %bash
`("-c" ,(string-append "echo " txt "> $out"))
#:inputs `((,%bash) (,txt))
#:allowed-references '())))
(guard (c ((nix-protocol-error? c)
;; There's no specific error message to check for.
#t))
(build-derivations %store (list drv))
#f)))
(test-assert "derivation #:allowed-references, self allowed"
(let ((drv (derivation %store "allowed" %bash
'("-c" "echo $out > $out")
#:inputs `((,%bash))
#:allowed-references '("out"))))
(build-derivations %store (list drv))))
(test-assert "derivation #:allowed-references, self not allowed"
(let ((drv (derivation %store "disallowed" %bash
`("-c" ,"echo $out > $out")
#:inputs `((,%bash))
#:allowed-references '())))
(guard (c ((nix-protocol-error? c)
;; There's no specific error message to check for.
#t))
(build-derivations %store (list drv))
#f)))
(define %coreutils
(false-if-exception
(and (getaddrinfo "www.gnu.org" "80" AI_NUMERICSERV)
(or (package-derivation %store %bootstrap-coreutils&co)
(nixpkgs-derivation "coreutils")))))
(test-skip (if %coreutils 0 1))
(test-assert "build derivation with coreutils"
(let* ((builder
(add-text-to-store %store "build-with-coreutils.sh"
"echo $PATH ; mkdir --version ; mkdir $out ; touch $out/good"
'()))
(drv
(derivation %store "foo"
%bash `(,builder)
#:env-vars `(("PATH" .
,(string-append
(derivation->output-path %coreutils)
"/bin")))
#:inputs `((,builder)
(,%coreutils))))
(succeeded?
(build-derivations %store (list drv))))
(and succeeded?
(let ((p (derivation->output-path drv)))
(and (valid-path? %store p)
(file-exists? (string-append p "/good")))))))
(test-skip (if (%guile-for-build) 0 8))
(test-assert "build-expression->derivation and derivation-prerequisites"
(let ((drv (build-expression->derivation %store "fail" #f)))
(any (match-lambda
(($ <derivation-input> path)
(string=? path (derivation-file-name (%guile-for-build)))))
(derivation-prerequisites drv))))
(test-assert "build-expression->derivation without inputs"
(let* ((builder '(begin
(mkdir %output)
(call-with-output-file (string-append %output "/test")
(lambda (p)
(display '(hello guix) p)))))
(drv (build-expression->derivation %store "goo" builder))
(succeeded? (build-derivations %store (list drv))))
(and succeeded?
(let ((p (derivation->output-path drv)))
(equal? '(hello guix)
(call-with-input-file (string-append p "/test") read))))))
(test-assert "build-expression->derivation and max-silent-time"
(let* ((store (let ((s (open-connection)))
(set-build-options s #:max-silent-time 1)
s))
(builder '(begin (sleep 100) (mkdir %output) #t))
(drv (build-expression->derivation store "silent" builder))
(out-path (derivation->output-path drv)))
(guard (c ((nix-protocol-error? c)
(and (string-contains (nix-protocol-error-message c)
"failed")
(not (valid-path? store out-path)))))
(build-derivations store (list drv))
#f)))
(test-assert "build-expression->derivation and timeout"
(let* ((store (let ((s (open-connection)))
(set-build-options s #:timeout 1)
s))
(builder '(begin (sleep 100) (mkdir %output) #t))
(drv (build-expression->derivation store "slow" builder))
(out-path (derivation->output-path drv)))
(guard (c ((nix-protocol-error? c)
(and (string-contains (nix-protocol-error-message c)
"failed")
(not (valid-path? store out-path)))))
(build-derivations store (list drv))
#f)))
(test-assert "build-expression->derivation and derivation-prerequisites-to-build"
(let ((drv (build-expression->derivation %store "fail" #f)))
;; The only direct dependency is (%guile-for-build) and it's already
;; built.
(null? (derivation-prerequisites-to-build %store drv))))
(test-assert "derivation-prerequisites-to-build when outputs already present"
(let* ((builder '(begin (mkdir %output) #t))
(input-drv (build-expression->derivation %store "input" builder))
(input-path (derivation-output-path
(assoc-ref (derivation-outputs input-drv)
"out")))
(drv (build-expression->derivation %store "something" builder
#:inputs
`(("i" ,input-drv))))
(output (derivation->output-path drv)))
;; Make sure these things are not already built.
(when (valid-path? %store input-path)
(delete-paths %store (list input-path)))
(when (valid-path? %store output)
(delete-paths %store (list output)))
(and (equal? (map derivation-input-path
(derivation-prerequisites-to-build %store drv))
(list (derivation-file-name input-drv)))
Build DRV and delete its input .
(build-derivations %store (list drv))
(delete-paths %store (list input-path))
(not (valid-path? %store input-path))
;; Now INPUT-PATH is missing, yet it shouldn't be listed as a
prerequisite to build because DRV itself is already built .
(null? (derivation-prerequisites-to-build %store drv)))))
(test-skip (if (getenv "GUIX_BINARY_SUBSTITUTE_URL") 0 1))
(test-assert "derivation-prerequisites-to-build and substitutes"
(let* ((store (open-connection))
(drv (build-expression->derivation store "prereq-subst"
(random 1000)))
(output (derivation->output-path drv))
(dir (and=> (getenv "GUIX_BINARY_SUBSTITUTE_URL")
(compose uri-path string->uri))))
;; Create fake substituter data, to be read by `substitute-binary'.
(call-with-output-file (string-append dir "/nix-cache-info")
(lambda (p)
(format p "StoreDir: ~a\nWantMassQuery: 0\n"
(%store-prefix))))
(call-with-output-file (string-append dir "/" (store-path-hash-part output)
".narinfo")
(lambda (p)
(format p "StorePath: ~a
URL: ~a
Compression: none
NarSize: 1234
References:
System: ~a
Deriver: ~a~%"
StorePath
(string-append dir "/example.nar") ; URL
System
(basename
Deriver
;; Make sure substitutes are usable.
(set-build-options store #:use-substitutes? #t)
(let-values (((build download)
(derivation-prerequisites-to-build store drv))
((build* download*)
(derivation-prerequisites-to-build store drv
#:use-substitutes? #f)))
(pk build download build* download*)
(and (null? build)
(equal? download (list output))
(null? download*)
(null? build*)))))
(test-assert "build-expression->derivation with expression returning #f"
(let* ((builder '(begin
(mkdir %output)
#f)) ; fail!
(drv (build-expression->derivation %store "fail" builder))
(out-path (derivation->output-path drv)))
(guard (c ((nix-protocol-error? c)
;; Note that the output path may exist at this point, but it
;; is invalid.
(and (string-match "build .* failed"
(nix-protocol-error-message c))
(not (valid-path? %store out-path)))))
(build-derivations %store (list drv))
#f)))
(test-assert "build-expression->derivation with two outputs"
(let* ((builder '(begin
(call-with-output-file (assoc-ref %outputs "out")
(lambda (p)
(display '(hello) p)))
(call-with-output-file (assoc-ref %outputs "second")
(lambda (p)
(display '(world) p)))))
(drv (build-expression->derivation %store "double" builder
#:outputs '("out"
"second")))
(succeeded? (build-derivations %store (list drv))))
(and succeeded?
(let ((one (derivation->output-path drv))
(two (derivation->output-path drv "second")))
(and (equal? '(hello) (call-with-input-file one read))
(equal? '(world) (call-with-input-file two read)))))))
(test-skip (if %coreutils 0 1))
(test-assert "build-expression->derivation with one input"
(let* ((builder '(call-with-output-file %output
(lambda (p)
(let ((cu (assoc-ref %build-inputs "cu")))
(close 1)
(dup2 (port->fdes p) 1)
(execl (string-append cu "/bin/uname")
"uname" "-a")))))
(drv (build-expression->derivation %store "uname" builder
#:inputs
`(("cu" ,%coreutils))))
(succeeded? (build-derivations %store (list drv))))
(and succeeded?
(let ((p (derivation->output-path drv)))
(string-contains (call-with-input-file p read-line) "GNU")))))
(test-assert "imported-files"
(let* ((files `(("x" . ,(search-path %load-path "ice-9/q.scm"))
("a/b/c" . ,(search-path %load-path
"guix/derivations.scm"))
("p/q" . ,(search-path %load-path "guix.scm"))
("p/z" . ,(search-path %load-path "guix/store.scm"))))
(drv (imported-files %store files)))
(and (build-derivations %store (list drv))
(let ((dir (derivation->output-path drv)))
(every (match-lambda
((path . source)
(equal? (call-with-input-file (string-append dir "/" path)
get-bytevector-all)
(call-with-input-file source
get-bytevector-all))))
files)))))
(test-assert "build-expression->derivation with modules"
(let* ((builder `(begin
(use-modules (guix build utils))
(let ((out (assoc-ref %outputs "out")))
(mkdir-p (string-append out "/guile/guix/nix"))
#t)))
(drv (build-expression->derivation %store "test-with-modules"
builder
#:modules
'((guix build utils)))))
(and (build-derivations %store (list drv))
(let* ((p (derivation->output-path drv))
(s (stat (string-append p "/guile/guix/nix"))))
(eq? (stat:type s) 'directory)))))
(test-assert "build-expression->derivation: same fixed-output path"
(let* ((builder1 '(call-with-output-file %output
(lambda (p)
(write "hello" p))))
(builder2 '(call-with-output-file (pk 'difference-here! %output)
(lambda (p)
(write "hello" p))))
(hash (sha256 (string->utf8 "hello")))
(input1 (build-expression->derivation %store "fixed" builder1
#:hash hash
#:hash-algo 'sha256))
(input2 (build-expression->derivation %store "fixed" builder2
#:hash hash
#:hash-algo 'sha256))
(succeeded? (build-derivations %store (list input1 input2))))
(and succeeded?
(not (string=? (derivation-file-name input1)
(derivation-file-name input2)))
(string=? (derivation->output-path input1)
(derivation->output-path input2)))))
(test-assert "build-expression->derivation with a fixed-output input"
(let* ((builder1 '(call-with-output-file %output
(lambda (p)
(write "hello" p))))
(builder2 '(call-with-output-file (pk 'difference-here! %output)
(lambda (p)
(write "hello" p))))
(hash (sha256 (string->utf8 "hello")))
(input1 (build-expression->derivation %store "fixed" builder1
#:hash hash
#:hash-algo 'sha256))
(input2 (build-expression->derivation %store "fixed" builder2
#:hash hash
#:hash-algo 'sha256))
(builder3 '(let ((input (assoc-ref %build-inputs "input")))
(call-with-output-file %output
(lambda (out)
(format #f "My input is ~a.~%" input)))))
(final1 (build-expression->derivation %store "final" builder3
#:inputs
`(("input" ,input1))))
(final2 (build-expression->derivation %store "final" builder3
#:inputs
`(("input" ,input2)))))
(and (string=? (derivation->output-path final1)
(derivation->output-path final2))
(string=? (derivation->output-path final1)
(derivation-path->output-path
(derivation-file-name final1)))
(build-derivations %store (list final1 final2)))))
(test-assert "build-expression->derivation produces recursive fixed-output"
(let* ((builder '(begin
(use-modules (srfi srfi-26))
(mkdir %output)
(chdir %output)
(call-with-output-file "exe"
(cut display "executable" <>))
(chmod "exe" #o777)
(symlink "exe" "symlink")
(mkdir "subdir")))
(drv (build-expression->derivation %store "fixed-rec" builder
#:hash-algo 'sha256
#:hash (base32
"10k1lw41wyrjf9mxydi0is5nkpynlsvgslinics4ppir13g7d74p")
#:recursive? #t)))
(and (build-derivations %store (list drv))
(let* ((dir (derivation->output-path drv))
(exe (string-append dir "/exe"))
(link (string-append dir "/symlink"))
(subdir (string-append dir "/subdir")))
(and (executable-file? exe)
(string=? "executable"
(call-with-input-file exe get-string-all))
(string=? "exe" (readlink link))
(file-is-directory? subdir))))))
(test-assert "build-expression->derivation uses recursive fixed-output"
(let* ((builder '(call-with-output-file %output
(lambda (port)
(display "hello" port))))
(fixed (build-expression->derivation %store "small-fixed-rec"
builder
#:hash-algo 'sha256
#:hash (base32
"0sg9f58l1jj88w6pdrfdpj5x9b1zrwszk84j81zvby36q9whhhqa")
#:recursive? #t))
(in (derivation->output-path fixed))
(builder `(begin
(mkdir %output)
(chdir %output)
(symlink ,in "symlink")))
(drv (build-expression->derivation %store "fixed-rec-user"
builder
#:inputs `(("fixed" ,fixed)))))
(and (build-derivations %store (list drv))
(let ((out (derivation->output-path drv)))
(string=? (readlink (string-append out "/symlink")) in)))))
(test-assert "build-expression->derivation with #:references-graphs"
(let* ((input (add-text-to-store %store "foo" "hello"
(list %bash %mkdir)))
(builder '(copy-file "input" %output))
(drv (build-expression->derivation %store "references-graphs"
builder
#:references-graphs
`(("input" . ,input))))
(out (derivation->output-path drv)))
(define (deps path . deps)
(let ((count (length deps)))
(string-append path "\n\n" (number->string count) "\n"
(string-join (sort deps string<?) "\n")
(if (zero? count) "" "\n"))))
(and (build-derivations %store (list drv))
(equal? (call-with-input-file out get-string-all)
(string-concatenate
(map cdr
(sort (map (lambda (p d)
(cons p (apply deps p d)))
(list input %bash %mkdir)
(list (list %bash %mkdir)
'() '()))
(lambda (x y)
(match x
((p1 . _)
(match y
((p2 . _)
(string<? p1 p2)))))))))))))
(test-equal "map-derivation"
"hello"
(let* ((joke (package-derivation %store guile-1.8))
(good (package-derivation %store %bootstrap-guile))
(drv1 (build-expression->derivation %store "original-drv1"
#f ; systematically fail
#:guile-for-build joke))
(drv2 (build-expression->derivation %store "original-drv2"
'(call-with-output-file %output
(lambda (p)
(display "hello" p)))))
(drv3 (build-expression->derivation %store "drv-to-remap"
'(let ((in (assoc-ref
%build-inputs "in")))
(copy-file in %output))
#:inputs `(("in" ,drv1))
#:guile-for-build joke))
(drv4 (map-derivation %store drv3 `((,drv1 . ,drv2)
(,joke . ,good))))
(out (derivation->output-path drv4)))
(and (build-derivations %store (list (pk 'remapped drv4)))
(call-with-input-file out get-string-all))))
(test-equal "map-derivation, sources"
"hello"
(let* ((script1 (add-text-to-store %store "fail.sh" "exit 1"))
(script2 (add-text-to-store %store "hi.sh" "echo -n hello > $out"))
(bash-full (package-derivation %store (@ (gnu packages bash) bash)))
(drv1 (derivation %store "drv-to-remap"
;; XXX: This wouldn't work in practice, but if
;; we append "/bin/bash" then we can't replace
;; it with the bootstrap bash, which is a
;; single file.
(derivation->output-path bash-full)
`("-e" ,script1)
#:inputs `((,bash-full) (,script1))))
(drv2 (map-derivation %store drv1
`((,bash-full . ,%bash)
(,script1 . ,script2))))
(out (derivation->output-path drv2)))
(and (build-derivations %store (list (pk 'remapped* drv2)))
(call-with-input-file out get-string-all))))
(test-end)
(exit (= (test-runner-fail-count (test-runner-current)) 0))
| null | https://raw.githubusercontent.com/antono/guix-debian/85ef443788f0788a62010a942973d4f7714d10b4/tests/derivations.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Make sure we build everything by ourselves.
enter?
leaf
down
up
skip
error
Cheat to pass the actual file name to the
builder.
← local file name
Note: we can't compare the files because the above trick alters
the contents.
optional
A derivation D using a fixed-output derivation F doesn't has the same
path.
Here, the outputs are not listed in alphabetic order. Yet, the store
Check whether specifying several inputs coming from the same
multiple-output derivation works.
do echo $l ; done) < bash > $out/bash
do echo $l ; done) < input1 > $out/input1
do echo $l ; done) < input2 > $out/input2"
There's no specific error message to check for.
There's no specific error message to check for.
The only direct dependency is (%guile-for-build) and it's already
built.
Make sure these things are not already built.
Now INPUT-PATH is missing, yet it shouldn't be listed as a
Create fake substituter data, to be read by `substitute-binary'.
URL
Make sure substitutes are usable.
fail!
Note that the output path may exist at this point, but it
is invalid.
systematically fail
XXX: This wouldn't work in practice, but if
we append "/bin/bash" then we can't replace
it with the bootstrap bash, which is a
single file. | Copyright © 2012 , 2013 , 2014 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (test-derivations)
#:use-module (guix derivations)
#:use-module (guix store)
#:use-module (guix utils)
#:use-module (guix hash)
#:use-module (guix base32)
#:use-module ((guix packages) #:select (package-derivation base32))
#:use-module ((guix build utils) #:select (executable-file?))
#:use-module ((gnu packages) #:select (search-bootstrap-binary))
#:use-module (gnu packages bootstrap)
#:use-module ((gnu packages guile) #:select (guile-1.8))
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-11)
#:use-module (srfi srfi-26)
#:use-module (srfi srfi-34)
#:use-module (srfi srfi-64)
#:use-module (rnrs io ports)
#:use-module (rnrs bytevectors)
#:use-module (web uri)
#:use-module (ice-9 rdelim)
#:use-module (ice-9 regex)
#:use-module (ice-9 ftw)
#:use-module (ice-9 match))
(define %store
(false-if-exception (open-connection)))
(when %store
(set-build-options %store #:use-substitutes? #f)
By default , use % BOOTSTRAP - GUILE for the current system .
(let ((drv (package-derivation %store %bootstrap-guile)))
(%guile-for-build drv)))
(define (bootstrap-binary name)
(let ((bin (search-bootstrap-binary name (%current-system))))
(and %store
(add-to-store %store name #t "sha256" bin))))
(define %bash
(bootstrap-binary "bash"))
(define %mkdir
(bootstrap-binary "mkdir"))
(define* (directory-contents dir #:optional (slurp get-bytevector-all))
"Return an alist representing the contents of DIR."
(define prefix-len (string-length dir))
(alist-cons (string-drop path prefix-len)
(call-with-input-file path slurp)
result))
'()
dir)
(lambda (e1 e2)
(string<? (car e1) (car e2)))))
(test-begin "derivations")
(test-assert "parse & export"
(let* ((f (search-path %load-path "tests/test.drv"))
(b1 (call-with-input-file f get-bytevector-all))
(d1 (read-derivation (open-bytevector-input-port b1)))
(b2 (call-with-bytevector-output-port (cut write-derivation d1 <>)))
(d2 (read-derivation (open-bytevector-input-port b2))))
(and (equal? b1 b2)
(equal? d1 d2))))
(test-skip (if %store 0 12))
(test-assert "add-to-store, flat"
(let* ((file (search-path %load-path "language/tree-il/spec.scm"))
(drv (add-to-store %store "flat-test" #f "sha256" file)))
(and (eq? 'regular (stat:type (stat drv)))
(valid-path? %store drv)
(equal? (call-with-input-file file get-bytevector-all)
(call-with-input-file drv get-bytevector-all)))))
(test-assert "add-to-store, recursive"
(let* ((dir (dirname (search-path %load-path "language/tree-il/spec.scm")))
(drv (add-to-store %store "dir-tree-test" #t "sha256" dir)))
(and (eq? 'directory (stat:type (stat drv)))
(valid-path? %store drv)
(equal? (directory-contents dir)
(directory-contents drv)))))
(test-assert "derivation with no inputs"
(let* ((builder (add-text-to-store %store "my-builder.sh"
"echo hello, world\n"
'()))
(drv (derivation %store "foo"
%bash `("-e" ,builder)
#:env-vars '(("HOME" . "/homeless")))))
(and (store-path? (derivation-file-name drv))
(valid-path? %store (derivation-file-name drv)))))
(test-assert "build derivation with 1 source"
(let* ((builder (add-text-to-store %store "my-builder.sh"
"echo hello, world > \"$out\"\n"
'()))
(drv (derivation %store "foo"
%bash `(,builder)
#:env-vars '(("HOME" . "/homeless")
("zzz" . "Z!")
("AAA" . "A!"))
#:inputs `((,%bash) (,builder))))
(succeeded?
(build-derivations %store (list drv))))
(and succeeded?
(let ((path (derivation->output-path drv)))
(and (valid-path? %store path)
(string=? (call-with-input-file path read-line)
"hello, world"))))))
(test-assert "derivation with local file as input"
(let* ((builder (add-text-to-store
%store "my-builder.sh"
"(while read line ; do echo \"$line\" ; done) < $in > $out"
'()))
(input (search-path %load-path "ice-9/boot-9.scm"))
(input* (add-to-store %store (basename input)
#t "sha256" input))
(drv (derivation %store "derivation-with-input-file"
%bash `(,builder)
#:env-vars `(("in" . ,input*))
#:inputs `((,%bash)
(,builder)
(and (build-derivations %store (list drv))
(valid-path? %store (derivation->output-path drv)))))
(test-assert "fixed-output-derivation?"
(let* ((builder (add-text-to-store %store "my-fixed-builder.sh"
"echo -n hello > $out" '()))
(hash (sha256 (string->utf8 "hello")))
(drv (derivation %store "fixed"
%bash `(,builder)
#:inputs `((,builder))
#:hash hash #:hash-algo 'sha256)))
(fixed-output-derivation? drv)))
(test-assert "fixed-output derivation"
(let* ((builder (add-text-to-store %store "my-fixed-builder.sh"
"echo -n hello > $out" '()))
(hash (sha256 (string->utf8 "hello")))
(drv (derivation %store "fixed"
%bash `(,builder)
#:hash hash #:hash-algo 'sha256))
(succeeded? (build-derivations %store (list drv))))
(and succeeded?
(let ((p (derivation->output-path drv)))
(and (equal? (string->utf8 "hello")
(call-with-input-file p get-bytevector-all))
(bytevector? (query-path-hash %store p)))))))
(test-assert "fixed-output derivation: output paths are equal"
(let* ((builder1 (add-text-to-store %store "fixed-builder1.sh"
"echo -n hello > $out" '()))
(builder2 (add-text-to-store %store "fixed-builder2.sh"
"echo hey; echo -n hello > $out" '()))
(hash (sha256 (string->utf8 "hello")))
(drv1 (derivation %store "fixed"
%bash `(,builder1)
#:hash hash #:hash-algo 'sha256))
(drv2 (derivation %store "fixed"
%bash `(,builder2)
#:hash hash #:hash-algo 'sha256))
(succeeded? (build-derivations %store (list drv1 drv2))))
(and succeeded?
(equal? (derivation->output-path drv1)
(derivation->output-path drv2)))))
(test-assert "fixed-output derivation, recursive"
(let* ((builder (add-text-to-store %store "my-fixed-builder.sh"
"echo -n hello > $out" '()))
(hash (sha256 (string->utf8 "hello")))
(drv (derivation %store "fixed-rec"
%bash `(,builder)
#:inputs `((,builder))
#:hash (base32 "0sg9f58l1jj88w6pdrfdpj5x9b1zrwszk84j81zvby36q9whhhqa")
#:hash-algo 'sha256
#:recursive? #t))
(succeeded? (build-derivations %store (list drv))))
(and succeeded?
(let ((p (derivation->output-path drv)))
(and (equal? (string->utf8 "hello")
(call-with-input-file p get-bytevector-all))
(bytevector? (query-path-hash %store p)))))))
(test-assert "derivation with a fixed-output input"
output path when passed F or F ' , as long as F and F ' have the same output
(let* ((builder1 (add-text-to-store %store "fixed-builder1.sh"
"echo -n hello > $out" '()))
(builder2 (add-text-to-store %store "fixed-builder2.sh"
"echo hey; echo -n hello > $out" '()))
(hash (sha256 (string->utf8 "hello")))
(fixed1 (derivation %store "fixed"
%bash `(,builder1)
#:hash hash #:hash-algo 'sha256))
(fixed2 (derivation %store "fixed"
%bash `(,builder2)
#:hash hash #:hash-algo 'sha256))
(fixed-out (derivation->output-path fixed1))
(builder3 (add-text-to-store
%store "final-builder.sh"
Use Bash hackery to avoid Coreutils .
"echo $in ; (read -u 3 c; echo $c) 3< $in > $out" '()))
(final1 (derivation %store "final"
%bash `(,builder3)
#:env-vars `(("in" . ,fixed-out))
#:inputs `((,%bash) (,builder3) (,fixed1))))
(final2 (derivation %store "final"
%bash `(,builder3)
#:env-vars `(("in" . ,fixed-out))
#:inputs `((,%bash) (,builder3) (,fixed2))))
(succeeded? (build-derivations %store
(list final1 final2))))
(and succeeded?
(equal? (derivation->output-path final1)
(derivation->output-path final2)))))
(test-assert "multiple-output derivation"
(let* ((builder (add-text-to-store %store "my-fixed-builder.sh"
"echo one > $out ; echo two > $second"
'()))
(drv (derivation %store "fixed"
%bash `(,builder)
#:env-vars '(("HOME" . "/homeless")
("zzz" . "Z!")
("AAA" . "A!"))
#:inputs `((,%bash) (,builder))
#:outputs '("out" "second")))
(succeeded? (build-derivations %store (list drv))))
(and succeeded?
(let ((one (derivation->output-path drv "out"))
(two (derivation->output-path drv "second")))
(and (lset= equal?
(derivation->output-paths drv)
`(("out" . ,one) ("second" . ,two)))
(eq? 'one (call-with-input-file one read))
(eq? 'two (call-with-input-file two read)))))))
(test-assert "multiple-output derivation, non-alphabetic order"
path computation must reorder them first .
(let* ((builder (add-text-to-store %store "my-fixed-builder.sh"
"echo one > $out ; echo two > $AAA"
'()))
(drv (derivation %store "fixed"
%bash `(,builder)
#:inputs `((,%bash) (,builder))
#:outputs '("out" "AAA")))
(succeeded? (build-derivations %store (list drv))))
(and succeeded?
(let ((one (derivation->output-path drv "out"))
(two (derivation->output-path drv "AAA")))
(and (eq? 'one (call-with-input-file one read))
(eq? 'two (call-with-input-file two read)))))))
(test-assert "multiple-output derivation, derivation-path->output-path"
(let* ((builder (add-text-to-store %store "builder.sh"
"echo one > $out ; echo two > $second"
'()))
(drv (derivation %store "multiple"
%bash `(,builder)
#:outputs '("out" "second")))
(drv-file (derivation-file-name drv))
(one (derivation->output-path drv "out"))
(two (derivation->output-path drv "second"))
(first (derivation-path->output-path drv-file "out"))
(second (derivation-path->output-path drv-file "second")))
(and (not (string=? one two))
(string-suffix? "-second" two)
(string=? first one)
(string=? second two))))
(test-assert "user of multiple-output derivation"
(let* ((builder1 (add-text-to-store %store "my-mo-builder.sh"
"echo one > $out ; echo two > $two"
'()))
(mdrv (derivation %store "multiple-output"
%bash `(,builder1)
#:inputs `((,%bash) (,builder1))
#:outputs '("out" "two")))
(builder2 (add-text-to-store %store "my-mo-user-builder.sh"
echo \"($x $y)\" > $out"
'()))
(udrv (derivation %store "multiple-output-user"
%bash `(,builder2)
#:env-vars `(("one"
. ,(derivation->output-path
mdrv "out"))
("two"
. ,(derivation->output-path
mdrv "two")))
#:inputs `((,%bash)
(,builder2)
two occurrences of MDRV :
(,mdrv)
(,mdrv "two")))))
(and (build-derivations %store (list (pk 'udrv udrv)))
(let ((p (derivation->output-path udrv)))
(and (valid-path? %store p)
(equal? '(one two) (call-with-input-file p read)))))))
(test-assert "derivation with #:references-graphs"
(let* ((input1 (add-text-to-store %store "foo" "hello"
(list %bash)))
(input2 (add-text-to-store %store "bar"
(number->string (random 7777))
(list input1)))
(builder (add-text-to-store %store "build-graph"
(format #f "
~a $out
%mkdir)
(list %mkdir)))
(drv (derivation %store "closure-graphs"
%bash `(,builder)
#:references-graphs
`(("bash" . ,%bash)
("input1" . ,input1)
("input2" . ,input2))
#:inputs `((,%bash) (,builder))))
(out (derivation->output-path drv)))
(define (deps path . deps)
(let ((count (length deps)))
(string-append path "\n\n" (number->string count) "\n"
(string-join (sort deps string<?) "\n")
(if (zero? count) "" "\n"))))
(and (build-derivations %store (list drv))
(equal? (directory-contents out get-string-all)
`(("/bash" . ,(string-append %bash "\n\n0\n"))
("/input1" . ,(if (string>? input1 %bash)
(string-append (deps %bash)
(deps input1 %bash))
(string-append (deps input1 %bash)
(deps %bash))))
("/input2" . ,(string-concatenate
(map cdr
(sort
(map (lambda (p d)
(cons p (apply deps p d)))
(list %bash input1 input2)
(list '() (list %bash) (list input1)))
(lambda (x y)
(match x
((p1 . _)
(match y
((p2 . _)
(string<? p1 p2)))))))))))))))
(test-assert "derivation #:allowed-references, ok"
(let ((drv (derivation %store "allowed" %bash
'("-c" "echo hello > $out")
#:inputs `((,%bash))
#:allowed-references '())))
(build-derivations %store (list drv))))
(test-assert "derivation #:allowed-references, not allowed"
(let* ((txt (add-text-to-store %store "foo" "Hello, world."))
(drv (derivation %store "disallowed" %bash
`("-c" ,(string-append "echo " txt "> $out"))
#:inputs `((,%bash) (,txt))
#:allowed-references '())))
(guard (c ((nix-protocol-error? c)
#t))
(build-derivations %store (list drv))
#f)))
(test-assert "derivation #:allowed-references, self allowed"
(let ((drv (derivation %store "allowed" %bash
'("-c" "echo $out > $out")
#:inputs `((,%bash))
#:allowed-references '("out"))))
(build-derivations %store (list drv))))
(test-assert "derivation #:allowed-references, self not allowed"
(let ((drv (derivation %store "disallowed" %bash
`("-c" ,"echo $out > $out")
#:inputs `((,%bash))
#:allowed-references '())))
(guard (c ((nix-protocol-error? c)
#t))
(build-derivations %store (list drv))
#f)))
(define %coreutils
(false-if-exception
(and (getaddrinfo "www.gnu.org" "80" AI_NUMERICSERV)
(or (package-derivation %store %bootstrap-coreutils&co)
(nixpkgs-derivation "coreutils")))))
(test-skip (if %coreutils 0 1))
(test-assert "build derivation with coreutils"
(let* ((builder
(add-text-to-store %store "build-with-coreutils.sh"
"echo $PATH ; mkdir --version ; mkdir $out ; touch $out/good"
'()))
(drv
(derivation %store "foo"
%bash `(,builder)
#:env-vars `(("PATH" .
,(string-append
(derivation->output-path %coreutils)
"/bin")))
#:inputs `((,builder)
(,%coreutils))))
(succeeded?
(build-derivations %store (list drv))))
(and succeeded?
(let ((p (derivation->output-path drv)))
(and (valid-path? %store p)
(file-exists? (string-append p "/good")))))))
(test-skip (if (%guile-for-build) 0 8))
(test-assert "build-expression->derivation and derivation-prerequisites"
(let ((drv (build-expression->derivation %store "fail" #f)))
(any (match-lambda
(($ <derivation-input> path)
(string=? path (derivation-file-name (%guile-for-build)))))
(derivation-prerequisites drv))))
(test-assert "build-expression->derivation without inputs"
(let* ((builder '(begin
(mkdir %output)
(call-with-output-file (string-append %output "/test")
(lambda (p)
(display '(hello guix) p)))))
(drv (build-expression->derivation %store "goo" builder))
(succeeded? (build-derivations %store (list drv))))
(and succeeded?
(let ((p (derivation->output-path drv)))
(equal? '(hello guix)
(call-with-input-file (string-append p "/test") read))))))
(test-assert "build-expression->derivation and max-silent-time"
(let* ((store (let ((s (open-connection)))
(set-build-options s #:max-silent-time 1)
s))
(builder '(begin (sleep 100) (mkdir %output) #t))
(drv (build-expression->derivation store "silent" builder))
(out-path (derivation->output-path drv)))
(guard (c ((nix-protocol-error? c)
(and (string-contains (nix-protocol-error-message c)
"failed")
(not (valid-path? store out-path)))))
(build-derivations store (list drv))
#f)))
(test-assert "build-expression->derivation and timeout"
(let* ((store (let ((s (open-connection)))
(set-build-options s #:timeout 1)
s))
(builder '(begin (sleep 100) (mkdir %output) #t))
(drv (build-expression->derivation store "slow" builder))
(out-path (derivation->output-path drv)))
(guard (c ((nix-protocol-error? c)
(and (string-contains (nix-protocol-error-message c)
"failed")
(not (valid-path? store out-path)))))
(build-derivations store (list drv))
#f)))
(test-assert "build-expression->derivation and derivation-prerequisites-to-build"
(let ((drv (build-expression->derivation %store "fail" #f)))
(null? (derivation-prerequisites-to-build %store drv))))
(test-assert "derivation-prerequisites-to-build when outputs already present"
(let* ((builder '(begin (mkdir %output) #t))
(input-drv (build-expression->derivation %store "input" builder))
(input-path (derivation-output-path
(assoc-ref (derivation-outputs input-drv)
"out")))
(drv (build-expression->derivation %store "something" builder
#:inputs
`(("i" ,input-drv))))
(output (derivation->output-path drv)))
(when (valid-path? %store input-path)
(delete-paths %store (list input-path)))
(when (valid-path? %store output)
(delete-paths %store (list output)))
(and (equal? (map derivation-input-path
(derivation-prerequisites-to-build %store drv))
(list (derivation-file-name input-drv)))
Build DRV and delete its input .
(build-derivations %store (list drv))
(delete-paths %store (list input-path))
(not (valid-path? %store input-path))
prerequisite to build because DRV itself is already built .
(null? (derivation-prerequisites-to-build %store drv)))))
(test-skip (if (getenv "GUIX_BINARY_SUBSTITUTE_URL") 0 1))
(test-assert "derivation-prerequisites-to-build and substitutes"
(let* ((store (open-connection))
(drv (build-expression->derivation store "prereq-subst"
(random 1000)))
(output (derivation->output-path drv))
(dir (and=> (getenv "GUIX_BINARY_SUBSTITUTE_URL")
(compose uri-path string->uri))))
(call-with-output-file (string-append dir "/nix-cache-info")
(lambda (p)
(format p "StoreDir: ~a\nWantMassQuery: 0\n"
(%store-prefix))))
(call-with-output-file (string-append dir "/" (store-path-hash-part output)
".narinfo")
(lambda (p)
(format p "StorePath: ~a
URL: ~a
Compression: none
NarSize: 1234
References:
System: ~a
Deriver: ~a~%"
StorePath
System
(basename
Deriver
(set-build-options store #:use-substitutes? #t)
(let-values (((build download)
(derivation-prerequisites-to-build store drv))
((build* download*)
(derivation-prerequisites-to-build store drv
#:use-substitutes? #f)))
(pk build download build* download*)
(and (null? build)
(equal? download (list output))
(null? download*)
(null? build*)))))
(test-assert "build-expression->derivation with expression returning #f"
(let* ((builder '(begin
(mkdir %output)
(drv (build-expression->derivation %store "fail" builder))
(out-path (derivation->output-path drv)))
(guard (c ((nix-protocol-error? c)
(and (string-match "build .* failed"
(nix-protocol-error-message c))
(not (valid-path? %store out-path)))))
(build-derivations %store (list drv))
#f)))
(test-assert "build-expression->derivation with two outputs"
(let* ((builder '(begin
(call-with-output-file (assoc-ref %outputs "out")
(lambda (p)
(display '(hello) p)))
(call-with-output-file (assoc-ref %outputs "second")
(lambda (p)
(display '(world) p)))))
(drv (build-expression->derivation %store "double" builder
#:outputs '("out"
"second")))
(succeeded? (build-derivations %store (list drv))))
(and succeeded?
(let ((one (derivation->output-path drv))
(two (derivation->output-path drv "second")))
(and (equal? '(hello) (call-with-input-file one read))
(equal? '(world) (call-with-input-file two read)))))))
(test-skip (if %coreutils 0 1))
(test-assert "build-expression->derivation with one input"
(let* ((builder '(call-with-output-file %output
(lambda (p)
(let ((cu (assoc-ref %build-inputs "cu")))
(close 1)
(dup2 (port->fdes p) 1)
(execl (string-append cu "/bin/uname")
"uname" "-a")))))
(drv (build-expression->derivation %store "uname" builder
#:inputs
`(("cu" ,%coreutils))))
(succeeded? (build-derivations %store (list drv))))
(and succeeded?
(let ((p (derivation->output-path drv)))
(string-contains (call-with-input-file p read-line) "GNU")))))
(test-assert "imported-files"
(let* ((files `(("x" . ,(search-path %load-path "ice-9/q.scm"))
("a/b/c" . ,(search-path %load-path
"guix/derivations.scm"))
("p/q" . ,(search-path %load-path "guix.scm"))
("p/z" . ,(search-path %load-path "guix/store.scm"))))
(drv (imported-files %store files)))
(and (build-derivations %store (list drv))
(let ((dir (derivation->output-path drv)))
(every (match-lambda
((path . source)
(equal? (call-with-input-file (string-append dir "/" path)
get-bytevector-all)
(call-with-input-file source
get-bytevector-all))))
files)))))
(test-assert "build-expression->derivation with modules"
(let* ((builder `(begin
(use-modules (guix build utils))
(let ((out (assoc-ref %outputs "out")))
(mkdir-p (string-append out "/guile/guix/nix"))
#t)))
(drv (build-expression->derivation %store "test-with-modules"
builder
#:modules
'((guix build utils)))))
(and (build-derivations %store (list drv))
(let* ((p (derivation->output-path drv))
(s (stat (string-append p "/guile/guix/nix"))))
(eq? (stat:type s) 'directory)))))
(test-assert "build-expression->derivation: same fixed-output path"
(let* ((builder1 '(call-with-output-file %output
(lambda (p)
(write "hello" p))))
(builder2 '(call-with-output-file (pk 'difference-here! %output)
(lambda (p)
(write "hello" p))))
(hash (sha256 (string->utf8 "hello")))
(input1 (build-expression->derivation %store "fixed" builder1
#:hash hash
#:hash-algo 'sha256))
(input2 (build-expression->derivation %store "fixed" builder2
#:hash hash
#:hash-algo 'sha256))
(succeeded? (build-derivations %store (list input1 input2))))
(and succeeded?
(not (string=? (derivation-file-name input1)
(derivation-file-name input2)))
(string=? (derivation->output-path input1)
(derivation->output-path input2)))))
(test-assert "build-expression->derivation with a fixed-output input"
(let* ((builder1 '(call-with-output-file %output
(lambda (p)
(write "hello" p))))
(builder2 '(call-with-output-file (pk 'difference-here! %output)
(lambda (p)
(write "hello" p))))
(hash (sha256 (string->utf8 "hello")))
(input1 (build-expression->derivation %store "fixed" builder1
#:hash hash
#:hash-algo 'sha256))
(input2 (build-expression->derivation %store "fixed" builder2
#:hash hash
#:hash-algo 'sha256))
(builder3 '(let ((input (assoc-ref %build-inputs "input")))
(call-with-output-file %output
(lambda (out)
(format #f "My input is ~a.~%" input)))))
(final1 (build-expression->derivation %store "final" builder3
#:inputs
`(("input" ,input1))))
(final2 (build-expression->derivation %store "final" builder3
#:inputs
`(("input" ,input2)))))
(and (string=? (derivation->output-path final1)
(derivation->output-path final2))
(string=? (derivation->output-path final1)
(derivation-path->output-path
(derivation-file-name final1)))
(build-derivations %store (list final1 final2)))))
(test-assert "build-expression->derivation produces recursive fixed-output"
(let* ((builder '(begin
(use-modules (srfi srfi-26))
(mkdir %output)
(chdir %output)
(call-with-output-file "exe"
(cut display "executable" <>))
(chmod "exe" #o777)
(symlink "exe" "symlink")
(mkdir "subdir")))
(drv (build-expression->derivation %store "fixed-rec" builder
#:hash-algo 'sha256
#:hash (base32
"10k1lw41wyrjf9mxydi0is5nkpynlsvgslinics4ppir13g7d74p")
#:recursive? #t)))
(and (build-derivations %store (list drv))
(let* ((dir (derivation->output-path drv))
(exe (string-append dir "/exe"))
(link (string-append dir "/symlink"))
(subdir (string-append dir "/subdir")))
(and (executable-file? exe)
(string=? "executable"
(call-with-input-file exe get-string-all))
(string=? "exe" (readlink link))
(file-is-directory? subdir))))))
(test-assert "build-expression->derivation uses recursive fixed-output"
(let* ((builder '(call-with-output-file %output
(lambda (port)
(display "hello" port))))
(fixed (build-expression->derivation %store "small-fixed-rec"
builder
#:hash-algo 'sha256
#:hash (base32
"0sg9f58l1jj88w6pdrfdpj5x9b1zrwszk84j81zvby36q9whhhqa")
#:recursive? #t))
(in (derivation->output-path fixed))
(builder `(begin
(mkdir %output)
(chdir %output)
(symlink ,in "symlink")))
(drv (build-expression->derivation %store "fixed-rec-user"
builder
#:inputs `(("fixed" ,fixed)))))
(and (build-derivations %store (list drv))
(let ((out (derivation->output-path drv)))
(string=? (readlink (string-append out "/symlink")) in)))))
(test-assert "build-expression->derivation with #:references-graphs"
(let* ((input (add-text-to-store %store "foo" "hello"
(list %bash %mkdir)))
(builder '(copy-file "input" %output))
(drv (build-expression->derivation %store "references-graphs"
builder
#:references-graphs
`(("input" . ,input))))
(out (derivation->output-path drv)))
(define (deps path . deps)
(let ((count (length deps)))
(string-append path "\n\n" (number->string count) "\n"
(string-join (sort deps string<?) "\n")
(if (zero? count) "" "\n"))))
(and (build-derivations %store (list drv))
(equal? (call-with-input-file out get-string-all)
(string-concatenate
(map cdr
(sort (map (lambda (p d)
(cons p (apply deps p d)))
(list input %bash %mkdir)
(list (list %bash %mkdir)
'() '()))
(lambda (x y)
(match x
((p1 . _)
(match y
((p2 . _)
(string<? p1 p2)))))))))))))
(test-equal "map-derivation"
"hello"
(let* ((joke (package-derivation %store guile-1.8))
(good (package-derivation %store %bootstrap-guile))
(drv1 (build-expression->derivation %store "original-drv1"
#:guile-for-build joke))
(drv2 (build-expression->derivation %store "original-drv2"
'(call-with-output-file %output
(lambda (p)
(display "hello" p)))))
(drv3 (build-expression->derivation %store "drv-to-remap"
'(let ((in (assoc-ref
%build-inputs "in")))
(copy-file in %output))
#:inputs `(("in" ,drv1))
#:guile-for-build joke))
(drv4 (map-derivation %store drv3 `((,drv1 . ,drv2)
(,joke . ,good))))
(out (derivation->output-path drv4)))
(and (build-derivations %store (list (pk 'remapped drv4)))
(call-with-input-file out get-string-all))))
(test-equal "map-derivation, sources"
"hello"
(let* ((script1 (add-text-to-store %store "fail.sh" "exit 1"))
(script2 (add-text-to-store %store "hi.sh" "echo -n hello > $out"))
(bash-full (package-derivation %store (@ (gnu packages bash) bash)))
(drv1 (derivation %store "drv-to-remap"
(derivation->output-path bash-full)
`("-e" ,script1)
#:inputs `((,bash-full) (,script1))))
(drv2 (map-derivation %store drv1
`((,bash-full . ,%bash)
(,script1 . ,script2))))
(out (derivation->output-path drv2)))
(and (build-derivations %store (list (pk 'remapped* drv2)))
(call-with-input-file out get-string-all))))
(test-end)
(exit (= (test-runner-fail-count (test-runner-current)) 0))
|
1ee8d080c44edd6f58d1e99adadd744787796e2813fac129aef623b8fa99bc2d | lumberdev/auth0-clojure | management.clj | (ns auth0-clojure.descriptors.management)
;; TODO - better docs
;; TODO - query params (in the format {:filter "string"} for now
(def api-descriptor
{:version "2.0"
:metadata {:endpoint-prefix "/api/v2/"}
:operations {
;; Branding
:get-branding-settings {:name :get-branding-settings
:doc "Use this endpoint to retrieve various settings related to branding."
:doc-url "#!/Branding/get_branding"
:http {:path ["branding"]
:method :get
:response-code 200}}
:update-branding-settings {:name :update-branding-settings
:doc "Use this endpoint to update various fields related to branding."
:doc-url "#!/Branding/patch_branding"
:http {:path ["branding"]
:method :patch
:response-code 200}}
;; Client Grants
:get-client-grants {:name :get-client-grants
:doc "Retrieve client grants."
:doc-url "#!/Client_Grants/get_client_grants"
:http {:path ["client-grants"]
:method :get
:response-code 200}}
:create-client-grant {:name :create-client-grant
:doc "Create a client grant."
:doc-url "#!/Client_Grants/post_client_grants"
:http {:path ["client-grants"]
:method :post
:response-code 201}}
:update-client-grant {:name :update-client-grant
:doc "Update a client grant."
:doc-url "#!/Client_Grants/patch_client_grants_by_id"
:http {:path ["client-grants" :id]
:method :patch
:response-code 200}}
:delete-client-grant {:name :delete-client-grant
:doc "Delete a client grant."
:doc-url "#!/Client_Grants/delete_client_grants_by_id"
:http {:path ["client-grants" :id]
:method :delete
:response-code 204}}
;;Clients
:get-clients {:name :get-clients
:doc "Retrieves a list of all client applications. Accepts a list of fields to include or exclude. Important: The client_secret and encryption_key attributes can only be retrieved with the read:client_keys scope."
:doc-url "#!/Clients/get_clients"
:http {:path ["clients"]
:method :get
:response-code 200}}
:create-client {:name :create-client
:doc "Creates a new client application. The samples on the right show most attributes that can be used. We recommend to let us to generate a safe secret for you, but you can also provide your own with the client_secret parameter"
:doc-url "#!/Clients/post_clients"
:http {:path ["clients"]
:method :post
:response-code 201}}
:get-client {:name :get-client
:doc "Retrieves a client by its id. Important: The client_secret encryption_key and signing_keys attributes can only be retrieved with the read:client_keys scope."
:doc-url "#!/Clients/get_clients_by_id"
:http {:path ["clients" :id]
:method :get
:response-code 200}}
:update-client {:name :update-client
:doc "Important: The client_secret and encryption_key attributes can only be updated with the update:client_keys scope."
:doc-url "#!/Clients/patch_clients_by_id"
:http {:path ["clients" :id]
:method :patch
:response-code 200}}
:delete-client {:name :delete-client
:doc "Deletes a client and all its related assets (like rules, connections, etc) given its id."
:doc-url "#!/Clients/delete_clients_by_id"
:http {:path ["clients" :id]
:method :delete
:response-code 204}}
:rotate-client-secret {:name :rotate-client-secret
:doc "Rotate a client secret. The generated secret is NOT base64 encoded."
:doc-url "#!/Clients/post_rotate_secret"
:http {:path ["clients" :id "rotate-secret"]
:method :post
:response-code 200}}
Connections
:get-connections {:name :get-connections
:doc "Retrieves every connection matching the specified strategy. All connections are retrieved if no strategy is being specified. Accepts a list of fields to include or exclude in the resulting list of connection objects."
:doc-url "#!/Connections/get_connections"
:http {:path ["connections"]
:method :get
:response-code 200}}
:create-connection {:name :create-connection
:doc "Creates a new connection according to the JSON object received in body. Valid Strategy names are: ad, adfs, amazon, apple, dropbox, bitbucket, aol, auth0-adldap, auth0-oidc, auth0, baidu, bitly, box, custom, daccount, dwolla, email, evernote-sandbox, evernote, exact, facebook, fitbit, flickr, github, google-apps, google-oauth2, instagram, ip, linkedin, miicard, oauth1, oauth2, office365, oidc, paypal, paypal-sandbox, pingfederate, planningcenter, renren, salesforce-community, salesforce-sandbox, salesforce, samlp, sharepoint, shopify, sms, soundcloud, thecity-sandbox, thecity, thirtysevensignals, twitter, untappd, vkontakte, waad, weibo, windowslive, wordpress, yahoo, yammer, yandex, line."
:doc-url "#!/Connections/post_connections"
:http {:path ["connections"]
:method :post
:response-code 201}}
:get-connection {:name :get-connection
:doc "Retrieves a connection by its ID."
:doc-url "#!/Connections/get_connections_by_id"
:http {:path ["connections" :id]
:method :get
:response-code 200}}
:update-connection {:name :update-connection
:doc "Updates a connection."
:doc-url "#!/Connections/patch_connections_by_id"
:http {:path ["connections" :id]
:method :patch
:response-code 200}}
:delete-connection {:name :delete-connection
:doc "Deletes a connection and all its users."
:doc-url "#!/Connections/delete_connections_by_id"
:http {:path ["connections" :id]
:method :delete
:response-code 204}}
:delete-user-by-email {:name :delete-user-by-email
:doc "Deletes a specified connection user by its email (you cannot delete all users from specific connection). Currently, only Database Connections are supported."
:doc-url "#!/Connections/delete_users_by_email"
:http {:path ["connections" :id "users"]
:method :delete
:response-code 204}}
;; Custom Domains
:get-custom-domains {:name :get-custom-domains
:doc "Retrieves details on custom domains."
:doc-url "#!/Custom_Domains/get_custom_domains"
:http {:path ["custom-domains"]
:method :get
:response-code 200}}
:config-new-custom-domain {:name :config-new-custom-domain
:doc "Create a new custom domain."
:doc-url "#!/Custom_Domains/post_custom_domains"
:http {:path ["custom-domains"]
:method :post
:response-code 201}}
:get-custom-domain {:name :get-custom-domain
:doc "Retrieve a custom domain configuration and status."
:doc-url "#!/Custom_Domains/get_custom_domains_by_id"
:http {:path ["custom-domains" :id]
:method :get
:response-code 200}}
:verify-custom-domain {:name :verify-custom-domain
:doc "Run the verification process on a custom domain. Note: Check the `status` field to see its verification status. Once verification is complete, it may take up to 10 minutes before the custom domain can start accepting requests."
:doc-url "#!/Custom_Domains/post_verify"
:http {:path ["custom-domains" :id "verify"]
:method :post
:response-code 200}}
:delete-custom-domain-config {:name :delete-custom-domain-config
:doc "Delete a custom domain and stop serving requests for it."
:doc-url "#!/Custom_Domains/delete_custom_domains_by_id"
:http {:path ["custom-domains" :id]
:method :delete
:response-code 204}}
;; Device Credentials
:get-device-credentials {:name :get-device-credentials
:doc "Manage the devices that are recognized and authenticated. Please note that Device Credentials endpoints are designed for ad hoc administrative use only."
:doc-url "#!/Device_Credentials/get_device_credentials"
:http {:path ["device-credentials"]
:method :get
:response-code 200}}
:create-device-public-key {:name :create-device-public-key
:doc "Manage the devices that are recognized and authenticated. Please note that Device Credentials endpoints are designed for ad hoc administrative use only."
:doc-url "#!/Device_Credentials/post_device_credentials"
:http {:path ["device-credentials"]
:method :post
:response-code 201}}
:delete-device-public-key {:name :delete-device-public-key
:doc "Manage the devices that are recognized and authenticated. Please note that Device Credentials endpoints are designed for ad hoc administrative use only."
:doc-url "#!/Device_Credentials/delete_device_credentials_by_id"
:http {:path ["device-credentials" :id]
:method :delete
:response-code 204}}
;; Grants
:get-grants {:name :get-grants
:doc "Manage the grants associated with your account."
:doc-url "#!/Grants/get_grants"
:http {:path ["grants"]
:method :get
:response-code 200}}
:delete-grant {:name :delete-grant
:doc ""
:doc-url "#!/Grants/delete_grants_by_id"
:http {:path ["grants" :id]
:method :delete
:response-code 204}}
;; Logs
:search-log-events {:name :search-log-events
:doc "Retrieves log entries that match the specified search criteria (or lists all log entries if no criteria are used). Set custom search criteria using the q parameter, or search from a specific log ID (\"search from checkpoint\")."
:doc-url "#!/Logs/get_logs"
:http {:path ["logs"]
:method :get
:response-code 200}}
:get-log-event {:name :get-log-event
:doc "Retrieves the data related to the log entry identified by id. This returns a single log entry representation as specified in the schema."
:doc-url "#!/Logs/get_logs_by_id"
:http {:path ["logs" :id]
:method :get
:response-code 200}}
;; Prompts
:get-prompt-settings {:name :get-prompt-settings
:doc "Retrieve prompts settings."
:doc-url "#!/Prompts/get_prompts"
:http {:path ["prompts"]
:method :get
:response-code 200}}
:update-prompt-settings {:name :update-prompt-settings
:doc "Update prompts settings."
:doc-url "#!/Prompts/patch_prompts"
:http {:path ["prompts"]
:method :patch
:response-code 200}}
;; Roles
:get-roles {:name :get-roles
:doc "Lists all the roles."
:doc-url "#!/Roles/get_roles"
:http {:path ["roles"]
:method :get
:response-code 200}}
:create-role {:name :create-role
:doc "Creates a new role."
:doc-url "#!/Roles/post_roles"
:http {:path ["roles"]
:method :post
:response-code 200}}
:get-role {:name :get-role
:doc "Gets the information for a role."
:doc-url "#!/Roles/get_roles_by_id"
:http {:path ["roles" :id]
:method :get
:response-code 200}}
:update-role {:name :update-role
:doc "Updates a role with new values."
:doc-url "#!/Roles/patch_roles_by_id"
:http {:path ["roles" :id]
:method :patch
:response-code 200}}
:delete-role {:name :delete-role
:doc "Deletes a role used in authorization of users against resource servers."
:doc-url "#!/Roles/delete_roles_by_id"
:http {:path ["roles" :id]
:method :delete
:response-code 204}}
:get-role-permissions {:name :get-role-permissions
:doc "Gets the permissions for a role."
:doc-url "#!/Roles/get_role_permission"
:http {:path ["roles" :id "permissions"]
:method :get
:response-code 200}}
:associate-role-permissions {:name :associate-role-permissions
:doc "Associates permissions with a role."
:doc-url "#!/Roles/post_role_permission_assignment"
:http {:path ["roles" :id "permissions"]
:method :post
:response-code 201}}
:unassociate-role-permissions {:name :unassociate-role-permissions
:doc "Unassociates permissions from a role."
:doc-url "#!/Roles/delete_role_permission_assignment"
:http {:path ["roles" :id "permissions"]
:method :delete
TODO - descriptor - should n't this be 204 ? ? ?
:response-code 200}}
:get-role-users {:name :get-role-users
:doc "Lists the users that have been associated with a given role."
:doc-url "#!/Roles/get_role_user"
:http {:path ["roles" :id "users"]
:method :get
:response-code 200}}
:assign-role-users {:name :assign-role-users
:doc "Assign users to a role."
:doc-url "#!/Roles/post_role_users"
:http {:path ["roles" :id "users"]
:method :post
:response-code 200}}
;; Rules
:get-rules {:name :get-rules
:doc "Retrieves a list of all rules. Accepts a list of fields to include or exclude."
:doc-url "#!/Rules/get_rules"
:http {:path ["rules"]
:method :get
:response-code 200}}
:create-rule {:name :create-rule
:doc "Creates a new rule according to the JSON object received in body."
:doc-url "#!/Rules/post_rules"
:http {:path ["rules"]
:method :post
:response-code 201}}
:get-rule {:name :get-rule
:doc "Retrieves a rule by its ID. Accepts a list of fields to include or exclude in the result."
:doc-url "#!/Rules/get_rules_by_id"
:http {:path ["rules" :id]
:method :get
:response-code 200}}
:update-rule {:name :update-rule
:doc "Use this endpoint to update an existing rule."
:doc-url "#!/Rules/patch_rules_by_id"
:http {:path ["rules" :id]
:method :patch
:response-code 200}}
:delete-rule {:name :delete-rule
:doc "To be used to delete a rule."
:doc-url "#!/Rules/delete_rules_by_id"
:http {:path ["rules" :id]
:method :delete
:response-code 204}}
;; Rules Configs
:get-rules-configs {:name :get-rules-configs
:doc "Returns only rules config variable keys. For security, config variable values cannot be retrieved outside rule execution"
:doc-url "#!/Rules_Configs/get_rules_configs"
:http {:path ["rules-configs"]
:method :get
:response-code 200}}
:set-rules-config {:name :set-rules-config
:doc "Rules config keys must be of the format ^[A-Za-z0-9_\\-@*+:]*$."
:doc-url "#!/Rules_Configs/put_rules_configs_by_key"
:http {:path ["rules-configs" :key]
:method :put
:response-code 200}}
:delete-rules-config {:name :delete-rules-config
:doc "Rules config keys must be of the format ^[A-Za-z0-9_\\-@*+:]*$."
:doc-url "#!/Rules_Configs/delete_rules_configs_by_key"
:http {:path ["rules-configs" :key]
:method :delete
:response-code 204}}
;; User Blocks
:get-user-blocks {:name :get-user-blocks
:doc "This endpoint can be used to retrieve a list of blocked IP addresses of a particular user given a user_id."
:doc-url "#!/User_Blocks/get_user_blocks_by_id"
:http {:path ["user-blocks" :id]
:method :get
:response-code 200}}
:unblock-user {:name :unblock-user
:doc "This endpoint can be used to unblock a user that was blocked due to an excessive amount of incorrectly provided credentials."
:doc-url "#!/User_Blocks/delete_user_blocks_by_id"
:http {:path ["user-blocks" :id]
:method :delete
:response-code 204}}
:get-user-blocks-by-identifier {:name :get-user-blocks-by-identifier
:doc "This endpoint can be used to retrieve a list of blocked IP addresses for a given key."
:doc-url "#!/User_Blocks/get_user_blocks"
:http {:path ["user-blocks"]
:method :get
:response-code 200}}
:unblock-user-by-identifier {:name :unblock-user-by-identifier
:doc "This endpoint can be used to unblock a given key that was blocked due to an excessive amount of incorrectly provided credentials."
:doc-url "#!/User_Blocks/delete_user_blocks"
:http {:path ["user-blocks"]
:method :delete
:response-code 204}}
;; Users
:get-users {:name :get-users
:doc "This endpoint can be used to retrieve a list of users."
:doc-url "#!/Users/get_users"
:http {:path ["users"]
:method :get
:response-code 200}}
:get-users-by-email {:name :get-users-by-email
:doc "If Auth0 is the identify provider (idP), the email address associated with a user is saved in lower case, regardless of how you initially provided it. For example, if you register a user as , Auth0 saves the user's email as . In cases where Auth0 is not the idP, the `email` is stored based on the rules of idP, so make sure the search is made using the correct capitalization."
:doc-url "#!/Users_By_Email/get_users_by_email"
:http {:path ["users-by-email"]
:method :get
:response-code 200}}
:create-user {:name :create-user
:doc "Creates a new user according to the JSON object received in body. It works only for database and passwordless connections."
:doc-url "#!/Users/post_users"
:http {:path ["users"]
:method :post
:response-code 201}}
:get-user {:name :get-user
:doc "This endpoint can be used to retrieve user details given the user_id."
:doc-url "#!/Users/get_users_by_id"
:http {:path ["users" :id]
:method :get
:response-code 200}}
:update-user {:name :update-user
:doc "Updates a user with the object's properties received in the request's body (the object should be a JSON object)."
:doc-url "#!/Users/patch_users_by_id"
:http {:path ["users" :id]
:method :patch
:response-code 200}}
:delete-user {:name :delete-user
:doc "This endpoint can be used to delete a single user based on the id."
:doc-url "#!/Users/delete_users_by_id"
:http {:path ["users" :id]
:method :delete
:response-code 204}}
:get-user-roles {:name :get-user-roles
:doc "List the the roles associated with a user."
:doc-url "#!/Users/get_user_roles"
:http {:path ["users" :id "roles"]
:method :get
:response-code 200}}
:assign-user-roles {:name :assign-user-roles
:doc "Associate an array of roles with a user."
:doc-url "#!/Users/post_user_roles"
:http {:path ["users" :id "roles"]
:method :post
:response-code 201}}
:unassign-user-roles {:name :unassign-user-roles
:doc "Removes an array of roles from a user."
:doc-url "#!/Users/delete_user_roles"
:http {:path ["users" :id "roles"]
:method :delete
:response-code 204}}
:get-user-log-events {:name :get-user-log-events
:doc "Retrieve every log event for a specific user id."
:doc-url "#!/Users/get_logs_by_user"
:http {:path ["users" :id "logs"]
:method :get
:response-code 200}}
:get-user-guardian-enrollments {:name :get-user-guardian-enrollments
:doc "Retrieves all Guardian enrollments."
:doc-url "#!/Users/get_enrollments"
:http {:path ["users" :id "enrollments"]
:method :get
:response-code 200}}
:generate-guardian-recovery-code {:name :generate-guardian-recovery-code
:doc "This endpoint removes the current Guardian recovery code then generates and returns a new one."
:doc-url "#!/Users/post_recovery_code_regeneration"
:http {:path ["users" :id "recovery-code-generation"]
:method :post
:response-code 200}}
:get-user-permissions {:name :get-user-permissions
:doc "Get the permissions associated to the user."
:doc-url "#!/Users/get_permissions"
:http {:path ["users" :id "permissions"]
:method :get
:response-code 200}}
:assign-user-permissions {:name :assign-user-permissions
:doc "This endpoint assigns the permission specified in the request payload to the user defined in the path."
:doc-url "#!/Users/post_permissions"
:http {:path ["users" :id "permissions"]
:method :post
:response-code 201}}
:unassign-user-permissions {:name :unassign-user-permissions
:doc "Removes permissions from a user."
:doc-url "#!/Users/delete_permissions"
:http {:path ["users" :id "permissions"]
:method :delete
:response-code 204}}
:delete-user-multifactor-provider {:name :delete-user-multifactor-provider
:doc "This endpoint can be used to delete the multifactor provider settings for a particular user. This will force user to re-configure the multifactor provider."
:doc-url "#!/Users/delete_multifactor_by_provider"
:http {:path ["users" :id "multifactor" :provider]
:method :delete
:response-code 204}}
:link-user-account {:name :link-user-account
:doc "Links the account specified in the body (secondary account) to the account specified by the id param of the URL (primary account)."
:doc-url "#!/Users/post_identities"
:http {:path ["users" :id "identities"]
:method :post
:response-code 201}}
:unlink-user-account {:name :unlink-user-account
:doc "Unlinks an identity from the target user, and it becomes a separated user again."
:doc-url "#!/Users/delete_user_identity_by_user_id"
:http {:path ["users" :id "identities" :provider :user-id]
:method :delete
:response-code 204}}
:invalidate-user-mfa-browsers {:name :invalidate-user-mfa-browsers
:doc "This endpoint invalidates all remembered browsers for all authentication factors for the selected user."
:doc-url "#!/Users/post_invalidate_remember_browser"
:http {:path ["users" :id "multifactor" "actions" "invalidate-remember-browser"]
:method :post
:response-code 204}}
Blacklists
:get-blacklisted-tokens {:name :get-blacklisted-tokens
:doc "Retrieve the `jti` and `aud` of all tokens that are blacklisted."
:doc-url "#!/Blacklists/get_tokens"
:http {:path ["blacklists" "tokens"]
:method :get
:response-code 200}}
:blacklist-token {:name :blacklist-token
:doc "Add the token identified by the `jti` to a blacklist for the tenant."
:doc-url "#!/Blacklists/post_tokens"
:http {:path ["blacklists" "tokens"]
:method :post
:response-code 204}}
;; Email Templates
:create-email-template {:name :create-email-template
:doc ""
:doc-url "#!/Email_Templates/post_email_templates"
:http {:path ["email-templates"]
:method :post
:response-code 200}}
:get-email-template {:name :get-email-template
:doc ""
:doc-url "#!/Email_Templates/get_email_templates_by_templateName"
:http {:path ["email-templates" :template-name]
:method :get
:response-code 200}}
:update-email-template {:name :update-email-template
:doc ""
:doc-url "#!/Email_Templates/patch_email_templates_by_templateName"
:http {:path ["email-templates" :template-name]
:method :patch
:response-code 200}}
:set-email-template {:name :set-email-template
:doc ""
:doc-url "#!/Email_Templates/put_email_templates_by_templateName"
:http {:path ["email-templates" :template-name]
:method :put
:response-code 200}}
;; Emails
:create-email-provider {:name :create-email-provider
:doc "To be used to set a new email provider."
:doc-url "#!/Emails/post_provider"
:http {:path ["emails" "provider"]
:method :post
:response-code 200}}
:get-email-provider {:name :get-email-provider
:doc "This endpoint can be used to retrieve the current email provider configuration."
:doc-url "#!/Emails/get_provider"
:http {:path ["emails" "provider"]
:method :get
:response-code 200}}
:update-email-provider {:name :update-email-provider
:doc "Can be used to change details for an email provider.\n"
:doc-url "#!/Emails/patch_provider"
:http {:path ["emails" "provider"]
:method :patch
:response-code 200}}
:delete-email-provider {:name :delete-email-provider
:doc ""
:doc-url "#!/Emails/delete_provider"
:http {:path ["emails" "provider"]
:method :delete
:response-code 204}}
Guardian
:get-guardian-factors {:name :get-guardian-factors
:doc "Retrieves all factors. Useful to check factor enablement and trial status."
:doc-url "#!/Guardian/get_factors"
:http {:path ["guardian" "factors"]
:method :get
:response-code 200}}
:set-guardian-factor {:name :set-guardian-factor
:doc "Useful to enable / disable factor."
:doc-url "#!/Guardian/put_factors_by_name"
:http {:path ["guardian" "factors" :name]
:method :put
:response-code 200}}
:create-guardian-enrollment-ticket {:name :create-guardian-enrollment-ticket
:doc "Generate an email with a link to start the Guardian enrollment process."
:doc-url "#!/Guardian/post_ticket"
:http {:path ["guardian" "enrollments" "ticket"]
:method :post
:response-code 204}}
:get-guardian-enrollment {:name :get-guardian-enrollment
:doc "Retrieves an enrollment. Useful to check its type and related metadata. Note that phone number data is partially obfuscated."
:doc-url "#!/Guardian/get_enrollments_by_id"
:http {:path ["guardian" "enrollments" :id]
:method :get
:response-code 200}}
:delete-guardian-enrollment {:name :delete-guardian-enrollment
:doc "Deletes an enrollment. Useful when you want to force the user to re-enroll with Guardian."
:doc-url "#!/Guardian/delete_enrollments_by_id"
:http {:path ["guardian" "enrollments" :id]
:method :delete
:response-code 200}}
:get-guardian-factor-templates {:name :get-guardian-factor-templates
:doc "Retrieves enrollment and verification templates. You can use this to check the current values for your templates."
:doc-url "#!/Guardian/get_templates"
:http {:path ["guardian" "factors" "sms" "templates"]
:method :get
:response-code 200}}
:update-guardian-factor-templates {:name :update-guardian-factor-templates
:doc "Useful to send custom messages on SMS enrollment and verification."
:doc-url "#!/Guardian/put_templates"
:http {:path ["guardian" "factors" "sms" "templates"]
:method :put
:response-code 200}}
:get-guardian-factor-sns {:name :get-guardian-factor-sns
:doc "Returns provider configuration for AWS SNS."
:doc-url "#!/Guardian/get_sns"
:http {:path ["guardian" "factors" "push-notification" "providers" "sns"]
:method :get
:response-code 200}}
:set-guardian-factor-sns {:name :set-guardian-factor-sns
:doc "Useful to configure the push notification provider."
:doc-url "#!/Guardian/put_sns"
:http {:path ["guardian" "factors" "push-notification" "providers" "sns"]
:method :put
:response-code 200}}
:get-guardian-factor-twilio {:name :get-guardian-factor-twilio
:doc "Returns provider configuration."
:doc-url "#!/Guardian/get_twilio"
:http {:path ["guardian" "factors" "push-notification" "providers" "twilio"]
:method :get
:response-code 200}}
:set-guardian-factor-twilio {:name :set-guardian-factor-twilio
:doc "Useful to configure SMS provider."
:doc-url "#!/Guardian/put_twilio"
:http {:path ["guardian" "factors" "push-notification" "providers" "twilio"]
:method :put
:response-code 200}}
;; Jobs
:get-job {:name :get-job
:doc "Retrieves a job. Useful to check its status."
:doc-url "#!/Jobs/get_jobs_by_id"
:http {:path ["jobs" :id]
:method :get
:response-code 200}}
:get-job-errors {:name :get-job-errors
:doc "Retrieve error details of a failed job."
:doc-url "#!/Jobs/get_errors"
:http {:path ["jobs" :id "errors"]
:method :get
:response-code 200}}
:get-job-results {:name :get-job-results
:doc ""
:doc-url "#!/Jobs/get_results"
:http {:path ["jobs" :id "results"]
:method :get
:response-code 200}}
:create-export-users-job {:name :create-export-users-job
:doc "Export all users to a file via a long-running job."
:doc-url "#!/Jobs/post_users_exports"
:http {:path ["jobs" "users-exports"]
:method :post
:response-code 201}}
:create-import-users-job {:name :create-import-users-job
:doc "Import users from a formatted file into a connection via a long-running job."
:doc-url "#!/Jobs/post_users_imports"
:http {:path ["jobs" "users-imports"]
:method :post
:response-code 201}}
:send-verification-email {:name :send-verification-email
:doc "Send an email to the specified user that asks them to click a link to verify their email address."
:doc-url "#!/Jobs/post_verification_email"
:http {:path ["jobs" "verification-email"]
:method :post
:response-code 201}}
;; Stats
:get-active-users-count {:name :get-active-users-count
:doc "Retrieve the number of active users that logged in during the last 30 days."
:doc-url "#!/Stats/get_active_users"
:http {:path ["stats" "active-users"]
:method :get
:response-code 200}}
:get-daily-stats {:name :get-daily-stats
:doc "Retrieve the number of logins, signups and breached-password detections (subscription required) that occurred each day within a specified date range."
:doc-url "#!/Stats/get_daily"
:http {:path ["stats" "daily"]
:method :get
:response-code 200}}
;; Tenants
:get-tenant-settings {:name :get-tenant-settings
:doc "Use this endpoint to retrieve various settings for a tenant."
:doc-url "#!/Tenants/get_settings"
:http {:path ["tenants" "settings"]
:method :get
:response-code 200}}
:update-tenant-settings {:name :update-tenant-settings
:doc "Use this endpoint to update various fields for a tenant. Enter the new settings in a JSON string in the body parameter."
:doc-url "#!/Tenants/patch_settings"
:http {:path ["tenants" "settings"]
:method :patch
:response-code 200}}
;; Anomaly
:check-if-ip-blocked {:name :check-if-ip-blocked
:doc "Check if a given IP address is blocked via the multiple user accounts trigger due to multiple failed logins."
:doc-url "#!/Anomaly/get_ips_by_id"
:http {:path ["anomaly" "blocks" "ips" :id]
:method :get
:response-code 200}}
:unblock-ip {:name :unblock-ip
:doc "Unblock an IP address currently blocked by the multiple user accounts trigger due to multiple failed logins."
:doc-url "#!/Anomaly/delete_ips_by_id"
:http {:path ["anomaly" "blocks" "ips" :id]
:method :delete
:response-code 204}}
;; Tickets
:create-email-verification-ticket {:name :create-email-verification-ticket
:doc "Create a ticket to verify a user's email address."
:doc-url "#!/Tickets/post_email_verification"
:http {:path ["tickets" "email-verification"]
:method :post
:response-code 201}}
:create-password-change-ticket {:name :create-password-change-ticket
:doc "Create a password change ticket for a user."
:doc-url "#!/Tickets/post_password_change"
:http {:path ["tickets" "password-change"]
:method :post
:response-code 201}}}})
| null | https://raw.githubusercontent.com/lumberdev/auth0-clojure/ed01e95d7a11e6948d286a35aead100ab5a39a00/src/auth0_clojure/descriptors/management.clj | clojure | TODO - better docs
TODO - query params (in the format {:filter "string"} for now
Branding
Client Grants
Clients
Custom Domains
Device Credentials
Grants
Logs
Prompts
Roles
Rules
Rules Configs
User Blocks
Users
Email Templates
Emails
Jobs
Stats
Tenants
Anomaly
Tickets | (ns auth0-clojure.descriptors.management)
(def api-descriptor
{:version "2.0"
:metadata {:endpoint-prefix "/api/v2/"}
:operations {
:get-branding-settings {:name :get-branding-settings
:doc "Use this endpoint to retrieve various settings related to branding."
:doc-url "#!/Branding/get_branding"
:http {:path ["branding"]
:method :get
:response-code 200}}
:update-branding-settings {:name :update-branding-settings
:doc "Use this endpoint to update various fields related to branding."
:doc-url "#!/Branding/patch_branding"
:http {:path ["branding"]
:method :patch
:response-code 200}}
:get-client-grants {:name :get-client-grants
:doc "Retrieve client grants."
:doc-url "#!/Client_Grants/get_client_grants"
:http {:path ["client-grants"]
:method :get
:response-code 200}}
:create-client-grant {:name :create-client-grant
:doc "Create a client grant."
:doc-url "#!/Client_Grants/post_client_grants"
:http {:path ["client-grants"]
:method :post
:response-code 201}}
:update-client-grant {:name :update-client-grant
:doc "Update a client grant."
:doc-url "#!/Client_Grants/patch_client_grants_by_id"
:http {:path ["client-grants" :id]
:method :patch
:response-code 200}}
:delete-client-grant {:name :delete-client-grant
:doc "Delete a client grant."
:doc-url "#!/Client_Grants/delete_client_grants_by_id"
:http {:path ["client-grants" :id]
:method :delete
:response-code 204}}
:get-clients {:name :get-clients
:doc "Retrieves a list of all client applications. Accepts a list of fields to include or exclude. Important: The client_secret and encryption_key attributes can only be retrieved with the read:client_keys scope."
:doc-url "#!/Clients/get_clients"
:http {:path ["clients"]
:method :get
:response-code 200}}
:create-client {:name :create-client
:doc "Creates a new client application. The samples on the right show most attributes that can be used. We recommend to let us to generate a safe secret for you, but you can also provide your own with the client_secret parameter"
:doc-url "#!/Clients/post_clients"
:http {:path ["clients"]
:method :post
:response-code 201}}
:get-client {:name :get-client
:doc "Retrieves a client by its id. Important: The client_secret encryption_key and signing_keys attributes can only be retrieved with the read:client_keys scope."
:doc-url "#!/Clients/get_clients_by_id"
:http {:path ["clients" :id]
:method :get
:response-code 200}}
:update-client {:name :update-client
:doc "Important: The client_secret and encryption_key attributes can only be updated with the update:client_keys scope."
:doc-url "#!/Clients/patch_clients_by_id"
:http {:path ["clients" :id]
:method :patch
:response-code 200}}
:delete-client {:name :delete-client
:doc "Deletes a client and all its related assets (like rules, connections, etc) given its id."
:doc-url "#!/Clients/delete_clients_by_id"
:http {:path ["clients" :id]
:method :delete
:response-code 204}}
:rotate-client-secret {:name :rotate-client-secret
:doc "Rotate a client secret. The generated secret is NOT base64 encoded."
:doc-url "#!/Clients/post_rotate_secret"
:http {:path ["clients" :id "rotate-secret"]
:method :post
:response-code 200}}
Connections
:get-connections {:name :get-connections
:doc "Retrieves every connection matching the specified strategy. All connections are retrieved if no strategy is being specified. Accepts a list of fields to include or exclude in the resulting list of connection objects."
:doc-url "#!/Connections/get_connections"
:http {:path ["connections"]
:method :get
:response-code 200}}
:create-connection {:name :create-connection
:doc "Creates a new connection according to the JSON object received in body. Valid Strategy names are: ad, adfs, amazon, apple, dropbox, bitbucket, aol, auth0-adldap, auth0-oidc, auth0, baidu, bitly, box, custom, daccount, dwolla, email, evernote-sandbox, evernote, exact, facebook, fitbit, flickr, github, google-apps, google-oauth2, instagram, ip, linkedin, miicard, oauth1, oauth2, office365, oidc, paypal, paypal-sandbox, pingfederate, planningcenter, renren, salesforce-community, salesforce-sandbox, salesforce, samlp, sharepoint, shopify, sms, soundcloud, thecity-sandbox, thecity, thirtysevensignals, twitter, untappd, vkontakte, waad, weibo, windowslive, wordpress, yahoo, yammer, yandex, line."
:doc-url "#!/Connections/post_connections"
:http {:path ["connections"]
:method :post
:response-code 201}}
:get-connection {:name :get-connection
:doc "Retrieves a connection by its ID."
:doc-url "#!/Connections/get_connections_by_id"
:http {:path ["connections" :id]
:method :get
:response-code 200}}
:update-connection {:name :update-connection
:doc "Updates a connection."
:doc-url "#!/Connections/patch_connections_by_id"
:http {:path ["connections" :id]
:method :patch
:response-code 200}}
:delete-connection {:name :delete-connection
:doc "Deletes a connection and all its users."
:doc-url "#!/Connections/delete_connections_by_id"
:http {:path ["connections" :id]
:method :delete
:response-code 204}}
:delete-user-by-email {:name :delete-user-by-email
:doc "Deletes a specified connection user by its email (you cannot delete all users from specific connection). Currently, only Database Connections are supported."
:doc-url "#!/Connections/delete_users_by_email"
:http {:path ["connections" :id "users"]
:method :delete
:response-code 204}}
:get-custom-domains {:name :get-custom-domains
:doc "Retrieves details on custom domains."
:doc-url "#!/Custom_Domains/get_custom_domains"
:http {:path ["custom-domains"]
:method :get
:response-code 200}}
:config-new-custom-domain {:name :config-new-custom-domain
:doc "Create a new custom domain."
:doc-url "#!/Custom_Domains/post_custom_domains"
:http {:path ["custom-domains"]
:method :post
:response-code 201}}
:get-custom-domain {:name :get-custom-domain
:doc "Retrieve a custom domain configuration and status."
:doc-url "#!/Custom_Domains/get_custom_domains_by_id"
:http {:path ["custom-domains" :id]
:method :get
:response-code 200}}
:verify-custom-domain {:name :verify-custom-domain
:doc "Run the verification process on a custom domain. Note: Check the `status` field to see its verification status. Once verification is complete, it may take up to 10 minutes before the custom domain can start accepting requests."
:doc-url "#!/Custom_Domains/post_verify"
:http {:path ["custom-domains" :id "verify"]
:method :post
:response-code 200}}
:delete-custom-domain-config {:name :delete-custom-domain-config
:doc "Delete a custom domain and stop serving requests for it."
:doc-url "#!/Custom_Domains/delete_custom_domains_by_id"
:http {:path ["custom-domains" :id]
:method :delete
:response-code 204}}
:get-device-credentials {:name :get-device-credentials
:doc "Manage the devices that are recognized and authenticated. Please note that Device Credentials endpoints are designed for ad hoc administrative use only."
:doc-url "#!/Device_Credentials/get_device_credentials"
:http {:path ["device-credentials"]
:method :get
:response-code 200}}
:create-device-public-key {:name :create-device-public-key
:doc "Manage the devices that are recognized and authenticated. Please note that Device Credentials endpoints are designed for ad hoc administrative use only."
:doc-url "#!/Device_Credentials/post_device_credentials"
:http {:path ["device-credentials"]
:method :post
:response-code 201}}
:delete-device-public-key {:name :delete-device-public-key
:doc "Manage the devices that are recognized and authenticated. Please note that Device Credentials endpoints are designed for ad hoc administrative use only."
:doc-url "#!/Device_Credentials/delete_device_credentials_by_id"
:http {:path ["device-credentials" :id]
:method :delete
:response-code 204}}
:get-grants {:name :get-grants
:doc "Manage the grants associated with your account."
:doc-url "#!/Grants/get_grants"
:http {:path ["grants"]
:method :get
:response-code 200}}
:delete-grant {:name :delete-grant
:doc ""
:doc-url "#!/Grants/delete_grants_by_id"
:http {:path ["grants" :id]
:method :delete
:response-code 204}}
:search-log-events {:name :search-log-events
:doc "Retrieves log entries that match the specified search criteria (or lists all log entries if no criteria are used). Set custom search criteria using the q parameter, or search from a specific log ID (\"search from checkpoint\")."
:doc-url "#!/Logs/get_logs"
:http {:path ["logs"]
:method :get
:response-code 200}}
:get-log-event {:name :get-log-event
:doc "Retrieves the data related to the log entry identified by id. This returns a single log entry representation as specified in the schema."
:doc-url "#!/Logs/get_logs_by_id"
:http {:path ["logs" :id]
:method :get
:response-code 200}}
:get-prompt-settings {:name :get-prompt-settings
:doc "Retrieve prompts settings."
:doc-url "#!/Prompts/get_prompts"
:http {:path ["prompts"]
:method :get
:response-code 200}}
:update-prompt-settings {:name :update-prompt-settings
:doc "Update prompts settings."
:doc-url "#!/Prompts/patch_prompts"
:http {:path ["prompts"]
:method :patch
:response-code 200}}
:get-roles {:name :get-roles
:doc "Lists all the roles."
:doc-url "#!/Roles/get_roles"
:http {:path ["roles"]
:method :get
:response-code 200}}
:create-role {:name :create-role
:doc "Creates a new role."
:doc-url "#!/Roles/post_roles"
:http {:path ["roles"]
:method :post
:response-code 200}}
:get-role {:name :get-role
:doc "Gets the information for a role."
:doc-url "#!/Roles/get_roles_by_id"
:http {:path ["roles" :id]
:method :get
:response-code 200}}
:update-role {:name :update-role
:doc "Updates a role with new values."
:doc-url "#!/Roles/patch_roles_by_id"
:http {:path ["roles" :id]
:method :patch
:response-code 200}}
:delete-role {:name :delete-role
:doc "Deletes a role used in authorization of users against resource servers."
:doc-url "#!/Roles/delete_roles_by_id"
:http {:path ["roles" :id]
:method :delete
:response-code 204}}
:get-role-permissions {:name :get-role-permissions
:doc "Gets the permissions for a role."
:doc-url "#!/Roles/get_role_permission"
:http {:path ["roles" :id "permissions"]
:method :get
:response-code 200}}
:associate-role-permissions {:name :associate-role-permissions
:doc "Associates permissions with a role."
:doc-url "#!/Roles/post_role_permission_assignment"
:http {:path ["roles" :id "permissions"]
:method :post
:response-code 201}}
:unassociate-role-permissions {:name :unassociate-role-permissions
:doc "Unassociates permissions from a role."
:doc-url "#!/Roles/delete_role_permission_assignment"
:http {:path ["roles" :id "permissions"]
:method :delete
TODO - descriptor - should n't this be 204 ? ? ?
:response-code 200}}
:get-role-users {:name :get-role-users
:doc "Lists the users that have been associated with a given role."
:doc-url "#!/Roles/get_role_user"
:http {:path ["roles" :id "users"]
:method :get
:response-code 200}}
:assign-role-users {:name :assign-role-users
:doc "Assign users to a role."
:doc-url "#!/Roles/post_role_users"
:http {:path ["roles" :id "users"]
:method :post
:response-code 200}}
:get-rules {:name :get-rules
:doc "Retrieves a list of all rules. Accepts a list of fields to include or exclude."
:doc-url "#!/Rules/get_rules"
:http {:path ["rules"]
:method :get
:response-code 200}}
:create-rule {:name :create-rule
:doc "Creates a new rule according to the JSON object received in body."
:doc-url "#!/Rules/post_rules"
:http {:path ["rules"]
:method :post
:response-code 201}}
:get-rule {:name :get-rule
:doc "Retrieves a rule by its ID. Accepts a list of fields to include or exclude in the result."
:doc-url "#!/Rules/get_rules_by_id"
:http {:path ["rules" :id]
:method :get
:response-code 200}}
:update-rule {:name :update-rule
:doc "Use this endpoint to update an existing rule."
:doc-url "#!/Rules/patch_rules_by_id"
:http {:path ["rules" :id]
:method :patch
:response-code 200}}
:delete-rule {:name :delete-rule
:doc "To be used to delete a rule."
:doc-url "#!/Rules/delete_rules_by_id"
:http {:path ["rules" :id]
:method :delete
:response-code 204}}
:get-rules-configs {:name :get-rules-configs
:doc "Returns only rules config variable keys. For security, config variable values cannot be retrieved outside rule execution"
:doc-url "#!/Rules_Configs/get_rules_configs"
:http {:path ["rules-configs"]
:method :get
:response-code 200}}
:set-rules-config {:name :set-rules-config
:doc "Rules config keys must be of the format ^[A-Za-z0-9_\\-@*+:]*$."
:doc-url "#!/Rules_Configs/put_rules_configs_by_key"
:http {:path ["rules-configs" :key]
:method :put
:response-code 200}}
:delete-rules-config {:name :delete-rules-config
:doc "Rules config keys must be of the format ^[A-Za-z0-9_\\-@*+:]*$."
:doc-url "#!/Rules_Configs/delete_rules_configs_by_key"
:http {:path ["rules-configs" :key]
:method :delete
:response-code 204}}
:get-user-blocks {:name :get-user-blocks
:doc "This endpoint can be used to retrieve a list of blocked IP addresses of a particular user given a user_id."
:doc-url "#!/User_Blocks/get_user_blocks_by_id"
:http {:path ["user-blocks" :id]
:method :get
:response-code 200}}
:unblock-user {:name :unblock-user
:doc "This endpoint can be used to unblock a user that was blocked due to an excessive amount of incorrectly provided credentials."
:doc-url "#!/User_Blocks/delete_user_blocks_by_id"
:http {:path ["user-blocks" :id]
:method :delete
:response-code 204}}
:get-user-blocks-by-identifier {:name :get-user-blocks-by-identifier
:doc "This endpoint can be used to retrieve a list of blocked IP addresses for a given key."
:doc-url "#!/User_Blocks/get_user_blocks"
:http {:path ["user-blocks"]
:method :get
:response-code 200}}
:unblock-user-by-identifier {:name :unblock-user-by-identifier
:doc "This endpoint can be used to unblock a given key that was blocked due to an excessive amount of incorrectly provided credentials."
:doc-url "#!/User_Blocks/delete_user_blocks"
:http {:path ["user-blocks"]
:method :delete
:response-code 204}}
:get-users {:name :get-users
:doc "This endpoint can be used to retrieve a list of users."
:doc-url "#!/Users/get_users"
:http {:path ["users"]
:method :get
:response-code 200}}
:get-users-by-email {:name :get-users-by-email
:doc "If Auth0 is the identify provider (idP), the email address associated with a user is saved in lower case, regardless of how you initially provided it. For example, if you register a user as , Auth0 saves the user's email as . In cases where Auth0 is not the idP, the `email` is stored based on the rules of idP, so make sure the search is made using the correct capitalization."
:doc-url "#!/Users_By_Email/get_users_by_email"
:http {:path ["users-by-email"]
:method :get
:response-code 200}}
:create-user {:name :create-user
:doc "Creates a new user according to the JSON object received in body. It works only for database and passwordless connections."
:doc-url "#!/Users/post_users"
:http {:path ["users"]
:method :post
:response-code 201}}
:get-user {:name :get-user
:doc "This endpoint can be used to retrieve user details given the user_id."
:doc-url "#!/Users/get_users_by_id"
:http {:path ["users" :id]
:method :get
:response-code 200}}
:update-user {:name :update-user
:doc "Updates a user with the object's properties received in the request's body (the object should be a JSON object)."
:doc-url "#!/Users/patch_users_by_id"
:http {:path ["users" :id]
:method :patch
:response-code 200}}
:delete-user {:name :delete-user
:doc "This endpoint can be used to delete a single user based on the id."
:doc-url "#!/Users/delete_users_by_id"
:http {:path ["users" :id]
:method :delete
:response-code 204}}
:get-user-roles {:name :get-user-roles
:doc "List the the roles associated with a user."
:doc-url "#!/Users/get_user_roles"
:http {:path ["users" :id "roles"]
:method :get
:response-code 200}}
:assign-user-roles {:name :assign-user-roles
:doc "Associate an array of roles with a user."
:doc-url "#!/Users/post_user_roles"
:http {:path ["users" :id "roles"]
:method :post
:response-code 201}}
:unassign-user-roles {:name :unassign-user-roles
:doc "Removes an array of roles from a user."
:doc-url "#!/Users/delete_user_roles"
:http {:path ["users" :id "roles"]
:method :delete
:response-code 204}}
:get-user-log-events {:name :get-user-log-events
:doc "Retrieve every log event for a specific user id."
:doc-url "#!/Users/get_logs_by_user"
:http {:path ["users" :id "logs"]
:method :get
:response-code 200}}
:get-user-guardian-enrollments {:name :get-user-guardian-enrollments
:doc "Retrieves all Guardian enrollments."
:doc-url "#!/Users/get_enrollments"
:http {:path ["users" :id "enrollments"]
:method :get
:response-code 200}}
:generate-guardian-recovery-code {:name :generate-guardian-recovery-code
:doc "This endpoint removes the current Guardian recovery code then generates and returns a new one."
:doc-url "#!/Users/post_recovery_code_regeneration"
:http {:path ["users" :id "recovery-code-generation"]
:method :post
:response-code 200}}
:get-user-permissions {:name :get-user-permissions
:doc "Get the permissions associated to the user."
:doc-url "#!/Users/get_permissions"
:http {:path ["users" :id "permissions"]
:method :get
:response-code 200}}
:assign-user-permissions {:name :assign-user-permissions
:doc "This endpoint assigns the permission specified in the request payload to the user defined in the path."
:doc-url "#!/Users/post_permissions"
:http {:path ["users" :id "permissions"]
:method :post
:response-code 201}}
:unassign-user-permissions {:name :unassign-user-permissions
:doc "Removes permissions from a user."
:doc-url "#!/Users/delete_permissions"
:http {:path ["users" :id "permissions"]
:method :delete
:response-code 204}}
:delete-user-multifactor-provider {:name :delete-user-multifactor-provider
:doc "This endpoint can be used to delete the multifactor provider settings for a particular user. This will force user to re-configure the multifactor provider."
:doc-url "#!/Users/delete_multifactor_by_provider"
:http {:path ["users" :id "multifactor" :provider]
:method :delete
:response-code 204}}
:link-user-account {:name :link-user-account
:doc "Links the account specified in the body (secondary account) to the account specified by the id param of the URL (primary account)."
:doc-url "#!/Users/post_identities"
:http {:path ["users" :id "identities"]
:method :post
:response-code 201}}
:unlink-user-account {:name :unlink-user-account
:doc "Unlinks an identity from the target user, and it becomes a separated user again."
:doc-url "#!/Users/delete_user_identity_by_user_id"
:http {:path ["users" :id "identities" :provider :user-id]
:method :delete
:response-code 204}}
:invalidate-user-mfa-browsers {:name :invalidate-user-mfa-browsers
:doc "This endpoint invalidates all remembered browsers for all authentication factors for the selected user."
:doc-url "#!/Users/post_invalidate_remember_browser"
:http {:path ["users" :id "multifactor" "actions" "invalidate-remember-browser"]
:method :post
:response-code 204}}
Blacklists
:get-blacklisted-tokens {:name :get-blacklisted-tokens
:doc "Retrieve the `jti` and `aud` of all tokens that are blacklisted."
:doc-url "#!/Blacklists/get_tokens"
:http {:path ["blacklists" "tokens"]
:method :get
:response-code 200}}
:blacklist-token {:name :blacklist-token
:doc "Add the token identified by the `jti` to a blacklist for the tenant."
:doc-url "#!/Blacklists/post_tokens"
:http {:path ["blacklists" "tokens"]
:method :post
:response-code 204}}
:create-email-template {:name :create-email-template
:doc ""
:doc-url "#!/Email_Templates/post_email_templates"
:http {:path ["email-templates"]
:method :post
:response-code 200}}
:get-email-template {:name :get-email-template
:doc ""
:doc-url "#!/Email_Templates/get_email_templates_by_templateName"
:http {:path ["email-templates" :template-name]
:method :get
:response-code 200}}
:update-email-template {:name :update-email-template
:doc ""
:doc-url "#!/Email_Templates/patch_email_templates_by_templateName"
:http {:path ["email-templates" :template-name]
:method :patch
:response-code 200}}
:set-email-template {:name :set-email-template
:doc ""
:doc-url "#!/Email_Templates/put_email_templates_by_templateName"
:http {:path ["email-templates" :template-name]
:method :put
:response-code 200}}
:create-email-provider {:name :create-email-provider
:doc "To be used to set a new email provider."
:doc-url "#!/Emails/post_provider"
:http {:path ["emails" "provider"]
:method :post
:response-code 200}}
:get-email-provider {:name :get-email-provider
:doc "This endpoint can be used to retrieve the current email provider configuration."
:doc-url "#!/Emails/get_provider"
:http {:path ["emails" "provider"]
:method :get
:response-code 200}}
:update-email-provider {:name :update-email-provider
:doc "Can be used to change details for an email provider.\n"
:doc-url "#!/Emails/patch_provider"
:http {:path ["emails" "provider"]
:method :patch
:response-code 200}}
:delete-email-provider {:name :delete-email-provider
:doc ""
:doc-url "#!/Emails/delete_provider"
:http {:path ["emails" "provider"]
:method :delete
:response-code 204}}
Guardian
:get-guardian-factors {:name :get-guardian-factors
:doc "Retrieves all factors. Useful to check factor enablement and trial status."
:doc-url "#!/Guardian/get_factors"
:http {:path ["guardian" "factors"]
:method :get
:response-code 200}}
:set-guardian-factor {:name :set-guardian-factor
:doc "Useful to enable / disable factor."
:doc-url "#!/Guardian/put_factors_by_name"
:http {:path ["guardian" "factors" :name]
:method :put
:response-code 200}}
:create-guardian-enrollment-ticket {:name :create-guardian-enrollment-ticket
:doc "Generate an email with a link to start the Guardian enrollment process."
:doc-url "#!/Guardian/post_ticket"
:http {:path ["guardian" "enrollments" "ticket"]
:method :post
:response-code 204}}
:get-guardian-enrollment {:name :get-guardian-enrollment
:doc "Retrieves an enrollment. Useful to check its type and related metadata. Note that phone number data is partially obfuscated."
:doc-url "#!/Guardian/get_enrollments_by_id"
:http {:path ["guardian" "enrollments" :id]
:method :get
:response-code 200}}
:delete-guardian-enrollment {:name :delete-guardian-enrollment
:doc "Deletes an enrollment. Useful when you want to force the user to re-enroll with Guardian."
:doc-url "#!/Guardian/delete_enrollments_by_id"
:http {:path ["guardian" "enrollments" :id]
:method :delete
:response-code 200}}
:get-guardian-factor-templates {:name :get-guardian-factor-templates
:doc "Retrieves enrollment and verification templates. You can use this to check the current values for your templates."
:doc-url "#!/Guardian/get_templates"
:http {:path ["guardian" "factors" "sms" "templates"]
:method :get
:response-code 200}}
:update-guardian-factor-templates {:name :update-guardian-factor-templates
:doc "Useful to send custom messages on SMS enrollment and verification."
:doc-url "#!/Guardian/put_templates"
:http {:path ["guardian" "factors" "sms" "templates"]
:method :put
:response-code 200}}
:get-guardian-factor-sns {:name :get-guardian-factor-sns
:doc "Returns provider configuration for AWS SNS."
:doc-url "#!/Guardian/get_sns"
:http {:path ["guardian" "factors" "push-notification" "providers" "sns"]
:method :get
:response-code 200}}
:set-guardian-factor-sns {:name :set-guardian-factor-sns
:doc "Useful to configure the push notification provider."
:doc-url "#!/Guardian/put_sns"
:http {:path ["guardian" "factors" "push-notification" "providers" "sns"]
:method :put
:response-code 200}}
:get-guardian-factor-twilio {:name :get-guardian-factor-twilio
:doc "Returns provider configuration."
:doc-url "#!/Guardian/get_twilio"
:http {:path ["guardian" "factors" "push-notification" "providers" "twilio"]
:method :get
:response-code 200}}
:set-guardian-factor-twilio {:name :set-guardian-factor-twilio
:doc "Useful to configure SMS provider."
:doc-url "#!/Guardian/put_twilio"
:http {:path ["guardian" "factors" "push-notification" "providers" "twilio"]
:method :put
:response-code 200}}
:get-job {:name :get-job
:doc "Retrieves a job. Useful to check its status."
:doc-url "#!/Jobs/get_jobs_by_id"
:http {:path ["jobs" :id]
:method :get
:response-code 200}}
:get-job-errors {:name :get-job-errors
:doc "Retrieve error details of a failed job."
:doc-url "#!/Jobs/get_errors"
:http {:path ["jobs" :id "errors"]
:method :get
:response-code 200}}
:get-job-results {:name :get-job-results
:doc ""
:doc-url "#!/Jobs/get_results"
:http {:path ["jobs" :id "results"]
:method :get
:response-code 200}}
:create-export-users-job {:name :create-export-users-job
:doc "Export all users to a file via a long-running job."
:doc-url "#!/Jobs/post_users_exports"
:http {:path ["jobs" "users-exports"]
:method :post
:response-code 201}}
:create-import-users-job {:name :create-import-users-job
:doc "Import users from a formatted file into a connection via a long-running job."
:doc-url "#!/Jobs/post_users_imports"
:http {:path ["jobs" "users-imports"]
:method :post
:response-code 201}}
:send-verification-email {:name :send-verification-email
:doc "Send an email to the specified user that asks them to click a link to verify their email address."
:doc-url "#!/Jobs/post_verification_email"
:http {:path ["jobs" "verification-email"]
:method :post
:response-code 201}}
:get-active-users-count {:name :get-active-users-count
:doc "Retrieve the number of active users that logged in during the last 30 days."
:doc-url "#!/Stats/get_active_users"
:http {:path ["stats" "active-users"]
:method :get
:response-code 200}}
:get-daily-stats {:name :get-daily-stats
:doc "Retrieve the number of logins, signups and breached-password detections (subscription required) that occurred each day within a specified date range."
:doc-url "#!/Stats/get_daily"
:http {:path ["stats" "daily"]
:method :get
:response-code 200}}
:get-tenant-settings {:name :get-tenant-settings
:doc "Use this endpoint to retrieve various settings for a tenant."
:doc-url "#!/Tenants/get_settings"
:http {:path ["tenants" "settings"]
:method :get
:response-code 200}}
:update-tenant-settings {:name :update-tenant-settings
:doc "Use this endpoint to update various fields for a tenant. Enter the new settings in a JSON string in the body parameter."
:doc-url "#!/Tenants/patch_settings"
:http {:path ["tenants" "settings"]
:method :patch
:response-code 200}}
:check-if-ip-blocked {:name :check-if-ip-blocked
:doc "Check if a given IP address is blocked via the multiple user accounts trigger due to multiple failed logins."
:doc-url "#!/Anomaly/get_ips_by_id"
:http {:path ["anomaly" "blocks" "ips" :id]
:method :get
:response-code 200}}
:unblock-ip {:name :unblock-ip
:doc "Unblock an IP address currently blocked by the multiple user accounts trigger due to multiple failed logins."
:doc-url "#!/Anomaly/delete_ips_by_id"
:http {:path ["anomaly" "blocks" "ips" :id]
:method :delete
:response-code 204}}
:create-email-verification-ticket {:name :create-email-verification-ticket
:doc "Create a ticket to verify a user's email address."
:doc-url "#!/Tickets/post_email_verification"
:http {:path ["tickets" "email-verification"]
:method :post
:response-code 201}}
:create-password-change-ticket {:name :create-password-change-ticket
:doc "Create a password change ticket for a user."
:doc-url "#!/Tickets/post_password_change"
:http {:path ["tickets" "password-change"]
:method :post
:response-code 201}}}})
|
305dc00d707b2a093f9e5e74378fc4126279d128069080fab83de45b18c3d535 | otakar-smrz/elixir-fm | O.hs |
module Elixir.Data.Sunny.Regular.O (section) where
import Elixir.Lexicon
lexicon = include section
cluster_1 = cluster
|> "l ^g l ^g" <| [
KaRDaS `verb` {- <la^gla^g> -} [ ['s','t','a','m','m','e','r'], ['s','t','u','t','t','e','r'] ],
TaKaRDaS `verb` {- <tala^gla^g> -} [ ['s','t','a','m','m','e','r'], ['s','t','u','t','t','e','r'] ],
KaRDAS `adj` {- <la^glA^g> -} [ ['s','t','a','m','m','e','r','e','r'], ['s','t','u','t','t','e','r','e','r'] ],
MuKaRDaS `adj` {- <mula^gla^g> -} [ ['r','e','i','t','e','r','a','t','e','d'], ['r','e','p','e','a','t','e','d'] ] ]
cluster_2 = cluster
|> "l ^g m" <| [
FaCaL `verb` {- <la^gam> -} [ ['s','e','w'] ]
`imperf` FCuL,
FaCCaL `verb` {- <la^g^gam> -} [ ['r','e','s','t','r','a','i','n'], ['b','r','i','d','l','e'] ],
HaFCaL `verb` {- <'al^gam> -} [ ['r','e','s','t','r','a','i','n'], ['b','r','i','d','l','e'] ],
IFtaCaL `verb` {- <ilta^gam> -} [ unwords [ ['b','e'], ['b','r','i','d','l','e','d'] ], unwords [ ['b','e'], ['h','a','r','n','e','s','s','e','d'] ] ],
FiCAL `noun` {- <li^gAm> -} [ ['r','e','i','n'], ['b','r','i','d','l','e'] ]
`plural` HaFCiL |< aT
`plural` FuCuL,
MaFCUL `adj` {- <mal^gUm> -} [ ['b','r','i','d','l','e','d'], ['h','a','r','n','e','s','s','e','d'] ],
MuFCaL `adj` {- <mul^gam> -} [ ['b','r','i','d','l','e','d'], ['h','a','r','n','e','s','s','e','d'] ],
TaFCIL `noun` {- <tal^gIm> -} [ ['r','e','s','t','r','a','i','n','i','n','g'], ['h','a','r','n','e','s','s','i','n','g'], ['b','r','i','d','l','i','n','g'] ]
`plural` TaFCIL |< At ]
cluster_3 = cluster
|> "l ^g n" <| [
FaCiL `verb` {- <la^gin> -} [ ['a','d','h','e','r','e'], ['c','l','i','n','g'], ['s','t','i','c','k'] ]
`imperf` FCaL,
FaCL |< aT `noun` {- <la^gnaT> -} [ ['c','o','u','n','c','i','l'], ['c','o','m','m','i','t','t','e','e'], ['c','o','m','m','i','s','s','i','o','n'] ]
`plural` FiCAL
`plural` FiCaL
`plural` FaCaL |< At,
FuCayL `adj` {- <lu^gayn> -} [ ['s','i','l','v','e','r'], ['s','i','l','v','e','r','y'] ] ]
cluster_4 = cluster
|> "l .h b" <| [
FACiL `adj` {- <lA.hib> -} [ ['p','a','s','s','a','b','l','e'], unwords [ ['o','p','e','n'], "(", ['r','o','a','d'], ")" ] ]
`plural` FawACiL,
FACiL `noun` {- <lA.hib> -} [ ['e','l','e','c','t','r','o','d','e'] ]
`plural` FawACiL ]
cluster_5 = cluster
|> "l .h ^g" <| [
FaCaL `noun` {- <la.ha^g> -} [ ['L','a','h','e','j'], ['L','a','h','i','j'] ] ]
cluster_6 = cluster
|> "l .h d" <| [
FaCaL `verb` {- <la.had> -} [ ['b','u','r','y'], ['a','p','o','s','t','a','t','i','z','e'] ]
`imperf` FCaL,
HaFCaL `verb` {- <'al.had> -} [ ['a','p','o','s','t','a','t','i','z','e'], unwords [ ['b','e','c','o','m','e'], ['a','n'], ['a','t','h','e','i','s','t'] ] ],
IFtaCaL `verb` {- <ilta.had> -} [ ['d','e','v','i','a','t','e'], ['a','p','o','s','t','a','t','i','z','e'] ],
FaCL `noun` {- <la.hd> -} [ ['t','o','m','b'], ['g','r','a','v','e'] ]
`plural` HaFCAL
`plural` FuCUL,
FaCaL `noun` {- <la.had> -} [ ['L','a','h','a','d'] ],
FaCL |< Iy `adj` {- <la.hdIy> -} [ ['L','a','h','d','i','t','e','s'], unwords [ ['L','a','h','a','d'], ['p','a','r','t','i','s','a','n','s'] ] ],
FaCUL `noun` {- <la.hUd> -} [ ['L','a','h','o','u','d'] ],
FaCCAL `noun` {- <la.h.hAd> -} [ ['g','r','a','v','e','d','i','g','g','e','r'] ]
`plural` FaCCAL |< Un
`femini` FaCCAL |< aT,
HiFCAL `noun` {- <'il.hAd> -} [ ['a','t','h','e','i','s','m'], ['a','p','o','s','t','a','s','y'] ],
HiFCAL |< Iy `adj` {- <'il.hAdIy> -} [ ['a','t','h','e','i','s','t'], ['g','o','d','l','e','s','s'] ],
MuFCiL `noun` {- <mul.hid> -} [ ['a','t','h','e','i','s','t'], ['h','e','r','e','t','i','c'] ]
`plural` MuFCiL |< Un
`plural` MaFACiL |< aT
`femini` MuFCiL |< aT ]
cluster_7 = cluster
|> "l .h s" <| [
FaCaL `verb` {- <la.has> -} [ ['d','e','v','o','u','r'], unwords [ ['e','a','t'], ['a','w','a','y'], ['a','t'] ] ]
`imperf` FCaL,
FaCiL `verb` {- <la.his> -} [ unwords [ ['l','i','c','k'], ['u','p'] ], unwords [ ['l','a','p'], ['u','p'] ] ]
`imperf` FCaL,
FaCL `noun` {- <la.hs> -} [ unwords [ ['l','a','p','p','i','n','g'], ['u','p'] ], unwords [ ['e','a','t','i','n','g'], ['a','w','a','y'], ['a','t'] ] ],
FaCL |< aT `noun` {- <la.hsaT> -} [ ['l','i','c','k','i','n','g'], ['l','a','p','p','i','n','g'] ],
MaFCaL `noun` {- <mal.has> -} [ ['l','i','c','k','i','n','g'], ['l','a','p','p','i','n','g'] ],
MaFCUL `adj` {- <mal.hUs> -} [ ['l','i','c','k','e','d'], ['i','m','b','e','c','i','l','e'] ] ]
cluster_8 = cluster
|> "l .h .z" <| [
FaCaL `verb` {- <la.ha.z> -} [ ['p','e','r','c','e','i','v','e'], ['r','e','g','a','r','d'] ]
`imperf` FCaL
`masdar` FaCL
`masdar` FaCaLAn,
FACaL `verb` {- <lA.ha.z> -} [ ['n','o','t','i','c','e'], ['o','b','s','e','r','v','e'] ],
FaCL `noun` {- <la.h.z> -} [ ['l','o','o','k'], ['g','l','a','n','c','e'] ]
`plural` HaFCAL,
FaCL |< aT `noun` {- <la.h.zaT> -} [ ['m','o','m','e','n','t'], ['i','n','s','t','a','n','t'] ]
`plural` FaCaL |< At,
FaCL |< aT |<< "a" |<< "'i_diN" `adv` {- <la.h.zaTa'i_diN> -} [ unwords [ ['a','t'], ['t','h','a','t'], ['m','o','m','e','n','t'] ] ],
MaFCaL `noun` {- <mal.ha.z> -} [ ['o','b','s','e','r','v','a','t','i','o','n'], ['r','e','m','a','r','k'], ['s','t','a','t','e','m','e','n','t'] ]
`plural` MaFACiL,
MuFACaL |< aT `noun` {- <mulA.ha.zaT> -} [ ['o','b','s','e','r','v','a','t','i','o','n'], ['r','e','m','a','r','k'], ['g','u','i','d','e','l','i','n','e','s'] ]
`plural` MuFACaL |< At,
FACiL |< aT `noun` {- <lA.hi.zaT> -} [ ['g','l','a','n','c','e'], ['l','o','o','k'] ]
`plural` FawACiL,
MaFCUL `adj` {- <mal.hU.z> -} [ ['n','o','t','i','c','e','a','b','l','e'], ['o','b','s','e','r','v','a','b','l','e'], ['r','e','m','a','r','k','a','b','l','e'] ],
MaFCUL |< aT `noun` {- <mal.hU.zaT> -} [ ['o','b','s','e','r','v','a','t','i','o','n'], ['n','o','t','e'], ['r','e','m','a','r','k'] ]
`plural` MaFCUL |< At,
MuFACiL `noun` {- <mulA.hi.z> -} [ ['o','b','s','e','r','v','e','r'], ['s','u','p','e','r','v','i','s','o','r'] ]
`plural` MuFACiL |< Un
`femini` MuFACiL |< aT,
MuFACaL `adj` {- <mulA.ha.z> -} [ ['e','v','i','d','e','n','t'], ['o','b','v','i','o','u','s'] ] ]
cluster_9 = cluster
|> "l .h f" <| [
FaCaL `verb` {- <la.haf> -} [ ['w','r','a','p'], ['c','o','v','e','r'] ]
`imperf` FCaL,
HaFCaL `verb` {- <'al.haf> -} [ ['w','r','a','p'], ['c','o','v','e','r'], ['i','m','p','o','r','t','u','n','e'] ],
< tala.h.haf >
IFtaCaL `verb` {- <ilta.haf> -} [ unwords [ ['b','e'], ['w','r','a','p','p','e','d'] ] ],
FiCL `noun` {- <li.hf> -} [ unwords [ ['f','o','o','t'], ['o','f'], "a", ['m','o','u','n','t','a','i','n'] ] ],
FiCAL `noun` {- <li.hAf> -} [ ['c','o','v','e','r'], ['b','l','a','n','k','e','t'], ['w','r','a','p'] ]
`plural` HaFCiL |< aT
`plural` FuCuL,
MiFCaL `noun` {- <mil.haf> -} [ ['c','o','v','e','r'], ['b','l','a','n','k','e','t'], ['w','r','a','p'] ]
`plural` MaFACiL,
HiFCAL `noun` {- <'il.hAf> -} [ ['i','m','p','o','r','t','u','n','i','t','y'] ]
`plural` HiFCAL |< At,
MuFtaCiL `adj` {- <multa.hif> -} [ ['w','r','a','p','p','e','d'], ['c','o','v','e','r','e','d'] ] ]
cluster_10 = cluster
|> "l .h q" <| [
FaCiL `verb` {- <la.hiq> -} [ ['f','o','l','l','o','w'], unwords [ ['b','e'], ['a','t','t','a','c','h','e','d'] ] ]
`imperf` FCaL,
FACaL `verb` {- <lA.haq> -} [ unwords [ ['g','o'], ['a','f','t','e','r'] ], ['j','o','i','n'], ['p','e','r','s','e','c','u','t','e'] ],
HaFCaL `verb` {- <'al.haq> -} [ ['a','t','t','a','c','h'], ['a','p','p','e','n','d'], ['e','n','r','o','l','l'] ],
TaFACaL `verb` {- <talA.haq> -} [ unwords [ ['f','o','l','l','o','w'], ['s','u','c','c','e','s','s','i','v','e','l','y'] ] ],
IFtaCaL `verb` {- <ilta.haq> -} [ ['e','n','r','o','l','l'], ['e','n','l','i','s','t'], unwords [ ['b','e'], ['a','t','t','a','c','h','e','d'] ] ],
IstaFCaL `verb` {- <istal.haq> -} [ ['a','n','n','e','x'] ],
FaCaL `noun` {- <la.haq> -} [ unwords [ ['a','l','l','u','v','i','a','l'], ['s','o','i','l'] ] ]
`plural` HaFCAL,
FaCaL |< Iy `adj` {- <la.haqIy> -} [ ['a','l','l','u','v','i','a','l'] ],
FiCAL `noun` {- <li.hAq> -} [ ['m','e','m','b','e','r','s','h','i','p'], ['e','n','r','o','l','l','m','e','n','t'] ],
MuFACaL |< aT `noun` {- <mulA.haqaT> -} [ ['p','e','r','s','e','c','u','t','i','o','n'], ['p','u','r','s','u','i','t'] ],
< ' >
`plural` HiFCAL |< At,
< ' >
`plural` HiFCAL |< At,
< ' >
IFtiCAL `noun` {- <ilti.hAq> -} [ ['e','n','t','e','r','i','n','g'], ['j','o','i','n','i','n','g'], ['a','f','f','i','l','i','a','t','i','o','n'] ]
`plural` IFtiCAL |< At,
IstiFCAL `noun` {- <istil.hAq> -} [ ['a','n','n','e','x','a','t','i','o','n'] ]
`plural` IstiFCAL |< At,
FACiL `adj` {- <lA.hiq> -} [ ['l','a','t','e','r'], ['s','o','o','n'], ['s','u','b','s','e','q','u','e','n','t'], ['a','t','t','a','c','h','e','d'], ['j','o','i','n','e','d'] ],
FACiL |< aT `noun` {- <lA.hiqaT> -} [ ['a','d','j','u','n','c','t'], ['a','p','p','e','n','d','a','g','e'] ]
`plural` FawACiL,
MuFCaL `noun` {- <mul.haq> -} [ ['a','t','t','a','c','h','e'] ]
`plural` MuFCaL |< Un
`femini` MuFCaL |< aT,
MuFCaL `adj` {- <mul.haq> -} [ ['a','p','p','e','n','d','e','d'], ['a','d','j','a','c','e','n','t'], ['a','n','n','e','x','e','d'] ],
MuFCaL `noun` {- <mul.haq> -} [ ['a','p','p','e','n','d','i','x'], ['a','d','d','e','n','d','u','m'] ]
`plural` MaFACiL
`plural` MuFCaL |< At,
MuFCaL |< Iy |< aT `noun` {- <mul.haqIyaT> -} [ unwords [ ['a','t','t','a','c','h','e','\'','s'], ['s','e','c','t','i','o','n'] ] ],
MuFACiL `noun` {- <mulA.hiq> -} [ ['f','o','l','l','o','w','e','r'], ['c','o','m','p','a','n','i','o','n'] ]
`plural` MuFACiL |< Un
`femini` MuFACiL |< aT,
MutaFACiL `adj` {- <mutalA.hiq> -} [ ['s','u','c','c','e','s','s','i','v','e'], ['c','o','n','s','e','c','u','t','i','v','e'], ['c','o','n','t','i','n','u','o','u','s'] ] ]
cluster_11 = cluster
|> "l .h m" <| [
FaCaL `verb` {- <la.ham> -} [ ['w','e','l','d'], ['s','o','l','d','e','r'] ]
`imperf` FCuL,
FaCiL `verb` {- <la.him> -} [ unwords [ ['g','e','t'], ['s','t','u','c','k'] ] ]
`imperf` FCaL,
FaCCaL `verb` {- <la.h.ham> -} [ ['s','o','l','d','e','r'], ['w','e','l','d'] ],
TaFACaL `verb` {- <talA.ham> -} [ unwords [ ['c','l','i','n','g'], ['t','o','g','e','t','h','e','r'] ], unwords [ ['h','o','l','d'], ['f','i','r','m','l','y'], ['t','o','g','e','t','h','e','r'] ] ],
IFtaCaL `verb` {- <ilta.ham> -} [ unwords [ ['c','l','i','n','g'], ['t','o','g','e','t','h','e','r'] ], unwords [ ['h','o','l','d'], ['f','i','r','m','l','y'], ['t','o','g','e','t','h','e','r'] ] ],
FaCL `noun` {- <la.hm> -} [ ['L','a','h','m'] ],
FaCL `noun` {- <la.hm> -} [ ['m','e','a','t'], ['f','l','e','s','h'] ]
`plural` FiCAL
`plural` FuCUL,
FuCL |< aT `noun` {- <lu.hmaT> -} [ unwords [ ['d','e','c','i','s','i','v','e'], ['f','a','c','t','o','r'] ], ['k','i','n','s','h','i','p'] ],
FaCL |< Iy |< aT `noun` {- <la.hmIyaT> -} [ ['c','o','n','j','u','n','c','t','i','v','a'] ],
FaCiL `adj` {- <la.him> -} [ ['c','o','r','p','u','l','e','n','t'] ],
FiCAL `noun` {- <li.hAm> -} [ ['s','o','l','d','e','r','i','n','g'], ['w','e','l','d','i','n','g'] ]
`plural` FiCAL |< At,
FaCCAL `noun` {- <la.h.hAm> -} [ ['b','u','t','c','h','e','r'], ['w','e','l','d','e','r'] ]
`plural` FaCCAL |< Un
`femini` FaCCAL |< aT,
FaCCAL `noun` {- <la.h.hAm> -} [ ['L','a','h','h','a','m'] ],
< la.hIm >
FaCAL |< aT `noun` {- <la.hAmaT> -} [ ['c','o','r','p','u','l','e','n','c','e'] ],
MaFCaL |< aT `noun` {- <mal.hamaT> -} [ unwords [ ['f','i','e','r','c','e'], ['b','a','t','t','l','e'] ], ['m','a','s','s','a','c','r','e'], ['e','p','i','c'] ]
`plural` MaFACiL,
MaFCaL |< Iy `adj` {- <mal.hamIy> -} [ ['h','e','r','o','i','c'], ['e','p','i','c'] ],
TaFACuL `noun` {- <talA.hum> -} [ unwords [ ['c','l','i','n','g','i','n','g'], ['t','o','g','e','t','h','e','r'] ], unwords [ ['h','o','l','d','i','n','g'], ['f','i','r','m','l','y'], ['t','o','g','e','t','h','e','r'] ] ]
`plural` TaFACuL |< At,
IFtiCAL `noun` {- <ilti.hAm> -} [ ['c','o','h','e','s','i','o','n'], ['a','d','h','e','s','i','o','n'], unwords [ ['c','l','o','s','e'], ['u','n','i','o','n'] ] ]
`plural` IFtiCAL |< At,
IFtiCAL `noun` {- <ilti.hAm> -} [ ['e','n','g','a','g','e','m','e','n','t'], ['c','o','n','f','r','o','n','t','a','t','i','o','n'] ]
`plural` IFtiCAL |< At,
MuFtaCaL `noun` {- <multa.ham> -} [ ['m','e','r','g','e','d'], ['f','u','s','e','d'] ],
MuFtaCaL |< aT `noun` {- <multa.hamaT> -} [ unwords [ ['c','o','n','j','u','n','c','t','i','v','a'], "(", ['m','e','m','b','r','a','n','e'], ['c','o','v','e','r','i','n','g'], ['i','n','t','e','r','n','a','l'], ['p','a','r','t'], ['o','f'], ['e','y','e','l','i','d'], ")" ] ] ]
cluster_12 = cluster
|> "l .h n" <| [
FaCaL `verb` {- <la.han> -} [ unwords [ ['s','p','e','a','k'], ['u','n','g','r','a','m','m','a','t','i','c','a','l','l','y'] ] ]
`imperf` FCaL
`masdar` FaCL
`masdar` FuCUL
`masdar` FaCAL |< aT,
FaCCaL `verb` {- <la.h.han> -} [ unwords [ ['m','a','k','e'], ['m','u','s','i','c'] ], unwords [ ['c','o','m','p','o','s','e'], ['m','u','s','i','c'] ] ],
HaFCaL `verb` {- <'al.han> -} [ unwords [ ['s','p','e','a','k'], ['u','n','g','r','a','m','m','a','t','i','c','a','l','l','y'] ], ['m','i','s','p','r','o','n','o','u','n','c','e'] ],
FaCL `noun` {- <la.hn> -} [ ['m','e','l','o','d','y'], ['s','o','l','e','c','i','s','m'] ]
`plural` HaFCAL
`plural` FuCUL,
FaCiL `noun` {- <la.hin> -} [ ['s','e','n','s','i','b','l','e'] ],
TaFCIL `noun` {- <tal.hIn> -} [ unwords [ ['m','u','s','i','c','a','l'], ['c','o','m','p','o','s','i','t','i','o','n'] ] ]
`plural` TaFACIL,
TaFCIL |< Iy `adj` {- <tal.hInIy> -} [ ['s','i','n','g','a','b','l','e'] ],
MaFCUL `adj` {- <mal.hUn> -} [ ['u','n','g','r','a','m','m','a','t','i','c','a','l'], ['c','o','l','l','o','q','u','i','a','l'] ],
MuFaCCiL `noun` {- <mula.h.hin> -} [ unwords [ ['m','u','s','i','c'], ['c','o','m','p','o','s','e','r'] ] ]
`plural` MuFaCCiL |< Un
`femini` MuFaCCiL |< aT ]
cluster_13 = cluster
|> "l _h b .t" <| [
KaRDaS `verb` {- <la_hba.t> -} [ ['d','i','s','o','r','g','a','n','i','z','e'], ['d','i','s','a','r','r','a','n','g','e'] ],
KaRDaS |< aT `noun` {- <la_hba.taT> -} [ ['d','i','s','o','r','d','e','r'], ['c','o','n','f','u','s','i','o','n'] ],
MuKaRDaS `adj` {- <mula_hba.t> -} [ unwords [ ['m','i','x','e','d'], ['u','p'] ], ['d','i','s','o','r','d','e','r','e','d'] ] ]
cluster_14 = cluster
|> "l _h .s" <| [
FaCCaL `verb` {- <la_h_ha.s> -} [ unwords [ ['s','u','m'], ['u','p'] ], ['s','u','m','m','a','r','i','z','e'] ],
TaFaCCaL `verb` {- <tala_h_ha.s> -} [ unwords [ ['b','e'], ['s','u','m','m','a','r','i','z','e','d'] ] ],
TaFCIL `noun` {- <tal_hI.s> -} [ ['s','u','m','m','a','r','y'], ['o','u','t','l','i','n','e'], unwords [ ['s','h','o','r','t'], ['r','e','p','o','r','t'] ] ]
`plural` TaFCIL |< At,
MuFaCCaL `adj` {- <mula_h_ha.s> -} [ ['a','b','r','i','d','g','e','d'], ['c','o','n','d','e','n','s','e','d'] ],
MuFaCCaL `noun` {- <mula_h_ha.s> -} [ ['s','u','m','m','a','r','y'], ['e','x','t','r','a','c','t'] ]
`plural` MuFaCCaL |< At ]
cluster_15 = cluster
|> "l _h l _h" <| [
KaRDaS `verb` {- <la_hla_h> -} [ unwords [ ['s','h','a','k','e'], ['o','f','f'] ] ],
TaKaRDaS `verb` {- <tala_hla_h> -} [ ['s','h','a','k','e'], ['t','o','t','t','e','r'] ],
MuKaRDaS `adj` {- <mula_hla_h> -} [ ['u','n','s','t','e','a','d','y'], ['t','o','t','t','e','r','i','n','g'] ] ]
cluster_16 = cluster
|> "l _h m" <| [
FaCaL |< aT `noun` {- <la_hamaT> -} [ ['o','a','f'], ['l','o','u','t'] ],
MaFCUL `adj` {- <mal_hUm> -} [ ['a','w','k','w','a','r','d'], ['c','l','u','m','s','y'] ] ]
cluster_17 = cluster
|> "l _h n" <| [
FaCaL `noun` {- <la_han> -} [ unwords [ ['p','u','t','r','i','d'], ['s','t','e','n','c','h'] ] ],
HaFCaL `adj` {- <'al_han> -} [ ['s','t','i','n','k','i','n','g'] ]
`plural` FuCL
`femini` FaCLA',
HaFCaL `adj` {- <'al_han> -} [ ['u','n','c','i','r','c','u','m','c','i','s','e','d'] ]
`plural` FuCL
`femini` FaCLA' ]
cluster_18 = cluster
|> "l d .g" <| [
FaCaL `verb` {- <lada.g> -} [ ['s','t','i','n','g'], ['b','i','t','e'], ['p','r','i','c','k'] ]
`imperf` FCuL,
FaCL |< aT `noun` {- <lad.gaT> -} [ ['s','t','i','n','g'], ['b','i','t'] ],
FaCIL `adj` {- <ladI.g> -} [ ['s','t','u','n','g'], ['b','i','t','t','e','n'] ]
`plural` FuCaLA'
`plural` FaCLY,
FACiL `adj` {- <lAdi.g> -} [ ['s','t','i','n','g','i','n','g'], ['b','i','t','i','n','g'] ],
MaFCUL `adj` {- <maldU.g> -} [ ['s','t','u','n','g'], ['b','i','t','t','e','n'] ] ]
cluster_19 = cluster
|> "l d n" <| [
FaCuL `verb` {- <ladun> -} [ unwords [ ['b','e'], ['s','o','f','t'] ], unwords [ ['b','e'], ['f','l','e','x','i','b','l','e'] ] ]
`imperf` FCuL
`masdar` FaCAL |< aT
`masdar` FuCUL |< aT,
< laddan >
FaCiL `noun` {- <ladin> -} [ ['L','a','d','e','n'], ['L','a','d','i','n'] ],
FaCL `adj` {- <ladn> -} [ ['s','o','f','t'], ['p','l','i','a','n','t'], ['f','l','e','x','i','b','l','e'] ]
`plural` FuCL
`plural` FiCAL,
FaCuL `prep` {- <ladun> -} [ ['n','e','a','r'] ],
FACiL `noun` {- <lAdin> -} [ ['L','a','d','e','n'], ['L','a','d','i','n'] ],
< lAdan >
FaCAL |< aT `noun` {- <ladAnaT> -} [ ['s','o','f','t','n','e','s','s'], ['p','l','i','a','b','i','l','i','t','y'], ['f','l','e','x','i','b','i','l','i','t','y'] ],
FaCUL |< aT `noun` {- <ladUnaT> -} [ ['s','o','f','t','n','e','s','s'], ['p','l','i','a','b','i','l','i','t','y'], ['f','l','e','x','i','b','i','l','i','t','y'] ],
FaCA'iL `noun` {- <ladA'in> -} [ ['p','l','a','s','t','i','c','s'] ]
`plural` FaCA'iL
`limited` "-------P--",
FaCuL |< Iy `adj` {- <ladunIy> -} [ ['m','y','s','t','i','c'], ['i','n','t','u','i','t','i','v','e'] ] ]
cluster_20 = cluster
|> "l _d `" <| [
FaCaL `verb` {- <la_da`> -} [ ['b','u','r','n'], ['c','a','u','t','e','r','i','z','e'], ['o','f','f','e','n','d'] ]
`imperf` FCaL,
TaFaCCaL `verb` {- <tala_d_da`> -} [ ['b','u','r','n'] ],
FaCL `noun` {- <la_d`> -} [ ['b','u','r','n','i','n','g'], ['c','o','m','b','u','s','t','i','o','n'] ],
FaCL `noun` {- <la_d`> -} [ ['c','o','n','f','l','a','g','r','a','t','i','o','n'], ['f','i','r','e'] ],
FaCCAL `adj` {- <la_d_dA`> -} [ ['b','u','r','n','i','n','g'], ['p','u','n','g','e','n','t'], ['s','h','a','r','p'] ],
FACiL `adj` {- <lA_di`> -} [ ['b','u','r','n','i','n','g'], ['s','h','a','r','p'], ['s','t','i','n','g','i','n','g'] ],
FACiL |< aT `noun` {- <lA_di`aT> -} [ ['g','i','b','e'], ['t','a','u','n','t'] ]
`plural` FawACiL,
FawCaL `noun` {- <law_da`> -} [ ['w','i','t','t','y'], unwords [ ['q','u','i','c','k'], "-", ['w','i','t','t','e','d'] ] ],
FawCaL |< Iy `adj` {- <law_da`Iy> -} [ ['w','i','t','t','y'], unwords [ ['q','u','i','c','k'], "-", ['w','i','t','t','e','d'] ] ],
FawCaL |< Iy |< aT `noun` {- <law_da`IyaT> -} [ ['w','i','t'], unwords [ ['q','u','i','c','k'], "-", ['w','i','t','t','e','d','n','e','s','s'] ] ] ]
cluster_21 = cluster
|> "l _d q" <| [
FACiL |< Iy |< aT `noun` {- <lA_diqIyaT> -} [ ['L','a','t','a','k','i','a'] ] ]
cluster_22 = cluster
|> ['l','U','r'] <| [
_____ `noun` {- <lUr> -} [ ['l','y','r','e'] ] ]
cluster_23 = cluster
|> ['l','I','r'] <| [
_____ |< aT `noun` {- <lIraT> -} [ ['p','o','u','n','d'], ['l','i','r','a'] ]
`plural` _____ |< At ]
cluster_24 = cluster
|> ['l','U','r','I'] <| [
_____ `noun` {- <lUrI> -} [ ['l','o','r','r','y'], ['t','r','u','c','k'] ] ]
cluster_25 = cluster
|> "l z b" <| [
FaCaL `verb` {- <lazab> -} [ ['a','d','h','e','r','e'], ['s','t','i','c','k'] ]
`imperf` FCuL,
FaCiL `verb` {- <lazib> -} [ unwords [ ['s','t','i','c','k'], ['t','o','g','e','t','h','e','r'] ] ]
`imperf` FCaL,
FaCiL `adj` {- <lazib> -} [ ['l','i','t','t','l','e'] ]
`plural` FiCAL,
FaCL |< aT `noun` {- <lazbaT> -} [ ['m','i','s','f','o','r','t','u','n','e'], ['c','a','l','a','m','i','t','y'] ]
`plural` FiCaL,
FACiL `adj` {- <lAzib> -} [ unwords [ ['a','d','h','e','r','i','n','g'], ['t','i','g','h','t','l','y'] ], unwords [ ['f','i','r','m','l','y'], ['f','i','x','e','d'] ] ] ]
cluster_26 = cluster
|> "l z ^g" <| [
< lazi^g >
`imperf` FCaL
`masdar` FaCaL
`masdar` FuCUL,
< lazi^g >
FuCUL |< aT `noun` {- <luzU^gaT> -} [ ['s','t','i','c','k','i','n','e','s','s'], ['a','d','h','e','s','i','v','e','n','e','s','s'] ] ]
cluster_27 = cluster
|> "l z q" <| [
FaCiL `verb` {- <laziq> -} [ ['a','d','h','e','r','e'], ['c','l','i','n','g'] ]
`imperf` FCaL,
FaCCaL `verb` {- <lazzaq> -} [ unwords [ ['p','a','s','t','e'], ['o','n'] ], unwords [ ['s','t','i','c','k'], ['o','n'] ] ],
HaFCaL `verb` {- <'alzaq> -} [ unwords [ ['p','a','s','t','e'], ['o','n'] ], unwords [ ['s','t','i','c','k'], ['o','n'] ] ],
IFtaCaL `verb` {- <iltazaq> -} [ ['a','d','h','e','r','e'], ['c','l','i','n','g'] ],
FiCL `adj` {- <lizq> -} [ ['a','d','j','a','c','e','n','t'], ['c','o','n','t','i','g','u','o','u','s'] ],
FaCiL `adj` {- <laziq> -} [ ['s','t','i','c','k','y'], ['g','l','u','e','y'] ],
FaCL |< aT `noun` {- <lazqaT> -} [ ['p','l','a','s','t','e','r'], ['c','o','m','p','r','e','s','s'] ],
FiCAL `noun` {- <lizAq> -} [ ['a','d','h','e','s','i','v','e'], ['g','l','u','e'], ['p','a','s','t','e'] ],
< lazUq >
< lAzUq >
cluster_28 = cluster
|> "l z m" <| [
< lazim >
`imperf` FCaL,
FACaL `verb` {- <lAzam> -} [ ['a','c','c','o','m','p','a','n','y'], unwords [ ['p','e','r','s','e','v','e','r','e'], ['i','n'] ] ],
HaFCaL `verb` {- <'alzam> -} [ ['o','b','l','i','g','a','t','e'], ['f','o','r','c','e'] ],
TaFACaL `verb` {- <talAzam> -} [ unwords [ ['b','e'], ['i','n','s','e','p','a','r','a','b','l','e'] ], unwords [ ['b','e'], ['a','t','t','a','c','h','e','d'], ['t','o'], ['e','a','c','h'], ['o','t','h','e','r'] ] ],
IFtaCaL `verb` {- <iltazam> -} [ unwords [ ['b','e'], ['c','o','m','m','i','t','t','e','d'] ], ['m','a','i','n','t','a','i','n'], ['p','r','e','s','e','r','v','e'] ],
IstaFCaL `verb` {- <istalzam> -} [ unwords [ ['d','e','e','m'], ['n','e','c','e','s','s','a','r','y'] ], ['r','e','q','u','i','r','e'] ],
FaCL |< aT `noun` {- <lazmaT> -} [ unwords [ ['o','f','f','i','c','i','a','l'], ['c','o','n','c','e','s','s','i','o','n'] ] ]
`plural` FaCaL |< At,
FuCUL `noun` {- <luzUm> -} [ ['r','e','q','u','i','r','e','m','e','n','t'], ['n','e','c','e','s','s','i','t','y'], ['e','x','i','g','e','n','c','y'] ],
FiCAL `noun` {- <lizAm> -} [ ['n','e','c','e','s','s','a','r','y'], ['r','e','q','u','i','s','i','t','e'] ],
HaFCaL `adj` {- <'alzam> -} [ unwords [ ['m','o','r','e'], "/", ['m','o','s','t'], ['n','e','c','e','s','s','a','r','y'] ] ],
MaFCaL |< aT `noun` {- <malzamaT> -} [ ['s','e','c','t','i','o','n'] ]
`plural` MaFACiL,
MiFCaL |< aT `noun` {- <milzamaT> -} [ ['v','i','s','e'], ['p','r','e','s','s'] ]
`plural` MaFACiL,
TaFCIL `noun` {- <talzIm> -} [ unwords [ ['a','w','a','r','d'], ['o','f'], ['o','p','e','n'], ['c','o','n','t','r','a','c','t'] ] ]
`plural` TaFCIL |< At,
< mulAzamaT >
HiFCAL `noun` {- <'ilzAm> -} [ ['c','o','e','r','c','i','o','n'], ['c','o','m','p','u','l','s','i','o','n'] ]
`plural` HiFCAL |< At,
HiFCAL |< Iy `adj` {- <'ilzAmIy> -} [ ['c','o','m','p','u','l','s','o','r','y'], ['o','b','l','i','g','a','t','o','r','y'] ],
HiFCAL |< Iy |< aT `noun` {- <'ilzAmIyaT> -} [ ['c','o','m','p','u','l','s','o','r','i','n','e','s','s'] ],
IFtiCAL `noun` {- <iltizAm> -} [ ['c','o','m','m','i','t','m','e','n','t'], ['o','b','l','i','g','a','t','i','o','n'] ]
`plural` IFtiCAL |< At,
IFtiCAL |< Iy `adj` {- <iltizAmIy> -} [ ['c','o','m','m','i','t','t','e','d'] ],
FACiL `adj` {- <lAzim> -} [ ['n','e','c','e','s','s','a','r','y'], ['r','e','q','u','i','r','e','d'], ['n','e','e','d','e','d'] ],
FACiL |< aT `noun` {- <lAzimaT> -} [ unwords [ ['i','n','h','e','r','e','n','t'], ['p','r','o','p','e','r','t','y'] ], unwords [ ['f','i','x','e','d'], ['a','t','t','r','i','b','u','t','e'] ], ['e','x','i','g','e','n','c','i','e','s'], ['r','e','q','u','i','s','i','t','e','s'] ]
`plural` FawACiL,
MaFCUL `adj` {- <malzUm> -} [ ['o','b','l','i','g','a','t','e','d'], ['l','i','a','b','l','e'] ],
MaFCUL |< Iy |< aT `noun` {- <malzUmIyaT> -} [ ['o','b','l','i','g','a','t','i','o','n'], ['l','i','a','b','i','l','i','t','y'] ],
MuFACiL `noun` {- <mulAzim> -} [ ['l','i','e','u','t','e','n','a','n','t'] ]
`plural` MuFACiL |< Un
`femini` MuFACiL |< aT,
MuFCiL `adj` {- <mulzim> -} [ ['b','i','n','d','i','n','g'], ['r','e','q','u','i','s','i','t','e'] ],
MuFCaL `adj` {- <mulzam> -} [ ['o','b','l','i','g','a','t','e','d'], ['l','i','a','b','l','e'] ],
MutaFACiL |< aT `noun` {- <mutalAzimaT> -} [ ['s','y','n','d','r','o','m','e'] ],
< multazim >
MuFtaCaL `noun` {- <multazam> -} [ ['r','e','q','u','i','r','e','m','e','n','t'] ]
`plural` MuFtaCaL |< At,
MustaFCaL `noun` {- <mustalzam> -} [ ['r','e','q','u','i','r','e','m','e','n','t'] ]
`plural` MustaFCaL |< At ]
cluster_29 = cluster
|> ['l','U','z','A','n'] <| [
_____ `xtra` {- <lUzAn> -} [ ['L','a','u','s','a','n','n','e'] ],
< >
cluster_30 = cluster
|> "l s `" <| [
FaCaL `verb` {- <lasa`> -} [ ['s','t','i','n','g'], ['b','u','r','n'] ]
`imperf` FCaL,
FaCL `noun` {- <las`> -} [ ['s','t','i','n','g','i','n','g'], ['b','u','r','n','i','n','g'] ],
FaCL |< aT `noun` {- <las`aT> -} [ ['s','t','i','n','g'], ['b','i','t','e'] ],
FaCIL `adj` {- <lasI`> -} [ ['s','t','u','n','g'] ]
`plural` FaCLY
`plural` FuCaLA',
FACiL `adj` {- <lAsi`> -} [ ['s','t','i','n','g','i','n','g'], ['b','i','t','i','n','g'], ['s','h','a','r','p'] ],
MaFCUL `adj` {- <malsU`> -} [ ['s','t','u','n','g'], ['b','i','t','t','e','n'] ] ]
cluster_31 = cluster
|> "l s n" <| [
FaCiL `verb` {- <lasin> -} [ unwords [ ['b','e'], ['e','l','o','q','u','e','n','t'] ] ]
`imperf` FCaL
`masdar` FaCaL,
FaCCaL `verb` {- <lassan> -} [ ['s','h','a','r','p','e','n'], ['t','a','p','e','r'] ],
TaFACaL `verb` {- <talAsan> -} [ ['a','l','t','e','r','c','a','t','e'], unwords [ ['e','x','c','h','a','n','g','e'], ['w','o','r','d','s'] ], unwords [ ['t','r','a','d','e'], ['i','n','s','u','l','t','s'] ] ],
< lasan >
FaCiL `adj` {- <lasin> -} [ ['e','l','o','q','u','e','n','t'] ],
HaFCaL `adj` {- <'alsan> -} [ ['e','l','o','q','u','e','n','t'] ]
`plural` FuCL
`femini` FaCLA',
FiCAL `noun` {- <lisAn> -} [ ['t','o','n','g','u','e'] ]
`plural` HaFCiL |< aT
`plural` HaFCuL,
FiCAL `noun` {- <lisAn> -} [ ['l','a','n','g','u','a','g','e'] ]
`plural` HaFCiL |< aT
`plural` HaFCuL,
FiCAL `noun` {- <lisAn> -} [ ['m','o','u','t','h','p','i','e','c','e'] ],
FiCAL |< Iy `adj` {- <lisAnIy> -} [ ['v','e','r','b','a','l'], ['o','r','a','l'] ],
FiCAL |< Iy |< At `noun` {- <lisAnIyAt> -} [ ['l','i','n','g','u','i','s','t','i','c','s'] ]
`plural` FiCAL |< Iy |< At
`limited` "-------P--",
TaFACuL `noun` {- <talAsun> -} [ ['a','l','t','e','r','c','a','t','i','o','n'], unwords [ ['e','x','c','h','a','n','g','e'], ['o','f'], ['w','o','r','d','s'] ] ]
`plural` TaFACuL |< At,
MaFCUL `noun` {- <malsUn> -} [ ['l','i','a','r'] ]
`plural` MaFCUL |< Un
`femini` MaFCUL |< aT ]
cluster_32 = cluster
|> ['l','I','s','A','n','s'] <| [
_____ `noun` {- <lIsAns> -} [ ['l','i','c','e','n','c','e'] ] ]
cluster_33 = cluster
|> ['l','a','s','t','i','k'] <| [
_____ `noun` {- <lastik> -} [ ['r','u','b','b','e','r'], ['e','r','a','s','e','r'] ] ]
|> ['l','a','s','t','I','k'] <| [
_____ `noun` {- <lastIk> -} [ ['r','u','b','b','e','r'], ['e','r','a','s','e','r'] ] ]
cluster_34 = cluster
|> ['l','i','^','s','b','U','n'] <| [
_____ |< aT `noun` {- <li^sbUnaT> -} [ ['L','i','s','b','o','n'] ]
`excepts` Diptote ]
cluster_35 = cluster
|> "l .s q" <| [
FaCiL `verb` {- <la.siq> -} [ ['a','d','h','e','r','e'], ['c','l','i','n','g'] ]
`imperf` FCaL,
FaCCaL `verb` {- <la.s.saq> -} [ unwords [ ['p','a','s','t','e'], ['t','o','g','e','t','h','e','r'] ], unwords [ ['s','t','i','c','k'], ['t','o','g','e','t','h','e','r'] ] ],
FACaL `verb` {- <lA.saq> -} [ unwords [ ['b','e'], ['n','e','x','t'], ['t','o'] ], unwords [ ['b','e'], ['i','n'], ['t','o','u','c','h'], ['w','i','t','h'] ] ],
HaFCaL `verb` {- <'al.saq> -} [ ['a','t','t','a','c','h'], ['a','p','p','e','n','d'], ['j','o','i','n'] ],
TaFACaL `verb` {- <talA.saq> -} [ unwords [ ['s','t','i','c','k'], ['t','o','g','e','t','h','e','r'] ], unwords [ ['b','e'], ['c','o','h','e','s','i','v','e'] ] ],
IFtaCaL `verb` {- <ilta.saq> -} [ ['a','t','t','a','c','h'], ['a','f','f','i','x'], ['a','d','h','e','r','e'] ],
FaCL |< Iy `adj` {- <la.sqIy> -} [ ['a','g','g','l','u','t','i','n','a','t','i','n','g'] ],
FiCL `noun` {- <li.sq> -} [ ['a','d','h','e','r','i','n','g'], ['c','l','i','n','g','i','n','g'] ],
FaCiL `adj` {- <la.siq> -} [ ['s','t','i','c','k','y'], ['g','l','u','e','y'], ['a','d','h','e','s','i','v','e'] ],
FaCIL `adj` {- <la.sIq> -} [ ['c','l','i','n','g','i','n','g'], ['c','o','n','t','i','g','u','o','u','s'], unwords [ ['c','l','o','s','e'], "-", ['f','i','t','t','i','n','g'] ] ],
FaCUL `noun` {- <la.sUq> -} [ ['p','l','a','s','t','e','r'], ['a','d','h','e','s','i','v','e'] ],
MuFACaL |< aT `noun` {- <mulA.saqaT> -} [ ['c','o','n','n','e','c','t','i','o','n'], ['a','d','h','e','s','i','o','n'], ['u','n','i','o','n'] ],
HiFCAL `noun` {- <'il.sAq> -} [ ['p','o','s','t','e','r'], ['p','l','a','c','a','r','d'] ]
`plural` HiFCAL |< At,
TaFACuL `noun` {- <talA.suq> -} [ ['c','o','h','e','s','i','o','n'], ['a','d','h','e','s','i','o','n'], ['c','o','n','t','a','c','t'] ]
`plural` TaFACuL |< At,
IFtiCAL `noun` {- <ilti.sAq> -} [ ['c','o','h','e','s','i','o','n'], ['a','d','h','e','s','i','o','n'], ['c','o','n','t','a','c','t'] ]
`plural` IFtiCAL |< At,
FACiL `adj` {- <lA.siq> -} [ ['a','d','h','e','s','i','v','e'] ],
FACiL |< aT `noun` {- <lA.siqaT> -} [ ['s','u','f','f','i','x'] ]
`plural` FawACiL,
MuFACiL `adj` {- <mulA.siq> -} [ ['c','o','n','t','i','g','u','o','u','s'], ['a','d','j','a','c','e','n','t'] ],
MuFACiL `noun` {- <mulA.siq> -} [ ['c','o','m','p','a','n','i','o','n'], ['n','e','i','g','h','b','o','r'], ['a','d','h','e','r','e','n','t'] ]
`plural` MuFACiL |< Un
`femini` MuFACiL |< aT,
MuFCaL `adj` {- <mul.saq> -} [ ['a','t','t','a','c','h','e','d'], unwords [ ['p','a','s','t','e','d'], ['o','n'] ], ['f','a','s','t','e','n','e','d'] ],
MuFCaL `noun` {- <mul.saq> -} [ ['p','o','s','t','e','r'], ['p','l','a','c','a','r','d'] ]
`plural` MuFCaL |< At,
MutaFACiL `adj` {- <mutalA.siq> -} [ unwords [ ['s','t','i','c','k','i','n','g'], ['t','o','g','e','t','h','e','r'] ], ['c','o','h','e','s','i','v','e'] ],
MuFtaCiL `adj` {- <multa.siq> -} [ ['a','t','t','a','c','h','e','d'], ['a','d','h','e','s','i','v','e'], unwords [ ['i','n'], ['c','o','n','t','a','c','t'] ] ] ]
cluster_36 = cluster
|> "l .d m" <| [
MaFCUL `adj` {- <mal.dUm> -} [ ['d','e','n','s','e'], ['c','l','o','s','e'] ] ]
cluster_37 = cluster
|> "l .t _h" <| [
FaCaL `verb` {- <la.ta_h> -} [ ['s','t','a','i','n'], ['s','o','i','l'], ['s','p','l','a','s','h'] ]
`imperf` FCaL,
FaCCaL `verb` {- <la.t.ta_h> -} [ ['s','t','a','i','n'], ['s','o','i','l'], ['s','p','l','a','s','h'] ],
TaFaCCaL `verb` {- <tala.t.ta_h> -} [ unwords [ ['b','e'], ['s','o','i','l','e','d'] ], unwords [ ['b','e'], ['s','t','a','i','n','e','d'] ] ],
FaCL `noun` {- <la.t_h> -} [ ['s','t','a','i','n','i','n','g'], ['s','o','i','l','i','n','g'] ],
FaCL |< aT `noun` {- <la.t_haT> -} [ ['s','t','a','i','n'], ['b','l','o','t','c','h'], ['b','l','e','m','i','s','h'] ]
`plural` FaCaL |< At,
FuCaL |< aT `noun` {- <lu.ta_haT> -} [ ['f','o','o','l'], ['d','o','l','t'] ]
`plural` FuCaL |< At,
FiCCIL `noun` {- <li.t.tI_h> -} [ ['f','o','o','l'], ['d','o','l','t'] ],
< mula.t.ta_h >
cluster_38 = cluster
|> "l .t s" <| [
< la.tas >
`imperf` FCuL,
FaCL `noun` {- <la.ts> -} [ ['s','t','r','i','k','i','n','g'], ['h','i','t','t','i','n','g'] ],
MiFCAL `noun` {- <mil.tAs> -} [ ['p','i','c','k','a','x'] ]
`plural` MaFACIL ]
cluster_39 = cluster
|> "l .t ^s" <| [
FaCaL `verb` {- <la.ta^s> -} [ ['s','t','r','i','k','e'], ['h','i','t'] ]
`imperf` FCuL,
FaCL `noun` {- <la.t^s> -} [ ['s','t','r','i','k','i','n','g'], ['h','i','t','t','i','n','g'] ] ]
cluster_40 = cluster
|> "l .t `" <| [
FaCaL `verb` {- <la.ta`> -} [ ['s','t','r','i','k','e'], ['h','i','t'], ['d','e','l','e','t','e'] ]
`imperf` FCaL,
FaCL `noun` {- <la.t`> -} [ ['s','t','r','i','k','i','n','g'], ['h','i','t','t','i','n','g'], ['d','e','l','e','t','i','o','n'] ],
FaCL |< aT `noun` {- <la.t`aT> -} [ ['b','l','o','t'], ['s','t','a','i','n'] ] ]
cluster_41 = cluster
|> "l .t f" <| [
FaCaL `verb` {- <la.taf> -} [ unwords [ ['b','e'], ['k','i','n','d'] ] ]
`imperf` FCuL
`masdar` FuCL
`masdar` FaCaL,
FaCuL `verb` {- <la.tuf> -} [ unwords [ ['b','e'], ['e','l','e','g','a','n','t'] ], unwords [ ['b','e'], ['a','m','i','a','b','l','e'] ] ]
`imperf` FCuL
`masdar` FaCAL |< aT,
FaCCaL `verb` {- <la.t.taf> -} [ ['s','o','f','t','e','n'], ['a','l','l','e','v','i','a','t','e'] ],
FACaL `verb` {- <lA.taf> -} [ unwords [ ['t','r','e','a','t'], ['k','i','n','d','l','y'] ], unwords [ ['b','e'], ['p','o','l','i','t','e'], ['w','i','t','h'] ] ],
TaFaCCaL `verb` {- <tala.t.taf> -} [ unwords [ ['b','e'], ['a','f','f','e','c','t','i','o','n','a','t','e'] ], unwords [ ['b','e'], ['m','o','d','e','r','a','t','e','d'] ] ],
TaFACaL `verb` {- <talA.taf> -} [ unwords [ ['b','e'], ['c','i','v','i','l'] ], unwords [ ['b','e'], ['c','o','u','r','t','e','o','u','s'] ] ],
IstaFCaL `verb` {- <istal.taf> -} [ unwords [ ['f','i','n','d'], ['p','l','e','a','s','a','n','t'] ] ],
FuCL `noun` {- <lu.tf> -} [ ['g','e','n','t','l','e','n','e','s','s'], ['c','i','v','i','l','i','t','y'] ],
FuCL |<< "aN" `noun` {- <lu.tfaN> -} [ ['p','l','e','a','s','e'] ],
FuCL |< Iy `noun` {- <lu.tfIy> -} [ ['L','u','t','f','i'] ],
FaCAL |< aT `noun` {- <la.tAfaT> -} [ ['k','i','n','d','n','e','s','s'], ['p','o','l','i','t','e','n','e','s','s'], ['r','e','f','i','n','e','m','e','n','t'] ],
FaCIL `adj` {- <la.tIf> -} [ ['d','e','l','i','c','a','t','e'], ['g','e','n','t','l','e'], ['p','o','l','i','t','e'] ]
`plural` FuCaLA'
`plural` FiCAL,
FaCIL `noun` {- <la.tIf> -} [ ['L','a','t','i','f'], ['L','a','t','e','e','f'] ],
FaCIL |< aT `noun` {- <la.tIfaT> -} [ ['q','u','i','p'], ['j','o','k','e'], ['s','u','b','t','l','e','t','y'] ]
`plural` FaCA'iL,
FaCIL |< aT `noun` {- <la.tIfaT> -} [ ['L','a','t','i','f','a'], ['L','a','t','e','e','f','a'] ],
HaFCaL `adj` {- <'al.taf> -} [ unwords [ ['f','i','n','e','r'], "/", ['f','i','n','e','s','t'] ], unwords [ ['n','i','c','e'], "/", ['n','i','c','e','s','t'] ] ],
MuFACaL |< aT `noun` {- <mulA.tafaT> -} [ ['c','o','u','r','t','e','s','y'], ['f','r','i','e','n','d','l','i','n','e','s','s'], ['k','i','n','d','n','e','s','s'] ],
MuFACaL |< At `noun` {- <mulA.tafAt> -} [ ['c','a','r','e','s','s','e','s'] ]
`plural` MuFACaL |< At
`limited` "-------P--",
TaFaCCuL `noun` {- <tala.t.tuf> -} [ ['f','r','i','e','n','d','l','i','n','e','s','s'], ['c','i','v','i','l','i','t','y'] ]
`plural` TaFaCCuL |< At,
MuFaCCiL `noun` {- <mula.t.tif> -} [ ['p','a','l','l','i','a','t','i','v','e'], ['s','e','d','a','t','i','v','e'] ]
`plural` MuFaCCiL |< At,
MuFaCCaL `adj` {- <mula.t.taf> -} [ ['k','i','n','d','e','r'], ['g','e','n','t','l','e','r'], ['s','o','f','t','e','r'] ] ]
cluster_42 = cluster
|> "l .t m" <| [
FaCaL `verb` {- <la.tam> -} [ ['s','l','a','p'], unwords [ ['s','t','r','i','k','e'], ['a','g','a','i','n','s','t'] ] ]
`imperf` FCiL,
TaFACaL `verb` {- <talA.tam> -} [ unwords [ ['e','x','c','h','a','n','g','e'], ['b','l','o','w','s'] ], ['b','r','a','w','l'] ],
IFtaCaL `verb` {- <ilta.tam> -} [ ['c','o','l','l','i','d','e'], ['c','l','a','s','h'] ],
FaCL |< aT `noun` {- <la.tmaT> -} [ ['s','l','a','p'], ['b','l','o','w'], ['s','h','o','v','e'] ]
`plural` FaCaL |< At,
FaCIL `adj` {- <la.tIm> -} [ ['p','a','r','e','n','t','l','e','s','s'] ],
MaFCaL `noun` {- <mal.tam> -} [ ['c','h','e','e','k'] ],
MutaFACiL `adj` {- <mutalA.tim> -} [ ['p','o','u','n','d','i','n','g'], ['c','o','l','l','i','d','i','n','g'] ],
MuFtaCaL `noun` {- <multa.tam> -} [ ['c','l','a','s','h'], ['t','u','r','m','o','i','l'], ['b','r','a','w','l'] ] ]
cluster_43 = cluster
|> "l ` b" <| [
FaCiL `verb` {- <la`ib> -} [ ['p','l','a','y'] ]
`imperf` FCaL,
FACaL `verb` {- <lA`ab> -} [ unwords [ ['p','l','a','y'], ['w','i','t','h'] ], unwords [ ['j','e','s','t'], ['w','i','t','h'] ] ],
TaFACaL `verb` {- <talA`ab> -} [ unwords [ ['b','e'], ['p','l','a','y','f','u','l'] ], ['m','o','c','k'], unwords [ ['a','c','t'], ['f','r','a','u','d','u','l','e','n','t','l','y'] ] ],
FaCL `noun` {- <la`b> -} [ ['g','a','m','e'], ['s','p','o','r','t'] ]
`plural` HaFCAL,
FaCL |< aT `noun` {- <la`baT> -} [ ['g','a','m','e'], ['m','a','t','c','h'], ['e','v','e','n','t'] ]
`plural` FaCaL |< At,
FuCL |< aT `noun` {- <lu`baT> -} [ ['t','o','y'], ['g','a','m','e'] ]
`plural` FuCaL,
FaCCAL `adj` {- <la``Ab> -} [ ['p','l','a','y','f','u','l'] ],
FiCCIL `adj` {- <li``Ib> -} [ ['p','l','a','y','f','u','l'] ],
FuCAL `noun` {- <lu`Ab> -} [ ['s','a','l','i','v','a'], ['d','r','i','v','e','l'] ],
FuCAL |< Iy `adj` {- <lu`AbIy> -} [ ['s','a','l','i','v','a','r','y'] ],
FuCayL |< aT `noun` {- <lu`aybaT> -} [ unwords [ ['l','i','t','t','l','e'], ['d','o','l','l'] ] ]
`plural` FuCayL |< At,
FaCUL `adj` {- <la`Ub> -} [ ['c','o','q','u','e','t','t','i','s','h'], ['f','l','i','r','t','a','t','i','o','u','s'] ],
HuFCUL |< aT `noun` {- <'ul`UbaT> -} [ ['p','l','a','y','t','h','i','n','g'], ['p','r','a','n','k'], ['t','r','i','c','k'], unwords [ ['s','h','a','d','o','w'], ['b','o','x','i','n','g'] ] ]
`plural` HaFACIL,
MaFCaL `noun` {- <mal`ab> -} [ ['p','l','a','y','g','r','o','u','n','d'], unwords [ ['s','p','o','r','t','s'], ['f','i','e','l','d'] ], ['s','t','a','d','i','u','m'] ]
`plural` MaFACiL,
MaFCaL |< aT `noun` {- <mal`abaT> -} [ ['p','l','a','y','t','h','i','n','g'], ['t','o','y'] ],
TaFACuL `noun` {- <talA`ub> -} [ ['g','a','m','e'], unwords [ ['f','r','e','e'], ['p','l','a','y'] ], ['v','e','n','a','l','i','t','y'] ]
`plural` TaFACuL |< At,
FACiL `noun` {- <lA`ib> -} [ ['p','l','a','y','e','r'], ['a','t','h','l','e','t','e'] ]
`plural` FACiL |< Un
`femini` FACiL |< aT,
MaFCUL `noun` {- <mal`Ub> -} [ ['s','l','o','b','b','e','r','i','n','g'], ['p','r','a','n','k'] ]
`plural` MaFACIL
`femini` MaFCUL |< aT,
MuFACiL `noun` {- <mulA`ib> -} [ ['p','l','a','y','e','r'], ['f','r','a','u','d','u','l','e','n','t'] ]
`plural` MuFACiL |< Un
`femini` MuFACiL |< aT,
< >
cluster_44 = cluster
|> "l ` _t m" <| [
TaKaRDaS `verb` {- <tala`_tam> -} [ ['h','e','s','i','t','a','t','e'], ['s','t','a','m','m','e','r'] ],
KaRDaS |< aT `noun` {- <la`_tamaT> -} [ ['h','e','s','i','t','a','t','i','o','n'], ['s','t','u','t','t','e','r','i','n','g'] ],
TaKaRDuS `noun` {- <tala`_tum> -} [ ['h','e','s','i','t','a','t','i','o','n'], ['s','t','u','t','t','e','r','i','n','g'] ]
`plural` TaKaRDuS |< At,
MutaKaRDiS `adj` {- <mutala`_tim> -} [ ['h','e','s','i','t','a','t','i','n','g'], ['s','t','u','t','t','e','r','i','n','g'] ] ]
cluster_45 = cluster
|> "l ` ^g" <| [
FaCaL `verb` {- <la`a^g> -} [ ['h','u','r','t'], ['b','u','r','n'] ]
`imperf` FCaL,
FACaL `verb` {- <lA`a^g> -} [ ['o','p','p','r','e','s','s'], ['d','i','s','t','r','e','s','s'] ],
FaCL |< aT `noun` {- <la`^gaT> -} [ ['p','a','i','n'] ],
< lA`i^g >
`plural` FawACiL,
< lA`i^g >
`plural` FawACiL ]
cluster_46 = cluster
|> "l ` s" <| [
HaFCaL `adj` {- <'al`as> -} [ unwords [ ['r','e','d'], "-", ['l','i','p','p','e','d'] ] ]
`femini` FaCLA' ]
cluster_47 = cluster
|> "l ` q" <| [
FaCiL `verb` {- <la`iq> -} [ ['l','i','c','k'] ]
`imperf` FCaL
`masdar` FaCL,
FuCL |< aT `noun` {- <lu`qaT> -} [ ['s','p','o','o','n','f','u','l'] ],
FaCUL `noun` {- <la`Uq> -} [ ['e','l','e','c','t','u','a','r','y'] ],
MiFCaL |< aT `noun` {- <mil`aqaT> -} [ ['s','p','o','o','n'] ]
`plural` MaFACiL ]
cluster_48 = cluster
|> "l ` l" <| [
FaCL `noun` {- <la`l> -} [ ['g','a','r','n','e','t'] ] ]
cluster_49 = cluster
|> "l ` l `" <| [
KaRDaS `verb` {- <la`la`> -} [ ['r','e','s','o','u','n','d'], ['r','e','v','e','r','b','e','r','a','t','e'] ],
TaKaRDaS `verb` {- <tala`la`> -} [ ['f','l','i','c','k','e','r'], ['s','h','i','m','m','e','r'] ],
KaRDaS `noun` {- <la`la`> -} [ unwords [ ['v','i','b','r','a','t','i','o','n'], ['o','f'], ['f','a','t','a'], ['m','o','r','g','a','n','a'] ] ]
`plural` KaRADiS ]
cluster_50 = cluster
|> "l ` n" <| [
FaCaL `verb` {- <la`an> -} [ ['c','u','r','s','e'], ['d','a','m','n'] ]
`imperf` FCaL
`masdar` FaCL,
FACaL `verb` {- <lA`an> -} [ ['i','m','p','r','e','c','a','t','e'], ['c','u','r','s','e'], ['d','a','m','n'] ],
TaFACaL `verb` {- <talA`an> -} [ unwords [ ['e','x','c','h','a','n','g','e'], ['i','m','p','r','e','c','a','t','i','o','n','s'] ] ],
FaCL `noun` {- <la`n> -} [ ['c','u','r','s','i','n','g'], ['i','m','p','r','e','c','a','t','i','n','g'] ],
FaCL |< aT `noun` {- <la`naT> -} [ ['c','u','r','s','e'], ['i','m','p','r','e','c','a','t','i','o','n'] ]
`plural` FaCaL |< At
`plural` FiCAL,
FuCL |< aT `noun` {- <lu`naT> -} [ ['c','u','r','s','e','d'], ['d','a','m','n','e','d'] ],
FiCAL `noun` {- <li`An> -} [ unwords [ ['o','a','t','h'], ['o','f'], ['c','o','n','d','e','m','n','a','t','i','o','n'] ] ],
FaCIL `adj` {- <la`In> -} [ ['c','u','r','s','e','d'], ['d','a','m','n','e','d'], ['d','e','t','e','s','t','e','d'] ],
MaFCUL `adj` {- <mal`Un> -} [ ['c','u','r','s','e','d'], ['d','a','m','n','e','d'] ]
`plural` MaFCUL |< Un
`plural` MaFACIL,
MutaFACiL `adj` {- <mutalA`in> -} [ unwords [ ['c','u','r','s','i','n','g'], ['e','a','c','h'], ['o','t','h','e','r'] ], ['h','o','s','t','i','l','e'] ] ]
cluster_51 = cluster
|> "l .g b" <| [
FuCUL `noun` {- <lu.gUb> -} [ ['e','x','h','a','u','s','t','i','o','n'], ['t','o','i','l'] ],
FaCUL `noun` {- <la.gUb> -} [ ['e','x','h','a','u','s','t','i','o','n'], ['t','o','i','l'] ],
< lA.gib >
`plural` FuCCAL ]
cluster_52 = cluster
|> "l .g d" <| [
FuCL `noun` {- <lu.gd> -} [ ['c','h','i','n'] ]
`plural` HaFCAL
`plural` FuCUL,
FuCLUL `noun` {- <lu.gdUd> -} [ ['c','h','i','n'] ]
`plural` FaCALIL,
FuCuL `noun` {- <lu.gud> -} [ ['L','u','g','h','u','d'] ]
`plural` FuCL ]
cluster_53 = cluster
|> ['l','U','.','g','A','r','I','t','m'] <| [
_____ `noun` {- <lU.gArItm> -} [ ['l','o','g','a','r','i','t','h','m'] ] ]
cluster_54 = cluster
|> "l .g z" <| [
FaCaL `verb` {- <la.gaz> -} [ ['e','q','u','i','v','o','c','a','t','e'], unwords [ ['s','p','e','a','k'], ['i','n'], ['r','i','d','d','l','e','s'] ] ]
`imperf` FCuL,
FACaL `verb` {- <lA.gaz> -} [ ['e','q','u','i','v','o','c','a','t','e'], unwords [ ['s','p','e','a','k'], ['i','n'], ['r','i','d','d','l','e','s'] ] ],
HaFCaL `verb` {- <'al.gaz> -} [ ['e','q','u','i','v','o','c','a','t','e'], unwords [ ['s','p','e','a','k'], ['i','n'], ['r','i','d','d','l','e','s'] ] ],
FuCL `noun` {- <lu.gz> -} [ ['m','y','s','t','e','r','y'], ['e','n','i','g','m','a'], ['r','i','d','d','l','e'] ]
`plural` HaFCAL,
MuFCaL `adj` {- <mul.gaz> -} [ ['m','y','s','t','e','r','i','o','u','s'], ['e','n','i','g','m','a','t','i','c'], ['c','r','y','p','t','i','c'] ] ]
cluster_55 = cluster
|> "l .g .t" <| [
FaCaL `verb` {- <la.ga.t> -} [ unwords [ ['b','e'], ['n','o','i','s','y'] ], unwords [ ['b','e'], ['c','l','a','m','o','r','o','u','s'] ] ]
`imperf` FCaL
`masdar` FaCL
`masdar` FaCIL,
FaCCaL `verb` {- <la.g.ga.t> -} [ unwords [ ['b','e'], ['n','o','i','s','y'] ], unwords [ ['b','e'], ['c','l','a','m','o','r','o','u','s'] ] ],
HaFCaL `verb` {- <'al.ga.t> -} [ unwords [ ['b','e'], ['n','o','i','s','y'] ], unwords [ ['b','e'], ['c','l','a','m','o','r','o','u','s'] ] ],
FaCL `noun` {- <la.g.t> -} [ ['n','o','i','s','e'], ['c','l','a','m','o','r'] ]
`plural` HaFCAL ]
cluster_56 = cluster
|> "l .g m" <| [
FaCaL `verb` {- <la.gam> -} [ unwords [ ['p','l','a','n','t'], ['m','i','n','e','s'] ], ['u','n','d','e','r','m','i','n','e'] ]
`imperf` FCaL
`imperf` FCuL
`masdar` FaCL,
FaCCaL `verb` {- <la.g.gam> -} [ unwords [ ['p','l','a','n','t'], ['m','i','n','e','s'] ], ['u','n','d','e','r','m','i','n','e'] ],
FaCL `noun` {- <la.gm> -} [ ['m','i','n','i','n','g'] ],
FuCL `noun` {- <lu.gm> -} [ ['m','i','n','e'] ]
`plural` HaFCAL,
FaCaL `noun` {- <la.gam> -} [ ['m','i','n','e'] ]
`plural` HaFCAL,
HiFCAL `noun` {- <'il.gAm> -} [ ['m','i','n','i','n','g'], unwords [ ['l','a','y','i','n','g'], ['m','i','n','e','s'] ] ]
`plural` HiFCAL |< At,
MaFCUL `adj` {- <mal.gUm> -} [ ['m','i','n','e','d'] ],
MuFaCCaL `adj` {- <mula.g.gam> -} [ ['m','i','n','e','d'] ] ]
|> "l .g m" <| [
HaFCaL `verb` {- <'al.gam> -} [ ['a','m','a','l','g','a','m','a','t','e'], unwords [ ['a','l','l','o','y'], ['w','i','t','h'], ['m','e','r','c','u','r','y'] ] ],
HiFCAL `noun` {- <'il.gAm> -} [ ['a','m','a','l','g','a','m','a','t','i','o','n'] ],
FuCAL `noun` {- <lu.gAm> -} [ ['f','o','a','m'], ['f','r','o','t','h'] ] ]
cluster_57 = cluster
|> "l .g m .t" <| [
KaRDaS `verb` {- <la.gma.t> -} [ ['s','u','l','l','y'], ['s','m','e','a','r'] ],
KaRDaS |< aT `noun` {- <la.gma.taT> -} [ ['s','u','l','l','y','i','n','g'], ['s','m','e','a','r','i','n','g'] ] ]
cluster_58 = cluster
|> "l f t" <| [
< >
`imperf` FCiL,
< >
HaFCaL `verb` {- <'alfat> -} [ ['t','u','r','n'], ['a','t','t','r','a','c','t'] ],
TaFaCCaL `verb` {- <talaffat> -} [ unwords [ ['t','u','r','n'], ['a','r','o','u','n','d'] ] ],
< >
< >
FaCL `noun` {- <laft> -} [ ['d','i','r','e','c','t','i','n','g'] ],
FiCL `noun` {- <lift> -} [ ['t','u','r','n','i','p'] ],
FaCL |< aT `noun` {- <laftaT> -} [ ['t','u','r','n','a','r','o','u','n','d'], unwords [ ['a','b','o','u','t'], "-", ['f','a','c','e'] ] ]
`plural` FaCaL |< At,
FaCUL `adj` {- <lafUt> -} [ ['s','u','l','l','e','n'], unwords [ ['i','l','l'], "-", ['t','e','m','p','e','r','e','d'] ] ],
FaCAL `adj` {- <lafAt> -} [ ['s','u','l','l','e','n'], unwords [ ['i','l','l'], "-", ['t','e','m','p','e','r','e','d'] ] ],
HaFCaL `adj` {- <'alfat> -} [ unwords [ ['l','e','f','t'], "-", ['h','a','n','d','e','d'] ] ]
`plural` FuCL
`femini` FaCLA',
HiFCAL `noun` {- <'ilfAt> -} [ ['d','i','r','e','c','t','i','n','g'] ],
IFtiCAL `noun` {- <iltifAt> -} [ ['t','u','r','n','i','n','g'], ['a','t','t','e','n','t','i','o','n'] ],
IFtiCAL |< aT `noun` {- <iltifAtaT> -} [ ['t','u','r','n'], ['g','l','a','n','c','e'] ],
IstiFCAL `noun` {- <istilfAt> -} [ unwords [ ['f','e','i','g','n','e','d'], ['a','t','t','e','n','t','i','o','n'] ] ],
< >
FACiL |< aT `noun` {- <lAfitaT> -} [ ['b','i','l','l','b','o','a','r','d'], ['p','l','a','c','a','r','d'] ]
`plural` FACiL |< At,
MuFCiL `adj` {- <mulfit> -} [ ['a','t','t','r','a','c','t','i','n','g'], ['t','u','r','n','i','n','g'] ],
MuFtaCiL `adj` {- <multafit> -} [ unwords [ ['t','u','r','n','i','n','g'], ['a','r','o','u','n','d'] ], ['a','t','t','e','n','t','i','v','e'] ] ]
cluster_59 = cluster
|> ['l','i','f','I','_','t','A','n'] <| [
_____ `noun` {- <lifI_tAn> -} [ ['l','e','v','i','a','t','h','a','n'] ],
_____ |< Iy `adj` {- <lifI_tAnIy> -} [ ['l','e','v','i','a','t','h','a','n'] ] ]
cluster_60 = cluster
|> "l f .h" <| [
FaCaL `verb` {- <lafa.h> -} [ ['b','u','r','n'], ['b','r','u','s','h'] ]
`imperf` FCaL,
FaCL `noun` {- <laf.h> -} [ ['b','u','r','n','i','n','g'], ['b','r','u','s','h','i','n','g'] ],
FaCaLAn `noun` {- <lafa.hAn> -} [ ['b','u','r','n','i','n','g'], ['b','r','u','s','h','i','n','g'] ],
FaCL |< aT `noun` {- <laf.haT> -} [ ['h','e','a','t'], ['f','i','r','e'] ]
`plural` FaCaL |< At,
FaCUL `adj` {- <lafU.h> -} [ ['b','u','r','n','i','n','g'], ['s','c','o','r','c','h','i','n','g'] ],
FACiL `adj` {- <lAfi.h> -} [ ['b','u','r','n','i','n','g'], ['s','c','o','r','c','h','i','n','g'] ]
`plural` FawACiL,
FuCCAL `noun` {- <luffA.h> -} [ ['m','a','n','d','r','a','k','e'] ],
TaFCIL |< aT `noun` {- <talfI.haT> -} [ unwords [ ['s','i','l','k'], ['m','u','f','f','l','e','r'] ] ]
`plural` TaFACIL ]
cluster_61 = cluster
|> "l f .z" <| [
FaCaL `verb` {- <lafa.z> -} [ ['p','r','o','n','o','u','n','c','e'], ['e','x','p','r','e','s','s'] ]
`imperf` FCiL,
TaFaCCaL `verb` {- <talaffa.z> -} [ ['p','r','o','n','o','u','n','c','e'], ['e','x','p','r','e','s','s'] ],
< laf.z >
`plural` HaFCAL,
FaCL |<< "aN" `noun` {- <laf.zaN> -} [ ['v','e','r','b','a','t','i','m'], ['l','i','t','e','r','a','l','l','y'] ],
FaCL |< Iy `adj` {- <laf.zIy> -} [ ['l','i','t','e','r','a','l'], ['v','e','r','b','a','l'] ],
< laf.zaT >
`plural` FaCaL |< At,
FaCIL `adj` {- <lafI.z> -} [ ['e','m','i','t','t','e','d'], ['p','r','o','n','o','u','n','c','e','d'] ],
TaFaCCuL `noun` {- <talaffu.z> -} [ ['p','r','o','n','u','n','c','i','a','t','i','o','n'], ['a','r','t','i','c','u','l','a','t','i','o','n'] ]
`plural` TaFaCCuL |< At,
MaFCUL `adj` {- <malfU.z> -} [ ['e','m','i','t','t','e','d'], ['p','r','o','n','o','u','n','c','e','d'] ] ]
cluster_62 = cluster
|> "l f `" <| [
FaCaL `verb` {- <lafa`> -} [ ['c','o','v','e','r'] ]
`imperf` FCaL,
FaCCaL `verb` {- <laffa`> -} [ ['c','o','v','e','r'], ['w','r','a','p'] ],
TaFaCCaL `verb` {- <talaffa`> -} [ unwords [ ['b','e'], ['w','r','a','p','p','e','d'], ['u','p'] ] ],
IFtaCaL `verb` {- <iltafa`> -} [ unwords [ ['b','e'], ['w','r','a','p','p','e','d'], ['u','p'] ] ],
FiCAL `noun` {- <lifA`> -} [ ['m','u','f','f','l','e','r'] ],
MiFCaL `noun` {- <milfa`> -} [ ['m','u','f','f','l','e','r'] ] ]
cluster_63 = cluster
|> "l f q" <| [
FaCCaL `verb` {- <laffaq> -} [ ['c','o','n','c','o','c','t'], ['f','a','l','s','i','f','y'] ],
TaFCIL `noun` {- <talfIq> -} [ ['c','o','n','c','o','c','t','i','o','n'], ['f','a','l','s','i','f','i','c','a','t','i','o','n'] ],
TaFCIL |< aT `noun` {- <talfIqaT> -} [ unwords [ ['c','o','n','c','o','c','t','e','d'], ['s','t','o','r','y'] ], ['f','a','b','r','i','c','a','t','i','o','n'] ]
`plural` TaFCIL |< At,
MuFaCCaL `adj` {- <mulaffaq> -} [ ['f','a','b','r','i','c','a','t','e','d'], ['f','a','l','s','i','f','i','e','d'] ] ]
cluster_64 = cluster
|> "l f l f" <| [
KaRDaS `verb` {- <laflaf> -} [ unwords [ ['w','r','a','p'], ['u','p'] ], ['e','n','v','e','l','o','p'] ],
< talaflaf >
KaRDaS |< aT `noun` {- <laflafaT> -} [ ['w','r','a','p','p','i','n','g'], ['e','n','v','e','l','o','p','i','n','g'] ] ]
cluster_65 = cluster
|> "l q b" <| [
FaCCaL `verb` {- <laqqab> -} [ ['c','a','l','l'], unwords [ ['a','d','d','r','e','s','s'], ['a','s'] ] ],
TaFaCCaL `verb` {- <talaqqab> -} [ unwords [ ['b','e'], ['c','a','l','l','e','d'] ], unwords [ ['b','e'], ['a','d','d','r','e','s','s','e','d'], ['a','s'] ] ],
FaCaL `noun` {- <laqab> -} [ ['t','i','t','l','e'], ['n','i','c','k','n','a','m','e'] ]
`plural` HaFCAL,
MuFaCCaL `adj` {- <mulaqqab> -} [ ['n','i','c','k','n','a','m','e','d'], ['c','a','l','l','e','d'] ] ]
cluster_66 = cluster
|> "l q .h" <| [
FaCaL `verb` {- <laqa.h> -} [ ['i','n','o','c','u','l','a','t','e'], ['p','o','l','l','i','n','a','t','e'], ['i','m','p','r','e','g','n','a','t','e'] ]
`imperf` FCaL
`masdar` FaCL,
FaCCaL `verb` {- <laqqa.h> -} [ ['i','n','o','c','u','l','a','t','e'], ['p','o','l','l','i','n','a','t','e'], ['i','m','p','r','e','g','n','a','t','e'] ],
TaFACaL `verb` {- <talAqa.h> -} [ unwords [ ['c','r','o','s','s'], "-", ['p','o','l','l','i','n','a','t','e'] ] ],
FaCL `noun` {- <laq.h> -} [ ['i','n','o','c','u','l','a','t','i','o','n'], ['p','o','l','l','i','n','a','t','i','o','n'], ['i','m','p','r','e','g','n','a','t','i','o','n'] ],
FaCAL `noun` {- <laqA.h> -} [ ['v','a','c','c','i','n','e'], ['p','o','l','l','e','n'], ['s','e','m','e','n'] ],
TaFCIL `noun` {- <talqI.h> -} [ ['i','n','o','c','u','l','a','t','i','o','n'], ['p','o','l','l','i','n','a','t','i','o','n'], ['i','m','p','r','e','g','n','a','t','i','o','n'] ]
`plural` TaFCIL |< At,
FawACiL `noun` {- <lawAqi.h> -} [ ['p','o','l','l','e','n'] ]
`plural` FawACiL
`limited` "-------P--",
MuFaCCaL `adj` {- <mulaqqa.h> -} [ ['v','a','c','c','i','n','a','t','e','d'], ['i','n','o','c','u','l','a','t','e','d'] ] ]
cluster_67 = cluster
|> "l q s" <| [
FaCiL `adj` {- <laqis> -} [ ['a','n','n','o','y','e','d'] ] ]
cluster_68 = cluster
|> "l q .t" <| [
FaCaL `verb` {- <laqa.t> -} [ ['g','a','t','h','e','r'], ['c','o','l','l','e','c','t'] ]
`imperf` FCuL,
FaCCaL `verb` {- <laqqa.t> -} [ ['g','a','t','h','e','r'], ['c','o','l','l','e','c','t'] ],
TaFaCCaL `verb` {- <talaqqa.t> -} [ ['g','a','t','h','e','r'], ['c','o','l','l','e','c','t'] ],
IFtaCaL `verb` {- <iltaqa.t> -} [ ['o','b','t','a','i','n'], ['r','e','c','e','i','v','e'], ['c','o','l','l','e','c','t'] ],
FaCaL `noun` {- <laqa.t> -} [ ['g','l','e','a','n','i','n','g','s'] ],
FaCL |< aT `noun` {- <laq.taT> -} [ ['p','i','c','t','u','r','e'], ['s','n','a','p','s','h','o','t'] ]
`plural` FaCaL |< At,
FuCL |< aT `noun` {- <luq.taT> -} [ unwords [ ['l','u','c','k','y'], ['f','i','n','d'] ], ['b','a','r','g','a','i','n'] ]
`plural` FuCaL,
FuCAL `noun` {- <luqA.t> -} [ ['g','l','e','a','n','e','d'], ['l','e','f','t','o','v','e','r'] ],
FaCIL `adj` {- <laqI.t> -} [ unwords [ ['p','i','c','k','e','d'], ['u','p'] ], ['f','o','u','n','d'], ['f','o','u','n','d','l','i','n','g'] ]
`plural` FuCaLA',
MiFCaL `noun` {- <milqa.t> -} [ ['t','w','e','e','z','e','r','s'], ['p','l','i','e','r','s'], ['p','i','n','c','e','r','s'] ]
`plural` MaFACiL,
IFtiCAL `noun` {- <iltiqA.t> -} [ ['r','e','c','e','p','t','i','o','n'], ['o','b','t','a','i','n','i','n','g'] ]
`plural` IFtiCAL |< At,
FACiL `noun` {- <lAqi.t> -} [ ['r','e','c','e','i','v','e','r'], ['p','i','c','k','u','p'], ['c','o','l','l','e','c','t','o','r'] ]
`plural` FACiL |< At,
FACiL |< aT `noun` {- <lAqi.taT> -} [ ['d','e','t','e','c','t','o','r'], unwords [ ['s','e','a','r','c','h'], ['d','e','v','i','c','e'] ] ]
`plural` FACiL |< At,
MuFtaCiL `noun` {- <multaqi.t> -} [ ['r','e','c','e','i','v','e','r'], ['d','e','t','e','c','t','o','r'] ] ]
cluster_69 = cluster
|> "l q `" <| [
FaCaL `verb` {- <laqa`> -} [ ['d','i','s','c','a','r','d'] ]
`imperf` FCaL,
< laq ` >
cluster_70 = cluster
|> "l q f" <| [
< >
`imperf` FCaL,
TaFaCCaL `verb` {- <talaqqaf> -} [ ['s','e','i','z','e'], ['c','a','t','c','h'] ],
IFtaCaL `verb` {- <iltaqaf> -} [ ['s','e','i','z','e'], ['c','a','t','c','h'] ],
FaCL `noun` {- <laqf> -} [ ['s','e','i','z','i','n','g'], ['c','a','t','c','h','i','n','g'] ],
FaCaLAn `noun` {- <laqafAn> -} [ ['s','e','i','z','i','n','g'], ['c','a','t','c','h','i','n','g'] ] ]
cluster_71 = cluster
|> "l q l q" <| [
KaRDaS `verb` {- <laqlaq> -} [ ['b','a','b','b','l','e'], ['c','h','a','t','t','e','r'] ],
KaRDaS |< aT `noun` {- <laqlaqaT> -} [ ['c','h','a','t','t','e','r','i','n','g'], ['g','o','s','s','i','p'] ],
KaRDaS `noun` {- <laqlaq> -} [ ['s','t','o','r','k'] ]
`plural` KaRADiS,
KaRDAS `noun` {- <laqlAq> -} [ ['s','t','o','r','k'] ]
`plural` KaRADiS ]
cluster_72 = cluster
|> "l q m" <| [
< laqam >
`imperf` FCuL,
FaCiL `verb` {- <laqim> -} [ ['e','a','t'], ['s','w','a','l','l','o','w'] ]
`imperf` FCaL,
FaCCaL `verb` {- <laqqam> -} [ ['f','e','e','d'], ['s','u','p','p','l','y'], ['l','o','a','d'], ['u','p','l','o','a','d'] ],
HaFCaL `verb` {- <'alqam> -} [ unwords [ ['m','a','k','e'], ['s','w','a','l','l','o','w'] ], ['f','e','e','d'] ],
IFtaCaL `verb` {- <iltaqam> -} [ ['s','w','a','l','l','o','w'], ['d','e','v','o','u','r'] ],
FuCL |< aT `noun` {- <luqmaT> -} [ ['m','o','r','s','e','l'], unwords [ ['d','a','i','l','y'], ['b','r','e','a','d'] ], ['b','i','t','e','s'] ]
`plural` FuCaL,
FuCayL |< aT `noun` {- <luqaymaT> -} [ ['s','n','a','c','k'], unwords [ ['s','m','a','l','l'], ['b','i','t','e'] ] ],
FaCIL `noun` {- <laqIm> -} [ ['s','u','p','p','l','y'], ['l','o','a','d'] ],
MuFaCCiL `noun` {- <mulaqqim> -} [ unwords [ ['s','e','c','o','n','d'], ['g','u','n','n','e','r'] ], unwords [ ['m','o','r','t','a','r'], ['m','a','n'] ] ]
`plural` MuFaCCiL |< Un
`femini` MuFaCCiL |< aT,
< laqmIy >
FACiL |< Iy `adj` {- <lAqimIy> -} [ unwords [ ['p','a','l','m'], ['w','i','n','e'] ] ],
FuCLAn `noun` {- <luqmAn> -} [ ['L','u','q','m','a','n'] ],
< talqIm >
`plural` TaFCIL |< At ]
cluster_73 = cluster
|> "l q n" <| [
< >
`imperf` FCaL,
FaCCaL `verb` {- <laqqan> -} [ ['t','e','a','c','h'], ['i','n','s','t','r','u','c','t'], ['s','u','g','g','e','s','t'] ],
TaFaCCaL `verb` {- <talaqqan> -} [ ['u','n','d','e','r','s','t','a','n','d'], ['i','n','f','e','r'] ],
FaCAL |< aT `noun` {- <laqAnaT> -} [ unwords [ ['q','u','i','c','k'], ['u','n','d','e','r','s','t','a','n','d','i','n','g'] ], unwords [ ['q','u','i','c','k'], ['g','r','a','s','p'] ] ],
FaCAL |< Iy |< aT `noun` {- <laqAnIyaT> -} [ unwords [ ['q','u','i','c','k'], ['u','n','d','e','r','s','t','a','n','d','i','n','g'] ], unwords [ ['q','u','i','c','k'], ['g','r','a','s','p'] ] ],
TaFCIL `noun` {- <talqIn> -} [ ['i','n','s','t','r','u','c','t','i','o','n'], ['d','i','c','t','a','t','i','o','n'], ['s','u','g','g','e','s','t','i','n','g'] ]
`plural` TaFCIL |< At,
MuFaCCiL `noun` {- <mulaqqin> -} [ ['p','r','o','m','p','t','e','r'], ['i','n','s','p','i','r','e','r'] ]
`plural` MuFaCCiL |< Un
`femini` MuFaCCiL |< aT ]
cluster_74 = cluster
|> "l k z" <| [
FaCaL `verb` {- <lakaz> -} [ ['s','t','r','i','k','e'], ['k','i','c','k'] ]
`imperf` FCuL,
< >
FaCiL `adj` {- <lakiz> -} [ ['m','i','s','e','r','l','y'], ['s','t','i','n','g','y'] ],
FiCAL `noun` {- <likAz> -} [ ['p','i','n'], ['n','a','i','l'], ['p','e','g'] ] ]
cluster_75 = cluster
|> "l k `" <| [
FaCIL `adj` {- <lakI`> -} [ ['w','i','c','k','e','d'], ['d','e','p','r','a','v','e','d'] ]
`plural` FuCaLA',
FaCAL |< aT `noun` {- <lakA`aT> -} [ ['w','i','c','k','e','d','n','e','s','s'], ['d','e','p','r','a','v','i','t','y'] ] ]
cluster_76 = cluster
|> "l k m" <| [
< >
`imperf` FCuL,
< >
< >
FaCL |< aT `noun` {- <lakmaT> -} [ ['p','u','n','c','h'] ]
`plural` FaCaL |< At,
MiFCaL |< aT `noun` {- <milkamaT> -} [ unwords [ ['b','o','x','i','n','g'], ['g','l','o','v','e'] ] ],
MuFACaL |< aT `noun` {- <mulAkamaT> -} [ ['b','o','x','i','n','g'] ],
MuFACiL `noun` {- <mulAkim> -} [ ['b','o','x','e','r'], ['p','u','g','i','l','i','s','t'] ]
`plural` MuFACiL |< Un
`femini` MuFACiL |< aT ]
cluster_77 = cluster
|> "l k n" <| [
FaCiL `verb` {- <lakin> -} [ ['s','t','a','m','m','e','r'] ]
`imperf` FCaL,
FaCL |< aT `noun` {- <laknaT> -} [ ['a','c','c','e','n','t'] ],
FuCL |< aT `noun` {- <luknaT> -} [ unwords [ ['i','n','c','o','r','r','e','c','t'], ['p','r','o','n','u','n','c','i','a','t','i','o','n'] ] ],
FaCAL |< aT `noun` {- <lakAnaT> -} [ ['s','t','a','m','m','e','r'], unwords [ ['s','p','e','e','c','h'], ['d','e','f','e','c','t'] ] ],
FuCUL |< aT `noun` {- <lukUnaT> -} [ ['s','t','a','m','m','e','r'], unwords [ ['s','p','e','e','c','h'], ['d','e','f','e','c','t'] ] ],
< ' >
`femini` FaCLA' ]
|> "l k n" <| [
FaCaL `noun` {- <lakan> -} [ ['b','a','s','i','n','s'] ]
`plural` HaFCAL ]
cluster_78 = cluster
|> ['l','U','k','A','n','d'] <| [
_____ |< aT `noun` {- <lUkAndaT> -} [ ['h','o','t','e','l'] ] ]
cluster_79 = cluster
|> ['l','A','m'] <| [
_____ `noun` {- <lAm> -} [ unwords [ ['l','a','m'], "(", ['A','r','a','b','i','c'], ['l','e','t','t','e','r'], ")" ] ]
`plural` _____ |< At ]
cluster_80 = cluster
|> ['l','a','m'] <| [
_____ `part` {- <lam> -} [ ['n','o','t'] ],
_____ |<< "mA" `part` {- <lammA> -} [ ['n','o','t'] ],
_____ |<< "mA" `conj` {- <lammA> -} [ ['w','h','e','n'], ['a','f','t','e','r'] ],
"mA" >>| _____ `conj` {- <mAlam> -} [ unwords [ ['a','s'], ['l','o','n','g'], ['a','s'] ] ] ]
cluster_81 = cluster
|> "l m ^g" <| [
TaFaCCaL `verb` {- <talamma^g> -} [ unwords [ ['h','a','v','e'], "a", ['s','n','a','c','k'] ] ],
FuCL |< aT `noun` {- <lum^gaT> -} [ ['a','p','p','e','t','i','z','e','r'], ['s','n','a','c','k'] ] ]
cluster_82 = cluster
|> "l m .h" <| [
FaCaL `verb` {- <lama.h> -} [ ['g','l','a','n','c','e'], ['n','o','t','i','c','e'] ]
`imperf` FCaL
`masdar` FaCL,
FaCCaL `verb` {- <lamma.h> -} [ ['a','l','l','u','d','e'], ['r','e','f','e','r'] ],
FACaL `verb` {- <lAma.h> -} [ unwords [ ['g','l','a','n','c','e'], ['a','t'] ] ],
HaFCaL `verb` {- <'alma.h> -} [ ['m','e','n','t','i','o','n'], ['r','e','f','e','r'] ],
TaFACaL `verb` {- <talAma.h> -} [ ['a','p','p','e','a','r'] ],
FaCL `noun` {- <lam.h> -} [ ['g','l','a','n','c','e'], ['i','n','s','t','a','n','t'] ],
FaCL |< aT `noun` {- <lam.haT> -} [ ['g','l','a','n','c','e'], ['g','l','i','m','p','s','e'] ]
`plural` FaCaL |< At,
FaCCAL `adj` {- <lammA.h> -} [ ['s','h','i','n','i','n','g'] ],
MaFACiL `noun` {- <malAmi.h> -} [ ['f','e','a','t','u','r','e','s'], ['c','h','a','r','a','c','t','e','r','i','s','t','i','c','s'] ]
`plural` MaFACiL
`limited` "-------P--",
TaFCIL `noun` {- <talmI.h> -} [ ['a','l','l','u','s','i','o','n'], ['s','u','g','g','e','s','t','i','o','n'], unwords [ ['e','a','r','l','y'], ['s','y','m','p','t','o','m','s'] ] ]
`plural` TaFCIL |< At
`plural` TaFACIL,
MuFaCCiL `adj` {- <mulammi.h> -} [ ['a','l','l','u','d','i','n','g'], ['r','e','f','e','r','r','i','n','g'] ] ]
cluster_83 = cluster
|> "l m z" <| [
< lamaz >
`imperf` FCiL
`imperf` FCuL,
FaCL `noun` {- <lamz> -} [ ['c','r','i','t','i','c','i','z','i','n','g'], ['s','l','a','n','d','e','r','i','n','g'] ],
FuCaL |< aT `noun` {- <lumazaT> -} [ unwords [ ['f','a','u','l','t'], "-", ['f','i','n','d','e','r'] ], ['c','a','r','p','e','r'] ],
FaCCAL `adj` {- <lammAz> -} [ unwords [ ['f','a','u','l','t'], "-", ['f','i','n','d','e','r'] ], ['c','a','r','p','e','r'] ] ]
cluster_84 = cluster
|> "l m s" <| [
FaCaL `verb` {- <lamas> -} [ ['t','o','u','c','h'], ['p','e','r','c','e','i','v','e'] ]
`imperf` FCuL
`imperf` FCiL
`masdar` FaCL,
FACaL `verb` {- <lAmas> -} [ ['t','o','u','c','h'], ['f','e','e','l'] ],
TaFaCCaL `verb` {- <talammas> -} [ unwords [ ['f','e','e','l'], ['o','u','t'] ], ['g','r','o','p','e'] ],
TaFACaL `verb` {- <talAmas> -} [ unwords [ ['b','e'], ['i','n'], ['m','u','t','u','a','l'], ['c','o','n','t','a','c','t'] ] ],
IFtaCaL `verb` {- <iltamas> -} [ ['s','o','l','i','c','i','t'], unwords [ ['s','e','a','r','c','h'], ['f','o','r'] ] ],
FaCL `noun` {- <lams> -} [ ['f','e','e','l','i','n','g'], ['t','o','u','c','h'] ],
< lamsIy >
FaCL |< aT `noun` {- <lamsaT> -} [ ['t','o','u','c','h'], ['t','i','n','g','e'], ['t','r','a','c','e'] ]
`plural` FaCaL |< At,
FaCL |< Iy |< aT `noun` {- <lamsIyaT> -} [ unwords [ ['u','n','r','i','p','e'], ['d','a','t','e'] ] ],
FaCIL `adj` {- <lamIs> -} [ unwords [ ['s','o','f','t'], ['t','o'], ['t','h','e'], ['t','o','u','c','h'] ] ],
MaFCaL `noun` {- <malmas> -} [ ['t','o','u','c','h'] ],
MaFCaL `noun` {- <malmas> -} [ unwords [ ['p','o','i','n','t'], ['o','f'], ['c','o','n','t','a','c','t'] ] ]
`plural` MaFACiL,
MaFCaL |< Iy `adj` {- <malmasIy> -} [ ['t','a','c','t','u','a','l'], ['t','a','c','t','i','l','e'] ],
< mulAmasaT >
TaFaCCuL `noun` {- <talammus> -} [ ['s','e','a','r','c','h'], ['q','u','e','s','t'] ]
`plural` TaFaCCuL |< At,
TaFACuL `noun` {- <talAmus> -} [ unwords [ ['m','u','t','u','a','l'], ['c','o','n','t','a','c','t'] ] ]
`plural` TaFACuL |< At,
IFtiCAL `noun` {- <iltimAs> -} [ ['r','e','q','u','e','s','t'], ['s','o','l','i','c','i','t','a','t','i','o','n'], ['p','e','t','i','t','i','o','n'] ]
`plural` IFtiCAL |< At,
MaFCUL `adj` {- <malmUs> -} [ ['t','a','n','g','i','b','l','e'], ['n','o','t','i','c','e','a','b','l','e'] ],
MuFtaCaL `noun` {- <multamas> -} [ ['r','e','q','u','e','s','t'], ['p','e','t','i','t','i','o','n'], ['a','p','p','l','i','c','a','t','i','o','n'] ]
`plural` MuFtaCaL |< At ]
cluster_85 = cluster
|> "l m .s" <| [
FaCaL `verb` {- <lama.s> -} [ unwords [ ['m','a','k','e'], ['f','a','c','e','s'], ['a','t'] ], unwords [ ['r','a','i','l'], ['a','t'] ] ]
`imperf` FCuL,
FaCL `noun` {- <lam.s> -} [ unwords [ ['m','a','k','i','n','g'], ['f','a','c','e','s'], ['a','t'] ], unwords [ ['r','a','i','l','i','n','g'], ['a','t'] ] ] ]
cluster_86 = cluster
|> "l m .z" <| [
FaCaL `verb` {- <lama.z> -} [ unwords [ ['s','m','a','c','k'], ['t','h','e'], ['l','i','p','s'] ] ]
`imperf` FCuL,
TaFaCCaL `verb` {- <talamma.z> -} [ unwords [ ['s','m','a','c','k'], ['t','h','e'], ['l','i','p','s'] ], ['s','l','a','n','d','e','r'] ],
FaCL `noun` {- <lam.z> -} [ unwords [ ['s','m','a','c','k','i','n','g'], ['t','h','e'], ['l','i','p','s'] ] ] ]
cluster_87 = cluster
|> "l m `" <| [
FaCaL `verb` {- <lama`> -} [ ['s','h','i','n','e'], ['g','l','i','t','t','e','r'] ]
`imperf` FCaL
`masdar` FaCL
`masdar` FaCaLAn,
FaCCaL `verb` {- <lamma`> -} [ ['p','o','l','i','s','h'], unwords [ ['m','a','k','e'], ['s','h','i','n','e'] ] ],
HaFCaL `verb` {- <'alma`> -} [ ['w','a','v','e'], unwords [ ['p','o','i','n','t'], ['o','u','t'] ] ],
IFtaCaL `verb` {- <iltama`> -} [ ['f','l','a','s','h'], ['g','l','i','t','t','e','r'] ],
FaCL `noun` {- <lam`> -} [ ['s','h','i','n','e'], ['g','l','i','t','t','e','r'] ],
FaCaLAn `noun` {- <lama`An> -} [ ['s','h','i','n','e'], ['g','l','i','t','t','e','r'] ],
FuCL |< aT `noun` {- <lum`aT> -} [ ['s','h','i','n','e'], ['g','l','i','t','t','e','r'] ]
`plural` FuCaL,
FiCAL `noun` {- <limA`> -} [ ['s','h','i','n','e'], ['g','l','i','t','t','e','r'] ],
FaCCAL `adj` {- <lammA`> -} [ ['s','h','i','n','i','n','g'], ['g','l','o','s','s','y'] ],
HaFCaL `adj` {- <'alma`> -} [ ['b','r','i','g','h','t'], ['s','h','r','e','w','d'] ],
HaFCaL |< Iy `adj` {- <'alma`Iy> -} [ ['b','r','i','g','h','t'], ['s','h','r','e','w','d'] ],
HaFCaL |< Iy |< aT `noun` {- <'alma`IyaT> -} [ ['c','l','e','v','e','r','n','e','s','s'], ['s','h','r','e','w','d','n','e','s','s'] ],
TaFCIL `noun` {- <talmI`> -} [ ['p','o','l','i','s','h','i','n','g'] ]
`plural` TaFCIL |< At,
HiFCAL `noun` {- <'ilmA`> -} [ ['a','l','l','u','s','i','o','n'] ]
`plural` HiFCAL |< At,
FACiL `adj` {- <lAmi`> -} [ ['s','p','l','e','n','d','i','d'], ['i','l','l','u','s','t','r','i','o','u','s'] ]
`plural` FawACiL,
FACiL |< aT `noun` {- <lAmi`aT> -} [ ['g','l','o','s','s'], ['s','h','i','n','e'] ],
MutaFaCCiL `adj` {- <mutalammi`> -} [ ['s','h','i','n','i','n','g'], ['r','a','d','i','a','n','t'] ] ]
cluster_88 = cluster
|> "l m l m" <| [
KaRDaS `verb` {- <lamlam> -} [ unwords [ ['g','a','t','h','e','r'], ['u','p'] ] ],
MuKaRDiS |< aT `noun` {- <mulamlimaT> -} [ unwords [ ['e','l','e','p','h','a','n','t'], ['t','r','u','n','k'] ], ['p','r','o','b','o','s','c','i','s'] ] ]
cluster_89 = cluster
|> ['l','I','m','A','n'] <| [
_____ `noun` {- <lImAn> -} [ ['p','o','r','t'], ['h','a','r','b','o','r'] ]
`plural` _____ |< At,
_____ `noun` {- <lImAn> -} [ ['p','r','i','s','o','n'] ]
`plural` _____ |< At ]
cluster_90 = cluster
|> ['l','U','m','A','n'] <| [
_____ `noun` {- <lUmAn> -} [ ['p','e','n','i','t','e','n','t','i','a','r','y'], unwords [ ['p','e','n','a','l'], ['s','e','r','v','i','t','u','d','e'] ], ['p','r','i','s','o','n'] ],
_____ |<< "^g" |< Iy `noun` {- <lUmAn^gIy> -} [ ['c','o','n','v','i','c','t'], ['i','n','m','a','t','e'] ] ]
cluster_91 = cluster
|> ['l','I','m','U','n','A','d'] <| [
_____ `noun` {- <lImUnAd> -} [ ['l','e','m','o','n','a','d','e'] ] ]
cluster_92 = cluster
|> ['l','a','m','b'] <| [
_____ |< aT `noun` {- <lambaT> -} [ ['l','a','m','p'] ]
`plural` _____ |< At ]
cluster_93 = cluster
|> ['l','a','n'] <| [
_____ `part` {- <lan> -} [ ['n','o','t'] ] ]
cluster_94 = cluster
|> ['l','a','n','d','a','n'] <| [
_____ `xtra` {- <landan> -} [ ['L','o','n','d','o','n'] ],
_____ |< Iy `adj` {- <landanIy> -} [ ['L','o','n','d','o','n'] ],
_____ |< Iy `noun` {- <landanIy> -} [ ['L','o','n','d','o','n','e','r'] ]
`plural` _____ |< Iy |< Un
`femini` _____ |< Iy |< aT ]
cluster_95 = cluster
|> ['l','A','n','^','s'] <| [
_____ `noun` {- <lAn^s> -} [ ['m','o','t','o','r','b','o','a','t'], ['l','a','u','n','c','h'] ]
`plural` _____ |< At ]
|> ['l','a','n','^','s'] <| [
_____ `noun` {- <lan^s> -} [ ['m','o','t','o','r','b','o','a','t'], ['l','a','u','n','c','h'] ]
`plural` _____ |< At ]
cluster_96 = cluster
|> "l h b" <| [
FaCiL `verb` {- <lahib> -} [ ['b','u','r','n'], ['f','l','a','m','e'] ]
`imperf` FCaL
`masdar` FaCaL
`masdar` FaCIL,
FaCCaL `verb` {- <lahhab> -} [ ['k','i','n','d','l','e'], ['p','r','o','v','o','k','e'], ['i','n','f','l','a','m','e'] ],
HaFCaL `verb` {- <'alhab> -} [ ['k','i','n','d','l','e'], ['p','r','o','v','o','k','e'], ['i','n','f','l','a','m','e'] ],
< >
IFtaCaL `verb` {- <iltahab> -} [ unwords [ ['f','l','a','r','e'], ['u','p'] ], unwords [ ['b','e'], ['i','n','f','l','a','m','e','d'] ] ],
FaCaL `noun` {- <lahab> -} [ ['f','l','a','m','e'] ],
FaCIL `noun` {- <lahIb> -} [ ['f','l','a','m','e'] ],
FuCAL `noun` {- <luhAb> -} [ ['f','l','a','m','e'] ],
FaCLAn `adj` {- <lahbAn> -} [ ['t','h','i','r','s','t','y'] ]
`plural` FaCLY
`plural` FiCAL,
HiFCAL `noun` {- <'ilhAb> -} [ ['k','i','n','d','l','i','n','g'], ['p','r','o','v','o','k','i','n','g'], ['i','n','f','l','a','m','i','n','g'] ]
`plural` HiFCAL |< At,
IFtiCAL `noun` {- <iltihAb> -} [ ['i','n','f','l','a','m','m','a','t','i','o','n'] ]
`plural` IFtiCAL |< At,
IFtiCAL |< Iy `adj` {- <iltihAbIy> -} [ ['i','n','f','l','a','m','m','a','t','o','r','y'], ['i','n','f','l','a','m','m','a','b','l','e'] ],
MuFtaCiL `adj` {- <multahib> -} [ ['b','u','r','n','i','n','g'], ['a','b','l','a','z','e'], ['i','n','f','l','a','m','e','d'] ] ]
cluster_97 = cluster
|> "l h _t" <| [
FaCaL `verb` {- <laha_t> -} [ ['p','a','n','t'], ['g','a','s','p'] ]
`imperf` FCaL,
FaCL `noun` {- <lah_t> -} [ ['p','a','n','t','i','n','g'], ['g','a','s','p','i','n','g'] ],
FuCAL `noun` {- <luhA_t> -} [ ['p','a','n','t','i','n','g'], ['g','a','s','p','i','n','g'] ],
FaCLAn `adj` {- <lah_tAn> -} [ ['p','a','n','t','i','n','g'], unwords [ ['o','u','t'], ['o','f'], ['b','r','e','a','t','h'] ] ]
`plural` FaCLY,
FACiL `adj` {- <lAhi_t> -} [ ['p','a','n','t','i','n','g'], unwords [ ['o','u','t'], ['o','f'], ['b','r','e','a','t','h'] ] ] ]
cluster_98 = cluster
|> "l h ^g" <| [
FaCiL `verb` {- <lahi^g> -} [ unwords [ ['b','e'], ['d','e','d','i','c','a','t','e','d'] ], unwords [ ['b','e'], ['f','o','n','d'], ['o','f'] ] ]
`imperf` FCaL,
HaFCaL `verb` {- <'alha^g> -} [ ['p','r','a','i','s','e'] ],
IFCALL `verb` {- <ilhA^g^g> -} [ ['c','u','r','d','l','e'], ['c','o','a','g','u','l','a','t','e'] ],
FaCL |< aT `noun` {- <lah^gaT> -} [ ['t','o','n','e'], ['d','i','a','l','e','c','t'] ]
`plural` FaCaL |< At,
FuCL |< aT `noun` {- <luh^gaT> -} [ ['a','p','p','e','t','i','z','e','r'] ] ]
cluster_99 = cluster
|> "l h d" <| [
< lahad >
`imperf` FCaL,
FaCL `noun` {- <lahd> -} [ ['o','v','e','r','b','u','r','d','e','n','i','n','g'] ] ]
cluster_100 = cluster
|> "l h _d m" <| [
KaRDaS `adj` {- <lah_dam> -} [ ['p','o','i','n','t','e','d'], ['s','h','a','r','p'] ] ]
section = [ cluster_1,
cluster_2,
cluster_3,
cluster_4,
cluster_5,
cluster_6,
cluster_7,
cluster_8,
cluster_9,
cluster_10,
cluster_11,
cluster_12,
cluster_13,
cluster_14,
cluster_15,
cluster_16,
cluster_17,
cluster_18,
cluster_19,
cluster_20,
cluster_21,
cluster_22,
cluster_23,
cluster_24,
cluster_25,
cluster_26,
cluster_27,
cluster_28,
cluster_29,
cluster_30,
cluster_31,
cluster_32,
cluster_33,
cluster_34,
cluster_35,
cluster_36,
cluster_37,
cluster_38,
cluster_39,
cluster_40,
cluster_41,
cluster_42,
cluster_43,
cluster_44,
cluster_45,
cluster_46,
cluster_47,
cluster_48,
cluster_49,
cluster_50,
cluster_51,
cluster_52,
cluster_53,
cluster_54,
cluster_55,
cluster_56,
cluster_57,
cluster_58,
cluster_59,
cluster_60,
cluster_61,
cluster_62,
cluster_63,
cluster_64,
cluster_65,
cluster_66,
cluster_67,
cluster_68,
cluster_69,
cluster_70,
cluster_71,
cluster_72,
cluster_73,
cluster_74,
cluster_75,
cluster_76,
cluster_77,
cluster_78,
cluster_79,
cluster_80,
cluster_81,
cluster_82,
cluster_83,
cluster_84,
cluster_85,
cluster_86,
cluster_87,
cluster_88,
cluster_89,
cluster_90,
cluster_91,
cluster_92,
cluster_93,
cluster_94,
cluster_95,
cluster_96,
cluster_97,
cluster_98,
cluster_99,
cluster_100 ]
| null | https://raw.githubusercontent.com/otakar-smrz/elixir-fm/fae5bab6dd53c15d25c1e147e7787b2c254aabf0/Haskell/ElixirFM/Elixir/Data/Sunny/Regular/O.hs | haskell | <la^gla^g>
<tala^gla^g>
<la^glA^g>
<mula^gla^g>
<la^gam>
<la^g^gam>
<'al^gam>
<ilta^gam>
<li^gAm>
<mal^gUm>
<mul^gam>
<tal^gIm>
<la^gin>
<la^gnaT>
<lu^gayn>
<lA.hib>
<lA.hib>
<la.ha^g>
<la.had>
<'al.had>
<ilta.had>
<la.hd>
<la.had>
<la.hdIy>
<la.hUd>
<la.h.hAd>
<'il.hAd>
<'il.hAdIy>
<mul.hid>
<la.has>
<la.his>
<la.hs>
<la.hsaT>
<mal.has>
<mal.hUs>
<la.ha.z>
<lA.ha.z>
<la.h.z>
<la.h.zaT>
<la.h.zaTa'i_diN>
<mal.ha.z>
<mulA.ha.zaT>
<lA.hi.zaT>
<mal.hU.z>
<mal.hU.zaT>
<mulA.hi.z>
<mulA.ha.z>
<la.haf>
<'al.haf>
<ilta.haf>
<li.hf>
<li.hAf>
<mil.haf>
<'il.hAf>
<multa.hif>
<la.hiq>
<lA.haq>
<'al.haq>
<talA.haq>
<ilta.haq>
<istal.haq>
<la.haq>
<la.haqIy>
<li.hAq>
<mulA.haqaT>
<ilti.hAq>
<istil.hAq>
<lA.hiq>
<lA.hiqaT>
<mul.haq>
<mul.haq>
<mul.haq>
<mul.haqIyaT>
<mulA.hiq>
<mutalA.hiq>
<la.ham>
<la.him>
<la.h.ham>
<talA.ham>
<ilta.ham>
<la.hm>
<la.hm>
<lu.hmaT>
<la.hmIyaT>
<la.him>
<li.hAm>
<la.h.hAm>
<la.h.hAm>
<la.hAmaT>
<mal.hamaT>
<mal.hamIy>
<talA.hum>
<ilti.hAm>
<ilti.hAm>
<multa.ham>
<multa.hamaT>
<la.han>
<la.h.han>
<'al.han>
<la.hn>
<la.hin>
<tal.hIn>
<tal.hInIy>
<mal.hUn>
<mula.h.hin>
<la_hba.t>
<la_hba.taT>
<mula_hba.t>
<la_h_ha.s>
<tala_h_ha.s>
<tal_hI.s>
<mula_h_ha.s>
<mula_h_ha.s>
<la_hla_h>
<tala_hla_h>
<mula_hla_h>
<la_hamaT>
<mal_hUm>
<la_han>
<'al_han>
<'al_han>
<lada.g>
<lad.gaT>
<ladI.g>
<lAdi.g>
<maldU.g>
<ladun>
<ladin>
<ladn>
<ladun>
<lAdin>
<ladAnaT>
<ladUnaT>
<ladA'in>
<ladunIy>
<la_da`>
<tala_d_da`>
<la_d`>
<la_d`>
<la_d_dA`>
<lA_di`>
<lA_di`aT>
<law_da`>
<law_da`Iy>
<law_da`IyaT>
<lA_diqIyaT>
<lUr>
<lIraT>
<lUrI>
<lazab>
<lazib>
<lazib>
<lazbaT>
<lAzib>
<luzU^gaT>
<laziq>
<lazzaq>
<'alzaq>
<iltazaq>
<lizq>
<laziq>
<lazqaT>
<lizAq>
<lAzam>
<'alzam>
<talAzam>
<iltazam>
<istalzam>
<lazmaT>
<luzUm>
<lizAm>
<'alzam>
<malzamaT>
<milzamaT>
<talzIm>
<'ilzAm>
<'ilzAmIy>
<'ilzAmIyaT>
<iltizAm>
<iltizAmIy>
<lAzim>
<lAzimaT>
<malzUm>
<malzUmIyaT>
<mulAzim>
<mulzim>
<mulzam>
<mutalAzimaT>
<multazam>
<mustalzam>
<lUzAn>
<lasa`>
<las`>
<las`aT>
<lasI`>
<lAsi`>
<malsU`>
<lasin>
<lassan>
<talAsan>
<lasin>
<'alsan>
<lisAn>
<lisAn>
<lisAn>
<lisAnIy>
<lisAnIyAt>
<talAsun>
<malsUn>
<lIsAns>
<lastik>
<lastIk>
<li^sbUnaT>
<la.siq>
<la.s.saq>
<lA.saq>
<'al.saq>
<talA.saq>
<ilta.saq>
<la.sqIy>
<li.sq>
<la.siq>
<la.sIq>
<la.sUq>
<mulA.saqaT>
<'il.sAq>
<talA.suq>
<ilti.sAq>
<lA.siq>
<lA.siqaT>
<mulA.siq>
<mulA.siq>
<mul.saq>
<mul.saq>
<mutalA.siq>
<multa.siq>
<mal.dUm>
<la.ta_h>
<la.t.ta_h>
<tala.t.ta_h>
<la.t_h>
<la.t_haT>
<lu.ta_haT>
<li.t.tI_h>
<la.ts>
<mil.tAs>
<la.ta^s>
<la.t^s>
<la.ta`>
<la.t`>
<la.t`aT>
<la.taf>
<la.tuf>
<la.t.taf>
<lA.taf>
<tala.t.taf>
<talA.taf>
<istal.taf>
<lu.tf>
<lu.tfaN>
<lu.tfIy>
<la.tAfaT>
<la.tIf>
<la.tIf>
<la.tIfaT>
<la.tIfaT>
<'al.taf>
<mulA.tafaT>
<mulA.tafAt>
<tala.t.tuf>
<mula.t.tif>
<mula.t.taf>
<la.tam>
<talA.tam>
<ilta.tam>
<la.tmaT>
<la.tIm>
<mal.tam>
<mutalA.tim>
<multa.tam>
<la`ib>
<lA`ab>
<talA`ab>
<la`b>
<la`baT>
<lu`baT>
<la``Ab>
<li``Ib>
<lu`Ab>
<lu`AbIy>
<lu`aybaT>
<la`Ub>
<'ul`UbaT>
<mal`ab>
<mal`abaT>
<talA`ub>
<lA`ib>
<mal`Ub>
<mulA`ib>
<tala`_tam>
<la`_tamaT>
<tala`_tum>
<mutala`_tim>
<la`a^g>
<lA`a^g>
<la`^gaT>
<'al`as>
<la`iq>
<lu`qaT>
<la`Uq>
<mil`aqaT>
<la`l>
<la`la`>
<tala`la`>
<la`la`>
<la`an>
<lA`an>
<talA`an>
<la`n>
<la`naT>
<lu`naT>
<li`An>
<la`In>
<mal`Un>
<mutalA`in>
<lu.gUb>
<la.gUb>
<lu.gd>
<lu.gdUd>
<lu.gud>
<lU.gArItm>
<la.gaz>
<lA.gaz>
<'al.gaz>
<lu.gz>
<mul.gaz>
<la.ga.t>
<la.g.ga.t>
<'al.ga.t>
<la.g.t>
<la.gam>
<la.g.gam>
<la.gm>
<lu.gm>
<la.gam>
<'il.gAm>
<mal.gUm>
<mula.g.gam>
<'al.gam>
<'il.gAm>
<lu.gAm>
<la.gma.t>
<la.gma.taT>
<'alfat>
<talaffat>
<laft>
<lift>
<laftaT>
<lafUt>
<lafAt>
<'alfat>
<'ilfAt>
<iltifAt>
<iltifAtaT>
<istilfAt>
<lAfitaT>
<mulfit>
<multafit>
<lifI_tAn>
<lifI_tAnIy>
<lafa.h>
<laf.h>
<lafa.hAn>
<laf.haT>
<lafU.h>
<lAfi.h>
<luffA.h>
<talfI.haT>
<lafa.z>
<talaffa.z>
<laf.zaN>
<laf.zIy>
<lafI.z>
<talaffu.z>
<malfU.z>
<lafa`>
<laffa`>
<talaffa`>
<iltafa`>
<lifA`>
<milfa`>
<laffaq>
<talfIq>
<talfIqaT>
<mulaffaq>
<laflaf>
<laflafaT>
<laqqab>
<talaqqab>
<laqab>
<mulaqqab>
<laqa.h>
<laqqa.h>
<talAqa.h>
<laq.h>
<laqA.h>
<talqI.h>
<lawAqi.h>
<mulaqqa.h>
<laqis>
<laqa.t>
<laqqa.t>
<talaqqa.t>
<iltaqa.t>
<laqa.t>
<laq.taT>
<luq.taT>
<luqA.t>
<laqI.t>
<milqa.t>
<iltiqA.t>
<lAqi.t>
<lAqi.taT>
<multaqi.t>
<laqa`>
<talaqqaf>
<iltaqaf>
<laqf>
<laqafAn>
<laqlaq>
<laqlaqaT>
<laqlaq>
<laqlAq>
<laqim>
<laqqam>
<'alqam>
<iltaqam>
<luqmaT>
<luqaymaT>
<laqIm>
<mulaqqim>
<lAqimIy>
<luqmAn>
<laqqan>
<talaqqan>
<laqAnaT>
<laqAnIyaT>
<talqIn>
<mulaqqin>
<lakaz>
<lakiz>
<likAz>
<lakI`>
<lakA`aT>
<lakmaT>
<milkamaT>
<mulAkamaT>
<mulAkim>
<lakin>
<laknaT>
<luknaT>
<lakAnaT>
<lukUnaT>
<lakan>
<lUkAndaT>
<lAm>
<lam>
<lammA>
<lammA>
<mAlam>
<talamma^g>
<lum^gaT>
<lama.h>
<lamma.h>
<lAma.h>
<'alma.h>
<talAma.h>
<lam.h>
<lam.haT>
<lammA.h>
<malAmi.h>
<talmI.h>
<mulammi.h>
<lamz>
<lumazaT>
<lammAz>
<lamas>
<lAmas>
<talammas>
<talAmas>
<iltamas>
<lams>
<lamsaT>
<lamsIyaT>
<lamIs>
<malmas>
<malmas>
<malmasIy>
<talammus>
<talAmus>
<iltimAs>
<malmUs>
<multamas>
<lama.s>
<lam.s>
<lama.z>
<talamma.z>
<lam.z>
<lama`>
<lamma`>
<'alma`>
<iltama`>
<lam`>
<lama`An>
<lum`aT>
<limA`>
<lammA`>
<'alma`>
<'alma`Iy>
<'alma`IyaT>
<talmI`>
<'ilmA`>
<lAmi`>
<lAmi`aT>
<mutalammi`>
<lamlam>
<mulamlimaT>
<lImAn>
<lImAn>
<lUmAn>
<lUmAn^gIy>
<lImUnAd>
<lambaT>
<lan>
<landan>
<landanIy>
<landanIy>
<lAn^s>
<lan^s>
<lahib>
<lahhab>
<'alhab>
<iltahab>
<lahab>
<lahIb>
<luhAb>
<lahbAn>
<'ilhAb>
<iltihAb>
<iltihAbIy>
<multahib>
<laha_t>
<lah_t>
<luhA_t>
<lah_tAn>
<lAhi_t>
<lahi^g>
<'alha^g>
<ilhA^g^g>
<lah^gaT>
<luh^gaT>
<lahd>
<lah_dam> |
module Elixir.Data.Sunny.Regular.O (section) where
import Elixir.Lexicon
lexicon = include section
cluster_1 = cluster
|> "l ^g l ^g" <| [
cluster_2 = cluster
|> "l ^g m" <| [
`imperf` FCuL,
`plural` HaFCiL |< aT
`plural` FuCuL,
`plural` TaFCIL |< At ]
cluster_3 = cluster
|> "l ^g n" <| [
`imperf` FCaL,
`plural` FiCAL
`plural` FiCaL
`plural` FaCaL |< At,
cluster_4 = cluster
|> "l .h b" <| [
`plural` FawACiL,
`plural` FawACiL ]
cluster_5 = cluster
|> "l .h ^g" <| [
cluster_6 = cluster
|> "l .h d" <| [
`imperf` FCaL,
`plural` HaFCAL
`plural` FuCUL,
`plural` FaCCAL |< Un
`femini` FaCCAL |< aT,
`plural` MuFCiL |< Un
`plural` MaFACiL |< aT
`femini` MuFCiL |< aT ]
cluster_7 = cluster
|> "l .h s" <| [
`imperf` FCaL,
`imperf` FCaL,
cluster_8 = cluster
|> "l .h .z" <| [
`imperf` FCaL
`masdar` FaCL
`masdar` FaCaLAn,
`plural` HaFCAL,
`plural` FaCaL |< At,
`plural` MaFACiL,
`plural` MuFACaL |< At,
`plural` FawACiL,
`plural` MaFCUL |< At,
`plural` MuFACiL |< Un
`femini` MuFACiL |< aT,
cluster_9 = cluster
|> "l .h f" <| [
`imperf` FCaL,
< tala.h.haf >
`plural` HaFCiL |< aT
`plural` FuCuL,
`plural` MaFACiL,
`plural` HiFCAL |< At,
cluster_10 = cluster
|> "l .h q" <| [
`imperf` FCaL,
`plural` HaFCAL,
< ' >
`plural` HiFCAL |< At,
< ' >
`plural` HiFCAL |< At,
< ' >
`plural` IFtiCAL |< At,
`plural` IstiFCAL |< At,
`plural` FawACiL,
`plural` MuFCaL |< Un
`femini` MuFCaL |< aT,
`plural` MaFACiL
`plural` MuFCaL |< At,
`plural` MuFACiL |< Un
`femini` MuFACiL |< aT,
cluster_11 = cluster
|> "l .h m" <| [
`imperf` FCuL,
`imperf` FCaL,
`plural` FiCAL
`plural` FuCUL,
`plural` FiCAL |< At,
`plural` FaCCAL |< Un
`femini` FaCCAL |< aT,
< la.hIm >
`plural` MaFACiL,
`plural` TaFACuL |< At,
`plural` IFtiCAL |< At,
`plural` IFtiCAL |< At,
cluster_12 = cluster
|> "l .h n" <| [
`imperf` FCaL
`masdar` FaCL
`masdar` FuCUL
`masdar` FaCAL |< aT,
`plural` HaFCAL
`plural` FuCUL,
`plural` TaFACIL,
`plural` MuFaCCiL |< Un
`femini` MuFaCCiL |< aT ]
cluster_13 = cluster
|> "l _h b .t" <| [
cluster_14 = cluster
|> "l _h .s" <| [
`plural` TaFCIL |< At,
`plural` MuFaCCaL |< At ]
cluster_15 = cluster
|> "l _h l _h" <| [
cluster_16 = cluster
|> "l _h m" <| [
cluster_17 = cluster
|> "l _h n" <| [
`plural` FuCL
`femini` FaCLA',
`plural` FuCL
`femini` FaCLA' ]
cluster_18 = cluster
|> "l d .g" <| [
`imperf` FCuL,
`plural` FuCaLA'
`plural` FaCLY,
cluster_19 = cluster
|> "l d n" <| [
`imperf` FCuL
`masdar` FaCAL |< aT
`masdar` FuCUL |< aT,
< laddan >
`plural` FuCL
`plural` FiCAL,
< lAdan >
`plural` FaCA'iL
`limited` "-------P--",
cluster_20 = cluster
|> "l _d `" <| [
`imperf` FCaL,
`plural` FawACiL,
cluster_21 = cluster
|> "l _d q" <| [
cluster_22 = cluster
|> ['l','U','r'] <| [
cluster_23 = cluster
|> ['l','I','r'] <| [
`plural` _____ |< At ]
cluster_24 = cluster
|> ['l','U','r','I'] <| [
cluster_25 = cluster
|> "l z b" <| [
`imperf` FCuL,
`imperf` FCaL,
`plural` FiCAL,
`plural` FiCaL,
cluster_26 = cluster
|> "l z ^g" <| [
< lazi^g >
`imperf` FCaL
`masdar` FaCaL
`masdar` FuCUL,
< lazi^g >
cluster_27 = cluster
|> "l z q" <| [
`imperf` FCaL,
< lazUq >
< lAzUq >
cluster_28 = cluster
|> "l z m" <| [
< lazim >
`imperf` FCaL,
`plural` FaCaL |< At,
`plural` MaFACiL,
`plural` MaFACiL,
`plural` TaFCIL |< At,
< mulAzamaT >
`plural` HiFCAL |< At,
`plural` IFtiCAL |< At,
`plural` FawACiL,
`plural` MuFACiL |< Un
`femini` MuFACiL |< aT,
< multazim >
`plural` MuFtaCaL |< At,
`plural` MustaFCaL |< At ]
cluster_29 = cluster
|> ['l','U','z','A','n'] <| [
< >
cluster_30 = cluster
|> "l s `" <| [
`imperf` FCaL,
`plural` FaCLY
`plural` FuCaLA',
cluster_31 = cluster
|> "l s n" <| [
`imperf` FCaL
`masdar` FaCaL,
< lasan >
`plural` FuCL
`femini` FaCLA',
`plural` HaFCiL |< aT
`plural` HaFCuL,
`plural` HaFCiL |< aT
`plural` HaFCuL,
`plural` FiCAL |< Iy |< At
`limited` "-------P--",
`plural` TaFACuL |< At,
`plural` MaFCUL |< Un
`femini` MaFCUL |< aT ]
cluster_32 = cluster
|> ['l','I','s','A','n','s'] <| [
cluster_33 = cluster
|> ['l','a','s','t','i','k'] <| [
|> ['l','a','s','t','I','k'] <| [
cluster_34 = cluster
|> ['l','i','^','s','b','U','n'] <| [
`excepts` Diptote ]
cluster_35 = cluster
|> "l .s q" <| [
`imperf` FCaL,
`plural` HiFCAL |< At,
`plural` TaFACuL |< At,
`plural` IFtiCAL |< At,
`plural` FawACiL,
`plural` MuFACiL |< Un
`femini` MuFACiL |< aT,
`plural` MuFCaL |< At,
cluster_36 = cluster
|> "l .d m" <| [
cluster_37 = cluster
|> "l .t _h" <| [
`imperf` FCaL,
`plural` FaCaL |< At,
`plural` FuCaL |< At,
< mula.t.ta_h >
cluster_38 = cluster
|> "l .t s" <| [
< la.tas >
`imperf` FCuL,
`plural` MaFACIL ]
cluster_39 = cluster
|> "l .t ^s" <| [
`imperf` FCuL,
cluster_40 = cluster
|> "l .t `" <| [
`imperf` FCaL,
cluster_41 = cluster
|> "l .t f" <| [
`imperf` FCuL
`masdar` FuCL
`masdar` FaCaL,
`imperf` FCuL
`masdar` FaCAL |< aT,
`plural` FuCaLA'
`plural` FiCAL,
`plural` FaCA'iL,
`plural` MuFACaL |< At
`limited` "-------P--",
`plural` TaFaCCuL |< At,
`plural` MuFaCCiL |< At,
cluster_42 = cluster
|> "l .t m" <| [
`imperf` FCiL,
`plural` FaCaL |< At,
cluster_43 = cluster
|> "l ` b" <| [
`imperf` FCaL,
`plural` HaFCAL,
`plural` FaCaL |< At,
`plural` FuCaL,
`plural` FuCayL |< At,
`plural` HaFACIL,
`plural` MaFACiL,
`plural` TaFACuL |< At,
`plural` FACiL |< Un
`femini` FACiL |< aT,
`plural` MaFACIL
`femini` MaFCUL |< aT,
`plural` MuFACiL |< Un
`femini` MuFACiL |< aT,
< >
cluster_44 = cluster
|> "l ` _t m" <| [
`plural` TaKaRDuS |< At,
cluster_45 = cluster
|> "l ` ^g" <| [
`imperf` FCaL,
< lA`i^g >
`plural` FawACiL,
< lA`i^g >
`plural` FawACiL ]
cluster_46 = cluster
|> "l ` s" <| [
`femini` FaCLA' ]
cluster_47 = cluster
|> "l ` q" <| [
`imperf` FCaL
`masdar` FaCL,
`plural` MaFACiL ]
cluster_48 = cluster
|> "l ` l" <| [
cluster_49 = cluster
|> "l ` l `" <| [
`plural` KaRADiS ]
cluster_50 = cluster
|> "l ` n" <| [
`imperf` FCaL
`masdar` FaCL,
`plural` FaCaL |< At
`plural` FiCAL,
`plural` MaFCUL |< Un
`plural` MaFACIL,
cluster_51 = cluster
|> "l .g b" <| [
< lA.gib >
`plural` FuCCAL ]
cluster_52 = cluster
|> "l .g d" <| [
`plural` HaFCAL
`plural` FuCUL,
`plural` FaCALIL,
`plural` FuCL ]
cluster_53 = cluster
|> ['l','U','.','g','A','r','I','t','m'] <| [
cluster_54 = cluster
|> "l .g z" <| [
`imperf` FCuL,
`plural` HaFCAL,
cluster_55 = cluster
|> "l .g .t" <| [
`imperf` FCaL
`masdar` FaCL
`masdar` FaCIL,
`plural` HaFCAL ]
cluster_56 = cluster
|> "l .g m" <| [
`imperf` FCaL
`imperf` FCuL
`masdar` FaCL,
`plural` HaFCAL,
`plural` HaFCAL,
`plural` HiFCAL |< At,
|> "l .g m" <| [
cluster_57 = cluster
|> "l .g m .t" <| [
cluster_58 = cluster
|> "l f t" <| [
< >
`imperf` FCiL,
< >
< >
< >
`plural` FaCaL |< At,
`plural` FuCL
`femini` FaCLA',
< >
`plural` FACiL |< At,
cluster_59 = cluster
|> ['l','i','f','I','_','t','A','n'] <| [
cluster_60 = cluster
|> "l f .h" <| [
`imperf` FCaL,
`plural` FaCaL |< At,
`plural` FawACiL,
`plural` TaFACIL ]
cluster_61 = cluster
|> "l f .z" <| [
`imperf` FCiL,
< laf.z >
`plural` HaFCAL,
< laf.zaT >
`plural` FaCaL |< At,
`plural` TaFaCCuL |< At,
cluster_62 = cluster
|> "l f `" <| [
`imperf` FCaL,
cluster_63 = cluster
|> "l f q" <| [
`plural` TaFCIL |< At,
cluster_64 = cluster
|> "l f l f" <| [
< talaflaf >
cluster_65 = cluster
|> "l q b" <| [
`plural` HaFCAL,
cluster_66 = cluster
|> "l q .h" <| [
`imperf` FCaL
`masdar` FaCL,
`plural` TaFCIL |< At,
`plural` FawACiL
`limited` "-------P--",
cluster_67 = cluster
|> "l q s" <| [
cluster_68 = cluster
|> "l q .t" <| [
`imperf` FCuL,
`plural` FaCaL |< At,
`plural` FuCaL,
`plural` FuCaLA',
`plural` MaFACiL,
`plural` IFtiCAL |< At,
`plural` FACiL |< At,
`plural` FACiL |< At,
cluster_69 = cluster
|> "l q `" <| [
`imperf` FCaL,
< laq ` >
cluster_70 = cluster
|> "l q f" <| [
< >
`imperf` FCaL,
cluster_71 = cluster
|> "l q l q" <| [
`plural` KaRADiS,
`plural` KaRADiS ]
cluster_72 = cluster
|> "l q m" <| [
< laqam >
`imperf` FCuL,
`imperf` FCaL,
`plural` FuCaL,
`plural` MuFaCCiL |< Un
`femini` MuFaCCiL |< aT,
< laqmIy >
< talqIm >
`plural` TaFCIL |< At ]
cluster_73 = cluster
|> "l q n" <| [
< >
`imperf` FCaL,
`plural` TaFCIL |< At,
`plural` MuFaCCiL |< Un
`femini` MuFaCCiL |< aT ]
cluster_74 = cluster
|> "l k z" <| [
`imperf` FCuL,
< >
cluster_75 = cluster
|> "l k `" <| [
`plural` FuCaLA',
cluster_76 = cluster
|> "l k m" <| [
< >
`imperf` FCuL,
< >
< >
`plural` FaCaL |< At,
`plural` MuFACiL |< Un
`femini` MuFACiL |< aT ]
cluster_77 = cluster
|> "l k n" <| [
`imperf` FCaL,
< ' >
`femini` FaCLA' ]
|> "l k n" <| [
`plural` HaFCAL ]
cluster_78 = cluster
|> ['l','U','k','A','n','d'] <| [
cluster_79 = cluster
|> ['l','A','m'] <| [
`plural` _____ |< At ]
cluster_80 = cluster
|> ['l','a','m'] <| [
cluster_81 = cluster
|> "l m ^g" <| [
cluster_82 = cluster
|> "l m .h" <| [
`imperf` FCaL
`masdar` FaCL,
`plural` FaCaL |< At,
`plural` MaFACiL
`limited` "-------P--",
`plural` TaFCIL |< At
`plural` TaFACIL,
cluster_83 = cluster
|> "l m z" <| [
< lamaz >
`imperf` FCiL
`imperf` FCuL,
cluster_84 = cluster
|> "l m s" <| [
`imperf` FCuL
`imperf` FCiL
`masdar` FaCL,
< lamsIy >
`plural` FaCaL |< At,
`plural` MaFACiL,
< mulAmasaT >
`plural` TaFaCCuL |< At,
`plural` TaFACuL |< At,
`plural` IFtiCAL |< At,
`plural` MuFtaCaL |< At ]
cluster_85 = cluster
|> "l m .s" <| [
`imperf` FCuL,
cluster_86 = cluster
|> "l m .z" <| [
`imperf` FCuL,
cluster_87 = cluster
|> "l m `" <| [
`imperf` FCaL
`masdar` FaCL
`masdar` FaCaLAn,
`plural` FuCaL,
`plural` TaFCIL |< At,
`plural` HiFCAL |< At,
`plural` FawACiL,
cluster_88 = cluster
|> "l m l m" <| [
cluster_89 = cluster
|> ['l','I','m','A','n'] <| [
`plural` _____ |< At,
`plural` _____ |< At ]
cluster_90 = cluster
|> ['l','U','m','A','n'] <| [
cluster_91 = cluster
|> ['l','I','m','U','n','A','d'] <| [
cluster_92 = cluster
|> ['l','a','m','b'] <| [
`plural` _____ |< At ]
cluster_93 = cluster
|> ['l','a','n'] <| [
cluster_94 = cluster
|> ['l','a','n','d','a','n'] <| [
`plural` _____ |< Iy |< Un
`femini` _____ |< Iy |< aT ]
cluster_95 = cluster
|> ['l','A','n','^','s'] <| [
`plural` _____ |< At ]
|> ['l','a','n','^','s'] <| [
`plural` _____ |< At ]
cluster_96 = cluster
|> "l h b" <| [
`imperf` FCaL
`masdar` FaCaL
`masdar` FaCIL,
< >
`plural` FaCLY
`plural` FiCAL,
`plural` HiFCAL |< At,
`plural` IFtiCAL |< At,
cluster_97 = cluster
|> "l h _t" <| [
`imperf` FCaL,
`plural` FaCLY,
cluster_98 = cluster
|> "l h ^g" <| [
`imperf` FCaL,
`plural` FaCaL |< At,
cluster_99 = cluster
|> "l h d" <| [
< lahad >
`imperf` FCaL,
cluster_100 = cluster
|> "l h _d m" <| [
section = [ cluster_1,
cluster_2,
cluster_3,
cluster_4,
cluster_5,
cluster_6,
cluster_7,
cluster_8,
cluster_9,
cluster_10,
cluster_11,
cluster_12,
cluster_13,
cluster_14,
cluster_15,
cluster_16,
cluster_17,
cluster_18,
cluster_19,
cluster_20,
cluster_21,
cluster_22,
cluster_23,
cluster_24,
cluster_25,
cluster_26,
cluster_27,
cluster_28,
cluster_29,
cluster_30,
cluster_31,
cluster_32,
cluster_33,
cluster_34,
cluster_35,
cluster_36,
cluster_37,
cluster_38,
cluster_39,
cluster_40,
cluster_41,
cluster_42,
cluster_43,
cluster_44,
cluster_45,
cluster_46,
cluster_47,
cluster_48,
cluster_49,
cluster_50,
cluster_51,
cluster_52,
cluster_53,
cluster_54,
cluster_55,
cluster_56,
cluster_57,
cluster_58,
cluster_59,
cluster_60,
cluster_61,
cluster_62,
cluster_63,
cluster_64,
cluster_65,
cluster_66,
cluster_67,
cluster_68,
cluster_69,
cluster_70,
cluster_71,
cluster_72,
cluster_73,
cluster_74,
cluster_75,
cluster_76,
cluster_77,
cluster_78,
cluster_79,
cluster_80,
cluster_81,
cluster_82,
cluster_83,
cluster_84,
cluster_85,
cluster_86,
cluster_87,
cluster_88,
cluster_89,
cluster_90,
cluster_91,
cluster_92,
cluster_93,
cluster_94,
cluster_95,
cluster_96,
cluster_97,
cluster_98,
cluster_99,
cluster_100 ]
|
d7de311b3aa1457151abc5911fc34868da79b2c91bb76d85877e6ceb5374fae8 | herd/herdtools7 | AArch64PteVal.ml | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris , France .
(* *)
Copyright 2020 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
open Printf
module Attrs = struct
type t = StringSet.t
By default we assume the attributes of the memory malloc would
return on Linux . This is architecture specific , however , for now ,
translation is supported only for AArch64 .
return on Linux. This is architecture specific, however, for now,
translation is supported only for AArch64. *)
let default = StringSet.empty
let compare a1 a2 = StringSet.compare a1 a2
let eq a1 a2 = StringSet.equal a1 a2
let pp a = StringSet.pp_str ", " Misc.identity a
let as_list a = StringSet.elements a
let of_list l = StringSet.of_list l
end
type t = {
oa : OutputAddress.t;
valid : int;
af : int;
db : int;
dbm : int;
el0 : int;
attrs: Attrs.t;
}
let eq_props p1 p2 =
Misc.int_eq p1.af p2.af &&
Misc.int_eq p1.db p2.db &&
Misc.int_eq p1.dbm p2.dbm &&
Misc.int_eq p1.valid p2.valid &&
Misc.int_eq p1.el0 p2.el0 &&
Attrs.eq p1.attrs p2.attrs
(* Let us abstract... *)
let is_af {af; _} = af <> 0
and same_oa {oa=oa1; _} {oa=oa2; _} = OutputAddress.eq oa1 oa2
(* *)
let writable ha hd p =
(p.af <> 0 || ha) && (* access allowed *)
(p.db <> 0 || (p.dbm <> 0 && hd)) (* write allowed *)
let get_attrs {attrs;_ } = Attrs.as_list attrs
(* For ordinary tests not to fault, the dirty bit has to be set. *)
let prot_default =
{ oa=OutputAddress.PHY "";
valid=1; af=1; db=1; dbm=0; el0=1; attrs=Attrs.default; }
let default s = { prot_default with oa=OutputAddress.PHY s; }
(* Page table entries for pointers into the page table
have el0 flag unset. Namely, page table access from
EL0 is disallowed. This correspond to expected behaviour:
user code cannot access the page table. *)
let of_pte s = { prot_default with oa=OutputAddress.PTE s; el0=0; }
let pp_field ok pp eq ac p k =
let f = ac p in if not ok && eq f (ac prot_default) then k else pp f::k
(* hexa arg is ignored, as it would complicate normalisation *)
let pp_int_field _hexa ok name =
let pp_int = sprintf "%d" in
pp_field ok (fun v -> sprintf "%s:%s" name (pp_int v)) Misc.int_eq
let pp_valid hexa ok = pp_int_field hexa ok "valid" (fun p -> p.valid)
and pp_af hexa ok = pp_int_field hexa ok "af" (fun p -> p.af)
and pp_db hexa ok = pp_int_field hexa ok "db" (fun p -> p.db)
and pp_dbm hexa ok = pp_int_field hexa ok "dbm" (fun p -> p.dbm)
and pp_el0 hexa ok = pp_int_field hexa ok "el0" (fun p -> p.el0)
and pp_attrs ok = pp_field ok (fun a -> Attrs.pp a) Attrs.eq (fun p -> p.attrs)
let is_default t = eq_props prot_default t
If showall is true , field will always be printed .
Otherwise , field will be printed only if non - default .
While computing hashes , backward compatibility commands that :
( 1 ) Fields older than el0 are always printed .
( 2 ) Fields from el0 ( included ) are printed if non - default .
Otherwise, field will be printed only if non-default.
While computing hashes, backward compatibility commands that:
(1) Fields older than el0 are always printed.
(2) Fields from el0 (included) are printed if non-default. *)
let pp_fields hexa showall p k =
let k = pp_el0 hexa false p k in
let k = pp_valid hexa showall p k in
let k = pp_dbm hexa showall p k in
let k = pp_db hexa showall p k in
let k = pp_af hexa showall p k in
k
let do_pp hexa showall old_oa p =
let k = pp_attrs false p [] in
let k = pp_fields hexa showall p k in
let k =
sprintf "oa:%s"
((if old_oa then OutputAddress.pp_old
else OutputAddress.pp) p.oa)::k in
let fs = String.concat ", " k in
sprintf "(%s)" fs
(* By default pp does not list fields whose value is default *)
let pp hexa = do_pp hexa false false
(* For initial values dumped for hashing, pp_hash is different,
for not altering hashes as much as possible *)
let pp_v = pp false
let pp_hash = do_pp false true true
let my_int_of_string s v =
let v = try int_of_string v with
_ -> Warn.user_error "PTE field %s should be an integer" s
in v
let add_field k v p =
match k with
| "af" -> { p with af = my_int_of_string k v }
| "db" -> { p with db = my_int_of_string k v }
| "dbm" -> { p with dbm = my_int_of_string k v }
| "valid" -> { p with valid = my_int_of_string k v }
| "el0" -> { p with el0 = my_int_of_string k v }
| _ ->
Warn.user_error "Illegal AArch64 page table entry property %s" k
let tr p =
let open ParsedPteVal in
let r = prot_default in
let r =
match p.p_oa with
| None -> r
| Some oa -> { r with oa; } in
let r = StringMap.fold add_field p.p_kv r in
let r =
let attrs = StringSet.union r.attrs p.p_attrs; in
{ r with attrs; } in
r
let pp_norm p =
let n = tr p in
pp_v n
let lex_compare c1 c2 x y = match c1 x y with
| 0 -> c2 x y
| r -> r
let compare =
let cmp = (fun p1 p2 -> Misc.int_compare p1.el0 p2.el0) in
let cmp =
lex_compare (fun p1 p2 -> Misc.int_compare p1.valid p2.valid) cmp in
let cmp =
lex_compare (fun p1 p2 -> Misc.int_compare p1.dbm p2.dbm) cmp in
let cmp =
lex_compare (fun p1 p2 -> Misc.int_compare p1.db p2.db) cmp in
let cmp =
lex_compare (fun p1 p2 -> Misc.int_compare p1.af p2.af) cmp in
let cmp =
lex_compare (fun p1 p2 -> OutputAddress.compare p1.oa p2.oa) cmp in
let cmp =
lex_compare (fun p1 p2 -> Attrs.compare p1.attrs p2.attrs) cmp in
cmp
let eq p1 p2 = OutputAddress.eq p1.oa p2.oa && eq_props p1 p2
(* For litmus *)
Those lists must of course match one with the other
let fields = ["af";"db";"dbm";"valid";"el0";]
and default_fields =
let p = prot_default in
let ds = [p.af; p.db; p.dbm; p.valid;p.el0;] in
List.map (Printf.sprintf "%i") ds
let norm =
let default =
try
List.fold_right2
(fun k v -> StringMap.add k v)
fields
default_fields
StringMap.empty
with Invalid_argument _ -> assert false in
fun kvs ->
StringMap.fold
(fun k v m ->
try
let v0 = StringMap.find k default in
if Misc.string_eq v v0 then m
else StringMap.add k v m
with
| Not_found -> StringMap.add k v m)
kvs StringMap.empty
let dump_pack pp_oa p =
sprintf
"pack_pack(%s,%d,%d,%d,%d,%d)"
(pp_oa (OutputAddress.pp_old p.oa))
p.af p.db p.dbm p.valid p.el0
let as_physical p = OutputAddress.as_physical p.oa
let as_flags p =
if is_default p then None
else
let add b s k = if b<>0 then s::k else k in
let msk =
add p.el0 "msk_el0"
(add p.valid "msk_valid"
(add p.af "msk_af"
(add p.dbm "msk_dbm"
(add p.db "msk_db" [])))) in
let msk = String.concat "|" msk in
Some msk
| null | https://raw.githubusercontent.com/herd/herdtools7/6a5b3085a9d2357f98f4d560d7dd12add34edabe/lib/AArch64PteVal.ml | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
Let us abstract...
access allowed
write allowed
For ordinary tests not to fault, the dirty bit has to be set.
Page table entries for pointers into the page table
have el0 flag unset. Namely, page table access from
EL0 is disallowed. This correspond to expected behaviour:
user code cannot access the page table.
hexa arg is ignored, as it would complicate normalisation
By default pp does not list fields whose value is default
For initial values dumped for hashing, pp_hash is different,
for not altering hashes as much as possible
For litmus | , University College London , UK .
, INRIA Paris , France .
Copyright 2020 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
open Printf
module Attrs = struct
type t = StringSet.t
By default we assume the attributes of the memory malloc would
return on Linux . This is architecture specific , however , for now ,
translation is supported only for AArch64 .
return on Linux. This is architecture specific, however, for now,
translation is supported only for AArch64. *)
let default = StringSet.empty
let compare a1 a2 = StringSet.compare a1 a2
let eq a1 a2 = StringSet.equal a1 a2
let pp a = StringSet.pp_str ", " Misc.identity a
let as_list a = StringSet.elements a
let of_list l = StringSet.of_list l
end
type t = {
oa : OutputAddress.t;
valid : int;
af : int;
db : int;
dbm : int;
el0 : int;
attrs: Attrs.t;
}
let eq_props p1 p2 =
Misc.int_eq p1.af p2.af &&
Misc.int_eq p1.db p2.db &&
Misc.int_eq p1.dbm p2.dbm &&
Misc.int_eq p1.valid p2.valid &&
Misc.int_eq p1.el0 p2.el0 &&
Attrs.eq p1.attrs p2.attrs
let is_af {af; _} = af <> 0
and same_oa {oa=oa1; _} {oa=oa2; _} = OutputAddress.eq oa1 oa2
let writable ha hd p =
let get_attrs {attrs;_ } = Attrs.as_list attrs
let prot_default =
{ oa=OutputAddress.PHY "";
valid=1; af=1; db=1; dbm=0; el0=1; attrs=Attrs.default; }
let default s = { prot_default with oa=OutputAddress.PHY s; }
let of_pte s = { prot_default with oa=OutputAddress.PTE s; el0=0; }
let pp_field ok pp eq ac p k =
let f = ac p in if not ok && eq f (ac prot_default) then k else pp f::k
let pp_int_field _hexa ok name =
let pp_int = sprintf "%d" in
pp_field ok (fun v -> sprintf "%s:%s" name (pp_int v)) Misc.int_eq
let pp_valid hexa ok = pp_int_field hexa ok "valid" (fun p -> p.valid)
and pp_af hexa ok = pp_int_field hexa ok "af" (fun p -> p.af)
and pp_db hexa ok = pp_int_field hexa ok "db" (fun p -> p.db)
and pp_dbm hexa ok = pp_int_field hexa ok "dbm" (fun p -> p.dbm)
and pp_el0 hexa ok = pp_int_field hexa ok "el0" (fun p -> p.el0)
and pp_attrs ok = pp_field ok (fun a -> Attrs.pp a) Attrs.eq (fun p -> p.attrs)
let is_default t = eq_props prot_default t
If showall is true , field will always be printed .
Otherwise , field will be printed only if non - default .
While computing hashes , backward compatibility commands that :
( 1 ) Fields older than el0 are always printed .
( 2 ) Fields from el0 ( included ) are printed if non - default .
Otherwise, field will be printed only if non-default.
While computing hashes, backward compatibility commands that:
(1) Fields older than el0 are always printed.
(2) Fields from el0 (included) are printed if non-default. *)
let pp_fields hexa showall p k =
let k = pp_el0 hexa false p k in
let k = pp_valid hexa showall p k in
let k = pp_dbm hexa showall p k in
let k = pp_db hexa showall p k in
let k = pp_af hexa showall p k in
k
let do_pp hexa showall old_oa p =
let k = pp_attrs false p [] in
let k = pp_fields hexa showall p k in
let k =
sprintf "oa:%s"
((if old_oa then OutputAddress.pp_old
else OutputAddress.pp) p.oa)::k in
let fs = String.concat ", " k in
sprintf "(%s)" fs
let pp hexa = do_pp hexa false false
let pp_v = pp false
let pp_hash = do_pp false true true
let my_int_of_string s v =
let v = try int_of_string v with
_ -> Warn.user_error "PTE field %s should be an integer" s
in v
let add_field k v p =
match k with
| "af" -> { p with af = my_int_of_string k v }
| "db" -> { p with db = my_int_of_string k v }
| "dbm" -> { p with dbm = my_int_of_string k v }
| "valid" -> { p with valid = my_int_of_string k v }
| "el0" -> { p with el0 = my_int_of_string k v }
| _ ->
Warn.user_error "Illegal AArch64 page table entry property %s" k
let tr p =
let open ParsedPteVal in
let r = prot_default in
let r =
match p.p_oa with
| None -> r
| Some oa -> { r with oa; } in
let r = StringMap.fold add_field p.p_kv r in
let r =
let attrs = StringSet.union r.attrs p.p_attrs; in
{ r with attrs; } in
r
let pp_norm p =
let n = tr p in
pp_v n
let lex_compare c1 c2 x y = match c1 x y with
| 0 -> c2 x y
| r -> r
let compare =
let cmp = (fun p1 p2 -> Misc.int_compare p1.el0 p2.el0) in
let cmp =
lex_compare (fun p1 p2 -> Misc.int_compare p1.valid p2.valid) cmp in
let cmp =
lex_compare (fun p1 p2 -> Misc.int_compare p1.dbm p2.dbm) cmp in
let cmp =
lex_compare (fun p1 p2 -> Misc.int_compare p1.db p2.db) cmp in
let cmp =
lex_compare (fun p1 p2 -> Misc.int_compare p1.af p2.af) cmp in
let cmp =
lex_compare (fun p1 p2 -> OutputAddress.compare p1.oa p2.oa) cmp in
let cmp =
lex_compare (fun p1 p2 -> Attrs.compare p1.attrs p2.attrs) cmp in
cmp
let eq p1 p2 = OutputAddress.eq p1.oa p2.oa && eq_props p1 p2
Those lists must of course match one with the other
let fields = ["af";"db";"dbm";"valid";"el0";]
and default_fields =
let p = prot_default in
let ds = [p.af; p.db; p.dbm; p.valid;p.el0;] in
List.map (Printf.sprintf "%i") ds
let norm =
let default =
try
List.fold_right2
(fun k v -> StringMap.add k v)
fields
default_fields
StringMap.empty
with Invalid_argument _ -> assert false in
fun kvs ->
StringMap.fold
(fun k v m ->
try
let v0 = StringMap.find k default in
if Misc.string_eq v v0 then m
else StringMap.add k v m
with
| Not_found -> StringMap.add k v m)
kvs StringMap.empty
let dump_pack pp_oa p =
sprintf
"pack_pack(%s,%d,%d,%d,%d,%d)"
(pp_oa (OutputAddress.pp_old p.oa))
p.af p.db p.dbm p.valid p.el0
let as_physical p = OutputAddress.as_physical p.oa
let as_flags p =
if is_default p then None
else
let add b s k = if b<>0 then s::k else k in
let msk =
add p.el0 "msk_el0"
(add p.valid "msk_valid"
(add p.af "msk_af"
(add p.dbm "msk_dbm"
(add p.db "msk_db" [])))) in
let msk = String.concat "|" msk in
Some msk
|
bddbda1383d9b3486574d6253126886dd47cdbdeea915567b737c28f018d51e8 | mistupv/cauder-core | tcp.erl | -module(tcp).
-export([main/0, server_fun/3, client_fun/4, ack/5]).
main() ->
Server_PID = spawn(?MODULE, server_fun, [self(), 50, 500]),
spawn(?MODULE, client_fun, [Server_PID, 57, 100, client1]),
spawn(?MODULE, client_fun, [Server_PID, 50, 200, client2]),
receive {data,D} -> D end.
server_fun(Main_PID, Port, Seq) ->
receive
{Client_PID, {syn, Port, SeqCl}} ->
Ack_PID = spawn(?MODULE, ack, [Main_PID, Port, SeqCl+1, Seq+1, Client_PID]),
Client_PID ! {Ack_PID, {syn_ack, SeqCl+1, Seq}},
server_fun(Main_PID, Port, Seq+1);
{Client_PID, {syn, _, _}} ->
Client_PID ! rst
end.
ack(Main_PID, Port, Ack, Seq, Client_PID) ->
receive
{Client_PID, {ack, Port, Seq, Ack}} ->
receive
{Client_PID, {data, Port, D}} -> Main_PID ! {data, D};
_ -> Main_PID ! {data, error_data}
end;
_ -> Main_PID ! {data, error_ack}
end.
client_fun(Server_PID, Port, Seq, Data) ->
Server_PID ! {self(), {syn, Port, Seq}}, syn_ack(Port, Data, Seq+1).
syn_ack(Port, Data, Ack) ->
receive
rst -> {port_rejected, Port} ;
{Ack_PID, {syn_ack, Ack, Seq}} ->
Ack_PID ! {self(), {Ack, Port, Seq+1, ack}},
Ack_PID ! {self(), {data, Port, Data}},
{Seq+1, Ack, Port, Data}
end.
| null | https://raw.githubusercontent.com/mistupv/cauder-core/b676fccd1bbd629eb63f3cb5259f7a9a8c6da899/case-studies/tcp/tcp.erl | erlang | -module(tcp).
-export([main/0, server_fun/3, client_fun/4, ack/5]).
main() ->
Server_PID = spawn(?MODULE, server_fun, [self(), 50, 500]),
spawn(?MODULE, client_fun, [Server_PID, 57, 100, client1]),
spawn(?MODULE, client_fun, [Server_PID, 50, 200, client2]),
receive {data,D} -> D end.
server_fun(Main_PID, Port, Seq) ->
receive
{Client_PID, {syn, Port, SeqCl}} ->
Ack_PID = spawn(?MODULE, ack, [Main_PID, Port, SeqCl+1, Seq+1, Client_PID]),
Client_PID ! {Ack_PID, {syn_ack, SeqCl+1, Seq}},
server_fun(Main_PID, Port, Seq+1);
{Client_PID, {syn, _, _}} ->
Client_PID ! rst
end.
ack(Main_PID, Port, Ack, Seq, Client_PID) ->
receive
{Client_PID, {ack, Port, Seq, Ack}} ->
receive
{Client_PID, {data, Port, D}} -> Main_PID ! {data, D};
_ -> Main_PID ! {data, error_data}
end;
_ -> Main_PID ! {data, error_ack}
end.
client_fun(Server_PID, Port, Seq, Data) ->
Server_PID ! {self(), {syn, Port, Seq}}, syn_ack(Port, Data, Seq+1).
syn_ack(Port, Data, Ack) ->
receive
rst -> {port_rejected, Port} ;
{Ack_PID, {syn_ack, Ack, Seq}} ->
Ack_PID ! {self(), {Ack, Port, Seq+1, ack}},
Ack_PID ! {self(), {data, Port, Data}},
{Seq+1, Ack, Port, Data}
end.
|
|
de722796654a2559680f970e082a0e4de69d3ef2d5170f280598d1a7ac34393e | maximvl/erl9p | lib9p.erl | -module(lib9p).
-include("9p.hrl").
-export([parse_message/2,
pack_message/3]).
%% Version
-spec parse_message(byte(), binary()) -> false | tuple() | binary().
parse_message(?Tversion, <<MSize:32/little-integer,
S:16/little-integer,
Version:S/binary>>) ->
{MSize, Version};
parse_message(?Rversion, <<MSize:32/little-integer,
S:16/little-integer,
Version:S/binary>>) ->
{MSize, Version};
parse_message(?Tauth, <<AFid:32/little-integer,
Su:16/little-integer,
Uname:Su/binary,
Sa:16/little-integer,
Aname:Sa/binary>>) ->
{AFid, Uname, Aname};
parse_message(?Rauth, <<AQid:13/binary>>) ->
binary_to_qid(AQid);
parse_message(?Rerror, <<S:16/little-integer,
Ename:S/binary>>) ->
Ename;
parse_message(?Tflush, <<OldTag:2/binary>>) ->
OldTag;
parse_message(?Rflush, <<>>) ->
<<>>;
parse_message(?Tattach, <<Fid:32/little-integer,
AFid:32/little-integer,
Su:16/little-integer,
Uname:Su/binary,
Sa:16/little-integer,
Aname:Sa/binary>>) ->
{Fid, AFid, Uname, Aname};
parse_message(?Rattach, <<Qid:13/binary>>) ->
binary_to_qid(Qid);
parse_message(?Twalk, <<Fid:32/little-integer,
NewFid:32/little-integer,
Nwname:16/little-integer,
Rest/binary>>) ->
Wnames = binary_to_wnames(Nwname, Rest),
{Fid, NewFid, Wnames};
parse_message(?Rwalk, <<Nwqid:16/little-integer,
Rest/binary>>) ->
binary_to_wqids(Nwqid, Rest);
parse_message(?Topen, <<Fid:32/little-integer,
Mode:1/binary>>) ->
{Fid, Mode};
parse_message(?Ropen, <<Qid:13/binary,
IOunit:32/little-integer>>) ->
{binary_to_qid(Qid), IOunit};
parse_message(?Tcreate, <<Fid:32/little-integer,
S:16/little-integer,
Name:S/binary,
Perm:32/little-integer,
Mode:1/binary>>) ->
{Fid, Name, Perm, Mode};
parse_message(?Rcreate, <<Qid:13/binary,
IOunit:32/little-integer>>) ->
{binary_to_qid(Qid), IOunit};
parse_message(?Tread, <<Fid:32/little-integer,
Offset:64/little-integer,
Count:32/little-integer>>) ->
{Fid, Offset, Count};
parse_message(?Rread, <<Count:32/little-integer,
Data:Count/binary>>) ->
Data;
parse_message(?Twrite, <<Fid:32/little-integer,
Offset:64/little-integer,
Count:32/little-integer,
Data:Count/binary>>) ->
{Fid, Offset, Data};
parse_message(?Rwrite, <<Count:32/little-integer>>) ->
Count;
parse_message(?Tclunk, <<Fid:32/little-integer>>) ->
Fid;
parse_message(?Rclunk, <<>>) ->
<<>>;
parse_message(?Tremove, <<Fid:32/little-integer>>) ->
Fid;
parse_message(?Rremove, <<>>) ->
<<>>;
parse_message(?Tstat, <<Fid:32/little-integer>>) ->
Fid;
parse_message(?Rstat, <<N:16/little-integer,
Stat:N/binary>>) ->
Stat;
parse_message(?Twstat, <<Fid:32/little-integer,
N:16/little-integer,
Stat:N/binary>>) ->
{Fid, Stat};
parse_message(?Rwstat, <<>>) ->
<<>>;
parse_message(_, _) ->
false.
%% Packing
-spec pack_message(byte(), binary(), tuple() | binary()) -> binary().
pack_message(Type, Tag, Data) ->
BinData = pack_message(Type, Data),
DSize = byte_size(BinData) + 7,
<<DSize:32/little-integer,
Type:8/little-integer,
Tag:2/binary,
BinData/binary>>.
-spec pack_message(integer(), any()) -> binary().
pack_message(?Tversion, {MSize, Version}) ->
S = byte_size(Version),
<<MSize:32/little-integer,
S:16/little-integer,
Version/binary>>;
pack_message(?Rversion, {MSize, Version}) ->
S = byte_size(Version),
<<MSize:32/little-integer,
S:16/little-integer,
Version/binary>>;
Auth
pack_message(?Tauth, {AFid, Uname, Aname}) ->
Su = byte_size(Uname),
Sa = byte_size(Aname),
<<AFid:32/little-integer,
Su:16/little-integer,
Uname/binary,
Sa:16/little-integer,
Aname/binary>>;
pack_message(?Rauth, AQid) ->
qid_to_binary(AQid);
%% Error
pack_message(?Rerror, Name) ->
S = byte_size(Name),
<<S:16/little-integer,
Name/binary>>;
%% Flush
pack_message(?Tflush, OldTag) ->
<<OldTag:2/binary>>;
pack_message(?Rflush, _) ->
<<>>;
%% Attach
pack_message(?Tattach, {Fid, AFid, Uname, Aname}) ->
Su = byte_size(Uname),
Sa = byte_size(Aname),
<<Fid:32/little-integer,
AFid:32/little-integer,
Su:16/little-integer,
Uname/binary,
Sa:16/little-integer,
Aname/binary>>;
pack_message(?Rattach, Qid) ->
qid_to_binary(Qid);
%% Walk
pack_message(?Twalk, {Fid, NewFid, Wnames}) ->
Nwname = length(Wnames),
BinNames = wnames_to_binary(Wnames),
<<Fid:32/little-integer,
NewFid:32/little-integer,
Nwname:16/little-integer,
BinNames/binary>>;
pack_message(?Rwalk, Wqids) ->
Nwqids = length(Wqids),
BinQids = wqids_to_binary(Wqids),
<<Nwqids:16/little-integer,
BinQids/binary>>;
%% Open
pack_message(?Topen, {Fid, Mode}) ->
<<Fid:32/little-integer,
Mode:1/binary>>;
pack_message(?Ropen, {Qid, IOunit}) ->
BQid = qid_to_binary(Qid),
<<BQid:13/binary,
IOunit:32/little-integer>>;
%% Create
pack_message(?Tcreate, {Fid, Name, Perm, Mode}) ->
S = byte_size(Name),
<<Fid:32/little-integer,
S:16/little-integer,
Name/binary,
Perm:32/little-integer,
Mode:1/binary>>;
pack_message(?Rcreate, {Qid, IOunit}) ->
BQid = qid_to_binary(Qid),
<<BQid:13/binary,
IOunit:32/little-integer>>;
%% read
pack_message(?Tread, {Fid, Offset, Count}) ->
<<Fid:32/little-integer,
Offset:64/little-integer,
Count:32/little-integer>>;
pack_message(?Rread, RData) ->
Count = byte_size(RData),
<<Count:32/little-integer,
RData/binary>>;
%% Write
pack_message(?Twrite, {Fid, Offset, WData}) ->
Count = byte_size(WData),
<<Fid:32/little-integer,
Offset:64/little-integer,
Count:32/little-integer,
WData/binary>>;
pack_message(?Rwrite, Count) ->
<<Count:32/little-integer>>;
%% Clunk
pack_message(?Tclunk, Fid) ->
<<Fid:32/little-integer>>;
pack_message(?Rclunk, _) ->
<<>>;
%% Remove
pack_message(?Tremove, Fid) ->
<<Fid:32/little-integer>>;
pack_message(?Rremove, _) ->
<<>>;
%% Stat
pack_message(?Tstat, Fid) ->
<<Fid:32/little-integer>>;
pack_message(?Rstat, Stat) ->
N = byte_size(Stat),
Stat1 = <<N:16/little-integer,
Stat/binary>>,
FSize = byte_size(Stat1),
<<FSize:16/little-integer, Stat1/binary>>;
WStat
pack_message(?Twstat, {Fid, Stat}) ->
N = byte_size(Stat),
<<Fid:32/little-integer,
N:16/little-integer,
Stat/binary>>;
pack_message(?Rwstat, _) ->
<<>>.
Utils
-spec wnames_to_binary([binary()]) -> binary().
wnames_to_binary(Names) ->
wnames_to_binary(Names, <<>>).
-spec wnames_to_binary([binary()], binary()) -> binary().
wnames_to_binary([], Acc) ->
Acc;
wnames_to_binary([H|T], Acc) ->
S = byte_size(H),
Data = <<S:16/little-integer,
H/binary>>,
wnames_to_binary(T, <<Acc/binary, Data/binary>>).
-spec binary_to_wnames(integer(), binary()) -> [binary()].
binary_to_wnames(0, _) ->
[];
binary_to_wnames(N, <<S:16/little-integer,
Wname:S/binary,
Rest/binary>>) ->
[Wname | binary_to_wnames(N-1, Rest)].
-spec wqids_to_binary([binary()]) -> binary().
wqids_to_binary(Qids) ->
wqids_to_binary(Qids, <<>>).
-spec wqids_to_binary([binary()], binary()) -> binary().
wqids_to_binary([], Acc) ->
Acc;
wqids_to_binary([H|T], Acc) ->
BQid = qid_to_binary(H),
wqids_to_binary(T, <<Acc/binary, BQid:13/binary>>).
-spec binary_to_wqids(integer(), binary()) -> [{byte(), integer(), integer()}].
binary_to_wqids(0, _) ->
[];
binary_to_wqids(N, <<Wqid:13/binary,
Rest/binary>>) ->
[binary_to_qid(Wqid) | binary_to_wqids(N-1, Rest)].
-spec binary_to_qid(binary()) -> {byte(), integer(), integer()}.
binary_to_qid(<<Type:8/little-integer,
Vers:32/little-integer,
Path:64/little-integer>>) ->
{Type, Vers, Path}.
-spec qid_to_binary({qid_type(), qid_version(), qid_path()}) ->
binary().
qid_to_binary({Type, Vers, Path}) ->
<<Type:8/little-integer,
Vers:32/little-integer,
Path:8/binary>>.
| null | https://raw.githubusercontent.com/maximvl/erl9p/c5410da3797811578a248ea4d2b8e449fabd0541/src/lib9p.erl | erlang | Version
Packing
Error
Flush
Attach
Walk
Open
Create
read
Write
Clunk
Remove
Stat | -module(lib9p).
-include("9p.hrl").
-export([parse_message/2,
pack_message/3]).
-spec parse_message(byte(), binary()) -> false | tuple() | binary().
parse_message(?Tversion, <<MSize:32/little-integer,
S:16/little-integer,
Version:S/binary>>) ->
{MSize, Version};
parse_message(?Rversion, <<MSize:32/little-integer,
S:16/little-integer,
Version:S/binary>>) ->
{MSize, Version};
parse_message(?Tauth, <<AFid:32/little-integer,
Su:16/little-integer,
Uname:Su/binary,
Sa:16/little-integer,
Aname:Sa/binary>>) ->
{AFid, Uname, Aname};
parse_message(?Rauth, <<AQid:13/binary>>) ->
binary_to_qid(AQid);
parse_message(?Rerror, <<S:16/little-integer,
Ename:S/binary>>) ->
Ename;
parse_message(?Tflush, <<OldTag:2/binary>>) ->
OldTag;
parse_message(?Rflush, <<>>) ->
<<>>;
parse_message(?Tattach, <<Fid:32/little-integer,
AFid:32/little-integer,
Su:16/little-integer,
Uname:Su/binary,
Sa:16/little-integer,
Aname:Sa/binary>>) ->
{Fid, AFid, Uname, Aname};
parse_message(?Rattach, <<Qid:13/binary>>) ->
binary_to_qid(Qid);
parse_message(?Twalk, <<Fid:32/little-integer,
NewFid:32/little-integer,
Nwname:16/little-integer,
Rest/binary>>) ->
Wnames = binary_to_wnames(Nwname, Rest),
{Fid, NewFid, Wnames};
parse_message(?Rwalk, <<Nwqid:16/little-integer,
Rest/binary>>) ->
binary_to_wqids(Nwqid, Rest);
parse_message(?Topen, <<Fid:32/little-integer,
Mode:1/binary>>) ->
{Fid, Mode};
parse_message(?Ropen, <<Qid:13/binary,
IOunit:32/little-integer>>) ->
{binary_to_qid(Qid), IOunit};
parse_message(?Tcreate, <<Fid:32/little-integer,
S:16/little-integer,
Name:S/binary,
Perm:32/little-integer,
Mode:1/binary>>) ->
{Fid, Name, Perm, Mode};
parse_message(?Rcreate, <<Qid:13/binary,
IOunit:32/little-integer>>) ->
{binary_to_qid(Qid), IOunit};
parse_message(?Tread, <<Fid:32/little-integer,
Offset:64/little-integer,
Count:32/little-integer>>) ->
{Fid, Offset, Count};
parse_message(?Rread, <<Count:32/little-integer,
Data:Count/binary>>) ->
Data;
parse_message(?Twrite, <<Fid:32/little-integer,
Offset:64/little-integer,
Count:32/little-integer,
Data:Count/binary>>) ->
{Fid, Offset, Data};
parse_message(?Rwrite, <<Count:32/little-integer>>) ->
Count;
parse_message(?Tclunk, <<Fid:32/little-integer>>) ->
Fid;
parse_message(?Rclunk, <<>>) ->
<<>>;
parse_message(?Tremove, <<Fid:32/little-integer>>) ->
Fid;
parse_message(?Rremove, <<>>) ->
<<>>;
parse_message(?Tstat, <<Fid:32/little-integer>>) ->
Fid;
parse_message(?Rstat, <<N:16/little-integer,
Stat:N/binary>>) ->
Stat;
parse_message(?Twstat, <<Fid:32/little-integer,
N:16/little-integer,
Stat:N/binary>>) ->
{Fid, Stat};
parse_message(?Rwstat, <<>>) ->
<<>>;
parse_message(_, _) ->
false.
-spec pack_message(byte(), binary(), tuple() | binary()) -> binary().
pack_message(Type, Tag, Data) ->
BinData = pack_message(Type, Data),
DSize = byte_size(BinData) + 7,
<<DSize:32/little-integer,
Type:8/little-integer,
Tag:2/binary,
BinData/binary>>.
-spec pack_message(integer(), any()) -> binary().
pack_message(?Tversion, {MSize, Version}) ->
S = byte_size(Version),
<<MSize:32/little-integer,
S:16/little-integer,
Version/binary>>;
pack_message(?Rversion, {MSize, Version}) ->
S = byte_size(Version),
<<MSize:32/little-integer,
S:16/little-integer,
Version/binary>>;
Auth
pack_message(?Tauth, {AFid, Uname, Aname}) ->
Su = byte_size(Uname),
Sa = byte_size(Aname),
<<AFid:32/little-integer,
Su:16/little-integer,
Uname/binary,
Sa:16/little-integer,
Aname/binary>>;
pack_message(?Rauth, AQid) ->
qid_to_binary(AQid);
pack_message(?Rerror, Name) ->
S = byte_size(Name),
<<S:16/little-integer,
Name/binary>>;
pack_message(?Tflush, OldTag) ->
<<OldTag:2/binary>>;
pack_message(?Rflush, _) ->
<<>>;
pack_message(?Tattach, {Fid, AFid, Uname, Aname}) ->
Su = byte_size(Uname),
Sa = byte_size(Aname),
<<Fid:32/little-integer,
AFid:32/little-integer,
Su:16/little-integer,
Uname/binary,
Sa:16/little-integer,
Aname/binary>>;
pack_message(?Rattach, Qid) ->
qid_to_binary(Qid);
pack_message(?Twalk, {Fid, NewFid, Wnames}) ->
Nwname = length(Wnames),
BinNames = wnames_to_binary(Wnames),
<<Fid:32/little-integer,
NewFid:32/little-integer,
Nwname:16/little-integer,
BinNames/binary>>;
pack_message(?Rwalk, Wqids) ->
Nwqids = length(Wqids),
BinQids = wqids_to_binary(Wqids),
<<Nwqids:16/little-integer,
BinQids/binary>>;
pack_message(?Topen, {Fid, Mode}) ->
<<Fid:32/little-integer,
Mode:1/binary>>;
pack_message(?Ropen, {Qid, IOunit}) ->
BQid = qid_to_binary(Qid),
<<BQid:13/binary,
IOunit:32/little-integer>>;
pack_message(?Tcreate, {Fid, Name, Perm, Mode}) ->
S = byte_size(Name),
<<Fid:32/little-integer,
S:16/little-integer,
Name/binary,
Perm:32/little-integer,
Mode:1/binary>>;
pack_message(?Rcreate, {Qid, IOunit}) ->
BQid = qid_to_binary(Qid),
<<BQid:13/binary,
IOunit:32/little-integer>>;
pack_message(?Tread, {Fid, Offset, Count}) ->
<<Fid:32/little-integer,
Offset:64/little-integer,
Count:32/little-integer>>;
pack_message(?Rread, RData) ->
Count = byte_size(RData),
<<Count:32/little-integer,
RData/binary>>;
pack_message(?Twrite, {Fid, Offset, WData}) ->
Count = byte_size(WData),
<<Fid:32/little-integer,
Offset:64/little-integer,
Count:32/little-integer,
WData/binary>>;
pack_message(?Rwrite, Count) ->
<<Count:32/little-integer>>;
pack_message(?Tclunk, Fid) ->
<<Fid:32/little-integer>>;
pack_message(?Rclunk, _) ->
<<>>;
pack_message(?Tremove, Fid) ->
<<Fid:32/little-integer>>;
pack_message(?Rremove, _) ->
<<>>;
pack_message(?Tstat, Fid) ->
<<Fid:32/little-integer>>;
pack_message(?Rstat, Stat) ->
N = byte_size(Stat),
Stat1 = <<N:16/little-integer,
Stat/binary>>,
FSize = byte_size(Stat1),
<<FSize:16/little-integer, Stat1/binary>>;
WStat
pack_message(?Twstat, {Fid, Stat}) ->
N = byte_size(Stat),
<<Fid:32/little-integer,
N:16/little-integer,
Stat/binary>>;
pack_message(?Rwstat, _) ->
<<>>.
Utils
-spec wnames_to_binary([binary()]) -> binary().
wnames_to_binary(Names) ->
wnames_to_binary(Names, <<>>).
-spec wnames_to_binary([binary()], binary()) -> binary().
wnames_to_binary([], Acc) ->
Acc;
wnames_to_binary([H|T], Acc) ->
S = byte_size(H),
Data = <<S:16/little-integer,
H/binary>>,
wnames_to_binary(T, <<Acc/binary, Data/binary>>).
-spec binary_to_wnames(integer(), binary()) -> [binary()].
binary_to_wnames(0, _) ->
[];
binary_to_wnames(N, <<S:16/little-integer,
Wname:S/binary,
Rest/binary>>) ->
[Wname | binary_to_wnames(N-1, Rest)].
-spec wqids_to_binary([binary()]) -> binary().
wqids_to_binary(Qids) ->
wqids_to_binary(Qids, <<>>).
-spec wqids_to_binary([binary()], binary()) -> binary().
wqids_to_binary([], Acc) ->
Acc;
wqids_to_binary([H|T], Acc) ->
BQid = qid_to_binary(H),
wqids_to_binary(T, <<Acc/binary, BQid:13/binary>>).
-spec binary_to_wqids(integer(), binary()) -> [{byte(), integer(), integer()}].
binary_to_wqids(0, _) ->
[];
binary_to_wqids(N, <<Wqid:13/binary,
Rest/binary>>) ->
[binary_to_qid(Wqid) | binary_to_wqids(N-1, Rest)].
-spec binary_to_qid(binary()) -> {byte(), integer(), integer()}.
binary_to_qid(<<Type:8/little-integer,
Vers:32/little-integer,
Path:64/little-integer>>) ->
{Type, Vers, Path}.
-spec qid_to_binary({qid_type(), qid_version(), qid_path()}) ->
binary().
qid_to_binary({Type, Vers, Path}) ->
<<Type:8/little-integer,
Vers:32/little-integer,
Path:8/binary>>.
|
df83622ff4f0ecc82e9e373200b781be80faaccf27cee663e43b811e99e7dbf6 | jordanthayer/ocaml-search | dwa_optimistic.ml | (** Optimistic Search *)
open Optimistic_search
let make_expand expand hd wt initial_d =
(** Takes the [expand] function for the domain nodes and converts it into
an expand function which will operate on search nodes. [hd] is a cost
distance estimator. [wt] is the optimistic weight, and [initial_d] is
the estimated distance from the root node to a goal. *)
let make_child =
(fun (n, g) ->
let h,d = hd n in
let factor = Math.fmax 1.
(Math.fmin wt (wt *. (d /. initial_d))) in
{ fp = g +. factor *. h;
h = h;
g = g;
fpos = Dpq.no_position;
ppos = Dpq.no_position;
dpos = Dpq.no_position;
data = n;}) in
(fun parent ->
List.map make_child (expand parent.data parent.g))
(***************************************************************************)
let no_dups sface args =
(** Performs DwA* optimistic search on domains with few / no duplicates.
[sface] is the search interface, [bound] is the desired quality bound and
[wt] is the optimistic factor *)
let bound = Search_args.get_float "Dwa_optimistic.no_dups" args 0
and wt = Search_args.get_float "Dwa_optimistic.no_dups" args 1 in
let search_interface = Search_interface.make
~node_expand:(make_expand sface.Search_interface.domain_expand
sface.Search_interface.hd wt
(sface.Search_interface.d sface.Search_interface.initial))
~key:(wrap sface.Search_interface.key)
~goal_p:(wrap sface.Search_interface.goal_p)
~halt_on:sface.Search_interface.halt_on
~hash:sface.Search_interface.hash
~equals:sface.Search_interface.equals
sface.Search_interface.domain
{ fp = neg_infinity;
h = neg_infinity;
g = 0.;
ppos = Dpq.no_position;
fpos = Dpq.no_position;
dpos = Dpq.no_position;
data = sface.Search_interface.initial}
better_p
(Limit.make_default_logger (fun n -> n.g +. n.h)
(wrap sface.Search_interface.get_sol_length)) in
Limit.unwrap_sol5 unwrap_sol
(Optimistic_framework.no_dups
search_interface
get_node
ordered_p
bound
better_p
ordered_f
set_pq_pos
set_f_pos)
let dups sface args =
(** Performs DwA* optimistic search on domains with duplicates.
[sface] is the search interface, [bound] is the desired quality bound and
[wt] is the optimistic factor *)
let bound = Search_args.get_float "Dwa_optimistic.dups" args 0
and wt = Search_args.get_float "Dwa_optimistic.dups" args 1 in
let search_interface = Search_interface.make
~node_expand:(make_expand sface.Search_interface.domain_expand
sface.Search_interface.hd wt
(sface.Search_interface.d sface.Search_interface.initial))
~key:(wrap sface.Search_interface.key)
~goal_p:(wrap sface.Search_interface.goal_p)
~halt_on:sface.Search_interface.halt_on
~hash:sface.Search_interface.hash
~equals:sface.Search_interface.equals
sface.Search_interface.domain
{ fp = neg_infinity;
h = neg_infinity;
g = 0.;
ppos = Dpq.no_position;
fpos = Dpq.no_position;
dpos = Dpq.no_position;
data = sface.Search_interface.initial}
better_p
(Limit.make_default_logger (fun n -> n.g +. n.h)
(wrap sface.Search_interface.get_sol_length)) in
Limit.unwrap_sol6 unwrap_sol
(Optimistic_framework.dups
search_interface
get_node
ordered_p
bound
better_p
ordered_f
set_pq_pos
set_f_pos
get_pq_pos
get_f_pos)
let delay_dups sface args =
(** Performs DwA* optimistic search on domains with duplicates.
[sface] is the search interface, [bound] is the desired quality bound and
[wt] is the optimistic factor. Duplicate nodes are not explored until
the cleanup phase of the search*)
let bound = Search_args.get_float "Dwa_optimistic.delay_dups" args 0
and wt = Search_args.get_float "Dwa_optimistic.delay_dups" args 1 in
let search_interface = Search_interface.make
~node_expand:(make_expand sface.Search_interface.domain_expand
sface.Search_interface.hd wt
(sface.Search_interface.d sface.Search_interface.initial))
~key:(wrap sface.Search_interface.key)
~goal_p:(wrap sface.Search_interface.goal_p)
~halt_on:sface.Search_interface.halt_on
~hash:sface.Search_interface.hash
~equals:sface.Search_interface.equals
sface.Search_interface.domain
{ fp = neg_infinity;
h = neg_infinity;
g = 0.;
ppos = Dpq.no_position;
fpos = Dpq.no_position;
dpos = Dpq.no_position;
data = sface.Search_interface.initial}
better_p
(Limit.make_default_logger (fun n -> n.g +. n.h)
(wrap sface.Search_interface.get_sol_length)) in
Limit.unwrap_sol6 unwrap_sol
(Optimistic_framework.delay
search_interface
get_node
ordered_p
bound
better_p
ordered_f
set_pq_pos
set_d_pos
set_f_pos
get_pq_pos
get_d_pos
get_f_pos)
EOF
| null | https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/search/optimistic/dwa_optimistic.ml | ocaml | * Optimistic Search
* Takes the [expand] function for the domain nodes and converts it into
an expand function which will operate on search nodes. [hd] is a cost
distance estimator. [wt] is the optimistic weight, and [initial_d] is
the estimated distance from the root node to a goal.
*************************************************************************
* Performs DwA* optimistic search on domains with few / no duplicates.
[sface] is the search interface, [bound] is the desired quality bound and
[wt] is the optimistic factor
* Performs DwA* optimistic search on domains with duplicates.
[sface] is the search interface, [bound] is the desired quality bound and
[wt] is the optimistic factor
* Performs DwA* optimistic search on domains with duplicates.
[sface] is the search interface, [bound] is the desired quality bound and
[wt] is the optimistic factor. Duplicate nodes are not explored until
the cleanup phase of the search |
open Optimistic_search
let make_expand expand hd wt initial_d =
let make_child =
(fun (n, g) ->
let h,d = hd n in
let factor = Math.fmax 1.
(Math.fmin wt (wt *. (d /. initial_d))) in
{ fp = g +. factor *. h;
h = h;
g = g;
fpos = Dpq.no_position;
ppos = Dpq.no_position;
dpos = Dpq.no_position;
data = n;}) in
(fun parent ->
List.map make_child (expand parent.data parent.g))
let no_dups sface args =
let bound = Search_args.get_float "Dwa_optimistic.no_dups" args 0
and wt = Search_args.get_float "Dwa_optimistic.no_dups" args 1 in
let search_interface = Search_interface.make
~node_expand:(make_expand sface.Search_interface.domain_expand
sface.Search_interface.hd wt
(sface.Search_interface.d sface.Search_interface.initial))
~key:(wrap sface.Search_interface.key)
~goal_p:(wrap sface.Search_interface.goal_p)
~halt_on:sface.Search_interface.halt_on
~hash:sface.Search_interface.hash
~equals:sface.Search_interface.equals
sface.Search_interface.domain
{ fp = neg_infinity;
h = neg_infinity;
g = 0.;
ppos = Dpq.no_position;
fpos = Dpq.no_position;
dpos = Dpq.no_position;
data = sface.Search_interface.initial}
better_p
(Limit.make_default_logger (fun n -> n.g +. n.h)
(wrap sface.Search_interface.get_sol_length)) in
Limit.unwrap_sol5 unwrap_sol
(Optimistic_framework.no_dups
search_interface
get_node
ordered_p
bound
better_p
ordered_f
set_pq_pos
set_f_pos)
let dups sface args =
let bound = Search_args.get_float "Dwa_optimistic.dups" args 0
and wt = Search_args.get_float "Dwa_optimistic.dups" args 1 in
let search_interface = Search_interface.make
~node_expand:(make_expand sface.Search_interface.domain_expand
sface.Search_interface.hd wt
(sface.Search_interface.d sface.Search_interface.initial))
~key:(wrap sface.Search_interface.key)
~goal_p:(wrap sface.Search_interface.goal_p)
~halt_on:sface.Search_interface.halt_on
~hash:sface.Search_interface.hash
~equals:sface.Search_interface.equals
sface.Search_interface.domain
{ fp = neg_infinity;
h = neg_infinity;
g = 0.;
ppos = Dpq.no_position;
fpos = Dpq.no_position;
dpos = Dpq.no_position;
data = sface.Search_interface.initial}
better_p
(Limit.make_default_logger (fun n -> n.g +. n.h)
(wrap sface.Search_interface.get_sol_length)) in
Limit.unwrap_sol6 unwrap_sol
(Optimistic_framework.dups
search_interface
get_node
ordered_p
bound
better_p
ordered_f
set_pq_pos
set_f_pos
get_pq_pos
get_f_pos)
let delay_dups sface args =
let bound = Search_args.get_float "Dwa_optimistic.delay_dups" args 0
and wt = Search_args.get_float "Dwa_optimistic.delay_dups" args 1 in
let search_interface = Search_interface.make
~node_expand:(make_expand sface.Search_interface.domain_expand
sface.Search_interface.hd wt
(sface.Search_interface.d sface.Search_interface.initial))
~key:(wrap sface.Search_interface.key)
~goal_p:(wrap sface.Search_interface.goal_p)
~halt_on:sface.Search_interface.halt_on
~hash:sface.Search_interface.hash
~equals:sface.Search_interface.equals
sface.Search_interface.domain
{ fp = neg_infinity;
h = neg_infinity;
g = 0.;
ppos = Dpq.no_position;
fpos = Dpq.no_position;
dpos = Dpq.no_position;
data = sface.Search_interface.initial}
better_p
(Limit.make_default_logger (fun n -> n.g +. n.h)
(wrap sface.Search_interface.get_sol_length)) in
Limit.unwrap_sol6 unwrap_sol
(Optimistic_framework.delay
search_interface
get_node
ordered_p
bound
better_p
ordered_f
set_pq_pos
set_d_pos
set_f_pos
get_pq_pos
get_d_pos
get_f_pos)
EOF
|
88512a0235dbe403269220ddf98d7a6e93e7143d9249b28241a10194daf4c851 | jacobobryant/mystery-cows | lib.clj | (ns cows.lib)
(defmacro capture-env [nspace]
`(capture-env* (ns-publics ~nspace)))
(defmacro defcursors [db & forms]
`(do
~@(for [[sym path] (partition 2 forms)]
`(defonce ~sym (rum.core/cursor-in ~db ~path)))))
(defn flatten-form [form]
(if (some #(% form)
[list?
#(instance? clojure.lang.IMapEntry %)
seq?
#(instance? clojure.lang.IRecord %)
coll?])
(mapcat flatten-form form)
(list form)))
(defn derivations [sources nspace & forms]
(->> (partition 2 forms)
(reduce
(fn [[defs sources] [sym form]]
(let [deps (->> form
flatten-form
(map sources)
(filter some?)
distinct
vec)
k (keyword (name nspace) (name sym))]
[(conj defs `(defonce ~sym (rum.core/derived-atom ~deps ~k
(fn ~deps
~form))))
(conj sources sym)]))
[[] (set sources)])
first))
(defmacro defderivations [& args]
`(do ~@(apply derivations args)))
| null | https://raw.githubusercontent.com/jacobobryant/mystery-cows/5edbab7d5ca5dcd8b14f855ae4665690d9b1387e/src/cows/lib.clj | clojure | (ns cows.lib)
(defmacro capture-env [nspace]
`(capture-env* (ns-publics ~nspace)))
(defmacro defcursors [db & forms]
`(do
~@(for [[sym path] (partition 2 forms)]
`(defonce ~sym (rum.core/cursor-in ~db ~path)))))
(defn flatten-form [form]
(if (some #(% form)
[list?
#(instance? clojure.lang.IMapEntry %)
seq?
#(instance? clojure.lang.IRecord %)
coll?])
(mapcat flatten-form form)
(list form)))
(defn derivations [sources nspace & forms]
(->> (partition 2 forms)
(reduce
(fn [[defs sources] [sym form]]
(let [deps (->> form
flatten-form
(map sources)
(filter some?)
distinct
vec)
k (keyword (name nspace) (name sym))]
[(conj defs `(defonce ~sym (rum.core/derived-atom ~deps ~k
(fn ~deps
~form))))
(conj sources sym)]))
[[] (set sources)])
first))
(defmacro defderivations [& args]
`(do ~@(apply derivations args)))
|
|
7dfe2c0940bb381849e46bb66ed0186e7bd843f70b2a2cc62accd6768654bc1c | xsc/kithara | config.clj | (ns kithara.config
"Lyra configuration builders."
(:import [net.jodah.lyra.config
RecoveryPolicies
RetryPolicies]
[net.jodah.lyra.util Duration]))
# # Helper Macro
(defn- generate-builder
[result-class method]
(if (sequential? method)
(let [[method-name _ & processors] method
this (with-meta 'this {:tag result-class})
param (gensym)]
`(fn [~this ~param]
(. ~this ~method-name
~@(for [processor processors]
(cond (= processor ::none) param
(sequential? processor) `(~@processor ~param)
:else `(~processor ~param))))))
(recur result-class [method])))
(defn- run-builders
[builders initial config]
(reduce
(fn [result [k v]]
(if-let [builder (get builders k)]
(builder result v)
result))
initial config))
(defn- generate-meta
[result-class mapping]
(let [max-len (+ 3 (apply max (map (comp count name key) mapping)))
padded-fmt (str "%-" max-len "s")
padded #(format padded-fmt %)
sep (apply str \: (repeat (dec max-len) \-))]
{:arglists '([] [configuration-map] [base configuration-map])
:tag result-class
:doc (str (apply str
"Generates a `" result-class "` (see Lyra documentation).\n\n"
"| " (padded "option") " | |\n"
"| " sep " | ------------ |\n"
(for [[k [f]] (sort-by key mapping)]
(format "| %s | delegates to `%s` |\n"
(padded (str "`" k "`"))
f)))
"\n`base` can be an instance of `" result-class "` in which case all "
"of the given options will be applied to it.")}))
(defmacro ^:private defconfig
"Creates a function that converts a value (e.g. a Clojure map) into a
configuration object."
[sym _ result-class mapping & [defaults]]
`(let [builders# ~(->> (for [[k method] mapping]
[k (generate-builder result-class method)])
(into {}))
defaults# ~defaults]
(doto (defn ~sym
([] (~sym {}))
([config#]
(if (instance? ~result-class config#)
config#
(or (some-> (get defaults# config#) (~sym))
(~sym (new ~result-class) config#))))
([initial# config#]
(run-builders builders# initial# config#)))
(alter-meta!
merge
(quote ~(generate-meta result-class mapping))))))
# # Converters
(defn- to-int
(^long [value] (int value))
(^long [k default value]
(to-int (get value k default))))
(defn- to-duration
(^Duration
[value]
(if (instance? Duration value)
value
(Duration/milliseconds value)))
(^Duration
[k default value]
(let [n (get value k default)]
(to-duration n))))
(defmacro ^:private varargs
[fully-qualified-class value]
(with-meta
`(into-array ~fully-qualified-class ~value)
{:tag (str "[L" fully-qualified-class ";")}))
(defmacro ^:private with
[f mapping value]
`(~f (let [v# ~value] (get ~mapping v# v#))))
(defmacro ^:private arg
[class value]
(with-meta
`(identity ~value)
{:tag class}))
;; ## RecoveryPolicy
(defconfig recovery-policy :> net.jodah.lyra.config.RecoveryPolicy
{:backoff
[withBackoff :<
(to-duration :min 1000)
(to-duration :max 30000)
(to-int :factor 2)]
:interval
[withInterval :< to-duration]
:max-attempts
[withMaxAttempts :< (with to-int {:always -1})]
:max-duration
[withMaxDuration :< to-duration]}
{:always (RecoveryPolicies/recoverAlways)
:never (RecoveryPolicies/recoverNever)})
# # Retry Policy
(defconfig retry-policy :> net.jodah.lyra.config.RetryPolicy
{:backoff
[withBackoff :<
(to-duration :min 1000)
(to-duration :max 30000)
(to-int :factor 2)]
:interval
[withInterval :< to-duration]
:max-attempts
[withMaxAttempts :< (with to-int {:always -1})]
:max-duration
[withMaxDuration :< to-duration]}
{:always (RetryPolicies/retryAlways)
:never (RetryPolicies/retryNever)})
;; ## Behaviour Config
(defconfig behaviour :> net.jodah.lyra.config.Config
{:recovery-policy [withRecoveryPolicy :< recovery-policy]
:retry-policy [withRetryPolicy :< retry-policy]
:queue-recovery? [withQueueRecovery :< boolean]
:exchange-recovery? [withExchangeRecovery :< boolean]
:consumer-recovery? [withConsumerRecovery :< boolean]
:connection-listeners [withConnectionListeners :< (varargs net.jodah.lyra.event.ConnectionListener)]
:channel-listeners [withChannelListeners :< (varargs net.jodah.lyra.event.ChannelListener)]
:consumer-listeners [withConsumerListeners :< (varargs net.jodah.lyra.event.ConsumerListener)]})
# # Connection Options
(defconfig connection :> net.jodah.lyra.ConnectionOptions
{;; node info
:addresses [withAddresses :< (varargs com.rabbitmq.client.Address)]
:address-str [withAddresses :< str]
:host [withHost :< str]
:hosts [withHosts :< (varargs java.lang.String)]
:port [withPort :< int]
:username [withUsername :< str]
:password [withPassword :< str]
:vhost [withVirtualHost :< str]
;; SSL
:ssl? [withSsl]
:ssl-context [withSslProtocol :< (arg javax.net.ssl.SSLContext)]
:ssl-protocol [withSslProtocol :< str]
;; client info
:name [withName :< str]
:properties [withClientProperties :< identity]
;; behaviour
:socket-factory [withSocketFactory :< identity]
:factory [withConnectionFactory :< identity]
:timeout [withConnectionTimeout :< (with to-duration {:none 0})]
:executor [withConsumerExecutor :< identity]
:heartbeat [withRequestedHeartbeat :< (with to-duration {:none 0})]})
| null | https://raw.githubusercontent.com/xsc/kithara/3394a9e9ef5e6e605637a74e070c7d24bfaf19cc/src/kithara/config.clj | clojure | ## RecoveryPolicy
## Behaviour Config
node info
SSL
client info
behaviour | (ns kithara.config
"Lyra configuration builders."
(:import [net.jodah.lyra.config
RecoveryPolicies
RetryPolicies]
[net.jodah.lyra.util Duration]))
# # Helper Macro
(defn- generate-builder
[result-class method]
(if (sequential? method)
(let [[method-name _ & processors] method
this (with-meta 'this {:tag result-class})
param (gensym)]
`(fn [~this ~param]
(. ~this ~method-name
~@(for [processor processors]
(cond (= processor ::none) param
(sequential? processor) `(~@processor ~param)
:else `(~processor ~param))))))
(recur result-class [method])))
(defn- run-builders
[builders initial config]
(reduce
(fn [result [k v]]
(if-let [builder (get builders k)]
(builder result v)
result))
initial config))
(defn- generate-meta
[result-class mapping]
(let [max-len (+ 3 (apply max (map (comp count name key) mapping)))
padded-fmt (str "%-" max-len "s")
padded #(format padded-fmt %)
sep (apply str \: (repeat (dec max-len) \-))]
{:arglists '([] [configuration-map] [base configuration-map])
:tag result-class
:doc (str (apply str
"Generates a `" result-class "` (see Lyra documentation).\n\n"
"| " (padded "option") " | |\n"
"| " sep " | ------------ |\n"
(for [[k [f]] (sort-by key mapping)]
(format "| %s | delegates to `%s` |\n"
(padded (str "`" k "`"))
f)))
"\n`base` can be an instance of `" result-class "` in which case all "
"of the given options will be applied to it.")}))
(defmacro ^:private defconfig
"Creates a function that converts a value (e.g. a Clojure map) into a
configuration object."
[sym _ result-class mapping & [defaults]]
`(let [builders# ~(->> (for [[k method] mapping]
[k (generate-builder result-class method)])
(into {}))
defaults# ~defaults]
(doto (defn ~sym
([] (~sym {}))
([config#]
(if (instance? ~result-class config#)
config#
(or (some-> (get defaults# config#) (~sym))
(~sym (new ~result-class) config#))))
([initial# config#]
(run-builders builders# initial# config#)))
(alter-meta!
merge
(quote ~(generate-meta result-class mapping))))))
# # Converters
(defn- to-int
(^long [value] (int value))
(^long [k default value]
(to-int (get value k default))))
(defn- to-duration
(^Duration
[value]
(if (instance? Duration value)
value
(Duration/milliseconds value)))
(^Duration
[k default value]
(let [n (get value k default)]
(to-duration n))))
(defmacro ^:private varargs
[fully-qualified-class value]
(with-meta
`(into-array ~fully-qualified-class ~value)
{:tag (str "[L" fully-qualified-class ";")}))
(defmacro ^:private with
[f mapping value]
`(~f (let [v# ~value] (get ~mapping v# v#))))
(defmacro ^:private arg
[class value]
(with-meta
`(identity ~value)
{:tag class}))
(defconfig recovery-policy :> net.jodah.lyra.config.RecoveryPolicy
{:backoff
[withBackoff :<
(to-duration :min 1000)
(to-duration :max 30000)
(to-int :factor 2)]
:interval
[withInterval :< to-duration]
:max-attempts
[withMaxAttempts :< (with to-int {:always -1})]
:max-duration
[withMaxDuration :< to-duration]}
{:always (RecoveryPolicies/recoverAlways)
:never (RecoveryPolicies/recoverNever)})
# # Retry Policy
(defconfig retry-policy :> net.jodah.lyra.config.RetryPolicy
{:backoff
[withBackoff :<
(to-duration :min 1000)
(to-duration :max 30000)
(to-int :factor 2)]
:interval
[withInterval :< to-duration]
:max-attempts
[withMaxAttempts :< (with to-int {:always -1})]
:max-duration
[withMaxDuration :< to-duration]}
{:always (RetryPolicies/retryAlways)
:never (RetryPolicies/retryNever)})
(defconfig behaviour :> net.jodah.lyra.config.Config
{:recovery-policy [withRecoveryPolicy :< recovery-policy]
:retry-policy [withRetryPolicy :< retry-policy]
:queue-recovery? [withQueueRecovery :< boolean]
:exchange-recovery? [withExchangeRecovery :< boolean]
:consumer-recovery? [withConsumerRecovery :< boolean]
:connection-listeners [withConnectionListeners :< (varargs net.jodah.lyra.event.ConnectionListener)]
:channel-listeners [withChannelListeners :< (varargs net.jodah.lyra.event.ChannelListener)]
:consumer-listeners [withConsumerListeners :< (varargs net.jodah.lyra.event.ConsumerListener)]})
# # Connection Options
(defconfig connection :> net.jodah.lyra.ConnectionOptions
:addresses [withAddresses :< (varargs com.rabbitmq.client.Address)]
:address-str [withAddresses :< str]
:host [withHost :< str]
:hosts [withHosts :< (varargs java.lang.String)]
:port [withPort :< int]
:username [withUsername :< str]
:password [withPassword :< str]
:vhost [withVirtualHost :< str]
:ssl? [withSsl]
:ssl-context [withSslProtocol :< (arg javax.net.ssl.SSLContext)]
:ssl-protocol [withSslProtocol :< str]
:name [withName :< str]
:properties [withClientProperties :< identity]
:socket-factory [withSocketFactory :< identity]
:factory [withConnectionFactory :< identity]
:timeout [withConnectionTimeout :< (with to-duration {:none 0})]
:executor [withConsumerExecutor :< identity]
:heartbeat [withRequestedHeartbeat :< (with to-duration {:none 0})]})
|
b6577564c87a45b2a66abe3feea8ed82553bdff565c9cab457596d676e4a6e48 | haskell-compat/base-compat | Repl.hs | {-# LANGUAGE PackageImports #-}
# OPTIONS_GHC -fno - warn - dodgy - exports -fno - warn - unused - imports #
| Reexports " Control . . Compat "
-- from a globally unique namespace.
module Control.Monad.Compat.Repl (
module Control.Monad.Compat
) where
import "this" Control.Monad.Compat
| null | https://raw.githubusercontent.com/haskell-compat/base-compat/847aa35c4142f529525ffc645cd035ddb23ce8ee/base-compat/src/Control/Monad/Compat/Repl.hs | haskell | # LANGUAGE PackageImports #
from a globally unique namespace. | # OPTIONS_GHC -fno - warn - dodgy - exports -fno - warn - unused - imports #
| Reexports " Control . . Compat "
module Control.Monad.Compat.Repl (
module Control.Monad.Compat
) where
import "this" Control.Monad.Compat
|
9d2026393f19b5b60331cb7f5fa2f45a599b35c31598bdd8ae1aa66580026545 | tlehman/sicp-exercises | ex-2.06.scm | Exercise 2.06 : In case representing pairs with procedures was n't
; mind-boggling enough, consider that, in a language that can
; manipulate procedures, we can get by without numbers by implementing
0 and the operation of adding 1 as :
\sz.z
(define zero (lambda (s)
(lambda (z) z))
; \nfx.f(nfx)
(define add-1 (lambda (n)
(lambda (f)
(lambda (x)
(f ((n f) x))))))
; This representation is know as Church numerals, after its inventor,
Alonzo Church , the logician who invented lambda calculus .
;
( 2.06 ) Define 1 and 2 directly :
( add-1 zero )
;; (lambda (f)
;; (lambda (x)
( f ( ( zero f ) x ) ) ) )
;; (lambda (f)
;; (lambda (x)
;; (f (id x))))
;; (lambda (f)
;; (lambda (x)
;; (f x)))
(define one (lambda (f)
(lambda (x)
(f x))))
(define two (lambda (f)
(lambda (x)
(f (f x)))))
; Give a direct definition of the addition procedure +
(define (+ a b)
((a add-1) b))
From ' " A Tutorial Introduction to the Lambda Calculus " ,
;; /~gupta/courses/apl/lambda.pdf
;;
Addition of Church numerals a and b was derived using the successor
;; function S as ((aS)b)
| null | https://raw.githubusercontent.com/tlehman/sicp-exercises/57151ec07d09a98318e91c83b6eacaa49361d156/ex-2.06.scm | scheme | mind-boggling enough, consider that, in a language that can
manipulate procedures, we can get by without numbers by implementing
\nfx.f(nfx)
This representation is know as Church numerals, after its inventor,
(lambda (f)
(lambda (x)
(lambda (f)
(lambda (x)
(f (id x))))
(lambda (f)
(lambda (x)
(f x)))
Give a direct definition of the addition procedure +
/~gupta/courses/apl/lambda.pdf
function S as ((aS)b) | Exercise 2.06 : In case representing pairs with procedures was n't
0 and the operation of adding 1 as :
\sz.z
(define zero (lambda (s)
(lambda (z) z))
(define add-1 (lambda (n)
(lambda (f)
(lambda (x)
(f ((n f) x))))))
Alonzo Church , the logician who invented lambda calculus .
( 2.06 ) Define 1 and 2 directly :
( add-1 zero )
( f ( ( zero f ) x ) ) ) )
(define one (lambda (f)
(lambda (x)
(f x))))
(define two (lambda (f)
(lambda (x)
(f (f x)))))
(define (+ a b)
((a add-1) b))
From ' " A Tutorial Introduction to the Lambda Calculus " ,
Addition of Church numerals a and b was derived using the successor
|
6d64ad46cd84181f63e7800ea16acc502e823d77af03aeab1b704cad99cca1ed | realworldocaml/book | ext_pointer.ml | * [ Ext_pointer ] uses values of the OCaml type " int " to represent pointers to 2 - byte
aligned memory blocks allocated outside the OCaml heap .
The least significant bit of the address of a 2 - byte aligned memory block is 0 .
This bit is used by this library to represent the address as an OCaml int , which
prevents the OCaml GC from following pointers to external memory .
To encode an external pointer as int : set the least significant bit .
To decode int into an external pointer : clear the least significant bit .
Note that these encode and decode operations are not the same as tagging and untagging
operations on OCaml representation of int , which involves shifting .
[ Ext_pointer ] allows OCaml code to pass around and manipulate pointers to external
memory blocks without using " naked pointers " .
aligned memory blocks allocated outside the OCaml heap.
The least significant bit of the address of a 2-byte aligned memory block is 0.
This bit is used by this library to represent the address as an OCaml int, which
prevents the OCaml GC from following pointers to external memory.
To encode an external pointer as int: set the least significant bit.
To decode int into an external pointer: clear the least significant bit.
Note that these encode and decode operations are not the same as tagging and untagging
operations on OCaml representation of int, which involves shifting.
[Ext_pointer] allows OCaml code to pass around and manipulate pointers to external
memory blocks without using "naked pointers".
*)
type t = private int
external create : int -> t = "%identity"
module Immediate (V : sig
type t [@@immediate]
end) =
struct
(** [load_immediate t] assumes without checking that
the value pointed to by [t] is immediate. *)
external unsafe_load_immediate : t -> V.t = "caml_ext_pointer_load_immediate"
[@@noalloc] [@@builtin] [@@no_effects]
(** [store_int t i] stores the immediate [i] to the memory address
represented by [t]. *)
external store_immediate : t -> V.t -> unit = "caml_ext_pointer_store_immediate"
[@@noalloc] [@@builtin] [@@no_coeffects]
end
module Int = Immediate (Stdlib.Int)
module Bool = Immediate (Stdlib.Bool)
(** [load_int t] reads untagged int pointed to by [t] and returns
the corresponding tagged int.
This should only be used to read a value
written by [store_untagged_int]. Otherwise, if the value has most significant
bit set, it will be lost by tagging. To avoid it,
use [load_unboxed_nativeint] and check before converting to int
(should not allocate). The native C stub is the same for both.
*)
external load_untagged_int
: t
-> (int[@untagged])
= "caml_ext_pointer_load_untagged_int" "caml_ext_pointer_load_unboxed_nativeint"
[@@noalloc] [@@builtin] [@@no_effects]
(** [store_int t d] untags [d] and stores the result to the memory pointed to by
[t]. *)
external store_untagged_int
: t
-> (int[@untagged])
-> unit
= "caml_ext_pointer_store_untagged_int" "caml_ext_pointer_store_unboxed_nativeint"
[@@noalloc] [@@builtin] [@@no_coeffects]
(** [load_unboxed_nativeint t] reads unboxed nativeint pointed to by [t] and returns
the corresponding (boxed) nativeint allocated on the OCaml heap. *)
external load_unboxed_nativeint
: t
-> (nativeint[@unboxed])
= "caml_ext_pointer_load_unboxed_nativeint_bytecode" "caml_ext_pointer_load_unboxed_nativeint"
[@@noalloc] [@@builtin] [@@no_effects]
(** [store_unboxed_nativeint t d] stores the unboxed nativeint to the memory pointed to by
[t]. *)
external store_unboxed_nativeint
: t
-> (nativeint[@unboxed])
-> unit
= "caml_ext_pointer_store_unboxed_nativeint_bytecode" "caml_ext_pointer_store_unboxed_nativeint"
[@@noalloc] [@@builtin] [@@no_coeffects]
* [ load_unboxed_int64 t ] reads unboxed int64 pointed to by [ t ] and returns
the corresponding ( boxed ) int64 allocated on the OCaml heap .
the corresponding (boxed) int64 allocated on the OCaml heap. *)
external load_unboxed_int64
: t
-> (int64[@unboxed])
= "caml_ext_pointer_load_unboxed_int64_bytecode" "caml_ext_pointer_load_unboxed_int64"
[@@noalloc] [@@builtin] [@@no_effects]
* [ ] stores the unboxed int64 to the memory pointed to by [ t ] .
external store_unboxed_int64
: t
-> (int64[@unboxed])
-> unit
= "caml_ext_pointer_store_unboxed_int64_bytecode" "caml_ext_pointer_store_unboxed_int64"
[@@noalloc] [@@builtin] [@@no_coeffects]
(** [load_unboxed_int32 t] reads unboxed int32 pointed to by [t] and returns
the corresponding (boxed) int32 allocated on the OCaml heap. *)
external load_unboxed_int32
: t
-> (int32[@unboxed])
= "caml_ext_pointer_load_unboxed_int32_bytecode" "caml_ext_pointer_load_unboxed_int32"
[@@noalloc] [@@builtin] [@@no_effects]
(** [store_unboxed_int32 t d] stores the unboxed int32 to the memory pointed to by [t]. *)
external store_unboxed_int32
: t
-> (int32[@unboxed])
-> unit
= "caml_ext_pointer_store_unboxed_int32_bytecode" "caml_ext_pointer_store_unboxed_int32"
[@@noalloc] [@@builtin] [@@no_coeffects]
* For float operations , the pointer must be aligned at least to the native integer
machine width ( meaning on 32 - bit platforms , a 32 - bit - aligned pointer is acceptable
even though the width of the float is 64 bits ) .
machine width (meaning on 32-bit platforms, a 32-bit-aligned pointer is acceptable
even though the width of the float is 64 bits). *)
(** [load_unboxed_float t] reads the unboxed float pointed to by [t]. (If the result is
not directly passed to another operation expecting an unboxed float, then it will
be boxed.) *)
external load_unboxed_float
: t
-> (float[@unboxed])
= "caml_ext_pointer_load_unboxed_float_bytecode" "caml_ext_pointer_load_unboxed_float"
[@@noalloc] [@@builtin] [@@no_effects]
(** [store_unboxed_float t d] stores the unboxed float to the memory pointed to by [t]. *)
external store_unboxed_float
: t
-> (float[@unboxed])
-> unit
= "caml_ext_pointer_store_unboxed_float_bytecode" "caml_ext_pointer_store_unboxed_float"
[@@noalloc] [@@builtin] [@@no_coeffects]
| null | https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/ocaml_intrinsics/src/ext_pointer.ml | ocaml | * [load_immediate t] assumes without checking that
the value pointed to by [t] is immediate.
* [store_int t i] stores the immediate [i] to the memory address
represented by [t].
* [load_int t] reads untagged int pointed to by [t] and returns
the corresponding tagged int.
This should only be used to read a value
written by [store_untagged_int]. Otherwise, if the value has most significant
bit set, it will be lost by tagging. To avoid it,
use [load_unboxed_nativeint] and check before converting to int
(should not allocate). The native C stub is the same for both.
* [store_int t d] untags [d] and stores the result to the memory pointed to by
[t].
* [load_unboxed_nativeint t] reads unboxed nativeint pointed to by [t] and returns
the corresponding (boxed) nativeint allocated on the OCaml heap.
* [store_unboxed_nativeint t d] stores the unboxed nativeint to the memory pointed to by
[t].
* [load_unboxed_int32 t] reads unboxed int32 pointed to by [t] and returns
the corresponding (boxed) int32 allocated on the OCaml heap.
* [store_unboxed_int32 t d] stores the unboxed int32 to the memory pointed to by [t].
* [load_unboxed_float t] reads the unboxed float pointed to by [t]. (If the result is
not directly passed to another operation expecting an unboxed float, then it will
be boxed.)
* [store_unboxed_float t d] stores the unboxed float to the memory pointed to by [t]. | * [ Ext_pointer ] uses values of the OCaml type " int " to represent pointers to 2 - byte
aligned memory blocks allocated outside the OCaml heap .
The least significant bit of the address of a 2 - byte aligned memory block is 0 .
This bit is used by this library to represent the address as an OCaml int , which
prevents the OCaml GC from following pointers to external memory .
To encode an external pointer as int : set the least significant bit .
To decode int into an external pointer : clear the least significant bit .
Note that these encode and decode operations are not the same as tagging and untagging
operations on OCaml representation of int , which involves shifting .
[ Ext_pointer ] allows OCaml code to pass around and manipulate pointers to external
memory blocks without using " naked pointers " .
aligned memory blocks allocated outside the OCaml heap.
The least significant bit of the address of a 2-byte aligned memory block is 0.
This bit is used by this library to represent the address as an OCaml int, which
prevents the OCaml GC from following pointers to external memory.
To encode an external pointer as int: set the least significant bit.
To decode int into an external pointer: clear the least significant bit.
Note that these encode and decode operations are not the same as tagging and untagging
operations on OCaml representation of int, which involves shifting.
[Ext_pointer] allows OCaml code to pass around and manipulate pointers to external
memory blocks without using "naked pointers".
*)
type t = private int
external create : int -> t = "%identity"
module Immediate (V : sig
type t [@@immediate]
end) =
struct
external unsafe_load_immediate : t -> V.t = "caml_ext_pointer_load_immediate"
[@@noalloc] [@@builtin] [@@no_effects]
external store_immediate : t -> V.t -> unit = "caml_ext_pointer_store_immediate"
[@@noalloc] [@@builtin] [@@no_coeffects]
end
module Int = Immediate (Stdlib.Int)
module Bool = Immediate (Stdlib.Bool)
external load_untagged_int
: t
-> (int[@untagged])
= "caml_ext_pointer_load_untagged_int" "caml_ext_pointer_load_unboxed_nativeint"
[@@noalloc] [@@builtin] [@@no_effects]
external store_untagged_int
: t
-> (int[@untagged])
-> unit
= "caml_ext_pointer_store_untagged_int" "caml_ext_pointer_store_unboxed_nativeint"
[@@noalloc] [@@builtin] [@@no_coeffects]
external load_unboxed_nativeint
: t
-> (nativeint[@unboxed])
= "caml_ext_pointer_load_unboxed_nativeint_bytecode" "caml_ext_pointer_load_unboxed_nativeint"
[@@noalloc] [@@builtin] [@@no_effects]
external store_unboxed_nativeint
: t
-> (nativeint[@unboxed])
-> unit
= "caml_ext_pointer_store_unboxed_nativeint_bytecode" "caml_ext_pointer_store_unboxed_nativeint"
[@@noalloc] [@@builtin] [@@no_coeffects]
* [ load_unboxed_int64 t ] reads unboxed int64 pointed to by [ t ] and returns
the corresponding ( boxed ) int64 allocated on the OCaml heap .
the corresponding (boxed) int64 allocated on the OCaml heap. *)
external load_unboxed_int64
: t
-> (int64[@unboxed])
= "caml_ext_pointer_load_unboxed_int64_bytecode" "caml_ext_pointer_load_unboxed_int64"
[@@noalloc] [@@builtin] [@@no_effects]
* [ ] stores the unboxed int64 to the memory pointed to by [ t ] .
external store_unboxed_int64
: t
-> (int64[@unboxed])
-> unit
= "caml_ext_pointer_store_unboxed_int64_bytecode" "caml_ext_pointer_store_unboxed_int64"
[@@noalloc] [@@builtin] [@@no_coeffects]
external load_unboxed_int32
: t
-> (int32[@unboxed])
= "caml_ext_pointer_load_unboxed_int32_bytecode" "caml_ext_pointer_load_unboxed_int32"
[@@noalloc] [@@builtin] [@@no_effects]
external store_unboxed_int32
: t
-> (int32[@unboxed])
-> unit
= "caml_ext_pointer_store_unboxed_int32_bytecode" "caml_ext_pointer_store_unboxed_int32"
[@@noalloc] [@@builtin] [@@no_coeffects]
* For float operations , the pointer must be aligned at least to the native integer
machine width ( meaning on 32 - bit platforms , a 32 - bit - aligned pointer is acceptable
even though the width of the float is 64 bits ) .
machine width (meaning on 32-bit platforms, a 32-bit-aligned pointer is acceptable
even though the width of the float is 64 bits). *)
external load_unboxed_float
: t
-> (float[@unboxed])
= "caml_ext_pointer_load_unboxed_float_bytecode" "caml_ext_pointer_load_unboxed_float"
[@@noalloc] [@@builtin] [@@no_effects]
external store_unboxed_float
: t
-> (float[@unboxed])
-> unit
= "caml_ext_pointer_store_unboxed_float_bytecode" "caml_ext_pointer_store_unboxed_float"
[@@noalloc] [@@builtin] [@@no_coeffects]
|
0e39adb3d37bd4d98d6b56d665549e1e4edee806fefb741d38880af772f37df6 | malcolmreynolds/GSLL | bernoulli.lisp | Regression test BERNOULLI for GSLL , automatically generated
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST BERNOULLI
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST (LIST 0 1 1 0 1 1 0 0 0 0 0))
(MULTIPLE-VALUE-LIST
(LET ((RNG (MAKE-RANDOM-NUMBER-GENERATOR +MT19937+ 0)))
(LOOP FOR I FROM 0 TO 10 COLLECT
(sample rng 'bernoulli :probability 0.5d0)))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0.5d0)
(MULTIPLE-VALUE-LIST (BERNOULLI-PDF 0 0.5d0))))
| null | https://raw.githubusercontent.com/malcolmreynolds/GSLL/2f722f12f1d08e1b9550a46e2a22adba8e1e52c4/tests/bernoulli.lisp | lisp | Regression test BERNOULLI for GSLL , automatically generated
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST BERNOULLI
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST (LIST 0 1 1 0 1 1 0 0 0 0 0))
(MULTIPLE-VALUE-LIST
(LET ((RNG (MAKE-RANDOM-NUMBER-GENERATOR +MT19937+ 0)))
(LOOP FOR I FROM 0 TO 10 COLLECT
(sample rng 'bernoulli :probability 0.5d0)))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0.5d0)
(MULTIPLE-VALUE-LIST (BERNOULLI-PDF 0 0.5d0))))
|
|
604dd33a935824d588ab45ff7d0880ad24a10cb5aa71a0704d0380dc2bdb5b76 | nasa/pvslib | patch-20210421-prooflite.lisp | ;;
;; prooflite.lisp
Release : ( 11/05/20 )
;;
Contact : ( )
NASA Langley Research Center
;;
;;
Copyright ( c ) 2011 - 2012 United States Government as represented by
the National Aeronautics and Space Administration . No copyright
is claimed in the United States under Title 17 , U.S.Code . All Other
;; Rights Reserved.
;;
(defparameter *prooflite-version* "7.1.0 (Nov 05, 2020)")
(defun associate-proof-with-formulas (theory-name formula-name strategy force
&optional
(overwrite-default-proof? t)
(save-prf-file? t))
overwrite - default - proof ? is meaninless if force is nil
(let ((theory (get-typechecked-theory theory-name)))
(if theory
(let* ((fname (match-formula-name formula-name))
(name (car fname))
(args (cdr fname)))
(if fname
(let* ((regexp (expand-rex name))
(str (if force "" "untried "))
(fdecls (remove-if-not
#'(lambda (d)
(and (formula-decl? d)
(let ((idstr (format nil "~a" (id d))))
(and (or (not (proofs d)) force)
(pregexp-match regexp idstr)))))
(all-decls theory))))
(if fdecls
(associate-proof-with-formula
theory regexp (instantiate-script strategy args 1 "#")
fdecls
overwrite-default-proof?
save-prf-file?)
(pvs-message
"\"~a\" does not match any ~aformula" name str)))
(pvs-message
"\"~a\" is not a valid proof script header" formula-name)))
(pvs-message "Theory ~a not found" theory-name))))
(defun associate-proof-with-formula (theory regexp strategy fdecls
&optional
(overwrite-default-proof? t)
(save-prf-file? t))
"This function overwrites the default proof in FDECLS if OVERWRITE-DEFAULT-PROOF? is t (default)."
(when fdecls
(let* ((fdecl (car fdecls))
(match (pregexp-match regexp (format nil "~a" (id fdecl))))
(script (instantiate-script strategy match 0 "\\$")))
(multiple-value-bind (strat err)
#+(and allegro (not pvs6) (not pvs7))
(unwind-protect
(progn (excl:set-case-mode :case-insensitive-lower)
(ignore-errors (values (read-from-string script))))
(excl:set-case-mode :case-sensitive-lower))
#-(and allegro (not pvs6) (not pvs7))
(ignore-errors (values (read-from-string script)))
(let ((just (unless err
(or (revert-justification strat)
(revert-justification (list "" strat))
strat))))
(unless just
(type-error script
"Bad form for script~% ~s" script))
(if overwrite-default-proof?
(setf (justification fdecl) just)
(let ((nextid (next-proof-id fdecl)))
(format t "~%~a~%" nextid)
(make-default-proof fdecl (extract-justification-sexp just) nextid)))
;; Save proof to prf file only if requested
(when save-prf-file?
(save-all-proofs theory))
(pvs-message "Proof script ~a was installed" (id fdecl)))))
(associate-proof-with-formula theory regexp strategy (cdr fdecls))))
Returns a list of theory names defined in a PVS file
(defun theories-in-file (file)
gethash returns a list of form ( date th1 th2 ... ) , where date is the
;; time the file was parsed.
(cdr (gethash file (current-pvs-files))))
;; Returns a list of theories imported in theory-names
(defun imported-theories-in-theories (theory-names)
(remove-duplicates
(mapcan #'(lambda (theo) (imported-theories-in-theory theo))
theory-names)))
(defun my-collect-theory-usings (theory)
(unless (or (memq theory *modules-visited*)
(from-prelude? theory)
(lib-datatype-or-theory? theory))
(push theory *modules-visited*)
(dolist (use (get-immediate-usings theory))
(let ((th (get-theory use)))
(when th
(my-collect-theory-usings
(if (typep th 'rectype-theory)
(get-typechecked-theory (generated-by th))
th)))))))
;; Returns a list of immediately imported theories in the theory-name
(defun immediate-theories-in-theory (theory-name)
(let ((theory (get-typechecked-theory theory-name)))
(when theory
(remove-duplicates
(loop for use in (get-immediate-usings theory)
for th = (get-theory use)
when th
unless (from-prelude? th)
collect (if (typep th 'rectype-theory)
(get-typechecked-theory (generated-by th))
th))))))
;; Returns a list of theories imported in the theory-name
(defun imported-theories-in-theory (theory-name)
(let ((theory (get-typechecked-theory theory-name)))
(when theory
(let* ((*modules-visited* nil))
(my-collect-theory-usings theory)
(nreverse *modules-visited*)))))
(defun trim-left (str)
(string-left-trim '(#\Space #\Tab) str))
(defun trim-right (str)
(string-right-trim '(#\Space #\Tab) str))
(defun trim (str)
(string-trim '(#\Space #\Tab) str))
(defun ident () "([\\w\\*?]+)")
(defun spaces () "[\\s\\t]*")
(defun greedyspaces () "(?<!\\s\\t)[\\s\\t]*(?!\\s\\t)")
(defun replace-all-str (string part replacement &key (test #'char=))
"Returns a new string in which all the occurences of the part
is replaced with replacement."
(with-output-to-string (out)
(loop with part-length = (length part)
for old-pos = 0 then (+ pos part-length)
for pos = (search part string
:start2 old-pos
:test test)
do (write-string string out
:start old-pos
:end (or pos (length string)))
when pos do (write-string replacement out)
while pos)))
(defun expand-rex (str)
(format nil "^~a$" (replace-all-str (pregexp-replace* "*" str "(.+)") "?" "\\?")))
(defun read-one-line (file)
(let* ((str (read-line file nil nil))
(strim (when str (trim str))))
(cond ((and (> (length strim) 3) (string= strim "%|-" :end1 3))
strim)
((and (> (length strim) 0) (char= (elt strim 0) #\%))
"%")
(strim ""))))
(defun match-formula-name (str)
(let ((match (cdr (pregexp-match
(format nil "^~a(?:$|~a\\[(.*)\\]$)"
(ident) (greedyspaces))
str))))
(when match
(let* ((name (car match))
(argstr (cadr match))
(args (when argstr (pregexp-split ";" (trim argstr))))
(nargs (when args (mapcar #'(lambda (x) (trim x)) args))))
(cons name nargs)))))
(defun is-proof-comment (str)
(when (> (length str) 3) (trim-left (subseq str 3))))
(defun is-comment (str) (> (length str) 0))
(defun match-proof (str)
(let ((match (pregexp-match-positions
(format nil "^(.+):~a(?i:proof)\\b" (spaces))
str)))
(when match
(cons (trim-right (subseq str (caadr match) (cdadr match)))
(trim (subseq str (cdar match) (length str)))))))
(defun match-qed (str)
(let ((match (pregexp-match "^(.*)\\b(?i:qed).*$" str)))
(when match
(trim (cadr match)))))
(defun install-script (theory script formulas force &optional (overwrite-default-proof? t) (save-prf-file? t))
(let ((strategy (format nil "(\"\" ~a)" script)))
(multiple-value-bind (strat err)
(ignore-errors (values (read-from-string strategy)))
(if err
(pvs-error "Prooflite script error"
(format nil "Error in script for formula ~{~a~^, ~}: ~a." formulas err))
(multiple-value-bind (msg subjust)
(check-edited-justification strat)
(if msg
(pvs-error
"Proof syntax error"
(format nil
"Error in script for formula ~{~a~^, ~}: ~a ~@[(Offending proof part: ~s)~]"
formulas
(or msg "Proof syntax error")
subjust))
(when formulas
(associate-proof-with-formulas
theory
(car formulas)
strategy
force
overwrite-default-proof?
save-prf-file?)
(install-script theory script (cdr formulas) force overwrite-default-proof? save-prf-file?))))))))
(defun new-script (script new)
(let ((notempty (> (length new) 0)))
(cond ((and script notempty)
(format nil "~a ~a" script new))
(script script)
(notempty new))))
(defun instantiate-script (script args n str)
(if args
(let ((new (pregexp-replace* (format nil "~a~a" str n) script
(car args))))
(instantiate-script new (cdr args) (+ n 1) str))
script))
(defun install-prooflite-scripts (filename theory line force)
(with-open-file
(file (make-specpath filename) :direction :input)
(let* ((loc (place (get-theory theory)))
(lfrom (aref loc 0))
(lto (aref loc 2)))
(loop repeat (- lfrom 1) do (read-line file nil nil))
(if (= line 0)
(pvs-message "Installing inlined proof scripts into theory ~a."
theory)
(pvs-message "Installing proof script at line ~a of file ~a."
line filename))
(do ((str (read-one-line file))
(n lfrom)
(formulas)
(script))
((or (null str) (> n lto)))
(let ((proofcomment (is-proof-comment str)))
(cond (proofcomment
(let* ((proof (match-proof proofcomment))
(formula (car proof))
(qed (match-qed proofcomment)))
(cond
(formula
(when (and script (< line n))
(pvs-message
"QED is missing in proof script(s) ~a [Theory: ~a]"
formulas theory))
(setq str (format nil "%|-~a" (cdr proof)))
(setq formulas (cons formula
(when (not script) formulas)))
(setq script nil))
(qed
(let ((newscript (new-script script qed)))
(when (and newscript formulas (<= line n))
(install-script theory newscript
(reverse formulas)
force))
(cond ((or (= line 0) (< n line))
(setq str (read-one-line file))
(setq n (+ n 1))
(setq formulas nil)
(setq script nil))
((not formulas)
(pvs-message
"No script was installed [Theory: ~a]"
theory)
(setq str nil))
(t (setq str nil)))))
(t (setq str (read-one-line file))
(setq n (+ n 1))
(setq script (new-script script proofcomment))))))
((is-comment str)
(setq str (read-one-line file))
(setq n (+ n 1)))
(t
(when (and formulas (< line n))
(pvs-error
"Prooflite script error"
(format
nil
"QED is missing in proof script~:[~;s~] ~{~#[~;~a~;~a and ~a~:;~@{~a~#[~;, and ~:;, ~]~}~]~} [Theory: ~a]"
(cadr formulas)
formulas theory)))
(cond ((or (= line 0) (< n line))
(setq str (read-one-line file))
(setq n (+ n 1))
(setq formulas nil)
(setq script nil))
((and (< 0 line) (or (not formulas) (= line n)))
(pvs-message "No script was installed [Theory: ~a]"
theory)
(setq str nil))
(t (setq str nil))))))))))
(defun install-prooflite-scripts-from-prl-file (theory prl-filename force &optional (plain-script? t))
"Installs all the prooflite scripts from a file called PRL-FILENAME into the theory THEORY.
It assumes that the prl file exists and that theory is not nil."
(let((at-least-one-script-saved? nil))
(with-open-file
(file prl-filename :direction :input)
(do ((str (read-line file nil))
(formulas)
(script))
((null str))
(let ((proofcomment (if plain-script?
(pregexp-replace "\%.*" (trim-left str) "")
(is-proof-comment str))))
(cond (proofcomment
(let* ((proof (match-proof proofcomment))
(formula (car proof))
(qed (match-qed proofcomment)))
(cond
(formula
(when script
(pvs-error
"Prooflite script error"
(format
nil
"QED is missing in proof script~:[~;s~] ~{~#[~;~a~;~a and ~a~:;~@{~a~#[~;, and ~:;, ~]~}~]~} [Theory: ~a]"
(cadr formulas)
formulas theory)))
(setq str (format nil "~a" (cdr proof)))
(setq formulas (cons formula
(when (not script) formulas)))
(setq script nil))
(qed
(let ((newscript (new-script script qed)))
(when (and newscript formulas)
(install-script theory newscript
(reverse formulas)
force
t
nil)
(setq at-least-one-script-saved? t))
(cond ((not formulas)
(pvs-message
"No script was installed [Theory: ~a]"
theory)
(setq str nil))
(t
(setq str (read-line file nil))
(setq formulas nil)
(setq script nil)))))
(t (setq str (read-line file nil))
(setq script (new-script script proofcomment))))))
((is-comment str)
(setq str (read-line file nil)))
(t
(when formulas
(pvs-error
"Prooflite script error"
(format
nil
"QED is missing in proof script~:[~;s~] ~{~#[~;~a~;~a and ~a~:;~@{~a~#[~;, and ~:;, ~]~}~]~} [Theory: ~a]"
(cadr formulas)
formulas theory)))
(setq str (read-line file nil))
(setq formulas nil)
(setq script nil)))))
(when at-least-one-script-saved? (save-all-proofs)))))
(defun then-prooflite (script)
(cond ((and
(cdr script)
(null (cddr script))
(listp (caadr script)))
(list (list 'spread
(car script)
(mapcar #'(lambda (s) (to-prooflite (cdr s)))
(cadr script)))))
(script
(cons (car script) (then-prooflite (cdr script))))))
(defun to-prooflite (script)
(cond ((null (cdr script))
(car script))
((and (null (cddr script))
(listp (caadr script)))
(car (then-prooflite script)))
(t
(cons 'then (then-prooflite script)))))
(defun prooflite-script (fdecl)
(when fdecl
(if (justification fdecl)
(to-prooflite (cdr (editable-justification
(justification fdecl))))
(list 'postpone))))
(defun proof-to-prooflite-script (name line)
(let* ((fdecl (formula-decl-to-prove name nil line "pvs")))
(when fdecl
(pvs-buffer
"ProofLite"
(with-output-to-string
(out)
(write-prooflite-script fdecl out)))
(list (aref (place fdecl) 2)))))
(defun find-formula (theory-name formula)
(let ((theory (get-typechecked-theory theory-name)))
(when theory
(find-if #'(lambda (d) (and (formula-decl? d)
(string= (format nil "~a" (id d))
formula)))
(all-decls theory)))))
(defun all-decl-names (theory-name)
(let ((theory (get-typechecked-theory theory-name)))
(when theory
(mapcar #'(lambda (d) (format nil "~a" (id d)))
(remove-if-not #'(lambda (d) (formula-decl? d))
(all-decls theory))))))
(defun display-prooflite-script (theory formula)
(let* ((fdecl (find-formula theory formula)))
(when fdecl
(pvs-buffer
"ProofLite"
(with-output-to-string
(out)
(write-prooflite-script fdecl out))))))
(defun write-prooflite-script (fdecl &optional (outstream t))
(format outstream "~a : PROOF~%" (id fdecl))
(write (prooflite-script fdecl)
:stream outstream :pretty t :escape t
:level nil :length nil
:pprint-dispatch *proof-script-pprint-dispatch*)
(format outstream "~%QED ~a~%" (id fdecl)))
(defun get-prooflite-file-name (theory)
(format nil "~a.prl" (id theory)))
(defun write-all-prooflite-scripts-to-file (theoryname)
"Writes the proofscripts of all declarations in the theory (including TCCs) into a file called \"<filename>__<theoryname>.prl\", where <filename> is the name of the file where the theory is defined. This function overwrites the \"prl\" file if it already exists. It returns the filename of the produced file on success and nil on error."
(let((theory (get-typechecked-theory theoryname)))
(if theory
(let ((prl-filename (get-prooflite-file-name theory)))
(pvs-message "Storing proofs from theory \"~a\" into file \"~a\"." (id theory) prl-filename)
(handler-case
(with-open-file
(outs prl-filename
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(loop for d in (all-decls theory)
when (and (formula-decl? d) (not (or (axiom? d) (assumption? d))))
do (write-prooflite-script d outs)
finally (return prl-filename)))
(file-error
(e)
(pvs-error "File error" (format nil "Error: Could not write into ~a.~%" (file-error-pathname e)))
nil)))
(pvs-error "Theory not found" (format nil "Error: Theory ~a not found in context.~%" theoryname)))))
(defun get-default-proof-script (theory-name formula)
(let ((formula-declaration (find-formula theory-name formula)))
(when (and formula-declaration (justification formula-declaration))
(format t "~a" (get-proof-script-output-string formula-declaration nil))))
(values))
| null | https://raw.githubusercontent.com/nasa/pvslib/d3601073537a52eb99946a94d1563760cdd5272b/pvs-patches/patch-20210421-prooflite.lisp | lisp |
prooflite.lisp
Rights Reserved.
Save proof to prf file only if requested
time the file was parsed.
Returns a list of theories imported in theory-names
Returns a list of immediately imported theories in the theory-name
Returns a list of theories imported in the theory-name | Release : ( 11/05/20 )
Contact : ( )
NASA Langley Research Center
Copyright ( c ) 2011 - 2012 United States Government as represented by
the National Aeronautics and Space Administration . No copyright
is claimed in the United States under Title 17 , U.S.Code . All Other
(defparameter *prooflite-version* "7.1.0 (Nov 05, 2020)")
(defun associate-proof-with-formulas (theory-name formula-name strategy force
&optional
(overwrite-default-proof? t)
(save-prf-file? t))
overwrite - default - proof ? is meaninless if force is nil
(let ((theory (get-typechecked-theory theory-name)))
(if theory
(let* ((fname (match-formula-name formula-name))
(name (car fname))
(args (cdr fname)))
(if fname
(let* ((regexp (expand-rex name))
(str (if force "" "untried "))
(fdecls (remove-if-not
#'(lambda (d)
(and (formula-decl? d)
(let ((idstr (format nil "~a" (id d))))
(and (or (not (proofs d)) force)
(pregexp-match regexp idstr)))))
(all-decls theory))))
(if fdecls
(associate-proof-with-formula
theory regexp (instantiate-script strategy args 1 "#")
fdecls
overwrite-default-proof?
save-prf-file?)
(pvs-message
"\"~a\" does not match any ~aformula" name str)))
(pvs-message
"\"~a\" is not a valid proof script header" formula-name)))
(pvs-message "Theory ~a not found" theory-name))))
(defun associate-proof-with-formula (theory regexp strategy fdecls
&optional
(overwrite-default-proof? t)
(save-prf-file? t))
"This function overwrites the default proof in FDECLS if OVERWRITE-DEFAULT-PROOF? is t (default)."
(when fdecls
(let* ((fdecl (car fdecls))
(match (pregexp-match regexp (format nil "~a" (id fdecl))))
(script (instantiate-script strategy match 0 "\\$")))
(multiple-value-bind (strat err)
#+(and allegro (not pvs6) (not pvs7))
(unwind-protect
(progn (excl:set-case-mode :case-insensitive-lower)
(ignore-errors (values (read-from-string script))))
(excl:set-case-mode :case-sensitive-lower))
#-(and allegro (not pvs6) (not pvs7))
(ignore-errors (values (read-from-string script)))
(let ((just (unless err
(or (revert-justification strat)
(revert-justification (list "" strat))
strat))))
(unless just
(type-error script
"Bad form for script~% ~s" script))
(if overwrite-default-proof?
(setf (justification fdecl) just)
(let ((nextid (next-proof-id fdecl)))
(format t "~%~a~%" nextid)
(make-default-proof fdecl (extract-justification-sexp just) nextid)))
(when save-prf-file?
(save-all-proofs theory))
(pvs-message "Proof script ~a was installed" (id fdecl)))))
(associate-proof-with-formula theory regexp strategy (cdr fdecls))))
Returns a list of theory names defined in a PVS file
(defun theories-in-file (file)
gethash returns a list of form ( date th1 th2 ... ) , where date is the
(cdr (gethash file (current-pvs-files))))
(defun imported-theories-in-theories (theory-names)
(remove-duplicates
(mapcan #'(lambda (theo) (imported-theories-in-theory theo))
theory-names)))
(defun my-collect-theory-usings (theory)
(unless (or (memq theory *modules-visited*)
(from-prelude? theory)
(lib-datatype-or-theory? theory))
(push theory *modules-visited*)
(dolist (use (get-immediate-usings theory))
(let ((th (get-theory use)))
(when th
(my-collect-theory-usings
(if (typep th 'rectype-theory)
(get-typechecked-theory (generated-by th))
th)))))))
(defun immediate-theories-in-theory (theory-name)
(let ((theory (get-typechecked-theory theory-name)))
(when theory
(remove-duplicates
(loop for use in (get-immediate-usings theory)
for th = (get-theory use)
when th
unless (from-prelude? th)
collect (if (typep th 'rectype-theory)
(get-typechecked-theory (generated-by th))
th))))))
(defun imported-theories-in-theory (theory-name)
(let ((theory (get-typechecked-theory theory-name)))
(when theory
(let* ((*modules-visited* nil))
(my-collect-theory-usings theory)
(nreverse *modules-visited*)))))
(defun trim-left (str)
(string-left-trim '(#\Space #\Tab) str))
(defun trim-right (str)
(string-right-trim '(#\Space #\Tab) str))
(defun trim (str)
(string-trim '(#\Space #\Tab) str))
(defun ident () "([\\w\\*?]+)")
(defun spaces () "[\\s\\t]*")
(defun greedyspaces () "(?<!\\s\\t)[\\s\\t]*(?!\\s\\t)")
(defun replace-all-str (string part replacement &key (test #'char=))
"Returns a new string in which all the occurences of the part
is replaced with replacement."
(with-output-to-string (out)
(loop with part-length = (length part)
for old-pos = 0 then (+ pos part-length)
for pos = (search part string
:start2 old-pos
:test test)
do (write-string string out
:start old-pos
:end (or pos (length string)))
when pos do (write-string replacement out)
while pos)))
(defun expand-rex (str)
(format nil "^~a$" (replace-all-str (pregexp-replace* "*" str "(.+)") "?" "\\?")))
(defun read-one-line (file)
(let* ((str (read-line file nil nil))
(strim (when str (trim str))))
(cond ((and (> (length strim) 3) (string= strim "%|-" :end1 3))
strim)
((and (> (length strim) 0) (char= (elt strim 0) #\%))
"%")
(strim ""))))
(defun match-formula-name (str)
(let ((match (cdr (pregexp-match
(format nil "^~a(?:$|~a\\[(.*)\\]$)"
(ident) (greedyspaces))
str))))
(when match
(let* ((name (car match))
(argstr (cadr match))
(args (when argstr (pregexp-split ";" (trim argstr))))
(nargs (when args (mapcar #'(lambda (x) (trim x)) args))))
(cons name nargs)))))
(defun is-proof-comment (str)
(when (> (length str) 3) (trim-left (subseq str 3))))
(defun is-comment (str) (> (length str) 0))
(defun match-proof (str)
(let ((match (pregexp-match-positions
(format nil "^(.+):~a(?i:proof)\\b" (spaces))
str)))
(when match
(cons (trim-right (subseq str (caadr match) (cdadr match)))
(trim (subseq str (cdar match) (length str)))))))
(defun match-qed (str)
(let ((match (pregexp-match "^(.*)\\b(?i:qed).*$" str)))
(when match
(trim (cadr match)))))
(defun install-script (theory script formulas force &optional (overwrite-default-proof? t) (save-prf-file? t))
(let ((strategy (format nil "(\"\" ~a)" script)))
(multiple-value-bind (strat err)
(ignore-errors (values (read-from-string strategy)))
(if err
(pvs-error "Prooflite script error"
(format nil "Error in script for formula ~{~a~^, ~}: ~a." formulas err))
(multiple-value-bind (msg subjust)
(check-edited-justification strat)
(if msg
(pvs-error
"Proof syntax error"
(format nil
"Error in script for formula ~{~a~^, ~}: ~a ~@[(Offending proof part: ~s)~]"
formulas
(or msg "Proof syntax error")
subjust))
(when formulas
(associate-proof-with-formulas
theory
(car formulas)
strategy
force
overwrite-default-proof?
save-prf-file?)
(install-script theory script (cdr formulas) force overwrite-default-proof? save-prf-file?))))))))
(defun new-script (script new)
(let ((notempty (> (length new) 0)))
(cond ((and script notempty)
(format nil "~a ~a" script new))
(script script)
(notempty new))))
(defun instantiate-script (script args n str)
(if args
(let ((new (pregexp-replace* (format nil "~a~a" str n) script
(car args))))
(instantiate-script new (cdr args) (+ n 1) str))
script))
(defun install-prooflite-scripts (filename theory line force)
(with-open-file
(file (make-specpath filename) :direction :input)
(let* ((loc (place (get-theory theory)))
(lfrom (aref loc 0))
(lto (aref loc 2)))
(loop repeat (- lfrom 1) do (read-line file nil nil))
(if (= line 0)
(pvs-message "Installing inlined proof scripts into theory ~a."
theory)
(pvs-message "Installing proof script at line ~a of file ~a."
line filename))
(do ((str (read-one-line file))
(n lfrom)
(formulas)
(script))
((or (null str) (> n lto)))
(let ((proofcomment (is-proof-comment str)))
(cond (proofcomment
(let* ((proof (match-proof proofcomment))
(formula (car proof))
(qed (match-qed proofcomment)))
(cond
(formula
(when (and script (< line n))
(pvs-message
"QED is missing in proof script(s) ~a [Theory: ~a]"
formulas theory))
(setq str (format nil "%|-~a" (cdr proof)))
(setq formulas (cons formula
(when (not script) formulas)))
(setq script nil))
(qed
(let ((newscript (new-script script qed)))
(when (and newscript formulas (<= line n))
(install-script theory newscript
(reverse formulas)
force))
(cond ((or (= line 0) (< n line))
(setq str (read-one-line file))
(setq n (+ n 1))
(setq formulas nil)
(setq script nil))
((not formulas)
(pvs-message
"No script was installed [Theory: ~a]"
theory)
(setq str nil))
(t (setq str nil)))))
(t (setq str (read-one-line file))
(setq n (+ n 1))
(setq script (new-script script proofcomment))))))
((is-comment str)
(setq str (read-one-line file))
(setq n (+ n 1)))
(t
(when (and formulas (< line n))
(pvs-error
"Prooflite script error"
(format
nil
"QED is missing in proof script~:[~;s~] ~{~#[~;~a~;~a and ~a~:;~@{~a~#[~;, and ~:;, ~]~}~]~} [Theory: ~a]"
(cadr formulas)
formulas theory)))
(cond ((or (= line 0) (< n line))
(setq str (read-one-line file))
(setq n (+ n 1))
(setq formulas nil)
(setq script nil))
((and (< 0 line) (or (not formulas) (= line n)))
(pvs-message "No script was installed [Theory: ~a]"
theory)
(setq str nil))
(t (setq str nil))))))))))
(defun install-prooflite-scripts-from-prl-file (theory prl-filename force &optional (plain-script? t))
"Installs all the prooflite scripts from a file called PRL-FILENAME into the theory THEORY.
It assumes that the prl file exists and that theory is not nil."
(let((at-least-one-script-saved? nil))
(with-open-file
(file prl-filename :direction :input)
(do ((str (read-line file nil))
(formulas)
(script))
((null str))
(let ((proofcomment (if plain-script?
(pregexp-replace "\%.*" (trim-left str) "")
(is-proof-comment str))))
(cond (proofcomment
(let* ((proof (match-proof proofcomment))
(formula (car proof))
(qed (match-qed proofcomment)))
(cond
(formula
(when script
(pvs-error
"Prooflite script error"
(format
nil
"QED is missing in proof script~:[~;s~] ~{~#[~;~a~;~a and ~a~:;~@{~a~#[~;, and ~:;, ~]~}~]~} [Theory: ~a]"
(cadr formulas)
formulas theory)))
(setq str (format nil "~a" (cdr proof)))
(setq formulas (cons formula
(when (not script) formulas)))
(setq script nil))
(qed
(let ((newscript (new-script script qed)))
(when (and newscript formulas)
(install-script theory newscript
(reverse formulas)
force
t
nil)
(setq at-least-one-script-saved? t))
(cond ((not formulas)
(pvs-message
"No script was installed [Theory: ~a]"
theory)
(setq str nil))
(t
(setq str (read-line file nil))
(setq formulas nil)
(setq script nil)))))
(t (setq str (read-line file nil))
(setq script (new-script script proofcomment))))))
((is-comment str)
(setq str (read-line file nil)))
(t
(when formulas
(pvs-error
"Prooflite script error"
(format
nil
"QED is missing in proof script~:[~;s~] ~{~#[~;~a~;~a and ~a~:;~@{~a~#[~;, and ~:;, ~]~}~]~} [Theory: ~a]"
(cadr formulas)
formulas theory)))
(setq str (read-line file nil))
(setq formulas nil)
(setq script nil)))))
(when at-least-one-script-saved? (save-all-proofs)))))
(defun then-prooflite (script)
(cond ((and
(cdr script)
(null (cddr script))
(listp (caadr script)))
(list (list 'spread
(car script)
(mapcar #'(lambda (s) (to-prooflite (cdr s)))
(cadr script)))))
(script
(cons (car script) (then-prooflite (cdr script))))))
(defun to-prooflite (script)
(cond ((null (cdr script))
(car script))
((and (null (cddr script))
(listp (caadr script)))
(car (then-prooflite script)))
(t
(cons 'then (then-prooflite script)))))
(defun prooflite-script (fdecl)
(when fdecl
(if (justification fdecl)
(to-prooflite (cdr (editable-justification
(justification fdecl))))
(list 'postpone))))
(defun proof-to-prooflite-script (name line)
(let* ((fdecl (formula-decl-to-prove name nil line "pvs")))
(when fdecl
(pvs-buffer
"ProofLite"
(with-output-to-string
(out)
(write-prooflite-script fdecl out)))
(list (aref (place fdecl) 2)))))
(defun find-formula (theory-name formula)
(let ((theory (get-typechecked-theory theory-name)))
(when theory
(find-if #'(lambda (d) (and (formula-decl? d)
(string= (format nil "~a" (id d))
formula)))
(all-decls theory)))))
(defun all-decl-names (theory-name)
(let ((theory (get-typechecked-theory theory-name)))
(when theory
(mapcar #'(lambda (d) (format nil "~a" (id d)))
(remove-if-not #'(lambda (d) (formula-decl? d))
(all-decls theory))))))
(defun display-prooflite-script (theory formula)
(let* ((fdecl (find-formula theory formula)))
(when fdecl
(pvs-buffer
"ProofLite"
(with-output-to-string
(out)
(write-prooflite-script fdecl out))))))
(defun write-prooflite-script (fdecl &optional (outstream t))
(format outstream "~a : PROOF~%" (id fdecl))
(write (prooflite-script fdecl)
:stream outstream :pretty t :escape t
:level nil :length nil
:pprint-dispatch *proof-script-pprint-dispatch*)
(format outstream "~%QED ~a~%" (id fdecl)))
(defun get-prooflite-file-name (theory)
(format nil "~a.prl" (id theory)))
(defun write-all-prooflite-scripts-to-file (theoryname)
"Writes the proofscripts of all declarations in the theory (including TCCs) into a file called \"<filename>__<theoryname>.prl\", where <filename> is the name of the file where the theory is defined. This function overwrites the \"prl\" file if it already exists. It returns the filename of the produced file on success and nil on error."
(let((theory (get-typechecked-theory theoryname)))
(if theory
(let ((prl-filename (get-prooflite-file-name theory)))
(pvs-message "Storing proofs from theory \"~a\" into file \"~a\"." (id theory) prl-filename)
(handler-case
(with-open-file
(outs prl-filename
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(loop for d in (all-decls theory)
when (and (formula-decl? d) (not (or (axiom? d) (assumption? d))))
do (write-prooflite-script d outs)
finally (return prl-filename)))
(file-error
(e)
(pvs-error "File error" (format nil "Error: Could not write into ~a.~%" (file-error-pathname e)))
nil)))
(pvs-error "Theory not found" (format nil "Error: Theory ~a not found in context.~%" theoryname)))))
(defun get-default-proof-script (theory-name formula)
(let ((formula-declaration (find-formula theory-name formula)))
(when (and formula-declaration (justification formula-declaration))
(format t "~a" (get-proof-script-output-string formula-declaration nil))))
(values))
|
c1a953f9167a18115d534eaf42be5f30eb57eda44b12fe9d1fd333103e8f62c8 | TakaiKinoko/Cornell_CS3110_OCaml | set.ml | module type Set = sig
type 'a t
(* [empty] is the empty set *)
val empty : 'a t
(* [mem x s] holds iff [x] is an element of [s] *)
val mem : 'a -> 'a t -> bool
(* [add x s] is the set [s] unioned with the set containing exactly [x] *)
val add : 'a -> 'a t -> 'a t
(* [elts s] is a list containing the elements of [s]. No guarantee
* is made about the ordering of that list. *)
val elts : 'a t -> 'a list
end
(**an implementation of that interface using a list to represent the set.
This implementation ensures that the list never contains any duplicate elements, since sets themselves do not: *)
module ListSetNoDups : Set = struct
type 'a t = 'a list
let empty = []
let mem x s = List.mem x s
let add x s = if mem x s then s else x::s
let elts s = s
end
* a second implementation , which permits duplicates in the list
module ListSetDups : Set = struct
type 'a t = 'a list
let empty = []
let mem = List.mem
let add x s = x::s (** O(1) *)
let elts s = List.sort_uniq Pervasives.compare s (** O(lgn) *)
end
* : ( ' a - > ' a - > int ) - > ' a list - > ' a list | null | https://raw.githubusercontent.com/TakaiKinoko/Cornell_CS3110_OCaml/0a830bc50a5e39f010074dc289161426294cad1d/Chap5_Modules/03more_examples/set.ml | ocaml | [empty] is the empty set
[mem x s] holds iff [x] is an element of [s]
[add x s] is the set [s] unioned with the set containing exactly [x]
[elts s] is a list containing the elements of [s]. No guarantee
* is made about the ordering of that list.
*an implementation of that interface using a list to represent the set.
This implementation ensures that the list never contains any duplicate elements, since sets themselves do not:
* O(1)
* O(lgn) | module type Set = sig
type 'a t
val empty : 'a t
val mem : 'a -> 'a t -> bool
val add : 'a -> 'a t -> 'a t
val elts : 'a t -> 'a list
end
module ListSetNoDups : Set = struct
type 'a t = 'a list
let empty = []
let mem x s = List.mem x s
let add x s = if mem x s then s else x::s
let elts s = s
end
* a second implementation , which permits duplicates in the list
module ListSetDups : Set = struct
type 'a t = 'a list
let empty = []
let mem = List.mem
end
* : ( ' a - > ' a - > int ) - > ' a list - > ' a list |
4200438bb6989133500df4b3a02838509c51059ef20bbc2af0e2e71958136c9e | johnwhitington/camlpdf | pdftransform.mli | * Affine Transformations in Two Dimensions
(** {2 Types} *)
(** A single transformation operation. *)
type transform_op =
| Scale of (float * float) * float * float
| Rotate of (float * float) * float
| Translate of float * float
| ShearX of (float * float) * float
| ShearY of (float * float) * float
* A list of transformations , the first at the end of the list ( thus , to append
another transformation , just cons to the beginning . )
another transformation, just cons to the beginning.) *)
type transform = transform_op list
* A transformation matrix ( first row [ a c e ] , second row [ b d f ] , third row [ 0 0 1 ] )
type transform_matrix =
{a : float; b : float; c : float; d : float; e : float; f : float}
(** The identity transform *)
val i : transform
(** Make a string of a transform for debug purposes. *)
val string_of_transform : transform -> string
* { 2 Making transformation matrices }
(** The identity matrix *)
val i_matrix : transform_matrix
(** String of a transformation matrix. *)
val string_of_matrix : transform_matrix -> string
(** Make a transformation matrix from x and y translation. *)
val mktranslate : float -> float -> transform_matrix
(** Make a transformation matrix from an x and y scale and a point to scale about. *)
val mkscale : (float * float) -> float -> float -> transform_matrix
(** Make a rotation matrix to rotate by a number of radians around a point. *)
val mkrotate : (float * float) -> float -> transform_matrix
(** Matrix to shear in x by a given factor about a point. *)
val mkshearx : (float * float) -> float -> transform_matrix
(** Matrix to shear in y by a given factor about a point. *)
val mksheary : (float * float) -> float -> transform_matrix
* { 2 Composing and manipulating transforms }
(** [compose t ts] adds operation [t] to the transform [ts]. *)
val compose : transform_op -> transform -> transform
(** [append a b] is a transform with the same effect as performing b then a *)
val append : (transform -> transform -> transform)
(** [compose a b] produces a matrix equivalent to performing [b] then [a]. *)
val matrix_compose : transform_matrix -> transform_matrix -> transform_matrix
(** Make a matrix from a single transformation operation *)
val matrix_of_op : transform_op -> transform_matrix
(** Make a matrix from a transform *)
val matrix_of_transform : transform -> transform_matrix
* { 2 Inverting transforms }
(** Exception raised if a matrix is non-invertable *)
exception NonInvertable
* Matrix inversion . May raise [ NonInvertable ]
val matrix_invert : transform_matrix -> transform_matrix
(** Transform a coordinate by a given transform. *)
val transform : transform -> float * float -> float * float
(** Transform a coordinate by a given transformation matrix. *)
val transform_matrix : transform_matrix -> float * float -> float * float
* { 2 Decomposing and recomposing matrices }
* Decompose a transformation matrix to scale , aspect , rotation , shear ,
translation in x , translation in y. Always succeeds , but results are not
guaranteed to mean anything .
translation in x, translation in y. Always succeeds, but results are not
guaranteed to mean anything. *)
val decompose :
transform_matrix -> float * float * float * float * float * float
* from the above information . It is not guaranteed that recompose
( decompose t ) = t
(decompose t) = t *)
val recompose :
float -> float -> float -> float -> float -> float -> transform_matrix
| null | https://raw.githubusercontent.com/johnwhitington/camlpdf/dc7cfafaf9671bed1503a5c4143632922226b02d/pdftransform.mli | ocaml | * {2 Types}
* A single transformation operation.
* The identity transform
* Make a string of a transform for debug purposes.
* The identity matrix
* String of a transformation matrix.
* Make a transformation matrix from x and y translation.
* Make a transformation matrix from an x and y scale and a point to scale about.
* Make a rotation matrix to rotate by a number of radians around a point.
* Matrix to shear in x by a given factor about a point.
* Matrix to shear in y by a given factor about a point.
* [compose t ts] adds operation [t] to the transform [ts].
* [append a b] is a transform with the same effect as performing b then a
* [compose a b] produces a matrix equivalent to performing [b] then [a].
* Make a matrix from a single transformation operation
* Make a matrix from a transform
* Exception raised if a matrix is non-invertable
* Transform a coordinate by a given transform.
* Transform a coordinate by a given transformation matrix. | * Affine Transformations in Two Dimensions
type transform_op =
| Scale of (float * float) * float * float
| Rotate of (float * float) * float
| Translate of float * float
| ShearX of (float * float) * float
| ShearY of (float * float) * float
* A list of transformations , the first at the end of the list ( thus , to append
another transformation , just cons to the beginning . )
another transformation, just cons to the beginning.) *)
type transform = transform_op list
* A transformation matrix ( first row [ a c e ] , second row [ b d f ] , third row [ 0 0 1 ] )
type transform_matrix =
{a : float; b : float; c : float; d : float; e : float; f : float}
val i : transform
val string_of_transform : transform -> string
* { 2 Making transformation matrices }
val i_matrix : transform_matrix
val string_of_matrix : transform_matrix -> string
val mktranslate : float -> float -> transform_matrix
val mkscale : (float * float) -> float -> float -> transform_matrix
val mkrotate : (float * float) -> float -> transform_matrix
val mkshearx : (float * float) -> float -> transform_matrix
val mksheary : (float * float) -> float -> transform_matrix
* { 2 Composing and manipulating transforms }
val compose : transform_op -> transform -> transform
val append : (transform -> transform -> transform)
val matrix_compose : transform_matrix -> transform_matrix -> transform_matrix
val matrix_of_op : transform_op -> transform_matrix
val matrix_of_transform : transform -> transform_matrix
* { 2 Inverting transforms }
exception NonInvertable
* Matrix inversion . May raise [ NonInvertable ]
val matrix_invert : transform_matrix -> transform_matrix
val transform : transform -> float * float -> float * float
val transform_matrix : transform_matrix -> float * float -> float * float
* { 2 Decomposing and recomposing matrices }
* Decompose a transformation matrix to scale , aspect , rotation , shear ,
translation in x , translation in y. Always succeeds , but results are not
guaranteed to mean anything .
translation in x, translation in y. Always succeeds, but results are not
guaranteed to mean anything. *)
val decompose :
transform_matrix -> float * float * float * float * float * float
* from the above information . It is not guaranteed that recompose
( decompose t ) = t
(decompose t) = t *)
val recompose :
float -> float -> float -> float -> float -> float -> transform_matrix
|
ece27e73921d9c991de3f626d7d9662874e3c5d0d1bb2ba72ba04d023d450f0f | ghcjs/ghcjs | drvrun007.hs | module Main( main ) where
-- This one crashed Hugs98
data X = X | X :\ X deriving Show
main = putStrLn (show (X :\ X))
| null | https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/deriving/drvrun007.hs | haskell | This one crashed Hugs98 | module Main( main ) where
data X = X | X :\ X deriving Show
main = putStrLn (show (X :\ X))
|
6b0f2d377324f90affeb6b0698cb4a2c149a732adc436f6300ebce85af307b8a | fakedata-haskell/fakedata | Address.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
module Faker.Address where
import Data.Text (Text)
import Faker (Fake, FakeT(..), FakerSettings(..), getLocale)
import Faker.Internal (cachedRandomUnresolvedVec, cachedRandomVec, cachedRegex, RegexFakeValue(..))
import Faker.Provider.Address
import Faker.TH
import Control.Monad.Catch
import Control.Monad.IO.Class
country :: Fake Text
country = Fake (cachedRandomVec "address" "country" countryProvider)
$(generateFakeField "address" "cityPrefix")
citySuffix :: Fake Text
citySuffix = Fake (cachedRandomVec "address" "citySuffix" citySuffixProvider)
countryCode :: Fake Text
countryCode = Fake (cachedRandomVec "address" "countryCode" countryCodeProvider)
countryCodeLong :: Fake Text
countryCodeLong =
Fake (cachedRandomVec "address" "countryCodeLong" countryCodeLongProvider)
buildingNumber :: Fake Text
buildingNumber =
Fake
(cachedRandomUnresolvedVec
"address"
"buildingNumber"
buildingNumberProvider
resolveAddressText)
communityPrefix :: Fake Text
communityPrefix =
Fake (cachedRandomVec "address" "communityPrefix" communityPrefixProvider)
communitySuffix :: Fake Text
communitySuffix =
Fake (cachedRandomVec "address" "communitySuffix" communitySuffixProvider)
$(generateFakeFieldUnresolved "address" "community")
streetSuffix :: Fake Text
streetSuffix =
Fake (cachedRandomVec "address" "streetSuffix" streetSuffixProvider)
secondaryAddress :: Fake Text
secondaryAddress =
Fake
(cachedRandomUnresolvedVec
"address"
"secondaryAddress"
secondaryAddressProvider
resolveAddressText)
postcode :: Fake Text
postcode = Fake handlePostcode
where
handlePostcode :: (MonadIO m, MonadThrow m) => FakerSettings -> m Text
handlePostcode settings =
case (getLocale settings) `elem` ["vi", "en-CA", "fr-CA", "en-GB", "nl"] of
True ->
unRegexFakeValue <$>
(cachedRegex "address" "postcode" postcodeRegexProvider settings)
False ->
cachedRandomUnresolvedVec
"address"
"postcode"
postcodeProvider
resolveAddressText
settings
state :: Fake Text
state = Fake (cachedRandomVec "address" "state" stateProvider)
stateAbbr :: Fake Text
stateAbbr = Fake (cachedRandomVec "address" "stateAbbr" stateAbbrProvider)
timeZone :: Fake Text
timeZone = Fake (cachedRandomVec "address" "timeZone" timeZoneProvider)
city :: Fake Text
city =
Fake
(cachedRandomUnresolvedVec "address" "city" cityProvider resolveAddressText)
streetName :: Fake Text
streetName =
Fake
(cachedRandomUnresolvedVec
"address"
"streetName"
streetNameProvider
resolveAddressText)
streetAddress :: Fake Text
streetAddress =
Fake
(cachedRandomUnresolvedVec
"address"
"streetAddress"
streetAddressProvider
resolveAddressText)
fullAddress :: Fake Text
fullAddress =
Fake
(cachedRandomUnresolvedVec
"address"
"fullAddress"
fullAddressProvider
resolveAddressText)
| @since 0.6.0
mailBox :: Fake Text
mailBox =
Fake
(cachedRandomUnresolvedVec
"address"
"mail_box"
mailBoxProvider
resolveAddressText)
| @since 0.7.0
cityWithState :: Fake Text
cityWithState =
Fake
(cachedRandomUnresolvedVec
"address"
"city_with_state"
cityWithStateProvider
resolveAddressText)
| null | https://raw.githubusercontent.com/fakedata-haskell/fakedata/d27461f8a97cf3d6e08d7cbd0134661aecd31459/src/Faker/Address.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE TemplateHaskell #
module Faker.Address where
import Data.Text (Text)
import Faker (Fake, FakeT(..), FakerSettings(..), getLocale)
import Faker.Internal (cachedRandomUnresolvedVec, cachedRandomVec, cachedRegex, RegexFakeValue(..))
import Faker.Provider.Address
import Faker.TH
import Control.Monad.Catch
import Control.Monad.IO.Class
country :: Fake Text
country = Fake (cachedRandomVec "address" "country" countryProvider)
$(generateFakeField "address" "cityPrefix")
citySuffix :: Fake Text
citySuffix = Fake (cachedRandomVec "address" "citySuffix" citySuffixProvider)
countryCode :: Fake Text
countryCode = Fake (cachedRandomVec "address" "countryCode" countryCodeProvider)
countryCodeLong :: Fake Text
countryCodeLong =
Fake (cachedRandomVec "address" "countryCodeLong" countryCodeLongProvider)
buildingNumber :: Fake Text
buildingNumber =
Fake
(cachedRandomUnresolvedVec
"address"
"buildingNumber"
buildingNumberProvider
resolveAddressText)
communityPrefix :: Fake Text
communityPrefix =
Fake (cachedRandomVec "address" "communityPrefix" communityPrefixProvider)
communitySuffix :: Fake Text
communitySuffix =
Fake (cachedRandomVec "address" "communitySuffix" communitySuffixProvider)
$(generateFakeFieldUnresolved "address" "community")
streetSuffix :: Fake Text
streetSuffix =
Fake (cachedRandomVec "address" "streetSuffix" streetSuffixProvider)
secondaryAddress :: Fake Text
secondaryAddress =
Fake
(cachedRandomUnresolvedVec
"address"
"secondaryAddress"
secondaryAddressProvider
resolveAddressText)
postcode :: Fake Text
postcode = Fake handlePostcode
where
handlePostcode :: (MonadIO m, MonadThrow m) => FakerSettings -> m Text
handlePostcode settings =
case (getLocale settings) `elem` ["vi", "en-CA", "fr-CA", "en-GB", "nl"] of
True ->
unRegexFakeValue <$>
(cachedRegex "address" "postcode" postcodeRegexProvider settings)
False ->
cachedRandomUnresolvedVec
"address"
"postcode"
postcodeProvider
resolveAddressText
settings
state :: Fake Text
state = Fake (cachedRandomVec "address" "state" stateProvider)
stateAbbr :: Fake Text
stateAbbr = Fake (cachedRandomVec "address" "stateAbbr" stateAbbrProvider)
timeZone :: Fake Text
timeZone = Fake (cachedRandomVec "address" "timeZone" timeZoneProvider)
city :: Fake Text
city =
Fake
(cachedRandomUnresolvedVec "address" "city" cityProvider resolveAddressText)
streetName :: Fake Text
streetName =
Fake
(cachedRandomUnresolvedVec
"address"
"streetName"
streetNameProvider
resolveAddressText)
streetAddress :: Fake Text
streetAddress =
Fake
(cachedRandomUnresolvedVec
"address"
"streetAddress"
streetAddressProvider
resolveAddressText)
fullAddress :: Fake Text
fullAddress =
Fake
(cachedRandomUnresolvedVec
"address"
"fullAddress"
fullAddressProvider
resolveAddressText)
| @since 0.6.0
mailBox :: Fake Text
mailBox =
Fake
(cachedRandomUnresolvedVec
"address"
"mail_box"
mailBoxProvider
resolveAddressText)
| @since 0.7.0
cityWithState :: Fake Text
cityWithState =
Fake
(cachedRandomUnresolvedVec
"address"
"city_with_state"
cityWithStateProvider
resolveAddressText)
|
e29edf671a66d04baaab780d83a679a163e8acf3f5b54ce604d26fe152b04c03 | jaspervdj/advent-of-code | 15.hs | import AdventOfCode.Main
import qualified AdventOfCode.NanoParser as NP
import Data.List (foldl')
import Data.Maybe (mapMaybe)
--------------------------------------------------------------------------------
data RangeSet
= RSCons {-# UNPACK #-} !Int {-# UNPACK #-} !Int !RangeSet
| RSNil
empty :: RangeSet
empty = RSNil
insert :: Int -> Int -> RangeSet -> RangeSet
insert l h RSNil = RSCons l h RSNil
insert l0 h0 rs@(RSCons l1 h1 rss)
| h0 + 1 < l1 = RSCons l0 h0 rs
| l0 > h1 + 1 = RSCons l1 h1 (insert l0 h0 rss)
| otherwise = insert (min l0 l1) (max h0 h1) rss
holes :: RangeSet -> RangeSet
holes (RSCons _ h0 rs@(RSCons l1 _ _)) = RSCons (h0 + 1) (l1 - 1) (holes rs)
holes _ = RSNil
size :: RangeSet -> Int
size (RSCons l h rs) = h - l + 1 + size rs
size RSNil = 0
toList :: RangeSet -> [Int]
toList (RSCons l h rs) = [l .. h] ++ toList rs
toList RSNil = []
--------------------------------------------------------------------------------
data Pos = Pos {-# UNPACK #-} !Int {-# UNPACK #-} !Int
manhattan :: Pos -> Pos -> Int
manhattan (Pos x0 y0) (Pos x1 y1) = abs (x1 - x0) + abs (y1 - y0)
--------------------------------------------------------------------------------
data Sensor = Sensor !Pos !Pos
parseSensors :: NP.Parser Char [Sensor]
parseSensors = NP.sepBy1 pair NP.newline
where
pair = Sensor
<$> (NP.string "Sensor at " *> pos)
<*> (NP.string ": closest beacon is at " *> pos)
pos = Pos
<$> (NP.string "x=" *> NP.signedDecimal)
<*> (NP.string ", y=" *> NP.signedDecimal)
coverRow :: Int -> Sensor -> Maybe (Int, Int)
coverRow y (Sensor sensor@(Pos sx sy) beacon)
| dy > dist = Nothing
| otherwise = Just (sx - dist + dy, sx + dist - dy)
where
dy = abs $ y - sy
dist = manhattan sensor beacon
part1 :: Int -> [Sensor] -> Int
part1 row =
size . foldl' (\rs (lo, hi) -> insert lo hi rs) empty .
mapMaybe (coverRow row)
part2 :: Int -> [Sensor] -> Int
part2 bound sensors = head $ do
y <- [0 .. bound]
x <- toList . holes $
foldl' (\rs (lo, hi) -> insert lo hi rs) empty $
mapMaybe (coverRow y) sensors
pure $ x * bound + y
main :: IO ()
main = pureMain $ \str -> do
input <- NP.runParser parseSensors str
pure (pure (part1 2000000 input), pure (part2 4000000 input))
| null | https://raw.githubusercontent.com/jaspervdj/advent-of-code/33130b9814f2017916016381be42ddaaf2493e4b/2022/15.hs | haskell | ------------------------------------------------------------------------------
# UNPACK #
# UNPACK #
------------------------------------------------------------------------------
# UNPACK #
# UNPACK #
------------------------------------------------------------------------------ | import AdventOfCode.Main
import qualified AdventOfCode.NanoParser as NP
import Data.List (foldl')
import Data.Maybe (mapMaybe)
data RangeSet
| RSNil
empty :: RangeSet
empty = RSNil
insert :: Int -> Int -> RangeSet -> RangeSet
insert l h RSNil = RSCons l h RSNil
insert l0 h0 rs@(RSCons l1 h1 rss)
| h0 + 1 < l1 = RSCons l0 h0 rs
| l0 > h1 + 1 = RSCons l1 h1 (insert l0 h0 rss)
| otherwise = insert (min l0 l1) (max h0 h1) rss
holes :: RangeSet -> RangeSet
holes (RSCons _ h0 rs@(RSCons l1 _ _)) = RSCons (h0 + 1) (l1 - 1) (holes rs)
holes _ = RSNil
size :: RangeSet -> Int
size (RSCons l h rs) = h - l + 1 + size rs
size RSNil = 0
toList :: RangeSet -> [Int]
toList (RSCons l h rs) = [l .. h] ++ toList rs
toList RSNil = []
manhattan :: Pos -> Pos -> Int
manhattan (Pos x0 y0) (Pos x1 y1) = abs (x1 - x0) + abs (y1 - y0)
data Sensor = Sensor !Pos !Pos
parseSensors :: NP.Parser Char [Sensor]
parseSensors = NP.sepBy1 pair NP.newline
where
pair = Sensor
<$> (NP.string "Sensor at " *> pos)
<*> (NP.string ": closest beacon is at " *> pos)
pos = Pos
<$> (NP.string "x=" *> NP.signedDecimal)
<*> (NP.string ", y=" *> NP.signedDecimal)
coverRow :: Int -> Sensor -> Maybe (Int, Int)
coverRow y (Sensor sensor@(Pos sx sy) beacon)
| dy > dist = Nothing
| otherwise = Just (sx - dist + dy, sx + dist - dy)
where
dy = abs $ y - sy
dist = manhattan sensor beacon
part1 :: Int -> [Sensor] -> Int
part1 row =
size . foldl' (\rs (lo, hi) -> insert lo hi rs) empty .
mapMaybe (coverRow row)
part2 :: Int -> [Sensor] -> Int
part2 bound sensors = head $ do
y <- [0 .. bound]
x <- toList . holes $
foldl' (\rs (lo, hi) -> insert lo hi rs) empty $
mapMaybe (coverRow y) sensors
pure $ x * bound + y
main :: IO ()
main = pureMain $ \str -> do
input <- NP.runParser parseSensors str
pure (pure (part1 2000000 input), pure (part2 4000000 input))
|
eae327fd8bd396bde957e15c6f58312b08deb01d6b97f2d8fa4266e34e55ac02 | aantron/bisect_ppx | at_exit_hook.ml | [@@@coverage exclude_file]
let is_child = ref false
let () =
at_exit (fun () ->
if !is_child then begin
Unix.sleep 5;
print_endline "I should've been woken up by now."
end)
| null | https://raw.githubusercontent.com/aantron/bisect_ppx/a12047019fc021d51488be6157e89a014a210e93/test/sigterm/at_exit_hook.ml | ocaml | [@@@coverage exclude_file]
let is_child = ref false
let () =
at_exit (fun () ->
if !is_child then begin
Unix.sleep 5;
print_endline "I should've been woken up by now."
end)
|
|
4ed9849faff5f72931229c7c2583462f359087c68602aa03b72225ed44a06bf0 | ocaml-flambda/flambda-backend | lambda_to_flambda_primitives_helpers.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, OCamlPro
and ,
(* *)
(* Copyright 2013--2019 OCamlPro SAS *)
Copyright 2014 - -2019 Jane Street Group LLC
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open! Flambda.Import
open Closure_conversion_aux
module P = Flambda_primitive
module VB = Bound_var
type failure =
| Division_by_zero
| Index_out_of_bounds
type expr_primitive =
| Simple of Simple.t
| Nullary of Flambda_primitive.nullary_primitive
| Unary of P.unary_primitive * simple_or_prim
| Binary of P.binary_primitive * simple_or_prim * simple_or_prim
| Ternary of
P.ternary_primitive * simple_or_prim * simple_or_prim * simple_or_prim
| Variadic of P.variadic_primitive * simple_or_prim list
| Checked of
{ validity_conditions : expr_primitive list;
primitive : expr_primitive;
failure : failure;
(* Predefined exception *)
dbg : Debuginfo.t
}
| If_then_else of expr_primitive * expr_primitive * expr_primitive
and simple_or_prim =
| Simple of Simple.t
| Prim of expr_primitive
let rec print_expr_primitive ppf expr_primitive =
let module W = Flambda_primitive.Without_args in
match expr_primitive with
| Simple simple -> Simple.print ppf simple
| Nullary prim -> W.print ppf (Nullary prim)
| Unary (prim, _) -> W.print ppf (Unary prim)
| Binary (prim, _, _) -> W.print ppf (Binary prim)
| Ternary (prim, _, _, _) -> W.print ppf (Ternary prim)
| Variadic (prim, _) -> W.print ppf (Variadic prim)
| Checked { primitive; _ } ->
Format.fprintf ppf "@[<hov 1>(Checked@ %a)@]" print_expr_primitive primitive
| If_then_else (cond, ifso, ifnot) ->
Format.fprintf ppf
"@[<hov 1>(If_then_else@ (cond@ %a)@ (ifso@ %a)@ (ifnot@ %a))@]"
print_expr_primitive cond print_expr_primitive ifso print_expr_primitive
ifnot
let print_simple_or_prim ppf (simple_or_prim : simple_or_prim) =
match simple_or_prim with
| Simple simple -> Simple.print ppf simple
| Prim _ -> Format.pp_print_string ppf "<prim>"
let print_list_of_simple_or_prim ppf simple_or_prim_list =
Format.fprintf ppf "@[(%a)@]"
(Format.pp_print_list ~pp_sep:Format.pp_print_space print_simple_or_prim)
simple_or_prim_list
let raise_exn_for_failure acc ~dbg exn_cont exn_bucket extra_let_binding =
let exn_handler = Exn_continuation.exn_handler exn_cont in
let trap_action =
Trap_action.Pop { exn_handler; raise_kind = Some Regular }
in
let args =
let extra_args =
List.map
(fun (simple, _kind) -> simple)
(Exn_continuation.extra_args exn_cont)
in
exn_bucket :: extra_args
in
let acc, apply_cont =
Apply_cont_with_acc.create acc ~trap_action exn_handler ~args ~dbg
in
let acc, apply_cont = Expr_with_acc.create_apply_cont acc apply_cont in
match extra_let_binding with
| None -> acc, apply_cont
| Some (bound_var, defining_expr) ->
Let_with_acc.create acc
(Bound_pattern.singleton bound_var)
defining_expr ~body:apply_cont
let symbol_for_prim id =
Flambda2_import.Symbol.for_predef_ident id |> Symbol.create_wrapped
let expression_for_failure acc exn_cont ~register_const_string primitive dbg
(failure : failure) =
let exn_cont =
match exn_cont with
| Some exn_cont -> exn_cont
| None ->
Misc.fatal_errorf
"Validity checks for primitive@ %a@ may raise, but no exception \
continuation was supplied with the Lambda primitive"
print_expr_primitive primitive
in
match failure with
| Division_by_zero ->
let division_by_zero = symbol_for_prim Predef.ident_division_by_zero in
raise_exn_for_failure acc ~dbg exn_cont
(Simple.symbol division_by_zero)
None
| Index_out_of_bounds ->
let exn_bucket = Variable.create "exn_bucket" in
(* CR mshinwell: Share this text with elsewhere. *)
let acc, error_text = register_const_string acc "index out of bounds" in
let invalid_argument =
(* [Predef.invalid_argument] is not exposed; the following avoids a change
to the frontend. *)
let matches ident = String.equal (Ident.name ident) "Invalid_argument" in
let invalid_argument =
match List.find matches Predef.all_predef_exns with
| exception Not_found ->
Misc.fatal_error "Cannot find Invalid_argument exception in Predef"
| ident -> ident
in
symbol_for_prim invalid_argument
in
let contents_of_exn_bucket =
[Simple.symbol invalid_argument; Simple.symbol error_text]
in
let named =
Named.create_prim
(Variadic
( Make_block
( Values
( Tag.Scannable.zero,
[ Flambda_kind.With_subkind.any_value;
Flambda_kind.With_subkind.any_value ] ),
Immutable,
Alloc_mode.For_allocations.heap ),
contents_of_exn_bucket ))
dbg
in
let extra_let_binding =
Bound_var.create exn_bucket Name_mode.normal, named
in
raise_exn_for_failure acc ~dbg exn_cont (Simple.var exn_bucket)
(Some extra_let_binding)
let rec bind_rec acc exn_cont ~register_const_string (prim : expr_primitive)
(dbg : Debuginfo.t) (cont : Acc.t -> Named.t -> Expr_with_acc.t) :
Expr_with_acc.t =
match prim with
| Simple simple ->
let named = Named.create_simple simple in
cont acc named
| Nullary prim ->
let named = Named.create_prim (Nullary prim) dbg in
cont acc named
| Unary (prim, arg) ->
let cont acc (arg : Simple.t) =
let named = Named.create_prim (Unary (prim, arg)) dbg in
cont acc named
in
bind_rec_primitive acc exn_cont ~register_const_string arg dbg cont
| Binary (prim, arg1, arg2) ->
let cont acc (arg2 : Simple.t) =
let cont acc (arg1 : Simple.t) =
let named = Named.create_prim (Binary (prim, arg1, arg2)) dbg in
cont acc named
in
bind_rec_primitive acc exn_cont ~register_const_string arg1 dbg cont
in
bind_rec_primitive acc exn_cont ~register_const_string arg2 dbg cont
| Ternary (prim, arg1, arg2, arg3) ->
let cont acc (arg3 : Simple.t) =
let cont acc (arg2 : Simple.t) =
let cont acc (arg1 : Simple.t) =
let named =
Named.create_prim (Ternary (prim, arg1, arg2, arg3)) dbg
in
cont acc named
in
bind_rec_primitive acc exn_cont ~register_const_string arg1 dbg cont
in
bind_rec_primitive acc exn_cont ~register_const_string arg2 dbg cont
in
bind_rec_primitive acc exn_cont ~register_const_string arg3 dbg cont
| Variadic (prim, args) ->
let cont acc args =
let named = Named.create_prim (Variadic (prim, args)) dbg in
cont acc named
in
let rec build_cont acc args_to_convert converted_args =
match args_to_convert with
| [] -> cont acc converted_args
| arg :: args_to_convert ->
let cont acc arg =
build_cont acc args_to_convert (arg :: converted_args)
in
bind_rec_primitive acc exn_cont ~register_const_string arg dbg cont
in
build_cont acc (List.rev args) []
| Checked { validity_conditions; primitive; failure; dbg } ->
let primitive_cont = Continuation.create () in
let primitive_handler_expr acc =
bind_rec acc exn_cont ~register_const_string primitive dbg cont
in
let failure_cont = Continuation.create () in
let failure_handler_expr acc =
expression_for_failure acc exn_cont ~register_const_string primitive dbg
failure
in
let check_validity_conditions =
let prim_apply_cont acc =
let acc, expr = Apply_cont_with_acc.goto acc primitive_cont in
Expr_with_acc.create_apply_cont acc expr
in
List.fold_left
(fun condition_passed_expr expr_primitive acc ->
let condition_passed_cont = Continuation.create () in
let body acc =
bind_rec_primitive acc exn_cont ~register_const_string
(Prim expr_primitive) dbg (fun acc prim_result ->
let acc, condition_passed =
Apply_cont_with_acc.goto acc condition_passed_cont
in
let acc, failure = Apply_cont_with_acc.goto acc failure_cont in
Expr_with_acc.create_switch acc
(Switch.create ~condition_dbg:dbg ~scrutinee:prim_result
~arms:
(Targetint_31_63.Map.of_list
[ Targetint_31_63.bool_true, condition_passed;
Targetint_31_63.bool_false, failure ])))
in
Let_cont_with_acc.build_non_recursive acc condition_passed_cont
~handler_params:Bound_parameters.empty
~handler:condition_passed_expr ~body ~is_exn_handler:false)
prim_apply_cont validity_conditions
in
let body acc =
Let_cont_with_acc.build_non_recursive acc failure_cont
~handler_params:Bound_parameters.empty ~handler:failure_handler_expr
~body:check_validity_conditions ~is_exn_handler:false
in
Let_cont_with_acc.build_non_recursive acc primitive_cont
~handler_params:Bound_parameters.empty ~handler:primitive_handler_expr
~body ~is_exn_handler:false
| If_then_else (cond, ifso, ifnot) ->
let cond_result = Variable.create "cond_result" in
let cond_result_pat = Bound_var.create cond_result Name_mode.normal in
let ifso_cont = Continuation.create () in
let ifso_result = Variable.create "ifso_result" in
let ifso_result_pat = Bound_var.create ifso_result Name_mode.normal in
let ifnot_cont = Continuation.create () in
let ifnot_result = Variable.create "ifnot_result" in
let ifnot_result_pat = Bound_var.create ifnot_result Name_mode.normal in
let join_point_cont = Continuation.create () in
let result_var = Variable.create "if_then_else_result" in
let result_param =
Bound_parameter.create result_var Flambda_kind.With_subkind.any_value
in
bind_rec acc exn_cont ~register_const_string cond dbg @@ fun acc cond ->
let compute_cond_and_switch acc =
let acc, ifso_cont = Apply_cont_with_acc.goto acc ifso_cont in
let acc, ifnot_cont = Apply_cont_with_acc.goto acc ifnot_cont in
let acc, switch =
Expr_with_acc.create_switch acc
(Switch.create ~condition_dbg:dbg ~scrutinee:(Simple.var cond_result)
~arms:
(Targetint_31_63.Map.of_list
[ Targetint_31_63.bool_true, ifso_cont;
Targetint_31_63.bool_false, ifnot_cont ]))
in
Let_with_acc.create acc
(Bound_pattern.singleton cond_result_pat)
cond ~body:switch
in
let join_handler_expr acc =
cont acc (Named.create_simple (Simple.var result_var))
in
let ifso_handler_expr acc =
bind_rec acc exn_cont ~register_const_string ifso dbg @@ fun acc ifso ->
let acc, apply_cont =
Apply_cont_with_acc.create acc join_point_cont
~args:[Simple.var ifso_result]
~dbg
in
let acc, body = Expr_with_acc.create_apply_cont acc apply_cont in
Let_with_acc.create acc
(Bound_pattern.singleton ifso_result_pat)
ifso ~body
in
let ifnot_handler_expr acc =
bind_rec acc exn_cont ~register_const_string ifnot dbg @@ fun acc ifnot ->
let acc, apply_cont =
Apply_cont_with_acc.create acc join_point_cont
~args:[Simple.var ifnot_result]
~dbg
in
let acc, body = Expr_with_acc.create_apply_cont acc apply_cont in
Let_with_acc.create acc
(Bound_pattern.singleton ifnot_result_pat)
ifnot ~body
in
let body acc =
Let_cont_with_acc.build_non_recursive acc ifnot_cont
~handler_params:Bound_parameters.empty ~handler:ifnot_handler_expr
~body:compute_cond_and_switch ~is_exn_handler:false
in
let body acc =
Let_cont_with_acc.build_non_recursive acc ifso_cont
~handler_params:Bound_parameters.empty ~handler:ifso_handler_expr ~body
~is_exn_handler:false
in
Let_cont_with_acc.build_non_recursive acc join_point_cont
~handler_params:(Bound_parameters.create [result_param])
~handler:join_handler_expr ~body ~is_exn_handler:false
and bind_rec_primitive acc exn_cont ~register_const_string
(prim : simple_or_prim) (dbg : Debuginfo.t)
(cont : Acc.t -> Simple.t -> Expr_with_acc.t) : Expr_with_acc.t =
match prim with
| Simple s -> cont acc s
| Prim p ->
let var = Variable.create "prim" in
let var' = VB.create var Name_mode.normal in
let cont acc (named : Named.t) =
let acc, body = cont acc (Simple.var var) in
Let_with_acc.create acc (Bound_pattern.singleton var') named ~body
in
bind_rec acc exn_cont ~register_const_string p dbg cont
| null | https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/cef317cfa2fc02b27006ae398bdd09fdc189c0a3/middle_end/flambda2/from_lambda/lambda_to_flambda_primitives_helpers.ml | ocaml | ************************************************************************
OCaml
Copyright 2013--2019 OCamlPro SAS
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Predefined exception
CR mshinwell: Share this text with elsewhere.
[Predef.invalid_argument] is not exposed; the following avoids a change
to the frontend. | , OCamlPro
and ,
Copyright 2014 - -2019 Jane Street Group LLC
the GNU Lesser General Public License version 2.1 , with the
open! Flambda.Import
open Closure_conversion_aux
module P = Flambda_primitive
module VB = Bound_var
type failure =
| Division_by_zero
| Index_out_of_bounds
type expr_primitive =
| Simple of Simple.t
| Nullary of Flambda_primitive.nullary_primitive
| Unary of P.unary_primitive * simple_or_prim
| Binary of P.binary_primitive * simple_or_prim * simple_or_prim
| Ternary of
P.ternary_primitive * simple_or_prim * simple_or_prim * simple_or_prim
| Variadic of P.variadic_primitive * simple_or_prim list
| Checked of
{ validity_conditions : expr_primitive list;
primitive : expr_primitive;
failure : failure;
dbg : Debuginfo.t
}
| If_then_else of expr_primitive * expr_primitive * expr_primitive
and simple_or_prim =
| Simple of Simple.t
| Prim of expr_primitive
let rec print_expr_primitive ppf expr_primitive =
let module W = Flambda_primitive.Without_args in
match expr_primitive with
| Simple simple -> Simple.print ppf simple
| Nullary prim -> W.print ppf (Nullary prim)
| Unary (prim, _) -> W.print ppf (Unary prim)
| Binary (prim, _, _) -> W.print ppf (Binary prim)
| Ternary (prim, _, _, _) -> W.print ppf (Ternary prim)
| Variadic (prim, _) -> W.print ppf (Variadic prim)
| Checked { primitive; _ } ->
Format.fprintf ppf "@[<hov 1>(Checked@ %a)@]" print_expr_primitive primitive
| If_then_else (cond, ifso, ifnot) ->
Format.fprintf ppf
"@[<hov 1>(If_then_else@ (cond@ %a)@ (ifso@ %a)@ (ifnot@ %a))@]"
print_expr_primitive cond print_expr_primitive ifso print_expr_primitive
ifnot
let print_simple_or_prim ppf (simple_or_prim : simple_or_prim) =
match simple_or_prim with
| Simple simple -> Simple.print ppf simple
| Prim _ -> Format.pp_print_string ppf "<prim>"
let print_list_of_simple_or_prim ppf simple_or_prim_list =
Format.fprintf ppf "@[(%a)@]"
(Format.pp_print_list ~pp_sep:Format.pp_print_space print_simple_or_prim)
simple_or_prim_list
let raise_exn_for_failure acc ~dbg exn_cont exn_bucket extra_let_binding =
let exn_handler = Exn_continuation.exn_handler exn_cont in
let trap_action =
Trap_action.Pop { exn_handler; raise_kind = Some Regular }
in
let args =
let extra_args =
List.map
(fun (simple, _kind) -> simple)
(Exn_continuation.extra_args exn_cont)
in
exn_bucket :: extra_args
in
let acc, apply_cont =
Apply_cont_with_acc.create acc ~trap_action exn_handler ~args ~dbg
in
let acc, apply_cont = Expr_with_acc.create_apply_cont acc apply_cont in
match extra_let_binding with
| None -> acc, apply_cont
| Some (bound_var, defining_expr) ->
Let_with_acc.create acc
(Bound_pattern.singleton bound_var)
defining_expr ~body:apply_cont
let symbol_for_prim id =
Flambda2_import.Symbol.for_predef_ident id |> Symbol.create_wrapped
let expression_for_failure acc exn_cont ~register_const_string primitive dbg
(failure : failure) =
let exn_cont =
match exn_cont with
| Some exn_cont -> exn_cont
| None ->
Misc.fatal_errorf
"Validity checks for primitive@ %a@ may raise, but no exception \
continuation was supplied with the Lambda primitive"
print_expr_primitive primitive
in
match failure with
| Division_by_zero ->
let division_by_zero = symbol_for_prim Predef.ident_division_by_zero in
raise_exn_for_failure acc ~dbg exn_cont
(Simple.symbol division_by_zero)
None
| Index_out_of_bounds ->
let exn_bucket = Variable.create "exn_bucket" in
let acc, error_text = register_const_string acc "index out of bounds" in
let invalid_argument =
let matches ident = String.equal (Ident.name ident) "Invalid_argument" in
let invalid_argument =
match List.find matches Predef.all_predef_exns with
| exception Not_found ->
Misc.fatal_error "Cannot find Invalid_argument exception in Predef"
| ident -> ident
in
symbol_for_prim invalid_argument
in
let contents_of_exn_bucket =
[Simple.symbol invalid_argument; Simple.symbol error_text]
in
let named =
Named.create_prim
(Variadic
( Make_block
( Values
( Tag.Scannable.zero,
[ Flambda_kind.With_subkind.any_value;
Flambda_kind.With_subkind.any_value ] ),
Immutable,
Alloc_mode.For_allocations.heap ),
contents_of_exn_bucket ))
dbg
in
let extra_let_binding =
Bound_var.create exn_bucket Name_mode.normal, named
in
raise_exn_for_failure acc ~dbg exn_cont (Simple.var exn_bucket)
(Some extra_let_binding)
let rec bind_rec acc exn_cont ~register_const_string (prim : expr_primitive)
(dbg : Debuginfo.t) (cont : Acc.t -> Named.t -> Expr_with_acc.t) :
Expr_with_acc.t =
match prim with
| Simple simple ->
let named = Named.create_simple simple in
cont acc named
| Nullary prim ->
let named = Named.create_prim (Nullary prim) dbg in
cont acc named
| Unary (prim, arg) ->
let cont acc (arg : Simple.t) =
let named = Named.create_prim (Unary (prim, arg)) dbg in
cont acc named
in
bind_rec_primitive acc exn_cont ~register_const_string arg dbg cont
| Binary (prim, arg1, arg2) ->
let cont acc (arg2 : Simple.t) =
let cont acc (arg1 : Simple.t) =
let named = Named.create_prim (Binary (prim, arg1, arg2)) dbg in
cont acc named
in
bind_rec_primitive acc exn_cont ~register_const_string arg1 dbg cont
in
bind_rec_primitive acc exn_cont ~register_const_string arg2 dbg cont
| Ternary (prim, arg1, arg2, arg3) ->
let cont acc (arg3 : Simple.t) =
let cont acc (arg2 : Simple.t) =
let cont acc (arg1 : Simple.t) =
let named =
Named.create_prim (Ternary (prim, arg1, arg2, arg3)) dbg
in
cont acc named
in
bind_rec_primitive acc exn_cont ~register_const_string arg1 dbg cont
in
bind_rec_primitive acc exn_cont ~register_const_string arg2 dbg cont
in
bind_rec_primitive acc exn_cont ~register_const_string arg3 dbg cont
| Variadic (prim, args) ->
let cont acc args =
let named = Named.create_prim (Variadic (prim, args)) dbg in
cont acc named
in
let rec build_cont acc args_to_convert converted_args =
match args_to_convert with
| [] -> cont acc converted_args
| arg :: args_to_convert ->
let cont acc arg =
build_cont acc args_to_convert (arg :: converted_args)
in
bind_rec_primitive acc exn_cont ~register_const_string arg dbg cont
in
build_cont acc (List.rev args) []
| Checked { validity_conditions; primitive; failure; dbg } ->
let primitive_cont = Continuation.create () in
let primitive_handler_expr acc =
bind_rec acc exn_cont ~register_const_string primitive dbg cont
in
let failure_cont = Continuation.create () in
let failure_handler_expr acc =
expression_for_failure acc exn_cont ~register_const_string primitive dbg
failure
in
let check_validity_conditions =
let prim_apply_cont acc =
let acc, expr = Apply_cont_with_acc.goto acc primitive_cont in
Expr_with_acc.create_apply_cont acc expr
in
List.fold_left
(fun condition_passed_expr expr_primitive acc ->
let condition_passed_cont = Continuation.create () in
let body acc =
bind_rec_primitive acc exn_cont ~register_const_string
(Prim expr_primitive) dbg (fun acc prim_result ->
let acc, condition_passed =
Apply_cont_with_acc.goto acc condition_passed_cont
in
let acc, failure = Apply_cont_with_acc.goto acc failure_cont in
Expr_with_acc.create_switch acc
(Switch.create ~condition_dbg:dbg ~scrutinee:prim_result
~arms:
(Targetint_31_63.Map.of_list
[ Targetint_31_63.bool_true, condition_passed;
Targetint_31_63.bool_false, failure ])))
in
Let_cont_with_acc.build_non_recursive acc condition_passed_cont
~handler_params:Bound_parameters.empty
~handler:condition_passed_expr ~body ~is_exn_handler:false)
prim_apply_cont validity_conditions
in
let body acc =
Let_cont_with_acc.build_non_recursive acc failure_cont
~handler_params:Bound_parameters.empty ~handler:failure_handler_expr
~body:check_validity_conditions ~is_exn_handler:false
in
Let_cont_with_acc.build_non_recursive acc primitive_cont
~handler_params:Bound_parameters.empty ~handler:primitive_handler_expr
~body ~is_exn_handler:false
| If_then_else (cond, ifso, ifnot) ->
let cond_result = Variable.create "cond_result" in
let cond_result_pat = Bound_var.create cond_result Name_mode.normal in
let ifso_cont = Continuation.create () in
let ifso_result = Variable.create "ifso_result" in
let ifso_result_pat = Bound_var.create ifso_result Name_mode.normal in
let ifnot_cont = Continuation.create () in
let ifnot_result = Variable.create "ifnot_result" in
let ifnot_result_pat = Bound_var.create ifnot_result Name_mode.normal in
let join_point_cont = Continuation.create () in
let result_var = Variable.create "if_then_else_result" in
let result_param =
Bound_parameter.create result_var Flambda_kind.With_subkind.any_value
in
bind_rec acc exn_cont ~register_const_string cond dbg @@ fun acc cond ->
let compute_cond_and_switch acc =
let acc, ifso_cont = Apply_cont_with_acc.goto acc ifso_cont in
let acc, ifnot_cont = Apply_cont_with_acc.goto acc ifnot_cont in
let acc, switch =
Expr_with_acc.create_switch acc
(Switch.create ~condition_dbg:dbg ~scrutinee:(Simple.var cond_result)
~arms:
(Targetint_31_63.Map.of_list
[ Targetint_31_63.bool_true, ifso_cont;
Targetint_31_63.bool_false, ifnot_cont ]))
in
Let_with_acc.create acc
(Bound_pattern.singleton cond_result_pat)
cond ~body:switch
in
let join_handler_expr acc =
cont acc (Named.create_simple (Simple.var result_var))
in
let ifso_handler_expr acc =
bind_rec acc exn_cont ~register_const_string ifso dbg @@ fun acc ifso ->
let acc, apply_cont =
Apply_cont_with_acc.create acc join_point_cont
~args:[Simple.var ifso_result]
~dbg
in
let acc, body = Expr_with_acc.create_apply_cont acc apply_cont in
Let_with_acc.create acc
(Bound_pattern.singleton ifso_result_pat)
ifso ~body
in
let ifnot_handler_expr acc =
bind_rec acc exn_cont ~register_const_string ifnot dbg @@ fun acc ifnot ->
let acc, apply_cont =
Apply_cont_with_acc.create acc join_point_cont
~args:[Simple.var ifnot_result]
~dbg
in
let acc, body = Expr_with_acc.create_apply_cont acc apply_cont in
Let_with_acc.create acc
(Bound_pattern.singleton ifnot_result_pat)
ifnot ~body
in
let body acc =
Let_cont_with_acc.build_non_recursive acc ifnot_cont
~handler_params:Bound_parameters.empty ~handler:ifnot_handler_expr
~body:compute_cond_and_switch ~is_exn_handler:false
in
let body acc =
Let_cont_with_acc.build_non_recursive acc ifso_cont
~handler_params:Bound_parameters.empty ~handler:ifso_handler_expr ~body
~is_exn_handler:false
in
Let_cont_with_acc.build_non_recursive acc join_point_cont
~handler_params:(Bound_parameters.create [result_param])
~handler:join_handler_expr ~body ~is_exn_handler:false
and bind_rec_primitive acc exn_cont ~register_const_string
(prim : simple_or_prim) (dbg : Debuginfo.t)
(cont : Acc.t -> Simple.t -> Expr_with_acc.t) : Expr_with_acc.t =
match prim with
| Simple s -> cont acc s
| Prim p ->
let var = Variable.create "prim" in
let var' = VB.create var Name_mode.normal in
let cont acc (named : Named.t) =
let acc, body = cont acc (Simple.var var) in
Let_with_acc.create acc (Bound_pattern.singleton var') named ~body
in
bind_rec acc exn_cont ~register_const_string p dbg cont
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.