_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 |
|---|---|---|---|---|---|---|---|---|
bb354f963d5de23fd64e7d0e7a881e0f6d9d9400109dd4fbef36aaa168b6c562 | tzemanovic/haskell-yesod-realworld-example-app | JWT.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
module Auth.JWT
( lookupToken
, jsonToToken
, tokenToJson
)
where
import ClassyPrelude.Yesod
import Data.Char (isSpace)
import Data.Map as Map (fromList, (!?))
import Web.JWT as JWT
| Try to lookup token from the Authorization header
lookupToken :: MonadHandler m => m (Maybe Text)
lookupToken = do
mAuth <- lookupHeader "Authorization"
return $ extractToken . decodeUtf8 =<< mAuth
-- | Create a token out of a given JSON 'Value'
jsonToToken :: Text -> Value -> Text
jsonToToken jwtSecret userId =
encodeSigned (JWT.hmacSecret jwtSecret)
mempty {unregisteredClaims = ClaimsMap $ Map.fromList [(jwtKey, userId)]}
-- | Extract a JSON 'Value' out of a token
tokenToJson :: Text -> Text -> Maybe Value
tokenToJson jwtSecret token = do
jwt <- JWT.decodeAndVerifySignature (JWT.hmacSecret jwtSecret) token
unClaimsMap (JWT.unregisteredClaims (JWT.claims jwt)) !? jwtKey
jwtKey :: Text
jwtKey = "jwt"
extractToken :: Text -> Maybe Text
extractToken auth
| toLower x == "token" = Just $ dropWhile isSpace y
| otherwise = Nothing
where (x, y) = break isSpace auth
| null | https://raw.githubusercontent.com/tzemanovic/haskell-yesod-realworld-example-app/d9f5191a909fa3c0087c5f28fcaae7ad1eca8b9a/app/src/Auth/JWT.hs | haskell | # LANGUAGE OverloadedStrings #
| Create a token out of a given JSON 'Value'
| Extract a JSON 'Value' out of a token | # LANGUAGE NoImplicitPrelude #
module Auth.JWT
( lookupToken
, jsonToToken
, tokenToJson
)
where
import ClassyPrelude.Yesod
import Data.Char (isSpace)
import Data.Map as Map (fromList, (!?))
import Web.JWT as JWT
| Try to lookup token from the Authorization header
lookupToken :: MonadHandler m => m (Maybe Text)
lookupToken = do
mAuth <- lookupHeader "Authorization"
return $ extractToken . decodeUtf8 =<< mAuth
jsonToToken :: Text -> Value -> Text
jsonToToken jwtSecret userId =
encodeSigned (JWT.hmacSecret jwtSecret)
mempty {unregisteredClaims = ClaimsMap $ Map.fromList [(jwtKey, userId)]}
tokenToJson :: Text -> Text -> Maybe Value
tokenToJson jwtSecret token = do
jwt <- JWT.decodeAndVerifySignature (JWT.hmacSecret jwtSecret) token
unClaimsMap (JWT.unregisteredClaims (JWT.claims jwt)) !? jwtKey
jwtKey :: Text
jwtKey = "jwt"
extractToken :: Text -> Maybe Text
extractToken auth
| toLower x == "token" = Just $ dropWhile isSpace y
| otherwise = Nothing
where (x, y) = break isSpace auth
|
5280b3e132c0c90f62f56092cb3dfa7f7392891be88eb398517d10ab6620a820 | evrim/core-server | xml.lisp | ;; +------------------------------------------------------------------------
;; | XML Base
;; +------------------------------------------------------------------------
(in-package :core-server)
;; -------------------------------------------------------------------------
Protocol
;; -------------------------------------------------------------------------
(defgeneric xml.tag (xml)
(:documentation "Returns tag"))
(defgeneric xml.namespace (xml)
(:documentation "Returns namespace"))
(defgeneric xml.attributes (xml)
(:documentation "Returns symbol names of attributes"))
(defgeneric xml.attribute (xml attribute)
(:documentation "Returns the value of the 'attribute'"))
(defgeneric xml.children (xml)
(:documentation "Returns children of xml node"))
(defgeneric xml.equal (a b)
(:documentation "XML Equivalence Predicate")
(:method ((a t) (b t)) (eq a b))
(:method ((a string) (b string)) (equal a b)))
;; -------------------------------------------------------------------------
XML
;; -------------------------------------------------------------------------
(defclass xml+ (class+)
((tag :initform nil :initarg :tag :reader xml+.tag)
(namespace :initform nil :initarg :namespace :reader xml+.namespace)
(schema :initform nil :initarg :schema :reader xml+.schema)
(attributes :initarg :attributes :initform nil :reader xml+.attributes)))
(defmethod class+.ctor ((self xml+))
(let ((name (class+.name self)))
`(progn
(fmakunbound ',(class+.ctor-name self))
(defun ,(class+.ctor-name self) (&rest args)
(multiple-value-bind (attributes children) (tag-attributes args)
(apply #'make-instance ',name
(list* :children (flatten children) attributes)))))))
;; -------------------------------------------------------------------------
;; XML Base Class
;; -------------------------------------------------------------------------
(defclass xml ()
((xmlns :initarg :xmlns :accessor xml.xmlns)
(children :initform nil :initarg :children :accessor xml.children)))
(defmethod xml.tag ((xml xml))
(any (lambda (a) (and (typep a 'xml+) (xml+.tag a)))
(class+.superclasses (class-of xml))))
(defmethod xml.attributes ((xml xml))
(any (lambda (a) (and (typep a 'xml+) (xml+.attributes a)))
(class-superclasses (class-of xml))))
(defmethod xml.namespace ((xml xml))
(any (lambda (a) (and (typep a 'xml+) (xml+.namespace a)))
(class-superclasses (class-of xml))))
(defmethod xml.attribute ((xml xml) attribute)
(slot-value xml attribute))
(defmethod xml.equal ((a xml) (b xml))
(and
(string= (xml.tag a) (xml.tag b))
(string= (xml.namespace a) (xml.namespace b))
(reduce (lambda (acc attr)
(and acc (xml.equal (xml.attribute a attr)
(xml.attribute a attr))))
(xml.attributes a)
:initial-value t)
(= (length (xml.children a)) (length (xml.children b)))
(reduce (lambda (acc child)
(and acc (xml.equal (car child) (cdr child))))
(mapcar #'cons (xml.children a) (xml.children b))
:initial-value t)))
(defmethod xml.children ((self t)) nil)
(defun make-xml-type-matcher (type)
(lambda (a) (typep a type)))
(defun xml-search (elements goal-p &optional (successor #'xml.children))
(let ((result))
(core-search (if (listp elements)
elements
(list elements))
(lambda (a)
(if (typep a 'xml)
(if (funcall goal-p a)
(pushnew a result)))
nil)
successor
#'append)
result))
(defun filter-xml-nodes (root goal-p)
(cond
((stringp root) root)
(t
(let ((ctor (core-server::class+.ctor-name (class-of root))))
(apply ctor
(append (reduce0
(lambda (acc attribute)
(aif (xml.attribute root attribute)
(cons (make-keyword attribute)
(cons it acc))
acc))
(xml.attributes root))
(nreverse
(reduce0 (lambda (acc child)
(if (and (not (stringp child))
(funcall goal-p child))
acc
(cons (filter-xml-nodes child goal-p)
acc)))
(xml.children root)))))))))
;; -------------------------------------------------------------------------
XML defining macro :
;; -------------------------------------------------------------------------
(defmacro defxml (name &rest attributes)
`(defclass+ ,name (xml)
(,@(mapcar (lambda (attr) (list attr :print t))
attributes))
(:metaclass xml+)
(:tag ,@(string-downcase (symbol-name name)))
(:namespace ,@(string-downcase
(subseq (package-name (symbol-package name)) 1)))
(:attributes ,@attributes)))
;; -------------------------------------------------------------------------
;; XML Generic Class
;; -------------------------------------------------------------------------
(defclass generic-xml (xml)
((tag :initarg :tag :initform nil :accessor xml.tag)
(namespace :initarg :namespace :initform nil :accessor xml.namespace)
(attributes :initarg :attributes :initform nil)))
(defmethod xml.attributes ((xml generic-xml))
(mapcar #'car (slot-value xml 'attributes)))
(defmethod xml.attribute ((xml generic-xml) attribute)
(cdr (assoc attribute (slot-value xml 'attributes))))
;; -------------------------------------------------------------------------
;; Generic XML Constructor
;; -------------------------------------------------------------------------
(defun xml (tag namespace attributes &rest children)
(make-instance 'generic-xml
:tag tag
:namespace namespace
:attributes attributes
:children (flatten children)))
(defprint-object (self generic-xml)
(with-slots (tag namespace attributes children) self
(if namespace
(format *standard-output* "<~A:~A(~D)~{ ~A~}>"
namespace tag (length children) attributes)
(format *standard-output* "<~A(~D)~{ ~A~}>"
tag (length children) attributes))))
;;---------------------------------------------------------------------------
XML Parser
;;---------------------------------------------------------------------------
(defatom xml-attribute-char? ()
(or (alphanum? c) (= c #.(char-code #\-)) (= c #.(char-code #\_))))
(defrule xml-attribute-name? (c attribute namespace)
(:type xml-attribute-char? c)
(:do (setq attribute (make-accumulator)))
(:collect c attribute)
(:zom (:type xml-attribute-char? c) (:collect c attribute))
(:or (:and #\:
(:do (setq namespace attribute)
(setq attribute (make-accumulator)))
(:oom (:type xml-attribute-char? c)
(:collect c attribute))
(:return (if namespace
(values attribute namespace)
attribute)))
(:return (if namespace
(values attribute namespace)
attribute))))
(defrule xml-attribute-value? (c val)
(:or (:and (:quoted? val) (:return val))
(:and (:oom (:not #\Space) (:not #\>) (:not #\/)
(:not #\") (:not #\')
(:do (setq val (make-accumulator :byte)))
(:type octet? c) (:collect c val))
(:return (if val (octets-to-string val :utf-8))))))
(defrule xml-attribute? (name value)
(:xml-attribute-name? name)
#\=
(:xml-attribute-value? value)
(:return (cons name value)))
(defrule xml-tag-name? (tag namespace)
(:xml-attribute-name? tag namespace)
(:return (values tag namespace)))
(defrule xml-lwsp? (c)
(:oom (:or (:and (:type (or space? tab?)))
(:and (:type (or carriage-return? linefeed?))
(:do (setf c t))))
(:if c
(:return #\Newline)
(:return #\Space))))
(defrule xml-text-node? (c acc)
(:not #\/)
;; (:not #\<)
(: checkpoint # \ < (: rewind - return ( octets - to - string acc : utf-8 ) ) )
(: and # \ & (: or (: and (: seq " gt ; " ) (: do ( setf c # \ < ) ) )
(: and (: seq " lt ; " ) (: do ( setf c # \ > ) ) ) ) )
(:and (:seq ">") (:do (setf c #\<)))
(:and (:seq "<") (:do (setf c #\>)))
(:and (:seq """) (:do (setf c #\")))
(:xml-lwsp? c)
(:type octet? c))
(:do (setq acc (make-accumulator :byte)))
(:collect c acc)
(:zom (:not #\<)
(: checkpoint # \ < (: rewind - return ( octets - to - string acc : utf-8 ) ) )
(:or (:and (:seq ">") (:do (setf c #\<)))
(:and (:seq "<") (:do (setf c #\>)))
(:and (:seq """) (:do (setf c #\")))
(: and # \ & (: or (: and (: seq " gt ; " ) (: do ( setf c # \ < ) ) )
(: and (: seq " lt ; " ) (: do ( setf c # \ > ) ) ) ) )
(:xml-lwsp? c)
(:type octet? c))
(:collect c acc))
(:if (> (length acc) 0)
(:return (octets-to-string acc :utf-8))))
(defrule xml-cdata? (c acc)
(:seq "CDATA[")
(:do (setq acc (make-accumulator :byte)))
(:zom (:not (:seq "]]>")) (:type octet? c) (:collect c acc))
(:return (octets-to-string acc :utf-8)))
(defrule xml-comment? (c acc)
;; #\<
;; #\!
#\- #\- ;; (:seq "<!--")
(:do (setq acc (make-accumulator)))
(:collect #\< acc) (:collect #\! acc)
(:collect #\- acc) (:collect #\- acc)
(:zom (:not (:seq "-->"))
(:type octet? c)
(:collect c acc))
(:collect #\- acc)
(:collect #\- acc)
(:collect #\> acc)
(:return acc))
(defparser %xml-lexer? (tag namespace attr attrs child children
a b c d)
(:xml-tag-name? tag namespace)
(:zom (:lwsp?) (:xml-attribute? attr)
(:do (push attr attrs)))
(:or
(:and (:lwsp?) (:seq "/>")
(:return (values tag namespace (nreverse attrs))))
(:and #\>
(:checkpoint
(:zom (:lwsp?)
;; (:debug)
(:or
(:and #\<
(:or (:and #\!
(:or (:xml-cdata? child)
(:xml-comment? child))
(:do (push child children)))
(:and (:%xml-lexer? a b c d)
(:do (push (list* a b c d) children)))))
(:and (:%xml-lexer? a b c d)
(:do (push (list* a b c d) children)))
(:and (:xml-text-node? child)
(:do (push child children))
# \/
;; (:if namespace
;; (:and (:sci namespace) #\: (:sci tag))
;; (:sci tag))
;; #\>
(: return ( values tag namespace ( )
( children ) ) )
)
))
(:or (:and #\/
(:if namespace
(:and (:sci namespace) #\: (:sci tag))
(:sci tag))
#\>
(:return (values tag namespace (nreverse attrs)
(nreverse children))))
(:rewind-return (values tag namespace (nreverse attrs))))))))
(defparser xml-lexer? (tag namespace attrs children child)
(:lwsp?)
(:checkpoint (:seq "<?xml")
(:zom (:not #\>) (:type octet?)) (:lwsp?) (:commit))
(:checkpoint (:seq "<!DOCTYPE")
(:zom (:not #\>) (:type octet?)) (:lwsp?) (:commit))
#\<
(:optional #\! (:or (:xml-cdata? child) (:xml-comment? child))
(:lwsp?) #\<)
(:%xml-lexer? tag namespace attrs children)
(:return (list* tag namespace attrs children)))
(defvar +xml-namespace+ (find-package :<))
(defparameter +xml-namespaces-table+
(list (cons "" (find-package :<db))
(cons "" (find-package :<core-server))
(cons "" (find-package :<xs))
(cons "" (find-package :<atom))
(cons "" (find-package :<gphoto))
(cons "/" (find-package :<media))
(cons ""
(find-package :<open-search))
(cons "/" (find-package :<wordpress))
(cons "/" (find-package :<content))
(cons "/" (find-package :<dc))
(cons "/" (find-package :<excerpt))))
(defun register-xml-namespace (namespace package)
(let ((package (find-package package)))
(assert (not (null package)))
(setf +xml-namespaces-table+
(cons (cons namespace package)
(remove namespace +xml-namespaces-table+ :key #'car :test #'equal)))))
(declaim (inline xml->symbol))
(defun xml->symbol (name &optional package)
(let ((a (reduce (lambda (acc a)
(cond
((and (> (char-code a) 64)
(< (char-code a) 91))
(push-atom #\- acc)
(push-atom (code-char (+ (char-code a)
32))
acc))
(t (push-atom a acc)))
acc)
name :initial-value (make-accumulator))))
(if package
(intern (string-upcase a) package)
(intern (string-upcase a) (find-package :<)))))
(defun parse-xml (xml &optional default-namespace)
(labels ((make-generic-element (tag namespace attributes children)
(warn "<~A:~A> tag not found, using generic xml element."
namespace tag)
(apply #'xml tag namespace
(cons attributes (mapcar #'parse-xml children))))
(make-element (symbol attributes children)
(apply symbol
(append
(reduce0 (lambda (acc attr)
(cons (js->keyword (car attr))
(cons (cdr attr) acc)))
attributes)
(mapcar #'parse-xml children)))))
(if (atom xml)
xml
(destructuring-bind (tag namespace attributes &rest children) xml
(let* ((+xml-namespace+
(acond
((and namespace (find-package
(make-keyword
(format nil "<~A"
(symbol-name
(xml->symbol namespace))))))
it)
((cdr (assoc (cdr
(assoc "xmlns" attributes :test #'string=))
+xml-namespaces-table+ :test #'string=))
it)
((and default-namespace
(find-package
(make-keyword
(format nil "<~A"
(symbol-name
(xml->symbol default-namespace))))))
it)
(t +xml-namespace+)))
(symbol (let ((symbol1 (xml->symbol tag +xml-namespace+))
(symbol2 (intern tag +xml-namespace+)))
(if (fboundp symbol1)
symbol1
(if (fboundp symbol2)
symbol2)))))
(if (and symbol
(not (eq (symbol-package symbol) #.(find-package :cl)))
;; (not (eq (symbol-package symbol) #.(find-package :arnesi)))
)
(let ((instance (make-element symbol attributes children)))
(if (slot-exists-p instance 'tag)
(setf (slot-value instance 'tag) tag))
(if (slot-exists-p instance 'namespace)
(setf (slot-value instance 'namespace) namespace))
instance)
(make-generic-element tag namespace attributes children)))))))
;; +------------------------------------------------------------------------
;; | XML Stream
;; +------------------------------------------------------------------------
(defclass xml-stream (wrapping-stream)
((namespace :initform nil :initarg :namespace :reader namespace)))
(defun make-xml-stream (stream &optional namespace)
(make-instance 'xml-stream :stream stream
:namespace namespace))
(defmethod read-stream ((stream xml-stream))
(parse-xml (xml-lexer? (slot-value stream '%stream))
(namespace stream)))
(defmethod write-stream ((stream xml-stream) (list list))
(reduce #'write-stream list :initial-value stream))
(defmethod write-stream ((stream xml-stream) (string string))
(prog1 stream
(with-slots (%stream) stream
(disable-indentation %stream)
(string! %stream
(reduce (lambda (acc atom)
(cond
((eq atom #\<)
(push-atom #\& acc)
(push-atom #\g acc)
(push-atom #\t acc)
(push-atom #\; acc))
((eq atom #\>)
(push-atom #\& acc)
(push-atom #\l acc)
(push-atom #\t acc)
(push-atom #\; acc))
(t
(push-atom atom acc)))
acc)
string
:initial-value (make-accumulator)))
(enable-indentation %stream))))
(defmethod intro! ((stream xml-stream) (object xml))
(with-slots (%stream) stream
(let ((tag (xml.tag object))
(namespace (xml.namespace object)))
(char! %stream #\<)
(if (and namespace (not (equal namespace (namespace stream))))
(progn
(string! %stream namespace)
(char! %stream #\:)
(string! %stream tag))
(string! %stream tag)))
stream))
(defmethod attribute! ((stream xml-stream) attribute)
(with-slots (%stream) stream
(char! %stream #\Space)
(if (symbolp (car attribute))
(string! %stream (symbol-to-js (car attribute)))
(string! %stream (car attribute)))
(char! %stream #\=)
(quoted! %stream (format nil "~A" (cdr attribute)))
stream))
(defmethod child! ((stream xml-stream) object)
(char! (slot-value stream '%stream) #\Newline)
(write-stream stream object)
stream)
(defmethod outro! ((stream xml-stream) (object xml))
(with-slots (%stream) stream
(let ((tag (xml.tag object))
(namespace (xml.namespace object)))
(string! %stream "</")
(if (and namespace (not (equal (namespace stream) namespace)))
(progn
(string! %stream namespace)
(char! %stream #\:)
(string! %stream tag))
(string! %stream tag))
(char! %stream #\>))
stream))
(defmethod write-stream ((stream xml-stream) (object xml))
(with-slots (%stream) stream
(intro! stream object)
(reduce #'attribute!
(reduce0 (lambda (acc slot)
(aif (slot-value object slot)
(cons (cons slot it) acc)
acc))
(xml.attributes object))
:initial-value stream)
(cond
((null (xml.children object))
(string! %stream "/>"))
((eq 1 (length (xml.children object)))
(stringp (car (xml.children object)))
(char! %stream #\>)
(write-stream stream (car (xml.children object)))
(outro! stream object))
(t
(char! %stream #\>)
(increase-indent %stream)
(reduce #'child!
(slot-value object 'children)
:initial-value stream)
(decrease-indent %stream)
(char! %stream #\Newline)
(outro! stream object)))
stream))
(defmethod write-stream ((stream xml-stream) (object generic-xml))
(with-slots (%stream) stream
(intro! stream object)
(reduce #'attribute!
(slot-value object 'attributes)
:initial-value stream)
(cond
((null (xml.children object))
(string! %stream "/>"))
((stringp (car (xml.children object)))
(char! %stream #\>)
(write-stream stream (car (xml.children object)))
(outro! stream object))
(t
(char! %stream #\>)
(increase-indent %stream)
(reduce #'child!
(slot-value object 'children)
:initial-value stream)
(decrease-indent %stream)
(char! %stream #\Newline)
(outro! stream object)))
stream))
(deftrace xml-render
'(intro! outro! child! write-stream attribute!))
;;---------------------------------------------------------------------------
Relaxed XML Parser
;;---------------------------------------------------------------------------
;; This is a duplicate of the xml parser that is slow but allows
;; us to parse some of the broken xml's like HTML.
-us/library/ms537495.aspx
(eval-when (:load-toplevel :compile-toplevel :execute)
(defparameter +xml-entities+
'(("gt" . #\<)
("lt" . #\>)
("quot" . #\")
("nbsp" . #\Space)
("amp" . #\&)
("Uuml" . #\Ü)
("Ouml" . #\Ö)
("Ccedil" . #\Ç)
("uuml" . #\ü)
("ouml" . #\ö)
("ccedil" . #\ç))))
(defmacro defxml-entity-parser (entities)
`(defparser xml-entity? ()
(:or ,@(mapcar (lambda (e)
`(:and (:seq ,(format nil "~A;" (car e)))
(:return ,(cdr e))))
(symbol-value entities)))))
(defxml-entity-parser +xml-entities+)
(defrule relaxed-xml-text-node? (c (acc (make-accumulator :byte)))
(:debug)
(:not #\<)
(: checkpoint # \ < (: rewind - return ( octets - to - string acc : utf-8 ) ) )
(:oom (:checkpoint #\< (:rewind-return (octets-to-string acc :utf-8)))
(:or (:and #\& (:xml-entity? c)
(:do (reduce (lambda (acc a)
(push-atom a acc)
acc)
(string-to-octets (format nil "~A" c) :utf-8)
:initial-value acc)))
(:and (:or (:xml-lwsp? c)
(:type octet? c)) (:collect c acc))))
(:if (> (length acc) 0)
(:return (octets-to-string acc :utf-8))))
(defrule relaxed-xml-comment? (c acc)
(:seq "<!--")
(:do (setq acc (make-accumulator :byte)))
(:collect #\< acc) (:collect #\! acc)
(:collect #\- acc) (:collect #\- acc)
(:zom (:not (:seq "-->")) (:type octet? c) (:collect c acc))
(:collect #\- acc) (:collect #\- acc) (:collect #\> acc)
(:return (octets-to-string acc :utf-8)))
(defparser %relaxed-xml-lexer? (tag namespace attr attrs child children
immediate)
#\<
(:xml-tag-name? tag namespace)
(:do (describe (list tag namespace)))
(:debug)
(:zom (:lwsp?) (:xml-attribute? attr)
(:do (push attr attrs)))
(:or (:and (:lwsp?)
(:seq "/>")
(:return (list tag namespace (nreverse attrs))))
(:and #\>
(:zom (:lwsp?)
(:or
(:debug)
(:checkpoint
(:seq "</")
(:if namespace
(:not (:and (:sci namespace) #\: (:sci tag)))
(:not (:sci tag)))
(:debug)
(:do (describe (list 'foo tag namespace children) ))
(:rewind-return nil ;; (values
( list * tag namespace ( )
( nreverse children ) )
;; t)
))
(:oom (:%relaxed-xml-lexer? child)
(:do (push child children)))
(:relaxed-xml-comment? child)
(:xml-text-node? child)
(:xml-cdata? child))
(:do (push child children)))
(:or (:and (:seq "</")
(:if namespace
(:and (:sci namespace) #\: (:sci tag))
(:sci tag))
#\>
(:return (list* tag namespace (nreverse attrs)
(nreverse children))))
(:return (list* tag namespace (nreverse attrs)
(nreverse children)))))))
(defparser relaxed-xml-lexer? (tag namespace attr attrs child children)
(:lwsp?)
(:checkpoint (:seq "<?xml")
(:zom (:not #\>) (:type octet?)) (:lwsp?) (:commit))
(:checkpoint (:sci "<!DOCTYPE")
(:zom (:not #\>) (:type octet?)) (:lwsp?) (:commit))
(:zom (:lwsp?) (:relaxed-xml-comment? child) (:lwsp?))
(:%relaxed-xml-lexer? tag)
(:return tag))
;; +------------------------------------------------------------------------
;; | Relaxed XML Stream
;; +------------------------------------------------------------------------
(defclass relaxed-xml-stream (xml-stream)
())
(defun make-relaxed-xml-stream (stream &optional namespace)
(make-instance 'relaxed-xml-stream :stream stream
:namespace namespace))
(defmethod read-stream ((stream relaxed-xml-stream))
(parse-xml (xml-lexer? (slot-value stream '%stream))
(namespace stream)))
(defmethod write-stream ((stream relaxed-xml-stream) (object xml))
(with-slots (%stream) stream
(intro! stream object)
(reduce #'attribute!
(reduce0 (lambda (acc slot)
(aif (slot-value object slot)
(cons (cons slot it) acc)
acc))
(xml.attributes object))
:initial-value stream)
(cond
;; ((null (xml.children object))
;; (string! %stream "/>"))
((eq 1 (length (xml.children object)))
(stringp (car (xml.children object)))
(char! %stream #\>)
(write-stream stream (car (xml.children object)))
(outro! stream object))
(t
(char! %stream #\>)
(increase-indent %stream)
(reduce #'child!
(slot-value object 'children)
:initial-value stream)
(decrease-indent %stream)
(char! %stream #\Newline)
(outro! stream object)))
stream))
(defmethod write-stream ((stream relaxed-xml-stream) (object generic-xml))
(with-slots (%stream) stream
(intro! stream object)
(reduce #'attribute!
(slot-value object 'attributes)
:initial-value stream)
(cond
;; ((null (xml.children object))
;; (string! %stream "/>"))
((stringp (car (xml.children object)))
(char! %stream #\>)
(write-stream stream (car (xml.children object)))
(outro! stream object))
(t
(char! %stream #\>)
(increase-indent %stream)
(reduce #'child!
(slot-value object 'children)
:initial-value stream)
(decrease-indent %stream)
(char! %stream #\Newline)
(outro! stream object)))
stream))
;; -------------------------------------------------------------------------
;; Trace Definition
;; -------------------------------------------------------------------------
(deftrace xml-parsers
'(xml-tag-name? xml-lexer? xml-comment? xml-text-node?
xml-cdata? %xml-lexer? xml-lwsp? xml-attribute?
xml-attribute-name? xml-attribute-value?
xml-tag-name? relaxed-xml-lexer? relaxed-xml-comment?
relaxed-xml-text-node? xml-cdata? xml-lwsp?
xml-attribute? xml-attribute-name?
xml-attribute-value? parse-xml))
| null | https://raw.githubusercontent.com/evrim/core-server/200ea8151d2f8d81b593d605b183a9cddae1e82d/src/markup/xml.lisp | lisp | +------------------------------------------------------------------------
| XML Base
+------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
XML Base Class
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
XML Generic Class
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Generic XML Constructor
-------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
(:not #\<)
#\<
#\!
(:seq "<!--")
(:debug)
(:if namespace
(:and (:sci namespace) #\: (:sci tag))
(:sci tag))
#\>
(not (eq (symbol-package symbol) #.(find-package :arnesi)))
+------------------------------------------------------------------------
| XML Stream
+------------------------------------------------------------------------
acc))
acc))
---------------------------------------------------------------------------
---------------------------------------------------------------------------
This is a duplicate of the xml parser that is slow but allows
us to parse some of the broken xml's like HTML.
(values
t)
+------------------------------------------------------------------------
| Relaxed XML Stream
+------------------------------------------------------------------------
((null (xml.children object))
(string! %stream "/>"))
((null (xml.children object))
(string! %stream "/>"))
-------------------------------------------------------------------------
Trace Definition
------------------------------------------------------------------------- | (in-package :core-server)
Protocol
(defgeneric xml.tag (xml)
(:documentation "Returns tag"))
(defgeneric xml.namespace (xml)
(:documentation "Returns namespace"))
(defgeneric xml.attributes (xml)
(:documentation "Returns symbol names of attributes"))
(defgeneric xml.attribute (xml attribute)
(:documentation "Returns the value of the 'attribute'"))
(defgeneric xml.children (xml)
(:documentation "Returns children of xml node"))
(defgeneric xml.equal (a b)
(:documentation "XML Equivalence Predicate")
(:method ((a t) (b t)) (eq a b))
(:method ((a string) (b string)) (equal a b)))
XML
(defclass xml+ (class+)
((tag :initform nil :initarg :tag :reader xml+.tag)
(namespace :initform nil :initarg :namespace :reader xml+.namespace)
(schema :initform nil :initarg :schema :reader xml+.schema)
(attributes :initarg :attributes :initform nil :reader xml+.attributes)))
(defmethod class+.ctor ((self xml+))
(let ((name (class+.name self)))
`(progn
(fmakunbound ',(class+.ctor-name self))
(defun ,(class+.ctor-name self) (&rest args)
(multiple-value-bind (attributes children) (tag-attributes args)
(apply #'make-instance ',name
(list* :children (flatten children) attributes)))))))
(defclass xml ()
((xmlns :initarg :xmlns :accessor xml.xmlns)
(children :initform nil :initarg :children :accessor xml.children)))
(defmethod xml.tag ((xml xml))
(any (lambda (a) (and (typep a 'xml+) (xml+.tag a)))
(class+.superclasses (class-of xml))))
(defmethod xml.attributes ((xml xml))
(any (lambda (a) (and (typep a 'xml+) (xml+.attributes a)))
(class-superclasses (class-of xml))))
(defmethod xml.namespace ((xml xml))
(any (lambda (a) (and (typep a 'xml+) (xml+.namespace a)))
(class-superclasses (class-of xml))))
(defmethod xml.attribute ((xml xml) attribute)
(slot-value xml attribute))
(defmethod xml.equal ((a xml) (b xml))
(and
(string= (xml.tag a) (xml.tag b))
(string= (xml.namespace a) (xml.namespace b))
(reduce (lambda (acc attr)
(and acc (xml.equal (xml.attribute a attr)
(xml.attribute a attr))))
(xml.attributes a)
:initial-value t)
(= (length (xml.children a)) (length (xml.children b)))
(reduce (lambda (acc child)
(and acc (xml.equal (car child) (cdr child))))
(mapcar #'cons (xml.children a) (xml.children b))
:initial-value t)))
(defmethod xml.children ((self t)) nil)
(defun make-xml-type-matcher (type)
(lambda (a) (typep a type)))
(defun xml-search (elements goal-p &optional (successor #'xml.children))
(let ((result))
(core-search (if (listp elements)
elements
(list elements))
(lambda (a)
(if (typep a 'xml)
(if (funcall goal-p a)
(pushnew a result)))
nil)
successor
#'append)
result))
(defun filter-xml-nodes (root goal-p)
(cond
((stringp root) root)
(t
(let ((ctor (core-server::class+.ctor-name (class-of root))))
(apply ctor
(append (reduce0
(lambda (acc attribute)
(aif (xml.attribute root attribute)
(cons (make-keyword attribute)
(cons it acc))
acc))
(xml.attributes root))
(nreverse
(reduce0 (lambda (acc child)
(if (and (not (stringp child))
(funcall goal-p child))
acc
(cons (filter-xml-nodes child goal-p)
acc)))
(xml.children root)))))))))
XML defining macro :
(defmacro defxml (name &rest attributes)
`(defclass+ ,name (xml)
(,@(mapcar (lambda (attr) (list attr :print t))
attributes))
(:metaclass xml+)
(:tag ,@(string-downcase (symbol-name name)))
(:namespace ,@(string-downcase
(subseq (package-name (symbol-package name)) 1)))
(:attributes ,@attributes)))
(defclass generic-xml (xml)
((tag :initarg :tag :initform nil :accessor xml.tag)
(namespace :initarg :namespace :initform nil :accessor xml.namespace)
(attributes :initarg :attributes :initform nil)))
(defmethod xml.attributes ((xml generic-xml))
(mapcar #'car (slot-value xml 'attributes)))
(defmethod xml.attribute ((xml generic-xml) attribute)
(cdr (assoc attribute (slot-value xml 'attributes))))
(defun xml (tag namespace attributes &rest children)
(make-instance 'generic-xml
:tag tag
:namespace namespace
:attributes attributes
:children (flatten children)))
(defprint-object (self generic-xml)
(with-slots (tag namespace attributes children) self
(if namespace
(format *standard-output* "<~A:~A(~D)~{ ~A~}>"
namespace tag (length children) attributes)
(format *standard-output* "<~A(~D)~{ ~A~}>"
tag (length children) attributes))))
XML Parser
(defatom xml-attribute-char? ()
(or (alphanum? c) (= c #.(char-code #\-)) (= c #.(char-code #\_))))
(defrule xml-attribute-name? (c attribute namespace)
(:type xml-attribute-char? c)
(:do (setq attribute (make-accumulator)))
(:collect c attribute)
(:zom (:type xml-attribute-char? c) (:collect c attribute))
(:or (:and #\:
(:do (setq namespace attribute)
(setq attribute (make-accumulator)))
(:oom (:type xml-attribute-char? c)
(:collect c attribute))
(:return (if namespace
(values attribute namespace)
attribute)))
(:return (if namespace
(values attribute namespace)
attribute))))
(defrule xml-attribute-value? (c val)
(:or (:and (:quoted? val) (:return val))
(:and (:oom (:not #\Space) (:not #\>) (:not #\/)
(:not #\") (:not #\')
(:do (setq val (make-accumulator :byte)))
(:type octet? c) (:collect c val))
(:return (if val (octets-to-string val :utf-8))))))
(defrule xml-attribute? (name value)
(:xml-attribute-name? name)
#\=
(:xml-attribute-value? value)
(:return (cons name value)))
(defrule xml-tag-name? (tag namespace)
(:xml-attribute-name? tag namespace)
(:return (values tag namespace)))
(defrule xml-lwsp? (c)
(:oom (:or (:and (:type (or space? tab?)))
(:and (:type (or carriage-return? linefeed?))
(:do (setf c t))))
(:if c
(:return #\Newline)
(:return #\Space))))
(defrule xml-text-node? (c acc)
(:not #\/)
(: checkpoint # \ < (: rewind - return ( octets - to - string acc : utf-8 ) ) )
(: and # \ & (: or (: and (: seq " gt ; " ) (: do ( setf c # \ < ) ) )
(: and (: seq " lt ; " ) (: do ( setf c # \ > ) ) ) ) )
(:and (:seq ">") (:do (setf c #\<)))
(:and (:seq "<") (:do (setf c #\>)))
(:and (:seq """) (:do (setf c #\")))
(:xml-lwsp? c)
(:type octet? c))
(:do (setq acc (make-accumulator :byte)))
(:collect c acc)
(:zom (:not #\<)
(: checkpoint # \ < (: rewind - return ( octets - to - string acc : utf-8 ) ) )
(:or (:and (:seq ">") (:do (setf c #\<)))
(:and (:seq "<") (:do (setf c #\>)))
(:and (:seq """) (:do (setf c #\")))
(: and # \ & (: or (: and (: seq " gt ; " ) (: do ( setf c # \ < ) ) )
(: and (: seq " lt ; " ) (: do ( setf c # \ > ) ) ) ) )
(:xml-lwsp? c)
(:type octet? c))
(:collect c acc))
(:if (> (length acc) 0)
(:return (octets-to-string acc :utf-8))))
(defrule xml-cdata? (c acc)
(:seq "CDATA[")
(:do (setq acc (make-accumulator :byte)))
(:zom (:not (:seq "]]>")) (:type octet? c) (:collect c acc))
(:return (octets-to-string acc :utf-8)))
(defrule xml-comment? (c acc)
(:do (setq acc (make-accumulator)))
(:collect #\< acc) (:collect #\! acc)
(:collect #\- acc) (:collect #\- acc)
(:zom (:not (:seq "-->"))
(:type octet? c)
(:collect c acc))
(:collect #\- acc)
(:collect #\- acc)
(:collect #\> acc)
(:return acc))
(defparser %xml-lexer? (tag namespace attr attrs child children
a b c d)
(:xml-tag-name? tag namespace)
(:zom (:lwsp?) (:xml-attribute? attr)
(:do (push attr attrs)))
(:or
(:and (:lwsp?) (:seq "/>")
(:return (values tag namespace (nreverse attrs))))
(:and #\>
(:checkpoint
(:zom (:lwsp?)
(:or
(:and #\<
(:or (:and #\!
(:or (:xml-cdata? child)
(:xml-comment? child))
(:do (push child children)))
(:and (:%xml-lexer? a b c d)
(:do (push (list* a b c d) children)))))
(:and (:%xml-lexer? a b c d)
(:do (push (list* a b c d) children)))
(:and (:xml-text-node? child)
(:do (push child children))
# \/
(: return ( values tag namespace ( )
( children ) ) )
)
))
(:or (:and #\/
(:if namespace
(:and (:sci namespace) #\: (:sci tag))
(:sci tag))
#\>
(:return (values tag namespace (nreverse attrs)
(nreverse children))))
(:rewind-return (values tag namespace (nreverse attrs))))))))
(defparser xml-lexer? (tag namespace attrs children child)
(:lwsp?)
(:checkpoint (:seq "<?xml")
(:zom (:not #\>) (:type octet?)) (:lwsp?) (:commit))
(:checkpoint (:seq "<!DOCTYPE")
(:zom (:not #\>) (:type octet?)) (:lwsp?) (:commit))
#\<
(:optional #\! (:or (:xml-cdata? child) (:xml-comment? child))
(:lwsp?) #\<)
(:%xml-lexer? tag namespace attrs children)
(:return (list* tag namespace attrs children)))
(defvar +xml-namespace+ (find-package :<))
(defparameter +xml-namespaces-table+
(list (cons "" (find-package :<db))
(cons "" (find-package :<core-server))
(cons "" (find-package :<xs))
(cons "" (find-package :<atom))
(cons "" (find-package :<gphoto))
(cons "/" (find-package :<media))
(cons ""
(find-package :<open-search))
(cons "/" (find-package :<wordpress))
(cons "/" (find-package :<content))
(cons "/" (find-package :<dc))
(cons "/" (find-package :<excerpt))))
(defun register-xml-namespace (namespace package)
(let ((package (find-package package)))
(assert (not (null package)))
(setf +xml-namespaces-table+
(cons (cons namespace package)
(remove namespace +xml-namespaces-table+ :key #'car :test #'equal)))))
(declaim (inline xml->symbol))
(defun xml->symbol (name &optional package)
(let ((a (reduce (lambda (acc a)
(cond
((and (> (char-code a) 64)
(< (char-code a) 91))
(push-atom #\- acc)
(push-atom (code-char (+ (char-code a)
32))
acc))
(t (push-atom a acc)))
acc)
name :initial-value (make-accumulator))))
(if package
(intern (string-upcase a) package)
(intern (string-upcase a) (find-package :<)))))
(defun parse-xml (xml &optional default-namespace)
(labels ((make-generic-element (tag namespace attributes children)
(warn "<~A:~A> tag not found, using generic xml element."
namespace tag)
(apply #'xml tag namespace
(cons attributes (mapcar #'parse-xml children))))
(make-element (symbol attributes children)
(apply symbol
(append
(reduce0 (lambda (acc attr)
(cons (js->keyword (car attr))
(cons (cdr attr) acc)))
attributes)
(mapcar #'parse-xml children)))))
(if (atom xml)
xml
(destructuring-bind (tag namespace attributes &rest children) xml
(let* ((+xml-namespace+
(acond
((and namespace (find-package
(make-keyword
(format nil "<~A"
(symbol-name
(xml->symbol namespace))))))
it)
((cdr (assoc (cdr
(assoc "xmlns" attributes :test #'string=))
+xml-namespaces-table+ :test #'string=))
it)
((and default-namespace
(find-package
(make-keyword
(format nil "<~A"
(symbol-name
(xml->symbol default-namespace))))))
it)
(t +xml-namespace+)))
(symbol (let ((symbol1 (xml->symbol tag +xml-namespace+))
(symbol2 (intern tag +xml-namespace+)))
(if (fboundp symbol1)
symbol1
(if (fboundp symbol2)
symbol2)))))
(if (and symbol
(not (eq (symbol-package symbol) #.(find-package :cl)))
)
(let ((instance (make-element symbol attributes children)))
(if (slot-exists-p instance 'tag)
(setf (slot-value instance 'tag) tag))
(if (slot-exists-p instance 'namespace)
(setf (slot-value instance 'namespace) namespace))
instance)
(make-generic-element tag namespace attributes children)))))))
(defclass xml-stream (wrapping-stream)
((namespace :initform nil :initarg :namespace :reader namespace)))
(defun make-xml-stream (stream &optional namespace)
(make-instance 'xml-stream :stream stream
:namespace namespace))
(defmethod read-stream ((stream xml-stream))
(parse-xml (xml-lexer? (slot-value stream '%stream))
(namespace stream)))
(defmethod write-stream ((stream xml-stream) (list list))
(reduce #'write-stream list :initial-value stream))
(defmethod write-stream ((stream xml-stream) (string string))
(prog1 stream
(with-slots (%stream) stream
(disable-indentation %stream)
(string! %stream
(reduce (lambda (acc atom)
(cond
((eq atom #\<)
(push-atom #\& acc)
(push-atom #\g acc)
(push-atom #\t acc)
((eq atom #\>)
(push-atom #\& acc)
(push-atom #\l acc)
(push-atom #\t acc)
(t
(push-atom atom acc)))
acc)
string
:initial-value (make-accumulator)))
(enable-indentation %stream))))
(defmethod intro! ((stream xml-stream) (object xml))
(with-slots (%stream) stream
(let ((tag (xml.tag object))
(namespace (xml.namespace object)))
(char! %stream #\<)
(if (and namespace (not (equal namespace (namespace stream))))
(progn
(string! %stream namespace)
(char! %stream #\:)
(string! %stream tag))
(string! %stream tag)))
stream))
(defmethod attribute! ((stream xml-stream) attribute)
(with-slots (%stream) stream
(char! %stream #\Space)
(if (symbolp (car attribute))
(string! %stream (symbol-to-js (car attribute)))
(string! %stream (car attribute)))
(char! %stream #\=)
(quoted! %stream (format nil "~A" (cdr attribute)))
stream))
(defmethod child! ((stream xml-stream) object)
(char! (slot-value stream '%stream) #\Newline)
(write-stream stream object)
stream)
(defmethod outro! ((stream xml-stream) (object xml))
(with-slots (%stream) stream
(let ((tag (xml.tag object))
(namespace (xml.namespace object)))
(string! %stream "</")
(if (and namespace (not (equal (namespace stream) namespace)))
(progn
(string! %stream namespace)
(char! %stream #\:)
(string! %stream tag))
(string! %stream tag))
(char! %stream #\>))
stream))
(defmethod write-stream ((stream xml-stream) (object xml))
(with-slots (%stream) stream
(intro! stream object)
(reduce #'attribute!
(reduce0 (lambda (acc slot)
(aif (slot-value object slot)
(cons (cons slot it) acc)
acc))
(xml.attributes object))
:initial-value stream)
(cond
((null (xml.children object))
(string! %stream "/>"))
((eq 1 (length (xml.children object)))
(stringp (car (xml.children object)))
(char! %stream #\>)
(write-stream stream (car (xml.children object)))
(outro! stream object))
(t
(char! %stream #\>)
(increase-indent %stream)
(reduce #'child!
(slot-value object 'children)
:initial-value stream)
(decrease-indent %stream)
(char! %stream #\Newline)
(outro! stream object)))
stream))
(defmethod write-stream ((stream xml-stream) (object generic-xml))
(with-slots (%stream) stream
(intro! stream object)
(reduce #'attribute!
(slot-value object 'attributes)
:initial-value stream)
(cond
((null (xml.children object))
(string! %stream "/>"))
((stringp (car (xml.children object)))
(char! %stream #\>)
(write-stream stream (car (xml.children object)))
(outro! stream object))
(t
(char! %stream #\>)
(increase-indent %stream)
(reduce #'child!
(slot-value object 'children)
:initial-value stream)
(decrease-indent %stream)
(char! %stream #\Newline)
(outro! stream object)))
stream))
(deftrace xml-render
'(intro! outro! child! write-stream attribute!))
Relaxed XML Parser
-us/library/ms537495.aspx
(eval-when (:load-toplevel :compile-toplevel :execute)
(defparameter +xml-entities+
'(("gt" . #\<)
("lt" . #\>)
("quot" . #\")
("nbsp" . #\Space)
("amp" . #\&)
("Uuml" . #\Ü)
("Ouml" . #\Ö)
("Ccedil" . #\Ç)
("uuml" . #\ü)
("ouml" . #\ö)
("ccedil" . #\ç))))
(defmacro defxml-entity-parser (entities)
`(defparser xml-entity? ()
(:or ,@(mapcar (lambda (e)
`(:and (:seq ,(format nil "~A;" (car e)))
(:return ,(cdr e))))
(symbol-value entities)))))
(defxml-entity-parser +xml-entities+)
(defrule relaxed-xml-text-node? (c (acc (make-accumulator :byte)))
(:debug)
(:not #\<)
(: checkpoint # \ < (: rewind - return ( octets - to - string acc : utf-8 ) ) )
(:oom (:checkpoint #\< (:rewind-return (octets-to-string acc :utf-8)))
(:or (:and #\& (:xml-entity? c)
(:do (reduce (lambda (acc a)
(push-atom a acc)
acc)
(string-to-octets (format nil "~A" c) :utf-8)
:initial-value acc)))
(:and (:or (:xml-lwsp? c)
(:type octet? c)) (:collect c acc))))
(:if (> (length acc) 0)
(:return (octets-to-string acc :utf-8))))
(defrule relaxed-xml-comment? (c acc)
(:seq "<!--")
(:do (setq acc (make-accumulator :byte)))
(:collect #\< acc) (:collect #\! acc)
(:collect #\- acc) (:collect #\- acc)
(:zom (:not (:seq "-->")) (:type octet? c) (:collect c acc))
(:collect #\- acc) (:collect #\- acc) (:collect #\> acc)
(:return (octets-to-string acc :utf-8)))
(defparser %relaxed-xml-lexer? (tag namespace attr attrs child children
immediate)
#\<
(:xml-tag-name? tag namespace)
(:do (describe (list tag namespace)))
(:debug)
(:zom (:lwsp?) (:xml-attribute? attr)
(:do (push attr attrs)))
(:or (:and (:lwsp?)
(:seq "/>")
(:return (list tag namespace (nreverse attrs))))
(:and #\>
(:zom (:lwsp?)
(:or
(:debug)
(:checkpoint
(:seq "</")
(:if namespace
(:not (:and (:sci namespace) #\: (:sci tag)))
(:not (:sci tag)))
(:debug)
(:do (describe (list 'foo tag namespace children) ))
( list * tag namespace ( )
( nreverse children ) )
))
(:oom (:%relaxed-xml-lexer? child)
(:do (push child children)))
(:relaxed-xml-comment? child)
(:xml-text-node? child)
(:xml-cdata? child))
(:do (push child children)))
(:or (:and (:seq "</")
(:if namespace
(:and (:sci namespace) #\: (:sci tag))
(:sci tag))
#\>
(:return (list* tag namespace (nreverse attrs)
(nreverse children))))
(:return (list* tag namespace (nreverse attrs)
(nreverse children)))))))
(defparser relaxed-xml-lexer? (tag namespace attr attrs child children)
(:lwsp?)
(:checkpoint (:seq "<?xml")
(:zom (:not #\>) (:type octet?)) (:lwsp?) (:commit))
(:checkpoint (:sci "<!DOCTYPE")
(:zom (:not #\>) (:type octet?)) (:lwsp?) (:commit))
(:zom (:lwsp?) (:relaxed-xml-comment? child) (:lwsp?))
(:%relaxed-xml-lexer? tag)
(:return tag))
(defclass relaxed-xml-stream (xml-stream)
())
(defun make-relaxed-xml-stream (stream &optional namespace)
(make-instance 'relaxed-xml-stream :stream stream
:namespace namespace))
(defmethod read-stream ((stream relaxed-xml-stream))
(parse-xml (xml-lexer? (slot-value stream '%stream))
(namespace stream)))
(defmethod write-stream ((stream relaxed-xml-stream) (object xml))
(with-slots (%stream) stream
(intro! stream object)
(reduce #'attribute!
(reduce0 (lambda (acc slot)
(aif (slot-value object slot)
(cons (cons slot it) acc)
acc))
(xml.attributes object))
:initial-value stream)
(cond
((eq 1 (length (xml.children object)))
(stringp (car (xml.children object)))
(char! %stream #\>)
(write-stream stream (car (xml.children object)))
(outro! stream object))
(t
(char! %stream #\>)
(increase-indent %stream)
(reduce #'child!
(slot-value object 'children)
:initial-value stream)
(decrease-indent %stream)
(char! %stream #\Newline)
(outro! stream object)))
stream))
(defmethod write-stream ((stream relaxed-xml-stream) (object generic-xml))
(with-slots (%stream) stream
(intro! stream object)
(reduce #'attribute!
(slot-value object 'attributes)
:initial-value stream)
(cond
((stringp (car (xml.children object)))
(char! %stream #\>)
(write-stream stream (car (xml.children object)))
(outro! stream object))
(t
(char! %stream #\>)
(increase-indent %stream)
(reduce #'child!
(slot-value object 'children)
:initial-value stream)
(decrease-indent %stream)
(char! %stream #\Newline)
(outro! stream object)))
stream))
(deftrace xml-parsers
'(xml-tag-name? xml-lexer? xml-comment? xml-text-node?
xml-cdata? %xml-lexer? xml-lwsp? xml-attribute?
xml-attribute-name? xml-attribute-value?
xml-tag-name? relaxed-xml-lexer? relaxed-xml-comment?
relaxed-xml-text-node? xml-cdata? xml-lwsp?
xml-attribute? xml-attribute-name?
xml-attribute-value? parse-xml))
|
14dd05c48b3e54637803788239922b3301bb1550d22bdc5163eada45839a0f96 | SimulaVR/godot-haskell | GraphEdit.hs | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.GraphEdit
(Godot.Core.GraphEdit.sig__begin_node_move,
Godot.Core.GraphEdit.sig__end_node_move,
Godot.Core.GraphEdit.sig_connection_from_empty,
Godot.Core.GraphEdit.sig_connection_request,
Godot.Core.GraphEdit.sig_connection_to_empty,
Godot.Core.GraphEdit.sig_copy_nodes_request,
Godot.Core.GraphEdit.sig_delete_nodes_request,
Godot.Core.GraphEdit.sig_disconnection_request,
Godot.Core.GraphEdit.sig_duplicate_nodes_request,
Godot.Core.GraphEdit.sig_node_selected,
Godot.Core.GraphEdit.sig_paste_nodes_request,
Godot.Core.GraphEdit.sig_popup_request,
Godot.Core.GraphEdit.sig_scroll_offset_changed,
Godot.Core.GraphEdit._connections_layer_draw,
Godot.Core.GraphEdit._graph_node_moved,
Godot.Core.GraphEdit._graph_node_raised,
Godot.Core.GraphEdit._gui_input,
Godot.Core.GraphEdit._scroll_moved,
Godot.Core.GraphEdit._snap_toggled,
Godot.Core.GraphEdit._snap_value_changed,
Godot.Core.GraphEdit._top_layer_draw,
Godot.Core.GraphEdit._top_layer_input,
Godot.Core.GraphEdit._update_scroll_offset,
Godot.Core.GraphEdit._zoom_minus, Godot.Core.GraphEdit._zoom_plus,
Godot.Core.GraphEdit._zoom_reset,
Godot.Core.GraphEdit.add_valid_connection_type,
Godot.Core.GraphEdit.add_valid_left_disconnect_type,
Godot.Core.GraphEdit.add_valid_right_disconnect_type,
Godot.Core.GraphEdit.clear_connections,
Godot.Core.GraphEdit.connect_node,
Godot.Core.GraphEdit.disconnect_node,
Godot.Core.GraphEdit.get_connection_list,
Godot.Core.GraphEdit.get_scroll_ofs, Godot.Core.GraphEdit.get_snap,
Godot.Core.GraphEdit.get_zoom, Godot.Core.GraphEdit.get_zoom_hbox,
Godot.Core.GraphEdit.is_node_connected,
Godot.Core.GraphEdit.is_right_disconnects_enabled,
Godot.Core.GraphEdit.is_using_snap,
Godot.Core.GraphEdit.is_valid_connection_type,
Godot.Core.GraphEdit.remove_valid_connection_type,
Godot.Core.GraphEdit.remove_valid_left_disconnect_type,
Godot.Core.GraphEdit.remove_valid_right_disconnect_type,
Godot.Core.GraphEdit.set_connection_activity,
Godot.Core.GraphEdit.set_right_disconnects,
Godot.Core.GraphEdit.set_scroll_ofs,
Godot.Core.GraphEdit.set_selected, Godot.Core.GraphEdit.set_snap,
Godot.Core.GraphEdit.set_use_snap, Godot.Core.GraphEdit.set_zoom)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.Control()
| Emitted at the beginning of a GraphNode movement .
sig__begin_node_move :: Godot.Internal.Dispatch.Signal GraphEdit
sig__begin_node_move
= Godot.Internal.Dispatch.Signal "_begin_node_move"
instance NodeSignal GraphEdit "_begin_node_move" '[]
| Emitted at the end of a GraphNode movement .
sig__end_node_move :: Godot.Internal.Dispatch.Signal GraphEdit
sig__end_node_move
= Godot.Internal.Dispatch.Signal "_end_node_move"
instance NodeSignal GraphEdit "_end_node_move" '[]
-- | Emitted when user dragging connection from input port into empty space of the graph.
sig_connection_from_empty ::
Godot.Internal.Dispatch.Signal GraphEdit
sig_connection_from_empty
= Godot.Internal.Dispatch.Signal "connection_from_empty"
instance NodeSignal GraphEdit "connection_from_empty"
'[GodotString, Int, Vector2]
| Emitted to the GraphEdit when the connection between the @from_slot@ slot of the @from@ and the @to_slot@ slot of the @to@ is attempted to be created .
sig_connection_request :: Godot.Internal.Dispatch.Signal GraphEdit
sig_connection_request
= Godot.Internal.Dispatch.Signal "connection_request"
instance NodeSignal GraphEdit "connection_request"
'[GodotString, Int, GodotString, Int]
-- | Emitted when user dragging connection from output port into empty space of the graph.
sig_connection_to_empty :: Godot.Internal.Dispatch.Signal GraphEdit
sig_connection_to_empty
= Godot.Internal.Dispatch.Signal "connection_to_empty"
instance NodeSignal GraphEdit "connection_to_empty"
'[GodotString, Int, Vector2]
-- | Emitted when the user presses @Ctrl + C@.
sig_copy_nodes_request :: Godot.Internal.Dispatch.Signal GraphEdit
sig_copy_nodes_request
= Godot.Internal.Dispatch.Signal "copy_nodes_request"
instance NodeSignal GraphEdit "copy_nodes_request" '[]
| Emitted when a is attempted to be removed from the GraphEdit .
sig_delete_nodes_request ::
Godot.Internal.Dispatch.Signal GraphEdit
sig_delete_nodes_request
= Godot.Internal.Dispatch.Signal "delete_nodes_request"
instance NodeSignal GraphEdit "delete_nodes_request" '[]
| Emitted to the GraphEdit when the connection between @from_slot@ slot of @from@ and @to_slot@ slot of @to@ is attempted to be removed .
sig_disconnection_request ::
Godot.Internal.Dispatch.Signal GraphEdit
sig_disconnection_request
= Godot.Internal.Dispatch.Signal "disconnection_request"
instance NodeSignal GraphEdit "disconnection_request"
'[GodotString, Int, GodotString, Int]
| Emitted when a is attempted to be duplicated in the GraphEdit .
sig_duplicate_nodes_request ::
Godot.Internal.Dispatch.Signal GraphEdit
sig_duplicate_nodes_request
= Godot.Internal.Dispatch.Signal "duplicate_nodes_request"
instance NodeSignal GraphEdit "duplicate_nodes_request" '[]
| Emitted when a is selected .
sig_node_selected :: Godot.Internal.Dispatch.Signal GraphEdit
sig_node_selected = Godot.Internal.Dispatch.Signal "node_selected"
instance NodeSignal GraphEdit "node_selected" '[Node]
-- | Emitted when the user presses @Ctrl + V@.
sig_paste_nodes_request :: Godot.Internal.Dispatch.Signal GraphEdit
sig_paste_nodes_request
= Godot.Internal.Dispatch.Signal "paste_nodes_request"
instance NodeSignal GraphEdit "paste_nodes_request" '[]
| Emitted when a popup is requested . Happens on right - clicking in the GraphEdit . @position@ is the position of the mouse pointer when the signal is sent .
sig_popup_request :: Godot.Internal.Dispatch.Signal GraphEdit
sig_popup_request = Godot.Internal.Dispatch.Signal "popup_request"
instance NodeSignal GraphEdit "popup_request" '[Vector2]
-- | Emitted when the scroll offset is changed by the user. It will not be emitted when changed in code.
sig_scroll_offset_changed ::
Godot.Internal.Dispatch.Signal GraphEdit
sig_scroll_offset_changed
= Godot.Internal.Dispatch.Signal "scroll_offset_changed"
instance NodeSignal GraphEdit "scroll_offset_changed" '[Vector2]
instance NodeProperty GraphEdit "right_disconnects" Bool 'False
where
nodeProperty
= (is_right_disconnects_enabled,
wrapDroppingSetter set_right_disconnects, Nothing)
instance NodeProperty GraphEdit "scroll_offset" Vector2 'False
where
nodeProperty
= (get_scroll_ofs, wrapDroppingSetter set_scroll_ofs, Nothing)
instance NodeProperty GraphEdit "snap_distance" Int 'False where
nodeProperty = (get_snap, wrapDroppingSetter set_snap, Nothing)
instance NodeProperty GraphEdit "use_snap" Bool 'False where
nodeProperty
= (is_using_snap, wrapDroppingSetter set_use_snap, Nothing)
instance NodeProperty GraphEdit "zoom" Float 'False where
nodeProperty = (get_zoom, wrapDroppingSetter set_zoom, Nothing)
# NOINLINE bindGraphEdit__connections_layer_draw #
bindGraphEdit__connections_layer_draw :: MethodBind
bindGraphEdit__connections_layer_draw
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_connections_layer_draw" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_connections_layer_draw ::
(GraphEdit :< cls, Object :< cls) => cls -> IO ()
_connections_layer_draw cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__connections_layer_draw
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_connections_layer_draw" '[] (IO ())
where
nodeMethod = Godot.Core.GraphEdit._connections_layer_draw
# NOINLINE bindGraphEdit__graph_node_moved #
bindGraphEdit__graph_node_moved :: MethodBind
bindGraphEdit__graph_node_moved
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_graph_node_moved" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_graph_node_moved ::
(GraphEdit :< cls, Object :< cls) => cls -> Node -> IO ()
_graph_node_moved cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__graph_node_moved (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_graph_node_moved" '[Node] (IO ())
where
nodeMethod = Godot.Core.GraphEdit._graph_node_moved
{-# NOINLINE bindGraphEdit__graph_node_raised #-}
bindGraphEdit__graph_node_raised :: MethodBind
bindGraphEdit__graph_node_raised
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_graph_node_raised" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_graph_node_raised ::
(GraphEdit :< cls, Object :< cls) => cls -> Node -> IO ()
_graph_node_raised cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__graph_node_raised
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_graph_node_raised" '[Node] (IO ())
where
nodeMethod = Godot.Core.GraphEdit._graph_node_raised
# NOINLINE bindGraphEdit__gui_input #
bindGraphEdit__gui_input :: MethodBind
bindGraphEdit__gui_input
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_gui_input" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_gui_input ::
(GraphEdit :< cls, Object :< cls) => cls -> InputEvent -> IO ()
_gui_input cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__gui_input (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_gui_input" '[InputEvent] (IO ())
where
nodeMethod = Godot.Core.GraphEdit._gui_input
# NOINLINE bindGraphEdit__scroll_moved #
bindGraphEdit__scroll_moved :: MethodBind
bindGraphEdit__scroll_moved
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_scroll_moved" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_scroll_moved ::
(GraphEdit :< cls, Object :< cls) => cls -> Float -> IO ()
_scroll_moved cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__scroll_moved (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_scroll_moved" '[Float] (IO ())
where
nodeMethod = Godot.Core.GraphEdit._scroll_moved
# NOINLINE bindGraphEdit__snap_toggled #
bindGraphEdit__snap_toggled :: MethodBind
bindGraphEdit__snap_toggled
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_snap_toggled" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_snap_toggled :: (GraphEdit :< cls, Object :< cls) => cls -> IO ()
_snap_toggled cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__snap_toggled (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_snap_toggled" '[] (IO ()) where
nodeMethod = Godot.Core.GraphEdit._snap_toggled
# NOINLINE bindGraphEdit__snap_value_changed #
bindGraphEdit__snap_value_changed :: MethodBind
bindGraphEdit__snap_value_changed
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_snap_value_changed" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_snap_value_changed ::
(GraphEdit :< cls, Object :< cls) => cls -> Float -> IO ()
_snap_value_changed cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__snap_value_changed
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_snap_value_changed" '[Float]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit._snap_value_changed
# NOINLINE bindGraphEdit__top_layer_draw #
bindGraphEdit__top_layer_draw :: MethodBind
bindGraphEdit__top_layer_draw
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_top_layer_draw" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_top_layer_draw ::
(GraphEdit :< cls, Object :< cls) => cls -> IO ()
_top_layer_draw cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__top_layer_draw (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_top_layer_draw" '[] (IO ()) where
nodeMethod = Godot.Core.GraphEdit._top_layer_draw
# NOINLINE bindGraphEdit__top_layer_input #
bindGraphEdit__top_layer_input :: MethodBind
bindGraphEdit__top_layer_input
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_top_layer_input" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_top_layer_input ::
(GraphEdit :< cls, Object :< cls) => cls -> InputEvent -> IO ()
_top_layer_input cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__top_layer_input (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_top_layer_input" '[InputEvent]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit._top_layer_input
# NOINLINE bindGraphEdit__update_scroll_offset #
bindGraphEdit__update_scroll_offset :: MethodBind
bindGraphEdit__update_scroll_offset
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_update_scroll_offset" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_update_scroll_offset ::
(GraphEdit :< cls, Object :< cls) => cls -> IO ()
_update_scroll_offset cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__update_scroll_offset
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_update_scroll_offset" '[] (IO ())
where
nodeMethod = Godot.Core.GraphEdit._update_scroll_offset
# NOINLINE bindGraphEdit__zoom_minus #
bindGraphEdit__zoom_minus :: MethodBind
bindGraphEdit__zoom_minus
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_zoom_minus" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_zoom_minus :: (GraphEdit :< cls, Object :< cls) => cls -> IO ()
_zoom_minus cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__zoom_minus (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_zoom_minus" '[] (IO ()) where
nodeMethod = Godot.Core.GraphEdit._zoom_minus
# NOINLINE bindGraphEdit__zoom_plus #
bindGraphEdit__zoom_plus :: MethodBind
bindGraphEdit__zoom_plus
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_zoom_plus" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_zoom_plus :: (GraphEdit :< cls, Object :< cls) => cls -> IO ()
_zoom_plus cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__zoom_plus (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_zoom_plus" '[] (IO ()) where
nodeMethod = Godot.Core.GraphEdit._zoom_plus
# NOINLINE bindGraphEdit__zoom_reset #
bindGraphEdit__zoom_reset :: MethodBind
bindGraphEdit__zoom_reset
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_zoom_reset" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_zoom_reset :: (GraphEdit :< cls, Object :< cls) => cls -> IO ()
_zoom_reset cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__zoom_reset (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_zoom_reset" '[] (IO ()) where
nodeMethod = Godot.Core.GraphEdit._zoom_reset
# NOINLINE bindGraphEdit_add_valid_connection_type #
| Makes possible the connection between two different slot types . The type is defined with the @method GraphNode.set_slot@ method .
bindGraphEdit_add_valid_connection_type :: MethodBind
bindGraphEdit_add_valid_connection_type
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "add_valid_connection_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Makes possible the connection between two different slot types . The type is defined with the @method GraphNode.set_slot@ method .
add_valid_connection_type ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> Int -> IO ()
add_valid_connection_type cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_add_valid_connection_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "add_valid_connection_type"
'[Int, Int]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.add_valid_connection_type
# NOINLINE bindGraphEdit_add_valid_left_disconnect_type #
-- | Makes possible to disconnect nodes when dragging from the slot at the left if it has the specified type.
bindGraphEdit_add_valid_left_disconnect_type :: MethodBind
bindGraphEdit_add_valid_left_disconnect_type
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "add_valid_left_disconnect_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Makes possible to disconnect nodes when dragging from the slot at the left if it has the specified type.
add_valid_left_disconnect_type ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> IO ()
add_valid_left_disconnect_type cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_add_valid_left_disconnect_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "add_valid_left_disconnect_type"
'[Int]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.add_valid_left_disconnect_type
# NOINLINE bindGraphEdit_add_valid_right_disconnect_type #
-- | Makes possible to disconnect nodes when dragging from the slot at the right if it has the specified type.
bindGraphEdit_add_valid_right_disconnect_type :: MethodBind
bindGraphEdit_add_valid_right_disconnect_type
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "add_valid_right_disconnect_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Makes possible to disconnect nodes when dragging from the slot at the right if it has the specified type.
add_valid_right_disconnect_type ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> IO ()
add_valid_right_disconnect_type cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call
bindGraphEdit_add_valid_right_disconnect_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "add_valid_right_disconnect_type"
'[Int]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.add_valid_right_disconnect_type
# NOINLINE bindGraphEdit_clear_connections #
-- | Removes all connections between nodes.
bindGraphEdit_clear_connections :: MethodBind
bindGraphEdit_clear_connections
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "clear_connections" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Removes all connections between nodes.
clear_connections ::
(GraphEdit :< cls, Object :< cls) => cls -> IO ()
clear_connections cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_clear_connections (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "clear_connections" '[] (IO ()) where
nodeMethod = Godot.Core.GraphEdit.clear_connections
# NOINLINE bindGraphEdit_connect_node #
| Create a connection between the @from_port@ slot of the @from@ GraphNode and the @to_port@ slot of the @to@ GraphNode . If the connection already exists , no connection is created .
bindGraphEdit_connect_node :: MethodBind
bindGraphEdit_connect_node
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "connect_node" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Create a connection between the @from_port@ slot of the @from@ GraphNode and the @to_port@ slot of the @to@ GraphNode . If the connection already exists , no connection is created .
connect_node ::
(GraphEdit :< cls, Object :< cls) =>
cls -> GodotString -> Int -> GodotString -> Int -> IO Int
connect_node cls arg1 arg2 arg3 arg4
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3, toVariant arg4]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_connect_node (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "connect_node"
'[GodotString, Int, GodotString, Int]
(IO Int)
where
nodeMethod = Godot.Core.GraphEdit.connect_node
# NOINLINE bindGraphEdit_disconnect_node #
| Removes the connection between the @from_port@ slot of the @from@ GraphNode and the @to_port@ slot of the @to@ GraphNode . If the connection does not exist , no connection is removed .
bindGraphEdit_disconnect_node :: MethodBind
bindGraphEdit_disconnect_node
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "disconnect_node" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Removes the connection between the @from_port@ slot of the @from@ GraphNode and the @to_port@ slot of the @to@ GraphNode . If the connection does not exist , no connection is removed .
disconnect_node ::
(GraphEdit :< cls, Object :< cls) =>
cls -> GodotString -> Int -> GodotString -> Int -> IO ()
disconnect_node cls arg1 arg2 arg3 arg4
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3, toVariant arg4]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_disconnect_node (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "disconnect_node"
'[GodotString, Int, GodotString, Int]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.disconnect_node
# NOINLINE bindGraphEdit_get_connection_list #
| Returns an Array containing the list of connections . A connection consists in a structure of the form @ { from_port : 0 , from : " name 0 " , to_port : 1 , to : " name 1 " } @.
bindGraphEdit_get_connection_list :: MethodBind
bindGraphEdit_get_connection_list
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "get_connection_list" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns an Array containing the list of connections . A connection consists in a structure of the form @ { from_port : 0 , from : " name 0 " , to_port : 1 , to : " name 1 " } @.
get_connection_list ::
(GraphEdit :< cls, Object :< cls) => cls -> IO Array
get_connection_list cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_get_connection_list
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "get_connection_list" '[] (IO Array)
where
nodeMethod = Godot.Core.GraphEdit.get_connection_list
# NOINLINE bindGraphEdit_get_scroll_ofs #
-- | The scroll offset.
bindGraphEdit_get_scroll_ofs :: MethodBind
bindGraphEdit_get_scroll_ofs
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "get_scroll_ofs" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | The scroll offset.
get_scroll_ofs ::
(GraphEdit :< cls, Object :< cls) => cls -> IO Vector2
get_scroll_ofs cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_get_scroll_ofs (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "get_scroll_ofs" '[] (IO Vector2)
where
nodeMethod = Godot.Core.GraphEdit.get_scroll_ofs
# NOINLINE bindGraphEdit_get_snap #
-- | The snapping distance in pixels.
bindGraphEdit_get_snap :: MethodBind
bindGraphEdit_get_snap
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "get_snap" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | The snapping distance in pixels.
get_snap :: (GraphEdit :< cls, Object :< cls) => cls -> IO Int
get_snap cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_get_snap (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "get_snap" '[] (IO Int) where
nodeMethod = Godot.Core.GraphEdit.get_snap
# NOINLINE bindGraphEdit_get_zoom #
-- | The current zoom value.
bindGraphEdit_get_zoom :: MethodBind
bindGraphEdit_get_zoom
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "get_zoom" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | The current zoom value.
get_zoom :: (GraphEdit :< cls, Object :< cls) => cls -> IO Float
get_zoom cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_get_zoom (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "get_zoom" '[] (IO Float) where
nodeMethod = Godot.Core.GraphEdit.get_zoom
# NOINLINE bindGraphEdit_get_zoom_hbox #
-- | Gets the @HBoxContainer@ that contains the zooming and grid snap controls in the top left of the graph.
-- Warning: The intended usage of this function is to allow you to reposition or add your own custom controls to the container. This is an internal control and as such should not be freed. If you wish to hide this or any of it's children use their @CanvasItem.visible@ property instead.
bindGraphEdit_get_zoom_hbox :: MethodBind
bindGraphEdit_get_zoom_hbox
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "get_zoom_hbox" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Gets the @HBoxContainer@ that contains the zooming and grid snap controls in the top left of the graph.
-- Warning: The intended usage of this function is to allow you to reposition or add your own custom controls to the container. This is an internal control and as such should not be freed. If you wish to hide this or any of it's children use their @CanvasItem.visible@ property instead.
get_zoom_hbox ::
(GraphEdit :< cls, Object :< cls) => cls -> IO HBoxContainer
get_zoom_hbox cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_get_zoom_hbox (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "get_zoom_hbox" '[]
(IO HBoxContainer)
where
nodeMethod = Godot.Core.GraphEdit.get_zoom_hbox
# NOINLINE bindGraphEdit_is_node_connected #
| Returns @true@ if the @from_port@ slot of the @from@ GraphNode is connected to the @to_port@ slot of the @to@ GraphNode .
bindGraphEdit_is_node_connected :: MethodBind
bindGraphEdit_is_node_connected
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "is_node_connected" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns @true@ if the @from_port@ slot of the @from@ GraphNode is connected to the @to_port@ slot of the @to@ GraphNode .
is_node_connected ::
(GraphEdit :< cls, Object :< cls) =>
cls -> GodotString -> Int -> GodotString -> Int -> IO Bool
is_node_connected cls arg1 arg2 arg3 arg4
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3, toVariant arg4]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_is_node_connected (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "is_node_connected"
'[GodotString, Int, GodotString, Int]
(IO Bool)
where
nodeMethod = Godot.Core.GraphEdit.is_node_connected
# NOINLINE bindGraphEdit_is_right_disconnects_enabled #
| If @true@ , enables disconnection of existing connections in the GraphEdit by dragging the right end .
bindGraphEdit_is_right_disconnects_enabled :: MethodBind
bindGraphEdit_is_right_disconnects_enabled
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "is_right_disconnects_enabled" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , enables disconnection of existing connections in the GraphEdit by dragging the right end .
is_right_disconnects_enabled ::
(GraphEdit :< cls, Object :< cls) => cls -> IO Bool
is_right_disconnects_enabled cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_is_right_disconnects_enabled
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "is_right_disconnects_enabled" '[]
(IO Bool)
where
nodeMethod = Godot.Core.GraphEdit.is_right_disconnects_enabled
# NOINLINE bindGraphEdit_is_using_snap #
| If @true@ , enables snapping .
bindGraphEdit_is_using_snap :: MethodBind
bindGraphEdit_is_using_snap
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "is_using_snap" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , enables snapping .
is_using_snap ::
(GraphEdit :< cls, Object :< cls) => cls -> IO Bool
is_using_snap cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_is_using_snap (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "is_using_snap" '[] (IO Bool) where
nodeMethod = Godot.Core.GraphEdit.is_using_snap
# NOINLINE bindGraphEdit_is_valid_connection_type #
-- | Returns whether it's possible to connect slots of the specified types.
bindGraphEdit_is_valid_connection_type :: MethodBind
bindGraphEdit_is_valid_connection_type
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "is_valid_connection_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns whether it's possible to connect slots of the specified types.
is_valid_connection_type ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> Int -> IO Bool
is_valid_connection_type cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_is_valid_connection_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "is_valid_connection_type"
'[Int, Int]
(IO Bool)
where
nodeMethod = Godot.Core.GraphEdit.is_valid_connection_type
# NOINLINE bindGraphEdit_remove_valid_connection_type #
| Makes it not possible to connect between two different slot types . The type is defined with the @method GraphNode.set_slot@ method .
bindGraphEdit_remove_valid_connection_type :: MethodBind
bindGraphEdit_remove_valid_connection_type
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "remove_valid_connection_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Makes it not possible to connect between two different slot types . The type is defined with the @method GraphNode.set_slot@ method .
remove_valid_connection_type ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> Int -> IO ()
remove_valid_connection_type cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_remove_valid_connection_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "remove_valid_connection_type"
'[Int, Int]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.remove_valid_connection_type
# NOINLINE bindGraphEdit_remove_valid_left_disconnect_type #
-- | Removes the possibility to disconnect nodes when dragging from the slot at the left if it has the specified type.
bindGraphEdit_remove_valid_left_disconnect_type :: MethodBind
bindGraphEdit_remove_valid_left_disconnect_type
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "remove_valid_left_disconnect_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Removes the possibility to disconnect nodes when dragging from the slot at the left if it has the specified type.
remove_valid_left_disconnect_type ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> IO ()
remove_valid_left_disconnect_type cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call
bindGraphEdit_remove_valid_left_disconnect_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "remove_valid_left_disconnect_type"
'[Int]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.remove_valid_left_disconnect_type
# NOINLINE bindGraphEdit_remove_valid_right_disconnect_type #
-- | Removes the possibility to disconnect nodes when dragging from the slot at the right if it has the specified type.
bindGraphEdit_remove_valid_right_disconnect_type :: MethodBind
bindGraphEdit_remove_valid_right_disconnect_type
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "remove_valid_right_disconnect_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Removes the possibility to disconnect nodes when dragging from the slot at the right if it has the specified type.
remove_valid_right_disconnect_type ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> IO ()
remove_valid_right_disconnect_type cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call
bindGraphEdit_remove_valid_right_disconnect_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "remove_valid_right_disconnect_type"
'[Int]
(IO ())
where
nodeMethod
= Godot.Core.GraphEdit.remove_valid_right_disconnect_type
{-# NOINLINE bindGraphEdit_set_connection_activity #-}
| Sets the coloration of the connection between @from@ 's @from_port@ and @to@ 's @to_port@ with the color provided in the @activity@ theme property .
bindGraphEdit_set_connection_activity :: MethodBind
bindGraphEdit_set_connection_activity
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "set_connection_activity" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the coloration of the connection between @from@ 's @from_port@ and @to@ 's @to_port@ with the color provided in the @activity@ theme property .
set_connection_activity ::
(GraphEdit :< cls, Object :< cls) =>
cls -> GodotString -> Int -> GodotString -> Int -> Float -> IO ()
set_connection_activity cls arg1 arg2 arg3 arg4 arg5
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3, toVariant arg4,
toVariant arg5]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_set_connection_activity
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "set_connection_activity"
'[GodotString, Int, GodotString, Int, Float]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.set_connection_activity
# NOINLINE bindGraphEdit_set_right_disconnects #
| If @true@ , enables disconnection of existing connections in the GraphEdit by dragging the right end .
bindGraphEdit_set_right_disconnects :: MethodBind
bindGraphEdit_set_right_disconnects
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "set_right_disconnects" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , enables disconnection of existing connections in the GraphEdit by dragging the right end .
set_right_disconnects ::
(GraphEdit :< cls, Object :< cls) => cls -> Bool -> IO ()
set_right_disconnects cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_set_right_disconnects
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "set_right_disconnects" '[Bool]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.set_right_disconnects
{-# NOINLINE bindGraphEdit_set_scroll_ofs #-}
-- | The scroll offset.
bindGraphEdit_set_scroll_ofs :: MethodBind
bindGraphEdit_set_scroll_ofs
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "set_scroll_ofs" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | The scroll offset.
set_scroll_ofs ::
(GraphEdit :< cls, Object :< cls) => cls -> Vector2 -> IO ()
set_scroll_ofs cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_set_scroll_ofs (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "set_scroll_ofs" '[Vector2] (IO ())
where
nodeMethod = Godot.Core.GraphEdit.set_scroll_ofs
# NOINLINE bindGraphEdit_set_selected #
-- | Sets the specified @node@ as the one selected.
bindGraphEdit_set_selected :: MethodBind
bindGraphEdit_set_selected
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "set_selected" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Sets the specified @node@ as the one selected.
set_selected ::
(GraphEdit :< cls, Object :< cls) => cls -> Node -> IO ()
set_selected cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_set_selected (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "set_selected" '[Node] (IO ()) where
nodeMethod = Godot.Core.GraphEdit.set_selected
# NOINLINE bindGraphEdit_set_snap #
-- | The snapping distance in pixels.
bindGraphEdit_set_snap :: MethodBind
bindGraphEdit_set_snap
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "set_snap" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | The snapping distance in pixels.
set_snap ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> IO ()
set_snap cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_set_snap (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "set_snap" '[Int] (IO ()) where
nodeMethod = Godot.Core.GraphEdit.set_snap
# NOINLINE bindGraphEdit_set_use_snap #
| If @true@ , enables snapping .
bindGraphEdit_set_use_snap :: MethodBind
bindGraphEdit_set_use_snap
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "set_use_snap" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , enables snapping .
set_use_snap ::
(GraphEdit :< cls, Object :< cls) => cls -> Bool -> IO ()
set_use_snap cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_set_use_snap (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "set_use_snap" '[Bool] (IO ()) where
nodeMethod = Godot.Core.GraphEdit.set_use_snap
# NOINLINE bindGraphEdit_set_zoom #
-- | The current zoom value.
bindGraphEdit_set_zoom :: MethodBind
bindGraphEdit_set_zoom
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "set_zoom" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | The current zoom value.
set_zoom ::
(GraphEdit :< cls, Object :< cls) => cls -> Float -> IO ()
set_zoom cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_set_zoom (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "set_zoom" '[Float] (IO ()) where
nodeMethod = Godot.Core.GraphEdit.set_zoom | null | https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/GraphEdit.hs | haskell | | Emitted when user dragging connection from input port into empty space of the graph.
| Emitted when user dragging connection from output port into empty space of the graph.
| Emitted when the user presses @Ctrl + C@.
| Emitted when the user presses @Ctrl + V@.
| Emitted when the scroll offset is changed by the user. It will not be emitted when changed in code.
# NOINLINE bindGraphEdit__graph_node_raised #
| Makes possible to disconnect nodes when dragging from the slot at the left if it has the specified type.
| Makes possible to disconnect nodes when dragging from the slot at the left if it has the specified type.
| Makes possible to disconnect nodes when dragging from the slot at the right if it has the specified type.
| Makes possible to disconnect nodes when dragging from the slot at the right if it has the specified type.
| Removes all connections between nodes.
| Removes all connections between nodes.
| The scroll offset.
| The scroll offset.
| The snapping distance in pixels.
| The snapping distance in pixels.
| The current zoom value.
| The current zoom value.
| Gets the @HBoxContainer@ that contains the zooming and grid snap controls in the top left of the graph.
Warning: The intended usage of this function is to allow you to reposition or add your own custom controls to the container. This is an internal control and as such should not be freed. If you wish to hide this or any of it's children use their @CanvasItem.visible@ property instead.
| Gets the @HBoxContainer@ that contains the zooming and grid snap controls in the top left of the graph.
Warning: The intended usage of this function is to allow you to reposition or add your own custom controls to the container. This is an internal control and as such should not be freed. If you wish to hide this or any of it's children use their @CanvasItem.visible@ property instead.
| Returns whether it's possible to connect slots of the specified types.
| Returns whether it's possible to connect slots of the specified types.
| Removes the possibility to disconnect nodes when dragging from the slot at the left if it has the specified type.
| Removes the possibility to disconnect nodes when dragging from the slot at the left if it has the specified type.
| Removes the possibility to disconnect nodes when dragging from the slot at the right if it has the specified type.
| Removes the possibility to disconnect nodes when dragging from the slot at the right if it has the specified type.
# NOINLINE bindGraphEdit_set_connection_activity #
# NOINLINE bindGraphEdit_set_scroll_ofs #
| The scroll offset.
| The scroll offset.
| Sets the specified @node@ as the one selected.
| Sets the specified @node@ as the one selected.
| The snapping distance in pixels.
| The snapping distance in pixels.
| The current zoom value.
| The current zoom value. | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.GraphEdit
(Godot.Core.GraphEdit.sig__begin_node_move,
Godot.Core.GraphEdit.sig__end_node_move,
Godot.Core.GraphEdit.sig_connection_from_empty,
Godot.Core.GraphEdit.sig_connection_request,
Godot.Core.GraphEdit.sig_connection_to_empty,
Godot.Core.GraphEdit.sig_copy_nodes_request,
Godot.Core.GraphEdit.sig_delete_nodes_request,
Godot.Core.GraphEdit.sig_disconnection_request,
Godot.Core.GraphEdit.sig_duplicate_nodes_request,
Godot.Core.GraphEdit.sig_node_selected,
Godot.Core.GraphEdit.sig_paste_nodes_request,
Godot.Core.GraphEdit.sig_popup_request,
Godot.Core.GraphEdit.sig_scroll_offset_changed,
Godot.Core.GraphEdit._connections_layer_draw,
Godot.Core.GraphEdit._graph_node_moved,
Godot.Core.GraphEdit._graph_node_raised,
Godot.Core.GraphEdit._gui_input,
Godot.Core.GraphEdit._scroll_moved,
Godot.Core.GraphEdit._snap_toggled,
Godot.Core.GraphEdit._snap_value_changed,
Godot.Core.GraphEdit._top_layer_draw,
Godot.Core.GraphEdit._top_layer_input,
Godot.Core.GraphEdit._update_scroll_offset,
Godot.Core.GraphEdit._zoom_minus, Godot.Core.GraphEdit._zoom_plus,
Godot.Core.GraphEdit._zoom_reset,
Godot.Core.GraphEdit.add_valid_connection_type,
Godot.Core.GraphEdit.add_valid_left_disconnect_type,
Godot.Core.GraphEdit.add_valid_right_disconnect_type,
Godot.Core.GraphEdit.clear_connections,
Godot.Core.GraphEdit.connect_node,
Godot.Core.GraphEdit.disconnect_node,
Godot.Core.GraphEdit.get_connection_list,
Godot.Core.GraphEdit.get_scroll_ofs, Godot.Core.GraphEdit.get_snap,
Godot.Core.GraphEdit.get_zoom, Godot.Core.GraphEdit.get_zoom_hbox,
Godot.Core.GraphEdit.is_node_connected,
Godot.Core.GraphEdit.is_right_disconnects_enabled,
Godot.Core.GraphEdit.is_using_snap,
Godot.Core.GraphEdit.is_valid_connection_type,
Godot.Core.GraphEdit.remove_valid_connection_type,
Godot.Core.GraphEdit.remove_valid_left_disconnect_type,
Godot.Core.GraphEdit.remove_valid_right_disconnect_type,
Godot.Core.GraphEdit.set_connection_activity,
Godot.Core.GraphEdit.set_right_disconnects,
Godot.Core.GraphEdit.set_scroll_ofs,
Godot.Core.GraphEdit.set_selected, Godot.Core.GraphEdit.set_snap,
Godot.Core.GraphEdit.set_use_snap, Godot.Core.GraphEdit.set_zoom)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.Control()
| Emitted at the beginning of a GraphNode movement .
sig__begin_node_move :: Godot.Internal.Dispatch.Signal GraphEdit
sig__begin_node_move
= Godot.Internal.Dispatch.Signal "_begin_node_move"
instance NodeSignal GraphEdit "_begin_node_move" '[]
| Emitted at the end of a GraphNode movement .
sig__end_node_move :: Godot.Internal.Dispatch.Signal GraphEdit
sig__end_node_move
= Godot.Internal.Dispatch.Signal "_end_node_move"
instance NodeSignal GraphEdit "_end_node_move" '[]
sig_connection_from_empty ::
Godot.Internal.Dispatch.Signal GraphEdit
sig_connection_from_empty
= Godot.Internal.Dispatch.Signal "connection_from_empty"
instance NodeSignal GraphEdit "connection_from_empty"
'[GodotString, Int, Vector2]
| Emitted to the GraphEdit when the connection between the @from_slot@ slot of the @from@ and the @to_slot@ slot of the @to@ is attempted to be created .
sig_connection_request :: Godot.Internal.Dispatch.Signal GraphEdit
sig_connection_request
= Godot.Internal.Dispatch.Signal "connection_request"
instance NodeSignal GraphEdit "connection_request"
'[GodotString, Int, GodotString, Int]
sig_connection_to_empty :: Godot.Internal.Dispatch.Signal GraphEdit
sig_connection_to_empty
= Godot.Internal.Dispatch.Signal "connection_to_empty"
instance NodeSignal GraphEdit "connection_to_empty"
'[GodotString, Int, Vector2]
sig_copy_nodes_request :: Godot.Internal.Dispatch.Signal GraphEdit
sig_copy_nodes_request
= Godot.Internal.Dispatch.Signal "copy_nodes_request"
instance NodeSignal GraphEdit "copy_nodes_request" '[]
| Emitted when a is attempted to be removed from the GraphEdit .
sig_delete_nodes_request ::
Godot.Internal.Dispatch.Signal GraphEdit
sig_delete_nodes_request
= Godot.Internal.Dispatch.Signal "delete_nodes_request"
instance NodeSignal GraphEdit "delete_nodes_request" '[]
| Emitted to the GraphEdit when the connection between @from_slot@ slot of @from@ and @to_slot@ slot of @to@ is attempted to be removed .
sig_disconnection_request ::
Godot.Internal.Dispatch.Signal GraphEdit
sig_disconnection_request
= Godot.Internal.Dispatch.Signal "disconnection_request"
instance NodeSignal GraphEdit "disconnection_request"
'[GodotString, Int, GodotString, Int]
| Emitted when a is attempted to be duplicated in the GraphEdit .
sig_duplicate_nodes_request ::
Godot.Internal.Dispatch.Signal GraphEdit
sig_duplicate_nodes_request
= Godot.Internal.Dispatch.Signal "duplicate_nodes_request"
instance NodeSignal GraphEdit "duplicate_nodes_request" '[]
| Emitted when a is selected .
sig_node_selected :: Godot.Internal.Dispatch.Signal GraphEdit
sig_node_selected = Godot.Internal.Dispatch.Signal "node_selected"
instance NodeSignal GraphEdit "node_selected" '[Node]
sig_paste_nodes_request :: Godot.Internal.Dispatch.Signal GraphEdit
sig_paste_nodes_request
= Godot.Internal.Dispatch.Signal "paste_nodes_request"
instance NodeSignal GraphEdit "paste_nodes_request" '[]
| Emitted when a popup is requested . Happens on right - clicking in the GraphEdit . @position@ is the position of the mouse pointer when the signal is sent .
sig_popup_request :: Godot.Internal.Dispatch.Signal GraphEdit
sig_popup_request = Godot.Internal.Dispatch.Signal "popup_request"
instance NodeSignal GraphEdit "popup_request" '[Vector2]
sig_scroll_offset_changed ::
Godot.Internal.Dispatch.Signal GraphEdit
sig_scroll_offset_changed
= Godot.Internal.Dispatch.Signal "scroll_offset_changed"
instance NodeSignal GraphEdit "scroll_offset_changed" '[Vector2]
instance NodeProperty GraphEdit "right_disconnects" Bool 'False
where
nodeProperty
= (is_right_disconnects_enabled,
wrapDroppingSetter set_right_disconnects, Nothing)
instance NodeProperty GraphEdit "scroll_offset" Vector2 'False
where
nodeProperty
= (get_scroll_ofs, wrapDroppingSetter set_scroll_ofs, Nothing)
instance NodeProperty GraphEdit "snap_distance" Int 'False where
nodeProperty = (get_snap, wrapDroppingSetter set_snap, Nothing)
instance NodeProperty GraphEdit "use_snap" Bool 'False where
nodeProperty
= (is_using_snap, wrapDroppingSetter set_use_snap, Nothing)
instance NodeProperty GraphEdit "zoom" Float 'False where
nodeProperty = (get_zoom, wrapDroppingSetter set_zoom, Nothing)
# NOINLINE bindGraphEdit__connections_layer_draw #
bindGraphEdit__connections_layer_draw :: MethodBind
bindGraphEdit__connections_layer_draw
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_connections_layer_draw" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_connections_layer_draw ::
(GraphEdit :< cls, Object :< cls) => cls -> IO ()
_connections_layer_draw cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__connections_layer_draw
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_connections_layer_draw" '[] (IO ())
where
nodeMethod = Godot.Core.GraphEdit._connections_layer_draw
# NOINLINE bindGraphEdit__graph_node_moved #
bindGraphEdit__graph_node_moved :: MethodBind
bindGraphEdit__graph_node_moved
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_graph_node_moved" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_graph_node_moved ::
(GraphEdit :< cls, Object :< cls) => cls -> Node -> IO ()
_graph_node_moved cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__graph_node_moved (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_graph_node_moved" '[Node] (IO ())
where
nodeMethod = Godot.Core.GraphEdit._graph_node_moved
bindGraphEdit__graph_node_raised :: MethodBind
bindGraphEdit__graph_node_raised
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_graph_node_raised" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_graph_node_raised ::
(GraphEdit :< cls, Object :< cls) => cls -> Node -> IO ()
_graph_node_raised cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__graph_node_raised
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_graph_node_raised" '[Node] (IO ())
where
nodeMethod = Godot.Core.GraphEdit._graph_node_raised
# NOINLINE bindGraphEdit__gui_input #
bindGraphEdit__gui_input :: MethodBind
bindGraphEdit__gui_input
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_gui_input" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_gui_input ::
(GraphEdit :< cls, Object :< cls) => cls -> InputEvent -> IO ()
_gui_input cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__gui_input (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_gui_input" '[InputEvent] (IO ())
where
nodeMethod = Godot.Core.GraphEdit._gui_input
# NOINLINE bindGraphEdit__scroll_moved #
bindGraphEdit__scroll_moved :: MethodBind
bindGraphEdit__scroll_moved
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_scroll_moved" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_scroll_moved ::
(GraphEdit :< cls, Object :< cls) => cls -> Float -> IO ()
_scroll_moved cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__scroll_moved (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_scroll_moved" '[Float] (IO ())
where
nodeMethod = Godot.Core.GraphEdit._scroll_moved
# NOINLINE bindGraphEdit__snap_toggled #
bindGraphEdit__snap_toggled :: MethodBind
bindGraphEdit__snap_toggled
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_snap_toggled" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_snap_toggled :: (GraphEdit :< cls, Object :< cls) => cls -> IO ()
_snap_toggled cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__snap_toggled (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_snap_toggled" '[] (IO ()) where
nodeMethod = Godot.Core.GraphEdit._snap_toggled
# NOINLINE bindGraphEdit__snap_value_changed #
bindGraphEdit__snap_value_changed :: MethodBind
bindGraphEdit__snap_value_changed
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_snap_value_changed" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_snap_value_changed ::
(GraphEdit :< cls, Object :< cls) => cls -> Float -> IO ()
_snap_value_changed cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__snap_value_changed
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_snap_value_changed" '[Float]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit._snap_value_changed
# NOINLINE bindGraphEdit__top_layer_draw #
bindGraphEdit__top_layer_draw :: MethodBind
bindGraphEdit__top_layer_draw
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_top_layer_draw" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_top_layer_draw ::
(GraphEdit :< cls, Object :< cls) => cls -> IO ()
_top_layer_draw cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__top_layer_draw (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_top_layer_draw" '[] (IO ()) where
nodeMethod = Godot.Core.GraphEdit._top_layer_draw
# NOINLINE bindGraphEdit__top_layer_input #
bindGraphEdit__top_layer_input :: MethodBind
bindGraphEdit__top_layer_input
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_top_layer_input" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_top_layer_input ::
(GraphEdit :< cls, Object :< cls) => cls -> InputEvent -> IO ()
_top_layer_input cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__top_layer_input (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_top_layer_input" '[InputEvent]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit._top_layer_input
# NOINLINE bindGraphEdit__update_scroll_offset #
bindGraphEdit__update_scroll_offset :: MethodBind
bindGraphEdit__update_scroll_offset
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_update_scroll_offset" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_update_scroll_offset ::
(GraphEdit :< cls, Object :< cls) => cls -> IO ()
_update_scroll_offset cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__update_scroll_offset
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_update_scroll_offset" '[] (IO ())
where
nodeMethod = Godot.Core.GraphEdit._update_scroll_offset
# NOINLINE bindGraphEdit__zoom_minus #
bindGraphEdit__zoom_minus :: MethodBind
bindGraphEdit__zoom_minus
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_zoom_minus" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_zoom_minus :: (GraphEdit :< cls, Object :< cls) => cls -> IO ()
_zoom_minus cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__zoom_minus (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_zoom_minus" '[] (IO ()) where
nodeMethod = Godot.Core.GraphEdit._zoom_minus
# NOINLINE bindGraphEdit__zoom_plus #
bindGraphEdit__zoom_plus :: MethodBind
bindGraphEdit__zoom_plus
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_zoom_plus" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_zoom_plus :: (GraphEdit :< cls, Object :< cls) => cls -> IO ()
_zoom_plus cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__zoom_plus (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_zoom_plus" '[] (IO ()) where
nodeMethod = Godot.Core.GraphEdit._zoom_plus
# NOINLINE bindGraphEdit__zoom_reset #
bindGraphEdit__zoom_reset :: MethodBind
bindGraphEdit__zoom_reset
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "_zoom_reset" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_zoom_reset :: (GraphEdit :< cls, Object :< cls) => cls -> IO ()
_zoom_reset cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit__zoom_reset (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "_zoom_reset" '[] (IO ()) where
nodeMethod = Godot.Core.GraphEdit._zoom_reset
# NOINLINE bindGraphEdit_add_valid_connection_type #
| Makes possible the connection between two different slot types . The type is defined with the @method GraphNode.set_slot@ method .
bindGraphEdit_add_valid_connection_type :: MethodBind
bindGraphEdit_add_valid_connection_type
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "add_valid_connection_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Makes possible the connection between two different slot types . The type is defined with the @method GraphNode.set_slot@ method .
add_valid_connection_type ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> Int -> IO ()
add_valid_connection_type cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_add_valid_connection_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "add_valid_connection_type"
'[Int, Int]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.add_valid_connection_type
# NOINLINE bindGraphEdit_add_valid_left_disconnect_type #
bindGraphEdit_add_valid_left_disconnect_type :: MethodBind
bindGraphEdit_add_valid_left_disconnect_type
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "add_valid_left_disconnect_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
add_valid_left_disconnect_type ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> IO ()
add_valid_left_disconnect_type cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_add_valid_left_disconnect_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "add_valid_left_disconnect_type"
'[Int]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.add_valid_left_disconnect_type
# NOINLINE bindGraphEdit_add_valid_right_disconnect_type #
bindGraphEdit_add_valid_right_disconnect_type :: MethodBind
bindGraphEdit_add_valid_right_disconnect_type
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "add_valid_right_disconnect_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
add_valid_right_disconnect_type ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> IO ()
add_valid_right_disconnect_type cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call
bindGraphEdit_add_valid_right_disconnect_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "add_valid_right_disconnect_type"
'[Int]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.add_valid_right_disconnect_type
# NOINLINE bindGraphEdit_clear_connections #
bindGraphEdit_clear_connections :: MethodBind
bindGraphEdit_clear_connections
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "clear_connections" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
clear_connections ::
(GraphEdit :< cls, Object :< cls) => cls -> IO ()
clear_connections cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_clear_connections (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "clear_connections" '[] (IO ()) where
nodeMethod = Godot.Core.GraphEdit.clear_connections
# NOINLINE bindGraphEdit_connect_node #
| Create a connection between the @from_port@ slot of the @from@ GraphNode and the @to_port@ slot of the @to@ GraphNode . If the connection already exists , no connection is created .
bindGraphEdit_connect_node :: MethodBind
bindGraphEdit_connect_node
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "connect_node" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Create a connection between the @from_port@ slot of the @from@ GraphNode and the @to_port@ slot of the @to@ GraphNode . If the connection already exists , no connection is created .
connect_node ::
(GraphEdit :< cls, Object :< cls) =>
cls -> GodotString -> Int -> GodotString -> Int -> IO Int
connect_node cls arg1 arg2 arg3 arg4
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3, toVariant arg4]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_connect_node (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "connect_node"
'[GodotString, Int, GodotString, Int]
(IO Int)
where
nodeMethod = Godot.Core.GraphEdit.connect_node
# NOINLINE bindGraphEdit_disconnect_node #
| Removes the connection between the @from_port@ slot of the @from@ GraphNode and the @to_port@ slot of the @to@ GraphNode . If the connection does not exist , no connection is removed .
bindGraphEdit_disconnect_node :: MethodBind
bindGraphEdit_disconnect_node
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "disconnect_node" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Removes the connection between the @from_port@ slot of the @from@ GraphNode and the @to_port@ slot of the @to@ GraphNode . If the connection does not exist , no connection is removed .
disconnect_node ::
(GraphEdit :< cls, Object :< cls) =>
cls -> GodotString -> Int -> GodotString -> Int -> IO ()
disconnect_node cls arg1 arg2 arg3 arg4
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3, toVariant arg4]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_disconnect_node (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "disconnect_node"
'[GodotString, Int, GodotString, Int]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.disconnect_node
# NOINLINE bindGraphEdit_get_connection_list #
| Returns an Array containing the list of connections . A connection consists in a structure of the form @ { from_port : 0 , from : " name 0 " , to_port : 1 , to : " name 1 " } @.
bindGraphEdit_get_connection_list :: MethodBind
bindGraphEdit_get_connection_list
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "get_connection_list" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns an Array containing the list of connections . A connection consists in a structure of the form @ { from_port : 0 , from : " name 0 " , to_port : 1 , to : " name 1 " } @.
get_connection_list ::
(GraphEdit :< cls, Object :< cls) => cls -> IO Array
get_connection_list cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_get_connection_list
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "get_connection_list" '[] (IO Array)
where
nodeMethod = Godot.Core.GraphEdit.get_connection_list
# NOINLINE bindGraphEdit_get_scroll_ofs #
bindGraphEdit_get_scroll_ofs :: MethodBind
bindGraphEdit_get_scroll_ofs
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "get_scroll_ofs" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
get_scroll_ofs ::
(GraphEdit :< cls, Object :< cls) => cls -> IO Vector2
get_scroll_ofs cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_get_scroll_ofs (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "get_scroll_ofs" '[] (IO Vector2)
where
nodeMethod = Godot.Core.GraphEdit.get_scroll_ofs
# NOINLINE bindGraphEdit_get_snap #
bindGraphEdit_get_snap :: MethodBind
bindGraphEdit_get_snap
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "get_snap" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
get_snap :: (GraphEdit :< cls, Object :< cls) => cls -> IO Int
get_snap cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_get_snap (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "get_snap" '[] (IO Int) where
nodeMethod = Godot.Core.GraphEdit.get_snap
# NOINLINE bindGraphEdit_get_zoom #
bindGraphEdit_get_zoom :: MethodBind
bindGraphEdit_get_zoom
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "get_zoom" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
get_zoom :: (GraphEdit :< cls, Object :< cls) => cls -> IO Float
get_zoom cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_get_zoom (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "get_zoom" '[] (IO Float) where
nodeMethod = Godot.Core.GraphEdit.get_zoom
# NOINLINE bindGraphEdit_get_zoom_hbox #
bindGraphEdit_get_zoom_hbox :: MethodBind
bindGraphEdit_get_zoom_hbox
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "get_zoom_hbox" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
get_zoom_hbox ::
(GraphEdit :< cls, Object :< cls) => cls -> IO HBoxContainer
get_zoom_hbox cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_get_zoom_hbox (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "get_zoom_hbox" '[]
(IO HBoxContainer)
where
nodeMethod = Godot.Core.GraphEdit.get_zoom_hbox
# NOINLINE bindGraphEdit_is_node_connected #
| Returns @true@ if the @from_port@ slot of the @from@ GraphNode is connected to the @to_port@ slot of the @to@ GraphNode .
bindGraphEdit_is_node_connected :: MethodBind
bindGraphEdit_is_node_connected
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "is_node_connected" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns @true@ if the @from_port@ slot of the @from@ GraphNode is connected to the @to_port@ slot of the @to@ GraphNode .
is_node_connected ::
(GraphEdit :< cls, Object :< cls) =>
cls -> GodotString -> Int -> GodotString -> Int -> IO Bool
is_node_connected cls arg1 arg2 arg3 arg4
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3, toVariant arg4]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_is_node_connected (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "is_node_connected"
'[GodotString, Int, GodotString, Int]
(IO Bool)
where
nodeMethod = Godot.Core.GraphEdit.is_node_connected
# NOINLINE bindGraphEdit_is_right_disconnects_enabled #
| If @true@ , enables disconnection of existing connections in the GraphEdit by dragging the right end .
bindGraphEdit_is_right_disconnects_enabled :: MethodBind
bindGraphEdit_is_right_disconnects_enabled
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "is_right_disconnects_enabled" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , enables disconnection of existing connections in the GraphEdit by dragging the right end .
is_right_disconnects_enabled ::
(GraphEdit :< cls, Object :< cls) => cls -> IO Bool
is_right_disconnects_enabled cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_is_right_disconnects_enabled
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "is_right_disconnects_enabled" '[]
(IO Bool)
where
nodeMethod = Godot.Core.GraphEdit.is_right_disconnects_enabled
# NOINLINE bindGraphEdit_is_using_snap #
| If @true@ , enables snapping .
bindGraphEdit_is_using_snap :: MethodBind
bindGraphEdit_is_using_snap
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "is_using_snap" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , enables snapping .
is_using_snap ::
(GraphEdit :< cls, Object :< cls) => cls -> IO Bool
is_using_snap cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_is_using_snap (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "is_using_snap" '[] (IO Bool) where
nodeMethod = Godot.Core.GraphEdit.is_using_snap
# NOINLINE bindGraphEdit_is_valid_connection_type #
bindGraphEdit_is_valid_connection_type :: MethodBind
bindGraphEdit_is_valid_connection_type
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "is_valid_connection_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
is_valid_connection_type ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> Int -> IO Bool
is_valid_connection_type cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_is_valid_connection_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "is_valid_connection_type"
'[Int, Int]
(IO Bool)
where
nodeMethod = Godot.Core.GraphEdit.is_valid_connection_type
# NOINLINE bindGraphEdit_remove_valid_connection_type #
| Makes it not possible to connect between two different slot types . The type is defined with the @method GraphNode.set_slot@ method .
bindGraphEdit_remove_valid_connection_type :: MethodBind
bindGraphEdit_remove_valid_connection_type
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "remove_valid_connection_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Makes it not possible to connect between two different slot types . The type is defined with the @method GraphNode.set_slot@ method .
remove_valid_connection_type ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> Int -> IO ()
remove_valid_connection_type cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_remove_valid_connection_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "remove_valid_connection_type"
'[Int, Int]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.remove_valid_connection_type
# NOINLINE bindGraphEdit_remove_valid_left_disconnect_type #
bindGraphEdit_remove_valid_left_disconnect_type :: MethodBind
bindGraphEdit_remove_valid_left_disconnect_type
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "remove_valid_left_disconnect_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
remove_valid_left_disconnect_type ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> IO ()
remove_valid_left_disconnect_type cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call
bindGraphEdit_remove_valid_left_disconnect_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "remove_valid_left_disconnect_type"
'[Int]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.remove_valid_left_disconnect_type
# NOINLINE bindGraphEdit_remove_valid_right_disconnect_type #
bindGraphEdit_remove_valid_right_disconnect_type :: MethodBind
bindGraphEdit_remove_valid_right_disconnect_type
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "remove_valid_right_disconnect_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
remove_valid_right_disconnect_type ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> IO ()
remove_valid_right_disconnect_type cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call
bindGraphEdit_remove_valid_right_disconnect_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "remove_valid_right_disconnect_type"
'[Int]
(IO ())
where
nodeMethod
= Godot.Core.GraphEdit.remove_valid_right_disconnect_type
| Sets the coloration of the connection between @from@ 's @from_port@ and @to@ 's @to_port@ with the color provided in the @activity@ theme property .
bindGraphEdit_set_connection_activity :: MethodBind
bindGraphEdit_set_connection_activity
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "set_connection_activity" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the coloration of the connection between @from@ 's @from_port@ and @to@ 's @to_port@ with the color provided in the @activity@ theme property .
set_connection_activity ::
(GraphEdit :< cls, Object :< cls) =>
cls -> GodotString -> Int -> GodotString -> Int -> Float -> IO ()
set_connection_activity cls arg1 arg2 arg3 arg4 arg5
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3, toVariant arg4,
toVariant arg5]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_set_connection_activity
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "set_connection_activity"
'[GodotString, Int, GodotString, Int, Float]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.set_connection_activity
# NOINLINE bindGraphEdit_set_right_disconnects #
| If @true@ , enables disconnection of existing connections in the GraphEdit by dragging the right end .
bindGraphEdit_set_right_disconnects :: MethodBind
bindGraphEdit_set_right_disconnects
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "set_right_disconnects" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , enables disconnection of existing connections in the GraphEdit by dragging the right end .
set_right_disconnects ::
(GraphEdit :< cls, Object :< cls) => cls -> Bool -> IO ()
set_right_disconnects cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_set_right_disconnects
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "set_right_disconnects" '[Bool]
(IO ())
where
nodeMethod = Godot.Core.GraphEdit.set_right_disconnects
bindGraphEdit_set_scroll_ofs :: MethodBind
bindGraphEdit_set_scroll_ofs
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "set_scroll_ofs" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
set_scroll_ofs ::
(GraphEdit :< cls, Object :< cls) => cls -> Vector2 -> IO ()
set_scroll_ofs cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_set_scroll_ofs (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "set_scroll_ofs" '[Vector2] (IO ())
where
nodeMethod = Godot.Core.GraphEdit.set_scroll_ofs
# NOINLINE bindGraphEdit_set_selected #
bindGraphEdit_set_selected :: MethodBind
bindGraphEdit_set_selected
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "set_selected" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
set_selected ::
(GraphEdit :< cls, Object :< cls) => cls -> Node -> IO ()
set_selected cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_set_selected (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "set_selected" '[Node] (IO ()) where
nodeMethod = Godot.Core.GraphEdit.set_selected
# NOINLINE bindGraphEdit_set_snap #
bindGraphEdit_set_snap :: MethodBind
bindGraphEdit_set_snap
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "set_snap" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
set_snap ::
(GraphEdit :< cls, Object :< cls) => cls -> Int -> IO ()
set_snap cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_set_snap (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "set_snap" '[Int] (IO ()) where
nodeMethod = Godot.Core.GraphEdit.set_snap
# NOINLINE bindGraphEdit_set_use_snap #
| If @true@ , enables snapping .
bindGraphEdit_set_use_snap :: MethodBind
bindGraphEdit_set_use_snap
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "set_use_snap" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , enables snapping .
set_use_snap ::
(GraphEdit :< cls, Object :< cls) => cls -> Bool -> IO ()
set_use_snap cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_set_use_snap (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "set_use_snap" '[Bool] (IO ()) where
nodeMethod = Godot.Core.GraphEdit.set_use_snap
# NOINLINE bindGraphEdit_set_zoom #
bindGraphEdit_set_zoom :: MethodBind
bindGraphEdit_set_zoom
= unsafePerformIO $
withCString "GraphEdit" $
\ clsNamePtr ->
withCString "set_zoom" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
set_zoom ::
(GraphEdit :< cls, Object :< cls) => cls -> Float -> IO ()
set_zoom cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGraphEdit_set_zoom (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GraphEdit "set_zoom" '[Float] (IO ()) where
nodeMethod = Godot.Core.GraphEdit.set_zoom |
205c0f9c6bf2a4d8e87356eb3563b953a6ebdc5347ae6e2f13f2af105c7f9687 | haskell-opengl/OpenGLRaw | ColorBufferFloat.hs | # LANGUAGE PatternSynonyms #
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.ColorBufferFloat
Copyright : ( c ) 2019
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.ColorBufferFloat (
-- * Extension Support
glGetARBColorBufferFloat,
gl_ARB_color_buffer_float,
-- * Enums
pattern GL_CLAMP_FRAGMENT_COLOR_ARB,
pattern GL_CLAMP_READ_COLOR_ARB,
pattern GL_CLAMP_VERTEX_COLOR_ARB,
pattern GL_FIXED_ONLY_ARB,
pattern GL_RGBA_FLOAT_MODE_ARB,
-- * Functions
glClampColorARB
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| null | https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/ARB/ColorBufferFloat.hs | haskell | ------------------------------------------------------------------------------
|
Module : Graphics.GL.ARB.ColorBufferFloat
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
* Extension Support
* Enums
* Functions | # LANGUAGE PatternSynonyms #
Copyright : ( c ) 2019
Maintainer : < >
module Graphics.GL.ARB.ColorBufferFloat (
glGetARBColorBufferFloat,
gl_ARB_color_buffer_float,
pattern GL_CLAMP_FRAGMENT_COLOR_ARB,
pattern GL_CLAMP_READ_COLOR_ARB,
pattern GL_CLAMP_VERTEX_COLOR_ARB,
pattern GL_FIXED_ONLY_ARB,
pattern GL_RGBA_FLOAT_MODE_ARB,
glClampColorARB
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
cf0e83aa9bb759963d6a1ba6809fcd83eedebd3736aa881b7306fb5b57408d4a | al3623/rippl | pair_annots.ml | open Ast
open Scanner
open Parser
open Get_fresh_var
let rec pair_helper decs last_annot annot main_found =
if (List.length decs) = 0
then if not last_annot
then (if main_found
then []
else raise(Failure "main not type annotated"))
else raise (Failure "unmatched type annotation")
else match (List.hd decs) with
| Annot(name, tname) -> (match last_annot with
| true -> raise (Failure "unmatched type annotation")
| false -> pair_helper (List.tl decs) true (name, tname)
(if not main_found then name = "main" else main_found))
| Vdef(vname, vexpr) -> (match last_annot with
| true ->
if vname = (fst annot) then
(Annot(fst annot, snd annot), Vdef(vname, vexpr))
:: (pair_helper (List.tl decs) false annot main_found)
else raise (Failure "mismatched identifier name in annotation and declaration")
| false ->
let vapair = (Annot(vname, Tvar(get_fresh "t")), Vdef(vname, vexpr)) in
vapair :: (pair_helper (List.tl decs) false annot main_found))
let pair_av prog = match prog with
| x :: xs -> pair_helper (x :: xs) false ("", Tvar("")) false
| [] -> []
| null | https://raw.githubusercontent.com/al3623/rippl/a7e5c24f67935b3513324148279791042856a1fa/src/passes/pair_annots.ml | ocaml | open Ast
open Scanner
open Parser
open Get_fresh_var
let rec pair_helper decs last_annot annot main_found =
if (List.length decs) = 0
then if not last_annot
then (if main_found
then []
else raise(Failure "main not type annotated"))
else raise (Failure "unmatched type annotation")
else match (List.hd decs) with
| Annot(name, tname) -> (match last_annot with
| true -> raise (Failure "unmatched type annotation")
| false -> pair_helper (List.tl decs) true (name, tname)
(if not main_found then name = "main" else main_found))
| Vdef(vname, vexpr) -> (match last_annot with
| true ->
if vname = (fst annot) then
(Annot(fst annot, snd annot), Vdef(vname, vexpr))
:: (pair_helper (List.tl decs) false annot main_found)
else raise (Failure "mismatched identifier name in annotation and declaration")
| false ->
let vapair = (Annot(vname, Tvar(get_fresh "t")), Vdef(vname, vexpr)) in
vapair :: (pair_helper (List.tl decs) false annot main_found))
let pair_av prog = match prog with
| x :: xs -> pair_helper (x :: xs) false ("", Tvar("")) false
| [] -> []
| |
7f1fcd3665ddb8021b9fb49e6766c081df05060916ed9759df3d6a4bddaa853b | xtdb/xtdb | index_store.clj | (ns ^:no-doc xtdb.metrics.index-store
(:require [xtdb.bus :as bus]
[xtdb.api :as xt]
[xtdb.tx :as tx]
[xtdb.metrics.dropwizard :as dropwizard])
(:import (java.util Date)))
(defn assign-tx-id-lag [registry {:xtdb/keys [node]}]
(dropwizard/gauge registry
["index-store" "tx-id-lag"]
#(when-let [completed (xt/latest-completed-tx node)]
(when-let [submitted (xt/latest-submitted-tx node)]
(- (::xt/tx-id submitted)
(::xt/tx-id completed))))))
(defn assign-tx-latency-gauge [registry {:xtdb/keys [bus]}]
(let [!last-tx-lag (atom 0)]
(bus/listen bus
{::xt/event-types #{::tx/indexed-tx}}
(fn [{:keys [submitted-tx]}]
(reset! !last-tx-lag (- (System/currentTimeMillis)
(.getTime ^Date (::xt/tx-time submitted-tx))))))
(dropwizard/gauge registry
["index-store" "tx-latency"]
(fn []
(first (reset-vals! !last-tx-lag 0))))))
(defn assign-doc-meters [registry {:xtdb/keys [bus]}]
(let [docs-ingested-meter (dropwizard/meter registry ["index-store" "indexed-docs"])
av-ingested-meter (dropwizard/meter registry ["index-store" "indexed-avs"])
bytes-ingested-meter (dropwizard/meter registry ["index-store" "indexed-bytes"])]
(bus/listen bus
{::xt/event-types #{::tx/indexed-tx}}
(fn [{:keys [doc-ids av-count bytes-indexed]}]
(when (seq doc-ids)
(dropwizard/mark! docs-ingested-meter (count doc-ids))
(dropwizard/mark! av-ingested-meter av-count)
(dropwizard/mark! bytes-ingested-meter bytes-indexed))))
{:docs-ingested-meter docs-ingested-meter
:av-ingested-meter av-ingested-meter
:bytes-ingested-meter bytes-ingested-meter}))
(defn assign-tx-timer [registry {:xtdb/keys [bus]}]
(let [timer (dropwizard/timer registry ["index-store" "indexed-txs"])
!timer-store (atom {})]
(bus/listen bus
{::xt/event-types #{::tx/indexing-tx ::tx/indexed-tx}}
(fn [{:keys [::xt/event-type submitted-tx]}]
(case event-type
::tx/indexing-tx
(swap! !timer-store assoc submitted-tx (dropwizard/start timer))
::tx/indexed-tx
(when-let [timer-context (get @!timer-store submitted-tx)]
(dropwizard/stop timer-context)
(swap! !timer-store dissoc submitted-tx)))))
timer))
(defn assign-listeners
"Assigns listeners to an event bus for a given node.
Returns an atom containing updating metrics"
[registry deps]
(merge (assign-doc-meters registry deps)
{:tx-id-lag (assign-tx-id-lag registry deps)
:tx-latency-gauge (assign-tx-latency-gauge registry deps)
:tx-ingest-timer (assign-tx-timer registry deps)}))
| null | https://raw.githubusercontent.com/xtdb/xtdb/6c3c5dbff964553460081db70d2b85548bdc8553/modules/metrics/src/xtdb/metrics/index_store.clj | clojure | (ns ^:no-doc xtdb.metrics.index-store
(:require [xtdb.bus :as bus]
[xtdb.api :as xt]
[xtdb.tx :as tx]
[xtdb.metrics.dropwizard :as dropwizard])
(:import (java.util Date)))
(defn assign-tx-id-lag [registry {:xtdb/keys [node]}]
(dropwizard/gauge registry
["index-store" "tx-id-lag"]
#(when-let [completed (xt/latest-completed-tx node)]
(when-let [submitted (xt/latest-submitted-tx node)]
(- (::xt/tx-id submitted)
(::xt/tx-id completed))))))
(defn assign-tx-latency-gauge [registry {:xtdb/keys [bus]}]
(let [!last-tx-lag (atom 0)]
(bus/listen bus
{::xt/event-types #{::tx/indexed-tx}}
(fn [{:keys [submitted-tx]}]
(reset! !last-tx-lag (- (System/currentTimeMillis)
(.getTime ^Date (::xt/tx-time submitted-tx))))))
(dropwizard/gauge registry
["index-store" "tx-latency"]
(fn []
(first (reset-vals! !last-tx-lag 0))))))
(defn assign-doc-meters [registry {:xtdb/keys [bus]}]
(let [docs-ingested-meter (dropwizard/meter registry ["index-store" "indexed-docs"])
av-ingested-meter (dropwizard/meter registry ["index-store" "indexed-avs"])
bytes-ingested-meter (dropwizard/meter registry ["index-store" "indexed-bytes"])]
(bus/listen bus
{::xt/event-types #{::tx/indexed-tx}}
(fn [{:keys [doc-ids av-count bytes-indexed]}]
(when (seq doc-ids)
(dropwizard/mark! docs-ingested-meter (count doc-ids))
(dropwizard/mark! av-ingested-meter av-count)
(dropwizard/mark! bytes-ingested-meter bytes-indexed))))
{:docs-ingested-meter docs-ingested-meter
:av-ingested-meter av-ingested-meter
:bytes-ingested-meter bytes-ingested-meter}))
(defn assign-tx-timer [registry {:xtdb/keys [bus]}]
(let [timer (dropwizard/timer registry ["index-store" "indexed-txs"])
!timer-store (atom {})]
(bus/listen bus
{::xt/event-types #{::tx/indexing-tx ::tx/indexed-tx}}
(fn [{:keys [::xt/event-type submitted-tx]}]
(case event-type
::tx/indexing-tx
(swap! !timer-store assoc submitted-tx (dropwizard/start timer))
::tx/indexed-tx
(when-let [timer-context (get @!timer-store submitted-tx)]
(dropwizard/stop timer-context)
(swap! !timer-store dissoc submitted-tx)))))
timer))
(defn assign-listeners
"Assigns listeners to an event bus for a given node.
Returns an atom containing updating metrics"
[registry deps]
(merge (assign-doc-meters registry deps)
{:tx-id-lag (assign-tx-id-lag registry deps)
:tx-latency-gauge (assign-tx-latency-gauge registry deps)
:tx-ingest-timer (assign-tx-timer registry deps)}))
| |
23a193df7f463c1c67d60274add8bed38748801bec1d13007760efd4f4ff5c86 | sschwarzer/racket-glossary | info.rkt | #lang info
(define collection "racket-glossary")
(define deps '("base"))
(define build-deps '("racket-doc"
"rackunit-lib"
"scribble-lib"
"al2-test-runner"))
(define scribblings '(("scribblings/racket-glossary.scrbl" ())))
(define pkg-desc "Glossary of Racket concepts")
(define version "0.1.0-dev")
(define pkg-authors '(sschwarzer))
(define license '(Apache-2.0 OR MIT))
| null | https://raw.githubusercontent.com/sschwarzer/racket-glossary/c652805064fb1069058713fd0e726364fdb508e0/info.rkt | racket | #lang info
(define collection "racket-glossary")
(define deps '("base"))
(define build-deps '("racket-doc"
"rackunit-lib"
"scribble-lib"
"al2-test-runner"))
(define scribblings '(("scribblings/racket-glossary.scrbl" ())))
(define pkg-desc "Glossary of Racket concepts")
(define version "0.1.0-dev")
(define pkg-authors '(sschwarzer))
(define license '(Apache-2.0 OR MIT))
| |
b55f53c11cccb890125f0c35f9f6b2517c158de000b7ce2192bccb44420bcf47 | SNePS/SNePS2 | sniphandler.lisp | -*- Mode : Lisp ; Syntax : Common - Lisp ; Package : SNEBR ; Base : 10 -*-
Copyright ( C ) 1984 - -2013
Research Foundation of State University of New York
Version : $ I d : , v 1.3 2013/08/28 19:07:24 shapiro Exp $
;; This file is part of SNePS.
$ BEGIN LICENSE$
The contents of this file are subject to the University at
Buffalo Public License Version 1.0 ( the " License " ) ; you may
;;; not use this file except in compliance with the License. You
;;; may obtain a copy of the License at
;;; . edu/sneps/Downloads/ubpl.pdf.
;;;
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 gov
;;; erning rights and limitations under the License.
;;;
The Original Code is SNePS 2.8 .
;;;
The Initial Developer of the Original Code is Research Foun
dation of State University of New York , on behalf of Univer
sity at Buffalo .
;;;
Portions created by the Initial Developer are Copyright ( C )
2011 Research Foundation of State University of New York , on
behalf of University at Buffalo . All Rights Reserved .
$ END LICENSE$
(in-package :snebr)
; =============================================================================
;
; snip-contr-handler
; -------------------
;
;
; arguments : newnode - <node>
contrnd - < node >
; context - <context>
;
; returns : ---
;
; description : This function takes as arguments a node `contrnd' which
; contradicts some newly derived node `newnode' (refer
; to the function ck-contradiction), and a context
; `context' under which the newly asserted node was derived.
; It warns the user of the detected contradiction and
; calls the function contr-h to handle the contradiction.
;
;
;
; written : mrc 11/15/88
;
;
;
;
(defun snip-contr-handler (newnode contrnd context)
(declare (special sneps:outunit snip:crntctname *br-auto-mode*))
(progn
(unless *br-auto-mode*
(format sneps:outunit
"~%~%~T A contradiction was detected within context ~A.~
~%~T The contradiction involves the newly derived proposition:~
~%~T~T~T ~A ~
~%~T and the previously existing proposition:~
~%~T~T~T ~A"
snip:crntctname
(snip:describe-or-surface newnode nil)
(snip:describe-or-surface contrnd nil)))
(contr-h (ctcs-to-cts (sneps:node-asupport newnode))
(ctcs-to-cts (sneps:node-asupport contrnd))
(sneps:ctcs-to-ots (sneps:node-asupport newnode))
(sneps:ctcs-to-ots (sneps:node-asupport contrnd))
context)))
;
; =============================================================================
;
;
; contr-h
; -------
;
; arguments : newnd-supps - <context set>
contrnd - supps - < context set >
; newnd-otlst - <ot list>
contrnd - otlst - < ot list >
; context - <context>
;
; returns : <node set>
;
; description : This function handles contradictions detected during
; inference.
; In the current implementation the contradiction is
resolved by the user which may choose one of three
; options:
1 . [ C]ontinue anyway , knowing that a contradiction
; is derivable;
2 . [ R]e - start the exact same run in a different
; context which is not inconsistent;
3 . [ D]rop the run altogether .
;
; This function asks the user what his choice is and
; takes the necessary actions to execute that choice.
;
;
;
; written : jpm 11/30/82
; modified: njm 10/06/88
; modified: mrc 11/15/88
hc
; flj 03/22/99
;
;
;
(defun contr-h (newnd-supps contrnd-supps newnd-otlst contrnd-otlst context)
(declare (special sneps:outunit snip:crntctname *br-auto-mode*
*most-entrenched-props*))
(unless *br-auto-mode* (options-in-contr-h))
(let* ((ans (if *br-auto-mode* 'snepsul:A (read-contr-h-option)))
(lastcommand #-explorer (value.sv 'sneps:command)
#+explorer (if (eql (first (value.sv 'sneps:command))
'sys:displaced)
(second (value.sv 'sneps:command))
(value.sv 'sneps:command))
)
(mep *most-entrenched-props*))
(cond ((or (eq ans 'snepsul:C) (eql ans 2)))
((or (eq ans 'snepsul:A) (eql ans 1))
(autobr newnd-supps contrnd-supps context)
(if (sneps:issubset.ns (context-hyps (car newnd-supps)) (context-hyps sneps:crntct))
(progn
(setf *most-entrenched-props* mep)
(sneps:topsneval lastcommand))
(throw 'snip:Stop-Handled-by-Contradiction-Handler nil)))
(t (multi:clear-all-queues)
(sneps:clear-infer)
(cond ((or (eq ans 'snepsul:R)(eq ans 'snepslog::R)(eql ans 3))
(change-context newnd-supps contrnd-supps
newnd-otlst contrnd-otlst
context snip:crntctname)
(sneps:topsneval lastcommand))
((is-add lastcommand) (remove-new-hyp lastcommand)))
(throw 'snip:Stop-Handled-by-Contradiction-Handler nil)))))
;
; =============================================================================
;
;
; options-in-contr-h
; ------------------
;
;
; arguments :
;
; returns : nil
;
; description : This function tells the user the possibilities he
; has for handling a contradiction detected during
; inference.
;
;
;
;
; written : jpm 11/30/82
; modified: njm 10/06/88
;
;
;
(defun options-in-contr-h ()
(declare (special sneps:outunit))
(format sneps:outunit
"~%~T You have the following options:~
~%~T~T 1. [A]ttempt to resolve the contradiction automatically;~
~%~T~T 2. [C]ontinue anyway, knowing that a contradiction is derivable;~
~%~T~T 3. [R]e-start the exact same run in a different context which is~
~%~T~T not inconsistent;~
~%~T~T 4. [D]rop the run altogether.
~%~T (please type a, c, r or d)"))
;
; =============================================================================
;
;
; read-contr-h-option
; -------------------
;
;
; arguments :
;
; returns : 'C | 'R | 'D
;
; description : This function reads an answer of the user.
;
;
;
;
; written : jpm 11/30/82
; modified: njm 10/06/88
; hc 10/19/88 (get rid of repeat)
;
(defun read-contr-h-option ()
(declare (special sneps:outunit sneps:inunit))
(let (ans)
(loop (ct-prompt)
(case (setf ans (read sneps:inunit))
((1 2 3 4 snepsul:A snepsul:C snepsul:R snepsul:D)
(return ans))
((snepslog::A snepslog::C snepslog::R snepslog::D)
(return ans)))
(format sneps:outunit "Please type a, c, r or d"))))
;
; =============================================================================
;
; change-context
; --------------
;
;
; arguments : newnd-supps - <context set>
contrnd - supps - < context set >
; newnd-otlst - <origin tag list>
contrnd - otlst - < origin tag list >
; context - <context>
;
; returns : <node set>
;
; description : This function takes as arguments:
; 'newnd-supps' - set of contexts that support the
; newly derived node
; 'contrnd-supps' - set of contexts that support the
; node which contradicts the newly
; derived node.
; 'newnd-otlst' - list of origin tags corresponding
; to 'newnd-supps'.
; 'contrnd-otlst' - list of origin tags corresponding
; to 'contrnd-supps'.
; 'context' - context in which the new node was
; derived.
; 'context-name' - the name of the context above
;
;
; This function changes the current context, which is
; inconsistent, to a consistent context. The user may
; change the current context by
- removing one or more hypotheses from inconsistent
; sets of hypotheses that are part of the cuurent
; context (see make-consistent)
; - removing hypotheses from a set of hypotheses that
; is not known to be inconsistent and that is
; also part of the current context (see browse-
; through)
; - adding new hypotheses to the current context
; (see add-new-hyps)
;
;
; written : jpm 11/30/82
modified : mrc 12/12/88
modified : flj 3/22/99
;
(defun change-context (newnd-supps contrnd-supps
newnd-otlst contrnd-otlst
context context-name)
(inform-user newnd-supps contrnd-supps context)
(let ((crntct (context-hyps context))
(unseen-hyps (context-hyps context))
(new-hyps (new.ns))
(new-ot nil)
(contr-ot nil)
(contr-otlst contrnd-otlst))
(sneps:do.cts
(new-supp newnd-supps)
(setf new-ot (first newnd-otlst))
(setf newnd-otlst (rest newnd-otlst))
(setf contr-otlst contrnd-otlst)
(sneps:do.cts
(contr-supp contrnd-supps)
(let* ((inc-hyps
(sneps::union.ns (context-hyps new-supp)
(context-hyps contr-supp)))
(intersec-hyps
(sneps::intersect.ns (context-hyps new-supp)
(context-hyps contr-supp))))
(setf contr-ot (first contr-otlst))
(setf contr-otlst (rest contr-otlst))
(when (sneps:issubset.ns inc-hyps crntct)
(if intersec-hyps (warn-intersection intersec-hyps))
(setf crntct
(union.ns (compl.ns crntct inc-hyps)
(make-consistent inc-hyps
(fullbuildcontext crntct (new.cts))
new-supp
contr-supp
new-ot
contr-ot))))
(setf unseen-hyps (compl.ns unseen-hyps inc-hyps)))))
(when (not (isnew.ns unseen-hyps))
(setf crntct (union.ns (compl.ns crntct unseen-hyps)
(browse-through unseen-hyps crntct))))
(change-context-name crntct context-name)
(if (and (not (isnew.ns (setf new-hyps (add-new-hyps))))
(choose.ns new-hyps))
(change-context-name (union.ns crntct new-hyps) context-name)
crntct)))
;
; =============================================================================
;
;
; change-context-name
; -------------------
;
;
; arguments : lhyps - <node set>
; crntname - <context name>
;
;
; returns : <lhyps>
;
; description : This function resets the current context name to refer
to the context formed by lhyps .
;
;
modified : flj 3/22/99
;
;
(defun change-context-name (lhyps crntname)
(name.ct (fullbuildcontext lhyps (new.cts)) crntname)
lhyps)
;
; =============================================================================
;
;
; inform-user
; -----------
;
;
; arguments : newnd-supps - <context set>
contrnd - supps - < context set >
; context - <context>
;
; returns : <>
;
; description : This function tells the user from which sets he
must remove one or more hypotheses in order to
make the current consistent . Modification in 99
to advise user of WFFS common to more than one set .
;
;
;
; written : mrc 11/16/88
modified : flj 3/22/99
;
(defun inform-user (newnd-supps contrnd-supps context)
(declare (special sneps:outunit))
(let ((hyp-sets nil))
(format sneps:outunit
"~%~%~T In order to make the context consistent you must delete at least~
~%~T one hypothesis from each of the following sets of hypotheses:")
(sneps:do.cts
(newsupp newnd-supps)
(if (null contrnd-supps)
(let ((union-hyps (context-hyps newsupp)))
(if (sneps::issubset.ns union-hyps (context-hyps context))
(progn
(setf hyp-sets (cons union-hyps hyp-sets))
(format sneps:outunit "~%~T~T~T ~A"
(snip:slight-describe-or-surface.ns
union-hyps
nil)))))
(sneps:do.cts
(contrsupp contrnd-supps)
(let ((union-hyps (union.ns (context-hyps newsupp)
(context-hyps contrsupp))))
(if (sneps::issubset.ns union-hyps (context-hyps context))
(progn
(setf hyp-sets (cons union-hyps hyp-sets))
(format sneps:outunit "~%~T~T~T ~A"
(snip:slight-describe-or-surface.ns
union-hyps
nil)))))))
)
(let* ((one-list (apply #'append hyp-sets))
(doubles (get-doubles one-list)))
(if doubles
(progn
(if (> (cardinality.ns doubles) 1)
(format sneps:outunit
"~%~%~T~T The hypotheses listed below are included in more than~
~%~T one set. Removing one of these will make more than one~
~%~T set consistent.")
(format sneps:outunit
"~%~%~T The hypothesis listed below is included in more than one~
~%~T set. Removing it will make more than one set consistent."))
(format sneps:outunit "~%~T~T~T ~A"
(snip:slight-describe-or-surface.ns
doubles
nil)))))
)
(format sneps:outunit "~%~%~T"))
;
; =============================================================================
;
; get-doubles
; -----------
;
;
arguments : lst - < node set >
; slst - <node set> (optional)
; dlst - <node set> (optional)
;
; returns : <node set>
;
; description : helper function called by inform-user to find any
elements listed more than once in lst
;
;
;
;
written : flj 3/22/99
; modified:
;
(defun get-doubles (lst &optional slst dlst)
"Returns a list of all elements in lst that are listed more than once"
(cond ((null lst) (reverse dlst))
((member (first lst) dlst) (get-doubles (rest lst) slst dlst))
((member (first lst) slst) (get-doubles (rest lst) slst (cons
(first lst)
dlst)))
(t (get-doubles (rest lst) (cons (first lst) slst) dlst))))
; =============================================================================
;
; warn-intersection
; -----------------
;
;
arguments : hyps - < node set >
;
; returns : <>
;
; description : Called by change-context.
Warns user when context to be revised has wff(s ) common
to BOTH contradictory WFFS ( number sensitive )
;
;
;
;
written : flj 3/22/99
; modified:
;
(defun warn-intersection (hyps)
(declare (special sneps:outunit))
(if (> (cardinality.ns hyps) 1)
(format sneps:outunit
"~T WARNING: the following hypotheses support BOTH contradictory WFFS,~
~%~T so removing one of these might be too extreme a revision.~%")
(format sneps:outunit
"~T WARNING: the following hypothesis supports BOTH contradictory WFFS,~
~%~T so removing it might be too extreme a revision.~%"))
(print-lst hyps))
;
; =============================================================================
;
; browse-through
; --------------
;
;
arguments : hyplst - < node set >
; fullcthyps - <node set>
;
; returns : <node set>
;
; description : This function allows the user to inspect and
; eventually discard any hypotheses in 'hyplst'
( see browse - through - hyps ) . 99 modification
; changed list elements appearancefrom "M#!"
; style to "WFF#" style.
;
;
;
; written : jpm 11/30/82
modified : flj 3/22/99
;
;
(defun browse-through (hyplst fullcthyps)
(declare (special sneps:outunit))
(format sneps:outunit
"~%~T The following (not known to be inconsistent) set of ~
~%~T hypotheses was also part of the context where the ~
~%~T contradiction was derived: ~
~%~T~T~T ~A
~%~T Do you want to inspect or discard some of them?"
(snip:slight-describe-or-surface.ns
hyplst
nil))
(cond ((user-says-yes) (browse-through-hyps hyplst fullcthyps))
(t hyplst)))
;
; =============================================================================
;
; add-new-hyps
; ------------
;
;
; arguments : -----
;
; returns : <node set>
;
; description : This function asks the user if he wants to
; add new hypotheses to the current context
; and returns the hypotheses added by the user
; (eventually none).
;
;
; written : jpm 11/30/82
; modified:
;
;
(defun add-new-hyps ()
(declare (special sneps:outunit snepslog:*SNePSLOGRunning*))
(let ((option (if snepslog:*SNePSLOGRunning*
'snepsul::o
'snepsul::u))
(add-new? (yes-or-no-p "~%~T Do you want to add a new hypothesis? "))
(newhyps (new.ns)))
(loop
while add-new?
do (setf newhyps (insert.ns
(request-new-hyp option) newhyps)
add-new? (yes-or-no-p
"~%~T Do you want to add another hypothesis? ")))
newhyps))
;
; =============================================================================
;
;
; request-new-hyp
; ---------------
;
;
; arguments : ----
;
; returns : <node set>
;
; description : This function reads a hypothesis entered by the
; user and returns it.
;
; written : choi ??/??/92
(defun request-new-hyp (option)
(declare (special sneps:outunit sneps:inunit))
(if (eq option 'snepsul::u)
(format sneps:outunit
"~%~T Enter a hypothesis using the SNePSUL command `assert': ")
(format sneps:outunit
"~%~T Enter a hypothesis using SNePSLOG all on one line and ending with a period: "))
(let (newhyp ans)
(loop (ct-prompt)
(if (eq option 'snepsul::u)
(setq ans (read sneps:inunit))
(setq ans (snepslog::snepslog-read sneps:inunit)))
(setq newhyp (sneps:topsneval (insert-context ans)))
(cond (newhyp
(return (sneps:choose.ns newhyp)))
(t
(format sneps:outunit
"~%~T Oops... something went wrong~
~%~T Would you try to enter again?")
(unless (user-says-yes)
(return (new.ns))))))))
(defun insert-context (comm)
(declare (special sneps:crntct))
`(,@comm :context ,(intern (string sneps:crntct) 'snepsul)))
;
; =============================================================================
;
;
; remove-new-hyp
; --------------
;
;
; arguments : <command>
;
; returns : <node set>
;
; description : This function removes the node built by
; the last command (which was an add command)
; from the current context.
;
;
;
written : mrc 12/20/88
modified : flj 3/22/99
;
(defun remove-new-hyp (lastcommand)
;; Assume (is-add lastcommand) is True
(let ((addcommand (if (eql (first lastcommand) 'snip:add)
(cons 'sneps:assert (rest lastcommand))
(cons 'sneps:assert (rest (second lastcommand))))))
(remove-new-hyp-1 (sneps:topsneval addcommand))))
(defun remove-new-hyp-1 (newhyp)
(declare (special snip:crntctname sneps:outunit))
(format sneps:outunit "Changing the hypothesis set of ~A.~%" snip:crntctname)
(change-context-name (compl.ns (context-hyps (value.sv snip:crntctname))
newhyp) snip:crntctname))
;
; =============================================================================
;
;
; is-add
; ------
;
;
; arguments : <command>
;
; returns : T | NIL
;
; description : This function returns T if 'command'
; is an add command.
;
;
;
written : mrc 12/20/88
; modified:
;
;
(defun is-add (command)
(or (eq (first command) 'snip:add)
(and (consp (second command))
(eql (first (second command)) 'snip:add))))
| null | https://raw.githubusercontent.com/SNePS/SNePS2/d3862108609b1879f2c546112072ad4caefc050d/snebr/sniphandler.lisp | lisp | Syntax : Common - Lisp ; Package : SNEBR ; Base : 10 -*-
This file is part of SNePS.
you may
not use this file except in compliance with the License. You
may obtain a copy of the License at
. edu/sneps/Downloads/ubpl.pdf.
or implied. See the License for the specific language gov
erning rights and limitations under the License.
=============================================================================
snip-contr-handler
-------------------
arguments : newnode - <node>
context - <context>
returns : ---
description : This function takes as arguments a node `contrnd' which
contradicts some newly derived node `newnode' (refer
to the function ck-contradiction), and a context
`context' under which the newly asserted node was derived.
It warns the user of the detected contradiction and
calls the function contr-h to handle the contradiction.
written : mrc 11/15/88
=============================================================================
contr-h
-------
arguments : newnd-supps - <context set>
newnd-otlst - <ot list>
context - <context>
returns : <node set>
description : This function handles contradictions detected during
inference.
In the current implementation the contradiction is
options:
is derivable;
context which is not inconsistent;
This function asks the user what his choice is and
takes the necessary actions to execute that choice.
written : jpm 11/30/82
modified: njm 10/06/88
modified: mrc 11/15/88
flj 03/22/99
=============================================================================
options-in-contr-h
------------------
arguments :
returns : nil
description : This function tells the user the possibilities he
has for handling a contradiction detected during
inference.
written : jpm 11/30/82
modified: njm 10/06/88
~
~
~
=============================================================================
read-contr-h-option
-------------------
arguments :
returns : 'C | 'R | 'D
description : This function reads an answer of the user.
written : jpm 11/30/82
modified: njm 10/06/88
hc 10/19/88 (get rid of repeat)
=============================================================================
change-context
--------------
arguments : newnd-supps - <context set>
newnd-otlst - <origin tag list>
context - <context>
returns : <node set>
description : This function takes as arguments:
'newnd-supps' - set of contexts that support the
newly derived node
'contrnd-supps' - set of contexts that support the
node which contradicts the newly
derived node.
'newnd-otlst' - list of origin tags corresponding
to 'newnd-supps'.
'contrnd-otlst' - list of origin tags corresponding
to 'contrnd-supps'.
'context' - context in which the new node was
derived.
'context-name' - the name of the context above
This function changes the current context, which is
inconsistent, to a consistent context. The user may
change the current context by
sets of hypotheses that are part of the cuurent
context (see make-consistent)
- removing hypotheses from a set of hypotheses that
is not known to be inconsistent and that is
also part of the current context (see browse-
through)
- adding new hypotheses to the current context
(see add-new-hyps)
written : jpm 11/30/82
=============================================================================
change-context-name
-------------------
arguments : lhyps - <node set>
crntname - <context name>
returns : <lhyps>
description : This function resets the current context name to refer
=============================================================================
inform-user
-----------
arguments : newnd-supps - <context set>
context - <context>
returns : <>
description : This function tells the user from which sets he
written : mrc 11/16/88
=============================================================================
get-doubles
-----------
slst - <node set> (optional)
dlst - <node set> (optional)
returns : <node set>
description : helper function called by inform-user to find any
modified:
=============================================================================
warn-intersection
-----------------
returns : <>
description : Called by change-context.
modified:
=============================================================================
browse-through
--------------
fullcthyps - <node set>
returns : <node set>
description : This function allows the user to inspect and
eventually discard any hypotheses in 'hyplst'
changed list elements appearancefrom "M#!"
style to "WFF#" style.
written : jpm 11/30/82
=============================================================================
add-new-hyps
------------
arguments : -----
returns : <node set>
description : This function asks the user if he wants to
add new hypotheses to the current context
and returns the hypotheses added by the user
(eventually none).
written : jpm 11/30/82
modified:
=============================================================================
request-new-hyp
---------------
arguments : ----
returns : <node set>
description : This function reads a hypothesis entered by the
user and returns it.
written : choi ??/??/92
=============================================================================
remove-new-hyp
--------------
arguments : <command>
returns : <node set>
description : This function removes the node built by
the last command (which was an add command)
from the current context.
Assume (is-add lastcommand) is True
=============================================================================
is-add
------
arguments : <command>
returns : T | NIL
description : This function returns T if 'command'
is an add command.
modified:
|
Copyright ( C ) 1984 - -2013
Research Foundation of State University of New York
Version : $ I d : , v 1.3 2013/08/28 19:07:24 shapiro Exp $
$ BEGIN LICENSE$
The contents of this file are subject to the University at
Software distributed under the License is distributed on an
" AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express
The Original Code is SNePS 2.8 .
The Initial Developer of the Original Code is Research Foun
dation of State University of New York , on behalf of Univer
sity at Buffalo .
Portions created by the Initial Developer are Copyright ( C )
2011 Research Foundation of State University of New York , on
behalf of University at Buffalo . All Rights Reserved .
$ END LICENSE$
(in-package :snebr)
contrnd - < node >
(defun snip-contr-handler (newnode contrnd context)
(declare (special sneps:outunit snip:crntctname *br-auto-mode*))
(progn
(unless *br-auto-mode*
(format sneps:outunit
"~%~%~T A contradiction was detected within context ~A.~
~%~T The contradiction involves the newly derived proposition:~
~%~T~T~T ~A ~
~%~T and the previously existing proposition:~
~%~T~T~T ~A"
snip:crntctname
(snip:describe-or-surface newnode nil)
(snip:describe-or-surface contrnd nil)))
(contr-h (ctcs-to-cts (sneps:node-asupport newnode))
(ctcs-to-cts (sneps:node-asupport contrnd))
(sneps:ctcs-to-ots (sneps:node-asupport newnode))
(sneps:ctcs-to-ots (sneps:node-asupport contrnd))
context)))
contrnd - supps - < context set >
contrnd - otlst - < ot list >
resolved by the user which may choose one of three
1 . [ C]ontinue anyway , knowing that a contradiction
2 . [ R]e - start the exact same run in a different
3 . [ D]rop the run altogether .
hc
(defun contr-h (newnd-supps contrnd-supps newnd-otlst contrnd-otlst context)
(declare (special sneps:outunit snip:crntctname *br-auto-mode*
*most-entrenched-props*))
(unless *br-auto-mode* (options-in-contr-h))
(let* ((ans (if *br-auto-mode* 'snepsul:A (read-contr-h-option)))
(lastcommand #-explorer (value.sv 'sneps:command)
#+explorer (if (eql (first (value.sv 'sneps:command))
'sys:displaced)
(second (value.sv 'sneps:command))
(value.sv 'sneps:command))
)
(mep *most-entrenched-props*))
(cond ((or (eq ans 'snepsul:C) (eql ans 2)))
((or (eq ans 'snepsul:A) (eql ans 1))
(autobr newnd-supps contrnd-supps context)
(if (sneps:issubset.ns (context-hyps (car newnd-supps)) (context-hyps sneps:crntct))
(progn
(setf *most-entrenched-props* mep)
(sneps:topsneval lastcommand))
(throw 'snip:Stop-Handled-by-Contradiction-Handler nil)))
(t (multi:clear-all-queues)
(sneps:clear-infer)
(cond ((or (eq ans 'snepsul:R)(eq ans 'snepslog::R)(eql ans 3))
(change-context newnd-supps contrnd-supps
newnd-otlst contrnd-otlst
context snip:crntctname)
(sneps:topsneval lastcommand))
((is-add lastcommand) (remove-new-hyp lastcommand)))
(throw 'snip:Stop-Handled-by-Contradiction-Handler nil)))))
(defun options-in-contr-h ()
(declare (special sneps:outunit))
(format sneps:outunit
"~%~T You have the following options:~
~%~T~T 3. [R]e-start the exact same run in a different context which is~
~%~T~T 4. [D]rop the run altogether.
~%~T (please type a, c, r or d)"))
(defun read-contr-h-option ()
(declare (special sneps:outunit sneps:inunit))
(let (ans)
(loop (ct-prompt)
(case (setf ans (read sneps:inunit))
((1 2 3 4 snepsul:A snepsul:C snepsul:R snepsul:D)
(return ans))
((snepslog::A snepslog::C snepslog::R snepslog::D)
(return ans)))
(format sneps:outunit "Please type a, c, r or d"))))
contrnd - supps - < context set >
contrnd - otlst - < origin tag list >
- removing one or more hypotheses from inconsistent
modified : mrc 12/12/88
modified : flj 3/22/99
(defun change-context (newnd-supps contrnd-supps
newnd-otlst contrnd-otlst
context context-name)
(inform-user newnd-supps contrnd-supps context)
(let ((crntct (context-hyps context))
(unseen-hyps (context-hyps context))
(new-hyps (new.ns))
(new-ot nil)
(contr-ot nil)
(contr-otlst contrnd-otlst))
(sneps:do.cts
(new-supp newnd-supps)
(setf new-ot (first newnd-otlst))
(setf newnd-otlst (rest newnd-otlst))
(setf contr-otlst contrnd-otlst)
(sneps:do.cts
(contr-supp contrnd-supps)
(let* ((inc-hyps
(sneps::union.ns (context-hyps new-supp)
(context-hyps contr-supp)))
(intersec-hyps
(sneps::intersect.ns (context-hyps new-supp)
(context-hyps contr-supp))))
(setf contr-ot (first contr-otlst))
(setf contr-otlst (rest contr-otlst))
(when (sneps:issubset.ns inc-hyps crntct)
(if intersec-hyps (warn-intersection intersec-hyps))
(setf crntct
(union.ns (compl.ns crntct inc-hyps)
(make-consistent inc-hyps
(fullbuildcontext crntct (new.cts))
new-supp
contr-supp
new-ot
contr-ot))))
(setf unseen-hyps (compl.ns unseen-hyps inc-hyps)))))
(when (not (isnew.ns unseen-hyps))
(setf crntct (union.ns (compl.ns crntct unseen-hyps)
(browse-through unseen-hyps crntct))))
(change-context-name crntct context-name)
(if (and (not (isnew.ns (setf new-hyps (add-new-hyps))))
(choose.ns new-hyps))
(change-context-name (union.ns crntct new-hyps) context-name)
crntct)))
to the context formed by lhyps .
modified : flj 3/22/99
(defun change-context-name (lhyps crntname)
(name.ct (fullbuildcontext lhyps (new.cts)) crntname)
lhyps)
contrnd - supps - < context set >
must remove one or more hypotheses in order to
make the current consistent . Modification in 99
to advise user of WFFS common to more than one set .
modified : flj 3/22/99
(defun inform-user (newnd-supps contrnd-supps context)
(declare (special sneps:outunit))
(let ((hyp-sets nil))
(format sneps:outunit
"~%~%~T In order to make the context consistent you must delete at least~
~%~T one hypothesis from each of the following sets of hypotheses:")
(sneps:do.cts
(newsupp newnd-supps)
(if (null contrnd-supps)
(let ((union-hyps (context-hyps newsupp)))
(if (sneps::issubset.ns union-hyps (context-hyps context))
(progn
(setf hyp-sets (cons union-hyps hyp-sets))
(format sneps:outunit "~%~T~T~T ~A"
(snip:slight-describe-or-surface.ns
union-hyps
nil)))))
(sneps:do.cts
(contrsupp contrnd-supps)
(let ((union-hyps (union.ns (context-hyps newsupp)
(context-hyps contrsupp))))
(if (sneps::issubset.ns union-hyps (context-hyps context))
(progn
(setf hyp-sets (cons union-hyps hyp-sets))
(format sneps:outunit "~%~T~T~T ~A"
(snip:slight-describe-or-surface.ns
union-hyps
nil)))))))
)
(let* ((one-list (apply #'append hyp-sets))
(doubles (get-doubles one-list)))
(if doubles
(progn
(if (> (cardinality.ns doubles) 1)
(format sneps:outunit
"~%~%~T~T The hypotheses listed below are included in more than~
~%~T one set. Removing one of these will make more than one~
~%~T set consistent.")
(format sneps:outunit
"~%~%~T The hypothesis listed below is included in more than one~
~%~T set. Removing it will make more than one set consistent."))
(format sneps:outunit "~%~T~T~T ~A"
(snip:slight-describe-or-surface.ns
doubles
nil)))))
)
(format sneps:outunit "~%~%~T"))
arguments : lst - < node set >
elements listed more than once in lst
written : flj 3/22/99
(defun get-doubles (lst &optional slst dlst)
"Returns a list of all elements in lst that are listed more than once"
(cond ((null lst) (reverse dlst))
((member (first lst) dlst) (get-doubles (rest lst) slst dlst))
((member (first lst) slst) (get-doubles (rest lst) slst (cons
(first lst)
dlst)))
(t (get-doubles (rest lst) (cons (first lst) slst) dlst))))
arguments : hyps - < node set >
Warns user when context to be revised has wff(s ) common
to BOTH contradictory WFFS ( number sensitive )
written : flj 3/22/99
(defun warn-intersection (hyps)
(declare (special sneps:outunit))
(if (> (cardinality.ns hyps) 1)
(format sneps:outunit
"~T WARNING: the following hypotheses support BOTH contradictory WFFS,~
~%~T so removing one of these might be too extreme a revision.~%")
(format sneps:outunit
"~T WARNING: the following hypothesis supports BOTH contradictory WFFS,~
~%~T so removing it might be too extreme a revision.~%"))
(print-lst hyps))
arguments : hyplst - < node set >
( see browse - through - hyps ) . 99 modification
modified : flj 3/22/99
(defun browse-through (hyplst fullcthyps)
(declare (special sneps:outunit))
(format sneps:outunit
"~%~T The following (not known to be inconsistent) set of ~
~%~T hypotheses was also part of the context where the ~
~%~T contradiction was derived: ~
~%~T~T~T ~A
~%~T Do you want to inspect or discard some of them?"
(snip:slight-describe-or-surface.ns
hyplst
nil))
(cond ((user-says-yes) (browse-through-hyps hyplst fullcthyps))
(t hyplst)))
(defun add-new-hyps ()
(declare (special sneps:outunit snepslog:*SNePSLOGRunning*))
(let ((option (if snepslog:*SNePSLOGRunning*
'snepsul::o
'snepsul::u))
(add-new? (yes-or-no-p "~%~T Do you want to add a new hypothesis? "))
(newhyps (new.ns)))
(loop
while add-new?
do (setf newhyps (insert.ns
(request-new-hyp option) newhyps)
add-new? (yes-or-no-p
"~%~T Do you want to add another hypothesis? ")))
newhyps))
(defun request-new-hyp (option)
(declare (special sneps:outunit sneps:inunit))
(if (eq option 'snepsul::u)
(format sneps:outunit
"~%~T Enter a hypothesis using the SNePSUL command `assert': ")
(format sneps:outunit
"~%~T Enter a hypothesis using SNePSLOG all on one line and ending with a period: "))
(let (newhyp ans)
(loop (ct-prompt)
(if (eq option 'snepsul::u)
(setq ans (read sneps:inunit))
(setq ans (snepslog::snepslog-read sneps:inunit)))
(setq newhyp (sneps:topsneval (insert-context ans)))
(cond (newhyp
(return (sneps:choose.ns newhyp)))
(t
(format sneps:outunit
"~%~T Oops... something went wrong~
~%~T Would you try to enter again?")
(unless (user-says-yes)
(return (new.ns))))))))
(defun insert-context (comm)
(declare (special sneps:crntct))
`(,@comm :context ,(intern (string sneps:crntct) 'snepsul)))
written : mrc 12/20/88
modified : flj 3/22/99
(defun remove-new-hyp (lastcommand)
(let ((addcommand (if (eql (first lastcommand) 'snip:add)
(cons 'sneps:assert (rest lastcommand))
(cons 'sneps:assert (rest (second lastcommand))))))
(remove-new-hyp-1 (sneps:topsneval addcommand))))
(defun remove-new-hyp-1 (newhyp)
(declare (special snip:crntctname sneps:outunit))
(format sneps:outunit "Changing the hypothesis set of ~A.~%" snip:crntctname)
(change-context-name (compl.ns (context-hyps (value.sv snip:crntctname))
newhyp) snip:crntctname))
written : mrc 12/20/88
(defun is-add (command)
(or (eq (first command) 'snip:add)
(and (consp (second command))
(eql (first (second command)) 'snip:add))))
|
1c1e663d235c5c8fd1c61405d7de8471e580c4e6d93384b5d8e7926204726590 | vernemq/vernemq | vmq_dev_api_SUITE.erl | -module(vmq_dev_api_SUITE).
-compile([nowarn_export_all,export_all]).
-include_lib("vmq_commons/include/vmq_types.hrl").
-include_lib("common_test/include/ct.hrl").
suite() ->
[{timetrap,{seconds,30}}].
init_per_suite(Config) ->
cover:start(),
Config.
end_per_suite(_Config) ->
ok.
init_per_group(_GroupName, Config) ->
Config.
end_per_group(_GroupName, _Config) ->
ok.
init_per_testcase(_TestCase, Config) ->
ets:new(?MODULE, [named_table, public]),
vmq_test_utils:setup(),
enable_on_subscribe(),
enable_on_publish(),
vmq_server_cmd:set_config(allow_anonymous, true),
vmq_server_cmd:set_config(retry_interval, 10),
vmq_server_cmd:listener_start(1888, [{allowed_protocol_versions, "3,4,5"}]),
Config.
end_per_testcase(_TestCase, _Config) ->
ets:delete(?MODULE),
vmq_test_utils:teardown(),
ok.
groups() ->
[].
all() ->
[reauthorize_works,
reauthorize_works_m5].
reauthorize_works_m5(_Config) ->
Connect = packetv5:gen_connect("vmq-reauth-client", [{keepalive,60},{clean_start, false}]),
Connack = packetv5:gen_connack(?M5_CONNACK_ACCEPT),
SubTopic1 = packetv5:gen_subtopic(<<"some/reauth/1">>, 0),
SubTopic2 = packetv5:gen_subtopic(<<"some/reauth/2">>, 0),
Subscribe = packetv5:gen_subscribe(1, [SubTopic1, SubTopic2], #{}),
Suback = packetv5:gen_suback(1, [0, 0], #{}),
{ok, Socket} = packetv5:do_client_connect(Connect, Connack, []),
ets:insert(?MODULE, {[<<"some">>,<<"reauth">>, <<"1">>]}),
ets:insert(?MODULE, {[<<"some">>,<<"reauth">>, <<"2">>]}),
ok = gen_tcp:send(Socket, Subscribe),
ok = packetv5:expect_frame(Socket, Suback),
Publish = packetv5:gen_publish("some/reauth/1", 0, <<"thepayload">>, [{mid, 2}]),
ok = gen_tcp:send(Socket, Publish),
ok = packetv5:expect_frame(Socket, Publish),
% disabling the subscribe hook, and reauthorizing the client will reject the publish
ets:delete(?MODULE, [<<"some">>,<<"reauth">>, <<"1">>]),
Node = node(),
Changes0 = vernemq_dev_api:reauthorize_subscriptions(undefined, {"", <<"vmq-reauth-client">>}, []),
{[{Node, [{[<<"some">>, <<"reauth">>, <<"1">>], {0, _SubInfo}}]}], []} = Changes0,
ok = gen_tcp:send(Socket, Publish),
{error, timeout} = gen_tcp:recv(Socket, 0, 100),
gen_tcp:close(Socket).
reauthorize_works(_Config) ->
Connect = packet:gen_connect("vmq-reauth-client", [{keepalive,60},{clean_session, false}]),
Connack = packet:gen_connack(0),
Subscribe = packet:gen_subscribe(1, [{"some/reauth/1", 0}, {"some/reauth/2", 0}]),
Suback = packet:gen_suback(1, [0, 0]),
{ok, Socket} = packet:do_client_connect(Connect, Connack, []),
ets:insert(?MODULE, {[<<"some">>,<<"reauth">>, <<"1">>]}),
ets:insert(?MODULE, {[<<"some">>,<<"reauth">>, <<"2">>]}),
ok = gen_tcp:send(Socket, Subscribe),
ok = packet:expect_packet(Socket, "suback", Suback),
Publish = packet:gen_publish("some/reauth/1", 0, <<"thepayload">>, [{mid, 2}]),
ok = gen_tcp:send(Socket, Publish),
ok = packet:expect_packet(Socket, "publish", Publish),
% disabling the subscribe hook, and reauthorizing the client will reject the publish
ets:delete(?MODULE, [<<"some">>,<<"reauth">>, <<"1">>]),
Node = node(),
Changes0 = vernemq_dev_api:reauthorize_subscriptions(undefined, {"", <<"vmq-reauth-client">>}, []),
{[{Node, [{[<<"some">>, <<"reauth">>, <<"1">>], 0}]}], []} = Changes0,
ok = gen_tcp:send(Socket, Publish),
{error, timeout} = gen_tcp:recv(Socket, 0, 100),
gen_tcp:close(Socket).
enable_on_subscribe() ->
ok = vmq_plugin_mgr:enable_module_plugin(
auth_on_subscribe, ?MODULE, hook_auth_on_subscribe, 3),
ok = vmq_plugin_mgr:enable_module_plugin(
auth_on_subscribe, ?MODULE, hook_auth_on_subscribe, 3,
[{compat, {auth_on_subscribe_m5, vmq_plugin_compat_m5,
convert, 4}}]).
enable_on_publish() ->
ok = vmq_plugin_mgr:enable_module_plugin(
auth_on_publish, ?MODULE, hook_auth_on_publish, 6),
ok = vmq_plugin_mgr:enable_module_plugin(
auth_on_publish, ?MODULE, hook_auth_on_publish, 6,
[{compat, {auth_on_publish_m5, vmq_plugin_compat_m5,
convert, 7}}]).
hook_auth_on_subscribe(_, _, Topics) ->
Verdict =
lists:foldl(fun(_, false) ->
false;
({T, _}, true) ->
case ets:lookup(?MODULE, T) of
[] ->
false;
_ ->
true
end
end, true, Topics),
case Verdict of
true -> ok;
false -> next
end.
hook_auth_on_publish(_,_,_,_,_,_) ->
ok.
| null | https://raw.githubusercontent.com/vernemq/vernemq/eb1a262035af47e90d9edf07f36c1b1503557c1f/apps/vmq_server/test/vmq_dev_api_SUITE.erl | erlang | disabling the subscribe hook, and reauthorizing the client will reject the publish
disabling the subscribe hook, and reauthorizing the client will reject the publish | -module(vmq_dev_api_SUITE).
-compile([nowarn_export_all,export_all]).
-include_lib("vmq_commons/include/vmq_types.hrl").
-include_lib("common_test/include/ct.hrl").
suite() ->
[{timetrap,{seconds,30}}].
init_per_suite(Config) ->
cover:start(),
Config.
end_per_suite(_Config) ->
ok.
init_per_group(_GroupName, Config) ->
Config.
end_per_group(_GroupName, _Config) ->
ok.
init_per_testcase(_TestCase, Config) ->
ets:new(?MODULE, [named_table, public]),
vmq_test_utils:setup(),
enable_on_subscribe(),
enable_on_publish(),
vmq_server_cmd:set_config(allow_anonymous, true),
vmq_server_cmd:set_config(retry_interval, 10),
vmq_server_cmd:listener_start(1888, [{allowed_protocol_versions, "3,4,5"}]),
Config.
end_per_testcase(_TestCase, _Config) ->
ets:delete(?MODULE),
vmq_test_utils:teardown(),
ok.
groups() ->
[].
all() ->
[reauthorize_works,
reauthorize_works_m5].
reauthorize_works_m5(_Config) ->
Connect = packetv5:gen_connect("vmq-reauth-client", [{keepalive,60},{clean_start, false}]),
Connack = packetv5:gen_connack(?M5_CONNACK_ACCEPT),
SubTopic1 = packetv5:gen_subtopic(<<"some/reauth/1">>, 0),
SubTopic2 = packetv5:gen_subtopic(<<"some/reauth/2">>, 0),
Subscribe = packetv5:gen_subscribe(1, [SubTopic1, SubTopic2], #{}),
Suback = packetv5:gen_suback(1, [0, 0], #{}),
{ok, Socket} = packetv5:do_client_connect(Connect, Connack, []),
ets:insert(?MODULE, {[<<"some">>,<<"reauth">>, <<"1">>]}),
ets:insert(?MODULE, {[<<"some">>,<<"reauth">>, <<"2">>]}),
ok = gen_tcp:send(Socket, Subscribe),
ok = packetv5:expect_frame(Socket, Suback),
Publish = packetv5:gen_publish("some/reauth/1", 0, <<"thepayload">>, [{mid, 2}]),
ok = gen_tcp:send(Socket, Publish),
ok = packetv5:expect_frame(Socket, Publish),
ets:delete(?MODULE, [<<"some">>,<<"reauth">>, <<"1">>]),
Node = node(),
Changes0 = vernemq_dev_api:reauthorize_subscriptions(undefined, {"", <<"vmq-reauth-client">>}, []),
{[{Node, [{[<<"some">>, <<"reauth">>, <<"1">>], {0, _SubInfo}}]}], []} = Changes0,
ok = gen_tcp:send(Socket, Publish),
{error, timeout} = gen_tcp:recv(Socket, 0, 100),
gen_tcp:close(Socket).
reauthorize_works(_Config) ->
Connect = packet:gen_connect("vmq-reauth-client", [{keepalive,60},{clean_session, false}]),
Connack = packet:gen_connack(0),
Subscribe = packet:gen_subscribe(1, [{"some/reauth/1", 0}, {"some/reauth/2", 0}]),
Suback = packet:gen_suback(1, [0, 0]),
{ok, Socket} = packet:do_client_connect(Connect, Connack, []),
ets:insert(?MODULE, {[<<"some">>,<<"reauth">>, <<"1">>]}),
ets:insert(?MODULE, {[<<"some">>,<<"reauth">>, <<"2">>]}),
ok = gen_tcp:send(Socket, Subscribe),
ok = packet:expect_packet(Socket, "suback", Suback),
Publish = packet:gen_publish("some/reauth/1", 0, <<"thepayload">>, [{mid, 2}]),
ok = gen_tcp:send(Socket, Publish),
ok = packet:expect_packet(Socket, "publish", Publish),
ets:delete(?MODULE, [<<"some">>,<<"reauth">>, <<"1">>]),
Node = node(),
Changes0 = vernemq_dev_api:reauthorize_subscriptions(undefined, {"", <<"vmq-reauth-client">>}, []),
{[{Node, [{[<<"some">>, <<"reauth">>, <<"1">>], 0}]}], []} = Changes0,
ok = gen_tcp:send(Socket, Publish),
{error, timeout} = gen_tcp:recv(Socket, 0, 100),
gen_tcp:close(Socket).
enable_on_subscribe() ->
ok = vmq_plugin_mgr:enable_module_plugin(
auth_on_subscribe, ?MODULE, hook_auth_on_subscribe, 3),
ok = vmq_plugin_mgr:enable_module_plugin(
auth_on_subscribe, ?MODULE, hook_auth_on_subscribe, 3,
[{compat, {auth_on_subscribe_m5, vmq_plugin_compat_m5,
convert, 4}}]).
enable_on_publish() ->
ok = vmq_plugin_mgr:enable_module_plugin(
auth_on_publish, ?MODULE, hook_auth_on_publish, 6),
ok = vmq_plugin_mgr:enable_module_plugin(
auth_on_publish, ?MODULE, hook_auth_on_publish, 6,
[{compat, {auth_on_publish_m5, vmq_plugin_compat_m5,
convert, 7}}]).
hook_auth_on_subscribe(_, _, Topics) ->
Verdict =
lists:foldl(fun(_, false) ->
false;
({T, _}, true) ->
case ets:lookup(?MODULE, T) of
[] ->
false;
_ ->
true
end
end, true, Topics),
case Verdict of
true -> ok;
false -> next
end.
hook_auth_on_publish(_,_,_,_,_,_) ->
ok.
|
fbf9176bb6bceb28d02e633dfb8b8baf4e2d87d032915415eed912dd018ab00a | dmillett/clash | pivot_test.clj | Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns ^{:author "dmillett"} clash.pivot_test
(:require [clojure.math.combinatorics :as cmb]
[clash.core :as c]
[clash.tools :as t]
[clojure.string :as s])
(:use [clojure.test]
[clash.pivot]))
(defn- divisible-by?
[x]
(fn [n] (zero? (mod n x)) ) )
(defn- foo-divide?
"2 arg nonsensical division function."
[d i]
(fn [n] (zero? (mod n (+ d i)))))
(def foo-numbers '(2 3 4 5 9 11 12 15 20 21 25 26 27))
(deftest test-pivot
(let [r1 (pivot foo-numbers "" :b [number?] :p divisible-by? :v [2 3 4])
r2 (pivot foo-numbers "foo" :b [number?] :p divisible-by? :v [2 3 4])
r3 (pivot foo-numbers "foo" :b [number?] :p divisible-by? :v [2 3 4] :plevel 2)
r4 (pivot foo-numbers "foo2" :b [number?] :p foo-divide? :v [[2 3] [4 5]])
r5 ( perf ( pivot foo - numbers [ number ? ] divide - by - x ? ' ( 2 3 4 ) ) " ( pivot a ) " )
]
(are [x y] (= x y)
3 (:result (get r1 "pivot_[4]"))
6 (:result (get r1 "pivot_[3]"))
5 (:result (get r1 "pivot_[2]"))
;
3 (:result (get r2 "foo_[4]"))
6 (:result (get r2 "foo_[3]"))
5 (:result (get r2 "foo_[2]"))
;
3 (:result (get r3 "foo_[4]"))
6 (:result (get r3 "foo_[3]"))
5 (:result (get r3 "foo_[2]"))
;
4 (:result (get r4 "foo2_[[2 3]]"))
2 (:result (get r4 "foo2_[[4 5]]"))
)
) )
(def foo-numbers-mixed '(2 3 4 5 9 "a" 11 12 15 20 21 "b" 25 26 27))
(def hundred (range 1 100))
; reducers/fold requires [] for multi-threads
(def sc (into [] (range 1 1001)))
Usually takes < = 0.8 seconds for a million data points on 6 core AMD ( 3.4 ghz )
(deftest test-pivot-matrix
(let [even-numbers [number? even?]
divyX2 [divisible-by? divisible-by?]
cp (map #(into [] %) (cmb/cartesian-product (range 2 5) (range 5 8)))
r1 (pivot-matrix hundred "r1" :b [number? even?] :p [divisible-by?] :v [(range 2 5)])
r2 (pivot-matrix hundred "r2" :b even-numbers :p [divisible-by? divisible-by?] :v [(range 2 5) (range 6 8)])
r3p (pivot-matrix hundred "r1" :b even-numbers :p [divisible-by?] :v (list (range 2 5)) :plevel 2)
r4p (pivot-matrix hundred "r2" :b even-numbers :p divyX2 :v [(range 2 5) (range 6 8)] :plevel 2)
r5pp (pivot-matrix hundred "r1" :b even-numbers :p [divisible-by?] :v (list (range 2 5)) :plevel 3)
r6pp (pivot-matrix hundred "r2" :b even-numbers :p divyX2 :v [(range 2 5) (range 6 8)] :plevel 3)
r7 (pivot-matrix hundred "r7" :b even-numbers :p [divisible-by? foo-divide?] :v [(range 2 5) '([2 4] [4 5])])
r8 (pivot-matrix hundred "r8" :b even-numbers :p [divisible-by? foo-divide?] :v [(range 2 4) cp])
;; performance testing
lc ( into [ ] ( range 1 1000001 ) )
r10 ( t / perf ( pivot - matrix lc " r2lc " : b even - numbers :p divyX2 : v [ ( range 2 11 ) ( range 7 18 ) ] : plevel 3 ) " " )
]
(are [x y] (= x y)
3 (count r1)
49 (get-in r1 ["r1_[2]" :count])
16 (get-in r1 ["r1_[3]" :count])
24 (get-in r1 ["r1_[4]" :count])
;
6 (count r2)
16 (get-in r2 ["r2_[3|6]" :count])
7 (get-in r2 ["r2_[2|7]" :count])
2 (get-in r2 ["r2_[3|7]" :count])
;
6 (count r7)
16 (get-in r7 ["r7_[3|[2 4]]" :count])
8 (get-in r7 ["r7_[4|[2 4]]" :count])
2 (get-in r7 ["r7_[4|[4 5]]" :count])
;
3 (count r3p)
49 (get-in r3p ["r1_[2]" :count])
16 (get-in r3p ["r1_[3]" :count])
24 (get-in r3p ["r1_[4]" :count])
;
6 (count r4p)
16 (get-in r4p ["r2_[3|6]" :count])
7 (get-in r4p ["r2_[2|7]" :count])
2 (get-in r4p ["r2_[3|7]" :count])
;
3 (count r5pp)
49 (get-in r5pp ["r1_[2]" :count])
16 (get-in r5pp ["r1_[3]" :count])
24 (get-in r5pp ["r1_[4]" :count])
;
6 (count r6pp)
16 (get-in r6pp ["r2_[3|6]" :count])
7 (get-in r6pp ["r2_[2|7]" :count])
2 (get-in r6pp ["r2_[3|7]" :count])
;
18 (count r8)
12 (get-in r8 ["r8_[2|[3 5]]" :count])
) ) )
(deftest test-pivot-matrix*
(let [data ["foo" "bar" "zoo"]
fx? (fn [c] #(s/includes? % c))
r1 (pivot-matrix* data "r1" :pivots [{:f fx? :v ["a" "b" "c"]} {:f fx? :v ["r" "d"]}])
r2 (pivot-matrix* data "r2" :combfx? t/none? :refine false :pivots [{:f fx? :v ["a" "b" "c"]} {:f fx? :v ["r" "d"]}])
r3 (pivot-matrix* data "r3" :combfx? t/any? :pivots [{:f fx? :v ["a" "b" "c"]} {:f fx? :v ["r" "d"]}])
]
(are [x y] (= x y)
1 (get-in r1 ["r1_[b|r]" :count])
0 (get-in r1 ["r1_[c|r]" :count])
;
3 (get-in r2 ["r2_[c|d]" :count])
2 (get-in r2 ["r2_[c|r]" :count])
2 (get-in r2 ["r2_[b|r]" :count])
;
1 (get-in r3 ["r3_[c|r]" :count])
1 (get-in r3 ["r3_[b|r]" :count])
0 (get-in r3 ["r3_[c|d]" :count])
) ) )
(defn- ratio
"The ratio of (/ a b) for counts of predicate matches."
[a b]
(cond
(and (nil? a) (nil? b)) nil
(nil? a) 0
(nil? b) (/ a 1)
:else (read-string (format "%.3f" (/ a (float b))))
) )
(deftest test-pivot-compare
(let [c1 (range 0 20)
c2 (range 10 30)
expected {"divy1_[3]" true, "divy1_[4]" false, "divy1_[2]" false}]
(are [x y] (= x y)
{} (pivot-compare c1 c2 "empty" >)
expected (pivot-compare c1 c2 "divy1" > :b [number?] :p divisible-by? :v [2 3 4])
expected (pivot-compare c1 c2 "divy1" > :b [number?] :p divisible-by? :v [2 3 4] :plevel 2)
) ) )
(deftest test-pivot-matrix-compare
(let [r1 (pivot-matrix-compare (range 1 50) (range 50 120) "foo" ratio :b [number?]
:p [divisible-by?]
:v [(range 2 6)])]
(are [x y] (= x y)
4 (count r1)
0.706 (get-in r1 ["foo_[4]" :result])
0.696 (get-in r1 ["foo_[3]" :result])
0.686 (get-in r1 ["foo_[2]" :result])
0.643 (get-in r1 ["foo_[5]" :result])
)
) )
(deftest test-pivot-rs
(let [hundred (range 1 100)
m1 (pivot-matrix hundred "foo" :b [even?] :p [divisible-by?] :v [(range 2 6)])
r1 (pivot-rs hundred m1 "foo_[5]")
m2 (pivot-matrix-compare (range 1 50) (range 50 120) "foo" ratio :b [number?]
:p [divisible-by?]
:v [(range 2 6)])
r2 (pivot-rs hundred m2 "foo_[5]")
]
(are [x y] (= x y)
9 (count r1)
r1 [10 20 30 40 50 60 70 80 90]
19 (count r2)
r2 [5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95]
)
) )
(deftest test-filter-pivots
(let [pm1 (pivot-matrix* hundred "find" :pivots [{:f divisible-by? :v (range 2 6)}])]
(are [x y] (= x y)
pm1 (filter-pivots pm1)
24 (get-in (filter-pivots pm1 :cfx even?) ["find_[4]" :count])
24 (get-in (filter-pivots pm1 :kterms ["4"]) ["find_[4]" :count])
33 (get-in (filter-pivots pm1 :kterms ["3"] :cfx odd?) ["find_[3]" :count])
) ) )
(deftest test-haystack
(let [d1 [{:a {:c "c"} :b {:d "d"}}, {:a {:c "c1"} :b {:d "d"}}, {:a {:c "c"} :b {:d "d1"}}, {:a {:c "c1"} :b {:d "d"}}]
d2 [{:a {:b 1 :c 2 :d 3}}, {:a {:b 1 :c 3 :d 3}}, {:a {:b 2 :c 3 :d 3}}]
d3 [{:a {:b 1 :c 2}} {:a {:b 1 :c 3}} {:a {:b 2 :c 3}}]
d4 [{:a {:b "b1" :c "c1"} :d "d" :e "e1"}, {:a {:b "b2" :c "c1"} :d "d" :e "e2"}]
;
vffx1 #(t/filter-value-frequencies % (fn [[_ v]] (even? v)))
vffx2 #(t/filter-value-frequencies % (fn [[k _]] (even? k)))
top1 (partial t/reduce-vfreqs #(take 1 (t/sort-map-by-value %)))
dmod? (fn [n] #(try (zero? (mod (get-in % [:a :d]) n)) (catch NullPointerException _ false)))
;
h1 (haystack d1 :vfkpsets [{:kp [:a]}] :vffx #(t/sort-value-frequencies %))
h1p (haystack d1 :vfkpsets [{:kp [:a]}] :vffx #(t/sort-value-frequencies %) :plevel 2)
h2 (haystack d2 :vfkpsets [{:kp [:a]}])
h3 (haystack d2 :vfkpsets [{:kp [:a] :ks [:b :c]}])
h4 (haystack d2 :vfkpsets [{:kp [:a] :ks [:b :c]}] :vffx vffx1)
h4p (haystack d2 :vfkpsets [{:kp [:a] :ks [:b :c]}] :vffx vffx1 :plevel 2)
h5 (haystack d2 :vfkpsets [{:kp [:a] :ks [:b :c]}] :vffx vffx2)
h6 (haystack d2 :vfkpsets [{:kp [:a]}] :vffx top1)
;
h7 (haystack d2 :pvmsg "d2_[dmod]" :vfkpsets [{:kp [:a]}] :pivots [{:f dmod? :v [3]}])
h8 (haystack d3 :pvmsg "d3_[dmod]" :vfkpsets [{:kp [:a] :ks [:b :c]}] :pivots [{:f dmod? :v [3]}])
h8p (haystack d3 :pvmsg "d3_[dmod]" :vfkpsets [{:kp [:a] :ks [:b :c]}] :pivots [{:f dmod? :v [3]}] :plevel 2)
h9 (haystack d4 :vfkpsets [{:kp [:a] :ks [:c]}, {:ks [:d]}])
h10 (haystack d4 :vfkpsets [{:ks [:d]}])
h11 (haystack d4 :vfkpsets [{:ks [:d :e]}])
h12 (haystack d4 :vfkpsets [{:kp [:a] :ks [:c]} {:ks [:d :e]}])
]
(are [x y] (= x y)
2 (count h1)
2 (:count (get h1 "haystack([:a :c])_[c]"))
2 (:count (get h1 "haystack([:a :c])_[c1]"))
(map #(:count %) (vals h1)) (map #(:count %) (vals h1p))
;
4 (count h2)
1 (:count (get h2 "haystack([:a :b]|[:a :c]|[:a :d])_[2|3|3]"))
1 (:count (get h2 "haystack([:a :b]|[:a :c]|[:a :d])_[1|3|3]"))
1 (:count (get h2 "haystack([:a :b]|[:a :c]|[:a :d])_[1|2|3]"))
0 (:count (get h2 "haystack([:a :b]|[:a :c]|[:a :d])_[2|2|3]"))
;
4 (count h3)
1 (:count (get h3 "haystack([:a :b]|[:a :c])_[2|3]"))
1 (:count (get h3 "haystack([:a :b]|[:a :c])_[1|3]"))
1 (:count (get h3 "haystack([:a :b]|[:a :c])_[1|2]"))
0 (:count (get h3 "haystack([:a :b]|[:a :c])_[2|2]"))
;
value frequencies : ' { : b { 1 2 , 2 1 } , : c { 2 1 , 3 2 } } '
1 (count h4)
1 (:count (get h4 "haystack([:a :b]|[:a :c])_[1|3]"))
(map #(:count %) (vals h4)) (map #(:count %) (vals h4p))
;
1 (count h5)
0 (:count (get h5 "haystack([:a :b]|[:a :c])_[2|2]"))
1 (count h6)
1 (:count (get h6 "haystack([:a :b]|[:a :c]|[:a :d])_[1|3|3]"))
4 (count h7)
1 (:count (get h7 "d2_[dmod]([:a :b]|[:a :c]|[:a :d])_[[3]|2|3|3]"))
'(1 1 1 0) (map #(:count %) (vals h7))
;
4 (count h8)
'(0 0 0 0) (map #(:count %) (vals h8))
(map #(:count %) (vals h8)) (map #(:count %) (vals h8p))
;
1 (count h9)
2 (:count (get h9 "haystack([:a :c]|[:d])_[c1|d]"))
1 (count h10)
2 (:count (get h10 "haystack([:d])_[d]"))
2 (count h11)
1 (:count (get h11 "haystack([:d]|[:e])_[d|e2]"))
2 (count h12)
1 (:count (get h12 "haystack([:a :c]|[:d]|[:e])_[c1|d|e1]"))
))) | null | https://raw.githubusercontent.com/dmillett/clash/ea36a916ccfd9e1c61cb88ac6147b6a952f33dcf/test/clash/pivot_test.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
reducers/fold requires [] for multi-threads
performance testing
| Copyright ( c ) . All rights reserved .
(ns ^{:author "dmillett"} clash.pivot_test
(:require [clojure.math.combinatorics :as cmb]
[clash.core :as c]
[clash.tools :as t]
[clojure.string :as s])
(:use [clojure.test]
[clash.pivot]))
(defn- divisible-by?
[x]
(fn [n] (zero? (mod n x)) ) )
(defn- foo-divide?
"2 arg nonsensical division function."
[d i]
(fn [n] (zero? (mod n (+ d i)))))
(def foo-numbers '(2 3 4 5 9 11 12 15 20 21 25 26 27))
(deftest test-pivot
(let [r1 (pivot foo-numbers "" :b [number?] :p divisible-by? :v [2 3 4])
r2 (pivot foo-numbers "foo" :b [number?] :p divisible-by? :v [2 3 4])
r3 (pivot foo-numbers "foo" :b [number?] :p divisible-by? :v [2 3 4] :plevel 2)
r4 (pivot foo-numbers "foo2" :b [number?] :p foo-divide? :v [[2 3] [4 5]])
r5 ( perf ( pivot foo - numbers [ number ? ] divide - by - x ? ' ( 2 3 4 ) ) " ( pivot a ) " )
]
(are [x y] (= x y)
3 (:result (get r1 "pivot_[4]"))
6 (:result (get r1 "pivot_[3]"))
5 (:result (get r1 "pivot_[2]"))
3 (:result (get r2 "foo_[4]"))
6 (:result (get r2 "foo_[3]"))
5 (:result (get r2 "foo_[2]"))
3 (:result (get r3 "foo_[4]"))
6 (:result (get r3 "foo_[3]"))
5 (:result (get r3 "foo_[2]"))
4 (:result (get r4 "foo2_[[2 3]]"))
2 (:result (get r4 "foo2_[[4 5]]"))
)
) )
(def foo-numbers-mixed '(2 3 4 5 9 "a" 11 12 15 20 21 "b" 25 26 27))
(def hundred (range 1 100))
(def sc (into [] (range 1 1001)))
Usually takes < = 0.8 seconds for a million data points on 6 core AMD ( 3.4 ghz )
(deftest test-pivot-matrix
(let [even-numbers [number? even?]
divyX2 [divisible-by? divisible-by?]
cp (map #(into [] %) (cmb/cartesian-product (range 2 5) (range 5 8)))
r1 (pivot-matrix hundred "r1" :b [number? even?] :p [divisible-by?] :v [(range 2 5)])
r2 (pivot-matrix hundred "r2" :b even-numbers :p [divisible-by? divisible-by?] :v [(range 2 5) (range 6 8)])
r3p (pivot-matrix hundred "r1" :b even-numbers :p [divisible-by?] :v (list (range 2 5)) :plevel 2)
r4p (pivot-matrix hundred "r2" :b even-numbers :p divyX2 :v [(range 2 5) (range 6 8)] :plevel 2)
r5pp (pivot-matrix hundred "r1" :b even-numbers :p [divisible-by?] :v (list (range 2 5)) :plevel 3)
r6pp (pivot-matrix hundred "r2" :b even-numbers :p divyX2 :v [(range 2 5) (range 6 8)] :plevel 3)
r7 (pivot-matrix hundred "r7" :b even-numbers :p [divisible-by? foo-divide?] :v [(range 2 5) '([2 4] [4 5])])
r8 (pivot-matrix hundred "r8" :b even-numbers :p [divisible-by? foo-divide?] :v [(range 2 4) cp])
lc ( into [ ] ( range 1 1000001 ) )
r10 ( t / perf ( pivot - matrix lc " r2lc " : b even - numbers :p divyX2 : v [ ( range 2 11 ) ( range 7 18 ) ] : plevel 3 ) " " )
]
(are [x y] (= x y)
3 (count r1)
49 (get-in r1 ["r1_[2]" :count])
16 (get-in r1 ["r1_[3]" :count])
24 (get-in r1 ["r1_[4]" :count])
6 (count r2)
16 (get-in r2 ["r2_[3|6]" :count])
7 (get-in r2 ["r2_[2|7]" :count])
2 (get-in r2 ["r2_[3|7]" :count])
6 (count r7)
16 (get-in r7 ["r7_[3|[2 4]]" :count])
8 (get-in r7 ["r7_[4|[2 4]]" :count])
2 (get-in r7 ["r7_[4|[4 5]]" :count])
3 (count r3p)
49 (get-in r3p ["r1_[2]" :count])
16 (get-in r3p ["r1_[3]" :count])
24 (get-in r3p ["r1_[4]" :count])
6 (count r4p)
16 (get-in r4p ["r2_[3|6]" :count])
7 (get-in r4p ["r2_[2|7]" :count])
2 (get-in r4p ["r2_[3|7]" :count])
3 (count r5pp)
49 (get-in r5pp ["r1_[2]" :count])
16 (get-in r5pp ["r1_[3]" :count])
24 (get-in r5pp ["r1_[4]" :count])
6 (count r6pp)
16 (get-in r6pp ["r2_[3|6]" :count])
7 (get-in r6pp ["r2_[2|7]" :count])
2 (get-in r6pp ["r2_[3|7]" :count])
18 (count r8)
12 (get-in r8 ["r8_[2|[3 5]]" :count])
) ) )
(deftest test-pivot-matrix*
(let [data ["foo" "bar" "zoo"]
fx? (fn [c] #(s/includes? % c))
r1 (pivot-matrix* data "r1" :pivots [{:f fx? :v ["a" "b" "c"]} {:f fx? :v ["r" "d"]}])
r2 (pivot-matrix* data "r2" :combfx? t/none? :refine false :pivots [{:f fx? :v ["a" "b" "c"]} {:f fx? :v ["r" "d"]}])
r3 (pivot-matrix* data "r3" :combfx? t/any? :pivots [{:f fx? :v ["a" "b" "c"]} {:f fx? :v ["r" "d"]}])
]
(are [x y] (= x y)
1 (get-in r1 ["r1_[b|r]" :count])
0 (get-in r1 ["r1_[c|r]" :count])
3 (get-in r2 ["r2_[c|d]" :count])
2 (get-in r2 ["r2_[c|r]" :count])
2 (get-in r2 ["r2_[b|r]" :count])
1 (get-in r3 ["r3_[c|r]" :count])
1 (get-in r3 ["r3_[b|r]" :count])
0 (get-in r3 ["r3_[c|d]" :count])
) ) )
(defn- ratio
"The ratio of (/ a b) for counts of predicate matches."
[a b]
(cond
(and (nil? a) (nil? b)) nil
(nil? a) 0
(nil? b) (/ a 1)
:else (read-string (format "%.3f" (/ a (float b))))
) )
(deftest test-pivot-compare
(let [c1 (range 0 20)
c2 (range 10 30)
expected {"divy1_[3]" true, "divy1_[4]" false, "divy1_[2]" false}]
(are [x y] (= x y)
{} (pivot-compare c1 c2 "empty" >)
expected (pivot-compare c1 c2 "divy1" > :b [number?] :p divisible-by? :v [2 3 4])
expected (pivot-compare c1 c2 "divy1" > :b [number?] :p divisible-by? :v [2 3 4] :plevel 2)
) ) )
(deftest test-pivot-matrix-compare
(let [r1 (pivot-matrix-compare (range 1 50) (range 50 120) "foo" ratio :b [number?]
:p [divisible-by?]
:v [(range 2 6)])]
(are [x y] (= x y)
4 (count r1)
0.706 (get-in r1 ["foo_[4]" :result])
0.696 (get-in r1 ["foo_[3]" :result])
0.686 (get-in r1 ["foo_[2]" :result])
0.643 (get-in r1 ["foo_[5]" :result])
)
) )
(deftest test-pivot-rs
(let [hundred (range 1 100)
m1 (pivot-matrix hundred "foo" :b [even?] :p [divisible-by?] :v [(range 2 6)])
r1 (pivot-rs hundred m1 "foo_[5]")
m2 (pivot-matrix-compare (range 1 50) (range 50 120) "foo" ratio :b [number?]
:p [divisible-by?]
:v [(range 2 6)])
r2 (pivot-rs hundred m2 "foo_[5]")
]
(are [x y] (= x y)
9 (count r1)
r1 [10 20 30 40 50 60 70 80 90]
19 (count r2)
r2 [5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95]
)
) )
(deftest test-filter-pivots
(let [pm1 (pivot-matrix* hundred "find" :pivots [{:f divisible-by? :v (range 2 6)}])]
(are [x y] (= x y)
pm1 (filter-pivots pm1)
24 (get-in (filter-pivots pm1 :cfx even?) ["find_[4]" :count])
24 (get-in (filter-pivots pm1 :kterms ["4"]) ["find_[4]" :count])
33 (get-in (filter-pivots pm1 :kterms ["3"] :cfx odd?) ["find_[3]" :count])
) ) )
(deftest test-haystack
(let [d1 [{:a {:c "c"} :b {:d "d"}}, {:a {:c "c1"} :b {:d "d"}}, {:a {:c "c"} :b {:d "d1"}}, {:a {:c "c1"} :b {:d "d"}}]
d2 [{:a {:b 1 :c 2 :d 3}}, {:a {:b 1 :c 3 :d 3}}, {:a {:b 2 :c 3 :d 3}}]
d3 [{:a {:b 1 :c 2}} {:a {:b 1 :c 3}} {:a {:b 2 :c 3}}]
d4 [{:a {:b "b1" :c "c1"} :d "d" :e "e1"}, {:a {:b "b2" :c "c1"} :d "d" :e "e2"}]
vffx1 #(t/filter-value-frequencies % (fn [[_ v]] (even? v)))
vffx2 #(t/filter-value-frequencies % (fn [[k _]] (even? k)))
top1 (partial t/reduce-vfreqs #(take 1 (t/sort-map-by-value %)))
dmod? (fn [n] #(try (zero? (mod (get-in % [:a :d]) n)) (catch NullPointerException _ false)))
h1 (haystack d1 :vfkpsets [{:kp [:a]}] :vffx #(t/sort-value-frequencies %))
h1p (haystack d1 :vfkpsets [{:kp [:a]}] :vffx #(t/sort-value-frequencies %) :plevel 2)
h2 (haystack d2 :vfkpsets [{:kp [:a]}])
h3 (haystack d2 :vfkpsets [{:kp [:a] :ks [:b :c]}])
h4 (haystack d2 :vfkpsets [{:kp [:a] :ks [:b :c]}] :vffx vffx1)
h4p (haystack d2 :vfkpsets [{:kp [:a] :ks [:b :c]}] :vffx vffx1 :plevel 2)
h5 (haystack d2 :vfkpsets [{:kp [:a] :ks [:b :c]}] :vffx vffx2)
h6 (haystack d2 :vfkpsets [{:kp [:a]}] :vffx top1)
h7 (haystack d2 :pvmsg "d2_[dmod]" :vfkpsets [{:kp [:a]}] :pivots [{:f dmod? :v [3]}])
h8 (haystack d3 :pvmsg "d3_[dmod]" :vfkpsets [{:kp [:a] :ks [:b :c]}] :pivots [{:f dmod? :v [3]}])
h8p (haystack d3 :pvmsg "d3_[dmod]" :vfkpsets [{:kp [:a] :ks [:b :c]}] :pivots [{:f dmod? :v [3]}] :plevel 2)
h9 (haystack d4 :vfkpsets [{:kp [:a] :ks [:c]}, {:ks [:d]}])
h10 (haystack d4 :vfkpsets [{:ks [:d]}])
h11 (haystack d4 :vfkpsets [{:ks [:d :e]}])
h12 (haystack d4 :vfkpsets [{:kp [:a] :ks [:c]} {:ks [:d :e]}])
]
(are [x y] (= x y)
2 (count h1)
2 (:count (get h1 "haystack([:a :c])_[c]"))
2 (:count (get h1 "haystack([:a :c])_[c1]"))
(map #(:count %) (vals h1)) (map #(:count %) (vals h1p))
4 (count h2)
1 (:count (get h2 "haystack([:a :b]|[:a :c]|[:a :d])_[2|3|3]"))
1 (:count (get h2 "haystack([:a :b]|[:a :c]|[:a :d])_[1|3|3]"))
1 (:count (get h2 "haystack([:a :b]|[:a :c]|[:a :d])_[1|2|3]"))
0 (:count (get h2 "haystack([:a :b]|[:a :c]|[:a :d])_[2|2|3]"))
4 (count h3)
1 (:count (get h3 "haystack([:a :b]|[:a :c])_[2|3]"))
1 (:count (get h3 "haystack([:a :b]|[:a :c])_[1|3]"))
1 (:count (get h3 "haystack([:a :b]|[:a :c])_[1|2]"))
0 (:count (get h3 "haystack([:a :b]|[:a :c])_[2|2]"))
value frequencies : ' { : b { 1 2 , 2 1 } , : c { 2 1 , 3 2 } } '
1 (count h4)
1 (:count (get h4 "haystack([:a :b]|[:a :c])_[1|3]"))
(map #(:count %) (vals h4)) (map #(:count %) (vals h4p))
1 (count h5)
0 (:count (get h5 "haystack([:a :b]|[:a :c])_[2|2]"))
1 (count h6)
1 (:count (get h6 "haystack([:a :b]|[:a :c]|[:a :d])_[1|3|3]"))
4 (count h7)
1 (:count (get h7 "d2_[dmod]([:a :b]|[:a :c]|[:a :d])_[[3]|2|3|3]"))
'(1 1 1 0) (map #(:count %) (vals h7))
4 (count h8)
'(0 0 0 0) (map #(:count %) (vals h8))
(map #(:count %) (vals h8)) (map #(:count %) (vals h8p))
1 (count h9)
2 (:count (get h9 "haystack([:a :c]|[:d])_[c1|d]"))
1 (count h10)
2 (:count (get h10 "haystack([:d])_[d]"))
2 (count h11)
1 (:count (get h11 "haystack([:d]|[:e])_[d|e2]"))
2 (count h12)
1 (:count (get h12 "haystack([:a :c]|[:d]|[:e])_[c1|d|e1]"))
))) |
b3e9762de0ed87dbf482199e770107d8044f0b203c90e3f1dba03990ddff854c | MariaGrozdeva/Functional_programming | level.rkt | #lang racket/base
(define (level tree i)
(if (not (null? tree))
(if (= i 1)
(list (car tree))
(append (level (cadr tree) (- i 1)) (level (caddr tree) (- i 1))) )
'()
)
) | null | https://raw.githubusercontent.com/MariaGrozdeva/Functional_programming/002e3dbbbc64558094eecd147cb1fd064ee84a03/Tasks%20on%20binary%20trees/level.rkt | racket | #lang racket/base
(define (level tree i)
(if (not (null? tree))
(if (= i 1)
(list (car tree))
(append (level (cadr tree) (- i 1)) (level (caddr tree) (- i 1))) )
'()
)
) | |
790b683c7f996be71f4c64305404b5964d72300a91d977595d44f0a7ce049f46 | foreverbell/project-euler-solutions | 59.hs | import qualified Data.Text as T
import Data.List (group, sort, maximumBy)
import Data.Function (on)
import Data.Bits (xor)
import Data.Char (ord, chr, isAlpha)
group3 a b c _ [] = (reverse a, reverse b, reverse c)
group3 a b c n (x:xs) = case (n `mod` 3) of
0 -> group3 (x:a) b c (n + 1) xs
1 -> group3 a (x:b) c (n + 1) xs
2 -> group3 a b (x:c) (n + 1) xs
comb3 [] [] [] = []
comb3 [a] [] [] = [a]
comb3 [a] [b] [] = [a, b]
comb3 (a:as) (b:bs) (c:cs) = a:b:c:(comb3 as bs cs)
findKey :: [Int] -> Int
findKey xs = maximumBy (compare `on` score) [(ord 'a') .. (ord 'z')] where
score key = length $ filter (isAlpha . chr) $ map (xor key) xs
solve :: String -> Int
solve input = sum result where
t = T.pack input
ts = T.split (== ',') t
xs = map (read . (T.unpack)) ts :: [Int]
(a,b,c) = group3 [] [] [] 0 xs
decrypte xs = map (xor (findKey xs)) xs
result = comb3 (decrypte a) (decrypte b) (decrypte c)
main = readFile "input/p059_cipher.txt" >>= (print . solve)
| null | https://raw.githubusercontent.com/foreverbell/project-euler-solutions/c0bf2746aafce9be510892814e2d03e20738bf2b/src/59.hs | haskell | import qualified Data.Text as T
import Data.List (group, sort, maximumBy)
import Data.Function (on)
import Data.Bits (xor)
import Data.Char (ord, chr, isAlpha)
group3 a b c _ [] = (reverse a, reverse b, reverse c)
group3 a b c n (x:xs) = case (n `mod` 3) of
0 -> group3 (x:a) b c (n + 1) xs
1 -> group3 a (x:b) c (n + 1) xs
2 -> group3 a b (x:c) (n + 1) xs
comb3 [] [] [] = []
comb3 [a] [] [] = [a]
comb3 [a] [b] [] = [a, b]
comb3 (a:as) (b:bs) (c:cs) = a:b:c:(comb3 as bs cs)
findKey :: [Int] -> Int
findKey xs = maximumBy (compare `on` score) [(ord 'a') .. (ord 'z')] where
score key = length $ filter (isAlpha . chr) $ map (xor key) xs
solve :: String -> Int
solve input = sum result where
t = T.pack input
ts = T.split (== ',') t
xs = map (read . (T.unpack)) ts :: [Int]
(a,b,c) = group3 [] [] [] 0 xs
decrypte xs = map (xor (findKey xs)) xs
result = comb3 (decrypte a) (decrypte b) (decrypte c)
main = readFile "input/p059_cipher.txt" >>= (print . solve)
| |
1d3abc5e5dd9e9865d2b06ff5be9cd232fc9089a2b1dc9d01add5a7f0201a001 | donaldsonjw/bigloo | control.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / runtime / Ieee / control.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Fri Jan 20 17:48:44 1995 * /
* Last change : Tue Jan 29 17:12:19 2013 ( serrano ) * /
;* ------------------------------------------------------------- */
* 6.9 . Control features ( page 27 , r4 ) * /
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* Le module */
;*---------------------------------------------------------------------*/
(module __r4_control_features_6_9
(import __error
__param)
(use __type
__bigloo
__tvector
__bexit
__bignum
__r4_equivalence_6_2
__r4_vectors_6_8
__r4_strings_6_7
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_booleans_6_1
__r4_symbols_6_4
__r4_pairs_and_lists_6_3
__r5_control_features_6_4
__evenv
__evaluate)
(extern (macro c-procedure?::bool (::obj) "PROCEDUREP")
(call-cc::obj (::procedure) "call_cc")
(macro push-before!::obj (::procedure) "PUSH_BEFORE")
(macro pop-before!::obj () "POP_BEFORE"))
(java (class foreign
(method static c-procedure?::bool (::obj) "PROCEDUREP")
;(method static call-cc::obj (::procedure) "call_cc")
(method static push-before!::obj (::procedure) "PUSH_BEFORE")
(method static pop-before!::obj () "POP_BEFORE")))
(export (inline procedure?::bool ::obj)
(apply ::procedure obj1 . args)
(map::pair-nil ::procedure . pair)
(map!::pair-nil ::procedure . pair)
(map-2::pair-nil ::procedure ::pair-nil)
(append-map::pair-nil ::procedure . pair)
(append-map!::pair-nil ::procedure . pair)
(filter-map::pair-nil ::procedure . pair)
(for-each ::procedure . pair)
(for-each-2 ::procedure ::pair-nil)
(filter::pair-nil ::procedure ::pair-nil)
(filter!::pair-nil ::procedure ::pair-nil)
(inline force promise)
(make-promise ::procedure)
(call/cc ::procedure)
(inline call-with-current-continuation ::procedure)
(dynamic-wind ::procedure ::procedure ::procedure))
(pragma (c-procedure? (predicate-of procedure) no-cfa-top nesting)
(procedure? side-effect-free no-cfa-top nesting)))
;*---------------------------------------------------------------------*/
;* procedure? ... */
;*---------------------------------------------------------------------*/
(define-inline (procedure? obj)
(c-procedure? obj))
;*---------------------------------------------------------------------*/
;* apply ... */
;*---------------------------------------------------------------------*/
(define (apply proc args . opt)
(let ((args (if (pair? opt)
(cons args (let loop ((opt opt))
(if (pair? (cdr opt))
(cons (car opt) (loop (cdr opt)))
(car opt))))
args)))
(apply proc args)))
;*---------------------------------------------------------------------*/
;* map-2 ... */
;*---------------------------------------------------------------------*/
(define (map-2 f l)
(let loop ((l l)
(res '()))
(if (null? l)
(reverse! res)
(loop (cdr l) (cons (f (car l)) res)))))
;*---------------------------------------------------------------------*/
;* map ... */
;*---------------------------------------------------------------------*/
(define (map f . l)
(cond
((null? l)
'())
((null? (cdr l))
(map-2 f (car l)))
(else
(let loop ((l l))
(if (null? (car l))
'()
(cons (apply f (map-2 car l))
(loop (map-2 cdr l))))))))
;*---------------------------------------------------------------------*/
;* map-2! ... */
;*---------------------------------------------------------------------*/
(define (map-2! f l0)
(let loop ((l l0))
(if (null? l)
l0
(begin
(set-car! l (f (car l)))
(loop (cdr l))))))
;*---------------------------------------------------------------------*/
;* map! ... */
;*---------------------------------------------------------------------*/
(define (map! f . l)
(cond
((null? l)
'())
((null? (cdr l))
(map-2! f (car l)))
(else
(let ((l0 (car l)))
(let loop ((l l))
(if (null? (car l))
l0
(begin
(set-car! (car l) (apply f (map-2 car l)))
(loop (map-2 cdr l)))))))))
;*---------------------------------------------------------------------*/
;* append-map2 ... */
;*---------------------------------------------------------------------*/
(define (append-map2 f l)
(let loop ((l l))
(if (null? l)
'()
(append (f (car l)) (loop (cdr l))))))
;*---------------------------------------------------------------------*/
;* append-map ... */
;*---------------------------------------------------------------------*/
(define (append-map f . l)
(cond
((null? l)
'())
((null? (cdr l))
(append-map2 f (car l)))
(else
(let loop ((l l))
(if (null? (car l))
'()
(append (apply f (map-2 car l)) (loop (map-2 cdr l))))))))
;*---------------------------------------------------------------------*/
;* append-map2! ... */
;*---------------------------------------------------------------------*/
(define (append-map2! f l)
(let loop ((l l))
(if (null? l)
'()
(append! (f (car l)) (loop (cdr l))))))
;*---------------------------------------------------------------------*/
;* append-map! ... */
;*---------------------------------------------------------------------*/
(define (append-map! f . l)
(cond
((null? l)
'())
((null? (cdr l))
(append-map2! f (car l)))
(else
(let loop ((l l))
(if (null? (car l))
'()
(append! (apply f (map-2 car l)) (loop (map-2 cdr l))))))))
;*---------------------------------------------------------------------*/
;* filter-map-2 ... */
;*---------------------------------------------------------------------*/
(define (filter-map-2 f l)
(let loop ((l l)
(res '()))
(if (null? l)
(reverse! res)
(let ((hd (f (car l))))
(if hd
(loop (cdr l) (cons hd res))
(loop (cdr l) res))))))
;*---------------------------------------------------------------------*/
;* filter-map ... */
;*---------------------------------------------------------------------*/
(define (filter-map f . l)
(cond
((null? l)
'())
((null? (cdr l))
(filter-map-2 f (car l)))
(else
(let loop ((l l))
(if (null? (car l))
'()
(let ((hd (apply f (map-2 car l))))
(if hd
(cons hd (loop (map-2 cdr l)))
(loop (map-2 cdr l)))))))))
;*---------------------------------------------------------------------*/
;* for-each-2 ... */
;*---------------------------------------------------------------------*/
(define (for-each-2 f l)
(let loop ((l l))
(if (null? l)
#unspecified
(begin
(f (car l))
(loop (cdr l))))))
;*---------------------------------------------------------------------*/
;* for-each ... */
;*---------------------------------------------------------------------*/
(define (for-each f . l)
(cond
((null? l)
#unspecified)
((null? (cdr l))
(for-each-2 f (car l)))
(else
(let loop ((l l))
(if (null? (car l))
#unspecified
(begin
(apply f (map-2 car l))
(loop (map-2 cdr l))))))))
;*---------------------------------------------------------------------*/
;* filter ... */
;*---------------------------------------------------------------------*/
(define (filter pred lis)
(let recur ((lis lis))
(if (null? lis)
lis
(let ((head (car lis))
(tail (cdr lis)))
(if (pred head)
(let ((new-tail (recur tail)))
(if (eq? tail new-tail)
lis
(cons head new-tail)))
(recur tail))))))
;*---------------------------------------------------------------------*/
;* filter! ... */
;*---------------------------------------------------------------------*/
(define (filter! pred lis)
(let lp ((ans lis))
(cond
((null? ans)
ans)
((not (pred (car ans)))
(lp (cdr ans)))
(else
(letrec ((scan-in (lambda (prev lis)
(if (pair? lis)
(if (pred (car lis))
(scan-in lis (cdr lis))
(scan-out prev (cdr lis))))))
(scan-out (lambda (prev lis)
(let lp ((lis lis))
(if (pair? lis)
(if (pred (car lis))
(begin
(set-cdr! prev lis)
(scan-in lis (cdr lis)))
(lp (cdr lis)))
(set-cdr! prev lis))))))
(scan-in ans (cdr ans))
ans)))))
;*---------------------------------------------------------------------*/
;* force ... */
;*---------------------------------------------------------------------*/
(define-inline (force promise)
(promise))
;*---------------------------------------------------------------------*/
;* make-promise ... */
;*---------------------------------------------------------------------*/
(define (make-promise proc)
(let ((result-ready? #f)
(result #f))
(lambda ()
(if result-ready?
result
(let ((x (proc)))
(if result-ready?
result
(begin
(set! result-ready? #t)
(set! result x)
result)))))))
;*---------------------------------------------------------------------*/
;* call/cc ... */
;*---------------------------------------------------------------------*/
(define (call/cc proc)
(call-cc (lambda (cont)
(let ((evc (get-evaluation-context)))
(proc (lambda vals
(set-evaluation-context! evc)
(if (and (pair? vals) (null? (cdr vals)))
(cont (car vals))
(begin
(%set-mvalues-number! -1)
(cont vals)))))))))
(cond-expand
(bigloo-jvm
(define (call-cc proc) (bind-exit (exit) (proc exit)))))
;*---------------------------------------------------------------------*/
;* call-with-current-continuation ... */
;*---------------------------------------------------------------------*/
(define-inline (call-with-current-continuation proc)
(call/cc proc))
;*---------------------------------------------------------------------*/
;* dynamic-wind ... */
;*---------------------------------------------------------------------*/
(define (dynamic-wind before::procedure thunk::procedure after::procedure)
(before)
(let ()
(push-before! before)
(unwind-protect
(thunk)
(begin
(after)
(pop-before!)))))
| null | https://raw.githubusercontent.com/donaldsonjw/bigloo/a4d06e409d0004e159ce92b9908719510a18aed5/runtime/Ieee/control.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
*=====================================================================*/
*---------------------------------------------------------------------*/
* Le module */
*---------------------------------------------------------------------*/
(method static call-cc::obj (::procedure) "call_cc")
*---------------------------------------------------------------------*/
* procedure? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* apply ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* map-2 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* map ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* map-2! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* map! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* append-map2 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* append-map ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* append-map2! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* append-map! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* filter-map-2 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* filter-map ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* for-each-2 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* for-each ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* filter ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* filter! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* make-promise ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* call/cc ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* call-with-current-continuation ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* dynamic-wind ... */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / bigloo / runtime / Ieee / control.scm * /
* Author : * /
* Creation : Fri Jan 20 17:48:44 1995 * /
* Last change : Tue Jan 29 17:12:19 2013 ( serrano ) * /
* 6.9 . Control features ( page 27 , r4 ) * /
(module __r4_control_features_6_9
(import __error
__param)
(use __type
__bigloo
__tvector
__bexit
__bignum
__r4_equivalence_6_2
__r4_vectors_6_8
__r4_strings_6_7
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_booleans_6_1
__r4_symbols_6_4
__r4_pairs_and_lists_6_3
__r5_control_features_6_4
__evenv
__evaluate)
(extern (macro c-procedure?::bool (::obj) "PROCEDUREP")
(call-cc::obj (::procedure) "call_cc")
(macro push-before!::obj (::procedure) "PUSH_BEFORE")
(macro pop-before!::obj () "POP_BEFORE"))
(java (class foreign
(method static c-procedure?::bool (::obj) "PROCEDUREP")
(method static push-before!::obj (::procedure) "PUSH_BEFORE")
(method static pop-before!::obj () "POP_BEFORE")))
(export (inline procedure?::bool ::obj)
(apply ::procedure obj1 . args)
(map::pair-nil ::procedure . pair)
(map!::pair-nil ::procedure . pair)
(map-2::pair-nil ::procedure ::pair-nil)
(append-map::pair-nil ::procedure . pair)
(append-map!::pair-nil ::procedure . pair)
(filter-map::pair-nil ::procedure . pair)
(for-each ::procedure . pair)
(for-each-2 ::procedure ::pair-nil)
(filter::pair-nil ::procedure ::pair-nil)
(filter!::pair-nil ::procedure ::pair-nil)
(inline force promise)
(make-promise ::procedure)
(call/cc ::procedure)
(inline call-with-current-continuation ::procedure)
(dynamic-wind ::procedure ::procedure ::procedure))
(pragma (c-procedure? (predicate-of procedure) no-cfa-top nesting)
(procedure? side-effect-free no-cfa-top nesting)))
(define-inline (procedure? obj)
(c-procedure? obj))
(define (apply proc args . opt)
(let ((args (if (pair? opt)
(cons args (let loop ((opt opt))
(if (pair? (cdr opt))
(cons (car opt) (loop (cdr opt)))
(car opt))))
args)))
(apply proc args)))
(define (map-2 f l)
(let loop ((l l)
(res '()))
(if (null? l)
(reverse! res)
(loop (cdr l) (cons (f (car l)) res)))))
(define (map f . l)
(cond
((null? l)
'())
((null? (cdr l))
(map-2 f (car l)))
(else
(let loop ((l l))
(if (null? (car l))
'()
(cons (apply f (map-2 car l))
(loop (map-2 cdr l))))))))
(define (map-2! f l0)
(let loop ((l l0))
(if (null? l)
l0
(begin
(set-car! l (f (car l)))
(loop (cdr l))))))
(define (map! f . l)
(cond
((null? l)
'())
((null? (cdr l))
(map-2! f (car l)))
(else
(let ((l0 (car l)))
(let loop ((l l))
(if (null? (car l))
l0
(begin
(set-car! (car l) (apply f (map-2 car l)))
(loop (map-2 cdr l)))))))))
(define (append-map2 f l)
(let loop ((l l))
(if (null? l)
'()
(append (f (car l)) (loop (cdr l))))))
(define (append-map f . l)
(cond
((null? l)
'())
((null? (cdr l))
(append-map2 f (car l)))
(else
(let loop ((l l))
(if (null? (car l))
'()
(append (apply f (map-2 car l)) (loop (map-2 cdr l))))))))
(define (append-map2! f l)
(let loop ((l l))
(if (null? l)
'()
(append! (f (car l)) (loop (cdr l))))))
(define (append-map! f . l)
(cond
((null? l)
'())
((null? (cdr l))
(append-map2! f (car l)))
(else
(let loop ((l l))
(if (null? (car l))
'()
(append! (apply f (map-2 car l)) (loop (map-2 cdr l))))))))
(define (filter-map-2 f l)
(let loop ((l l)
(res '()))
(if (null? l)
(reverse! res)
(let ((hd (f (car l))))
(if hd
(loop (cdr l) (cons hd res))
(loop (cdr l) res))))))
(define (filter-map f . l)
(cond
((null? l)
'())
((null? (cdr l))
(filter-map-2 f (car l)))
(else
(let loop ((l l))
(if (null? (car l))
'()
(let ((hd (apply f (map-2 car l))))
(if hd
(cons hd (loop (map-2 cdr l)))
(loop (map-2 cdr l)))))))))
(define (for-each-2 f l)
(let loop ((l l))
(if (null? l)
#unspecified
(begin
(f (car l))
(loop (cdr l))))))
(define (for-each f . l)
(cond
((null? l)
#unspecified)
((null? (cdr l))
(for-each-2 f (car l)))
(else
(let loop ((l l))
(if (null? (car l))
#unspecified
(begin
(apply f (map-2 car l))
(loop (map-2 cdr l))))))))
(define (filter pred lis)
(let recur ((lis lis))
(if (null? lis)
lis
(let ((head (car lis))
(tail (cdr lis)))
(if (pred head)
(let ((new-tail (recur tail)))
(if (eq? tail new-tail)
lis
(cons head new-tail)))
(recur tail))))))
(define (filter! pred lis)
(let lp ((ans lis))
(cond
((null? ans)
ans)
((not (pred (car ans)))
(lp (cdr ans)))
(else
(letrec ((scan-in (lambda (prev lis)
(if (pair? lis)
(if (pred (car lis))
(scan-in lis (cdr lis))
(scan-out prev (cdr lis))))))
(scan-out (lambda (prev lis)
(let lp ((lis lis))
(if (pair? lis)
(if (pred (car lis))
(begin
(set-cdr! prev lis)
(scan-in lis (cdr lis)))
(lp (cdr lis)))
(set-cdr! prev lis))))))
(scan-in ans (cdr ans))
ans)))))
(define-inline (force promise)
(promise))
(define (make-promise proc)
(let ((result-ready? #f)
(result #f))
(lambda ()
(if result-ready?
result
(let ((x (proc)))
(if result-ready?
result
(begin
(set! result-ready? #t)
(set! result x)
result)))))))
(define (call/cc proc)
(call-cc (lambda (cont)
(let ((evc (get-evaluation-context)))
(proc (lambda vals
(set-evaluation-context! evc)
(if (and (pair? vals) (null? (cdr vals)))
(cont (car vals))
(begin
(%set-mvalues-number! -1)
(cont vals)))))))))
(cond-expand
(bigloo-jvm
(define (call-cc proc) (bind-exit (exit) (proc exit)))))
(define-inline (call-with-current-continuation proc)
(call/cc proc))
(define (dynamic-wind before::procedure thunk::procedure after::procedure)
(before)
(let ()
(push-before! before)
(unwind-protect
(thunk)
(begin
(after)
(pop-before!)))))
|
5ca3151d51065ed6d8f9f86b853ab9f353135e5f25c68a5ae3edda0fb09b89d7 | neil-lindquist/CI-Utils | features.lisp | ;;; Push the new features
(when (or (uiop:getenvp "CI")
(uiop:getenv "TF_BUILD") ;special case for azure pipelines
(uiop:getenvp "GITHUB_ACTIONS")) ;special case for github actions
(pushnew :ci *features*)
(pushnew (cond
((uiop:getenvp "TRAVIS") :travis-ci)
((uiop:getenvp "CIRCLECI") :circleci)
((uiop:getenvp "APPVEYOR") :appveyor)
((uiop:getenvp "GITLAB_CI") :gitlab-ci)
((uiop:getenvp "BITBUCKET_BUILD_NUMBER") :bitbucket-pipelines)
((string-equal "true" (uiop:getenv "TF_BUILD")) :azure-pipelines)
((uiop:getenvp "GITHUB_ACTIONS") :github-actions)
(t :unknown-ci))
*features*))
(when (uiop:getenvp "COVERALLS")
(pushnew :coveralls *features*))
| null | https://raw.githubusercontent.com/neil-lindquist/CI-Utils/2d5a059ac74f0d9499eecf4710afa60f5b292d7a/src/features.lisp | lisp | Push the new features
special case for azure pipelines
special case for github actions |
(when (or (uiop:getenvp "CI")
(pushnew :ci *features*)
(pushnew (cond
((uiop:getenvp "TRAVIS") :travis-ci)
((uiop:getenvp "CIRCLECI") :circleci)
((uiop:getenvp "APPVEYOR") :appveyor)
((uiop:getenvp "GITLAB_CI") :gitlab-ci)
((uiop:getenvp "BITBUCKET_BUILD_NUMBER") :bitbucket-pipelines)
((string-equal "true" (uiop:getenv "TF_BUILD")) :azure-pipelines)
((uiop:getenvp "GITHUB_ACTIONS") :github-actions)
(t :unknown-ci))
*features*))
(when (uiop:getenvp "COVERALLS")
(pushnew :coveralls *features*))
|
6075dcaa008e35e150232a30d73eca9a903591ca7804654f5981a14cf1c18dfa | mstewartgallus/hs-callbypushvalue | Name.hs | {-# LANGUAGE StrictData #-}
module Name (Name (..)) where
import Data.Text (Text)
import TextShow
data Name = Name {package :: Text, name :: Text} deriving (Eq, Ord)
instance TextShow Name where
showb x = fromText (package x) <> fromString "/" <> fromText (name x)
| null | https://raw.githubusercontent.com/mstewartgallus/hs-callbypushvalue/d8770b7e9e444e1261901f5ee435fcefb0f7ad75/src/Name.hs | haskell | # LANGUAGE StrictData # |
module Name (Name (..)) where
import Data.Text (Text)
import TextShow
data Name = Name {package :: Text, name :: Text} deriving (Eq, Ord)
instance TextShow Name where
showb x = fromText (package x) <> fromString "/" <> fromText (name x)
|
b4542ff7b06368840039549e741a52952b9ecff28ab676b4a1226f0686fa0c94 | ashwinbhaskar/google-drive-file-uploader | config.clj | (ns google-drive-file-uploader.config
(:require [clojure.java.io :as io]))
(def config (-> (io/resource "config.edn")
slurp
clojure.edn/read-string))
(defn file-upload-url []
(:file-upload-url config))
(defn new-access-token-url []
(:new-access-token-url config))
(defn get-files-url []
(:get-files-url config))
(defn validate-access-token-url []
(:access-token-validation-url config))
| null | https://raw.githubusercontent.com/ashwinbhaskar/google-drive-file-uploader/16e2e763ec9137f2be69dfd12dc6fad4e9d0d71f/src/google_drive_file_uploader/config.clj | clojure | (ns google-drive-file-uploader.config
(:require [clojure.java.io :as io]))
(def config (-> (io/resource "config.edn")
slurp
clojure.edn/read-string))
(defn file-upload-url []
(:file-upload-url config))
(defn new-access-token-url []
(:new-access-token-url config))
(defn get-files-url []
(:get-files-url config))
(defn validate-access-token-url []
(:access-token-validation-url config))
| |
7bdb43b53e83165c1ccdb24fb33ad94934be87be8c0314c539b555f6aa186a40 | coq/coq | goptions.ml | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
(* This module manages customization parameters at the vernacular level *)
open Util
type option_name = string list
type option_value =
| BoolValue of bool
| IntValue of int option
| StringValue of string
| StringOptValue of string option
type table_value =
| StringRefValue of string
| QualidRefValue of Libnames.qualid
(** Summary of an option status *)
type option_state = {
opt_depr : bool;
opt_value : option_value;
}
(****************************************************************************)
(* 0- Common things *)
let nickname table = String.concat " " table
let error_no_table_of_this_type ~kind key =
CErrors.user_err
Pp.(str ("There is no " ^ kind ^ "-valued table with this name: \""
^ nickname key ^ "\"."))
let error_undeclared_key key =
CErrors.user_err
Pp.(str ("There is no flag, option or table with this name: \""
^ nickname key ^ "\"."))
(****************************************************************************)
(* 1- Tables *)
type 'a table_of_A = {
add : Environ.env -> 'a -> unit;
remove : Environ.env -> 'a -> unit;
mem : Environ.env -> 'a -> unit;
print : unit -> unit;
}
module MakeTable =
functor
(A : sig
type t
type key
module Set : CSig.SetS with type elt = t
val table : (string * key table_of_A) list ref
val encode : Environ.env -> key -> t
val subst : Mod_subst.substitution -> t -> t
val printer : t -> Pp.t
val key : option_name
val title : string
val member_message : t -> bool -> Pp.t
end) ->
struct
type option_mark =
| GOadd
| GOrmv
let nick = nickname A.key
let () =
if String.List.mem_assoc nick !A.table then
CErrors.user_err
Pp.(strbrk "Sorry, this table name (" ++ str nick
++ strbrk ") is already used.")
module MySet = A.Set
let t = Summary.ref ~stage:Summary.Stage.Synterp MySet.empty ~name:nick
let (add_option,remove_option) =
let cache_options (f,p) = match f with
| GOadd -> t := MySet.add p !t
| GOrmv -> t := MySet.remove p !t in
let load_options i o = if Int.equal i 1 then cache_options o in
let subst_options (subst,(f,p as obj)) =
let p' = A.subst subst p in
if p' == p then obj else
(f,p')
in
let inGo : option_mark * A.t -> Libobject.obj =
Libobject.declare_object {(Libobject.default_object nick) with
Libobject.object_stage = Summary.Stage.Synterp;
Libobject.load_function = load_options;
Libobject.open_function = Libobject.simple_open load_options;
Libobject.cache_function = cache_options;
Libobject.subst_function = subst_options;
Libobject.classify_function = (fun x -> Substitute)}
in
((fun c -> Lib.add_leaf (inGo (GOadd, c))),
(fun c -> Lib.add_leaf (inGo (GOrmv, c))))
let print_table table_name printer table =
Feedback.msg_notice
Pp.(str table_name ++
(hov 0
(if MySet.is_empty table then str " None" ++ fnl ()
else MySet.fold
(fun a b -> spc () ++ printer a ++ b)
table (mt ()) ++ str "." ++ fnl ())))
let table_of_A = {
add = (fun env x -> add_option (A.encode env x));
remove = (fun env x -> remove_option (A.encode env x));
mem = (fun env x ->
let y = A.encode env x in
let answer = MySet.mem y !t in
Feedback.msg_info (A.member_message y answer));
print = (fun () -> print_table A.title A.printer !t);
}
let _ = A.table := (nick, table_of_A)::!A.table
let v () = !t
let active x = A.Set.mem x !t
let set x b = if b then add_option x else remove_option x
end
let string_table = ref []
let get_string_table k = String.List.assoc (nickname k) !string_table
module type StringConvertArg =
sig
val key : option_name
val title : string
val member_message : string -> bool -> Pp.t
end
module StringConvert = functor (A : StringConvertArg) ->
struct
type t = string
type key = string
module Set = CString.Set
let table = string_table
let encode _env x = x
let subst _ x = x
let printer = Pp.str
let key = A.key
let title = A.title
let member_message = A.member_message
end
module MakeStringTable =
functor (A : StringConvertArg) -> MakeTable (StringConvert(A))
let ref_table = ref []
let get_ref_table k = String.List.assoc (nickname k) !ref_table
module type RefConvertArg =
sig
type t
module Set : CSig.SetS with type elt = t
val encode : Environ.env -> Libnames.qualid -> t
val subst : Mod_subst.substitution -> t -> t
val printer : t -> Pp.t
val key : option_name
val title : string
val member_message : t -> bool -> Pp.t
end
module RefConvert = functor (A : RefConvertArg) ->
struct
type t = A.t
type key = Libnames.qualid
module Set = A.Set
let table = ref_table
let encode = A.encode
let subst = A.subst
let printer = A.printer
let key = A.key
let title = A.title
let member_message = A.member_message
end
module MakeRefTable =
functor (A : RefConvertArg) -> MakeTable (RefConvert(A))
type iter_table_aux = { aux : 'a. 'a table_of_A -> Environ.env -> 'a -> unit }
let iter_table f key lv =
let aux = function
| StringRefValue s ->
begin
try f.aux (get_string_table key) (Global.env()) s
with Not_found -> error_no_table_of_this_type ~kind:"string" key
end
| QualidRefValue locqid ->
begin
try f.aux (get_ref_table key) (Global.env()) locqid
with Not_found -> error_no_table_of_this_type ~kind:"qualid" key
end
in
List.iter aux lv
(****************************************************************************)
(* 2- Flags. *)
type 'a option_sig = {
optstage : Summary.Stage.t;
optdepr : bool;
optkey : option_name;
optread : unit -> 'a;
optwrite : 'a -> unit }
type option_locality = OptDefault | OptLocal | OptExport | OptGlobal
type option_mod = OptSet | OptAppend
module OptionOrd =
struct
type t = option_name
let compare opt1 opt2 = List.compare String.compare opt1 opt2
end
module OptionMap = Map.Make(OptionOrd)
let value_tab = ref OptionMap.empty
(* This raises Not_found if option of key [key] is unknown *)
let get_option key = OptionMap.find key !value_tab
let check_key key = try
let _ = get_option key in
CErrors.user_err Pp.(str "Sorry, this option name ("
++ str (nickname key) ++ str ") is already used.")
with Not_found ->
if String.List.mem_assoc (nickname key) !string_table
|| String.List.mem_assoc (nickname key) !ref_table
then CErrors.user_err Pp.(str "Sorry, this option name ("
++ str (nickname key) ++ str ") is already used.")
open Libobject
let warn_deprecated_option =
CWarnings.create ~name:"deprecated-option" ~category:"deprecated" (fun key ->
Pp.(str "Option" ++ spc () ++ str (nickname key) ++ strbrk " is deprecated"))
let declare_option cast uncast append ?(preprocess = fun x -> x)
{ optstage=stage; optdepr=depr; optkey=key; optread=read; optwrite=write } =
check_key key;
let default = read() in
let change =
let _ = Summary.declare_summary (nickname key)
{ stage;
Summary.freeze_function = (fun ~marshallable -> read ());
Summary.unfreeze_function = write;
Summary.init_function = (fun () -> write default) } in
let cache_options (l,m,v) =
match m with
| OptSet -> write v
| OptAppend -> write (append (read ()) v) in
let load_options i (l, _, _ as o) = match l with
| OptGlobal -> cache_options o
| OptExport -> ()
| OptLocal | OptDefault ->
(* Ruled out by classify_function *)
assert false
in
let open_options i (l, _, _ as o) = match l with
| OptExport -> if Int.equal i 1 then cache_options o
| OptGlobal -> ()
| OptLocal | OptDefault ->
(* Ruled out by classify_function *)
assert false
in
let subst_options (subst,obj) = obj in
let discharge_options (l,_,_ as o) =
match l with OptLocal -> None | (OptExport | OptGlobal | OptDefault) -> Some o in
let classify_options (l,_,_) =
match l with (OptExport | OptGlobal) -> Substitute | (OptLocal | OptDefault) -> Dispose in
let options : option_locality * option_mod * _ -> obj =
declare_object
{ (default_object (nickname key)) with
object_stage = stage;
load_function = load_options;
open_function = simple_open open_options;
cache_function = cache_options;
subst_function = subst_options;
discharge_function = discharge_options;
classify_function = classify_options } in
(fun l m v -> let v = preprocess v in Lib.add_leaf (options (l, m, v)))
in
let warn () = if depr then warn_deprecated_option key in
let cread () = cast (read ()) in
let cwrite l v = warn (); change l OptSet (uncast v) in
let cappend l v = warn (); change l OptAppend (uncast v) in
value_tab := OptionMap.add key (depr, stage, (cread,cwrite,cappend)) !value_tab
let declare_int_option =
declare_option
(fun v -> IntValue v)
(function IntValue v -> v | _ -> CErrors.anomaly (Pp.str "async_option."))
(fun _ _ -> CErrors.anomaly (Pp.str "async_option."))
let declare_bool_option =
declare_option
(fun v -> BoolValue v)
(function BoolValue v -> v | _ -> CErrors.anomaly (Pp.str "async_option."))
(fun _ _ -> CErrors.anomaly (Pp.str "async_option."))
let declare_string_option =
declare_option
(fun v -> StringValue v)
(function StringValue v -> v | _ -> CErrors.anomaly (Pp.str "async_option."))
(fun x y -> x^","^y)
let declare_stringopt_option =
declare_option
(fun v -> StringOptValue v)
(function StringOptValue v -> v | _ -> CErrors.anomaly (Pp.str "async_option."))
(fun _ _ -> CErrors.anomaly (Pp.str "async_option."))
type 'a opt_decl = stage:Summary.Stage.t -> depr:bool -> key:option_name -> 'a
let declare_int_option_and_ref ~stage ~depr ~key ~(value:int) =
let r_opt = ref value in
let optwrite v = r_opt := Option.default value v in
let optread () = Some !r_opt in
let _ = declare_int_option {
optstage = stage;
optdepr = depr;
optkey = key;
optread; optwrite
} in
fun () -> !r_opt
let declare_intopt_option_and_ref ~stage ~depr ~key =
let r_opt = ref None in
let optwrite v = r_opt := v in
let optread () = !r_opt in
let _ = declare_int_option {
optstage = stage;
optdepr = depr;
optkey = key;
optread; optwrite
} in
optread
let declare_nat_option_and_ref ~stage ~depr ~key ~(value:int) =
assert (value >= 0);
let r_opt = ref value in
let optwrite v =
let v = Option.default value v in
if v < 0 then
CErrors.user_err Pp.(str "This option expects a non-negative value.");
r_opt := v
in
let optread () = Some !r_opt in
let _ = declare_int_option {
optstage = stage;
optdepr = depr;
optkey = key;
optread; optwrite
} in
fun () -> !r_opt
let declare_bool_option_and_ref ~stage ~depr ~key ~(value:bool) =
let r_opt = ref value in
let optwrite v = r_opt := v in
let optread () = !r_opt in
let _ = declare_bool_option {
optstage = stage;
optdepr = depr;
optkey = key;
optread; optwrite
} in
optread
let declare_string_option_and_ref ~stage ~depr ~key ~(value:string) =
let r_opt = ref value in
let optwrite v = r_opt := Option.default value v in
let optread () = Some !r_opt in
let _ = declare_stringopt_option {
optstage = stage;
optdepr = depr;
optkey = key;
optread; optwrite
} in
fun () -> !r_opt
let declare_stringopt_option_and_ref ~stage ~depr ~key =
let r_opt = ref None in
let optwrite v = r_opt := v in
let optread () = !r_opt in
let _ = declare_stringopt_option {
optstage = stage;
optdepr = depr;
optkey = key;
optread; optwrite
} in
optread
let declare_interpreted_string_option_and_ref ~stage ~depr ~key ~(value:'a) from_string to_string =
let r_opt = ref value in
let optwrite v = r_opt := Option.default value @@ Option.map from_string v in
let optread () = Some (to_string !r_opt) in
let _ = declare_stringopt_option {
optstage = stage;
optdepr = depr;
optkey = key;
optread; optwrite
} in
fun () -> !r_opt
(* 3- User accessible commands *)
(* Setting values of options *)
let warn_unknown_option =
CWarnings.create
~name:"unknown-option" ~category:"option"
Pp.(fun key -> strbrk "There is no flag or option with this name: \"" ++
str (nickname key) ++ str "\".")
* Sets the option only if [ stage ] matches the option declaration or if [ stage ]
is omitted . If the option is not found , a warning is emitted only if the stage
is [ Interp ] or omitted .
is omitted. If the option is not found, a warning is emitted only if the stage
is [Interp] or omitted. *)
let set_option_value ?(locality = OptDefault) ?stage check_and_cast key v =
let opt = try Some (get_option key) with Not_found -> None in
match opt with
| None -> begin match stage with None | Some Summary.Stage.Interp -> warn_unknown_option key | _ -> () end
| Some (depr, option_stage, (read,write,append)) ->
if Option.cata (fun s -> s = option_stage) true stage then
write locality (check_and_cast v (read ()))
let bad_type_error ~expected ~got =
CErrors.user_err Pp.(strbrk "Bad type of value for this option:" ++ spc()
++ str "expected " ++ str expected ++ str ", got " ++ str got ++ str ".")
let error_flag () =
CErrors.user_err Pp.(str "This is a flag. It does not take a value.")
let check_int_value v = function
| BoolValue _ -> error_flag ()
| IntValue _ -> IntValue v
| StringValue _ | StringOptValue _ ->
bad_type_error ~expected:"string" ~got:"int"
let check_bool_value v = function
| BoolValue _ -> BoolValue v
| _ ->
CErrors.user_err
Pp.(str "This is an option. A value must be provided.")
let check_string_value v = function
| BoolValue _ -> error_flag ()
| IntValue _ -> bad_type_error ~expected:"int" ~got:"string"
| StringValue _ -> StringValue v
| StringOptValue _ -> StringOptValue (Some v)
let check_unset_value v = function
| BoolValue _ -> BoolValue false
| IntValue _ -> IntValue None
| StringOptValue _ -> StringOptValue None
| StringValue _ ->
CErrors.user_err
Pp.(str "This option does not support the \"Unset\" command.")
(* Nota: For compatibility reasons, some errors are treated as
warnings. This allows a script to refer to an option that doesn't
exist anymore *)
let set_int_option_value_gen ?locality ?stage =
set_option_value ?locality ?stage check_int_value
let set_bool_option_value_gen ?locality ?stage key v =
set_option_value ?locality ?stage check_bool_value key v
let set_string_option_value_gen ?locality ?stage =
set_option_value ?locality ?stage check_string_value
let unset_option_value_gen ?locality ?stage key =
set_option_value ?locality ?stage check_unset_value key ()
let set_string_option_append_value_gen ?(locality = OptDefault) ?stage key v =
let opt = try Some (get_option key) with Not_found -> None in
match opt with
| None -> warn_unknown_option key
| Some (depr, option_stage, (read,write,append)) ->
if Option.cata (fun s -> s = option_stage) true stage then
append locality (check_string_value v (read ()))
let set_int_option_value ?stage opt v = set_int_option_value_gen ?stage opt v
let set_bool_option_value ?stage opt v = set_bool_option_value_gen ?stage opt v
let set_string_option_value ?stage opt v = set_string_option_value_gen ?stage opt v
(* Printing options/tables *)
let msg_option_value = Pp.(function
| BoolValue true -> str "on"
| BoolValue false -> str "off"
| IntValue (Some n) -> int n
| IntValue None -> str "undefined"
| StringValue s -> quote (str s)
| StringOptValue None -> str "undefined"
| StringOptValue (Some s) -> quote (str s))
let print_option_value key =
let (depr, _stage, (read,_,_)) = get_option key in
let s = read () in
match s with
| BoolValue b ->
Feedback.msg_notice Pp.(prlist_with_sep spc str key ++ str " is "
++ str (if b then "on" else "off"))
| _ ->
Feedback.msg_notice Pp.(str "Current value of "
++ prlist_with_sep spc str key ++ str " is " ++ msg_option_value s)
let get_tables () =
let tables = !value_tab in
let fold key (depr, _stage, (read,_,_)) accu =
let state = {
opt_depr = depr;
opt_value = read ();
} in
OptionMap.add key state accu
in
OptionMap.fold fold tables OptionMap.empty
let print_tables () =
let open Pp in
let print_option key value depr =
let msg = str " " ++ str (nickname key) ++ str ": " ++ msg_option_value value in
if depr then msg ++ str " [DEPRECATED]" ++ fnl ()
else msg ++ fnl ()
in
str "Options:" ++ fnl () ++
OptionMap.fold
(fun key (depr, _stage, (read,_,_)) p ->
p ++ print_option key (read ()) depr)
!value_tab (mt ()) ++
str "Tables:" ++ fnl () ++
List.fold_right
(fun (nickkey,_) p -> p ++ str " " ++ str nickkey ++ fnl ())
!string_table (mt ()) ++
List.fold_right
(fun (nickkey,_) p -> p ++ str " " ++ str nickkey ++ fnl ())
!ref_table (mt ()) ++
fnl ()
| null | https://raw.githubusercontent.com/coq/coq/aba52f112d6ca6e809c5b33f7bd2020cdcef0100/library/goptions.ml | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
**********************************************************************
This module manages customization parameters at the vernacular level
* Summary of an option status
**************************************************************************
0- Common things
**************************************************************************
1- Tables
**************************************************************************
2- Flags.
This raises Not_found if option of key [key] is unknown
Ruled out by classify_function
Ruled out by classify_function
3- User accessible commands
Setting values of options
Nota: For compatibility reasons, some errors are treated as
warnings. This allows a script to refer to an option that doesn't
exist anymore
Printing options/tables | v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
open Util
type option_name = string list
type option_value =
| BoolValue of bool
| IntValue of int option
| StringValue of string
| StringOptValue of string option
type table_value =
| StringRefValue of string
| QualidRefValue of Libnames.qualid
type option_state = {
opt_depr : bool;
opt_value : option_value;
}
let nickname table = String.concat " " table
let error_no_table_of_this_type ~kind key =
CErrors.user_err
Pp.(str ("There is no " ^ kind ^ "-valued table with this name: \""
^ nickname key ^ "\"."))
let error_undeclared_key key =
CErrors.user_err
Pp.(str ("There is no flag, option or table with this name: \""
^ nickname key ^ "\"."))
type 'a table_of_A = {
add : Environ.env -> 'a -> unit;
remove : Environ.env -> 'a -> unit;
mem : Environ.env -> 'a -> unit;
print : unit -> unit;
}
module MakeTable =
functor
(A : sig
type t
type key
module Set : CSig.SetS with type elt = t
val table : (string * key table_of_A) list ref
val encode : Environ.env -> key -> t
val subst : Mod_subst.substitution -> t -> t
val printer : t -> Pp.t
val key : option_name
val title : string
val member_message : t -> bool -> Pp.t
end) ->
struct
type option_mark =
| GOadd
| GOrmv
let nick = nickname A.key
let () =
if String.List.mem_assoc nick !A.table then
CErrors.user_err
Pp.(strbrk "Sorry, this table name (" ++ str nick
++ strbrk ") is already used.")
module MySet = A.Set
let t = Summary.ref ~stage:Summary.Stage.Synterp MySet.empty ~name:nick
let (add_option,remove_option) =
let cache_options (f,p) = match f with
| GOadd -> t := MySet.add p !t
| GOrmv -> t := MySet.remove p !t in
let load_options i o = if Int.equal i 1 then cache_options o in
let subst_options (subst,(f,p as obj)) =
let p' = A.subst subst p in
if p' == p then obj else
(f,p')
in
let inGo : option_mark * A.t -> Libobject.obj =
Libobject.declare_object {(Libobject.default_object nick) with
Libobject.object_stage = Summary.Stage.Synterp;
Libobject.load_function = load_options;
Libobject.open_function = Libobject.simple_open load_options;
Libobject.cache_function = cache_options;
Libobject.subst_function = subst_options;
Libobject.classify_function = (fun x -> Substitute)}
in
((fun c -> Lib.add_leaf (inGo (GOadd, c))),
(fun c -> Lib.add_leaf (inGo (GOrmv, c))))
let print_table table_name printer table =
Feedback.msg_notice
Pp.(str table_name ++
(hov 0
(if MySet.is_empty table then str " None" ++ fnl ()
else MySet.fold
(fun a b -> spc () ++ printer a ++ b)
table (mt ()) ++ str "." ++ fnl ())))
let table_of_A = {
add = (fun env x -> add_option (A.encode env x));
remove = (fun env x -> remove_option (A.encode env x));
mem = (fun env x ->
let y = A.encode env x in
let answer = MySet.mem y !t in
Feedback.msg_info (A.member_message y answer));
print = (fun () -> print_table A.title A.printer !t);
}
let _ = A.table := (nick, table_of_A)::!A.table
let v () = !t
let active x = A.Set.mem x !t
let set x b = if b then add_option x else remove_option x
end
let string_table = ref []
let get_string_table k = String.List.assoc (nickname k) !string_table
module type StringConvertArg =
sig
val key : option_name
val title : string
val member_message : string -> bool -> Pp.t
end
module StringConvert = functor (A : StringConvertArg) ->
struct
type t = string
type key = string
module Set = CString.Set
let table = string_table
let encode _env x = x
let subst _ x = x
let printer = Pp.str
let key = A.key
let title = A.title
let member_message = A.member_message
end
module MakeStringTable =
functor (A : StringConvertArg) -> MakeTable (StringConvert(A))
let ref_table = ref []
let get_ref_table k = String.List.assoc (nickname k) !ref_table
module type RefConvertArg =
sig
type t
module Set : CSig.SetS with type elt = t
val encode : Environ.env -> Libnames.qualid -> t
val subst : Mod_subst.substitution -> t -> t
val printer : t -> Pp.t
val key : option_name
val title : string
val member_message : t -> bool -> Pp.t
end
module RefConvert = functor (A : RefConvertArg) ->
struct
type t = A.t
type key = Libnames.qualid
module Set = A.Set
let table = ref_table
let encode = A.encode
let subst = A.subst
let printer = A.printer
let key = A.key
let title = A.title
let member_message = A.member_message
end
module MakeRefTable =
functor (A : RefConvertArg) -> MakeTable (RefConvert(A))
type iter_table_aux = { aux : 'a. 'a table_of_A -> Environ.env -> 'a -> unit }
let iter_table f key lv =
let aux = function
| StringRefValue s ->
begin
try f.aux (get_string_table key) (Global.env()) s
with Not_found -> error_no_table_of_this_type ~kind:"string" key
end
| QualidRefValue locqid ->
begin
try f.aux (get_ref_table key) (Global.env()) locqid
with Not_found -> error_no_table_of_this_type ~kind:"qualid" key
end
in
List.iter aux lv
type 'a option_sig = {
optstage : Summary.Stage.t;
optdepr : bool;
optkey : option_name;
optread : unit -> 'a;
optwrite : 'a -> unit }
type option_locality = OptDefault | OptLocal | OptExport | OptGlobal
type option_mod = OptSet | OptAppend
module OptionOrd =
struct
type t = option_name
let compare opt1 opt2 = List.compare String.compare opt1 opt2
end
module OptionMap = Map.Make(OptionOrd)
let value_tab = ref OptionMap.empty
let get_option key = OptionMap.find key !value_tab
let check_key key = try
let _ = get_option key in
CErrors.user_err Pp.(str "Sorry, this option name ("
++ str (nickname key) ++ str ") is already used.")
with Not_found ->
if String.List.mem_assoc (nickname key) !string_table
|| String.List.mem_assoc (nickname key) !ref_table
then CErrors.user_err Pp.(str "Sorry, this option name ("
++ str (nickname key) ++ str ") is already used.")
open Libobject
let warn_deprecated_option =
CWarnings.create ~name:"deprecated-option" ~category:"deprecated" (fun key ->
Pp.(str "Option" ++ spc () ++ str (nickname key) ++ strbrk " is deprecated"))
let declare_option cast uncast append ?(preprocess = fun x -> x)
{ optstage=stage; optdepr=depr; optkey=key; optread=read; optwrite=write } =
check_key key;
let default = read() in
let change =
let _ = Summary.declare_summary (nickname key)
{ stage;
Summary.freeze_function = (fun ~marshallable -> read ());
Summary.unfreeze_function = write;
Summary.init_function = (fun () -> write default) } in
let cache_options (l,m,v) =
match m with
| OptSet -> write v
| OptAppend -> write (append (read ()) v) in
let load_options i (l, _, _ as o) = match l with
| OptGlobal -> cache_options o
| OptExport -> ()
| OptLocal | OptDefault ->
assert false
in
let open_options i (l, _, _ as o) = match l with
| OptExport -> if Int.equal i 1 then cache_options o
| OptGlobal -> ()
| OptLocal | OptDefault ->
assert false
in
let subst_options (subst,obj) = obj in
let discharge_options (l,_,_ as o) =
match l with OptLocal -> None | (OptExport | OptGlobal | OptDefault) -> Some o in
let classify_options (l,_,_) =
match l with (OptExport | OptGlobal) -> Substitute | (OptLocal | OptDefault) -> Dispose in
let options : option_locality * option_mod * _ -> obj =
declare_object
{ (default_object (nickname key)) with
object_stage = stage;
load_function = load_options;
open_function = simple_open open_options;
cache_function = cache_options;
subst_function = subst_options;
discharge_function = discharge_options;
classify_function = classify_options } in
(fun l m v -> let v = preprocess v in Lib.add_leaf (options (l, m, v)))
in
let warn () = if depr then warn_deprecated_option key in
let cread () = cast (read ()) in
let cwrite l v = warn (); change l OptSet (uncast v) in
let cappend l v = warn (); change l OptAppend (uncast v) in
value_tab := OptionMap.add key (depr, stage, (cread,cwrite,cappend)) !value_tab
let declare_int_option =
declare_option
(fun v -> IntValue v)
(function IntValue v -> v | _ -> CErrors.anomaly (Pp.str "async_option."))
(fun _ _ -> CErrors.anomaly (Pp.str "async_option."))
let declare_bool_option =
declare_option
(fun v -> BoolValue v)
(function BoolValue v -> v | _ -> CErrors.anomaly (Pp.str "async_option."))
(fun _ _ -> CErrors.anomaly (Pp.str "async_option."))
let declare_string_option =
declare_option
(fun v -> StringValue v)
(function StringValue v -> v | _ -> CErrors.anomaly (Pp.str "async_option."))
(fun x y -> x^","^y)
let declare_stringopt_option =
declare_option
(fun v -> StringOptValue v)
(function StringOptValue v -> v | _ -> CErrors.anomaly (Pp.str "async_option."))
(fun _ _ -> CErrors.anomaly (Pp.str "async_option."))
type 'a opt_decl = stage:Summary.Stage.t -> depr:bool -> key:option_name -> 'a
let declare_int_option_and_ref ~stage ~depr ~key ~(value:int) =
let r_opt = ref value in
let optwrite v = r_opt := Option.default value v in
let optread () = Some !r_opt in
let _ = declare_int_option {
optstage = stage;
optdepr = depr;
optkey = key;
optread; optwrite
} in
fun () -> !r_opt
let declare_intopt_option_and_ref ~stage ~depr ~key =
let r_opt = ref None in
let optwrite v = r_opt := v in
let optread () = !r_opt in
let _ = declare_int_option {
optstage = stage;
optdepr = depr;
optkey = key;
optread; optwrite
} in
optread
let declare_nat_option_and_ref ~stage ~depr ~key ~(value:int) =
assert (value >= 0);
let r_opt = ref value in
let optwrite v =
let v = Option.default value v in
if v < 0 then
CErrors.user_err Pp.(str "This option expects a non-negative value.");
r_opt := v
in
let optread () = Some !r_opt in
let _ = declare_int_option {
optstage = stage;
optdepr = depr;
optkey = key;
optread; optwrite
} in
fun () -> !r_opt
let declare_bool_option_and_ref ~stage ~depr ~key ~(value:bool) =
let r_opt = ref value in
let optwrite v = r_opt := v in
let optread () = !r_opt in
let _ = declare_bool_option {
optstage = stage;
optdepr = depr;
optkey = key;
optread; optwrite
} in
optread
let declare_string_option_and_ref ~stage ~depr ~key ~(value:string) =
let r_opt = ref value in
let optwrite v = r_opt := Option.default value v in
let optread () = Some !r_opt in
let _ = declare_stringopt_option {
optstage = stage;
optdepr = depr;
optkey = key;
optread; optwrite
} in
fun () -> !r_opt
let declare_stringopt_option_and_ref ~stage ~depr ~key =
let r_opt = ref None in
let optwrite v = r_opt := v in
let optread () = !r_opt in
let _ = declare_stringopt_option {
optstage = stage;
optdepr = depr;
optkey = key;
optread; optwrite
} in
optread
let declare_interpreted_string_option_and_ref ~stage ~depr ~key ~(value:'a) from_string to_string =
let r_opt = ref value in
let optwrite v = r_opt := Option.default value @@ Option.map from_string v in
let optread () = Some (to_string !r_opt) in
let _ = declare_stringopt_option {
optstage = stage;
optdepr = depr;
optkey = key;
optread; optwrite
} in
fun () -> !r_opt
let warn_unknown_option =
CWarnings.create
~name:"unknown-option" ~category:"option"
Pp.(fun key -> strbrk "There is no flag or option with this name: \"" ++
str (nickname key) ++ str "\".")
* Sets the option only if [ stage ] matches the option declaration or if [ stage ]
is omitted . If the option is not found , a warning is emitted only if the stage
is [ Interp ] or omitted .
is omitted. If the option is not found, a warning is emitted only if the stage
is [Interp] or omitted. *)
let set_option_value ?(locality = OptDefault) ?stage check_and_cast key v =
let opt = try Some (get_option key) with Not_found -> None in
match opt with
| None -> begin match stage with None | Some Summary.Stage.Interp -> warn_unknown_option key | _ -> () end
| Some (depr, option_stage, (read,write,append)) ->
if Option.cata (fun s -> s = option_stage) true stage then
write locality (check_and_cast v (read ()))
let bad_type_error ~expected ~got =
CErrors.user_err Pp.(strbrk "Bad type of value for this option:" ++ spc()
++ str "expected " ++ str expected ++ str ", got " ++ str got ++ str ".")
let error_flag () =
CErrors.user_err Pp.(str "This is a flag. It does not take a value.")
let check_int_value v = function
| BoolValue _ -> error_flag ()
| IntValue _ -> IntValue v
| StringValue _ | StringOptValue _ ->
bad_type_error ~expected:"string" ~got:"int"
let check_bool_value v = function
| BoolValue _ -> BoolValue v
| _ ->
CErrors.user_err
Pp.(str "This is an option. A value must be provided.")
let check_string_value v = function
| BoolValue _ -> error_flag ()
| IntValue _ -> bad_type_error ~expected:"int" ~got:"string"
| StringValue _ -> StringValue v
| StringOptValue _ -> StringOptValue (Some v)
let check_unset_value v = function
| BoolValue _ -> BoolValue false
| IntValue _ -> IntValue None
| StringOptValue _ -> StringOptValue None
| StringValue _ ->
CErrors.user_err
Pp.(str "This option does not support the \"Unset\" command.")
let set_int_option_value_gen ?locality ?stage =
set_option_value ?locality ?stage check_int_value
let set_bool_option_value_gen ?locality ?stage key v =
set_option_value ?locality ?stage check_bool_value key v
let set_string_option_value_gen ?locality ?stage =
set_option_value ?locality ?stage check_string_value
let unset_option_value_gen ?locality ?stage key =
set_option_value ?locality ?stage check_unset_value key ()
let set_string_option_append_value_gen ?(locality = OptDefault) ?stage key v =
let opt = try Some (get_option key) with Not_found -> None in
match opt with
| None -> warn_unknown_option key
| Some (depr, option_stage, (read,write,append)) ->
if Option.cata (fun s -> s = option_stage) true stage then
append locality (check_string_value v (read ()))
let set_int_option_value ?stage opt v = set_int_option_value_gen ?stage opt v
let set_bool_option_value ?stage opt v = set_bool_option_value_gen ?stage opt v
let set_string_option_value ?stage opt v = set_string_option_value_gen ?stage opt v
let msg_option_value = Pp.(function
| BoolValue true -> str "on"
| BoolValue false -> str "off"
| IntValue (Some n) -> int n
| IntValue None -> str "undefined"
| StringValue s -> quote (str s)
| StringOptValue None -> str "undefined"
| StringOptValue (Some s) -> quote (str s))
let print_option_value key =
let (depr, _stage, (read,_,_)) = get_option key in
let s = read () in
match s with
| BoolValue b ->
Feedback.msg_notice Pp.(prlist_with_sep spc str key ++ str " is "
++ str (if b then "on" else "off"))
| _ ->
Feedback.msg_notice Pp.(str "Current value of "
++ prlist_with_sep spc str key ++ str " is " ++ msg_option_value s)
let get_tables () =
let tables = !value_tab in
let fold key (depr, _stage, (read,_,_)) accu =
let state = {
opt_depr = depr;
opt_value = read ();
} in
OptionMap.add key state accu
in
OptionMap.fold fold tables OptionMap.empty
let print_tables () =
let open Pp in
let print_option key value depr =
let msg = str " " ++ str (nickname key) ++ str ": " ++ msg_option_value value in
if depr then msg ++ str " [DEPRECATED]" ++ fnl ()
else msg ++ fnl ()
in
str "Options:" ++ fnl () ++
OptionMap.fold
(fun key (depr, _stage, (read,_,_)) p ->
p ++ print_option key (read ()) depr)
!value_tab (mt ()) ++
str "Tables:" ++ fnl () ++
List.fold_right
(fun (nickkey,_) p -> p ++ str " " ++ str nickkey ++ fnl ())
!string_table (mt ()) ++
List.fold_right
(fun (nickkey,_) p -> p ++ str " " ++ str nickkey ++ fnl ())
!ref_table (mt ()) ++
fnl ()
|
7ad79347ea11ca505dd233b9ad40e8e0d60f56044dfad45f0a3f97842ecbde22 | essen/egs | egs_items_db.erl | @author < >
2010 - 2011 .
@doc EGS items database .
%%
This file is part of EGS .
%%
EGS 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.
%%
EGS 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 EGS . If not , see < / > .
-module(egs_items_db).
-behavior(gen_server).
-export([start_link/0, stop/0, desc/1, read/1, reload/0]). %% API.
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %% gen_server.
%% Use the module name for the server's name.
-define(SERVER, ?MODULE).
-include("include/records.hrl").
-include("../../priv/items.hrl").
%% API.
( ) - > { ok , Pid::pid ( ) }
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
stop ( ) - > stopped
stop() ->
gen_server:call(?SERVER, stop).
desc(ItemID ) - > string ( )
desc(ItemID) ->
gen_server:call(?SERVER, {desc, ItemID}).
@spec read(ItemID ) - > term ( ) | undefined
read(ItemID) ->
gen_server:call(?SERVER, {read, ItemID}).
@spec reload ( ) - > ok
reload() ->
gen_server:cast(?SERVER, reload).
%% gen_server.
init([]) ->
error_logger:info_report("egs_items_db started"),
{ok, undefined}.
handle_call({desc, ItemID}, _From, State) ->
Filename = io_lib:format("priv/item_descs/~8.16.0b.txt", [ItemID]),
Desc = case filelib:is_regular(Filename) of
false -> << << X:8, 0:8 >> || X <- "Always bet on Dammy." >>;
true -> {ok, File} = file:read_file(Filename), File
end,
{reply, Desc, State};
handle_call({read, ItemID}, _From, State) ->
{reply, proplists:get_value(ItemID, ?ITEMS), State};
handle_call(stop, _From, State) ->
{stop, normal, stopped, State};
handle_call(_Request, _From, State) ->
{reply, ignored, State}.
%% @doc Compile this file here and let the reloader reload the code properly.
handle_cast(reload, State) ->
compile:file(?FILE, [verbose, report_errors, report_warnings, {outdir, "ebin/"}]),
{noreply, State};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
| null | https://raw.githubusercontent.com/essen/egs/ceea04c3b438cee9a8470f2abc6297429bf347c5/apps/egs/src/egs_items_db.erl | erlang |
License, or (at your option) any later version.
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.
API.
gen_server.
Use the module name for the server's name.
API.
gen_server.
@doc Compile this file here and let the reloader reload the code properly. | @author < >
2010 - 2011 .
@doc EGS items database .
This file is part of EGS .
EGS 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
EGS is distributed in the hope that it will be useful ,
You should have received a copy of the GNU Affero General Public License
along with EGS . If not , see < / > .
-module(egs_items_db).
-behavior(gen_server).
-define(SERVER, ?MODULE).
-include("include/records.hrl").
-include("../../priv/items.hrl").
( ) - > { ok , Pid::pid ( ) }
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
stop ( ) - > stopped
stop() ->
gen_server:call(?SERVER, stop).
desc(ItemID ) - > string ( )
desc(ItemID) ->
gen_server:call(?SERVER, {desc, ItemID}).
@spec read(ItemID ) - > term ( ) | undefined
read(ItemID) ->
gen_server:call(?SERVER, {read, ItemID}).
@spec reload ( ) - > ok
reload() ->
gen_server:cast(?SERVER, reload).
init([]) ->
error_logger:info_report("egs_items_db started"),
{ok, undefined}.
handle_call({desc, ItemID}, _From, State) ->
Filename = io_lib:format("priv/item_descs/~8.16.0b.txt", [ItemID]),
Desc = case filelib:is_regular(Filename) of
false -> << << X:8, 0:8 >> || X <- "Always bet on Dammy." >>;
true -> {ok, File} = file:read_file(Filename), File
end,
{reply, Desc, State};
handle_call({read, ItemID}, _From, State) ->
{reply, proplists:get_value(ItemID, ?ITEMS), State};
handle_call(stop, _From, State) ->
{stop, normal, stopped, State};
handle_call(_Request, _From, State) ->
{reply, ignored, State}.
handle_cast(reload, State) ->
compile:file(?FILE, [verbose, report_errors, report_warnings, {outdir, "ebin/"}]),
{noreply, State};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
|
98414961aa19e0a0e2b2caa91bec04cbda4b36aa660c191b431c8fa457c9fa26 | korya/efuns | xpmroot.ml | (***********************************************************************)
(* *)
xlib for
(* *)
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
open Xtypes
open Xbuffer
open Xlib
let dpyname = ref ""
let main filename =
let dpy = openDisplay !dpyname in
let screen = defaultScreen dpy in
let root = defaultRoot dpy in
let cmap = defaultColormap dpy in
let depth = defaultDepth dpy in
let (dx,dy,_,pix,_) = Xpm.createPixmapFromFile dpy root cmap depth filename in
X.changeWindowAttributes dpy root [CWBackPixmap pix];
X.clearArea dpy root 0 0 0 0 false;
let prop = try X.internAtom dpy "_XSETROOT_ID" false with Not_found -> failwith "interAtom" in
let _ =
try
let gp = X.getProperty dpy root false prop anyPropertyType 0 4 in
if gp.gp_type = XA.xa_pixmap && gp.gp_format = 32 &&
gp.gp_length = 1 && gp.gp_left = 0 then
let pix = Xbuffer.getCard32 gp.gp_value 0 in
X.killClient dpy pix
with
Not_found -> ()
in
X.changeProperty dpy root PropModeReplace
prop XA.xa_pixmap 1 (let b = newString 1 in setEnum32 b 0 pix; b);
X.setCloseDownMode dpy RetainPermanent;
Xlib.closeDisplay dpy
let _ =
Arg.parse [
"-d", Arg.String (fun s -> dpyname := s), "display: set display";
] main "Usage: xpmroot filename.xpm"
| null | https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/xlib/examples/xpmroot.ml | ocaml | *********************************************************************
********************************************************************* | xlib for
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
Copyright 1999 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
open Xtypes
open Xbuffer
open Xlib
let dpyname = ref ""
let main filename =
let dpy = openDisplay !dpyname in
let screen = defaultScreen dpy in
let root = defaultRoot dpy in
let cmap = defaultColormap dpy in
let depth = defaultDepth dpy in
let (dx,dy,_,pix,_) = Xpm.createPixmapFromFile dpy root cmap depth filename in
X.changeWindowAttributes dpy root [CWBackPixmap pix];
X.clearArea dpy root 0 0 0 0 false;
let prop = try X.internAtom dpy "_XSETROOT_ID" false with Not_found -> failwith "interAtom" in
let _ =
try
let gp = X.getProperty dpy root false prop anyPropertyType 0 4 in
if gp.gp_type = XA.xa_pixmap && gp.gp_format = 32 &&
gp.gp_length = 1 && gp.gp_left = 0 then
let pix = Xbuffer.getCard32 gp.gp_value 0 in
X.killClient dpy pix
with
Not_found -> ()
in
X.changeProperty dpy root PropModeReplace
prop XA.xa_pixmap 1 (let b = newString 1 in setEnum32 b 0 pix; b);
X.setCloseDownMode dpy RetainPermanent;
Xlib.closeDisplay dpy
let _ =
Arg.parse [
"-d", Arg.String (fun s -> dpyname := s), "display: set display";
] main "Usage: xpmroot filename.xpm"
|
012132dced70036031b74376c9e48eabd8fb630cbebed953cadda978967fd689 | kowainik/prolens | Prolens.hs | module Test.Prolens
( unitSpecs
) where
import Data.Function ((&))
import Test.Hspec (Spec, describe, it, shouldBe)
import Prolens (preview, set, view, (.~), (^.))
import Test.Data (Grade (..), gradeMark, gradeOther, me, nameL, _Mark)
unitSpecs :: Spec
unitSpecs = describe "Prolens unit tests" $ do
lensSpecs
prismSpecs
lensSpecs :: Spec
lensSpecs = describe "Lenses" $ do
describe "getter" $ do
it "should get name" $
view nameL me `shouldBe` "Veronika"
it "should get name with ^." $
(me ^. nameL) `shouldBe` "Veronika"
describe "setter" $ do
it "should set name" $
view nameL (set nameL "Dmitrii" me) `shouldBe` "Dmitrii"
it "should set name with .~" $
(me & nameL .~ "Dmitrii") ^. nameL `shouldBe` "Dmitrii"
prismSpecs :: Spec
prismSpecs = describe "Prisms" $ do
describe "preview" $ do
it "should get mark" $
preview _Mark gradeMark `shouldBe` Just 5
it "should not get mark" $
preview _Mark gradeOther `shouldBe` Nothing
describe "set" $ do
it "should get mark" $
set _Mark 4 gradeMark `shouldBe` Mark 4
it "should not get mark" $
set _Mark 4 gradeOther `shouldBe` gradeOther
| null | https://raw.githubusercontent.com/kowainik/prolens/5d0f9311c87f59b851f932e1e37b70d519f5c39e/test/Test/Prolens.hs | haskell | module Test.Prolens
( unitSpecs
) where
import Data.Function ((&))
import Test.Hspec (Spec, describe, it, shouldBe)
import Prolens (preview, set, view, (.~), (^.))
import Test.Data (Grade (..), gradeMark, gradeOther, me, nameL, _Mark)
unitSpecs :: Spec
unitSpecs = describe "Prolens unit tests" $ do
lensSpecs
prismSpecs
lensSpecs :: Spec
lensSpecs = describe "Lenses" $ do
describe "getter" $ do
it "should get name" $
view nameL me `shouldBe` "Veronika"
it "should get name with ^." $
(me ^. nameL) `shouldBe` "Veronika"
describe "setter" $ do
it "should set name" $
view nameL (set nameL "Dmitrii" me) `shouldBe` "Dmitrii"
it "should set name with .~" $
(me & nameL .~ "Dmitrii") ^. nameL `shouldBe` "Dmitrii"
prismSpecs :: Spec
prismSpecs = describe "Prisms" $ do
describe "preview" $ do
it "should get mark" $
preview _Mark gradeMark `shouldBe` Just 5
it "should not get mark" $
preview _Mark gradeOther `shouldBe` Nothing
describe "set" $ do
it "should get mark" $
set _Mark 4 gradeMark `shouldBe` Mark 4
it "should not get mark" $
set _Mark 4 gradeOther `shouldBe` gradeOther
| |
1ccb31d3d128d8af166534993ecdd440d5dc02bb1b0a6a20e18289efc99e7fa1 | corecursive/sicp-study-group | operation-test.scm | (load "type.scm")
(load "complex-package/rectangular.scm")
(load "complex-package/polar.scm")
(load "complex-package/operation.scm")
(install-rectangular-package)
(install-polar-package)
(define z1 (make-from-real-imag 1 2))
(define z2 (make-from-real-imag 2 1))
(assert (eq? 'rectangular (type z1)))
(assert (eq? 'rectangular (type z2)))
(assert (eq? 'rectangular (type (+c z1 z2))))
(assert (eq? 'rectangular (type (-c z1 z2))))
(assert (eq? 'polar (type (*c z1 z2))))
(assert (eq? 'polar (type (/c z1 z2))))
| null | https://raw.githubusercontent.com/corecursive/sicp-study-group/82b92a9759ed6c72d15cf955c806ce2a94336f83/wulab/lecture-4b/generic-operation/complex-package/operation-test.scm | scheme | (load "type.scm")
(load "complex-package/rectangular.scm")
(load "complex-package/polar.scm")
(load "complex-package/operation.scm")
(install-rectangular-package)
(install-polar-package)
(define z1 (make-from-real-imag 1 2))
(define z2 (make-from-real-imag 2 1))
(assert (eq? 'rectangular (type z1)))
(assert (eq? 'rectangular (type z2)))
(assert (eq? 'rectangular (type (+c z1 z2))))
(assert (eq? 'rectangular (type (-c z1 z2))))
(assert (eq? 'polar (type (*c z1 z2))))
(assert (eq? 'polar (type (/c z1 z2))))
| |
6024c51d6aa372453a9565ec9333390f3296ac4d64dfef0d72f5cba89f6bb30b | well-typed-lightbulbs/ocaml-esp32 | array.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
type 'a t = 'a array
(** An alias for the type of arrays. *)
(** Array operations. *)
external length : 'a array -> int = "%array_length"
(** Return the length (number of elements) of the given array. *)
external get : 'a array -> int -> 'a = "%array_safe_get"
* [ Array.get a n ] returns the element number [ n ] of array [ a ] .
The first element has number 0 .
The last element has number [ Array.length a - 1 ] .
You can also write [ a.(n ) ] instead of [ Array.get a n ] .
Raise [ Invalid_argument ]
if [ n ] is outside the range 0 to [ ( Array.length a - 1 ) ] .
The first element has number 0.
The last element has number [Array.length a - 1].
You can also write [a.(n)] instead of [Array.get a n].
Raise [Invalid_argument]
if [n] is outside the range 0 to [(Array.length a - 1)]. *)
external set : 'a array -> int -> 'a -> unit = "%array_safe_set"
* [ Array.set a n x ] modifies array [ a ] in place , replacing
element number [ n ] with [ x ] .
You can also write [ a.(n ) < - x ] instead of [ Array.set a n x ] .
Raise [ Invalid_argument ]
if [ n ] is outside the range 0 to [ Array.length a - 1 ] .
element number [n] with [x].
You can also write [a.(n) <- x] instead of [Array.set a n x].
Raise [Invalid_argument]
if [n] is outside the range 0 to [Array.length a - 1]. *)
external make : int -> 'a -> 'a array = "caml_make_vect"
* [ Array.make n x ] returns a fresh array of length [ n ] ,
initialized with [ x ] .
All the elements of this new array are initially
physically equal to [ x ] ( in the sense of the [= =] predicate ) .
Consequently , if [ x ] is mutable , it is shared among all elements
of the array , and modifying [ x ] through one of the array entries
will modify all other entries at the same time .
Raise [ Invalid_argument ] if [ n < 0 ] or [ n > Sys.max_array_length ] .
If the value of [ x ] is a floating - point number , then the maximum
size is only [ / 2 ] .
initialized with [x].
All the elements of this new array are initially
physically equal to [x] (in the sense of the [==] predicate).
Consequently, if [x] is mutable, it is shared among all elements
of the array, and modifying [x] through one of the array entries
will modify all other entries at the same time.
Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length].
If the value of [x] is a floating-point number, then the maximum
size is only [Sys.max_array_length / 2].*)
external create : int -> 'a -> 'a array = "caml_make_vect"
[@@ocaml.deprecated "Use Array.make instead."]
(** @deprecated [Array.create] is an alias for {!Array.make}. *)
external create_float: int -> float array = "caml_make_float_vect"
* [ n ] returns a fresh float array of length [ n ] ,
with uninitialized data .
@since 4.03
with uninitialized data.
@since 4.03 *)
val make_float: int -> float array
[@@ocaml.deprecated "Use Array.create_float instead."]
* @deprecated [ Array.make_float ] is an alias for { ! } .
val init : int -> (int -> 'a) -> 'a array
* [ Array.init n f ] returns a fresh array of length [ n ] ,
with element number [ i ] initialized to the result of [ f i ] .
In other terms , [ Array.init n f ] tabulates the results of [ f ]
applied to the integers [ 0 ] to [ n-1 ] .
Raise [ Invalid_argument ] if [ n < 0 ] or [ n > Sys.max_array_length ] .
If the return type of [ f ] is [ float ] , then the maximum
size is only [ / 2 ] .
with element number [i] initialized to the result of [f i].
In other terms, [Array.init n f] tabulates the results of [f]
applied to the integers [0] to [n-1].
Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length].
If the return type of [f] is [float], then the maximum
size is only [Sys.max_array_length / 2].*)
val make_matrix : int -> int -> 'a -> 'a array array
* [ Array.make_matrix dimx e ] returns a two - dimensional array
( an array of arrays ) with first dimension [ dimx ] and
second dimension [ dimy ] . All the elements of this new matrix
are initially physically equal to [ e ] .
The element ( [ x , y ] ) of a matrix [ m ] is accessed
with the notation [ m.(x).(y ) ] .
Raise [ Invalid_argument ] if [ dimx ] or [ dimy ] is negative or
greater than { ! } .
If the value of [ e ] is a floating - point number , then the maximum
size is only [ / 2 ] .
(an array of arrays) with first dimension [dimx] and
second dimension [dimy]. All the elements of this new matrix
are initially physically equal to [e].
The element ([x,y]) of a matrix [m] is accessed
with the notation [m.(x).(y)].
Raise [Invalid_argument] if [dimx] or [dimy] is negative or
greater than {!Sys.max_array_length}.
If the value of [e] is a floating-point number, then the maximum
size is only [Sys.max_array_length / 2]. *)
val create_matrix : int -> int -> 'a -> 'a array array
[@@ocaml.deprecated "Use Array.make_matrix instead."]
* @deprecated [ Array.create_matrix ] is an alias for { ! Array.make_matrix } .
val append : 'a array -> 'a array -> 'a array
(** [Array.append v1 v2] returns a fresh array containing the
concatenation of the arrays [v1] and [v2].
Raise [Invalid_argument] if
[Array.length v1 + Array.length v2 > Sys.max_array_length]. *)
val concat : 'a array list -> 'a array
(** Same as {!Array.append}, but concatenates a list of arrays. *)
val sub : 'a array -> int -> int -> 'a array
* [ Array.sub a start len ] returns a fresh array of length [ len ] ,
containing the elements number [ start ] to [ start + len - 1 ]
of array [ a ] .
Raise [ Invalid_argument ] if [ start ] and [ len ] do not
designate a valid subarray of [ a ] ; that is , if
[ start < 0 ] , or [ len < 0 ] , or [ start + len > Array.length a ] .
containing the elements number [start] to [start + len - 1]
of array [a].
Raise [Invalid_argument] if [start] and [len] do not
designate a valid subarray of [a]; that is, if
[start < 0], or [len < 0], or [start + len > Array.length a]. *)
val copy : 'a array -> 'a array
(** [Array.copy a] returns a copy of [a], that is, a fresh array
containing the same elements as [a]. *)
val fill : 'a array -> int -> int -> 'a -> unit
* [ Array.fill ] modifies the array [ a ] in place ,
storing [ x ] in elements number [ ofs ] to ] .
Raise [ Invalid_argument ] if [ ofs ] and [ len ] do not
designate a valid subarray of [ a ] .
storing [x] in elements number [ofs] to [ofs + len - 1].
Raise [Invalid_argument] if [ofs] and [len] do not
designate a valid subarray of [a]. *)
val blit : 'a array -> int -> 'a array -> int -> int -> unit
* [ Array.blit v1 o1 v2 o2 len ] copies [ len ] elements
from array [ v1 ] , starting at element number [ o1 ] , to array [ v2 ] ,
starting at element number [ o2 ] . It works correctly even if
[ v1 ] and [ v2 ] are the same array , and the source and
destination chunks overlap .
Raise [ Invalid_argument ] if [ o1 ] and [ len ] do not
designate a valid subarray of [ v1 ] , or if [ o2 ] and [ len ] do not
designate a valid subarray of [ v2 ] .
from array [v1], starting at element number [o1], to array [v2],
starting at element number [o2]. It works correctly even if
[v1] and [v2] are the same array, and the source and
destination chunks overlap.
Raise [Invalid_argument] if [o1] and [len] do not
designate a valid subarray of [v1], or if [o2] and [len] do not
designate a valid subarray of [v2]. *)
val to_list : 'a array -> 'a list
(** [Array.to_list a] returns the list of all the elements of [a]. *)
val of_list : 'a list -> 'a array
* [ Array.of_list l ] returns a fresh array containing the elements
of [ l ] .
Raise [ Invalid_argument ] if the length of [ l ] is greater than
[ ] .
of [l].
Raise [Invalid_argument] if the length of [l] is greater than
[Sys.max_array_length].*)
(** {1 Iterators} *)
val iter : ('a -> unit) -> 'a array -> unit
* [ Array.iter f a ] applies function [ f ] in turn to all
the elements of [ a ] . It is equivalent to
[ f ) ; f a.(1 ) ; ... ; f a.(Array.length a - 1 ) ; ( ) ] .
the elements of [a]. It is equivalent to
[f a.(0); f a.(1); ...; f a.(Array.length a - 1); ()]. *)
val iteri : (int -> 'a -> unit) -> 'a array -> unit
* Same as { ! Array.iter } , but the
function is applied with the index of the element as first argument ,
and the element itself as second argument .
function is applied with the index of the element as first argument,
and the element itself as second argument. *)
val map : ('a -> 'b) -> 'a array -> 'b array
* [ Array.map f a ] applies function [ f ] to all the elements of [ a ] ,
and builds an array with the results returned by [ f ] :
[ [ | f ) ; f a.(1 ) ; ... ; f a.(Array.length a - 1 ) | ] ] .
and builds an array with the results returned by [f]:
[[| f a.(0); f a.(1); ...; f a.(Array.length a - 1) |]]. *)
val mapi : (int -> 'a -> 'b) -> 'a array -> 'b array
* Same as { ! } , but the
function is applied to the index of the element as first argument ,
and the element itself as second argument .
function is applied to the index of the element as first argument,
and the element itself as second argument. *)
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b array -> 'a
* [ Array.fold_left f x a ] computes
[ f ( ... ( f ( f x ) ) a.(1 ) ) ... ) a.(n-1 ) ] ,
where [ n ] is the length of the array [ a ] .
[f (... (f (f x a.(0)) a.(1)) ...) a.(n-1)],
where [n] is the length of the array [a]. *)
val fold_right : ('b -> 'a -> 'a) -> 'b array -> 'a -> 'a
* [ Array.fold_right f a x ] computes
[ f ) ( f a.(1 ) ( ... ( f a.(n-1 ) x ) ... ) ) ] ,
where [ n ] is the length of the array [ a ] .
[f a.(0) (f a.(1) ( ... (f a.(n-1) x) ...))],
where [n] is the length of the array [a]. *)
* { 1 Iterators on two arrays }
val iter2 : ('a -> 'b -> unit) -> 'a array -> 'b array -> unit
* [ Array.iter2 f a b ] applies function [ f ] to all the elements of [ a ]
and [ b ] .
Raise [ Invalid_argument ] if the arrays are not the same size .
@since 4.03.0
and [b].
Raise [Invalid_argument] if the arrays are not the same size.
@since 4.03.0 *)
val map2 : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array
* [ Array.map2 f a b ] applies function [ f ] to all the elements of [ a ]
and [ b ] , and builds an array with the results returned by [ f ] :
[ [ | f a.(0 ) ) ; ... ; f a.(Array.length a - 1 ) b.(Array.length b - 1)| ] ] .
Raise [ Invalid_argument ] if the arrays are not the same size .
@since 4.03.0
and [b], and builds an array with the results returned by [f]:
[[| f a.(0) b.(0); ...; f a.(Array.length a - 1) b.(Array.length b - 1)|]].
Raise [Invalid_argument] if the arrays are not the same size.
@since 4.03.0 *)
(** {1 Array scanning} *)
val for_all : ('a -> bool) -> 'a array -> bool
* [ Array.for_all p [ |a1 ; ... ; an| ] ] checks if all elements of the array
satisfy the predicate [ p ] . That is , it returns
[ ( p a1 ) & & ( p a2 ) & & ... & & ( p an ) ] .
@since 4.03.0
satisfy the predicate [p]. That is, it returns
[(p a1) && (p a2) && ... && (p an)].
@since 4.03.0 *)
val exists : ('a -> bool) -> 'a array -> bool
* [ Array.exists p [ |a1 ; ... ; an| ] ] checks if at least one element of
the array satisfies the predicate [ p ] . That is , it returns
[ ( p a1 ) || ( p a2 ) || ... || ( p an ) ] .
@since 4.03.0
the array satisfies the predicate [p]. That is, it returns
[(p a1) || (p a2) || ... || (p an)].
@since 4.03.0 *)
val mem : 'a -> 'a array -> bool
* [ mem a l ] is true if and only if [ a ] is structurally equal
to an element of [ l ] ( i.e. there is an [ x ] in [ l ] such that
[ compare a x = 0 ] ) .
@since 4.03.0
to an element of [l] (i.e. there is an [x] in [l] such that
[compare a x = 0]).
@since 4.03.0 *)
val memq : 'a -> 'a array -> bool
* Same as { ! Array.mem } , but uses physical equality instead of structural
equality to compare elements .
@since 4.03.0
equality to compare elements.
@since 4.03.0 *)
(** {1 Sorting} *)
val sort : ('a -> 'a -> int) -> 'a array -> unit
* Sort an array in increasing order according to a comparison
function . The comparison function must return 0 if its arguments
compare as equal , a positive integer if the first is greater ,
and a negative integer if the first is smaller ( see below for a
complete specification ) . For example , { ! Stdlib.compare } is
a suitable comparison function . After calling [ Array.sort ] , the
array is sorted in place in increasing order .
[ Array.sort ] is guaranteed to run in constant heap space
and ( at most ) logarithmic stack space .
The current implementation uses Heap Sort . It runs in constant
stack space .
Specification of the comparison function :
Let [ a ] be the array and [ cmp ] the comparison function . The following
must be true for all [ x ] , [ y ] , [ z ] in [ a ] :
- [ cmp x y ] > 0 if and only if [ cmp y x ] < 0
- if [ cmp x y ] > = 0 and [ cmp y z ] > = 0 then [ cmp x z ] > = 0
When [ Array.sort ] returns , [ a ] contains the same elements as before ,
reordered in such a way that for all i and j valid indices of [ a ] :
- [ cmp a.(i ) ) ] > = 0 if and only if i > = j
function. The comparison function must return 0 if its arguments
compare as equal, a positive integer if the first is greater,
and a negative integer if the first is smaller (see below for a
complete specification). For example, {!Stdlib.compare} is
a suitable comparison function. After calling [Array.sort], the
array is sorted in place in increasing order.
[Array.sort] is guaranteed to run in constant heap space
and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant
stack space.
Specification of the comparison function:
Let [a] be the array and [cmp] the comparison function. The following
must be true for all [x], [y], [z] in [a] :
- [cmp x y] > 0 if and only if [cmp y x] < 0
- if [cmp x y] >= 0 and [cmp y z] >= 0 then [cmp x z] >= 0
When [Array.sort] returns, [a] contains the same elements as before,
reordered in such a way that for all i and j valid indices of [a] :
- [cmp a.(i) a.(j)] >= 0 if and only if i >= j
*)
val stable_sort : ('a -> 'a -> int) -> 'a array -> unit
* Same as { ! Array.sort } , but the sorting algorithm is stable ( i.e.
elements that compare equal are kept in their original order ) and
not guaranteed to run in constant heap space .
The current implementation uses Merge Sort . It uses a temporary
array of length [ ] , where [ n ] is the length of the array .
It is usually faster than the current implementation of { ! Array.sort } .
elements that compare equal are kept in their original order) and
not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary
array of length [n/2], where [n] is the length of the array.
It is usually faster than the current implementation of {!Array.sort}.
*)
val fast_sort : ('a -> 'a -> int) -> 'a array -> unit
(** Same as {!Array.sort} or {!Array.stable_sort}, whichever is faster
on typical input.
*)
(** {1 Iterators} *)
val to_seq : 'a array -> 'a Seq.t
* Iterate on the array , in increasing order . Modifications of the
array during iteration will be reflected in the iterator .
@since 4.07
array during iteration will be reflected in the iterator.
@since 4.07 *)
val to_seqi : 'a array -> (int * 'a) Seq.t
* Iterate on the array , in increasing order , yielding indices along elements .
Modifications of the array during iteration will be reflected in the
iterator .
@since 4.07
Modifications of the array during iteration will be reflected in the
iterator.
@since 4.07 *)
val of_seq : 'a Seq.t -> 'a array
* Create an array from the generator
@since 4.07
@since 4.07 *)
(**/**)
* { 1 Undocumented functions }
(* The following is for system use only. Do not call directly. *)
external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get"
external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set"
module Floatarray : sig
external create : int -> floatarray = "caml_floatarray_create"
external length : floatarray -> int = "%floatarray_length"
external get : floatarray -> int -> float = "%floatarray_safe_get"
external set : floatarray -> int -> float -> unit = "%floatarray_safe_set"
external unsafe_get : floatarray -> int -> float = "%floatarray_unsafe_get"
external unsafe_set : floatarray -> int -> float -> unit
= "%floatarray_unsafe_set"
end
| null | https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/stdlib/array.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* An alias for the type of arrays.
* Array operations.
* Return the length (number of elements) of the given array.
* @deprecated [Array.create] is an alias for {!Array.make}.
* [Array.append v1 v2] returns a fresh array containing the
concatenation of the arrays [v1] and [v2].
Raise [Invalid_argument] if
[Array.length v1 + Array.length v2 > Sys.max_array_length].
* Same as {!Array.append}, but concatenates a list of arrays.
* [Array.copy a] returns a copy of [a], that is, a fresh array
containing the same elements as [a].
* [Array.to_list a] returns the list of all the elements of [a].
* {1 Iterators}
* {1 Array scanning}
* {1 Sorting}
* Same as {!Array.sort} or {!Array.stable_sort}, whichever is faster
on typical input.
* {1 Iterators}
*/*
The following is for system use only. Do not call directly. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
type 'a t = 'a array
external length : 'a array -> int = "%array_length"
external get : 'a array -> int -> 'a = "%array_safe_get"
* [ Array.get a n ] returns the element number [ n ] of array [ a ] .
The first element has number 0 .
The last element has number [ Array.length a - 1 ] .
You can also write [ a.(n ) ] instead of [ Array.get a n ] .
Raise [ Invalid_argument ]
if [ n ] is outside the range 0 to [ ( Array.length a - 1 ) ] .
The first element has number 0.
The last element has number [Array.length a - 1].
You can also write [a.(n)] instead of [Array.get a n].
Raise [Invalid_argument]
if [n] is outside the range 0 to [(Array.length a - 1)]. *)
external set : 'a array -> int -> 'a -> unit = "%array_safe_set"
* [ Array.set a n x ] modifies array [ a ] in place , replacing
element number [ n ] with [ x ] .
You can also write [ a.(n ) < - x ] instead of [ Array.set a n x ] .
Raise [ Invalid_argument ]
if [ n ] is outside the range 0 to [ Array.length a - 1 ] .
element number [n] with [x].
You can also write [a.(n) <- x] instead of [Array.set a n x].
Raise [Invalid_argument]
if [n] is outside the range 0 to [Array.length a - 1]. *)
external make : int -> 'a -> 'a array = "caml_make_vect"
* [ Array.make n x ] returns a fresh array of length [ n ] ,
initialized with [ x ] .
All the elements of this new array are initially
physically equal to [ x ] ( in the sense of the [= =] predicate ) .
Consequently , if [ x ] is mutable , it is shared among all elements
of the array , and modifying [ x ] through one of the array entries
will modify all other entries at the same time .
Raise [ Invalid_argument ] if [ n < 0 ] or [ n > Sys.max_array_length ] .
If the value of [ x ] is a floating - point number , then the maximum
size is only [ / 2 ] .
initialized with [x].
All the elements of this new array are initially
physically equal to [x] (in the sense of the [==] predicate).
Consequently, if [x] is mutable, it is shared among all elements
of the array, and modifying [x] through one of the array entries
will modify all other entries at the same time.
Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length].
If the value of [x] is a floating-point number, then the maximum
size is only [Sys.max_array_length / 2].*)
external create : int -> 'a -> 'a array = "caml_make_vect"
[@@ocaml.deprecated "Use Array.make instead."]
external create_float: int -> float array = "caml_make_float_vect"
* [ n ] returns a fresh float array of length [ n ] ,
with uninitialized data .
@since 4.03
with uninitialized data.
@since 4.03 *)
val make_float: int -> float array
[@@ocaml.deprecated "Use Array.create_float instead."]
* @deprecated [ Array.make_float ] is an alias for { ! } .
val init : int -> (int -> 'a) -> 'a array
* [ Array.init n f ] returns a fresh array of length [ n ] ,
with element number [ i ] initialized to the result of [ f i ] .
In other terms , [ Array.init n f ] tabulates the results of [ f ]
applied to the integers [ 0 ] to [ n-1 ] .
Raise [ Invalid_argument ] if [ n < 0 ] or [ n > Sys.max_array_length ] .
If the return type of [ f ] is [ float ] , then the maximum
size is only [ / 2 ] .
with element number [i] initialized to the result of [f i].
In other terms, [Array.init n f] tabulates the results of [f]
applied to the integers [0] to [n-1].
Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length].
If the return type of [f] is [float], then the maximum
size is only [Sys.max_array_length / 2].*)
val make_matrix : int -> int -> 'a -> 'a array array
* [ Array.make_matrix dimx e ] returns a two - dimensional array
( an array of arrays ) with first dimension [ dimx ] and
second dimension [ dimy ] . All the elements of this new matrix
are initially physically equal to [ e ] .
The element ( [ x , y ] ) of a matrix [ m ] is accessed
with the notation [ m.(x).(y ) ] .
Raise [ Invalid_argument ] if [ dimx ] or [ dimy ] is negative or
greater than { ! } .
If the value of [ e ] is a floating - point number , then the maximum
size is only [ / 2 ] .
(an array of arrays) with first dimension [dimx] and
second dimension [dimy]. All the elements of this new matrix
are initially physically equal to [e].
The element ([x,y]) of a matrix [m] is accessed
with the notation [m.(x).(y)].
Raise [Invalid_argument] if [dimx] or [dimy] is negative or
greater than {!Sys.max_array_length}.
If the value of [e] is a floating-point number, then the maximum
size is only [Sys.max_array_length / 2]. *)
val create_matrix : int -> int -> 'a -> 'a array array
[@@ocaml.deprecated "Use Array.make_matrix instead."]
* @deprecated [ Array.create_matrix ] is an alias for { ! Array.make_matrix } .
val append : 'a array -> 'a array -> 'a array
val concat : 'a array list -> 'a array
val sub : 'a array -> int -> int -> 'a array
* [ Array.sub a start len ] returns a fresh array of length [ len ] ,
containing the elements number [ start ] to [ start + len - 1 ]
of array [ a ] .
Raise [ Invalid_argument ] if [ start ] and [ len ] do not
designate a valid subarray of [ a ] ; that is , if
[ start < 0 ] , or [ len < 0 ] , or [ start + len > Array.length a ] .
containing the elements number [start] to [start + len - 1]
of array [a].
Raise [Invalid_argument] if [start] and [len] do not
designate a valid subarray of [a]; that is, if
[start < 0], or [len < 0], or [start + len > Array.length a]. *)
val copy : 'a array -> 'a array
val fill : 'a array -> int -> int -> 'a -> unit
* [ Array.fill ] modifies the array [ a ] in place ,
storing [ x ] in elements number [ ofs ] to ] .
Raise [ Invalid_argument ] if [ ofs ] and [ len ] do not
designate a valid subarray of [ a ] .
storing [x] in elements number [ofs] to [ofs + len - 1].
Raise [Invalid_argument] if [ofs] and [len] do not
designate a valid subarray of [a]. *)
val blit : 'a array -> int -> 'a array -> int -> int -> unit
* [ Array.blit v1 o1 v2 o2 len ] copies [ len ] elements
from array [ v1 ] , starting at element number [ o1 ] , to array [ v2 ] ,
starting at element number [ o2 ] . It works correctly even if
[ v1 ] and [ v2 ] are the same array , and the source and
destination chunks overlap .
Raise [ Invalid_argument ] if [ o1 ] and [ len ] do not
designate a valid subarray of [ v1 ] , or if [ o2 ] and [ len ] do not
designate a valid subarray of [ v2 ] .
from array [v1], starting at element number [o1], to array [v2],
starting at element number [o2]. It works correctly even if
[v1] and [v2] are the same array, and the source and
destination chunks overlap.
Raise [Invalid_argument] if [o1] and [len] do not
designate a valid subarray of [v1], or if [o2] and [len] do not
designate a valid subarray of [v2]. *)
val to_list : 'a array -> 'a list
val of_list : 'a list -> 'a array
* [ Array.of_list l ] returns a fresh array containing the elements
of [ l ] .
Raise [ Invalid_argument ] if the length of [ l ] is greater than
[ ] .
of [l].
Raise [Invalid_argument] if the length of [l] is greater than
[Sys.max_array_length].*)
val iter : ('a -> unit) -> 'a array -> unit
* [ Array.iter f a ] applies function [ f ] in turn to all
the elements of [ a ] . It is equivalent to
[ f ) ; f a.(1 ) ; ... ; f a.(Array.length a - 1 ) ; ( ) ] .
the elements of [a]. It is equivalent to
[f a.(0); f a.(1); ...; f a.(Array.length a - 1); ()]. *)
val iteri : (int -> 'a -> unit) -> 'a array -> unit
* Same as { ! Array.iter } , but the
function is applied with the index of the element as first argument ,
and the element itself as second argument .
function is applied with the index of the element as first argument,
and the element itself as second argument. *)
val map : ('a -> 'b) -> 'a array -> 'b array
* [ Array.map f a ] applies function [ f ] to all the elements of [ a ] ,
and builds an array with the results returned by [ f ] :
[ [ | f ) ; f a.(1 ) ; ... ; f a.(Array.length a - 1 ) | ] ] .
and builds an array with the results returned by [f]:
[[| f a.(0); f a.(1); ...; f a.(Array.length a - 1) |]]. *)
val mapi : (int -> 'a -> 'b) -> 'a array -> 'b array
* Same as { ! } , but the
function is applied to the index of the element as first argument ,
and the element itself as second argument .
function is applied to the index of the element as first argument,
and the element itself as second argument. *)
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b array -> 'a
* [ Array.fold_left f x a ] computes
[ f ( ... ( f ( f x ) ) a.(1 ) ) ... ) a.(n-1 ) ] ,
where [ n ] is the length of the array [ a ] .
[f (... (f (f x a.(0)) a.(1)) ...) a.(n-1)],
where [n] is the length of the array [a]. *)
val fold_right : ('b -> 'a -> 'a) -> 'b array -> 'a -> 'a
* [ Array.fold_right f a x ] computes
[ f ) ( f a.(1 ) ( ... ( f a.(n-1 ) x ) ... ) ) ] ,
where [ n ] is the length of the array [ a ] .
[f a.(0) (f a.(1) ( ... (f a.(n-1) x) ...))],
where [n] is the length of the array [a]. *)
* { 1 Iterators on two arrays }
val iter2 : ('a -> 'b -> unit) -> 'a array -> 'b array -> unit
* [ Array.iter2 f a b ] applies function [ f ] to all the elements of [ a ]
and [ b ] .
Raise [ Invalid_argument ] if the arrays are not the same size .
@since 4.03.0
and [b].
Raise [Invalid_argument] if the arrays are not the same size.
@since 4.03.0 *)
val map2 : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array
* [ Array.map2 f a b ] applies function [ f ] to all the elements of [ a ]
and [ b ] , and builds an array with the results returned by [ f ] :
[ [ | f a.(0 ) ) ; ... ; f a.(Array.length a - 1 ) b.(Array.length b - 1)| ] ] .
Raise [ Invalid_argument ] if the arrays are not the same size .
@since 4.03.0
and [b], and builds an array with the results returned by [f]:
[[| f a.(0) b.(0); ...; f a.(Array.length a - 1) b.(Array.length b - 1)|]].
Raise [Invalid_argument] if the arrays are not the same size.
@since 4.03.0 *)
val for_all : ('a -> bool) -> 'a array -> bool
* [ Array.for_all p [ |a1 ; ... ; an| ] ] checks if all elements of the array
satisfy the predicate [ p ] . That is , it returns
[ ( p a1 ) & & ( p a2 ) & & ... & & ( p an ) ] .
@since 4.03.0
satisfy the predicate [p]. That is, it returns
[(p a1) && (p a2) && ... && (p an)].
@since 4.03.0 *)
val exists : ('a -> bool) -> 'a array -> bool
* [ Array.exists p [ |a1 ; ... ; an| ] ] checks if at least one element of
the array satisfies the predicate [ p ] . That is , it returns
[ ( p a1 ) || ( p a2 ) || ... || ( p an ) ] .
@since 4.03.0
the array satisfies the predicate [p]. That is, it returns
[(p a1) || (p a2) || ... || (p an)].
@since 4.03.0 *)
val mem : 'a -> 'a array -> bool
* [ mem a l ] is true if and only if [ a ] is structurally equal
to an element of [ l ] ( i.e. there is an [ x ] in [ l ] such that
[ compare a x = 0 ] ) .
@since 4.03.0
to an element of [l] (i.e. there is an [x] in [l] such that
[compare a x = 0]).
@since 4.03.0 *)
val memq : 'a -> 'a array -> bool
* Same as { ! Array.mem } , but uses physical equality instead of structural
equality to compare elements .
@since 4.03.0
equality to compare elements.
@since 4.03.0 *)
val sort : ('a -> 'a -> int) -> 'a array -> unit
* Sort an array in increasing order according to a comparison
function . The comparison function must return 0 if its arguments
compare as equal , a positive integer if the first is greater ,
and a negative integer if the first is smaller ( see below for a
complete specification ) . For example , { ! Stdlib.compare } is
a suitable comparison function . After calling [ Array.sort ] , the
array is sorted in place in increasing order .
[ Array.sort ] is guaranteed to run in constant heap space
and ( at most ) logarithmic stack space .
The current implementation uses Heap Sort . It runs in constant
stack space .
Specification of the comparison function :
Let [ a ] be the array and [ cmp ] the comparison function . The following
must be true for all [ x ] , [ y ] , [ z ] in [ a ] :
- [ cmp x y ] > 0 if and only if [ cmp y x ] < 0
- if [ cmp x y ] > = 0 and [ cmp y z ] > = 0 then [ cmp x z ] > = 0
When [ Array.sort ] returns , [ a ] contains the same elements as before ,
reordered in such a way that for all i and j valid indices of [ a ] :
- [ cmp a.(i ) ) ] > = 0 if and only if i > = j
function. The comparison function must return 0 if its arguments
compare as equal, a positive integer if the first is greater,
and a negative integer if the first is smaller (see below for a
complete specification). For example, {!Stdlib.compare} is
a suitable comparison function. After calling [Array.sort], the
array is sorted in place in increasing order.
[Array.sort] is guaranteed to run in constant heap space
and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant
stack space.
Specification of the comparison function:
Let [a] be the array and [cmp] the comparison function. The following
must be true for all [x], [y], [z] in [a] :
- [cmp x y] > 0 if and only if [cmp y x] < 0
- if [cmp x y] >= 0 and [cmp y z] >= 0 then [cmp x z] >= 0
When [Array.sort] returns, [a] contains the same elements as before,
reordered in such a way that for all i and j valid indices of [a] :
- [cmp a.(i) a.(j)] >= 0 if and only if i >= j
*)
val stable_sort : ('a -> 'a -> int) -> 'a array -> unit
* Same as { ! Array.sort } , but the sorting algorithm is stable ( i.e.
elements that compare equal are kept in their original order ) and
not guaranteed to run in constant heap space .
The current implementation uses Merge Sort . It uses a temporary
array of length [ ] , where [ n ] is the length of the array .
It is usually faster than the current implementation of { ! Array.sort } .
elements that compare equal are kept in their original order) and
not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary
array of length [n/2], where [n] is the length of the array.
It is usually faster than the current implementation of {!Array.sort}.
*)
val fast_sort : ('a -> 'a -> int) -> 'a array -> unit
val to_seq : 'a array -> 'a Seq.t
* Iterate on the array , in increasing order . Modifications of the
array during iteration will be reflected in the iterator .
@since 4.07
array during iteration will be reflected in the iterator.
@since 4.07 *)
val to_seqi : 'a array -> (int * 'a) Seq.t
* Iterate on the array , in increasing order , yielding indices along elements .
Modifications of the array during iteration will be reflected in the
iterator .
@since 4.07
Modifications of the array during iteration will be reflected in the
iterator.
@since 4.07 *)
val of_seq : 'a Seq.t -> 'a array
* Create an array from the generator
@since 4.07
@since 4.07 *)
* { 1 Undocumented functions }
external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get"
external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set"
module Floatarray : sig
external create : int -> floatarray = "caml_floatarray_create"
external length : floatarray -> int = "%floatarray_length"
external get : floatarray -> int -> float = "%floatarray_safe_get"
external set : floatarray -> int -> float -> unit = "%floatarray_safe_set"
external unsafe_get : floatarray -> int -> float = "%floatarray_unsafe_get"
external unsafe_set : floatarray -> int -> float -> unit
= "%floatarray_unsafe_set"
end
|
462bbdcc63ee34f554a8f8ef93aa497eb74104031e1569acbaddbb6c212c5c71 | codinuum/cca | xchannel.ml |
Copyright 2012 - 2020 Codinuum Software Lab < >
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2012-2020 Codinuum Software Lab <>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
(* xchannel.ml *)
module C = Compression
exception Error of string
exception File_exists of string
exception File_not_found of string
let sprintf = Printf.sprintf
(* output channel *)
module Destination = struct
type t =
| File of string
| Buffer of Buffer.t
| Channel of out_channel
let of_file f = File f
let of_buffer b = Buffer b
let of_channel ch = Channel ch
let to_string = function
| File s -> sprintf "<file:%s>" s
| Buffer _ -> "<buffer>"
| Channel _ -> "<out_channel>"
end
module D = Destination
class out_channel ?(overwrite=true) ?(comp=C.none) dest
=
object (self)
val mutable extchs = []
val mutable och = Obj.magic ()
method private close_extra =
List.iter (fun c -> c#close_out()) extchs
initializer
let ooch =
try
if comp = C.none then begin
match dest with
| D.File file -> begin
if Sys.file_exists file && not overwrite then
raise (File_exists file)
else
new Netchannels.output_channel (open_out file)
end
| D.Buffer buf -> new Netchannels.output_buffer buf
| D.Channel ch -> new Netchannels.output_channel ch
end
else if comp = C.gzip then begin
let lv = comp#level in
match dest with
| D.File file -> begin
if Sys.file_exists file && not overwrite then
raise (File_exists file)
else
let go = Gzip.open_out ~level:lv file in
new Netgzip.output_gzip go
end
| D.Buffer buf ->
let c = new Netchannels.output_buffer buf in
extchs <- c :: extchs;
let pipe = new Netgzip.deflating_pipe ~level:lv () in
new Netchannels.output_filter pipe c
| D.Channel ch ->
let c = new Netchannels.output_channel ch in
extchs <- c :: extchs;
let pipe = new Netgzip.deflating_pipe ~level:lv () in
new Netchannels.output_filter pipe c
end
else
raise (Error "unknown compression")
with
| File_exists s -> raise (File_exists s)
| e -> raise (Error (Printexc.to_string e))
in
och <- ooch
method out_obj_channel = och
method flush =
och#flush()
method output (buf : bytes) pos len =
try
och#output buf pos len
with
| e -> raise (Error (Printexc.to_string e))
method output_ (buf : string) pos len =
try
och#output (Bytes.of_string buf) pos len
with
| e -> raise (Error (Printexc.to_string e))
method close =
try
och#close_out();
self#close_extra
with
| e -> raise (Error (Printexc.to_string e))
end (* of class Xchannel.out_channel *)
let output_bytes (ch : out_channel) b =
ignore (ch#output b 0 (Bytes.length b))
let output_string (ch : out_channel) s =
let b = Bytes.of_string s in
output_bytes ch b
let fprintf ch fmt = Printf.ksprintf (output_string ch) fmt
let dump : ?comp:C.c -> ?add_ext:bool -> string -> ('och -> unit) -> unit =
fun ?(comp=C.none) ?(add_ext=true) fname dumper ->
let fname =
if add_ext then
fname^comp#ext
else
fname
in
try
let dest = Destination.of_file fname in
let ch = new out_channel ~comp dest in
begin
try
dumper ch
with
| Error s -> WARN_MSG s
end;
try
ch#close
with
| Error s -> WARN_MSG s
with
| Error s -> WARN_MSG s
(* input channel *)
module Source = struct
type t =
| File of string
| Channel of in_channel
let of_file f = File f
let of_channel ch = Channel ch
let to_string = function
| File s -> sprintf "<file:%s>" s
| Channel _ -> "<in_channel>"
end
module S = Source
class in_channel ?(comp=C.none) source
=
object (self)
val mutable extchs = []
val mutable ich = Obj.magic ()
method close_extra =
List.iter (fun c -> c#close_in()) extchs
initializer
let ioch =
try
if comp = C.none then begin
match source with
| S.File file -> begin
if not (Sys.file_exists file) then
raise (File_not_found file)
else
new Netchannels.input_channel (open_in file)
end
| S.Channel ch -> new Netchannels.input_channel ch
end
else if comp = C.gzip then begin
match source with
| S.File file -> begin
if Sys.file_exists file then
let gi = Gzip.open_in file in
new Netgzip.input_gzip gi
else
raise (File_not_found file)
end
| S.Channel ch ->
let c = new Netchannels.input_channel ch in
extchs <- c :: extchs;
let pipe = new Netgzip.inflating_pipe () in
new Netchannels.input_filter c pipe
end
else
raise (Error "unknown compression")
with
| File_exists s -> raise (File_exists s)
| File_not_found s -> raise (File_not_found s)
| e -> raise (Error (Printexc.to_string e))
in
ich <- ioch
method in_obj_channel = ich
method input buf pos len =
try
ich#input buf pos len
with
| e -> raise (Error (Printexc.to_string e))
method close =
try
ich#close_in();
self#close_extra
with
| e -> raise (Error (Printexc.to_string e))
of class Xchannel.in_channel
| null | https://raw.githubusercontent.com/codinuum/cca/88ea07f3fe3671b78518769d804fdebabcd28e90/src/util/xchannel.ml | ocaml | xchannel.ml
output channel
of class Xchannel.out_channel
input channel |
Copyright 2012 - 2020 Codinuum Software Lab < >
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2012-2020 Codinuum Software Lab <>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module C = Compression
exception Error of string
exception File_exists of string
exception File_not_found of string
let sprintf = Printf.sprintf
module Destination = struct
type t =
| File of string
| Buffer of Buffer.t
| Channel of out_channel
let of_file f = File f
let of_buffer b = Buffer b
let of_channel ch = Channel ch
let to_string = function
| File s -> sprintf "<file:%s>" s
| Buffer _ -> "<buffer>"
| Channel _ -> "<out_channel>"
end
module D = Destination
class out_channel ?(overwrite=true) ?(comp=C.none) dest
=
object (self)
val mutable extchs = []
val mutable och = Obj.magic ()
method private close_extra =
List.iter (fun c -> c#close_out()) extchs
initializer
let ooch =
try
if comp = C.none then begin
match dest with
| D.File file -> begin
if Sys.file_exists file && not overwrite then
raise (File_exists file)
else
new Netchannels.output_channel (open_out file)
end
| D.Buffer buf -> new Netchannels.output_buffer buf
| D.Channel ch -> new Netchannels.output_channel ch
end
else if comp = C.gzip then begin
let lv = comp#level in
match dest with
| D.File file -> begin
if Sys.file_exists file && not overwrite then
raise (File_exists file)
else
let go = Gzip.open_out ~level:lv file in
new Netgzip.output_gzip go
end
| D.Buffer buf ->
let c = new Netchannels.output_buffer buf in
extchs <- c :: extchs;
let pipe = new Netgzip.deflating_pipe ~level:lv () in
new Netchannels.output_filter pipe c
| D.Channel ch ->
let c = new Netchannels.output_channel ch in
extchs <- c :: extchs;
let pipe = new Netgzip.deflating_pipe ~level:lv () in
new Netchannels.output_filter pipe c
end
else
raise (Error "unknown compression")
with
| File_exists s -> raise (File_exists s)
| e -> raise (Error (Printexc.to_string e))
in
och <- ooch
method out_obj_channel = och
method flush =
och#flush()
method output (buf : bytes) pos len =
try
och#output buf pos len
with
| e -> raise (Error (Printexc.to_string e))
method output_ (buf : string) pos len =
try
och#output (Bytes.of_string buf) pos len
with
| e -> raise (Error (Printexc.to_string e))
method close =
try
och#close_out();
self#close_extra
with
| e -> raise (Error (Printexc.to_string e))
let output_bytes (ch : out_channel) b =
ignore (ch#output b 0 (Bytes.length b))
let output_string (ch : out_channel) s =
let b = Bytes.of_string s in
output_bytes ch b
let fprintf ch fmt = Printf.ksprintf (output_string ch) fmt
let dump : ?comp:C.c -> ?add_ext:bool -> string -> ('och -> unit) -> unit =
fun ?(comp=C.none) ?(add_ext=true) fname dumper ->
let fname =
if add_ext then
fname^comp#ext
else
fname
in
try
let dest = Destination.of_file fname in
let ch = new out_channel ~comp dest in
begin
try
dumper ch
with
| Error s -> WARN_MSG s
end;
try
ch#close
with
| Error s -> WARN_MSG s
with
| Error s -> WARN_MSG s
module Source = struct
type t =
| File of string
| Channel of in_channel
let of_file f = File f
let of_channel ch = Channel ch
let to_string = function
| File s -> sprintf "<file:%s>" s
| Channel _ -> "<in_channel>"
end
module S = Source
class in_channel ?(comp=C.none) source
=
object (self)
val mutable extchs = []
val mutable ich = Obj.magic ()
method close_extra =
List.iter (fun c -> c#close_in()) extchs
initializer
let ioch =
try
if comp = C.none then begin
match source with
| S.File file -> begin
if not (Sys.file_exists file) then
raise (File_not_found file)
else
new Netchannels.input_channel (open_in file)
end
| S.Channel ch -> new Netchannels.input_channel ch
end
else if comp = C.gzip then begin
match source with
| S.File file -> begin
if Sys.file_exists file then
let gi = Gzip.open_in file in
new Netgzip.input_gzip gi
else
raise (File_not_found file)
end
| S.Channel ch ->
let c = new Netchannels.input_channel ch in
extchs <- c :: extchs;
let pipe = new Netgzip.inflating_pipe () in
new Netchannels.input_filter c pipe
end
else
raise (Error "unknown compression")
with
| File_exists s -> raise (File_exists s)
| File_not_found s -> raise (File_not_found s)
| e -> raise (Error (Printexc.to_string e))
in
ich <- ioch
method in_obj_channel = ich
method input buf pos len =
try
ich#input buf pos len
with
| e -> raise (Error (Printexc.to_string e))
method close =
try
ich#close_in();
self#close_extra
with
| e -> raise (Error (Printexc.to_string e))
of class Xchannel.in_channel
|
1c487c02fbc1cb5ba2075ad11e53bc23aa848b34627a8555b323925d7e180302 | Incanus3/ExiL | env-rules.lisp | (in-package :exil-env)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; RULES
(defun add-rule%% (env rule)
(add-rule% env rule)
(new-production (rete env) rule)
(when (watched-p env :rules)
(fresh-format t "==> ~A" rule))
(dolist (fact (facts env))
(add-wme (rete env) fact))
(notify env))
(defun rule-already-there (env rule)
(let ((orig-rule (find-rule env (name rule))))
(and orig-rule (rule-equal-p orig-rule rule))))
; public
(defmethod add-rule ((env environment) (rule rule) &optional
(undo-label "(add-rule)"))
(unless (rule-already-there env rule)
(with-saved-slots env (rules rete agenda) undo-label
(add-rule%% env rule)))
nil)
(defun rem-rule%% (env name rule)
(when (watched-p env :rules)
(format t "<== ~A" rule))
(rem-rule% env name)
(remove-production (rete env) rule)
(rem-matches-with-rule env rule)
(notify env))
; public
(defmethod rem-rule ((env environment) (name symbol) &optional
(undo-label "(rem-rule)"))
(let ((rule (find-rule env name)))
(when rule
(with-saved-slots env (rules rete agenda) undo-label
(rem-rule%% env name rule)))))
| null | https://raw.githubusercontent.com/Incanus3/ExiL/de0f7c37538cecb7032cc1f2aa070524b0bc048d/src/environment/env-rules.lisp | lisp |
RULES
public
public | (in-package :exil-env)
(defun add-rule%% (env rule)
(add-rule% env rule)
(new-production (rete env) rule)
(when (watched-p env :rules)
(fresh-format t "==> ~A" rule))
(dolist (fact (facts env))
(add-wme (rete env) fact))
(notify env))
(defun rule-already-there (env rule)
(let ((orig-rule (find-rule env (name rule))))
(and orig-rule (rule-equal-p orig-rule rule))))
(defmethod add-rule ((env environment) (rule rule) &optional
(undo-label "(add-rule)"))
(unless (rule-already-there env rule)
(with-saved-slots env (rules rete agenda) undo-label
(add-rule%% env rule)))
nil)
(defun rem-rule%% (env name rule)
(when (watched-p env :rules)
(format t "<== ~A" rule))
(rem-rule% env name)
(remove-production (rete env) rule)
(rem-matches-with-rule env rule)
(notify env))
(defmethod rem-rule ((env environment) (name symbol) &optional
(undo-label "(rem-rule)"))
(let ((rule (find-rule env name)))
(when rule
(with-saved-slots env (rules rete agenda) undo-label
(rem-rule%% env name rule)))))
|
e75f268faf329dafb4d8e097a41e7b64fed60cb6e03a55cd4daf5dc14b99db1a | ocaml-ppx/ocamlformat | Chunk.ml | (**************************************************************************)
(* *)
(* OCamlFormat *)
(* *)
Copyright ( c ) Facebook , Inc. and its affiliates .
(* *)
This source code is licensed under the MIT license found in
(* the LICENSE file in the root directory of this source tree. *)
(* *)
(**************************************************************************)
open Extended_ast
type state = Enable | Disable of Location.t
type 'a t =
| Structure : structure t
| Signature : signature t
| Use_file : use_file t
let update_conf ?quiet c l = List.fold ~init:c l ~f:(Conf.update ?quiet)
let disabling (c : Conf.t) attr =
(not c.opr_opts.disable.v)
&& (update_conf ~quiet:true c [attr]).opr_opts.disable.v
let enabling (c : Conf.t) attr =
c.opr_opts.disable.v
&& not (update_conf ~quiet:true c [attr]).opr_opts.disable.v
let init_loc =
let pos =
Lexing.
{pos_cnum= 0; pos_bol= 0; pos_lnum= 0; pos_fname= !Location.input_name}
in
Location.{loc_ghost= false; loc_start= pos; loc_end= pos}
let is_attr (type a) (fg : a list t) (x : a) =
match (fg, x) with
| Structure, {pstr_desc= Pstr_attribute x; pstr_loc} -> Some (x, pstr_loc)
| Signature, {psig_desc= Psig_attribute x; psig_loc} -> Some (x, psig_loc)
| Use_file, Ptop_def ({pstr_desc= Pstr_attribute x; pstr_loc} :: _) ->
Some (x, pstr_loc)
| _ -> None
let is_state_attr fg ~f c x =
match is_attr fg x with
| Some (attr, loc) when f c attr -> Some loc
| _ -> None
let split fg c l =
List.fold_left l ~init:([], c) ~f:(fun (acc, c) x ->
match is_state_attr fg ~f:disabling c x with
| Some loc -> ((Disable loc, [x]) :: acc, Conf.update_state c `Disable)
| None -> (
match is_state_attr fg ~f:enabling c x with
| Some _ -> ((Enable, [x]) :: acc, Conf.update_state c `Enable)
| None -> (
match acc with
| [] ->
let chunk =
if c.opr_opts.disable.v then (Disable init_loc, [x])
else (Enable, [x])
in
(chunk :: acc, c)
| (st, h) :: t -> ((st, x :: h) :: t, c) ) ) )
|> fst
|> List.rev_map ~f:(function state, lx -> (state, List.rev lx))
| null | https://raw.githubusercontent.com/ocaml-ppx/ocamlformat/70f897a5aa88f8cc52e2a5bba330752d27359145/lib/Chunk.ml | ocaml | ************************************************************************
OCamlFormat
the LICENSE file in the root directory of this source tree.
************************************************************************ | Copyright ( c ) Facebook , Inc. and its affiliates .
This source code is licensed under the MIT license found in
open Extended_ast
type state = Enable | Disable of Location.t
type 'a t =
| Structure : structure t
| Signature : signature t
| Use_file : use_file t
let update_conf ?quiet c l = List.fold ~init:c l ~f:(Conf.update ?quiet)
let disabling (c : Conf.t) attr =
(not c.opr_opts.disable.v)
&& (update_conf ~quiet:true c [attr]).opr_opts.disable.v
let enabling (c : Conf.t) attr =
c.opr_opts.disable.v
&& not (update_conf ~quiet:true c [attr]).opr_opts.disable.v
let init_loc =
let pos =
Lexing.
{pos_cnum= 0; pos_bol= 0; pos_lnum= 0; pos_fname= !Location.input_name}
in
Location.{loc_ghost= false; loc_start= pos; loc_end= pos}
let is_attr (type a) (fg : a list t) (x : a) =
match (fg, x) with
| Structure, {pstr_desc= Pstr_attribute x; pstr_loc} -> Some (x, pstr_loc)
| Signature, {psig_desc= Psig_attribute x; psig_loc} -> Some (x, psig_loc)
| Use_file, Ptop_def ({pstr_desc= Pstr_attribute x; pstr_loc} :: _) ->
Some (x, pstr_loc)
| _ -> None
let is_state_attr fg ~f c x =
match is_attr fg x with
| Some (attr, loc) when f c attr -> Some loc
| _ -> None
let split fg c l =
List.fold_left l ~init:([], c) ~f:(fun (acc, c) x ->
match is_state_attr fg ~f:disabling c x with
| Some loc -> ((Disable loc, [x]) :: acc, Conf.update_state c `Disable)
| None -> (
match is_state_attr fg ~f:enabling c x with
| Some _ -> ((Enable, [x]) :: acc, Conf.update_state c `Enable)
| None -> (
match acc with
| [] ->
let chunk =
if c.opr_opts.disable.v then (Disable init_loc, [x])
else (Enable, [x])
in
(chunk :: acc, c)
| (st, h) :: t -> ((st, x :: h) :: t, c) ) ) )
|> fst
|> List.rev_map ~f:(function state, lx -> (state, List.rev lx))
|
a20301dd3ef70dd79ecb24a08a7f077c347b1895ff12d5a05d356410f82ab066 | conscell/hugs-android | SizedSeq.hs | Copyright ( c ) 1998 - 1999 .
-- See COPYRIGHT file for terms and conditions.
module SizedSeq
{-# DEPRECATED "This module is unmaintained, and will disappear soon" #-}
(
-- generic adaptor for sequences to keep track of the current size
Sized s instance of Sequence , Functor , Monad , MonadPlus
-- sequence operations
empty,single,cons,snoc,append,lview,lhead,ltail,rview,rhead,rtail,
null,size,concat,reverse,reverseOnto,fromList,toList,
map,concatMap,foldr,foldl,foldr1,foldl1,reducer,reducel,reduce1,
copy,tabulate,inBounds,lookup,lookupM,lookupWithDefault,update,adjust,
mapWithIndex,foldrWithIndex,foldlWithIndex,
take,drop,splitAt,subseq,filter,partition,takeWhile,dropWhile,splitWhile,
zip,zip3,zipWith,zipWith3,unzip,unzip3,unzipWith,unzipWith3,
-- documentation
moduleName,instanceName,
-- other supported operations
fromSeq,toSeq,
re - export view type from EdisonPrelude for convenience
Maybe2(Just2,Nothing2)
) where
import Prelude hiding (concat,reverse,map,concatMap,foldr,foldl,foldr1,foldl1,
filter,takeWhile,dropWhile,lookup,take,drop,splitAt,
zip,zip3,zipWith,zipWith3,unzip,unzip3,null)
import EdisonPrelude(Maybe2(Just2,Nothing2))
import qualified Sequence as S ( Sequence(..) )
import qualified Sequence as S
import SequenceDefaults -- only used by concatMap
import Monad
import QuickCheck
This module defines a sequence adaptor
-- If s is a sequence type constructor, then Sized s
-- is a sequence type constructor that is identical to s,
-- except that it also keeps track of the current size of
-- each sequence.
-- signatures for exported functions
moduleName :: String
instanceName :: S.Sequence s => Sized s a -> String
empty :: S.Sequence s => Sized s a
single :: S.Sequence s => a -> Sized s a
cons :: S.Sequence s => a -> Sized s a -> Sized s a
snoc :: S.Sequence s => Sized s a -> a -> Sized s a
append :: S.Sequence s => Sized s a -> Sized s a -> Sized s a
lview :: S.Sequence s => Sized s a -> Maybe2 a (Sized s a)
lhead :: S.Sequence s => Sized s a -> a
ltail :: S.Sequence s => Sized s a -> Sized s a
rview :: S.Sequence s => Sized s a -> Maybe2 (Sized s a) a
rhead :: S.Sequence s => Sized s a -> a
rtail :: S.Sequence s => Sized s a -> Sized s a
null :: S.Sequence s => Sized s a -> Bool
size :: S.Sequence s => Sized s a -> Int
concat :: S.Sequence s => Sized s (Sized s a) -> Sized s a
reverse :: S.Sequence s => Sized s a -> Sized s a
reverseOnto :: S.Sequence s => Sized s a -> Sized s a -> Sized s a
fromList :: S.Sequence s => [a] -> Sized s a
toList :: S.Sequence s => Sized s a -> [a]
map :: S.Sequence s => (a -> b) -> Sized s a -> Sized s b
concatMap :: S.Sequence s => (a -> Sized s b) -> Sized s a -> Sized s b
foldr :: S.Sequence s => (a -> b -> b) -> b -> Sized s a -> b
foldl :: S.Sequence s => (b -> a -> b) -> b -> Sized s a -> b
foldr1 :: S.Sequence s => (a -> a -> a) -> Sized s a -> a
foldl1 :: S.Sequence s => (a -> a -> a) -> Sized s a -> a
reducer :: S.Sequence s => (a -> a -> a) -> a -> Sized s a -> a
reducel :: S.Sequence s => (a -> a -> a) -> a -> Sized s a -> a
reduce1 :: S.Sequence s => (a -> a -> a) -> Sized s a -> a
copy :: S.Sequence s => Int -> a -> Sized s a
tabulate :: S.Sequence s => Int -> (Int -> a) -> Sized s a
inBounds :: S.Sequence s => Sized s a -> Int -> Bool
lookup :: S.Sequence s => Sized s a -> Int -> a
lookupM :: S.Sequence s => Sized s a -> Int -> Maybe a
lookupWithDefault :: S.Sequence s => a -> Sized s a -> Int -> a
update :: S.Sequence s => Int -> a -> Sized s a -> Sized s a
adjust :: S.Sequence s => (a -> a) -> Int -> Sized s a -> Sized s a
mapWithIndex :: S.Sequence s => (Int -> a -> b) -> Sized s a -> Sized s b
foldrWithIndex :: S.Sequence s => (Int -> a -> b -> b) -> b -> Sized s a -> b
foldlWithIndex :: S.Sequence s => (b -> Int -> a -> b) -> b -> Sized s a -> b
take :: S.Sequence s => Int -> Sized s a -> Sized s a
drop :: S.Sequence s => Int -> Sized s a -> Sized s a
splitAt :: S.Sequence s => Int -> Sized s a -> (Sized s a, Sized s a)
subseq :: S.Sequence s => Int -> Int -> Sized s a -> Sized s a
filter :: S.Sequence s => (a -> Bool) -> Sized s a -> Sized s a
partition :: S.Sequence s => (a -> Bool) -> Sized s a -> (Sized s a, Sized s a)
takeWhile :: S.Sequence s => (a -> Bool) -> Sized s a -> Sized s a
dropWhile :: S.Sequence s => (a -> Bool) -> Sized s a -> Sized s a
splitWhile :: S.Sequence s => (a -> Bool) -> Sized s a -> (Sized s a, Sized s a)
zip :: S.Sequence s => Sized s a -> Sized s b -> Sized s (a,b)
zip3 :: S.Sequence s => Sized s a -> Sized s b -> Sized s c -> Sized s (a,b,c)
zipWith :: S.Sequence s => (a -> b -> c) -> Sized s a -> Sized s b -> Sized s c
zipWith3 :: S.Sequence s => (a -> b -> c -> d) -> Sized s a -> Sized s b -> Sized s c -> Sized s d
unzip :: S.Sequence s => Sized s (a,b) -> (Sized s a, Sized s b)
unzip3 :: S.Sequence s => Sized s (a,b,c) -> (Sized s a, Sized s b, Sized s c)
unzipWith :: S.Sequence s => (a -> b) -> (a -> c) -> Sized s a -> (Sized s b, Sized s c)
unzipWith3 :: S.Sequence s => (a -> b) -> (a -> c) -> (a -> d) -> Sized s a -> (Sized s b, Sized s c, Sized s d)
bonus functions , not in Sequence signature
fromSeq :: S.Sequence s => s a -> Sized s a
toSeq :: S.Sequence s => Sized s a -> s a
moduleName = "SizedSeq"
instanceName (N n s) = "SizedSeq(" ++ S.instanceName s ++ ")"
data Sized s a = N !Int (s a)
fromSeq xs = N (S.size xs) xs
toSeq (N n xs) = xs
empty = N 0 S.empty
single x = N 1 (S.single x)
cons x (N n xs) = N (n+1) (S.cons x xs)
snoc (N n xs) x = N (n+1) (S.snoc xs x)
append (N m xs) (N n ys) = N (m+n) (S.append xs ys)
lview (N n xs) = case S.lview xs of
Nothing2 -> Nothing2
Just2 x xs -> Just2 x (N (n-1) xs)
lhead (N n xs) = S.lhead xs
ltail (N 0 xs) = empty
ltail (N n xs) = N (n-1) (S.ltail xs)
rview (N n xs) = case S.rview xs of
Nothing2 -> Nothing2
Just2 xs x -> Just2 (N (n-1) xs) x
rhead (N n xs) = S.rhead xs
rtail (N 0 xs) = empty
rtail (N n xs) = N (n-1) (S.rtail xs)
null (N n xs) = n == 0
size (N n xs) = n
concat (N n xss) = fromSeq (S.concat (S.map toSeq xss))
reverse (N n xs) = N n (S.reverse xs)
reverseOnto (N m xs) (N n ys) = N (m+n) (S.reverseOnto xs ys)
fromList = fromSeq . S.fromList
toList (N n xs) = S.toList xs
map f (N n xs) = N n (S.map f xs)
concatMap = concatMapUsingFoldr -- only function that uses a default
foldr f e (N n xs) = S.foldr f e xs
foldl f e (N n xs) = S.foldl f e xs
foldr1 f (N n xs) = S.foldr1 f xs
foldl1 f (N n xs) = S.foldl1 f xs
reducer f e (N n xs) = S.reducer f e xs
reducel f e (N n xs) = S.reducel f e xs
reduce1 f (N n xs) = S.reduce1 f xs
copy n x
| n <= 0 = empty
| otherwise = N n (S.copy n x)
tabulate n f
| n <= 0 = empty
| otherwise = N n (S.tabulate n f)
inBounds (N n xs) i = (i >= 0) && (i < n)
lookup (N n xs) = S.lookup xs
lookupM (N n xs) = S.lookupM xs
lookupWithDefault d (N n xs) = S.lookupWithDefault d xs
update i x (N n xs) = N n (S.update i x xs)
adjust f i (N n xs) = N n (S.adjust f i xs)
mapWithIndex f (N n xs) = N n (S.mapWithIndex f xs)
foldrWithIndex f e (N n xs) = S.foldrWithIndex f e xs
foldlWithIndex f e (N n xs) = S.foldlWithIndex f e xs
take i original@(N n xs)
| i <= 0 = empty
| i >= n = original
| otherwise = N i (S.take i xs)
drop i original@(N n xs)
| i <= 0 = original
| i >= n = empty
| otherwise = N (n-i) (S.drop i xs)
splitAt i original@(N n xs)
| i <= 0 = (empty, original)
| i >= n = (original, empty)
| otherwise = let (ys,zs) = S.splitAt i xs
in (N i ys, N (n-i) zs)
subseq i len original@(N n xs)
| i <= 0 = take len original
| i >= n || len <= 0 = empty
| i+len >= n = N (n-i) (S.drop i xs)
| otherwise = N len (S.subseq i len xs)
filter p = fromSeq . S.filter p . toSeq
partition p (N n xs) = (N m ys, N (n-m) zs)
where (ys,zs) = S.partition p xs
m = S.size ys
takeWhile p = fromSeq . S.takeWhile p . toSeq
dropWhile p = fromSeq . S.dropWhile p . toSeq
splitWhile p (N n xs) = (N m ys, N (n-m) zs)
where (ys,zs) = S.splitWhile p xs
m = S.size ys
zip (N m xs) (N n ys) = N (min m n) (S.zip xs ys)
zip3 (N l xs) (N m ys) (N n zs) = N (min l (min m n)) (S.zip3 xs ys zs)
zipWith f (N m xs) (N n ys) = N (min m n) (S.zipWith f xs ys)
zipWith3 f (N l xs) (N m ys) (N n zs) = N (min l (min m n)) (S.zipWith3 f xs ys zs)
unzip (N n xys) = (N n xs, N n ys)
where (xs,ys) = S.unzip xys
unzip3 (N n xyzs) = (N n xs, N n ys, N n zs)
where (xs,ys,zs) = S.unzip3 xyzs
unzipWith f g (N n xys) = (N n xs, N n ys)
where (xs,ys) = S.unzipWith f g xys
unzipWith3 f g h (N n xyzs) = (N n xs, N n ys, N n zs)
where (xs,ys,zs) = S.unzipWith3 f g h xyzs
-- instances
instance S.Sequence s => S.Sequence (Sized s) where
{empty = empty; single = single; cons = cons; snoc = snoc;
append = append; lview = lview; lhead = lhead; ltail = ltail;
rview = rview; rhead = rhead; rtail = rtail; null = null;
size = size; concat = concat; reverse = reverse;
reverseOnto = reverseOnto; fromList = fromList; toList = toList;
map = map; concatMap = concatMap; foldr = foldr; foldl = foldl;
foldr1 = foldr1; foldl1 = foldl1; reducer = reducer;
reducel = reducel; reduce1 = reduce1; copy = copy;
tabulate = tabulate; inBounds = inBounds; lookup = lookup;
lookupM = lookupM; lookupWithDefault = lookupWithDefault;
update = update; adjust = adjust; mapWithIndex = mapWithIndex;
foldrWithIndex = foldrWithIndex; foldlWithIndex = foldlWithIndex;
take = take; drop = drop; splitAt = splitAt; subseq = subseq;
filter = filter; partition = partition; takeWhile = takeWhile;
dropWhile = dropWhile; splitWhile = splitWhile; zip = zip;
zip3 = zip3; zipWith = zipWith; zipWith3 = zipWith3; unzip = unzip;
unzip3 = unzip3; unzipWith = unzipWith; unzipWith3 = unzipWith3;
instanceName = instanceName}
instance S.Sequence s => Functor (Sized s) where
fmap = map
instance S.Sequence s => Monad (Sized s) where
return = single
xs >>= k = concatMap k xs
instance S.Sequence s => MonadPlus (Sized s) where
mplus = append
mzero = empty
instance Eq (s a) => Eq (Sized s a) where
(N m xs) == (N n ys) = (m == n) && (xs == ys)
-- this is probably identical to the code that would be
-- generated by "deriving (Eq)", but I wanted to be *sure*
-- that the sizes were compared before the inner sequences
instance (S.Sequence s, Show (s a)) => Show (Sized s a) where
show xs = show (toSeq xs)
instance (S.Sequence s, Arbitrary (s a)) => Arbitrary (Sized s a) where
arbitrary = do xs <- arbitrary
return (fromSeq xs)
coarbitrary xs = coarbitrary (toSeq xs)
| null | https://raw.githubusercontent.com/conscell/hugs-android/31e5861bc1a1dd9931e6b2471a9f45c14e3c6c7e/hugs/lib/hugs/oldlib/SizedSeq.hs | haskell | See COPYRIGHT file for terms and conditions.
# DEPRECATED "This module is unmaintained, and will disappear soon" #
generic adaptor for sequences to keep track of the current size
sequence operations
documentation
other supported operations
only used by concatMap
If s is a sequence type constructor, then Sized s
is a sequence type constructor that is identical to s,
except that it also keeps track of the current size of
each sequence.
signatures for exported functions
only function that uses a default
instances
this is probably identical to the code that would be
generated by "deriving (Eq)", but I wanted to be *sure*
that the sizes were compared before the inner sequences | Copyright ( c ) 1998 - 1999 .
module SizedSeq
(
Sized s instance of Sequence , Functor , Monad , MonadPlus
empty,single,cons,snoc,append,lview,lhead,ltail,rview,rhead,rtail,
null,size,concat,reverse,reverseOnto,fromList,toList,
map,concatMap,foldr,foldl,foldr1,foldl1,reducer,reducel,reduce1,
copy,tabulate,inBounds,lookup,lookupM,lookupWithDefault,update,adjust,
mapWithIndex,foldrWithIndex,foldlWithIndex,
take,drop,splitAt,subseq,filter,partition,takeWhile,dropWhile,splitWhile,
zip,zip3,zipWith,zipWith3,unzip,unzip3,unzipWith,unzipWith3,
moduleName,instanceName,
fromSeq,toSeq,
re - export view type from EdisonPrelude for convenience
Maybe2(Just2,Nothing2)
) where
import Prelude hiding (concat,reverse,map,concatMap,foldr,foldl,foldr1,foldl1,
filter,takeWhile,dropWhile,lookup,take,drop,splitAt,
zip,zip3,zipWith,zipWith3,unzip,unzip3,null)
import EdisonPrelude(Maybe2(Just2,Nothing2))
import qualified Sequence as S ( Sequence(..) )
import qualified Sequence as S
import Monad
import QuickCheck
This module defines a sequence adaptor
moduleName :: String
instanceName :: S.Sequence s => Sized s a -> String
empty :: S.Sequence s => Sized s a
single :: S.Sequence s => a -> Sized s a
cons :: S.Sequence s => a -> Sized s a -> Sized s a
snoc :: S.Sequence s => Sized s a -> a -> Sized s a
append :: S.Sequence s => Sized s a -> Sized s a -> Sized s a
lview :: S.Sequence s => Sized s a -> Maybe2 a (Sized s a)
lhead :: S.Sequence s => Sized s a -> a
ltail :: S.Sequence s => Sized s a -> Sized s a
rview :: S.Sequence s => Sized s a -> Maybe2 (Sized s a) a
rhead :: S.Sequence s => Sized s a -> a
rtail :: S.Sequence s => Sized s a -> Sized s a
null :: S.Sequence s => Sized s a -> Bool
size :: S.Sequence s => Sized s a -> Int
concat :: S.Sequence s => Sized s (Sized s a) -> Sized s a
reverse :: S.Sequence s => Sized s a -> Sized s a
reverseOnto :: S.Sequence s => Sized s a -> Sized s a -> Sized s a
fromList :: S.Sequence s => [a] -> Sized s a
toList :: S.Sequence s => Sized s a -> [a]
map :: S.Sequence s => (a -> b) -> Sized s a -> Sized s b
concatMap :: S.Sequence s => (a -> Sized s b) -> Sized s a -> Sized s b
foldr :: S.Sequence s => (a -> b -> b) -> b -> Sized s a -> b
foldl :: S.Sequence s => (b -> a -> b) -> b -> Sized s a -> b
foldr1 :: S.Sequence s => (a -> a -> a) -> Sized s a -> a
foldl1 :: S.Sequence s => (a -> a -> a) -> Sized s a -> a
reducer :: S.Sequence s => (a -> a -> a) -> a -> Sized s a -> a
reducel :: S.Sequence s => (a -> a -> a) -> a -> Sized s a -> a
reduce1 :: S.Sequence s => (a -> a -> a) -> Sized s a -> a
copy :: S.Sequence s => Int -> a -> Sized s a
tabulate :: S.Sequence s => Int -> (Int -> a) -> Sized s a
inBounds :: S.Sequence s => Sized s a -> Int -> Bool
lookup :: S.Sequence s => Sized s a -> Int -> a
lookupM :: S.Sequence s => Sized s a -> Int -> Maybe a
lookupWithDefault :: S.Sequence s => a -> Sized s a -> Int -> a
update :: S.Sequence s => Int -> a -> Sized s a -> Sized s a
adjust :: S.Sequence s => (a -> a) -> Int -> Sized s a -> Sized s a
mapWithIndex :: S.Sequence s => (Int -> a -> b) -> Sized s a -> Sized s b
foldrWithIndex :: S.Sequence s => (Int -> a -> b -> b) -> b -> Sized s a -> b
foldlWithIndex :: S.Sequence s => (b -> Int -> a -> b) -> b -> Sized s a -> b
take :: S.Sequence s => Int -> Sized s a -> Sized s a
drop :: S.Sequence s => Int -> Sized s a -> Sized s a
splitAt :: S.Sequence s => Int -> Sized s a -> (Sized s a, Sized s a)
subseq :: S.Sequence s => Int -> Int -> Sized s a -> Sized s a
filter :: S.Sequence s => (a -> Bool) -> Sized s a -> Sized s a
partition :: S.Sequence s => (a -> Bool) -> Sized s a -> (Sized s a, Sized s a)
takeWhile :: S.Sequence s => (a -> Bool) -> Sized s a -> Sized s a
dropWhile :: S.Sequence s => (a -> Bool) -> Sized s a -> Sized s a
splitWhile :: S.Sequence s => (a -> Bool) -> Sized s a -> (Sized s a, Sized s a)
zip :: S.Sequence s => Sized s a -> Sized s b -> Sized s (a,b)
zip3 :: S.Sequence s => Sized s a -> Sized s b -> Sized s c -> Sized s (a,b,c)
zipWith :: S.Sequence s => (a -> b -> c) -> Sized s a -> Sized s b -> Sized s c
zipWith3 :: S.Sequence s => (a -> b -> c -> d) -> Sized s a -> Sized s b -> Sized s c -> Sized s d
unzip :: S.Sequence s => Sized s (a,b) -> (Sized s a, Sized s b)
unzip3 :: S.Sequence s => Sized s (a,b,c) -> (Sized s a, Sized s b, Sized s c)
unzipWith :: S.Sequence s => (a -> b) -> (a -> c) -> Sized s a -> (Sized s b, Sized s c)
unzipWith3 :: S.Sequence s => (a -> b) -> (a -> c) -> (a -> d) -> Sized s a -> (Sized s b, Sized s c, Sized s d)
bonus functions , not in Sequence signature
fromSeq :: S.Sequence s => s a -> Sized s a
toSeq :: S.Sequence s => Sized s a -> s a
moduleName = "SizedSeq"
instanceName (N n s) = "SizedSeq(" ++ S.instanceName s ++ ")"
data Sized s a = N !Int (s a)
fromSeq xs = N (S.size xs) xs
toSeq (N n xs) = xs
empty = N 0 S.empty
single x = N 1 (S.single x)
cons x (N n xs) = N (n+1) (S.cons x xs)
snoc (N n xs) x = N (n+1) (S.snoc xs x)
append (N m xs) (N n ys) = N (m+n) (S.append xs ys)
lview (N n xs) = case S.lview xs of
Nothing2 -> Nothing2
Just2 x xs -> Just2 x (N (n-1) xs)
lhead (N n xs) = S.lhead xs
ltail (N 0 xs) = empty
ltail (N n xs) = N (n-1) (S.ltail xs)
rview (N n xs) = case S.rview xs of
Nothing2 -> Nothing2
Just2 xs x -> Just2 (N (n-1) xs) x
rhead (N n xs) = S.rhead xs
rtail (N 0 xs) = empty
rtail (N n xs) = N (n-1) (S.rtail xs)
null (N n xs) = n == 0
size (N n xs) = n
concat (N n xss) = fromSeq (S.concat (S.map toSeq xss))
reverse (N n xs) = N n (S.reverse xs)
reverseOnto (N m xs) (N n ys) = N (m+n) (S.reverseOnto xs ys)
fromList = fromSeq . S.fromList
toList (N n xs) = S.toList xs
map f (N n xs) = N n (S.map f xs)
foldr f e (N n xs) = S.foldr f e xs
foldl f e (N n xs) = S.foldl f e xs
foldr1 f (N n xs) = S.foldr1 f xs
foldl1 f (N n xs) = S.foldl1 f xs
reducer f e (N n xs) = S.reducer f e xs
reducel f e (N n xs) = S.reducel f e xs
reduce1 f (N n xs) = S.reduce1 f xs
copy n x
| n <= 0 = empty
| otherwise = N n (S.copy n x)
tabulate n f
| n <= 0 = empty
| otherwise = N n (S.tabulate n f)
inBounds (N n xs) i = (i >= 0) && (i < n)
lookup (N n xs) = S.lookup xs
lookupM (N n xs) = S.lookupM xs
lookupWithDefault d (N n xs) = S.lookupWithDefault d xs
update i x (N n xs) = N n (S.update i x xs)
adjust f i (N n xs) = N n (S.adjust f i xs)
mapWithIndex f (N n xs) = N n (S.mapWithIndex f xs)
foldrWithIndex f e (N n xs) = S.foldrWithIndex f e xs
foldlWithIndex f e (N n xs) = S.foldlWithIndex f e xs
take i original@(N n xs)
| i <= 0 = empty
| i >= n = original
| otherwise = N i (S.take i xs)
drop i original@(N n xs)
| i <= 0 = original
| i >= n = empty
| otherwise = N (n-i) (S.drop i xs)
splitAt i original@(N n xs)
| i <= 0 = (empty, original)
| i >= n = (original, empty)
| otherwise = let (ys,zs) = S.splitAt i xs
in (N i ys, N (n-i) zs)
subseq i len original@(N n xs)
| i <= 0 = take len original
| i >= n || len <= 0 = empty
| i+len >= n = N (n-i) (S.drop i xs)
| otherwise = N len (S.subseq i len xs)
filter p = fromSeq . S.filter p . toSeq
partition p (N n xs) = (N m ys, N (n-m) zs)
where (ys,zs) = S.partition p xs
m = S.size ys
takeWhile p = fromSeq . S.takeWhile p . toSeq
dropWhile p = fromSeq . S.dropWhile p . toSeq
splitWhile p (N n xs) = (N m ys, N (n-m) zs)
where (ys,zs) = S.splitWhile p xs
m = S.size ys
zip (N m xs) (N n ys) = N (min m n) (S.zip xs ys)
zip3 (N l xs) (N m ys) (N n zs) = N (min l (min m n)) (S.zip3 xs ys zs)
zipWith f (N m xs) (N n ys) = N (min m n) (S.zipWith f xs ys)
zipWith3 f (N l xs) (N m ys) (N n zs) = N (min l (min m n)) (S.zipWith3 f xs ys zs)
unzip (N n xys) = (N n xs, N n ys)
where (xs,ys) = S.unzip xys
unzip3 (N n xyzs) = (N n xs, N n ys, N n zs)
where (xs,ys,zs) = S.unzip3 xyzs
unzipWith f g (N n xys) = (N n xs, N n ys)
where (xs,ys) = S.unzipWith f g xys
unzipWith3 f g h (N n xyzs) = (N n xs, N n ys, N n zs)
where (xs,ys,zs) = S.unzipWith3 f g h xyzs
instance S.Sequence s => S.Sequence (Sized s) where
{empty = empty; single = single; cons = cons; snoc = snoc;
append = append; lview = lview; lhead = lhead; ltail = ltail;
rview = rview; rhead = rhead; rtail = rtail; null = null;
size = size; concat = concat; reverse = reverse;
reverseOnto = reverseOnto; fromList = fromList; toList = toList;
map = map; concatMap = concatMap; foldr = foldr; foldl = foldl;
foldr1 = foldr1; foldl1 = foldl1; reducer = reducer;
reducel = reducel; reduce1 = reduce1; copy = copy;
tabulate = tabulate; inBounds = inBounds; lookup = lookup;
lookupM = lookupM; lookupWithDefault = lookupWithDefault;
update = update; adjust = adjust; mapWithIndex = mapWithIndex;
foldrWithIndex = foldrWithIndex; foldlWithIndex = foldlWithIndex;
take = take; drop = drop; splitAt = splitAt; subseq = subseq;
filter = filter; partition = partition; takeWhile = takeWhile;
dropWhile = dropWhile; splitWhile = splitWhile; zip = zip;
zip3 = zip3; zipWith = zipWith; zipWith3 = zipWith3; unzip = unzip;
unzip3 = unzip3; unzipWith = unzipWith; unzipWith3 = unzipWith3;
instanceName = instanceName}
instance S.Sequence s => Functor (Sized s) where
fmap = map
instance S.Sequence s => Monad (Sized s) where
return = single
xs >>= k = concatMap k xs
instance S.Sequence s => MonadPlus (Sized s) where
mplus = append
mzero = empty
instance Eq (s a) => Eq (Sized s a) where
(N m xs) == (N n ys) = (m == n) && (xs == ys)
instance (S.Sequence s, Show (s a)) => Show (Sized s a) where
show xs = show (toSeq xs)
instance (S.Sequence s, Arbitrary (s a)) => Arbitrary (Sized s a) where
arbitrary = do xs <- arbitrary
return (fromSeq xs)
coarbitrary xs = coarbitrary (toSeq xs)
|
08200a6352c353b6c055d7346891f3f6a04a5bb072e293f23a520ea72033027e | clojure/clojurescript | reader_types.clj | Copyright ( c ) , Rich Hickey & contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns ^{:doc "Protocols and default Reader types implementation"
:author "Bronsa"}
cljs.vendor.clojure.tools.reader.reader-types
(:refer-clojure :exclude [char read-line])
(:require [cljs.vendor.clojure.tools.reader.impl.utils :refer [char whitespace? newline? make-var]])
(:import clojure.lang.LineNumberingPushbackReader
(java.io InputStream BufferedReader Closeable)))
(defmacro ^:private update! [what f]
(list 'set! what (list f what)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reader protocols
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol Reader
(read-char [reader]
"Returns the next char from the Reader, nil if the end of stream has been reached")
(peek-char [reader]
"Returns the next char from the Reader without removing it from the reader stream"))
(defprotocol IPushbackReader
(unread [reader ch]
"Pushes back a single character on to the stream"))
(defprotocol IndexingReader
(get-line-number [reader]
"Returns the line number of the next character to be read from the stream")
(get-column-number [reader]
"Returns the column number of the next character to be read from the stream")
(get-file-name [reader]
"Returns the file name the reader is reading from, or nil"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reader deftypes
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftype StringReader
[^String s ^long s-len ^:unsynchronized-mutable ^long s-pos]
Reader
(read-char [reader]
(when (> s-len s-pos)
(let [r (nth s s-pos)]
(update! s-pos inc)
r)))
(peek-char [reader]
(when (> s-len s-pos)
(nth s s-pos))))
(deftype InputStreamReader [^InputStream is ^:unsynchronized-mutable ^"[B" buf]
Reader
(read-char [reader]
(if buf
(let [c (aget buf 0)]
(set! buf nil)
(char c))
(let [c (.read is)]
(when (>= c 0)
(char c)))))
(peek-char [reader]
(when-not buf
(set! buf (byte-array 1))
(when (== -1 (.read is buf))
(set! buf nil)))
(when buf
(char (aget buf 0))))
Closeable
(close [this]
(.close is)))
(deftype PushbackReader
[rdr ^"[Ljava.lang.Object;" buf ^long buf-len ^:unsynchronized-mutable ^long buf-pos]
Reader
(read-char [reader]
(char
(if (< buf-pos buf-len)
(let [r (aget buf buf-pos)]
(update! buf-pos inc)
r)
(read-char rdr))))
(peek-char [reader]
(char
(if (< buf-pos buf-len)
(aget buf buf-pos)
(peek-char rdr))))
IPushbackReader
(unread [reader ch]
(when ch
(if (zero? buf-pos) (throw (RuntimeException. "Pushback buffer is full")))
(update! buf-pos dec)
(aset buf buf-pos ch)))
Closeable
(close [this]
(when (instance? Closeable rdr)
(.close ^Closeable rdr))))
(deftype IndexingPushbackReader
[rdr ^:unsynchronized-mutable ^long line ^:unsynchronized-mutable ^long column
^:unsynchronized-mutable line-start? ^:unsynchronized-mutable prev
^:unsynchronized-mutable ^long prev-column file-name
^:unsynchronized-mutable normalize?]
Reader
(read-char [reader]
(when-let [ch (read-char rdr)]
(let [ch (if normalize?
(do (set! normalize? false)
(if (or (identical? \newline ch)
(identical? \formfeed ch))
(read-char rdr)
ch))
ch)
ch (if (identical? \return ch)
(do (set! normalize? true)
\newline)
ch)]
(set! prev line-start?)
(set! line-start? (newline? ch))
(when line-start?
(set! prev-column column)
(set! column 0)
(update! line inc))
(update! column inc)
ch)))
(peek-char [reader]
(peek-char rdr))
IPushbackReader
(unread [reader ch]
(if line-start?
(do (update! line dec)
(set! column prev-column))
(update! column dec))
(set! line-start? prev)
;; This may look a bit convoluted, but it helps in the following
;; scenario:
+ The underlying reader is about to return \return from the
;; next read-char, and then \newline after that.
+ read - char gets \return , sets normalize ? to true , returns
\newline instead .
;; + Caller calls unread on the \newline it just got. If we
unread the \newline to the underlying reader , now it is ready
to return two \newline chars in a row , which will throw off
;; the tracked line numbers.
(let [ch (if normalize?
(do (set! normalize? false)
(if (identical? \newline ch)
\return
ch))
ch)]
(unread rdr ch)))
IndexingReader
(get-line-number [reader] (int line))
(get-column-number [reader] (int column))
(get-file-name [reader] file-name)
Closeable
(close [this]
(when (instance? Closeable rdr)
(.close ^Closeable rdr))))
Java interop
(extend-type java.io.PushbackReader
Reader
(read-char [rdr]
(let [c (.read ^java.io.PushbackReader rdr)]
(when (>= c 0)
(char c))))
(peek-char [rdr]
(when-let [c (read-char rdr)]
(unread rdr c)
c))
IPushbackReader
(unread [rdr c]
(when c
(.unread ^java.io.PushbackReader rdr (int c)))))
(extend LineNumberingPushbackReader
IndexingReader
{:get-line-number (fn [rdr] (.getLineNumber ^LineNumberingPushbackReader rdr))
:get-column-number (fn [rdr]
(.getColumnNumber ^LineNumberingPushbackReader rdr))
:get-file-name (constantly nil)})
(defprotocol ReaderCoercer
(to-rdr [rdr]))
(declare string-reader push-back-reader)
(extend-protocol ReaderCoercer
Object
(to-rdr [rdr]
(if (satisfies? Reader rdr)
rdr
(throw (IllegalArgumentException. (str "Argument of type: " (class rdr) " cannot be converted to Reader")))))
cljs.vendor.clojure.tools.reader.reader_types.Reader
(to-rdr [rdr] rdr)
String
(to-rdr [str] (string-reader str))
java.io.Reader
(to-rdr [rdr] (java.io.PushbackReader. rdr)))
(defprotocol PushbackReaderCoercer
(to-pbr [rdr buf-len]))
(extend-protocol PushbackReaderCoercer
Object
(to-pbr [rdr buf-len]
(if (satisfies? Reader rdr)
(push-back-reader rdr buf-len)
(throw (IllegalArgumentException. (str "Argument of type: " (class rdr) " cannot be converted to IPushbackReader")))))
cljs.vendor.clojure.tools.reader.reader_types.Reader
(to-pbr [rdr buf-len] (push-back-reader rdr buf-len))
cljs.vendor.clojure.tools.reader.reader_types.PushbackReader
(to-pbr [rdr buf-len] (push-back-reader rdr buf-len))
String
(to-pbr [str buf-len] (push-back-reader str buf-len))
java.io.Reader
(to-pbr [rdr buf-len] (java.io.PushbackReader. rdr buf-len)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Source Logging support
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn merge-meta
"Returns an object of the same type and value as `obj`, with its
metadata merged over `m`."
[obj m]
(let [orig-meta (meta obj)]
(with-meta obj (merge m (dissoc orig-meta :source)))))
(defn- peek-source-log
"Returns a string containing the contents of the top most source
logging frame."
[source-log-frames]
(let [current-frame @source-log-frames]
(.substring ^StringBuilder (:buffer current-frame) (:offset current-frame))))
(defn- log-source-char
"Logs `char` to all currently active source logging frames."
[source-log-frames char]
(when-let [^StringBuilder buffer (:buffer @source-log-frames)]
(.append buffer char)))
(defn- drop-last-logged-char
"Removes the last logged character from all currently active source
logging frames. Called when pushing a character back."
[source-log-frames]
(when-let [^StringBuilder buffer (:buffer @source-log-frames)]
(.deleteCharAt buffer (dec (.length buffer)))))
(deftype SourceLoggingPushbackReader
[rdr ^:unsynchronized-mutable ^long line ^:unsynchronized-mutable ^long column
^:unsynchronized-mutable line-start? ^:unsynchronized-mutable prev
^:unsynchronized-mutable ^long prev-column file-name source-log-frames
^:unsynchronized-mutable normalize?]
Reader
(read-char [reader]
(when-let [ch (read-char rdr)]
(let [ch (if normalize?
(do (set! normalize? false)
(if (or (identical? \newline ch)
(identical? \formfeed ch))
(read-char rdr)
ch))
ch)
ch (if (identical? \return ch)
(do (set! normalize? true)
\newline)
ch)]
(set! prev line-start?)
(set! line-start? (newline? ch))
(when line-start?
(set! prev-column column)
(set! column 0)
(update! line inc))
(update! column inc)
(log-source-char source-log-frames ch)
ch)))
(peek-char [reader]
(peek-char rdr))
IPushbackReader
(unread [reader ch]
(if line-start?
(do (update! line dec)
(set! column prev-column))
(update! column dec))
(set! line-start? prev)
(when ch
(drop-last-logged-char source-log-frames))
(unread rdr ch))
IndexingReader
(get-line-number [reader] (int line))
(get-column-number [reader] (int column))
(get-file-name [reader] file-name)
Closeable
(close [this]
(when (instance? Closeable rdr)
(.close ^Closeable rdr))))
(defn log-source*
[reader f]
(let [frame (.source-log-frames ^SourceLoggingPushbackReader reader)
^StringBuilder buffer (:buffer @frame)
new-frame (assoc-in @frame [:offset] (.length buffer))]
(with-bindings {frame new-frame}
(let [ret (f)]
(if (instance? clojure.lang.IObj ret)
(merge-meta ret {:source (peek-source-log frame)})
ret)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Public API
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; fast check for provided implementations
(defn indexing-reader?
"Returns true if the reader satisfies IndexingReader"
[rdr]
(or (instance? cljs.vendor.clojure.tools.reader.reader_types.IndexingReader rdr)
(instance? LineNumberingPushbackReader rdr)
(and (not (instance? cljs.vendor.clojure.tools.reader.reader_types.PushbackReader rdr))
(not (instance? cljs.vendor.clojure.tools.reader.reader_types.StringReader rdr))
(not (instance? cljs.vendor.clojure.tools.reader.reader_types.InputStreamReader rdr))
(get (:impls IndexingReader) (class rdr)))))
(defn string-reader
"Creates a StringReader from a given string"
([^String s]
(StringReader. s (count s) 0)))
(defn ^Closeable push-back-reader
"Creates a PushbackReader from a given reader or string"
([rdr] (push-back-reader rdr 1))
([rdr buf-len] (PushbackReader. (to-rdr rdr) (object-array buf-len) buf-len buf-len)))
(defn ^Closeable string-push-back-reader
"Creates a PushbackReader from a given string"
([s]
(string-push-back-reader s 1))
([^String s buf-len]
(push-back-reader (string-reader s) buf-len)))
(defn ^Closeable input-stream-reader
"Creates an InputStreamReader from an InputStream"
[is]
(InputStreamReader. is nil))
(defn ^Closeable input-stream-push-back-reader
"Creates a PushbackReader from a given InputStream"
([is]
(input-stream-push-back-reader is 1))
([^InputStream is buf-len]
(push-back-reader (input-stream-reader is) buf-len)))
(defn ^Closeable indexing-push-back-reader
"Creates an IndexingPushbackReader from a given string or PushbackReader"
([s-or-rdr]
(indexing-push-back-reader s-or-rdr 1))
([s-or-rdr buf-len]
(indexing-push-back-reader s-or-rdr buf-len nil))
([s-or-rdr buf-len file-name]
(IndexingPushbackReader.
(to-pbr s-or-rdr buf-len) 1 1 true nil 0 file-name false)))
(defn ^Closeable source-logging-push-back-reader
"Creates a SourceLoggingPushbackReader from a given string or PushbackReader"
([s-or-rdr]
(source-logging-push-back-reader s-or-rdr 1))
([s-or-rdr buf-len]
(source-logging-push-back-reader s-or-rdr buf-len nil))
([s-or-rdr buf-len file-name]
(SourceLoggingPushbackReader.
(to-pbr s-or-rdr buf-len)
1
1
true
nil
0
file-name
(doto (make-var)
(alter-var-root (constantly {:buffer (StringBuilder.)
:offset 0})))
false)))
(defn read-line
"Reads a line from the reader or from *in* if no reader is specified"
([] (read-line *in*))
([rdr]
(if (or (instance? LineNumberingPushbackReader rdr)
(instance? BufferedReader rdr))
(binding [*in* rdr]
(clojure.core/read-line))
(loop [c (read-char rdr) s (StringBuilder.)]
(if (newline? c)
(str s)
(recur (read-char rdr) (.append s c)))))))
(defn source-logging-reader?
[rdr]
(instance? SourceLoggingPushbackReader rdr))
(defmacro log-source
"If reader is a SourceLoggingPushbackReader, execute body in a source
logging context. Otherwise, execute body, returning the result."
[reader & body]
`(if (and (source-logging-reader? ~reader)
(not (whitespace? (peek-char ~reader))))
(log-source* ~reader (^:once fn* [] ~@body))
(do ~@body)))
(defn line-start?
"Returns true if rdr is an IndexingReader and the current char starts a new line"
[rdr]
(when (indexing-reader? rdr)
(== 1 (int (get-column-number rdr)))))
| null | https://raw.githubusercontent.com/clojure/clojurescript/e30e26dbd221b5d7c4bbc567d10d0c3c01cf5f98/src/main/clojure/cljs/vendor/clojure/tools/reader/reader_types.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
reader protocols
reader deftypes
This may look a bit convoluted, but it helps in the following
scenario:
next read-char, and then \newline after that.
+ Caller calls unread on the \newline it just got. If we
the tracked line numbers.
Source Logging support
Public API
fast check for provided implementations | Copyright ( c ) , Rich Hickey & contributors .
(ns ^{:doc "Protocols and default Reader types implementation"
:author "Bronsa"}
cljs.vendor.clojure.tools.reader.reader-types
(:refer-clojure :exclude [char read-line])
(:require [cljs.vendor.clojure.tools.reader.impl.utils :refer [char whitespace? newline? make-var]])
(:import clojure.lang.LineNumberingPushbackReader
(java.io InputStream BufferedReader Closeable)))
(defmacro ^:private update! [what f]
(list 'set! what (list f what)))
(defprotocol Reader
(read-char [reader]
"Returns the next char from the Reader, nil if the end of stream has been reached")
(peek-char [reader]
"Returns the next char from the Reader without removing it from the reader stream"))
(defprotocol IPushbackReader
(unread [reader ch]
"Pushes back a single character on to the stream"))
(defprotocol IndexingReader
(get-line-number [reader]
"Returns the line number of the next character to be read from the stream")
(get-column-number [reader]
"Returns the column number of the next character to be read from the stream")
(get-file-name [reader]
"Returns the file name the reader is reading from, or nil"))
(deftype StringReader
[^String s ^long s-len ^:unsynchronized-mutable ^long s-pos]
Reader
(read-char [reader]
(when (> s-len s-pos)
(let [r (nth s s-pos)]
(update! s-pos inc)
r)))
(peek-char [reader]
(when (> s-len s-pos)
(nth s s-pos))))
(deftype InputStreamReader [^InputStream is ^:unsynchronized-mutable ^"[B" buf]
Reader
(read-char [reader]
(if buf
(let [c (aget buf 0)]
(set! buf nil)
(char c))
(let [c (.read is)]
(when (>= c 0)
(char c)))))
(peek-char [reader]
(when-not buf
(set! buf (byte-array 1))
(when (== -1 (.read is buf))
(set! buf nil)))
(when buf
(char (aget buf 0))))
Closeable
(close [this]
(.close is)))
(deftype PushbackReader
[rdr ^"[Ljava.lang.Object;" buf ^long buf-len ^:unsynchronized-mutable ^long buf-pos]
Reader
(read-char [reader]
(char
(if (< buf-pos buf-len)
(let [r (aget buf buf-pos)]
(update! buf-pos inc)
r)
(read-char rdr))))
(peek-char [reader]
(char
(if (< buf-pos buf-len)
(aget buf buf-pos)
(peek-char rdr))))
IPushbackReader
(unread [reader ch]
(when ch
(if (zero? buf-pos) (throw (RuntimeException. "Pushback buffer is full")))
(update! buf-pos dec)
(aset buf buf-pos ch)))
Closeable
(close [this]
(when (instance? Closeable rdr)
(.close ^Closeable rdr))))
(deftype IndexingPushbackReader
[rdr ^:unsynchronized-mutable ^long line ^:unsynchronized-mutable ^long column
^:unsynchronized-mutable line-start? ^:unsynchronized-mutable prev
^:unsynchronized-mutable ^long prev-column file-name
^:unsynchronized-mutable normalize?]
Reader
(read-char [reader]
(when-let [ch (read-char rdr)]
(let [ch (if normalize?
(do (set! normalize? false)
(if (or (identical? \newline ch)
(identical? \formfeed ch))
(read-char rdr)
ch))
ch)
ch (if (identical? \return ch)
(do (set! normalize? true)
\newline)
ch)]
(set! prev line-start?)
(set! line-start? (newline? ch))
(when line-start?
(set! prev-column column)
(set! column 0)
(update! line inc))
(update! column inc)
ch)))
(peek-char [reader]
(peek-char rdr))
IPushbackReader
(unread [reader ch]
(if line-start?
(do (update! line dec)
(set! column prev-column))
(update! column dec))
(set! line-start? prev)
+ The underlying reader is about to return \return from the
+ read - char gets \return , sets normalize ? to true , returns
\newline instead .
unread the \newline to the underlying reader , now it is ready
to return two \newline chars in a row , which will throw off
(let [ch (if normalize?
(do (set! normalize? false)
(if (identical? \newline ch)
\return
ch))
ch)]
(unread rdr ch)))
IndexingReader
(get-line-number [reader] (int line))
(get-column-number [reader] (int column))
(get-file-name [reader] file-name)
Closeable
(close [this]
(when (instance? Closeable rdr)
(.close ^Closeable rdr))))
Java interop
(extend-type java.io.PushbackReader
Reader
(read-char [rdr]
(let [c (.read ^java.io.PushbackReader rdr)]
(when (>= c 0)
(char c))))
(peek-char [rdr]
(when-let [c (read-char rdr)]
(unread rdr c)
c))
IPushbackReader
(unread [rdr c]
(when c
(.unread ^java.io.PushbackReader rdr (int c)))))
(extend LineNumberingPushbackReader
IndexingReader
{:get-line-number (fn [rdr] (.getLineNumber ^LineNumberingPushbackReader rdr))
:get-column-number (fn [rdr]
(.getColumnNumber ^LineNumberingPushbackReader rdr))
:get-file-name (constantly nil)})
(defprotocol ReaderCoercer
(to-rdr [rdr]))
(declare string-reader push-back-reader)
(extend-protocol ReaderCoercer
Object
(to-rdr [rdr]
(if (satisfies? Reader rdr)
rdr
(throw (IllegalArgumentException. (str "Argument of type: " (class rdr) " cannot be converted to Reader")))))
cljs.vendor.clojure.tools.reader.reader_types.Reader
(to-rdr [rdr] rdr)
String
(to-rdr [str] (string-reader str))
java.io.Reader
(to-rdr [rdr] (java.io.PushbackReader. rdr)))
(defprotocol PushbackReaderCoercer
(to-pbr [rdr buf-len]))
(extend-protocol PushbackReaderCoercer
Object
(to-pbr [rdr buf-len]
(if (satisfies? Reader rdr)
(push-back-reader rdr buf-len)
(throw (IllegalArgumentException. (str "Argument of type: " (class rdr) " cannot be converted to IPushbackReader")))))
cljs.vendor.clojure.tools.reader.reader_types.Reader
(to-pbr [rdr buf-len] (push-back-reader rdr buf-len))
cljs.vendor.clojure.tools.reader.reader_types.PushbackReader
(to-pbr [rdr buf-len] (push-back-reader rdr buf-len))
String
(to-pbr [str buf-len] (push-back-reader str buf-len))
java.io.Reader
(to-pbr [rdr buf-len] (java.io.PushbackReader. rdr buf-len)))
(defn merge-meta
"Returns an object of the same type and value as `obj`, with its
metadata merged over `m`."
[obj m]
(let [orig-meta (meta obj)]
(with-meta obj (merge m (dissoc orig-meta :source)))))
(defn- peek-source-log
"Returns a string containing the contents of the top most source
logging frame."
[source-log-frames]
(let [current-frame @source-log-frames]
(.substring ^StringBuilder (:buffer current-frame) (:offset current-frame))))
(defn- log-source-char
"Logs `char` to all currently active source logging frames."
[source-log-frames char]
(when-let [^StringBuilder buffer (:buffer @source-log-frames)]
(.append buffer char)))
(defn- drop-last-logged-char
"Removes the last logged character from all currently active source
logging frames. Called when pushing a character back."
[source-log-frames]
(when-let [^StringBuilder buffer (:buffer @source-log-frames)]
(.deleteCharAt buffer (dec (.length buffer)))))
(deftype SourceLoggingPushbackReader
[rdr ^:unsynchronized-mutable ^long line ^:unsynchronized-mutable ^long column
^:unsynchronized-mutable line-start? ^:unsynchronized-mutable prev
^:unsynchronized-mutable ^long prev-column file-name source-log-frames
^:unsynchronized-mutable normalize?]
Reader
(read-char [reader]
(when-let [ch (read-char rdr)]
(let [ch (if normalize?
(do (set! normalize? false)
(if (or (identical? \newline ch)
(identical? \formfeed ch))
(read-char rdr)
ch))
ch)
ch (if (identical? \return ch)
(do (set! normalize? true)
\newline)
ch)]
(set! prev line-start?)
(set! line-start? (newline? ch))
(when line-start?
(set! prev-column column)
(set! column 0)
(update! line inc))
(update! column inc)
(log-source-char source-log-frames ch)
ch)))
(peek-char [reader]
(peek-char rdr))
IPushbackReader
(unread [reader ch]
(if line-start?
(do (update! line dec)
(set! column prev-column))
(update! column dec))
(set! line-start? prev)
(when ch
(drop-last-logged-char source-log-frames))
(unread rdr ch))
IndexingReader
(get-line-number [reader] (int line))
(get-column-number [reader] (int column))
(get-file-name [reader] file-name)
Closeable
(close [this]
(when (instance? Closeable rdr)
(.close ^Closeable rdr))))
(defn log-source*
[reader f]
(let [frame (.source-log-frames ^SourceLoggingPushbackReader reader)
^StringBuilder buffer (:buffer @frame)
new-frame (assoc-in @frame [:offset] (.length buffer))]
(with-bindings {frame new-frame}
(let [ret (f)]
(if (instance? clojure.lang.IObj ret)
(merge-meta ret {:source (peek-source-log frame)})
ret)))))
(defn indexing-reader?
"Returns true if the reader satisfies IndexingReader"
[rdr]
(or (instance? cljs.vendor.clojure.tools.reader.reader_types.IndexingReader rdr)
(instance? LineNumberingPushbackReader rdr)
(and (not (instance? cljs.vendor.clojure.tools.reader.reader_types.PushbackReader rdr))
(not (instance? cljs.vendor.clojure.tools.reader.reader_types.StringReader rdr))
(not (instance? cljs.vendor.clojure.tools.reader.reader_types.InputStreamReader rdr))
(get (:impls IndexingReader) (class rdr)))))
(defn string-reader
"Creates a StringReader from a given string"
([^String s]
(StringReader. s (count s) 0)))
(defn ^Closeable push-back-reader
"Creates a PushbackReader from a given reader or string"
([rdr] (push-back-reader rdr 1))
([rdr buf-len] (PushbackReader. (to-rdr rdr) (object-array buf-len) buf-len buf-len)))
(defn ^Closeable string-push-back-reader
"Creates a PushbackReader from a given string"
([s]
(string-push-back-reader s 1))
([^String s buf-len]
(push-back-reader (string-reader s) buf-len)))
(defn ^Closeable input-stream-reader
"Creates an InputStreamReader from an InputStream"
[is]
(InputStreamReader. is nil))
(defn ^Closeable input-stream-push-back-reader
"Creates a PushbackReader from a given InputStream"
([is]
(input-stream-push-back-reader is 1))
([^InputStream is buf-len]
(push-back-reader (input-stream-reader is) buf-len)))
(defn ^Closeable indexing-push-back-reader
"Creates an IndexingPushbackReader from a given string or PushbackReader"
([s-or-rdr]
(indexing-push-back-reader s-or-rdr 1))
([s-or-rdr buf-len]
(indexing-push-back-reader s-or-rdr buf-len nil))
([s-or-rdr buf-len file-name]
(IndexingPushbackReader.
(to-pbr s-or-rdr buf-len) 1 1 true nil 0 file-name false)))
(defn ^Closeable source-logging-push-back-reader
"Creates a SourceLoggingPushbackReader from a given string or PushbackReader"
([s-or-rdr]
(source-logging-push-back-reader s-or-rdr 1))
([s-or-rdr buf-len]
(source-logging-push-back-reader s-or-rdr buf-len nil))
([s-or-rdr buf-len file-name]
(SourceLoggingPushbackReader.
(to-pbr s-or-rdr buf-len)
1
1
true
nil
0
file-name
(doto (make-var)
(alter-var-root (constantly {:buffer (StringBuilder.)
:offset 0})))
false)))
(defn read-line
"Reads a line from the reader or from *in* if no reader is specified"
([] (read-line *in*))
([rdr]
(if (or (instance? LineNumberingPushbackReader rdr)
(instance? BufferedReader rdr))
(binding [*in* rdr]
(clojure.core/read-line))
(loop [c (read-char rdr) s (StringBuilder.)]
(if (newline? c)
(str s)
(recur (read-char rdr) (.append s c)))))))
(defn source-logging-reader?
[rdr]
(instance? SourceLoggingPushbackReader rdr))
(defmacro log-source
"If reader is a SourceLoggingPushbackReader, execute body in a source
logging context. Otherwise, execute body, returning the result."
[reader & body]
`(if (and (source-logging-reader? ~reader)
(not (whitespace? (peek-char ~reader))))
(log-source* ~reader (^:once fn* [] ~@body))
(do ~@body)))
(defn line-start?
"Returns true if rdr is an IndexingReader and the current char starts a new line"
[rdr]
(when (indexing-reader? rdr)
(== 1 (int (get-column-number rdr)))))
|
262f8d0832a69ffc074df9795199e65598ef234a964feb6452a1af089fd58e95 | basho/riak_kv | riak_kv_wm_props.erl | %% -------------------------------------------------------------------
%%
riak_kv_wm_props : Webmachine resource for listing bucket properties .
%%
Copyright ( c ) 2007 - 2013 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
@doc Resource for serving Riak bucket properties over HTTP .
%%
%% URLs that begin with `/types' are necessary for the new bucket
types implementation in Riak 2.0 , those that begin with ` /buckets '
%% are for the default bucket type, and `/riak' is an old URL style,
%% also only works for the default bucket type.
%%
%% It is possible to reconfigure the `/riak' prefix but that seems to
%% be rarely if ever used.
%%
%% ```
%% GET /types/Type/buckets/Bucket/props
%% GET /buckets/Bucket/props
%% GET /riak/Bucket'''
%%
%% Get information about the named Bucket, in JSON form:
` { " props":{Prop1 : Val1,Prop2 : Val2 , ... } } '
%%
%% Each bucket property will be included in the `props' object.
%% `linkfun' and `chash_keyfun' properties will be encoded as
%% JSON objects of the form:
%% ```
%% {"mod":ModuleName,
%% "fun":FunctionName}'''
%%
Where ModuleName and FunctionName are each strings representing
%% a module and function.
%%
%% ```
%% PUT /types/Type/buckets/Bucket/props
%% PUT /buckets/Bucket/props
PUT /riak / Bucket '' '
%%
%% Modify bucket properties.
%%
%% Content-type must be `application/json', and the body must have
%% the form:
%% `{"props":{Prop:Val}}'
%%
%% Where the `props' object takes the same form as returned from
%% a GET of the same resource.
%%
%% ```
%% DELETE /types/Type/buckets/Bucket/props
%% DELETE /buckets/Bucket/props'''
%%
%% Reset bucket properties back to the default settings
-module(riak_kv_wm_props).
%% webmachine resource exports
-export([
init/1,
service_available/2,
is_authorized/2,
forbidden/2,
allowed_methods/2,
malformed_request/2,
content_types_provided/2,
encodings_provided/2,
content_types_accepted/2,
resource_exists/2,
produce_bucket_body/2,
accept_bucket_body/2,
get_bucket_props_json/2,
delete_resource/2
]).
-record(ctx, {bucket_type, %% binary() - Bucket type (from uri)
bucket, %% binary() - Bucket name (from uri)
client, %% riak_client() - the store client
prefix, %% string() - prefix for resource uris
riak, %% local | {node(), atom()} - params for riak client
bucketprops, %% proplist() - properties of the bucket
method, %% atom() - HTTP method for the request
api_version, %% non_neg_integer() - old or new http api
security %% security context
}).
-type context() :: #ctx{}.
-include_lib("webmachine/include/webmachine.hrl").
-include("riak_kv_wm_raw.hrl").
-spec init(proplists:proplist()) -> {ok, context()}.
%% @doc Initialize this resource. This function extracts the
%% 'prefix' and 'riak' properties from the dispatch args.
init(Props) ->
{ok, #ctx{
prefix=proplists:get_value(prefix, Props),
riak=proplists:get_value(riak, Props),
api_version=proplists:get_value(api_version,Props),
bucket_type=proplists:get_value(bucket_type, Props)
}}.
-spec service_available(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
@doc Determine whether or not a connection to can be
%% established. This function also takes this opportunity to extract
%% the 'bucket' bindings from the dispatch.
service_available(RD, Ctx0=#ctx{riak=RiakProps}) ->
Ctx = riak_kv_wm_utils:ensure_bucket_type(RD, Ctx0, #ctx.bucket_type),
case riak_kv_wm_utils:get_riak_client(RiakProps, riak_kv_wm_utils:get_client_id(RD)) of
{ok, C} ->
{true,
RD,
Ctx#ctx{
method=wrq:method(RD),
client=C,
bucket=case wrq:path_info(bucket, RD) of
undefined -> undefined;
B -> list_to_binary(riak_kv_wm_utils:maybe_decode_uri(RD, B))
end
}};
Error ->
{false,
wrq:set_resp_body(
io_lib:format("Unable to connect to Riak: ~p~n", [Error]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
is_authorized(ReqData, Ctx) ->
case riak_api_web_security:is_authorized(ReqData) of
false ->
{"Basic realm=\"Riak\"", ReqData, Ctx};
{true, SecContext} ->
{true, ReqData, Ctx#ctx{security=SecContext}};
insecure ->
%% XXX 301 may be more appropriate here, but since the http and
%% https port are different and configurable, it is hard to figure
%% out the redirect URL to serve.
{{halt, 426}, wrq:append_to_resp_body(<<"Security is enabled and "
"Riak does not accept credentials over HTTP. Try HTTPS "
"instead.">>, ReqData), Ctx}
end.
forbidden(RD, Ctx = #ctx{security=undefined}) ->
{riak_kv_wm_utils:is_forbidden(RD), RD, Ctx};
forbidden(RD, Ctx=#ctx{security=Security}) ->
case riak_kv_wm_utils:is_forbidden(RD) of
true ->
{true, RD, Ctx};
false ->
Perm = case Ctx#ctx.method of
'PUT' ->
"riak_core.set_bucket";
'GET' ->
"riak_core.get_bucket";
'HEAD' ->
"riak_core.get_bucket";
'DELETE' ->
"riak_core.set_bucket"
end,
Res = riak_core_security:check_permission({Perm,
{Ctx#ctx.bucket_type,
Ctx#ctx.bucket}},
Security),
case Res of
{false, Error, _} ->
RD1 = wrq:set_resp_header("Content-Type", "text/plain", RD),
{true, wrq:append_to_resp_body(unicode:characters_to_binary(Error, utf8, utf8), RD1), Ctx};
{true, _} ->
{false, RD, Ctx}
end
end.
-spec allowed_methods(#wm_reqdata{}, context()) ->
{[atom()], #wm_reqdata{}, context()}.
%% @doc Get the list of methods this resource supports.
Properties allows HEAD , GET , and PUT .
allowed_methods(RD, Ctx) when Ctx#ctx.api_version =:= 1 ->
{['HEAD', 'GET', 'PUT'], RD, Ctx};
allowed_methods(RD, Ctx) when Ctx#ctx.api_version =:= 2;
Ctx#ctx.api_version =:= 3 ->
{['HEAD', 'GET', 'PUT', 'DELETE'], RD, Ctx}.
-spec malformed_request(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
%% @doc Determine whether query parameters, request headers,
%% and request body are badly-formed.
%% Body format is checked to be valid JSON, including
%% a "props" object for a bucket-PUT.
malformed_request(RD, Ctx) when Ctx#ctx.method =:= 'PUT' ->
malformed_bucket_put(RD, Ctx);
malformed_request(RD, Ctx) ->
{false, RD, Ctx}.
-spec malformed_bucket_put(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
@doc Check the JSON format of a bucket - level PUT .
%% Must be a valid JSON object, containing a "props" object.
malformed_bucket_put(RD, Ctx) ->
case catch mochijson2:decode(wrq:req_body(RD)) of
{struct, Fields} ->
case proplists:get_value(?JSON_PROPS, Fields) of
{struct, Props} ->
{false, RD, Ctx#ctx{bucketprops=Props}};
_ ->
{true, bucket_format_message(RD), Ctx}
end;
_ ->
{true, bucket_format_message(RD), Ctx}
end.
-spec bucket_format_message(#wm_reqdata{}) -> #wm_reqdata{}.
%% @doc Put an error about the format of the bucket-PUT body
in the response body of the # wm_reqdata { } .
bucket_format_message(RD) ->
wrq:append_to_resp_body(
["bucket PUT must be a JSON object of the form:\n",
"{\"",?JSON_PROPS,"\":{...bucket properties...}}"],
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)).
resource_exists(RD, Ctx) ->
{riak_kv_wm_utils:bucket_type_exists(Ctx#ctx.bucket_type), RD, Ctx}.
-spec content_types_provided(#wm_reqdata{}, context()) ->
{[{ContentType::string(), Producer::atom()}], #wm_reqdata{}, context()}.
%% @doc List the content types available for representing this resource.
%% "application/json" is the content-type for props requests.
content_types_provided(RD, Ctx) ->
{[{"application/json", produce_bucket_body}], RD, Ctx}.
-spec encodings_provided(#wm_reqdata{}, context()) ->
{[{Encoding::string(), Producer::function()}], #wm_reqdata{}, context()}.
%% @doc List the encodings available for representing this resource.
%% "identity" and "gzip" are available for props requests.
encodings_provided(RD, Ctx) ->
{riak_kv_wm_utils:default_encodings(), RD, Ctx}.
-spec content_types_accepted(#wm_reqdata{}, context()) ->
{[{ContentType::string(), Acceptor::atom()}],
#wm_reqdata{}, context()}.
%% @doc Get the list of content types this resource will accept.
" application / json " is the only type accepted for props PUT .
content_types_accepted(RD, Ctx) ->
{[{"application/json", accept_bucket_body}], RD, Ctx}.
-spec produce_bucket_body(#wm_reqdata{}, context()) ->
{binary(), #wm_reqdata{}, context()}.
%% @doc Produce the bucket properties as JSON.
produce_bucket_body(RD, Ctx) ->
Client = Ctx#ctx.client,
Bucket = riak_kv_wm_utils:maybe_bucket_type(Ctx#ctx.bucket_type, Ctx#ctx.bucket),
JsonProps1 = get_bucket_props_json(Client, Bucket),
JsonProps2 = {struct, [JsonProps1]},
JsonProps3 = mochijson2:encode(JsonProps2),
{JsonProps3, RD, Ctx}.
get_bucket_props_json(Client, Bucket) ->
Props1 = riak_client:get_bucket(Bucket, Client),
Props2 = lists:map(fun riak_kv_wm_utils:jsonify_bucket_prop/1, Props1),
{?JSON_PROPS, {struct, Props2}}.
-spec accept_bucket_body(#wm_reqdata{}, context()) -> {true, #wm_reqdata{}, context()}.
%% @doc Modify the bucket properties according to the body of the
bucket - level PUT request .
accept_bucket_body(RD, Ctx=#ctx{bucket_type=T, bucket=B, client=C, bucketprops=Props}) ->
ErlProps = lists:map(fun riak_kv_wm_utils:erlify_bucket_prop/1, Props),
case riak_client:set_bucket({T,B}, ErlProps, C) of
ok ->
{true, RD, Ctx};
{error, Details} ->
JSON = mochijson2:encode(Details),
RD2 = wrq:append_to_resp_body(JSON, RD),
{{halt, 400}, RD2, Ctx}
end.
-spec delete_resource(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
%% @doc Reset the bucket properties back to the default values
delete_resource(RD, Ctx=#ctx{bucket_type=T, bucket=B, client=C}) ->
riak_client:reset_bucket({T,B}, C),
{true, RD, Ctx}.
| null | https://raw.githubusercontent.com/basho/riak_kv/aeef1591704d32230b773d952a2f1543cbfa1889/src/riak_kv_wm_props.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
URLs that begin with `/types' are necessary for the new bucket
are for the default bucket type, and `/riak' is an old URL style,
also only works for the default bucket type.
It is possible to reconfigure the `/riak' prefix but that seems to
be rarely if ever used.
```
GET /types/Type/buckets/Bucket/props
GET /buckets/Bucket/props
GET /riak/Bucket'''
Get information about the named Bucket, in JSON form:
Each bucket property will be included in the `props' object.
`linkfun' and `chash_keyfun' properties will be encoded as
JSON objects of the form:
```
{"mod":ModuleName,
"fun":FunctionName}'''
a module and function.
```
PUT /types/Type/buckets/Bucket/props
PUT /buckets/Bucket/props
Modify bucket properties.
Content-type must be `application/json', and the body must have
the form:
`{"props":{Prop:Val}}'
Where the `props' object takes the same form as returned from
a GET of the same resource.
```
DELETE /types/Type/buckets/Bucket/props
DELETE /buckets/Bucket/props'''
Reset bucket properties back to the default settings
webmachine resource exports
binary() - Bucket type (from uri)
binary() - Bucket name (from uri)
riak_client() - the store client
string() - prefix for resource uris
local | {node(), atom()} - params for riak client
proplist() - properties of the bucket
atom() - HTTP method for the request
non_neg_integer() - old or new http api
security context
@doc Initialize this resource. This function extracts the
'prefix' and 'riak' properties from the dispatch args.
established. This function also takes this opportunity to extract
the 'bucket' bindings from the dispatch.
XXX 301 may be more appropriate here, but since the http and
https port are different and configurable, it is hard to figure
out the redirect URL to serve.
@doc Get the list of methods this resource supports.
@doc Determine whether query parameters, request headers,
and request body are badly-formed.
Body format is checked to be valid JSON, including
a "props" object for a bucket-PUT.
Must be a valid JSON object, containing a "props" object.
@doc Put an error about the format of the bucket-PUT body
@doc List the content types available for representing this resource.
"application/json" is the content-type for props requests.
@doc List the encodings available for representing this resource.
"identity" and "gzip" are available for props requests.
@doc Get the list of content types this resource will accept.
@doc Produce the bucket properties as JSON.
@doc Modify the bucket properties according to the body of the
@doc Reset the bucket properties back to the default values | riak_kv_wm_props : Webmachine resource for listing bucket properties .
Copyright ( c ) 2007 - 2013 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
@doc Resource for serving Riak bucket properties over HTTP .
types implementation in Riak 2.0 , those that begin with ` /buckets '
` { " props":{Prop1 : Val1,Prop2 : Val2 , ... } } '
Where ModuleName and FunctionName are each strings representing
PUT /riak / Bucket '' '
-module(riak_kv_wm_props).
-export([
init/1,
service_available/2,
is_authorized/2,
forbidden/2,
allowed_methods/2,
malformed_request/2,
content_types_provided/2,
encodings_provided/2,
content_types_accepted/2,
resource_exists/2,
produce_bucket_body/2,
accept_bucket_body/2,
get_bucket_props_json/2,
delete_resource/2
]).
}).
-type context() :: #ctx{}.
-include_lib("webmachine/include/webmachine.hrl").
-include("riak_kv_wm_raw.hrl").
-spec init(proplists:proplist()) -> {ok, context()}.
init(Props) ->
{ok, #ctx{
prefix=proplists:get_value(prefix, Props),
riak=proplists:get_value(riak, Props),
api_version=proplists:get_value(api_version,Props),
bucket_type=proplists:get_value(bucket_type, Props)
}}.
-spec service_available(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
@doc Determine whether or not a connection to can be
service_available(RD, Ctx0=#ctx{riak=RiakProps}) ->
Ctx = riak_kv_wm_utils:ensure_bucket_type(RD, Ctx0, #ctx.bucket_type),
case riak_kv_wm_utils:get_riak_client(RiakProps, riak_kv_wm_utils:get_client_id(RD)) of
{ok, C} ->
{true,
RD,
Ctx#ctx{
method=wrq:method(RD),
client=C,
bucket=case wrq:path_info(bucket, RD) of
undefined -> undefined;
B -> list_to_binary(riak_kv_wm_utils:maybe_decode_uri(RD, B))
end
}};
Error ->
{false,
wrq:set_resp_body(
io_lib:format("Unable to connect to Riak: ~p~n", [Error]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
is_authorized(ReqData, Ctx) ->
case riak_api_web_security:is_authorized(ReqData) of
false ->
{"Basic realm=\"Riak\"", ReqData, Ctx};
{true, SecContext} ->
{true, ReqData, Ctx#ctx{security=SecContext}};
insecure ->
{{halt, 426}, wrq:append_to_resp_body(<<"Security is enabled and "
"Riak does not accept credentials over HTTP. Try HTTPS "
"instead.">>, ReqData), Ctx}
end.
forbidden(RD, Ctx = #ctx{security=undefined}) ->
{riak_kv_wm_utils:is_forbidden(RD), RD, Ctx};
forbidden(RD, Ctx=#ctx{security=Security}) ->
case riak_kv_wm_utils:is_forbidden(RD) of
true ->
{true, RD, Ctx};
false ->
Perm = case Ctx#ctx.method of
'PUT' ->
"riak_core.set_bucket";
'GET' ->
"riak_core.get_bucket";
'HEAD' ->
"riak_core.get_bucket";
'DELETE' ->
"riak_core.set_bucket"
end,
Res = riak_core_security:check_permission({Perm,
{Ctx#ctx.bucket_type,
Ctx#ctx.bucket}},
Security),
case Res of
{false, Error, _} ->
RD1 = wrq:set_resp_header("Content-Type", "text/plain", RD),
{true, wrq:append_to_resp_body(unicode:characters_to_binary(Error, utf8, utf8), RD1), Ctx};
{true, _} ->
{false, RD, Ctx}
end
end.
-spec allowed_methods(#wm_reqdata{}, context()) ->
{[atom()], #wm_reqdata{}, context()}.
Properties allows HEAD , GET , and PUT .
allowed_methods(RD, Ctx) when Ctx#ctx.api_version =:= 1 ->
{['HEAD', 'GET', 'PUT'], RD, Ctx};
allowed_methods(RD, Ctx) when Ctx#ctx.api_version =:= 2;
Ctx#ctx.api_version =:= 3 ->
{['HEAD', 'GET', 'PUT', 'DELETE'], RD, Ctx}.
-spec malformed_request(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
malformed_request(RD, Ctx) when Ctx#ctx.method =:= 'PUT' ->
malformed_bucket_put(RD, Ctx);
malformed_request(RD, Ctx) ->
{false, RD, Ctx}.
-spec malformed_bucket_put(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
@doc Check the JSON format of a bucket - level PUT .
malformed_bucket_put(RD, Ctx) ->
case catch mochijson2:decode(wrq:req_body(RD)) of
{struct, Fields} ->
case proplists:get_value(?JSON_PROPS, Fields) of
{struct, Props} ->
{false, RD, Ctx#ctx{bucketprops=Props}};
_ ->
{true, bucket_format_message(RD), Ctx}
end;
_ ->
{true, bucket_format_message(RD), Ctx}
end.
-spec bucket_format_message(#wm_reqdata{}) -> #wm_reqdata{}.
in the response body of the # wm_reqdata { } .
bucket_format_message(RD) ->
wrq:append_to_resp_body(
["bucket PUT must be a JSON object of the form:\n",
"{\"",?JSON_PROPS,"\":{...bucket properties...}}"],
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)).
resource_exists(RD, Ctx) ->
{riak_kv_wm_utils:bucket_type_exists(Ctx#ctx.bucket_type), RD, Ctx}.
-spec content_types_provided(#wm_reqdata{}, context()) ->
{[{ContentType::string(), Producer::atom()}], #wm_reqdata{}, context()}.
content_types_provided(RD, Ctx) ->
{[{"application/json", produce_bucket_body}], RD, Ctx}.
-spec encodings_provided(#wm_reqdata{}, context()) ->
{[{Encoding::string(), Producer::function()}], #wm_reqdata{}, context()}.
encodings_provided(RD, Ctx) ->
{riak_kv_wm_utils:default_encodings(), RD, Ctx}.
-spec content_types_accepted(#wm_reqdata{}, context()) ->
{[{ContentType::string(), Acceptor::atom()}],
#wm_reqdata{}, context()}.
" application / json " is the only type accepted for props PUT .
content_types_accepted(RD, Ctx) ->
{[{"application/json", accept_bucket_body}], RD, Ctx}.
-spec produce_bucket_body(#wm_reqdata{}, context()) ->
{binary(), #wm_reqdata{}, context()}.
produce_bucket_body(RD, Ctx) ->
Client = Ctx#ctx.client,
Bucket = riak_kv_wm_utils:maybe_bucket_type(Ctx#ctx.bucket_type, Ctx#ctx.bucket),
JsonProps1 = get_bucket_props_json(Client, Bucket),
JsonProps2 = {struct, [JsonProps1]},
JsonProps3 = mochijson2:encode(JsonProps2),
{JsonProps3, RD, Ctx}.
get_bucket_props_json(Client, Bucket) ->
Props1 = riak_client:get_bucket(Bucket, Client),
Props2 = lists:map(fun riak_kv_wm_utils:jsonify_bucket_prop/1, Props1),
{?JSON_PROPS, {struct, Props2}}.
-spec accept_bucket_body(#wm_reqdata{}, context()) -> {true, #wm_reqdata{}, context()}.
bucket - level PUT request .
accept_bucket_body(RD, Ctx=#ctx{bucket_type=T, bucket=B, client=C, bucketprops=Props}) ->
ErlProps = lists:map(fun riak_kv_wm_utils:erlify_bucket_prop/1, Props),
case riak_client:set_bucket({T,B}, ErlProps, C) of
ok ->
{true, RD, Ctx};
{error, Details} ->
JSON = mochijson2:encode(Details),
RD2 = wrq:append_to_resp_body(JSON, RD),
{{halt, 400}, RD2, Ctx}
end.
-spec delete_resource(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
delete_resource(RD, Ctx=#ctx{bucket_type=T, bucket=B, client=C}) ->
riak_client:reset_bucket({T,B}, C),
{true, RD, Ctx}.
|
9f695ea75b99b5c46dbf75305913b9dbe89e68fbfb12756dab83b56fbc807443 | aaronallen8455/breakpoint | ApplicativeDo.hs | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE DerivingStrategies #
# LANGUAGE ApplicativeDo #
module ApplicativeDo
( testTree
) where
import qualified Data.Map as M
import Data.Maybe
import Test.Tasty
import Test.Tasty.HUnit
import Debug.Breakpoint
-- Needs to be a separate module b/c ApplicativeDo affects other tests
testTree :: TestTree
testTree = testGroup "ApplicativeDo"
[ testCase "applicative do bindings" applicativeDoBindings
, testCase "monadic binds scoped" monadicBindsScoped
]
applicativeDoBindings :: Assertion
applicativeDoBindings =
runM test1 @?= Just (M.fromList [("a", "True"), ("b", "False")])
newtype M a = M { runM :: Maybe a }
deriving newtype (Functor, Applicative)
test1 :: Applicative m => m (M.Map String String)
test1 = do
let b = False
a <- pure True
return captureVars
monadicBindsScoped :: Assertion
monadicBindsScoped = M.delete "m" test2 @?= M.fromList [("a", "True")]
test2 :: M.Map String String
test2 = fromMaybe mempty $ do
a <- Just True
NB : need to reference ' a ' here b / c of ApplicativeDo
b <- Just False
pure m
| null | https://raw.githubusercontent.com/aaronallen8455/breakpoint/b9103baedde3907670006c9b8bb729c9234ea231/test/ApplicativeDo.hs | haskell | Needs to be a separate module b/c ApplicativeDo affects other tests | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE DerivingStrategies #
# LANGUAGE ApplicativeDo #
module ApplicativeDo
( testTree
) where
import qualified Data.Map as M
import Data.Maybe
import Test.Tasty
import Test.Tasty.HUnit
import Debug.Breakpoint
testTree :: TestTree
testTree = testGroup "ApplicativeDo"
[ testCase "applicative do bindings" applicativeDoBindings
, testCase "monadic binds scoped" monadicBindsScoped
]
applicativeDoBindings :: Assertion
applicativeDoBindings =
runM test1 @?= Just (M.fromList [("a", "True"), ("b", "False")])
newtype M a = M { runM :: Maybe a }
deriving newtype (Functor, Applicative)
test1 :: Applicative m => m (M.Map String String)
test1 = do
let b = False
a <- pure True
return captureVars
monadicBindsScoped :: Assertion
monadicBindsScoped = M.delete "m" test2 @?= M.fromList [("a", "True")]
test2 :: M.Map String String
test2 = fromMaybe mempty $ do
a <- Just True
NB : need to reference ' a ' here b / c of ApplicativeDo
b <- Just False
pure m
|
cf62b8a971a11b3e1c4010670080ba699e17cc18200866a1ab829ecd19f5e288 | ivanjovanovic/sicp | e-4.19.scm | Exercise 4.19 . , , and
are arguing about the desired result of
; evaluating the expression
(let ((a 1))
(define (f x)
(define b (+ a x))
(define a 5)
(+ a b))
(f 10))
asserts that the result should be obtained using
the sequential rule for define : b is defined to be 11 ,
then a is defined to be 5 , so the result is 16 .
; objects that mutual recursion requires the simultaneous
; scope rule for internal procedure definitions, and that
; it is unreasonable to treat procedure names differently
; from other names. Thus, she argues for the mechanism
implemented in exercise 4.16 . This would lead to a
; being unassigned at the time that the value for b is to
be computed . Hence , in 's view the procedure
should produce an error . has a third opinion . She
; says that if the definitions of a and b are truly meant
to be simultaneous , then the value 5 for a should be
used in evaluating b. Hence , in 's view a should be
5 , b should be 15 , and the result should be 20 . Which
; (if any) of these viewpoints do you support? Can you
; devise a way to implement internal definitions so that
they behave as prefers ?
; ------------------------------------------------------------
; I would say that in order to keep the predictability of
; the computational model we use, and remove possibilities for ambiguous
; interpretations, throwing an error is good option, as authors suggest.
;
To implement Evas point of view , I guess it would need one more convention
; additional to the `sequental` scoping.
If there is a direct value definition as ( define a 5 ) , then variable
; should be initialized to that value and not unassigned, before all other definitions.
; That way using it in any other definition is straightforward.
| null | https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/4.1/e-4.19.scm | scheme | evaluating the expression
objects that mutual recursion requires the simultaneous
scope rule for internal procedure definitions, and that
it is unreasonable to treat procedure names differently
from other names. Thus, she argues for the mechanism
being unassigned at the time that the value for b is to
says that if the definitions of a and b are truly meant
(if any) of these viewpoints do you support? Can you
devise a way to implement internal definitions so that
------------------------------------------------------------
I would say that in order to keep the predictability of
the computational model we use, and remove possibilities for ambiguous
interpretations, throwing an error is good option, as authors suggest.
additional to the `sequental` scoping.
should be initialized to that value and not unassigned, before all other definitions.
That way using it in any other definition is straightforward. | Exercise 4.19 . , , and
are arguing about the desired result of
(let ((a 1))
(define (f x)
(define b (+ a x))
(define a 5)
(+ a b))
(f 10))
asserts that the result should be obtained using
the sequential rule for define : b is defined to be 11 ,
then a is defined to be 5 , so the result is 16 .
implemented in exercise 4.16 . This would lead to a
be computed . Hence , in 's view the procedure
should produce an error . has a third opinion . She
to be simultaneous , then the value 5 for a should be
used in evaluating b. Hence , in 's view a should be
5 , b should be 15 , and the result should be 20 . Which
they behave as prefers ?
To implement Evas point of view , I guess it would need one more convention
If there is a direct value definition as ( define a 5 ) , then variable
|
52e31d3c8a1063680d44c354e586c8f8eca40066db3b155dba910de9b536c559 | lispbuilder/lispbuilder | objects.lisp | ;;;;; Converted from the "Objects" Processing example at:
;;;;; ""
;;;;; (C)2006 Luke J Crook
(in-package #:sdl-examples)
(defvar *objects-width* 200)
(defvar *objects-height* 200)
(defclass m-rect ()
((x :accessor x :initarg :x)
(y :accessor y :initarg :y)
(w :accessor w :initarg :w)
(h :accessor h :initarg :h)
(d :accessor d :initform 0 :initarg :d)
(tt :accessor tt :initform 0 :initarg :tt)))
(defvar *r1* (make-instance 'm-rect :w 1 :x 134.0 :h 0.532 :y (* 0.083 *objects-height*) :d 10.0 :tt 60))
(defvar *r2* (make-instance 'm-rect :w 2 :x 44.0 :h 0.166 :y (* 0.332 *objects-height*) :d 5.0 :tt 50))
(defvar *r3* (make-instance 'm-rect :w 2 :x 58.0 :h 0.332 :y (* 0.4482 *objects-height*) :d 10.0 :tt 35))
(defvar *r4* (make-instance 'm-rect :w 1 :x 120.0 :h 0.0498 :y (* 0.913 *objects-height*) :d 15.0 :tt 60))
(defgeneric move-to-y (m-rect posy damping))
(defmethod move-to-y ((m-rect m-rect) posy damping)
(let ((dif (- (y m-rect) posy)))
(if (> (abs dif) 1)
(decf (y m-rect) (/ dif damping)))))
(defgeneric move-to-x (m-rect posx damping))
(defmethod move-to-x ((m-rect m-rect) posx damping)
(let ((dif (- (x m-rect) posx)))
(if (> (abs dif) 1)
(decf (x m-rect) (/ dif damping)))))
(defgeneric display (m-rect &key surface))
(defmethod display ((m-rect m-rect) &key (surface sdl:*default-display*))
(dotimes (i (tt m-rect))
(sdl:draw-box-* (sdl-base:to-int (sdl-base::clamp-to-sshort (+ (x m-rect)
(* i (+ (d m-rect)
(w m-rect))))))
(sdl-base:to-int (sdl-base::clamp-to-sshort (y m-rect)))
(sdl-base:to-int (sdl-base::clamp-to-sshort (w m-rect)))
(sdl-base:to-int (sdl-base::clamp-to-sshort (* (h m-rect)
(sdl:height surface))))
:surface surface
:color sdl:*white*)))
(defun objects ()
(let ((mouse-x 0) (mouse-y 0)
(100-frames-p (every-n-frames 100)))
(sdl:with-init ()
(sdl:window *objects-width* *objects-height*
:title-caption "Objects, from Processing.org")
(setf (sdl:frame-rate) 60)
(sdl:clear-display (sdl:color))
(sdl:initialise-default-font sdl:*font-5x7*)
(draw-fps "Calculating FPS....."
10 150 sdl:*default-font* sdl:*default-surface* t)
(sdl:with-events ()
(:quit-event () t)
(:video-expose-event () (sdl:update-display))
(:mouse-motion-event (:x x :y y)
(setf mouse-x x
mouse-y y))
(:idle ()
(sdl:clear-display sdl:*black*)
(display *r1*)
(display *r2*)
(display *r3*)
(display *r4*)
(move-to-x *r1* (- mouse-x (/ *objects-width* 2)) 30)
(move-to-x *r2* (mod (+ mouse-x (* *objects-width* 0.05)) *objects-width*) 20)
(move-to-x *r3* (/ mouse-x 4) 40)
(move-to-x *r4* (- mouse-x (/ *objects-width* 2)) 50)
(move-to-y *r1* (+ mouse-y (* *objects-height* 0.1)) 30)
(move-to-y *r2* (+ mouse-y (* *objects-height* 0.025)) 20)
(move-to-y *r3* (- mouse-y (* *objects-height* 0.025)) 40)
(move-to-y *r4* (- *objects-height* mouse-y) 50)
;; Optimization; Draw the font each frame,
but only render the font once every 100 frames .
(draw-fps (format nil "FPS : ~2$" (sdl:average-fps))
10 150 sdl:*default-font* sdl:*default-surface*
(funcall 100-frames-p))
(sdl:update-display))))))
| null | https://raw.githubusercontent.com/lispbuilder/lispbuilder/589b3c6d552bbec4b520f61388117d6c7b3de5ab/lispbuilder-sdl/examples/objects.lisp | lisp | Converted from the "Objects" Processing example at:
""
(C)2006 Luke J Crook
Optimization; Draw the font each frame, |
(in-package #:sdl-examples)
(defvar *objects-width* 200)
(defvar *objects-height* 200)
(defclass m-rect ()
((x :accessor x :initarg :x)
(y :accessor y :initarg :y)
(w :accessor w :initarg :w)
(h :accessor h :initarg :h)
(d :accessor d :initform 0 :initarg :d)
(tt :accessor tt :initform 0 :initarg :tt)))
(defvar *r1* (make-instance 'm-rect :w 1 :x 134.0 :h 0.532 :y (* 0.083 *objects-height*) :d 10.0 :tt 60))
(defvar *r2* (make-instance 'm-rect :w 2 :x 44.0 :h 0.166 :y (* 0.332 *objects-height*) :d 5.0 :tt 50))
(defvar *r3* (make-instance 'm-rect :w 2 :x 58.0 :h 0.332 :y (* 0.4482 *objects-height*) :d 10.0 :tt 35))
(defvar *r4* (make-instance 'm-rect :w 1 :x 120.0 :h 0.0498 :y (* 0.913 *objects-height*) :d 15.0 :tt 60))
(defgeneric move-to-y (m-rect posy damping))
(defmethod move-to-y ((m-rect m-rect) posy damping)
(let ((dif (- (y m-rect) posy)))
(if (> (abs dif) 1)
(decf (y m-rect) (/ dif damping)))))
(defgeneric move-to-x (m-rect posx damping))
(defmethod move-to-x ((m-rect m-rect) posx damping)
(let ((dif (- (x m-rect) posx)))
(if (> (abs dif) 1)
(decf (x m-rect) (/ dif damping)))))
(defgeneric display (m-rect &key surface))
(defmethod display ((m-rect m-rect) &key (surface sdl:*default-display*))
(dotimes (i (tt m-rect))
(sdl:draw-box-* (sdl-base:to-int (sdl-base::clamp-to-sshort (+ (x m-rect)
(* i (+ (d m-rect)
(w m-rect))))))
(sdl-base:to-int (sdl-base::clamp-to-sshort (y m-rect)))
(sdl-base:to-int (sdl-base::clamp-to-sshort (w m-rect)))
(sdl-base:to-int (sdl-base::clamp-to-sshort (* (h m-rect)
(sdl:height surface))))
:surface surface
:color sdl:*white*)))
(defun objects ()
(let ((mouse-x 0) (mouse-y 0)
(100-frames-p (every-n-frames 100)))
(sdl:with-init ()
(sdl:window *objects-width* *objects-height*
:title-caption "Objects, from Processing.org")
(setf (sdl:frame-rate) 60)
(sdl:clear-display (sdl:color))
(sdl:initialise-default-font sdl:*font-5x7*)
(draw-fps "Calculating FPS....."
10 150 sdl:*default-font* sdl:*default-surface* t)
(sdl:with-events ()
(:quit-event () t)
(:video-expose-event () (sdl:update-display))
(:mouse-motion-event (:x x :y y)
(setf mouse-x x
mouse-y y))
(:idle ()
(sdl:clear-display sdl:*black*)
(display *r1*)
(display *r2*)
(display *r3*)
(display *r4*)
(move-to-x *r1* (- mouse-x (/ *objects-width* 2)) 30)
(move-to-x *r2* (mod (+ mouse-x (* *objects-width* 0.05)) *objects-width*) 20)
(move-to-x *r3* (/ mouse-x 4) 40)
(move-to-x *r4* (- mouse-x (/ *objects-width* 2)) 50)
(move-to-y *r1* (+ mouse-y (* *objects-height* 0.1)) 30)
(move-to-y *r2* (+ mouse-y (* *objects-height* 0.025)) 20)
(move-to-y *r3* (- mouse-y (* *objects-height* 0.025)) 40)
(move-to-y *r4* (- *objects-height* mouse-y) 50)
but only render the font once every 100 frames .
(draw-fps (format nil "FPS : ~2$" (sdl:average-fps))
10 150 sdl:*default-font* sdl:*default-surface*
(funcall 100-frames-p))
(sdl:update-display))))))
|
cc2cdaeb90e03a7cbf654f7ffb2b917c2acf402e0e87bea151b2a66f360483aa | APTE/APTE | length_algorithm.mli | open Standard_library
val decide_trace_equivalence : Process.process -> Process.process -> bool
| null | https://raw.githubusercontent.com/APTE/APTE/d5f1bbd29c2fc324a6015ac50173a0cc8ad66623/Source/length_equivalence/length_algorithm.mli | ocaml | open Standard_library
val decide_trace_equivalence : Process.process -> Process.process -> bool
| |
68db2d8cfafd600a07b664420d0b4fdcb68882f367fb5028f3a85f32fbfac12b | S8A/htdp-exercises | ex342.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex342) (read-case-sensitive #t) (teachpacks ((lib "abstraction.rkt" "teachpack" "2htdp") (lib "dir.rkt" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "abstraction.rkt" "teachpack" "2htdp") (lib "dir.rkt" "teachpack" "htdp")) #f)))
(define file-part1 (make-file "part1" 99 ""))
(define file-part2 (make-file "part2" 52 ""))
(define file-part3 (make-file "part3" 17 ""))
(define file-hang (make-file "hang" 8 ""))
(define file-draw (make-file "draw" 2 ""))
(define file-docs-read (make-file "read!" 19 ""))
(define file-ts-read (make-file "read!" 10 ""))
(define dir-text (make-dir "Text" '() (list file-part1 file-part2 file-part3)))
(define dir-code (make-dir "Code" '() (list file-hang file-draw)))
(define dir-docs (make-dir "Docs" '() (list file-docs-read)))
(define dir-libs (make-dir "Libs" (list dir-code dir-docs) '()))
(define dir-ts (make-dir "TS" (list dir-text dir-libs) (list file-ts-read)))
; String Dir -> [Maybe Path]
; if there's a file f in the given directory tree, produce its path; otherwise
; produce #false
(define (find f d)
(local ((define this-dir-name (dir-name d))
; Dir -> Boolean
(define (file-in-dir? dir)
(member? f (map file-name (dir-files dir))))
; [List-of Dir] -> [Maybe Path]
(define (find-in-dirs lod)
(first (filter (lambda (item) (not (false? item)))
(map (lambda (dir) (find f dir)) lod)))))
(if (find? f d)
(cond
[(file-in-dir? d) (list this-dir-name f)]
[else (cons this-dir-name (find-in-dirs (dir-dirs d)))])
#false)))
(check-expect (find "read!" dir-text) #false)
(check-expect (find "read!" dir-code) #false)
(check-expect (find "read!" dir-docs) '("Docs" "read!"))
(check-expect (find "read!" dir-libs) '("Libs" "Docs" "read!"))
(check-expect (find "read!" dir-ts) '("TS" "read!"))
; String Dir -> [List-of Path]
; produces the lists of paths belonging to files named f in the given
; directory tree
(define (find-all f d)
(local ((define this-dir-name (dir-name d))
; Dir -> [List-of Path]
(define (find-everywhere dir)
(if (file-in-dir? dir)
(cons (list f) (find-in-dirs (dir-dirs dir)))
(find-in-dirs (dir-dirs dir))))
; Dir -> Boolean
(define (file-in-dir? dir)
(member? f (map file-name (dir-files dir))))
; [List-of Dir] -> [List-of Path]
(define (find-in-dirs lod)
(filter (lambda (item) (not (false? item)))
(foldr append '()
(map (lambda (dir) (find-all f dir)) lod)))))
(if (find? f d)
(map (lambda (path) (cons this-dir-name path))
(find-everywhere d))
'())))
(check-expect (find-all "read!" dir-text) '())
(check-expect (find-all "read!" dir-code) '())
(check-expect (find-all "read!" dir-docs) '(("Docs" "read!")))
(check-expect (find-all "read!" dir-libs) '(("Libs" "Docs" "read!")))
(check-expect (find-all "read!" dir-ts) '(("TS" "read!")
("TS" "Libs" "Docs" "read!")))
; String Dir -> Boolean
; determines whether a file named n exists in the given directory tree
(define (find? n d)
(or (member? n (map file-name (dir-files d)))
(ormap (lambda (sub) (find? n sub)) (dir-dirs d))))
| null | https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex342.rkt | racket | about the language level of this file in a form that our tools can easily process.
String Dir -> [Maybe Path]
if there's a file f in the given directory tree, produce its path; otherwise
produce #false
Dir -> Boolean
[List-of Dir] -> [Maybe Path]
String Dir -> [List-of Path]
produces the lists of paths belonging to files named f in the given
directory tree
Dir -> [List-of Path]
Dir -> Boolean
[List-of Dir] -> [List-of Path]
String Dir -> Boolean
determines whether a file named n exists in the given directory tree | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex342) (read-case-sensitive #t) (teachpacks ((lib "abstraction.rkt" "teachpack" "2htdp") (lib "dir.rkt" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "abstraction.rkt" "teachpack" "2htdp") (lib "dir.rkt" "teachpack" "htdp")) #f)))
(define file-part1 (make-file "part1" 99 ""))
(define file-part2 (make-file "part2" 52 ""))
(define file-part3 (make-file "part3" 17 ""))
(define file-hang (make-file "hang" 8 ""))
(define file-draw (make-file "draw" 2 ""))
(define file-docs-read (make-file "read!" 19 ""))
(define file-ts-read (make-file "read!" 10 ""))
(define dir-text (make-dir "Text" '() (list file-part1 file-part2 file-part3)))
(define dir-code (make-dir "Code" '() (list file-hang file-draw)))
(define dir-docs (make-dir "Docs" '() (list file-docs-read)))
(define dir-libs (make-dir "Libs" (list dir-code dir-docs) '()))
(define dir-ts (make-dir "TS" (list dir-text dir-libs) (list file-ts-read)))
(define (find f d)
(local ((define this-dir-name (dir-name d))
(define (file-in-dir? dir)
(member? f (map file-name (dir-files dir))))
(define (find-in-dirs lod)
(first (filter (lambda (item) (not (false? item)))
(map (lambda (dir) (find f dir)) lod)))))
(if (find? f d)
(cond
[(file-in-dir? d) (list this-dir-name f)]
[else (cons this-dir-name (find-in-dirs (dir-dirs d)))])
#false)))
(check-expect (find "read!" dir-text) #false)
(check-expect (find "read!" dir-code) #false)
(check-expect (find "read!" dir-docs) '("Docs" "read!"))
(check-expect (find "read!" dir-libs) '("Libs" "Docs" "read!"))
(check-expect (find "read!" dir-ts) '("TS" "read!"))
(define (find-all f d)
(local ((define this-dir-name (dir-name d))
(define (find-everywhere dir)
(if (file-in-dir? dir)
(cons (list f) (find-in-dirs (dir-dirs dir)))
(find-in-dirs (dir-dirs dir))))
(define (file-in-dir? dir)
(member? f (map file-name (dir-files dir))))
(define (find-in-dirs lod)
(filter (lambda (item) (not (false? item)))
(foldr append '()
(map (lambda (dir) (find-all f dir)) lod)))))
(if (find? f d)
(map (lambda (path) (cons this-dir-name path))
(find-everywhere d))
'())))
(check-expect (find-all "read!" dir-text) '())
(check-expect (find-all "read!" dir-code) '())
(check-expect (find-all "read!" dir-docs) '(("Docs" "read!")))
(check-expect (find-all "read!" dir-libs) '(("Libs" "Docs" "read!")))
(check-expect (find-all "read!" dir-ts) '(("TS" "read!")
("TS" "Libs" "Docs" "read!")))
(define (find? n d)
(or (member? n (map file-name (dir-files d)))
(ormap (lambda (sub) (find? n sub)) (dir-dirs d))))
|
e0ee2d2e45a4b7542266f8dc3134ff449a6bf7e899700525dee45b0c85059f69 | dasuxullebt/uxul-world | game-object-with-animation.lisp | Copyright 2009 - 2011
(in-package :uxul-world)
;; as many game-objects do have an animation related to them, instead
;; of just having a draw-method which will manually draw anything, we
;; declare a standard-class for that, with some useful methods.
(defclass game-object-with-animation (game-object)
((animation-translation :initarg :animation-translation
:accessor animation-translation
:initform (make-xy 0 0)
:documentation "The translation of the
animation (in double zoom).")
(animation :initarg :animation
:accessor animation
:documentation "The animation of this object")
(animation-bounds :initarg :animation-bounds
:accessor animation-bounds
:initform (make-xy 50 50)
:documentation "When drawing, objects outside the
screen are tried not to be drawn via SDL. This determines, how far
in every direction the graphics may go outside the
collision-rectangle. Try to keep this number small. If it is too
huge, you may get numeric errors. 50/50 should be sufficient for
most objects. If this value is nil, the object will always be
drawn.")))
(defmethod (setf animation) ((newval animation) (obj game-object-with-animation))
"Sets the animation and x and y-coordinates. Wont rewind the animation."
(setf (slot-value obj 'animation) newval)
(setf (x obj) (x obj))
(setf (y obj) (y obj))
(setf (visible obj) (visible obj)))
(defmethod (setf x) (newval (obj game-object-with-animation))
(call-next-method)
(setf (x (animation obj)) (+ (x obj) (x (animation-translation obj)))))
(defmethod (setf y) (newval (obj game-object-with-animation))
(call-next-method)
(setf (y (animation obj)) (+ (y obj) (y (animation-translation obj)))))
(defmethod (setf visible) (newval (obj game-object-with-animation))
(call-next-method)
(setf (visible (animation obj)) newval))
(defun rectangle-in-screen (obj)
(let ((bounds (animation-bounds obj)))
(if bounds
(rectangles-overlap
HAAAAAAAAAAAAAAACK
(- (x obj) (x bounds))
(- (y obj) (y bounds))
(+ (x obj) (width obj) (x bounds))
(+ (y obj) (height obj) (y bounds))
(- *current-translation-x*)
(- *current-translation-y*)
(- (ash +screen-width+ (- *zoom-ash*)) *current-translation-x*)
(- (ash +screen-height+ (- *zoom-ash*)) *current-translation-y*))
T))
)
(defmethod draw ((obj game-object-with-animation))
;(if (rectangle-in-screen obj)
(draw (animation obj))
;)
)
(defmethod shared-initialize :after ((instance game-object-with-animation) spam &rest
initargs &key &allow-other-keys)
(declare (ignore initargs))
(declare (ignore spam))
"Set the x and y-Coordinates in the drawable and the rectangle (this
had to be done by hand before)"
; (write (x instance))
; (write (y instance))
(setf (x instance) (x instance))
(setf (y instance) (y instance))
(setf (visible instance) (visible instance)))
| null | https://raw.githubusercontent.com/dasuxullebt/uxul-world/f05e44b099e5976411b3ef1f980ec616bd221425/game-object-with-animation.lisp | lisp | as many game-objects do have an animation related to them, instead
of just having a draw-method which will manually draw anything, we
declare a standard-class for that, with some useful methods.
(if (rectangle-in-screen obj)
)
(write (x instance))
(write (y instance)) | Copyright 2009 - 2011
(in-package :uxul-world)
(defclass game-object-with-animation (game-object)
((animation-translation :initarg :animation-translation
:accessor animation-translation
:initform (make-xy 0 0)
:documentation "The translation of the
animation (in double zoom).")
(animation :initarg :animation
:accessor animation
:documentation "The animation of this object")
(animation-bounds :initarg :animation-bounds
:accessor animation-bounds
:initform (make-xy 50 50)
:documentation "When drawing, objects outside the
screen are tried not to be drawn via SDL. This determines, how far
in every direction the graphics may go outside the
collision-rectangle. Try to keep this number small. If it is too
huge, you may get numeric errors. 50/50 should be sufficient for
most objects. If this value is nil, the object will always be
drawn.")))
(defmethod (setf animation) ((newval animation) (obj game-object-with-animation))
"Sets the animation and x and y-coordinates. Wont rewind the animation."
(setf (slot-value obj 'animation) newval)
(setf (x obj) (x obj))
(setf (y obj) (y obj))
(setf (visible obj) (visible obj)))
(defmethod (setf x) (newval (obj game-object-with-animation))
(call-next-method)
(setf (x (animation obj)) (+ (x obj) (x (animation-translation obj)))))
(defmethod (setf y) (newval (obj game-object-with-animation))
(call-next-method)
(setf (y (animation obj)) (+ (y obj) (y (animation-translation obj)))))
(defmethod (setf visible) (newval (obj game-object-with-animation))
(call-next-method)
(setf (visible (animation obj)) newval))
(defun rectangle-in-screen (obj)
(let ((bounds (animation-bounds obj)))
(if bounds
(rectangles-overlap
HAAAAAAAAAAAAAAACK
(- (x obj) (x bounds))
(- (y obj) (y bounds))
(+ (x obj) (width obj) (x bounds))
(+ (y obj) (height obj) (y bounds))
(- *current-translation-x*)
(- *current-translation-y*)
(- (ash +screen-width+ (- *zoom-ash*)) *current-translation-x*)
(- (ash +screen-height+ (- *zoom-ash*)) *current-translation-y*))
T))
)
(defmethod draw ((obj game-object-with-animation))
(draw (animation obj))
)
(defmethod shared-initialize :after ((instance game-object-with-animation) spam &rest
initargs &key &allow-other-keys)
(declare (ignore initargs))
(declare (ignore spam))
"Set the x and y-Coordinates in the drawable and the rectangle (this
had to be done by hand before)"
(setf (x instance) (x instance))
(setf (y instance) (y instance))
(setf (visible instance) (visible instance)))
|
7a638d86c385ff301505c8f421be42ad1b82dc8eb1fc4065a42e1a69e35a6092 | ggreif/omega | SyntaxExt.hs | module SyntaxExt where
import Auxillary
import Data.List(nub)
import ParserAll -- This for defining parsers
To import ParserAll you must define CommentDef.hs and TokenDef.hs
-- These should be in the same directory as this file.
import Data.Char(isLower)
import qualified Text.PrettyPrint.HughesPJ as PP
import Text.PrettyPrint.HughesPJ(Doc,text,int,(<>),(<+>),($$),($+$),render)
data SyntaxStyle = OLD | NEW
type SynAssoc a = Either a a
data SynExt t -- Syntax Extension
= Ox -- no extension
| Ix (String,Maybe (SynAssoc (t,t)),Maybe(t,t),Maybe (SynAssoc t),Maybe (SynAssoc (t,t)),Maybe t,Maybe t,Maybe t,Maybe (t,t,t,t))
| Parsex (String,SyntaxStyle,[(t,Int)],[(t,[t])])
data Extension t
[ x , y ; [ x ; y , z]i
4i ( 2+x)i
( a , b , c)i
| Recordx (SynAssoc [(t,t)]) (Maybe t) String -- {x=t,y=s ; zs}i {zs ; y=s,x=t}i
( e`3)i
| Unitx String -- ()i
| Itemx t String -- (e)i
| Applicativex t String -- (f a b)i
-------------------------------------------------------------
-- Show instances
instance Show a => Show (SynExt a) where
show Ox = "Ox"
show (Ix(k,l,n,p,r,t,u,i,a)) = "Ix "++k++f' "List" l++f "Nat" n++g' "Pair" p++f' "Record" r++g "Tick" t++g "Unit" u++g "Item" i++g "Applicative" a
where f nm Nothing = ""
f nm (Just(x,y)) = " "++nm++"["++show x++","++show y++"]"
f' nm (Just (Right x)) = f nm (Just x)
f' nm (Just (Left x)) = f ("Left"++nm) (Just x)
f' _ Nothing = ""
g nm Nothing = ""
g nm (Just x) = " "++nm++"["++show x++"]"
g' nm Nothing = ""
g' nm (Just (Right x)) = g nm (Just x)
g' nm (Just (Left x)) = g ("Left"++nm) (Just x)
show (Parsex(k,_,_,zs)) = "Px "++k++show zs
instance Show x => Show(Extension x) where
show (Listx ts' Nothing tag) = plist "[" ts "," ("]"++tag)
where (_, ts) = outLR ts'
show (Listx (Right ts) (Just t) tag) = plist "[" ts "," "; " ++ show t ++"]"++tag
show (Listx (Left ts) (Just t) tag) = "[" ++ show t ++ "; " ++ plist "" ts "," ("]"++tag)
show (Natx n Nothing tag) = show n++tag
show (Natx n (Just t) tag) = "("++show n++"+"++show t++")"++tag
show (Unitx tag) = "()"++tag
show (Itemx x tag) = "("++show x++")"++tag
show (Pairx ts' tag) = "("++ help ts ++")"++tag
where help [] = ""
help [x] = show x
help (x:xs) = show x++","++help xs
(_, ts) = outLR ts'
show (Recordx ts' Nothing tag) = plistf f "{" ts "," ("}"++tag)
where f (x,y) = show x++"="++show y
(_, ts) = outLR ts'
show (Recordx (Right ts) (Just ys) tag) = plistf f "{" ts "," (";"++show ys++"}"++tag)
where f (x,y) = show x++"="++show y
show (Recordx (Left ts) (Just ys) tag) = "{" ++ show ys ++ "; " ++ plistf f "" ts "," ("}"++tag)
where f (x,y) = show x++"="++show y
show (Tickx n t tag) = "("++show t++"`"++show n++")"++tag
show (Applicativex x tag) = "("++show x++")"++tag
extKey :: Extension a -> String
extKey (Listx xs _ s) = s
extKey (Recordx xs _ s) = s
extKey (Natx n _ s) = s
extKey (Unitx s) = s
extKey (Itemx x s) = s
extKey (Pairx xs s) = s
extKey (Tickx n x s) = s
extKey (Applicativex x s) = s
extName :: Extension a -> String
extName (Listx (Right xs) _ s) = "List"
extName (Listx (Left xs) _ s) = "LeftList"
extName (Recordx (Right xs) _ s) = "Record"
extName (Recordx (Left xs) _ s) = "LeftRecord"
extName (Natx n _ s) = "Nat"
extName (Unitx s) = "Unit"
extName (Itemx _ s) = "Item"
extName (Pairx (Right xs) s) = "Pair"
extName (Pairx (Left xs) s) = "LeftPair"
extName (Tickx n _ s) = "Tick"
extName (Applicativex _ s) = "Applicative"
outLR (Right xs) = (Right, xs)
outLR (Left xs) = (Left, xs)
----------------------------------------------------
-- Creating formatted documents
ppExt :: (a -> Doc) -> Extension a -> Doc
ppExt f((Listx (Right xs) (Just x) s)) = PP.sep (PP.lbrack: PP.punctuate PP.comma (map f xs)++[PP.semi,f x,text ("]"++s)])
ppExt f((Listx (Left xs) (Just x) s)) = PP.sep (PP.lbrack: f x: PP.semi: PP.punctuate PP.comma (map f xs)++[text ("]"++s)])
ppExt f((Listx xs' Nothing s)) = PP.sep (PP.lbrack: PP.punctuate PP.comma (map f xs)++[text ("]"++s)])
where (_, xs) = outLR xs'
ppExt f((Natx n (Just x) s)) = PP.hcat [PP.lparen,PP.int n,text "+",f x,text (")"++s)]
ppExt f((Natx n Nothing s)) = PP.hcat [PP.int n,text s]
ppExt f((Unitx s)) = text ("()"++s)
ppExt f((Itemx x s)) = PP.lparen <> f x <> text (")"++s)
ppExt f((Pairx xs' s)) = PP.lparen <> PP.hcat(PP.punctuate PP.comma (map f xs)) <> text (")"++s)
where (_, xs) = outLR xs'
ppExt f((Recordx (Right xs) (Just x) s)) = PP.lbrace <> PP.hcat(PP.punctuate PP.comma (map g xs)) <> PP.semi <> f x <> text ("}"++s)
where g (x,y) = f x <> PP.equals <> f y
ppExt f((Recordx (Left xs) (Just x) s)) = PP.lbrace <> f x <> PP.semi <> PP.hcat(PP.punctuate PP.comma (map g xs)) <> text ("}"++s)
where g (x,y) = f x <> PP.equals <> f y
ppExt f (Recordx xs' Nothing s) = PP.lbrace <> PP.hcat(PP.punctuate PP.comma (map g xs)) <> text ("}"++s)
where g (x,y) = f x <> PP.equals <> f y
(_, xs) = outLR xs'
ppExt f((Tickx n x s)) = PP.hcat [PP.lparen,f x,text "`",PP.int n,text (")"++s)]
ppExt f((Applicativex x s)) = PP.hcat [PP.lparen,f x,text (")"++s)]
-------------------------------------------------------
-- map and fold-like operations
extList :: Extension a -> [a]
extList ((Listx (Right xs) (Just x) _)) = x:xs
extList ((Listx (Left xs) (Just x) _)) = foldr (:) [x] xs
extList ((Listx xs' Nothing _)) = xs
where (_, xs) = outLR xs'
extList ((Recordx (Right xs) (Just x) _)) = (x: flat2 xs)
extList ((Recordx (Left xs) (Just x) _)) = foldr (:) [x] (flat2 xs)
extList ((Recordx xs' Nothing _)) = flat2 xs
where (_, xs) = outLR xs'
extList ((Natx n (Just x) _)) = [x]
extList ((Natx n Nothing _)) = []
extList ((Unitx _)) = []
extList ((Itemx x _)) = [x]
extList ((Pairx xs' _)) = xs
where (_, xs) = outLR xs'
extList ((Tickx n x _)) = [x]
extList ((Applicativex x _)) = [x]
instance Eq t => Eq (Extension t) where
(Listx (Right ts1) (Just t1) s1) == (Listx (Right xs1) (Just x1) s2) = s1==s2 && (t1:ts1)==(x1:xs1)
(Listx (Left ts1) (Just t1) s1) == (Listx (Left xs1) (Just x1) s2) = s1==s2 && (t1:ts1)==(x1:xs1)
(Listx ts1 Nothing s1) == (Listx xs1 Nothing s2) = s1==s2 && ts1==xs1
(Natx n (Just t1) s1) == (Natx m (Just x1) s2) = s1==s2 && t1==x1 && n==m
(Natx n Nothing s1) == (Natx m Nothing s2) = s1==s2 && n==m
(Unitx s) == (Unitx t) = s==t
(Itemx x s) == (Itemx y t) = x==y && s==t
(Pairx xs s) == (Pairx ys t) = xs==ys && s==t
(Recordx (Right ts1) (Just t1) s1) == (Recordx (Right xs1) (Just x1) s2) = s1==s2 && t1==x1 && ts1==xs1
(Recordx (Left ts1) (Just t1) s1) == (Recordx (Left xs1) (Just x1) s2) = s1==s2 && t1==x1 && ts1==xs1
(Recordx ts1 Nothing s1) == (Recordx xs1 Nothing s2) = s1==s2 && ts1==xs1
(Tickx n t1 s1) == (Tickx m x1 s2) = s1==s2 && t1==x1 && n==m
(Applicativex x s) == (Applicativex y t) = x==y && s==t
_ == _ = False
extM :: Monad a => (b -> a c) -> Extension b -> a (Extension c)
extM f (Listx (Right xs) (Just x) s) = do { ys <- mapM f xs; y <- f x; return((Listx (Right ys) (Just y) s))}
extM f (Listx (Left xs) (Just x) s) = do { y <- f x; ys <- mapM f xs; return((Listx (Left ys) (Just y) s))}
extM f (Listx xs' Nothing s) = do { ys <- mapM f xs; return((Listx (lr ys) Nothing s))}
where (lr, xs) = outLR xs'
extM f (Natx n (Just x) s) = do { y <- f x; return((Natx n (Just y) s))}
extM f (Natx n Nothing s) = return((Natx n Nothing s))
extM f (Unitx s) = return(Unitx s)
extM f (Itemx x s) = do { y <- f x; return((Itemx y s))}
extM f (Pairx xs' s) = do { ys <- mapM f xs; return((Pairx (lr ys) s))}
where (lr, xs) = outLR xs'
extM f (Recordx (Right xs) (Just x) s) = do { ys <- mapM g xs; y <- f x; return(Recordx (Right ys) (Just y) s)}
where g (x,y) = do { a <- f x; b <- f y; return(a,b) }
extM f (Recordx (Left xs) (Just x) s) = do { y <- f x; ys <- mapM g xs; return(Recordx (Left ys) (Just y) s)}
where g (x,y) = do { a <- f x; b <- f y; return(a,b) }
extM f (Recordx xs' Nothing s) = do { ys <- mapM g xs; return(Recordx (lr ys) Nothing s)}
where g (x,y) = do { a <- f x; b <- f y; return(a,b) }
(lr, xs) = outLR xs'
extM f (Tickx n x s) = do { y <- f x; return((Tickx n y s))}
extM f (Applicativex x s) = do { y <- f x; return((Applicativex y s))}
threadL f [] n = return([],n)
threadL f (x:xs) n =
do { (x',n1) <- f x n
; (xs',n2) <- threadL f xs n1
; return(x' : xs', n2)}
threadPair f (x,y) n = do { (a,n1) <- f x n; (b,n2) <- f y n1; return((a,b),n2)}
extThread :: Monad m => (b -> c -> m(d,c)) -> c -> Extension b -> m(Extension d,c)
extThread f n (Listx (Right xs) (Just x) s) =
do { (ys,n1) <- threadL f xs n; (y,n2) <- f x n1; return(Listx (Right ys) (Just y) s,n2)}
extThread f n (Listx (Left xs) (Just x) s) =
do { (y,n1) <- f x n; (ys,n2) <- threadL f xs n1; return(Listx (Left ys) (Just y) s,n2)}
extThread f n (Listx xs' Nothing s) =
do { (ys,n1) <- threadL f xs n; return(Listx (lr ys) Nothing s,n1)}
where (lr, xs) = outLR xs'
extThread f n (Natx m (Just x) s) = do { (y,n1) <- f x n; return(Natx m (Just y) s,n1)}
extThread f n (Natx m Nothing s) = return(Natx m Nothing s,n)
extThread f n (Unitx s) = return(Unitx s,n)
extThread f n (Itemx x s) = do { (y,n1) <- f x n; return(Itemx y s,n1)}
extThread f n (Pairx xs' s) = do { (ys,n1) <- threadL f xs n; return(Pairx (lr ys) s,n1)}
where (lr, xs) = outLR xs'
extThread f n (Recordx (Right xs) (Just x) s) =
do { (ys,n1) <- threadL (threadPair f) xs n; (y,n2) <- f x n1; return(Recordx (Right ys) (Just y) s,n2)}
extThread f n (Recordx (Left xs) (Just x) s) =
do { (y,n1) <- f x n; (ys,n2) <- threadL (threadPair f) xs n1; return(Recordx (Left ys) (Just y) s,n2)}
extThread f n (Recordx xs' Nothing s) =
do { (ys,n1) <- threadL (threadPair f) xs n; return(Recordx (lr ys) Nothing s,n1)}
where (lr, xs) = outLR xs'
extThread f n (Tickx m x s) = do { (y,n1) <- f x n; return(Tickx m y s,n1)}
cross f (x,y) = (f x,f y)
instance Functor Extension where
fmap f (Listx xs' (Just x) s) = (Listx (lr (map f xs)) (Just(f x)) s)
where (lr, xs) = outLR xs'
fmap f (Listx xs' Nothing s) = (Listx (lr (map f xs)) Nothing s)
where (lr, xs) = outLR xs'
fmap f (Natx n (Just x) s) = (Natx n (Just (f x)) s)
fmap f (Natx n Nothing s) = (Natx n Nothing s)
fmap f (Unitx s) = (Unitx s)
fmap f (Itemx x s) = (Itemx (f x) s)
fmap f (Pairx xs' s) = (Pairx (lr $ map f xs) s)
where (lr, xs) = outLR xs'
fmap f (Recordx xs' (Just x) s) = (Recordx (lr (map (cross f) xs)) (Just(f x)) s)
where (lr, xs) = outLR xs'
fmap f (Recordx xs' Nothing s) = (Recordx (lr (map (cross f) xs)) Nothing s)
where (lr, xs) = outLR xs'
fmap f (Tickx n x s) = (Tickx n (f x) s)
fmap f (Applicativex x s) = (Applicativex (f x) s)
--------------------------------------------------------
-- Other primitive operations like selection and equality
-- Equal if the same kind and the same key
instance Eq a => Eq (SynExt a) where
Ox == Ox = True
(Ix(k1,_,_,_,_,_,_,_,_)) == (Ix(k2,_,_,_,_,_,_,_,_)) = k1==k2
(Parsex(k1,_,_,_)) == (Parsex(k2,_,_,_)) = k1==k2
_ == _ = False
synKey Ox = ""
synKey (Ix (s,_,_,_,_,_,_,_,_)) = s
synKey (Parsex(s,_,_,_)) = s
synName Ox = ""
synName (Ix (s,Just(Right _),_,_,_,_,_,_,_)) = "List"
synName (Ix (s,Just(Left _),_,_,_,_,_,_,_)) = "LeftList"
synName (Ix (s,_,Just _,_,_,_,_,_,_)) = "Nat"
synName (Ix (s,_,_,Just(Right _),_,_,_,_,_)) = "Pair"
synName (Ix (s,_,_,Just(Left _),_,_,_,_,_)) = "LeftPair"
synName (Ix (s,_,_,_,Just(Right _),_,_,_,_)) = "Record"
synName (Ix (s,_,_,_,Just(Left _),_,_,_,_)) = "LeftRecord"
synName (Ix (s,_,_,_,_,Just _,_,_,_)) = "Tick"
synName (Ix (s,_,_,_,_,_,Just _,_,_)) = "Unit"
synName (Ix (s,_,_,_,_,_,_,Just _,_)) = "Item"
synName (Ix (s,_,_,_,_,_,_,_,Just _)) = "Applicative"
synName (Parsex (s,_,_,_)) = "Parse"
-- Both the name and the type match. Different types (i.e. List,Nat,Pair)
-- can use the same name.
matchExt (Listx (Right _) _ s) (Ix(t,Just(Right _),_,_,_,_,_,_,_)) | s==t = return True
matchExt (Listx (Left _) _ s) (Ix(t,Just(Left _),_,_,_,_,_,_,_)) | s==t = return True
matchExt (Natx _ _ s) (Ix(t,_,Just _,_,_,_,_,_,_)) | s==t = return True
matchExt (Unitx s) (Ix(t,_,_,_,_,_,Just _,_,_)) | s==t = return True
matchExt (Itemx _ s) (Ix(t,_,_,_,_,_,_,Just _,_)) | s==t = return True
matchExt (Pairx (Right _) s) (Ix(t,_,_,Just(Right _),_,_,_,_,_)) | s==t = return True
matchExt (Pairx (Left _) s) (Ix(t,_,_,Just(Left _),_,_,_,_,_)) | s==t = return True
matchExt (Recordx (Right _) _ s) (Ix(t,_,_,_,Just(Right _),_,_,_,_)) | s==t = return True
matchExt (Recordx (Left _) _ s) (Ix(t,_,_,_,Just(Left _),_,_,_,_)) | s==t = return True
matchExt (Tickx _ _ s) (Ix(t,_,_,_,_,Just _,_,_,_)) | s==t = return True
matchExt (Applicativex _ s) (Ix(t,_,_,_,_,_,_,_,Just _)) | s==t = return True
matchExt _ _ = return False
----------------------------------------------------------
-- Building such objects in an abstract manner
findM:: Monad m => String -> (a -> m Bool) -> [a] -> m a
findM mes p [] = fail mes
findM mes p (x:xs) =
do { b <- p x
; if b then return x else findM mes p xs}
-- harmonizeExt: correct inevitable little errors that happened during parsing
--
harmonizeExt x@(Listx (Right xs) Nothing s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Listx (Left xs) Nothing s
harmonizeExt x@(Listx (Right [h]) (Just t) s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Listx (Left [t]) (Just h) s
harmonizeExt x@(Recordx (Right xs) Nothing s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Recordx (Left xs) Nothing s
harmonizeExt x@(Pairx (Right xs) s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Pairx (Left xs) s
harmonizeExt x@(Itemx e s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Applicativex e s
harmonizeExt x _ = return x
data ApplicativeSyntaxDict a = AD { var :: a -> a
, app :: a -> a -> a
, lam :: a -> a -> a
, lt :: a -> a -> a -> a }
class ApplicativeSyntax a where
expandApplicative :: Show a => ApplicativeSyntaxDict a -> a -> a
expandApplicative _ a = error ("Cannot expand applicative: "++show a)
rot3 f a b c = f c a b
buildExt :: (Show c,Show b,Monad m,ApplicativeSyntax c) => String -> (b -> c,b -> c -> c,b -> c -> c -> c,b -> c -> c -> c -> c) ->
Extension c -> [SynExt b] -> m c
buildExt loc (lift0,lift1,lift2,lift3) x ys =
do { x <- harmonizeExt x ys
; y <- findM ("\nAt "++loc++
"\nCan't find a "++extName x++" syntax extension called: '"++
extKey x++"', for "++show x++"\n "++plistf show "" ys "\n " "")
(matchExt x) ys
; case (x,y) of
(Listx (Right xs) (Just x) _,Ix(tag,Just(Right(nil,cons)),_,_,_,_,_,_,_)) -> return(foldr (lift2 cons) x xs)
(Listx (Left xs) (Just x) _,Ix(tag,Just(Left(nil,cons)),_,_,_,_,_,_,_)) -> return(foldr (flip $ lift2 cons) x (reverse xs))
(Listx (Right xs) Nothing _,Ix(tag,Just(Right(nil,cons)),_,_,_,_,_,_,_)) -> return(foldr (lift2 cons) (lift0 nil) xs)
(Listx (Left xs) Nothing _,Ix(tag,Just(Left(nil,cons)),_,_,_,_,_,_,_)) -> return(foldr (flip $ lift2 cons) (lift0 nil) (reverse xs))
(Recordx (Right xs) (Just x) _,Ix(tag,_,_,_,Just(Right(nil,cons)),_,_,_,_)) -> return(foldr (uncurry(lift3 cons)) x xs)
(Recordx (Left xs) (Just x) _,Ix(tag,_,_,_,Just(Left(nil,cons)),_,_,_,_)) -> return(foldr (uncurry(rot3 $ lift3 cons)) x (reverse xs))
(Recordx (Right xs) Nothing _,Ix(tag,_,_,_,Just(Right(nil,cons)),_,_,_,_)) -> return(foldr (uncurry(lift3 cons)) (lift0 nil) xs)
(Recordx (Left xs) Nothing _,Ix(tag,_,_,_,Just(Left(nil,cons)),_,_,_,_)) -> return(foldr (uncurry(rot3 $ lift3 cons)) (lift0 nil) (reverse xs))
(Tickx n x _,Ix(tag,_,_,_,_,Just tick,_,_,_)) -> return(buildNat x (lift1 tick) n)
(Natx n (Just x) _,Ix(tag,_,Just(zero,succ),_,_,_,_,_,_)) -> return(buildNat x (lift1 succ) n)
(Natx n Nothing _,Ix(tag,_,Just(zero,succ),_,_,_,_,_,_)) -> return(buildNat (lift0 zero) (lift1 succ) n)
(Unitx _,Ix(tag,_,_,_,_,_,Just unit,_,_)) -> return(buildUnit (lift0 unit))
(Itemx x _,Ix(tag,_,_,_,_,_,_,Just item,_)) -> return(buildItem (lift1 item) x)
(Pairx (Right xs) _,Ix(tag,_,_,Just(Right pair),_,_,_,_,_)) -> return(buildTuple (lift2 pair) xs)
(Pairx (Left xs) _,Ix(tag,_,_,Just(Left pair),_,_,_,_,_)) -> return(buildTuple (flip $ lift2 pair) (reverse xs))
(Applicativex x _,Ix(tag,_,_,_,_,_,_,_,Just (va,ap,la,le))) -> return(expandApplicative dict x)
where dict = AD {var = lift1 va, app = lift2 ap, lam = lift2 la, lt = lift3 le}
_ -> fail ("\nSyntax extension: "++extKey x++" doesn't match use, at "++loc)}
buildNat :: (Eq a, Num a) => b -> (b -> b) -> a -> b
buildNat z s 0 = z
buildNat z s n = s(buildNat z s (n-1))
buildUnit unit = unit
buildItem item i = item i
buildTuple pair [] = error "No empty tuples: ()"
buildTuple pair [p] = p
buildTuple pair [x,y] = pair x y
buildTuple pair (x:xs) = pair x (buildTuple pair xs)
flat2 [] = []
flat2 ((a,b):xs) = a : b : flat2 xs
-----------------------------------------------------------------------
-- extensions for predefined data structures
listx = Ix("",Just$Right("[]",":"),Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing) -- Lx("","[]",":")
natx = Ix("n",Nothing,Just("Z","S"),Nothing,Nothing,Nothing,Nothing,Nothing,Nothing) -- Nx("n","Z","S")
( " " , " ( , ) " )
recordx = Ix("",Nothing,Nothing,Nothing,Just$Right("Rnil","Rcons"),Nothing,Nothing,Nothing,Nothing) -- Rx("","Rnil","Rcons")
tickx tag tick = Ix(tag,Nothing,Nothing,Nothing,Nothing,Just tick,Nothing,Nothing,Nothing)
normalList (Ix("",Just(Right("[]",":")),_,_,_,_,_,_,_)) = True
normalList _ = False
------------------------------------------------------
-- Recognizing Extension constructors
listCons c (Ix(k,Just(Right(nil,cons)),_,_,_,_,_,_,_)) = c==cons
listCons c _ = False
listNil c (Ix(k,Just(Right(nil,cons)),_,_,_,_,_,_,_)) = c==nil
listNil c _ = False
leftListCons c (Ix(k,Just(Left(nil,cons)),_,_,_,_,_,_,_)) = c==cons
leftListCons c _ = False
leftListNil c (Ix(k,Just(Left(nil,cons)),_,_,_,_,_,_,_)) = c==nil
leftListNil c _ = False
natZero c (Ix(k,_,Just(z,s),_,_,_,_,_,_)) = c==z
natZero c _ = False
natSucc c (Ix(k,_,Just(z,s),_,_,_,_,_,_)) = c==s
natSucc c _ = False
unitUnit c (Ix(k,_,_,_,_,_,Just unit,_,_)) = c==unit
unitUnit c _ = False
itemItem c (Ix(k,_,_,_,_,_,_,Just item,_)) = c==item
itemItem c _ = False
pairProd c (Ix(k,_,_,Just(Right prod),_,_,_,_,_)) = c==prod
pairProd c _ = False
leftPairProd c (Ix(k,_,_,Just(Left prod),_,_,_,_,_)) = c==prod
leftPairProd c _ = False
recordCons c (Ix(k,_,_,_,Just(Right(nil,cons)),_,_,_,_)) = c==cons
recordCons c _ = False
recordNil c (Ix(k,_,_,_,Just(Right(nil,cons)),_,_,_,_)) = c==nil
recordNil c _ = False
leftRecordCons c (Ix(k,_,_,_,Just(Left(nil,cons)),_,_,_,_)) = c==cons
leftRecordCons c _ = False
leftRecordNil c (Ix(k,_,_,_,Just(Left(nil,cons)),_,_,_,_)) = c==nil
leftRecordNil c _ = False
tickSucc c (Ix(k,_,_,_,_,Just succ,_,_,_)) = c==succ
tickSucc c _ = False
applicativeVar c (Ix(k,_,_,_,_,_,_,_,Just (var,_,_,_))) = c==var
applicativeVar _ _ = False
applicativeApply c (Ix(k,_,_,_,_,_,_,_,Just (_,app,_,_))) = c==app
applicativeApply _ _ = False
-- recognizing extension tags
listExt c x = listCons c x || listNil c x
leftListExt c x = leftListCons c x || leftListNil c x
natExt c x = natZero c x || natSucc c x
recordExt c x = recordCons c x || recordNil c x
leftRecordExt c x = leftRecordCons c x || leftRecordNil c x
-----------------------------------------------------------
Parsers for Syntactic Extensions
# " abc " [ x , y ; zs]i # 4 4i ( 2+x)i ( a , b , c)i { a = Int , b = String ; r}i
semiTailSeq left right elem tail buildf =
do { lexeme left
; xs <- sepBy elem comma
; x <- (do { semi; y <- tail; return(Just y)}) <|>
(return Nothing)
; right -- No lexeme here because the tag must follow immediately
; tag <- many (lower <|> char '\'')
; return(buildf xs x tag)}
semiHeadSeq left right head elem buildf =
do { lexeme left
; x <- head
; semi
; xs <- sepBy elem comma
; right -- No lexeme here because the tag must follow immediately
; tag <- many (lower <|> char '\'')
; return(buildf (Just x) xs tag)}
extP : : Parsec [ Char ] u a - > Parsec [ Char ] u ( Extension a )
extP p = try(lexeme(try(listP p) <|> leftListP p <|> parensP p <|> try(recP p) <|> leftRecP p))
where listP p = semiTailSeq (char '[') (char ']') p p (\xs x t -> Listx (Right xs) x t)
leftListP p = semiHeadSeq (char '[') (char ']') p p (\x xs t -> Listx (Left xs) x t)
recP p = semiTailSeq (char '{') (char '}') pair p (\xs x t -> Recordx (Right xs) x t)
where pair = do { x <- p; symbol "="; y <- p; return(x,y)}
leftRecP p = semiHeadSeq (char '{') (char '}') p pair (\x xs t -> Recordx (Left xs) x t)
where pair = do { x <- p; symbol "="; y <- p; return(x,y)}
parensP p =
do { f <- try(incr p) <|> try(seqX p) <|> try(tickP p)
; tag <- many lower
; return(f tag)}
incr p =
do { lexeme (char '(')
; n <- lexeme natNoSpace
; symbol "+"; x <- p
; char ')'
; return(Natx n (Just x))}
tickP p =
do { lexeme (char '(')
; x <- p
; symbol "`";
; n <- lexeme natNoSpace
; char ')'
; return(Tickx n x)}
seqX p =
do { lexeme (char '(')
; xs <- sepBy p comma
; char ')'
; return(pairlike xs)}
where pairlike xs "" = Pairx (Right xs) ""
pairlike [] tag = Unitx tag
pairlike [x] tag = Itemx x tag
pairlike xs tag = Pairx (Right xs) tag
natP : : Parsec [ Char ] u ( Extension a )
natP = try $ lexeme $
(do{ satisfy ('#'==); n <- natNoSpace; return(Natx n Nothing "n")}) <|>
(do{ n <- natNoSpace; tag <- many lower; return(Natx n Nothing tag)})
---------------------------------------------------------------------
mergey ("List",[a,b]) (Ix(k,Nothing,n,p,r,t,u,i,ap)) = Ix(k,Just$Right(a,b),n,p,r,t,u,i,ap)
mergey ("LeftList",[a,b]) (Ix(k,Nothing,n,p,r,t,u,i,ap)) = Ix(k,Just$Left(a,b),n,p,r,t,u,i,ap)
mergey ("Nat",[a,b]) (Ix(k,l,Nothing,p,r,t,u,i,ap)) = Ix(k,l,Just(a,b),p,r,t,u,i,ap)
mergey ("Unit",[a]) (Ix(k,l,n,p,r,t,Nothing,i,ap)) = Ix(k,l,n,p,r,t,Just a,i,ap)
mergey ("Item",[a]) (Ix(k,l,n,p,r,t,u,Nothing,ap)) = Ix(k,l,n,p,r,t,u,Just a,ap)
mergey ("Pair",[a]) (Ix(k,l,n,Nothing,r,t,u,i,ap)) = Ix(k,l,n,Just$Right a,r,t,u,i,ap)
mergey ("LeftPair",[a]) (Ix(k,l,n,Nothing,r,t,u,i,ap)) = Ix(k,l,n,Just$Left a,r,t,u,i,ap)
mergey ("Record",[a,b]) (Ix(k,l,n,p,Nothing,t,u,i,ap)) = Ix(k,l,n,p,Just$Right(a,b),t,u,i,ap)
mergey ("LeftRecord",[a,b]) (Ix(k,l,n,p,Nothing,t,u,i,ap)) = Ix(k,l,n,p,Just$Left(a,b),t,u,i,ap)
mergey ("Tick",[a]) (Ix(k,l,n,p,r,Nothing,u,i,ap)) = Ix(k,l,n,p,r,Just a,u,i,ap)
mergey ("Applicative",[v,a,lam,lt]) (Ix(k,l,n,p,r,t,u,i,Nothing)) = Ix(k,l,n,p,r,t,u,i,Just (v,a,lam,lt))
mergey _ i = i
-----------------------------------------------------------
-- check that in a syntactic extension like:
-- deriving syntax(i) List(A,B) Nat(C,D) Tick(G)
-- that the constructors (A,B,C,D,G) have the correct arity for
the extension they belong to ( 0,2 , 0,1 , 1 )
-- List Nat Tick
-- for each extension, the name of the roles, and their expected arities
expectedArities =
[("List",Just "LeftList",[("Nil ",0),("Cons ",2::Int)])
,("LeftList",Just "List",[("Nil ",0),("Snoc ",2)])
,("Nat" ,Nothing ,[("Zero ",0),("Succ ",1)])
,("Unit" ,Nothing ,[("Unit ",0)])
,("Item" ,Nothing ,[("Item ",1)])
,("Pair",Just "LeftPair",[("Pair ",2)])
,("LeftPair",Just "Pair",[("Pair ",2)])
,("Record",Just "LeftRecord",[("RecNil ",0),("RecCons",3)])
,("LeftRecord",Just "Record",[("RecNil ",0),("RecSnoc",3)])
,("Tick" ,Nothing ,[("Tick ",1)])
,("Applicative",Nothing ,[("Var ",1),("Apply ",2),("Lambda ",2),("Let ",3)])
]
-- Check a list of arities against the expected arities, indicate with
( False , _ ) if 1 ) arities do n't match
2 ) there are extra constructors with no corresponding role
3 ) there are too few constructors for the roles of that extension
checkArities name style expected actual =
case (expected,actual) of
([],[]) -> []
((c,n):xs,(d,m):ys) -> (n==m,(c,show n,d,show m),arityfix (n==m) d)
: checkArities name style xs ys
([] ,(d,m):ys) -> (False,(" "," ",d++" unexpected extra constructor",show m),extrafix style d)
: checkArities name style [] ys
((c,n):xs,[] ) -> (False,(c,show n,"? - missing role.","?"),missingfix style c)
: checkArities name style xs []
where suffix OLD = " from the deriving clause."
suffix NEW = " from the constructors of the data declaration."
arityfix True d = ""
arityfix False d = "Fix the arity of "++d++" in the data declaration."
extrafix OLD d = "Remove, extra constructor "++detrail d++" from the data declaration."
extrafix NEW d = "Remove, extra constructor "++detrail d++" from the syntax clause for "++name++"."
missingfix OLD c = "Add a constructor for "++detrail c++" to the data declaration."
missingfix NEW c = "Add a constructor for "++detrail c++" to the syntax clause for "++name++"."
suggestFix style [] = ""
suggestFix style ((True,_,fix): xs) = suggestFix style xs
suggestFix style ((False,_,fix): xs) = "\n "++fix ++ suggestFix style xs
detrail xs = reverse (dropWhile (==' ') (reverse xs))
fstOfTriple (x,y,z) = x
dropMid (x,y,z) = (x,z)
-- If the extension name doesn't fit, report an error
badName name = Right ("\n'"++name++"' is not a valid syntactic extension name, choose from: "++
plistf fstOfTriple "" expectedArities ", " ".\n")
reportRepeated name = Just ("'"++name++"' syntactic extension cannot be specified twice.")
reportIncompatible (name, Just reversed, _) = Just ("'"++name++"' and '"++reversed++"' syntactic extensions cannot be specified together.")
wellFormed (("List",_,_):_) (name@"List") (Ix(tag,Just(Right _),_,_,_,_,_,_,_)) = reportRepeated name
wellFormed (syn@("List",Just _, _):_) "List" (Ix(tag,Just(Left _),_,_,_,_,_,_,_)) = reportIncompatible syn
wellFormed (("LeftList",_,_):_) (name@"LeftList") (Ix(tag,Just(Left _),_,_,_,_,_,_,_)) = reportRepeated name
wellFormed (syn@("LeftList", Just no, _):_) "LeftList" (Ix(tag,Just(Right _),_,_,_,_,_,_,_)) = reportIncompatible syn
wellFormed (("Nat",_,_):_) (name@"Nat") (Ix(tag,_,Just _,_,_,_,_,_,_)) = reportRepeated name
wellFormed (("Unit",_,_):_) (name@"Unit") (Ix(tag,_,_,_,_,_,Just _,_,_)) = reportRepeated name
wellFormed (("Item",_,_):_) (name@"Item") (Ix(tag,_,_,_,_,_,_,Just _,_)) = reportRepeated name
wellFormed (("Pair",_,_):_) (name@"Pair") (Ix(tag,_,_,Just(Left _),_,_,_,_,_)) = reportRepeated name
wellFormed (syn@("Pair",Just _,_):_) "Pair" (Ix(tag,_,_,Just(Right _),_,_,_,_,_)) = reportIncompatible syn
wellFormed (("LeftPair",_,_):_) (name@"LeftPair") (Ix(tag,_,_,Just(Right _),_,_,_,_,_)) = reportRepeated name
wellFormed (syn@("LeftPair",Just _,_):_) "LeftPair" (Ix(tag,_,_,Just(Left _),_,_,_,_,_)) = reportIncompatible syn
wellFormed (("Record",_,_):_) (name@"Record") (Ix(tag,_,_,_,Just(Right _),_,_,_,_)) = reportRepeated name
wellFormed (syn@("Record",Just _,_):_) "Record" (Ix(tag,_,_,_,Just(Left _),_,_,_,_)) = reportIncompatible syn
wellFormed (("LeftRecord",_,_):_) (name@"LeftRecord") (Ix(tag,_,_,_,Just(Left _),_,_,_,_)) = reportRepeated name
wellFormed (syn@("LeftRecord",Just _,_):_) "LeftRecord" (Ix(tag,_,_,_,Just(Right _),_,_,_,_)) = reportIncompatible syn
wellFormed (("Tick",_,_):_) (name@"Tick") (Ix(tag,_,_,_,_,Just _,_,_,_)) = reportRepeated name
wellFormed (("Applicative",_,_):_) (name@"Applicative") (Ix(tag,_,_,_,_,_,_,_,Just _)) = reportRepeated name
wellFormed (_:rest) name info = wellFormed rest name info
wellFormed [] _ _ = Nothing
Check a list of extensions , and build a Ix synExt data structure
checkMany :: SyntaxStyle -> String -> [(String,[(String,Int)])] -> Either (SynExt String) String
checkMany style tag [] = Left (Ix(tag,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing))
checkMany style tag ((name,args):more) =
case checkMany style tag more of
Right x -> Right x
Left info ->
case (lookup name (map dropMid expectedArities), wellFormed expectedArities name info) of
(Nothing, _) -> badName name
(_, Just problem) -> Right problem
(Just expected, _) -> if not good then Right s else Left info'
where ans = checkArities name style expected args
good = all fstOfTriple ans
printname = case style of
OLD -> name++"("++tag++")"
NEW -> name++ plistf fst "(" args "," ")"
g (bool,(c,n,d,m),fix) = concat["\n ",c," ",n," ",m," ",d]
s = concat(["\nError in syntactic extension declaration ",printname
,"\n Expected Actual"
,"\n Role Arity Arity Constructor\n"]
++ map g ans) ++ fixes
fixes = if good then "" else "\n\nPossible fix(es):" ++ suggestFix style ans
info' = mergey (name,map fst args) info
duplicates [] = []
duplicates (x:xs) = nub(if elem x xs then x : duplicates xs else duplicates xs)
liftEither (Left x) = return x
liftEither (Right x) = fail x
checkClause arityCs (name,args) =
do { let printname = name++plistf id "(" args "," ")"
; ys <- mapM (computeArity printname arityCs) args
; return(name,ys) }
computeArity printname arityCs c =
case lookup c arityCs of
Nothing -> fail (concat["\nThe name "++c++", in the syntax derivation "
,printname,",\nis not amongst the declared"
," constructors: ",plistf fst "" arityCs ", " ".\n"])
Just n -> return (c,n)
wExt = Ix("w",Just$Right("Nil","Cons"),Just("Zero","Succ"),Just$Right "Pair",Just$Right("RNil","RCons"),
Just "Next",Just "Unit",Just "Item",Just ("Var","Apply","Lambda","Let"))
go x = case checkMany OLD "tag" x of
Left x -> putStrLn(show x)
Right y -> putStrLn y
| null | https://raw.githubusercontent.com/ggreif/omega/016a3b48313ec2c68e8d8ad60147015bc38f2767/src/SyntaxExt.hs | haskell | This for defining parsers
These should be in the same directory as this file.
Syntax Extension
no extension
{x=t,y=s ; zs}i {zs ; y=s,x=t}i
()i
(e)i
(f a b)i
-----------------------------------------------------------
Show instances
--------------------------------------------------
Creating formatted documents
-----------------------------------------------------
map and fold-like operations
------------------------------------------------------
Other primitive operations like selection and equality
Equal if the same kind and the same key
Both the name and the type match. Different types (i.e. List,Nat,Pair)
can use the same name.
--------------------------------------------------------
Building such objects in an abstract manner
harmonizeExt: correct inevitable little errors that happened during parsing
---------------------------------------------------------------------
extensions for predefined data structures
Lx("","[]",":")
Nx("n","Z","S")
Rx("","Rnil","Rcons")
----------------------------------------------------
Recognizing Extension constructors
recognizing extension tags
---------------------------------------------------------
No lexeme here because the tag must follow immediately
No lexeme here because the tag must follow immediately
-------------------------------------------------------------------
---------------------------------------------------------
check that in a syntactic extension like:
deriving syntax(i) List(A,B) Nat(C,D) Tick(G)
that the constructors (A,B,C,D,G) have the correct arity for
List Nat Tick
for each extension, the name of the roles, and their expected arities
Check a list of arities against the expected arities, indicate with
If the extension name doesn't fit, report an error | module SyntaxExt where
import Auxillary
import Data.List(nub)
To import ParserAll you must define CommentDef.hs and TokenDef.hs
import Data.Char(isLower)
import qualified Text.PrettyPrint.HughesPJ as PP
import Text.PrettyPrint.HughesPJ(Doc,text,int,(<>),(<+>),($$),($+$),render)
data SyntaxStyle = OLD | NEW
type SynAssoc a = Either a a
| Ix (String,Maybe (SynAssoc (t,t)),Maybe(t,t),Maybe (SynAssoc t),Maybe (SynAssoc (t,t)),Maybe t,Maybe t,Maybe t,Maybe (t,t,t,t))
| Parsex (String,SyntaxStyle,[(t,Int)],[(t,[t])])
data Extension t
[ x , y ; [ x ; y , z]i
4i ( 2+x)i
( a , b , c)i
( e`3)i
instance Show a => Show (SynExt a) where
show Ox = "Ox"
show (Ix(k,l,n,p,r,t,u,i,a)) = "Ix "++k++f' "List" l++f "Nat" n++g' "Pair" p++f' "Record" r++g "Tick" t++g "Unit" u++g "Item" i++g "Applicative" a
where f nm Nothing = ""
f nm (Just(x,y)) = " "++nm++"["++show x++","++show y++"]"
f' nm (Just (Right x)) = f nm (Just x)
f' nm (Just (Left x)) = f ("Left"++nm) (Just x)
f' _ Nothing = ""
g nm Nothing = ""
g nm (Just x) = " "++nm++"["++show x++"]"
g' nm Nothing = ""
g' nm (Just (Right x)) = g nm (Just x)
g' nm (Just (Left x)) = g ("Left"++nm) (Just x)
show (Parsex(k,_,_,zs)) = "Px "++k++show zs
instance Show x => Show(Extension x) where
show (Listx ts' Nothing tag) = plist "[" ts "," ("]"++tag)
where (_, ts) = outLR ts'
show (Listx (Right ts) (Just t) tag) = plist "[" ts "," "; " ++ show t ++"]"++tag
show (Listx (Left ts) (Just t) tag) = "[" ++ show t ++ "; " ++ plist "" ts "," ("]"++tag)
show (Natx n Nothing tag) = show n++tag
show (Natx n (Just t) tag) = "("++show n++"+"++show t++")"++tag
show (Unitx tag) = "()"++tag
show (Itemx x tag) = "("++show x++")"++tag
show (Pairx ts' tag) = "("++ help ts ++")"++tag
where help [] = ""
help [x] = show x
help (x:xs) = show x++","++help xs
(_, ts) = outLR ts'
show (Recordx ts' Nothing tag) = plistf f "{" ts "," ("}"++tag)
where f (x,y) = show x++"="++show y
(_, ts) = outLR ts'
show (Recordx (Right ts) (Just ys) tag) = plistf f "{" ts "," (";"++show ys++"}"++tag)
where f (x,y) = show x++"="++show y
show (Recordx (Left ts) (Just ys) tag) = "{" ++ show ys ++ "; " ++ plistf f "" ts "," ("}"++tag)
where f (x,y) = show x++"="++show y
show (Tickx n t tag) = "("++show t++"`"++show n++")"++tag
show (Applicativex x tag) = "("++show x++")"++tag
extKey :: Extension a -> String
extKey (Listx xs _ s) = s
extKey (Recordx xs _ s) = s
extKey (Natx n _ s) = s
extKey (Unitx s) = s
extKey (Itemx x s) = s
extKey (Pairx xs s) = s
extKey (Tickx n x s) = s
extKey (Applicativex x s) = s
extName :: Extension a -> String
extName (Listx (Right xs) _ s) = "List"
extName (Listx (Left xs) _ s) = "LeftList"
extName (Recordx (Right xs) _ s) = "Record"
extName (Recordx (Left xs) _ s) = "LeftRecord"
extName (Natx n _ s) = "Nat"
extName (Unitx s) = "Unit"
extName (Itemx _ s) = "Item"
extName (Pairx (Right xs) s) = "Pair"
extName (Pairx (Left xs) s) = "LeftPair"
extName (Tickx n _ s) = "Tick"
extName (Applicativex _ s) = "Applicative"
outLR (Right xs) = (Right, xs)
outLR (Left xs) = (Left, xs)
ppExt :: (a -> Doc) -> Extension a -> Doc
ppExt f((Listx (Right xs) (Just x) s)) = PP.sep (PP.lbrack: PP.punctuate PP.comma (map f xs)++[PP.semi,f x,text ("]"++s)])
ppExt f((Listx (Left xs) (Just x) s)) = PP.sep (PP.lbrack: f x: PP.semi: PP.punctuate PP.comma (map f xs)++[text ("]"++s)])
ppExt f((Listx xs' Nothing s)) = PP.sep (PP.lbrack: PP.punctuate PP.comma (map f xs)++[text ("]"++s)])
where (_, xs) = outLR xs'
ppExt f((Natx n (Just x) s)) = PP.hcat [PP.lparen,PP.int n,text "+",f x,text (")"++s)]
ppExt f((Natx n Nothing s)) = PP.hcat [PP.int n,text s]
ppExt f((Unitx s)) = text ("()"++s)
ppExt f((Itemx x s)) = PP.lparen <> f x <> text (")"++s)
ppExt f((Pairx xs' s)) = PP.lparen <> PP.hcat(PP.punctuate PP.comma (map f xs)) <> text (")"++s)
where (_, xs) = outLR xs'
ppExt f((Recordx (Right xs) (Just x) s)) = PP.lbrace <> PP.hcat(PP.punctuate PP.comma (map g xs)) <> PP.semi <> f x <> text ("}"++s)
where g (x,y) = f x <> PP.equals <> f y
ppExt f((Recordx (Left xs) (Just x) s)) = PP.lbrace <> f x <> PP.semi <> PP.hcat(PP.punctuate PP.comma (map g xs)) <> text ("}"++s)
where g (x,y) = f x <> PP.equals <> f y
ppExt f (Recordx xs' Nothing s) = PP.lbrace <> PP.hcat(PP.punctuate PP.comma (map g xs)) <> text ("}"++s)
where g (x,y) = f x <> PP.equals <> f y
(_, xs) = outLR xs'
ppExt f((Tickx n x s)) = PP.hcat [PP.lparen,f x,text "`",PP.int n,text (")"++s)]
ppExt f((Applicativex x s)) = PP.hcat [PP.lparen,f x,text (")"++s)]
extList :: Extension a -> [a]
extList ((Listx (Right xs) (Just x) _)) = x:xs
extList ((Listx (Left xs) (Just x) _)) = foldr (:) [x] xs
extList ((Listx xs' Nothing _)) = xs
where (_, xs) = outLR xs'
extList ((Recordx (Right xs) (Just x) _)) = (x: flat2 xs)
extList ((Recordx (Left xs) (Just x) _)) = foldr (:) [x] (flat2 xs)
extList ((Recordx xs' Nothing _)) = flat2 xs
where (_, xs) = outLR xs'
extList ((Natx n (Just x) _)) = [x]
extList ((Natx n Nothing _)) = []
extList ((Unitx _)) = []
extList ((Itemx x _)) = [x]
extList ((Pairx xs' _)) = xs
where (_, xs) = outLR xs'
extList ((Tickx n x _)) = [x]
extList ((Applicativex x _)) = [x]
instance Eq t => Eq (Extension t) where
(Listx (Right ts1) (Just t1) s1) == (Listx (Right xs1) (Just x1) s2) = s1==s2 && (t1:ts1)==(x1:xs1)
(Listx (Left ts1) (Just t1) s1) == (Listx (Left xs1) (Just x1) s2) = s1==s2 && (t1:ts1)==(x1:xs1)
(Listx ts1 Nothing s1) == (Listx xs1 Nothing s2) = s1==s2 && ts1==xs1
(Natx n (Just t1) s1) == (Natx m (Just x1) s2) = s1==s2 && t1==x1 && n==m
(Natx n Nothing s1) == (Natx m Nothing s2) = s1==s2 && n==m
(Unitx s) == (Unitx t) = s==t
(Itemx x s) == (Itemx y t) = x==y && s==t
(Pairx xs s) == (Pairx ys t) = xs==ys && s==t
(Recordx (Right ts1) (Just t1) s1) == (Recordx (Right xs1) (Just x1) s2) = s1==s2 && t1==x1 && ts1==xs1
(Recordx (Left ts1) (Just t1) s1) == (Recordx (Left xs1) (Just x1) s2) = s1==s2 && t1==x1 && ts1==xs1
(Recordx ts1 Nothing s1) == (Recordx xs1 Nothing s2) = s1==s2 && ts1==xs1
(Tickx n t1 s1) == (Tickx m x1 s2) = s1==s2 && t1==x1 && n==m
(Applicativex x s) == (Applicativex y t) = x==y && s==t
_ == _ = False
extM :: Monad a => (b -> a c) -> Extension b -> a (Extension c)
extM f (Listx (Right xs) (Just x) s) = do { ys <- mapM f xs; y <- f x; return((Listx (Right ys) (Just y) s))}
extM f (Listx (Left xs) (Just x) s) = do { y <- f x; ys <- mapM f xs; return((Listx (Left ys) (Just y) s))}
extM f (Listx xs' Nothing s) = do { ys <- mapM f xs; return((Listx (lr ys) Nothing s))}
where (lr, xs) = outLR xs'
extM f (Natx n (Just x) s) = do { y <- f x; return((Natx n (Just y) s))}
extM f (Natx n Nothing s) = return((Natx n Nothing s))
extM f (Unitx s) = return(Unitx s)
extM f (Itemx x s) = do { y <- f x; return((Itemx y s))}
extM f (Pairx xs' s) = do { ys <- mapM f xs; return((Pairx (lr ys) s))}
where (lr, xs) = outLR xs'
extM f (Recordx (Right xs) (Just x) s) = do { ys <- mapM g xs; y <- f x; return(Recordx (Right ys) (Just y) s)}
where g (x,y) = do { a <- f x; b <- f y; return(a,b) }
extM f (Recordx (Left xs) (Just x) s) = do { y <- f x; ys <- mapM g xs; return(Recordx (Left ys) (Just y) s)}
where g (x,y) = do { a <- f x; b <- f y; return(a,b) }
extM f (Recordx xs' Nothing s) = do { ys <- mapM g xs; return(Recordx (lr ys) Nothing s)}
where g (x,y) = do { a <- f x; b <- f y; return(a,b) }
(lr, xs) = outLR xs'
extM f (Tickx n x s) = do { y <- f x; return((Tickx n y s))}
extM f (Applicativex x s) = do { y <- f x; return((Applicativex y s))}
threadL f [] n = return([],n)
threadL f (x:xs) n =
do { (x',n1) <- f x n
; (xs',n2) <- threadL f xs n1
; return(x' : xs', n2)}
threadPair f (x,y) n = do { (a,n1) <- f x n; (b,n2) <- f y n1; return((a,b),n2)}
extThread :: Monad m => (b -> c -> m(d,c)) -> c -> Extension b -> m(Extension d,c)
extThread f n (Listx (Right xs) (Just x) s) =
do { (ys,n1) <- threadL f xs n; (y,n2) <- f x n1; return(Listx (Right ys) (Just y) s,n2)}
extThread f n (Listx (Left xs) (Just x) s) =
do { (y,n1) <- f x n; (ys,n2) <- threadL f xs n1; return(Listx (Left ys) (Just y) s,n2)}
extThread f n (Listx xs' Nothing s) =
do { (ys,n1) <- threadL f xs n; return(Listx (lr ys) Nothing s,n1)}
where (lr, xs) = outLR xs'
extThread f n (Natx m (Just x) s) = do { (y,n1) <- f x n; return(Natx m (Just y) s,n1)}
extThread f n (Natx m Nothing s) = return(Natx m Nothing s,n)
extThread f n (Unitx s) = return(Unitx s,n)
extThread f n (Itemx x s) = do { (y,n1) <- f x n; return(Itemx y s,n1)}
extThread f n (Pairx xs' s) = do { (ys,n1) <- threadL f xs n; return(Pairx (lr ys) s,n1)}
where (lr, xs) = outLR xs'
extThread f n (Recordx (Right xs) (Just x) s) =
do { (ys,n1) <- threadL (threadPair f) xs n; (y,n2) <- f x n1; return(Recordx (Right ys) (Just y) s,n2)}
extThread f n (Recordx (Left xs) (Just x) s) =
do { (y,n1) <- f x n; (ys,n2) <- threadL (threadPair f) xs n1; return(Recordx (Left ys) (Just y) s,n2)}
extThread f n (Recordx xs' Nothing s) =
do { (ys,n1) <- threadL (threadPair f) xs n; return(Recordx (lr ys) Nothing s,n1)}
where (lr, xs) = outLR xs'
extThread f n (Tickx m x s) = do { (y,n1) <- f x n; return(Tickx m y s,n1)}
cross f (x,y) = (f x,f y)
instance Functor Extension where
fmap f (Listx xs' (Just x) s) = (Listx (lr (map f xs)) (Just(f x)) s)
where (lr, xs) = outLR xs'
fmap f (Listx xs' Nothing s) = (Listx (lr (map f xs)) Nothing s)
where (lr, xs) = outLR xs'
fmap f (Natx n (Just x) s) = (Natx n (Just (f x)) s)
fmap f (Natx n Nothing s) = (Natx n Nothing s)
fmap f (Unitx s) = (Unitx s)
fmap f (Itemx x s) = (Itemx (f x) s)
fmap f (Pairx xs' s) = (Pairx (lr $ map f xs) s)
where (lr, xs) = outLR xs'
fmap f (Recordx xs' (Just x) s) = (Recordx (lr (map (cross f) xs)) (Just(f x)) s)
where (lr, xs) = outLR xs'
fmap f (Recordx xs' Nothing s) = (Recordx (lr (map (cross f) xs)) Nothing s)
where (lr, xs) = outLR xs'
fmap f (Tickx n x s) = (Tickx n (f x) s)
fmap f (Applicativex x s) = (Applicativex (f x) s)
instance Eq a => Eq (SynExt a) where
Ox == Ox = True
(Ix(k1,_,_,_,_,_,_,_,_)) == (Ix(k2,_,_,_,_,_,_,_,_)) = k1==k2
(Parsex(k1,_,_,_)) == (Parsex(k2,_,_,_)) = k1==k2
_ == _ = False
synKey Ox = ""
synKey (Ix (s,_,_,_,_,_,_,_,_)) = s
synKey (Parsex(s,_,_,_)) = s
synName Ox = ""
synName (Ix (s,Just(Right _),_,_,_,_,_,_,_)) = "List"
synName (Ix (s,Just(Left _),_,_,_,_,_,_,_)) = "LeftList"
synName (Ix (s,_,Just _,_,_,_,_,_,_)) = "Nat"
synName (Ix (s,_,_,Just(Right _),_,_,_,_,_)) = "Pair"
synName (Ix (s,_,_,Just(Left _),_,_,_,_,_)) = "LeftPair"
synName (Ix (s,_,_,_,Just(Right _),_,_,_,_)) = "Record"
synName (Ix (s,_,_,_,Just(Left _),_,_,_,_)) = "LeftRecord"
synName (Ix (s,_,_,_,_,Just _,_,_,_)) = "Tick"
synName (Ix (s,_,_,_,_,_,Just _,_,_)) = "Unit"
synName (Ix (s,_,_,_,_,_,_,Just _,_)) = "Item"
synName (Ix (s,_,_,_,_,_,_,_,Just _)) = "Applicative"
synName (Parsex (s,_,_,_)) = "Parse"
matchExt (Listx (Right _) _ s) (Ix(t,Just(Right _),_,_,_,_,_,_,_)) | s==t = return True
matchExt (Listx (Left _) _ s) (Ix(t,Just(Left _),_,_,_,_,_,_,_)) | s==t = return True
matchExt (Natx _ _ s) (Ix(t,_,Just _,_,_,_,_,_,_)) | s==t = return True
matchExt (Unitx s) (Ix(t,_,_,_,_,_,Just _,_,_)) | s==t = return True
matchExt (Itemx _ s) (Ix(t,_,_,_,_,_,_,Just _,_)) | s==t = return True
matchExt (Pairx (Right _) s) (Ix(t,_,_,Just(Right _),_,_,_,_,_)) | s==t = return True
matchExt (Pairx (Left _) s) (Ix(t,_,_,Just(Left _),_,_,_,_,_)) | s==t = return True
matchExt (Recordx (Right _) _ s) (Ix(t,_,_,_,Just(Right _),_,_,_,_)) | s==t = return True
matchExt (Recordx (Left _) _ s) (Ix(t,_,_,_,Just(Left _),_,_,_,_)) | s==t = return True
matchExt (Tickx _ _ s) (Ix(t,_,_,_,_,Just _,_,_,_)) | s==t = return True
matchExt (Applicativex _ s) (Ix(t,_,_,_,_,_,_,_,Just _)) | s==t = return True
matchExt _ _ = return False
findM:: Monad m => String -> (a -> m Bool) -> [a] -> m a
findM mes p [] = fail mes
findM mes p (x:xs) =
do { b <- p x
; if b then return x else findM mes p xs}
harmonizeExt x@(Listx (Right xs) Nothing s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Listx (Left xs) Nothing s
harmonizeExt x@(Listx (Right [h]) (Just t) s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Listx (Left [t]) (Just h) s
harmonizeExt x@(Recordx (Right xs) Nothing s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Recordx (Left xs) Nothing s
harmonizeExt x@(Pairx (Right xs) s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Pairx (Left xs) s
harmonizeExt x@(Itemx e s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Applicativex e s
harmonizeExt x _ = return x
data ApplicativeSyntaxDict a = AD { var :: a -> a
, app :: a -> a -> a
, lam :: a -> a -> a
, lt :: a -> a -> a -> a }
class ApplicativeSyntax a where
expandApplicative :: Show a => ApplicativeSyntaxDict a -> a -> a
expandApplicative _ a = error ("Cannot expand applicative: "++show a)
rot3 f a b c = f c a b
buildExt :: (Show c,Show b,Monad m,ApplicativeSyntax c) => String -> (b -> c,b -> c -> c,b -> c -> c -> c,b -> c -> c -> c -> c) ->
Extension c -> [SynExt b] -> m c
buildExt loc (lift0,lift1,lift2,lift3) x ys =
do { x <- harmonizeExt x ys
; y <- findM ("\nAt "++loc++
"\nCan't find a "++extName x++" syntax extension called: '"++
extKey x++"', for "++show x++"\n "++plistf show "" ys "\n " "")
(matchExt x) ys
; case (x,y) of
(Listx (Right xs) (Just x) _,Ix(tag,Just(Right(nil,cons)),_,_,_,_,_,_,_)) -> return(foldr (lift2 cons) x xs)
(Listx (Left xs) (Just x) _,Ix(tag,Just(Left(nil,cons)),_,_,_,_,_,_,_)) -> return(foldr (flip $ lift2 cons) x (reverse xs))
(Listx (Right xs) Nothing _,Ix(tag,Just(Right(nil,cons)),_,_,_,_,_,_,_)) -> return(foldr (lift2 cons) (lift0 nil) xs)
(Listx (Left xs) Nothing _,Ix(tag,Just(Left(nil,cons)),_,_,_,_,_,_,_)) -> return(foldr (flip $ lift2 cons) (lift0 nil) (reverse xs))
(Recordx (Right xs) (Just x) _,Ix(tag,_,_,_,Just(Right(nil,cons)),_,_,_,_)) -> return(foldr (uncurry(lift3 cons)) x xs)
(Recordx (Left xs) (Just x) _,Ix(tag,_,_,_,Just(Left(nil,cons)),_,_,_,_)) -> return(foldr (uncurry(rot3 $ lift3 cons)) x (reverse xs))
(Recordx (Right xs) Nothing _,Ix(tag,_,_,_,Just(Right(nil,cons)),_,_,_,_)) -> return(foldr (uncurry(lift3 cons)) (lift0 nil) xs)
(Recordx (Left xs) Nothing _,Ix(tag,_,_,_,Just(Left(nil,cons)),_,_,_,_)) -> return(foldr (uncurry(rot3 $ lift3 cons)) (lift0 nil) (reverse xs))
(Tickx n x _,Ix(tag,_,_,_,_,Just tick,_,_,_)) -> return(buildNat x (lift1 tick) n)
(Natx n (Just x) _,Ix(tag,_,Just(zero,succ),_,_,_,_,_,_)) -> return(buildNat x (lift1 succ) n)
(Natx n Nothing _,Ix(tag,_,Just(zero,succ),_,_,_,_,_,_)) -> return(buildNat (lift0 zero) (lift1 succ) n)
(Unitx _,Ix(tag,_,_,_,_,_,Just unit,_,_)) -> return(buildUnit (lift0 unit))
(Itemx x _,Ix(tag,_,_,_,_,_,_,Just item,_)) -> return(buildItem (lift1 item) x)
(Pairx (Right xs) _,Ix(tag,_,_,Just(Right pair),_,_,_,_,_)) -> return(buildTuple (lift2 pair) xs)
(Pairx (Left xs) _,Ix(tag,_,_,Just(Left pair),_,_,_,_,_)) -> return(buildTuple (flip $ lift2 pair) (reverse xs))
(Applicativex x _,Ix(tag,_,_,_,_,_,_,_,Just (va,ap,la,le))) -> return(expandApplicative dict x)
where dict = AD {var = lift1 va, app = lift2 ap, lam = lift2 la, lt = lift3 le}
_ -> fail ("\nSyntax extension: "++extKey x++" doesn't match use, at "++loc)}
buildNat :: (Eq a, Num a) => b -> (b -> b) -> a -> b
buildNat z s 0 = z
buildNat z s n = s(buildNat z s (n-1))
buildUnit unit = unit
buildItem item i = item i
buildTuple pair [] = error "No empty tuples: ()"
buildTuple pair [p] = p
buildTuple pair [x,y] = pair x y
buildTuple pair (x:xs) = pair x (buildTuple pair xs)
flat2 [] = []
flat2 ((a,b):xs) = a : b : flat2 xs
( " " , " ( , ) " )
tickx tag tick = Ix(tag,Nothing,Nothing,Nothing,Nothing,Just tick,Nothing,Nothing,Nothing)
normalList (Ix("",Just(Right("[]",":")),_,_,_,_,_,_,_)) = True
normalList _ = False
listCons c (Ix(k,Just(Right(nil,cons)),_,_,_,_,_,_,_)) = c==cons
listCons c _ = False
listNil c (Ix(k,Just(Right(nil,cons)),_,_,_,_,_,_,_)) = c==nil
listNil c _ = False
leftListCons c (Ix(k,Just(Left(nil,cons)),_,_,_,_,_,_,_)) = c==cons
leftListCons c _ = False
leftListNil c (Ix(k,Just(Left(nil,cons)),_,_,_,_,_,_,_)) = c==nil
leftListNil c _ = False
natZero c (Ix(k,_,Just(z,s),_,_,_,_,_,_)) = c==z
natZero c _ = False
natSucc c (Ix(k,_,Just(z,s),_,_,_,_,_,_)) = c==s
natSucc c _ = False
unitUnit c (Ix(k,_,_,_,_,_,Just unit,_,_)) = c==unit
unitUnit c _ = False
itemItem c (Ix(k,_,_,_,_,_,_,Just item,_)) = c==item
itemItem c _ = False
pairProd c (Ix(k,_,_,Just(Right prod),_,_,_,_,_)) = c==prod
pairProd c _ = False
leftPairProd c (Ix(k,_,_,Just(Left prod),_,_,_,_,_)) = c==prod
leftPairProd c _ = False
recordCons c (Ix(k,_,_,_,Just(Right(nil,cons)),_,_,_,_)) = c==cons
recordCons c _ = False
recordNil c (Ix(k,_,_,_,Just(Right(nil,cons)),_,_,_,_)) = c==nil
recordNil c _ = False
leftRecordCons c (Ix(k,_,_,_,Just(Left(nil,cons)),_,_,_,_)) = c==cons
leftRecordCons c _ = False
leftRecordNil c (Ix(k,_,_,_,Just(Left(nil,cons)),_,_,_,_)) = c==nil
leftRecordNil c _ = False
tickSucc c (Ix(k,_,_,_,_,Just succ,_,_,_)) = c==succ
tickSucc c _ = False
applicativeVar c (Ix(k,_,_,_,_,_,_,_,Just (var,_,_,_))) = c==var
applicativeVar _ _ = False
applicativeApply c (Ix(k,_,_,_,_,_,_,_,Just (_,app,_,_))) = c==app
applicativeApply _ _ = False
listExt c x = listCons c x || listNil c x
leftListExt c x = leftListCons c x || leftListNil c x
natExt c x = natZero c x || natSucc c x
recordExt c x = recordCons c x || recordNil c x
leftRecordExt c x = leftRecordCons c x || leftRecordNil c x
Parsers for Syntactic Extensions
# " abc " [ x , y ; zs]i # 4 4i ( 2+x)i ( a , b , c)i { a = Int , b = String ; r}i
semiTailSeq left right elem tail buildf =
do { lexeme left
; xs <- sepBy elem comma
; x <- (do { semi; y <- tail; return(Just y)}) <|>
(return Nothing)
; tag <- many (lower <|> char '\'')
; return(buildf xs x tag)}
semiHeadSeq left right head elem buildf =
do { lexeme left
; x <- head
; semi
; xs <- sepBy elem comma
; tag <- many (lower <|> char '\'')
; return(buildf (Just x) xs tag)}
extP : : Parsec [ Char ] u a - > Parsec [ Char ] u ( Extension a )
extP p = try(lexeme(try(listP p) <|> leftListP p <|> parensP p <|> try(recP p) <|> leftRecP p))
where listP p = semiTailSeq (char '[') (char ']') p p (\xs x t -> Listx (Right xs) x t)
leftListP p = semiHeadSeq (char '[') (char ']') p p (\x xs t -> Listx (Left xs) x t)
recP p = semiTailSeq (char '{') (char '}') pair p (\xs x t -> Recordx (Right xs) x t)
where pair = do { x <- p; symbol "="; y <- p; return(x,y)}
leftRecP p = semiHeadSeq (char '{') (char '}') p pair (\x xs t -> Recordx (Left xs) x t)
where pair = do { x <- p; symbol "="; y <- p; return(x,y)}
parensP p =
do { f <- try(incr p) <|> try(seqX p) <|> try(tickP p)
; tag <- many lower
; return(f tag)}
incr p =
do { lexeme (char '(')
; n <- lexeme natNoSpace
; symbol "+"; x <- p
; char ')'
; return(Natx n (Just x))}
tickP p =
do { lexeme (char '(')
; x <- p
; symbol "`";
; n <- lexeme natNoSpace
; char ')'
; return(Tickx n x)}
seqX p =
do { lexeme (char '(')
; xs <- sepBy p comma
; char ')'
; return(pairlike xs)}
where pairlike xs "" = Pairx (Right xs) ""
pairlike [] tag = Unitx tag
pairlike [x] tag = Itemx x tag
pairlike xs tag = Pairx (Right xs) tag
natP : : Parsec [ Char ] u ( Extension a )
natP = try $ lexeme $
(do{ satisfy ('#'==); n <- natNoSpace; return(Natx n Nothing "n")}) <|>
(do{ n <- natNoSpace; tag <- many lower; return(Natx n Nothing tag)})
mergey ("List",[a,b]) (Ix(k,Nothing,n,p,r,t,u,i,ap)) = Ix(k,Just$Right(a,b),n,p,r,t,u,i,ap)
mergey ("LeftList",[a,b]) (Ix(k,Nothing,n,p,r,t,u,i,ap)) = Ix(k,Just$Left(a,b),n,p,r,t,u,i,ap)
mergey ("Nat",[a,b]) (Ix(k,l,Nothing,p,r,t,u,i,ap)) = Ix(k,l,Just(a,b),p,r,t,u,i,ap)
mergey ("Unit",[a]) (Ix(k,l,n,p,r,t,Nothing,i,ap)) = Ix(k,l,n,p,r,t,Just a,i,ap)
mergey ("Item",[a]) (Ix(k,l,n,p,r,t,u,Nothing,ap)) = Ix(k,l,n,p,r,t,u,Just a,ap)
mergey ("Pair",[a]) (Ix(k,l,n,Nothing,r,t,u,i,ap)) = Ix(k,l,n,Just$Right a,r,t,u,i,ap)
mergey ("LeftPair",[a]) (Ix(k,l,n,Nothing,r,t,u,i,ap)) = Ix(k,l,n,Just$Left a,r,t,u,i,ap)
mergey ("Record",[a,b]) (Ix(k,l,n,p,Nothing,t,u,i,ap)) = Ix(k,l,n,p,Just$Right(a,b),t,u,i,ap)
mergey ("LeftRecord",[a,b]) (Ix(k,l,n,p,Nothing,t,u,i,ap)) = Ix(k,l,n,p,Just$Left(a,b),t,u,i,ap)
mergey ("Tick",[a]) (Ix(k,l,n,p,r,Nothing,u,i,ap)) = Ix(k,l,n,p,r,Just a,u,i,ap)
mergey ("Applicative",[v,a,lam,lt]) (Ix(k,l,n,p,r,t,u,i,Nothing)) = Ix(k,l,n,p,r,t,u,i,Just (v,a,lam,lt))
mergey _ i = i
the extension they belong to ( 0,2 , 0,1 , 1 )
expectedArities =
[("List",Just "LeftList",[("Nil ",0),("Cons ",2::Int)])
,("LeftList",Just "List",[("Nil ",0),("Snoc ",2)])
,("Nat" ,Nothing ,[("Zero ",0),("Succ ",1)])
,("Unit" ,Nothing ,[("Unit ",0)])
,("Item" ,Nothing ,[("Item ",1)])
,("Pair",Just "LeftPair",[("Pair ",2)])
,("LeftPair",Just "Pair",[("Pair ",2)])
,("Record",Just "LeftRecord",[("RecNil ",0),("RecCons",3)])
,("LeftRecord",Just "Record",[("RecNil ",0),("RecSnoc",3)])
,("Tick" ,Nothing ,[("Tick ",1)])
,("Applicative",Nothing ,[("Var ",1),("Apply ",2),("Lambda ",2),("Let ",3)])
]
( False , _ ) if 1 ) arities do n't match
2 ) there are extra constructors with no corresponding role
3 ) there are too few constructors for the roles of that extension
checkArities name style expected actual =
case (expected,actual) of
([],[]) -> []
((c,n):xs,(d,m):ys) -> (n==m,(c,show n,d,show m),arityfix (n==m) d)
: checkArities name style xs ys
([] ,(d,m):ys) -> (False,(" "," ",d++" unexpected extra constructor",show m),extrafix style d)
: checkArities name style [] ys
((c,n):xs,[] ) -> (False,(c,show n,"? - missing role.","?"),missingfix style c)
: checkArities name style xs []
where suffix OLD = " from the deriving clause."
suffix NEW = " from the constructors of the data declaration."
arityfix True d = ""
arityfix False d = "Fix the arity of "++d++" in the data declaration."
extrafix OLD d = "Remove, extra constructor "++detrail d++" from the data declaration."
extrafix NEW d = "Remove, extra constructor "++detrail d++" from the syntax clause for "++name++"."
missingfix OLD c = "Add a constructor for "++detrail c++" to the data declaration."
missingfix NEW c = "Add a constructor for "++detrail c++" to the syntax clause for "++name++"."
suggestFix style [] = ""
suggestFix style ((True,_,fix): xs) = suggestFix style xs
suggestFix style ((False,_,fix): xs) = "\n "++fix ++ suggestFix style xs
detrail xs = reverse (dropWhile (==' ') (reverse xs))
fstOfTriple (x,y,z) = x
dropMid (x,y,z) = (x,z)
badName name = Right ("\n'"++name++"' is not a valid syntactic extension name, choose from: "++
plistf fstOfTriple "" expectedArities ", " ".\n")
reportRepeated name = Just ("'"++name++"' syntactic extension cannot be specified twice.")
reportIncompatible (name, Just reversed, _) = Just ("'"++name++"' and '"++reversed++"' syntactic extensions cannot be specified together.")
wellFormed (("List",_,_):_) (name@"List") (Ix(tag,Just(Right _),_,_,_,_,_,_,_)) = reportRepeated name
wellFormed (syn@("List",Just _, _):_) "List" (Ix(tag,Just(Left _),_,_,_,_,_,_,_)) = reportIncompatible syn
wellFormed (("LeftList",_,_):_) (name@"LeftList") (Ix(tag,Just(Left _),_,_,_,_,_,_,_)) = reportRepeated name
wellFormed (syn@("LeftList", Just no, _):_) "LeftList" (Ix(tag,Just(Right _),_,_,_,_,_,_,_)) = reportIncompatible syn
wellFormed (("Nat",_,_):_) (name@"Nat") (Ix(tag,_,Just _,_,_,_,_,_,_)) = reportRepeated name
wellFormed (("Unit",_,_):_) (name@"Unit") (Ix(tag,_,_,_,_,_,Just _,_,_)) = reportRepeated name
wellFormed (("Item",_,_):_) (name@"Item") (Ix(tag,_,_,_,_,_,_,Just _,_)) = reportRepeated name
wellFormed (("Pair",_,_):_) (name@"Pair") (Ix(tag,_,_,Just(Left _),_,_,_,_,_)) = reportRepeated name
wellFormed (syn@("Pair",Just _,_):_) "Pair" (Ix(tag,_,_,Just(Right _),_,_,_,_,_)) = reportIncompatible syn
wellFormed (("LeftPair",_,_):_) (name@"LeftPair") (Ix(tag,_,_,Just(Right _),_,_,_,_,_)) = reportRepeated name
wellFormed (syn@("LeftPair",Just _,_):_) "LeftPair" (Ix(tag,_,_,Just(Left _),_,_,_,_,_)) = reportIncompatible syn
wellFormed (("Record",_,_):_) (name@"Record") (Ix(tag,_,_,_,Just(Right _),_,_,_,_)) = reportRepeated name
wellFormed (syn@("Record",Just _,_):_) "Record" (Ix(tag,_,_,_,Just(Left _),_,_,_,_)) = reportIncompatible syn
wellFormed (("LeftRecord",_,_):_) (name@"LeftRecord") (Ix(tag,_,_,_,Just(Left _),_,_,_,_)) = reportRepeated name
wellFormed (syn@("LeftRecord",Just _,_):_) "LeftRecord" (Ix(tag,_,_,_,Just(Right _),_,_,_,_)) = reportIncompatible syn
wellFormed (("Tick",_,_):_) (name@"Tick") (Ix(tag,_,_,_,_,Just _,_,_,_)) = reportRepeated name
wellFormed (("Applicative",_,_):_) (name@"Applicative") (Ix(tag,_,_,_,_,_,_,_,Just _)) = reportRepeated name
wellFormed (_:rest) name info = wellFormed rest name info
wellFormed [] _ _ = Nothing
Check a list of extensions , and build a Ix synExt data structure
checkMany :: SyntaxStyle -> String -> [(String,[(String,Int)])] -> Either (SynExt String) String
checkMany style tag [] = Left (Ix(tag,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing))
checkMany style tag ((name,args):more) =
case checkMany style tag more of
Right x -> Right x
Left info ->
case (lookup name (map dropMid expectedArities), wellFormed expectedArities name info) of
(Nothing, _) -> badName name
(_, Just problem) -> Right problem
(Just expected, _) -> if not good then Right s else Left info'
where ans = checkArities name style expected args
good = all fstOfTriple ans
printname = case style of
OLD -> name++"("++tag++")"
NEW -> name++ plistf fst "(" args "," ")"
g (bool,(c,n,d,m),fix) = concat["\n ",c," ",n," ",m," ",d]
s = concat(["\nError in syntactic extension declaration ",printname
,"\n Expected Actual"
,"\n Role Arity Arity Constructor\n"]
++ map g ans) ++ fixes
fixes = if good then "" else "\n\nPossible fix(es):" ++ suggestFix style ans
info' = mergey (name,map fst args) info
duplicates [] = []
duplicates (x:xs) = nub(if elem x xs then x : duplicates xs else duplicates xs)
liftEither (Left x) = return x
liftEither (Right x) = fail x
checkClause arityCs (name,args) =
do { let printname = name++plistf id "(" args "," ")"
; ys <- mapM (computeArity printname arityCs) args
; return(name,ys) }
computeArity printname arityCs c =
case lookup c arityCs of
Nothing -> fail (concat["\nThe name "++c++", in the syntax derivation "
,printname,",\nis not amongst the declared"
," constructors: ",plistf fst "" arityCs ", " ".\n"])
Just n -> return (c,n)
wExt = Ix("w",Just$Right("Nil","Cons"),Just("Zero","Succ"),Just$Right "Pair",Just$Right("RNil","RCons"),
Just "Next",Just "Unit",Just "Item",Just ("Var","Apply","Lambda","Let"))
go x = case checkMany OLD "tag" x of
Left x -> putStrLn(show x)
Right y -> putStrLn y
|
6840fc42e91fd148849f4d7ba703ee3aa87d1f3bdb6154fa8b9cffe22661aafb | ClojureBridge/drawing | lines.clj | (ns drawing.lines
(:require [quil.core :as q]))
(defn setup []
Set frame rate to 30 frames per second .
(q/frame-rate 30)
; Set color mode to RGB
(q/color-mode :rgb)
; Set color of line to Red
(q/stroke 255 0 0))
(defn mouse-color [x y]
"Calculate a color based on two values"
;TODO: Take a look at B (of RGB). Right now it is just 0.
[(mod x 255) (mod y 255) 0])
(defn draw []
; Throughout the draw function, get the position of the
; mouse with mouse-x and mouse-y
; Set the line color based on mouse position
(apply q/stroke (mouse-color (q/mouse-x) (q/mouse-y)))
; Draw a line from the origin to the position of the mouse
(q/line 0 0 (q/mouse-x) (q/mouse-y))
Draw a line from 200 pixels right from the top left
; to the position of the mouse
(q/line 200 0 (q/mouse-x) (q/mouse-y))
Draw a line from 200 pixels down from the top left
; to the position of the mouse
(q/line 0 200 (q/mouse-x) (q/mouse-y))
Draw a line from 200 pixels right and down from the top left
; to the position of the mouse
(q/line 200 200 (q/mouse-x) (q/mouse-y)))
(q/defsketch hello-lines
; Set the title of the sketch
:title "You can see lines"
; Set the size of the sketch
:size [500 500]
; setup function is called setup
:setup setup
; draw function is called draw
:draw draw
:features [:keep-on-top])
| null | https://raw.githubusercontent.com/ClojureBridge/drawing/5feabef315c4f61b316f38a42f5024e9da76bc41/src/drawing/lines.clj | clojure | Set color mode to RGB
Set color of line to Red
TODO: Take a look at B (of RGB). Right now it is just 0.
Throughout the draw function, get the position of the
mouse with mouse-x and mouse-y
Set the line color based on mouse position
Draw a line from the origin to the position of the mouse
to the position of the mouse
to the position of the mouse
to the position of the mouse
Set the title of the sketch
Set the size of the sketch
setup function is called setup
draw function is called draw | (ns drawing.lines
(:require [quil.core :as q]))
(defn setup []
Set frame rate to 30 frames per second .
(q/frame-rate 30)
(q/color-mode :rgb)
(q/stroke 255 0 0))
(defn mouse-color [x y]
"Calculate a color based on two values"
[(mod x 255) (mod y 255) 0])
(defn draw []
(apply q/stroke (mouse-color (q/mouse-x) (q/mouse-y)))
(q/line 0 0 (q/mouse-x) (q/mouse-y))
Draw a line from 200 pixels right from the top left
(q/line 200 0 (q/mouse-x) (q/mouse-y))
Draw a line from 200 pixels down from the top left
(q/line 0 200 (q/mouse-x) (q/mouse-y))
Draw a line from 200 pixels right and down from the top left
(q/line 200 200 (q/mouse-x) (q/mouse-y)))
(q/defsketch hello-lines
:title "You can see lines"
:size [500 500]
:setup setup
:draw draw
:features [:keep-on-top])
|
c7a3ded03fef8e9fcb1be38f2c9de8ee7106ca237dbbdd14300ee4f5c6847e87 | FestCat/festival-ca | nitech_us_slt_arctic_clunits.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;;
Carnegie Mellon University ; ; ;
and and ; ; ;
Copyright ( c ) 1998 - 2000 ; ; ;
All Rights Reserved . ; ; ;
;;; ;;;
;;; Permission is hereby granted, free of charge, to use and distribute ;;;
;;; this software and its documentation without restriction, including ;;;
;;; without limitation the rights to use, copy, modify, merge, publish, ;;;
;;; distribute, sublicense, and/or sell copies of this work, and to ;;;
;;; permit persons to whom this work is furnished to do so, subject to ;;;
;;; the following conditions: ;;;
1 . The code must retain the above copyright notice , this list of ; ; ;
;;; conditions and the following disclaimer. ;;;
2 . Any modifications must be clearly marked as such . ; ; ;
3 . Original authors ' names are not deleted . ; ; ;
4 . The authors ' names are not used to endorse or promote products ; ; ;
;;; derived from this software without specific prior written ;;;
;;; permission. ;;;
;;; ;;;
CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK ; ; ;
;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE ; ; ;
;;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , IN ; ; ;
;;; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
;;; THIS SOFTWARE. ;;;
;;; ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;
;;; A generic voice definition file for a clunits synthesizer ;;
;;; Customized for: nitech_us_slt_arctic ;;
;;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Ensure this version of festival has been compiled with clunits module
(require_module 'clunits)
(require 'clunits) ;; runtime scheme support
;;; Try to find the directory where the voice is, this may be from
;;; .../festival/lib/voices/ or from the current directory
(if (assoc 'nitech_us_slt_arctic_clunits voice-locations)
(defvar nitech_us_slt_arctic::clunits_dir
(cdr (assoc 'nitech_us_slt_arctic_clunits voice-locations)))
(defvar nitech_us_slt_arctic::clunits_dir (string-append (pwd) "/")))
;;; Did we succeed in finding it
(if (not (probe_file (path-append nitech_us_slt_arctic::clunits_dir "festvox/")))
(begin
(format stderr "nitech_us_slt_arctic::clunits: Can't find voice scm files they are not in\n")
(format stderr " %s\n" (path-append nitech_us_slt_arctic::clunits_dir "festvox/"))
(format stderr " Either the voice isn't linked in Festival library\n")
(format stderr " or you are starting festival in the wrong directory\n")
(error)))
;;; Add the directory contains general voice stuff to load-path
(set! load-path (cons (path-append nitech_us_slt_arctic::clunits_dir "festvox/")
load-path))
;;; Voice specific parameter are defined in each of the following
;;; files
(require 'nitech_us_slt_arctic_phoneset)
(require 'nitech_us_slt_arctic_tokenizer)
(require 'nitech_us_slt_arctic_tagger)
(require 'nitech_us_slt_arctic_lexicon)
(require 'nitech_us_slt_arctic_phrasing)
(require 'nitech_us_slt_arctic_intonation)
(require 'nitech_us_slt_arctic_duration)
(require 'nitech_us_slt_arctic_f0model)
(require 'nitech_us_slt_arctic_other)
;; ... and others as required
;;;
;;; Code specific to the clunits waveform synthesis method
;;;
;;; Flag to save multiple loading of db
(defvar nitech_us_slt_arctic::clunits_loaded nil)
;;; When set to non-nil clunits voices *always* use their closest voice
;;; this is used when generating the prompts
(defvar nitech_us_slt_arctic::clunits_prompting_stage nil)
;;; Flag to allow new lexical items to be added only once
(defvar nitech_us_slt_arctic::clunits_added_extra_lex_items nil)
;;; You may wish to change this (only used in building the voice)
(set! nitech_us_slt_arctic::closest_voice 'voice_kal_diphone)
;;; These are the parameters which are needed at run time
build time parameters are added to his list in nitech_us_slt_arctic_build.scm
(set! nitech_us_slt_arctic::dt_params
(list
(list 'db_dir nitech_us_slt_arctic::clunits_dir)
'(name nitech_us_slt_arctic)
'(index_name nitech_us_slt_arctic)
'(f0_join_weight 0.0)
'(join_weights
(0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 ))
'(trees_dir "festival/trees/")
'(catalogue_dir "festival/clunits/")
'(coeffs_dir "mcep/")
'(coeffs_ext ".mcep")
'(clunit_name_feat lisp_nitech_us_slt_arctic::clunit_name)
;; Run time parameters
'(join_method windowed)
;; if pitch mark extraction is bad this is better than the above
; '(join_method smoothedjoin)
; '(join_method modified_lpc)
'(continuity_weight 5)
' ( log_scores 1 ) ; ; good for high variance joins ( not so good for ldom )
'(optimal_coupling 1)
'(extend_selections 2)
'(pm_coeffs_dir "mcep/")
'(pm_coeffs_ext ".mcep")
'(sig_dir "wav/")
'(sig_ext ".wav")
; '(pm_coeffs_dir "lpc/")
' ( pm_coeffs_ext " .lpc " )
; '(sig_dir "lpc/")
; '(sig_ext ".res")
' ( clunits_debug 1 )
))
(define (nitech_us_slt_arctic::clunit_name i)
"(nitech_us_slt_arctic::clunit_name i)
Defines the unit name for unit selection for us. The can be modified
changes the basic classification of unit for the clustering. By default
this we just use the phone name, but you may want to make this, phone
plus previous phone (or something else)."
(let ((name (item.name i)))
(cond
((and (not nitech_us_slt_arctic::clunits_loaded)
(or (string-equal "h#" name)
(string-equal "1" (item.feat i "ignore"))
(and (string-equal "pau" name)
(or (string-equal "pau" (item.feat i "p.name"))
(string-equal "h#" (item.feat i "p.name")))
(string-equal "pau" (item.feat i "n.name")))))
"ignore")
((string-matches name "[aeiou].*")
(string-append
name
(item.feat i "R:SylStructure.parent.stress")))
((string-equal name "pau")
name)
(t
(string-append
name
(item.feat i "seg_onsetcoda"))))))
(define (nitech_us_slt_arctic::clunits_load)
"(nitech_us_slt_arctic::clunits_load)
Function that actual loads in the databases and selection trees.
SHould only be called once per session."
(set! dt_params nitech_us_slt_arctic::dt_params)
(set! clunits_params nitech_us_slt_arctic::dt_params)
(clunits:load_db clunits_params)
(load (string-append
(string-append
nitech_us_slt_arctic::clunits_dir "/"
(get_param 'trees_dir dt_params "trees/")
(get_param 'index_name dt_params "all")
".tree")))
(set! nitech_us_slt_arctic::clunits_clunit_selection_trees clunits_selection_trees)
(set! nitech_us_slt_arctic::clunits_loaded t))
(define (nitech_us_slt_arctic::voice_reset)
"(nitech_us_slt_arctic::voice_reset)
Reset global variables back to previous voice."
(nitech_us_slt_arctic::reset_phoneset)
(nitech_us_slt_arctic::reset_tokenizer)
(nitech_us_slt_arctic::reset_tagger)
(nitech_us_slt_arctic::reset_lexicon)
(nitech_us_slt_arctic::reset_phrasing)
(nitech_us_slt_arctic::reset_intonation)
(nitech_us_slt_arctic::reset_duration)
(nitech_us_slt_arctic::reset_f0model)
(nitech_us_slt_arctic::reset_other)
t
)
;; This function is called to setup a voice. It will typically
;; simply call functions that are defined in other files in this directory
;; Sometime these simply set up standard Festival modules othertimes
;; these will be specific to this voice.
;; Feel free to add to this list if your language requires it
(define (voice_nitech_us_slt_arctic_clunits)
"(voice_nitech_us_slt_arctic_clunits)
Define voice for us."
;; *always* required
(voice_reset)
;; Select appropriate phone set
(nitech_us_slt_arctic::select_phoneset)
;; Select appropriate tokenization
(nitech_us_slt_arctic::select_tokenizer)
;; For part of speech tagging
(nitech_us_slt_arctic::select_tagger)
(nitech_us_slt_arctic::select_lexicon)
For clunits selection you probably do n't want vowel reduction
;; the unit selection will do that
(if (string-equal "americanenglish" (Param.get 'Language))
(set! postlex_vowel_reduce_cart_tree nil))
(nitech_us_slt_arctic::select_phrasing)
(nitech_us_slt_arctic::select_intonation)
(nitech_us_slt_arctic::select_duration)
(nitech_us_slt_arctic::select_f0model)
Waveform synthesis model : clunits
Load in the clunits databases ( or select it if its already loaded )
(if (not nitech_us_slt_arctic::clunits_prompting_stage)
(begin
(if (not nitech_us_slt_arctic::clunits_loaded)
(nitech_us_slt_arctic::clunits_load)
(clunits:select 'nitech_us_slt_arctic))
(set! clunits_selection_trees
nitech_us_slt_arctic::clunits_clunit_selection_trees)
(Parameter.set 'Synth_Method 'Cluster)))
;; This is where you can modify power (and sampling rate) if desired
(set! after_synth_hooks nil)
; (set! after_synth_hooks
; (list
; (lambda (utt)
; (utt.wave.rescale utt 2.1))))
(set! current_voice_reset nitech_us_slt_arctic::voice_reset)
(set! current-voice 'nitech_us_slt_arctic_clunits)
)
(define (is_pau i)
(if (phone_is_silence (item.name i))
"1"
"0"))
(provide 'nitech_us_slt_arctic_clunits)
| null | https://raw.githubusercontent.com/FestCat/festival-ca/f6b2d9bf4fc4f77b80890ebb95770075ad36ccaf/src/data/festvox.orig/nitech_us_slt_arctic_clunits.scm | scheme |
;;;
; ;
; ;
; ;
; ;
;;;
Permission is hereby granted, free of charge, to use and distribute ;;;
this software and its documentation without restriction, including ;;;
without limitation the rights to use, copy, modify, merge, publish, ;;;
distribute, sublicense, and/or sell copies of this work, and to ;;;
permit persons to whom this work is furnished to do so, subject to ;;;
the following conditions: ;;;
; ;
conditions and the following disclaimer. ;;;
; ;
; ;
; ;
derived from this software without specific prior written ;;;
permission. ;;;
;;;
; ;
DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
; ;
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
; ;
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
THIS SOFTWARE. ;;;
;;;
;;
A generic voice definition file for a clunits synthesizer ;;
Customized for: nitech_us_slt_arctic ;;
;;
runtime scheme support
Try to find the directory where the voice is, this may be from
.../festival/lib/voices/ or from the current directory
Did we succeed in finding it
Add the directory contains general voice stuff to load-path
Voice specific parameter are defined in each of the following
files
... and others as required
Code specific to the clunits waveform synthesis method
Flag to save multiple loading of db
When set to non-nil clunits voices *always* use their closest voice
this is used when generating the prompts
Flag to allow new lexical items to be added only once
You may wish to change this (only used in building the voice)
These are the parameters which are needed at run time
Run time parameters
if pitch mark extraction is bad this is better than the above
'(join_method smoothedjoin)
'(join_method modified_lpc)
; good for high variance joins ( not so good for ldom )
'(pm_coeffs_dir "lpc/")
'(sig_dir "lpc/")
'(sig_ext ".res")
This function is called to setup a voice. It will typically
simply call functions that are defined in other files in this directory
Sometime these simply set up standard Festival modules othertimes
these will be specific to this voice.
Feel free to add to this list if your language requires it
*always* required
Select appropriate phone set
Select appropriate tokenization
For part of speech tagging
the unit selection will do that
This is where you can modify power (and sampling rate) if desired
(set! after_synth_hooks
(list
(lambda (utt)
(utt.wave.rescale utt 2.1)))) |
Ensure this version of festival has been compiled with clunits module
(require_module 'clunits)
(if (assoc 'nitech_us_slt_arctic_clunits voice-locations)
(defvar nitech_us_slt_arctic::clunits_dir
(cdr (assoc 'nitech_us_slt_arctic_clunits voice-locations)))
(defvar nitech_us_slt_arctic::clunits_dir (string-append (pwd) "/")))
(if (not (probe_file (path-append nitech_us_slt_arctic::clunits_dir "festvox/")))
(begin
(format stderr "nitech_us_slt_arctic::clunits: Can't find voice scm files they are not in\n")
(format stderr " %s\n" (path-append nitech_us_slt_arctic::clunits_dir "festvox/"))
(format stderr " Either the voice isn't linked in Festival library\n")
(format stderr " or you are starting festival in the wrong directory\n")
(error)))
(set! load-path (cons (path-append nitech_us_slt_arctic::clunits_dir "festvox/")
load-path))
(require 'nitech_us_slt_arctic_phoneset)
(require 'nitech_us_slt_arctic_tokenizer)
(require 'nitech_us_slt_arctic_tagger)
(require 'nitech_us_slt_arctic_lexicon)
(require 'nitech_us_slt_arctic_phrasing)
(require 'nitech_us_slt_arctic_intonation)
(require 'nitech_us_slt_arctic_duration)
(require 'nitech_us_slt_arctic_f0model)
(require 'nitech_us_slt_arctic_other)
(defvar nitech_us_slt_arctic::clunits_loaded nil)
(defvar nitech_us_slt_arctic::clunits_prompting_stage nil)
(defvar nitech_us_slt_arctic::clunits_added_extra_lex_items nil)
(set! nitech_us_slt_arctic::closest_voice 'voice_kal_diphone)
build time parameters are added to his list in nitech_us_slt_arctic_build.scm
(set! nitech_us_slt_arctic::dt_params
(list
(list 'db_dir nitech_us_slt_arctic::clunits_dir)
'(name nitech_us_slt_arctic)
'(index_name nitech_us_slt_arctic)
'(f0_join_weight 0.0)
'(join_weights
(0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 ))
'(trees_dir "festival/trees/")
'(catalogue_dir "festival/clunits/")
'(coeffs_dir "mcep/")
'(coeffs_ext ".mcep")
'(clunit_name_feat lisp_nitech_us_slt_arctic::clunit_name)
'(join_method windowed)
'(continuity_weight 5)
'(optimal_coupling 1)
'(extend_selections 2)
'(pm_coeffs_dir "mcep/")
'(pm_coeffs_ext ".mcep")
'(sig_dir "wav/")
'(sig_ext ".wav")
' ( pm_coeffs_ext " .lpc " )
' ( clunits_debug 1 )
))
(define (nitech_us_slt_arctic::clunit_name i)
"(nitech_us_slt_arctic::clunit_name i)
Defines the unit name for unit selection for us. The can be modified
changes the basic classification of unit for the clustering. By default
this we just use the phone name, but you may want to make this, phone
plus previous phone (or something else)."
(let ((name (item.name i)))
(cond
((and (not nitech_us_slt_arctic::clunits_loaded)
(or (string-equal "h#" name)
(string-equal "1" (item.feat i "ignore"))
(and (string-equal "pau" name)
(or (string-equal "pau" (item.feat i "p.name"))
(string-equal "h#" (item.feat i "p.name")))
(string-equal "pau" (item.feat i "n.name")))))
"ignore")
((string-matches name "[aeiou].*")
(string-append
name
(item.feat i "R:SylStructure.parent.stress")))
((string-equal name "pau")
name)
(t
(string-append
name
(item.feat i "seg_onsetcoda"))))))
(define (nitech_us_slt_arctic::clunits_load)
"(nitech_us_slt_arctic::clunits_load)
Function that actual loads in the databases and selection trees.
SHould only be called once per session."
(set! dt_params nitech_us_slt_arctic::dt_params)
(set! clunits_params nitech_us_slt_arctic::dt_params)
(clunits:load_db clunits_params)
(load (string-append
(string-append
nitech_us_slt_arctic::clunits_dir "/"
(get_param 'trees_dir dt_params "trees/")
(get_param 'index_name dt_params "all")
".tree")))
(set! nitech_us_slt_arctic::clunits_clunit_selection_trees clunits_selection_trees)
(set! nitech_us_slt_arctic::clunits_loaded t))
(define (nitech_us_slt_arctic::voice_reset)
"(nitech_us_slt_arctic::voice_reset)
Reset global variables back to previous voice."
(nitech_us_slt_arctic::reset_phoneset)
(nitech_us_slt_arctic::reset_tokenizer)
(nitech_us_slt_arctic::reset_tagger)
(nitech_us_slt_arctic::reset_lexicon)
(nitech_us_slt_arctic::reset_phrasing)
(nitech_us_slt_arctic::reset_intonation)
(nitech_us_slt_arctic::reset_duration)
(nitech_us_slt_arctic::reset_f0model)
(nitech_us_slt_arctic::reset_other)
t
)
(define (voice_nitech_us_slt_arctic_clunits)
"(voice_nitech_us_slt_arctic_clunits)
Define voice for us."
(voice_reset)
(nitech_us_slt_arctic::select_phoneset)
(nitech_us_slt_arctic::select_tokenizer)
(nitech_us_slt_arctic::select_tagger)
(nitech_us_slt_arctic::select_lexicon)
For clunits selection you probably do n't want vowel reduction
(if (string-equal "americanenglish" (Param.get 'Language))
(set! postlex_vowel_reduce_cart_tree nil))
(nitech_us_slt_arctic::select_phrasing)
(nitech_us_slt_arctic::select_intonation)
(nitech_us_slt_arctic::select_duration)
(nitech_us_slt_arctic::select_f0model)
Waveform synthesis model : clunits
Load in the clunits databases ( or select it if its already loaded )
(if (not nitech_us_slt_arctic::clunits_prompting_stage)
(begin
(if (not nitech_us_slt_arctic::clunits_loaded)
(nitech_us_slt_arctic::clunits_load)
(clunits:select 'nitech_us_slt_arctic))
(set! clunits_selection_trees
nitech_us_slt_arctic::clunits_clunit_selection_trees)
(Parameter.set 'Synth_Method 'Cluster)))
(set! after_synth_hooks nil)
(set! current_voice_reset nitech_us_slt_arctic::voice_reset)
(set! current-voice 'nitech_us_slt_arctic_clunits)
)
(define (is_pau i)
(if (phone_is_silence (item.name i))
"1"
"0"))
(provide 'nitech_us_slt_arctic_clunits)
|
e2bbd4799069c9c705d6dd673f95eff696a6ab7031d88bdd56e121074a9877be | vmchale/jacinda | Include.hs | module Jacinda.Include ( defaultIncludes
, resolveImport
) where
import Control.Exception (Exception, throwIO)
import Control.Monad (filterM)
import Data.List.Split (splitWhen)
import Data.Maybe (listToMaybe)
import Paths_jacinda (getDataDir)
import System.Directory (doesFileExist, getCurrentDirectory)
import System.Environment (lookupEnv)
import System.FilePath ((</>))
data ImportError = FileNotFound !FilePath ![FilePath] deriving (Show)
instance Exception ImportError where
defaultIncludes :: IO ([FilePath] -> [FilePath])
defaultIncludes = do
path <- jacPath
d <- getDataDir
dot <- getCurrentDirectory
pure $ (dot:) . (d:) . (++path)
|
jacPath :: IO [FilePath]
jacPath = maybe [] splitEnv <$> lookupEnv "JAC_PATH"
splitEnv :: String -> [FilePath]
splitEnv = splitWhen (== ':')
resolveImport :: [FilePath] -- ^ Places to look
-> FilePath
-> IO FilePath
resolveImport incl fp =
maybe (throwIO $ FileNotFound fp incl) pure . listToMaybe
=<< (filterM doesFileExist . fmap (</> fp) $ incl)
| null | https://raw.githubusercontent.com/vmchale/jacinda/c84bdac286e856ca631620d06b39dd988044574f/src/Jacinda/Include.hs | haskell | ^ Places to look | module Jacinda.Include ( defaultIncludes
, resolveImport
) where
import Control.Exception (Exception, throwIO)
import Control.Monad (filterM)
import Data.List.Split (splitWhen)
import Data.Maybe (listToMaybe)
import Paths_jacinda (getDataDir)
import System.Directory (doesFileExist, getCurrentDirectory)
import System.Environment (lookupEnv)
import System.FilePath ((</>))
data ImportError = FileNotFound !FilePath ![FilePath] deriving (Show)
instance Exception ImportError where
defaultIncludes :: IO ([FilePath] -> [FilePath])
defaultIncludes = do
path <- jacPath
d <- getDataDir
dot <- getCurrentDirectory
pure $ (dot:) . (d:) . (++path)
|
jacPath :: IO [FilePath]
jacPath = maybe [] splitEnv <$> lookupEnv "JAC_PATH"
splitEnv :: String -> [FilePath]
splitEnv = splitWhen (== ':')
-> FilePath
-> IO FilePath
resolveImport incl fp =
maybe (throwIO $ FileNotFound fp incl) pure . listToMaybe
=<< (filterM doesFileExist . fmap (</> fp) $ incl)
|
6bafae094b44b2644128e8cbc68db9f1b0b7f376c0622fb39dbd9b324e0c83b7 | choener/ADPfusion | GChr.hs |
module ADPfusion.Multi.GChr where
import Data.Array.Repa.Index
import Data.Strict.Tuple
import qualified Data.Vector.Fusion.Stream.Monadic as S
import qualified Data.Vector.Generic as VG
import Data.Array.Repa.Index.Points
import Data.Array.Repa.Index.Subword
import ADPfusion.Chr
import ADPfusion.Classes
import ADPfusion.Multi.Classes
type instance TermOf (Term ts (GChr r xs)) = TermOf ts :. r
* Multi - dim ' Subword 's .
TODO we want to evaluate @f xs $ j-1@ just once before the stream is
-- generated. Unfortunately, this will evaluate cases like index (-1) as well,
-- which leads to crashes. The code below is safe but slower. We should
-- incorporate a version that performs and @outerCheck@ in the code.
instance
( Monad m
, TermElm m ts is
) => TermElm m (Term ts (GChr r xs)) (is:.Subword) where
termStream (ts :! GChr f xs) (io:.Outer) (is:.ij@(Subword(i:.j)))
= S.map (\(zs :!: (zix:.kl) :!: zis :!: e) -> (zs :!: zix :!: (zis:.subword (j-1) j) :!: (e:.(f xs $ j-1))))
. termStream ts io is
. S.map (\(zs :!: zix :!: (zis:.kl)) -> (zs :!: (zix:.kl) :!: zis))
termStream (ts :! GChr f xs) (io:.Inner _ _) (is:.ij)
= S.map (\(zs :!: (zix:.kl@(Subword(k:.l))) :!: zis :!: e) -> let dta = f xs l in dta `seq` (zs :!: zix :!: (zis:.subword l (l+1)) :!: (e:.dta)))
. termStream ts io is
. S.map (\(zs :!: zix :!: (zis:.kl)) -> (zs :!: (zix:.kl) :!: zis))
# INLINE termStream #
instance
( TermValidIndex ts is
) => TermValidIndex (Term ts (GChr r xs)) (is:.Subword) where
termDimensionsValid (ts:!GChr _ xs) (prs:.(a:!:b:!:c)) (is:.Subword(i:.j))
= i>=a && j<=VG.length xs -c && i+b<=j && termDimensionsValid ts prs is
getTermParserRange (ts:!GChr _ _) (is:._) (prs:.(a:!:b:!:c))
= getTermParserRange ts is prs :. (a:!:b+1:!:max 0 (c-1))
termInnerOuter (ts:!_) (is:._) (ios:.io) = termInnerOuter ts is ios :. io
termLeftIndex (ts:!_) (is:.Subword (i:.j)) = termLeftIndex ts is :. subword i (j-1)
# INLINE termDimensionsValid #
# INLINE getTermParserRange #
# INLINE termInnerOuter #
{-# INLINE termLeftIndex #-}
-- * Multi-dim 'PointL's
-- | NOTE This instance is currently the only one using an "inline outer
-- check". If This behaves well, it could be possible to put checks for valid
-- indices inside the outerCheck function. (Currently disabled, as the compiler
chokes on four - way alignments ) .
instance
( Monad m
, TermElm m ts is
) => TermElm m (Term ts (GChr r xs)) (is:.PointL) where
termStream (ts :! GChr f xs) (io:.Outer) (is:.ij@(PointL(i:.j)))
= outerCheck ( j>0 )
. let dta = ( f xs $ j-1 ) in dta ` seq ` S.map ( \(zs : ! : ( zix:.kl ) : ! : : ! : e ) - > ( zs : ! : : ! : ( zis:.pointL ( j-1 ) j ) : ! : ( e:.dta ) ) )
= S.map (\(zs :!: (zix:.kl) :!: zis :!: e) -> (zs :!: zix :!: (zis:.pointL (j-1) j) :!: (e:.(f xs $ j-1))))
. termStream ts io is
. S.map (\(zs :!: zix :!: (zis:.kl)) -> (zs :!: (zix:.kl) :!: zis))
termStream (ts :! GChr f xs) (io:.Inner _ _) (is:.ij)
= S.map (\(zs :!: (zix:.kl@(PointL(k:.l))) :!: zis :!: e) -> let dta = f xs l in dta `seq` (zs :!: zix :!: (zis:.pointL l (l+1)) :!: (e:.dta)))
. termStream ts io is
. S.map (\(zs :!: zix :!: (zis:.kl)) -> (zs :!: (zix:.kl) :!: zis))
# INLINE termStream #
TODO auto - generated , check correctness
instance
( TermValidIndex ts is
) => TermValidIndex (Term ts (GChr r xs)) (is:.PointL) where
termDimensionsValid (ts:!GChr _ xs) (prs:.(a:!:b:!:c)) (is:.PointL(i:.j))
i>=a & & j<=VG.length xs -c & & i+b<=j & &
getTermParserRange (ts:!GChr _ _) (is:._) (prs:.(a:!:b:!:c))
= getTermParserRange ts is prs :. (a:!:b+1:!:max 0 (c-1))
termInnerOuter (ts:!_) (is:._) (ios:.io) = termInnerOuter ts is ios :. io
termLeftIndex (ts:!_) (is:.PointL (i:.j)) = termLeftIndex ts is :. pointL i (j-1)
# INLINE termDimensionsValid #
# INLINE getTermParserRange #
# INLINE termInnerOuter #
{-# INLINE termLeftIndex #-}
| null | https://raw.githubusercontent.com/choener/ADPfusion/fcbbf05d0f438883928077e3d8a7f1cbf8c2e58d/ADPfusion/Multi/GChr.hs | haskell | generated. Unfortunately, this will evaluate cases like index (-1) as well,
which leads to crashes. The code below is safe but slower. We should
incorporate a version that performs and @outerCheck@ in the code.
# INLINE termLeftIndex #
* Multi-dim 'PointL's
| NOTE This instance is currently the only one using an "inline outer
check". If This behaves well, it could be possible to put checks for valid
indices inside the outerCheck function. (Currently disabled, as the compiler
# INLINE termLeftIndex # |
module ADPfusion.Multi.GChr where
import Data.Array.Repa.Index
import Data.Strict.Tuple
import qualified Data.Vector.Fusion.Stream.Monadic as S
import qualified Data.Vector.Generic as VG
import Data.Array.Repa.Index.Points
import Data.Array.Repa.Index.Subword
import ADPfusion.Chr
import ADPfusion.Classes
import ADPfusion.Multi.Classes
type instance TermOf (Term ts (GChr r xs)) = TermOf ts :. r
* Multi - dim ' Subword 's .
TODO we want to evaluate @f xs $ j-1@ just once before the stream is
instance
( Monad m
, TermElm m ts is
) => TermElm m (Term ts (GChr r xs)) (is:.Subword) where
termStream (ts :! GChr f xs) (io:.Outer) (is:.ij@(Subword(i:.j)))
= S.map (\(zs :!: (zix:.kl) :!: zis :!: e) -> (zs :!: zix :!: (zis:.subword (j-1) j) :!: (e:.(f xs $ j-1))))
. termStream ts io is
. S.map (\(zs :!: zix :!: (zis:.kl)) -> (zs :!: (zix:.kl) :!: zis))
termStream (ts :! GChr f xs) (io:.Inner _ _) (is:.ij)
= S.map (\(zs :!: (zix:.kl@(Subword(k:.l))) :!: zis :!: e) -> let dta = f xs l in dta `seq` (zs :!: zix :!: (zis:.subword l (l+1)) :!: (e:.dta)))
. termStream ts io is
. S.map (\(zs :!: zix :!: (zis:.kl)) -> (zs :!: (zix:.kl) :!: zis))
# INLINE termStream #
instance
( TermValidIndex ts is
) => TermValidIndex (Term ts (GChr r xs)) (is:.Subword) where
termDimensionsValid (ts:!GChr _ xs) (prs:.(a:!:b:!:c)) (is:.Subword(i:.j))
= i>=a && j<=VG.length xs -c && i+b<=j && termDimensionsValid ts prs is
getTermParserRange (ts:!GChr _ _) (is:._) (prs:.(a:!:b:!:c))
= getTermParserRange ts is prs :. (a:!:b+1:!:max 0 (c-1))
termInnerOuter (ts:!_) (is:._) (ios:.io) = termInnerOuter ts is ios :. io
termLeftIndex (ts:!_) (is:.Subword (i:.j)) = termLeftIndex ts is :. subword i (j-1)
# INLINE termDimensionsValid #
# INLINE getTermParserRange #
# INLINE termInnerOuter #
chokes on four - way alignments ) .
instance
( Monad m
, TermElm m ts is
) => TermElm m (Term ts (GChr r xs)) (is:.PointL) where
termStream (ts :! GChr f xs) (io:.Outer) (is:.ij@(PointL(i:.j)))
= outerCheck ( j>0 )
. let dta = ( f xs $ j-1 ) in dta ` seq ` S.map ( \(zs : ! : ( zix:.kl ) : ! : : ! : e ) - > ( zs : ! : : ! : ( zis:.pointL ( j-1 ) j ) : ! : ( e:.dta ) ) )
= S.map (\(zs :!: (zix:.kl) :!: zis :!: e) -> (zs :!: zix :!: (zis:.pointL (j-1) j) :!: (e:.(f xs $ j-1))))
. termStream ts io is
. S.map (\(zs :!: zix :!: (zis:.kl)) -> (zs :!: (zix:.kl) :!: zis))
termStream (ts :! GChr f xs) (io:.Inner _ _) (is:.ij)
= S.map (\(zs :!: (zix:.kl@(PointL(k:.l))) :!: zis :!: e) -> let dta = f xs l in dta `seq` (zs :!: zix :!: (zis:.pointL l (l+1)) :!: (e:.dta)))
. termStream ts io is
. S.map (\(zs :!: zix :!: (zis:.kl)) -> (zs :!: (zix:.kl) :!: zis))
# INLINE termStream #
TODO auto - generated , check correctness
instance
( TermValidIndex ts is
) => TermValidIndex (Term ts (GChr r xs)) (is:.PointL) where
termDimensionsValid (ts:!GChr _ xs) (prs:.(a:!:b:!:c)) (is:.PointL(i:.j))
i>=a & & j<=VG.length xs -c & & i+b<=j & &
getTermParserRange (ts:!GChr _ _) (is:._) (prs:.(a:!:b:!:c))
= getTermParserRange ts is prs :. (a:!:b+1:!:max 0 (c-1))
termInnerOuter (ts:!_) (is:._) (ios:.io) = termInnerOuter ts is ios :. io
termLeftIndex (ts:!_) (is:.PointL (i:.j)) = termLeftIndex ts is :. pointL i (j-1)
# INLINE termDimensionsValid #
# INLINE getTermParserRange #
# INLINE termInnerOuter #
|
21280605a907b99b0f941e3f12da9e1561155f553dcd6e57c73207e2604e26a3 | owlbarn/owl_ode | symplectic_d.mli |
* OWL - OCaml Scientific and Engineering Computing
* OWL - ODE - Ordinary Differential Equation Solvers
*
* Copyright ( c ) 2019 >
* Copyright ( c ) 2019 < >
* OWL - OCaml Scientific and Engineering Computing
* OWL-ODE - Ordinary Differential Equation Solvers
*
* Copyright (c) 2019 Ta-Chu Kao <>
* Copyright (c) 2019 Marcello Seri <>
*)
module Types = Owl_ode_base.Types
type mat = Owl_dense_matrix_d.mat
module Symplectic_Euler :
Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat
module PseudoLeapfrog :
Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat
module Leapfrog :
Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat
module Ruth3 :
Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat
module Ruth4 :
Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat
val symplectic_euler
: (module Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat)
val leapfrog
: (module Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat)
val pseudoleapfrog
: (module Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat)
val ruth3
: (module Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat)
val ruth4
: (module Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat)
(* ----- helper function ----- *)
val to_state_array : ?axis:int -> int * int -> mat -> mat -> mat array * mat array
| null | https://raw.githubusercontent.com/owlbarn/owl_ode/5d934fbff87eea9f060d6c949bf78467024d8791/src/ode/symplectic/symplectic_d.mli | ocaml | ----- helper function ----- |
* OWL - OCaml Scientific and Engineering Computing
* OWL - ODE - Ordinary Differential Equation Solvers
*
* Copyright ( c ) 2019 >
* Copyright ( c ) 2019 < >
* OWL - OCaml Scientific and Engineering Computing
* OWL-ODE - Ordinary Differential Equation Solvers
*
* Copyright (c) 2019 Ta-Chu Kao <>
* Copyright (c) 2019 Marcello Seri <>
*)
module Types = Owl_ode_base.Types
type mat = Owl_dense_matrix_d.mat
module Symplectic_Euler :
Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat
module PseudoLeapfrog :
Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat
module Leapfrog :
Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat
module Ruth3 :
Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat
module Ruth4 :
Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat
val symplectic_euler
: (module Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat)
val leapfrog
: (module Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat)
val pseudoleapfrog
: (module Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat)
val ruth3
: (module Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat)
val ruth4
: (module Types.Solver
with type state = mat * mat
and type f = mat * mat -> float -> mat
and type step_output = (mat * mat) * float
and type solve_output = mat * mat * mat)
val to_state_array : ?axis:int -> int * int -> mat -> mat -> mat array * mat array
|
e6afbb76ae5ffa7ed958da914b5974b675968d3fab066ed5c42f2a71d44d039d | pjotrp/guix | music.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2015 < >
Copyright © 2015 < >
;;;
;;; 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 (gnu packages music)
#:use-module (guix utils)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix build-system gnu)
#:use-module (guix build-system cmake)
#:use-module (guix build-system python)
#:use-module (guix build-system waf)
#:use-module (gnu packages)
#:use-module (gnu packages algebra)
#:use-module (gnu packages audio)
#:use-module (gnu packages autotools)
libbdf
#:use-module (gnu packages boost)
#:use-module (gnu packages bison)
#:use-module (gnu packages cdrom)
#:use-module (gnu packages code)
#:use-module (gnu packages check)
#:use-module (gnu packages compression)
#:use-module (gnu packages docbook)
#:use-module (gnu packages doxygen)
#:use-module (gnu packages flex)
#:use-module (gnu packages fltk)
#:use-module (gnu packages fonts)
#:use-module (gnu packages fontutils)
#:use-module (gnu packages gcc)
#:use-module (gnu packages gettext)
#:use-module (gnu packages ghostscript)
#:use-module (gnu packages gl)
#:use-module (gnu packages glib)
#:use-module (gnu packages gnome)
#:use-module (gnu packages gtk)
#:use-module (gnu packages guile)
#:use-module (gnu packages image)
#:use-module (gnu packages imagemagick)
#:use-module (gnu packages java)
#:use-module (gnu packages linux) ; for alsa-utils
#:use-module (gnu packages man)
#:use-module (gnu packages mp3)
#:use-module (gnu packages ncurses)
#:use-module (gnu packages netpbm)
#:use-module (gnu packages pdf)
#:use-module (gnu packages perl)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages pulseaudio) ;libsndfile
#:use-module (gnu packages python)
#:use-module (gnu packages qt)
#:use-module (gnu packages rdf)
#:use-module (gnu packages readline)
#:use-module (gnu packages rsync)
#:use-module (gnu packages tcl)
#:use-module (gnu packages texinfo)
#:use-module (gnu packages texlive)
#:use-module (gnu packages video)
#:use-module (gnu packages web)
#:use-module (gnu packages xml)
#:use-module (gnu packages xorg)
#:use-module (gnu packages xiph)
#:use-module (gnu packages zip)
#:use-module ((srfi srfi-1) #:select (last)))
(define-public cmus
(package
(name "cmus")
(version "2.7.1")
(source (origin
(method url-fetch)
(uri (string-append
"/" name "/" name "/archive/v"
version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32
"0raixgjavkm7hxppzsc5zqbfbh2bhjcmbiplhnsxsmyj8flafyc1"))))
(build-system gnu-build-system)
(arguments
`(#:tests? #f ; cmus does not include tests
#:phases
(modify-phases %standard-phases
(replace
'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
;; It's an idiosyncratic configure script that doesn't
understand --prefix= .. ; it wants .. instead .
(zero?
(system* "./configure"
(string-append "prefix=" out)))))))))
;; TODO: cmus optionally supports the following formats, which haven't yet
been added to :
;;
;; - Roar, libroar
;;
;; - DISCID_LIBS, apparently different from cd-discid which is included in
. See < / >
(native-inputs
`(("pkg-config" ,pkg-config)))
(inputs
`(("alsa-lib" ,alsa-lib)
("ao" ,ao)
("ffmpeg" ,ffmpeg)
("flac" ,flac)
("jack" ,jack-1)
("libcddb" ,libcddb)
("libcdio-paranoia" ,libcdio-paranoia)
("libcue" ,libcue)
("libmad" ,libmad)
("libmodplug" ,libmodplug)
("libmpcdec" ,libmpcdec)
("libsamplerate" ,libsamplerate)
("libvorbis" ,libvorbis)
("ncurses" ,ncurses)
("opusfile" ,opusfile)
("pulseaudio" ,pulseaudio)
("wavpack" ,wavpack)))
(home-page "/")
(synopsis "Small console music player")
(description "Cmus is a small and fast console music player. It supports
many input formats and provides a customisable Vi-style user interface.")
(license license:gpl2+)))
(define-public hydrogen
(package
(name "hydrogen")
(version "0.9.5.1")
(source (origin
(method url-fetch)
(uri (string-append
"mirror/"
(version-prefix version 3) "%20Sources/"
"hydrogen-" version ".tar.gz"))
(sha256
(base32
"1fvyp6gfzcqcc90dmaqbm11p272zczz5pfz1z4lj33nfr7z0bqgb"))))
(build-system gnu-build-system)
(arguments
`(#:tests? #f ;no "check" target
#:phases
;; TODO: Add scons-build-system and use it here.
(modify-phases %standard-phases
(delete 'configure)
(add-after 'unpack 'scons-propagate-environment
(lambda _
;; By design, SCons does not, by default, propagate
;; environment variables to subprocesses. See:
;; <>
Here , we modify the Sconstruct file to arrange for
;; environment variables to be propagated.
(substitute* "Sconstruct"
(("^env = Environment\\(")
"env = Environment(ENV=os.environ, "))))
(replace 'build
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(zero? (system* "scons"
(string-append "prefix=" out)
"lrdf=0" ; cannot be found
"lash=1")))))
(add-before
'install
'fix-img-install
(lambda _
The whole ./data / img directory is copied to the target first .
;; Scons complains about existing files when we try to install all
images a second time .
(substitute* "Sconstruct"
(("os.path.walk\\(\"./data/img/\",install_images,env\\)") ""))
#t))
(replace 'install (lambda _ (zero? (system* "scons" "install")))))))
(native-inputs
`(("scons" ,scons)
("python" ,python-2)
("pkg-config" ,pkg-config)))
(inputs
`(("zlib" ,zlib)
("libtar" ,libtar)
("alsa-lib" ,alsa-lib)
("jack" ,jack-1)
("lash" ,lash)
( " lrdf " , lrdf ) ; FIXME : can not be found by scons
("qt" ,qt-4)
("libsndfile" ,libsndfile)))
(home-page "-music.org")
(synopsis "Drum machine")
(description
"Hydrogen is an advanced drum machine for GNU/Linux. Its main goal is to
enable professional yet simple and intuitive pattern-based drum programming.")
(license license:gpl2+)))
(define-public klick
(package
(name "klick")
(version "0.12.2")
(source (origin
(method url-fetch)
(uri (string-append "-"
version ".tar.gz"))
(sha256
(base32
"0hmcaywnwzjci3pp4xpvbijnnwvibz7gf9xzcdjbdca910y5728j"))))
(build-system gnu-build-system)
(arguments
`(#:tests? #f ;no "check" target
#:phases
;; TODO: Add scons-build-system and use it here.
(modify-phases %standard-phases
(delete 'configure)
(replace 'build
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(mkdir-p out)
(zero? (system* "scons" (string-append "PREFIX=" out))))))
(replace 'install (lambda _ (zero? (system* "scons" "install")))))))
(inputs
`(("boost" ,boost)
("jack" ,jack-1)
("libsndfile" ,libsndfile)
("libsamplerate" ,libsamplerate)
("liblo" ,liblo)
("rubberband" ,rubberband)))
(native-inputs
`(("scons" ,scons)
("python" ,python-2)
("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Metronome for JACK")
(description
"klick is an advanced command-line based metronome for JACK. It allows
you to define complex tempo maps for entire songs or performances.")
(license license:gpl2+)))
(define-public lilypond
(package
(name "lilypond")
(version "2.19.33")
(source (origin
(method url-fetch)
(uri (string-append
""
(version-major+minor version) "/"
name "-" version ".tar.gz"))
(sha256
(base32
"0s4vbbfy4xwq4da4kmlnndalmcyx2jaz7y8praah2146qbnr90xh"))))
(build-system gnu-build-system)
(arguments
`(#:tests? #f ; out-test/collated-files.html fails
#:out-of-source? #t
#:make-flags '("conf=www") ;to generate images for info manuals
#:configure-flags
(list "CONFIGURATION=www"
(string-append "--with-texgyre-dir="
(assoc-ref %build-inputs "font-tex-gyre")
"/share/fonts/opentype/"))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'fix-path-references
(lambda _
(substitute* "scm/backend-library.scm"
(("\\(search-executable '\\(\"gs\"\\)\\)")
(string-append "\"" (which "gs") "\""))
(("\"/bin/sh\"")
(string-append "\"" (which "sh") "\"")))
#t))
(add-before 'configure 'prepare-configuration
(lambda _
(substitute* "configure"
(("SHELL=/bin/sh") "SHELL=sh"))
(setenv "out" "www")
(setenv "conf" "www")
#t))
(add-after 'install 'install-info
(lambda _
(zero? (system* "make"
"-j" (number->string (parallel-job-count))
"conf=www" "install-info")))))))
(inputs
`(("guile" ,guile-1.8)
("font-dejavu" ,font-dejavu)
("font-tex-gyre" ,font-tex-gyre)
("fontconfig" ,fontconfig)
("freetype" ,freetype)
("ghostscript" ,ghostscript)
("pango" ,pango)
("python" ,python-2)))
(native-inputs
`(("bison" ,bison)
("perl" ,perl)
("flex" ,flex)
("fontforge" ,fontforge)
("dblatex" ,dblatex)
("gettext" ,gnu-gettext)
("imagemagick" ,imagemagick)
for pngtopnm
metafont and metapost
("texinfo" ,texinfo)
("texi2html" ,texi2html)
("rsync" ,rsync)
("pkg-config" ,pkg-config)
("zip" ,zip)))
(home-page "/")
(synopsis "Music typesetting")
(description
"GNU LilyPond is a music typesetter, which produces high-quality sheet
music. Music is input in a text file containing control sequences which are
interpreted by LilyPond to produce the final document. It is extendable with
Guile.")
(license license:gpl3+)))
(define-public non-sequencer
The latest tagged release is three years old and uses a custom build
;; system, so we take the last commit affecting the "sequencer" directory.
(let ((commit "1d9bd576"))
(package
(name "non-sequencer")
(version (string-append "1.9.5-" commit))
(source (origin
(method git-fetch)
(uri (git-reference
(url "git")
(commit commit)))
(sha256
(base32
"0pkkw8q6d55j38xm7r4rwpdv1wy00a44h8c4wrn7vbgpq9nij46y"))
(file-name (string-append name "-" version "-checkout"))))
(build-system waf-build-system)
(arguments
`(#:tests? #f ;no "check" target
#:configure-flags
(list "--project=sequencer"
Disable the use of SSE unless on x86_64 .
,@(if (not (string-prefix? "x86_64" (or (%current-target-system)
(%current-system))))
'("--disable-sse")
'()))
#:phases
(modify-phases %standard-phases
(add-before
'configure 'set-flags
(lambda _
Compile with C++11 , required by libsigc++ .
(setenv "CXXFLAGS" "-std=c++11")
#t)))
#:python ,python-2))
(inputs
`(("jack" ,jack-1)
("libsigc++" ,libsigc++)
("liblo" ,liblo)
("ntk" ,ntk)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(home-page "")
(synopsis "Pattern-based MIDI sequencer")
(description
"The Non Sequencer is a powerful, lightweight, real-time,
pattern-based MIDI sequencer. It utilizes the JACK Audio Connection Kit for
MIDI I/O and the NTK GUI toolkit for its user interface. Everything in Non
Sequencer happens on-line, in real-time. Music can be composed live, while the
transport is rolling.")
(license license:gpl2+))))
(define-public solfege
(package
(name "solfege")
(version "3.22.2")
(source (origin
(method url-fetch)
(uri (string-append
"mirror-"
version ".tar.xz"))
(sha256
(base32
"1w25rxdbj907nsx285k9nm480pvy12w3yknfh4n1dfv17cwy072i"))))
(build-system gnu-build-system)
(arguments
xmllint attempts to download
#:test-target "test"
#:phases
(alist-cons-after
'unpack 'fix-configuration
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "default.config"
(("csound=csound")
(string-append "csound="
(assoc-ref inputs "csound")
"/bin/csound"))
(("/usr/bin/aplay")
(string-append (assoc-ref inputs "aplay")
"/bin/aplay"))
(("/usr/bin/timidity")
(string-append (assoc-ref inputs "timidity")
"/bin/timidity"))
(("/usr/bin/mpg123")
(string-append (assoc-ref inputs "mpg123")
"/bin/mpg123"))
(("/usr/bin/ogg123")
(string-append (assoc-ref inputs "ogg123")
"/bin/ogg123"))))
(alist-cons-before
'build 'patch-python-shebangs
(lambda _
Two python scripts begin with a Unicode BOM , so patch - shebang
;; has no effect.
(substitute* '("solfege/parsetree.py"
"solfege/presetup.py")
(("#!/usr/bin/python") (string-append "#!" (which "python")))))
(alist-cons-before
'build 'add-sitedirs
.pth files are not automatically interpreted unless the
;; directories containing them are added as "sites". The directories
;; are then added to those in the PYTHONPATH. This is required for
the operation of pygtk and pygobject .
(lambda _
(substitute* "run-solfege.py"
(("import os")
"import os, site
for path in [path for path in sys.path if 'site-packages' in path]: site.addsitedir(path)")))
(alist-cons-before
'build 'adjust-config-file-prefix
(lambda* (#:key outputs #:allow-other-keys)
(substitute* "run-solfege.py"
(("prefix = os.path.*$")
(string-append "prefix = " (assoc-ref outputs "out")))))
(alist-cons-after
'install 'wrap-program
(lambda* (#:key inputs outputs #:allow-other-keys)
;; Make sure 'solfege' runs with the correct PYTHONPATH. We
also need to modify GDK_PIXBUF_MODULE_FILE for SVG support .
(let* ((out (assoc-ref outputs "out"))
(path (getenv "PYTHONPATH"))
(rsvg (assoc-ref inputs "librsvg"))
(pixbuf (find-files rsvg "^loaders\\.cache$")))
(wrap-program (string-append out "/bin/solfege")
`("PYTHONPATH" ":" prefix (,path))
`("GDK_PIXBUF_MODULE_FILE" ":" prefix ,pixbuf))))
%standard-phases)))))))
(inputs
`(("python" ,python-2)
("pygtk" ,python2-pygtk)
("gettext" ,gnu-gettext)
("gtk" ,gtk+)
;; TODO: Lilypond is optional. Produces errors at build time:
;; Drawing systems...Error: /undefinedresult in --glyphshow--
Fontconfig is needed to fix one of the errors , but other similar
;; errors remain.
;;("lilypond" ,lilypond)
("librsvg" ,librsvg) ; needed at runtime for icons
("libpng" ,libpng) ; needed at runtime for icons
;; players needed at runtime
("aplay" ,alsa-utils)
("csound" ,csound) ; optional, needed for some exercises
("mpg123" ,mpg123)
("ogg123" ,vorbis-tools)
("timidity" ,timidity++)))
(native-inputs
`(("pkg-config" ,pkg-config)
("txt2man" ,txt2man)
("libxml2" ,libxml2) ; for tests
("ghostscript" ,ghostscript)
;;("fontconfig" ,fontconfig) ; only needed with lilypond
;;("freetype" ,freetype) ; only needed with lilypond
("texinfo" ,texinfo)))
(home-page "/")
(synopsis "Ear training")
(description
"GNU Solfege is a program for practicing musical ear-training. With it,
you can practice your recognition of various musical intervals and chords. It
features a statistics overview so you can monitor your progress across several
sessions. Solfege is also designed to be extensible so you can easily write
your own lessons.")
(license license:gpl3+)))
(define-public powertabeditor
(package
(name "powertabeditor")
(version "2.0.0-alpha8")
(source (origin
(method url-fetch)
(uri (string-append
"/"
version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32
"0gaa2x209v3azql8ak3r1n9a9qbxjx2ssirvwdxwklv2lmfqkm82"))
(modules '((guix build utils)))
(snippet
'(begin
;; Remove bundled sources for external libraries
(delete-file-recursively "external")
(substitute* "CMakeLists.txt"
(("include_directories\\(\\$\\{PROJECT_SOURCE_DIR\\}/external/.*") "")
(("add_subdirectory\\(external\\)") ""))
(substitute* "test/CMakeLists.txt"
(("include_directories\\(\\$\\{PROJECT_SOURCE_DIR\\}/external/.*") ""))
;; Add install target
(substitute* "source/CMakeLists.txt"
(("qt5_use_modules")
(string-append
"install(TARGETS powertabeditor "
"RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin)\n"
"install(FILES data/tunings.json DESTINATION "
"${CMAKE_INSTALL_PREFIX}/share/powertabeditor/)\n"
"qt5_use_modules")))
#t))))
(build-system cmake-build-system)
(arguments
`(#:modules ((guix build cmake-build-system)
(guix build utils)
(ice-9 match))
#:configure-flags
;; CMake appears to lose the RUNPATH for some reason, so it has to be
;; explicitly set with CMAKE_INSTALL_RPATH.
(list "-DCMAKE_BUILD_WITH_INSTALL_RPATH=TRUE"
if can not be built
(string-append "-DCMAKE_INSTALL_RPATH="
(string-join (map (match-lambda
((name . directory)
(string-append directory "/lib")))
%build-inputs) ";")))
#:phases
(modify-phases %standard-phases
(replace
'check
(lambda _
(zero? (system* "bin/pte_tests"
;; Exclude this failing test
"~Formats/PowerTabOldImport/Directions"))))
(add-before
'configure 'fix-tests
(lambda _
;; Tests cannot be built with precompiled headers
(substitute* "test/CMakeLists.txt"
(("cotire\\(pte_tests\\)") ""))
#t))
(add-before
'configure 'remove-third-party-libs
(lambda* (#:key inputs #:allow-other-keys)
;; Link with required static libraries, because we're not
using the bundled version of withershins .
(substitute* '("source/CMakeLists.txt"
"test/CMakeLists.txt")
(("target_link_libraries\\((powertabeditor|pte_tests)" _ target)
(string-append "target_link_libraries(" target " "
(assoc-ref inputs "binutils")
"/lib/libbfd.a "
(assoc-ref inputs "libiberty")
"/lib/libiberty.a "
"dl")))
#t)))))
(inputs
`(("boost" ,boost)
("alsa-lib" ,alsa-lib)
("qt" ,qt)
("withershins" ,withershins)
for withershins
for -lbfd and -liberty ( for )
("timidity" ,timidity++)
("pugixml" ,pugixml)
("rtmidi" ,rtmidi)
("rapidjson" ,rapidjson)
("zlib" ,zlib)))
(native-inputs
`(("catch" ,catch-framework)
("pkg-config" ,pkg-config)))
(home-page "")
(synopsis "Guitar tablature editor")
(description
"Power Tab Editor 2.0 is the successor to the famous original Power Tab
Editor. It is compatible with Power Tab Editor 1.7 and Guitar Pro.")
(license license:gpl3+)))
(define-public setbfree
(package
(name "setbfree")
(version "0.8.0")
(source (origin
(method url-fetch)
(uri
(string-append
""
version "/setbfree-" version ".tar.gz"))
(sha256
(base32
"045bgp7qsigpbrhk7qvgvliwiy26sajifwn7f2jvk90ckfqnlw4b"))))
(build-system gnu-build-system)
(arguments
`(#:tests? #f ; no "check" target
#:make-flags
(list (string-append "PREFIX=" (assoc-ref %outputs "out"))
(string-append "FONTFILE="
(assoc-ref %build-inputs "font-bitstream-vera")
"/share/fonts/truetype/VeraBd.ttf")
;; Disable unsupported optimization flags on non-x86
,@(let ((system (or (%current-target-system)
(%current-system))))
(if (or (string-prefix? "x86_64" system)
(string-prefix? "i686" system))
'()
'("OPTIMIZATIONS=-ffast-math -fomit-frame-pointer -O3"))))
#:phases
(modify-phases %standard-phases
(add-before 'build 'set-CC-variable
(lambda _ (setenv "CC" "gcc") #t))
(delete 'configure))))
(inputs
`(("jack" ,jack-1)
("lv2" ,lv2)
("zita-convolver" ,zita-convolver)
("glu" ,glu)
("ftgl" ,ftgl)
("font-bitstream-vera" ,font-bitstream-vera)))
(native-inputs
`(("help2man" ,help2man)
("pkg-config" ,pkg-config)))
(home-page "")
(synopsis "Tonewheel organ")
(description
"setBfree is a MIDI-controlled, software synthesizer designed to imitate
the sound and properties of the electromechanical organs and sound
modification devices that brought world-wide fame to the names and products of
Laurens Hammond and Don Leslie.")
(license license:gpl2+)))
(define-public bristol
(package
(name "bristol")
(version "0.60.11")
(source (origin
(method url-fetch)
(uri (string-append "mirror/"
(version-major+minor version)
"/bristol-" version ".tar.gz"))
(sha256
(base32
"1fi2m4gmvxdi260821y09lxsimq82yv4k5bbgk3kyc3x1nyhn7vx"))))
(build-system gnu-build-system)
(inputs
`(("alsa-lib" ,alsa-lib)
("jack" ,jack-1)
("liblo" ,liblo)
("libx11" ,libx11)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Synthesizer emulator")
(description
"Bristol is an emulation package for a number of different 'classic'
synthesizers including additive and subtractive and a few organs. The
application consists of the engine, which is called bristol, and its own GUI
library called brighton that represents all the emulations. There are
currently more than twenty different emulations; each does sound different
although the author maintains that the quality and accuracy of each emulation
is subjective.")
(license license:gpl3+)))
(define-public tuxguitar
(package
(name "tuxguitar")
(version "1.2")
(source (origin
(method url-fetch)
(uri (string-append
"mirror-"
version "/tuxguitar-src-" version ".tar.gz"))
(sha256
(base32
"1g1yf2gd06fzdhqb8kb8dmdcmr602s9y24f01kyl4940wimgr944"))))
(build-system gnu-build-system)
(arguments
`(#:make-flags (list (string-append "LDFLAGS=-Wl,-rpath="
(assoc-ref %outputs "out") "/lib")
(string-append "PREFIX="
(assoc-ref %outputs "out"))
(string-append "SWT_PATH="
(assoc-ref %build-inputs "swt")
"/share/java/swt.jar"))
#:tests? #f ;no "check" target
#:parallel-build? #f ;not supported
#:phases
(alist-cons-before
'build 'enter-dir-set-path-and-pass-ldflags
(lambda* (#:key inputs #:allow-other-keys)
(chdir "TuxGuitar")
(substitute* "GNUmakefile"
(("PROPERTIES\\?=")
(string-append "PROPERTIES?= -Dswt.library.path="
(assoc-ref inputs "swt") "/lib"))
(("\\$\\(GCJ\\) -o") "$(GCJ) $(LDFLAGS) -o"))
#t)
(alist-delete 'configure %standard-phases))))
(inputs
`(("swt" ,swt)))
(native-inputs
`(("gcj" ,gcj)
("pkg-config" ,pkg-config)))
(home-page "")
(synopsis "Multitrack tablature editor and player")
(description
"TuxGuitar is a guitar tablature editor with player support through midi.
It can display scores and multitrack tabs. TuxGuitar provides various
additional features, including autoscrolling while playing, note duration
management, bend/slide/vibrato/hammer-on/pull-off effects, support for
tuplets, time signature management, tempo management, gp3/gp4/gp5 import and
export.")
(license license:lgpl2.1+)))
(define-public pd
(package
(name "pd")
(version "0.45.4")
(source (origin
(method url-fetch)
(uri
(string-append "mirror-data/pure-data/"
version "/pd-" (version-major+minor version)
"-" (last (string-split version #\.))
".src.tar.gz"))
(sha256
(base32
"1ls2ap5yi2zxvmr247621g4jx0hhfds4j5704a050bn2n3l0va2p"))))
(build-system gnu-build-system)
(arguments
`(#:tests? #f ; no "check" target
#:phases
(modify-phases %standard-phases
(add-before
'configure 'fix-wish-path
(lambda _
(substitute* "src/s_inter.c"
((" wish ") (string-append " " (which "wish8.6") " ")))
(substitute* "tcl/pd-gui.tcl"
(("exec wish ") (string-append "exec " (which "wish8.6") " ")))
#t))
(add-after
'unpack 'autoconf
(lambda _ (zero? (system* "autoreconf" "-vfi")))))))
(native-inputs
`(("autoconf" ,autoconf)
("automake" ,automake)
("libtool" ,libtool)
("gettext" ,gnu-gettext)
("pkg-config" ,pkg-config)))
(inputs
`(("tk" ,tk)
("alsa-lib" ,alsa-lib)
("jack" ,jack-1)))
(home-page "")
(synopsis "Visual programming language for artistic performances")
(description
"Pure Data (aka Pd) is a visual programming language. Pd enables
musicians, visual artists, performers, researchers, and developers to create
software graphically, without writing lines of code. Pd is used to process
and generate sound, video, 2D/3D graphics, and interface sensors, input
devices, and MIDI. Pd can easily work over local and remote networks to
integrate wearable technology, motor systems, lighting rigs, and other
equipment. Pd is suitable for learning basic multimedia processing and visual
programming methods as well as for realizing complex systems for large-scale
projects.")
(license license:bsd-3)))
(define-public frescobaldi
(package
(name "frescobaldi")
(version "2.18.1")
(source (origin
(method url-fetch)
(uri (string-append
""
version "/frescobaldi-" version ".tar.gz"))
(sha256
(base32
"1hflc6gck6dn17czc2ldai5j0ynfg3df8lqcggdry06qxsdbnns7"))))
(build-system python-build-system)
(inputs
`(("lilypond" ,lilypond)
("python-pyqt-4" ,python-pyqt-4)
("python-ly" ,python-ly)
("poppler" ,poppler)
("python-poppler-qt4" ,python-poppler-qt4)
("python-sip" ,python-sip)))
(home-page "/")
(synopsis "LilyPond sheet music text editor")
(description
"Frescobaldi is a LilyPond sheet music text editor with syntax
highlighting and automatic completion. Among other things, it can render
scores next to the source, can capture input from MIDI or read MusicXML and
ABC files, has a MIDI player for proof-listening, and includes a documentation
browser.")
(license license:gpl2+)))
(define-public drumstick
(package
(name "drumstick")
(version "1.0.1")
(source (origin
(method url-fetch)
(uri (string-append "mirror/"
version "/drumstick-" version ".tar.bz2"))
(sha256
(base32
"0mxgix85b2qqs859z91cxik5x0s60dykqiflbj62px9akvf91qdv"))))
(build-system cmake-build-system)
(arguments
`(#:tests? #f ; no test target
#:configure-flags '("-DLIB_SUFFIX=")
#:phases
(modify-phases %standard-phases
(add-before 'configure 'fix-docbook
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "cmake_admin/CreateManpages.cmake"
(("")
(string-append (assoc-ref inputs "docbook-xsl")
"/xml/xsl/docbook-xsl-"
,(package-version docbook-xsl)
"/manpages/docbook.xsl")))
#t)))))
(inputs
`(("qt" ,qt)
("alsa-lib" ,alsa-lib)
("fluidsynth" ,fluidsynth)))
(native-inputs
`(("pkg-config" ,pkg-config)
for xsltproc
("docbook-xsl" ,docbook-xsl)
("doxygen" ,doxygen)))
(home-page "/")
(synopsis "C++ MIDI library")
(description
"Drumstick is a set of MIDI libraries using C++/Qt5 idioms and style. It
includes a C++ wrapper around the ALSA library sequencer interface. A
complementary library provides classes for processing SMF (Standard MIDI
files: .MID/.KAR), Cakewalk (.WRK), and Overture (.OVE) file formats. A
multiplatform realtime MIDI I/O library is also provided with various output
backends, including ALSA, OSS, Network and FluidSynth.")
(license license:gpl2+)))
(define-public vmpk
(package
(name "vmpk")
(version "0.6.1")
(source (origin
(method url-fetch)
(uri (string-append "mirror/"
version "/vmpk-" version ".tar.bz2"))
(sha256
(base32
"0ranldd033bd31m9d2vkbkn9zp1k46xbaysllai2i95rf1nhirqc"))))
(build-system cmake-build-system)
(arguments
`(#:tests? #f ; no test target
#:phases
(modify-phases %standard-phases
(add-before 'configure 'fix-docbook
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "cmake_admin/CreateManpages.cmake"
(("")
(string-append (assoc-ref inputs "docbook-xsl")
"/xml/xsl/docbook-xsl-"
,(package-version docbook-xsl)
"/manpages/docbook.xsl")))
#t)))))
(inputs
`(("drumstick" ,drumstick)
("qt" ,qt)))
(native-inputs
for xsltproc
("docbook-xsl" ,docbook-xsl)
("pkg-config" ,pkg-config)))
(home-page "")
(synopsis "Virtual MIDI piano keyboard")
(description
"Virtual MIDI Piano Keyboard is a MIDI events generator and receiver. It
doesn't produce any sound by itself, but can be used to drive a MIDI
synthesizer (either hardware or software, internal or external). You can use
the computer's keyboard to play MIDI notes, and also the mouse. You can use
the Virtual MIDI Piano Keyboard to display the played MIDI notes from another
instrument or MIDI file player.")
(license license:gpl3+)))
(define-public zynaddsubfx
(package
(name "zynaddsubfx")
(version "2.5.2")
(source (origin
(method url-fetch)
(uri (string-append
"mirror/"
version "/zynaddsubfx-" version ".tar.gz"))
(sha256
(base32
"11yrady7xwfrzszkk2fvq81ymv99mq474h60qnirk27khdygk24m"))))
(build-system cmake-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
Move SSE compiler optimization flags from generic target to
;; athlon64 and core2 targets, because otherwise the build would fail
on non - Intel machines .
(add-after 'unpack 'remove-sse-flags-from-generic-target
(lambda _
(substitute* "src/CMakeLists.txt"
(("-msse -msse2 -mfpmath=sse") "")
(("-march=(athlon64|core2)" flag)
(string-append flag " -msse -msse2 -mfpmath=sse")))
#t)))))
(inputs
`(("liblo" ,liblo)
("ntk" ,ntk)
("alsa-lib" ,alsa-lib)
("jack" ,jack-1)
("fftw" ,fftw)
("minixml" ,minixml)
("libxpm" ,libxpm)
("zlib" ,zlib)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Software synthesizer")
(description
"ZynAddSubFX is a feature heavy realtime software synthesizer. It offers
three synthesizer engines, multitimbral and polyphonic synths, microtonal
capabilities, custom envelopes, effects, etc.")
(license license:gpl2)))
(define-public yoshimi
(package
(name "yoshimi")
(version "1.3.7.1")
(source (origin
(method url-fetch)
(uri (string-append "mirror/"
(version-major+minor version)
"/yoshimi-" version ".tar.bz2"))
(sha256
(base32
"13xc1x8jrr2rn26jx4dini692ww3771d5j5xf7f56ixqr7mmdhvz"))))
(build-system cmake-build-system)
(arguments
`(#:tests? #f ; there are no tests
#:configure-flags
(list (string-append "-DCMAKE_INSTALL_DATAROOTDIR="
(assoc-ref %outputs "out") "/share"))
#:phases
(modify-phases %standard-phases
(add-before 'configure 'enter-dir
(lambda _ (chdir "src") #t))
Move SSE compiler optimization flags from generic target to
;; athlon64 and core2 targets, because otherwise the build would fail
on non - Intel machines .
(add-after 'unpack 'remove-sse-flags-from-generic-target
(lambda _
(substitute* "src/CMakeLists.txt"
(("-msse -msse2 -mfpmath=sse") "")
(("-march=(athlon64|core2)" flag)
(string-append flag " -msse -msse2 -mfpmath=sse")))
#t)))))
(inputs
`(("boost" ,boost)
("fftwf" ,fftwf)
("alsa-lib" ,alsa-lib)
("jack" ,jack-1)
("fontconfig" ,fontconfig)
("minixml" ,minixml)
("mesa" ,mesa)
("fltk" ,fltk)
("lv2" ,lv2)
("readline" ,readline)
("ncurses" ,ncurses)
("cairo" ,cairo)
("zlib" ,zlib)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Multi-paradigm software synthesizer")
(description
"Yoshimi is a fork of ZynAddSubFX, a feature heavy realtime software
synthesizer. It offers three synthesizer engines, multitimbral and polyphonic
synths, microtonal capabilities, custom envelopes, effects, etc. Yoshimi
improves on support for JACK features, such as JACK MIDI.")
(license license:gpl2)))
| null | https://raw.githubusercontent.com/pjotrp/guix/96250294012c2f1520b67f12ea80bfd6b98075a2/gnu/packages/music.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.
for alsa-utils
libsndfile
cmus does not include tests
It's an idiosyncratic configure script that doesn't
it wants .. instead .
TODO: cmus optionally supports the following formats, which haven't yet
- Roar, libroar
- DISCID_LIBS, apparently different from cd-discid which is included in
no "check" target
TODO: Add scons-build-system and use it here.
By design, SCons does not, by default, propagate
environment variables to subprocesses. See:
<>
environment variables to be propagated.
cannot be found
Scons complains about existing files when we try to install all
FIXME : can not be found by scons
no "check" target
TODO: Add scons-build-system and use it here.
out-test/collated-files.html fails
to generate images for info manuals
system, so we take the last commit affecting the "sequencer" directory.
no "check" target
has no effect.
directories containing them are added as "sites". The directories
are then added to those in the PYTHONPATH. This is required for
Make sure 'solfege' runs with the correct PYTHONPATH. We
TODO: Lilypond is optional. Produces errors at build time:
Drawing systems...Error: /undefinedresult in --glyphshow--
errors remain.
("lilypond" ,lilypond)
needed at runtime for icons
needed at runtime for icons
players needed at runtime
optional, needed for some exercises
for tests
("fontconfig" ,fontconfig) ; only needed with lilypond
("freetype" ,freetype) ; only needed with lilypond
Remove bundled sources for external libraries
Add install target
CMake appears to lose the RUNPATH for some reason, so it has to be
explicitly set with CMAKE_INSTALL_RPATH.
Exclude this failing test
Tests cannot be built with precompiled headers
Link with required static libraries, because we're not
no "check" target
Disable unsupported optimization flags on non-x86
each does sound different
no "check" target
not supported
no "check" target
no test target
no test target
athlon64 and core2 targets, because otherwise the build would fail
there are no tests
athlon64 and core2 targets, because otherwise the build would fail | Copyright © 2015 < >
Copyright © 2015 < >
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 (gnu packages music)
#:use-module (guix utils)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix build-system gnu)
#:use-module (guix build-system cmake)
#:use-module (guix build-system python)
#:use-module (guix build-system waf)
#:use-module (gnu packages)
#:use-module (gnu packages algebra)
#:use-module (gnu packages audio)
#:use-module (gnu packages autotools)
libbdf
#:use-module (gnu packages boost)
#:use-module (gnu packages bison)
#:use-module (gnu packages cdrom)
#:use-module (gnu packages code)
#:use-module (gnu packages check)
#:use-module (gnu packages compression)
#:use-module (gnu packages docbook)
#:use-module (gnu packages doxygen)
#:use-module (gnu packages flex)
#:use-module (gnu packages fltk)
#:use-module (gnu packages fonts)
#:use-module (gnu packages fontutils)
#:use-module (gnu packages gcc)
#:use-module (gnu packages gettext)
#:use-module (gnu packages ghostscript)
#:use-module (gnu packages gl)
#:use-module (gnu packages glib)
#:use-module (gnu packages gnome)
#:use-module (gnu packages gtk)
#:use-module (gnu packages guile)
#:use-module (gnu packages image)
#:use-module (gnu packages imagemagick)
#:use-module (gnu packages java)
#:use-module (gnu packages man)
#:use-module (gnu packages mp3)
#:use-module (gnu packages ncurses)
#:use-module (gnu packages netpbm)
#:use-module (gnu packages pdf)
#:use-module (gnu packages perl)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages python)
#:use-module (gnu packages qt)
#:use-module (gnu packages rdf)
#:use-module (gnu packages readline)
#:use-module (gnu packages rsync)
#:use-module (gnu packages tcl)
#:use-module (gnu packages texinfo)
#:use-module (gnu packages texlive)
#:use-module (gnu packages video)
#:use-module (gnu packages web)
#:use-module (gnu packages xml)
#:use-module (gnu packages xorg)
#:use-module (gnu packages xiph)
#:use-module (gnu packages zip)
#:use-module ((srfi srfi-1) #:select (last)))
(define-public cmus
(package
(name "cmus")
(version "2.7.1")
(source (origin
(method url-fetch)
(uri (string-append
"/" name "/" name "/archive/v"
version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32
"0raixgjavkm7hxppzsc5zqbfbh2bhjcmbiplhnsxsmyj8flafyc1"))))
(build-system gnu-build-system)
(arguments
#:phases
(modify-phases %standard-phases
(replace
'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(zero?
(system* "./configure"
(string-append "prefix=" out)))))))))
been added to :
. See < / >
(native-inputs
`(("pkg-config" ,pkg-config)))
(inputs
`(("alsa-lib" ,alsa-lib)
("ao" ,ao)
("ffmpeg" ,ffmpeg)
("flac" ,flac)
("jack" ,jack-1)
("libcddb" ,libcddb)
("libcdio-paranoia" ,libcdio-paranoia)
("libcue" ,libcue)
("libmad" ,libmad)
("libmodplug" ,libmodplug)
("libmpcdec" ,libmpcdec)
("libsamplerate" ,libsamplerate)
("libvorbis" ,libvorbis)
("ncurses" ,ncurses)
("opusfile" ,opusfile)
("pulseaudio" ,pulseaudio)
("wavpack" ,wavpack)))
(home-page "/")
(synopsis "Small console music player")
(description "Cmus is a small and fast console music player. It supports
many input formats and provides a customisable Vi-style user interface.")
(license license:gpl2+)))
(define-public hydrogen
(package
(name "hydrogen")
(version "0.9.5.1")
(source (origin
(method url-fetch)
(uri (string-append
"mirror/"
(version-prefix version 3) "%20Sources/"
"hydrogen-" version ".tar.gz"))
(sha256
(base32
"1fvyp6gfzcqcc90dmaqbm11p272zczz5pfz1z4lj33nfr7z0bqgb"))))
(build-system gnu-build-system)
(arguments
#:phases
(modify-phases %standard-phases
(delete 'configure)
(add-after 'unpack 'scons-propagate-environment
(lambda _
Here , we modify the Sconstruct file to arrange for
(substitute* "Sconstruct"
(("^env = Environment\\(")
"env = Environment(ENV=os.environ, "))))
(replace 'build
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(zero? (system* "scons"
(string-append "prefix=" out)
"lash=1")))))
(add-before
'install
'fix-img-install
(lambda _
The whole ./data / img directory is copied to the target first .
images a second time .
(substitute* "Sconstruct"
(("os.path.walk\\(\"./data/img/\",install_images,env\\)") ""))
#t))
(replace 'install (lambda _ (zero? (system* "scons" "install")))))))
(native-inputs
`(("scons" ,scons)
("python" ,python-2)
("pkg-config" ,pkg-config)))
(inputs
`(("zlib" ,zlib)
("libtar" ,libtar)
("alsa-lib" ,alsa-lib)
("jack" ,jack-1)
("lash" ,lash)
("qt" ,qt-4)
("libsndfile" ,libsndfile)))
(home-page "-music.org")
(synopsis "Drum machine")
(description
"Hydrogen is an advanced drum machine for GNU/Linux. Its main goal is to
enable professional yet simple and intuitive pattern-based drum programming.")
(license license:gpl2+)))
(define-public klick
(package
(name "klick")
(version "0.12.2")
(source (origin
(method url-fetch)
(uri (string-append "-"
version ".tar.gz"))
(sha256
(base32
"0hmcaywnwzjci3pp4xpvbijnnwvibz7gf9xzcdjbdca910y5728j"))))
(build-system gnu-build-system)
(arguments
#:phases
(modify-phases %standard-phases
(delete 'configure)
(replace 'build
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(mkdir-p out)
(zero? (system* "scons" (string-append "PREFIX=" out))))))
(replace 'install (lambda _ (zero? (system* "scons" "install")))))))
(inputs
`(("boost" ,boost)
("jack" ,jack-1)
("libsndfile" ,libsndfile)
("libsamplerate" ,libsamplerate)
("liblo" ,liblo)
("rubberband" ,rubberband)))
(native-inputs
`(("scons" ,scons)
("python" ,python-2)
("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Metronome for JACK")
(description
"klick is an advanced command-line based metronome for JACK. It allows
you to define complex tempo maps for entire songs or performances.")
(license license:gpl2+)))
(define-public lilypond
(package
(name "lilypond")
(version "2.19.33")
(source (origin
(method url-fetch)
(uri (string-append
""
(version-major+minor version) "/"
name "-" version ".tar.gz"))
(sha256
(base32
"0s4vbbfy4xwq4da4kmlnndalmcyx2jaz7y8praah2146qbnr90xh"))))
(build-system gnu-build-system)
(arguments
#:out-of-source? #t
#:configure-flags
(list "CONFIGURATION=www"
(string-append "--with-texgyre-dir="
(assoc-ref %build-inputs "font-tex-gyre")
"/share/fonts/opentype/"))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'fix-path-references
(lambda _
(substitute* "scm/backend-library.scm"
(("\\(search-executable '\\(\"gs\"\\)\\)")
(string-append "\"" (which "gs") "\""))
(("\"/bin/sh\"")
(string-append "\"" (which "sh") "\"")))
#t))
(add-before 'configure 'prepare-configuration
(lambda _
(substitute* "configure"
(("SHELL=/bin/sh") "SHELL=sh"))
(setenv "out" "www")
(setenv "conf" "www")
#t))
(add-after 'install 'install-info
(lambda _
(zero? (system* "make"
"-j" (number->string (parallel-job-count))
"conf=www" "install-info")))))))
(inputs
`(("guile" ,guile-1.8)
("font-dejavu" ,font-dejavu)
("font-tex-gyre" ,font-tex-gyre)
("fontconfig" ,fontconfig)
("freetype" ,freetype)
("ghostscript" ,ghostscript)
("pango" ,pango)
("python" ,python-2)))
(native-inputs
`(("bison" ,bison)
("perl" ,perl)
("flex" ,flex)
("fontforge" ,fontforge)
("dblatex" ,dblatex)
("gettext" ,gnu-gettext)
("imagemagick" ,imagemagick)
for pngtopnm
metafont and metapost
("texinfo" ,texinfo)
("texi2html" ,texi2html)
("rsync" ,rsync)
("pkg-config" ,pkg-config)
("zip" ,zip)))
(home-page "/")
(synopsis "Music typesetting")
(description
"GNU LilyPond is a music typesetter, which produces high-quality sheet
music. Music is input in a text file containing control sequences which are
interpreted by LilyPond to produce the final document. It is extendable with
Guile.")
(license license:gpl3+)))
(define-public non-sequencer
The latest tagged release is three years old and uses a custom build
(let ((commit "1d9bd576"))
(package
(name "non-sequencer")
(version (string-append "1.9.5-" commit))
(source (origin
(method git-fetch)
(uri (git-reference
(url "git")
(commit commit)))
(sha256
(base32
"0pkkw8q6d55j38xm7r4rwpdv1wy00a44h8c4wrn7vbgpq9nij46y"))
(file-name (string-append name "-" version "-checkout"))))
(build-system waf-build-system)
(arguments
#:configure-flags
(list "--project=sequencer"
Disable the use of SSE unless on x86_64 .
,@(if (not (string-prefix? "x86_64" (or (%current-target-system)
(%current-system))))
'("--disable-sse")
'()))
#:phases
(modify-phases %standard-phases
(add-before
'configure 'set-flags
(lambda _
Compile with C++11 , required by libsigc++ .
(setenv "CXXFLAGS" "-std=c++11")
#t)))
#:python ,python-2))
(inputs
`(("jack" ,jack-1)
("libsigc++" ,libsigc++)
("liblo" ,liblo)
("ntk" ,ntk)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(home-page "")
(synopsis "Pattern-based MIDI sequencer")
(description
"The Non Sequencer is a powerful, lightweight, real-time,
pattern-based MIDI sequencer. It utilizes the JACK Audio Connection Kit for
MIDI I/O and the NTK GUI toolkit for its user interface. Everything in Non
Sequencer happens on-line, in real-time. Music can be composed live, while the
transport is rolling.")
(license license:gpl2+))))
(define-public solfege
(package
(name "solfege")
(version "3.22.2")
(source (origin
(method url-fetch)
(uri (string-append
"mirror-"
version ".tar.xz"))
(sha256
(base32
"1w25rxdbj907nsx285k9nm480pvy12w3yknfh4n1dfv17cwy072i"))))
(build-system gnu-build-system)
(arguments
xmllint attempts to download
#:test-target "test"
#:phases
(alist-cons-after
'unpack 'fix-configuration
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "default.config"
(("csound=csound")
(string-append "csound="
(assoc-ref inputs "csound")
"/bin/csound"))
(("/usr/bin/aplay")
(string-append (assoc-ref inputs "aplay")
"/bin/aplay"))
(("/usr/bin/timidity")
(string-append (assoc-ref inputs "timidity")
"/bin/timidity"))
(("/usr/bin/mpg123")
(string-append (assoc-ref inputs "mpg123")
"/bin/mpg123"))
(("/usr/bin/ogg123")
(string-append (assoc-ref inputs "ogg123")
"/bin/ogg123"))))
(alist-cons-before
'build 'patch-python-shebangs
(lambda _
Two python scripts begin with a Unicode BOM , so patch - shebang
(substitute* '("solfege/parsetree.py"
"solfege/presetup.py")
(("#!/usr/bin/python") (string-append "#!" (which "python")))))
(alist-cons-before
'build 'add-sitedirs
.pth files are not automatically interpreted unless the
the operation of pygtk and pygobject .
(lambda _
(substitute* "run-solfege.py"
(("import os")
"import os, site
for path in [path for path in sys.path if 'site-packages' in path]: site.addsitedir(path)")))
(alist-cons-before
'build 'adjust-config-file-prefix
(lambda* (#:key outputs #:allow-other-keys)
(substitute* "run-solfege.py"
(("prefix = os.path.*$")
(string-append "prefix = " (assoc-ref outputs "out")))))
(alist-cons-after
'install 'wrap-program
(lambda* (#:key inputs outputs #:allow-other-keys)
also need to modify GDK_PIXBUF_MODULE_FILE for SVG support .
(let* ((out (assoc-ref outputs "out"))
(path (getenv "PYTHONPATH"))
(rsvg (assoc-ref inputs "librsvg"))
(pixbuf (find-files rsvg "^loaders\\.cache$")))
(wrap-program (string-append out "/bin/solfege")
`("PYTHONPATH" ":" prefix (,path))
`("GDK_PIXBUF_MODULE_FILE" ":" prefix ,pixbuf))))
%standard-phases)))))))
(inputs
`(("python" ,python-2)
("pygtk" ,python2-pygtk)
("gettext" ,gnu-gettext)
("gtk" ,gtk+)
Fontconfig is needed to fix one of the errors , but other similar
("aplay" ,alsa-utils)
("mpg123" ,mpg123)
("ogg123" ,vorbis-tools)
("timidity" ,timidity++)))
(native-inputs
`(("pkg-config" ,pkg-config)
("txt2man" ,txt2man)
("ghostscript" ,ghostscript)
("texinfo" ,texinfo)))
(home-page "/")
(synopsis "Ear training")
(description
"GNU Solfege is a program for practicing musical ear-training. With it,
you can practice your recognition of various musical intervals and chords. It
features a statistics overview so you can monitor your progress across several
sessions. Solfege is also designed to be extensible so you can easily write
your own lessons.")
(license license:gpl3+)))
(define-public powertabeditor
(package
(name "powertabeditor")
(version "2.0.0-alpha8")
(source (origin
(method url-fetch)
(uri (string-append
"/"
version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32
"0gaa2x209v3azql8ak3r1n9a9qbxjx2ssirvwdxwklv2lmfqkm82"))
(modules '((guix build utils)))
(snippet
'(begin
(delete-file-recursively "external")
(substitute* "CMakeLists.txt"
(("include_directories\\(\\$\\{PROJECT_SOURCE_DIR\\}/external/.*") "")
(("add_subdirectory\\(external\\)") ""))
(substitute* "test/CMakeLists.txt"
(("include_directories\\(\\$\\{PROJECT_SOURCE_DIR\\}/external/.*") ""))
(substitute* "source/CMakeLists.txt"
(("qt5_use_modules")
(string-append
"install(TARGETS powertabeditor "
"RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin)\n"
"install(FILES data/tunings.json DESTINATION "
"${CMAKE_INSTALL_PREFIX}/share/powertabeditor/)\n"
"qt5_use_modules")))
#t))))
(build-system cmake-build-system)
(arguments
`(#:modules ((guix build cmake-build-system)
(guix build utils)
(ice-9 match))
#:configure-flags
(list "-DCMAKE_BUILD_WITH_INSTALL_RPATH=TRUE"
if can not be built
(string-append "-DCMAKE_INSTALL_RPATH="
(string-join (map (match-lambda
((name . directory)
(string-append directory "/lib")))
%build-inputs) ";")))
#:phases
(modify-phases %standard-phases
(replace
'check
(lambda _
(zero? (system* "bin/pte_tests"
"~Formats/PowerTabOldImport/Directions"))))
(add-before
'configure 'fix-tests
(lambda _
(substitute* "test/CMakeLists.txt"
(("cotire\\(pte_tests\\)") ""))
#t))
(add-before
'configure 'remove-third-party-libs
(lambda* (#:key inputs #:allow-other-keys)
using the bundled version of withershins .
(substitute* '("source/CMakeLists.txt"
"test/CMakeLists.txt")
(("target_link_libraries\\((powertabeditor|pte_tests)" _ target)
(string-append "target_link_libraries(" target " "
(assoc-ref inputs "binutils")
"/lib/libbfd.a "
(assoc-ref inputs "libiberty")
"/lib/libiberty.a "
"dl")))
#t)))))
(inputs
`(("boost" ,boost)
("alsa-lib" ,alsa-lib)
("qt" ,qt)
("withershins" ,withershins)
for withershins
for -lbfd and -liberty ( for )
("timidity" ,timidity++)
("pugixml" ,pugixml)
("rtmidi" ,rtmidi)
("rapidjson" ,rapidjson)
("zlib" ,zlib)))
(native-inputs
`(("catch" ,catch-framework)
("pkg-config" ,pkg-config)))
(home-page "")
(synopsis "Guitar tablature editor")
(description
"Power Tab Editor 2.0 is the successor to the famous original Power Tab
Editor. It is compatible with Power Tab Editor 1.7 and Guitar Pro.")
(license license:gpl3+)))
(define-public setbfree
(package
(name "setbfree")
(version "0.8.0")
(source (origin
(method url-fetch)
(uri
(string-append
""
version "/setbfree-" version ".tar.gz"))
(sha256
(base32
"045bgp7qsigpbrhk7qvgvliwiy26sajifwn7f2jvk90ckfqnlw4b"))))
(build-system gnu-build-system)
(arguments
#:make-flags
(list (string-append "PREFIX=" (assoc-ref %outputs "out"))
(string-append "FONTFILE="
(assoc-ref %build-inputs "font-bitstream-vera")
"/share/fonts/truetype/VeraBd.ttf")
,@(let ((system (or (%current-target-system)
(%current-system))))
(if (or (string-prefix? "x86_64" system)
(string-prefix? "i686" system))
'()
'("OPTIMIZATIONS=-ffast-math -fomit-frame-pointer -O3"))))
#:phases
(modify-phases %standard-phases
(add-before 'build 'set-CC-variable
(lambda _ (setenv "CC" "gcc") #t))
(delete 'configure))))
(inputs
`(("jack" ,jack-1)
("lv2" ,lv2)
("zita-convolver" ,zita-convolver)
("glu" ,glu)
("ftgl" ,ftgl)
("font-bitstream-vera" ,font-bitstream-vera)))
(native-inputs
`(("help2man" ,help2man)
("pkg-config" ,pkg-config)))
(home-page "")
(synopsis "Tonewheel organ")
(description
"setBfree is a MIDI-controlled, software synthesizer designed to imitate
the sound and properties of the electromechanical organs and sound
modification devices that brought world-wide fame to the names and products of
Laurens Hammond and Don Leslie.")
(license license:gpl2+)))
(define-public bristol
(package
(name "bristol")
(version "0.60.11")
(source (origin
(method url-fetch)
(uri (string-append "mirror/"
(version-major+minor version)
"/bristol-" version ".tar.gz"))
(sha256
(base32
"1fi2m4gmvxdi260821y09lxsimq82yv4k5bbgk3kyc3x1nyhn7vx"))))
(build-system gnu-build-system)
(inputs
`(("alsa-lib" ,alsa-lib)
("jack" ,jack-1)
("liblo" ,liblo)
("libx11" ,libx11)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Synthesizer emulator")
(description
"Bristol is an emulation package for a number of different 'classic'
synthesizers including additive and subtractive and a few organs. The
application consists of the engine, which is called bristol, and its own GUI
library called brighton that represents all the emulations. There are
although the author maintains that the quality and accuracy of each emulation
is subjective.")
(license license:gpl3+)))
(define-public tuxguitar
(package
(name "tuxguitar")
(version "1.2")
(source (origin
(method url-fetch)
(uri (string-append
"mirror-"
version "/tuxguitar-src-" version ".tar.gz"))
(sha256
(base32
"1g1yf2gd06fzdhqb8kb8dmdcmr602s9y24f01kyl4940wimgr944"))))
(build-system gnu-build-system)
(arguments
`(#:make-flags (list (string-append "LDFLAGS=-Wl,-rpath="
(assoc-ref %outputs "out") "/lib")
(string-append "PREFIX="
(assoc-ref %outputs "out"))
(string-append "SWT_PATH="
(assoc-ref %build-inputs "swt")
"/share/java/swt.jar"))
#:phases
(alist-cons-before
'build 'enter-dir-set-path-and-pass-ldflags
(lambda* (#:key inputs #:allow-other-keys)
(chdir "TuxGuitar")
(substitute* "GNUmakefile"
(("PROPERTIES\\?=")
(string-append "PROPERTIES?= -Dswt.library.path="
(assoc-ref inputs "swt") "/lib"))
(("\\$\\(GCJ\\) -o") "$(GCJ) $(LDFLAGS) -o"))
#t)
(alist-delete 'configure %standard-phases))))
(inputs
`(("swt" ,swt)))
(native-inputs
`(("gcj" ,gcj)
("pkg-config" ,pkg-config)))
(home-page "")
(synopsis "Multitrack tablature editor and player")
(description
"TuxGuitar is a guitar tablature editor with player support through midi.
It can display scores and multitrack tabs. TuxGuitar provides various
additional features, including autoscrolling while playing, note duration
management, bend/slide/vibrato/hammer-on/pull-off effects, support for
tuplets, time signature management, tempo management, gp3/gp4/gp5 import and
export.")
(license license:lgpl2.1+)))
(define-public pd
(package
(name "pd")
(version "0.45.4")
(source (origin
(method url-fetch)
(uri
(string-append "mirror-data/pure-data/"
version "/pd-" (version-major+minor version)
"-" (last (string-split version #\.))
".src.tar.gz"))
(sha256
(base32
"1ls2ap5yi2zxvmr247621g4jx0hhfds4j5704a050bn2n3l0va2p"))))
(build-system gnu-build-system)
(arguments
#:phases
(modify-phases %standard-phases
(add-before
'configure 'fix-wish-path
(lambda _
(substitute* "src/s_inter.c"
((" wish ") (string-append " " (which "wish8.6") " ")))
(substitute* "tcl/pd-gui.tcl"
(("exec wish ") (string-append "exec " (which "wish8.6") " ")))
#t))
(add-after
'unpack 'autoconf
(lambda _ (zero? (system* "autoreconf" "-vfi")))))))
(native-inputs
`(("autoconf" ,autoconf)
("automake" ,automake)
("libtool" ,libtool)
("gettext" ,gnu-gettext)
("pkg-config" ,pkg-config)))
(inputs
`(("tk" ,tk)
("alsa-lib" ,alsa-lib)
("jack" ,jack-1)))
(home-page "")
(synopsis "Visual programming language for artistic performances")
(description
"Pure Data (aka Pd) is a visual programming language. Pd enables
musicians, visual artists, performers, researchers, and developers to create
software graphically, without writing lines of code. Pd is used to process
and generate sound, video, 2D/3D graphics, and interface sensors, input
devices, and MIDI. Pd can easily work over local and remote networks to
integrate wearable technology, motor systems, lighting rigs, and other
equipment. Pd is suitable for learning basic multimedia processing and visual
programming methods as well as for realizing complex systems for large-scale
projects.")
(license license:bsd-3)))
(define-public frescobaldi
(package
(name "frescobaldi")
(version "2.18.1")
(source (origin
(method url-fetch)
(uri (string-append
""
version "/frescobaldi-" version ".tar.gz"))
(sha256
(base32
"1hflc6gck6dn17czc2ldai5j0ynfg3df8lqcggdry06qxsdbnns7"))))
(build-system python-build-system)
(inputs
`(("lilypond" ,lilypond)
("python-pyqt-4" ,python-pyqt-4)
("python-ly" ,python-ly)
("poppler" ,poppler)
("python-poppler-qt4" ,python-poppler-qt4)
("python-sip" ,python-sip)))
(home-page "/")
(synopsis "LilyPond sheet music text editor")
(description
"Frescobaldi is a LilyPond sheet music text editor with syntax
highlighting and automatic completion. Among other things, it can render
scores next to the source, can capture input from MIDI or read MusicXML and
ABC files, has a MIDI player for proof-listening, and includes a documentation
browser.")
(license license:gpl2+)))
(define-public drumstick
(package
(name "drumstick")
(version "1.0.1")
(source (origin
(method url-fetch)
(uri (string-append "mirror/"
version "/drumstick-" version ".tar.bz2"))
(sha256
(base32
"0mxgix85b2qqs859z91cxik5x0s60dykqiflbj62px9akvf91qdv"))))
(build-system cmake-build-system)
(arguments
#:configure-flags '("-DLIB_SUFFIX=")
#:phases
(modify-phases %standard-phases
(add-before 'configure 'fix-docbook
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "cmake_admin/CreateManpages.cmake"
(("")
(string-append (assoc-ref inputs "docbook-xsl")
"/xml/xsl/docbook-xsl-"
,(package-version docbook-xsl)
"/manpages/docbook.xsl")))
#t)))))
(inputs
`(("qt" ,qt)
("alsa-lib" ,alsa-lib)
("fluidsynth" ,fluidsynth)))
(native-inputs
`(("pkg-config" ,pkg-config)
for xsltproc
("docbook-xsl" ,docbook-xsl)
("doxygen" ,doxygen)))
(home-page "/")
(synopsis "C++ MIDI library")
(description
"Drumstick is a set of MIDI libraries using C++/Qt5 idioms and style. It
includes a C++ wrapper around the ALSA library sequencer interface. A
complementary library provides classes for processing SMF (Standard MIDI
files: .MID/.KAR), Cakewalk (.WRK), and Overture (.OVE) file formats. A
multiplatform realtime MIDI I/O library is also provided with various output
backends, including ALSA, OSS, Network and FluidSynth.")
(license license:gpl2+)))
(define-public vmpk
(package
(name "vmpk")
(version "0.6.1")
(source (origin
(method url-fetch)
(uri (string-append "mirror/"
version "/vmpk-" version ".tar.bz2"))
(sha256
(base32
"0ranldd033bd31m9d2vkbkn9zp1k46xbaysllai2i95rf1nhirqc"))))
(build-system cmake-build-system)
(arguments
#:phases
(modify-phases %standard-phases
(add-before 'configure 'fix-docbook
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "cmake_admin/CreateManpages.cmake"
(("")
(string-append (assoc-ref inputs "docbook-xsl")
"/xml/xsl/docbook-xsl-"
,(package-version docbook-xsl)
"/manpages/docbook.xsl")))
#t)))))
(inputs
`(("drumstick" ,drumstick)
("qt" ,qt)))
(native-inputs
for xsltproc
("docbook-xsl" ,docbook-xsl)
("pkg-config" ,pkg-config)))
(home-page "")
(synopsis "Virtual MIDI piano keyboard")
(description
"Virtual MIDI Piano Keyboard is a MIDI events generator and receiver. It
doesn't produce any sound by itself, but can be used to drive a MIDI
synthesizer (either hardware or software, internal or external). You can use
the computer's keyboard to play MIDI notes, and also the mouse. You can use
the Virtual MIDI Piano Keyboard to display the played MIDI notes from another
instrument or MIDI file player.")
(license license:gpl3+)))
(define-public zynaddsubfx
(package
(name "zynaddsubfx")
(version "2.5.2")
(source (origin
(method url-fetch)
(uri (string-append
"mirror/"
version "/zynaddsubfx-" version ".tar.gz"))
(sha256
(base32
"11yrady7xwfrzszkk2fvq81ymv99mq474h60qnirk27khdygk24m"))))
(build-system cmake-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
Move SSE compiler optimization flags from generic target to
on non - Intel machines .
(add-after 'unpack 'remove-sse-flags-from-generic-target
(lambda _
(substitute* "src/CMakeLists.txt"
(("-msse -msse2 -mfpmath=sse") "")
(("-march=(athlon64|core2)" flag)
(string-append flag " -msse -msse2 -mfpmath=sse")))
#t)))))
(inputs
`(("liblo" ,liblo)
("ntk" ,ntk)
("alsa-lib" ,alsa-lib)
("jack" ,jack-1)
("fftw" ,fftw)
("minixml" ,minixml)
("libxpm" ,libxpm)
("zlib" ,zlib)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Software synthesizer")
(description
"ZynAddSubFX is a feature heavy realtime software synthesizer. It offers
three synthesizer engines, multitimbral and polyphonic synths, microtonal
capabilities, custom envelopes, effects, etc.")
(license license:gpl2)))
(define-public yoshimi
(package
(name "yoshimi")
(version "1.3.7.1")
(source (origin
(method url-fetch)
(uri (string-append "mirror/"
(version-major+minor version)
"/yoshimi-" version ".tar.bz2"))
(sha256
(base32
"13xc1x8jrr2rn26jx4dini692ww3771d5j5xf7f56ixqr7mmdhvz"))))
(build-system cmake-build-system)
(arguments
#:configure-flags
(list (string-append "-DCMAKE_INSTALL_DATAROOTDIR="
(assoc-ref %outputs "out") "/share"))
#:phases
(modify-phases %standard-phases
(add-before 'configure 'enter-dir
(lambda _ (chdir "src") #t))
Move SSE compiler optimization flags from generic target to
on non - Intel machines .
(add-after 'unpack 'remove-sse-flags-from-generic-target
(lambda _
(substitute* "src/CMakeLists.txt"
(("-msse -msse2 -mfpmath=sse") "")
(("-march=(athlon64|core2)" flag)
(string-append flag " -msse -msse2 -mfpmath=sse")))
#t)))))
(inputs
`(("boost" ,boost)
("fftwf" ,fftwf)
("alsa-lib" ,alsa-lib)
("jack" ,jack-1)
("fontconfig" ,fontconfig)
("minixml" ,minixml)
("mesa" ,mesa)
("fltk" ,fltk)
("lv2" ,lv2)
("readline" ,readline)
("ncurses" ,ncurses)
("cairo" ,cairo)
("zlib" ,zlib)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Multi-paradigm software synthesizer")
(description
"Yoshimi is a fork of ZynAddSubFX, a feature heavy realtime software
synthesizer. It offers three synthesizer engines, multitimbral and polyphonic
synths, microtonal capabilities, custom envelopes, effects, etc. Yoshimi
improves on support for JACK features, such as JACK MIDI.")
(license license:gpl2)))
|
4db402bf94d6a14a51acbf08b27c7e0dbbb5194b767400240353c7814860f5f0 | amnh/poy5 | latex.ml | POY 5.1.1 . A phylogenetic analysis program using Dynamic Homologies .
Copyright ( C ) 2014 , , , Ward Wheeler ,
and the American Museum of Natural History .
(* *)
(* This program is free software; you can redistribute it and/or modify *)
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
(* (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston ,
USA
let debug = false
type parsed =
| Word of string
| WordNoSpace of string
| Blank
| Text of parsed list
| Command of (string * parsed list)
| Comment of string
let channel = ref stdout
let failwithf format = Printf.ksprintf (failwith) format
let rec string_of_parsed = function
| Word x -> Printf.sprintf "Word:%s" x
| WordNoSpace x -> Printf.sprintf "Word:%s" x
| Blank -> Printf.sprintf "' '";
| Text l ->
(List.fold_left (fun acc x -> acc^", "^string_of_parsed x) "[" l)^"]"
| Command (x,l) ->
let init = Printf.sprintf "CMD:%s[" x in
(List.fold_left (fun acc x -> acc^", "^string_of_parsed x) init l)^"]"
| Comment x -> Printf.sprintf "Comment:%s\n" x
let print_parsed l =
let rec print_parsed d x =
let () = print_depth d in match x with
| Word x -> Printf.printf "Word:%s\n" x
| WordNoSpace x -> Printf.printf "Word:%s\n" x
| Blank -> Printf.printf "' '\n";
| Text l -> List.iter (print_parsed (d+1)) l;
| Command (x,l) -> Printf.printf "CMD:%s\n" x;
List.iter (print_parsed (d+1)) l
| Comment x -> Printf.printf "Comment:%s\n" x
and print_depth x =
if x = 0
then ()
else begin
Printf.printf "\t";
print_depth (x-1)
end
in
print_parsed 0 l
let string_of_parsed ?(sep=", ") lst =
List.fold_left (fun acc x -> (string_of_parsed x)^sep^acc) "" lst
let rec produce_latex channel data =
let o str = output_string channel str in
let rec produce_latex x = match x with
| (Command ("begin", (Word h :: tl))) ->
begin match h with
| "command" ->
begin match tl with
| h::_ -> o "@]\n\n.\n"; produce_latex h; o "\n@[<v 2>"
| [] -> failwith "command with no args?"
end
| "syntax" ->
o "@,@,@[<v 2>@{<c:cyan>Syntax@}@,@,@[<v>"
| "description" ->
o "@,@[<v 2>@,@["
| "poydescription" ->
o "@,@[<v 2>@{<c:cyan>Description@}@,@,@["
| "arguments" ->
o "@,@,@[<v 2>@{<c:cyan>Arguments@}@,@,@[<v>"
| "argumentgroup" ->
begin match tl with
| [title ; description] ->
o "@,@[<v 2>@{<c:cyan>@[";
produce_latex title;
o "@]@}@,@[";
produce_latex description
| [title] ->
o "@,@[<v 2>@{<c:cyan>@[";
produce_latex title;
o "@]@}@,@["
| x ->
failwithf "I found argument group with %d args, %s"
(List.length x) (string_of_parsed tl)
end
| "statement" -> o "@,@[@,@["
| "poyexamples" -> o "@,@[<v 2>@{<c:cyan>Examples@}@,@,@[<v>"
| "poyalso" -> o "@,@[<v 2>@[@{<c:cyan>See Also@}@]@,@,@[<v>"
| "flushleft"
| "center" -> o "@[<v 2>@,@["
| "atsymbol" -> o "@@"
| _ -> ()
end
| Command ("%", []) -> o "%"
| Command (h, []) when h = "" -> ()
| Command (h, []) when h.[0] = '_' -> o h
| Command ("end", [Word h]) -> o "@]@]@,"
| Command ("argumentdefinition", [com ; args ; definition ; cross_reference]) ->
o "@[<v 2>@,@[@{<c:yellow>";
produce_latex com;
produce_latex args;
o "@}@]@,@[";
produce_latex definition;
o "@]@]@,"
| Command ("poydefaults", [args; descr]) ->
o "@,@,@[<v 2>@{<c:cyan>Defaults@}@,@,@[";
produce_latex args;
o "@]@,@[";
produce_latex descr;
o "@]@]@,"
| Command ("obligatory", [arg]) ->
o ": ";
produce_latex arg
| Command ("optional", [arg]) ->
o "[: ";
produce_latex arg;
o "]";
| Command ("poyexample", [example; explanation]) ->
o "@[<v 2>@[@{<c:green>";
produce_latex example;
o "@}@]@,@[";
produce_latex explanation;
o " @]@]@,@,@?"
| Command ("ncross", [arg; _])
| Command ("cross", [arg]) ->
o "@["; produce_latex arg; o "@]@,"
| Command ("poycommand", arg) ->
o "@[<h>"; List.iter produce_latex arg; o " @]"
| Command ("ccross", [Word arg])
| Command ("nccross", [Word arg; _]) ->
o (arg ^ " (see help (" ^ arg ^ ")) ");
| Command _ -> ()
| Text lst ->
List.iter produce_latex lst
| Word x ->
if x <> "~" then o x
| WordNoSpace x ->
if x <> "~" then o x
| Blank ->
o " "
| Comment _ -> ()
in
produce_latex data
let rec produce_troff channel data =
let o str = output_string channel str in
let rec produce_troff = function
| Command ("begin", (Word h :: tl)) ->
begin match h with
| "command" ->
begin match tl with
| h::_ -> o "\n.SH "; produce_troff h; o "\n.P\n"
| [] -> failwith "command with no args?"
end
| "description" ->
o "\n.P\n"
| "poydescription" ->
o "\n.SS Description\n"
| "syntax" ->
o "\n. Syntax\n"
| "arguments" ->
o "\n.SS Arguments\n"
| "argumentgroup" ->
begin match tl with
| [title ; description] ->
o "\n.SS \"";
produce_troff title;
o "\"\n.P\n";
produce_troff description
| [title] ->
o "\n.SS \"";
produce_troff title;
o "\"\n.P\n"
| x ->
failwithf "I found argument group with %d args, %s"
(List.length x) (string_of_parsed tl)
end
| "statement" -> o "\n.P\n"
| "poyexamples" ->
o "\n.SS Examples\n"
| "poyalso" ->
o "\n.SS \"See Also\"\n"
| "flushleft"
| "center" -> o "\n.P\n"
| "atsymbol" -> o "@"
| _ -> ()
end
| Command ("%", []) -> o "%"
| Command (h, []) when h = "" -> ()
| Command (h, []) when h.[0] = '_' -> o h
| Command ("end", [Word h]) -> o "\n.P\n"
| Command ("argumentdefinition", [com ; args ; definition ; cross_reference]) ->
o "\n.IP \"";
produce_troff com;
produce_troff args;
o "\"\n";
produce_troff definition;
o "\n"
| Command ("poydefaults", [args; descr]) ->
o "\n.SS Defaults\n.P\n";
produce_troff args;
o "\n.P\n";
produce_troff descr;
o "\n";
| Command ("obligatory", [arg]) ->
o ": ";
produce_troff arg
| Command ("optional", [arg]) ->
o "[: ";
produce_troff arg;
o "]";
| Command ("poyexample", [example; explanation]) ->
o "\n.P\n";
produce_troff example;
o "\n.P\n";
produce_troff explanation;
o "\n";
| Command ("ncross", [arg; _])
| Command ("cross", [arg]) ->
produce_troff arg;
o "\n.br\n";
| Command ("poycommand", arg) ->
o " ";
List.iter produce_troff arg;
o " ";
| Command ("ccross", [Word arg])
| Command ("nccross", [Word arg; _]) ->
o (arg ^ "(see help (" ^ arg ^ ")) ");
| Command _ -> ()
| Text lst ->
List.iter produce_troff lst;
| Word x ->
if x <> "~" then o x;
| WordNoSpace x ->
if x <> "~" then o x
| Blank -> o " "
| Comment _ -> ()
in
produce_troff data
let rec collapse = function
| Blank
| (WordNoSpace _)
| (Comment _)
| (Word _) as x -> x
| Text [(Text _) as y] -> collapse y
| Text [(Word _) as y] -> y
| Text x ->
Text (List.map collapse x)
| Command ("poy", _) -> Word "POY "
| Command ("poybool", _) -> Word "BOOL "
| Command ("poyfloat", _) -> Word "FLOAT "
| Command ("poyint", _) -> Word "INTEGER "
| Command ("poystring", _) -> Word "STRING "
| Command ("poylident", _) -> Word "LIDENT "
| Command ("poycommand", [arg]) ->
Command ("poycommand", [collapse arg])
| Command ("poyargument", [arg])
| Command ("texttt", [arg])
| Command ("emph", [arg]) ->
collapse arg
| Command (a, b) ->
Command (a, List.map collapse b)
let rec flatten x = match x with
| ((Comment _) as h) :: t
| ((WordNoSpace _) as h) :: t
| ((Word _) as h) :: t -> h :: (flatten t)
| (Text x) :: t -> (flatten x) @ (flatten t)
| h :: t -> h :: (flatten t)
| [] -> []
let rec collapse2 = function
| (Text a) :: t ->
collapse2 ((flatten a) @ t)
| (Word a) :: (Command (h, [])) :: t when h = "" ->
Word h :: (collapse2 t)
| (Word a) :: (Command (h, [])) :: t when h.[0] = '_' ->
Word (a ^ h) :: (collapse2 t)
| ((Word a) as h) :: (((Word b) :: _) as t) ->
if b = "." || b = "," || b = ")" || b = "]" || b = "," || b = ";" then
(WordNoSpace a) :: (collapse2 t)
else h :: (collapse2 t)
| h :: t -> h :: (collapse2 t)
| [] -> []
let rec the_parser mode fstream =
let brstr = match mode with
| `OnlineHelp -> "\n\n"
| `Troff -> "\n.br\n"
in
let is_newline fstream =
fstream#skip_ws_nl;
fstream#match_prefix "\\\\"
in
let is_command fstream =
fstream#skip_ws_nl;
fstream#match_prefix "\\"
in
let is_escape_underscore fstream =
fstream#skip_ws_nl;
if fstream#match_prefix "\\" then
if fstream#match_prefix "_" then
true
else begin
fstream#putback '\\';
false
end
else
false
in
let is_escape fstream =
fstream#skip_ws_nl;
if fstream#match_prefix "\\" then
if fstream#match_prefix "\\" then
true
else begin
fstream#putback '\\';
false
end
else
false
in
let is_comment fstream =
fstream#skip_ws_nl;
fstream#match_prefix "%"
in
let is_word fstream =
fstream#skip_ws_nl;
not (fstream#match_prefix "\\")
in
let is_enclosed fstream =
fstream#skip_ws_nl;
fstream#match_prefix "{"
in
let is_close_command fstream =
fstream#skip_ws_nl;
fstream#match_prefix "}"
in
let is_end_of_file fstream =
match fstream#getch_safe with
| Some x -> fstream#putback x; false
| None -> true
in
let is_blank fstream =
let res = fstream#read_incl [' '; '\t'; '\010'; '\013'] in
if res = "" then false
else true
in
let rec get_param acc fstream =
fstream#skip_ws_nl;
if fstream#match_prefix "{" then begin
let res = the_parser mode fstream in
get_param (acc @ [(Text res)]) fstream
end else acc
in
let skip1 = [' '; '\t'; '\\'; '\010'; '\013'; '{'; '}'; ','; '.'; ')'; '('; '['; ']'; '~']
and noskip = ['('; ')'; ','; '.'; '['; ']'; '~'] in
let get_comm fstream =
fstream#skip_ws_nl;
let cmd = fstream#read_excl skip1 in
let param = get_param [] fstream in
Command (cmd, param)
and get_word fstream =
fstream#skip_ws_nl;
let cmd = fstream#read_excl skip1 in
let cmd =
if cmd = "" then fstream#read_incl noskip
else cmd
in
Text [Word cmd]
and get_comment fstream =
fstream#skip_ws_nl;
let comment = fstream#read_excl ['\n';'\013';'\010'] in
Comment comment
in
let rec split_on_commands acc fstream =
if is_end_of_file fstream then
let data = List.rev acc in
let () = if debug then List.iter print_parsed data in
data
else if is_blank fstream then
split_on_commands (Blank :: acc) fstream
else if is_close_command fstream then
List.rev acc
else if is_newline fstream then
split_on_commands ((Text [Word brstr]) :: acc) fstream
else if is_comment fstream then
split_on_commands ((get_comment fstream) :: acc) fstream
else if is_escape fstream then
split_on_commands acc fstream
else if is_escape_underscore fstream then
split_on_commands ((Word "_")::acc) fstream
else if is_command fstream then
split_on_commands ((get_comm fstream) :: acc) fstream
else if is_enclosed fstream then
split_on_commands ((Text (the_parser mode fstream)) :: acc) fstream
else if is_word fstream then
split_on_commands ((get_word fstream) :: acc) fstream
else failwith "Huh?";
in
let res = split_on_commands [] fstream in
collapse2 (List.map collapse res)
let process parsed mode channel =
let generator = match mode with
| `OnlineHelp -> produce_latex channel
| `Troff -> produce_troff channel
in
List.iter generator parsed
let process_file parsed mode output_file =
let channel = open_out output_file in
let o str = output_string channel str in
match mode with
| `Troff ->
o (".TH POY 1 LOCAL\n\n");
o (".SH NAME\npoy \\- A phylogenetic analysis program using dynamic \
homologies\n.SH SYNOPSIS\n.B poy [options] filename.\n\n\
.SH DESCRIPTION\npoy is a phylogenetic analysis program for morphological \
and molecular characters with support for dynamic homology characters: \
that is, supports the analysis of unaligned sequences.\n\n.SH OPTIONS\n\n\
.TP 5\n\
-w\n\
Run poy in the specified working directory. \n\
.TP\n\
-e\n\
Exit upon error. \n\n\
.TP\n\
-d\n\
Dump filename in case of error. \n\
.TP\n\
-q \n\
Don't wait for input other than the program argument script. \n\
.TP\n\
-no-output-xml \n\
Do not generate the output.xml file. \n\
.TP\n\
-help\n\
Display this list of options. \n\
.TP\n\
--help\n\
Display this list of options. \n\
\n.SH VERSION\n 4.0." ^ (Str.global_replace (Str.regexp " ") "" BuildNumber.build) ^ "\n\
.SH COMMANDS\n.P\n\
For complete documentation go to \
-research/computational-sciences/research/projects/systematic-biology/poy.\n\
The following are the valid commands for \n\
.B poy.");
process parsed mode channel;
o "\n.SH AUTHOR\nPOY was written by Andres Varon, Lin Hong, \
NIcholas Lucaroni, and Ward Wheeler.\n.PP\nThis manual page was written \
by Andres Varon, Lin Hong, Nicholas Lucaroni, Ward Wheeler\
Ilya Temkin, Megan Cevasco, Kurt M. Pickett, Julian Faivovich, \
Taran Grant, and William Leo Smith.\n.RS\n\n"
| `OnlineHelp ->
o (".\nauthors\n@[<v 2> POY was written by Andres Varon, Lin Hong, \
Nicholas Lucaroni, and Ward Wheeler.This manual page was written \
by Andres Varon, Lin Hong, Nicholas Lucaroni, Ward Wheeler\
Ilya Temkin, Megan Cevasco, Kurt M. Pickett, Julian Faivovich, \
Taran Grant, and William Leo Smith.@]\n\n");
o (".\ncopyright\n@[<v 2>"^ Version.copyright_authors ^ Version.warrenty_information ^"@]\n\n");
o (".\nversion\n@[<v 2> "^ Version.copyright_authors ^ Version.compile_information ^ "@]\n\n");
process parsed mode channel;
()
let () =
let ch = FileStream.Pervasives.open_in (`Local "../doc/allcommands.tex") in
let parsed = the_parser `Troff ch in
let () = process_file parsed `OnlineHelp "help.txt" in
let () = process_file parsed `Troff "poy.1" in
()
| null | https://raw.githubusercontent.com/amnh/poy5/da563a2339d3fa9c0110ae86cc35fad576f728ab/src/latex.ml | ocaml |
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.
| POY 5.1.1 . A phylogenetic analysis program using Dynamic Homologies .
Copyright ( C ) 2014 , , , Ward Wheeler ,
and the American Museum of Natural History .
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
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
let debug = false
type parsed =
| Word of string
| WordNoSpace of string
| Blank
| Text of parsed list
| Command of (string * parsed list)
| Comment of string
let channel = ref stdout
let failwithf format = Printf.ksprintf (failwith) format
let rec string_of_parsed = function
| Word x -> Printf.sprintf "Word:%s" x
| WordNoSpace x -> Printf.sprintf "Word:%s" x
| Blank -> Printf.sprintf "' '";
| Text l ->
(List.fold_left (fun acc x -> acc^", "^string_of_parsed x) "[" l)^"]"
| Command (x,l) ->
let init = Printf.sprintf "CMD:%s[" x in
(List.fold_left (fun acc x -> acc^", "^string_of_parsed x) init l)^"]"
| Comment x -> Printf.sprintf "Comment:%s\n" x
let print_parsed l =
let rec print_parsed d x =
let () = print_depth d in match x with
| Word x -> Printf.printf "Word:%s\n" x
| WordNoSpace x -> Printf.printf "Word:%s\n" x
| Blank -> Printf.printf "' '\n";
| Text l -> List.iter (print_parsed (d+1)) l;
| Command (x,l) -> Printf.printf "CMD:%s\n" x;
List.iter (print_parsed (d+1)) l
| Comment x -> Printf.printf "Comment:%s\n" x
and print_depth x =
if x = 0
then ()
else begin
Printf.printf "\t";
print_depth (x-1)
end
in
print_parsed 0 l
let string_of_parsed ?(sep=", ") lst =
List.fold_left (fun acc x -> (string_of_parsed x)^sep^acc) "" lst
let rec produce_latex channel data =
let o str = output_string channel str in
let rec produce_latex x = match x with
| (Command ("begin", (Word h :: tl))) ->
begin match h with
| "command" ->
begin match tl with
| h::_ -> o "@]\n\n.\n"; produce_latex h; o "\n@[<v 2>"
| [] -> failwith "command with no args?"
end
| "syntax" ->
o "@,@,@[<v 2>@{<c:cyan>Syntax@}@,@,@[<v>"
| "description" ->
o "@,@[<v 2>@,@["
| "poydescription" ->
o "@,@[<v 2>@{<c:cyan>Description@}@,@,@["
| "arguments" ->
o "@,@,@[<v 2>@{<c:cyan>Arguments@}@,@,@[<v>"
| "argumentgroup" ->
begin match tl with
| [title ; description] ->
o "@,@[<v 2>@{<c:cyan>@[";
produce_latex title;
o "@]@}@,@[";
produce_latex description
| [title] ->
o "@,@[<v 2>@{<c:cyan>@[";
produce_latex title;
o "@]@}@,@["
| x ->
failwithf "I found argument group with %d args, %s"
(List.length x) (string_of_parsed tl)
end
| "statement" -> o "@,@[@,@["
| "poyexamples" -> o "@,@[<v 2>@{<c:cyan>Examples@}@,@,@[<v>"
| "poyalso" -> o "@,@[<v 2>@[@{<c:cyan>See Also@}@]@,@,@[<v>"
| "flushleft"
| "center" -> o "@[<v 2>@,@["
| "atsymbol" -> o "@@"
| _ -> ()
end
| Command ("%", []) -> o "%"
| Command (h, []) when h = "" -> ()
| Command (h, []) when h.[0] = '_' -> o h
| Command ("end", [Word h]) -> o "@]@]@,"
| Command ("argumentdefinition", [com ; args ; definition ; cross_reference]) ->
o "@[<v 2>@,@[@{<c:yellow>";
produce_latex com;
produce_latex args;
o "@}@]@,@[";
produce_latex definition;
o "@]@]@,"
| Command ("poydefaults", [args; descr]) ->
o "@,@,@[<v 2>@{<c:cyan>Defaults@}@,@,@[";
produce_latex args;
o "@]@,@[";
produce_latex descr;
o "@]@]@,"
| Command ("obligatory", [arg]) ->
o ": ";
produce_latex arg
| Command ("optional", [arg]) ->
o "[: ";
produce_latex arg;
o "]";
| Command ("poyexample", [example; explanation]) ->
o "@[<v 2>@[@{<c:green>";
produce_latex example;
o "@}@]@,@[";
produce_latex explanation;
o " @]@]@,@,@?"
| Command ("ncross", [arg; _])
| Command ("cross", [arg]) ->
o "@["; produce_latex arg; o "@]@,"
| Command ("poycommand", arg) ->
o "@[<h>"; List.iter produce_latex arg; o " @]"
| Command ("ccross", [Word arg])
| Command ("nccross", [Word arg; _]) ->
o (arg ^ " (see help (" ^ arg ^ ")) ");
| Command _ -> ()
| Text lst ->
List.iter produce_latex lst
| Word x ->
if x <> "~" then o x
| WordNoSpace x ->
if x <> "~" then o x
| Blank ->
o " "
| Comment _ -> ()
in
produce_latex data
let rec produce_troff channel data =
let o str = output_string channel str in
let rec produce_troff = function
| Command ("begin", (Word h :: tl)) ->
begin match h with
| "command" ->
begin match tl with
| h::_ -> o "\n.SH "; produce_troff h; o "\n.P\n"
| [] -> failwith "command with no args?"
end
| "description" ->
o "\n.P\n"
| "poydescription" ->
o "\n.SS Description\n"
| "syntax" ->
o "\n. Syntax\n"
| "arguments" ->
o "\n.SS Arguments\n"
| "argumentgroup" ->
begin match tl with
| [title ; description] ->
o "\n.SS \"";
produce_troff title;
o "\"\n.P\n";
produce_troff description
| [title] ->
o "\n.SS \"";
produce_troff title;
o "\"\n.P\n"
| x ->
failwithf "I found argument group with %d args, %s"
(List.length x) (string_of_parsed tl)
end
| "statement" -> o "\n.P\n"
| "poyexamples" ->
o "\n.SS Examples\n"
| "poyalso" ->
o "\n.SS \"See Also\"\n"
| "flushleft"
| "center" -> o "\n.P\n"
| "atsymbol" -> o "@"
| _ -> ()
end
| Command ("%", []) -> o "%"
| Command (h, []) when h = "" -> ()
| Command (h, []) when h.[0] = '_' -> o h
| Command ("end", [Word h]) -> o "\n.P\n"
| Command ("argumentdefinition", [com ; args ; definition ; cross_reference]) ->
o "\n.IP \"";
produce_troff com;
produce_troff args;
o "\"\n";
produce_troff definition;
o "\n"
| Command ("poydefaults", [args; descr]) ->
o "\n.SS Defaults\n.P\n";
produce_troff args;
o "\n.P\n";
produce_troff descr;
o "\n";
| Command ("obligatory", [arg]) ->
o ": ";
produce_troff arg
| Command ("optional", [arg]) ->
o "[: ";
produce_troff arg;
o "]";
| Command ("poyexample", [example; explanation]) ->
o "\n.P\n";
produce_troff example;
o "\n.P\n";
produce_troff explanation;
o "\n";
| Command ("ncross", [arg; _])
| Command ("cross", [arg]) ->
produce_troff arg;
o "\n.br\n";
| Command ("poycommand", arg) ->
o " ";
List.iter produce_troff arg;
o " ";
| Command ("ccross", [Word arg])
| Command ("nccross", [Word arg; _]) ->
o (arg ^ "(see help (" ^ arg ^ ")) ");
| Command _ -> ()
| Text lst ->
List.iter produce_troff lst;
| Word x ->
if x <> "~" then o x;
| WordNoSpace x ->
if x <> "~" then o x
| Blank -> o " "
| Comment _ -> ()
in
produce_troff data
let rec collapse = function
| Blank
| (WordNoSpace _)
| (Comment _)
| (Word _) as x -> x
| Text [(Text _) as y] -> collapse y
| Text [(Word _) as y] -> y
| Text x ->
Text (List.map collapse x)
| Command ("poy", _) -> Word "POY "
| Command ("poybool", _) -> Word "BOOL "
| Command ("poyfloat", _) -> Word "FLOAT "
| Command ("poyint", _) -> Word "INTEGER "
| Command ("poystring", _) -> Word "STRING "
| Command ("poylident", _) -> Word "LIDENT "
| Command ("poycommand", [arg]) ->
Command ("poycommand", [collapse arg])
| Command ("poyargument", [arg])
| Command ("texttt", [arg])
| Command ("emph", [arg]) ->
collapse arg
| Command (a, b) ->
Command (a, List.map collapse b)
let rec flatten x = match x with
| ((Comment _) as h) :: t
| ((WordNoSpace _) as h) :: t
| ((Word _) as h) :: t -> h :: (flatten t)
| (Text x) :: t -> (flatten x) @ (flatten t)
| h :: t -> h :: (flatten t)
| [] -> []
let rec collapse2 = function
| (Text a) :: t ->
collapse2 ((flatten a) @ t)
| (Word a) :: (Command (h, [])) :: t when h = "" ->
Word h :: (collapse2 t)
| (Word a) :: (Command (h, [])) :: t when h.[0] = '_' ->
Word (a ^ h) :: (collapse2 t)
| ((Word a) as h) :: (((Word b) :: _) as t) ->
if b = "." || b = "," || b = ")" || b = "]" || b = "," || b = ";" then
(WordNoSpace a) :: (collapse2 t)
else h :: (collapse2 t)
| h :: t -> h :: (collapse2 t)
| [] -> []
let rec the_parser mode fstream =
let brstr = match mode with
| `OnlineHelp -> "\n\n"
| `Troff -> "\n.br\n"
in
let is_newline fstream =
fstream#skip_ws_nl;
fstream#match_prefix "\\\\"
in
let is_command fstream =
fstream#skip_ws_nl;
fstream#match_prefix "\\"
in
let is_escape_underscore fstream =
fstream#skip_ws_nl;
if fstream#match_prefix "\\" then
if fstream#match_prefix "_" then
true
else begin
fstream#putback '\\';
false
end
else
false
in
let is_escape fstream =
fstream#skip_ws_nl;
if fstream#match_prefix "\\" then
if fstream#match_prefix "\\" then
true
else begin
fstream#putback '\\';
false
end
else
false
in
let is_comment fstream =
fstream#skip_ws_nl;
fstream#match_prefix "%"
in
let is_word fstream =
fstream#skip_ws_nl;
not (fstream#match_prefix "\\")
in
let is_enclosed fstream =
fstream#skip_ws_nl;
fstream#match_prefix "{"
in
let is_close_command fstream =
fstream#skip_ws_nl;
fstream#match_prefix "}"
in
let is_end_of_file fstream =
match fstream#getch_safe with
| Some x -> fstream#putback x; false
| None -> true
in
let is_blank fstream =
let res = fstream#read_incl [' '; '\t'; '\010'; '\013'] in
if res = "" then false
else true
in
let rec get_param acc fstream =
fstream#skip_ws_nl;
if fstream#match_prefix "{" then begin
let res = the_parser mode fstream in
get_param (acc @ [(Text res)]) fstream
end else acc
in
let skip1 = [' '; '\t'; '\\'; '\010'; '\013'; '{'; '}'; ','; '.'; ')'; '('; '['; ']'; '~']
and noskip = ['('; ')'; ','; '.'; '['; ']'; '~'] in
let get_comm fstream =
fstream#skip_ws_nl;
let cmd = fstream#read_excl skip1 in
let param = get_param [] fstream in
Command (cmd, param)
and get_word fstream =
fstream#skip_ws_nl;
let cmd = fstream#read_excl skip1 in
let cmd =
if cmd = "" then fstream#read_incl noskip
else cmd
in
Text [Word cmd]
and get_comment fstream =
fstream#skip_ws_nl;
let comment = fstream#read_excl ['\n';'\013';'\010'] in
Comment comment
in
let rec split_on_commands acc fstream =
if is_end_of_file fstream then
let data = List.rev acc in
let () = if debug then List.iter print_parsed data in
data
else if is_blank fstream then
split_on_commands (Blank :: acc) fstream
else if is_close_command fstream then
List.rev acc
else if is_newline fstream then
split_on_commands ((Text [Word brstr]) :: acc) fstream
else if is_comment fstream then
split_on_commands ((get_comment fstream) :: acc) fstream
else if is_escape fstream then
split_on_commands acc fstream
else if is_escape_underscore fstream then
split_on_commands ((Word "_")::acc) fstream
else if is_command fstream then
split_on_commands ((get_comm fstream) :: acc) fstream
else if is_enclosed fstream then
split_on_commands ((Text (the_parser mode fstream)) :: acc) fstream
else if is_word fstream then
split_on_commands ((get_word fstream) :: acc) fstream
else failwith "Huh?";
in
let res = split_on_commands [] fstream in
collapse2 (List.map collapse res)
let process parsed mode channel =
let generator = match mode with
| `OnlineHelp -> produce_latex channel
| `Troff -> produce_troff channel
in
List.iter generator parsed
let process_file parsed mode output_file =
let channel = open_out output_file in
let o str = output_string channel str in
match mode with
| `Troff ->
o (".TH POY 1 LOCAL\n\n");
o (".SH NAME\npoy \\- A phylogenetic analysis program using dynamic \
homologies\n.SH SYNOPSIS\n.B poy [options] filename.\n\n\
.SH DESCRIPTION\npoy is a phylogenetic analysis program for morphological \
and molecular characters with support for dynamic homology characters: \
that is, supports the analysis of unaligned sequences.\n\n.SH OPTIONS\n\n\
.TP 5\n\
-w\n\
Run poy in the specified working directory. \n\
.TP\n\
-e\n\
Exit upon error. \n\n\
.TP\n\
-d\n\
Dump filename in case of error. \n\
.TP\n\
-q \n\
Don't wait for input other than the program argument script. \n\
.TP\n\
-no-output-xml \n\
Do not generate the output.xml file. \n\
.TP\n\
-help\n\
Display this list of options. \n\
.TP\n\
--help\n\
Display this list of options. \n\
\n.SH VERSION\n 4.0." ^ (Str.global_replace (Str.regexp " ") "" BuildNumber.build) ^ "\n\
.SH COMMANDS\n.P\n\
For complete documentation go to \
-research/computational-sciences/research/projects/systematic-biology/poy.\n\
The following are the valid commands for \n\
.B poy.");
process parsed mode channel;
o "\n.SH AUTHOR\nPOY was written by Andres Varon, Lin Hong, \
NIcholas Lucaroni, and Ward Wheeler.\n.PP\nThis manual page was written \
by Andres Varon, Lin Hong, Nicholas Lucaroni, Ward Wheeler\
Ilya Temkin, Megan Cevasco, Kurt M. Pickett, Julian Faivovich, \
Taran Grant, and William Leo Smith.\n.RS\n\n"
| `OnlineHelp ->
o (".\nauthors\n@[<v 2> POY was written by Andres Varon, Lin Hong, \
Nicholas Lucaroni, and Ward Wheeler.This manual page was written \
by Andres Varon, Lin Hong, Nicholas Lucaroni, Ward Wheeler\
Ilya Temkin, Megan Cevasco, Kurt M. Pickett, Julian Faivovich, \
Taran Grant, and William Leo Smith.@]\n\n");
o (".\ncopyright\n@[<v 2>"^ Version.copyright_authors ^ Version.warrenty_information ^"@]\n\n");
o (".\nversion\n@[<v 2> "^ Version.copyright_authors ^ Version.compile_information ^ "@]\n\n");
process parsed mode channel;
()
let () =
let ch = FileStream.Pervasives.open_in (`Local "../doc/allcommands.tex") in
let parsed = the_parser `Troff ch in
let () = process_file parsed `OnlineHelp "help.txt" in
let () = process_file parsed `Troff "poy.1" in
()
|
bf57f131388dcca7ad0f639b89bdf9f046684d35a1925b102765b5c361d038b5 | pirapira/coq2rust | feedback.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Xml_datatype
open Serialize
type message_level =
| Debug of string
| Info
| Notice
| Warning
| Error
type message = {
message_level : message_level;
message_content : string;
}
let of_message_level = function
| Debug s ->
Serialize.constructor "message_level" "debug" [Xml_datatype.PCData s]
| Info -> Serialize.constructor "message_level" "info" []
| Notice -> Serialize.constructor "message_level" "notice" []
| Warning -> Serialize.constructor "message_level" "warning" []
| Error -> Serialize.constructor "message_level" "error" []
let to_message_level =
Serialize.do_match "message_level" (fun s args -> match s with
| "debug" -> Debug (Serialize.raw_string args)
| "info" -> Info
| "notice" -> Notice
| "warning" -> Warning
| "error" -> Error
| _ -> raise Serialize.Marshal_error)
let of_message msg =
let lvl = of_message_level msg.message_level in
let content = Serialize.of_string msg.message_content in
Xml_datatype.Element ("message", [], [lvl; content])
let to_message xml = match xml with
| Xml_datatype.Element ("message", [], [lvl; content]) -> {
message_level = to_message_level lvl;
message_content = Serialize.to_string content }
| _ -> raise Serialize.Marshal_error
let is_message = function
| Xml_datatype.Element ("message", _, _) -> true
| _ -> false
type edit_id = int
type state_id = Stateid.t
type edit_or_state_id = Edit of edit_id | State of state_id
type route_id = int
type feedback_content =
| Processed
| Incomplete
| Complete
| ErrorMsg of Loc.t * string
| ProcessingIn of string
| InProgress of int
| WorkerStatus of string * string
| Goals of Loc.t * string
| AddedAxiom
| GlobRef of Loc.t * string * string * string * string
| GlobDef of Loc.t * string * string * string
| FileDependency of string option * string
| FileLoaded of string * string
| Custom of Loc.t * string * xml
| Message of message
type feedback = {
id : edit_or_state_id;
contents : feedback_content;
route : route_id;
}
let to_feedback_content = do_match "feedback_content" (fun s a -> match s,a with
| "addedaxiom", _ -> AddedAxiom
| "processed", _ -> Processed
| "processingin", [where] -> ProcessingIn (to_string where)
| "incomplete", _ -> Incomplete
| "complete", _ -> Complete
| "globref", [loc; filepath; modpath; ident; ty] ->
GlobRef(to_loc loc, to_string filepath,
to_string modpath, to_string ident, to_string ty)
| "globdef", [loc; ident; secpath; ty] ->
GlobDef(to_loc loc, to_string ident, to_string secpath, to_string ty)
| "errormsg", [loc; s] -> ErrorMsg (to_loc loc, to_string s)
| "inprogress", [n] -> InProgress (to_int n)
| "workerstatus", [ns] ->
let n, s = to_pair to_string to_string ns in
WorkerStatus(n,s)
| "goals", [loc;s] -> Goals (to_loc loc, to_string s)
| "custom", [loc;name;x]-> Custom (to_loc loc, to_string name, x)
| "filedependency", [from; dep] ->
FileDependency (to_option to_string from, to_string dep)
| "fileloaded", [dirpath; filename] ->
FileLoaded (to_string dirpath, to_string filename)
| "message", [m] -> Message (to_message m)
| _ -> raise Marshal_error)
let of_feedback_content = function
| AddedAxiom -> constructor "feedback_content" "addedaxiom" []
| Processed -> constructor "feedback_content" "processed" []
| ProcessingIn where ->
constructor "feedback_content" "processingin" [of_string where]
| Incomplete -> constructor "feedback_content" "incomplete" []
| Complete -> constructor "feedback_content" "complete" []
| GlobRef(loc, filepath, modpath, ident, ty) ->
constructor "feedback_content" "globref" [
of_loc loc;
of_string filepath;
of_string modpath;
of_string ident;
of_string ty ]
| GlobDef(loc, ident, secpath, ty) ->
constructor "feedback_content" "globdef" [
of_loc loc;
of_string ident;
of_string secpath;
of_string ty ]
| ErrorMsg(loc, s) ->
constructor "feedback_content" "errormsg" [of_loc loc; of_string s]
| InProgress n -> constructor "feedback_content" "inprogress" [of_int n]
| WorkerStatus(n,s) ->
constructor "feedback_content" "workerstatus"
[of_pair of_string of_string (n,s)]
| Goals (loc,s) ->
constructor "feedback_content" "goals" [of_loc loc;of_string s]
| Custom (loc, name, x) ->
constructor "feedback_content" "custom" [of_loc loc; of_string name; x]
| FileDependency (from, depends_on) ->
constructor "feedback_content" "filedependency" [
of_option of_string from;
of_string depends_on]
| FileLoaded (dirpath, filename) ->
constructor "feedback_content" "fileloaded" [
of_string dirpath;
of_string filename ]
| Message m -> constructor "feedback_content" "message" [ of_message m ]
let of_edit_or_state_id = function
| Edit id -> ["object","edit"], of_edit_id id
| State id -> ["object","state"], Stateid.to_xml id
let of_feedback msg =
let content = of_feedback_content msg.contents in
let obj, id = of_edit_or_state_id msg.id in
let route = string_of_int msg.route in
Element ("feedback", obj @ ["route",route], [id;content])
let to_feedback xml = match xml with
| Element ("feedback", ["object","edit";"route",route], [id;content]) -> {
id = Edit(to_edit_id id);
route = int_of_string route;
contents = to_feedback_content content }
| Element ("feedback", ["object","state";"route",route], [id;content]) -> {
id = State(Stateid.of_xml id);
route = int_of_string route;
contents = to_feedback_content content }
| _ -> raise Marshal_error
let is_feedback = function
| Element ("feedback", _, _) -> true
| _ -> false
let default_route = 0
| null | https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/lib/feedback.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
********************************************************************** | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Xml_datatype
open Serialize
type message_level =
| Debug of string
| Info
| Notice
| Warning
| Error
type message = {
message_level : message_level;
message_content : string;
}
let of_message_level = function
| Debug s ->
Serialize.constructor "message_level" "debug" [Xml_datatype.PCData s]
| Info -> Serialize.constructor "message_level" "info" []
| Notice -> Serialize.constructor "message_level" "notice" []
| Warning -> Serialize.constructor "message_level" "warning" []
| Error -> Serialize.constructor "message_level" "error" []
let to_message_level =
Serialize.do_match "message_level" (fun s args -> match s with
| "debug" -> Debug (Serialize.raw_string args)
| "info" -> Info
| "notice" -> Notice
| "warning" -> Warning
| "error" -> Error
| _ -> raise Serialize.Marshal_error)
let of_message msg =
let lvl = of_message_level msg.message_level in
let content = Serialize.of_string msg.message_content in
Xml_datatype.Element ("message", [], [lvl; content])
let to_message xml = match xml with
| Xml_datatype.Element ("message", [], [lvl; content]) -> {
message_level = to_message_level lvl;
message_content = Serialize.to_string content }
| _ -> raise Serialize.Marshal_error
let is_message = function
| Xml_datatype.Element ("message", _, _) -> true
| _ -> false
type edit_id = int
type state_id = Stateid.t
type edit_or_state_id = Edit of edit_id | State of state_id
type route_id = int
type feedback_content =
| Processed
| Incomplete
| Complete
| ErrorMsg of Loc.t * string
| ProcessingIn of string
| InProgress of int
| WorkerStatus of string * string
| Goals of Loc.t * string
| AddedAxiom
| GlobRef of Loc.t * string * string * string * string
| GlobDef of Loc.t * string * string * string
| FileDependency of string option * string
| FileLoaded of string * string
| Custom of Loc.t * string * xml
| Message of message
type feedback = {
id : edit_or_state_id;
contents : feedback_content;
route : route_id;
}
let to_feedback_content = do_match "feedback_content" (fun s a -> match s,a with
| "addedaxiom", _ -> AddedAxiom
| "processed", _ -> Processed
| "processingin", [where] -> ProcessingIn (to_string where)
| "incomplete", _ -> Incomplete
| "complete", _ -> Complete
| "globref", [loc; filepath; modpath; ident; ty] ->
GlobRef(to_loc loc, to_string filepath,
to_string modpath, to_string ident, to_string ty)
| "globdef", [loc; ident; secpath; ty] ->
GlobDef(to_loc loc, to_string ident, to_string secpath, to_string ty)
| "errormsg", [loc; s] -> ErrorMsg (to_loc loc, to_string s)
| "inprogress", [n] -> InProgress (to_int n)
| "workerstatus", [ns] ->
let n, s = to_pair to_string to_string ns in
WorkerStatus(n,s)
| "goals", [loc;s] -> Goals (to_loc loc, to_string s)
| "custom", [loc;name;x]-> Custom (to_loc loc, to_string name, x)
| "filedependency", [from; dep] ->
FileDependency (to_option to_string from, to_string dep)
| "fileloaded", [dirpath; filename] ->
FileLoaded (to_string dirpath, to_string filename)
| "message", [m] -> Message (to_message m)
| _ -> raise Marshal_error)
let of_feedback_content = function
| AddedAxiom -> constructor "feedback_content" "addedaxiom" []
| Processed -> constructor "feedback_content" "processed" []
| ProcessingIn where ->
constructor "feedback_content" "processingin" [of_string where]
| Incomplete -> constructor "feedback_content" "incomplete" []
| Complete -> constructor "feedback_content" "complete" []
| GlobRef(loc, filepath, modpath, ident, ty) ->
constructor "feedback_content" "globref" [
of_loc loc;
of_string filepath;
of_string modpath;
of_string ident;
of_string ty ]
| GlobDef(loc, ident, secpath, ty) ->
constructor "feedback_content" "globdef" [
of_loc loc;
of_string ident;
of_string secpath;
of_string ty ]
| ErrorMsg(loc, s) ->
constructor "feedback_content" "errormsg" [of_loc loc; of_string s]
| InProgress n -> constructor "feedback_content" "inprogress" [of_int n]
| WorkerStatus(n,s) ->
constructor "feedback_content" "workerstatus"
[of_pair of_string of_string (n,s)]
| Goals (loc,s) ->
constructor "feedback_content" "goals" [of_loc loc;of_string s]
| Custom (loc, name, x) ->
constructor "feedback_content" "custom" [of_loc loc; of_string name; x]
| FileDependency (from, depends_on) ->
constructor "feedback_content" "filedependency" [
of_option of_string from;
of_string depends_on]
| FileLoaded (dirpath, filename) ->
constructor "feedback_content" "fileloaded" [
of_string dirpath;
of_string filename ]
| Message m -> constructor "feedback_content" "message" [ of_message m ]
let of_edit_or_state_id = function
| Edit id -> ["object","edit"], of_edit_id id
| State id -> ["object","state"], Stateid.to_xml id
let of_feedback msg =
let content = of_feedback_content msg.contents in
let obj, id = of_edit_or_state_id msg.id in
let route = string_of_int msg.route in
Element ("feedback", obj @ ["route",route], [id;content])
let to_feedback xml = match xml with
| Element ("feedback", ["object","edit";"route",route], [id;content]) -> {
id = Edit(to_edit_id id);
route = int_of_string route;
contents = to_feedback_content content }
| Element ("feedback", ["object","state";"route",route], [id;content]) -> {
id = State(Stateid.of_xml id);
route = int_of_string route;
contents = to_feedback_content content }
| _ -> raise Marshal_error
let is_feedback = function
| Element ("feedback", _, _) -> true
| _ -> false
let default_route = 0
|
b830486e4f44e239279793e31b38fd5201e1d05c971f76bb31f4023a69eaa9e0 | bob-cd/bob | externals.clj | ; Copyright 2018- Rahul De
;
Use of this source code is governed by an MIT - style
; license that can be found in the LICENSE file or at
; .
(ns apiserver.entities.externals
(:require
[clojure.tools.logging :as log]
[xtdb.api :as xt]))
(defn create
"Register with an unique name and an url supplied in a map."
[db kind {:keys [name url]}]
(let [id (keyword (format "bob.%s/%s" kind name))]
(log/infof "Creating %s at %s with id %s" kind url id)
(xt/await-tx
db
(xt/submit-tx db
[[::xt/put
{:xt/id id
:type (keyword kind)
:url url
:name name}]]))))
(defn delete
"Unregisters by its name supplied in a map."
[db kind id]
(log/infof "Deleting %s %s" kind id)
(xt/await-tx
db
(xt/submit-tx db [[::xt/delete (keyword (format "bob.%s/%s" kind id))]])))
| null | https://raw.githubusercontent.com/bob-cd/bob/2c1a50e305a7086d2398419525288d87389fe1b2/apiserver/src/apiserver/entities/externals.clj | clojure | Copyright 2018- Rahul De
license that can be found in the LICENSE file or at
. | Use of this source code is governed by an MIT - style
(ns apiserver.entities.externals
(:require
[clojure.tools.logging :as log]
[xtdb.api :as xt]))
(defn create
"Register with an unique name and an url supplied in a map."
[db kind {:keys [name url]}]
(let [id (keyword (format "bob.%s/%s" kind name))]
(log/infof "Creating %s at %s with id %s" kind url id)
(xt/await-tx
db
(xt/submit-tx db
[[::xt/put
{:xt/id id
:type (keyword kind)
:url url
:name name}]]))))
(defn delete
"Unregisters by its name supplied in a map."
[db kind id]
(log/infof "Deleting %s %s" kind id)
(xt/await-tx
db
(xt/submit-tx db [[::xt/delete (keyword (format "bob.%s/%s" kind id))]])))
|
61a2d307e079710c65d5972e9ea65d42f1cc98d9ea42079338450b52b1d609e2 | swamp-agr/blaze-textual | Int.hs | # LANGUAGE BangPatterns , CPP , MagicHash , OverloadedStrings , UnboxedTuples #
Module : Blaze . Text . Int
Copyright : ( c ) 2011 MailRank , Inc.
License : BSD3
Maintainer : < >
-- Stability: experimental
-- Portability: portable
--
-- Efficiently serialize an integral value as a lazy 'L.ByteString'.
module Blaze.Text.Int
(
digit
, integral
, minus
) where
import Blaze.ByteString.Builder
import Blaze.ByteString.Builder.Char8
import Data.ByteString.Char8 ()
import Data.Int (Int8, Int16, Int32, Int64)
import Data.Monoid (mappend, mempty)
import Data.Word (Word, Word8, Word16, Word32, Word64)
import GHC.Base (quotInt, remInt)
#if MIN_VERSION_base(4,15,0)
#else
import GHC.Num (quotRemInteger)
#endif
import GHC.Types (Int(..))
#if defined(INTEGER_GMP)
import GHC.Integer.GMP.Internals
#elif defined(INTEGER_SIMPLE)
import GHC.Integer.Simple.Internals
#endif
#define PAIR(a,b) (# a,b #)
integral :: (Integral a, Show a) => a -> Builder
{-# RULES "integral/Int" integral = bounded :: Int -> Builder #-}
{-# RULES "integral/Int8" integral = bounded :: Int8 -> Builder #-}
{-# RULES "integral/Int16" integral = bounded :: Int16 -> Builder #-}
# RULES " integral / Int32 " integral = bounded : : Int32 - > Builder #
# RULES " integral / Int64 " integral = bounded : : Int64 - > Builder #
{-# RULES "integral/Word" integral = nonNegative :: Word -> Builder #-}
{-# RULES "integral/Word8" integral = nonNegative :: Word8 -> Builder #-}
# RULES " integral / Word16 " integral = nonNegative : : Word16 - > Builder #
# RULES " integral / Word32 " integral = nonNegative : : Word32 - > Builder #
{-# RULES "integral/Word64" integral = nonNegative :: Word64 -> Builder #-}
{-# RULES "integral/Integer" integral = integer :: Integer -> Builder #-}
-- This definition of the function is here PURELY to be used by ghci
and those rare cases where GHC is being invoked without
-- optimization, as otherwise the rewrite rules above should fire. The
test for ` ( -i ) = = i ` catches when we render , in which case
-- using `-i` would be wrong. An example is `-(-128 :: Int8) == -128`.
integral i
| i >= 0 = nonNegative i
| (-i) == i = fromString (show i)
| otherwise = b
where b = minus `mappend` nonNegative (-i)
# NOINLINE integral #
bounded :: (Bounded a, Integral a) => a -> Builder
{-# SPECIALIZE bounded :: Int -> Builder #-}
{-# SPECIALIZE bounded :: Int8 -> Builder #-}
{-# SPECIALIZE bounded :: Int16 -> Builder #-}
{-# SPECIALIZE bounded :: Int32 -> Builder #-}
{-# SPECIALIZE bounded :: Int64 -> Builder #-}
bounded i
| i >= 0 = nonNegative i
| i > minBound = minus `mappend` nonNegative (-i)
| otherwise = minus `mappend`
nonNegative (negate (k `quot` 10)) `mappend`
digit (negate (k `rem` 10))
where k = minBound `asTypeOf` i
nonNegative :: Integral a => a -> Builder
{-# SPECIALIZE nonNegative :: Int -> Builder #-}
{-# SPECIALIZE nonNegative :: Int8 -> Builder #-}
{-# SPECIALIZE nonNegative :: Int16 -> Builder #-}
{-# SPECIALIZE nonNegative :: Int32 -> Builder #-}
{-# SPECIALIZE nonNegative :: Int64 -> Builder #-}
{-# SPECIALIZE nonNegative :: Word -> Builder #-}
{-# SPECIALIZE nonNegative :: Word8 -> Builder #-}
# SPECIALIZE nonNegative : : Word16 - > Builder #
# SPECIALIZE nonNegative : : Word32 - > Builder #
{-# SPECIALIZE nonNegative :: Word64 -> Builder #-}
nonNegative x
| x < 0 = error $ "nonNegative: Called with negative number " ++ show (fromIntegral x :: Integer)
| otherwise = go x
where
go n | n < 10 = digit n
| otherwise = go (n `quot` 10) `mappend` digit (n `rem` 10)
digit :: Integral a => a -> Builder
digit n = fromWord8 $! fromIntegral n + 48
# INLINE digit #
minus :: Builder
minus = fromWord8 45
int :: Int -> Builder
int = integral
# INLINE int #
integer :: Integer -> Builder
#if defined(INTEGER_GMP)
integer (S# i#) = int (I# i#)
#endif
integer i
| i < 0 = minus `mappend` go (-i)
| otherwise = go i
where
go n | n < maxInt = int (fromInteger n)
| otherwise = putH (splitf (maxInt * maxInt) n)
splitf p n
| p > n = [n]
| otherwise = splith p (splitf (p*p) n)
splith p (n:ns) = case n `quotRemInteger` p of
PAIR(q,r) | q > 0 -> q : r : splitb p ns
| otherwise -> r : splitb p ns
splith _ _ = error "splith: the impossible happened."
splitb p (n:ns) = case n `quotRemInteger` p of
PAIR(q,r) -> q : r : splitb p ns
splitb _ _ = []
data T = T !Integer !Int
fstT :: T -> Integer
fstT (T a _) = a
maxInt :: Integer
maxDigits :: Int
T maxInt maxDigits =
until ((>mi) . (*10) . fstT) (\(T n d) -> T (n*10) (d+1)) (T 10 1)
where mi = fromIntegral (maxBound :: Int)
putH :: [Integer] -> Builder
putH (n:ns) = case n `quotRemInteger` maxInt of
PAIR(x,y)
| q > 0 -> int q `mappend` pblock r `mappend` putB ns
| otherwise -> int r `mappend` putB ns
where q = fromInteger x
r = fromInteger y
putH _ = error "putH: the impossible happened"
putB :: [Integer] -> Builder
putB (n:ns) = case n `quotRemInteger` maxInt of
PAIR(x,y) -> pblock q `mappend` pblock r `mappend` putB ns
where q = fromInteger x
r = fromInteger y
putB _ = mempty
pblock :: Int -> Builder
pblock = go maxDigits
where
go !d !n
| d == 1 = digit n
| otherwise = go (d-1) q `mappend` digit r
where q = n `quotInt` 10
r = n `remInt` 10
| null | https://raw.githubusercontent.com/swamp-agr/blaze-textual/ebe28bc40a19074fe32768f07a3bfd95ca20a673/Blaze/Text/Int.hs | haskell | Stability: experimental
Portability: portable
Efficiently serialize an integral value as a lazy 'L.ByteString'.
# RULES "integral/Int" integral = bounded :: Int -> Builder #
# RULES "integral/Int8" integral = bounded :: Int8 -> Builder #
# RULES "integral/Int16" integral = bounded :: Int16 -> Builder #
# RULES "integral/Word" integral = nonNegative :: Word -> Builder #
# RULES "integral/Word8" integral = nonNegative :: Word8 -> Builder #
# RULES "integral/Word64" integral = nonNegative :: Word64 -> Builder #
# RULES "integral/Integer" integral = integer :: Integer -> Builder #
This definition of the function is here PURELY to be used by ghci
optimization, as otherwise the rewrite rules above should fire. The
using `-i` would be wrong. An example is `-(-128 :: Int8) == -128`.
# SPECIALIZE bounded :: Int -> Builder #
# SPECIALIZE bounded :: Int8 -> Builder #
# SPECIALIZE bounded :: Int16 -> Builder #
# SPECIALIZE bounded :: Int32 -> Builder #
# SPECIALIZE bounded :: Int64 -> Builder #
# SPECIALIZE nonNegative :: Int -> Builder #
# SPECIALIZE nonNegative :: Int8 -> Builder #
# SPECIALIZE nonNegative :: Int16 -> Builder #
# SPECIALIZE nonNegative :: Int32 -> Builder #
# SPECIALIZE nonNegative :: Int64 -> Builder #
# SPECIALIZE nonNegative :: Word -> Builder #
# SPECIALIZE nonNegative :: Word8 -> Builder #
# SPECIALIZE nonNegative :: Word64 -> Builder # | # LANGUAGE BangPatterns , CPP , MagicHash , OverloadedStrings , UnboxedTuples #
Module : Blaze . Text . Int
Copyright : ( c ) 2011 MailRank , Inc.
License : BSD3
Maintainer : < >
module Blaze.Text.Int
(
digit
, integral
, minus
) where
import Blaze.ByteString.Builder
import Blaze.ByteString.Builder.Char8
import Data.ByteString.Char8 ()
import Data.Int (Int8, Int16, Int32, Int64)
import Data.Monoid (mappend, mempty)
import Data.Word (Word, Word8, Word16, Word32, Word64)
import GHC.Base (quotInt, remInt)
#if MIN_VERSION_base(4,15,0)
#else
import GHC.Num (quotRemInteger)
#endif
import GHC.Types (Int(..))
#if defined(INTEGER_GMP)
import GHC.Integer.GMP.Internals
#elif defined(INTEGER_SIMPLE)
import GHC.Integer.Simple.Internals
#endif
#define PAIR(a,b) (# a,b #)
integral :: (Integral a, Show a) => a -> Builder
# RULES " integral / Int32 " integral = bounded : : Int32 - > Builder #
# RULES " integral / Int64 " integral = bounded : : Int64 - > Builder #
# RULES " integral / Word16 " integral = nonNegative : : Word16 - > Builder #
# RULES " integral / Word32 " integral = nonNegative : : Word32 - > Builder #
and those rare cases where GHC is being invoked without
test for ` ( -i ) = = i ` catches when we render , in which case
integral i
| i >= 0 = nonNegative i
| (-i) == i = fromString (show i)
| otherwise = b
where b = minus `mappend` nonNegative (-i)
# NOINLINE integral #
bounded :: (Bounded a, Integral a) => a -> Builder
bounded i
| i >= 0 = nonNegative i
| i > minBound = minus `mappend` nonNegative (-i)
| otherwise = minus `mappend`
nonNegative (negate (k `quot` 10)) `mappend`
digit (negate (k `rem` 10))
where k = minBound `asTypeOf` i
nonNegative :: Integral a => a -> Builder
# SPECIALIZE nonNegative : : Word16 - > Builder #
# SPECIALIZE nonNegative : : Word32 - > Builder #
nonNegative x
| x < 0 = error $ "nonNegative: Called with negative number " ++ show (fromIntegral x :: Integer)
| otherwise = go x
where
go n | n < 10 = digit n
| otherwise = go (n `quot` 10) `mappend` digit (n `rem` 10)
digit :: Integral a => a -> Builder
digit n = fromWord8 $! fromIntegral n + 48
# INLINE digit #
minus :: Builder
minus = fromWord8 45
int :: Int -> Builder
int = integral
# INLINE int #
integer :: Integer -> Builder
#if defined(INTEGER_GMP)
integer (S# i#) = int (I# i#)
#endif
integer i
| i < 0 = minus `mappend` go (-i)
| otherwise = go i
where
go n | n < maxInt = int (fromInteger n)
| otherwise = putH (splitf (maxInt * maxInt) n)
splitf p n
| p > n = [n]
| otherwise = splith p (splitf (p*p) n)
splith p (n:ns) = case n `quotRemInteger` p of
PAIR(q,r) | q > 0 -> q : r : splitb p ns
| otherwise -> r : splitb p ns
splith _ _ = error "splith: the impossible happened."
splitb p (n:ns) = case n `quotRemInteger` p of
PAIR(q,r) -> q : r : splitb p ns
splitb _ _ = []
data T = T !Integer !Int
fstT :: T -> Integer
fstT (T a _) = a
maxInt :: Integer
maxDigits :: Int
T maxInt maxDigits =
until ((>mi) . (*10) . fstT) (\(T n d) -> T (n*10) (d+1)) (T 10 1)
where mi = fromIntegral (maxBound :: Int)
putH :: [Integer] -> Builder
putH (n:ns) = case n `quotRemInteger` maxInt of
PAIR(x,y)
| q > 0 -> int q `mappend` pblock r `mappend` putB ns
| otherwise -> int r `mappend` putB ns
where q = fromInteger x
r = fromInteger y
putH _ = error "putH: the impossible happened"
putB :: [Integer] -> Builder
putB (n:ns) = case n `quotRemInteger` maxInt of
PAIR(x,y) -> pblock q `mappend` pblock r `mappend` putB ns
where q = fromInteger x
r = fromInteger y
putB _ = mempty
pblock :: Int -> Builder
pblock = go maxDigits
where
go !d !n
| d == 1 = digit n
| otherwise = go (d-1) q `mappend` digit r
where q = n `quotInt` 10
r = n `remInt` 10
|
09473fbe3e69bde931cda02aa7ab4c6e1446045cf4b16f1fdac518b08eba91c0 | BinaryAnalysisPlatform/bap | bap_primus_observation.ml | open Core_kernel[@@warning "-D"]
open Bap.Std
open Bap_knowledge
open Bap_future.Std
open Monads.Std
module Name = Knowledge.Name
module Info = Bap_primus_info
type 'a observation = 'a Univ_map.Key.t
type 'a statement = 'a observation
type 'a t = 'a observation
type ('m,'a) observers = {
last : int;
subs : (int * ('a -> 'm)) list
}
type provider = {
info : Info.t;
newdata : Sexp.t signal;
data : Sexp.t stream;
newtrigger : unit signal;
triggers : unit stream;
observers : int;
key : Sexp.t Univ_map.Key.t;
}
type 'a mstream = {
providers : provider list;
}
let providers : (string,provider) Hashtbl.t = Hashtbl.create (module String)
let provider ?desc ?(package="primus") name =
let data,newdata = Stream.create () in
let triggers,newtrigger = Stream.create () in
let name = Name.create ~package name in
let info = Info.create ?desc name in
let key = Univ_map.Key.create ~name:(Name.show name) Fn.id in
{info; newdata; data; triggers; newtrigger; observers=0; key}
let update_provider provider ~f =
Hashtbl.update providers provider ~f:(function
| None -> failwithf "bug: unregistered provider: %s" provider ()
| Some p -> f p)
let register_observer =
update_provider ~f:(fun p -> {p with observers = p.observers + 1})
let provide ?desc ?(inspect=sexp_of_opaque) ?package name =
let provider = provider ?desc ?package name in
let name = Name.show @@ Info.name provider.info in
if Hashtbl.mem providers name then
failwithf "Observation name `%s' is already used by another \
component. Please, choose a different name" name ();
Hashtbl.add_exn providers ~key:name ~data:provider;
let k = Univ_map.Key.create ~name inspect in
k,k
let inspect = Univ_map.Key.to_sexp
let name = Univ_map.Key.name
let of_statement = Fn.id
module Key = struct
type 'a t = 'a Type_equal.Id.t [@@deriving sexp_of]
let to_type_id = Fn.id
let type_id = Fn.id
end
module Map = Univ_map.Make1(Key)(struct
type ('a,'m) t = ('a,'m) observers
let sexp_of_t _ _ = sexp_of_opaque
end)
type 'e observations = 'e Map.t
type subscription = Subs : _ observation * int -> subscription
let add_observer observers key obs =
register_observer (name key);
match Map.find observers key with
| None ->
Map.add_exn observers key {last=1; subs=[1,obs]},
Subs (key,1)
| Some {last; subs} ->
Map.set observers key {
last = last + 1;
subs = (last + 1, obs) :: subs
},
Subs (key,last+1)
let cancel (Subs (key,id)) observers =
Map.change observers key ~f:(function
| None -> None
| Some obs ->
match List.rev_filter obs.subs ~f:(fun (id',_) -> id <> id') with
| [] -> None
| subs -> Some {obs with subs})
let add_watcher observers {key} obs =
add_observer observers key obs
let callbacks os key =
match Map.find_exn os key with
| exception _ -> []
| {subs} -> subs
module Make(Machine : Monad.S) = struct
open Machine.Syntax
let apply inj x = function
| [] -> Machine.return ()
| xs ->
let data = inj x in
Machine.List.iter xs ~f:(fun (_,ob) -> ob data)
let push_data p key os ws x =
let sexp = lazy (inspect key x) in
if Stream.has_subscribers p.data
then Signal.send p.newdata (Lazy.force sexp);
apply Fn.id x os >>= fun () ->
apply Lazy.force sexp ws
let notify os key x =
let p = Hashtbl.find_exn providers (name key) in
let os = callbacks os key and ws = callbacks os p.key in
Signal.send p.newtrigger ();
push_data p key os ws x
[@@inline]
let notify_if_observed os key k =
let p = Hashtbl.find_exn providers (name key) in
Signal.send p.newtrigger ();
match callbacks os key, callbacks os p.key with
| [], [] ->
if Stream.has_subscribers p.data
then k @@ fun x ->
Signal.send p.newdata (inspect key x);
Machine.return ()
else Machine.return ()
| os, ws -> k @@ fun x ->
push_data p key os ws x
[@@inline]
end
let empty = Map.empty
let list_providers () = Hashtbl.data providers
let list () = list_providers () |>
List.map ~f:(fun {info} -> info)
module Provider = struct
type t = provider
let name t =
let name = Info.name t.info in
let short = Name.unqualified name in
match Name.package name with
| "primus" -> short
| package -> sprintf "%s:%s" package short
let fullname t = Info.name t.info
let data t = t.data
let triggers t = t.triggers
let observers t = t.observers
end
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/253afc171bbfd0fe1b34f6442795dbf4b1798348/lib/bap_primus/bap_primus_observation.ml | ocaml | open Core_kernel[@@warning "-D"]
open Bap.Std
open Bap_knowledge
open Bap_future.Std
open Monads.Std
module Name = Knowledge.Name
module Info = Bap_primus_info
type 'a observation = 'a Univ_map.Key.t
type 'a statement = 'a observation
type 'a t = 'a observation
type ('m,'a) observers = {
last : int;
subs : (int * ('a -> 'm)) list
}
type provider = {
info : Info.t;
newdata : Sexp.t signal;
data : Sexp.t stream;
newtrigger : unit signal;
triggers : unit stream;
observers : int;
key : Sexp.t Univ_map.Key.t;
}
type 'a mstream = {
providers : provider list;
}
let providers : (string,provider) Hashtbl.t = Hashtbl.create (module String)
let provider ?desc ?(package="primus") name =
let data,newdata = Stream.create () in
let triggers,newtrigger = Stream.create () in
let name = Name.create ~package name in
let info = Info.create ?desc name in
let key = Univ_map.Key.create ~name:(Name.show name) Fn.id in
{info; newdata; data; triggers; newtrigger; observers=0; key}
let update_provider provider ~f =
Hashtbl.update providers provider ~f:(function
| None -> failwithf "bug: unregistered provider: %s" provider ()
| Some p -> f p)
let register_observer =
update_provider ~f:(fun p -> {p with observers = p.observers + 1})
let provide ?desc ?(inspect=sexp_of_opaque) ?package name =
let provider = provider ?desc ?package name in
let name = Name.show @@ Info.name provider.info in
if Hashtbl.mem providers name then
failwithf "Observation name `%s' is already used by another \
component. Please, choose a different name" name ();
Hashtbl.add_exn providers ~key:name ~data:provider;
let k = Univ_map.Key.create ~name inspect in
k,k
let inspect = Univ_map.Key.to_sexp
let name = Univ_map.Key.name
let of_statement = Fn.id
module Key = struct
type 'a t = 'a Type_equal.Id.t [@@deriving sexp_of]
let to_type_id = Fn.id
let type_id = Fn.id
end
module Map = Univ_map.Make1(Key)(struct
type ('a,'m) t = ('a,'m) observers
let sexp_of_t _ _ = sexp_of_opaque
end)
type 'e observations = 'e Map.t
type subscription = Subs : _ observation * int -> subscription
let add_observer observers key obs =
register_observer (name key);
match Map.find observers key with
| None ->
Map.add_exn observers key {last=1; subs=[1,obs]},
Subs (key,1)
| Some {last; subs} ->
Map.set observers key {
last = last + 1;
subs = (last + 1, obs) :: subs
},
Subs (key,last+1)
let cancel (Subs (key,id)) observers =
Map.change observers key ~f:(function
| None -> None
| Some obs ->
match List.rev_filter obs.subs ~f:(fun (id',_) -> id <> id') with
| [] -> None
| subs -> Some {obs with subs})
let add_watcher observers {key} obs =
add_observer observers key obs
let callbacks os key =
match Map.find_exn os key with
| exception _ -> []
| {subs} -> subs
module Make(Machine : Monad.S) = struct
open Machine.Syntax
let apply inj x = function
| [] -> Machine.return ()
| xs ->
let data = inj x in
Machine.List.iter xs ~f:(fun (_,ob) -> ob data)
let push_data p key os ws x =
let sexp = lazy (inspect key x) in
if Stream.has_subscribers p.data
then Signal.send p.newdata (Lazy.force sexp);
apply Fn.id x os >>= fun () ->
apply Lazy.force sexp ws
let notify os key x =
let p = Hashtbl.find_exn providers (name key) in
let os = callbacks os key and ws = callbacks os p.key in
Signal.send p.newtrigger ();
push_data p key os ws x
[@@inline]
let notify_if_observed os key k =
let p = Hashtbl.find_exn providers (name key) in
Signal.send p.newtrigger ();
match callbacks os key, callbacks os p.key with
| [], [] ->
if Stream.has_subscribers p.data
then k @@ fun x ->
Signal.send p.newdata (inspect key x);
Machine.return ()
else Machine.return ()
| os, ws -> k @@ fun x ->
push_data p key os ws x
[@@inline]
end
let empty = Map.empty
let list_providers () = Hashtbl.data providers
let list () = list_providers () |>
List.map ~f:(fun {info} -> info)
module Provider = struct
type t = provider
let name t =
let name = Info.name t.info in
let short = Name.unqualified name in
match Name.package name with
| "primus" -> short
| package -> sprintf "%s:%s" package short
let fullname t = Info.name t.info
let data t = t.data
let triggers t = t.triggers
let observers t = t.observers
end
| |
b2506d2d635af5c37d6f2a3a124305620abed4242c7bc80ac3aa637e36a3bde7 | lasp-lang/types | orddict_ext.erl | %%
Copyright ( c ) 2015 - 2016 . All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(orddict_ext).
-author("Vitor Enes Duarte <>").
-export([equal/3,
fetch/3]).
-spec equal(orddict:orddict(), orddict:orddict(), function()) ->
boolean().
equal(Dict1, Dict2, Fun) ->
orddict:size(Dict1) == orddict:size(Dict2) andalso
lists_ext:iterate_until(
fun({Key, Value1}) ->
case orddict:find(Key, Dict2) of
{ok, Value2} ->
Fun(Value1, Value2);
error ->
false
end
end,
Dict1
).
%% @doc
fetch(K, M, Default) ->
case orddict:find(K, M) of
{ok, V} ->
V;
error ->
Default
end.
| null | https://raw.githubusercontent.com/lasp-lang/types/e35b9b3a32b8f580daff1a7d1102813ad530835e/src/orddict_ext.erl | erlang |
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
@doc | Copyright ( c ) 2015 - 2016 . All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(orddict_ext).
-author("Vitor Enes Duarte <>").
-export([equal/3,
fetch/3]).
-spec equal(orddict:orddict(), orddict:orddict(), function()) ->
boolean().
equal(Dict1, Dict2, Fun) ->
orddict:size(Dict1) == orddict:size(Dict2) andalso
lists_ext:iterate_until(
fun({Key, Value1}) ->
case orddict:find(Key, Dict2) of
{ok, Value2} ->
Fun(Value1, Value2);
error ->
false
end
end,
Dict1
).
fetch(K, M, Default) ->
case orddict:find(K, M) of
{ok, V} ->
V;
error ->
Default
end.
|
a0b2ddc17fbad94db797fe9b4db9b75e9268f704d83e611c583d141ed88f1f95 | coq/coq | wg_Command.mli | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
class command_window : string -> Coq.coqtop -> CoqOps.coqops ->
Wg_RoutedMessageViews.message_views_router -> int ->
object
method new_query : ?command:string -> ?term:string -> unit -> unit
method pack_in : (GObj.widget -> unit) -> unit
method show : unit
method hide : unit
method visible : bool
end
| null | https://raw.githubusercontent.com/coq/coq/e0de9db708817cc08efb20d65b9819d8f2b0ea68/ide/coqide/wg_Command.mli | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
********************************************************************** | v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
class command_window : string -> Coq.coqtop -> CoqOps.coqops ->
Wg_RoutedMessageViews.message_views_router -> int ->
object
method new_query : ?command:string -> ?term:string -> unit -> unit
method pack_in : (GObj.widget -> unit) -> unit
method show : unit
method hide : unit
method visible : bool
end
|
f1f9a3c5700ccc7d169ff5ab18538652969f47b40a65179dda509050dfa7511f | privet-kitty/cl-competitive | map-flipping-subseq.lisp | (defpackage :cp/map-flipping-subseq
(:use :cl)
(:export #:map-flipping-subseq))
(in-package :cp/map-flipping-subseq)
(declaim (inline map-flipping-subseq))
(defun map-flipping-subseq (function vector &key (test #'eql))
"Applies FUNCTION to each `flipping' subarray of VECTOR. `Flipping' here means
that all two adjacent elements are different. FUNCTION receives two arguments L
and R which represent the interval [L, R).
CL-USER> (map-flipping-subseq (lambda (x y) (format t \"~&~D ~D\" x y))
#(1 0 1 0 1 1 1 0))
0 5
5 6
6 8
"
(declare (vector vector))
(let ((n (length vector))
(base 0))
(declare ((mod #.array-dimension-limit) base))
(loop for i from 1 below n
when (funcall test (aref vector i) (aref vector (- i 1)))
do (funcall function base i)
(setq base i)
finally (funcall function base n))))
| null | https://raw.githubusercontent.com/privet-kitty/cl-competitive/8b6b73ea3f743fa112587f3af16dfdf9f1845aba/module/map-flipping-subseq.lisp | lisp | (defpackage :cp/map-flipping-subseq
(:use :cl)
(:export #:map-flipping-subseq))
(in-package :cp/map-flipping-subseq)
(declaim (inline map-flipping-subseq))
(defun map-flipping-subseq (function vector &key (test #'eql))
"Applies FUNCTION to each `flipping' subarray of VECTOR. `Flipping' here means
that all two adjacent elements are different. FUNCTION receives two arguments L
and R which represent the interval [L, R).
CL-USER> (map-flipping-subseq (lambda (x y) (format t \"~&~D ~D\" x y))
#(1 0 1 0 1 1 1 0))
0 5
5 6
6 8
"
(declare (vector vector))
(let ((n (length vector))
(base 0))
(declare ((mod #.array-dimension-limit) base))
(loop for i from 1 below n
when (funcall test (aref vector i) (aref vector (- i 1)))
do (funcall function base i)
(setq base i)
finally (funcall function base n))))
| |
f4158d51b8fa4e687e0b94245a79e9c343e7ed2336dd9b7ed756fc665d63575c | google/proto-lens | map_test.hs | -- Copyright 2016 Google Inc. All Rights Reserved.
--
-- Use of this source code is governed by a BSD-style
-- license that can be found in the LICENSE file or at
-- -source/licenses/bsd
# LANGUAGE OverloadedLists #
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Proto.Map
import Proto.Map_Fields
import Data.ProtoLens
import Lens.Family2 ((&), (.~))
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder (Builder, byteString)
import Data.Word (Word64)
import Data.ProtoLens.TestUtil
defFoo :: Foo
defFoo = defMessage
entry :: Word64 -> String -> Builder
entry k v = tagged 1 $ Lengthy $ tagged 1 (VarInt k)
<> taggedValue v
taggedValue :: String -> Builder
taggedValue = tagged 2 . Lengthy . byteString . C.pack
kvPair :: Doc -> Doc -> Doc
kvPair k v = keyed "key" k $+$ keyed "value" v
-- Note how OverloadedLists work here in the "bar" field.
-- For proto-lens, it resolves to a (Map Int32 Text).
main :: IO ()
main = testMain
[ serializeTo "default" defFoo "" mempty
, serializeTo "singleton"
(defFoo & bar .~ [(42, "qwerty")])
(braced "bar" $ kvPair "42" $ doubleQuotes "qwerty")
(entry 42 "qwerty")
, serializeTo "moreElements"
(defFoo & bar .~ [(17, "abc"), (42, "qwerty")])
(braced "bar" (kvPair "17" $ doubleQuotes "abc")
$+$ braced "bar" (kvPair "42" $ doubleQuotes "qwerty"))
(entry 17 "abc" <> entry 42 "qwerty")
-- Check that we can tolerate missing keys and values.
, deserializeFrom "missing key"
(Just $ defFoo & bar .~ [(0, "abc")])
$ tagged 1 $ Lengthy $ taggedValue "abc"
, deserializeFrom "missing value"
(Just $ defFoo & bar .~ [(42, "")])
$ tagged 1 $ Lengthy $ tagged 1 $ VarInt 42
, runTypedTest (roundTripTest "roundtrip" :: TypedTest Foo)
]
| null | https://raw.githubusercontent.com/google/proto-lens/081815877430afc1db669ca5e4edde1558b5fd9d/proto-lens-tests/tests/map_test.hs | haskell | Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file or at
-source/licenses/bsd
# LANGUAGE OverloadedStrings #
Note how OverloadedLists work here in the "bar" field.
For proto-lens, it resolves to a (Map Int32 Text).
Check that we can tolerate missing keys and values. |
# LANGUAGE OverloadedLists #
module Main where
import Proto.Map
import Proto.Map_Fields
import Data.ProtoLens
import Lens.Family2 ((&), (.~))
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder (Builder, byteString)
import Data.Word (Word64)
import Data.ProtoLens.TestUtil
defFoo :: Foo
defFoo = defMessage
entry :: Word64 -> String -> Builder
entry k v = tagged 1 $ Lengthy $ tagged 1 (VarInt k)
<> taggedValue v
taggedValue :: String -> Builder
taggedValue = tagged 2 . Lengthy . byteString . C.pack
kvPair :: Doc -> Doc -> Doc
kvPair k v = keyed "key" k $+$ keyed "value" v
main :: IO ()
main = testMain
[ serializeTo "default" defFoo "" mempty
, serializeTo "singleton"
(defFoo & bar .~ [(42, "qwerty")])
(braced "bar" $ kvPair "42" $ doubleQuotes "qwerty")
(entry 42 "qwerty")
, serializeTo "moreElements"
(defFoo & bar .~ [(17, "abc"), (42, "qwerty")])
(braced "bar" (kvPair "17" $ doubleQuotes "abc")
$+$ braced "bar" (kvPair "42" $ doubleQuotes "qwerty"))
(entry 17 "abc" <> entry 42 "qwerty")
, deserializeFrom "missing key"
(Just $ defFoo & bar .~ [(0, "abc")])
$ tagged 1 $ Lengthy $ taggedValue "abc"
, deserializeFrom "missing value"
(Just $ defFoo & bar .~ [(42, "")])
$ tagged 1 $ Lengthy $ tagged 1 $ VarInt 42
, runTypedTest (roundTripTest "roundtrip" :: TypedTest Foo)
]
|
b72ecdecb09183cf9bcd255e99d87cfb2527c45187d90f231f967d72ad6126b6 | SamB/coq | explore.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(*i $Id$ i*)
(*s Search strategies. *)
(*s A search problem implements the following signature [SearchProblem].
[state] is the type of states of the search tree.
[branching] is the branching function; if [branching s] returns an
empty list, then search from [s] is aborted; successors of [s] are
recursively searched in the order they appear in the list.
[success] determines whether a given state is a success.
[pp] is a pretty-printer for states used in debugging versions of the
search functions. *)
module type SearchProblem = sig
type state
val branching : state -> state list
val success : state -> bool
val pp : state -> unit
end
(*s Functor [Make] returns some search functions given a search problem.
Search functions raise [Not_found] if no success is found.
States are always visited in the order they appear in the
output of [branching] (whatever the search method is).
Debugging versions of the search functions print the position of the
visited state together with the state it-self (using [S.pp]). *)
module Make : functor(S : SearchProblem) -> sig
val depth_first : S.state -> S.state
val debug_depth_first : S.state -> S.state
val breadth_first : S.state -> S.state
val debug_breadth_first : S.state -> S.state
end
| null | https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/lib/explore.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i $Id$ i
s Search strategies.
s A search problem implements the following signature [SearchProblem].
[state] is the type of states of the search tree.
[branching] is the branching function; if [branching s] returns an
empty list, then search from [s] is aborted; successors of [s] are
recursively searched in the order they appear in the list.
[success] determines whether a given state is a success.
[pp] is a pretty-printer for states used in debugging versions of the
search functions.
s Functor [Make] returns some search functions given a search problem.
Search functions raise [Not_found] if no success is found.
States are always visited in the order they appear in the
output of [branching] (whatever the search method is).
Debugging versions of the search functions print the position of the
visited state together with the state it-self (using [S.pp]). | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
module type SearchProblem = sig
type state
val branching : state -> state list
val success : state -> bool
val pp : state -> unit
end
module Make : functor(S : SearchProblem) -> sig
val depth_first : S.state -> S.state
val debug_depth_first : S.state -> S.state
val breadth_first : S.state -> S.state
val debug_breadth_first : S.state -> S.state
end
|
dcd4bed6e3143e945fee027023ca37b69c42e44752a2a9a450cfecce494e9f33 | joshuamiller/cljs-react-navigation-example | subs.cljs | (ns nav-example.subs
(:require [re-frame.core :refer [reg-sub]]))
(reg-sub
:get-greeting
(fn [db _]
(:greeting db))) | null | https://raw.githubusercontent.com/joshuamiller/cljs-react-navigation-example/45568ed191e782c3f8c0580d2d8774c6b2add52f/src/nav_example/subs.cljs | clojure | (ns nav-example.subs
(:require [re-frame.core :refer [reg-sub]]))
(reg-sub
:get-greeting
(fn [db _]
(:greeting db))) | |
921d963234a7b907b9303395cccbacedf69d5e9325fc85bea05d7c8ae698e57d | con-kitty/categorifier | Main.hs | # LANGUAGE DataKinds #
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
To avoid turning @if then else@ into ` ifThenElse ` .
# LANGUAGE NoRebindableSyntax #
-- | See @Test/Cat/ConCat/Main.hs@ for copious notes on the testing situation here.
module Main
( main,
)
where
import Categorifier.Hedgehog (genFloating, genLargeIntegral)
import Categorifier.Test.Categories.Instances (Hask (..), Term)
import Categorifier.Test.Data (Pair (..))
import Categorifier.Test.HList (HMap1 (..))
import Categorifier.Test.Tests
( TestCases (..),
TestCategory (..),
TestStrategy (..),
defaultTestTerms,
mkTestTerms,
zerosafeUnsignedPrimitiveCases,
)
import Control.Arrow (Arrow (..), ArrowChoice (..))
import Data.Bool (bool)
import Data.Functor.Identity (Identity (..))
import Data.Proxy (Proxy (..))
import Data.Semigroup (Sum (..))
import GHC.Int (Int16, Int32, Int64, Int8)
import GHC.Word (Word16, Word32, Word64, Word8)
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import System.Exit (exitFailure, exitSuccess)
-- For @NoRebindableSyntax@
# ANN module ( " HLint : ignore Avoid restricted integration " : : String ) #
mkTestTerms
defaultTestTerms
-- name type prefix strategy
[ TestCategory ''Term [t|Term|] "term" CheckCompileOnly,
TestCategory ''(->) [t|(->)|] "plainArrow" $ ComputeFromInput [|id|],
TestCategory ''Hask [t|Hask|] "hask" (ComputeFromInput [|runHask|])
]
-- core
. HInsert1 (Proxy @"LamId") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1 (Proxy @"ComposeLam") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"ConstLam")
( TestCases
( const
[ ( ([t|Int64|], [t|Word8|]),
pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1 (Proxy @"ReturnLam") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1 (Proxy @"BuildTuple") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"EliminateTupleFst")
( TestCases
(const [([t|Word8|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EliminateTupleSnd")
( TestCases
(const [([t|Word8|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EliminateNestedTuples")
( TestCases
( const
[ ( [t|Word8|],
pure
( [|(,) <$> Gen.enumBounded <*> ((,) <$> Gen.enumBounded <*> Gen.enumBounded)|],
[|show|]
)
)
]
)
)
. HInsert1 (Proxy @"LocalFixedPoint") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"ApplyArg")
( TestCases
( const
[ ( [t|Word8|],
pure ([|Gen.choice [const <$> Gen.enumBounded, pure id]|], [|const "<function>"|])
)
]
)
)
. HInsert1
(Proxy @"If")
( TestCases
( const
[ ( [t|Int64|],
pure
([|(,) <$> Gen.bool <*> ((,) <$> Gen.enumBounded <*> Gen.enumBounded)|], [|show|])
)
]
)
)
-- plugin
. HInsert1
(Proxy @"Abst")
( TestCases
(const [([t|Word8|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Repr")
( TestCases
(const [([t|Word8|], pure ([|Pair <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
-- base
. HInsert1 (Proxy @"Id") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"Const")
( TestCases
( const
[ ( ([t|Int64|], [t|Word8|]),
pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"Snd")
( TestCases
( const
[ ( ([t|Word8|], [t|Word8|]),
pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"FstSnd")
( TestCases
( const
[ ( ([t|Word8|], [t|Word8|], [t|Word8|]),
pure
( [|
(,)
<$> Gen.enumBounded
<*> ((,) <$> Gen.enumBounded <*> Gen.enumBounded)
|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"FstLet")
( TestCases
( const
[ ( ([t|Word8|], [t|Word8|], [t|Word8|]),
pure
( [|(,) <$> Gen.enumBounded <*> ((,) <$> Gen.enumBounded <*> Gen.enumBounded)|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"Swap")
( TestCases
( const
[ ( ([t|Word8|], [t|Int64|]),
pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1 (Proxy @"Fork") (TestCases (const [(([t|Int64|], [t|Word8|]), pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"Join")
( TestCases
( const
[ ( ([t|Int64|], [t|Word8|]),
pure
([|Gen.choice [Left <$> Gen.enumBounded, Right <$> Gen.enumBounded]|], [|show|])
)
]
)
)
. HInsert1 (Proxy @"Arr") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1
(Proxy @"Either")
( TestCases
( const
[ ( ([t|Int64|], [t|Word8|]),
pure
([|Gen.choice [Left <$> Gen.enumBounded, Right <$> Gen.enumBounded]|], [|show|])
)
]
)
)
. HInsert1 (Proxy @"Coerce") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1 (Proxy @"ComposedCoerce") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"Bool")
( TestCases
( const
[ ( [t|Bool|],
pure
( [|(,,) <$> Gen.bool <*> Gen.bool <*> Gen.bool|],
[|show|]
)
),
( [t|Word8|],
pure
( [|(,,) <$> Gen.enumBounded <*> Gen.enumBounded <*> Gen.bool|],
[|show|]
)
),
( [t|Word16|],
pure
( [|(,,) <$> Gen.enumBounded <*> Gen.enumBounded <*> Gen.bool|],
[|show|]
)
),
( [t|Word32|],
pure
( [|(,,) <$> Gen.enumBounded <*> Gen.enumBounded <*> Gen.bool|],
[|show|]
)
),
( [t|Word64|],
pure
( [|(,,) <$> genLargeIntegral <*> genLargeIntegral <*> Gen.bool|],
[|show|]
)
),
( [t|Int8|],
pure
( [|(,,) <$> Gen.enumBounded <*> Gen.enumBounded <*> Gen.bool|],
[|show|]
)
),
( [t|Int16|],
pure
( [|(,,) <$> Gen.enumBounded <*> Gen.enumBounded <*> Gen.bool|],
[|show|]
)
),
( [t|Int32|],
pure
( [|(,,) <$> Gen.enumBounded <*> Gen.enumBounded <*> Gen.bool|],
[|show|]
)
),
( [t|Int64|],
pure
( [|(,,) <$> Gen.enumBounded <*> Gen.enumBounded <*> Gen.bool|],
[|show|]
)
),
( [t|Float|],
pure
( [|(,,) <$> genFloating <*> genFloating <*> Gen.bool|],
[|show|]
)
),
( [t|Double|],
pure
( [|(,,) <$> genFloating <*> genFloating <*> Gen.bool|],
[|show|]
)
)
]
)
)
. HInsert1 (Proxy @"Acos") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Acosh") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AcoshDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AcoshFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Asin") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Asinh") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AsinhDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AsinhFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Atan") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Atanh") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AtanhDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AtanhFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Cos") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Cosh") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AcosDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AsinDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AtanDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"CosDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"CoshDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AcosFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AsinFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AtanFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"CosFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"CoshFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Double2Float") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Exp") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Float2Double") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"IsDenormalized") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"IsInfinite") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"IsNaN") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"IsNegativeZero") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Log") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"LogDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"LogFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"MinusDouble") (TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"MinusFloat") (TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"NegateDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"NegateFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"PlusDouble") (TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"PlusFloat") (TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"Power")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"PowerDouble")
(TestCases (const [((), pure ([|Gen.filter (/= (0, 0)) $ (,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"PowerFloat")
(TestCases (const [((), pure ([|Gen.filter (/= (0, 0)) $ (,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Sin") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Sinh") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"SinDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"SinhDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"SinFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"SinhFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Sqrt") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"SqrtDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"SqrtFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Tan") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Tanh") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"TanDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"TanhDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"TanFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"TanhFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"TimesDouble") (TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"TimesFloat") (TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"And")
(TestCases (const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"Or")
(TestCases (const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"Equal")
( TestCases
(const [([t|Int64|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqual")
( TestCases
(const [([t|Int64|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Ge")
( TestCases
(const [([t|Int64|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Gt")
( TestCases
(const [([t|Int64|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Le")
( TestCases
(const [([t|Int64|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Lt")
( TestCases
(const [([t|Int64|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualDouble")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"GeDouble")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"GtDouble")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"LeDouble")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"LtDouble")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"EqualFloat")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"GeFloat")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"GtFloat")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"LeFloat")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"LtFloat")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"EqualInt")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualInt")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeInt")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtInt")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeInt")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtInt")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualInt16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualInt16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeInt16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtInt16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeInt16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtInt16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualInt32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualInt32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeInt32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtInt32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeInt32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtInt32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualInt64")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualInt64")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeInt64")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtInt64")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeInt64")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtInt64")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualInt8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualInt8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeInt8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtInt8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeInt8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtInt8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualWord")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualWord")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"GeWord")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"GtWord")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"LeWord")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"LtWord")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"EqualWord16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualWord16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeWord16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtWord16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeWord16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtWord16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualWord32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualWord32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeWord32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtWord32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeWord32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtWord32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualWord64")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualWord64")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"GeWord64")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"GtWord64")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"LeWord64")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"LtWord64")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"EqualWord8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualWord8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeWord8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtWord8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeWord8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtWord8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Compare")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"Max")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"Min")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Not") (TestCases (const [((), pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"Plus")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"Minus")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"Times")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Quot") (TestCases (const zerosafeUnsignedPrimitiveCases))
. HInsert1
(Proxy @"RealToFrac")
(TestCases (const [(([t|Double|], [t|Float|]), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Recip") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Rem") (TestCases (const zerosafeUnsignedPrimitiveCases))
. HInsert1
(Proxy @"Div")
( TestCases
( const
[ ( [t|Word8|],
pure
([|(,) <$> Gen.enumBounded <*> Gen.integral (Range.linear 1 maxBound)|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"Mod")
( TestCases
( const
[ ( [t|Word8|],
pure
([|(,) <$> Gen.enumBounded <*> Gen.integral (Range.linear 1 maxBound)|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"Divide")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"DivideDouble")
(TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"DivideFloat")
(TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Atan2") (TestCases (const [])) -- no support for `atan2` in Categories
. HInsert1 (Proxy @"Abs") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Negate") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Signum") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"PowI") (TestCases (const []))
. HInsert1 (Proxy @"PowInt") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1
(Proxy @"FromInteger")
( TestCases
( const
[ ( [t|Double|],
pure
( [|
Gen.integral $
Range.linearFrom
0
(toInteger (minBound :: Int64) - 1)
(toInteger (maxBound :: Int64) + 1)
|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"FromIntegral")
( TestCases
(const [(([t|Int64|], [t|Double|]), pure ([|Gen.int64 Range.linearBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Append")
( TestCases
( const
[ ( [t|[Word8]|],
pure
( [|
(,)
<$> Gen.list (Range.linear 0 100) Gen.enumBounded
<*> Gen.list (Range.linear 0 100) Gen.enumBounded
|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"Mappend")
( TestCases
( const
[ ( [t|[Word8]|],
pure
( [|
(,)
<$> Gen.list (Range.linear 0 100) Gen.enumBounded
<*> Gen.list (Range.linear 0 100) Gen.enumBounded
|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"ListAppend")
( TestCases
( const
[ ( [t|Word8|],
pure
( [|
(,)
<$> Gen.list (Range.linear 0 100) Gen.enumBounded
<*> Gen.list (Range.linear 0 100) Gen.enumBounded
|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"Pure")
( TestCases
( const
[ ([t|Double|], pure ([|genFloating|], [|show|])),
([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))
]
)
)
. HInsert1 (Proxy @"Return") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Error") (TestCases (const [])) -- no support for `error` in Categories
. HInsert1
(Proxy @"BuildLeft")
(TestCases (const [(([t|Int64|], [t|Word8|]), pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"BuildRight")
(TestCases (const [(([t|Int64|], [t|Word8|]), pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"EliminateEither")
( TestCases
( const
[ ( [t|Word8|],
pure
( [|
do
x :: Word8 <- Gen.enumBounded
Gen.element [Left x, Right x]
|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"EliminateEitherSwapped")
( TestCases
( const
[ ( [t|Word8|],
pure
( [|
do
x :: Word8 <- Gen.enumBounded
Gen.element [Left x, Right x]
|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"Apply")
( TestCases
( const
[ ( ([t|Word8|], [t|Bool|]),
pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"BareFMap")
( TestCases
( const
[ ( [t|Word8|],
pure
( [|
(,)
<$> Gen.element [const 42, id]
<*> (Pair <$> Gen.enumBounded <*> Gen.enumBounded)
|],
[|show . snd|]
)
)
]
)
)
. HInsert1
(Proxy @"PartialFmap")
( TestCases
(const [([t|Word8|], pure ([|Pair <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Fmap")
( TestCases
( const
[ ( ([t|Pair|], [t|Word8|]),
pure ([|Pair <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"Fmap'")
( TestCases
(const [([t|Word8|], pure ([|Pair <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"ConstNot")
( TestCases
(const [([t|Word8|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"MapList")
( TestCases
( const
[([t|Word8|], pure ([|Gen.list (Range.exponential 1 1024) Gen.enumBounded|], [|show|]))]
)
)
. HInsert1
(Proxy @"Ap")
( TestCases
( const
[ ( ([t|[]|], [t|Int64|]),
pure ([|Gen.list (Range.linear 0 100) Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1 (Proxy @"LiftA2") (TestCases (const [])) -- no support for `liftA2` in Categories
. HInsert1
(Proxy @"Bind")
( TestCases
( const
[ ( [t|Word8|],
pure ([|(\x -> (x, pure)) . Identity <$> Gen.enumBounded|], [|show . fst|])
)
]
)
)
. HInsert1
(Proxy @"Curry")
( TestCases
( const
[ ( ([t|Word8|], [t|Bool|]),
pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"Uncurry")
( TestCases
( const
[ ( ([t|Word8|], [t|Bool|]),
pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1 (Proxy @"SequenceA") (TestCases (const []))
. HInsert1 (Proxy @"Traverse") (TestCases (const []))
. HInsert1
(Proxy @"UnsafeCoerce")
(TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Sum") (TestCases (const [])) -- can only work with specialization
. HInsert1 (Proxy @"SumList") (TestCases (const []))
. HInsert1 (Proxy @"ToList") (TestCases (const [])) -- can only work with specialization
. HInsert1 (Proxy @"Even") (TestCases (const []))
. HInsert1 (Proxy @"Odd") (TestCases (const []))
$ HEmpty1
main :: IO ()
main = bool exitFailure exitSuccess . and =<< allTestTerms
| null | https://raw.githubusercontent.com/con-kitty/categorifier/d8dc1106c4600c2168889519d2c3f843db2e9410/integrations/categories/integration-test/test/Categories/Main.hs | haskell | # LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
| See @Test/Cat/ConCat/Main.hs@ for copious notes on the testing situation here.
For @NoRebindableSyntax@
name type prefix strategy
core
plugin
base
no support for `atan2` in Categories
no support for `error` in Categories
no support for `liftA2` in Categories
can only work with specialization
can only work with specialization | # LANGUAGE DataKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
To avoid turning @if then else@ into ` ifThenElse ` .
# LANGUAGE NoRebindableSyntax #
module Main
( main,
)
where
import Categorifier.Hedgehog (genFloating, genLargeIntegral)
import Categorifier.Test.Categories.Instances (Hask (..), Term)
import Categorifier.Test.Data (Pair (..))
import Categorifier.Test.HList (HMap1 (..))
import Categorifier.Test.Tests
( TestCases (..),
TestCategory (..),
TestStrategy (..),
defaultTestTerms,
mkTestTerms,
zerosafeUnsignedPrimitiveCases,
)
import Control.Arrow (Arrow (..), ArrowChoice (..))
import Data.Bool (bool)
import Data.Functor.Identity (Identity (..))
import Data.Proxy (Proxy (..))
import Data.Semigroup (Sum (..))
import GHC.Int (Int16, Int32, Int64, Int8)
import GHC.Word (Word16, Word32, Word64, Word8)
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import System.Exit (exitFailure, exitSuccess)
# ANN module ( " HLint : ignore Avoid restricted integration " : : String ) #
mkTestTerms
defaultTestTerms
[ TestCategory ''Term [t|Term|] "term" CheckCompileOnly,
TestCategory ''(->) [t|(->)|] "plainArrow" $ ComputeFromInput [|id|],
TestCategory ''Hask [t|Hask|] "hask" (ComputeFromInput [|runHask|])
]
. HInsert1 (Proxy @"LamId") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1 (Proxy @"ComposeLam") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"ConstLam")
( TestCases
( const
[ ( ([t|Int64|], [t|Word8|]),
pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1 (Proxy @"ReturnLam") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1 (Proxy @"BuildTuple") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"EliminateTupleFst")
( TestCases
(const [([t|Word8|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EliminateTupleSnd")
( TestCases
(const [([t|Word8|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EliminateNestedTuples")
( TestCases
( const
[ ( [t|Word8|],
pure
( [|(,) <$> Gen.enumBounded <*> ((,) <$> Gen.enumBounded <*> Gen.enumBounded)|],
[|show|]
)
)
]
)
)
. HInsert1 (Proxy @"LocalFixedPoint") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"ApplyArg")
( TestCases
( const
[ ( [t|Word8|],
pure ([|Gen.choice [const <$> Gen.enumBounded, pure id]|], [|const "<function>"|])
)
]
)
)
. HInsert1
(Proxy @"If")
( TestCases
( const
[ ( [t|Int64|],
pure
([|(,) <$> Gen.bool <*> ((,) <$> Gen.enumBounded <*> Gen.enumBounded)|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"Abst")
( TestCases
(const [([t|Word8|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Repr")
( TestCases
(const [([t|Word8|], pure ([|Pair <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1 (Proxy @"Id") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"Const")
( TestCases
( const
[ ( ([t|Int64|], [t|Word8|]),
pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"Snd")
( TestCases
( const
[ ( ([t|Word8|], [t|Word8|]),
pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"FstSnd")
( TestCases
( const
[ ( ([t|Word8|], [t|Word8|], [t|Word8|]),
pure
( [|
(,)
<$> Gen.enumBounded
<*> ((,) <$> Gen.enumBounded <*> Gen.enumBounded)
|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"FstLet")
( TestCases
( const
[ ( ([t|Word8|], [t|Word8|], [t|Word8|]),
pure
( [|(,) <$> Gen.enumBounded <*> ((,) <$> Gen.enumBounded <*> Gen.enumBounded)|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"Swap")
( TestCases
( const
[ ( ([t|Word8|], [t|Int64|]),
pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1 (Proxy @"Fork") (TestCases (const [(([t|Int64|], [t|Word8|]), pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"Join")
( TestCases
( const
[ ( ([t|Int64|], [t|Word8|]),
pure
([|Gen.choice [Left <$> Gen.enumBounded, Right <$> Gen.enumBounded]|], [|show|])
)
]
)
)
. HInsert1 (Proxy @"Arr") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1
(Proxy @"Either")
( TestCases
( const
[ ( ([t|Int64|], [t|Word8|]),
pure
([|Gen.choice [Left <$> Gen.enumBounded, Right <$> Gen.enumBounded]|], [|show|])
)
]
)
)
. HInsert1 (Proxy @"Coerce") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1 (Proxy @"ComposedCoerce") (TestCases (const [([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"Bool")
( TestCases
( const
[ ( [t|Bool|],
pure
( [|(,,) <$> Gen.bool <*> Gen.bool <*> Gen.bool|],
[|show|]
)
),
( [t|Word8|],
pure
( [|(,,) <$> Gen.enumBounded <*> Gen.enumBounded <*> Gen.bool|],
[|show|]
)
),
( [t|Word16|],
pure
( [|(,,) <$> Gen.enumBounded <*> Gen.enumBounded <*> Gen.bool|],
[|show|]
)
),
( [t|Word32|],
pure
( [|(,,) <$> Gen.enumBounded <*> Gen.enumBounded <*> Gen.bool|],
[|show|]
)
),
( [t|Word64|],
pure
( [|(,,) <$> genLargeIntegral <*> genLargeIntegral <*> Gen.bool|],
[|show|]
)
),
( [t|Int8|],
pure
( [|(,,) <$> Gen.enumBounded <*> Gen.enumBounded <*> Gen.bool|],
[|show|]
)
),
( [t|Int16|],
pure
( [|(,,) <$> Gen.enumBounded <*> Gen.enumBounded <*> Gen.bool|],
[|show|]
)
),
( [t|Int32|],
pure
( [|(,,) <$> Gen.enumBounded <*> Gen.enumBounded <*> Gen.bool|],
[|show|]
)
),
( [t|Int64|],
pure
( [|(,,) <$> Gen.enumBounded <*> Gen.enumBounded <*> Gen.bool|],
[|show|]
)
),
( [t|Float|],
pure
( [|(,,) <$> genFloating <*> genFloating <*> Gen.bool|],
[|show|]
)
),
( [t|Double|],
pure
( [|(,,) <$> genFloating <*> genFloating <*> Gen.bool|],
[|show|]
)
)
]
)
)
. HInsert1 (Proxy @"Acos") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Acosh") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AcoshDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AcoshFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Asin") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Asinh") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AsinhDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AsinhFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Atan") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Atanh") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AtanhDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AtanhFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Cos") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Cosh") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AcosDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AsinDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AtanDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"CosDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"CoshDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AcosFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AsinFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"AtanFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"CosFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"CoshFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Double2Float") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Exp") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Float2Double") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"IsDenormalized") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"IsInfinite") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"IsNaN") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"IsNegativeZero") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Log") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"LogDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"LogFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"MinusDouble") (TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"MinusFloat") (TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"NegateDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"NegateFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"PlusDouble") (TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"PlusFloat") (TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"Power")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"PowerDouble")
(TestCases (const [((), pure ([|Gen.filter (/= (0, 0)) $ (,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"PowerFloat")
(TestCases (const [((), pure ([|Gen.filter (/= (0, 0)) $ (,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Sin") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Sinh") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"SinDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"SinhDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"SinFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"SinhFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Sqrt") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"SqrtDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"SqrtFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Tan") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Tanh") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"TanDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"TanhDouble") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"TanFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"TanhFloat") (TestCases (const [((), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"TimesDouble") (TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"TimesFloat") (TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"And")
(TestCases (const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"Or")
(TestCases (const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"Equal")
( TestCases
(const [([t|Int64|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqual")
( TestCases
(const [([t|Int64|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Ge")
( TestCases
(const [([t|Int64|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Gt")
( TestCases
(const [([t|Int64|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Le")
( TestCases
(const [([t|Int64|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Lt")
( TestCases
(const [([t|Int64|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualDouble")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"GeDouble")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"GtDouble")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"LeDouble")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"LtDouble")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"EqualFloat")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"GeFloat")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"GtFloat")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"LeFloat")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"LtFloat")
( TestCases
(const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))])
)
. HInsert1
(Proxy @"EqualInt")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualInt")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeInt")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtInt")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeInt")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtInt")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualInt16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualInt16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeInt16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtInt16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeInt16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtInt16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualInt32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualInt32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeInt32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtInt32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeInt32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtInt32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualInt64")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualInt64")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeInt64")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtInt64")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeInt64")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtInt64")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualInt8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualInt8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeInt8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtInt8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeInt8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtInt8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualWord")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualWord")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"GeWord")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"GtWord")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"LeWord")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"LtWord")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"EqualWord16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualWord16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeWord16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtWord16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeWord16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtWord16")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualWord32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualWord32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeWord32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtWord32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeWord32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtWord32")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"EqualWord64")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualWord64")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"GeWord64")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"GtWord64")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"LeWord64")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"LtWord64")
( TestCases
(const [((), pure ([|(,) <$> genLargeIntegral <*> genLargeIntegral|], [|show|]))])
)
. HInsert1
(Proxy @"EqualWord8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"NotEqualWord8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GeWord8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"GtWord8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LeWord8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"LtWord8")
( TestCases
(const [((), pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Compare")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"Max")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"Min")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Not") (TestCases (const [((), pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"Plus")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"Minus")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"Times")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Quot") (TestCases (const zerosafeUnsignedPrimitiveCases))
. HInsert1
(Proxy @"RealToFrac")
(TestCases (const [(([t|Double|], [t|Float|]), pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Recip") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Rem") (TestCases (const zerosafeUnsignedPrimitiveCases))
. HInsert1
(Proxy @"Div")
( TestCases
( const
[ ( [t|Word8|],
pure
([|(,) <$> Gen.enumBounded <*> Gen.integral (Range.linear 1 maxBound)|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"Mod")
( TestCases
( const
[ ( [t|Word8|],
pure
([|(,) <$> Gen.enumBounded <*> Gen.integral (Range.linear 1 maxBound)|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"Divide")
(TestCases (const [([t|Double|], pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"DivideDouble")
(TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1
(Proxy @"DivideFloat")
(TestCases (const [((), pure ([|(,) <$> genFloating <*> genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Abs") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Negate") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"Signum") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"PowI") (TestCases (const []))
. HInsert1 (Proxy @"PowInt") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1
(Proxy @"FromInteger")
( TestCases
( const
[ ( [t|Double|],
pure
( [|
Gen.integral $
Range.linearFrom
0
(toInteger (minBound :: Int64) - 1)
(toInteger (maxBound :: Int64) + 1)
|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"FromIntegral")
( TestCases
(const [(([t|Int64|], [t|Double|]), pure ([|Gen.int64 Range.linearBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Append")
( TestCases
( const
[ ( [t|[Word8]|],
pure
( [|
(,)
<$> Gen.list (Range.linear 0 100) Gen.enumBounded
<*> Gen.list (Range.linear 0 100) Gen.enumBounded
|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"Mappend")
( TestCases
( const
[ ( [t|[Word8]|],
pure
( [|
(,)
<$> Gen.list (Range.linear 0 100) Gen.enumBounded
<*> Gen.list (Range.linear 0 100) Gen.enumBounded
|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"ListAppend")
( TestCases
( const
[ ( [t|Word8|],
pure
( [|
(,)
<$> Gen.list (Range.linear 0 100) Gen.enumBounded
<*> Gen.list (Range.linear 0 100) Gen.enumBounded
|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"Pure")
( TestCases
( const
[ ([t|Double|], pure ([|genFloating|], [|show|])),
([t|Word8|], pure ([|Gen.enumBounded|], [|show|]))
]
)
)
. HInsert1 (Proxy @"Return") (TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1
(Proxy @"BuildLeft")
(TestCases (const [(([t|Int64|], [t|Word8|]), pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"BuildRight")
(TestCases (const [(([t|Int64|], [t|Word8|]), pure ([|Gen.enumBounded|], [|show|]))]))
. HInsert1
(Proxy @"EliminateEither")
( TestCases
( const
[ ( [t|Word8|],
pure
( [|
do
x :: Word8 <- Gen.enumBounded
Gen.element [Left x, Right x]
|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"EliminateEitherSwapped")
( TestCases
( const
[ ( [t|Word8|],
pure
( [|
do
x :: Word8 <- Gen.enumBounded
Gen.element [Left x, Right x]
|],
[|show|]
)
)
]
)
)
. HInsert1
(Proxy @"Apply")
( TestCases
( const
[ ( ([t|Word8|], [t|Bool|]),
pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"BareFMap")
( TestCases
( const
[ ( [t|Word8|],
pure
( [|
(,)
<$> Gen.element [const 42, id]
<*> (Pair <$> Gen.enumBounded <*> Gen.enumBounded)
|],
[|show . snd|]
)
)
]
)
)
. HInsert1
(Proxy @"PartialFmap")
( TestCases
(const [([t|Word8|], pure ([|Pair <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"Fmap")
( TestCases
( const
[ ( ([t|Pair|], [t|Word8|]),
pure ([|Pair <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"Fmap'")
( TestCases
(const [([t|Word8|], pure ([|Pair <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"ConstNot")
( TestCases
(const [([t|Word8|], pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|]))])
)
. HInsert1
(Proxy @"MapList")
( TestCases
( const
[([t|Word8|], pure ([|Gen.list (Range.exponential 1 1024) Gen.enumBounded|], [|show|]))]
)
)
. HInsert1
(Proxy @"Ap")
( TestCases
( const
[ ( ([t|[]|], [t|Int64|]),
pure ([|Gen.list (Range.linear 0 100) Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"Bind")
( TestCases
( const
[ ( [t|Word8|],
pure ([|(\x -> (x, pure)) . Identity <$> Gen.enumBounded|], [|show . fst|])
)
]
)
)
. HInsert1
(Proxy @"Curry")
( TestCases
( const
[ ( ([t|Word8|], [t|Bool|]),
pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1
(Proxy @"Uncurry")
( TestCases
( const
[ ( ([t|Word8|], [t|Bool|]),
pure ([|(,) <$> Gen.enumBounded <*> Gen.enumBounded|], [|show|])
)
]
)
)
. HInsert1 (Proxy @"SequenceA") (TestCases (const []))
. HInsert1 (Proxy @"Traverse") (TestCases (const []))
. HInsert1
(Proxy @"UnsafeCoerce")
(TestCases (const [([t|Double|], pure ([|genFloating|], [|show|]))]))
. HInsert1 (Proxy @"SumList") (TestCases (const []))
. HInsert1 (Proxy @"Even") (TestCases (const []))
. HInsert1 (Proxy @"Odd") (TestCases (const []))
$ HEmpty1
main :: IO ()
main = bool exitFailure exitSuccess . and =<< allTestTerms
|
ab1e1c52320087acd56825312c922979eccd65235d2c52ac4d8cd278e446b80e | alanz/ghc-exactprint | LayoutLet4.hs | module LayoutLet4 where
-- Simple let expression, rename xxx to something longer or shorter
-- and the let/in layout should adjust accordingly
-- In this case the tokens for xxx + a + b should also shift out
foo xxx = let a = 1
b = 2
in xxx + a + b
bar = 3
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/transform/LayoutLet4.hs | haskell | Simple let expression, rename xxx to something longer or shorter
and the let/in layout should adjust accordingly
In this case the tokens for xxx + a + b should also shift out | module LayoutLet4 where
foo xxx = let a = 1
b = 2
in xxx + a + b
bar = 3
|
abe62a7b35da084d04ea872b1949a7d0a1ec064162ca10e51ec1a10bb02cd37a | well-typed-lightbulbs/ocaml-esp32 | poly.ml | (* TEST
* expect
*)
(*
Polymorphic methods are now available in the main branch.
Enjoy.
*)
(* Tests for explicit polymorphism *)
open StdLabels;;
type 'a t = { t : 'a };;
type 'a fold = { fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b };;
let f l = { fold = List.fold_left l };;
(f [1;2;3]).fold ~f:(+) ~init:0;;
[%%expect {|
type 'a t = { t : 'a; }
type 'a fold = { fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b; }
val f : 'a list -> 'a fold = <fun>
- : int = 6
|}];;
type pty = {pv : 'a. 'a list};;
[%%expect {|
type pty = { pv : 'a. 'a list; }
|}];;
type id = { id : 'a. 'a -> 'a };;
let id x = x;;
let {id} = id { id };;
[%%expect {|
type id = { id : 'a. 'a -> 'a; }
val id : 'a -> 'a = <fun>
val id : 'a -> 'a = <fun>
|}];;
let px = {pv = []};;
[%%expect {|
val px : pty = {pv = []}
|}];;
match px with
| {pv=[]} -> "OK"
| {pv=5::_} -> "int"
| {pv=true::_} -> "bool"
;;
[%%expect {|
Lines 1-4, characters 0-24:
1 | match px with
2 | | {pv=[]} -> "OK"
3 | | {pv=5::_} -> "int"
4 | | {pv=true::_} -> "bool"
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
{pv=false::_}
- : string = "OK"
|}];;
match px with
| {pv=[]} -> "OK"
| {pv=true::_} -> "bool"
| {pv=5::_} -> "int"
;;
[%%expect {|
Lines 1-4, characters 0-20:
1 | match px with
2 | | {pv=[]} -> "OK"
3 | | {pv=true::_} -> "bool"
4 | | {pv=5::_} -> "int"
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
{pv=0::_}
- : string = "OK"
|}];;
match px with
| {pv=[]} -> "OK"
| {pv=5::_} -> "int"
| {pv=true::_} -> "bool"
| {pv=false::_} -> "bool"
;;
[%%expect {|
- : string = "OK"
|}];;
fun {pv=v} -> true::v, 1::v;;
[%%expect {|
- : pty -> bool list * int list = <fun>
|}];;
class ['b] ilist l = object
val l = l
method add x = {< l = x :: l >}
method fold : 'a. f:('a -> 'b -> 'a) -> init:'a -> 'a =
List.fold_left l
end
;;
[%%expect {|
class ['b] ilist :
'b list ->
object ('c)
val l : 'b list
method add : 'b -> 'c
method fold : f:('a -> 'b -> 'a) -> init:'a -> 'a
end
|}];;
class virtual ['a] vlist = object (_ : 'self)
method virtual add : 'a -> 'self
method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
end
;;
[%%expect {|
class virtual ['a] vlist :
object ('c)
method virtual add : 'a -> 'c
method virtual fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
end
|}];;
class ilist2 l = object
inherit [int] vlist
val l = l
method add x = {< l = x :: l >}
method fold = List.fold_left l
end
;;
[%%expect {|
class ilist2 :
int list ->
object ('a)
val l : int list
method add : int -> 'a
method fold : f:('b -> int -> 'b) -> init:'b -> 'b
end
|}];;
let ilist2 l = object
inherit [_] vlist
val l = l
method add x = {< l = x :: l >}
method fold = List.fold_left l
end
;;
[%%expect {|
val ilist2 : 'a list -> 'a vlist = <fun>
|}];;
class ['a] ilist3 l = object
inherit ['a] vlist
val l = l
method add x = {< l = x :: l >}
method fold = List.fold_left l
end
;;
[%%expect {|
class ['a] ilist3 :
'a list ->
object ('c)
val l : 'a list
method add : 'a -> 'c
method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
end
|}];;
class ['a] ilist4 (l : 'a list) = object
val l = l
method virtual add : _
method add x = {< l = x :: l >}
method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
method fold = List.fold_left l
end
;;
[%%expect {|
class ['a] ilist4 :
'a list ->
object ('c)
val l : 'a list
method add : 'a -> 'c
method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
end
|}];;
class ['a] ilist5 (l : 'a list) = object (self)
val l = l
method add x = {< l = x :: l >}
method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
method virtual fold2 : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
method fold2 ~f ~init = self#fold ~f ~init:(self#fold ~f ~init)
method fold = List.fold_left l
end
;;
[%%expect {|
class ['a] ilist5 :
'a list ->
object ('c)
val l : 'a list
method add : 'a -> 'c
method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
method fold2 : f:('b -> 'a -> 'b) -> init:'b -> 'b
end
|}];;
class ['a] ilist6 l = object (self)
inherit ['a] vlist
val l = l
method add x = {< l = x :: l >}
method virtual fold2 : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
method fold2 ~f ~init = self#fold ~f ~init:(self#fold ~f ~init)
method fold = List.fold_left l
end
;;
[%%expect {|
class ['a] ilist6 :
'a list ->
object ('c)
val l : 'a list
method add : 'a -> 'c
method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
method fold2 : f:('b -> 'a -> 'b) -> init:'b -> 'b
end
|}];;
class virtual ['a] olist = object
method virtual fold : 'c. f:('a -> 'c -> 'c) -> init:'c -> 'c
end
;;
[%%expect {|
class virtual ['a] olist :
object method virtual fold : f:('a -> 'c -> 'c) -> init:'c -> 'c end
|}];;
class ['a] onil = object
inherit ['a] olist
method fold ~f ~init = init
end
;;
[%%expect {|
class ['a] onil :
object method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c end
|}];;
class ['a] ocons ~hd ~tl = object (_ : 'b)
inherit ['a] olist
val hd : 'a = hd
val tl : 'a olist = tl
method fold ~f ~init = f hd (tl#fold ~f ~init)
end
;;
[%%expect {|
class ['a] ocons :
hd:'a ->
tl:'a olist ->
object
val hd : 'a
val tl : 'a olist
method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c
end
|}];;
class ['a] ostream ~hd ~tl = object (_ : 'b)
inherit ['a] olist
val hd : 'a = hd
val tl : _ #olist = (tl : 'a ostream)
method fold ~f ~init = f hd (tl#fold ~f ~init)
method empty = false
end
;;
[%%expect {|
class ['a] ostream :
hd:'a ->
tl:'a ostream ->
object
val hd : 'a
val tl : < empty : bool; fold : 'c. f:('a -> 'c -> 'c) -> init:'c -> 'c >
method empty : bool
method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c
end
|}];;
class ['a] ostream1 ~hd ~tl = object (self : 'b)
inherit ['a] olist
val hd = hd
val tl : 'b = tl
method hd = hd
method tl = tl
method fold ~f ~init =
self#tl#fold ~f ~init:(f self#hd init)
end
[%%expect {|
class ['a] ostream1 :
hd:'a ->
tl:'b ->
object ('b)
val hd : 'a
val tl : 'b
method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c
method hd : 'a
method tl : 'b
end
|}, Principal{|
Line 8, characters 4-16:
8 | self#tl#fold ~f ~init:(f self#hd init)
^^^^^^^^^^^^
Warning 18: this use of a polymorphic method is not principal.
class ['a] ostream1 :
hd:'a ->
tl:'b ->
object ('b)
val hd : 'a
val tl : 'b
method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c
method hd : 'a
method tl : 'b
end
|}];;
class vari = object
method virtual m : 'a. ([< `A|`B|`C] as 'a) -> int
method m = function `A -> 1 | `B|`C -> 0
end
;;
[%%expect {|
class vari : object method m : [< `A | `B | `C ] -> int end
|}];;
class vari = object
method m : 'a. ([< `A|`B|`C] as 'a) -> int = function `A -> 1 | `B|`C -> 0
end
;;
[%%expect {|
class vari : object method m : [< `A | `B | `C ] -> int end
|}];;
module V =
struct
type v = [`A | `B | `C]
let m : [< v] -> int = function `A -> 1 | #v -> 0
end
;;
[%%expect {|
module V : sig type v = [ `A | `B | `C ] val m : [< v ] -> int end
|}];;
class varj = object
method virtual m : 'a. ([< V.v] as 'a) -> int
method m = V.m
end
;;
[%%expect {|
class varj : object method m : [< V.v ] -> int end
|}];;
module type T = sig
class vari : object method m : 'a. ([< `A | `B | `C] as 'a) -> int end
end
;;
[%%expect {|
module type T =
sig class vari : object method m : [< `A | `B | `C ] -> int end end
|}];;
module M0 = struct
class vari = object
method virtual m : 'a. ([< `A|`B|`C] as 'a) -> int
method m = function `A -> 1 | `B|`C -> 0
end
end
;;
[%%expect {|
module M0 :
sig class vari : object method m : [< `A | `B | `C ] -> int end end
|}];;
module M : T = M0
;;
[%%expect {|
module M : T
|}];;
let v = new M.vari;;
[%%expect {|
val v : M.vari = <obj>
|}];;
v#m `A;;
[%%expect {|
- : int = 1
|}];;
class point ~x ~y = object
val x : int = x
val y : int = y
method x = x
method y = y
end
;;
[%%expect {|
class point :
x:int ->
y:int -> object val x : int val y : int method x : int method y : int end
|}];;
class color_point ~x ~y ~color = object
inherit point ~x ~y
val color : string = color
method color = color
end
;;
[%%expect {|
class color_point :
x:int ->
y:int ->
color:string ->
object
val color : string
val x : int
val y : int
method color : string
method x : int
method y : int
end
|}];;
class circle (p : #point) ~r = object
val p = (p :> point)
val r = r
method virtual distance : 'a. (#point as 'a) -> float
method distance p' =
let dx = p#x - p'#x and dy = p#y - p'#y in
let d = sqrt (float (dx * dx + dy * dy)) -. float r in
if d < 0. then 0. else d
end
;;
[%%expect {|
class circle :
#point ->
r:int ->
object val p : point val r : int method distance : #point -> float end
|}];;
let p0 = new point ~x:3 ~y:5
let p1 = new point ~x:10 ~y:13
let cp = new color_point ~x:12 ~y:(-5) ~color:"green"
let c = new circle p0 ~r:2
let d = floor (c#distance cp)
;;
let f (x : < m : 'a. 'a -> 'a >) = (x : < m : 'b. 'b -> 'b >)
;;
let f (x : < m : 'a. 'a -> 'a list >) = (x : < m : 'b. 'b -> 'c >)
;;
[%%expect {|
val p0 : point = <obj>
val p1 : point = <obj>
val cp : color_point = <obj>
val c : circle = <obj>
val d : float = 11.
val f : < m : 'a. 'a -> 'a > -> < m : 'b. 'b -> 'b > = <fun>
Line 9, characters 41-42:
9 | let f (x : < m : 'a. 'a -> 'a list >) = (x : < m : 'b. 'b -> 'c >)
^
Error: This expression has type < m : 'b. 'b -> 'b list >
but an expression was expected of type < m : 'b. 'b -> 'c >
The method m has type 'b. 'b -> 'b list,
but the expected method type was 'b. 'b -> 'c
The universal variable 'b would escape its scope
|}];;
class id = object
method virtual id : 'a. 'a -> 'a
method id x = x
end
;;
[%%expect {|
class id : object method id : 'a -> 'a end
|}];;
class type id_spec = object
method id : 'a -> 'a
end
;;
[%%expect {|
class type id_spec = object method id : 'a -> 'a end
|}];;
class id_impl = object (_ : #id_spec)
method id x = x
end
;;
[%%expect {|
class id_impl : object method id : 'a -> 'a end
|}];;
class a = object
method m = (new b : id_spec)#id true
end
and b = object (_ : #id_spec)
method id x = x
end
;;
[%%expect {|
class a : object method m : bool end
and b : object method id : 'a -> 'a end
|}];;
class ['a] id1 = object
method virtual id : 'b. 'b -> 'a
method id x = x
end
;;
[%%expect {|
Line 3, characters 12-17:
3 | method id x = x
^^^^^
Error: This method has type 'a -> 'a which is less general than 'b. 'b -> 'a
|}];;
class id2 (x : 'a) = object
method virtual id : 'b. 'b -> 'a
method id x = x
end
;;
[%%expect {|
Line 3, characters 12-17:
3 | method id x = x
^^^^^
Error: This method has type 'a -> 'a which is less general than 'b. 'b -> 'a
|}];;
class id3 x = object
val x = x
method virtual id : 'a. 'a -> 'a
method id _ = x
end
;;
[%%expect {|
Line 4, characters 12-17:
4 | method id _ = x
^^^^^
Error: This method has type 'b -> 'b which is less general than 'a. 'a -> 'a
|}];;
class id4 () = object
val mutable r = None
method virtual id : 'a. 'a -> 'a
method id x =
match r with
None -> r <- Some x; x
| Some y -> y
end
;;
[%%expect {|
Lines 4-7, characters 12-17:
4 | ............x =
5 | match r with
6 | None -> r <- Some x; x
7 | | Some y -> y
Error: This method has type 'b -> 'b which is less general than 'a. 'a -> 'a
|}];;
class c = object
method virtual m : 'a 'b. 'a -> 'b -> 'a
method m x y = x
end
;;
[%%expect {|
class c : object method m : 'a -> 'b -> 'a end
|}];;
let f1 (f : id) = f#id 1, f#id true
;;
let f2 f = (f : id)#id 1, (f : id)#id true
;;
let f3 f = f#id 1, f#id true
;;
let f4 f = ignore(f : id); f#id 1, f#id true
;;
[%%expect {|
val f1 : id -> int * bool = <fun>
val f2 : id -> int * bool = <fun>
Line 5, characters 24-28:
5 | let f3 f = f#id 1, f#id true
^^^^
Error: This expression has type bool but an expression was expected of type
int
|}];;
class c = object
method virtual m : 'a. (#id as 'a) -> int * bool
method m (f : #id) = f#id 1, f#id true
end
;;
[%%expect {|
class c : object method m : #id -> int * bool end
|}];;
class id2 = object (_ : 'b)
method virtual id : 'a. 'a -> 'a
method id x = x
method mono (x : int) = x
end
;;
let app = new c #m (new id2)
;;
type 'a foo = 'a foo list
;;
[%%expect {|
class id2 : object method id : 'a -> 'a method mono : int -> int end
val app : int * bool = (1, true)
Line 9, characters 0-25:
9 | type 'a foo = 'a foo list
^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The type abbreviation foo is cyclic
|}];;
class ['a] bar (x : 'a) = object end
;;
type 'a foo = 'a foo bar
;;
[%%expect {|
class ['a] bar : 'a -> object end
type 'a foo = 'a foo bar
|}];;
fun x -> (x : < m : 'a. 'a * 'b > as 'b)#m;;
fun x -> (x : < m : 'a. 'b * 'a list> as 'b)#m;;
let f x = (x : < m : 'a. 'b * (< n : 'a; .. > as 'a) > as 'b)#m;;
fun (x : < p : 'a. < m : 'a ; n : 'b ; .. > as 'a > as 'b) -> x#p;;
fun (x : <m:'a. 'a * <p:'b. 'b * 'c * 'd> as 'c> as 'd) -> x#m;;
(* printer is wrong on the next (no official syntax) *)
fun (x : <m:'a.<p:'a;..> >) -> x#m;;
[%%expect {|
- : (< m : 'a. 'a * 'b > as 'b) -> 'c * 'b = <fun>
- : (< m : 'a. 'b * 'a list > as 'b) -> 'b * 'c list = <fun>
val f :
(< m : 'b. 'a * (< n : 'b; .. > as 'b) > as 'a) ->
'a * (< n : 'c; .. > as 'c) = <fun>
- : (< p : 'b. < m : 'b; n : 'a; .. > as 'b > as 'a) ->
(< m : 'c; n : 'a; .. > as 'c)
= <fun>
- : (< m : 'a. 'a * < p : 'b. 'b * 'd * 'c > as 'd > as 'c) ->
('f * < p : 'b. 'b * 'e * 'c > as 'e)
= <fun>
- : < m : 'a. < p : 'a; .. > as 'b > -> 'b = <fun>
|}, Principal{|
- : (< m : 'a. 'a * 'b > as 'b) -> 'c * (< m : 'a. 'a * 'd > as 'd) = <fun>
- : (< m : 'a. 'b * 'a list > as 'b) ->
(< m : 'a. 'c * 'a list > as 'c) * 'd list
= <fun>
val f :
(< m : 'b. 'a * (< n : 'b; .. > as 'b) > as 'a) ->
(< m : 'd. 'c * (< n : 'd; .. > as 'd) > as 'c) * (< n : 'e; .. > as 'e) =
<fun>
- : (< p : 'b. < m : 'b; n : 'a; .. > as 'b > as 'a) ->
(< m : 'c; n : < p : 'e. < m : 'e; n : 'd; .. > as 'e > as 'd; .. > as 'c)
= <fun>
- : (< m : 'a. 'a * < p : 'b. 'b * 'd * 'c > as 'd > as 'c) ->
('f *
< p : 'b.
'b * 'e *
(< m : 'a. 'a * < p : 'b0. 'b0 * 'h * 'g > as 'h > as 'g) >
as 'e)
= <fun>
- : < m : 'a. < p : 'a; .. > as 'b > -> 'b = <fun>
|}];;
type sum = T of < id: 'a. 'a -> 'a > ;;
fun (T x) -> x#id;;
[%%expect {|
type sum = T of < id : 'a. 'a -> 'a >
- : sum -> 'a -> 'a = <fun>
|}];;
type record = { r: < id: 'a. 'a -> 'a > } ;;
fun x -> x.r#id;;
fun {r=x} -> x#id;;
[%%expect {|
type record = { r : < id : 'a. 'a -> 'a >; }
- : record -> 'a -> 'a = <fun>
- : record -> 'a -> 'a = <fun>
|}];;
class myself = object (self)
method self : 'a. 'a -> 'b = fun _ -> self
end;;
[%%expect {|
class myself : object ('b) method self : 'a -> 'b end
|}];;
class number = object (self : 'self)
val num = 0
method num = num
method succ = {< num = num + 1 >}
method prev =
self#switch ~zero:(fun () -> failwith "zero") ~prev:(fun x -> x)
method switch : 'a. zero:(unit -> 'a) -> prev:('self -> 'a) -> 'a =
fun ~zero ~prev ->
if num = 0 then zero () else prev {< num = num - 1 >}
end
;;
[%%expect {|
class number :
object ('b)
val num : int
method num : int
method prev : 'b
method succ : 'b
method switch : zero:(unit -> 'a) -> prev:('b -> 'a) -> 'a
end
|}];;
let id x = x
;;
class c = object
method id : 'a. 'a -> 'a = id
end
;;
class c' = object
inherit c
method id = id
end
;;
class d = object
inherit c as c
val mutable count = 0
method id x = count <- count+1; x
method count = count
method old : 'a. 'a -> 'a = c#id
end
;;
class ['a] olist l = object
val l = l
method fold : 'b. f:('a -> 'b -> 'b) -> init:'b -> 'b
= List.fold_right l
method cons a = {< l = a :: l >}
end
;;
let sum (l : 'a #olist) = l#fold ~f:(fun x acc -> x+acc) ~init:0
;;
let count (l : 'a #olist) = l#fold ~f:(fun _ acc -> acc+1) ~init:0
;;
let append (l : 'a #olist) (l' : 'b #olist) =
l#fold ~init:l' ~f:(fun x acc -> acc#cons x)
;;
[%%expect {|
val id : 'a -> 'a = <fun>
class c : object method id : 'a -> 'a end
class c' : object method id : 'a -> 'a end
class d :
object
val mutable count : int
method count : int
method id : 'a -> 'a
method old : 'a -> 'a
end
class ['a] olist :
'a list ->
object ('c)
val l : 'a list
method cons : 'a -> 'c
method fold : f:('a -> 'b -> 'b) -> init:'b -> 'b
end
val sum : int #olist -> int = <fun>
val count : 'a #olist -> int = <fun>
val append : 'a #olist -> ('a #olist as 'b) -> 'b = <fun>
|}];;
type 'a t = unit
;;
class o = object method x : 'a. ([> `A] as 'a) t -> unit = fun _ -> () end
;;
[%%expect {|
type 'a t = unit
class o : object method x : unit -> unit end
|}];;
class c = object method m = new d () end and d ?(x=0) () = object end;;
class d ?(x=0) () = object end and c = object method m = new d () end;;
[%%expect {|
class c : object method m : d end
and d : ?x:int -> unit -> object end
class d : ?x:int -> unit -> object end
and c : object method m : d end
|}];;
class type numeral = object method fold : ('a -> 'a) -> 'a -> 'a end
class zero = object (_ : #numeral) method fold f x = x end
class next (n : #numeral) =
object (_ : #numeral) method fold f x = n#fold f (f x) end
;;
[%%expect {|
class type numeral = object method fold : ('a -> 'a) -> 'a -> 'a end
class zero : object method fold : ('a -> 'a) -> 'a -> 'a end
class next : #numeral -> object method fold : ('a -> 'a) -> 'a -> 'a end
|}];;
class type node_type = object
method as_variant : [> `Node of node_type]
end;;
class node : node_type = object (self)
method as_variant : 'a. [> `Node of node_type] as 'a
= `Node (self :> node_type)
end;;
class node = object (self : #node_type)
method as_variant = `Node (self :> node_type)
end;;
[%%expect {|
class type node_type = object method as_variant : [> `Node of node_type ] end
class node : node_type
class node : object method as_variant : [> `Node of node_type ] end
|}];;
type bad = {bad : 'a. 'a option ref};;
let bad = {bad = ref None};;
type bad2 = {mutable bad2 : 'a. 'a option ref option};;
let bad2 = {bad2 = None};;
bad2.bad2 <- Some (ref None);;
[%%expect {|
type bad = { bad : 'a. 'a option ref; }
Line 2, characters 17-25:
2 | let bad = {bad = ref None};;
^^^^^^^^
Error: This field value has type 'b option ref which is less general than
'a. 'a option ref
|}];;
(* Type variable scope *)
let f (x: <m:'a.<p: 'a * 'b> as 'b>) (y : 'b) = ();;
let f (x: <m:'a. 'a * (<p:int*'b> as 'b)>) (y : 'b) = ();;
[%%expect {|
val f : < m : 'a. < p : 'a * 'c > as 'c > -> 'b -> unit = <fun>
val f : < m : 'a. 'a * (< p : int * 'b > as 'b) > -> 'b -> unit = <fun>
|}, Principal{|
val f : < m : 'a. < p : 'a * 'c > as 'c > -> 'b -> unit = <fun>
val f :
< m : 'a. 'a * (< p : int * 'b > as 'b) > ->
(< p : int * 'c > as 'c) -> unit = <fun>
|}];;
PR#3643
type 'a t= [`A of 'a];;
class c = object (self)
method m : 'a. ([> 'a t] as 'a) -> unit
= fun x -> self#m x
end;;
class c = object (self)
method m : 'a. ([> 'a t] as 'a) -> unit = function
| `A x' -> self#m x'
| _ -> failwith "c#m"
end;;
class c = object (self)
method m : 'a. ([> 'a t] as 'a) -> 'a = fun x -> self#m x
end;;
[%%expect {|
type 'a t = [ `A of 'a ]
class c : object method m : ([> 'a t ] as 'a) -> unit end
class c : object method m : ([> 'a t ] as 'a) -> unit end
class c : object method m : ([> 'a t ] as 'a) -> 'a end
|}];;
(* use before instancing *)
class c = object method m : 'a. 'a option -> ([> `A] as 'a) = fun x -> `A end;;
[%%expect {|
class c : object method m : ([> `A ] as 'a) option -> 'a end
|}];;
(* various old bugs *)
class virtual ['a] visitor =
object method virtual caseNil : 'a end
and virtual int_list =
object method virtual visit : 'a.('a visitor -> 'a) end;;
[%%expect {|
Line 4, characters 30-51:
4 | object method virtual visit : 'a.('a visitor -> 'a) end;;
^^^^^^^^^^^^^^^^^^^^^
Error: The universal type variable 'a cannot be generalized:
it escapes its scope.
|}];;
type ('a,'b) list_visitor = < caseNil : 'a; caseCons : 'b -> 'b list -> 'a >
type 'b alist = < visit : 'a. ('a,'b) list_visitor -> 'a >
[%%expect {|
type ('a, 'b) list_visitor = < caseCons : 'b -> 'b list -> 'a; caseNil : 'a >
type 'b alist = < visit : 'a. ('a, 'b) list_visitor -> 'a >
|}];;
PR#8074
class type ct = object ('s)
method fold : ('b -> 's -> 'b) -> 'b -> 'b
end
type t = {f : 'a 'b. ('b -> (#ct as 'a) -> 'b) -> 'b};;
[%%expect {|
class type ct = object ('a) method fold : ('b -> 'a -> 'b) -> 'b -> 'b end
type t = { f : 'a 'b. ('b -> (#ct as 'a) -> 'b) -> 'b; }
|}];;
PR#8124
type t = u and u = t;;
[%%expect {|
Line 1, characters 0-10:
1 | type t = u and u = t;;
^^^^^^^^^^
Error: The definition of t contains a cycle:
u
|}];;
PR#8188
class ['t] a = object constraint 't = [> `A of 't a] end
type t = [ `A of t a ];;
[%%expect {|
class ['a] a : object constraint 'a = [> `A of 'a a ] end
type t = [ `A of t a ]
|}];;
Wrong in 3.06
type ('a,'b) t constraint 'a = 'b and ('a,'b) u = ('a,'b) t;;
[%%expect {|
Line 1, characters 50-59:
1 | type ('a,'b) t constraint 'a = 'b and ('a,'b) u = ('a,'b) t;;
^^^^^^^^^
Error: Constraints are not satisfied in this type.
Type ('a, 'b) t should be an instance of ('c, 'c) t
|}];;
(* Full polymorphism if we do not expand *)
type 'a t = 'a and u = int t;;
[%%expect {|
type 'a t = 'a
and u = int t
|}];;
(* Loose polymorphism if we expand *)
type 'a t constraint 'a = int;;
type 'a u = 'a and 'a v = 'a u t;;
type 'a u = 'a and 'a v = 'a u t constraint 'a = int;;
[%%expect {|
type 'a t constraint 'a = int
Line 2, characters 26-32:
2 | type 'a u = 'a and 'a v = 'a u t;;
^^^^^^
Error: Constraints are not satisfied in this type.
Type 'a u t should be an instance of int t
|}];;
(* Behaviour is unstable *)
type g = int;;
type 'a t = unit constraint 'a = g;;
type 'a u = 'a and 'a v = 'a u t;;
type 'a u = 'a and 'a v = 'a u t constraint 'a = int;;
[%%expect {|
type g = int
type 'a t = unit constraint 'a = g
Line 3, characters 26-32:
3 | type 'a u = 'a and 'a v = 'a u t;;
^^^^^^
Error: Constraints are not satisfied in this type.
Type 'a u t should be an instance of g t
|}];;
(* Example of wrong expansion *)
type 'a u = < m : 'a v > and 'a v = 'a list u;;
[%%expect {|
Line 1, characters 0-24:
1 | type 'a u = < m : 'a v > and 'a v = 'a list u;;
^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition of v, type 'a list u should be 'a u
|}];;
(* PR#8198: Ctype.matches *)
type 'a t = 'a
type 'a u = A of 'a t;;
[%%expect {|
type 'a t = 'a
type 'a u = A of 'a t
|}];;
(* Unification of cyclic terms *)
type 'a t = < a : 'a >;;
fun (x : 'a t as 'a) -> (x : 'b t);;
type u = 'a t as 'a;;
[%%expect {|
type 'a t = < a : 'a >
- : ('a t as 'a) -> 'a t = <fun>
type u = 'a t as 'a
|}, Principal{|
type 'a t = < a : 'a >
- : ('a t as 'a) -> ('b t as 'b) t = <fun>
type u = 'a t as 'a
|}];;
(* pass typetexp, but fails during Typedecl.check_recursion *)
type ('a, 'b) a = 'a -> unit constraint 'a = [> `B of ('a, 'b) b as 'b]
and ('a, 'b) b = 'b -> unit constraint 'b = [> `A of ('a, 'b) a as 'a];;
[%%expect {|
Line 1, characters 0-71:
1 | type ('a, 'b) a = 'a -> unit constraint 'a = [> `B of ('a, 'b) b as 'b]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The definition of a contains a cycle:
[> `B of ('a, 'b) b as 'b ] as 'a
|}];;
: expanding may change original in Ctype.unify2
Note : since 3.11 , the abbreviations are not used when printing
a type where they occur recursively inside .
a type where they occur recursively inside. *)
class type ['a, 'b] a = object
method b: ('a, 'b) #b as 'b
method as_a: ('a, 'b) a
end and ['a, 'b] b = object
method a: ('a, 'b) #a as 'a
method as_b: ('a, 'b) b
end;;
[%%expect {|
class type ['a, 'b] a =
object
constraint 'a = < as_a : ('a, 'b) a as 'c; b : 'b; .. >
constraint 'b = < a : 'a; as_b : ('a, 'b) b; .. >
method as_a : 'c
method b : 'b
end
and ['a, 'b] b =
object
constraint 'a = < as_a : ('a, 'b) a; b : 'b; .. >
constraint 'b = < a : 'a; as_b : ('a, 'b) b; .. >
method a : 'a
method as_b : ('a, 'b) b
end
|}];;
class type ['b] ca = object ('s) inherit ['s, 'b] a end;;
class type ['a] cb = object ('s) inherit ['a, 's] b end;;
[%%expect {|
class type ['a] ca =
object ('b)
constraint 'a = < a : 'b; as_b : ('b, 'a) b; .. >
method as_a : ('b, 'a) a
method b : 'a
end
class type ['a] cb =
object ('b)
constraint 'a = < as_a : ('a, 'b) a; b : 'b; .. >
method a : 'a
method as_b : ('a, 'b) b
end
|}];;
type bt = 'b ca cb as 'b
;;
[%%expect {|
type bt = 'a ca cb as 'a
|}];;
(* final classes, etc... *)
class c = object method m = 1 end;;
let f () = object (self:c) method m = 1 end;;
let f () = object (self:c) method private n = 1 method m = self#n end;;
let f () = object method private n = 1 method m = {<>}#n end;;
let f () = object (self:c) method n = 1 method m = 2 end;;
let f () = object (_:'s) constraint 's = < n : int > method m = 1 end;;
class c = object (_ : 's)
method x = 1
method private m =
object (self: 's) method x = 3 method private m = self end
end;;
let o = object (_ : 's)
method x = 1
method private m =
object (self: 's) method x = 3 method private m = self end
end;;
[%%expect {|
class c : object method m : int end
val f : unit -> c = <fun>
val f : unit -> c = <fun>
Line 4, characters 11-60:
4 | let f () = object method private n = 1 method m = {<>}#n end;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 15: the following private methods were made public implicitly:
n.
val f : unit -> < m : int; n : int > = <fun>
Line 5, characters 11-56:
5 | let f () = object (self:c) method n = 1 method m = 2 end;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This object is expected to have type c but actually has type
< m : int; n : 'a >
The first object type has no method n
|}];;
(* Unsound! *)
fun (x : <m : 'a. 'a * <m: 'b. 'a * 'foo> > as 'foo) ->
(x : <m : 'a. 'a * (<m:'b. 'a * <m:'c. 'c * 'bar> > as 'bar) >);;
type 'a foo = <m: 'b. 'a * 'a foo>
type foo' = <m: 'a. 'a * 'a foo>
type 'a bar = <m: 'b. 'a * <m: 'c. 'c * 'a bar> >
type bar' = <m: 'a. 'a * 'a bar >
let f (x : foo') = (x : bar');;
[%%expect {|
Line 2, characters 3-4:
2 | (x : <m : 'a. 'a * (<m:'b. 'a * <m:'c. 'c * 'bar> > as 'bar) >);;
^
Error: This expression has type < m : 'a. 'a * < m : 'a * 'b > > as 'b
but an expression was expected of type
< m : 'a. 'a * (< m : 'a * < m : 'c. 'c * 'd > > as 'd) >
The method m has type
'a. 'a * (< m : 'a * < m : 'c. 'c * 'b > > as 'b),
but the expected method type was
'c. 'c * < m : 'a * < m : 'c. 'b > > as 'b
The universal variable 'a would escape its scope
|}];;
fun (x : <m : 'a. 'a * ('a * <m : 'a. 'a * 'foo> as 'foo)>) ->
(x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('c * 'bar)>)> as 'bar);;
fun (x : <m : 'a. 'a * ('a * <m : 'a. 'a * 'foo> as 'foo)>) ->
(x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('b * 'bar)>)> as 'bar);;
fun (x : <m : 'a. 'a * ('a * 'foo)> as 'foo) ->
(x : <m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)>);;
let f x =
(x : <m : 'a. 'a -> ('a * <m:'c. 'c -> 'bar> as 'bar)>
:> <m : 'a. 'a -> ('a * 'foo)> as 'foo);;
[%%expect {|
Line 2, characters 3-4:
2 | (x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('c * 'bar)>)> as 'bar);;
^
Error: This expression has type
< m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) >
but an expression was expected of type
< m : 'b. 'b * ('b * < m : 'c. 'c * ('c * 'd) >) > as 'd
Types for method m are incompatible
|}];;
module M
: sig val f : (<m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)>) -> unit end
= struct let f (x : <m : 'a. 'a * ('a * 'foo)> as 'foo) = () end;;
module M
: sig type t = <m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)> end
= struct type t = <m : 'a. 'a * ('a * 'foo)> as 'foo end;;
[%%expect {|
Line 3, characters 2-64:
3 | = struct let f (x : <m : 'a. 'a * ('a * 'foo)> as 'foo) = () end;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
sig val f : (< m : 'a. 'a * ('a * 'b) > as 'b) -> unit end
is not included in
sig
val f : < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) > -> unit
end
Values do not match:
val f : (< m : 'a. 'a * ('a * 'b) > as 'b) -> unit
is not included in
val f : < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) > -> unit
|}];;
module M : sig type 'a t type u = <m: 'a. 'a t> end
= struct type 'a t = int type u = <m: int> end;;
module M : sig type 'a t val f : <m: 'a. 'a t> -> int end
= struct type 'a t = int let f (x : <m:int>) = x#m end;;
(* The following should be accepted too! *)
module M : sig type 'a t val f : <m: 'a. 'a t> -> int end
= struct type 'a t = int let f x = x#m end;;
[%%expect {|
module M : sig type 'a t type u = < m : 'a. 'a t > end
module M : sig type 'a t val f : < m : 'a. 'a t > -> int end
module M : sig type 'a t val f : < m : 'a. 'a t > -> int end
|}];;
let f x y =
ignore (x :> <m:'a.'a -> 'c * < > > as 'c);
ignore (y :> <m:'b.'b -> 'd * < > > as 'd);
x = y;;
[%%expect {|
val f :
(< m : 'a. 'a -> (< m : 'a. 'a -> 'c * < > > as 'c) * < .. >; .. > as 'b) ->
'b -> bool = <fun>
|}];;
(* Subtyping *)
type t = [`A|`B];;
type v = private [> t];;
fun x -> (x : t :> v);;
type u = private [< t];;
fun x -> (x : u :> v);;
fun x -> (x : v :> u);;
type v = private [< t];;
fun x -> (x : u :> v);;
type p = <x:p>;;
type q = private <x:p; ..>;;
fun x -> (x : q :> p);;
fun x -> (x : p :> q);;
[%%expect {|
type t = [ `A | `B ]
type v = private [> t ]
- : t -> v = <fun>
type u = private [< t ]
- : u -> v = <fun>
Line 6, characters 9-21:
6 | fun x -> (x : v :> u);;
^^^^^^^^^^^^
Error: Type v = [> `A | `B ] is not a subtype of u = [< `A | `B ]
|}];;
let f1 x =
(x : <m:'a. (<p:int;..> as 'a) -> int>
:> <m:'b. (<p:int;q:int;..> as 'b) -> int>);;
let f2 x =
(x : <m:'a. (<p:<a:int>;..> as 'a) -> int>
:> <m:'b. (<p:<a:int;b:int>;..> as 'b) -> int>);;
let f3 x =
(x : <m:'a. (<p:<a:int;b:int>;..> as 'a) -> int>
:> <m:'b. (<p:<a:int>;..> as 'b) -> int>);;
let f4 x = (x : <p:<a:int;b:int>;..> :> <p:<a:int>;..>);;
let f5 x =
(x : <m:'a. [< `A of <p:int> ] as 'a> :> <m:'a. [< `A of < > ] as 'a>);;
let f6 x =
(x : <m:'a. [< `A of < > ] as 'a> :> <m:'a. [< `A of <p:int> ] as 'a>);;
[%%expect {|
Lines 2-3, characters 2-47:
2 | ..(x : <m:'a. (<p:int;..> as 'a) -> int>
3 | :> <m:'b. (<p:int;q:int;..> as 'b) -> int>)..
Error: Type < m : 'a. (< p : int; .. > as 'a) -> int > is not a subtype of
< m : 'b. (< p : int; q : int; .. > as 'b) -> int >
Type < p : int; q : int; .. > as 'c is not a subtype of
< p : int; .. > as 'd
|}];;
(* Keep sharing the epsilons *)
let f x = if true then (x : < m : 'a. 'a -> 'a >) else x;;
Warning 18
let f (x, y) = if true then (x : < m : 'a. 'a -> 'a >) else x;;
Warning 18
let f x = if true then [| (x : < m : 'a. 'a -> 'a >) |] else [|x|];;
Warning 18
[%%expect {|
val f : < m : 'a. 'a -> 'a > -> < m : 'a. 'a -> 'a > = <fun>
- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
val f : < m : 'a. 'a -> 'a > * 'b -> < m : 'a. 'a -> 'a > = <fun>
- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
val f : < m : 'a. 'a -> 'a > -> < m : 'a. 'a -> 'a > array = <fun>
- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
|}, Principal{|
val f : < m : 'a. 'a -> 'a > -> < m : 'a. 'a -> 'a > = <fun>
Line 2, characters 9-16:
Warning 18
^^^^^^^
Warning 18: this use of a polymorphic method is not principal.
- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
val f : < m : 'a. 'a -> 'a > * 'b -> < m : 'a. 'a -> 'a > = <fun>
Line 4, characters 9-20:
Warning 18
^^^^^^^^^^^
Warning 18: this use of a polymorphic method is not principal.
- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
val f : < m : 'a. 'a -> 'a > -> < m : 'a. 'a -> 'a > array = <fun>
Line 6, characters 9-20:
Warning 18
^^^^^^^^^^^
Warning 18: this use of a polymorphic method is not principal.
- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
|}];;
(* Not really principal? *)
class c = object method id : 'a. 'a -> 'a = fun x -> x end;;
type u = c option;;
let just = function None -> failwith "just" | Some x -> x;;
let f x = let l = [Some x; (None : u)] in (just(List.hd l))#id;;
let g x =
let none = (fun y -> ignore [y;(None:u)]; y) None in
let x = List.hd [Some x; none] in (just x)#id;;
let h x =
let none = let y = None in ignore [y;(None:u)]; y in
let x = List.hd [Some x; none] in (just x)#id;;
[%%expect {|
class c : object method id : 'a -> 'a end
type u = c option
val just : 'a option -> 'a = <fun>
val f : c -> 'a -> 'a = <fun>
val g : c -> 'a -> 'a = <fun>
val h : < id : 'a; .. > -> 'a = <fun>
|}, Principal{|
class c : object method id : 'a -> 'a end
type u = c option
val just : 'a option -> 'a = <fun>
Line 4, characters 42-62:
4 | let f x = let l = [Some x; (None : u)] in (just(List.hd l))#id;;
^^^^^^^^^^^^^^^^^^^^
Warning 18: this use of a polymorphic method is not principal.
val f : c -> 'a -> 'a = <fun>
Line 7, characters 36-47:
7 | let x = List.hd [Some x; none] in (just x)#id;;
^^^^^^^^^^^
Warning 18: this use of a polymorphic method is not principal.
val g : c -> 'a -> 'a = <fun>
val h : < id : 'a; .. > -> 'a = <fun>
|}];;
(* Only solved for parameterless abbreviations *)
type 'a u = c option;;
let just = function None -> failwith "just" | Some x -> x;;
let f x = let l = [Some x; (None : _ u)] in (just(List.hd l))#id;;
[%%expect {|
type 'a u = c option
val just : 'a option -> 'a = <fun>
val f : c -> 'a -> 'a = <fun>
|}];;
(* polymorphic recursion *)
let rec f : 'a. 'a -> _ = fun x -> 1 and g x = f x;;
type 'a t = Leaf of 'a | Node of ('a * 'a) t;;
let rec depth : 'a. 'a t -> _ =
function Leaf _ -> 1 | Node x -> 1 + depth x;;
let rec depth : 'a. 'a t -> _ =
function Leaf _ -> 1 | Node x -> 1 + d x
and d x = depth x;; (* fails *)
let rec depth : 'a. 'a t -> _ =
function Leaf x -> x | Node x -> 1 + depth x;; (* fails *)
let rec depth : 'a. 'a t -> _ =
function Leaf x -> x | Node x -> depth x;; (* fails *)
let rec depth : 'a 'b. 'a t -> 'b =
function Leaf x -> x | Node x -> depth x;; (* fails *)
let rec r : 'a. 'a list * 'b list ref = [], ref []
and q () = r;;
let f : 'a. _ -> _ = fun x -> x;;
let zero : 'a. [> `Int of int | `B of 'a] as 'a = `Int 0;; (* ok *)
let zero : 'a. [< `Int of int] as 'a = `Int 0;; (* fails *)
[%%expect {|
val f : 'a -> int = <fun>
val g : 'a -> int = <fun>
type 'a t = Leaf of 'a | Node of ('a * 'a) t
val depth : 'a t -> int = <fun>
Line 6, characters 2-42:
6 | function Leaf _ -> 1 | Node x -> 1 + d x
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This definition has type 'a t -> int which is less general than
'a0. 'a0 t -> int
|}];;
(* compare with records (should be the same) *)
type t = {f: 'a. [> `Int of int | `B of 'a] as 'a}
let zero = {f = `Int 0} ;;
type t = {f: 'a. [< `Int of int] as 'a}
let zero = {f = `Int 0} ;; (* fails *)
[%%expect {|
type t = { f : 'a. [> `B of 'a | `Int of int ] as 'a; }
val zero : t = {f = `Int 0}
type t = { f : 'a. [< `Int of int ] as 'a; }
Line 4, characters 16-22:
4 | let zero = {f = `Int 0} ;; (* fails *)
^^^^^^
Error: This expression has type [> `Int of int ]
but an expression was expected of type [< `Int of int ]
The second variant type is bound to the universal type variable 'a,
it may not allow the tag(s) `Int
|}];;
(* Yet another example *)
let rec id : 'a. 'a -> 'a = fun x -> x
and neg i b = (id (-i), id (not b));;
[%%expect {|
val id : 'a -> 'a = <fun>
val neg : int -> bool -> int * bool = <fun>
|}];;
type t = A of int | B of (int*t) list | C of (string*t) list
[%%expect {|
type t = A of int | B of (int * t) list | C of (string * t) list
|}];;
let rec transf f = function
| A x -> f x
| B l -> B (transf_alist f l)
| C l -> C (transf_alist f l)
and transf_alist : 'a. _ -> ('a*t) list -> ('a*t) list = fun f -> function
| [] -> []
| (k,v)::tl -> (k, transf f v) :: transf_alist f tl
;;
[%%expect {|
val transf : (int -> t) -> t -> t = <fun>
val transf_alist : (int -> t) -> ('a * t) list -> ('a * t) list = <fun>
|}];;
(* PR#4862 *)
type t = {f: 'a. ('a list -> int) Lazy.t}
let l : t = { f = lazy (raise Not_found)};;
[%%expect {|
type t = { f : 'a. ('a list -> int) Lazy.t; }
val l : t = {f = <lazy>}
|}];;
(* variant *)
type t = {f: 'a. 'a -> unit};;
let f ?x y = () in {f};;
let f ?x y = y in {f};; (* fail *)
[%%expect {|
type t = { f : 'a. 'a -> unit; }
- : t = {f = <fun>}
Line 3, characters 19-20:
3 | let f ?x y = y in {f};; (* fail *)
^
Error: This field value has type unit -> unit which is less general than
'a. 'a -> unit
|}];;
Polux Moon caml - list 2011 - 07 - 26
module Polux = struct
type 'par t = 'par
let ident v = v
class alias = object method alias : 'a . 'a t -> 'a = ident end
let f (x : <m : 'a. 'a t>) = (x : <m : 'a. 'a>)
end;;
[%%expect {|
module Polux :
sig
type 'par t = 'par
val ident : 'a -> 'a
class alias : object method alias : 'a t -> 'a end
val f : < m : 'a. 'a t > -> < m : 'a. 'a >
end
|}];;
(* PR#5560 *)
let (a, b) = (raise Exit : int * int);;
type t = { foo : int }
let {foo} = (raise Exit : t);;
type s = A of int
let (A x) = (raise Exit : s);;
[%%expect {|
Exception: Stdlib.Exit.
|}];;
PR#5224
type 'x t = < f : 'y. 'y t >;;
[%%expect {|
Line 1, characters 0-28:
1 | type 'x t = < f : 'y. 'y t >;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition of t, type 'y t should be 'x t
|}];;
(* PR#6056, PR#6057 *)
let using_match b =
let f =
match b with
| true -> fun x -> x
| false -> fun x -> x
in
f 0,f
;;
[%%expect {|
val using_match : bool -> int * ('a -> 'a) = <fun>
|}];;
match (fun x -> x), fun x -> x with x, y -> x, y;;
match fun x -> x with x -> x, x;;
[%%expect {|
- : ('a -> 'a) * ('b -> 'b) = (<fun>, <fun>)
- : ('a -> 'a) * ('b -> 'b) = (<fun>, <fun>)
|}];;
(* PR#6747 *)
(* ok *)
let n = object
method m : 'x 'o. ([< `Foo of 'x] as 'o) -> 'x = fun x -> assert false
end;;
[%%expect {|
val n : < m : 'x 'a. ([< `Foo of 'x ] as 'a) -> 'x > = <obj>
|}];;
(* ok *)
let n =
object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
[%%expect {|
val n : < m : 'x. [< `Foo of 'x ] -> 'x > = <obj>
|}];;
(* fail *)
let (n : < m : 'a. [< `Foo of int] -> 'a >) =
object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
[%%expect {|
Line 2, characters 2-72:
2 | object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This expression has type < m : 'x. [< `Foo of 'x ] -> 'x >
but an expression was expected of type
< m : 'a. [< `Foo of int ] -> 'a >
The universal variable 'x would escape its scope
|}];;
(* fail *)
let (n : 'b -> < m : 'a . ([< `Foo of int] as 'b) -> 'a >) = fun x ->
object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
[%%expect {|
Line 2, characters 2-72:
2 | object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This expression has type < m : 'x. [< `Foo of 'x ] -> 'x >
but an expression was expected of type
< m : 'a. [< `Foo of int ] -> 'a >
The universal variable 'x would escape its scope
|}];;
(* PR#6171 *)
let f b (x: 'x) =
let module M = struct type t = A end in
if b then x else M.A;;
[%%expect {|
Line 3, characters 19-22:
3 | if b then x else M.A;;
^^^
Error: This expression has type M.t but an expression was expected of type 'x
The type constructor M.t would escape its scope
|}];;
(* PR#6987 *)
type 'a t = V1 of 'a
type ('c,'t) pvariant = [ `V of ('c * 't t) ]
class ['c] clss =
object
method mthod : 't . 'c -> 't t -> ('c, 't) pvariant = fun c x ->
`V (c, x)
end;;
let f2 = fun o c x -> match x with | V1 _ -> x
let rec f1 o c x =
match (o :> _ clss)#mthod c x with
| `V c -> f2 o c x;;
[%%expect{|
type 'a t = V1 of 'a
type ('c, 't) pvariant = [ `V of 'c * 't t ]
class ['c] clss : object method mthod : 'c -> 't t -> ('c, 't) pvariant end
val f2 : 'a -> 'b -> 'c t -> 'c t = <fun>
val f1 :
< mthod : 't. 'a -> 't t -> [< `V of 'a * 't t ]; .. > ->
'a -> 'b t -> 'b t = <fun>
|}]
PR#7285
type (+'a,-'b) foo = private int;;
let f (x : int) : ('a,'a) foo = Obj.magic x;;
let x = f 3;;
[%%expect{|
type (+'a, -'b) foo = private int
val f : int -> ('a, 'a) foo = <fun>
val x : ('_weak1, '_weak1) foo = 3
|}]
(* PR#7344*)
let rec f : unit -> < m: 'a. 'a -> 'a> = fun () ->
let x = f () in
ignore (x#m 1);
ignore (x#m "hello");
assert false;;
[%%expect{|
val f : unit -> < m : 'a. 'a -> 'a > = <fun>
|}]
(* PR#7395 *)
type u
type 'a t = u;;
let c (f : u -> u) =
object
method apply: 'a. 'a t -> 'a t = fun x -> f x
end;;
[%%expect{|
type u
type 'a t = u
val c : (u -> u) -> < apply : 'a. u -> u > = <fun>
|}]
PR#7496
let f (x : < m: 'a. ([< `Foo of int & float] as 'a) -> unit>)
: < m: 'a. ([< `Foo of int & float] as 'a) -> unit> = x;;
type t = { x : 'a. ([< `Foo of int & float ] as 'a) -> unit };;
let f t = { x = t.x };;
[%%expect{|
val f :
< m : 'a. ([< `Foo of int & float ] as 'a) -> unit > ->
< m : 'b. ([< `Foo of int & float ] as 'b) -> unit > = <fun>
type t = { x : 'a. ([< `Foo of int & float ] as 'a) -> unit; }
val f : t -> t = <fun>
|}]
type t = <m:int>
type g = <n:string; t>
type h = <x:string; y:int; g>
[%%expect{|
type t = < m : int >
type g = < m : int; n : string >
type h = < m : int; n : string; x : string; y : int >
|}]
type t = <g>
and g = <a:t>
[%%expect{|
Line 1, characters 10-11:
1 | type t = <g>
^
Error: The type constructor g is not yet completely defined
|}]
type t = int
type g = <t>
[%%expect{|
type t = int
Line 2, characters 10-11:
2 | type g = <t>
^
Error: The type int is not an object type
|}]
type t = <a:int>
type g = <t; t; t;>
[%%expect{|
type t = < a : int >
type g = < a : int >
|}]
type c = <a:int; d:string>
let s:c = object method a=1; method d="123" end
[%%expect{|
type c = < a : int; d : string >
val s : c = <obj>
|}]
type 'a t = < m: 'a >
type s = < int t >
module M = struct type t = < m: int > end
type u = < M.t >
type r = < a : int; < b : int > >
type e = < >
type r1 = < a : int; e >
type r2 = < a : int; < < < > > > >
[%%expect{|
type 'a t = < m : 'a >
type s = < m : int >
module M : sig type t = < m : int > end
type u = < m : int >
type r = < a : int; b : int >
type e = < >
type r1 = < a : int >
type r2 = < a : int >
|}]
type gg = <a:int->float; a:int>
[%%expect{|
Line 1, characters 27-30:
1 | type gg = <a:int->float; a:int>
^^^
Error: Method 'a' has type int, which should be int -> float
|}]
type t = <a:int; b:string>
type g = <b:float; t;>
[%%expect{|
type t = < a : int; b : string >
Line 2, characters 19-20:
2 | type g = <b:float; t;>
^
Error: Method 'b' has type string, which should be float
|}]
module A = struct
class type ['a] t1 = object method f : 'a end
end
type t = < int A.t1 >
[%%expect{|
module A : sig class type ['a] t1 = object method f : 'a end end
type t = < f : int >
|}]
type t = < int #A.t1 >
[%%expect{|
Line 1, characters 11-20:
1 | type t = < int #A.t1 >
^^^^^^^^^
Error: Illegal open object type
|}]
let g = fun (y : ('a * 'b)) x -> (x : < <m: 'a> ; <m: 'b> >)
[%%expect{|
val g : 'a * 'a -> < m : 'a > -> < m : 'a > = <fun>
|}]
type 'a t = <m: 'a ; m: int>
[%%expect{|
type 'a t = < m : 'a > constraint 'a = int
|}]
GPR#1142
external reraise : exn -> 'a = "%reraise"
module M () = struct
let f : 'a -> 'a = assert false
let g : 'a -> 'a = raise Not_found
let h : 'a -> 'a = reraise Not_found
let i : 'a -> 'a = raise_notrace Not_found
end
[%%expect{|
external reraise : exn -> 'a = "%reraise"
module M :
functor () ->
sig
val f : 'a -> 'a
val g : 'a -> 'a
val h : 'a -> 'a
val i : 'a -> 'a
end
|}]
# 8550
class ['a] r = let r : 'a = ref [] in object method get = r end;;
[%%expect{|
Line 1, characters 0-63:
1 | class ['a] r = let r : 'a = ref [] in object method get = r end;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The type of this class,
class ['a] r :
object constraint 'a = '_weak2 list ref method get : 'a end,
contains type variables that cannot be generalized
|}]
# 8701
type 'a t = 'a constraint 'a = 'b list;;
type 'a s = 'a list;;
let id x = x;;
[%%expect{|
type 'a t = 'a constraint 'a = 'b list
type 'a s = 'a list
val id : 'a -> 'a = <fun>
|}]
let x : [ `Foo of _ s | `Foo of 'a t ] = id (`Foo []);;
[%%expect{|
val x : [ `Foo of 'a s ] = `Foo []
|}]
let x : [ `Foo of 'a t | `Foo of _ s ] = id (`Foo []);;
[%%expect{|
val x : [ `Foo of 'a list t ] = `Foo []
|}]
(* generalize spine of inherited methods too *)
class c = object (self) method m ?(x=0) () = x method n = self#m () end;;
class d = object (self) inherit c method n' = self#m () end;;
[%%expect{|
class c : object method m : ?x:int -> unit -> int method n : int end
class d :
object method m : ?x:int -> unit -> int method n : int method n' : int end
|}]
| null | https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/testsuite/tests/typing-poly/poly.ml | ocaml | TEST
* expect
Polymorphic methods are now available in the main branch.
Enjoy.
Tests for explicit polymorphism
printer is wrong on the next (no official syntax)
Type variable scope
use before instancing
various old bugs
Full polymorphism if we do not expand
Loose polymorphism if we expand
Behaviour is unstable
Example of wrong expansion
PR#8198: Ctype.matches
Unification of cyclic terms
pass typetexp, but fails during Typedecl.check_recursion
final classes, etc...
Unsound!
The following should be accepted too!
Subtyping
Keep sharing the epsilons
Not really principal?
Only solved for parameterless abbreviations
polymorphic recursion
fails
fails
fails
fails
ok
fails
compare with records (should be the same)
fails
fails
Yet another example
PR#4862
variant
fail
fail
PR#5560
PR#6056, PR#6057
PR#6747
ok
ok
fail
fail
PR#6171
PR#6987
PR#7344
PR#7395
generalize spine of inherited methods too |
open StdLabels;;
type 'a t = { t : 'a };;
type 'a fold = { fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b };;
let f l = { fold = List.fold_left l };;
(f [1;2;3]).fold ~f:(+) ~init:0;;
[%%expect {|
type 'a t = { t : 'a; }
type 'a fold = { fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b; }
val f : 'a list -> 'a fold = <fun>
- : int = 6
|}];;
type pty = {pv : 'a. 'a list};;
[%%expect {|
type pty = { pv : 'a. 'a list; }
|}];;
type id = { id : 'a. 'a -> 'a };;
let id x = x;;
let {id} = id { id };;
[%%expect {|
type id = { id : 'a. 'a -> 'a; }
val id : 'a -> 'a = <fun>
val id : 'a -> 'a = <fun>
|}];;
let px = {pv = []};;
[%%expect {|
val px : pty = {pv = []}
|}];;
match px with
| {pv=[]} -> "OK"
| {pv=5::_} -> "int"
| {pv=true::_} -> "bool"
;;
[%%expect {|
Lines 1-4, characters 0-24:
1 | match px with
2 | | {pv=[]} -> "OK"
3 | | {pv=5::_} -> "int"
4 | | {pv=true::_} -> "bool"
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
{pv=false::_}
- : string = "OK"
|}];;
match px with
| {pv=[]} -> "OK"
| {pv=true::_} -> "bool"
| {pv=5::_} -> "int"
;;
[%%expect {|
Lines 1-4, characters 0-20:
1 | match px with
2 | | {pv=[]} -> "OK"
3 | | {pv=true::_} -> "bool"
4 | | {pv=5::_} -> "int"
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
{pv=0::_}
- : string = "OK"
|}];;
match px with
| {pv=[]} -> "OK"
| {pv=5::_} -> "int"
| {pv=true::_} -> "bool"
| {pv=false::_} -> "bool"
;;
[%%expect {|
- : string = "OK"
|}];;
fun {pv=v} -> true::v, 1::v;;
[%%expect {|
- : pty -> bool list * int list = <fun>
|}];;
class ['b] ilist l = object
val l = l
method add x = {< l = x :: l >}
method fold : 'a. f:('a -> 'b -> 'a) -> init:'a -> 'a =
List.fold_left l
end
;;
[%%expect {|
class ['b] ilist :
'b list ->
object ('c)
val l : 'b list
method add : 'b -> 'c
method fold : f:('a -> 'b -> 'a) -> init:'a -> 'a
end
|}];;
class virtual ['a] vlist = object (_ : 'self)
method virtual add : 'a -> 'self
method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
end
;;
[%%expect {|
class virtual ['a] vlist :
object ('c)
method virtual add : 'a -> 'c
method virtual fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
end
|}];;
class ilist2 l = object
inherit [int] vlist
val l = l
method add x = {< l = x :: l >}
method fold = List.fold_left l
end
;;
[%%expect {|
class ilist2 :
int list ->
object ('a)
val l : int list
method add : int -> 'a
method fold : f:('b -> int -> 'b) -> init:'b -> 'b
end
|}];;
let ilist2 l = object
inherit [_] vlist
val l = l
method add x = {< l = x :: l >}
method fold = List.fold_left l
end
;;
[%%expect {|
val ilist2 : 'a list -> 'a vlist = <fun>
|}];;
class ['a] ilist3 l = object
inherit ['a] vlist
val l = l
method add x = {< l = x :: l >}
method fold = List.fold_left l
end
;;
[%%expect {|
class ['a] ilist3 :
'a list ->
object ('c)
val l : 'a list
method add : 'a -> 'c
method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
end
|}];;
class ['a] ilist4 (l : 'a list) = object
val l = l
method virtual add : _
method add x = {< l = x :: l >}
method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
method fold = List.fold_left l
end
;;
[%%expect {|
class ['a] ilist4 :
'a list ->
object ('c)
val l : 'a list
method add : 'a -> 'c
method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
end
|}];;
class ['a] ilist5 (l : 'a list) = object (self)
val l = l
method add x = {< l = x :: l >}
method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
method virtual fold2 : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
method fold2 ~f ~init = self#fold ~f ~init:(self#fold ~f ~init)
method fold = List.fold_left l
end
;;
[%%expect {|
class ['a] ilist5 :
'a list ->
object ('c)
val l : 'a list
method add : 'a -> 'c
method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
method fold2 : f:('b -> 'a -> 'b) -> init:'b -> 'b
end
|}];;
class ['a] ilist6 l = object (self)
inherit ['a] vlist
val l = l
method add x = {< l = x :: l >}
method virtual fold2 : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
method fold2 ~f ~init = self#fold ~f ~init:(self#fold ~f ~init)
method fold = List.fold_left l
end
;;
[%%expect {|
class ['a] ilist6 :
'a list ->
object ('c)
val l : 'a list
method add : 'a -> 'c
method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
method fold2 : f:('b -> 'a -> 'b) -> init:'b -> 'b
end
|}];;
class virtual ['a] olist = object
method virtual fold : 'c. f:('a -> 'c -> 'c) -> init:'c -> 'c
end
;;
[%%expect {|
class virtual ['a] olist :
object method virtual fold : f:('a -> 'c -> 'c) -> init:'c -> 'c end
|}];;
class ['a] onil = object
inherit ['a] olist
method fold ~f ~init = init
end
;;
[%%expect {|
class ['a] onil :
object method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c end
|}];;
class ['a] ocons ~hd ~tl = object (_ : 'b)
inherit ['a] olist
val hd : 'a = hd
val tl : 'a olist = tl
method fold ~f ~init = f hd (tl#fold ~f ~init)
end
;;
[%%expect {|
class ['a] ocons :
hd:'a ->
tl:'a olist ->
object
val hd : 'a
val tl : 'a olist
method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c
end
|}];;
class ['a] ostream ~hd ~tl = object (_ : 'b)
inherit ['a] olist
val hd : 'a = hd
val tl : _ #olist = (tl : 'a ostream)
method fold ~f ~init = f hd (tl#fold ~f ~init)
method empty = false
end
;;
[%%expect {|
class ['a] ostream :
hd:'a ->
tl:'a ostream ->
object
val hd : 'a
val tl : < empty : bool; fold : 'c. f:('a -> 'c -> 'c) -> init:'c -> 'c >
method empty : bool
method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c
end
|}];;
class ['a] ostream1 ~hd ~tl = object (self : 'b)
inherit ['a] olist
val hd = hd
val tl : 'b = tl
method hd = hd
method tl = tl
method fold ~f ~init =
self#tl#fold ~f ~init:(f self#hd init)
end
[%%expect {|
class ['a] ostream1 :
hd:'a ->
tl:'b ->
object ('b)
val hd : 'a
val tl : 'b
method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c
method hd : 'a
method tl : 'b
end
|}, Principal{|
Line 8, characters 4-16:
8 | self#tl#fold ~f ~init:(f self#hd init)
^^^^^^^^^^^^
Warning 18: this use of a polymorphic method is not principal.
class ['a] ostream1 :
hd:'a ->
tl:'b ->
object ('b)
val hd : 'a
val tl : 'b
method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c
method hd : 'a
method tl : 'b
end
|}];;
class vari = object
method virtual m : 'a. ([< `A|`B|`C] as 'a) -> int
method m = function `A -> 1 | `B|`C -> 0
end
;;
[%%expect {|
class vari : object method m : [< `A | `B | `C ] -> int end
|}];;
class vari = object
method m : 'a. ([< `A|`B|`C] as 'a) -> int = function `A -> 1 | `B|`C -> 0
end
;;
[%%expect {|
class vari : object method m : [< `A | `B | `C ] -> int end
|}];;
module V =
struct
type v = [`A | `B | `C]
let m : [< v] -> int = function `A -> 1 | #v -> 0
end
;;
[%%expect {|
module V : sig type v = [ `A | `B | `C ] val m : [< v ] -> int end
|}];;
class varj = object
method virtual m : 'a. ([< V.v] as 'a) -> int
method m = V.m
end
;;
[%%expect {|
class varj : object method m : [< V.v ] -> int end
|}];;
module type T = sig
class vari : object method m : 'a. ([< `A | `B | `C] as 'a) -> int end
end
;;
[%%expect {|
module type T =
sig class vari : object method m : [< `A | `B | `C ] -> int end end
|}];;
module M0 = struct
class vari = object
method virtual m : 'a. ([< `A|`B|`C] as 'a) -> int
method m = function `A -> 1 | `B|`C -> 0
end
end
;;
[%%expect {|
module M0 :
sig class vari : object method m : [< `A | `B | `C ] -> int end end
|}];;
module M : T = M0
;;
[%%expect {|
module M : T
|}];;
let v = new M.vari;;
[%%expect {|
val v : M.vari = <obj>
|}];;
v#m `A;;
[%%expect {|
- : int = 1
|}];;
class point ~x ~y = object
val x : int = x
val y : int = y
method x = x
method y = y
end
;;
[%%expect {|
class point :
x:int ->
y:int -> object val x : int val y : int method x : int method y : int end
|}];;
class color_point ~x ~y ~color = object
inherit point ~x ~y
val color : string = color
method color = color
end
;;
[%%expect {|
class color_point :
x:int ->
y:int ->
color:string ->
object
val color : string
val x : int
val y : int
method color : string
method x : int
method y : int
end
|}];;
class circle (p : #point) ~r = object
val p = (p :> point)
val r = r
method virtual distance : 'a. (#point as 'a) -> float
method distance p' =
let dx = p#x - p'#x and dy = p#y - p'#y in
let d = sqrt (float (dx * dx + dy * dy)) -. float r in
if d < 0. then 0. else d
end
;;
[%%expect {|
class circle :
#point ->
r:int ->
object val p : point val r : int method distance : #point -> float end
|}];;
let p0 = new point ~x:3 ~y:5
let p1 = new point ~x:10 ~y:13
let cp = new color_point ~x:12 ~y:(-5) ~color:"green"
let c = new circle p0 ~r:2
let d = floor (c#distance cp)
;;
let f (x : < m : 'a. 'a -> 'a >) = (x : < m : 'b. 'b -> 'b >)
;;
let f (x : < m : 'a. 'a -> 'a list >) = (x : < m : 'b. 'b -> 'c >)
;;
[%%expect {|
val p0 : point = <obj>
val p1 : point = <obj>
val cp : color_point = <obj>
val c : circle = <obj>
val d : float = 11.
val f : < m : 'a. 'a -> 'a > -> < m : 'b. 'b -> 'b > = <fun>
Line 9, characters 41-42:
9 | let f (x : < m : 'a. 'a -> 'a list >) = (x : < m : 'b. 'b -> 'c >)
^
Error: This expression has type < m : 'b. 'b -> 'b list >
but an expression was expected of type < m : 'b. 'b -> 'c >
The method m has type 'b. 'b -> 'b list,
but the expected method type was 'b. 'b -> 'c
The universal variable 'b would escape its scope
|}];;
class id = object
method virtual id : 'a. 'a -> 'a
method id x = x
end
;;
[%%expect {|
class id : object method id : 'a -> 'a end
|}];;
class type id_spec = object
method id : 'a -> 'a
end
;;
[%%expect {|
class type id_spec = object method id : 'a -> 'a end
|}];;
class id_impl = object (_ : #id_spec)
method id x = x
end
;;
[%%expect {|
class id_impl : object method id : 'a -> 'a end
|}];;
class a = object
method m = (new b : id_spec)#id true
end
and b = object (_ : #id_spec)
method id x = x
end
;;
[%%expect {|
class a : object method m : bool end
and b : object method id : 'a -> 'a end
|}];;
class ['a] id1 = object
method virtual id : 'b. 'b -> 'a
method id x = x
end
;;
[%%expect {|
Line 3, characters 12-17:
3 | method id x = x
^^^^^
Error: This method has type 'a -> 'a which is less general than 'b. 'b -> 'a
|}];;
class id2 (x : 'a) = object
method virtual id : 'b. 'b -> 'a
method id x = x
end
;;
[%%expect {|
Line 3, characters 12-17:
3 | method id x = x
^^^^^
Error: This method has type 'a -> 'a which is less general than 'b. 'b -> 'a
|}];;
class id3 x = object
val x = x
method virtual id : 'a. 'a -> 'a
method id _ = x
end
;;
[%%expect {|
Line 4, characters 12-17:
4 | method id _ = x
^^^^^
Error: This method has type 'b -> 'b which is less general than 'a. 'a -> 'a
|}];;
class id4 () = object
val mutable r = None
method virtual id : 'a. 'a -> 'a
method id x =
match r with
None -> r <- Some x; x
| Some y -> y
end
;;
[%%expect {|
Lines 4-7, characters 12-17:
4 | ............x =
5 | match r with
6 | None -> r <- Some x; x
7 | | Some y -> y
Error: This method has type 'b -> 'b which is less general than 'a. 'a -> 'a
|}];;
class c = object
method virtual m : 'a 'b. 'a -> 'b -> 'a
method m x y = x
end
;;
[%%expect {|
class c : object method m : 'a -> 'b -> 'a end
|}];;
let f1 (f : id) = f#id 1, f#id true
;;
let f2 f = (f : id)#id 1, (f : id)#id true
;;
let f3 f = f#id 1, f#id true
;;
let f4 f = ignore(f : id); f#id 1, f#id true
;;
[%%expect {|
val f1 : id -> int * bool = <fun>
val f2 : id -> int * bool = <fun>
Line 5, characters 24-28:
5 | let f3 f = f#id 1, f#id true
^^^^
Error: This expression has type bool but an expression was expected of type
int
|}];;
class c = object
method virtual m : 'a. (#id as 'a) -> int * bool
method m (f : #id) = f#id 1, f#id true
end
;;
[%%expect {|
class c : object method m : #id -> int * bool end
|}];;
class id2 = object (_ : 'b)
method virtual id : 'a. 'a -> 'a
method id x = x
method mono (x : int) = x
end
;;
let app = new c #m (new id2)
;;
type 'a foo = 'a foo list
;;
[%%expect {|
class id2 : object method id : 'a -> 'a method mono : int -> int end
val app : int * bool = (1, true)
Line 9, characters 0-25:
9 | type 'a foo = 'a foo list
^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The type abbreviation foo is cyclic
|}];;
class ['a] bar (x : 'a) = object end
;;
type 'a foo = 'a foo bar
;;
[%%expect {|
class ['a] bar : 'a -> object end
type 'a foo = 'a foo bar
|}];;
fun x -> (x : < m : 'a. 'a * 'b > as 'b)#m;;
fun x -> (x : < m : 'a. 'b * 'a list> as 'b)#m;;
let f x = (x : < m : 'a. 'b * (< n : 'a; .. > as 'a) > as 'b)#m;;
fun (x : < p : 'a. < m : 'a ; n : 'b ; .. > as 'a > as 'b) -> x#p;;
fun (x : <m:'a. 'a * <p:'b. 'b * 'c * 'd> as 'c> as 'd) -> x#m;;
fun (x : <m:'a.<p:'a;..> >) -> x#m;;
[%%expect {|
- : (< m : 'a. 'a * 'b > as 'b) -> 'c * 'b = <fun>
- : (< m : 'a. 'b * 'a list > as 'b) -> 'b * 'c list = <fun>
val f :
(< m : 'b. 'a * (< n : 'b; .. > as 'b) > as 'a) ->
'a * (< n : 'c; .. > as 'c) = <fun>
- : (< p : 'b. < m : 'b; n : 'a; .. > as 'b > as 'a) ->
(< m : 'c; n : 'a; .. > as 'c)
= <fun>
- : (< m : 'a. 'a * < p : 'b. 'b * 'd * 'c > as 'd > as 'c) ->
('f * < p : 'b. 'b * 'e * 'c > as 'e)
= <fun>
- : < m : 'a. < p : 'a; .. > as 'b > -> 'b = <fun>
|}, Principal{|
- : (< m : 'a. 'a * 'b > as 'b) -> 'c * (< m : 'a. 'a * 'd > as 'd) = <fun>
- : (< m : 'a. 'b * 'a list > as 'b) ->
(< m : 'a. 'c * 'a list > as 'c) * 'd list
= <fun>
val f :
(< m : 'b. 'a * (< n : 'b; .. > as 'b) > as 'a) ->
(< m : 'd. 'c * (< n : 'd; .. > as 'd) > as 'c) * (< n : 'e; .. > as 'e) =
<fun>
- : (< p : 'b. < m : 'b; n : 'a; .. > as 'b > as 'a) ->
(< m : 'c; n : < p : 'e. < m : 'e; n : 'd; .. > as 'e > as 'd; .. > as 'c)
= <fun>
- : (< m : 'a. 'a * < p : 'b. 'b * 'd * 'c > as 'd > as 'c) ->
('f *
< p : 'b.
'b * 'e *
(< m : 'a. 'a * < p : 'b0. 'b0 * 'h * 'g > as 'h > as 'g) >
as 'e)
= <fun>
- : < m : 'a. < p : 'a; .. > as 'b > -> 'b = <fun>
|}];;
type sum = T of < id: 'a. 'a -> 'a > ;;
fun (T x) -> x#id;;
[%%expect {|
type sum = T of < id : 'a. 'a -> 'a >
- : sum -> 'a -> 'a = <fun>
|}];;
type record = { r: < id: 'a. 'a -> 'a > } ;;
fun x -> x.r#id;;
fun {r=x} -> x#id;;
[%%expect {|
type record = { r : < id : 'a. 'a -> 'a >; }
- : record -> 'a -> 'a = <fun>
- : record -> 'a -> 'a = <fun>
|}];;
class myself = object (self)
method self : 'a. 'a -> 'b = fun _ -> self
end;;
[%%expect {|
class myself : object ('b) method self : 'a -> 'b end
|}];;
class number = object (self : 'self)
val num = 0
method num = num
method succ = {< num = num + 1 >}
method prev =
self#switch ~zero:(fun () -> failwith "zero") ~prev:(fun x -> x)
method switch : 'a. zero:(unit -> 'a) -> prev:('self -> 'a) -> 'a =
fun ~zero ~prev ->
if num = 0 then zero () else prev {< num = num - 1 >}
end
;;
[%%expect {|
class number :
object ('b)
val num : int
method num : int
method prev : 'b
method succ : 'b
method switch : zero:(unit -> 'a) -> prev:('b -> 'a) -> 'a
end
|}];;
let id x = x
;;
class c = object
method id : 'a. 'a -> 'a = id
end
;;
class c' = object
inherit c
method id = id
end
;;
class d = object
inherit c as c
val mutable count = 0
method id x = count <- count+1; x
method count = count
method old : 'a. 'a -> 'a = c#id
end
;;
class ['a] olist l = object
val l = l
method fold : 'b. f:('a -> 'b -> 'b) -> init:'b -> 'b
= List.fold_right l
method cons a = {< l = a :: l >}
end
;;
let sum (l : 'a #olist) = l#fold ~f:(fun x acc -> x+acc) ~init:0
;;
let count (l : 'a #olist) = l#fold ~f:(fun _ acc -> acc+1) ~init:0
;;
let append (l : 'a #olist) (l' : 'b #olist) =
l#fold ~init:l' ~f:(fun x acc -> acc#cons x)
;;
[%%expect {|
val id : 'a -> 'a = <fun>
class c : object method id : 'a -> 'a end
class c' : object method id : 'a -> 'a end
class d :
object
val mutable count : int
method count : int
method id : 'a -> 'a
method old : 'a -> 'a
end
class ['a] olist :
'a list ->
object ('c)
val l : 'a list
method cons : 'a -> 'c
method fold : f:('a -> 'b -> 'b) -> init:'b -> 'b
end
val sum : int #olist -> int = <fun>
val count : 'a #olist -> int = <fun>
val append : 'a #olist -> ('a #olist as 'b) -> 'b = <fun>
|}];;
type 'a t = unit
;;
class o = object method x : 'a. ([> `A] as 'a) t -> unit = fun _ -> () end
;;
[%%expect {|
type 'a t = unit
class o : object method x : unit -> unit end
|}];;
class c = object method m = new d () end and d ?(x=0) () = object end;;
class d ?(x=0) () = object end and c = object method m = new d () end;;
[%%expect {|
class c : object method m : d end
and d : ?x:int -> unit -> object end
class d : ?x:int -> unit -> object end
and c : object method m : d end
|}];;
class type numeral = object method fold : ('a -> 'a) -> 'a -> 'a end
class zero = object (_ : #numeral) method fold f x = x end
class next (n : #numeral) =
object (_ : #numeral) method fold f x = n#fold f (f x) end
;;
[%%expect {|
class type numeral = object method fold : ('a -> 'a) -> 'a -> 'a end
class zero : object method fold : ('a -> 'a) -> 'a -> 'a end
class next : #numeral -> object method fold : ('a -> 'a) -> 'a -> 'a end
|}];;
class type node_type = object
method as_variant : [> `Node of node_type]
end;;
class node : node_type = object (self)
method as_variant : 'a. [> `Node of node_type] as 'a
= `Node (self :> node_type)
end;;
class node = object (self : #node_type)
method as_variant = `Node (self :> node_type)
end;;
[%%expect {|
class type node_type = object method as_variant : [> `Node of node_type ] end
class node : node_type
class node : object method as_variant : [> `Node of node_type ] end
|}];;
type bad = {bad : 'a. 'a option ref};;
let bad = {bad = ref None};;
type bad2 = {mutable bad2 : 'a. 'a option ref option};;
let bad2 = {bad2 = None};;
bad2.bad2 <- Some (ref None);;
[%%expect {|
type bad = { bad : 'a. 'a option ref; }
Line 2, characters 17-25:
2 | let bad = {bad = ref None};;
^^^^^^^^
Error: This field value has type 'b option ref which is less general than
'a. 'a option ref
|}];;
let f (x: <m:'a.<p: 'a * 'b> as 'b>) (y : 'b) = ();;
let f (x: <m:'a. 'a * (<p:int*'b> as 'b)>) (y : 'b) = ();;
[%%expect {|
val f : < m : 'a. < p : 'a * 'c > as 'c > -> 'b -> unit = <fun>
val f : < m : 'a. 'a * (< p : int * 'b > as 'b) > -> 'b -> unit = <fun>
|}, Principal{|
val f : < m : 'a. < p : 'a * 'c > as 'c > -> 'b -> unit = <fun>
val f :
< m : 'a. 'a * (< p : int * 'b > as 'b) > ->
(< p : int * 'c > as 'c) -> unit = <fun>
|}];;
PR#3643
type 'a t= [`A of 'a];;
class c = object (self)
method m : 'a. ([> 'a t] as 'a) -> unit
= fun x -> self#m x
end;;
class c = object (self)
method m : 'a. ([> 'a t] as 'a) -> unit = function
| `A x' -> self#m x'
| _ -> failwith "c#m"
end;;
class c = object (self)
method m : 'a. ([> 'a t] as 'a) -> 'a = fun x -> self#m x
end;;
[%%expect {|
type 'a t = [ `A of 'a ]
class c : object method m : ([> 'a t ] as 'a) -> unit end
class c : object method m : ([> 'a t ] as 'a) -> unit end
class c : object method m : ([> 'a t ] as 'a) -> 'a end
|}];;
class c = object method m : 'a. 'a option -> ([> `A] as 'a) = fun x -> `A end;;
[%%expect {|
class c : object method m : ([> `A ] as 'a) option -> 'a end
|}];;
class virtual ['a] visitor =
object method virtual caseNil : 'a end
and virtual int_list =
object method virtual visit : 'a.('a visitor -> 'a) end;;
[%%expect {|
Line 4, characters 30-51:
4 | object method virtual visit : 'a.('a visitor -> 'a) end;;
^^^^^^^^^^^^^^^^^^^^^
Error: The universal type variable 'a cannot be generalized:
it escapes its scope.
|}];;
type ('a,'b) list_visitor = < caseNil : 'a; caseCons : 'b -> 'b list -> 'a >
type 'b alist = < visit : 'a. ('a,'b) list_visitor -> 'a >
[%%expect {|
type ('a, 'b) list_visitor = < caseCons : 'b -> 'b list -> 'a; caseNil : 'a >
type 'b alist = < visit : 'a. ('a, 'b) list_visitor -> 'a >
|}];;
PR#8074
class type ct = object ('s)
method fold : ('b -> 's -> 'b) -> 'b -> 'b
end
type t = {f : 'a 'b. ('b -> (#ct as 'a) -> 'b) -> 'b};;
[%%expect {|
class type ct = object ('a) method fold : ('b -> 'a -> 'b) -> 'b -> 'b end
type t = { f : 'a 'b. ('b -> (#ct as 'a) -> 'b) -> 'b; }
|}];;
PR#8124
type t = u and u = t;;
[%%expect {|
Line 1, characters 0-10:
1 | type t = u and u = t;;
^^^^^^^^^^
Error: The definition of t contains a cycle:
u
|}];;
PR#8188
class ['t] a = object constraint 't = [> `A of 't a] end
type t = [ `A of t a ];;
[%%expect {|
class ['a] a : object constraint 'a = [> `A of 'a a ] end
type t = [ `A of t a ]
|}];;
Wrong in 3.06
type ('a,'b) t constraint 'a = 'b and ('a,'b) u = ('a,'b) t;;
[%%expect {|
Line 1, characters 50-59:
1 | type ('a,'b) t constraint 'a = 'b and ('a,'b) u = ('a,'b) t;;
^^^^^^^^^
Error: Constraints are not satisfied in this type.
Type ('a, 'b) t should be an instance of ('c, 'c) t
|}];;
type 'a t = 'a and u = int t;;
[%%expect {|
type 'a t = 'a
and u = int t
|}];;
type 'a t constraint 'a = int;;
type 'a u = 'a and 'a v = 'a u t;;
type 'a u = 'a and 'a v = 'a u t constraint 'a = int;;
[%%expect {|
type 'a t constraint 'a = int
Line 2, characters 26-32:
2 | type 'a u = 'a and 'a v = 'a u t;;
^^^^^^
Error: Constraints are not satisfied in this type.
Type 'a u t should be an instance of int t
|}];;
type g = int;;
type 'a t = unit constraint 'a = g;;
type 'a u = 'a and 'a v = 'a u t;;
type 'a u = 'a and 'a v = 'a u t constraint 'a = int;;
[%%expect {|
type g = int
type 'a t = unit constraint 'a = g
Line 3, characters 26-32:
3 | type 'a u = 'a and 'a v = 'a u t;;
^^^^^^
Error: Constraints are not satisfied in this type.
Type 'a u t should be an instance of g t
|}];;
type 'a u = < m : 'a v > and 'a v = 'a list u;;
[%%expect {|
Line 1, characters 0-24:
1 | type 'a u = < m : 'a v > and 'a v = 'a list u;;
^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition of v, type 'a list u should be 'a u
|}];;
type 'a t = 'a
type 'a u = A of 'a t;;
[%%expect {|
type 'a t = 'a
type 'a u = A of 'a t
|}];;
type 'a t = < a : 'a >;;
fun (x : 'a t as 'a) -> (x : 'b t);;
type u = 'a t as 'a;;
[%%expect {|
type 'a t = < a : 'a >
- : ('a t as 'a) -> 'a t = <fun>
type u = 'a t as 'a
|}, Principal{|
type 'a t = < a : 'a >
- : ('a t as 'a) -> ('b t as 'b) t = <fun>
type u = 'a t as 'a
|}];;
type ('a, 'b) a = 'a -> unit constraint 'a = [> `B of ('a, 'b) b as 'b]
and ('a, 'b) b = 'b -> unit constraint 'b = [> `A of ('a, 'b) a as 'a];;
[%%expect {|
Line 1, characters 0-71:
1 | type ('a, 'b) a = 'a -> unit constraint 'a = [> `B of ('a, 'b) b as 'b]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The definition of a contains a cycle:
[> `B of ('a, 'b) b as 'b ] as 'a
|}];;
: expanding may change original in Ctype.unify2
Note : since 3.11 , the abbreviations are not used when printing
a type where they occur recursively inside .
a type where they occur recursively inside. *)
class type ['a, 'b] a = object
method b: ('a, 'b) #b as 'b
method as_a: ('a, 'b) a
end and ['a, 'b] b = object
method a: ('a, 'b) #a as 'a
method as_b: ('a, 'b) b
end;;
[%%expect {|
class type ['a, 'b] a =
object
constraint 'a = < as_a : ('a, 'b) a as 'c; b : 'b; .. >
constraint 'b = < a : 'a; as_b : ('a, 'b) b; .. >
method as_a : 'c
method b : 'b
end
and ['a, 'b] b =
object
constraint 'a = < as_a : ('a, 'b) a; b : 'b; .. >
constraint 'b = < a : 'a; as_b : ('a, 'b) b; .. >
method a : 'a
method as_b : ('a, 'b) b
end
|}];;
class type ['b] ca = object ('s) inherit ['s, 'b] a end;;
class type ['a] cb = object ('s) inherit ['a, 's] b end;;
[%%expect {|
class type ['a] ca =
object ('b)
constraint 'a = < a : 'b; as_b : ('b, 'a) b; .. >
method as_a : ('b, 'a) a
method b : 'a
end
class type ['a] cb =
object ('b)
constraint 'a = < as_a : ('a, 'b) a; b : 'b; .. >
method a : 'a
method as_b : ('a, 'b) b
end
|}];;
type bt = 'b ca cb as 'b
;;
[%%expect {|
type bt = 'a ca cb as 'a
|}];;
class c = object method m = 1 end;;
let f () = object (self:c) method m = 1 end;;
let f () = object (self:c) method private n = 1 method m = self#n end;;
let f () = object method private n = 1 method m = {<>}#n end;;
let f () = object (self:c) method n = 1 method m = 2 end;;
let f () = object (_:'s) constraint 's = < n : int > method m = 1 end;;
class c = object (_ : 's)
method x = 1
method private m =
object (self: 's) method x = 3 method private m = self end
end;;
let o = object (_ : 's)
method x = 1
method private m =
object (self: 's) method x = 3 method private m = self end
end;;
[%%expect {|
class c : object method m : int end
val f : unit -> c = <fun>
val f : unit -> c = <fun>
Line 4, characters 11-60:
4 | let f () = object method private n = 1 method m = {<>}#n end;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 15: the following private methods were made public implicitly:
n.
val f : unit -> < m : int; n : int > = <fun>
Line 5, characters 11-56:
5 | let f () = object (self:c) method n = 1 method m = 2 end;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This object is expected to have type c but actually has type
< m : int; n : 'a >
The first object type has no method n
|}];;
fun (x : <m : 'a. 'a * <m: 'b. 'a * 'foo> > as 'foo) ->
(x : <m : 'a. 'a * (<m:'b. 'a * <m:'c. 'c * 'bar> > as 'bar) >);;
type 'a foo = <m: 'b. 'a * 'a foo>
type foo' = <m: 'a. 'a * 'a foo>
type 'a bar = <m: 'b. 'a * <m: 'c. 'c * 'a bar> >
type bar' = <m: 'a. 'a * 'a bar >
let f (x : foo') = (x : bar');;
[%%expect {|
Line 2, characters 3-4:
2 | (x : <m : 'a. 'a * (<m:'b. 'a * <m:'c. 'c * 'bar> > as 'bar) >);;
^
Error: This expression has type < m : 'a. 'a * < m : 'a * 'b > > as 'b
but an expression was expected of type
< m : 'a. 'a * (< m : 'a * < m : 'c. 'c * 'd > > as 'd) >
The method m has type
'a. 'a * (< m : 'a * < m : 'c. 'c * 'b > > as 'b),
but the expected method type was
'c. 'c * < m : 'a * < m : 'c. 'b > > as 'b
The universal variable 'a would escape its scope
|}];;
fun (x : <m : 'a. 'a * ('a * <m : 'a. 'a * 'foo> as 'foo)>) ->
(x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('c * 'bar)>)> as 'bar);;
fun (x : <m : 'a. 'a * ('a * <m : 'a. 'a * 'foo> as 'foo)>) ->
(x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('b * 'bar)>)> as 'bar);;
fun (x : <m : 'a. 'a * ('a * 'foo)> as 'foo) ->
(x : <m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)>);;
let f x =
(x : <m : 'a. 'a -> ('a * <m:'c. 'c -> 'bar> as 'bar)>
:> <m : 'a. 'a -> ('a * 'foo)> as 'foo);;
[%%expect {|
Line 2, characters 3-4:
2 | (x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('c * 'bar)>)> as 'bar);;
^
Error: This expression has type
< m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) >
but an expression was expected of type
< m : 'b. 'b * ('b * < m : 'c. 'c * ('c * 'd) >) > as 'd
Types for method m are incompatible
|}];;
module M
: sig val f : (<m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)>) -> unit end
= struct let f (x : <m : 'a. 'a * ('a * 'foo)> as 'foo) = () end;;
module M
: sig type t = <m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)> end
= struct type t = <m : 'a. 'a * ('a * 'foo)> as 'foo end;;
[%%expect {|
Line 3, characters 2-64:
3 | = struct let f (x : <m : 'a. 'a * ('a * 'foo)> as 'foo) = () end;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
sig val f : (< m : 'a. 'a * ('a * 'b) > as 'b) -> unit end
is not included in
sig
val f : < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) > -> unit
end
Values do not match:
val f : (< m : 'a. 'a * ('a * 'b) > as 'b) -> unit
is not included in
val f : < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) > -> unit
|}];;
module M : sig type 'a t type u = <m: 'a. 'a t> end
= struct type 'a t = int type u = <m: int> end;;
module M : sig type 'a t val f : <m: 'a. 'a t> -> int end
= struct type 'a t = int let f (x : <m:int>) = x#m end;;
module M : sig type 'a t val f : <m: 'a. 'a t> -> int end
= struct type 'a t = int let f x = x#m end;;
[%%expect {|
module M : sig type 'a t type u = < m : 'a. 'a t > end
module M : sig type 'a t val f : < m : 'a. 'a t > -> int end
module M : sig type 'a t val f : < m : 'a. 'a t > -> int end
|}];;
let f x y =
ignore (x :> <m:'a.'a -> 'c * < > > as 'c);
ignore (y :> <m:'b.'b -> 'd * < > > as 'd);
x = y;;
[%%expect {|
val f :
(< m : 'a. 'a -> (< m : 'a. 'a -> 'c * < > > as 'c) * < .. >; .. > as 'b) ->
'b -> bool = <fun>
|}];;
type t = [`A|`B];;
type v = private [> t];;
fun x -> (x : t :> v);;
type u = private [< t];;
fun x -> (x : u :> v);;
fun x -> (x : v :> u);;
type v = private [< t];;
fun x -> (x : u :> v);;
type p = <x:p>;;
type q = private <x:p; ..>;;
fun x -> (x : q :> p);;
fun x -> (x : p :> q);;
[%%expect {|
type t = [ `A | `B ]
type v = private [> t ]
- : t -> v = <fun>
type u = private [< t ]
- : u -> v = <fun>
Line 6, characters 9-21:
6 | fun x -> (x : v :> u);;
^^^^^^^^^^^^
Error: Type v = [> `A | `B ] is not a subtype of u = [< `A | `B ]
|}];;
let f1 x =
(x : <m:'a. (<p:int;..> as 'a) -> int>
:> <m:'b. (<p:int;q:int;..> as 'b) -> int>);;
let f2 x =
(x : <m:'a. (<p:<a:int>;..> as 'a) -> int>
:> <m:'b. (<p:<a:int;b:int>;..> as 'b) -> int>);;
let f3 x =
(x : <m:'a. (<p:<a:int;b:int>;..> as 'a) -> int>
:> <m:'b. (<p:<a:int>;..> as 'b) -> int>);;
let f4 x = (x : <p:<a:int;b:int>;..> :> <p:<a:int>;..>);;
let f5 x =
(x : <m:'a. [< `A of <p:int> ] as 'a> :> <m:'a. [< `A of < > ] as 'a>);;
let f6 x =
(x : <m:'a. [< `A of < > ] as 'a> :> <m:'a. [< `A of <p:int> ] as 'a>);;
[%%expect {|
Lines 2-3, characters 2-47:
2 | ..(x : <m:'a. (<p:int;..> as 'a) -> int>
3 | :> <m:'b. (<p:int;q:int;..> as 'b) -> int>)..
Error: Type < m : 'a. (< p : int; .. > as 'a) -> int > is not a subtype of
< m : 'b. (< p : int; q : int; .. > as 'b) -> int >
Type < p : int; q : int; .. > as 'c is not a subtype of
< p : int; .. > as 'd
|}];;
let f x = if true then (x : < m : 'a. 'a -> 'a >) else x;;
Warning 18
let f (x, y) = if true then (x : < m : 'a. 'a -> 'a >) else x;;
Warning 18
let f x = if true then [| (x : < m : 'a. 'a -> 'a >) |] else [|x|];;
Warning 18
[%%expect {|
val f : < m : 'a. 'a -> 'a > -> < m : 'a. 'a -> 'a > = <fun>
- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
val f : < m : 'a. 'a -> 'a > * 'b -> < m : 'a. 'a -> 'a > = <fun>
- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
val f : < m : 'a. 'a -> 'a > -> < m : 'a. 'a -> 'a > array = <fun>
- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
|}, Principal{|
val f : < m : 'a. 'a -> 'a > -> < m : 'a. 'a -> 'a > = <fun>
Line 2, characters 9-16:
Warning 18
^^^^^^^
Warning 18: this use of a polymorphic method is not principal.
- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
val f : < m : 'a. 'a -> 'a > * 'b -> < m : 'a. 'a -> 'a > = <fun>
Line 4, characters 9-20:
Warning 18
^^^^^^^^^^^
Warning 18: this use of a polymorphic method is not principal.
- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
val f : < m : 'a. 'a -> 'a > -> < m : 'a. 'a -> 'a > array = <fun>
Line 6, characters 9-20:
Warning 18
^^^^^^^^^^^
Warning 18: this use of a polymorphic method is not principal.
- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
|}];;
class c = object method id : 'a. 'a -> 'a = fun x -> x end;;
type u = c option;;
let just = function None -> failwith "just" | Some x -> x;;
let f x = let l = [Some x; (None : u)] in (just(List.hd l))#id;;
let g x =
let none = (fun y -> ignore [y;(None:u)]; y) None in
let x = List.hd [Some x; none] in (just x)#id;;
let h x =
let none = let y = None in ignore [y;(None:u)]; y in
let x = List.hd [Some x; none] in (just x)#id;;
[%%expect {|
class c : object method id : 'a -> 'a end
type u = c option
val just : 'a option -> 'a = <fun>
val f : c -> 'a -> 'a = <fun>
val g : c -> 'a -> 'a = <fun>
val h : < id : 'a; .. > -> 'a = <fun>
|}, Principal{|
class c : object method id : 'a -> 'a end
type u = c option
val just : 'a option -> 'a = <fun>
Line 4, characters 42-62:
4 | let f x = let l = [Some x; (None : u)] in (just(List.hd l))#id;;
^^^^^^^^^^^^^^^^^^^^
Warning 18: this use of a polymorphic method is not principal.
val f : c -> 'a -> 'a = <fun>
Line 7, characters 36-47:
7 | let x = List.hd [Some x; none] in (just x)#id;;
^^^^^^^^^^^
Warning 18: this use of a polymorphic method is not principal.
val g : c -> 'a -> 'a = <fun>
val h : < id : 'a; .. > -> 'a = <fun>
|}];;
type 'a u = c option;;
let just = function None -> failwith "just" | Some x -> x;;
let f x = let l = [Some x; (None : _ u)] in (just(List.hd l))#id;;
[%%expect {|
type 'a u = c option
val just : 'a option -> 'a = <fun>
val f : c -> 'a -> 'a = <fun>
|}];;
let rec f : 'a. 'a -> _ = fun x -> 1 and g x = f x;;
type 'a t = Leaf of 'a | Node of ('a * 'a) t;;
let rec depth : 'a. 'a t -> _ =
function Leaf _ -> 1 | Node x -> 1 + depth x;;
let rec depth : 'a. 'a t -> _ =
function Leaf _ -> 1 | Node x -> 1 + d x
let rec depth : 'a. 'a t -> _ =
let rec depth : 'a. 'a t -> _ =
let rec depth : 'a 'b. 'a t -> 'b =
let rec r : 'a. 'a list * 'b list ref = [], ref []
and q () = r;;
let f : 'a. _ -> _ = fun x -> x;;
[%%expect {|
val f : 'a -> int = <fun>
val g : 'a -> int = <fun>
type 'a t = Leaf of 'a | Node of ('a * 'a) t
val depth : 'a t -> int = <fun>
Line 6, characters 2-42:
6 | function Leaf _ -> 1 | Node x -> 1 + d x
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This definition has type 'a t -> int which is less general than
'a0. 'a0 t -> int
|}];;
type t = {f: 'a. [> `Int of int | `B of 'a] as 'a}
let zero = {f = `Int 0} ;;
type t = {f: 'a. [< `Int of int] as 'a}
[%%expect {|
type t = { f : 'a. [> `B of 'a | `Int of int ] as 'a; }
val zero : t = {f = `Int 0}
type t = { f : 'a. [< `Int of int ] as 'a; }
Line 4, characters 16-22:
^^^^^^
Error: This expression has type [> `Int of int ]
but an expression was expected of type [< `Int of int ]
The second variant type is bound to the universal type variable 'a,
it may not allow the tag(s) `Int
|}];;
let rec id : 'a. 'a -> 'a = fun x -> x
and neg i b = (id (-i), id (not b));;
[%%expect {|
val id : 'a -> 'a = <fun>
val neg : int -> bool -> int * bool = <fun>
|}];;
type t = A of int | B of (int*t) list | C of (string*t) list
[%%expect {|
type t = A of int | B of (int * t) list | C of (string * t) list
|}];;
let rec transf f = function
| A x -> f x
| B l -> B (transf_alist f l)
| C l -> C (transf_alist f l)
and transf_alist : 'a. _ -> ('a*t) list -> ('a*t) list = fun f -> function
| [] -> []
| (k,v)::tl -> (k, transf f v) :: transf_alist f tl
;;
[%%expect {|
val transf : (int -> t) -> t -> t = <fun>
val transf_alist : (int -> t) -> ('a * t) list -> ('a * t) list = <fun>
|}];;
type t = {f: 'a. ('a list -> int) Lazy.t}
let l : t = { f = lazy (raise Not_found)};;
[%%expect {|
type t = { f : 'a. ('a list -> int) Lazy.t; }
val l : t = {f = <lazy>}
|}];;
type t = {f: 'a. 'a -> unit};;
let f ?x y = () in {f};;
[%%expect {|
type t = { f : 'a. 'a -> unit; }
- : t = {f = <fun>}
Line 3, characters 19-20:
^
Error: This field value has type unit -> unit which is less general than
'a. 'a -> unit
|}];;
Polux Moon caml - list 2011 - 07 - 26
module Polux = struct
type 'par t = 'par
let ident v = v
class alias = object method alias : 'a . 'a t -> 'a = ident end
let f (x : <m : 'a. 'a t>) = (x : <m : 'a. 'a>)
end;;
[%%expect {|
module Polux :
sig
type 'par t = 'par
val ident : 'a -> 'a
class alias : object method alias : 'a t -> 'a end
val f : < m : 'a. 'a t > -> < m : 'a. 'a >
end
|}];;
let (a, b) = (raise Exit : int * int);;
type t = { foo : int }
let {foo} = (raise Exit : t);;
type s = A of int
let (A x) = (raise Exit : s);;
[%%expect {|
Exception: Stdlib.Exit.
|}];;
PR#5224
type 'x t = < f : 'y. 'y t >;;
[%%expect {|
Line 1, characters 0-28:
1 | type 'x t = < f : 'y. 'y t >;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition of t, type 'y t should be 'x t
|}];;
let using_match b =
let f =
match b with
| true -> fun x -> x
| false -> fun x -> x
in
f 0,f
;;
[%%expect {|
val using_match : bool -> int * ('a -> 'a) = <fun>
|}];;
match (fun x -> x), fun x -> x with x, y -> x, y;;
match fun x -> x with x -> x, x;;
[%%expect {|
- : ('a -> 'a) * ('b -> 'b) = (<fun>, <fun>)
- : ('a -> 'a) * ('b -> 'b) = (<fun>, <fun>)
|}];;
let n = object
method m : 'x 'o. ([< `Foo of 'x] as 'o) -> 'x = fun x -> assert false
end;;
[%%expect {|
val n : < m : 'x 'a. ([< `Foo of 'x ] as 'a) -> 'x > = <obj>
|}];;
let n =
object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
[%%expect {|
val n : < m : 'x. [< `Foo of 'x ] -> 'x > = <obj>
|}];;
let (n : < m : 'a. [< `Foo of int] -> 'a >) =
object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
[%%expect {|
Line 2, characters 2-72:
2 | object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This expression has type < m : 'x. [< `Foo of 'x ] -> 'x >
but an expression was expected of type
< m : 'a. [< `Foo of int ] -> 'a >
The universal variable 'x would escape its scope
|}];;
let (n : 'b -> < m : 'a . ([< `Foo of int] as 'b) -> 'a >) = fun x ->
object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
[%%expect {|
Line 2, characters 2-72:
2 | object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This expression has type < m : 'x. [< `Foo of 'x ] -> 'x >
but an expression was expected of type
< m : 'a. [< `Foo of int ] -> 'a >
The universal variable 'x would escape its scope
|}];;
let f b (x: 'x) =
let module M = struct type t = A end in
if b then x else M.A;;
[%%expect {|
Line 3, characters 19-22:
3 | if b then x else M.A;;
^^^
Error: This expression has type M.t but an expression was expected of type 'x
The type constructor M.t would escape its scope
|}];;
type 'a t = V1 of 'a
type ('c,'t) pvariant = [ `V of ('c * 't t) ]
class ['c] clss =
object
method mthod : 't . 'c -> 't t -> ('c, 't) pvariant = fun c x ->
`V (c, x)
end;;
let f2 = fun o c x -> match x with | V1 _ -> x
let rec f1 o c x =
match (o :> _ clss)#mthod c x with
| `V c -> f2 o c x;;
[%%expect{|
type 'a t = V1 of 'a
type ('c, 't) pvariant = [ `V of 'c * 't t ]
class ['c] clss : object method mthod : 'c -> 't t -> ('c, 't) pvariant end
val f2 : 'a -> 'b -> 'c t -> 'c t = <fun>
val f1 :
< mthod : 't. 'a -> 't t -> [< `V of 'a * 't t ]; .. > ->
'a -> 'b t -> 'b t = <fun>
|}]
PR#7285
type (+'a,-'b) foo = private int;;
let f (x : int) : ('a,'a) foo = Obj.magic x;;
let x = f 3;;
[%%expect{|
type (+'a, -'b) foo = private int
val f : int -> ('a, 'a) foo = <fun>
val x : ('_weak1, '_weak1) foo = 3
|}]
let rec f : unit -> < m: 'a. 'a -> 'a> = fun () ->
let x = f () in
ignore (x#m 1);
ignore (x#m "hello");
assert false;;
[%%expect{|
val f : unit -> < m : 'a. 'a -> 'a > = <fun>
|}]
type u
type 'a t = u;;
let c (f : u -> u) =
object
method apply: 'a. 'a t -> 'a t = fun x -> f x
end;;
[%%expect{|
type u
type 'a t = u
val c : (u -> u) -> < apply : 'a. u -> u > = <fun>
|}]
PR#7496
let f (x : < m: 'a. ([< `Foo of int & float] as 'a) -> unit>)
: < m: 'a. ([< `Foo of int & float] as 'a) -> unit> = x;;
type t = { x : 'a. ([< `Foo of int & float ] as 'a) -> unit };;
let f t = { x = t.x };;
[%%expect{|
val f :
< m : 'a. ([< `Foo of int & float ] as 'a) -> unit > ->
< m : 'b. ([< `Foo of int & float ] as 'b) -> unit > = <fun>
type t = { x : 'a. ([< `Foo of int & float ] as 'a) -> unit; }
val f : t -> t = <fun>
|}]
type t = <m:int>
type g = <n:string; t>
type h = <x:string; y:int; g>
[%%expect{|
type t = < m : int >
type g = < m : int; n : string >
type h = < m : int; n : string; x : string; y : int >
|}]
type t = <g>
and g = <a:t>
[%%expect{|
Line 1, characters 10-11:
1 | type t = <g>
^
Error: The type constructor g is not yet completely defined
|}]
type t = int
type g = <t>
[%%expect{|
type t = int
Line 2, characters 10-11:
2 | type g = <t>
^
Error: The type int is not an object type
|}]
type t = <a:int>
type g = <t; t; t;>
[%%expect{|
type t = < a : int >
type g = < a : int >
|}]
type c = <a:int; d:string>
let s:c = object method a=1; method d="123" end
[%%expect{|
type c = < a : int; d : string >
val s : c = <obj>
|}]
type 'a t = < m: 'a >
type s = < int t >
module M = struct type t = < m: int > end
type u = < M.t >
type r = < a : int; < b : int > >
type e = < >
type r1 = < a : int; e >
type r2 = < a : int; < < < > > > >
[%%expect{|
type 'a t = < m : 'a >
type s = < m : int >
module M : sig type t = < m : int > end
type u = < m : int >
type r = < a : int; b : int >
type e = < >
type r1 = < a : int >
type r2 = < a : int >
|}]
type gg = <a:int->float; a:int>
[%%expect{|
Line 1, characters 27-30:
1 | type gg = <a:int->float; a:int>
^^^
Error: Method 'a' has type int, which should be int -> float
|}]
type t = <a:int; b:string>
type g = <b:float; t;>
[%%expect{|
type t = < a : int; b : string >
Line 2, characters 19-20:
2 | type g = <b:float; t;>
^
Error: Method 'b' has type string, which should be float
|}]
module A = struct
class type ['a] t1 = object method f : 'a end
end
type t = < int A.t1 >
[%%expect{|
module A : sig class type ['a] t1 = object method f : 'a end end
type t = < f : int >
|}]
type t = < int #A.t1 >
[%%expect{|
Line 1, characters 11-20:
1 | type t = < int #A.t1 >
^^^^^^^^^
Error: Illegal open object type
|}]
let g = fun (y : ('a * 'b)) x -> (x : < <m: 'a> ; <m: 'b> >)
[%%expect{|
val g : 'a * 'a -> < m : 'a > -> < m : 'a > = <fun>
|}]
type 'a t = <m: 'a ; m: int>
[%%expect{|
type 'a t = < m : 'a > constraint 'a = int
|}]
GPR#1142
external reraise : exn -> 'a = "%reraise"
module M () = struct
let f : 'a -> 'a = assert false
let g : 'a -> 'a = raise Not_found
let h : 'a -> 'a = reraise Not_found
let i : 'a -> 'a = raise_notrace Not_found
end
[%%expect{|
external reraise : exn -> 'a = "%reraise"
module M :
functor () ->
sig
val f : 'a -> 'a
val g : 'a -> 'a
val h : 'a -> 'a
val i : 'a -> 'a
end
|}]
# 8550
class ['a] r = let r : 'a = ref [] in object method get = r end;;
[%%expect{|
Line 1, characters 0-63:
1 | class ['a] r = let r : 'a = ref [] in object method get = r end;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The type of this class,
class ['a] r :
object constraint 'a = '_weak2 list ref method get : 'a end,
contains type variables that cannot be generalized
|}]
# 8701
type 'a t = 'a constraint 'a = 'b list;;
type 'a s = 'a list;;
let id x = x;;
[%%expect{|
type 'a t = 'a constraint 'a = 'b list
type 'a s = 'a list
val id : 'a -> 'a = <fun>
|}]
let x : [ `Foo of _ s | `Foo of 'a t ] = id (`Foo []);;
[%%expect{|
val x : [ `Foo of 'a s ] = `Foo []
|}]
let x : [ `Foo of 'a t | `Foo of _ s ] = id (`Foo []);;
[%%expect{|
val x : [ `Foo of 'a list t ] = `Foo []
|}]
class c = object (self) method m ?(x=0) () = x method n = self#m () end;;
class d = object (self) inherit c method n' = self#m () end;;
[%%expect{|
class c : object method m : ?x:int -> unit -> int method n : int end
class d :
object method m : ?x:int -> unit -> int method n : int method n' : int end
|}]
|
2929964f15c82fdadece6214dcdf9f523e297743be54e2e48ed628e16c928229 | facebookincubator/hsthrift | Client.hs | -----------------------------------------------------------------
Autogenerated by Thrift
--
-- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
@generated
-----------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - overlapping - patterns #
# OPTIONS_GHC -fno - warn - incomplete - patterns #
# OPTIONS_GHC -fno - warn - incomplete - uni - patterns #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Service.Y.Client (Y) where
import qualified Service.X.Client as X
import qualified Thrift.Codegen as Thrift
import Service.Types
data Y
type instance Thrift.Super Y = X.X | null | https://raw.githubusercontent.com/facebookincubator/hsthrift/d3ff75d487e9d0c2904d18327373b603456e7a01/compiler/test/fixtures/gen-hs2/Service/Y/Client.hs | haskell | ---------------------------------------------------------------
DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
---------------------------------------------------------------
# LANGUAGE OverloadedStrings #
# LANGUAGE BangPatterns # | Autogenerated by Thrift
@generated
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - overlapping - patterns #
# OPTIONS_GHC -fno - warn - incomplete - patterns #
# OPTIONS_GHC -fno - warn - incomplete - uni - patterns #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Service.Y.Client (Y) where
import qualified Service.X.Client as X
import qualified Thrift.Codegen as Thrift
import Service.Types
data Y
type instance Thrift.Super Y = X.X |
ab78b6d828380b0cccc2149a10c9fb954c951438d2243d1f486c6c62d88640c6 | kblake/erlang-chat-demo | action_toggle.erl | Nitrogen Web Framework for Erlang
Copyright ( c ) 2008 - 2010
See MIT - LICENSE for licensing information .
-module (action_toggle).
-include_lib ("wf.hrl").
-compile(export_all).
render_action(Record) ->
#jquery_effect {
type=toggle,
effect = Record#toggle.effect,
options = Record#toggle.options,
speed = Record#toggle.speed,
actions = Record#toggle.actions
}.
| null | https://raw.githubusercontent.com/kblake/erlang-chat-demo/6fd2fce12f2e059e25a24c9a84169b088710edaf/apps/nitrogen/src/actions/action_toggle.erl | erlang | Nitrogen Web Framework for Erlang
Copyright ( c ) 2008 - 2010
See MIT - LICENSE for licensing information .
-module (action_toggle).
-include_lib ("wf.hrl").
-compile(export_all).
render_action(Record) ->
#jquery_effect {
type=toggle,
effect = Record#toggle.effect,
options = Record#toggle.options,
speed = Record#toggle.speed,
actions = Record#toggle.actions
}.
| |
97c62669245aa46d94c0844c79b8a5b157f1539ef24ee1853ee41f4fae50f3f4 | nekketsuuu/tapis | stype.ml | (* simple type inference *)
open Error
open PiSyntax
open Location
open Type
open Sbst
exception UnifyT of Type.t * Type.t
exception UnifyR of Type.region * Type.region
sprint_expr_error : PiSyntax.pl - > Type.t - > Type.t - > string
let sprint_expr_error el actual_ty expected_ty =
(* TODO(nekketsuuu): 型のpretty print *)
(* TODO(nekketsuuu): print location *)
Printf.sprintf
"Type mismatch. An expression %s has type %s but an expression was expected of type %s"
(PiSyntax.show_el el)
(Type.show_t actual_ty)
(Type.show_t expected_ty)
let sprint_expr_error_chan el actual_ty =
Printf.sprintf
"Type mismatch. An expression %s has type %s but an expression was expected of channel type"
(PiSyntax.show_el el)
(Type.show_t actual_ty)
let rec sprint_error_chan_args x els actual_tys expected_tys =
match actual_tys, expected_tys with
| [], [] ->
"Unexpected error at sprint_error_chan_args"
| [], _ ->
Printf.sprintf
"Type mismatch. The number of channel arguments of %s is greater than expected"
x
| _, [] ->
Printf.sprintf
"Type mismatch. The number of channel arguments of %s is less than expected"
x
(* TODO(nekketsuuu): aty <> ety じゃなくて形で判断させたい *)
| (aty :: atys), (ety :: etys) when aty <> ety ->
Printf.sprintf
"Channel arguments %s has type %s but an expression was expected of type %s"
(PiSyntax.show_el @@ List.hd els)
(Type.show_t aty)
(Type.show_t ety)
| (aty :: atys), (ety :: etys) ->
sprint_error_chan_args x (List.tl els) atys etys
unifyT : ConstraintsT.t - > Type.t sbst
let rec unifyT ct =
if ct = ConstraintsT.empty then []
else
let tt = ConstraintsT.choose ct in
let ct = ConstraintsT.remove tt ct in
match tt with
| (ty1, ty2) when ty1 = ty2 ->
unifyT ct
| ((TChan(_, tys1, ro1) as ty1), (TChan(_, tys2, ro2) as ty2)) ->
if List.length tys1 = List.length tys2 then
let ct = List.fold_left2
(fun ct ty1 ty2 -> ConstraintsT.add (ty1, ty2) ct)
ct tys1 tys2
in unifyT ct
else
raise @@ UnifyT(ty1, ty2)
| (TVar(a), ty2) when not @@ Type.contain a ty2 ->
let ct = ConstraintsT.sbst [(a, ty2)] ct in
Sbst.compose (unifyT ct) [(a, ty2)]
| (ty1, TVar(a)) when not @@ Type.contain a ty1 ->
let ct = ConstraintsT.sbst [(a, ty1)] ct in
Sbst.compose (unifyT ct) [(a, ty1)]
| (ty1, ty2) ->
raise @@ UnifyT(ty1, ty2)
unifyR : ConstraintsR.t - > Type.region sbst
let rec unifyR cr =
if cr = ConstraintsR.empty then []
else
let rr = ConstraintsR.choose cr in
let cr = ConstraintsR.remove rr cr in
if fst rr = snd rr then
unifyR cr
else
let cr = ConstraintsR.sbst [rr] cr in
Sbst.compose (unifyR cr) [rr]
Gather constraints while checking that two types are the same shape
eq_type_pattern : ConstraintsT.t - > ConstraintsR.t - > Type.t - > Type.t - >
bool * ConstraintsT.t * ConstraintsR.t
bool * ConstraintsT.t * ConstraintsR.t *)
let rec eq_type_pattern ct cr ty1 ty2 =
match ty1, ty2 with
| TChan(_, tys1, ro1), TChan(_, tys2, ro2) ->
begin
match ro1, ro2 with
| Some(r1), Some(r2) ->
let (b, ct, cr) = eq_type_patterns ct cr tys1 tys2 in
(b, ct, ConstraintsR.add (r1, r2) cr)
| _, _ ->
(false, ct, cr)
end
| TUnit, TUnit
| TBool, TBool
| TInt, TInt ->
(true, ct, cr)
| TVar(_), _
| _, TVar(_) ->
(true, ConstraintsT.add (ty1, ty2) ct, cr)
| _, _ ->
(false, ct, cr)
and eq_type_patterns ct cr tys1 tys2 =
match tys1, tys2 with
| [], [] -> (true, ct, cr)
| [], _ -> (false, ct, cr)
| _, [] -> (false, ct, cr)
| ty1 :: tys1, ty2 :: tys2 ->
let (b, ct, cr) = eq_type_pattern ct cr ty1 ty2 in
if b then
eq_type_patterns ct cr tys1 tys2
else
(false, ct, cr)
infer_expr : Type.t - > PiSyntax.el - > Type.t * ConstraintsT.t * ConstraintsR.t
let rec infer_expr env el =
match el.loc_val with
| EVar(x) ->
if Env.mem x env then
(Env.find x env, ConstraintsT.empty, ConstraintsR.empty)
else
let ty = TVar(gensym_type ()) in
(ty, ConstraintsT.empty, ConstraintsR.empty)
| EUnit ->
(TUnit, ConstraintsT.empty, ConstraintsR.empty)
| EBool(b) ->
(TBool, ConstraintsT.empty, ConstraintsR.empty)
| EInt(i) ->
(TInt, ConstraintsT.empty, ConstraintsR.empty)
| ENot(el1) ->
infer_unary_expr env el1 TBool TBool
| EAnd(el1, el2)
| EOr(el1, el2) ->
infer_binary_expr env el1 el2 TBool TBool
| ENeg(el1) ->
infer_unary_expr env el1 TInt TInt
| EAdd(el1, el2)
| ESub(el1, el2)
| EMul(el1, el2)
| EDiv(el1, el2) ->
infer_binary_expr env el1 el2 TInt TInt
| ELt(el1, el2)
| EGt(el1, el2)
| ELeq(el1, el2)
| EGeq(el1, el2) ->
infer_binary_expr env el1 el2 TInt TBool
| EEq(el1, el2) ->
let (ty1, ct1, cr1) = infer_expr env el1 in
let (ty2, ct2, cr2) = infer_expr env el2 in
let ct = ConstraintsT.union ct1 ct2 in
let cr = ConstraintsR.union cr1 cr2 in
begin
match ty1, ty2 with
| TVar(_), _
| _, TVar(_) ->
let ct = ConstraintsT.add (ty1, ty2) ct in
(TBool, ct, cr)
| _, _ ->
let (b, ct, cr) = eq_type_pattern ct cr ty1 ty2 in
if b then
(TBool, ct, cr)
else
raise @@ TypeErr(sprint_expr_error el2 ty2 ty1)
end
and infer_unary_expr env el1 tyin tyout =
let (ty, ct, cr) = infer_expr env el1 in
match ty with
| _ when ty = tyin ->
(tyout, ct, cr)
| TVar(_) ->
(tyout, ConstraintsT.add (ty, tyin) ct, cr)
| _ ->
raise @@ TypeErr(sprint_expr_error el1 ty tyin)
and infer_binary_expr env el1 el2 tyin tyout =
let (ty1, ct1, cr1) = infer_expr env el1 in
let (ty2, ct2, cr2) = infer_expr env el2 in
let ct = ConstraintsT.union ct1 ct2 in
let cr = ConstraintsR.union cr1 cr2 in
match ty1, ty2 with
| _, _ when ty1 = tyin && ty2 = tyin ->
(tyout, ct, cr)
| TVar(_), _ when ty2 = tyin ->
(tyout, ConstraintsT.add (ty1, tyin) ct, cr)
| _, TVar(_) when ty1 = tyin ->
(tyout, ConstraintsT.add (ty2, tyin) ct, cr)
| TVar(_), TVar(_) ->
(tyout, ConstraintsT.add (ty1, tyin)
(ConstraintsT.add (ty2, tyin) ct), cr)
| TVar(_), _ ->
raise @@ TypeErr(sprint_expr_error el2 ty2 tyin)
| _, _ ->
raise @@ TypeErr(sprint_expr_error el1 ty1 tyin)
infer_proc : Type.t - > PiSyntax.pl - > ConstraintsT.t * ConstraintsR.t
let rec infer_proc env pl =
match pl.loc_val with
| PNil ->
(ConstraintsT.empty, ConstraintsR.empty)
| PIn(body)
| PRIn(body) ->
infer_proc_input env body pl.loc_start pl.loc_end
| POut(body) ->
let pack e = { loc_val = e; loc_start = pl.loc_start; loc_end = pl.loc_end } in
let fst (x, _, _) = x in
let snd (_, y, _) = y in
let trd (_, _, z) = z in
if Env.mem body.x env then
let ty = Env.find body.x env in
match ty with
| TChan(_, tys, _) ->
(* Check (types of es) = tys *)
let tyccs = List.map (infer_expr env) body.els in
let tys' = List.map fst tyccs in
let (b, ct', cr') = eq_type_patterns ConstraintsT.empty ConstraintsR.empty
tys tys' in
if b then
begin
let (ct', cr') =
List.fold_left
(fun (ct, cr) tycc -> (ConstraintsT.union (snd tycc) ct,
ConstraintsR.union (trd tycc) cr))
(ct', cr') tyccs in
let (ct, cr) = infer_proc env body.pl in
(ConstraintsT.union ct ct',
ConstraintsR.union cr cr')
end
else
raise @@ TypeErr(sprint_error_chan_args body.x body.els tys' tys)
| TVar(a) ->
(* Compose constraints *)
let tyccs = List.map (infer_expr env) body.els in
let tys = List.map fst tyccs in
let (ct, cr) = infer_proc env body.pl in
let (ct, cr) =
List.fold_left
(fun (ct, cr) tycc -> (ConstraintsT.union (snd tycc) ct,
ConstraintsR.union (trd tycc) cr))
(ct, cr) tyccs in
(ConstraintsT.add (ty, TChan(None, tys, Some(gensym_region ()))) ct,
cr)
| _ ->
raise @@ TypeErr(sprint_expr_error_chan (pack @@ EVar(body.x)) ty)
else
(* TODO(nekketsuuu): location *)
raise @@ TypeErr(Printf.sprintf
"Input process is not closed. The name %s is free."
body.x)
| PPar(body) ->
let (ct1, cr1) = infer_proc env body.pl1 in
let (ct2, cr2) = infer_proc env body.pl2 in
(ConstraintsT.union ct1 ct2, ConstraintsR.union cr1 cr2)
| PRes(body) ->
let ty = TVar(gensym_type ()) in
let env = Env.add body.x ty env in
body.tyxo <- Some(ty);
infer_proc env body.pl
| PIf(body) ->
let (tye, ct0, cr0) = infer_expr env body.el in
begin
match tye with
| TBool ->
let (ct1, cr1) = infer_proc env body.pl1 in
let (ct2, cr2) = infer_proc env body.pl2 in
(ConstraintsT.union ct0 (ConstraintsT.union ct1 ct2),
ConstraintsR.union cr0 (ConstraintsR.union cr1 cr2))
| TVar(_) ->
let (ct1, cr1) = infer_proc env body.pl1 in
let (ct2, cr2) = infer_proc env body.pl2 in
(ConstraintsT.add (tye, TBool)
(ConstraintsT.union ct0 (ConstraintsT.union ct1 ct2)),
ConstraintsR.union cr0 (ConstraintsR.union cr1 cr2))
| _ ->
raise @@ TypeErr(sprint_expr_error body.el tye TBool)
end
and infer_proc_input env body loc_start loc_end =
let pack e = { loc_val = e; loc_start = loc_start; loc_end = loc_end } in
if Env.mem body.x env then
let ty = Env.find body.x env in
match ty with
| TChan(_, tys, _) ->
let env = List.fold_left2
(fun env y ty -> Env.add y ty env)
env body.ys tys in
infer_proc env body.pl
| TVar(a) ->
let tys = List.map (fun _ -> TVar(gensym_type ())) body.ys in
let ty' = TChan(None, tys, Some(gensym_region ())) in
let env = Env.add body.x ty' env in
let env = List.fold_left2
(fun env y ty -> Env.add y ty env)
env body.ys tys in
let (ct, cr) = infer_proc env body.pl in
(ConstraintsT.add (ty, ty') ct, cr)
| _ ->
raise @@ TypeErr(sprint_expr_error_chan (pack @@ EVar(body.x)) ty)
else
(* TODO(nekketsuuu): location *)
raise @@ TypeErr(Printf.sprintf
"Input process is not closed. The name %s is free."
body.x)
(* annotate : Type.t sbst -> Type.region sbst -> PiSyntax.pl -> unit *)
let rec annotate sigmaT sigmaR pl =
match pl.loc_val with
| PNil -> ()
| PIn(body)
| PRIn(body) ->
annotate sigmaT sigmaR body.pl
| POut(body) ->
annotate sigmaT sigmaR body.pl
| PRes(body) ->
body.tyxo <- annotate_type_option sigmaT sigmaR body.tyxo;
annotate sigmaT sigmaR body.pl
| PPar(body) ->
annotate sigmaT sigmaR body.pl1;
annotate sigmaT sigmaR body.pl2
| PIf(body) ->
annotate sigmaT sigmaR body.pl1;
annotate sigmaT sigmaR body.pl2
and annotate_type_option (sigmaT : Type.t sbst) (sigmaR : Type.region sbst) tyo =
match tyo with
| Some(ty) -> Some(annotate_type sigmaT sigmaR ty)
| None -> None
and annotate_type (sigmaT : Type.t sbst) (sigmaR : Type.region sbst) ty =
match ty with
| TVar(a) ->
begin
try
let (_, ty) = List.find (fun (a', ty') -> a' = a) sigmaT in
annotate_type sigmaT sigmaR ty
with
| Not_found ->
(* TODO(nekketsuuu): 同じ型変数に対しては1回だけ出力するようにする? *)
(Printf.eprintf "Warning: An uninstantiated type variable %s is assumed type int\n%!" a;
TInt)
end
| TChan(lo, tys, ro) ->
(match ro with
| Some(r) ->
(try
let (_, r) = List.find (fun (r', r'') -> r' = r) sigmaR in
TChan(lo, List.map (annotate_type sigmaT sigmaR) tys, Some(r))
with
| Not_found ->
TChan(lo, List.map (annotate_type sigmaT sigmaR) tys, ro))
| None ->
raise @@ TypeErr("Unexpected error at annotate_type: region is None"))
| ty -> ty
(* infer : PiSyntax.pl -> unit *)
let infer pl =
let (ct, cr) = infer_proc Env.empty pl in
try
let sigmaT = unifyT ct in
let sigmaR = unifyR cr in
annotate sigmaT sigmaR pl
with
| UnifyT(ty1, ty2) ->
raise @@ TypeErr("TODO(nekketsuuu): type unify error")
| UnifyR(r1, r2) ->
raise @@ TypeErr("TODO(nekketsuuu): region unify error")
| null | https://raw.githubusercontent.com/nekketsuuu/tapis/a61ecff95eaf2af27a85290d2a5f99341d28b43c/src/stype.ml | ocaml | simple type inference
TODO(nekketsuuu): 型のpretty print
TODO(nekketsuuu): print location
TODO(nekketsuuu): aty <> ety じゃなくて形で判断させたい
Check (types of es) = tys
Compose constraints
TODO(nekketsuuu): location
TODO(nekketsuuu): location
annotate : Type.t sbst -> Type.region sbst -> PiSyntax.pl -> unit
TODO(nekketsuuu): 同じ型変数に対しては1回だけ出力するようにする?
infer : PiSyntax.pl -> unit |
open Error
open PiSyntax
open Location
open Type
open Sbst
exception UnifyT of Type.t * Type.t
exception UnifyR of Type.region * Type.region
sprint_expr_error : PiSyntax.pl - > Type.t - > Type.t - > string
let sprint_expr_error el actual_ty expected_ty =
Printf.sprintf
"Type mismatch. An expression %s has type %s but an expression was expected of type %s"
(PiSyntax.show_el el)
(Type.show_t actual_ty)
(Type.show_t expected_ty)
let sprint_expr_error_chan el actual_ty =
Printf.sprintf
"Type mismatch. An expression %s has type %s but an expression was expected of channel type"
(PiSyntax.show_el el)
(Type.show_t actual_ty)
let rec sprint_error_chan_args x els actual_tys expected_tys =
match actual_tys, expected_tys with
| [], [] ->
"Unexpected error at sprint_error_chan_args"
| [], _ ->
Printf.sprintf
"Type mismatch. The number of channel arguments of %s is greater than expected"
x
| _, [] ->
Printf.sprintf
"Type mismatch. The number of channel arguments of %s is less than expected"
x
| (aty :: atys), (ety :: etys) when aty <> ety ->
Printf.sprintf
"Channel arguments %s has type %s but an expression was expected of type %s"
(PiSyntax.show_el @@ List.hd els)
(Type.show_t aty)
(Type.show_t ety)
| (aty :: atys), (ety :: etys) ->
sprint_error_chan_args x (List.tl els) atys etys
unifyT : ConstraintsT.t - > Type.t sbst
let rec unifyT ct =
if ct = ConstraintsT.empty then []
else
let tt = ConstraintsT.choose ct in
let ct = ConstraintsT.remove tt ct in
match tt with
| (ty1, ty2) when ty1 = ty2 ->
unifyT ct
| ((TChan(_, tys1, ro1) as ty1), (TChan(_, tys2, ro2) as ty2)) ->
if List.length tys1 = List.length tys2 then
let ct = List.fold_left2
(fun ct ty1 ty2 -> ConstraintsT.add (ty1, ty2) ct)
ct tys1 tys2
in unifyT ct
else
raise @@ UnifyT(ty1, ty2)
| (TVar(a), ty2) when not @@ Type.contain a ty2 ->
let ct = ConstraintsT.sbst [(a, ty2)] ct in
Sbst.compose (unifyT ct) [(a, ty2)]
| (ty1, TVar(a)) when not @@ Type.contain a ty1 ->
let ct = ConstraintsT.sbst [(a, ty1)] ct in
Sbst.compose (unifyT ct) [(a, ty1)]
| (ty1, ty2) ->
raise @@ UnifyT(ty1, ty2)
unifyR : ConstraintsR.t - > Type.region sbst
let rec unifyR cr =
if cr = ConstraintsR.empty then []
else
let rr = ConstraintsR.choose cr in
let cr = ConstraintsR.remove rr cr in
if fst rr = snd rr then
unifyR cr
else
let cr = ConstraintsR.sbst [rr] cr in
Sbst.compose (unifyR cr) [rr]
Gather constraints while checking that two types are the same shape
eq_type_pattern : ConstraintsT.t - > ConstraintsR.t - > Type.t - > Type.t - >
bool * ConstraintsT.t * ConstraintsR.t
bool * ConstraintsT.t * ConstraintsR.t *)
let rec eq_type_pattern ct cr ty1 ty2 =
match ty1, ty2 with
| TChan(_, tys1, ro1), TChan(_, tys2, ro2) ->
begin
match ro1, ro2 with
| Some(r1), Some(r2) ->
let (b, ct, cr) = eq_type_patterns ct cr tys1 tys2 in
(b, ct, ConstraintsR.add (r1, r2) cr)
| _, _ ->
(false, ct, cr)
end
| TUnit, TUnit
| TBool, TBool
| TInt, TInt ->
(true, ct, cr)
| TVar(_), _
| _, TVar(_) ->
(true, ConstraintsT.add (ty1, ty2) ct, cr)
| _, _ ->
(false, ct, cr)
and eq_type_patterns ct cr tys1 tys2 =
match tys1, tys2 with
| [], [] -> (true, ct, cr)
| [], _ -> (false, ct, cr)
| _, [] -> (false, ct, cr)
| ty1 :: tys1, ty2 :: tys2 ->
let (b, ct, cr) = eq_type_pattern ct cr ty1 ty2 in
if b then
eq_type_patterns ct cr tys1 tys2
else
(false, ct, cr)
infer_expr : Type.t - > PiSyntax.el - > Type.t * ConstraintsT.t * ConstraintsR.t
let rec infer_expr env el =
match el.loc_val with
| EVar(x) ->
if Env.mem x env then
(Env.find x env, ConstraintsT.empty, ConstraintsR.empty)
else
let ty = TVar(gensym_type ()) in
(ty, ConstraintsT.empty, ConstraintsR.empty)
| EUnit ->
(TUnit, ConstraintsT.empty, ConstraintsR.empty)
| EBool(b) ->
(TBool, ConstraintsT.empty, ConstraintsR.empty)
| EInt(i) ->
(TInt, ConstraintsT.empty, ConstraintsR.empty)
| ENot(el1) ->
infer_unary_expr env el1 TBool TBool
| EAnd(el1, el2)
| EOr(el1, el2) ->
infer_binary_expr env el1 el2 TBool TBool
| ENeg(el1) ->
infer_unary_expr env el1 TInt TInt
| EAdd(el1, el2)
| ESub(el1, el2)
| EMul(el1, el2)
| EDiv(el1, el2) ->
infer_binary_expr env el1 el2 TInt TInt
| ELt(el1, el2)
| EGt(el1, el2)
| ELeq(el1, el2)
| EGeq(el1, el2) ->
infer_binary_expr env el1 el2 TInt TBool
| EEq(el1, el2) ->
let (ty1, ct1, cr1) = infer_expr env el1 in
let (ty2, ct2, cr2) = infer_expr env el2 in
let ct = ConstraintsT.union ct1 ct2 in
let cr = ConstraintsR.union cr1 cr2 in
begin
match ty1, ty2 with
| TVar(_), _
| _, TVar(_) ->
let ct = ConstraintsT.add (ty1, ty2) ct in
(TBool, ct, cr)
| _, _ ->
let (b, ct, cr) = eq_type_pattern ct cr ty1 ty2 in
if b then
(TBool, ct, cr)
else
raise @@ TypeErr(sprint_expr_error el2 ty2 ty1)
end
and infer_unary_expr env el1 tyin tyout =
let (ty, ct, cr) = infer_expr env el1 in
match ty with
| _ when ty = tyin ->
(tyout, ct, cr)
| TVar(_) ->
(tyout, ConstraintsT.add (ty, tyin) ct, cr)
| _ ->
raise @@ TypeErr(sprint_expr_error el1 ty tyin)
and infer_binary_expr env el1 el2 tyin tyout =
let (ty1, ct1, cr1) = infer_expr env el1 in
let (ty2, ct2, cr2) = infer_expr env el2 in
let ct = ConstraintsT.union ct1 ct2 in
let cr = ConstraintsR.union cr1 cr2 in
match ty1, ty2 with
| _, _ when ty1 = tyin && ty2 = tyin ->
(tyout, ct, cr)
| TVar(_), _ when ty2 = tyin ->
(tyout, ConstraintsT.add (ty1, tyin) ct, cr)
| _, TVar(_) when ty1 = tyin ->
(tyout, ConstraintsT.add (ty2, tyin) ct, cr)
| TVar(_), TVar(_) ->
(tyout, ConstraintsT.add (ty1, tyin)
(ConstraintsT.add (ty2, tyin) ct), cr)
| TVar(_), _ ->
raise @@ TypeErr(sprint_expr_error el2 ty2 tyin)
| _, _ ->
raise @@ TypeErr(sprint_expr_error el1 ty1 tyin)
infer_proc : Type.t - > PiSyntax.pl - > ConstraintsT.t * ConstraintsR.t
let rec infer_proc env pl =
match pl.loc_val with
| PNil ->
(ConstraintsT.empty, ConstraintsR.empty)
| PIn(body)
| PRIn(body) ->
infer_proc_input env body pl.loc_start pl.loc_end
| POut(body) ->
let pack e = { loc_val = e; loc_start = pl.loc_start; loc_end = pl.loc_end } in
let fst (x, _, _) = x in
let snd (_, y, _) = y in
let trd (_, _, z) = z in
if Env.mem body.x env then
let ty = Env.find body.x env in
match ty with
| TChan(_, tys, _) ->
let tyccs = List.map (infer_expr env) body.els in
let tys' = List.map fst tyccs in
let (b, ct', cr') = eq_type_patterns ConstraintsT.empty ConstraintsR.empty
tys tys' in
if b then
begin
let (ct', cr') =
List.fold_left
(fun (ct, cr) tycc -> (ConstraintsT.union (snd tycc) ct,
ConstraintsR.union (trd tycc) cr))
(ct', cr') tyccs in
let (ct, cr) = infer_proc env body.pl in
(ConstraintsT.union ct ct',
ConstraintsR.union cr cr')
end
else
raise @@ TypeErr(sprint_error_chan_args body.x body.els tys' tys)
| TVar(a) ->
let tyccs = List.map (infer_expr env) body.els in
let tys = List.map fst tyccs in
let (ct, cr) = infer_proc env body.pl in
let (ct, cr) =
List.fold_left
(fun (ct, cr) tycc -> (ConstraintsT.union (snd tycc) ct,
ConstraintsR.union (trd tycc) cr))
(ct, cr) tyccs in
(ConstraintsT.add (ty, TChan(None, tys, Some(gensym_region ()))) ct,
cr)
| _ ->
raise @@ TypeErr(sprint_expr_error_chan (pack @@ EVar(body.x)) ty)
else
raise @@ TypeErr(Printf.sprintf
"Input process is not closed. The name %s is free."
body.x)
| PPar(body) ->
let (ct1, cr1) = infer_proc env body.pl1 in
let (ct2, cr2) = infer_proc env body.pl2 in
(ConstraintsT.union ct1 ct2, ConstraintsR.union cr1 cr2)
| PRes(body) ->
let ty = TVar(gensym_type ()) in
let env = Env.add body.x ty env in
body.tyxo <- Some(ty);
infer_proc env body.pl
| PIf(body) ->
let (tye, ct0, cr0) = infer_expr env body.el in
begin
match tye with
| TBool ->
let (ct1, cr1) = infer_proc env body.pl1 in
let (ct2, cr2) = infer_proc env body.pl2 in
(ConstraintsT.union ct0 (ConstraintsT.union ct1 ct2),
ConstraintsR.union cr0 (ConstraintsR.union cr1 cr2))
| TVar(_) ->
let (ct1, cr1) = infer_proc env body.pl1 in
let (ct2, cr2) = infer_proc env body.pl2 in
(ConstraintsT.add (tye, TBool)
(ConstraintsT.union ct0 (ConstraintsT.union ct1 ct2)),
ConstraintsR.union cr0 (ConstraintsR.union cr1 cr2))
| _ ->
raise @@ TypeErr(sprint_expr_error body.el tye TBool)
end
and infer_proc_input env body loc_start loc_end =
let pack e = { loc_val = e; loc_start = loc_start; loc_end = loc_end } in
if Env.mem body.x env then
let ty = Env.find body.x env in
match ty with
| TChan(_, tys, _) ->
let env = List.fold_left2
(fun env y ty -> Env.add y ty env)
env body.ys tys in
infer_proc env body.pl
| TVar(a) ->
let tys = List.map (fun _ -> TVar(gensym_type ())) body.ys in
let ty' = TChan(None, tys, Some(gensym_region ())) in
let env = Env.add body.x ty' env in
let env = List.fold_left2
(fun env y ty -> Env.add y ty env)
env body.ys tys in
let (ct, cr) = infer_proc env body.pl in
(ConstraintsT.add (ty, ty') ct, cr)
| _ ->
raise @@ TypeErr(sprint_expr_error_chan (pack @@ EVar(body.x)) ty)
else
raise @@ TypeErr(Printf.sprintf
"Input process is not closed. The name %s is free."
body.x)
let rec annotate sigmaT sigmaR pl =
match pl.loc_val with
| PNil -> ()
| PIn(body)
| PRIn(body) ->
annotate sigmaT sigmaR body.pl
| POut(body) ->
annotate sigmaT sigmaR body.pl
| PRes(body) ->
body.tyxo <- annotate_type_option sigmaT sigmaR body.tyxo;
annotate sigmaT sigmaR body.pl
| PPar(body) ->
annotate sigmaT sigmaR body.pl1;
annotate sigmaT sigmaR body.pl2
| PIf(body) ->
annotate sigmaT sigmaR body.pl1;
annotate sigmaT sigmaR body.pl2
and annotate_type_option (sigmaT : Type.t sbst) (sigmaR : Type.region sbst) tyo =
match tyo with
| Some(ty) -> Some(annotate_type sigmaT sigmaR ty)
| None -> None
and annotate_type (sigmaT : Type.t sbst) (sigmaR : Type.region sbst) ty =
match ty with
| TVar(a) ->
begin
try
let (_, ty) = List.find (fun (a', ty') -> a' = a) sigmaT in
annotate_type sigmaT sigmaR ty
with
| Not_found ->
(Printf.eprintf "Warning: An uninstantiated type variable %s is assumed type int\n%!" a;
TInt)
end
| TChan(lo, tys, ro) ->
(match ro with
| Some(r) ->
(try
let (_, r) = List.find (fun (r', r'') -> r' = r) sigmaR in
TChan(lo, List.map (annotate_type sigmaT sigmaR) tys, Some(r))
with
| Not_found ->
TChan(lo, List.map (annotate_type sigmaT sigmaR) tys, ro))
| None ->
raise @@ TypeErr("Unexpected error at annotate_type: region is None"))
| ty -> ty
let infer pl =
let (ct, cr) = infer_proc Env.empty pl in
try
let sigmaT = unifyT ct in
let sigmaR = unifyR cr in
annotate sigmaT sigmaR pl
with
| UnifyT(ty1, ty2) ->
raise @@ TypeErr("TODO(nekketsuuu): type unify error")
| UnifyR(r1, r2) ->
raise @@ TypeErr("TODO(nekketsuuu): region unify error")
|
d9a0bf5087aa72c7238dfaadba074e78b677aa28ecbb4378a0c7858e027fe8c6 | ocamllabs/ocaml-modular-implicits | test9.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
open Event
type 'a swap_chan = ('a * 'a channel) channel
let swap msg_out ch =
guard (fun () ->
let ic = new_channel() in
choose [
wrap (receive ch) (fun (msg_in, oc) -> sync (send oc msg_out); msg_in);
wrap (send ch (msg_out, ic)) (fun () -> sync (receive ic))
])
let ch = new_channel()
let f () =
let res = sync (swap "F" ch) in
print_string "f "; print_string res; print_newline()
let g () =
let res = sync (swap "G" ch) in
print_string "g "; print_string res; print_newline()
let _ =
let id = Thread.create f () in
g ();
Thread.join id
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/lib-threads/test9.ml | ocaml | *********************************************************************
OCaml
********************************************************************* | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
open Event
type 'a swap_chan = ('a * 'a channel) channel
let swap msg_out ch =
guard (fun () ->
let ic = new_channel() in
choose [
wrap (receive ch) (fun (msg_in, oc) -> sync (send oc msg_out); msg_in);
wrap (send ch (msg_out, ic)) (fun () -> sync (receive ic))
])
let ch = new_channel()
let f () =
let res = sync (swap "F" ch) in
print_string "f "; print_string res; print_newline()
let g () =
let res = sync (swap "G" ch) in
print_string "g "; print_string res; print_newline()
let _ =
let id = Thread.create f () in
g ();
Thread.join id
|
22342696ecc17d0c1f819314ef31ae4f4d2e9020239cdd1834e48d05e1c881d4 | spectrum-finance/cardano-dex-sdk-haskell | Transaction.hs | {-# OPTIONS_GHC -Wno-unused-imports #-}
module SubmitAPI.Internal.Transaction where
import RIO
import qualified Data.Text as T
import qualified Data.Map.Strict as Map
import Codec.Serialise (serialise)
import Data.ByteString.Lazy (toStrict)
import Prettyprinter (Pretty(..))
import qualified Data.Set as Set
import qualified RIO.List as List
import Cardano.Api hiding (TxBodyError)
import Cardano.Api.Shelley (ProtocolParameters(..), ReferenceTxInsScriptsInlineDatumsSupportedInEra (ReferenceTxInsScriptsInlineDatumsInBabbageEra))
import qualified Cardano.Api.Shelley as C
import Plutus.Script.Utils.V1.Scripts
import qualified Plutus.V2.Ledger.Tx as PV2
import Plutus.V2.Ledger.Api (Datum(Datum))
import qualified Ledger as P
import Ledger (ToCardanoError(Tag))
import qualified Ledger.Tx.CardanoAPI as Interop
import qualified CardanoTx.Interop as Interop
import qualified Ledger.Ada as Ada
import Plutus.Script.Utils.Scripts (datumHash)
import qualified CardanoTx.Models as Sdk
import qualified SubmitAPI.Internal.Balancing as Balancing
import CardanoTx.ToPlutus
import NetworkAPI.Types
signTx
:: TxBody BabbageEra
-> [ShelleyWitnessSigningKey]
-> Tx BabbageEra
signTx body keys =
makeSignedTransaction wits body
where wits = keys <&> makeShelleyKeyWitness body
buildBalancedTx
:: (MonadThrow f)
=> SystemEnv
-> Map P.Script C.TxIn
-> NetworkId
-> Sdk.ChangeAddress
-> Set.Set Sdk.FullCollateralTxIn
-> Sdk.TxCandidate
-> f (BalancedTxBody BabbageEra)
buildBalancedTx SystemEnv{..} refScriptsMap network defaultChangeAddr collateral {..} = do
let eraInMode = BabbageEraInCardanoMode
witOverrides = Nothing
txBody <- buildTxBodyContent pparams network refScriptsMap collateral txc
inputsMap <- buildInputsUTxO network refScriptsMap (Set.elems txCandidateInputs) txCandidateRefIns
changeAddr <- absorbError $ case txCandidateChangePolicy of
Just (Sdk.ReturnTo addr) -> Interop.toCardanoAddressInEra network addr
_ -> Interop.toCardanoAddressInEra network $ Sdk.getAddress defaultChangeAddr
absorbBalancingError $
Balancing.makeTransactionBodyAutoBalance eraInMode sysstart eraHistory pparams pools inputsMap txBody changeAddr witOverrides
where
absorbBalancingError (Left e) = throwM $ BalancingError $ T.pack $ show e
absorbBalancingError (Right a) = pure a
estimateTxFee
:: (MonadThrow f)
=> ProtocolParameters
-> NetworkId
-> Map P.Script C.TxIn
-> Set.Set Sdk.FullCollateralTxIn
-> Sdk.TxCandidate
-> f Lovelace
estimateTxFee pparams network refScriptsMap collateral txc = do
txBodyContent <- buildTxBodyContent pparams network refScriptsMap collateral txc
txBody <- either (throwM . TxBodyError . T.pack . show) pure (makeTransactionBody txBodyContent)
pure $ evaluateTransactionFee pparams txBody 0 0
buildTxBodyContent
:: (MonadThrow f)
=> ProtocolParameters
-> NetworkId
-> Map P.Script C.TxIn
-> Set.Set Sdk.FullCollateralTxIn
-> Sdk.TxCandidate
-> f (TxBodyContent BuildTx BabbageEra)
buildTxBodyContent protocolParams network refScriptsMap collateral Sdk.TxCandidate{..} = do
txIns <- buildTxIns refScriptsMap $ Set.elems txCandidateInputs
txInsRef <- buildTxRefIns txCandidateRefIns
txInsCollateral <- buildTxCollateral $ Set.elems collateral
txOuts <- buildTxOuts network refScriptsMap txCandidateOutputs
txFee <- absorbError $ Interop.toCardanoFee dummyFee
txValidityRange <- absorbError $ Interop.toCardanoValidityRange txCandidateValidRange
txMintValue <-
let redeemers = buildMintRedeemers txCandidateMintInputs
valueMint = Sdk.unMintValue txCandidateValueMint
policies = Map.fromList $ toList (Sdk.mintInputsPolicies txCandidateMintInputs) <&> (\policy -> (mintingPolicyHash policy, policy))
in absorbError $ Interop.toCardanoMintValue redeemers valueMint policies
wits <- absorbError $ traverse Interop.toCardanoPaymentKeyHash txCandidateSigners
let
wits' =
if null wits
then TxExtraKeyWitnessesNone
else TxExtraKeyWitnesses ExtraKeyWitnessesInBabbageEra wits
pure $ TxBodyContent
{ txIns = txIns
, txInsCollateral = txInsCollateral
, txInsReference = txInsRef
, txOuts = txOuts
, txTotalCollateral = TxTotalCollateralNone
, txReturnCollateral = TxReturnCollateralNone
, txFee = txFee
, txValidityRange = txValidityRange
, txMintValue = txMintValue
, txProtocolParams = BuildTxWith $ Just protocolParams
, txExtraKeyWits = wits'
-- unused:
, txScriptValidity = TxScriptValidityNone
, txMetadata = TxMetadataNone
, txAuxScripts = TxAuxScriptsNone
, txWithdrawals = TxWithdrawalsNone
, txCertificates = TxCertificatesNone
, txUpdateProposal = TxUpdateProposalNone
}
buildTxIns
:: (MonadThrow f)
=> Map P.Script C.TxIn
-> [Sdk.FullTxIn]
-> f [(TxIn, BuildTxWith BuildTx (Witness WitCtxTxIn BabbageEra))]
buildTxIns refScripstMap =
mapM translate
where
translate Sdk.FullTxIn{fullTxInTxOut=Sdk.FullTxOut{..}, ..} = do
sWit <- absorbError $ Interop.toCardanoTxInWitnessV2 refScripstMap fullTxInType
txIn <- absorbError $ Interop.toCardanoTxIn fullTxOutRef
pure (txIn, BuildTxWith sWit)
buildTxRefIns
:: (MonadThrow f)
=> [Sdk.FullTxOut ]
-> f (TxInsReference BuildTx BabbageEra)
buildTxRefIns ins =
TxInsReference ReferenceTxInsScriptsInlineDatumsInBabbageEra <$> mapM translate ins
where
translate Sdk.FullTxOut{..} = do
absorbError $ Interop.toCardanoTxIn fullTxOutRef
buildTxCollateral
:: (MonadThrow f)
=> [Sdk.FullCollateralTxIn]
-> f (TxInsCollateral BabbageEra)
buildTxCollateral ins =
TxInsCollateral CollateralInBabbageEra <$> mapM translate ins
where
translate Sdk.FullCollateralTxIn{fullCollateralTxInTxOut=Sdk.FullTxOut{..}} =
absorbError $ Interop.toCardanoTxIn fullTxOutRef
buildTxOuts
:: (MonadThrow f)
=> NetworkId
-> Map P.Script C.TxIn
-> [Sdk.TxOutCandidate]
-> f [TxOut CtxTx BabbageEra]
buildTxOuts network scriptsMap =
mapM translate
where
datumCast :: (PV2.OutputDatum -> Either ToCardanoError (TxOutDatum CtxTx BabbageEra))
datumCast mDh =
case mDh of
PV2.NoOutputDatum -> pure TxOutDatumNone
PV2.OutputDatumHash dh -> do
scDataHash <- Interop.toCardanoScriptDataHash dh
pure $ TxOutDatumHash ScriptDataInBabbageEra scDataHash
PV2.OutputDatum d -> do
pure $ TxOutDatumInline ReferenceTxInsScriptsInlineDatumsInBabbageEra (Interop.toCardanoScriptData (P.getDatum d))
translate sdkOut = absorbError $ Interop.toCardanoTxOutV2 network scriptsMap datumCast $ toPlutus sdkOut
buildInputsUTxO
:: (MonadThrow f)
=> NetworkId
-> Map P.Script C.TxIn
-> [Sdk.FullTxIn]
-> [Sdk.FullTxOut]
-> f (UTxO BabbageEra)
buildInputsUTxO network scriptsMap inputs refOutputs = do
translatedInputs <- mapM (absorbError . translate) inputs
translatedRefOutputs <- mapM (absorbError . translateOutputs) refOutputs
pure . UTxO . Map.fromList $ translatedInputs ++ translatedRefOutputs
where
datumCast :: (PV2.OutputDatum -> Either ToCardanoError (TxOutDatum CtxTx BabbageEra))
datumCast mDh =
case mDh of
PV2.NoOutputDatum -> pure TxOutDatumNone
PV2.OutputDatumHash dh -> do
scDataHash <- Interop.toCardanoScriptDataHash dh
pure $ TxOutDatumHash ScriptDataInBabbageEra scDataHash
PV2.OutputDatum d -> do
pure $ TxOutDatumInline ReferenceTxInsScriptsInlineDatumsInBabbageEra (Interop.toCardanoScriptData (P.getDatum d))
translate Sdk.FullTxIn{fullTxInTxOut={..}} = do
txIn <- Interop.toCardanoTxIn fullTxOutRef
txOut <- Interop.toCardanoTxOutV2 network scriptsMap datumCast $ toPlutus out
pure (txIn, toCtxUTxOTxOut txOut)
translateOutputs {..} = do
txIn <- Interop.toCardanoTxIn fullTxOutRef
txOut <- Interop.toCardanoTxOutV2 network scriptsMap datumCast $ toPlutus out
pure (txIn, toCtxUTxOTxOut txOut)
buildMintRedeemers :: Sdk.MintInputs -> P.Redeemers
buildMintRedeemers Sdk.MintInputs{..} = Map.fromList $ Map.toList mintInputsRedeemers <&> first (P.RedeemerPtr P.Mint)
collectInputsData :: MonadThrow f => [Sdk.FullTxIn] -> f (Map.Map P.DatumHash P.Datum)
collectInputsData inputs = do
rawData <- mapM extractInputDatum inputs
pure $ Map.fromList $ rawData >>= maybe mempty pure
extractInputDatum :: MonadThrow f => Sdk.FullTxIn -> f (Maybe (P.DatumHash, P.Datum))
extractInputDatum Sdk.FullTxIn{fullTxInTxOut=Sdk.FullTxOut{fullTxOutDatum=Sdk.KnownDatum d}} =
pure $ Just (datumHash d, d)
extractInputDatum Sdk.FullTxIn{fullTxInTxOut=Sdk.FullTxOut{fullTxOutDatum=Sdk.KnownDatumHash dh}} =
throwM $ UnresolvedData dh
extractInputDatum _ = pure Nothing
dummyFee :: P.Value
dummyFee = Ada.lovelaceValueOf 0
data TxAssemblyError
= EvaluationError Text
| TxBodyError Text
| DeserializationError
| InvalidValidityRange
| ValueNotPureAda
| OutputHasZeroAda
| StakingPointersNotSupported
| SimpleScriptsNotSupportedToCardano
| MissingTxInType
| MissingMintingPolicy
| MissingMintingPolicyRedeemer
| ScriptPurposeNotSupported P.ScriptTag
| PublicKeyInputsNotSupported
| UnresolvedData P.DatumHash
| BalancingError Text
| CollateralNotAllowed
| FailedToSatisfyCollateral
| SignerNotFound P.PubKeyHash
deriving (Show, Exception)
absorbError :: (MonadThrow f) => Either Interop.ToCardanoError a -> f a
absorbError (Left err) = throwM $ adaptInteropError err
absorbError (Right vl) = pure vl
adaptInteropError :: Interop.ToCardanoError -> TxAssemblyError
adaptInteropError err =
case err of
Interop.TxBodyError _ -> TxBodyError renderedErr
Interop.DeserialisationError -> DeserializationError
Interop.InvalidValidityRange -> InvalidValidityRange
Interop.ValueNotPureAda -> ValueNotPureAda
Interop.OutputHasZeroAda -> OutputHasZeroAda
Interop.StakingPointersNotSupported -> StakingPointersNotSupported
Interop.SimpleScriptsNotSupportedToCardano -> SimpleScriptsNotSupportedToCardano
Interop.MissingTxInType -> MissingTxInType
Interop.MissingMintingPolicy -> MissingMintingPolicy
Interop.MissingMintingPolicyRedeemer -> MissingMintingPolicyRedeemer
Interop.ScriptPurposeNotSupported t -> ScriptPurposeNotSupported t
Interop.Tag _ e -> adaptInteropError e
where renderedErr = T.pack $ show $ pretty err
serializePlutusScript :: P.Script -> SerializedScript
serializePlutusScript s = toShort $ toStrict $ serialise s
type SerializedScript = ShortByteString
| null | https://raw.githubusercontent.com/spectrum-finance/cardano-dex-sdk-haskell/55493f5f2e800fece51fcb9e296fef2fc2c1331d/submit-api/src/SubmitAPI/Internal/Transaction.hs | haskell | # OPTIONS_GHC -Wno-unused-imports #
unused: | module SubmitAPI.Internal.Transaction where
import RIO
import qualified Data.Text as T
import qualified Data.Map.Strict as Map
import Codec.Serialise (serialise)
import Data.ByteString.Lazy (toStrict)
import Prettyprinter (Pretty(..))
import qualified Data.Set as Set
import qualified RIO.List as List
import Cardano.Api hiding (TxBodyError)
import Cardano.Api.Shelley (ProtocolParameters(..), ReferenceTxInsScriptsInlineDatumsSupportedInEra (ReferenceTxInsScriptsInlineDatumsInBabbageEra))
import qualified Cardano.Api.Shelley as C
import Plutus.Script.Utils.V1.Scripts
import qualified Plutus.V2.Ledger.Tx as PV2
import Plutus.V2.Ledger.Api (Datum(Datum))
import qualified Ledger as P
import Ledger (ToCardanoError(Tag))
import qualified Ledger.Tx.CardanoAPI as Interop
import qualified CardanoTx.Interop as Interop
import qualified Ledger.Ada as Ada
import Plutus.Script.Utils.Scripts (datumHash)
import qualified CardanoTx.Models as Sdk
import qualified SubmitAPI.Internal.Balancing as Balancing
import CardanoTx.ToPlutus
import NetworkAPI.Types
signTx
:: TxBody BabbageEra
-> [ShelleyWitnessSigningKey]
-> Tx BabbageEra
signTx body keys =
makeSignedTransaction wits body
where wits = keys <&> makeShelleyKeyWitness body
buildBalancedTx
:: (MonadThrow f)
=> SystemEnv
-> Map P.Script C.TxIn
-> NetworkId
-> Sdk.ChangeAddress
-> Set.Set Sdk.FullCollateralTxIn
-> Sdk.TxCandidate
-> f (BalancedTxBody BabbageEra)
buildBalancedTx SystemEnv{..} refScriptsMap network defaultChangeAddr collateral {..} = do
let eraInMode = BabbageEraInCardanoMode
witOverrides = Nothing
txBody <- buildTxBodyContent pparams network refScriptsMap collateral txc
inputsMap <- buildInputsUTxO network refScriptsMap (Set.elems txCandidateInputs) txCandidateRefIns
changeAddr <- absorbError $ case txCandidateChangePolicy of
Just (Sdk.ReturnTo addr) -> Interop.toCardanoAddressInEra network addr
_ -> Interop.toCardanoAddressInEra network $ Sdk.getAddress defaultChangeAddr
absorbBalancingError $
Balancing.makeTransactionBodyAutoBalance eraInMode sysstart eraHistory pparams pools inputsMap txBody changeAddr witOverrides
where
absorbBalancingError (Left e) = throwM $ BalancingError $ T.pack $ show e
absorbBalancingError (Right a) = pure a
estimateTxFee
:: (MonadThrow f)
=> ProtocolParameters
-> NetworkId
-> Map P.Script C.TxIn
-> Set.Set Sdk.FullCollateralTxIn
-> Sdk.TxCandidate
-> f Lovelace
estimateTxFee pparams network refScriptsMap collateral txc = do
txBodyContent <- buildTxBodyContent pparams network refScriptsMap collateral txc
txBody <- either (throwM . TxBodyError . T.pack . show) pure (makeTransactionBody txBodyContent)
pure $ evaluateTransactionFee pparams txBody 0 0
buildTxBodyContent
:: (MonadThrow f)
=> ProtocolParameters
-> NetworkId
-> Map P.Script C.TxIn
-> Set.Set Sdk.FullCollateralTxIn
-> Sdk.TxCandidate
-> f (TxBodyContent BuildTx BabbageEra)
buildTxBodyContent protocolParams network refScriptsMap collateral Sdk.TxCandidate{..} = do
txIns <- buildTxIns refScriptsMap $ Set.elems txCandidateInputs
txInsRef <- buildTxRefIns txCandidateRefIns
txInsCollateral <- buildTxCollateral $ Set.elems collateral
txOuts <- buildTxOuts network refScriptsMap txCandidateOutputs
txFee <- absorbError $ Interop.toCardanoFee dummyFee
txValidityRange <- absorbError $ Interop.toCardanoValidityRange txCandidateValidRange
txMintValue <-
let redeemers = buildMintRedeemers txCandidateMintInputs
valueMint = Sdk.unMintValue txCandidateValueMint
policies = Map.fromList $ toList (Sdk.mintInputsPolicies txCandidateMintInputs) <&> (\policy -> (mintingPolicyHash policy, policy))
in absorbError $ Interop.toCardanoMintValue redeemers valueMint policies
wits <- absorbError $ traverse Interop.toCardanoPaymentKeyHash txCandidateSigners
let
wits' =
if null wits
then TxExtraKeyWitnessesNone
else TxExtraKeyWitnesses ExtraKeyWitnessesInBabbageEra wits
pure $ TxBodyContent
{ txIns = txIns
, txInsCollateral = txInsCollateral
, txInsReference = txInsRef
, txOuts = txOuts
, txTotalCollateral = TxTotalCollateralNone
, txReturnCollateral = TxReturnCollateralNone
, txFee = txFee
, txValidityRange = txValidityRange
, txMintValue = txMintValue
, txProtocolParams = BuildTxWith $ Just protocolParams
, txExtraKeyWits = wits'
, txScriptValidity = TxScriptValidityNone
, txMetadata = TxMetadataNone
, txAuxScripts = TxAuxScriptsNone
, txWithdrawals = TxWithdrawalsNone
, txCertificates = TxCertificatesNone
, txUpdateProposal = TxUpdateProposalNone
}
buildTxIns
:: (MonadThrow f)
=> Map P.Script C.TxIn
-> [Sdk.FullTxIn]
-> f [(TxIn, BuildTxWith BuildTx (Witness WitCtxTxIn BabbageEra))]
buildTxIns refScripstMap =
mapM translate
where
translate Sdk.FullTxIn{fullTxInTxOut=Sdk.FullTxOut{..}, ..} = do
sWit <- absorbError $ Interop.toCardanoTxInWitnessV2 refScripstMap fullTxInType
txIn <- absorbError $ Interop.toCardanoTxIn fullTxOutRef
pure (txIn, BuildTxWith sWit)
buildTxRefIns
:: (MonadThrow f)
=> [Sdk.FullTxOut ]
-> f (TxInsReference BuildTx BabbageEra)
buildTxRefIns ins =
TxInsReference ReferenceTxInsScriptsInlineDatumsInBabbageEra <$> mapM translate ins
where
translate Sdk.FullTxOut{..} = do
absorbError $ Interop.toCardanoTxIn fullTxOutRef
buildTxCollateral
:: (MonadThrow f)
=> [Sdk.FullCollateralTxIn]
-> f (TxInsCollateral BabbageEra)
buildTxCollateral ins =
TxInsCollateral CollateralInBabbageEra <$> mapM translate ins
where
translate Sdk.FullCollateralTxIn{fullCollateralTxInTxOut=Sdk.FullTxOut{..}} =
absorbError $ Interop.toCardanoTxIn fullTxOutRef
buildTxOuts
:: (MonadThrow f)
=> NetworkId
-> Map P.Script C.TxIn
-> [Sdk.TxOutCandidate]
-> f [TxOut CtxTx BabbageEra]
buildTxOuts network scriptsMap =
mapM translate
where
datumCast :: (PV2.OutputDatum -> Either ToCardanoError (TxOutDatum CtxTx BabbageEra))
datumCast mDh =
case mDh of
PV2.NoOutputDatum -> pure TxOutDatumNone
PV2.OutputDatumHash dh -> do
scDataHash <- Interop.toCardanoScriptDataHash dh
pure $ TxOutDatumHash ScriptDataInBabbageEra scDataHash
PV2.OutputDatum d -> do
pure $ TxOutDatumInline ReferenceTxInsScriptsInlineDatumsInBabbageEra (Interop.toCardanoScriptData (P.getDatum d))
translate sdkOut = absorbError $ Interop.toCardanoTxOutV2 network scriptsMap datumCast $ toPlutus sdkOut
buildInputsUTxO
:: (MonadThrow f)
=> NetworkId
-> Map P.Script C.TxIn
-> [Sdk.FullTxIn]
-> [Sdk.FullTxOut]
-> f (UTxO BabbageEra)
buildInputsUTxO network scriptsMap inputs refOutputs = do
translatedInputs <- mapM (absorbError . translate) inputs
translatedRefOutputs <- mapM (absorbError . translateOutputs) refOutputs
pure . UTxO . Map.fromList $ translatedInputs ++ translatedRefOutputs
where
datumCast :: (PV2.OutputDatum -> Either ToCardanoError (TxOutDatum CtxTx BabbageEra))
datumCast mDh =
case mDh of
PV2.NoOutputDatum -> pure TxOutDatumNone
PV2.OutputDatumHash dh -> do
scDataHash <- Interop.toCardanoScriptDataHash dh
pure $ TxOutDatumHash ScriptDataInBabbageEra scDataHash
PV2.OutputDatum d -> do
pure $ TxOutDatumInline ReferenceTxInsScriptsInlineDatumsInBabbageEra (Interop.toCardanoScriptData (P.getDatum d))
translate Sdk.FullTxIn{fullTxInTxOut={..}} = do
txIn <- Interop.toCardanoTxIn fullTxOutRef
txOut <- Interop.toCardanoTxOutV2 network scriptsMap datumCast $ toPlutus out
pure (txIn, toCtxUTxOTxOut txOut)
translateOutputs {..} = do
txIn <- Interop.toCardanoTxIn fullTxOutRef
txOut <- Interop.toCardanoTxOutV2 network scriptsMap datumCast $ toPlutus out
pure (txIn, toCtxUTxOTxOut txOut)
buildMintRedeemers :: Sdk.MintInputs -> P.Redeemers
buildMintRedeemers Sdk.MintInputs{..} = Map.fromList $ Map.toList mintInputsRedeemers <&> first (P.RedeemerPtr P.Mint)
collectInputsData :: MonadThrow f => [Sdk.FullTxIn] -> f (Map.Map P.DatumHash P.Datum)
collectInputsData inputs = do
rawData <- mapM extractInputDatum inputs
pure $ Map.fromList $ rawData >>= maybe mempty pure
extractInputDatum :: MonadThrow f => Sdk.FullTxIn -> f (Maybe (P.DatumHash, P.Datum))
extractInputDatum Sdk.FullTxIn{fullTxInTxOut=Sdk.FullTxOut{fullTxOutDatum=Sdk.KnownDatum d}} =
pure $ Just (datumHash d, d)
extractInputDatum Sdk.FullTxIn{fullTxInTxOut=Sdk.FullTxOut{fullTxOutDatum=Sdk.KnownDatumHash dh}} =
throwM $ UnresolvedData dh
extractInputDatum _ = pure Nothing
dummyFee :: P.Value
dummyFee = Ada.lovelaceValueOf 0
data TxAssemblyError
= EvaluationError Text
| TxBodyError Text
| DeserializationError
| InvalidValidityRange
| ValueNotPureAda
| OutputHasZeroAda
| StakingPointersNotSupported
| SimpleScriptsNotSupportedToCardano
| MissingTxInType
| MissingMintingPolicy
| MissingMintingPolicyRedeemer
| ScriptPurposeNotSupported P.ScriptTag
| PublicKeyInputsNotSupported
| UnresolvedData P.DatumHash
| BalancingError Text
| CollateralNotAllowed
| FailedToSatisfyCollateral
| SignerNotFound P.PubKeyHash
deriving (Show, Exception)
absorbError :: (MonadThrow f) => Either Interop.ToCardanoError a -> f a
absorbError (Left err) = throwM $ adaptInteropError err
absorbError (Right vl) = pure vl
adaptInteropError :: Interop.ToCardanoError -> TxAssemblyError
adaptInteropError err =
case err of
Interop.TxBodyError _ -> TxBodyError renderedErr
Interop.DeserialisationError -> DeserializationError
Interop.InvalidValidityRange -> InvalidValidityRange
Interop.ValueNotPureAda -> ValueNotPureAda
Interop.OutputHasZeroAda -> OutputHasZeroAda
Interop.StakingPointersNotSupported -> StakingPointersNotSupported
Interop.SimpleScriptsNotSupportedToCardano -> SimpleScriptsNotSupportedToCardano
Interop.MissingTxInType -> MissingTxInType
Interop.MissingMintingPolicy -> MissingMintingPolicy
Interop.MissingMintingPolicyRedeemer -> MissingMintingPolicyRedeemer
Interop.ScriptPurposeNotSupported t -> ScriptPurposeNotSupported t
Interop.Tag _ e -> adaptInteropError e
where renderedErr = T.pack $ show $ pretty err
serializePlutusScript :: P.Script -> SerializedScript
serializePlutusScript s = toShort $ toStrict $ serialise s
type SerializedScript = ShortByteString
|
cb9c3064c83a8151d425c6f8b0c7ecd3f3fad90c22209e4548852309ac76840b | rcherrueau/APE | lang.rkt | #lang racket
(require (for-syntax racket/base
syntax/parse
(only-in "utils.rkt" unique-ids? primitive-op-id?))
(prefix-in racket/base/ racket/base)
racket/match
syntax/parse/define
typed/racket
"utils.rkt")
;; Adder+let -- A starter language that add number + Let-bindings and
;; simple stack allocations.
;;
;; See:
;; - -and-stack_notes.html
;; -
;; n ∈ Nat
;; id ∈ Identifier
;;
;; exp ::= (Exp)
n ( )
| ( add1 exp ) ( Prim1 Add1 )
;; | (sub1 exp) (Prim1 Sub1)
| i d ( I d ) -- New in adder+let
| ( let ( [ i d exp ] ... ) exp ) ( Let ) -- New in adder+let
Parser -- This language assumes an s - exp reader
(require "ast.rkt")
A module is an ` EXP ` , not the traditional list of ` EXP ` ( ie ,
EXP ... ) . In other word , it ensures that only one program could be
;; given instead of a list of programs.
;;
;; The module compiles the underlining expressions with `compile-exp`.
Function ` compile - exp ` takes an ` EXP ` and produces an ` ASM ` ( ie ,
List of ASM instructions ) . It then gives the compiled expression to
` asm->string ` that converts the ` ASM ` into a textual form .
(define-syntax (@%module-begin stx)
(syntax-parse stx
[(_ EXP:expr)
#'(racket/base/#%module-begin
Expose ` ast ` and ` asm ` out
;; for unit tests.
The AST of the Program
The ASM of the Program
Print textual form of ASM
)]))
;; Id
(define-syntax-parser @%id
[(_ . ID:id)
#'(Id 'ID)])
;; Let
(define-syntax (@let stx)
(syntax-parse stx
[(_ ([ID:id EXP] ...) BODY)
#:fail-when (not (unique-ids? #'(ID ...))) "duplicate identifier found"
#'(Let (list (cons 'ID EXP) ...) BODY)]))
;; Num -- Only Nat are valid program
(define-syntax-parser @%datum
[(_ . N:nat) #'(Num (racket/base/#%datum . N))])
;; Prim1 Add1
(define-syntax-parser @add1
[(_ EXP:expr) #'(Prim1 (Add1) EXP)])
;; Prim1 Sub1
(define-syntax-parser @sub1
[(_ EXP:expr) #'(Prim1 (Sub1) EXP)])
;; A Note on The Stack -- How memory is used in programs. See,
;; -and-stack_notes.html#(part._.The_stack)
;;
32 - bit architecture provides 32 bits to encode memory addresses .
That works out to 2 ^ 32 unique combinations of addresses . Thus ,
memory is - in theory - an array addressed from 0 to 2 ^ 32 . Note
that one address points to 1 byte of data . Therefore , memory is
made of 2 ^ 32 bytes of data ( ie , 4294967296 bytes or 4 Gigabytes ) .
;;
;; There are restrictions and conventions on how to use memory
;; addresses appropriately. The memory addresses are organized as
;; follow:
;;
;; Low: 0 → +-------+
;; |Code |
;; +-------+
;; |Global |
;; +-------+
;; | |
|Heap |
;; | |
;; +-------+
;; | |
;; |Stack |
;; | |
High : 2 ^ 32 → + -------+
;;
;; The /Code/ includes code for the program. The /Global/ includes
;; global data. The /Heap/ includes dynamically allocated memory. The
;; /Stack/ is used as program calls functions and returns from them.
;;
;; Heap and Stack are adjacent and they must not overlap, or else the
;; same region of memory would not have a unique interpretation, and
;; the program will crash. To avoid this, the convention has been that
;; the heap grows upwards from "Lower" addresses, while the stack
;; grows downward from "Higher" addresses.
;;
;; The stack itself must conform to a particular structure, so that
;; functions can call each other reliably. From a bird's eye view, the
;; stack is divided into /Stack Frames/, one per function-in-progress.
;; A stack frame holds statically allocated memory (ie, the static
;; values of local variables). In the following, values we push on the
stack are numbers and all * 4 bytes * long ( size of an int in C ) .
Because one address of the stack points to 1 byte of data , and we
push data on the Stack frame downward from ` ESP ` . The address of
the first local value is ` ESP - 4 ` , then the value of the second
;; local value is `ESP - 8` and so on. When the function returns, its
;; stack frame is feed for use by future calls.
;;
;; When a function is called, it needs to be told where its stack
;; frame begins. This address is stored in the `ESP` register (also
;; called, /Stack Pointer/):
;;
;; +--------------+
;; | |
;; | Not yet used |
;; | |
;; ESP - 8 → +--------------+
| Local # 2 |
;; ESP - 4 → +--------------+
| Local # 1 |
;; ESP → +--------------+
;; | Earlier |
;; | stack frames |
;; High → +--------------+
Compiler
(require "asm.rkt")
;; Take an `exp` and compiles into a list of assembly Instructions.
;; `env` is a map between and identifier and its address on the stack
;; frame (ie, its offset). `stack-offset` is the current offset value
for the stack frame ( ie , number of 4 bytes values actually pushed
;; on the stack frame)
(: compile-exp (Exp (Immutable-HashTable Symbol Integer) Integer -> ASM))
(define (compile-exp exp [env (make-immutable-hash)] [stack-offset 1])
(exp⇒asm exp
[(Id id)
;; Finds offset of `id`.
(define id-offset (hash-ref env id))
Loads address of ` i d ` in EAX .
(Move (Reg (EAX)) (Mem (ESP) id-offset))]
[(Let `((,id . ,val-exp)) body)
Compiles binder expression ` val - exp ` ; Result is in EAX .
(compile-exp val-exp env stack-offset)
Moves results of EAX on the stack at current offset .
(Move (Mem (ESP) stack-offset) (Reg (EAX)))
;; Puts id stack address in the env; Computes new offset; And
;; compiles Let body.
(let* ([new-env (hash-set env id stack-offset)]
[new-offset (add1 stack-offset)])
(compile-exp body new-env new-offset))]
[(Let `((,id . ,val-exp) ,bindings ...) body)
;; Rewrite Let* so that reminding bindings are part of a new Let
;; in the body (ie, recurs on Let binding until reducing to the
case with only one binder in the Let ) .
First binding
(define bs bindings) ;; Reminding bindings
=> (compile-exp (Let b1 (Let bs body)) env stack-offset)]
[(Prim1 (Add1) exp)
Compiles expression ` exp ` ; Result is in EAX .
(compile-exp exp env stack-offset)
Add 1 to EAX
(Add (Reg (EAX)) (Const 1))]
[(Prim1 (Sub1) exp)
Compiles expression ` exp ` ; Result is in EAX .
(compile-exp exp env stack-offset)
Add 1 to EAX
(Sub (Reg (EAX)) (Const 1))]
;; -- Definitions from "neonate"
[(Num n) => (Move (Reg (EAX)) (Const n))]
[else (error "Compilation Error: Unsupported Exp" exp)]))
Interface
(provide (rename-out [@%module-begin #%module-begin]
[@%datum #%datum]
[@add1 add1] [@sub1 sub1]
[@let let]
# % top wrapped unbound variables
)
quote
#%app #%top-interaction compile-exp)
| null | https://raw.githubusercontent.com/rcherrueau/APE/8b5302709000bd043b64d46d55642acb34ce5ba7/racket/pan/adder%2Blet/lang.rkt | racket | Adder+let -- A starter language that add number + Let-bindings and
simple stack allocations.
See:
- -and-stack_notes.html
-
n ∈ Nat
id ∈ Identifier
exp ::= (Exp)
| (sub1 exp) (Prim1 Sub1)
given instead of a list of programs.
The module compiles the underlining expressions with `compile-exp`.
for unit tests.
Id
Let
Num -- Only Nat are valid program
Prim1 Add1
Prim1 Sub1
A Note on The Stack -- How memory is used in programs. See,
-and-stack_notes.html#(part._.The_stack)
There are restrictions and conventions on how to use memory
addresses appropriately. The memory addresses are organized as
follow:
Low: 0 → +-------+
|Code |
+-------+
|Global |
+-------+
| |
| |
+-------+
| |
|Stack |
| |
The /Code/ includes code for the program. The /Global/ includes
global data. The /Heap/ includes dynamically allocated memory. The
/Stack/ is used as program calls functions and returns from them.
Heap and Stack are adjacent and they must not overlap, or else the
same region of memory would not have a unique interpretation, and
the program will crash. To avoid this, the convention has been that
the heap grows upwards from "Lower" addresses, while the stack
grows downward from "Higher" addresses.
The stack itself must conform to a particular structure, so that
functions can call each other reliably. From a bird's eye view, the
stack is divided into /Stack Frames/, one per function-in-progress.
A stack frame holds statically allocated memory (ie, the static
values of local variables). In the following, values we push on the
local value is `ESP - 8` and so on. When the function returns, its
stack frame is feed for use by future calls.
When a function is called, it needs to be told where its stack
frame begins. This address is stored in the `ESP` register (also
called, /Stack Pointer/):
+--------------+
| |
| Not yet used |
| |
ESP - 8 → +--------------+
ESP - 4 → +--------------+
ESP → +--------------+
| Earlier |
| stack frames |
High → +--------------+
Take an `exp` and compiles into a list of assembly Instructions.
`env` is a map between and identifier and its address on the stack
frame (ie, its offset). `stack-offset` is the current offset value
on the stack frame)
Finds offset of `id`.
Result is in EAX .
Puts id stack address in the env; Computes new offset; And
compiles Let body.
Rewrite Let* so that reminding bindings are part of a new Let
in the body (ie, recurs on Let binding until reducing to the
Reminding bindings
Result is in EAX .
Result is in EAX .
-- Definitions from "neonate" | #lang racket
(require (for-syntax racket/base
syntax/parse
(only-in "utils.rkt" unique-ids? primitive-op-id?))
(prefix-in racket/base/ racket/base)
racket/match
syntax/parse/define
typed/racket
"utils.rkt")
n ( )
| ( add1 exp ) ( Prim1 Add1 )
| i d ( I d ) -- New in adder+let
| ( let ( [ i d exp ] ... ) exp ) ( Let ) -- New in adder+let
Parser -- This language assumes an s - exp reader
(require "ast.rkt")
A module is an ` EXP ` , not the traditional list of ` EXP ` ( ie ,
EXP ... ) . In other word , it ensures that only one program could be
Function ` compile - exp ` takes an ` EXP ` and produces an ` ASM ` ( ie ,
List of ASM instructions ) . It then gives the compiled expression to
` asm->string ` that converts the ` ASM ` into a textual form .
(define-syntax (@%module-begin stx)
(syntax-parse stx
[(_ EXP:expr)
#'(racket/base/#%module-begin
Expose ` ast ` and ` asm ` out
The AST of the Program
The ASM of the Program
Print textual form of ASM
)]))
(define-syntax-parser @%id
[(_ . ID:id)
#'(Id 'ID)])
(define-syntax (@let stx)
(syntax-parse stx
[(_ ([ID:id EXP] ...) BODY)
#:fail-when (not (unique-ids? #'(ID ...))) "duplicate identifier found"
#'(Let (list (cons 'ID EXP) ...) BODY)]))
(define-syntax-parser @%datum
[(_ . N:nat) #'(Num (racket/base/#%datum . N))])
(define-syntax-parser @add1
[(_ EXP:expr) #'(Prim1 (Add1) EXP)])
(define-syntax-parser @sub1
[(_ EXP:expr) #'(Prim1 (Sub1) EXP)])
32 - bit architecture provides 32 bits to encode memory addresses .
That works out to 2 ^ 32 unique combinations of addresses . Thus ,
memory is - in theory - an array addressed from 0 to 2 ^ 32 . Note
that one address points to 1 byte of data . Therefore , memory is
made of 2 ^ 32 bytes of data ( ie , 4294967296 bytes or 4 Gigabytes ) .
|Heap |
High : 2 ^ 32 → + -------+
stack are numbers and all * 4 bytes * long ( size of an int in C ) .
Because one address of the stack points to 1 byte of data , and we
push data on the Stack frame downward from ` ESP ` . The address of
the first local value is ` ESP - 4 ` , then the value of the second
| Local # 2 |
| Local # 1 |
Compiler
(require "asm.rkt")
for the stack frame ( ie , number of 4 bytes values actually pushed
(: compile-exp (Exp (Immutable-HashTable Symbol Integer) Integer -> ASM))
(define (compile-exp exp [env (make-immutable-hash)] [stack-offset 1])
(exp⇒asm exp
[(Id id)
(define id-offset (hash-ref env id))
Loads address of ` i d ` in EAX .
(Move (Reg (EAX)) (Mem (ESP) id-offset))]
[(Let `((,id . ,val-exp)) body)
(compile-exp val-exp env stack-offset)
Moves results of EAX on the stack at current offset .
(Move (Mem (ESP) stack-offset) (Reg (EAX)))
(let* ([new-env (hash-set env id stack-offset)]
[new-offset (add1 stack-offset)])
(compile-exp body new-env new-offset))]
[(Let `((,id . ,val-exp) ,bindings ...) body)
case with only one binder in the Let ) .
First binding
=> (compile-exp (Let b1 (Let bs body)) env stack-offset)]
[(Prim1 (Add1) exp)
(compile-exp exp env stack-offset)
Add 1 to EAX
(Add (Reg (EAX)) (Const 1))]
[(Prim1 (Sub1) exp)
(compile-exp exp env stack-offset)
Add 1 to EAX
(Sub (Reg (EAX)) (Const 1))]
[(Num n) => (Move (Reg (EAX)) (Const n))]
[else (error "Compilation Error: Unsupported Exp" exp)]))
Interface
(provide (rename-out [@%module-begin #%module-begin]
[@%datum #%datum]
[@add1 add1] [@sub1 sub1]
[@let let]
# % top wrapped unbound variables
)
quote
#%app #%top-interaction compile-exp)
|
fec0ae51bf4b0865e23d3e8724f27ba25547732feeee35103767931c254b47b7 | den1k/vimsical | queries_test.clj | (ns vimsical.backend.handlers.user.queries-test
(:require [clojure.test :refer [are deftest is testing use-fixtures]]
[vimsical.backend.handlers.user.queries :as sut]
[vimsical.backend.system.fixture :refer [*service-fn* system]]))
(use-fixtures :each system)
(deftest me-test)
| null | https://raw.githubusercontent.com/den1k/vimsical/1e4a1f1297849b1121baf24bdb7a0c6ba3558954/test/backend/vimsical/backend/handlers/user/queries_test.clj | clojure | (ns vimsical.backend.handlers.user.queries-test
(:require [clojure.test :refer [are deftest is testing use-fixtures]]
[vimsical.backend.handlers.user.queries :as sut]
[vimsical.backend.system.fixture :refer [*service-fn* system]]))
(use-fixtures :each system)
(deftest me-test)
| |
290752966a497d51c4721c91af6ffad0674f9aaeace7ad43458c487b7b017367 | AmpersandTarski/Ampersand | Setup.hs | {-# LANGUAGE OverloadedStrings #-}
-- | Before each build, generate a BuildInfo_Generated module that exports the project version from cabal,
-- the current revision number and the build time. Also generate a file that contains files that
-- are being included into the ampersand.exe file
-- Note that in order for this Setup.hs to be used by cabal, the build-type should be Custom.
module Main where
import qualified Codec . Compression . as replace by Codec . Archive . Zip from package zip - archive . This reduces the amount of packages . ( We now use two for zipping / unzipping )
import Codec.Archive.Zip
import Distribution.PackageDescription
import Distribution.Pretty (prettyShow)
import Distribution.Simple
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Setup
import RIO
import RIO.Char
import qualified RIO.List as L
import qualified RIO.NonEmpty as NE
import qualified RIO.Text as T
import RIO.Time
import System.Directory
import System.Environment (getEnvironment)
import qualified System.Exit as SE
import System.FilePath
import System.Process (readProcessWithExitCode)
import Prelude (print, putStrLn)
main :: IO ()
main =
defaultMainWithHooks
simpleUserHooks
{ buildHook = customBuildHook,
replHook = customReplHook
}
-- | Generate Haskell modules that are required for the build and start the build
customBuildHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> BuildFlags -> IO ()
customBuildHook pd lbi uh bf = do
generateBuildInfoModule (T.pack . prettyShow . pkgVersion . package $ pd)
generateStaticFileModule
buildHook simpleUserHooks pd lbi uh bf -- start the build
-- | Generate Haskell modules that are required for the build and start the build
customReplHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> ReplFlags -> [String] -> IO ()
customReplHook pd lbi uh rf args = do
generateBuildInfoModule (T.pack . prettyShow . pkgVersion . package $ pd)
generateStaticFileModule
replHook simpleUserHooks pd lbi uh rf args -- start the build
generateBuildInfoModule :: Text -> IO ()
| Generate a Haskell module that contains information that is available
-- only during build time.
generateBuildInfoModule cabalVersionStr = do
content <-
buildInfoModule cabalVersionStr
<$> getGitInfoStr
<*> ( T.pack . formatTime defaultTimeLocale "%d-%b-%y %H:%M:%S %Z"
<$> (getCurrentTime >>= utcToLocalZonedTime)
)
writeFileUtf8 (pathFromModuleName buildInfoModuleName) content
where
buildInfoModuleName :: Text
buildInfoModuleName = "Ampersand.Basics.BuildInfo_Generated"
buildInfoModule :: Text -> Text -> Text -> Text
buildInfoModule cabalVersion gitInfo time =
T.unlines
[ "{-# LANGUAGE OverloadedStrings #-}",
"-- | This module is generated automatically by Setup.hs before building. Do not edit!",
"-- It contains some functions that are supposed to grab information at the time of",
"-- building the ampersand executable.",
"module " <> buildInfoModuleName <> "(",
" cabalVersionStr",
" , gitInfoStr",
" , buildTimeStr",
" ) where",
"import Ampersand.Basics.Prelude",
"",
"{-" <> "# NOINLINE cabalVersionStr #-}", -- disable inlining to prevent recompilation of dependent modules on each build
"-- | The version of Ampersand as it is stated in the package.yaml file.",
"cabalVersionStr :: Text",
"cabalVersionStr = \"" <> cabalVersion <> "\"",
"",
"{-" <> "# NOINLINE gitInfoStr #-}",
"-- | The version of Ampersand as seen by Git.",
"gitInfoStr :: Text",
"gitInfoStr = \"" <> gitInfo <> "\"",
"",
"{-" <> "# NOINLINE buildTimeStr #-}",
"-- | The time of the build.",
"buildTimeStr :: Text",
"buildTimeStr = \"" <> time <> "\"",
""
]
getGitInfoStr :: IO Text
getGitInfoStr = getInfoStr `catch` warnGracefully
where
getInfoStr :: IO Text
getInfoStr = do
eSHA <- readProcessEither "git" ["rev-parse", "--short", "HEAD"] ""
eBranch <- readProcessEither "git" ["rev-parse", "--abbrev-ref", "HEAD"] ""
(exitCode, _, _) <- readProcessWithExitCode "git" ["diff", "--quiet"] ""
let isDirty = exitCode /= SE.ExitSuccess -- exit code signals whether branch is dirty
case (eSHA, eBranch) of
(Right sha, Right branch) ->
return $ gitInfoStr sha branch isDirty
_ -> do
-- ci/cd will create some custom environment variables.
This is required in case of usage of cabal 2.4 or greater .
-- (See for
-- the discussion)
env <- getEnvironment
case ( lookup "GIT_SHA" env,
lookup "GIT_Branch" env
) of
(Just sha, Just branch) ->
return $ gitInfoStr (T.pack branch) (T.pack sha) False
_ -> do
mapM_ print $ lefts [eSHA, eBranch] -- errors during git execution
warnNoCommitInfo
warnGracefully :: IOException -> IO Text
warnGracefully err = do
print (err :: IOException)
warnNoCommitInfo
gitInfoStr :: Text -> Text -> Bool -> Text
gitInfoStr sha branch isDirty =
strip branch <> ":" <> strip sha <> (if isDirty then "*" else "")
strip :: Text -> Text
strip = T.reverse . T.dropWhile isSpace . T.reverse
readProcessEither :: FilePath -> [Text] -> Text -> IO (Either Text Text)
readProcessEither cmd args stdinStr = do
(exitCode, stdoutStr, stderrStr) <- readProcessWithExitCode cmd (map T.unpack args) (T.unpack stdinStr)
case exitCode of
SE.ExitSuccess -> return . Right . T.pack $ stdoutStr
SE.ExitFailure _ -> return . Left . T.pack $ stderrStr
warnNoCommitInfo :: IO Text
warnNoCommitInfo = do
putStrLn ""
putStrLn ""
putStrLn "WARNING: Execution of 'git' command failed."
putStrLn "BuildInfo_Generated.hs will not contain revision information, and"
putStrLn " therefore neither will fatal error messages."
putStrLn " Please check your installation."
return "no git info"
-- | datatype for several kinds of files to be included into the ampersand executable
data FileKind
= -- | Pandoc template files for the generation of documents in different pandoc formats.
PandocTemplates
| -- | The adl script files for formal ampersand
FormalAmpersand
| -- | The adl script files for the prototype context
PrototypeContext
deriving (Show, Eq, Bounded, Enum)
generateStaticFileModule :: IO ()
-- | For each set of files (by FileKind), we generate an Archive value,
which contains the information necessary for Ampersand to create the file at run - time .
--
-- To prevent compiling the generated module (which can get rather big) on each build, we compare the contents
-- the file we are about to generate with the contents of the already generated file and only write if there is a difference.
-- This complicates the build process, but seems the only way to handle large amounts of diverse static
files , until Cabal 's data - files mechanism is updated to allow fully recursive patterns .
generateStaticFileModule = do
previousModuleContents <- getPreviousModuleContents
currentModuleContents <- readAllStaticFiles
let updateRequired = previousModuleContents == currentModuleContents
if updateRequired
then putStrLn $ "Static files unchanged, no need to update " <> sfModulePath
else do
putStrLn $ "Static files have changed, updating " <> sfModulePath
writeFileUtf8 sfModulePath currentModuleContents
where
staticFileModuleName :: Text
staticFileModuleName = "Ampersand.Prototype.StaticFiles_Generated"
sfModulePath = pathFromModuleName staticFileModuleName
getPreviousModuleContents :: IO Text
getPreviousModuleContents = reader `catch` errorHandler
where
reader :: IO Text
reader = readFileUtf8 sfModulePath
errorHandler err = do
-- old generated module exists, but we can't read the file or read the contents
putStrLn $
unlines
[ "",
"Warning: Cannot read previously generated " <> sfModulePath <> ":",
show (err :: SomeException),
"This warning should disappear the next time you build Ampersand. If the error persists, please report this as a bug.",
""
]
return mempty
readAllStaticFiles :: IO Text
readAllStaticFiles = do
templates for several PANDOC output types
formalAmpersandFiles <- readStaticFiles FormalAmpersand "." -- meta information about Ampersand
Context for prototypes that Ampersand generates .
return $ mkStaticFileModule $ pandocTemplatesFiles <> formalAmpersandFiles <> systemContextFiles
readStaticFiles :: FileKind -> FilePath -> IO [(FileKind, Entry)]
readStaticFiles fkind fileOrDirPth = do
let path = base </> fileOrDirPth
isDir <- doesDirectoryExist path
if isDir
then do
fOrDs <- getProperDirectoryContents path
fmap concat $ mapM (\fOrD -> readStaticFiles fkind (fileOrDirPth </> fOrD)) fOrDs
else do
entry <- removeBase <$> readEntry [OptVerbose] (base </> fileOrDirPth)
return [(fkind, entry)]
where
removeBase :: Entry -> Entry
removeBase entry = entry {eRelativePath = rpWithoutBase}
where
rpWithoutBase = stripbase (eRelativePath entry)
stripbase :: FilePath -> FilePath
stripbase fp = case L.stripPrefix (base ++ "/") fp of
Just stripped -> stripped
Nothing ->
error . L.intercalate "\n" $
[ "ERROR: Reading static files failed:",
" base: " <> base,
" fp : " <> fp
]
base = case fkind of
PandocTemplates -> "outputTemplates"
FormalAmpersand -> "AmpersandData/FormalAmpersand"
PrototypeContext -> "AmpersandData/PrototypeContext"
mkStaticFileModule :: [(FileKind, Entry)] -> Text
mkStaticFileModule xs =
T.unlines staticFileModuleHeader
<> " [ "
<> T.intercalate "\n , " (map toText archives)
<> "\n"
<> " ]\n"
where
toText :: (FileKind, Archive) -> Text
toText (fk, archive) = "SF " <> tshow fk <> " " <> tshow archive
archives :: [(FileKind, Archive)]
archives = map mkArchive $ NE.groupBy tst xs
where
tst :: (FileKind, a) -> (FileKind, a) -> Bool
tst a b = fst a == fst b
mkArchive :: NE.NonEmpty (FileKind, Entry) -> (FileKind, Archive)
mkArchive entries =
( fst . NE.head $ entries,
foldr addEntryToArchive emptyArchive $ snd <$> NE.toList entries
)
staticFileModuleHeader :: [Text]
staticFileModuleHeader =
[ "{-# LANGUAGE OverloadedStrings #-}",
"module " <> staticFileModuleName,
" ( FileKind(..)",
" , getStaticFileContent",
" )",
"where",
"import Ampersand.Basics",
"import Codec.Archive.Zip",
"import qualified RIO.ByteString as B",
"import qualified RIO.ByteString.Lazy as BL",
"import qualified RIO.Text as T",
"",
"data FileKind = PandocTemplates | FormalAmpersand | PrototypeContext deriving (Show, Eq)",
"data StaticFile = SF FileKind Archive",
"",
"getStaticFileContent :: FileKind -> FilePath -> Maybe B.ByteString",
"getStaticFileContent fk fp = BL.toStrict <$>",
" case filter isRightArchive allStaticFiles of",
" [SF _ a] -> case findEntryByPath fp a of",
" Just entry -> Just $ fromEntry entry",
" Nothing -> fatal . T.intercalate \"\\n\" $ ",
" [ \"Looking for file: \"<>tshow fp",
" , \"in archive: \"<>tshow fk",
" , \"Archive found. it contains:\"",
" ]++map ((\" \" <>) . showEntry) (zEntries a)",
" xs -> fatal . T.intercalate \"\\n\" $",
" [ \"Looking for file: \"<>tshow fp",
" , \"in archive: \"<>tshow fk",
" ]++showArchives xs",
" where",
" isRightArchive :: StaticFile -> Bool",
" isRightArchive (SF fKind _) = fKind == fk",
" showEntry :: Entry -> Text",
" showEntry = tshow . eRelativePath ",
" showArchives :: [StaticFile] -> [Text]",
" showArchives xs = ",
" ( \"Number of archives: \"<>tshow (length xs)",
" ):",
" concatMap showSF xs",
" where",
" showSF :: StaticFile -> [Text]",
" showSF (SF fKind archive) = ",
" [ \" Archive: \"<>tshow fKind<>\" (\"<>(tshow . length . zEntries $ archive)<>\" entries)\"",
" ]",
"",
Workaround : break pragma start { - # , since it upsets Eclipse :-(
"allStaticFiles :: [StaticFile]",
"allStaticFiles = "
]
getProperDirectoryContents :: FilePath -> IO [FilePath]
getProperDirectoryContents fp = filter (`notElem` [".", "..", ".git"]) <$> getDirectoryContents fp
pathFromModuleName :: Text -> FilePath
pathFromModuleName m = T.unpack $ "src/" <> T.map (\c -> if c == '.' then '/' else c) m <> ".hs"
| null | https://raw.githubusercontent.com/AmpersandTarski/Ampersand/776767e0b2e2a8676ff204d624e6549d4b44018a/Setup.hs | haskell | # LANGUAGE OverloadedStrings #
| Before each build, generate a BuildInfo_Generated module that exports the project version from cabal,
the current revision number and the build time. Also generate a file that contains files that
are being included into the ampersand.exe file
Note that in order for this Setup.hs to be used by cabal, the build-type should be Custom.
| Generate Haskell modules that are required for the build and start the build
start the build
| Generate Haskell modules that are required for the build and start the build
start the build
only during build time.
disable inlining to prevent recompilation of dependent modules on each build
exit code signals whether branch is dirty
ci/cd will create some custom environment variables.
(See for
the discussion)
errors during git execution
| datatype for several kinds of files to be included into the ampersand executable
| Pandoc template files for the generation of documents in different pandoc formats.
| The adl script files for formal ampersand
| The adl script files for the prototype context
| For each set of files (by FileKind), we generate an Archive value,
To prevent compiling the generated module (which can get rather big) on each build, we compare the contents
the file we are about to generate with the contents of the already generated file and only write if there is a difference.
This complicates the build process, but seems the only way to handle large amounts of diverse static
old generated module exists, but we can't read the file or read the contents
meta information about Ampersand |
module Main where
import qualified Codec . Compression . as replace by Codec . Archive . Zip from package zip - archive . This reduces the amount of packages . ( We now use two for zipping / unzipping )
import Codec.Archive.Zip
import Distribution.PackageDescription
import Distribution.Pretty (prettyShow)
import Distribution.Simple
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Setup
import RIO
import RIO.Char
import qualified RIO.List as L
import qualified RIO.NonEmpty as NE
import qualified RIO.Text as T
import RIO.Time
import System.Directory
import System.Environment (getEnvironment)
import qualified System.Exit as SE
import System.FilePath
import System.Process (readProcessWithExitCode)
import Prelude (print, putStrLn)
main :: IO ()
main =
defaultMainWithHooks
simpleUserHooks
{ buildHook = customBuildHook,
replHook = customReplHook
}
customBuildHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> BuildFlags -> IO ()
customBuildHook pd lbi uh bf = do
generateBuildInfoModule (T.pack . prettyShow . pkgVersion . package $ pd)
generateStaticFileModule
customReplHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> ReplFlags -> [String] -> IO ()
customReplHook pd lbi uh rf args = do
generateBuildInfoModule (T.pack . prettyShow . pkgVersion . package $ pd)
generateStaticFileModule
generateBuildInfoModule :: Text -> IO ()
| Generate a Haskell module that contains information that is available
generateBuildInfoModule cabalVersionStr = do
content <-
buildInfoModule cabalVersionStr
<$> getGitInfoStr
<*> ( T.pack . formatTime defaultTimeLocale "%d-%b-%y %H:%M:%S %Z"
<$> (getCurrentTime >>= utcToLocalZonedTime)
)
writeFileUtf8 (pathFromModuleName buildInfoModuleName) content
where
buildInfoModuleName :: Text
buildInfoModuleName = "Ampersand.Basics.BuildInfo_Generated"
buildInfoModule :: Text -> Text -> Text -> Text
buildInfoModule cabalVersion gitInfo time =
T.unlines
[ "{-# LANGUAGE OverloadedStrings #-}",
"-- | This module is generated automatically by Setup.hs before building. Do not edit!",
"-- It contains some functions that are supposed to grab information at the time of",
"-- building the ampersand executable.",
"module " <> buildInfoModuleName <> "(",
" cabalVersionStr",
" , gitInfoStr",
" , buildTimeStr",
" ) where",
"import Ampersand.Basics.Prelude",
"",
"-- | The version of Ampersand as it is stated in the package.yaml file.",
"cabalVersionStr :: Text",
"cabalVersionStr = \"" <> cabalVersion <> "\"",
"",
"{-" <> "# NOINLINE gitInfoStr #-}",
"-- | The version of Ampersand as seen by Git.",
"gitInfoStr :: Text",
"gitInfoStr = \"" <> gitInfo <> "\"",
"",
"{-" <> "# NOINLINE buildTimeStr #-}",
"-- | The time of the build.",
"buildTimeStr :: Text",
"buildTimeStr = \"" <> time <> "\"",
""
]
getGitInfoStr :: IO Text
getGitInfoStr = getInfoStr `catch` warnGracefully
where
getInfoStr :: IO Text
getInfoStr = do
eSHA <- readProcessEither "git" ["rev-parse", "--short", "HEAD"] ""
eBranch <- readProcessEither "git" ["rev-parse", "--abbrev-ref", "HEAD"] ""
(exitCode, _, _) <- readProcessWithExitCode "git" ["diff", "--quiet"] ""
case (eSHA, eBranch) of
(Right sha, Right branch) ->
return $ gitInfoStr sha branch isDirty
_ -> do
This is required in case of usage of cabal 2.4 or greater .
env <- getEnvironment
case ( lookup "GIT_SHA" env,
lookup "GIT_Branch" env
) of
(Just sha, Just branch) ->
return $ gitInfoStr (T.pack branch) (T.pack sha) False
_ -> do
warnNoCommitInfo
warnGracefully :: IOException -> IO Text
warnGracefully err = do
print (err :: IOException)
warnNoCommitInfo
gitInfoStr :: Text -> Text -> Bool -> Text
gitInfoStr sha branch isDirty =
strip branch <> ":" <> strip sha <> (if isDirty then "*" else "")
strip :: Text -> Text
strip = T.reverse . T.dropWhile isSpace . T.reverse
readProcessEither :: FilePath -> [Text] -> Text -> IO (Either Text Text)
readProcessEither cmd args stdinStr = do
(exitCode, stdoutStr, stderrStr) <- readProcessWithExitCode cmd (map T.unpack args) (T.unpack stdinStr)
case exitCode of
SE.ExitSuccess -> return . Right . T.pack $ stdoutStr
SE.ExitFailure _ -> return . Left . T.pack $ stderrStr
warnNoCommitInfo :: IO Text
warnNoCommitInfo = do
putStrLn ""
putStrLn ""
putStrLn "WARNING: Execution of 'git' command failed."
putStrLn "BuildInfo_Generated.hs will not contain revision information, and"
putStrLn " therefore neither will fatal error messages."
putStrLn " Please check your installation."
return "no git info"
data FileKind
PandocTemplates
FormalAmpersand
PrototypeContext
deriving (Show, Eq, Bounded, Enum)
generateStaticFileModule :: IO ()
which contains the information necessary for Ampersand to create the file at run - time .
files , until Cabal 's data - files mechanism is updated to allow fully recursive patterns .
generateStaticFileModule = do
previousModuleContents <- getPreviousModuleContents
currentModuleContents <- readAllStaticFiles
let updateRequired = previousModuleContents == currentModuleContents
if updateRequired
then putStrLn $ "Static files unchanged, no need to update " <> sfModulePath
else do
putStrLn $ "Static files have changed, updating " <> sfModulePath
writeFileUtf8 sfModulePath currentModuleContents
where
staticFileModuleName :: Text
staticFileModuleName = "Ampersand.Prototype.StaticFiles_Generated"
sfModulePath = pathFromModuleName staticFileModuleName
getPreviousModuleContents :: IO Text
getPreviousModuleContents = reader `catch` errorHandler
where
reader :: IO Text
reader = readFileUtf8 sfModulePath
errorHandler err = do
putStrLn $
unlines
[ "",
"Warning: Cannot read previously generated " <> sfModulePath <> ":",
show (err :: SomeException),
"This warning should disappear the next time you build Ampersand. If the error persists, please report this as a bug.",
""
]
return mempty
readAllStaticFiles :: IO Text
readAllStaticFiles = do
templates for several PANDOC output types
Context for prototypes that Ampersand generates .
return $ mkStaticFileModule $ pandocTemplatesFiles <> formalAmpersandFiles <> systemContextFiles
readStaticFiles :: FileKind -> FilePath -> IO [(FileKind, Entry)]
readStaticFiles fkind fileOrDirPth = do
let path = base </> fileOrDirPth
isDir <- doesDirectoryExist path
if isDir
then do
fOrDs <- getProperDirectoryContents path
fmap concat $ mapM (\fOrD -> readStaticFiles fkind (fileOrDirPth </> fOrD)) fOrDs
else do
entry <- removeBase <$> readEntry [OptVerbose] (base </> fileOrDirPth)
return [(fkind, entry)]
where
removeBase :: Entry -> Entry
removeBase entry = entry {eRelativePath = rpWithoutBase}
where
rpWithoutBase = stripbase (eRelativePath entry)
stripbase :: FilePath -> FilePath
stripbase fp = case L.stripPrefix (base ++ "/") fp of
Just stripped -> stripped
Nothing ->
error . L.intercalate "\n" $
[ "ERROR: Reading static files failed:",
" base: " <> base,
" fp : " <> fp
]
base = case fkind of
PandocTemplates -> "outputTemplates"
FormalAmpersand -> "AmpersandData/FormalAmpersand"
PrototypeContext -> "AmpersandData/PrototypeContext"
mkStaticFileModule :: [(FileKind, Entry)] -> Text
mkStaticFileModule xs =
T.unlines staticFileModuleHeader
<> " [ "
<> T.intercalate "\n , " (map toText archives)
<> "\n"
<> " ]\n"
where
toText :: (FileKind, Archive) -> Text
toText (fk, archive) = "SF " <> tshow fk <> " " <> tshow archive
archives :: [(FileKind, Archive)]
archives = map mkArchive $ NE.groupBy tst xs
where
tst :: (FileKind, a) -> (FileKind, a) -> Bool
tst a b = fst a == fst b
mkArchive :: NE.NonEmpty (FileKind, Entry) -> (FileKind, Archive)
mkArchive entries =
( fst . NE.head $ entries,
foldr addEntryToArchive emptyArchive $ snd <$> NE.toList entries
)
staticFileModuleHeader :: [Text]
staticFileModuleHeader =
[ "{-# LANGUAGE OverloadedStrings #-}",
"module " <> staticFileModuleName,
" ( FileKind(..)",
" , getStaticFileContent",
" )",
"where",
"import Ampersand.Basics",
"import Codec.Archive.Zip",
"import qualified RIO.ByteString as B",
"import qualified RIO.ByteString.Lazy as BL",
"import qualified RIO.Text as T",
"",
"data FileKind = PandocTemplates | FormalAmpersand | PrototypeContext deriving (Show, Eq)",
"data StaticFile = SF FileKind Archive",
"",
"getStaticFileContent :: FileKind -> FilePath -> Maybe B.ByteString",
"getStaticFileContent fk fp = BL.toStrict <$>",
" case filter isRightArchive allStaticFiles of",
" [SF _ a] -> case findEntryByPath fp a of",
" Just entry -> Just $ fromEntry entry",
" Nothing -> fatal . T.intercalate \"\\n\" $ ",
" [ \"Looking for file: \"<>tshow fp",
" , \"in archive: \"<>tshow fk",
" , \"Archive found. it contains:\"",
" ]++map ((\" \" <>) . showEntry) (zEntries a)",
" xs -> fatal . T.intercalate \"\\n\" $",
" [ \"Looking for file: \"<>tshow fp",
" , \"in archive: \"<>tshow fk",
" ]++showArchives xs",
" where",
" isRightArchive :: StaticFile -> Bool",
" isRightArchive (SF fKind _) = fKind == fk",
" showEntry :: Entry -> Text",
" showEntry = tshow . eRelativePath ",
" showArchives :: [StaticFile] -> [Text]",
" showArchives xs = ",
" ( \"Number of archives: \"<>tshow (length xs)",
" ):",
" concatMap showSF xs",
" where",
" showSF :: StaticFile -> [Text]",
" showSF (SF fKind archive) = ",
" [ \" Archive: \"<>tshow fKind<>\" (\"<>(tshow . length . zEntries $ archive)<>\" entries)\"",
" ]",
"",
Workaround : break pragma start { - # , since it upsets Eclipse :-(
"allStaticFiles :: [StaticFile]",
"allStaticFiles = "
]
getProperDirectoryContents :: FilePath -> IO [FilePath]
getProperDirectoryContents fp = filter (`notElem` [".", "..", ".git"]) <$> getDirectoryContents fp
pathFromModuleName :: Text -> FilePath
pathFromModuleName m = T.unpack $ "src/" <> T.map (\c -> if c == '.' then '/' else c) m <> ".hs"
|
6914b3700b40b51cdace9fe1319e037b33fac1fb152a5d077d8f9e931b60d6b0 | tmattio/tyxml-components | my_story.ml | open Incr_dom.Tyxml.Html
let view =
Tyxml_stories.Component.make
~title:"My story component"
~code:{|
The demo code goes here.
|}
(div ~a:[ a_class [ "space-y-6 p-4" ] ] [ p [ txt "Hello world" ] ])
let () = Tyxml_stories.add ~name:"My story" ~url:"/hello-world" view
| null | https://raw.githubusercontent.com/tmattio/tyxml-components/57603f51ba81bb786a8364eaf9957d65743fd591/example/lib/my_story.ml | ocaml | open Incr_dom.Tyxml.Html
let view =
Tyxml_stories.Component.make
~title:"My story component"
~code:{|
The demo code goes here.
|}
(div ~a:[ a_class [ "space-y-6 p-4" ] ] [ p [ txt "Hello world" ] ])
let () = Tyxml_stories.add ~name:"My story" ~url:"/hello-world" view
| |
b6c19602ed0e80817ff22f70d34c37b7a8c3e4ce4955c9403c6b50c131c64147 | agda/agda | ImpossibleTest.hs | -- | Facility to test throwing internal errors.
module Agda.ImpossibleTest where
import Agda.TypeChecking.Monad.Base ( TCM, ReduceM, runReduceM )
import Agda.TypeChecking.Monad.Debug ( MonadDebug, __IMPOSSIBLE_VERBOSE__ )
import Agda.TypeChecking.Reduce.Monad ()
import Agda.Utils.CallStack ( HasCallStack )
import Agda.Utils.Impossible ( __IMPOSSIBLE__ )
-- | If the given list of words is non-empty, print them as debug message
-- (using '__IMPOSSIBLE_VERBOSE__') before raising the internal error.
impossibleTest :: (MonadDebug m, HasCallStack) => [String] -> m a
impossibleTest = \case
[] -> __IMPOSSIBLE__
strs -> __IMPOSSIBLE_VERBOSE__ $ unwords strs
impossibleTestReduceM :: (HasCallStack) => [String] -> TCM a
impossibleTestReduceM = runReduceM . \case
[] -> __IMPOSSIBLE__
strs -> __IMPOSSIBLE_VERBOSE__ $ unwords strs
| null | https://raw.githubusercontent.com/agda/agda/f6b86860cb6fa2203d28080d6e761d3e514bcfdf/src/full/Agda/ImpossibleTest.hs | haskell | | Facility to test throwing internal errors.
| If the given list of words is non-empty, print them as debug message
(using '__IMPOSSIBLE_VERBOSE__') before raising the internal error. |
module Agda.ImpossibleTest where
import Agda.TypeChecking.Monad.Base ( TCM, ReduceM, runReduceM )
import Agda.TypeChecking.Monad.Debug ( MonadDebug, __IMPOSSIBLE_VERBOSE__ )
import Agda.TypeChecking.Reduce.Monad ()
import Agda.Utils.CallStack ( HasCallStack )
import Agda.Utils.Impossible ( __IMPOSSIBLE__ )
impossibleTest :: (MonadDebug m, HasCallStack) => [String] -> m a
impossibleTest = \case
[] -> __IMPOSSIBLE__
strs -> __IMPOSSIBLE_VERBOSE__ $ unwords strs
impossibleTestReduceM :: (HasCallStack) => [String] -> TCM a
impossibleTestReduceM = runReduceM . \case
[] -> __IMPOSSIBLE__
strs -> __IMPOSSIBLE_VERBOSE__ $ unwords strs
|
555a6b77a80e6c6d413d8037c2db59cb46a319916c91799431ef1a4ad77537e6 | mzp/coq-ide-for-ios | xml.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// * The HELM Project / The EU MoWGLI Project
* University of Bologna
(************************************************************************)
(* This file is distributed under the terms of the *)
GNU Lesser General Public License Version 2.1
(* *)
Copyright ( C ) 2000 - 2004 , HELM Team .
(* *)
(************************************************************************)
i $ I d : xml.mli 13323 2010 - 07 - 24 15:57:30Z herbelin $ i
Tokens for , empty elements and not - empty elements
(* Usage: *)
Str cdata
Empty ( element_name , [ , ; ... ; attrnamen , valuen ]
( element_name , [ , value2 ; ... ; attrnamen , valuen ] ,
(* content *)
type token =
| Str of string
| Empty of string * (string * string) list
| NEmpty of string * (string * string) list * token Stream.t
(* currified versions of the token constructors make the code more readable *)
val xml_empty : string -> (string * string) list -> token Stream.t
val xml_nempty :
string -> (string * string) list -> token Stream.t -> token Stream.t
val xml_cdata : string -> token Stream.t
val pp_ch : token Stream.t -> out_channel -> unit
(* The pretty printer for streams of token *)
(* Usage: *)
pp tokens None pretty prints the output on stdout
(* pp tokens (Some filename) pretty prints the output on the file filename *)
val pp : token Stream.t -> string option -> unit
| null | https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/CoqIDE/coq-8.2pl2/plugins/xml/xml.mli | ocaml | **********************************************************************
**********************************************************************
This file is distributed under the terms of the
**********************************************************************
Usage:
content
currified versions of the token constructors make the code more readable
The pretty printer for streams of token
Usage:
pp tokens (Some filename) pretty prints the output on the file filename | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// * The HELM Project / The EU MoWGLI Project
* University of Bologna
GNU Lesser General Public License Version 2.1
Copyright ( C ) 2000 - 2004 , HELM Team .
i $ I d : xml.mli 13323 2010 - 07 - 24 15:57:30Z herbelin $ i
Tokens for , empty elements and not - empty elements
Str cdata
Empty ( element_name , [ , ; ... ; attrnamen , valuen ]
( element_name , [ , value2 ; ... ; attrnamen , valuen ] ,
type token =
| Str of string
| Empty of string * (string * string) list
| NEmpty of string * (string * string) list * token Stream.t
val xml_empty : string -> (string * string) list -> token Stream.t
val xml_nempty :
string -> (string * string) list -> token Stream.t -> token Stream.t
val xml_cdata : string -> token Stream.t
val pp_ch : token Stream.t -> out_channel -> unit
pp tokens None pretty prints the output on stdout
val pp : token Stream.t -> string option -> unit
|
fbba48be7584d78991bd70d44eac07f16d59191d9c18f80af3696034a1b75602 | interactive-ssr/issr-server | hooks.lisp | (in-package #:issr.server)
(defun server-uuid ()
(let ((filename
(merge-pathnames
"issr/uuid.txt"
(or (uiop:getenvp "XDG_DATA_HOME")
"~/.local/share/"))))
(unless (uiop:directory-exists-p (pathname-directory filename))
(ensure-directories-exist filename))
(if (uiop:file-exists-p filename)
(uiop:read-file-string filename)
(with-open-file (out filename
:direction :output
:if-does-not-exist :create)
(let ((uuid (princ-to-string (uuid:make-v4-uuid))))
(write-sequence uuid out))))))
(defvar *hook-listener-name* "issr-server-hook-listener")
(defun start-hook-listener (host port show-errors redis-host redis-port redis-pass)
(bt:make-thread
(lambda ()
(block exit
(loop
(block continue
(handler-case
(handler-bind
((redis:redis-error-reply
(lambda (c)
(when (str:containsp "WRONGPASS"
(redis:redis-error-message c))
(format *error-output*
(str:concat
"Could not connect to redis. "
"This is likely something wrong with your redis-config. "
"Make sure you are connecting to the correct redis-server with the correct password. "
"If you redis destination is just `6379', make sure there are no redis servers on that port since ISSR-server will try to start one there.~%"))
(uiop:quit)))))
(redis:with-connection (:host redis-host :port redis-port :auth redis-pass)
(format t "Connected to redis.~%")
(red:subscribe "issr-rr")
(loop
(let ((message (redis:expect :anything)))
(bt:make-thread
(lambda ()
(match (jojo:parse (third message) :as :alist)
((guard (list uuid client-id args)
(string= uuid (server-uuid)))
(redis:with-connection (:host redis-host :port redis-port :auth redis-pass)
(some-> client-id
get-id-client
(rr host port show-errors args))))))
:name "re-rendering")))))
(end-of-file () (return-from exit))
(usocket:connection-refused-error ()
(sleep 2)
(format t "Trying to connect to redis.~%")
(return-from continue)))))))
:name *hook-listener-name*))
(defun stop-hook-listener ()
(let ((hook-listeners
(remove *hook-listener-name*
(bt:all-threads)
:key 'bt:thread-name
:test-not 'string=)))
(when hook-listeners
(mapc 'bt:destroy-thread hook-listeners))))
| null | https://raw.githubusercontent.com/interactive-ssr/issr-server/e828e3ea6c6a711f27ceee5a80d3646a89473768/src/hooks.lisp | lisp | (in-package #:issr.server)
(defun server-uuid ()
(let ((filename
(merge-pathnames
"issr/uuid.txt"
(or (uiop:getenvp "XDG_DATA_HOME")
"~/.local/share/"))))
(unless (uiop:directory-exists-p (pathname-directory filename))
(ensure-directories-exist filename))
(if (uiop:file-exists-p filename)
(uiop:read-file-string filename)
(with-open-file (out filename
:direction :output
:if-does-not-exist :create)
(let ((uuid (princ-to-string (uuid:make-v4-uuid))))
(write-sequence uuid out))))))
(defvar *hook-listener-name* "issr-server-hook-listener")
(defun start-hook-listener (host port show-errors redis-host redis-port redis-pass)
(bt:make-thread
(lambda ()
(block exit
(loop
(block continue
(handler-case
(handler-bind
((redis:redis-error-reply
(lambda (c)
(when (str:containsp "WRONGPASS"
(redis:redis-error-message c))
(format *error-output*
(str:concat
"Could not connect to redis. "
"This is likely something wrong with your redis-config. "
"Make sure you are connecting to the correct redis-server with the correct password. "
"If you redis destination is just `6379', make sure there are no redis servers on that port since ISSR-server will try to start one there.~%"))
(uiop:quit)))))
(redis:with-connection (:host redis-host :port redis-port :auth redis-pass)
(format t "Connected to redis.~%")
(red:subscribe "issr-rr")
(loop
(let ((message (redis:expect :anything)))
(bt:make-thread
(lambda ()
(match (jojo:parse (third message) :as :alist)
((guard (list uuid client-id args)
(string= uuid (server-uuid)))
(redis:with-connection (:host redis-host :port redis-port :auth redis-pass)
(some-> client-id
get-id-client
(rr host port show-errors args))))))
:name "re-rendering")))))
(end-of-file () (return-from exit))
(usocket:connection-refused-error ()
(sleep 2)
(format t "Trying to connect to redis.~%")
(return-from continue)))))))
:name *hook-listener-name*))
(defun stop-hook-listener ()
(let ((hook-listeners
(remove *hook-listener-name*
(bt:all-threads)
:key 'bt:thread-name
:test-not 'string=)))
(when hook-listeners
(mapc 'bt:destroy-thread hook-listeners))))
| |
6a9e6d45d24569794ee24ce5da3407484823dc62b66a65785e41689ae345c977 | haskell/aeson | ErrorMessages.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
module ErrorMessages
(
tests
) where
import Prelude.Compat
import Data.Aeson (FromJSON(..), Value, json)
import Data.Aeson.Types (Parser, formatError, iparse)
import Data.Aeson.Parser (eitherDecodeWith)
import Data.Algorithm.Diff (PolyDiff (..), getGroupedDiff)
import Data.Proxy (Proxy(..))
import Data.Semigroup ((<>))
import Data.Sequence (Seq)
import Instances ()
import Numeric.Natural (Natural)
import Test.Tasty (TestTree, TestName)
import Test.Tasty.Golden.Advanced (goldenTest)
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.HashMap.Strict as HM
import Encoders
import Types
tests :: [TestTree]
tests =
[ aesonGoldenTest "simple" "tests/golden/simple.expected" output
, aesonGoldenTest "generic" "tests/golden/generic.expected" (outputGeneric G)
, aesonGoldenTest "generic" "tests/golden/th.expected" (outputGeneric TH)
]
output :: Output
output = concat
[ testFor "Int" (Proxy :: Proxy Int)
[ "\"\""
, "[]"
, "{}"
, "null"
]
, testFor "Integer" (Proxy :: Proxy Integer)
[ "44.44"
]
, testFor "Natural" (Proxy :: Proxy Natural)
[ "44.44"
, "-50"
]
, testFor "String" (Proxy :: Proxy String)
[ "1"
, "[]"
, "{}"
, "null"
]
, testFor "HashMap" (Proxy :: Proxy (HM.HashMap String Int))
[ "\"\""
, "[]"
]
issue # 356
, testFor "Either" (Proxy :: Proxy (Int, Either (Int, Bool) ()))
[ "[1,{\"Left\":[2,3]}]"
]
issue # 358
, testFor "Seq" (Proxy :: Proxy (Seq Int))
[ "[0,1,true]"
]
]
data Choice = TH | G
outputGeneric :: Choice -> Output
outputGeneric choice = concat
[ testWith "OneConstructor"
(select
thOneConstructorParseJSONDefault
gOneConstructorParseJSONDefault)
[ "\"X\""
, "[0]"
]
, testWith "Nullary"
(select
thNullaryParseJSONString
gNullaryParseJSONString)
[ "\"X\""
, "[]"
]
, testWithSomeType "SomeType (tagged)"
(select
thSomeTypeParseJSONTaggedObject
gSomeTypeParseJSONTaggedObject)
[ "{\"tag\": \"unary\", \"contents\": true}"
, "{\"tag\": \"unary\"}"
, "{\"tag\": \"record\"}"
, "{\"tag\": \"record\", \"testone\": true, \"testtwo\": null, \"testthree\": null}"
, "{\"tag\": \"X\"}"
, "{}"
, "[]"
]
, testWithSomeType "SomeType (single-field)"
(select
thSomeTypeParseJSONObjectWithSingleField
gSomeTypeParseJSONObjectWithSingleField)
[ "{\"unary\": {}}"
, "{\"unary\": []}"
, "{\"X\": []}"
, "{\"record\": {}, \"W\":{}}"
, "{}"
, "[]"
, "{\"unary\""
, "{\"unary\":"
, "{\"unary\":1"
]
, testWithSomeType "SomeType (two-element array)"
(select
thSomeTypeParseJSON2ElemArray
gSomeTypeParseJSON2ElemArray)
[ "[\"unary\", true]"
, "[\"record\", null]"
, "[\"X\", 0]"
, "[null, 0]"
, "[]"
, "{}"
, "[1"
, "[1,"
]
, testWithSomeType "SomeType (reject unknown fields)"
(select
thSomeTypeParseJSONRejectUnknownFields
gSomeTypeParseJSONRejectUnknownFields)
[ "{\"tag\": \"record\", \"testone\": 1.0, \"testZero\": 1}"
, "{\"testZero\": 1}"
, "{\"tag\": \"record\", \"testone\": true, \"testtwo\": null, \"testthree\": null}"
]
, testWithFoo "Foo (reject unknown fields)"
(select
thFooParseJSONRejectUnknownFields
gFooParseJSONRejectUnknownFields)
[ "{\"tag\": \"foo\"}"
]
, testWithFoo "Foo (reject unknown fields, tagged single)"
(select
thFooParseJSONRejectUnknownFieldsTagged
gFooParseJSONRejectUnknownFieldsTagged)
[ "{\"tag\": \"foo\", \"unknownField\": 0}"
]
, testWith "EitherTextInt"
(select
thEitherTextIntParseJSONUntaggedValue
gEitherTextIntParseJSONUntaggedValue)
[ "\"X\""
, "[]"
]
, testWith "Product2 Int Bool"
(select
thProduct2ParseJSON
gProduct2ParseJSON)
[ "[1, null]"
, "[]"
, "{}"
]
]
where
select a b = case choice of
TH -> a
G -> b
-- Test infrastructure
type Output = [String]
outputLine :: String -> Output
outputLine = pure
aesonGoldenTest :: TestName -> FilePath -> Output -> TestTree
aesonGoldenTest name ref out = goldenTest name (L.readFile ref) act cmp upd
where
act = pure (L.pack (unlines out))
upd = L.writeFile ref
cmp x y | x == y = return Nothing
cmp x y = return $ Just $ unlines $
concatMap f (getGroupedDiff (L.lines x) (L.lines y))
where
f (First xs) = map (cons3 '-' . L.unpack) xs
f (Second ys) = map (cons3 '+' . L.unpack) ys
-- we print unchanged lines too. It shouldn't be a problem while we have
-- reasonably small examples
f (Both xs _) = map (cons3 ' ' . L.unpack) xs
we add three characters , so the changed lines are easier to spot
cons3 c cs = c : c : c : ' ' : cs
testWith :: Show a => String -> (Value -> Parser a) -> [L.ByteString] -> Output
testWith name parser ts =
outputLine name <>
foldMap (\s ->
case eitherDecodeWith json (iparse parser) s of
Left err -> outputLine $ uncurry formatError err
Right a -> outputLine $ show a) ts
testFor :: forall a proxy. (FromJSON a, Show a)
=> String -> proxy a -> [L.ByteString] -> Output
testFor name _ = testWith name (parseJSON :: Value -> Parser a)
testWithSomeType :: String -> (Value -> Parser (SomeType Int)) -> [L.ByteString] -> Output
testWithSomeType = testWith
testWithFoo :: String -> (Value -> Parser Foo) -> [L.ByteString] -> Output
testWithFoo = testWith
| null | https://raw.githubusercontent.com/haskell/aeson/78c2338c20d31ba5dd46036d10d6c4815c12185d/tests/ErrorMessages.hs | haskell | # LANGUAGE OverloadedStrings #
Test infrastructure
we print unchanged lines too. It shouldn't be a problem while we have
reasonably small examples | # LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
module ErrorMessages
(
tests
) where
import Prelude.Compat
import Data.Aeson (FromJSON(..), Value, json)
import Data.Aeson.Types (Parser, formatError, iparse)
import Data.Aeson.Parser (eitherDecodeWith)
import Data.Algorithm.Diff (PolyDiff (..), getGroupedDiff)
import Data.Proxy (Proxy(..))
import Data.Semigroup ((<>))
import Data.Sequence (Seq)
import Instances ()
import Numeric.Natural (Natural)
import Test.Tasty (TestTree, TestName)
import Test.Tasty.Golden.Advanced (goldenTest)
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.HashMap.Strict as HM
import Encoders
import Types
tests :: [TestTree]
tests =
[ aesonGoldenTest "simple" "tests/golden/simple.expected" output
, aesonGoldenTest "generic" "tests/golden/generic.expected" (outputGeneric G)
, aesonGoldenTest "generic" "tests/golden/th.expected" (outputGeneric TH)
]
output :: Output
output = concat
[ testFor "Int" (Proxy :: Proxy Int)
[ "\"\""
, "[]"
, "{}"
, "null"
]
, testFor "Integer" (Proxy :: Proxy Integer)
[ "44.44"
]
, testFor "Natural" (Proxy :: Proxy Natural)
[ "44.44"
, "-50"
]
, testFor "String" (Proxy :: Proxy String)
[ "1"
, "[]"
, "{}"
, "null"
]
, testFor "HashMap" (Proxy :: Proxy (HM.HashMap String Int))
[ "\"\""
, "[]"
]
issue # 356
, testFor "Either" (Proxy :: Proxy (Int, Either (Int, Bool) ()))
[ "[1,{\"Left\":[2,3]}]"
]
issue # 358
, testFor "Seq" (Proxy :: Proxy (Seq Int))
[ "[0,1,true]"
]
]
data Choice = TH | G
outputGeneric :: Choice -> Output
outputGeneric choice = concat
[ testWith "OneConstructor"
(select
thOneConstructorParseJSONDefault
gOneConstructorParseJSONDefault)
[ "\"X\""
, "[0]"
]
, testWith "Nullary"
(select
thNullaryParseJSONString
gNullaryParseJSONString)
[ "\"X\""
, "[]"
]
, testWithSomeType "SomeType (tagged)"
(select
thSomeTypeParseJSONTaggedObject
gSomeTypeParseJSONTaggedObject)
[ "{\"tag\": \"unary\", \"contents\": true}"
, "{\"tag\": \"unary\"}"
, "{\"tag\": \"record\"}"
, "{\"tag\": \"record\", \"testone\": true, \"testtwo\": null, \"testthree\": null}"
, "{\"tag\": \"X\"}"
, "{}"
, "[]"
]
, testWithSomeType "SomeType (single-field)"
(select
thSomeTypeParseJSONObjectWithSingleField
gSomeTypeParseJSONObjectWithSingleField)
[ "{\"unary\": {}}"
, "{\"unary\": []}"
, "{\"X\": []}"
, "{\"record\": {}, \"W\":{}}"
, "{}"
, "[]"
, "{\"unary\""
, "{\"unary\":"
, "{\"unary\":1"
]
, testWithSomeType "SomeType (two-element array)"
(select
thSomeTypeParseJSON2ElemArray
gSomeTypeParseJSON2ElemArray)
[ "[\"unary\", true]"
, "[\"record\", null]"
, "[\"X\", 0]"
, "[null, 0]"
, "[]"
, "{}"
, "[1"
, "[1,"
]
, testWithSomeType "SomeType (reject unknown fields)"
(select
thSomeTypeParseJSONRejectUnknownFields
gSomeTypeParseJSONRejectUnknownFields)
[ "{\"tag\": \"record\", \"testone\": 1.0, \"testZero\": 1}"
, "{\"testZero\": 1}"
, "{\"tag\": \"record\", \"testone\": true, \"testtwo\": null, \"testthree\": null}"
]
, testWithFoo "Foo (reject unknown fields)"
(select
thFooParseJSONRejectUnknownFields
gFooParseJSONRejectUnknownFields)
[ "{\"tag\": \"foo\"}"
]
, testWithFoo "Foo (reject unknown fields, tagged single)"
(select
thFooParseJSONRejectUnknownFieldsTagged
gFooParseJSONRejectUnknownFieldsTagged)
[ "{\"tag\": \"foo\", \"unknownField\": 0}"
]
, testWith "EitherTextInt"
(select
thEitherTextIntParseJSONUntaggedValue
gEitherTextIntParseJSONUntaggedValue)
[ "\"X\""
, "[]"
]
, testWith "Product2 Int Bool"
(select
thProduct2ParseJSON
gProduct2ParseJSON)
[ "[1, null]"
, "[]"
, "{}"
]
]
where
select a b = case choice of
TH -> a
G -> b
type Output = [String]
outputLine :: String -> Output
outputLine = pure
aesonGoldenTest :: TestName -> FilePath -> Output -> TestTree
aesonGoldenTest name ref out = goldenTest name (L.readFile ref) act cmp upd
where
act = pure (L.pack (unlines out))
upd = L.writeFile ref
cmp x y | x == y = return Nothing
cmp x y = return $ Just $ unlines $
concatMap f (getGroupedDiff (L.lines x) (L.lines y))
where
f (First xs) = map (cons3 '-' . L.unpack) xs
f (Second ys) = map (cons3 '+' . L.unpack) ys
f (Both xs _) = map (cons3 ' ' . L.unpack) xs
we add three characters , so the changed lines are easier to spot
cons3 c cs = c : c : c : ' ' : cs
testWith :: Show a => String -> (Value -> Parser a) -> [L.ByteString] -> Output
testWith name parser ts =
outputLine name <>
foldMap (\s ->
case eitherDecodeWith json (iparse parser) s of
Left err -> outputLine $ uncurry formatError err
Right a -> outputLine $ show a) ts
testFor :: forall a proxy. (FromJSON a, Show a)
=> String -> proxy a -> [L.ByteString] -> Output
testFor name _ = testWith name (parseJSON :: Value -> Parser a)
testWithSomeType :: String -> (Value -> Parser (SomeType Int)) -> [L.ByteString] -> Output
testWithSomeType = testWith
testWithFoo :: String -> (Value -> Parser Foo) -> [L.ByteString] -> Output
testWithFoo = testWith
|
e74ad94b3dbc85d15242c49b792fe357534d7a2389ab1685eb128a33a2820508 | kuribas/haskell-opentype | OS2.hs | module Opentype.Fileformat.OS2
where
import Data.Word
import Data.Int
import Data.Binary.Put
import Data.Binary.Get
import Control.Monad (when)
-- | The OS/2 table consists of a set of metrics that are required in
OpenType fonts . For a description of these fields see :
--
data OS2Table = OS2Table {
os2version :: Word16,
xAvgCharWidth :: Int16,
usWeightClass :: Word16,
usWidthClass :: Word16,
fsType :: Word16,
ySubscriptXSize :: Int16,
ySubscriptYSize :: Int16,
ySubscriptXOffset :: Int16,
ySubscriptYOffset :: Int16,
ySuperscriptXSize :: Int16,
ySuperscriptYSize :: Int16,
ySuperscriptXOffset :: Int16,
ySuperscriptYOffset :: Int16,
yStrikeoutSize :: Int16,
yStrikeoutPosition :: Int16,
bFamilyClass :: Int16,
bFamilyType :: Int8,
bSerifStyle :: Int8,
bWeight :: Int8,
bProportion :: Int8,
bContrast :: Int8,
bStrokeVariation :: Int8,
bArmStyle :: Int8,
bLetterform :: Int8,
bMidline :: Int8,
bXHeight :: Int8,
ulUnicodeRange1 :: Word32,
ulUnicodeRange2 :: Word32,
ulUnicodeRange3 :: Word32,
ulUnicodeRange4 :: Word32,
achVendID :: Word32,
fsSelection :: Word16,
usFirstCharIndex :: Word16,
usLastCharIndex :: Word16,
sTypoAscender :: Int16,
sTypoDescender :: Int16,
sTypoLineGap :: Int16,
usWinAscent :: Word16,
usWinDescent :: Word16,
ulCodePageRange1 :: Word32,
ulCodePageRange2 :: Word32,
sxHeight :: Int16,
sCapHeight :: Int16,
usDefaultChar :: Word16,
usBreakChar :: Word16,
usMaxContext :: Word16,
usLowerOpticalPointSize :: Word16,
usUpperOpticalPointSize :: Word16
}
deriving Show
getOS2Table :: Get OS2Table
getOS2Table = do
version <- getWord16be
partial1 <- OS2Table version <$> getInt16be
<*> getWord16be <*> getWord16be <*> getWord16be
<*> getInt16be <*> getInt16be <*> getInt16be
<*> getInt16be <*> getInt16be <*> getInt16be
<*> getInt16be <*> getInt16be <*> getInt16be
<*> getInt16be <*> getInt16be <*> getInt8
<*> getInt8 <*> getInt8 <*> getInt8 <*> getInt8
<*> getInt8 <*> getInt8 <*> getInt8 <*> getInt8
<*> getInt8 <*> getWord32be <*> getWord32be <*> getWord32be
<*> getWord32be <*> getWord32be <*> getWord16be
<*> getWord16be <*> getWord16be <*> getInt16be
<*> getInt16be <*> getInt16be <*> getWord16be <*> getWord16be
if version == 0 then
return $ partial1 0 0 0 0 0 0 0 0 0
else do
partial2 <- partial1 <$> getWord32be <*> getWord32be
if version == 1 then
return $ partial2 0 0 0 0 0 0 0
else do
partial3 <- partial2 <$> getInt16be <*> getInt16be <*>
getWord16be <*> getWord16be <*> getWord16be
if version < 5 then
return $ partial3 0 0
else partial3 <$> getWord16be <*> getWord16be
putOS2Table :: OS2Table -> Put
putOS2Table (OS2Table version f2 f3 f4 f5 f6 f7 f8 f9 f10
f11 f12 f13 f14 f15 f16 f17 f18 f19 f20
f21 f22 f23 f24 f25 f26 f27 f28 f29 f30
f31 f32 f33 f34 f35 f36 f37 f38 f39 f40
f41 f42 f43 f44 f45 f46 f47 f48) =
do putWord16be version
putInt16be f2
putWord16be f3
putWord16be f4
putWord16be f5
putInt16be f6
putInt16be f7
putInt16be f8
putInt16be f9
putInt16be f10
putInt16be f11
putInt16be f12
putInt16be f13
putInt16be f14
putInt16be f15
putInt16be f16
putInt8 f17
putInt8 f18
putInt8 f19
putInt8 f20
putInt8 f21
putInt8 f22
putInt8 f23
putInt8 f24
putInt8 f25
putInt8 f26
putWord32be f27
putWord32be f28
putWord32be f29
putWord32be f30
putWord32be f31
putWord16be f32
putWord16be f33
putWord16be f34
putInt16be f35
putInt16be f36
putInt16be f37
putWord16be f38
putWord16be f39
when (version > 0) $ do
putWord32be f40
putWord32be f41
when (version > 1) $ do
putInt16be f42
putInt16be f43
putWord16be f44
putWord16be f45
putWord16be f46
when (version > 4) $ do
putWord16be f47
putWord16be f48
| null | https://raw.githubusercontent.com/kuribas/haskell-opentype/06d24f726370d68dc71509157a87e3a929475a4f/Opentype/Fileformat/OS2.hs | haskell | | The OS/2 table consists of a set of metrics that are required in
| module Opentype.Fileformat.OS2
where
import Data.Word
import Data.Int
import Data.Binary.Put
import Data.Binary.Get
import Control.Monad (when)
OpenType fonts . For a description of these fields see :
data OS2Table = OS2Table {
os2version :: Word16,
xAvgCharWidth :: Int16,
usWeightClass :: Word16,
usWidthClass :: Word16,
fsType :: Word16,
ySubscriptXSize :: Int16,
ySubscriptYSize :: Int16,
ySubscriptXOffset :: Int16,
ySubscriptYOffset :: Int16,
ySuperscriptXSize :: Int16,
ySuperscriptYSize :: Int16,
ySuperscriptXOffset :: Int16,
ySuperscriptYOffset :: Int16,
yStrikeoutSize :: Int16,
yStrikeoutPosition :: Int16,
bFamilyClass :: Int16,
bFamilyType :: Int8,
bSerifStyle :: Int8,
bWeight :: Int8,
bProportion :: Int8,
bContrast :: Int8,
bStrokeVariation :: Int8,
bArmStyle :: Int8,
bLetterform :: Int8,
bMidline :: Int8,
bXHeight :: Int8,
ulUnicodeRange1 :: Word32,
ulUnicodeRange2 :: Word32,
ulUnicodeRange3 :: Word32,
ulUnicodeRange4 :: Word32,
achVendID :: Word32,
fsSelection :: Word16,
usFirstCharIndex :: Word16,
usLastCharIndex :: Word16,
sTypoAscender :: Int16,
sTypoDescender :: Int16,
sTypoLineGap :: Int16,
usWinAscent :: Word16,
usWinDescent :: Word16,
ulCodePageRange1 :: Word32,
ulCodePageRange2 :: Word32,
sxHeight :: Int16,
sCapHeight :: Int16,
usDefaultChar :: Word16,
usBreakChar :: Word16,
usMaxContext :: Word16,
usLowerOpticalPointSize :: Word16,
usUpperOpticalPointSize :: Word16
}
deriving Show
getOS2Table :: Get OS2Table
getOS2Table = do
version <- getWord16be
partial1 <- OS2Table version <$> getInt16be
<*> getWord16be <*> getWord16be <*> getWord16be
<*> getInt16be <*> getInt16be <*> getInt16be
<*> getInt16be <*> getInt16be <*> getInt16be
<*> getInt16be <*> getInt16be <*> getInt16be
<*> getInt16be <*> getInt16be <*> getInt8
<*> getInt8 <*> getInt8 <*> getInt8 <*> getInt8
<*> getInt8 <*> getInt8 <*> getInt8 <*> getInt8
<*> getInt8 <*> getWord32be <*> getWord32be <*> getWord32be
<*> getWord32be <*> getWord32be <*> getWord16be
<*> getWord16be <*> getWord16be <*> getInt16be
<*> getInt16be <*> getInt16be <*> getWord16be <*> getWord16be
if version == 0 then
return $ partial1 0 0 0 0 0 0 0 0 0
else do
partial2 <- partial1 <$> getWord32be <*> getWord32be
if version == 1 then
return $ partial2 0 0 0 0 0 0 0
else do
partial3 <- partial2 <$> getInt16be <*> getInt16be <*>
getWord16be <*> getWord16be <*> getWord16be
if version < 5 then
return $ partial3 0 0
else partial3 <$> getWord16be <*> getWord16be
putOS2Table :: OS2Table -> Put
putOS2Table (OS2Table version f2 f3 f4 f5 f6 f7 f8 f9 f10
f11 f12 f13 f14 f15 f16 f17 f18 f19 f20
f21 f22 f23 f24 f25 f26 f27 f28 f29 f30
f31 f32 f33 f34 f35 f36 f37 f38 f39 f40
f41 f42 f43 f44 f45 f46 f47 f48) =
do putWord16be version
putInt16be f2
putWord16be f3
putWord16be f4
putWord16be f5
putInt16be f6
putInt16be f7
putInt16be f8
putInt16be f9
putInt16be f10
putInt16be f11
putInt16be f12
putInt16be f13
putInt16be f14
putInt16be f15
putInt16be f16
putInt8 f17
putInt8 f18
putInt8 f19
putInt8 f20
putInt8 f21
putInt8 f22
putInt8 f23
putInt8 f24
putInt8 f25
putInt8 f26
putWord32be f27
putWord32be f28
putWord32be f29
putWord32be f30
putWord32be f31
putWord16be f32
putWord16be f33
putWord16be f34
putInt16be f35
putInt16be f36
putInt16be f37
putWord16be f38
putWord16be f39
when (version > 0) $ do
putWord32be f40
putWord32be f41
when (version > 1) $ do
putInt16be f42
putInt16be f43
putWord16be f44
putWord16be f45
putWord16be f46
when (version > 4) $ do
putWord16be f47
putWord16be f48
|
3e8472ba764f9e6697266624057b9b2e8f4680b58878ac8442f0e4b5dd4570b0 | parapluu/Concuerror | harmless_exit.erl | -module(harmless_exit).
-export([test/0]).
test() ->
process_flag(trap_exit, true),
spawn_link(fun() -> exit(abnormal) end),
receive
_ -> ok
end.
| null | https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/tests-real/suites/output/src/harmless_exit.erl | erlang | -module(harmless_exit).
-export([test/0]).
test() ->
process_flag(trap_exit, true),
spawn_link(fun() -> exit(abnormal) end),
receive
_ -> ok
end.
| |
eacc5fea75ccb6a7cbe932067c7bbe51f4c9eecbad146bfbdc1cc4a66052f92f | OCamlPro/typerex-lint | lintParsing_Ast_iterator.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, LexiFi
(* *)
Copyright 2012 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
module Asttypes = LintParsing_Asttypes
module Ast_helper = LintParsing_Ast_helper
module Parsetree = LintParsing_Parsetree
module Docstrings = LintParsing_Docstrings
module Location = LintParsing_Location
module Syntaxerr = LintParsing_Syntaxerr
* { ! iterator } allows to implement AST inspection using open recursion . A
typical mapper would be based on { ! default_iterator } , a trivial iterator ,
and will fall back on it for handling the syntax it does not modify .
typical mapper would be based on {!default_iterator}, a trivial iterator,
and will fall back on it for handling the syntax it does not modify. *)
open Parsetree
* { 2 A generic Parsetree iterator }
type iterator = {
attribute: iterator -> attribute -> unit;
attributes: iterator -> attribute list -> unit;
case: iterator -> case -> unit;
cases: iterator -> case list -> unit;
class_declaration: iterator -> class_declaration -> unit;
class_description: iterator -> class_description -> unit;
class_expr: iterator -> class_expr -> unit;
class_field: iterator -> class_field -> unit;
class_signature: iterator -> class_signature -> unit;
class_structure: iterator -> class_structure -> unit;
class_type: iterator -> class_type -> unit;
class_type_declaration: iterator -> class_type_declaration -> unit;
class_type_field: iterator -> class_type_field -> unit;
constructor_declaration: iterator -> constructor_declaration -> unit;
expr: iterator -> expression -> unit;
extension: iterator -> extension -> unit;
extension_constructor: iterator -> extension_constructor -> unit;
include_declaration: iterator -> include_declaration -> unit;
include_description: iterator -> include_description -> unit;
label_declaration: iterator -> label_declaration -> unit;
location: iterator -> Location.t -> unit;
module_binding: iterator -> module_binding -> unit;
module_declaration: iterator -> module_declaration -> unit;
module_expr: iterator -> module_expr -> unit;
module_type: iterator -> module_type -> unit;
module_type_declaration: iterator -> module_type_declaration -> unit;
open_description: iterator -> open_description -> unit;
pat: iterator -> pattern -> unit;
payload: iterator -> payload -> unit;
signature: iterator -> signature -> unit;
signature_item: iterator -> signature_item -> unit;
structure: iterator -> structure -> unit;
structure_item: iterator -> structure_item -> unit;
typ: iterator -> core_type -> unit;
type_declaration: iterator -> type_declaration -> unit;
type_extension: iterator -> type_extension -> unit;
type_kind: iterator -> type_kind -> unit;
value_binding: iterator -> value_binding -> unit;
value_description: iterator -> value_description -> unit;
with_constraint: iterator -> with_constraint -> unit;
}
* A [ iterator ] record implements one " method " per syntactic category ,
using an open recursion style : each method takes as its first
argument the iterator to be applied to children in the syntax
tree .
using an open recursion style: each method takes as its first
argument the iterator to be applied to children in the syntax
tree. *)
val default_iterator: iterator
(** A default iterator, which implements a "do not do anything" mapping. *)
| null | https://raw.githubusercontent.com/OCamlPro/typerex-lint/6d9e994c8278fb65e1f7de91d74876531691120c/plugins/ocp-lint-plugin-parsing/lintParsing_Ast_iterator.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* A default iterator, which implements a "do not do anything" mapping. | , LexiFi
Copyright 2012 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
module Asttypes = LintParsing_Asttypes
module Ast_helper = LintParsing_Ast_helper
module Parsetree = LintParsing_Parsetree
module Docstrings = LintParsing_Docstrings
module Location = LintParsing_Location
module Syntaxerr = LintParsing_Syntaxerr
* { ! iterator } allows to implement AST inspection using open recursion . A
typical mapper would be based on { ! default_iterator } , a trivial iterator ,
and will fall back on it for handling the syntax it does not modify .
typical mapper would be based on {!default_iterator}, a trivial iterator,
and will fall back on it for handling the syntax it does not modify. *)
open Parsetree
* { 2 A generic Parsetree iterator }
type iterator = {
attribute: iterator -> attribute -> unit;
attributes: iterator -> attribute list -> unit;
case: iterator -> case -> unit;
cases: iterator -> case list -> unit;
class_declaration: iterator -> class_declaration -> unit;
class_description: iterator -> class_description -> unit;
class_expr: iterator -> class_expr -> unit;
class_field: iterator -> class_field -> unit;
class_signature: iterator -> class_signature -> unit;
class_structure: iterator -> class_structure -> unit;
class_type: iterator -> class_type -> unit;
class_type_declaration: iterator -> class_type_declaration -> unit;
class_type_field: iterator -> class_type_field -> unit;
constructor_declaration: iterator -> constructor_declaration -> unit;
expr: iterator -> expression -> unit;
extension: iterator -> extension -> unit;
extension_constructor: iterator -> extension_constructor -> unit;
include_declaration: iterator -> include_declaration -> unit;
include_description: iterator -> include_description -> unit;
label_declaration: iterator -> label_declaration -> unit;
location: iterator -> Location.t -> unit;
module_binding: iterator -> module_binding -> unit;
module_declaration: iterator -> module_declaration -> unit;
module_expr: iterator -> module_expr -> unit;
module_type: iterator -> module_type -> unit;
module_type_declaration: iterator -> module_type_declaration -> unit;
open_description: iterator -> open_description -> unit;
pat: iterator -> pattern -> unit;
payload: iterator -> payload -> unit;
signature: iterator -> signature -> unit;
signature_item: iterator -> signature_item -> unit;
structure: iterator -> structure -> unit;
structure_item: iterator -> structure_item -> unit;
typ: iterator -> core_type -> unit;
type_declaration: iterator -> type_declaration -> unit;
type_extension: iterator -> type_extension -> unit;
type_kind: iterator -> type_kind -> unit;
value_binding: iterator -> value_binding -> unit;
value_description: iterator -> value_description -> unit;
with_constraint: iterator -> with_constraint -> unit;
}
* A [ iterator ] record implements one " method " per syntactic category ,
using an open recursion style : each method takes as its first
argument the iterator to be applied to children in the syntax
tree .
using an open recursion style: each method takes as its first
argument the iterator to be applied to children in the syntax
tree. *)
val default_iterator: iterator
|
513e1042a71bea22342f9b9b07145b1ff28445ba911d6cceba990563438cba56 | dcavar/schemeNLP | average-re.scm | ;;; ":"; exec mzscheme -r $0 "$@"
;;; ----------------------------------------------------
;;; Filename: average-re.ss
Author : < >
;;;
( C ) 2006 by
;;;
;;; This code is published under the restrictive GPL!
;;; Please find the text of the GPL here:
;;;
;;;
;;; It is free for use, change, etc. as long as the copyright
;;; note above is included in any modified version of the code.
;;;
;;; This script assumes that the text is raw and encoded in UTF8.
;;;
If the command line parameters contain more than one text file ,
;;; the above results are accumulated over all the input text files.
;;;
;;; Usage:
;;; mzscheme -r average-re.ss test1.txt test2.txt ...
;;; ----------------------------------------------------
(require (lib "list.ss"))
(require (lib "string.ss")) ; for string-uppercase!
(require (lib "string.ss" "srfi" "13"))
(require (lib "vector-lib.ss" "srfi" "43"))
(require (lib "pregexp.ss")) ; for Perl compatible regular expressions
(load "english.ss")
;;; global counters
(define tokencount 0.0) ; total number of words
(define bigramcount 0.0) ; total number of bigrams
;;; hash-table containers
(define types (make-hash-table 'equal)) ; words and their counts
(define bigrams (make-hash-table 'equal)) ; bigrams and their counts
;;; extra hash-tables
(define lefttoken (make-hash-table 'equal)) ; key = left token in bigram, value = list of bigrams with key left
(define righttoken (make-hash-table 'equal)) ; key = right token in bigram, value = list of bigrams with key right
;;; sort hash table with by value
;;; assuming values = reals/ints
;;; returning a sorted list of key-value tuples (lists)
(define sort-by-value
(lambda (table)
(let ([keyval (hash-table-map table (lambda (key val) (list key val)))])
(sort keyval (lambda (a b)
(< (cadr a) (cadr b)))))))
(define add-data
(lambda (tokenlist)
(let ([count (- (length tokenlist) 1)])
; remember the total counts of tokens and bigrams
(set! tokencount (+ tokencount (length tokenlist)))
(set! bigramcount (+ bigramcount count))
count the first token in the list
(let ([value (hash-table-get types (car tokenlist) 0.0)])
(hash-table-put! types (car tokenlist) (+ value 1)))
; loop over the rest of the tokens
(let loop ([i 1])
token = second element of bigram
[bigram (list (list-ref tokenlist (- i 1)) token)] ; bigram = previous and current token as list
[wvalue (hash-table-get types token 0.0)] ; get value for token
[bvalue (hash-table-get bigrams bigram 0.0)] ; get value for bigram
[leftval (hash-table-get lefttoken (car bigram) '())] ; list of bigrams where token is left
[rightval (hash-table-get righttoken (cadr bigram) '())]) ; list of bigrams where token is right
; store the bigram in the value for left and right
(unless (member leftval bigram)
(set! leftval (cons bigram leftval))
(hash-table-put! lefttoken (car bigram) leftval))
(unless (member rightval bigram)
(set! rightval (cons bigram rightval))
(hash-table-put! righttoken (cadr bigram) rightval))
; store tokens and bigrams in their hash-tables
(hash-table-put! types token (+ wvalue 1)) ; increment counter for token
(hash-table-put! bigrams bigram (+ bvalue 1))) ; increment counter for bigram
; go back to loop, if more tokens left
(if (< i count)
(loop (+ i 1)))))))
;;; log2 of value
;;; Base transformation:
log2 is the natural log divided by the natural log of 2 ( the base )
(define log2
(lambda (x)
(/ (log x) (log 2))))
mutual - information of P(x ) , ) , )
calculate pointwise MI as
P(XY ) * log2 ( ) / ( P(X ) * ) ) )
(define mutual-information
(lambda (px py pxy)
(* pxy (log2 (/ pxy (* px py))))))
relative - entropy of ) , P(x ) , )
) log2 ( ) / P(y|x ) )
) log2 ( ) P(x)/P(xy ) )
(define relative-entropy
(lambda (px py pxy)
(* py (log2 (/ (* px py) pxy)))))
;;; load-file (filename)
;;; load text from file into a string variable and return it
(define load-file
(lambda (name)
(call-with-input-file name
(lambda (p)
(read-string (file-size name) p)))))
(begin
(vector-for-each (lambda (i fname)
(let ([text (load-file fname)])
(string-lowercase! text)
(add-data (string-tokenize (pregexp-replace* "([`'-.,!?;:<>()|\"\\]\\[$%/]+)" text " ")))))
argv)
; print out the bigram statistics
(let ([result (sort-by-value bigrams)])
(printf "bigram\tfreq\trel freq\tlRE\trRE\n")
(for-each (lambda (a)
(unless (or (member (caar a) stopwords)
(member (cadar a) stopwords))
(let ([px (/ (hash-table-get types (caar a)) tokencount)]
[py (/ (hash-table-get types (cadar a)) tokencount)]
[pxy (/ (cadr a) bigramcount)])
(printf "~a ~a\t~a\t~a\t~a\t~a\n"
(caar a)
(cadar a)
(cadr a)
pxy
(relative-entropy px py pxy)
(relative-entropy py px pxy)))))
(reverse result)))
(printf "---------------------------------------------------------\n"))
| null | https://raw.githubusercontent.com/dcavar/schemeNLP/daa0ddcc4fa67fe00dcf6054c4d30d11a00b2f7f/src/average-re.scm | scheme | ":"; exec mzscheme -r $0 "$@"
----------------------------------------------------
Filename: average-re.ss
This code is published under the restrictive GPL!
Please find the text of the GPL here:
It is free for use, change, etc. as long as the copyright
note above is included in any modified version of the code.
This script assumes that the text is raw and encoded in UTF8.
the above results are accumulated over all the input text files.
Usage:
mzscheme -r average-re.ss test1.txt test2.txt ...
----------------------------------------------------
for string-uppercase!
for Perl compatible regular expressions
global counters
total number of words
total number of bigrams
hash-table containers
words and their counts
bigrams and their counts
extra hash-tables
key = left token in bigram, value = list of bigrams with key left
key = right token in bigram, value = list of bigrams with key right
sort hash table with by value
assuming values = reals/ints
returning a sorted list of key-value tuples (lists)
remember the total counts of tokens and bigrams
loop over the rest of the tokens
bigram = previous and current token as list
get value for token
get value for bigram
list of bigrams where token is left
list of bigrams where token is right
store the bigram in the value for left and right
store tokens and bigrams in their hash-tables
increment counter for token
increment counter for bigram
go back to loop, if more tokens left
log2 of value
Base transformation:
load-file (filename)
load text from file into a string variable and return it
print out the bigram statistics |
Author : < >
( C ) 2006 by
If the command line parameters contain more than one text file ,
(require (lib "list.ss"))
(require (lib "string.ss" "srfi" "13"))
(require (lib "vector-lib.ss" "srfi" "43"))
(load "english.ss")
(define sort-by-value
(lambda (table)
(let ([keyval (hash-table-map table (lambda (key val) (list key val)))])
(sort keyval (lambda (a b)
(< (cadr a) (cadr b)))))))
(define add-data
(lambda (tokenlist)
(let ([count (- (length tokenlist) 1)])
(set! tokencount (+ tokencount (length tokenlist)))
(set! bigramcount (+ bigramcount count))
count the first token in the list
(let ([value (hash-table-get types (car tokenlist) 0.0)])
(hash-table-put! types (car tokenlist) (+ value 1)))
(let loop ([i 1])
token = second element of bigram
(unless (member leftval bigram)
(set! leftval (cons bigram leftval))
(hash-table-put! lefttoken (car bigram) leftval))
(unless (member rightval bigram)
(set! rightval (cons bigram rightval))
(hash-table-put! righttoken (cadr bigram) rightval))
(if (< i count)
(loop (+ i 1)))))))
log2 is the natural log divided by the natural log of 2 ( the base )
(define log2
(lambda (x)
(/ (log x) (log 2))))
mutual - information of P(x ) , ) , )
calculate pointwise MI as
P(XY ) * log2 ( ) / ( P(X ) * ) ) )
(define mutual-information
(lambda (px py pxy)
(* pxy (log2 (/ pxy (* px py))))))
relative - entropy of ) , P(x ) , )
) log2 ( ) / P(y|x ) )
) log2 ( ) P(x)/P(xy ) )
(define relative-entropy
(lambda (px py pxy)
(* py (log2 (/ (* px py) pxy)))))
(define load-file
(lambda (name)
(call-with-input-file name
(lambda (p)
(read-string (file-size name) p)))))
(begin
(vector-for-each (lambda (i fname)
(let ([text (load-file fname)])
(string-lowercase! text)
(add-data (string-tokenize (pregexp-replace* "([`'-.,!?;:<>()|\"\\]\\[$%/]+)" text " ")))))
argv)
(let ([result (sort-by-value bigrams)])
(printf "bigram\tfreq\trel freq\tlRE\trRE\n")
(for-each (lambda (a)
(unless (or (member (caar a) stopwords)
(member (cadar a) stopwords))
(let ([px (/ (hash-table-get types (caar a)) tokencount)]
[py (/ (hash-table-get types (cadar a)) tokencount)]
[pxy (/ (cadr a) bigramcount)])
(printf "~a ~a\t~a\t~a\t~a\t~a\n"
(caar a)
(cadar a)
(cadr a)
pxy
(relative-entropy px py pxy)
(relative-entropy py px pxy)))))
(reverse result)))
(printf "---------------------------------------------------------\n"))
|
186515f2a62026b01aa12bef9794ec394c823f6276136865832e875c813e82b3 | mbutterick/aoc-racket | test.rkt | #lang reader "lang.rkt"
abc | null | https://raw.githubusercontent.com/mbutterick/aoc-racket/2c6cb2f3ad876a91a82f33ce12844f7758b969d6/2016/day14/test.rkt | racket | #lang reader "lang.rkt"
abc | |
a754b69138d65620b87a73bd96641f7eda6c07645acb7402ca31bc65341065fa | ermine/kombain | kmb_input.ml | type input = {
buf : string;
pos : int;
len : int;
filename : string;
line : int;
col : int
}
type lexeme = {
start : int * int;
stop : int * int;
lexeme : string
}
let end_of_file input =
input.pos = input.len
let incr_pos input =
no boundaries check due to incr_pos is called only
after successful input tests
after successful input tests *)
if input.buf.[input.pos] = '\n' then
{input with pos = input.pos + 1;
line = input.line + 1;
col = 0
}
else if input.buf.[input.pos] = '\t' then
{ input with pos = input.pos + 1;
col = ((input.col + 8 - 1) / 8) * 8 + 1
}
else
{ input with pos = input.pos + 1;
col = input.col + 1
}
let make_input ?(filename="ghost") str =
{ pos = 0; len = String.length str; buf = str;
filename; line = 1; col = 0}
let read_file file =
let f = open_in file in
let rec aux_read acc =
let line =
try Some (input_line f)
with _ -> None in
match line with
| None -> List.rev acc
| Some line -> aux_read (line :: acc)
in
let lines = aux_read [] in
close_in f;
String.concat "\n" lines ^ "\n"
let of_string str =
make_input str
let of_file filename =
let content = read_file filename in
{ pos = 0; len = String.length content; buf = content;
filename; line = 1; col = 0}
let get_current input =
Char.code (input.buf.[input.pos])
let string_of_current input =
if input.pos < input.len then
Printf.sprintf "%d:%d %C" input.line input.col input.buf.[input.pos]
else
"eof"
let string_of_location input =
Printf.sprintf "File %S line %d col %d" input.filename input.line input.col
let string_of_cslit clist =
String.escaped (
String.concat "" (List.map (fun c ->
String.make 1 (if c < 255 then Char.chr c else '*')) clist))
let get_remaining input =
if input.pos < input.len then
String.sub input.buf input.pos (input.len - input.pos)
else
""
| null | https://raw.githubusercontent.com/ermine/kombain/07f643c892b0b9c2ef08d67428bb9125d5251f82/kmb/kmb_input.ml | ocaml | type input = {
buf : string;
pos : int;
len : int;
filename : string;
line : int;
col : int
}
type lexeme = {
start : int * int;
stop : int * int;
lexeme : string
}
let end_of_file input =
input.pos = input.len
let incr_pos input =
no boundaries check due to incr_pos is called only
after successful input tests
after successful input tests *)
if input.buf.[input.pos] = '\n' then
{input with pos = input.pos + 1;
line = input.line + 1;
col = 0
}
else if input.buf.[input.pos] = '\t' then
{ input with pos = input.pos + 1;
col = ((input.col + 8 - 1) / 8) * 8 + 1
}
else
{ input with pos = input.pos + 1;
col = input.col + 1
}
let make_input ?(filename="ghost") str =
{ pos = 0; len = String.length str; buf = str;
filename; line = 1; col = 0}
let read_file file =
let f = open_in file in
let rec aux_read acc =
let line =
try Some (input_line f)
with _ -> None in
match line with
| None -> List.rev acc
| Some line -> aux_read (line :: acc)
in
let lines = aux_read [] in
close_in f;
String.concat "\n" lines ^ "\n"
let of_string str =
make_input str
let of_file filename =
let content = read_file filename in
{ pos = 0; len = String.length content; buf = content;
filename; line = 1; col = 0}
let get_current input =
Char.code (input.buf.[input.pos])
let string_of_current input =
if input.pos < input.len then
Printf.sprintf "%d:%d %C" input.line input.col input.buf.[input.pos]
else
"eof"
let string_of_location input =
Printf.sprintf "File %S line %d col %d" input.filename input.line input.col
let string_of_cslit clist =
String.escaped (
String.concat "" (List.map (fun c ->
String.make 1 (if c < 255 then Char.chr c else '*')) clist))
let get_remaining input =
if input.pos < input.len then
String.sub input.buf input.pos (input.len - input.pos)
else
""
| |
772aed09f4dac8cbed76b2c7439a81e66b2af72dbfc80d64fdf442573e25ee8e | BinaryAnalysisPlatform/bap | bap_primus_lisp_word.mli | open Core_kernel[@@warning "-D"]
open Bap_primus_lisp_types
type t = word [@@deriving compare, sexp_of]
type read_error = Empty | Not_an_int | Unclosed | Bad_literal | Bad_type
val read : Id.t -> Eq.t -> string -> (t,read_error) result
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/253afc171bbfd0fe1b34f6442795dbf4b1798348/lib/bap_primus/bap_primus_lisp_word.mli | ocaml | open Core_kernel[@@warning "-D"]
open Bap_primus_lisp_types
type t = word [@@deriving compare, sexp_of]
type read_error = Empty | Not_an_int | Unclosed | Bad_literal | Bad_type
val read : Id.t -> Eq.t -> string -> (t,read_error) result
| |
94606882df0c70530b27fc7d35e29cbe91746de2cc64795606f28d8a2d350128 | NorfairKing/declops | ProviderName.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# LANGUAGE GeneralizedNewtypeDeriving #
module Declops.Provider.ProviderName where
import Autodocodec
import Data.Aeson (FromJSON, FromJSONKey, ToJSON, ToJSONKey)
import Data.Proxy
import Data.String
import Data.Text (Text)
import Data.Validity
import Data.Validity.Text ()
import Database.Persist.Sqlite
import GHC.Generics (Generic)
newtype ProviderName = ProviderName {unProviderName :: Text}
deriving stock (Generic)
deriving newtype (Show, Eq, Ord, IsString, FromJSONKey, ToJSONKey)
deriving (FromJSON, ToJSON) via (Autodocodec ProviderName)
instance Validity ProviderName
instance HasCodec ProviderName where
codec = dimapCodec ProviderName unProviderName codec
instance PersistField ProviderName where
toPersistValue = toPersistValue . unProviderName
fromPersistValue = fmap ProviderName . fromPersistValue
instance PersistFieldSql ProviderName where
sqlType Proxy = sqlType (Proxy :: Proxy Text)
| null | https://raw.githubusercontent.com/NorfairKing/declops/79ef87a7c17ff31eb5281b0be76a30857ae1c88a/declops-provider/src/Declops/Provider/ProviderName.hs | haskell | # LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# LANGUAGE GeneralizedNewtypeDeriving #
module Declops.Provider.ProviderName where
import Autodocodec
import Data.Aeson (FromJSON, FromJSONKey, ToJSON, ToJSONKey)
import Data.Proxy
import Data.String
import Data.Text (Text)
import Data.Validity
import Data.Validity.Text ()
import Database.Persist.Sqlite
import GHC.Generics (Generic)
newtype ProviderName = ProviderName {unProviderName :: Text}
deriving stock (Generic)
deriving newtype (Show, Eq, Ord, IsString, FromJSONKey, ToJSONKey)
deriving (FromJSON, ToJSON) via (Autodocodec ProviderName)
instance Validity ProviderName
instance HasCodec ProviderName where
codec = dimapCodec ProviderName unProviderName codec
instance PersistField ProviderName where
toPersistValue = toPersistValue . unProviderName
fromPersistValue = fmap ProviderName . fromPersistValue
instance PersistFieldSql ProviderName where
sqlType Proxy = sqlType (Proxy :: Proxy Text)
| |
ce7cd9b3cb6720fd7567823d1390c385ed7dfd1ed19334073582ac17d069ef00 | jhb563/MazeGame | MazeParser.hs | module MazeParser where
import Control.Monad (forM)
import Control.Monad.State (State, get, put, execState)
import qualified Data.Array as Array
import Data.Char (toLower, intToDigit, toUpper, digitToInt)
import Data.Either (fromRight)
import Data.List (groupBy)
import qualified Data.Map as Map
import Data.Maybe (fromJust, catMaybes)
import qualified Data.Set as Set
import Data.Text (Text, pack)
import Data.Void (Void)
import System.Random (StdGen, randomR)
import Text.Megaparsec (Parsec)
import qualified Text.Megaparsec as M
import qualified Text.Megaparsec.Char as M
import Types (Location, CellBoundaries(..), BoundaryType(..), World, Maze)
-- top-right-bottom-left
0 = 0000
1 = 0001
2 = 0010
3 = 0011
4 = 0100
5 = 0101
6 = 0110
7 = 0111
8 = 1000
9 = 1001
A = 1010
B = 1011
C = 1100
D = 1101
E = 1110
F = 1111
type MParser = Parsec Void Text
parseWorldFromFile :: FilePath -> IO World
parseWorldFromFile = undefined
sampleMaze :: Maze
sampleMaze = fromRight undefined $ M.runParser (mazeParser (5,5)) "" testMaze
testMaze :: Text
testMaze = pack $ unlines
[ "98CDF"
, "1041C"
, "34775"
, "90AA4"
, "32EB6"
]
mazeParser :: (Int, Int) -> MParser Maze
mazeParser (numRows, numColumns) = do
rows <- forM [(numRows - 1),(numRows - 2)..0] $ \i -> do
columns <- forM [0..(numColumns - 1)] $ \j -> do
c <- M.hexDigitChar
return (j, c)
M.newline
return $ map (\(col, char) -> ((col, i), char)) columns
return $ Map.fromList (cellSpecToBounds <$> (concat rows))
where
cellSpecToBounds :: (Location, Char) -> (Location, CellBoundaries)
cellSpecToBounds (loc@(x, y), c) =
let (topIsWall, rightIsWall, bottomIsWall, leftIsWall) = charToBoundsSet c
topCell = if topIsWall then if y + 1 == numRows then WorldBoundary else Wall
else (AdjacentCell (x, y + 1))
rightCell = if rightIsWall then if x + 1 == numColumns then WorldBoundary else Wall
else (AdjacentCell (x + 1, y))
bottomCell = if bottomIsWall then if y == 0 then WorldBoundary else Wall
else (AdjacentCell (x, y - 1))
leftCell = if leftIsWall then if x == 0 then WorldBoundary else Wall
else (AdjacentCell (x - 1, y))
in (loc, CellBoundaries topCell rightCell bottomCell leftCell)
charToBoundsSet :: Char -> (Bool, Bool, Bool, Bool)
charToBoundsSet c =
( num > 7
, num `mod` 8 > 3
, num `mod` 4 > 1
, num `mod` 2 == 1
)
where
num = digitToInt c
charToBoundsSet ' 0 ' = ( False , False , False , False )
charToBoundsSet ' 1 ' = ( False , False , False , True )
charToBoundsSet ' 2 ' = ( False , False , True , False )
charToBoundsSet ' 3 ' = ( False , False , True , True )
charToBoundsSet ' 4 ' = ( False , True , False , False )
charToBoundsSet ' 5 ' = ( False , True , False , True )
charToBoundsSet ' 6 ' = ( False , True , True , False )
charToBoundsSet ' 7 ' = ( False , True , True , True )
charToBoundsSet ' 8 ' = ( True , False , False , False )
charToBoundsSet ' 9 ' = ( True , False , False , True )
charToBoundsSet ' a ' = ( True , False , True , False )
charToBoundsSet ' b ' = ( True , False , True , True )
charToBoundsSet ' c ' = ( True , True , False , False )
charToBoundsSet 'd ' = ( True , True , False , True )
charToBoundsSet ' e ' = ( True , True , True , False )
charToBoundsSet ' f ' = ( True , True , True , True )
charToBoundsSet _ = error " Invalid character ! "
charToBoundsSet '1' = (False, False, False, True)
charToBoundsSet '2' = (False, False, True, False)
charToBoundsSet '3' = (False, False, True, True)
charToBoundsSet '4' = (False, True, False, False)
charToBoundsSet '5' = (False, True, False, True)
charToBoundsSet '6' = (False, True, True, False)
charToBoundsSet '7' = (False, True, True, True)
charToBoundsSet '8' = (True, False, False, False)
charToBoundsSet '9' = (True, False, False, True)
charToBoundsSet 'a' = (True, False, True, False)
charToBoundsSet 'b' = (True, False, True, True)
charToBoundsSet 'c' = (True, True, False, False)
charToBoundsSet 'd' = (True, True, False, True)
charToBoundsSet 'e' = (True, True, True, False)
charToBoundsSet 'f' = (True, True, True, True)
charToBoundsSet _ = error "Invalid character!"-}
dumpMaze :: Maze -> Text
dumpMaze maze = pack $ (unlines . reverse) (rowToString <$> cellsByRow)
where
transposedMap :: Maze
transposedMap = Map.mapKeys (\(x, y) -> (y, x)) maze
cellsByRow :: [[(Location, CellBoundaries)]]
cellsByRow = groupBy (\((r1, _), _) ((r2, _), _) -> r1 == r2) (Map.toList transposedMap)
rowToString :: [(Location, CellBoundaries)] -> String
rowToString = map (cellToChar . snd)
cellToChar :: CellBoundaries -> Char
cellToChar bounds =
let top = case upBoundary bounds of
(AdjacentCell _) -> 0
_ -> 8
right = case rightBoundary bounds of
(AdjacentCell _) -> 0
_ -> 4
down = case downBoundary bounds of
(AdjacentCell _) -> 0
_ -> 2
left = case leftBoundary bounds of
(AdjacentCell _) -> 0
_ -> 1
in toUpper $ intToDigit (top + right + down + left)
generateRandomMaze :: StdGen -> (Int, Int) -> (Maze, StdGen)
generateRandomMaze gen (numRows, numColumns) = (currentBoundaries finalState, randomGen finalState)
where
(startX, g1) = randomR (0, numColumns - 1) gen
(startY, g2) = randomR (0, numRows - 1) g1
initialState = SearchState g2 [(startX, startY)] initialBounds Set.empty
initialBounds :: Maze
initialBounds = case M.runParser (mazeParser (numRows, numColumns)) "" fullString of
Left _ -> error "Maze can't be parsed!"
Right success -> success
fullString :: Text
fullString = pack . unlines $ take numRows $ repeat (take numColumns (repeat 'F'))
finalState = execState dfsSearch initialState
-- Pick out start location. Pick end location. Set up initial state. Run DFS
data SearchState = SearchState
{ randomGen :: StdGen
, locationStack :: [Location]
, currentBoundaries :: Maze
, visitedCells :: Set.Set Location
}
dfsSearch :: State SearchState ()
dfsSearch = do
(SearchState gen locs bounds visited) <- get
case locs of
[] -> return ()
(currentLoc : rest) -> do
let candidateLocs = findCandidates currentLoc bounds visited
if null candidateLocs
then put (SearchState gen rest bounds visited) >> dfsSearch
else chooseCandidate candidateLocs >> dfsSearch
where
findCandidates :: Location -> Maze -> Set.Set Location -> [(Location, CellBoundaries, Location, CellBoundaries)]
findCandidates currentLocation@(x, y) bounds visited =
let currentLocBounds = fromJust $ Map.lookup currentLocation bounds
upLoc = (x, y + 1)
maybeUpCell = case (upBoundary currentLocBounds, Set.member upLoc visited) of
(Wall, False) -> Just
( upLoc
, (fromJust $ Map.lookup upLoc bounds) {downBoundary = AdjacentCell currentLocation}
, currentLocation
, currentLocBounds {upBoundary = AdjacentCell upLoc}
)
_ -> Nothing
rightLoc = (x + 1, y)
maybeRightCell = case (rightBoundary currentLocBounds, Set.member rightLoc visited) of
(Wall, False) -> Just
( rightLoc
, (fromJust $ Map.lookup rightLoc bounds) {leftBoundary = AdjacentCell currentLocation}
, currentLocation
, currentLocBounds {rightBoundary = AdjacentCell rightLoc}
)
_ -> Nothing
downLoc = (x, y - 1)
maybeDownCell = case (downBoundary currentLocBounds, Set.member downLoc visited) of
(Wall, False) -> Just
( downLoc
, (fromJust $ Map.lookup downLoc bounds) {upBoundary = AdjacentCell currentLocation}
, currentLocation
, currentLocBounds {downBoundary = AdjacentCell downLoc}
)
_ -> Nothing
leftLoc = (x - 1, y)
maybeLeftCell = case (leftBoundary currentLocBounds, Set.member leftLoc visited) of
(Wall, False) -> Just
( leftLoc
, (fromJust $ Map.lookup leftLoc bounds) {rightBoundary = AdjacentCell currentLocation}
, currentLocation
, currentLocBounds {leftBoundary = AdjacentCell leftLoc}
)
_ -> Nothing
in catMaybes [maybeUpCell, maybeRightCell, maybeDownCell, maybeLeftCell]
-- Input must be non empty!
chooseCandidate :: [(Location, CellBoundaries, Location, CellBoundaries)] -> State SearchState ()
chooseCandidate candidates = do
(SearchState gen currentLocs boundsMap visited) <- get
let (randomIndex, newGen) = randomR (0, (length candidates) - 1) gen
(chosenLocation, newChosenBounds, prevLocation, newPrevBounds) = candidates !! randomIndex
newBounds = Map.insert prevLocation newPrevBounds (Map.insert chosenLocation newChosenBounds boundsMap)
newVisited = Set.insert chosenLocation visited
put (SearchState newGen (chosenLocation : currentLocs) newBounds newVisited)
| null | https://raw.githubusercontent.com/jhb563/MazeGame/c921e77ff24cd6c2185e97808e2d54abf7c334c4/src/MazeParser.hs | haskell | top-right-bottom-left
Pick out start location. Pick end location. Set up initial state. Run DFS
Input must be non empty! | module MazeParser where
import Control.Monad (forM)
import Control.Monad.State (State, get, put, execState)
import qualified Data.Array as Array
import Data.Char (toLower, intToDigit, toUpper, digitToInt)
import Data.Either (fromRight)
import Data.List (groupBy)
import qualified Data.Map as Map
import Data.Maybe (fromJust, catMaybes)
import qualified Data.Set as Set
import Data.Text (Text, pack)
import Data.Void (Void)
import System.Random (StdGen, randomR)
import Text.Megaparsec (Parsec)
import qualified Text.Megaparsec as M
import qualified Text.Megaparsec.Char as M
import Types (Location, CellBoundaries(..), BoundaryType(..), World, Maze)
0 = 0000
1 = 0001
2 = 0010
3 = 0011
4 = 0100
5 = 0101
6 = 0110
7 = 0111
8 = 1000
9 = 1001
A = 1010
B = 1011
C = 1100
D = 1101
E = 1110
F = 1111
type MParser = Parsec Void Text
parseWorldFromFile :: FilePath -> IO World
parseWorldFromFile = undefined
sampleMaze :: Maze
sampleMaze = fromRight undefined $ M.runParser (mazeParser (5,5)) "" testMaze
testMaze :: Text
testMaze = pack $ unlines
[ "98CDF"
, "1041C"
, "34775"
, "90AA4"
, "32EB6"
]
mazeParser :: (Int, Int) -> MParser Maze
mazeParser (numRows, numColumns) = do
rows <- forM [(numRows - 1),(numRows - 2)..0] $ \i -> do
columns <- forM [0..(numColumns - 1)] $ \j -> do
c <- M.hexDigitChar
return (j, c)
M.newline
return $ map (\(col, char) -> ((col, i), char)) columns
return $ Map.fromList (cellSpecToBounds <$> (concat rows))
where
cellSpecToBounds :: (Location, Char) -> (Location, CellBoundaries)
cellSpecToBounds (loc@(x, y), c) =
let (topIsWall, rightIsWall, bottomIsWall, leftIsWall) = charToBoundsSet c
topCell = if topIsWall then if y + 1 == numRows then WorldBoundary else Wall
else (AdjacentCell (x, y + 1))
rightCell = if rightIsWall then if x + 1 == numColumns then WorldBoundary else Wall
else (AdjacentCell (x + 1, y))
bottomCell = if bottomIsWall then if y == 0 then WorldBoundary else Wall
else (AdjacentCell (x, y - 1))
leftCell = if leftIsWall then if x == 0 then WorldBoundary else Wall
else (AdjacentCell (x - 1, y))
in (loc, CellBoundaries topCell rightCell bottomCell leftCell)
charToBoundsSet :: Char -> (Bool, Bool, Bool, Bool)
charToBoundsSet c =
( num > 7
, num `mod` 8 > 3
, num `mod` 4 > 1
, num `mod` 2 == 1
)
where
num = digitToInt c
charToBoundsSet ' 0 ' = ( False , False , False , False )
charToBoundsSet ' 1 ' = ( False , False , False , True )
charToBoundsSet ' 2 ' = ( False , False , True , False )
charToBoundsSet ' 3 ' = ( False , False , True , True )
charToBoundsSet ' 4 ' = ( False , True , False , False )
charToBoundsSet ' 5 ' = ( False , True , False , True )
charToBoundsSet ' 6 ' = ( False , True , True , False )
charToBoundsSet ' 7 ' = ( False , True , True , True )
charToBoundsSet ' 8 ' = ( True , False , False , False )
charToBoundsSet ' 9 ' = ( True , False , False , True )
charToBoundsSet ' a ' = ( True , False , True , False )
charToBoundsSet ' b ' = ( True , False , True , True )
charToBoundsSet ' c ' = ( True , True , False , False )
charToBoundsSet 'd ' = ( True , True , False , True )
charToBoundsSet ' e ' = ( True , True , True , False )
charToBoundsSet ' f ' = ( True , True , True , True )
charToBoundsSet _ = error " Invalid character ! "
charToBoundsSet '1' = (False, False, False, True)
charToBoundsSet '2' = (False, False, True, False)
charToBoundsSet '3' = (False, False, True, True)
charToBoundsSet '4' = (False, True, False, False)
charToBoundsSet '5' = (False, True, False, True)
charToBoundsSet '6' = (False, True, True, False)
charToBoundsSet '7' = (False, True, True, True)
charToBoundsSet '8' = (True, False, False, False)
charToBoundsSet '9' = (True, False, False, True)
charToBoundsSet 'a' = (True, False, True, False)
charToBoundsSet 'b' = (True, False, True, True)
charToBoundsSet 'c' = (True, True, False, False)
charToBoundsSet 'd' = (True, True, False, True)
charToBoundsSet 'e' = (True, True, True, False)
charToBoundsSet 'f' = (True, True, True, True)
charToBoundsSet _ = error "Invalid character!"-}
dumpMaze :: Maze -> Text
dumpMaze maze = pack $ (unlines . reverse) (rowToString <$> cellsByRow)
where
transposedMap :: Maze
transposedMap = Map.mapKeys (\(x, y) -> (y, x)) maze
cellsByRow :: [[(Location, CellBoundaries)]]
cellsByRow = groupBy (\((r1, _), _) ((r2, _), _) -> r1 == r2) (Map.toList transposedMap)
rowToString :: [(Location, CellBoundaries)] -> String
rowToString = map (cellToChar . snd)
cellToChar :: CellBoundaries -> Char
cellToChar bounds =
let top = case upBoundary bounds of
(AdjacentCell _) -> 0
_ -> 8
right = case rightBoundary bounds of
(AdjacentCell _) -> 0
_ -> 4
down = case downBoundary bounds of
(AdjacentCell _) -> 0
_ -> 2
left = case leftBoundary bounds of
(AdjacentCell _) -> 0
_ -> 1
in toUpper $ intToDigit (top + right + down + left)
generateRandomMaze :: StdGen -> (Int, Int) -> (Maze, StdGen)
generateRandomMaze gen (numRows, numColumns) = (currentBoundaries finalState, randomGen finalState)
where
(startX, g1) = randomR (0, numColumns - 1) gen
(startY, g2) = randomR (0, numRows - 1) g1
initialState = SearchState g2 [(startX, startY)] initialBounds Set.empty
initialBounds :: Maze
initialBounds = case M.runParser (mazeParser (numRows, numColumns)) "" fullString of
Left _ -> error "Maze can't be parsed!"
Right success -> success
fullString :: Text
fullString = pack . unlines $ take numRows $ repeat (take numColumns (repeat 'F'))
finalState = execState dfsSearch initialState
data SearchState = SearchState
{ randomGen :: StdGen
, locationStack :: [Location]
, currentBoundaries :: Maze
, visitedCells :: Set.Set Location
}
dfsSearch :: State SearchState ()
dfsSearch = do
(SearchState gen locs bounds visited) <- get
case locs of
[] -> return ()
(currentLoc : rest) -> do
let candidateLocs = findCandidates currentLoc bounds visited
if null candidateLocs
then put (SearchState gen rest bounds visited) >> dfsSearch
else chooseCandidate candidateLocs >> dfsSearch
where
findCandidates :: Location -> Maze -> Set.Set Location -> [(Location, CellBoundaries, Location, CellBoundaries)]
findCandidates currentLocation@(x, y) bounds visited =
let currentLocBounds = fromJust $ Map.lookup currentLocation bounds
upLoc = (x, y + 1)
maybeUpCell = case (upBoundary currentLocBounds, Set.member upLoc visited) of
(Wall, False) -> Just
( upLoc
, (fromJust $ Map.lookup upLoc bounds) {downBoundary = AdjacentCell currentLocation}
, currentLocation
, currentLocBounds {upBoundary = AdjacentCell upLoc}
)
_ -> Nothing
rightLoc = (x + 1, y)
maybeRightCell = case (rightBoundary currentLocBounds, Set.member rightLoc visited) of
(Wall, False) -> Just
( rightLoc
, (fromJust $ Map.lookup rightLoc bounds) {leftBoundary = AdjacentCell currentLocation}
, currentLocation
, currentLocBounds {rightBoundary = AdjacentCell rightLoc}
)
_ -> Nothing
downLoc = (x, y - 1)
maybeDownCell = case (downBoundary currentLocBounds, Set.member downLoc visited) of
(Wall, False) -> Just
( downLoc
, (fromJust $ Map.lookup downLoc bounds) {upBoundary = AdjacentCell currentLocation}
, currentLocation
, currentLocBounds {downBoundary = AdjacentCell downLoc}
)
_ -> Nothing
leftLoc = (x - 1, y)
maybeLeftCell = case (leftBoundary currentLocBounds, Set.member leftLoc visited) of
(Wall, False) -> Just
( leftLoc
, (fromJust $ Map.lookup leftLoc bounds) {rightBoundary = AdjacentCell currentLocation}
, currentLocation
, currentLocBounds {leftBoundary = AdjacentCell leftLoc}
)
_ -> Nothing
in catMaybes [maybeUpCell, maybeRightCell, maybeDownCell, maybeLeftCell]
chooseCandidate :: [(Location, CellBoundaries, Location, CellBoundaries)] -> State SearchState ()
chooseCandidate candidates = do
(SearchState gen currentLocs boundsMap visited) <- get
let (randomIndex, newGen) = randomR (0, (length candidates) - 1) gen
(chosenLocation, newChosenBounds, prevLocation, newPrevBounds) = candidates !! randomIndex
newBounds = Map.insert prevLocation newPrevBounds (Map.insert chosenLocation newChosenBounds boundsMap)
newVisited = Set.insert chosenLocation visited
put (SearchState newGen (chosenLocation : currentLocs) newBounds newVisited)
|
94b38d14f2c62a17d80728e8c167cd541f0bce136b2c16937c05a9a43675b890 | visi-lang/visi | Markdown.hs | module Visi.Markdown (markdown) where
Copyright ( c ) 2003 - 2004
< / >
Copyright ( c ) 2012
All rights reserved .
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are
met :
* Redistributions of source code must retain the above copyright notice ,
this list of conditions and the following disclaimer .
* Redistributions in binary form must reproduce the above copyright
notice , this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution .
* Neither the name " Markdown " nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission .
This software is provided by the copyright holders and contributors " as
is " and any express or implied warranties , including , but not limited
to , the implied warranties of merchantability and fitness for a
particular purpose are disclaimed . In no event shall the copyright owner
or 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 .
Copyright (c) 2003-2004 John Gruber
</>
Copyright (c) 2012 David Pollak
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name "Markdown" nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
This software is provided by the copyright holders and contributors "as
is" and any express or implied warranties, including, but not limited
to, the implied warranties of merchantability and fitness for a
particular purpose are disclaimed. In no event shall the copyright owner
or 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.
-}
import Text.Regex.PCRE
import Data.Array
import Visi.Util
import Control.Monad.State.Lazy
import qualified Data.Map as M
import qualified Data.ByteString as B
import Data.ByteString.UTF8 (toString, fromString)
import Data.Tuple (swap)
type LocalState = State (M.Map B.ByteString B.ByteString)
escChars = map fromString $ map (\c -> [c]) "\\`*_{}[]()#+-.!"
escList = map (\s -> (s, fromString $ hexHash s)) escChars
htmlList = map (\(a,b) -> (fromString a, fromString b)) [(">", ">"), ("<", "<"), ("&", "&")]
escapeMap = M.fromList $ htmlList ++ escList
buildDefaultMap = M.fromList $ map swap escList
markdown :: String -> String
markdown s = (toString (evalState (xform $ fromString s) buildDefaultMap)) ++ "\n"
xform s = (return s) >>= (gsub "\r\n" "\n") >>= (gsub "\r" "\n") >>=
(\s -> return $ s `B.append` doubleNewline) >>= eachLine scrubTabs >>=
hashHtmlBlocks >>=
stripLinkDefinitions >>=
runBlockGamut >>=
unescapeSpecialChars
blockTags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
blockTags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
lessThanTab = tabWidth - 1
firstHtmlMatch = "(^<("++ blockTags_a ++ ")\\b(.*\n)*?</\\2>[ \t]*(?=\n+|\\Z))"
secondHtmlMatch = "(^<("++ blockTags_b ++ ")\\b(.*\n)*?.*</\2>[ \t]*(?=\n+|\\Z))"
hrHtmlMatch = "(?:(?<=\n\n)|\\A\n?)([ ]{0,"++(show lessThanTab)++"}<(hr)\\b([^<>])*?/?>[ \t]*(?=\n{2,}|\\Z))"
commentHtmlMatch = "(?:(?<=\n\n)|\\A\n?)([ ]{0,"++(show lessThanTab)++"}(?s:<!(--.*?--\\s*)+>)[ \t]*(?=\n{2,}|\\Z))"
doubleNewline = fromString "\n\n"
singleNewline = fromString "\n"
hashHtmlBlocks s = (return s) >>= gsub firstHtmlMatch subber >>=
gsub secondHtmlMatch subber >>= gsub hrHtmlMatch subber >>= gsub commentHtmlMatch subber
where
subber :: B.ByteString -> LocalState B.ByteString
subber str = do
let digest = fromString $ hexHash str
st <- get
put $ M.insert digest str st
return $ B.concat [doubleNewline, digest, doubleNewline]
FIXME
runBlockGamut :: B.ByteString -> LocalState B.ByteString
runBlockGamut s = (return s) >>= doHeaders >>= gsub "^[ ]{0,2}([ ]?\\*[ ]?){3,}[ \t]*$\n" "\n<hr>\n" >>=
gsub "^[ ]{0,2}([ ]? -[ ]?){3,}[ \t]*$\n" "\n<hr>\n" >>=
gsub "^[ ]{0,2}([ ]? _[ ]?){3,}[ \t]*$\n" "\n<hr>\n" >>=
doLists >>= doCodeBlocks >>= doBlockQuotes >>= hashHtmlBlocks >>= formParagraphs
FIXME
FIXME
endPara = fromString "</p>\n\n"
paragraphReplace :: B.ByteString -> LocalState B.ByteString
paragraphReplace s = split "\n{2,}" doParagraph s
where doParagraph :: B.ByteString -> LocalState B.ByteString
doParagraph str = do
st <- get
case M.lookup str st of
Just repl -> return $ repl `B.append` doubleNewline
_ -> (return str) >>= runSpanGamut >>= sub1 "^([ \t])*" "<p>" >>= (\s -> return $ s `B.append` endPara)
formParagraphs s = (return s) >>= gsub "\\A\n+" "" >>= gsub "\n+\\z" "" >>= paragraphReplace
runSpanGamut :: B.ByteString -> LocalState B.ByteString
runSpanGamut s = (return s) >>= doCodeSpans >>= doEscapeSpecialChars >>=
doImages >>= doAnchors >>= doAutoLinks >>= encodeAmpsAndAngles >>= doItalicsAndBold >>=
gsub " {2,}\n" "<br>"
FIXME
FIXME
FIXME
FIXME
FIXME
encodeAmpsAndAngles s = return s >>= gsub "&(?!#?[xX]?(?:[0-9a-fA-F]+|\\w+);)" "&" >>= gsub "<(?![a-zA-Z/?\\$!])" "<"
doItalicsAndBold s = (return s) >>=
gsub "(\\*\\*|__) (?=\\S) (.+?[*_]*) (?<=\\S) \1" (\s -> B.concat [preStrong, s, postStrong]) >>=
gsub "(\\*|_) (?=\\S) (.+?) (?<=\\S) \1" (\s -> B.concat [preEm, s, postEm])
preStrong = fromString "<strong>"
postStrong = fromString "</strong>"
preEm = fromString "<em>"
postEm = fromString "</em>"
FIXME
doCodeBlocks s = gsub ("(?:\n\n|\\A)((?:(?:[ ]{" ++ show tabWidth ++ "}|\t).*\n+)+)((?=^[ ]{0," ++ show tabWidth ++ "}\\S)|\\Z)") handleCode s
where handleCode :: (B.ByteString, MatchArray, [(Int, Int)]) -> LocalState B.ByteString
handleCode (str, ma, pairs) = return str >>= encodeCode >>= detab >>= gsub "\\A\n+" "" >>= gsub "\\s+\\z" "" >>=
(\s -> return $ B.concat [preStart, s, preEnd])
detab = eachLine $ sub1 "^(\t| )" ""
preStart = fromString "\n\n<pre><code>"
preEnd = fromString "\n</code></pre>\n\n"
encodeCode s = gsub "(&|>|<|\\*|_|{|}|\\[|\\]\\\\)" doCharThing s
where doCharThing str = escapeMap M.! str
replaceThem str (k,v) = gsub (toString k) v str
unescapeSpecialChars s =
do
chars <- get
foldM replaceThem s $ M.assocs chars
tabWidth = 4
scrubTabs :: B.ByteString -> B.ByteString
scrubTabs s =
if s =~ "^[ \t]*$\n" then singleNewline
else tabByTab s
grabSpaces pos = fromString " "
tabByTab :: B.ByteString -> B.ByteString
tabByTab s =
case elems (s =~ "(.*?)\t" :: MatchArray) of
(start, len):(_, ms):_ -> tabByTab $ B.concat [(before ms s),
grabSpaces ms,
(after (start + len) s)]
_ -> s
eachLine f = gsub "^.*$\n" runLine
where runLine s = (f s)
split :: AppFunc a => String -> a -> B.ByteString -> LocalState B.ByteString
split regex f str =
if B.null str then return B.empty
else
let ma = (str =~ regex :: MatchArray) in
case elems $ ma of
(0,0):_ -> return str
whole@(pos@(start,len):_) -> do
retStr <- applyFunc f (before start str, ma, whole)
endStr <- split regex f (after (start + len) str)
return $ retStr `B.append` endStr
_ -> return str
sub1 :: AppFunc a => String -> a -> B.ByteString -> LocalState B.ByteString
sub1 regex f str =
if B.null str then return B.empty
else
let ma = (str =~ regex :: MatchArray) in
case elems $ ma of
whole@(pos@(start,len):_) -> do
retStr <- applyFunc f (extract pos str, ma, whole)
let endStr = after (start + len) str
return $ B.concat [(before start str), retStr, endStr]
_ -> return $ str
gsub :: AppFunc a => String -> a -> B.ByteString -> LocalState B.ByteString
gsub regex f str =
if B.null str then return B.empty
else
let ma = (str =~ regex :: MatchArray) in
case elems $ ma of
(0,0):_ -> return $ str
whole@(pos@(start,len):_) -> do
retStr <- applyFunc f (extract pos str, ma, whole)
endStr <- gsub regex f $ after (start + len) str
return $ B.concat [(before start str), retStr, endStr]
_ -> return $ str
class AppFunc a where
applyFunc :: a -> (B.ByteString, MatchArray, [(Int, Int)]) -> LocalState B.ByteString
instance AppFunc (B.ByteString -> B.ByteString) where
applyFunc f (s, _, _) = return $ f s
instance AppFunc String where
applyFunc a s = return $ fromString a
instance AppFunc B.ByteString where
applyFunc a s = return $ a
instance AppFunc ([(Int, Int)] -> B.ByteString) where
applyFunc f (s, ma, whole) = return $ f whole
instance AppFunc ((B.ByteString, MatchArray, [(Int, Int)]) -> LocalState B.ByteString) where
applyFunc f v = f v
instance AppFunc (B.ByteString -> LocalState B.ByteString) where
applyFunc f (s, _, _) = (f s)
| null | https://raw.githubusercontent.com/visi-lang/visi/8993314128e562b829f27266bc660c5eff4623b8/core/src/Visi/Markdown.hs | haskell | module Visi.Markdown (markdown) where
Copyright ( c ) 2003 - 2004
< / >
Copyright ( c ) 2012
All rights reserved .
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are
met :
* Redistributions of source code must retain the above copyright notice ,
this list of conditions and the following disclaimer .
* Redistributions in binary form must reproduce the above copyright
notice , this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution .
* Neither the name " Markdown " nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission .
This software is provided by the copyright holders and contributors " as
is " and any express or implied warranties , including , but not limited
to , the implied warranties of merchantability and fitness for a
particular purpose are disclaimed . In no event shall the copyright owner
or 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 .
Copyright (c) 2003-2004 John Gruber
</>
Copyright (c) 2012 David Pollak
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name "Markdown" nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
This software is provided by the copyright holders and contributors "as
is" and any express or implied warranties, including, but not limited
to, the implied warranties of merchantability and fitness for a
particular purpose are disclaimed. In no event shall the copyright owner
or 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.
-}
import Text.Regex.PCRE
import Data.Array
import Visi.Util
import Control.Monad.State.Lazy
import qualified Data.Map as M
import qualified Data.ByteString as B
import Data.ByteString.UTF8 (toString, fromString)
import Data.Tuple (swap)
type LocalState = State (M.Map B.ByteString B.ByteString)
escChars = map fromString $ map (\c -> [c]) "\\`*_{}[]()#+-.!"
escList = map (\s -> (s, fromString $ hexHash s)) escChars
htmlList = map (\(a,b) -> (fromString a, fromString b)) [(">", ">"), ("<", "<"), ("&", "&")]
escapeMap = M.fromList $ htmlList ++ escList
buildDefaultMap = M.fromList $ map swap escList
markdown :: String -> String
markdown s = (toString (evalState (xform $ fromString s) buildDefaultMap)) ++ "\n"
xform s = (return s) >>= (gsub "\r\n" "\n") >>= (gsub "\r" "\n") >>=
(\s -> return $ s `B.append` doubleNewline) >>= eachLine scrubTabs >>=
hashHtmlBlocks >>=
stripLinkDefinitions >>=
runBlockGamut >>=
unescapeSpecialChars
blockTags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
blockTags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
lessThanTab = tabWidth - 1
firstHtmlMatch = "(^<("++ blockTags_a ++ ")\\b(.*\n)*?</\\2>[ \t]*(?=\n+|\\Z))"
secondHtmlMatch = "(^<("++ blockTags_b ++ ")\\b(.*\n)*?.*</\2>[ \t]*(?=\n+|\\Z))"
hrHtmlMatch = "(?:(?<=\n\n)|\\A\n?)([ ]{0,"++(show lessThanTab)++"}<(hr)\\b([^<>])*?/?>[ \t]*(?=\n{2,}|\\Z))"
commentHtmlMatch = "(?:(?<=\n\n)|\\A\n?)([ ]{0,"++(show lessThanTab)++"}(?s:<!(--.*?--\\s*)+>)[ \t]*(?=\n{2,}|\\Z))"
doubleNewline = fromString "\n\n"
singleNewline = fromString "\n"
hashHtmlBlocks s = (return s) >>= gsub firstHtmlMatch subber >>=
gsub secondHtmlMatch subber >>= gsub hrHtmlMatch subber >>= gsub commentHtmlMatch subber
where
subber :: B.ByteString -> LocalState B.ByteString
subber str = do
let digest = fromString $ hexHash str
st <- get
put $ M.insert digest str st
return $ B.concat [doubleNewline, digest, doubleNewline]
FIXME
runBlockGamut :: B.ByteString -> LocalState B.ByteString
runBlockGamut s = (return s) >>= doHeaders >>= gsub "^[ ]{0,2}([ ]?\\*[ ]?){3,}[ \t]*$\n" "\n<hr>\n" >>=
gsub "^[ ]{0,2}([ ]? -[ ]?){3,}[ \t]*$\n" "\n<hr>\n" >>=
gsub "^[ ]{0,2}([ ]? _[ ]?){3,}[ \t]*$\n" "\n<hr>\n" >>=
doLists >>= doCodeBlocks >>= doBlockQuotes >>= hashHtmlBlocks >>= formParagraphs
FIXME
FIXME
endPara = fromString "</p>\n\n"
paragraphReplace :: B.ByteString -> LocalState B.ByteString
paragraphReplace s = split "\n{2,}" doParagraph s
where doParagraph :: B.ByteString -> LocalState B.ByteString
doParagraph str = do
st <- get
case M.lookup str st of
Just repl -> return $ repl `B.append` doubleNewline
_ -> (return str) >>= runSpanGamut >>= sub1 "^([ \t])*" "<p>" >>= (\s -> return $ s `B.append` endPara)
formParagraphs s = (return s) >>= gsub "\\A\n+" "" >>= gsub "\n+\\z" "" >>= paragraphReplace
runSpanGamut :: B.ByteString -> LocalState B.ByteString
runSpanGamut s = (return s) >>= doCodeSpans >>= doEscapeSpecialChars >>=
doImages >>= doAnchors >>= doAutoLinks >>= encodeAmpsAndAngles >>= doItalicsAndBold >>=
gsub " {2,}\n" "<br>"
FIXME
FIXME
FIXME
FIXME
FIXME
encodeAmpsAndAngles s = return s >>= gsub "&(?!#?[xX]?(?:[0-9a-fA-F]+|\\w+);)" "&" >>= gsub "<(?![a-zA-Z/?\\$!])" "<"
doItalicsAndBold s = (return s) >>=
gsub "(\\*\\*|__) (?=\\S) (.+?[*_]*) (?<=\\S) \1" (\s -> B.concat [preStrong, s, postStrong]) >>=
gsub "(\\*|_) (?=\\S) (.+?) (?<=\\S) \1" (\s -> B.concat [preEm, s, postEm])
preStrong = fromString "<strong>"
postStrong = fromString "</strong>"
preEm = fromString "<em>"
postEm = fromString "</em>"
FIXME
doCodeBlocks s = gsub ("(?:\n\n|\\A)((?:(?:[ ]{" ++ show tabWidth ++ "}|\t).*\n+)+)((?=^[ ]{0," ++ show tabWidth ++ "}\\S)|\\Z)") handleCode s
where handleCode :: (B.ByteString, MatchArray, [(Int, Int)]) -> LocalState B.ByteString
handleCode (str, ma, pairs) = return str >>= encodeCode >>= detab >>= gsub "\\A\n+" "" >>= gsub "\\s+\\z" "" >>=
(\s -> return $ B.concat [preStart, s, preEnd])
detab = eachLine $ sub1 "^(\t| )" ""
preStart = fromString "\n\n<pre><code>"
preEnd = fromString "\n</code></pre>\n\n"
encodeCode s = gsub "(&|>|<|\\*|_|{|}|\\[|\\]\\\\)" doCharThing s
where doCharThing str = escapeMap M.! str
replaceThem str (k,v) = gsub (toString k) v str
unescapeSpecialChars s =
do
chars <- get
foldM replaceThem s $ M.assocs chars
tabWidth = 4
scrubTabs :: B.ByteString -> B.ByteString
scrubTabs s =
if s =~ "^[ \t]*$\n" then singleNewline
else tabByTab s
grabSpaces pos = fromString " "
tabByTab :: B.ByteString -> B.ByteString
tabByTab s =
case elems (s =~ "(.*?)\t" :: MatchArray) of
(start, len):(_, ms):_ -> tabByTab $ B.concat [(before ms s),
grabSpaces ms,
(after (start + len) s)]
_ -> s
eachLine f = gsub "^.*$\n" runLine
where runLine s = (f s)
split :: AppFunc a => String -> a -> B.ByteString -> LocalState B.ByteString
split regex f str =
if B.null str then return B.empty
else
let ma = (str =~ regex :: MatchArray) in
case elems $ ma of
(0,0):_ -> return str
whole@(pos@(start,len):_) -> do
retStr <- applyFunc f (before start str, ma, whole)
endStr <- split regex f (after (start + len) str)
return $ retStr `B.append` endStr
_ -> return str
sub1 :: AppFunc a => String -> a -> B.ByteString -> LocalState B.ByteString
sub1 regex f str =
if B.null str then return B.empty
else
let ma = (str =~ regex :: MatchArray) in
case elems $ ma of
whole@(pos@(start,len):_) -> do
retStr <- applyFunc f (extract pos str, ma, whole)
let endStr = after (start + len) str
return $ B.concat [(before start str), retStr, endStr]
_ -> return $ str
gsub :: AppFunc a => String -> a -> B.ByteString -> LocalState B.ByteString
gsub regex f str =
if B.null str then return B.empty
else
let ma = (str =~ regex :: MatchArray) in
case elems $ ma of
(0,0):_ -> return $ str
whole@(pos@(start,len):_) -> do
retStr <- applyFunc f (extract pos str, ma, whole)
endStr <- gsub regex f $ after (start + len) str
return $ B.concat [(before start str), retStr, endStr]
_ -> return $ str
class AppFunc a where
applyFunc :: a -> (B.ByteString, MatchArray, [(Int, Int)]) -> LocalState B.ByteString
instance AppFunc (B.ByteString -> B.ByteString) where
applyFunc f (s, _, _) = return $ f s
instance AppFunc String where
applyFunc a s = return $ fromString a
instance AppFunc B.ByteString where
applyFunc a s = return $ a
instance AppFunc ([(Int, Int)] -> B.ByteString) where
applyFunc f (s, ma, whole) = return $ f whole
instance AppFunc ((B.ByteString, MatchArray, [(Int, Int)]) -> LocalState B.ByteString) where
applyFunc f v = f v
instance AppFunc (B.ByteString -> LocalState B.ByteString) where
applyFunc f (s, _, _) = (f s)
| |
8397d632ebbbab06ba6d58e72b34a03d54eadff8567ef29bea1580cd2006c784 | ctford/overtunes | core.clj | (ns before.test.core
(:use [before.core])
(:use [clojure.test]))
(deftest replace-me ;; FIXME: write
(is false "No tests have been written."))
| null | https://raw.githubusercontent.com/ctford/overtunes/44dc2d6482315e1893cf19000cfe3381a2c41da4/test/overtunes/test/core.clj | clojure | FIXME: write | (ns before.test.core
(:use [before.core])
(:use [clojure.test]))
(is false "No tests have been written."))
|
13e3ebc950af58ab06a80d6d02a99821b3684ab12326c6fb2222e618a2af732b | sebhoss/finj | deprecation.clj | ;
Copyright © 2013 < >
; This work is free. You can redistribute it and/or modify it under the
terms of the Do What The Fuck You Want To Public License , Version 2 ,
as published by . See / for more details .
;
(ns finj.deprecation
"In accountancy, depreciation refers to two aspects of the same concept:
* the decrease in value of assets (fair value depreciation), and
* the allocation of the cost of assets to periods in which the assets are used (depreciation with the matching
principle).
The former affects the balance sheet of a business or entity, and the latter affects the net income that they report.
Generally the cost is allocated, as depreciation expense, among the periods in which the asset is expected to be
used. This expense is recognized by businesses for financial reporting and tax purposes. Methods of computing
depreciation, and the periods over which assets are depreciated, may vary between asset types within the same
business. These may be specified by law or accounting standards, which may vary by country. There are several
standard methods of computing depreciation expense, including fixed percentage, straight line, and declining balance
methods. Depreciation expense generally begins when the asset is placed in service. For example, a depreciation
expense of 100 per year for 5 years may be recognized for an asset costing 500.
References:
* "
(:require [com.github.sebhoss.def :refer :all]
[com.github.sebhoss.math :refer :all]
[com.github.sebhoss.predicate :refer :all]))
(defnk straight-line-annual-expense
"Calculates the annual deprecation expense of an asset using straight line deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (straight-line-annual-expense :fixed-asset 1000 :residual-value 100 :period 5)
=> 180
* (straight-line-annual-expense :fixed-asset 2000 :residual-value 200 :period 8)
=> 225
* (straight-line-annual-expense :fixed-asset 3000 :residual-value 300 :period 12)
=> 225
References:
* #Straight-line_depreciation"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(-> fixed-asset
(- residual-value)
(/ period)))
(defnk straight-line-expense
"Calculates the deprecation expense sequence of an asset using straight line deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (straight-line-expense :fixed-asset 1000 :residual-value 100 :period 5)
=> (180 180 180 180 180)
* (straight-line-expense :fixed-asset 2000 :residual-value 200 :period 8)
=> (225 225 225 225 225 225 225 225)
* (straight-line-expense :fixed-asset 3000 :residual-value 300 :period 12)
=> (225 225 225 225 225 225 225 225 225 225 225 225)
References:
* #Straight-line_depreciation"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(let [annual-expense (straight-line-annual-expense
:fixed-asset fixed-asset
:residual-value residual-value
:period period)]
(->> annual-expense
(repeat)
(take period))))
(defnk straight-line-accumulated
"Calculates the accumulated deprecation expense sequence of an asset using straight line deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (straight-line-accumulated :fixed-asset 1000 :residual-value 100 :period 5)
=> (180 360 540 720 900)
* (straight-line-accumulated :fixed-asset 2000 :residual-value 200 :period 8)
=> (225 450 675 900 1125 1350 1575 1800)
* (straight-line-accumulated :fixed-asset 3000 :residual-value 300 :period 12)
=> (225 450 675 900 1125 1350 1575 1800 2025 2250 2475 2700)
References:
* #Straight-line_depreciation"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(let [annual-expense (straight-line-annual-expense
:fixed-asset fixed-asset
:residual-value residual-value
:period period)]
(->> annual-expense
(iterate (partial + annual-expense))
(take period))))
(defnk straight-line-book-value
"Calculates the yearly book value sequence of an asset using straight line deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (straight-line-book-value :fixed-asset 1000 :residual-value 100 :period 5)
=> (1000 820 640 460 280 100)
* (straight-line-book-value :fixed-asset 2000 :residual-value 200 :period 8)
=> (2000 1775 1550 1325 1100 875 650 425 200)
* (straight-line-book-value :fixed-asset 3000 :residual-value 300 :period 12)
=> (3000 2775 2550 2325 2100 1875 1650 1425 1200 975 750 525 300)
References:
* #Straight-line_depreciation"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]
:post [(= fixed-asset (first %))
(≈ residual-value (last %))]}
(let [annual-expense (straight-line-annual-expense
:fixed-asset fixed-asset
:residual-value residual-value
:period period)]
(->> fixed-asset
(iterate #(- % annual-expense))
(take (inc period)))))
(defnk declining-balance-rate
"With the declining balance method, one can find the depreciation rate that would allow exactly for full depreciation
by the end of the period.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (declining-balance-rate :fixed-asset 1000 :residual-value 100 :period 5)
=> 0.36904265551980675
* (declining-balance-rate :fixed-asset 2000 :residual-value 200 :period 8)
=> 0.2501057906675441
* (declining-balance-rate :fixed-asset 3000 :residual-value 300 :period 12)
=> 0.1745958147319816
References:
* #Declining_Balance_Method"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(->> fixed-asset
(/ residual-value)
(root period)
(dec)
(abs)))
(defnk declining-balance-rate-book-value
"Calculates the book value sequence of an asset using declining balance rate deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (declining-balance-rate-book-value :fixed-asset 1000 :residual-value 100 :period 5)
=> (1000 630.9573444801932 398.1071705534972 251.188643150958 158.48931924611134 100.0)
* (declining-balance-rate-book-value :fixed-asset 2000 :residual-value 200 :period 8)
=> (2000 1499.7884186649117 1124.6826503806983 843.3930068571647 632.455532033676 474.2747411323312
355.6558820077847 266.70428643266496 200.0000000000001)
* (declining-balance-rate-book-value :fixed-asset 3000 :residual-value 300 :period 12)
=> (3000 2476.2125558040552 2043.8762071738838 1687.0239755710472 1392.4766500838336 1149.3560548671862
948.6832980505137 783.0471647047609 646.330407009565 533.4838230116767 440.33978028662074 363.45829758857644
300)
References:
* #Declining_Balance_Method"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]
:post [(= fixed-asset (first %))
(≈ residual-value (last %))]}
(let [rate (declining-balance-rate
:fixed-asset fixed-asset
:residual-value residual-value
:period period)]
(map #(if (< % residual-value) residual-value %)
(take (inc period) (iterate #(- % (* % rate)) fixed-asset)))))
(defnk declining-balance-rate-expense
"Calculates the deprecation expense sequence of an asset using declining balance rate deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (declining-balance-rate-expense :fixed-asset 1000 :residual-value 100 :period 5)
=> (369.0426555198068 232.850173926696 146.9185274025392 92.69932390484666 58.48931924611134)
* (declining-balance-rate-expense :fixed-asset 2000 :residual-value 200 :period 8)
=> (500.2115813350882 375.1057682842134 281.28964352353364 210.93747482348863 158.18079090134484
118.6188591245465 88.95159557511978 66.70428643266483)
* (declining-balance-rate-expense :fixed-asset 3000 :residual-value 300 :period 12)
=> (523.7874441959448 432.33634863017147 356.85223160283664 294.54732548721364 243.1205952166474
200.67275681667252 165.63613334575277 136.71675769519592 112.84658399788827 93.14404272505597
76.88148269804432 63.45829758857644)
References:
* #Declining_Balance_Method"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(let [rate (declining-balance-rate
:fixed-asset fixed-asset
:residual-value residual-value
:period period)
book-value (take period
(declining-balance-rate-book-value
:fixed-asset fixed-asset
:residual-value residual-value
:period period))]
(map #(if (< (- % (* % rate)) residual-value) (- % residual-value) (* % rate)) book-value)))
(defnk declining-balance-rate-accumulated
"Calculates the accumulated deprecation expense sequence of an asset using declining balance rate deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (declining-balance-rate-accumulated :fixed-asset 1000 :residual-value 100 :period 5)
=> (369.0426555198068 601.8928294465028 748.811356849042 841.5106807538887 900.0)
* (declining-balance-rate-accumulated :fixed-asset 2000 :residual-value 200 :period 8)
=> (500.2115813350882 875.3173496193017 1156.6069931428353 1367.544467966324 1525.7252588676688
1644.3441179922154 1733.2957135673353 1800.0)
* (declining-balance-rate-accumulated :fixed-asset 3000 :residual-value 300 :period 12)
=> (523.7874441959448 956.1237928261162 1312.9760244289528 1607.5233499161664 1850.6439451328138
2051.3167019494863 2216.952835295239 2353.669592990435 2466.5161769883234 2559.6602197133793
2636.5417024114236 2700.0)
References:
* #Declining_Balance_Method"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(let [expense (declining-balance-rate-expense
:fixed-asset fixed-asset
:residual-value residual-value
:period period)]
(reductions + expense)))
(defnk sum-of-years-digit-expense
"Calculates the deprecation expense sequence of an asset using sum of years digit deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (sum-of-years-digit-expense :fixed-asset 1000 :residual-value 100 :period 5)
=> (300N 240N 180N 120N 60N)
* (sum-of-years-digit-expense :fixed-asset 2000 :residual-value 200 :period 8)
=> (400N 350N 300N 250N 200N 150N 100N 50N)
* (sum-of-years-digit-expense :fixed-asset 3000 :residual-value 300 :period 12)
=> (5400/13 4950/13 4500/13 4050/13 3600/13 3150/13 2700/13 2250/13 1800/13 1350/13 900/13 450/13)
References:
* #Sum-of-years-digits_method"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(let [periods (range 1 (inc period))
sum-of-digits (reduce + periods)
total-depreciable-cost (- fixed-asset residual-value)]
(map #(* total-depreciable-cost (/ % sum-of-digits)) (reverse periods))))
(defnk sum-of-years-digit-accumulated
"Calculates the accumulated deprecation expense sequence of an asset using sum of years digit deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (sum-of-years-digit-accumulated :fixed-asset 1000 :residual-value 100 :period 5)
=> (300N 540N 720N 840N 900N)
* (sum-of-years-digit-accumulated :fixed-asset 2000 :residual-value 200 :period 8)
=> (400N 750N 1050N 1300N 1500N 1650N 1750N 1800N)
* (sum-of-years-digit-accumulated :fixed-asset 3000 :residual-value 300 :period 12)
=> (5400/13 10350/13 14850/13 18900/13 22500/13 25650/13 28350/13 30600/13 32400/13 33750/13 34650/13 2700N)
References:
* #Sum-of-years-digits_method"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(let [expenses (sum-of-years-digit-expense
:fixed-asset fixed-asset
:residual-value residual-value
:period period)]
(reductions + expenses)))
(defnk sum-of-years-digit-book-value
"Calculates the yearly book value sequence of an asset using sum of years digit deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (sum-of-years-digit-book-value :fixed-asset 1000 :residual-value 100 :period 5)
=> (1000 700N 460N 280N 160N 100N)
* (sum-of-years-digit-book-value :fixed-asset 2000 :residual-value 200 :period 8)
=> (2000 1600N 1250N 950N 700N 500N 350N 250N 200N)
* (sum-of-years-digit-book-value :fixed-asset 3000 :residual-value 300 :period 12)
=> (3000 33600/13 28650/13 24150/13 20100/13 16500/13 13350/13 10650/13 8400/13 6600/13 5250/13 4350/13 300N)
References:
* #Straight-line_depreciation"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]
:post [(= fixed-asset (first %))
(≈ residual-value (last %))]}
(let [accumulated (sum-of-years-digit-accumulated
:fixed-asset fixed-asset
:residual-value residual-value
:period period)]
(->> accumulated
(map #(- fixed-asset %))
(conj [fixed-asset])
(flatten))))
(defnk units-of-production-expense
"Calculates the deprecation expense sequence of an asset using units of production deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* production - The actual production per period. The number of items in this vector define how many
periods there are.
Examples:
* (units-of-production-expense :fixed-asset 1000 :residual-value 100 :production [100 110 120 130])
=> (4500/23 4950/23 5400/23 5850/23)
* (units-of-production-expense :fixed-asset 2000 :residual-value 200 :production [200 210 220 230])
=> (18000/43 18900/43 19800/43 20700/43)
* (units-of-production-expense :fixed-asset 3000 :residual-value 300 :production [300 310 320 330])
=> (4500/7 4650/7 4800/7 4950/7)
References:
* #Units-of-production_depreciation_method"
[:fixed-asset :residual-value :production]
{:pre [(number? fixed-asset)
(number? residual-value)
(coll? production)]}
(let [deprecation-per-unit (/ (- fixed-asset residual-value) (reduce + production))]
(map #(* % deprecation-per-unit) production)))
(defnk units-of-production-accumulated
"Calculates the accumulated deprecation expense sequence of an asset using units of production deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* production - The actual production per period. The number of items in this vector define how many
periods there are.
Examples:
* (units-of-production-accumulated :fixed-asset 1000 :residual-value 100 :production [100 110 120 130])
=> (4500/23 9450/23 14850/23 900N)
* (units-of-production-accumulated :fixed-asset 2000 :residual-value 200 :production [200 210 220 230])
=> (18000/43 36900/43 56700/43 1800N)
* (units-of-production-accumulated :fixed-asset 3000 :residual-value 300 :production [300 310 320 330])
=> (4500/7 9150/7 13950/7 2700N)
References:
* #Units-of-production_depreciation_method"
[:fixed-asset :residual-value :production]
{:pre [(number? fixed-asset)
(number? residual-value)
(coll? production)]}
(let [expenses (units-of-production-expense
:fixed-asset fixed-asset
:residual-value residual-value
:production production)]
(reductions + expenses)))
(defnk units-of-production-book-value
"Calculates the book value sequence of an asset using units of production deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* production - The actual production per period. The number of items in this vector define how many
periods there are.
Examples:
* (units-of-production-book-value :fixed-asset 1000 :residual-value 100 :production [100 110 120 130])
=> (1000 18500/23 13550/23 8150/23 100N)
* (units-of-production-book-value :fixed-asset 2000 :residual-value 200 :production [200 210 220 230])
=> (2000 68000/43 49100/43 29300/43 200N)
* (units-of-production-book-value :fixed-asset 3000 :residual-value 300 :production [300 310 320 330])
=> (3000 16500/7 11850/7 7050/7 300N)
References:
* #Units-of-production_depreciation_method"
[:fixed-asset :residual-value :production]
{:pre [(number? fixed-asset)
(number? residual-value)
(coll? production)]
:post [(= fixed-asset (first %))
(≈ residual-value (last %))]}
(let [accumulated (units-of-production-accumulated
:fixed-asset fixed-asset
:residual-value residual-value
:production production)]
(flatten (list fixed-asset (map #(- fixed-asset %) accumulated)))))
| null | https://raw.githubusercontent.com/sebhoss/finj/7c27cb506528642a6e8a673be1b9a49d68e533e5/src/main/clojure/finj/deprecation.clj | clojure |
This work is free. You can redistribute it and/or modify it under the
| Copyright © 2013 < >
terms of the Do What The Fuck You Want To Public License , Version 2 ,
as published by . See / for more details .
(ns finj.deprecation
"In accountancy, depreciation refers to two aspects of the same concept:
* the decrease in value of assets (fair value depreciation), and
* the allocation of the cost of assets to periods in which the assets are used (depreciation with the matching
principle).
The former affects the balance sheet of a business or entity, and the latter affects the net income that they report.
Generally the cost is allocated, as depreciation expense, among the periods in which the asset is expected to be
used. This expense is recognized by businesses for financial reporting and tax purposes. Methods of computing
depreciation, and the periods over which assets are depreciated, may vary between asset types within the same
business. These may be specified by law or accounting standards, which may vary by country. There are several
standard methods of computing depreciation expense, including fixed percentage, straight line, and declining balance
methods. Depreciation expense generally begins when the asset is placed in service. For example, a depreciation
expense of 100 per year for 5 years may be recognized for an asset costing 500.
References:
* "
(:require [com.github.sebhoss.def :refer :all]
[com.github.sebhoss.math :refer :all]
[com.github.sebhoss.predicate :refer :all]))
(defnk straight-line-annual-expense
"Calculates the annual deprecation expense of an asset using straight line deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (straight-line-annual-expense :fixed-asset 1000 :residual-value 100 :period 5)
=> 180
* (straight-line-annual-expense :fixed-asset 2000 :residual-value 200 :period 8)
=> 225
* (straight-line-annual-expense :fixed-asset 3000 :residual-value 300 :period 12)
=> 225
References:
* #Straight-line_depreciation"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(-> fixed-asset
(- residual-value)
(/ period)))
(defnk straight-line-expense
"Calculates the deprecation expense sequence of an asset using straight line deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (straight-line-expense :fixed-asset 1000 :residual-value 100 :period 5)
=> (180 180 180 180 180)
* (straight-line-expense :fixed-asset 2000 :residual-value 200 :period 8)
=> (225 225 225 225 225 225 225 225)
* (straight-line-expense :fixed-asset 3000 :residual-value 300 :period 12)
=> (225 225 225 225 225 225 225 225 225 225 225 225)
References:
* #Straight-line_depreciation"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(let [annual-expense (straight-line-annual-expense
:fixed-asset fixed-asset
:residual-value residual-value
:period period)]
(->> annual-expense
(repeat)
(take period))))
(defnk straight-line-accumulated
"Calculates the accumulated deprecation expense sequence of an asset using straight line deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (straight-line-accumulated :fixed-asset 1000 :residual-value 100 :period 5)
=> (180 360 540 720 900)
* (straight-line-accumulated :fixed-asset 2000 :residual-value 200 :period 8)
=> (225 450 675 900 1125 1350 1575 1800)
* (straight-line-accumulated :fixed-asset 3000 :residual-value 300 :period 12)
=> (225 450 675 900 1125 1350 1575 1800 2025 2250 2475 2700)
References:
* #Straight-line_depreciation"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(let [annual-expense (straight-line-annual-expense
:fixed-asset fixed-asset
:residual-value residual-value
:period period)]
(->> annual-expense
(iterate (partial + annual-expense))
(take period))))
(defnk straight-line-book-value
"Calculates the yearly book value sequence of an asset using straight line deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (straight-line-book-value :fixed-asset 1000 :residual-value 100 :period 5)
=> (1000 820 640 460 280 100)
* (straight-line-book-value :fixed-asset 2000 :residual-value 200 :period 8)
=> (2000 1775 1550 1325 1100 875 650 425 200)
* (straight-line-book-value :fixed-asset 3000 :residual-value 300 :period 12)
=> (3000 2775 2550 2325 2100 1875 1650 1425 1200 975 750 525 300)
References:
* #Straight-line_depreciation"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]
:post [(= fixed-asset (first %))
(≈ residual-value (last %))]}
(let [annual-expense (straight-line-annual-expense
:fixed-asset fixed-asset
:residual-value residual-value
:period period)]
(->> fixed-asset
(iterate #(- % annual-expense))
(take (inc period)))))
(defnk declining-balance-rate
"With the declining balance method, one can find the depreciation rate that would allow exactly for full depreciation
by the end of the period.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (declining-balance-rate :fixed-asset 1000 :residual-value 100 :period 5)
=> 0.36904265551980675
* (declining-balance-rate :fixed-asset 2000 :residual-value 200 :period 8)
=> 0.2501057906675441
* (declining-balance-rate :fixed-asset 3000 :residual-value 300 :period 12)
=> 0.1745958147319816
References:
* #Declining_Balance_Method"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(->> fixed-asset
(/ residual-value)
(root period)
(dec)
(abs)))
(defnk declining-balance-rate-book-value
"Calculates the book value sequence of an asset using declining balance rate deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (declining-balance-rate-book-value :fixed-asset 1000 :residual-value 100 :period 5)
=> (1000 630.9573444801932 398.1071705534972 251.188643150958 158.48931924611134 100.0)
* (declining-balance-rate-book-value :fixed-asset 2000 :residual-value 200 :period 8)
=> (2000 1499.7884186649117 1124.6826503806983 843.3930068571647 632.455532033676 474.2747411323312
355.6558820077847 266.70428643266496 200.0000000000001)
* (declining-balance-rate-book-value :fixed-asset 3000 :residual-value 300 :period 12)
=> (3000 2476.2125558040552 2043.8762071738838 1687.0239755710472 1392.4766500838336 1149.3560548671862
948.6832980505137 783.0471647047609 646.330407009565 533.4838230116767 440.33978028662074 363.45829758857644
300)
References:
* #Declining_Balance_Method"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]
:post [(= fixed-asset (first %))
(≈ residual-value (last %))]}
(let [rate (declining-balance-rate
:fixed-asset fixed-asset
:residual-value residual-value
:period period)]
(map #(if (< % residual-value) residual-value %)
(take (inc period) (iterate #(- % (* % rate)) fixed-asset)))))
(defnk declining-balance-rate-expense
"Calculates the deprecation expense sequence of an asset using declining balance rate deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (declining-balance-rate-expense :fixed-asset 1000 :residual-value 100 :period 5)
=> (369.0426555198068 232.850173926696 146.9185274025392 92.69932390484666 58.48931924611134)
* (declining-balance-rate-expense :fixed-asset 2000 :residual-value 200 :period 8)
=> (500.2115813350882 375.1057682842134 281.28964352353364 210.93747482348863 158.18079090134484
118.6188591245465 88.95159557511978 66.70428643266483)
* (declining-balance-rate-expense :fixed-asset 3000 :residual-value 300 :period 12)
=> (523.7874441959448 432.33634863017147 356.85223160283664 294.54732548721364 243.1205952166474
200.67275681667252 165.63613334575277 136.71675769519592 112.84658399788827 93.14404272505597
76.88148269804432 63.45829758857644)
References:
* #Declining_Balance_Method"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(let [rate (declining-balance-rate
:fixed-asset fixed-asset
:residual-value residual-value
:period period)
book-value (take period
(declining-balance-rate-book-value
:fixed-asset fixed-asset
:residual-value residual-value
:period period))]
(map #(if (< (- % (* % rate)) residual-value) (- % residual-value) (* % rate)) book-value)))
(defnk declining-balance-rate-accumulated
"Calculates the accumulated deprecation expense sequence of an asset using declining balance rate deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (declining-balance-rate-accumulated :fixed-asset 1000 :residual-value 100 :period 5)
=> (369.0426555198068 601.8928294465028 748.811356849042 841.5106807538887 900.0)
* (declining-balance-rate-accumulated :fixed-asset 2000 :residual-value 200 :period 8)
=> (500.2115813350882 875.3173496193017 1156.6069931428353 1367.544467966324 1525.7252588676688
1644.3441179922154 1733.2957135673353 1800.0)
* (declining-balance-rate-accumulated :fixed-asset 3000 :residual-value 300 :period 12)
=> (523.7874441959448 956.1237928261162 1312.9760244289528 1607.5233499161664 1850.6439451328138
2051.3167019494863 2216.952835295239 2353.669592990435 2466.5161769883234 2559.6602197133793
2636.5417024114236 2700.0)
References:
* #Declining_Balance_Method"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(let [expense (declining-balance-rate-expense
:fixed-asset fixed-asset
:residual-value residual-value
:period period)]
(reductions + expense)))
(defnk sum-of-years-digit-expense
"Calculates the deprecation expense sequence of an asset using sum of years digit deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (sum-of-years-digit-expense :fixed-asset 1000 :residual-value 100 :period 5)
=> (300N 240N 180N 120N 60N)
* (sum-of-years-digit-expense :fixed-asset 2000 :residual-value 200 :period 8)
=> (400N 350N 300N 250N 200N 150N 100N 50N)
* (sum-of-years-digit-expense :fixed-asset 3000 :residual-value 300 :period 12)
=> (5400/13 4950/13 4500/13 4050/13 3600/13 3150/13 2700/13 2250/13 1800/13 1350/13 900/13 450/13)
References:
* #Sum-of-years-digits_method"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(let [periods (range 1 (inc period))
sum-of-digits (reduce + periods)
total-depreciable-cost (- fixed-asset residual-value)]
(map #(* total-depreciable-cost (/ % sum-of-digits)) (reverse periods))))
(defnk sum-of-years-digit-accumulated
"Calculates the accumulated deprecation expense sequence of an asset using sum of years digit deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (sum-of-years-digit-accumulated :fixed-asset 1000 :residual-value 100 :period 5)
=> (300N 540N 720N 840N 900N)
* (sum-of-years-digit-accumulated :fixed-asset 2000 :residual-value 200 :period 8)
=> (400N 750N 1050N 1300N 1500N 1650N 1750N 1800N)
* (sum-of-years-digit-accumulated :fixed-asset 3000 :residual-value 300 :period 12)
=> (5400/13 10350/13 14850/13 18900/13 22500/13 25650/13 28350/13 30600/13 32400/13 33750/13 34650/13 2700N)
References:
* #Sum-of-years-digits_method"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]}
(let [expenses (sum-of-years-digit-expense
:fixed-asset fixed-asset
:residual-value residual-value
:period period)]
(reductions + expenses)))
(defnk sum-of-years-digit-book-value
"Calculates the yearly book value sequence of an asset using sum of years digit deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* period - Useful life of asset
Examples:
* (sum-of-years-digit-book-value :fixed-asset 1000 :residual-value 100 :period 5)
=> (1000 700N 460N 280N 160N 100N)
* (sum-of-years-digit-book-value :fixed-asset 2000 :residual-value 200 :period 8)
=> (2000 1600N 1250N 950N 700N 500N 350N 250N 200N)
* (sum-of-years-digit-book-value :fixed-asset 3000 :residual-value 300 :period 12)
=> (3000 33600/13 28650/13 24150/13 20100/13 16500/13 13350/13 10650/13 8400/13 6600/13 5250/13 4350/13 300N)
References:
* #Straight-line_depreciation"
[:fixed-asset :residual-value :period]
{:pre [(number? fixed-asset)
(number? residual-value)
(number? period)]
:post [(= fixed-asset (first %))
(≈ residual-value (last %))]}
(let [accumulated (sum-of-years-digit-accumulated
:fixed-asset fixed-asset
:residual-value residual-value
:period period)]
(->> accumulated
(map #(- fixed-asset %))
(conj [fixed-asset])
(flatten))))
(defnk units-of-production-expense
"Calculates the deprecation expense sequence of an asset using units of production deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* production - The actual production per period. The number of items in this vector define how many
periods there are.
Examples:
* (units-of-production-expense :fixed-asset 1000 :residual-value 100 :production [100 110 120 130])
=> (4500/23 4950/23 5400/23 5850/23)
* (units-of-production-expense :fixed-asset 2000 :residual-value 200 :production [200 210 220 230])
=> (18000/43 18900/43 19800/43 20700/43)
* (units-of-production-expense :fixed-asset 3000 :residual-value 300 :production [300 310 320 330])
=> (4500/7 4650/7 4800/7 4950/7)
References:
* #Units-of-production_depreciation_method"
[:fixed-asset :residual-value :production]
{:pre [(number? fixed-asset)
(number? residual-value)
(coll? production)]}
(let [deprecation-per-unit (/ (- fixed-asset residual-value) (reduce + production))]
(map #(* % deprecation-per-unit) production)))
(defnk units-of-production-accumulated
"Calculates the accumulated deprecation expense sequence of an asset using units of production deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* production - The actual production per period. The number of items in this vector define how many
periods there are.
Examples:
* (units-of-production-accumulated :fixed-asset 1000 :residual-value 100 :production [100 110 120 130])
=> (4500/23 9450/23 14850/23 900N)
* (units-of-production-accumulated :fixed-asset 2000 :residual-value 200 :production [200 210 220 230])
=> (18000/43 36900/43 56700/43 1800N)
* (units-of-production-accumulated :fixed-asset 3000 :residual-value 300 :production [300 310 320 330])
=> (4500/7 9150/7 13950/7 2700N)
References:
* #Units-of-production_depreciation_method"
[:fixed-asset :residual-value :production]
{:pre [(number? fixed-asset)
(number? residual-value)
(coll? production)]}
(let [expenses (units-of-production-expense
:fixed-asset fixed-asset
:residual-value residual-value
:production production)]
(reductions + expenses)))
(defnk units-of-production-book-value
"Calculates the book value sequence of an asset using units of production deprecation.
Parameters:
* fixed-asset - Cost of fixed asset
* residual-value - Estimate of the value of the asset at the time it will be sold or disposed of
* production - The actual production per period. The number of items in this vector define how many
periods there are.
Examples:
* (units-of-production-book-value :fixed-asset 1000 :residual-value 100 :production [100 110 120 130])
=> (1000 18500/23 13550/23 8150/23 100N)
* (units-of-production-book-value :fixed-asset 2000 :residual-value 200 :production [200 210 220 230])
=> (2000 68000/43 49100/43 29300/43 200N)
* (units-of-production-book-value :fixed-asset 3000 :residual-value 300 :production [300 310 320 330])
=> (3000 16500/7 11850/7 7050/7 300N)
References:
* #Units-of-production_depreciation_method"
[:fixed-asset :residual-value :production]
{:pre [(number? fixed-asset)
(number? residual-value)
(coll? production)]
:post [(= fixed-asset (first %))
(≈ residual-value (last %))]}
(let [accumulated (units-of-production-accumulated
:fixed-asset fixed-asset
:residual-value residual-value
:production production)]
(flatten (list fixed-asset (map #(- fixed-asset %) accumulated)))))
|
e68f38b50dd35501f8342d0a4e21a9732f9794132752b1f0d57d92412e4eb38c | gcross/LogicGrowsOnTrees | LogicGrowsOnTrees.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# LANGUAGE UnicodeSyntax #
{-| Basic functionality for building and exploring trees. -}
module LogicGrowsOnTrees
(
-- * Tree types
-- $types
Tree
, TreeIO
, TreeT(..)
* Explorable class features
-- $type-classes
, MonadExplorable(..)
, MonadExplorableTrans(..)
-- * Functions
-- $functions
-- ** ...that explore trees
-- $runners
, exploreTree
, exploreTreeT
, exploreTreeTAndIgnoreResults
, exploreTreeUntilFirst
, exploreTreeTUntilFirst
, exploreTreeUntilFound
, exploreTreeTUntilFound
-- ** ...that help building trees
-- $builders
, allFrom
, between
-- ** ...that transform trees
, endowTree
-- * Implementation
-- $implementation
, TreeTInstruction(..)
, TreeInstruction
) where
import Control.Applicative (Alternative(..),Applicative(..))
import Control.Monad (MonadPlus(..),(>=>),liftM,liftM2,msum)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Operational (ProgramT,ProgramViewT(..),singleton,view,viewT)
import Control.Monad.Trans.Class (MonadTrans(..))
import Control.Monad.Trans.List (ListT)
import Control.Monad.Trans.Maybe (MaybeT)
import Data.Foldable (Foldable)
import qualified Data.Foldable as Fold
import Data.Functor.Identity (Identity(..),runIdentity)
import Data.Maybe (isJust)
import Data.Monoid (Monoid(..))
import Data.Semigroup (Semigroup(..))
import Data.Serialize (Serialize(),encode)
--------------------------------------------------------------------------------
------------------------------------- Types ------------------------------------
--------------------------------------------------------------------------------
$ types
The following are the tree types that are accepted by most of the functions in
this package . You do not need to know the details of their definitions unless
you intend to write your own custom routines for running and transforming trees ,
in which case the relevant information is at the bottom of this page in the
Implementation section .
There is one type of pure tree and two types of impure trees . In general , your
tree should nearly always be pure if you are planning to make use of
checkpointing or parallel exploring , as parts of the tree may be explored
multiple times , some parts may not be run at all on a given processor , and
whenever a leaf is hit there will be a jump to a higher node , so if your tree is
impure then the result needs to not depend on how the tree is explored ; an
example of an acceptable use of an inner monad is when you want to memoize a
pure function using a stateful monad .
If you need something like state in your tree , then you should consider
nesting the tree monad in the state monad rather than vice - versa ,
because this will do things like automatically erasing the change in state that
happened between an inner node and a leaf when the tree jumps back up
from the leaf to an inner node , which will usually be what you want .
The following are the tree types that are accepted by most of the functions in
this package. You do not need to know the details of their definitions unless
you intend to write your own custom routines for running and transforming trees,
in which case the relevant information is at the bottom of this page in the
Implementation section.
There is one type of pure tree and two types of impure trees. In general, your
tree should nearly always be pure if you are planning to make use of
checkpointing or parallel exploring, as parts of the tree may be explored
multiple times, some parts may not be run at all on a given processor, and
whenever a leaf is hit there will be a jump to a higher node, so if your tree is
impure then the result needs to not depend on how the tree is explored; an
example of an acceptable use of an inner monad is when you want to memoize a
pure function using a stateful monad.
If you need something like state in your tree, then you should consider
nesting the tree monad in the state monad rather than vice-versa,
because this will do things like automatically erasing the change in state that
happened between an inner node and a leaf when the tree jumps back up
from the leaf to an inner node, which will usually be what you want.
-}
{-| A pure tree, which is what you should normally be using. -}
type Tree = TreeT Identity
{-| A tree running in the I/O monad, which you should only be using for doing
things like reading data from an external file or database that will be
constant for the entire run.
-}
type TreeIO = TreeT IO
{-| A tree run in an arbitrary monad. -}
newtype TreeT m α = TreeT { unwrapTreeT :: ProgramT (TreeTInstruction m) m α }
deriving (Applicative,Functor,Monad,MonadIO)
--------------------------------------------------------------------------------
--------------------------------- Type-classes ---------------------------------
--------------------------------------------------------------------------------
$ type - classes
' 's are instances of ' MonadExplorable ' and ' MonadExplorableTrans ' ,
which are both subclasses of ' MonadPlus ' . The additional functionality offered
by these type - classes is the ability to cache results so that a computation does
not need to be repeated when a node is explored a second time , which can happen
either when resuming from a checkpoint or when a workload has been stolen by
another processor , as the first step is to retrace the path through the tree
that leads to the stolen workload .
These features could have been provided as functions , but there are two reasons
why they were subsumed into type - classes : first , because one might want to
add another layer above the ' Tree ' monad transformers in the monad stack
( as is the case in " LogicGrowsOnTrees . Location " ) , and second , because one might want
to run a tree using a simpler monad such as List for testing purposes .
NOTE : Caching a computation takes space in the ' Checkpoint ' , so it is something
you should only do when the result is relatively small and the
computation is very expensive and is high enough in the search tree that
it is likely to be repeated often . If the calculation is low enough in
the search tree that it is unlikely to be repeated , is cheap enough so
that repeating it is not a big deal , or produces a result with an
incredibly large memory footprint , then you are probably better off not
caching the result .
'Tree's are instances of 'MonadExplorable' and 'MonadExplorableTrans',
which are both subclasses of 'MonadPlus'. The additional functionality offered
by these type-classes is the ability to cache results so that a computation does
not need to be repeated when a node is explored a second time, which can happen
either when resuming from a checkpoint or when a workload has been stolen by
another processor, as the first step is to retrace the path through the tree
that leads to the stolen workload.
These features could have been provided as functions, but there are two reasons
why they were subsumed into type-classes: first, because one might want to
add another layer above the 'Tree' monad transformers in the monad stack
(as is the case in "LogicGrowsOnTrees.Location"), and second, because one might want
to run a tree using a simpler monad such as List for testing purposes.
NOTE: Caching a computation takes space in the 'Checkpoint', so it is something
you should only do when the result is relatively small and the
computation is very expensive and is high enough in the search tree that
it is likely to be repeated often. If the calculation is low enough in
the search tree that it is unlikely to be repeated, is cheap enough so
that repeating it is not a big deal, or produces a result with an
incredibly large memory footprint, then you are probably better off not
caching the result.
-}
| The ' MonadExplorable ' class provides caching functionality when exploring a
tree , as well as a way to give a worker a chance to process any pending
requests ; at minimum ' ' needs to be defined .
tree, as well as a way to give a worker a chance to process any pending
requests; at minimum 'cacheMaybe' needs to be defined.
-}
class MonadPlus m ⇒ MonadExplorable m where
{-| Cache a value in case we explore this node again. -}
cache :: Serialize x ⇒ x → m x
cache = cacheMaybe . Just
{-| This does the same thing as 'guard' but it caches the result. -}
cacheGuard :: Bool → m ()
cacheGuard = cacheMaybe . (\x → if x then Just () else Nothing)
| This function is a combination of the previous two ; it performs a
computation which might fail by returning ' Nothing ' , and if that happens
it then backtracks ; if it passes then the result is cached and returned .
Note that the previous two methods are essentially specializations of
this method .
computation which might fail by returning 'Nothing', and if that happens
it then backtracks; if it passes then the result is cached and returned.
Note that the previous two methods are essentially specializations of
this method.
-}
cacheMaybe :: Serialize x ⇒ Maybe x → m x
{-| This function tells the worker to take a break to process any pending
requests; it does nothing if we are not in a parallel setting.
NOTE: You should normally never need to use this function, as requests
are processed whenever a choice point, a cache point, mzero, or a leaf
in the decision tree has been encountered. However, if you have noticed
that workload steals are taking such a large amount of time that workers
are spending too much time sitting idle while they wait for a workload,
and you can trace this as being due to a computation that takes so much
time that it almost never gives the worker a chance to process requests,
then you can use this method to ensure that requests are given a chance
to be processed.
-}
processPendingRequests :: m ()
processPendingRequests = return ()
{-| This class is like 'MonadExplorable', but it is designed to work with monad
stacks; at minimum 'runAndCacheMaybe' needs to be defined.
-}
class (MonadPlus m, Monad (NestedMonad m)) ⇒ MonadExplorableTrans m where
{-| The next layer down in the monad transformer stack. -}
type NestedMonad m :: * → *
{-| Runs the given action in the nested monad and caches the result. -}
runAndCache :: Serialize x ⇒ (NestedMonad m) x → m x
runAndCache = runAndCacheMaybe . liftM Just
{-| Runs the given action in the nested monad and then does the equivalent
of feeding it into 'guard', caching the result.
-}
runAndCacheGuard :: (NestedMonad m) Bool → m ()
runAndCacheGuard = runAndCacheMaybe . liftM (\x → if x then Just () else Nothing)
{-| Runs the given action in the nested monad; if it returns 'Nothing',
then it acts like 'mzero', if it returns 'Just x', then it caches the
result.
-}
runAndCacheMaybe :: Serialize x ⇒ (NestedMonad m) (Maybe x) → m x
--------------------------------------------------------------------------------
---------------------------------- Instances -----------------------------------
--------------------------------------------------------------------------------
| The ' Alternative ' instance functions just like the ' MonadPlus ' instance .
instance Monad m ⇒ Alternative (TreeT m) where
empty = mzero
(<|>) = mplus
| Two ' 's are equal if they have the same structure .
instance Eq α ⇒ Eq (Tree α) where
(TreeT x) == (TreeT y) = e x y
where
e x y = case (view x, view y) of
(Return x, Return y) → x == y
(Null :>>= _, Null :>>= _) → True
(Cache cx :>>= kx, Cache cy :>>= ky) →
case (runIdentity cx, runIdentity cy) of
(Nothing, Nothing) → True
(Just x, Just y) → e (kx x) (ky y)
_ → False
(Choice (TreeT ax) (TreeT bx) :>>= kx, Choice (TreeT ay) (TreeT by) :>>= ky) →
e (ax >>= kx) (ay >>= ky) && e (bx >>= kx) (by >>= ky)
(ProcessPendingRequests :>>= kx,ProcessPendingRequests :>>= ky) → e (kx ()) (ky ())
_ → False
| For this type , ' mplus ' creates a branch node with a choice between two
subtrees and ' mzero ' signifies failure which results in backtracking up the
tree .
subtrees and 'mzero' signifies failure which results in backtracking up the
tree.
-}
instance Monad m ⇒ MonadPlus (TreeT m) where
mzero = TreeT . singleton $ Null
left `mplus` right = TreeT . singleton $ Choice left right
{-| This instance performs no caching but is provided to make it easier to test
running a tree using the List monad.
-}
instance MonadExplorable [] where
cacheMaybe = maybe mzero return
{-| This instance performs no caching but is provided to make it easier to test
running a tree using the 'ListT' monad.
-}
instance Monad m ⇒ MonadExplorable (ListT m) where
cacheMaybe = maybe mzero return
{-| Like the 'MonadExplorable' instance, this instance does no caching. -}
instance Monad m ⇒ MonadExplorableTrans (ListT m) where
type NestedMonad (ListT m) = m
runAndCacheMaybe = lift >=> maybe mzero return
{-| This instance performs no caching but is provided to make it easier to test
running a tree using the 'Maybe' monad.
-}
instance MonadExplorable Maybe where
cacheMaybe = maybe mzero return
{-| This instance performs no caching but is provided to make it easier to test
running a tree using the 'MaybeT' monad.
-}
instance Monad m ⇒ MonadExplorable (MaybeT m) where
cacheMaybe = maybe mzero return
{-| Like the 'MonadExplorable' instance, this instance does no caching. -}
instance Monad m ⇒ MonadExplorableTrans (MaybeT m) where
type NestedMonad (MaybeT m) = m
runAndCacheMaybe = lift >=> maybe mzero return
instance Monad m ⇒ MonadExplorable (TreeT m) where
cache = runAndCache . return
cacheGuard = runAndCacheGuard . return
cacheMaybe = runAndCacheMaybe . return
processPendingRequests = TreeT . singleton $ ProcessPendingRequests
instance Monad m ⇒ MonadExplorableTrans (TreeT m) where
type NestedMonad (TreeT m) = m
runAndCache = runAndCacheMaybe . liftM Just
runAndCacheGuard = runAndCacheMaybe . liftM (\x → if x then Just () else Nothing)
runAndCacheMaybe = TreeT . singleton . Cache
instance MonadTrans TreeT where
lift = TreeT . lift
| The ' Semigroup ' instance also acts like the ' MonadPlus ' instance .
instance Monad m ⇒ Semigroup (TreeT m α) where
(<>) = mplus
sconcat = msum
| The ' Monoid ' instance also acts like the ' MonadPlus ' instance .
instance Monad m ⇒ Monoid (TreeT m α) where
mempty = mzero
instance Show α ⇒ Show (Tree α) where
show = s . unwrapTreeT
where
s x = case view x of
Return x → show x
Null :>>= _ → "<NULL> >>= (...)"
ProcessPendingRequests :>>= k → "<PPR> >>= " ++ (s . k $ ())
Cache c :>>= k →
case runIdentity c of
Nothing → "NullCache"
Just x → "Cache[" ++ (show . encode $ x) ++ "] >>= " ++ (s (k x))
Choice (TreeT a) (TreeT b) :>>= k → "(" ++ (s (a >>= k)) ++ ") | (" ++ (s (b >>= k)) ++ ")"
--------------------------------------------------------------------------------
---------------------------------- Functions -----------------------------------
--------------------------------------------------------------------------------
$ functions
There are three kinds of functions in this module : functions that explore trees
in various ways , functions that make it easier to build trees , and a function
that changes the base monad of a pure tree .
There are three kinds of functions in this module: functions that explore trees
in various ways, functions that make it easier to build trees, and a function
that changes the base monad of a pure tree.
-}
---------------------------------- Explorers -----------------------------------
$ runners
The following functions all take a tree as input and produce the result of
exploring it as output . There are seven functions because there are two kinds of
trees --- pure and impure --- and three ways of exploring a tree --- exploring
everything and summing all results ( i.e. , in the leaves ) , exploring until the
first result ( i.e. , in a leaf ) is encountered and immediately returning , and
gathering results ( i.e. , from the leaves ) until they satisfy a condition and
then returning --- plus a seventh function that explores a tree only for the
side - effects .
The following functions all take a tree as input and produce the result of
exploring it as output. There are seven functions because there are two kinds of
trees --- pure and impure --- and three ways of exploring a tree --- exploring
everything and summing all results (i.e., in the leaves), exploring until the
first result (i.e., in a leaf) is encountered and immediately returning, and
gathering results (i.e., from the leaves) until they satisfy a condition and
then returning --- plus a seventh function that explores a tree only for the
side-effects.
-}
{-| Explores all the nodes in a pure tree and sums over all the
results in the leaves.
-}
exploreTree ::
Monoid α ⇒
Tree α {-^ the (pure) tree to be explored -} →
α {-^ the sum over all results -}
exploreTree v =
case view (unwrapTreeT v) of
Return !x → x
Cache mx :>>= k → maybe mempty (exploreTree . TreeT . k) (runIdentity mx)
Choice left right :>>= k →
let !x = exploreTree $ left >>= TreeT . k
!y = exploreTree $ right >>= TreeT . k
!xy = mappend x y
in xy
Null :>>= _ → mempty
ProcessPendingRequests :>>= k → exploreTree . TreeT . k $ ()
{-# INLINEABLE exploreTree #-}
{-| Explores all the nodes in an impure tree and sums over all the
results in the leaves.
-}
exploreTreeT ::
(Monad m, Monoid α) ⇒
TreeT m α {-^ the (impure) tree to be explored -} →
m α {-^ the sum over all results -}
exploreTreeT = viewT . unwrapTreeT >=> \view →
case view of
Return !x → return x
Cache mx :>>= k → mx >>= maybe (return mempty) (exploreTreeT . TreeT . k)
Choice left right :>>= k →
liftM2 (\(!x) (!y) → let !xy = mappend x y in xy)
(exploreTreeT $ left >>= TreeT . k)
(exploreTreeT $ right >>= TreeT . k)
Null :>>= _ → return mempty
ProcessPendingRequests :>>= k → exploreTreeT . TreeT . k $ ()
# SPECIALIZE exploreTreeT : : Monoid α ⇒ Tree α → Identity α #
# SPECIALIZE exploreTreeT : : Monoid α ⇒ TreeIO α → IO α #
# INLINEABLE exploreTreeT #
{-| Explores a tree for its side-effects, ignoring all results. -}
exploreTreeTAndIgnoreResults ::
Monad m ⇒
TreeT m α {-^ the (impure) tree to be explored -} →
m ()
exploreTreeTAndIgnoreResults = viewT . unwrapTreeT >=> \view →
case view of
Return _ → return ()
Cache mx :>>= k → mx >>= maybe (return ()) (exploreTreeTAndIgnoreResults . TreeT . k)
Choice left right :>>= k → do
exploreTreeTAndIgnoreResults $ left >>= TreeT . k
exploreTreeTAndIgnoreResults $ right >>= TreeT . k
Null :>>= _ → return ()
ProcessPendingRequests :>>= k → exploreTreeTAndIgnoreResults . TreeT . k $ ()
{-# SPECIALIZE exploreTreeTAndIgnoreResults :: Tree α → Identity () #-}
{-# SPECIALIZE exploreTreeTAndIgnoreResults :: TreeIO α → IO () #-}
# INLINEABLE exploreTreeTAndIgnoreResults #
{-| Explores all the nodes in a tree until a result (i.e., a leaf) has been
found; if a result has been found then it is returned wrapped in 'Just',
otherwise 'Nothing' is returned.
-}
exploreTreeUntilFirst ::
Tree α {-^ the (pure) tree to be explored -} →
^ the first result found , if any
exploreTreeUntilFirst v =
case view (unwrapTreeT v) of
Return x → Just x
Cache mx :>>= k → maybe Nothing (exploreTreeUntilFirst . TreeT . k) (runIdentity mx)
Choice left right :>>= k →
let x = exploreTreeUntilFirst $ left >>= TreeT . k
y = exploreTreeUntilFirst $ right >>= TreeT . k
in if isJust x then x else y
Null :>>= _ → Nothing
ProcessPendingRequests :>>= k → exploreTreeUntilFirst . TreeT . k $ ()
# INLINEABLE exploreTreeUntilFirst #
{-| Same as 'exploreTreeUntilFirst', but taking an impure tree instead
of pure one.
-}
exploreTreeTUntilFirst ::
Monad m ⇒
TreeT m α {-^ the (impure) tree to be explored -} →
^ the first result found , if any
exploreTreeTUntilFirst = viewT . unwrapTreeT >=> \view →
case view of
Return !x → return (Just x)
Cache mx :>>= k → mx >>= maybe (return Nothing) (exploreTreeTUntilFirst . TreeT . k)
Choice left right :>>= k → do
x ← exploreTreeTUntilFirst $ left >>= TreeT . k
if isJust x
then return x
else exploreTreeTUntilFirst $ right >>= TreeT . k
Null :>>= _ → return Nothing
ProcessPendingRequests :>>= k → exploreTreeTUntilFirst . TreeT . k $ ()
# SPECIALIZE exploreTreeTUntilFirst : : Tree α → Identity ( Maybe α ) #
# SPECIALIZE exploreTreeTUntilFirst : : TreeIO α → IO ( Maybe α ) #
# INLINEABLE exploreTreeTUntilFirst #
| Explores all the nodes in a tree , summing all encountered results ( i.e. , in
the leaves ) until the current partial sum satisfies the condition provided
by the first function . The returned value is a pair where the first
component is all of the results that were found during the exploration and
the second component is ' True ' if the exploration terminated early due to
the condition being met and ' False ' otherwise .
NOTE : The condition function is assumed to have two properties : first , it
is assumed to return ' False ' for ' ' , and second , it is assumed
that if it returns ' True ' for @x@ then it also returns ' True ' for
@mappend x y@ and @mappend y x@ for all values @y@. The reason for
this is that the condition function is used to indicate when enough
results have been found , and so it should not be ' True ' for ' '
as nothing has been found and if it is ' True ' for @x@ then it should
not be ' False ' for the sum of @y@ with @x@ as this would mean that
having /more/ than enough results is no longer having enough results .
the leaves) until the current partial sum satisfies the condition provided
by the first function. The returned value is a pair where the first
component is all of the results that were found during the exploration and
the second component is 'True' if the exploration terminated early due to
the condition being met and 'False' otherwise.
NOTE: The condition function is assumed to have two properties: first, it
is assumed to return 'False' for 'mempty', and second, it is assumed
that if it returns 'True' for @x@ then it also returns 'True' for
@mappend x y@ and @mappend y x@ for all values @y@. The reason for
this is that the condition function is used to indicate when enough
results have been found, and so it should not be 'True' for 'mempty'
as nothing has been found and if it is 'True' for @x@ then it should
not be 'False' for the sum of @y@ with @x@ as this would mean that
having /more/ than enough results is no longer having enough results.
-}
exploreTreeUntilFound ::
Monoid α ⇒
(α → Bool) {-^ a function that determines when the desired results have been found -} →
Tree α {-^ the (pure) tree to be explored -} →
(α,Bool) {-^ the result of the exploration, which includes the results that
were found and a flag indicating if they matched the condition
function
-}
exploreTreeUntilFound f v =
case view (unwrapTreeT v) of
Return x → (x,f x)
Cache mx :>>= k →
maybe (mempty,False) (exploreTreeUntilFound f . TreeT . k)
$
runIdentity mx
Choice left right :>>= k →
let x@(xr,xf) = exploreTreeUntilFound f $ left >>= TreeT . k
(yr,yf) = exploreTreeUntilFound f $ right >>= TreeT . k
zr = xr <> yr
in if xf then x else (zr,yf || f zr)
Null :>>= _ → (mempty,False)
ProcessPendingRequests :>>= k → exploreTreeUntilFound f . TreeT . k $ ()
| Same as ' ' , but taking an impure tree instead of
a pure tree .
a pure tree.
-}
exploreTreeTUntilFound ::
(Monad m, Monoid α) ⇒
^ a function that determines when the desired results have been
found ; it is assumed that this function is ' False ' for ' '
found; it is assumed that this function is 'False' for 'mempty'
-} →
TreeT m α {-^ the (impure) tree to be explored -} →
m (α,Bool) {-^ the result of the exploration, which includes the results
that were found and a flag indicating if they matched the
condition function
-}
exploreTreeTUntilFound f = viewT . unwrapTreeT >=> \view →
case view of
Return x → return (x,f x)
Cache mx :>>= k →
mx
>>=
maybe (return (mempty,False)) (exploreTreeTUntilFound f . TreeT . k)
Choice left right :>>= k → do
x@(xr,xf) ← exploreTreeTUntilFound f $ left >>= TreeT . k
if xf
then return x
else do
(yr,yf) ← exploreTreeTUntilFound f $ right >>= TreeT . k
let zr = xr <> yr
return (zr,yf || f zr)
Null :>>= _ → return (mempty,False)
ProcessPendingRequests :>>= k → exploreTreeTUntilFound f . TreeT . k $ ()
---------------------------------- Builders ------------------------------------
{- $builders
The following functions all create a tree from various inputs.
-}
| Returns a tree ( or some other ' MonadPlus ' ) with all of the results in the
input list .
input list.
-}
allFrom ::
(Foldable t, Functor t, MonadPlus m) ⇒
^ the list ( or some other ` Foldable ` ) of results to generate
m α {-^ a tree that generates the given list of results -}
allFrom = Fold.msum . fmap return
# INLINE allFrom #
| Returns an optimally balanced tree ( or some other ' MonadPlus ' ) that
generates all of the elements in the given ( inclusive ) range ; if the lower
bound is greater than the upper bound it returns ' mzero ' .
generates all of the elements in the given (inclusive) range; if the lower
bound is greater than the upper bound it returns 'mzero'.
-}
between ::
(Enum n, MonadPlus m) ⇒
n {-^ the (inclusive) lower bound of the range -} →
n {-^ the (inclusive) upper bound of the range -} →
^ a tree ( or other ' MonadPlus ' ) that generates all the results in the range
between x y =
if a > b
then mzero
else go a b
where
a = fromEnum x
b = fromEnum y
go a b | a == b = return (toEnum a)
go a b | otherwise = go a (a+d) `mplus` go (a+d+1) b
where
d = (b-a) `div` 2
# INLINE between #
-------------------------------- Transformers ----------------------------------
{-| This function lets you take a pure tree and transform it into a
tree with an arbitrary base monad.
-}
endowTree ::
Monad m ⇒
Tree α {-^ the pure tree to transformed into an impure tree -} →
TreeT m α {-^ the resulting impure tree -}
endowTree tree =
case view . unwrapTreeT $ tree of
Return x → return x
Cache mx :>>= k →
cacheMaybe (runIdentity mx) >>= endowTree . TreeT . k
Choice left right :>>= k →
mplus
(endowTree left >>= endowTree . TreeT . k)
(endowTree right >>= endowTree . TreeT . k)
Null :>>= _ → mzero
ProcessPendingRequests :>>= k → endowTree . TreeT . k $ ()
--------------------------------------------------------------------------------
------------------------------- Implementation ---------------------------------
--------------------------------------------------------------------------------
$ implementation
The implementation of the ' Tree ' types uses the approach described in \"The
Operational Monad Tutorial\ " , published in
< / Issue 15 of The Monad . Reader > ;
specifically it uses the @operational@ package . The idea is that a list of
instructions are provided in ' TreeTInstruction ' , and then the operational monad
does all the heavy lifting of turning them into a monad .
The implementation of the 'Tree' types uses the approach described in \"The
Operational Monad Tutorial\", published in
</ Issue 15 of The Monad.Reader>;
specifically it uses the @operational@ package. The idea is that a list of
instructions are provided in 'TreeTInstruction', and then the operational monad
does all the heavy lifting of turning them into a monad.
-}
| The core of the implementation of ' Tree ' is mostly contained in this
type , which provides a list of primitive instructions for trees :
' Cache ' , which caches a value , ' Choice ' , which signals a branch with two
choices , ' Null ' , which indicates that there are no more results , and
' ProcessPendingRequests ' , which signals that a break should be taken from
exploration to process any pending requests ( only meant to be used in
exceptional cases ) .
type, which provides a list of primitive instructions for trees:
'Cache', which caches a value, 'Choice', which signals a branch with two
choices, 'Null', which indicates that there are no more results, and
'ProcessPendingRequests', which signals that a break should be taken from
exploration to process any pending requests (only meant to be used in
exceptional cases).
-}
data TreeTInstruction m α where
Cache :: Serialize α ⇒ m (Maybe α) → TreeTInstruction m α
Choice :: TreeT m α → TreeT m α → TreeTInstruction m α
Null :: TreeTInstruction m α
ProcessPendingRequests :: TreeTInstruction m ()
{-| This is just a convenient alias for working with pure trees. -}
type TreeInstruction = TreeTInstruction Identity
| null | https://raw.githubusercontent.com/gcross/LogicGrowsOnTrees/4befa81eb7152d877a7c78338d21bed61b06db66/LogicGrowsOnTrees/sources/LogicGrowsOnTrees.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE GADTs #
| Basic functionality for building and exploring trees.
* Tree types
$types
$type-classes
* Functions
$functions
** ...that explore trees
$runners
** ...that help building trees
$builders
** ...that transform trees
* Implementation
$implementation
------------------------------------------------------------------------------
----------------------------------- Types ------------------------------------
------------------------------------------------------------------------------
| A pure tree, which is what you should normally be using.
| A tree running in the I/O monad, which you should only be using for doing
things like reading data from an external file or database that will be
constant for the entire run.
| A tree run in an arbitrary monad.
------------------------------------------------------------------------------
------------------------------- Type-classes ---------------------------------
------------------------------------------------------------------------------
| Cache a value in case we explore this node again.
| This does the same thing as 'guard' but it caches the result.
| This function tells the worker to take a break to process any pending
requests; it does nothing if we are not in a parallel setting.
NOTE: You should normally never need to use this function, as requests
are processed whenever a choice point, a cache point, mzero, or a leaf
in the decision tree has been encountered. However, if you have noticed
that workload steals are taking such a large amount of time that workers
are spending too much time sitting idle while they wait for a workload,
and you can trace this as being due to a computation that takes so much
time that it almost never gives the worker a chance to process requests,
then you can use this method to ensure that requests are given a chance
to be processed.
| This class is like 'MonadExplorable', but it is designed to work with monad
stacks; at minimum 'runAndCacheMaybe' needs to be defined.
| The next layer down in the monad transformer stack.
| Runs the given action in the nested monad and caches the result.
| Runs the given action in the nested monad and then does the equivalent
of feeding it into 'guard', caching the result.
| Runs the given action in the nested monad; if it returns 'Nothing',
then it acts like 'mzero', if it returns 'Just x', then it caches the
result.
------------------------------------------------------------------------------
-------------------------------- Instances -----------------------------------
------------------------------------------------------------------------------
| This instance performs no caching but is provided to make it easier to test
running a tree using the List monad.
| This instance performs no caching but is provided to make it easier to test
running a tree using the 'ListT' monad.
| Like the 'MonadExplorable' instance, this instance does no caching.
| This instance performs no caching but is provided to make it easier to test
running a tree using the 'Maybe' monad.
| This instance performs no caching but is provided to make it easier to test
running a tree using the 'MaybeT' monad.
| Like the 'MonadExplorable' instance, this instance does no caching.
------------------------------------------------------------------------------
-------------------------------- Functions -----------------------------------
------------------------------------------------------------------------------
-------------------------------- Explorers -----------------------------------
- pure and impure --- and three ways of exploring a tree --- exploring
- plus a seventh function that explores a tree only for the
- pure and impure --- and three ways of exploring a tree --- exploring
- plus a seventh function that explores a tree only for the
| Explores all the nodes in a pure tree and sums over all the
results in the leaves.
^ the (pure) tree to be explored
^ the sum over all results
# INLINEABLE exploreTree #
| Explores all the nodes in an impure tree and sums over all the
results in the leaves.
^ the (impure) tree to be explored
^ the sum over all results
| Explores a tree for its side-effects, ignoring all results.
^ the (impure) tree to be explored
# SPECIALIZE exploreTreeTAndIgnoreResults :: Tree α → Identity () #
# SPECIALIZE exploreTreeTAndIgnoreResults :: TreeIO α → IO () #
| Explores all the nodes in a tree until a result (i.e., a leaf) has been
found; if a result has been found then it is returned wrapped in 'Just',
otherwise 'Nothing' is returned.
^ the (pure) tree to be explored
| Same as 'exploreTreeUntilFirst', but taking an impure tree instead
of pure one.
^ the (impure) tree to be explored
^ a function that determines when the desired results have been found
^ the (pure) tree to be explored
^ the result of the exploration, which includes the results that
were found and a flag indicating if they matched the condition
function
^ the (impure) tree to be explored
^ the result of the exploration, which includes the results
that were found and a flag indicating if they matched the
condition function
-------------------------------- Builders ------------------------------------
$builders
The following functions all create a tree from various inputs.
^ a tree that generates the given list of results
^ the (inclusive) lower bound of the range
^ the (inclusive) upper bound of the range
------------------------------ Transformers ----------------------------------
| This function lets you take a pure tree and transform it into a
tree with an arbitrary base monad.
^ the pure tree to transformed into an impure tree
^ the resulting impure tree
------------------------------------------------------------------------------
----------------------------- Implementation ---------------------------------
------------------------------------------------------------------------------
| This is just a convenient alias for working with pure trees. | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# LANGUAGE UnicodeSyntax #
module LogicGrowsOnTrees
(
Tree
, TreeIO
, TreeT(..)
* Explorable class features
, MonadExplorable(..)
, MonadExplorableTrans(..)
, exploreTree
, exploreTreeT
, exploreTreeTAndIgnoreResults
, exploreTreeUntilFirst
, exploreTreeTUntilFirst
, exploreTreeUntilFound
, exploreTreeTUntilFound
, allFrom
, between
, endowTree
, TreeTInstruction(..)
, TreeInstruction
) where
import Control.Applicative (Alternative(..),Applicative(..))
import Control.Monad (MonadPlus(..),(>=>),liftM,liftM2,msum)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Operational (ProgramT,ProgramViewT(..),singleton,view,viewT)
import Control.Monad.Trans.Class (MonadTrans(..))
import Control.Monad.Trans.List (ListT)
import Control.Monad.Trans.Maybe (MaybeT)
import Data.Foldable (Foldable)
import qualified Data.Foldable as Fold
import Data.Functor.Identity (Identity(..),runIdentity)
import Data.Maybe (isJust)
import Data.Monoid (Monoid(..))
import Data.Semigroup (Semigroup(..))
import Data.Serialize (Serialize(),encode)
$ types
The following are the tree types that are accepted by most of the functions in
this package . You do not need to know the details of their definitions unless
you intend to write your own custom routines for running and transforming trees ,
in which case the relevant information is at the bottom of this page in the
Implementation section .
There is one type of pure tree and two types of impure trees . In general , your
tree should nearly always be pure if you are planning to make use of
checkpointing or parallel exploring , as parts of the tree may be explored
multiple times , some parts may not be run at all on a given processor , and
whenever a leaf is hit there will be a jump to a higher node , so if your tree is
impure then the result needs to not depend on how the tree is explored ; an
example of an acceptable use of an inner monad is when you want to memoize a
pure function using a stateful monad .
If you need something like state in your tree , then you should consider
nesting the tree monad in the state monad rather than vice - versa ,
because this will do things like automatically erasing the change in state that
happened between an inner node and a leaf when the tree jumps back up
from the leaf to an inner node , which will usually be what you want .
The following are the tree types that are accepted by most of the functions in
this package. You do not need to know the details of their definitions unless
you intend to write your own custom routines for running and transforming trees,
in which case the relevant information is at the bottom of this page in the
Implementation section.
There is one type of pure tree and two types of impure trees. In general, your
tree should nearly always be pure if you are planning to make use of
checkpointing or parallel exploring, as parts of the tree may be explored
multiple times, some parts may not be run at all on a given processor, and
whenever a leaf is hit there will be a jump to a higher node, so if your tree is
impure then the result needs to not depend on how the tree is explored; an
example of an acceptable use of an inner monad is when you want to memoize a
pure function using a stateful monad.
If you need something like state in your tree, then you should consider
nesting the tree monad in the state monad rather than vice-versa,
because this will do things like automatically erasing the change in state that
happened between an inner node and a leaf when the tree jumps back up
from the leaf to an inner node, which will usually be what you want.
-}
type Tree = TreeT Identity
type TreeIO = TreeT IO
newtype TreeT m α = TreeT { unwrapTreeT :: ProgramT (TreeTInstruction m) m α }
deriving (Applicative,Functor,Monad,MonadIO)
$ type - classes
' 's are instances of ' MonadExplorable ' and ' MonadExplorableTrans ' ,
which are both subclasses of ' MonadPlus ' . The additional functionality offered
by these type - classes is the ability to cache results so that a computation does
not need to be repeated when a node is explored a second time , which can happen
either when resuming from a checkpoint or when a workload has been stolen by
another processor , as the first step is to retrace the path through the tree
that leads to the stolen workload .
These features could have been provided as functions , but there are two reasons
why they were subsumed into type - classes : first , because one might want to
add another layer above the ' Tree ' monad transformers in the monad stack
( as is the case in " LogicGrowsOnTrees . Location " ) , and second , because one might want
to run a tree using a simpler monad such as List for testing purposes .
NOTE : Caching a computation takes space in the ' Checkpoint ' , so it is something
you should only do when the result is relatively small and the
computation is very expensive and is high enough in the search tree that
it is likely to be repeated often . If the calculation is low enough in
the search tree that it is unlikely to be repeated , is cheap enough so
that repeating it is not a big deal , or produces a result with an
incredibly large memory footprint , then you are probably better off not
caching the result .
'Tree's are instances of 'MonadExplorable' and 'MonadExplorableTrans',
which are both subclasses of 'MonadPlus'. The additional functionality offered
by these type-classes is the ability to cache results so that a computation does
not need to be repeated when a node is explored a second time, which can happen
either when resuming from a checkpoint or when a workload has been stolen by
another processor, as the first step is to retrace the path through the tree
that leads to the stolen workload.
These features could have been provided as functions, but there are two reasons
why they were subsumed into type-classes: first, because one might want to
add another layer above the 'Tree' monad transformers in the monad stack
(as is the case in "LogicGrowsOnTrees.Location"), and second, because one might want
to run a tree using a simpler monad such as List for testing purposes.
NOTE: Caching a computation takes space in the 'Checkpoint', so it is something
you should only do when the result is relatively small and the
computation is very expensive and is high enough in the search tree that
it is likely to be repeated often. If the calculation is low enough in
the search tree that it is unlikely to be repeated, is cheap enough so
that repeating it is not a big deal, or produces a result with an
incredibly large memory footprint, then you are probably better off not
caching the result.
-}
| The ' MonadExplorable ' class provides caching functionality when exploring a
tree , as well as a way to give a worker a chance to process any pending
requests ; at minimum ' ' needs to be defined .
tree, as well as a way to give a worker a chance to process any pending
requests; at minimum 'cacheMaybe' needs to be defined.
-}
class MonadPlus m ⇒ MonadExplorable m where
cache :: Serialize x ⇒ x → m x
cache = cacheMaybe . Just
cacheGuard :: Bool → m ()
cacheGuard = cacheMaybe . (\x → if x then Just () else Nothing)
| This function is a combination of the previous two ; it performs a
computation which might fail by returning ' Nothing ' , and if that happens
it then backtracks ; if it passes then the result is cached and returned .
Note that the previous two methods are essentially specializations of
this method .
computation which might fail by returning 'Nothing', and if that happens
it then backtracks; if it passes then the result is cached and returned.
Note that the previous two methods are essentially specializations of
this method.
-}
cacheMaybe :: Serialize x ⇒ Maybe x → m x
processPendingRequests :: m ()
processPendingRequests = return ()
class (MonadPlus m, Monad (NestedMonad m)) ⇒ MonadExplorableTrans m where
type NestedMonad m :: * → *
runAndCache :: Serialize x ⇒ (NestedMonad m) x → m x
runAndCache = runAndCacheMaybe . liftM Just
runAndCacheGuard :: (NestedMonad m) Bool → m ()
runAndCacheGuard = runAndCacheMaybe . liftM (\x → if x then Just () else Nothing)
runAndCacheMaybe :: Serialize x ⇒ (NestedMonad m) (Maybe x) → m x
| The ' Alternative ' instance functions just like the ' MonadPlus ' instance .
instance Monad m ⇒ Alternative (TreeT m) where
empty = mzero
(<|>) = mplus
| Two ' 's are equal if they have the same structure .
instance Eq α ⇒ Eq (Tree α) where
(TreeT x) == (TreeT y) = e x y
where
e x y = case (view x, view y) of
(Return x, Return y) → x == y
(Null :>>= _, Null :>>= _) → True
(Cache cx :>>= kx, Cache cy :>>= ky) →
case (runIdentity cx, runIdentity cy) of
(Nothing, Nothing) → True
(Just x, Just y) → e (kx x) (ky y)
_ → False
(Choice (TreeT ax) (TreeT bx) :>>= kx, Choice (TreeT ay) (TreeT by) :>>= ky) →
e (ax >>= kx) (ay >>= ky) && e (bx >>= kx) (by >>= ky)
(ProcessPendingRequests :>>= kx,ProcessPendingRequests :>>= ky) → e (kx ()) (ky ())
_ → False
| For this type , ' mplus ' creates a branch node with a choice between two
subtrees and ' mzero ' signifies failure which results in backtracking up the
tree .
subtrees and 'mzero' signifies failure which results in backtracking up the
tree.
-}
instance Monad m ⇒ MonadPlus (TreeT m) where
mzero = TreeT . singleton $ Null
left `mplus` right = TreeT . singleton $ Choice left right
instance MonadExplorable [] where
cacheMaybe = maybe mzero return
instance Monad m ⇒ MonadExplorable (ListT m) where
cacheMaybe = maybe mzero return
instance Monad m ⇒ MonadExplorableTrans (ListT m) where
type NestedMonad (ListT m) = m
runAndCacheMaybe = lift >=> maybe mzero return
instance MonadExplorable Maybe where
cacheMaybe = maybe mzero return
instance Monad m ⇒ MonadExplorable (MaybeT m) where
cacheMaybe = maybe mzero return
instance Monad m ⇒ MonadExplorableTrans (MaybeT m) where
type NestedMonad (MaybeT m) = m
runAndCacheMaybe = lift >=> maybe mzero return
instance Monad m ⇒ MonadExplorable (TreeT m) where
cache = runAndCache . return
cacheGuard = runAndCacheGuard . return
cacheMaybe = runAndCacheMaybe . return
processPendingRequests = TreeT . singleton $ ProcessPendingRequests
instance Monad m ⇒ MonadExplorableTrans (TreeT m) where
type NestedMonad (TreeT m) = m
runAndCache = runAndCacheMaybe . liftM Just
runAndCacheGuard = runAndCacheMaybe . liftM (\x → if x then Just () else Nothing)
runAndCacheMaybe = TreeT . singleton . Cache
instance MonadTrans TreeT where
lift = TreeT . lift
| The ' Semigroup ' instance also acts like the ' MonadPlus ' instance .
instance Monad m ⇒ Semigroup (TreeT m α) where
(<>) = mplus
sconcat = msum
| The ' Monoid ' instance also acts like the ' MonadPlus ' instance .
instance Monad m ⇒ Monoid (TreeT m α) where
mempty = mzero
instance Show α ⇒ Show (Tree α) where
show = s . unwrapTreeT
where
s x = case view x of
Return x → show x
Null :>>= _ → "<NULL> >>= (...)"
ProcessPendingRequests :>>= k → "<PPR> >>= " ++ (s . k $ ())
Cache c :>>= k →
case runIdentity c of
Nothing → "NullCache"
Just x → "Cache[" ++ (show . encode $ x) ++ "] >>= " ++ (s (k x))
Choice (TreeT a) (TreeT b) :>>= k → "(" ++ (s (a >>= k)) ++ ") | (" ++ (s (b >>= k)) ++ ")"
$ functions
There are three kinds of functions in this module : functions that explore trees
in various ways , functions that make it easier to build trees , and a function
that changes the base monad of a pure tree .
There are three kinds of functions in this module: functions that explore trees
in various ways, functions that make it easier to build trees, and a function
that changes the base monad of a pure tree.
-}
$ runners
The following functions all take a tree as input and produce the result of
exploring it as output . There are seven functions because there are two kinds of
everything and summing all results ( i.e. , in the leaves ) , exploring until the
first result ( i.e. , in a leaf ) is encountered and immediately returning , and
gathering results ( i.e. , from the leaves ) until they satisfy a condition and
side - effects .
The following functions all take a tree as input and produce the result of
exploring it as output. There are seven functions because there are two kinds of
everything and summing all results (i.e., in the leaves), exploring until the
first result (i.e., in a leaf) is encountered and immediately returning, and
gathering results (i.e., from the leaves) until they satisfy a condition and
side-effects.
-}
exploreTree ::
Monoid α ⇒
exploreTree v =
case view (unwrapTreeT v) of
Return !x → x
Cache mx :>>= k → maybe mempty (exploreTree . TreeT . k) (runIdentity mx)
Choice left right :>>= k →
let !x = exploreTree $ left >>= TreeT . k
!y = exploreTree $ right >>= TreeT . k
!xy = mappend x y
in xy
Null :>>= _ → mempty
ProcessPendingRequests :>>= k → exploreTree . TreeT . k $ ()
exploreTreeT ::
(Monad m, Monoid α) ⇒
exploreTreeT = viewT . unwrapTreeT >=> \view →
case view of
Return !x → return x
Cache mx :>>= k → mx >>= maybe (return mempty) (exploreTreeT . TreeT . k)
Choice left right :>>= k →
liftM2 (\(!x) (!y) → let !xy = mappend x y in xy)
(exploreTreeT $ left >>= TreeT . k)
(exploreTreeT $ right >>= TreeT . k)
Null :>>= _ → return mempty
ProcessPendingRequests :>>= k → exploreTreeT . TreeT . k $ ()
# SPECIALIZE exploreTreeT : : Monoid α ⇒ Tree α → Identity α #
# SPECIALIZE exploreTreeT : : Monoid α ⇒ TreeIO α → IO α #
# INLINEABLE exploreTreeT #
exploreTreeTAndIgnoreResults ::
Monad m ⇒
m ()
exploreTreeTAndIgnoreResults = viewT . unwrapTreeT >=> \view →
case view of
Return _ → return ()
Cache mx :>>= k → mx >>= maybe (return ()) (exploreTreeTAndIgnoreResults . TreeT . k)
Choice left right :>>= k → do
exploreTreeTAndIgnoreResults $ left >>= TreeT . k
exploreTreeTAndIgnoreResults $ right >>= TreeT . k
Null :>>= _ → return ()
ProcessPendingRequests :>>= k → exploreTreeTAndIgnoreResults . TreeT . k $ ()
# INLINEABLE exploreTreeTAndIgnoreResults #
exploreTreeUntilFirst ::
^ the first result found , if any
exploreTreeUntilFirst v =
case view (unwrapTreeT v) of
Return x → Just x
Cache mx :>>= k → maybe Nothing (exploreTreeUntilFirst . TreeT . k) (runIdentity mx)
Choice left right :>>= k →
let x = exploreTreeUntilFirst $ left >>= TreeT . k
y = exploreTreeUntilFirst $ right >>= TreeT . k
in if isJust x then x else y
Null :>>= _ → Nothing
ProcessPendingRequests :>>= k → exploreTreeUntilFirst . TreeT . k $ ()
# INLINEABLE exploreTreeUntilFirst #
exploreTreeTUntilFirst ::
Monad m ⇒
^ the first result found , if any
exploreTreeTUntilFirst = viewT . unwrapTreeT >=> \view →
case view of
Return !x → return (Just x)
Cache mx :>>= k → mx >>= maybe (return Nothing) (exploreTreeTUntilFirst . TreeT . k)
Choice left right :>>= k → do
x ← exploreTreeTUntilFirst $ left >>= TreeT . k
if isJust x
then return x
else exploreTreeTUntilFirst $ right >>= TreeT . k
Null :>>= _ → return Nothing
ProcessPendingRequests :>>= k → exploreTreeTUntilFirst . TreeT . k $ ()
# SPECIALIZE exploreTreeTUntilFirst : : Tree α → Identity ( Maybe α ) #
# SPECIALIZE exploreTreeTUntilFirst : : TreeIO α → IO ( Maybe α ) #
# INLINEABLE exploreTreeTUntilFirst #
| Explores all the nodes in a tree , summing all encountered results ( i.e. , in
the leaves ) until the current partial sum satisfies the condition provided
by the first function . The returned value is a pair where the first
component is all of the results that were found during the exploration and
the second component is ' True ' if the exploration terminated early due to
the condition being met and ' False ' otherwise .
NOTE : The condition function is assumed to have two properties : first , it
is assumed to return ' False ' for ' ' , and second , it is assumed
that if it returns ' True ' for @x@ then it also returns ' True ' for
@mappend x y@ and @mappend y x@ for all values @y@. The reason for
this is that the condition function is used to indicate when enough
results have been found , and so it should not be ' True ' for ' '
as nothing has been found and if it is ' True ' for @x@ then it should
not be ' False ' for the sum of @y@ with @x@ as this would mean that
having /more/ than enough results is no longer having enough results .
the leaves) until the current partial sum satisfies the condition provided
by the first function. The returned value is a pair where the first
component is all of the results that were found during the exploration and
the second component is 'True' if the exploration terminated early due to
the condition being met and 'False' otherwise.
NOTE: The condition function is assumed to have two properties: first, it
is assumed to return 'False' for 'mempty', and second, it is assumed
that if it returns 'True' for @x@ then it also returns 'True' for
@mappend x y@ and @mappend y x@ for all values @y@. The reason for
this is that the condition function is used to indicate when enough
results have been found, and so it should not be 'True' for 'mempty'
as nothing has been found and if it is 'True' for @x@ then it should
not be 'False' for the sum of @y@ with @x@ as this would mean that
having /more/ than enough results is no longer having enough results.
-}
exploreTreeUntilFound ::
Monoid α ⇒
exploreTreeUntilFound f v =
case view (unwrapTreeT v) of
Return x → (x,f x)
Cache mx :>>= k →
maybe (mempty,False) (exploreTreeUntilFound f . TreeT . k)
$
runIdentity mx
Choice left right :>>= k →
let x@(xr,xf) = exploreTreeUntilFound f $ left >>= TreeT . k
(yr,yf) = exploreTreeUntilFound f $ right >>= TreeT . k
zr = xr <> yr
in if xf then x else (zr,yf || f zr)
Null :>>= _ → (mempty,False)
ProcessPendingRequests :>>= k → exploreTreeUntilFound f . TreeT . k $ ()
| Same as ' ' , but taking an impure tree instead of
a pure tree .
a pure tree.
-}
exploreTreeTUntilFound ::
(Monad m, Monoid α) ⇒
^ a function that determines when the desired results have been
found ; it is assumed that this function is ' False ' for ' '
found; it is assumed that this function is 'False' for 'mempty'
-} →
exploreTreeTUntilFound f = viewT . unwrapTreeT >=> \view →
case view of
Return x → return (x,f x)
Cache mx :>>= k →
mx
>>=
maybe (return (mempty,False)) (exploreTreeTUntilFound f . TreeT . k)
Choice left right :>>= k → do
x@(xr,xf) ← exploreTreeTUntilFound f $ left >>= TreeT . k
if xf
then return x
else do
(yr,yf) ← exploreTreeTUntilFound f $ right >>= TreeT . k
let zr = xr <> yr
return (zr,yf || f zr)
Null :>>= _ → return (mempty,False)
ProcessPendingRequests :>>= k → exploreTreeTUntilFound f . TreeT . k $ ()
| Returns a tree ( or some other ' MonadPlus ' ) with all of the results in the
input list .
input list.
-}
allFrom ::
(Foldable t, Functor t, MonadPlus m) ⇒
^ the list ( or some other ` Foldable ` ) of results to generate
allFrom = Fold.msum . fmap return
# INLINE allFrom #
| Returns an optimally balanced tree ( or some other ' MonadPlus ' ) that
generates all of the elements in the given ( inclusive ) range ; if the lower
bound is greater than the upper bound it returns ' mzero ' .
generates all of the elements in the given (inclusive) range; if the lower
bound is greater than the upper bound it returns 'mzero'.
-}
between ::
(Enum n, MonadPlus m) ⇒
^ a tree ( or other ' MonadPlus ' ) that generates all the results in the range
between x y =
if a > b
then mzero
else go a b
where
a = fromEnum x
b = fromEnum y
go a b | a == b = return (toEnum a)
go a b | otherwise = go a (a+d) `mplus` go (a+d+1) b
where
d = (b-a) `div` 2
# INLINE between #
endowTree ::
Monad m ⇒
endowTree tree =
case view . unwrapTreeT $ tree of
Return x → return x
Cache mx :>>= k →
cacheMaybe (runIdentity mx) >>= endowTree . TreeT . k
Choice left right :>>= k →
mplus
(endowTree left >>= endowTree . TreeT . k)
(endowTree right >>= endowTree . TreeT . k)
Null :>>= _ → mzero
ProcessPendingRequests :>>= k → endowTree . TreeT . k $ ()
$ implementation
The implementation of the ' Tree ' types uses the approach described in \"The
Operational Monad Tutorial\ " , published in
< / Issue 15 of The Monad . Reader > ;
specifically it uses the @operational@ package . The idea is that a list of
instructions are provided in ' TreeTInstruction ' , and then the operational monad
does all the heavy lifting of turning them into a monad .
The implementation of the 'Tree' types uses the approach described in \"The
Operational Monad Tutorial\", published in
</ Issue 15 of The Monad.Reader>;
specifically it uses the @operational@ package. The idea is that a list of
instructions are provided in 'TreeTInstruction', and then the operational monad
does all the heavy lifting of turning them into a monad.
-}
| The core of the implementation of ' Tree ' is mostly contained in this
type , which provides a list of primitive instructions for trees :
' Cache ' , which caches a value , ' Choice ' , which signals a branch with two
choices , ' Null ' , which indicates that there are no more results , and
' ProcessPendingRequests ' , which signals that a break should be taken from
exploration to process any pending requests ( only meant to be used in
exceptional cases ) .
type, which provides a list of primitive instructions for trees:
'Cache', which caches a value, 'Choice', which signals a branch with two
choices, 'Null', which indicates that there are no more results, and
'ProcessPendingRequests', which signals that a break should be taken from
exploration to process any pending requests (only meant to be used in
exceptional cases).
-}
data TreeTInstruction m α where
Cache :: Serialize α ⇒ m (Maybe α) → TreeTInstruction m α
Choice :: TreeT m α → TreeT m α → TreeTInstruction m α
Null :: TreeTInstruction m α
ProcessPendingRequests :: TreeTInstruction m ()
type TreeInstruction = TreeTInstruction Identity
|
8521532de318cfe3db748d2f08a589cc31c928758557f91c29933e0a249ca3a4 | facebook/duckling | Rules.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Volume.RO.Rules
( rules
) where
import Data.String
import Data.Text (Text)
import Prelude
import Duckling.Dimensions.Types
import Duckling.Types
import Duckling.Regex.Types
import Duckling.Volume.Helpers
import Duckling.Numeral.Helpers (isPositive)
import qualified Duckling.Volume.Types as TVolume
import qualified Duckling.Numeral.Types as TNumeral
volumes :: [(Text, String, TVolume.Unit)]
volumes = [ ("<latent vol> ml" , "(de )?m(ililitr[ui]|l)" , TVolume.Millilitre)
, ("<vol> hectoliters" , "(de )?hectolitr[ui]" , TVolume.Hectolitre)
, ("<vol> liters" , "(de )?l(itr[ui])?" , TVolume.Litre)
, ("<latent vol> gallon", "(de )?gal(oane|on)?" , TVolume.Gallon)
]
rulesVolumes :: [Rule]
rulesVolumes = map go volumes
where
go :: (Text, String, TVolume.Unit) -> Rule
go (name, regexPattern, u) = Rule
{ name = name
, pattern =
[ regex regexPattern
]
, prod = \_ -> Just . Token Volume $ unitOnly u
}
fractions :: [(Text, String, Double)]
fractions = [ ("half", "jum(a|ă)tate", 1/2)
]
rulesFractionalVolume :: [Rule]
rulesFractionalVolume = map go fractions
where
go :: (Text, String, Double) -> Rule
go (name, regexPattern, f) = Rule
{ name = name
, pattern =
[ regex regexPattern
, Predicate isUnitOnly
]
, prod = \case
(_:
Token Volume TVolume.VolumeData{TVolume.unit = Just u}:
_) ->
Just . Token Volume $ volume u f
_ -> Nothing
}
rules :: [Rule]
rules =
[
]
++ rulesVolumes
++ rulesFractionalVolume
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Volume/RO/Rules.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings # | Copyright ( c ) 2016 - present , Facebook , Inc.
# LANGUAGE LambdaCase #
module Duckling.Volume.RO.Rules
( rules
) where
import Data.String
import Data.Text (Text)
import Prelude
import Duckling.Dimensions.Types
import Duckling.Types
import Duckling.Regex.Types
import Duckling.Volume.Helpers
import Duckling.Numeral.Helpers (isPositive)
import qualified Duckling.Volume.Types as TVolume
import qualified Duckling.Numeral.Types as TNumeral
volumes :: [(Text, String, TVolume.Unit)]
volumes = [ ("<latent vol> ml" , "(de )?m(ililitr[ui]|l)" , TVolume.Millilitre)
, ("<vol> hectoliters" , "(de )?hectolitr[ui]" , TVolume.Hectolitre)
, ("<vol> liters" , "(de )?l(itr[ui])?" , TVolume.Litre)
, ("<latent vol> gallon", "(de )?gal(oane|on)?" , TVolume.Gallon)
]
rulesVolumes :: [Rule]
rulesVolumes = map go volumes
where
go :: (Text, String, TVolume.Unit) -> Rule
go (name, regexPattern, u) = Rule
{ name = name
, pattern =
[ regex regexPattern
]
, prod = \_ -> Just . Token Volume $ unitOnly u
}
fractions :: [(Text, String, Double)]
fractions = [ ("half", "jum(a|ă)tate", 1/2)
]
rulesFractionalVolume :: [Rule]
rulesFractionalVolume = map go fractions
where
go :: (Text, String, Double) -> Rule
go (name, regexPattern, f) = Rule
{ name = name
, pattern =
[ regex regexPattern
, Predicate isUnitOnly
]
, prod = \case
(_:
Token Volume TVolume.VolumeData{TVolume.unit = Just u}:
_) ->
Just . Token Volume $ volume u f
_ -> Nothing
}
rules :: [Rule]
rules =
[
]
++ rulesVolumes
++ rulesFractionalVolume
|
a60528ac3e984f11122b1bd1297eee174e2f54059fecdc0abc82a3b64c7de102 | shayne-fletcher/zen | curves_sig.mli | (** Curves.curve interface *)
module type S = sig
* { 2 Curve operations }
(** The curve type *)
type curve =
{
curve_dates : CalendarLib.Date.t list ;
curve_abscissae : float list ;
curve_ordinates : float list ;
curve_interpolation : float list -> float list -> float -> float
}
(** Make a string of curve *)
val string_of_curve : curve -> string
(** Append the implied discount factor to the curve *)
val append_deposit : curve -> Deals.cash -> curve
(** Append the implied discount factor to the curve *)
val append_vanilla_swap : curve -> Deals.vanilla_swap -> curve
* { 2 Curve querying }
(** Extract the base date from a curve *)
val base_date : curve -> CalendarLib.Date.t
(** Query the curve for a response *)
val evaluate : curve -> float -> float
end
| null | https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/curve/curves_sig.mli | ocaml | * Curves.curve interface
* The curve type
* Make a string of curve
* Append the implied discount factor to the curve
* Append the implied discount factor to the curve
* Extract the base date from a curve
* Query the curve for a response | module type S = sig
* { 2 Curve operations }
type curve =
{
curve_dates : CalendarLib.Date.t list ;
curve_abscissae : float list ;
curve_ordinates : float list ;
curve_interpolation : float list -> float list -> float -> float
}
val string_of_curve : curve -> string
val append_deposit : curve -> Deals.cash -> curve
val append_vanilla_swap : curve -> Deals.vanilla_swap -> curve
* { 2 Curve querying }
val base_date : curve -> CalendarLib.Date.t
val evaluate : curve -> float -> float
end
|
f62ddb428af5da083f1a2a98f409994d0a8622540a5a788d8364933e58a1d7db | rtrusso/scp | hw3.scm | (define get-number
(let ((number 3))
(lambda ()
(set! number (+ 1 number))
number)))
(display (get-number))
(newline)
(display (get-number))
(newline)
(display (get-number))
(newline)
| null | https://raw.githubusercontent.com/rtrusso/scp/2051e76df14bd36aef81aba519ffafa62b260f5c/src/tests/hw3.scm | scheme | (define get-number
(let ((number 3))
(lambda ()
(set! number (+ 1 number))
number)))
(display (get-number))
(newline)
(display (get-number))
(newline)
(display (get-number))
(newline)
| |
b8b51d0cc2e2de4e56b51ad6143864aaba942e4a867f906d76626b8b77f1d788 | weyrick/roadsend-php | gtk-static.scm | ;; ***** BEGIN LICENSE BLOCK *****
Roadsend PHP Compiler Runtime Libraries
Copyright ( C ) 2007 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 php-gtk-static-lib
; (include "../phpoo-extension.sch")
(load (php-macros "../../../php-macros.scm"))
(load (php-gtk-macros "php-gtk-macros.sch"))
; (library "common")
( library " bgtk " )
(import
(gtk-binding "cigloo/gtk.scm")
(gtk-signals "cigloo/signals.scm"))
(library php-runtime)
(import (php-gtk-common-lib "php-gtk-common.scm"))
; (import (gtk-foreign-types "gtk-foreign-types.scm"))
(export
(init-php-gtk-static-lib)
)
)
(define (init-php-gtk-static-lib)
1)
;;
GTK static methods
;; ==================
(defclass (Gtk pcc-gtk))
(def-static-method Gtk (quit_add main-level function #!optional data)
(let* ((main-level (mkfixnum main-level))
(function (mkstr function))
(callback (if data
(lambda () (php-funcall function data))
(lambda () (php-funcall function)))))
(convert-to-integer (gtk-quit-add main-level callback))))
(def-static-method Gtk (idle_add function #!optional (data #f))
(let* ((function (mkstr function))
(callback (if data
(lambda () (php-funcall function data))
(lambda () (php-funcall function)))))
(convert-to-integer (gtk-idle-add callback))))
(def-static-method Gtk (timeout_add interval function #!optional (data #f))
(let* ((interval (mkfixnum interval))
(function (mkstr function))
(callback (if data
(lambda () (php-funcall function data))
(lambda () (php-funcall function)))))
;; XXX note, php-gtk uses gtk_timeout_add_full with php_gtk_destroy_notify as the last argument
(convert-to-integer (gtk-timeout-add interval callback))))
(def-static-methods Gtk gtk
( ( gtk_accelerator_valid : return - type gboolean : c - name gtk_accelerator_valid ) ( keyval : gtk - type guint ) ( modifiers : gtk - type GdkModifierType ) )
( ( gtk_accelerator_parse : c - name ) ( accelerator : gtk - type const - gchar * ) ( accelerator_key : gtk - type guint * ) ( accelerator_mods : gtk - type GdkModifierType * ) )
( ( gtk_accelerator_name : return - type gchar * : c - name gtk_accelerator_name ) ( accelerator_key : gtk - type guint ) ( accelerator_mods : gtk - type GdkModifierType ) )
; ((gtk_accelerator_set_default_mod_mask :c-name gtk_accelerator_set_default_mod_mask) (default_mod_mask :gtk-type GdkModifierType))
( ( gtk_accelerator_get_default_mod_mask : return - type guint : c - name gtk_accelerator_get_default_mod_mask ) )
((accel_group_get_default :return-type GtkAccelGroup*))
( ( gtk_accel_groups_activate : return - type gboolean : c - name gtk_accel_groups_activate ) ( object : gtk - type GtkObject * ) ( accel_key : gtk - type guint ) ( accel_mods : gtk - type GdkModifierType ) )
( ( gtk_accel_group_handle_add : c - name gtk_accel_group_handle_add ) ( object : gtk - type GtkObject * ) ( accel_signal_id : gtk - type guint ) ( accel_group : gtk - type GtkAccelGroup * ) ( accel_key : gtk - type guint ) ( accel_mods : gtk - type GdkModifierType ) ( accel_flags : gtk - type GtkAccelFlags ) )
( ( gtk_accel_group_handle_remove : c - name gtk_accel_group_handle_remove ) ( object : gtk - type GtkObject * ) ( accel_group : gtk - type GtkAccelGroup * ) ( accel_key : gtk - type guint ) ( accel_mods : gtk - type GdkModifierType ) )
( ( gtk_accel_group_create_add : return - type guint : c - name gtk_accel_group_create_add ) ( class_type : gtk - type GtkType ) ( signal_flags : gtk - type GtkSignalRunType ) ( handler_offset : gtk - type guint ) )
( ( gtk_accel_group_create_remove : return - type guint : c - name gtk_accel_group_create_remove ) ( class_type : gtk - type GtkType ) ( signal_flags : gtk - type GtkSignalRunType ) ( handler_offset : gtk - type guint ) )
( ( gtk_accel_groups_from_object : return - type * : c - name gtk_accel_groups_from_object ) ( object : gtk - type GtkObject * ) )
( ( gtk_accel_group_entries_from_object : return - type * : c - name ) ( object : gtk - type GtkObject * ) )
(button_box_get_child_size_default (min_width :gtk-type gint*) (min_height :gtk-type gint*))
(button_box_get_child_ipadding_default (ipad_x :gtk-type gint*) (ipad_y :gtk-type gint*))
(button_box_set_child_size_default (min_width :gtk-type gint) (min_height :gtk-type gint))
(button_box_set_child_ipadding_default (ipad_x :gtk-type gint) (ipad_y :gtk-type gint))
((gtk_button_box_child_requisition :c-name gtk_button_box_child_requisition) (widget :gtk-type GtkWidget*) (nvis_children :gtk-type int*) (width :gtk-type int*) (height :gtk-type int*))
; ((gtk_container_get_toplevels :return-type GList* :c-name gtk_container_get_toplevels))
( ( gtk_container_add_child_arg_type : c - name gtk_container_add_child_arg_type ) ( arg_name : gtk - type const - gchar * ) ( arg_type : gtk - type GtkType ) ( arg_flags : gtk - type guint ) ( arg_id : gtk - type guint ) )
( ( : return - type GtkArg * : c - name ) ( class_type : gtk - type GtkType ) ( arg_flags : gtk - type * * ) ( nargs : gtk - type guint * ) )
( ( gtk_container_child_args_collect : return - type gchar * : c - name gtk_container_child_args_collect ) ( object_type : gtk - type GtkType ) ( arg_list_p : gtk - type * * ) ( info_list_p : gtk - type * * ) ( first_arg_name : gtk - type const - gchar * ) ( args : gtk - type va_list ) )
( ( : return - type gchar * : c - name ) ( object_type : gtk - type GtkType ) ( arg_name : gtk - type const - gchar * ) ( info_p : gtk - type GtkArgInfo * * ) )
((gtk_drag_finish :c-name gtk_drag_finish) (context :gtk-type GdkDragContext*) (success :gtk-type gboolean) (del :gtk-type gboolean) (time :gtk-type guint32))
((gtk_drag_get_source_widget :return-type GtkWidget* :c-name gtk_drag_get_source_widget) (context :gtk-type GdkDragContext*))
((gtk_drag_set_icon_widget :c-name gtk_drag_set_icon_widget) (context :gtk-type GdkDragContext*) (widget :gtk-type GtkWidget*) (hot_x :gtk-type gint) (hot_y :gtk-type gint))
((gtk_drag_set_icon_pixmap :c-name gtk_drag_set_icon_pixmap) (context :gtk-type GdkDragContext*) (colormap :gtk-type GdkColormap*) (pixmap :gtk-type GdkPixmap*) (mask :gtk-type GdkBitmap*) (hot_x :gtk-type gint) (hot_y :gtk-type gint))
((gtk_drag_set_icon_default :c-name gtk_drag_set_icon_default) (context :gtk-type GdkDragContext*))
((gtk_drag_set_default_icon :c-name gtk_drag_set_default_icon) (colormap :gtk-type GdkColormap*) (pixmap :gtk-type GdkPixmap*) (mask :gtk-type GdkBitmap*) (hot_x :gtk-type gint) (hot_y :gtk-type gint))
( ( gtk_drag_source_handle_event : c - name gtk_drag_source_handle_event ) ( widget : gtk - type GtkWidget * ) ( event : gtk - type GdkEvent * ) )
( ( gtk_drag_dest_handle_event : c - name gtk_drag_dest_handle_event ) ( toplevel : gtk - type GtkWidget * ) ( event : gtk - type GdkEvent * ) )
((hbutton_box_get_spacing_default :return-type gint))
((hbutton_box_get_layout_default :return-type GtkButtonBoxStyle))
(hbutton_box_set_spacing_default (spacing :gtk-type gint))
(hbutton_box_set_layout_default (layout :gtk-type GtkButtonBoxStyle))
((gtk_item_factory_parse_rc :c-name gtk_item_factory_parse_rc) (file_name :gtk-type const-gchar*))
((gtk_item_factory_parse_rc_string :c-name gtk_item_factory_parse_rc_string) (rc_string :gtk-type const-gchar*))
((gtk_item_factory_parse_rc_scanner :c-name gtk_item_factory_parse_rc_scanner) (scanner :gtk-type GScanner*))
((gtk_item_factory_add_foreign :c-name gtk_item_factory_add_foreign) (accel_widget :gtk-type GtkWidget*) (full_path :gtk-type const-gchar*) (accel_group :gtk-type GtkAccelGroup*) (keyval :gtk-type guint) (modifiers :gtk-type GdkModifierType))
((gtk_item_factory_from_widget :return-type GtkItemFactory* :c-name gtk_item_factory_from_widget) (widget :gtk-type GtkWidget*))
((gtk_item_factory_path_from_widget :return-type gchar* :c-name gtk_item_factory_path_from_widget) (widget :gtk-type GtkWidget*))
((gtk_item_factory_dump_items :c-name gtk_item_factory_dump_items) (path_pspec :gtk-type GtkPatternSpec*) (modified_only :gtk-type gboolean) (print_func :gtk-type GtkPrintFunc) (func_data :gtk-type gpointer))
((gtk_item_factory_dump_rc :c-name gtk_item_factory_dump_rc) (file_name :gtk-type const-gchar*) (path_pspec :gtk-type GtkPatternSpec*) (modified_only :gtk-type gboolean))
((gtk_item_factory_print_func :c-name gtk_item_factory_print_func) (FILE_pointer :gtk-type gpointer) (string :gtk-type gchar*))
((gtk_item_factory_popup_data_from_widget :return-type gpointer :c-name gtk_item_factory_popup_data_from_widget) (widget :gtk-type GtkWidget*))
((gtk_item_factory_from_path :return-type GtkItemFactory* :c-name gtk_item_factory_from_path) (path :gtk-type const-gchar*))
((gtk_item_factory_create_menu_entries :c-name gtk_item_factory_create_menu_entries) (n_entries :gtk-type guint) (entries :gtk-type GtkMenuEntry*))
((gtk_item_factories_path_delete :c-name gtk_item_factories_path_delete) (ifactory_path :gtk-type const-gchar*) (path :gtk-type const-gchar*))
((check_version :return-type gchar*) (required_major :gtk-type guint) (required_minor :gtk-type guint) (required_micro :gtk-type guint))
( init ( : gtk - type int * ) ( argv : gtk - type char * * * ) )
( ( init_check : return - type gboolean ) ( : gtk - type int * ) ( argv : gtk - type char * * * ) )
; (exit (error_code :gtk-type gint))
; ((set_locale :return-type gchar*))
((events_pending :return-type gint))
(main_do_event (event :gtk-type GdkEvent*))
(main)
((main_level :return-type guint))
(main_quit)
((main_iteration :return-type gint))
((main_iteration_do :return-type gint) (blocking :gtk-type gboolean :default TRUE))
( ( gtk_true : return - type gint : c - name ) )
; ((gtk_false :return-type gint :c-name gtk_false))
(grab_add (widget :gtk-type GtkWidget*))
((grab_get_current :return-type GtkWidget*))
(grab_remove (widget :gtk-type GtkWidget*))
( init_add ( function : gtk - type GtkFunction ) ( data : gtk - type gpointer ) )
(quit_add_destroy (main_level :gtk-type guint) (object :gtk-type GtkObject*))
( ( quit_add : return - type guint ) ( main_level : gtk - type guint ) ( function : gtk - type GtkFunction ) ( data : gtk - type gpointer ) )
( ( quit_add_full : return - type guint ) ( main_level : gtk - type guint ) ( function : gtk - type GtkFunction ) ( marshal : gtk - type GtkCallbackMarshal ) ( data : gtk - type gpointer ) ( destroy : gtk - type GtkDestroyNotify ) )
(quit_remove (quit_handler_id :gtk-type guint))
; (quit_remove_by_data (data :gtk-type gpointer))
( ( timeout_add : return - type guint ) ( interval : gtk - type ) ( function : gtk - type GtkFunction ) ( data : gtk - type gpointer ) )
( ( timeout_add_full : return - type guint ) ( interval : gtk - type ) ( function : gtk - type GtkFunction ) ( marshal : gtk - type GtkCallbackMarshal ) ( data : gtk - type gpointer ) ( destroy : gtk - type GtkDestroyNotify ) )
(timeout_remove (timeout_handler_id :gtk-type guint))
( ( idle_add : return - type guint ) ( function : gtk - type GtkFunction ) ( data : gtk - type gpointer ) )
( ( idle_add_priority : return - type guint ) ( priority : gtk - type gint ) ( function : gtk - type GtkFunction ) ( data : gtk - type gpointer ) )
( ( idle_add_full : return - type guint ) ( priority : gtk - type gint ) ( function : gtk - type GtkFunction ) ( marshal : gtk - type GtkCallbackMarshal ) ( data : gtk - type gpointer ) ( destroy : gtk - type GtkDestroyNotify ) )
(idle_remove (idle_handler_id :gtk-type guint))
; (idle_remove_by_data (data :gtk-type gpointer))
((input_add :return-type guint :c-name gtk_input_add_full) (source :gtk-type gint) (condition :gtk-type GdkInputCondition) (function :gtk-type GdkInputFunction) (marshal :gtk-type GtkCallbackMarshal) (data :gtk-type gpointer) (destroy :gtk-type GtkDestroyNotify))
(input_remove (input_handler_id :gtk-type guint))
( ( key_snooper_install : return - type guint ) ( snooper : gtk - type GtkKeySnoopFunc ) ( func_data : gtk - type gpointer ) )
( key_snooper_remove ( snooper_handler_id : gtk - type guint ) )
( ( get_current_event : return - type GdkEvent * ) )
( ( get_event_widget : return - type GtkWidget * ) ( event : gtk - type GdkEvent * ) )
( propagate_event ( widget : gtk - type GtkWidget * ) ( event : gtk - type GdkEvent * ) )
( ( gtk_object_query_args : return - type GtkArg * : c - name gtk_object_query_args ) ( class_type : gtk - type GtkType ) ( arg_flags : gtk - type * * ) ( n_args : gtk - type guint * ) )
( ( gtk_object_add_arg_type : c - name gtk_object_add_arg_type ) ( arg_name : gtk - type const - gchar * ) ( arg_type : gtk - type GtkType ) ( arg_flags : gtk - type guint ) ( arg_id : gtk - type guint ) )
( ( : return - type gchar * : c - name ) ( object_type : gtk - type GtkType ) ( arg_list_p : gtk - type * * ) ( info_list_p : gtk - type * * ) ( first_arg_name : gtk - type const - gchar * ) ( var_args : gtk - type va_list ) )
( ( gtk_object_arg_get_info : return - type gchar * : c - name gtk_object_arg_get_info ) ( object_type : gtk - type GtkType ) ( arg_name : gtk - type const - gchar * ) ( info_p : gtk - type GtkArgInfo * * ) )
( ( gtk_trace_referencing : c - name gtk_trace_referencing ) ( object : gtk - type GtkObject * ) ( func : gtk - type const - gchar * ) ( dummy : gtk - type guint ) ( line : gtk - type guint ) ( do_ref : gtk - type gboolean ) )
; ((gtk_preview_uninit :c-name gtk_preview_uninit))
(preview_set_gamma (gamma :gtk-type double))
(preview_set_color_cube (nred_shades :gtk-type guint) (ngreen_shades :gtk-type guint) (nblue_shades :gtk-type guint) (ngray_shades :gtk-type guint))
(preview_set_install_cmap (install_cmap :gtk-type gint))
(preview_set_reserved (nreserved :gtk-type gint))
((preview_get_visual :return-type GdkVisual*))
((preview_get_cmap :return-type GdkColormap*))
((preview_get_info :return-type GtkPreviewInfo*))
(preview_reset)
(rc_add_default_file (filename :gtk-type const-gchar*))
(rc_set_default_files (filenames :gtk-type gchar**))
((rc_get_default_files :return-type gchar**))
(rc_parse (filename :gtk-type const-gchar*))
(rc_parse_string (rc_string :gtk-type const-gchar*))
((rc_reparse_all :return-type gboolean))
((rc_get_style :return-type GtkStyle*) (widget :gtk-type GtkWidget*))
(rc_add_widget_name_style (rc_style :gtk-type GtkRcStyle*) (pattern :gtk-type const-gchar*))
(rc_add_widget_class_style (rc_style :gtk-type GtkRcStyle*) (pattern :gtk-type const-gchar*))
(rc_add_class_style (rc_style :gtk-type GtkRcStyle*) (pattern :gtk-type const-gchar*))
(rc_set_image_loader (loader :gtk-type GtkImageLoader))
((rc_load_image :return-type GdkPixmap*) (colormap :gtk-type GdkColormap*) (transparent_color :gtk-type GdkColor*) (filename :gtk-type const-gchar*))
((rc_find_pixmap_in_path :return-type gchar*) (scanner :gtk-type GScanner*) (pixmap_file :gtk-type const-gchar*))
((rc_find_module_in_path :return-type gchar*) (module_file :gtk-type const-gchar*))
((rc_get_theme_dir :return-type gchar*))
((rc_get_module_dir :return-type gchar*))
((rc_parse_color :return-type guint) (scanner :gtk-type GScanner*) (color :gtk-type GdkColor*))
((rc_parse_state :return-type guint) (scanner :gtk-type GScanner*) (state :gtk-type GtkStateType*))
((rc_parse_priority :return-type guint) (scanner :gtk-type GScanner*) (priority :gtk-type GtkPathPriorityType*))
( ( gtk_selection_incr_event : return - type gint : c - name gtk_selection_incr_event ) ( window : gtk - type GdkWindow * ) ( event : gtk - type GdkEventProperty * ) )
((gtk_signal_lookup :return-type guint :c-name gtk_signal_lookup) (name :gtk-type const-gchar*) (object_type :gtk-type GtkType))
((gtk_signal_name :return-type gchar* :c-name gtk_signal_name) (signal_id :gtk-type guint))
( ( gtk_signal_n_emissions : return - type guint : c - name gtk_signal_n_emissions ) ( object : gtk - type GtkObject * ) ( signal_id : gtk - type guint ) )
( ( gtk_signal_n_emissions_by_name : return - type guint : c - name gtk_signal_n_emissions_by_name ) ( object : gtk - type GtkObject * ) ( name : gtk - type const - gchar * ) )
( ( gtk_signal_connect_full : return - type guint : c - name gtk_signal_connect_full ) ( object : gtk - type GtkObject * ) ( name : gtk - type const - gchar * ) ( func : gtk - type GtkSignalFunc ) ( marshal : gtk - type GtkCallbackMarshal ) ( data : gtk - type gpointer ) ( destroy_func : gtk - type GtkDestroyNotify ) ( object_signal : gtk - type gint ) ( after : gtk - type gint ) )
( ( gtk_signal_connect_object_while_alive : c - name gtk_signal_connect_object_while_alive ) ( object : gtk - type GtkObject * ) ( signal : gtk - type const - gchar * ) ( func : gtk - type GtkSignalFunc ) ( alive_object : gtk - type GtkObject * ) )
( ( gtk_signal_connect_while_alive : c - name gtk_signal_connect_while_alive ) ( object : gtk - type GtkObject * ) ( signal : gtk - type const - gchar * ) ( func : gtk - type GtkSignalFunc ) ( func_data : gtk - type gpointer ) ( alive_object : gtk - type GtkObject * ) )
( ( gtk_signal_disconnect_by_func : c - name gtk_signal_disconnect_by_func ) ( object : gtk - type GtkObject * ) ( func : gtk - type GtkSignalFunc ) ( data : gtk - type gpointer ) )
( ( gtk_signal_disconnect_by_data : c - name gtk_signal_disconnect_by_data ) ( object : gtk - type GtkObject * ) ( data : gtk - type gpointer ) )
( ( gtk_signal_handler_block_by_func : c - name gtk_signal_handler_block_by_func ) ( object : gtk - type GtkObject * ) ( func : gtk - type GtkSignalFunc ) ( data : gtk - type gpointer ) )
( ( gtk_signal_handler_block_by_data : c - name gtk_signal_handler_block_by_data ) ( object : gtk - type GtkObject * ) ( data : gtk - type gpointer ) )
( ( gtk_signal_handler_unblock_by_func : c - name gtk_signal_handler_unblock_by_func ) ( object : gtk - type GtkObject * ) ( func : gtk - type GtkSignalFunc ) ( data : gtk - type gpointer ) )
( ( gtk_signal_handler_unblock_by_data : c - name gtk_signal_handler_unblock_by_data ) ( object : gtk - type GtkObject * ) ( data : gtk - type gpointer ) )
( ( gtk_signal_handler_pending_by_func : return - type guint : c - name gtk_signal_handler_pending_by_func ) ( object : gtk - type GtkObject * ) ( signal_id : gtk - type guint ) ( may_be_blocked : gtk - type gboolean ) ( func : gtk - type GtkSignalFunc ) ( data : gtk - type gpointer ) )
( ( gtk_signal_add_emission_hook : return - type guint : c - name gtk_signal_add_emission_hook ) ( signal_id : gtk - type guint ) ( hook_func : gtk - type GtkEmissionHook ) ( data : gtk - type gpointer ) )
((gtk_signal_add_emission_hook_full :return-type guint :c-name gtk_signal_add_emission_hook_full) (signal_id :gtk-type guint) (hook_func :gtk-type GtkEmissionHook) (data :gtk-type gpointer) (destroy :gtk-type GDestroyNotify))
((gtk_signal_remove_emission_hook :c-name gtk_signal_remove_emission_hook) (signal_id :gtk-type guint) (hook_id :gtk-type guint))
( ( gtk_signal_query : return - type GtkSignalQuery * : c - name gtk_signal_query ) ( signal_id : gtk - type guint ) )
( ( gtk_signal_emit_by_name : c - name gtk_signal_emit_by_name ) ( object : gtk - type GtkObject * ) ( name : gtk - type const - gchar * ) )
( ( gtk_signal_emitv : c - name gtk_signal_emitv ) ( object : gtk - type GtkObject * ) ( signal_id : gtk - type guint ) ( params : gtk - type GtkArg * ) )
( ( gtk_signal_emitv_by_name : c - name gtk_signal_emitv_by_name ) ( object : gtk - type GtkObject * ) ( name : gtk - type const - gchar * ) ( params : gtk - type GtkArg * ) )
( ( gtk_signal_set_funcs : c - name gtk_signal_set_funcs ) ( marshal_func : gtk - type GtkSignalMarshal ) ( destroy_func : gtk - type ) )
((gtk_draw_hline :c-name gtk_draw_hline) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (x1 :gtk-type gint) (x2 :gtk-type gint) (y :gtk-type gint))
((gtk_draw_vline :c-name gtk_draw_vline) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (y1 :gtk-type gint) (y2 :gtk-type gint) (x :gtk-type gint))
((gtk_draw_shadow :c-name gtk_draw_shadow) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_draw_polygon :c-name gtk_draw_polygon) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (points :gtk-type GdkPoint*) (npoints :gtk-type gint) (fill :gtk-type gboolean))
((gtk_draw_arrow :c-name gtk_draw_arrow) (style :gtk-type GtkStyle*) (window :gtk-type GdkDrawable*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (arrow_type :gtk-type GtkArrowType) (fill :gtk-type gboolean) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_draw_diamond :c-name gtk_draw_diamond) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_draw_oval :c-name gtk_draw_oval) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_draw_string :c-name gtk_draw_string) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (x :gtk-type gint) (y :gtk-type gint) (string :gtk-type const-gchar*))
((gtk_draw_box :c-name gtk_draw_box) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
( ( gtk_draw_flat_box : c - name gtk_draw_flat_box ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) )
( ( : c - name ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) )
( ( gtk_draw_option : c - name gtk_draw_option ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) )
( ( gtk_draw_cross : c - name ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) )
( ( gtk_draw_ramp : c - name gtk_draw_ramp ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( arrow_type : gtk - type GtkArrowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) )
( ( gtk_draw_tab : c - name gtk_draw_tab ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) )
( ( gtk_draw_shadow_gap : c - name ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) ( gap_side : gtk - type GtkPositionType ) ( gap_x : gtk - type gint ) ( gap_width : gtk - type gint ) )
( ( gtk_draw_box_gap : c - name gtk_draw_box_gap ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) ( gap_side : gtk - type GtkPositionType ) ( gap_x : gtk - type gint ) ( gap_width : gtk - type gint ) )
( ( gtk_draw_extension : c - name gtk_draw_extension ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) ( gap_side : gtk - type GtkPositionType ) )
( ( gtk_draw_focus : c - name gtk_draw_focus ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) )
( ( gtk_draw_slider : c - name gtk_draw_slider ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) ( orientation : gtk - type GtkOrientation ) )
( ( gtk_draw_handle : c - name gtk_draw_handle ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) ( orientation : gtk - type GtkOrientation ) )
((gtk_paint_hline :c-name gtk_paint_hline) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x1 :gtk-type gint) (x2 :gtk-type gint) (y :gtk-type gint))
((gtk_paint_vline :c-name gtk_paint_vline) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (y1 :gtk-type gint) (y2 :gtk-type gint) (x :gtk-type gint))
((gtk_paint_shadow :c-name gtk_paint_shadow) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_polygon :c-name gtk_paint_polygon) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (points :gtk-type GdkPoint*) (npoints :gtk-type gint) (fill :gtk-type gboolean))
((gtk_paint_arrow :c-name gtk_paint_arrow) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (arrow_type :gtk-type GtkArrowType) (fill :gtk-type gboolean) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_diamond :c-name gtk_paint_diamond) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_oval :c-name gtk_paint_oval) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_string :c-name gtk_paint_string) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (string :gtk-type const-gchar*))
((gtk_paint_box :c-name gtk_paint_box) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_flat_box :c-name gtk_paint_flat_box) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_check :c-name gtk_paint_check) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_option :c-name gtk_paint_option) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_cross :c-name gtk_paint_cross) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_ramp :c-name gtk_paint_ramp) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (arrow_type :gtk-type GtkArrowType) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_tab :c-name gtk_paint_tab) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_shadow_gap :c-name gtk_paint_shadow_gap) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint) (gap_side :gtk-type GtkPositionType) (gap_x :gtk-type gint) (gap_width :gtk-type gint))
((gtk_paint_box_gap :c-name gtk_paint_box_gap) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint) (gap_side :gtk-type GtkPositionType) (gap_x :gtk-type gint) (gap_width :gtk-type gint))
((gtk_paint_extension :c-name gtk_paint_extension) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint) (gap_side :gtk-type GtkPositionType))
((gtk_paint_focus :c-name gtk_paint_focus) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_slider :c-name gtk_paint_slider) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint) (orientation :gtk-type GtkOrientation))
((gtk_paint_handle :c-name gtk_paint_handle) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint) (orientation :gtk-type GtkOrientation))
( ( gtk_tooltips_data_get : return - type GtkTooltipsData * : c - name gtk_tooltips_data_get ) ( widget : gtk - type GtkWidget * ) )
((gtk_type_name :return-type gchar* :c-name gtk_type_name) (type :gtk-type guint))
((gtk_type_from_name :return-type GtkType :c-name gtk_type_from_name) (name :gtk-type const-gchar*))
( ( gtk_type_check_object_cast : return - type GtkTypeObject * : c - name gtk_type_check_object_cast ) ( type_object : gtk - type GtkTypeObject * ) ( cast_type : gtk - type GtkType ) )
( ( gtk_type_check_class_cast : return - type GtkTypeClass * : c - name gtk_type_check_class_cast ) ( klass : gtk - type GtkTypeClass * ) ( cast_type : gtk - type GtkType ) )
( ( : return - type GtkType : c - name ) ( type_name : gtk - type const - gchar * ) ( values : gtk - type GtkEnumValue * ) )
( ( gtk_type_register_flags : return - type GtkType : c - name ) ( type_name : gtk - type const - gchar * ) ( values : gtk - type GtkFlagValue * ) )
((vbutton_box_get_spacing_default :return-type gint))
(vbutton_box_set_spacing_default (spacing :gtk-type gint))
((vbutton_box_get_layout_default :return-type GtkButtonBoxStyle))
(vbutton_box_set_layout_default (layout :gtk-type GtkButtonBoxStyle))
(widget_push_style (style :gtk-type GtkStyle*))
(widget_push_colormap (cmap :gtk-type GdkColormap*))
(widget_push_visual (visual :gtk-type GdkVisual*))
(widget_push_composite_child)
(widget_pop_composite_child)
(widget_pop_style)
(widget_pop_colormap)
(widget_pop_visual)
(widget_set_default_style (style :gtk-type GtkStyle*))
(widget_set_default_colormap (colormap :gtk-type GdkColormap*))
(widget_set_default_visual (visual :gtk-type GdkVisual*))
((widget_get_default_style :return-type GtkStyle*))
((widget_get_default_colormap :return-type GdkColormap*))
((widget_get_default_visual :return-type GdkVisual*))
)
;;; casts
we ca n't use any of the foreign types defined in bgtk in our
export clauses , or else this would be in php-gtk-common.scm
(define (php-hash->string*::string* ar)
(string-list->string*
(map mkstr (php-hash->list (maybe-unbox ar)))))
(define (string*->php-hash ar)
(list->php-hash
(string*->string-list (maybe-unbox ar))))
| null | https://raw.githubusercontent.com/weyrick/roadsend-php/d6301a897b1a02d7a85bdb915bea91d0991eb158/runtime/ext/gtk/gtk-static.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 *****
(include "../phpoo-extension.sch")
(library "common")
(import (gtk-foreign-types "gtk-foreign-types.scm"))
==================
XXX note, php-gtk uses gtk_timeout_add_full with php_gtk_destroy_notify as the last argument
((gtk_accelerator_set_default_mod_mask :c-name gtk_accelerator_set_default_mod_mask) (default_mod_mask :gtk-type GdkModifierType))
((gtk_container_get_toplevels :return-type GList* :c-name gtk_container_get_toplevels))
(exit (error_code :gtk-type gint))
((set_locale :return-type gchar*))
((gtk_false :return-type gint :c-name gtk_false))
(quit_remove_by_data (data :gtk-type gpointer))
(idle_remove_by_data (data :gtk-type gpointer))
((gtk_preview_uninit :c-name gtk_preview_uninit))
casts | Roadsend PHP Compiler Runtime Libraries
Copyright ( C ) 2007 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 php-gtk-static-lib
(load (php-macros "../../../php-macros.scm"))
(load (php-gtk-macros "php-gtk-macros.sch"))
( library " bgtk " )
(import
(gtk-binding "cigloo/gtk.scm")
(gtk-signals "cigloo/signals.scm"))
(library php-runtime)
(import (php-gtk-common-lib "php-gtk-common.scm"))
(export
(init-php-gtk-static-lib)
)
)
(define (init-php-gtk-static-lib)
1)
GTK static methods
(defclass (Gtk pcc-gtk))
(def-static-method Gtk (quit_add main-level function #!optional data)
(let* ((main-level (mkfixnum main-level))
(function (mkstr function))
(callback (if data
(lambda () (php-funcall function data))
(lambda () (php-funcall function)))))
(convert-to-integer (gtk-quit-add main-level callback))))
(def-static-method Gtk (idle_add function #!optional (data #f))
(let* ((function (mkstr function))
(callback (if data
(lambda () (php-funcall function data))
(lambda () (php-funcall function)))))
(convert-to-integer (gtk-idle-add callback))))
(def-static-method Gtk (timeout_add interval function #!optional (data #f))
(let* ((interval (mkfixnum interval))
(function (mkstr function))
(callback (if data
(lambda () (php-funcall function data))
(lambda () (php-funcall function)))))
(convert-to-integer (gtk-timeout-add interval callback))))
(def-static-methods Gtk gtk
( ( gtk_accelerator_valid : return - type gboolean : c - name gtk_accelerator_valid ) ( keyval : gtk - type guint ) ( modifiers : gtk - type GdkModifierType ) )
( ( gtk_accelerator_parse : c - name ) ( accelerator : gtk - type const - gchar * ) ( accelerator_key : gtk - type guint * ) ( accelerator_mods : gtk - type GdkModifierType * ) )
( ( gtk_accelerator_name : return - type gchar * : c - name gtk_accelerator_name ) ( accelerator_key : gtk - type guint ) ( accelerator_mods : gtk - type GdkModifierType ) )
( ( gtk_accelerator_get_default_mod_mask : return - type guint : c - name gtk_accelerator_get_default_mod_mask ) )
((accel_group_get_default :return-type GtkAccelGroup*))
( ( gtk_accel_groups_activate : return - type gboolean : c - name gtk_accel_groups_activate ) ( object : gtk - type GtkObject * ) ( accel_key : gtk - type guint ) ( accel_mods : gtk - type GdkModifierType ) )
( ( gtk_accel_group_handle_add : c - name gtk_accel_group_handle_add ) ( object : gtk - type GtkObject * ) ( accel_signal_id : gtk - type guint ) ( accel_group : gtk - type GtkAccelGroup * ) ( accel_key : gtk - type guint ) ( accel_mods : gtk - type GdkModifierType ) ( accel_flags : gtk - type GtkAccelFlags ) )
( ( gtk_accel_group_handle_remove : c - name gtk_accel_group_handle_remove ) ( object : gtk - type GtkObject * ) ( accel_group : gtk - type GtkAccelGroup * ) ( accel_key : gtk - type guint ) ( accel_mods : gtk - type GdkModifierType ) )
( ( gtk_accel_group_create_add : return - type guint : c - name gtk_accel_group_create_add ) ( class_type : gtk - type GtkType ) ( signal_flags : gtk - type GtkSignalRunType ) ( handler_offset : gtk - type guint ) )
( ( gtk_accel_group_create_remove : return - type guint : c - name gtk_accel_group_create_remove ) ( class_type : gtk - type GtkType ) ( signal_flags : gtk - type GtkSignalRunType ) ( handler_offset : gtk - type guint ) )
( ( gtk_accel_groups_from_object : return - type * : c - name gtk_accel_groups_from_object ) ( object : gtk - type GtkObject * ) )
( ( gtk_accel_group_entries_from_object : return - type * : c - name ) ( object : gtk - type GtkObject * ) )
(button_box_get_child_size_default (min_width :gtk-type gint*) (min_height :gtk-type gint*))
(button_box_get_child_ipadding_default (ipad_x :gtk-type gint*) (ipad_y :gtk-type gint*))
(button_box_set_child_size_default (min_width :gtk-type gint) (min_height :gtk-type gint))
(button_box_set_child_ipadding_default (ipad_x :gtk-type gint) (ipad_y :gtk-type gint))
((gtk_button_box_child_requisition :c-name gtk_button_box_child_requisition) (widget :gtk-type GtkWidget*) (nvis_children :gtk-type int*) (width :gtk-type int*) (height :gtk-type int*))
( ( gtk_container_add_child_arg_type : c - name gtk_container_add_child_arg_type ) ( arg_name : gtk - type const - gchar * ) ( arg_type : gtk - type GtkType ) ( arg_flags : gtk - type guint ) ( arg_id : gtk - type guint ) )
( ( : return - type GtkArg * : c - name ) ( class_type : gtk - type GtkType ) ( arg_flags : gtk - type * * ) ( nargs : gtk - type guint * ) )
( ( gtk_container_child_args_collect : return - type gchar * : c - name gtk_container_child_args_collect ) ( object_type : gtk - type GtkType ) ( arg_list_p : gtk - type * * ) ( info_list_p : gtk - type * * ) ( first_arg_name : gtk - type const - gchar * ) ( args : gtk - type va_list ) )
( ( : return - type gchar * : c - name ) ( object_type : gtk - type GtkType ) ( arg_name : gtk - type const - gchar * ) ( info_p : gtk - type GtkArgInfo * * ) )
((gtk_drag_finish :c-name gtk_drag_finish) (context :gtk-type GdkDragContext*) (success :gtk-type gboolean) (del :gtk-type gboolean) (time :gtk-type guint32))
((gtk_drag_get_source_widget :return-type GtkWidget* :c-name gtk_drag_get_source_widget) (context :gtk-type GdkDragContext*))
((gtk_drag_set_icon_widget :c-name gtk_drag_set_icon_widget) (context :gtk-type GdkDragContext*) (widget :gtk-type GtkWidget*) (hot_x :gtk-type gint) (hot_y :gtk-type gint))
((gtk_drag_set_icon_pixmap :c-name gtk_drag_set_icon_pixmap) (context :gtk-type GdkDragContext*) (colormap :gtk-type GdkColormap*) (pixmap :gtk-type GdkPixmap*) (mask :gtk-type GdkBitmap*) (hot_x :gtk-type gint) (hot_y :gtk-type gint))
((gtk_drag_set_icon_default :c-name gtk_drag_set_icon_default) (context :gtk-type GdkDragContext*))
((gtk_drag_set_default_icon :c-name gtk_drag_set_default_icon) (colormap :gtk-type GdkColormap*) (pixmap :gtk-type GdkPixmap*) (mask :gtk-type GdkBitmap*) (hot_x :gtk-type gint) (hot_y :gtk-type gint))
( ( gtk_drag_source_handle_event : c - name gtk_drag_source_handle_event ) ( widget : gtk - type GtkWidget * ) ( event : gtk - type GdkEvent * ) )
( ( gtk_drag_dest_handle_event : c - name gtk_drag_dest_handle_event ) ( toplevel : gtk - type GtkWidget * ) ( event : gtk - type GdkEvent * ) )
((hbutton_box_get_spacing_default :return-type gint))
((hbutton_box_get_layout_default :return-type GtkButtonBoxStyle))
(hbutton_box_set_spacing_default (spacing :gtk-type gint))
(hbutton_box_set_layout_default (layout :gtk-type GtkButtonBoxStyle))
((gtk_item_factory_parse_rc :c-name gtk_item_factory_parse_rc) (file_name :gtk-type const-gchar*))
((gtk_item_factory_parse_rc_string :c-name gtk_item_factory_parse_rc_string) (rc_string :gtk-type const-gchar*))
((gtk_item_factory_parse_rc_scanner :c-name gtk_item_factory_parse_rc_scanner) (scanner :gtk-type GScanner*))
((gtk_item_factory_add_foreign :c-name gtk_item_factory_add_foreign) (accel_widget :gtk-type GtkWidget*) (full_path :gtk-type const-gchar*) (accel_group :gtk-type GtkAccelGroup*) (keyval :gtk-type guint) (modifiers :gtk-type GdkModifierType))
((gtk_item_factory_from_widget :return-type GtkItemFactory* :c-name gtk_item_factory_from_widget) (widget :gtk-type GtkWidget*))
((gtk_item_factory_path_from_widget :return-type gchar* :c-name gtk_item_factory_path_from_widget) (widget :gtk-type GtkWidget*))
((gtk_item_factory_dump_items :c-name gtk_item_factory_dump_items) (path_pspec :gtk-type GtkPatternSpec*) (modified_only :gtk-type gboolean) (print_func :gtk-type GtkPrintFunc) (func_data :gtk-type gpointer))
((gtk_item_factory_dump_rc :c-name gtk_item_factory_dump_rc) (file_name :gtk-type const-gchar*) (path_pspec :gtk-type GtkPatternSpec*) (modified_only :gtk-type gboolean))
((gtk_item_factory_print_func :c-name gtk_item_factory_print_func) (FILE_pointer :gtk-type gpointer) (string :gtk-type gchar*))
((gtk_item_factory_popup_data_from_widget :return-type gpointer :c-name gtk_item_factory_popup_data_from_widget) (widget :gtk-type GtkWidget*))
((gtk_item_factory_from_path :return-type GtkItemFactory* :c-name gtk_item_factory_from_path) (path :gtk-type const-gchar*))
((gtk_item_factory_create_menu_entries :c-name gtk_item_factory_create_menu_entries) (n_entries :gtk-type guint) (entries :gtk-type GtkMenuEntry*))
((gtk_item_factories_path_delete :c-name gtk_item_factories_path_delete) (ifactory_path :gtk-type const-gchar*) (path :gtk-type const-gchar*))
((check_version :return-type gchar*) (required_major :gtk-type guint) (required_minor :gtk-type guint) (required_micro :gtk-type guint))
( init ( : gtk - type int * ) ( argv : gtk - type char * * * ) )
( ( init_check : return - type gboolean ) ( : gtk - type int * ) ( argv : gtk - type char * * * ) )
((events_pending :return-type gint))
(main_do_event (event :gtk-type GdkEvent*))
(main)
((main_level :return-type guint))
(main_quit)
((main_iteration :return-type gint))
((main_iteration_do :return-type gint) (blocking :gtk-type gboolean :default TRUE))
( ( gtk_true : return - type gint : c - name ) )
(grab_add (widget :gtk-type GtkWidget*))
((grab_get_current :return-type GtkWidget*))
(grab_remove (widget :gtk-type GtkWidget*))
( init_add ( function : gtk - type GtkFunction ) ( data : gtk - type gpointer ) )
(quit_add_destroy (main_level :gtk-type guint) (object :gtk-type GtkObject*))
( ( quit_add : return - type guint ) ( main_level : gtk - type guint ) ( function : gtk - type GtkFunction ) ( data : gtk - type gpointer ) )
( ( quit_add_full : return - type guint ) ( main_level : gtk - type guint ) ( function : gtk - type GtkFunction ) ( marshal : gtk - type GtkCallbackMarshal ) ( data : gtk - type gpointer ) ( destroy : gtk - type GtkDestroyNotify ) )
(quit_remove (quit_handler_id :gtk-type guint))
( ( timeout_add : return - type guint ) ( interval : gtk - type ) ( function : gtk - type GtkFunction ) ( data : gtk - type gpointer ) )
( ( timeout_add_full : return - type guint ) ( interval : gtk - type ) ( function : gtk - type GtkFunction ) ( marshal : gtk - type GtkCallbackMarshal ) ( data : gtk - type gpointer ) ( destroy : gtk - type GtkDestroyNotify ) )
(timeout_remove (timeout_handler_id :gtk-type guint))
( ( idle_add : return - type guint ) ( function : gtk - type GtkFunction ) ( data : gtk - type gpointer ) )
( ( idle_add_priority : return - type guint ) ( priority : gtk - type gint ) ( function : gtk - type GtkFunction ) ( data : gtk - type gpointer ) )
( ( idle_add_full : return - type guint ) ( priority : gtk - type gint ) ( function : gtk - type GtkFunction ) ( marshal : gtk - type GtkCallbackMarshal ) ( data : gtk - type gpointer ) ( destroy : gtk - type GtkDestroyNotify ) )
(idle_remove (idle_handler_id :gtk-type guint))
((input_add :return-type guint :c-name gtk_input_add_full) (source :gtk-type gint) (condition :gtk-type GdkInputCondition) (function :gtk-type GdkInputFunction) (marshal :gtk-type GtkCallbackMarshal) (data :gtk-type gpointer) (destroy :gtk-type GtkDestroyNotify))
(input_remove (input_handler_id :gtk-type guint))
( ( key_snooper_install : return - type guint ) ( snooper : gtk - type GtkKeySnoopFunc ) ( func_data : gtk - type gpointer ) )
( key_snooper_remove ( snooper_handler_id : gtk - type guint ) )
( ( get_current_event : return - type GdkEvent * ) )
( ( get_event_widget : return - type GtkWidget * ) ( event : gtk - type GdkEvent * ) )
( propagate_event ( widget : gtk - type GtkWidget * ) ( event : gtk - type GdkEvent * ) )
( ( gtk_object_query_args : return - type GtkArg * : c - name gtk_object_query_args ) ( class_type : gtk - type GtkType ) ( arg_flags : gtk - type * * ) ( n_args : gtk - type guint * ) )
( ( gtk_object_add_arg_type : c - name gtk_object_add_arg_type ) ( arg_name : gtk - type const - gchar * ) ( arg_type : gtk - type GtkType ) ( arg_flags : gtk - type guint ) ( arg_id : gtk - type guint ) )
( ( : return - type gchar * : c - name ) ( object_type : gtk - type GtkType ) ( arg_list_p : gtk - type * * ) ( info_list_p : gtk - type * * ) ( first_arg_name : gtk - type const - gchar * ) ( var_args : gtk - type va_list ) )
( ( gtk_object_arg_get_info : return - type gchar * : c - name gtk_object_arg_get_info ) ( object_type : gtk - type GtkType ) ( arg_name : gtk - type const - gchar * ) ( info_p : gtk - type GtkArgInfo * * ) )
( ( gtk_trace_referencing : c - name gtk_trace_referencing ) ( object : gtk - type GtkObject * ) ( func : gtk - type const - gchar * ) ( dummy : gtk - type guint ) ( line : gtk - type guint ) ( do_ref : gtk - type gboolean ) )
(preview_set_gamma (gamma :gtk-type double))
(preview_set_color_cube (nred_shades :gtk-type guint) (ngreen_shades :gtk-type guint) (nblue_shades :gtk-type guint) (ngray_shades :gtk-type guint))
(preview_set_install_cmap (install_cmap :gtk-type gint))
(preview_set_reserved (nreserved :gtk-type gint))
((preview_get_visual :return-type GdkVisual*))
((preview_get_cmap :return-type GdkColormap*))
((preview_get_info :return-type GtkPreviewInfo*))
(preview_reset)
(rc_add_default_file (filename :gtk-type const-gchar*))
(rc_set_default_files (filenames :gtk-type gchar**))
((rc_get_default_files :return-type gchar**))
(rc_parse (filename :gtk-type const-gchar*))
(rc_parse_string (rc_string :gtk-type const-gchar*))
((rc_reparse_all :return-type gboolean))
((rc_get_style :return-type GtkStyle*) (widget :gtk-type GtkWidget*))
(rc_add_widget_name_style (rc_style :gtk-type GtkRcStyle*) (pattern :gtk-type const-gchar*))
(rc_add_widget_class_style (rc_style :gtk-type GtkRcStyle*) (pattern :gtk-type const-gchar*))
(rc_add_class_style (rc_style :gtk-type GtkRcStyle*) (pattern :gtk-type const-gchar*))
(rc_set_image_loader (loader :gtk-type GtkImageLoader))
((rc_load_image :return-type GdkPixmap*) (colormap :gtk-type GdkColormap*) (transparent_color :gtk-type GdkColor*) (filename :gtk-type const-gchar*))
((rc_find_pixmap_in_path :return-type gchar*) (scanner :gtk-type GScanner*) (pixmap_file :gtk-type const-gchar*))
((rc_find_module_in_path :return-type gchar*) (module_file :gtk-type const-gchar*))
((rc_get_theme_dir :return-type gchar*))
((rc_get_module_dir :return-type gchar*))
((rc_parse_color :return-type guint) (scanner :gtk-type GScanner*) (color :gtk-type GdkColor*))
((rc_parse_state :return-type guint) (scanner :gtk-type GScanner*) (state :gtk-type GtkStateType*))
((rc_parse_priority :return-type guint) (scanner :gtk-type GScanner*) (priority :gtk-type GtkPathPriorityType*))
( ( gtk_selection_incr_event : return - type gint : c - name gtk_selection_incr_event ) ( window : gtk - type GdkWindow * ) ( event : gtk - type GdkEventProperty * ) )
((gtk_signal_lookup :return-type guint :c-name gtk_signal_lookup) (name :gtk-type const-gchar*) (object_type :gtk-type GtkType))
((gtk_signal_name :return-type gchar* :c-name gtk_signal_name) (signal_id :gtk-type guint))
( ( gtk_signal_n_emissions : return - type guint : c - name gtk_signal_n_emissions ) ( object : gtk - type GtkObject * ) ( signal_id : gtk - type guint ) )
( ( gtk_signal_n_emissions_by_name : return - type guint : c - name gtk_signal_n_emissions_by_name ) ( object : gtk - type GtkObject * ) ( name : gtk - type const - gchar * ) )
( ( gtk_signal_connect_full : return - type guint : c - name gtk_signal_connect_full ) ( object : gtk - type GtkObject * ) ( name : gtk - type const - gchar * ) ( func : gtk - type GtkSignalFunc ) ( marshal : gtk - type GtkCallbackMarshal ) ( data : gtk - type gpointer ) ( destroy_func : gtk - type GtkDestroyNotify ) ( object_signal : gtk - type gint ) ( after : gtk - type gint ) )
( ( gtk_signal_connect_object_while_alive : c - name gtk_signal_connect_object_while_alive ) ( object : gtk - type GtkObject * ) ( signal : gtk - type const - gchar * ) ( func : gtk - type GtkSignalFunc ) ( alive_object : gtk - type GtkObject * ) )
( ( gtk_signal_connect_while_alive : c - name gtk_signal_connect_while_alive ) ( object : gtk - type GtkObject * ) ( signal : gtk - type const - gchar * ) ( func : gtk - type GtkSignalFunc ) ( func_data : gtk - type gpointer ) ( alive_object : gtk - type GtkObject * ) )
( ( gtk_signal_disconnect_by_func : c - name gtk_signal_disconnect_by_func ) ( object : gtk - type GtkObject * ) ( func : gtk - type GtkSignalFunc ) ( data : gtk - type gpointer ) )
( ( gtk_signal_disconnect_by_data : c - name gtk_signal_disconnect_by_data ) ( object : gtk - type GtkObject * ) ( data : gtk - type gpointer ) )
( ( gtk_signal_handler_block_by_func : c - name gtk_signal_handler_block_by_func ) ( object : gtk - type GtkObject * ) ( func : gtk - type GtkSignalFunc ) ( data : gtk - type gpointer ) )
( ( gtk_signal_handler_block_by_data : c - name gtk_signal_handler_block_by_data ) ( object : gtk - type GtkObject * ) ( data : gtk - type gpointer ) )
( ( gtk_signal_handler_unblock_by_func : c - name gtk_signal_handler_unblock_by_func ) ( object : gtk - type GtkObject * ) ( func : gtk - type GtkSignalFunc ) ( data : gtk - type gpointer ) )
( ( gtk_signal_handler_unblock_by_data : c - name gtk_signal_handler_unblock_by_data ) ( object : gtk - type GtkObject * ) ( data : gtk - type gpointer ) )
( ( gtk_signal_handler_pending_by_func : return - type guint : c - name gtk_signal_handler_pending_by_func ) ( object : gtk - type GtkObject * ) ( signal_id : gtk - type guint ) ( may_be_blocked : gtk - type gboolean ) ( func : gtk - type GtkSignalFunc ) ( data : gtk - type gpointer ) )
( ( gtk_signal_add_emission_hook : return - type guint : c - name gtk_signal_add_emission_hook ) ( signal_id : gtk - type guint ) ( hook_func : gtk - type GtkEmissionHook ) ( data : gtk - type gpointer ) )
((gtk_signal_add_emission_hook_full :return-type guint :c-name gtk_signal_add_emission_hook_full) (signal_id :gtk-type guint) (hook_func :gtk-type GtkEmissionHook) (data :gtk-type gpointer) (destroy :gtk-type GDestroyNotify))
((gtk_signal_remove_emission_hook :c-name gtk_signal_remove_emission_hook) (signal_id :gtk-type guint) (hook_id :gtk-type guint))
( ( gtk_signal_query : return - type GtkSignalQuery * : c - name gtk_signal_query ) ( signal_id : gtk - type guint ) )
( ( gtk_signal_emit_by_name : c - name gtk_signal_emit_by_name ) ( object : gtk - type GtkObject * ) ( name : gtk - type const - gchar * ) )
( ( gtk_signal_emitv : c - name gtk_signal_emitv ) ( object : gtk - type GtkObject * ) ( signal_id : gtk - type guint ) ( params : gtk - type GtkArg * ) )
( ( gtk_signal_emitv_by_name : c - name gtk_signal_emitv_by_name ) ( object : gtk - type GtkObject * ) ( name : gtk - type const - gchar * ) ( params : gtk - type GtkArg * ) )
( ( gtk_signal_set_funcs : c - name gtk_signal_set_funcs ) ( marshal_func : gtk - type GtkSignalMarshal ) ( destroy_func : gtk - type ) )
((gtk_draw_hline :c-name gtk_draw_hline) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (x1 :gtk-type gint) (x2 :gtk-type gint) (y :gtk-type gint))
((gtk_draw_vline :c-name gtk_draw_vline) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (y1 :gtk-type gint) (y2 :gtk-type gint) (x :gtk-type gint))
((gtk_draw_shadow :c-name gtk_draw_shadow) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_draw_polygon :c-name gtk_draw_polygon) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (points :gtk-type GdkPoint*) (npoints :gtk-type gint) (fill :gtk-type gboolean))
((gtk_draw_arrow :c-name gtk_draw_arrow) (style :gtk-type GtkStyle*) (window :gtk-type GdkDrawable*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (arrow_type :gtk-type GtkArrowType) (fill :gtk-type gboolean) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_draw_diamond :c-name gtk_draw_diamond) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_draw_oval :c-name gtk_draw_oval) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_draw_string :c-name gtk_draw_string) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (x :gtk-type gint) (y :gtk-type gint) (string :gtk-type const-gchar*))
((gtk_draw_box :c-name gtk_draw_box) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
( ( gtk_draw_flat_box : c - name gtk_draw_flat_box ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) )
( ( : c - name ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) )
( ( gtk_draw_option : c - name gtk_draw_option ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) )
( ( gtk_draw_cross : c - name ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) )
( ( gtk_draw_ramp : c - name gtk_draw_ramp ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( arrow_type : gtk - type GtkArrowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) )
( ( gtk_draw_tab : c - name gtk_draw_tab ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) )
( ( gtk_draw_shadow_gap : c - name ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) ( gap_side : gtk - type GtkPositionType ) ( gap_x : gtk - type gint ) ( gap_width : gtk - type gint ) )
( ( gtk_draw_box_gap : c - name gtk_draw_box_gap ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) ( gap_side : gtk - type GtkPositionType ) ( gap_x : gtk - type gint ) ( gap_width : gtk - type gint ) )
( ( gtk_draw_extension : c - name gtk_draw_extension ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) ( gap_side : gtk - type GtkPositionType ) )
( ( gtk_draw_focus : c - name gtk_draw_focus ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) )
( ( gtk_draw_slider : c - name gtk_draw_slider ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) ( orientation : gtk - type GtkOrientation ) )
( ( gtk_draw_handle : c - name gtk_draw_handle ) ( style : gtk - type GtkStyle * ) ( window : gtk - type GdkWindow * ) ( state_type : gtk - type GtkStateType ) ( shadow_type : gtk - type GtkShadowType ) ( x : gtk - type gint ) ( y : gtk - type gint ) ( width : gtk - type gint ) ( height : gtk - type gint ) ( orientation : gtk - type GtkOrientation ) )
((gtk_paint_hline :c-name gtk_paint_hline) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x1 :gtk-type gint) (x2 :gtk-type gint) (y :gtk-type gint))
((gtk_paint_vline :c-name gtk_paint_vline) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (y1 :gtk-type gint) (y2 :gtk-type gint) (x :gtk-type gint))
((gtk_paint_shadow :c-name gtk_paint_shadow) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_polygon :c-name gtk_paint_polygon) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (points :gtk-type GdkPoint*) (npoints :gtk-type gint) (fill :gtk-type gboolean))
((gtk_paint_arrow :c-name gtk_paint_arrow) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (arrow_type :gtk-type GtkArrowType) (fill :gtk-type gboolean) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_diamond :c-name gtk_paint_diamond) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_oval :c-name gtk_paint_oval) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_string :c-name gtk_paint_string) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (string :gtk-type const-gchar*))
((gtk_paint_box :c-name gtk_paint_box) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_flat_box :c-name gtk_paint_flat_box) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_check :c-name gtk_paint_check) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_option :c-name gtk_paint_option) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_cross :c-name gtk_paint_cross) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_ramp :c-name gtk_paint_ramp) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (arrow_type :gtk-type GtkArrowType) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_tab :c-name gtk_paint_tab) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_shadow_gap :c-name gtk_paint_shadow_gap) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint) (gap_side :gtk-type GtkPositionType) (gap_x :gtk-type gint) (gap_width :gtk-type gint))
((gtk_paint_box_gap :c-name gtk_paint_box_gap) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint) (gap_side :gtk-type GtkPositionType) (gap_x :gtk-type gint) (gap_width :gtk-type gint))
((gtk_paint_extension :c-name gtk_paint_extension) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint) (gap_side :gtk-type GtkPositionType))
((gtk_paint_focus :c-name gtk_paint_focus) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint))
((gtk_paint_slider :c-name gtk_paint_slider) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint) (orientation :gtk-type GtkOrientation))
((gtk_paint_handle :c-name gtk_paint_handle) (style :gtk-type GtkStyle*) (window :gtk-type GdkWindow*) (state_type :gtk-type GtkStateType) (shadow_type :gtk-type GtkShadowType) (area :gtk-type GdkRectangle*) (widget :gtk-type GtkWidget*) (detail :gtk-type gchar*) (x :gtk-type gint) (y :gtk-type gint) (width :gtk-type gint) (height :gtk-type gint) (orientation :gtk-type GtkOrientation))
( ( gtk_tooltips_data_get : return - type GtkTooltipsData * : c - name gtk_tooltips_data_get ) ( widget : gtk - type GtkWidget * ) )
((gtk_type_name :return-type gchar* :c-name gtk_type_name) (type :gtk-type guint))
((gtk_type_from_name :return-type GtkType :c-name gtk_type_from_name) (name :gtk-type const-gchar*))
( ( gtk_type_check_object_cast : return - type GtkTypeObject * : c - name gtk_type_check_object_cast ) ( type_object : gtk - type GtkTypeObject * ) ( cast_type : gtk - type GtkType ) )
( ( gtk_type_check_class_cast : return - type GtkTypeClass * : c - name gtk_type_check_class_cast ) ( klass : gtk - type GtkTypeClass * ) ( cast_type : gtk - type GtkType ) )
( ( : return - type GtkType : c - name ) ( type_name : gtk - type const - gchar * ) ( values : gtk - type GtkEnumValue * ) )
( ( gtk_type_register_flags : return - type GtkType : c - name ) ( type_name : gtk - type const - gchar * ) ( values : gtk - type GtkFlagValue * ) )
((vbutton_box_get_spacing_default :return-type gint))
(vbutton_box_set_spacing_default (spacing :gtk-type gint))
((vbutton_box_get_layout_default :return-type GtkButtonBoxStyle))
(vbutton_box_set_layout_default (layout :gtk-type GtkButtonBoxStyle))
(widget_push_style (style :gtk-type GtkStyle*))
(widget_push_colormap (cmap :gtk-type GdkColormap*))
(widget_push_visual (visual :gtk-type GdkVisual*))
(widget_push_composite_child)
(widget_pop_composite_child)
(widget_pop_style)
(widget_pop_colormap)
(widget_pop_visual)
(widget_set_default_style (style :gtk-type GtkStyle*))
(widget_set_default_colormap (colormap :gtk-type GdkColormap*))
(widget_set_default_visual (visual :gtk-type GdkVisual*))
((widget_get_default_style :return-type GtkStyle*))
((widget_get_default_colormap :return-type GdkColormap*))
((widget_get_default_visual :return-type GdkVisual*))
)
we ca n't use any of the foreign types defined in bgtk in our
export clauses , or else this would be in php-gtk-common.scm
(define (php-hash->string*::string* ar)
(string-list->string*
(map mkstr (php-hash->list (maybe-unbox ar)))))
(define (string*->php-hash ar)
(list->php-hash
(string*->string-list (maybe-unbox ar))))
|
b326f027a894957007427f9744d6437929bb2263832305d5be8bbb3958abcc82 | ocsigen/ocaml-eliom | unix.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
type error =
E2BIG
| EACCES
| EAGAIN
| EBADF
| EBUSY
| ECHILD
| EDEADLK
| EDOM
| EEXIST
| EFAULT
| EFBIG
| EINTR
| EINVAL
| EIO
| EISDIR
| EMFILE
| EMLINK
| ENAMETOOLONG
| ENFILE
| ENODEV
| ENOENT
| ENOEXEC
| ENOLCK
| ENOMEM
| ENOSPC
| ENOSYS
| ENOTDIR
| ENOTEMPTY
| ENOTTY
| ENXIO
| EPERM
| EPIPE
| ERANGE
| EROFS
| ESPIPE
| ESRCH
| EXDEV
| EWOULDBLOCK
| EINPROGRESS
| EALREADY
| ENOTSOCK
| EDESTADDRREQ
| EMSGSIZE
| EPROTOTYPE
| ENOPROTOOPT
| EPROTONOSUPPORT
| ESOCKTNOSUPPORT
| EOPNOTSUPP
| EPFNOSUPPORT
| EAFNOSUPPORT
| EADDRINUSE
| EADDRNOTAVAIL
| ENETDOWN
| ENETUNREACH
| ENETRESET
| ECONNABORTED
| ECONNRESET
| ENOBUFS
| EISCONN
| ENOTCONN
| ESHUTDOWN
| ETOOMANYREFS
| ETIMEDOUT
| ECONNREFUSED
| EHOSTDOWN
| EHOSTUNREACH
| ELOOP
| EOVERFLOW
| EUNKNOWNERR of int
exception Unix_error of error * string * string
let _ = Callback.register_exception "Unix.Unix_error"
(Unix_error(E2BIG, "", ""))
external error_message : error -> string = "unix_error_message"
let () =
Printexc.register_printer
(function
| Unix_error (e, s, s') ->
let msg = match e with
| E2BIG -> "E2BIG"
| EACCES -> "EACCES"
| EAGAIN -> "EAGAIN"
| EBADF -> "EBADF"
| EBUSY -> "EBUSY"
| ECHILD -> "ECHILD"
| EDEADLK -> "EDEADLK"
| EDOM -> "EDOM"
| EEXIST -> "EEXIST"
| EFAULT -> "EFAULT"
| EFBIG -> "EFBIG"
| EINTR -> "EINTR"
| EINVAL -> "EINVAL"
| EIO -> "EIO"
| EISDIR -> "EISDIR"
| EMFILE -> "EMFILE"
| EMLINK -> "EMLINK"
| ENAMETOOLONG -> "ENAMETOOLONG"
| ENFILE -> "ENFILE"
| ENODEV -> "ENODEV"
| ENOENT -> "ENOENT"
| ENOEXEC -> "ENOEXEC"
| ENOLCK -> "ENOLCK"
| ENOMEM -> "ENOMEM"
| ENOSPC -> "ENOSPC"
| ENOSYS -> "ENOSYS"
| ENOTDIR -> "ENOTDIR"
| ENOTEMPTY -> "ENOTEMPTY"
| ENOTTY -> "ENOTTY"
| ENXIO -> "ENXIO"
| EPERM -> "EPERM"
| EPIPE -> "EPIPE"
| ERANGE -> "ERANGE"
| EROFS -> "EROFS"
| ESPIPE -> "ESPIPE"
| ESRCH -> "ESRCH"
| EXDEV -> "EXDEV"
| EWOULDBLOCK -> "EWOULDBLOCK"
| EINPROGRESS -> "EINPROGRESS"
| EALREADY -> "EALREADY"
| ENOTSOCK -> "ENOTSOCK"
| EDESTADDRREQ -> "EDESTADDRREQ"
| EMSGSIZE -> "EMSGSIZE"
| EPROTOTYPE -> "EPROTOTYPE"
| ENOPROTOOPT -> "ENOPROTOOPT"
| EPROTONOSUPPORT -> "EPROTONOSUPPORT"
| ESOCKTNOSUPPORT -> "ESOCKTNOSUPPORT"
| EOPNOTSUPP -> "EOPNOTSUPP"
| EPFNOSUPPORT -> "EPFNOSUPPORT"
| EAFNOSUPPORT -> "EAFNOSUPPORT"
| EADDRINUSE -> "EADDRINUSE"
| EADDRNOTAVAIL -> "EADDRNOTAVAIL"
| ENETDOWN -> "ENETDOWN"
| ENETUNREACH -> "ENETUNREACH"
| ENETRESET -> "ENETRESET"
| ECONNABORTED -> "ECONNABORTED"
| ECONNRESET -> "ECONNRESET"
| ENOBUFS -> "ENOBUFS"
| EISCONN -> "EISCONN"
| ENOTCONN -> "ENOTCONN"
| ESHUTDOWN -> "ESHUTDOWN"
| ETOOMANYREFS -> "ETOOMANYREFS"
| ETIMEDOUT -> "ETIMEDOUT"
| ECONNREFUSED -> "ECONNREFUSED"
| EHOSTDOWN -> "EHOSTDOWN"
| EHOSTUNREACH -> "EHOSTUNREACH"
| ELOOP -> "ELOOP"
| EOVERFLOW -> "EOVERFLOW"
| EUNKNOWNERR x -> Printf.sprintf "EUNKNOWNERR %d" x in
Some (Printf.sprintf "Unix.Unix_error(Unix.%s, %S, %S)" msg s s')
| _ -> None)
let handle_unix_error f arg =
try
f arg
with Unix_error(err, fun_name, arg) ->
prerr_string Sys.argv.(0);
prerr_string ": \"";
prerr_string fun_name;
prerr_string "\" failed";
if String.length arg > 0 then begin
prerr_string " on \"";
prerr_string arg;
prerr_string "\""
end;
prerr_string ": ";
prerr_endline (error_message err);
exit 2
external environment : unit -> string array = "unix_environment"
external getenv: string -> string = "caml_sys_getenv"
external putenv: string -> string -> unit = "unix_putenv"
type process_status =
WEXITED of int
| WSIGNALED of int
| WSTOPPED of int
type wait_flag =
WNOHANG
| WUNTRACED
external execv : string -> string array -> 'a = "unix_execv"
external execve : string -> string array -> string array -> 'a = "unix_execve"
external execvp : string -> string array -> 'a = "unix_execvp"
external execvpe : string -> string array -> string array -> 'a = "unix_execvpe"
external fork : unit -> int = "unix_fork"
external wait : unit -> int * process_status = "unix_wait"
external waitpid : wait_flag list -> int -> int * process_status
= "unix_waitpid"
external getpid : unit -> int = "unix_getpid"
external getppid : unit -> int = "unix_getppid"
external nice : int -> int = "unix_nice"
type file_descr = int
let stdin = 0
let stdout = 1
let stderr = 2
type open_flag =
O_RDONLY
| O_WRONLY
| O_RDWR
| O_NONBLOCK
| O_APPEND
| O_CREAT
| O_TRUNC
| O_EXCL
| O_NOCTTY
| O_DSYNC
| O_SYNC
| O_RSYNC
| O_SHARE_DELETE
| O_CLOEXEC
type file_perm = int
external openfile : string -> open_flag list -> file_perm -> file_descr
= "unix_open"
external close : file_descr -> unit = "unix_close"
external unsafe_read : file_descr -> bytes -> int -> int -> int
= "unix_read"
external unsafe_write : file_descr -> bytes -> int -> int -> int = "unix_write"
external unsafe_single_write : file_descr -> bytes -> int -> int -> int
= "unix_single_write"
let read fd buf ofs len =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "Unix.read"
else unsafe_read fd buf ofs len
let write fd buf ofs len =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "Unix.write"
else unsafe_write fd buf ofs len
write misbehaves because it attempts to write all data by making repeated
calls to the Unix write function ( see comment in write.c and unix.mli ) .
single_write fixes this by never calling write twice .
calls to the Unix write function (see comment in write.c and unix.mli).
single_write fixes this by never calling write twice. *)
let single_write fd buf ofs len =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "Unix.single_write"
else unsafe_single_write fd buf ofs len
let write_substring fd buf ofs len =
write fd (Bytes.unsafe_of_string buf) ofs len
let single_write_substring fd buf ofs len =
single_write fd (Bytes.unsafe_of_string buf) ofs len
external in_channel_of_descr : file_descr -> in_channel
= "caml_ml_open_descriptor_in"
external out_channel_of_descr : file_descr -> out_channel
= "caml_ml_open_descriptor_out"
external descr_of_in_channel : in_channel -> file_descr
= "caml_channel_descriptor"
external descr_of_out_channel : out_channel -> file_descr
= "caml_channel_descriptor"
type seek_command =
SEEK_SET
| SEEK_CUR
| SEEK_END
external lseek : file_descr -> int -> seek_command -> int = "unix_lseek"
external truncate : string -> int -> unit = "unix_truncate"
external ftruncate : file_descr -> int -> unit = "unix_ftruncate"
type file_kind =
S_REG
| S_DIR
| S_CHR
| S_BLK
| S_LNK
| S_FIFO
| S_SOCK
type stats =
{ st_dev : int;
st_ino : int;
st_kind : file_kind;
st_perm : file_perm;
st_nlink : int;
st_uid : int;
st_gid : int;
st_rdev : int;
st_size : int;
st_atime : float;
st_mtime : float;
st_ctime : float }
external stat : string -> stats = "unix_stat"
external lstat : string -> stats = "unix_lstat"
external fstat : file_descr -> stats = "unix_fstat"
external isatty : file_descr -> bool = "unix_isatty"
external unlink : string -> unit = "unix_unlink"
external rename : string -> string -> unit = "unix_rename"
external link : string -> string -> unit = "unix_link"
module LargeFile =
struct
external lseek : file_descr -> int64 -> seek_command -> int64
= "unix_lseek_64"
external truncate : string -> int64 -> unit = "unix_truncate_64"
external ftruncate : file_descr -> int64 -> unit = "unix_ftruncate_64"
type stats =
{ st_dev : int;
st_ino : int;
st_kind : file_kind;
st_perm : file_perm;
st_nlink : int;
st_uid : int;
st_gid : int;
st_rdev : int;
st_size : int64;
st_atime : float;
st_mtime : float;
st_ctime : float;
}
external stat : string -> stats = "unix_stat_64"
external lstat : string -> stats = "unix_lstat_64"
external fstat : file_descr -> stats = "unix_fstat_64"
end
type access_permission =
R_OK
| W_OK
| X_OK
| F_OK
external chmod : string -> file_perm -> unit = "unix_chmod"
external fchmod : file_descr -> file_perm -> unit = "unix_fchmod"
external chown : string -> int -> int -> unit = "unix_chown"
external fchown : file_descr -> int -> int -> unit = "unix_fchown"
external umask : int -> int = "unix_umask"
external access : string -> access_permission list -> unit = "unix_access"
external dup : file_descr -> file_descr = "unix_dup"
external dup2 : file_descr -> file_descr -> unit = "unix_dup2"
external set_nonblock : file_descr -> unit = "unix_set_nonblock"
external clear_nonblock : file_descr -> unit = "unix_clear_nonblock"
external set_close_on_exec : file_descr -> unit = "unix_set_close_on_exec"
external clear_close_on_exec : file_descr -> unit = "unix_clear_close_on_exec"
FD_CLOEXEC should be supported on all Unix systems these days ,
but just in case ...
but just in case... *)
let try_set_close_on_exec fd =
try set_close_on_exec fd; true with Invalid_argument _ -> false
external mkdir : string -> file_perm -> unit = "unix_mkdir"
external rmdir : string -> unit = "unix_rmdir"
external chdir : string -> unit = "unix_chdir"
external getcwd : unit -> string = "unix_getcwd"
external chroot : string -> unit = "unix_chroot"
type dir_handle
external opendir : string -> dir_handle = "unix_opendir"
external readdir : dir_handle -> string = "unix_readdir"
external rewinddir : dir_handle -> unit = "unix_rewinddir"
external closedir : dir_handle -> unit = "unix_closedir"
external pipe : unit -> file_descr * file_descr = "unix_pipe"
external symlink : ?to_dir:bool -> string -> string -> unit = "unix_symlink"
external has_symlink : unit -> bool = "unix_has_symlink"
external readlink : string -> string = "unix_readlink"
external mkfifo : string -> file_perm -> unit = "unix_mkfifo"
external select :
file_descr list -> file_descr list -> file_descr list -> float ->
file_descr list * file_descr list * file_descr list = "unix_select"
type lock_command =
F_ULOCK
| F_LOCK
| F_TLOCK
| F_TEST
| F_RLOCK
| F_TRLOCK
external lockf : file_descr -> lock_command -> int -> unit = "unix_lockf"
external kill : int -> int -> unit = "unix_kill"
type sigprocmask_command = SIG_SETMASK | SIG_BLOCK | SIG_UNBLOCK
external sigprocmask: sigprocmask_command -> int list -> int list
= "unix_sigprocmask"
external sigpending: unit -> int list = "unix_sigpending"
external sigsuspend: int list -> unit = "unix_sigsuspend"
let pause() =
let sigs = sigprocmask SIG_BLOCK [] in sigsuspend sigs
type process_times =
{ tms_utime : float;
tms_stime : float;
tms_cutime : float;
tms_cstime : float }
type tm =
{ tm_sec : int;
tm_min : int;
tm_hour : int;
tm_mday : int;
tm_mon : int;
tm_year : int;
tm_wday : int;
tm_yday : int;
tm_isdst : bool }
external time : unit -> float = "unix_time"
external gettimeofday : unit -> float = "unix_gettimeofday"
external gmtime : float -> tm = "unix_gmtime"
external localtime : float -> tm = "unix_localtime"
external mktime : tm -> float * tm = "unix_mktime"
external alarm : int -> int = "unix_alarm"
external sleepf : float -> unit = "unix_sleep"
let sleep duration = sleepf (float duration)
external times : unit -> process_times = "unix_times"
external utimes : string -> float -> float -> unit = "unix_utimes"
type interval_timer =
ITIMER_REAL
| ITIMER_VIRTUAL
| ITIMER_PROF
type interval_timer_status =
{ it_interval: float; (* Period *)
it_value: float } (* Current value of the timer *)
external getitimer: interval_timer -> interval_timer_status = "unix_getitimer"
external setitimer:
interval_timer -> interval_timer_status -> interval_timer_status
= "unix_setitimer"
external getuid : unit -> int = "unix_getuid"
external geteuid : unit -> int = "unix_geteuid"
external setuid : int -> unit = "unix_setuid"
external getgid : unit -> int = "unix_getgid"
external getegid : unit -> int = "unix_getegid"
external setgid : int -> unit = "unix_setgid"
external getgroups : unit -> int array = "unix_getgroups"
external setgroups : int array -> unit = "unix_setgroups"
external initgroups : string -> int -> unit = "unix_initgroups"
type passwd_entry =
{ pw_name : string;
pw_passwd : string;
pw_uid : int;
pw_gid : int;
pw_gecos : string;
pw_dir : string;
pw_shell : string }
type group_entry =
{ gr_name : string;
gr_passwd : string;
gr_gid : int;
gr_mem : string array }
external getlogin : unit -> string = "unix_getlogin"
external getpwnam : string -> passwd_entry = "unix_getpwnam"
external getgrnam : string -> group_entry = "unix_getgrnam"
external getpwuid : int -> passwd_entry = "unix_getpwuid"
external getgrgid : int -> group_entry = "unix_getgrgid"
type inet_addr = string
let is_inet6_addr s = String.length s = 16
external inet_addr_of_string : string -> inet_addr
= "unix_inet_addr_of_string"
external string_of_inet_addr : inet_addr -> string
= "unix_string_of_inet_addr"
let inet_addr_any = inet_addr_of_string "0.0.0.0"
let inet_addr_loopback = inet_addr_of_string "127.0.0.1"
let inet6_addr_any =
try inet_addr_of_string "::" with Failure _ -> inet_addr_any
let inet6_addr_loopback =
try inet_addr_of_string "::1" with Failure _ -> inet_addr_loopback
type socket_domain =
PF_UNIX
| PF_INET
| PF_INET6
type socket_type =
SOCK_STREAM
| SOCK_DGRAM
| SOCK_RAW
| SOCK_SEQPACKET
type sockaddr =
ADDR_UNIX of string
| ADDR_INET of inet_addr * int
let domain_of_sockaddr = function
ADDR_UNIX _ -> PF_UNIX
| ADDR_INET(a, _) -> if is_inet6_addr a then PF_INET6 else PF_INET
type shutdown_command =
SHUTDOWN_RECEIVE
| SHUTDOWN_SEND
| SHUTDOWN_ALL
type msg_flag =
MSG_OOB
| MSG_DONTROUTE
| MSG_PEEK
external socket : socket_domain -> socket_type -> int -> file_descr
= "unix_socket"
external socketpair :
socket_domain -> socket_type -> int -> file_descr * file_descr
= "unix_socketpair"
external accept : file_descr -> file_descr * sockaddr = "unix_accept"
external bind : file_descr -> sockaddr -> unit = "unix_bind"
external connect : file_descr -> sockaddr -> unit = "unix_connect"
external listen : file_descr -> int -> unit = "unix_listen"
external shutdown : file_descr -> shutdown_command -> unit = "unix_shutdown"
external getsockname : file_descr -> sockaddr = "unix_getsockname"
external getpeername : file_descr -> sockaddr = "unix_getpeername"
external unsafe_recv :
file_descr -> bytes -> int -> int -> msg_flag list -> int
= "unix_recv"
external unsafe_recvfrom :
file_descr -> bytes -> int -> int -> msg_flag list -> int * sockaddr
= "unix_recvfrom"
external unsafe_send :
file_descr -> bytes -> int -> int -> msg_flag list -> int
= "unix_send"
external unsafe_sendto :
file_descr -> bytes -> int -> int -> msg_flag list -> sockaddr -> int
= "unix_sendto" "unix_sendto_native"
let recv fd buf ofs len flags =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "Unix.recv"
else unsafe_recv fd buf ofs len flags
let recvfrom fd buf ofs len flags =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "Unix.recvfrom"
else unsafe_recvfrom fd buf ofs len flags
let send fd buf ofs len flags =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "Unix.send"
else unsafe_send fd buf ofs len flags
let sendto fd buf ofs len flags addr =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "Unix.sendto"
else unsafe_sendto fd buf ofs len flags addr
let send_substring fd buf ofs len flags =
send fd (Bytes.unsafe_of_string buf) ofs len flags
let sendto_substring fd buf ofs len flags addr =
sendto fd (Bytes.unsafe_of_string buf) ofs len flags addr
type socket_bool_option =
SO_DEBUG
| SO_BROADCAST
| SO_REUSEADDR
| SO_KEEPALIVE
| SO_DONTROUTE
| SO_OOBINLINE
| SO_ACCEPTCONN
| TCP_NODELAY
| IPV6_ONLY
type socket_int_option =
SO_SNDBUF
| SO_RCVBUF
| SO_ERROR
| SO_TYPE
| SO_RCVLOWAT
| SO_SNDLOWAT
type socket_optint_option = SO_LINGER
type socket_float_option =
SO_RCVTIMEO
| SO_SNDTIMEO
type socket_error_option = SO_ERROR
module SO: sig
type ('opt, 'v) t
val bool: (socket_bool_option, bool) t
val int: (socket_int_option, int) t
val optint: (socket_optint_option, int option) t
val float: (socket_float_option, float) t
val error: (socket_error_option, error option) t
val get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
val set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
end = struct
type ('opt, 'v) t = int
let bool = 0
let int = 1
let optint = 2
let float = 3
let error = 4
external get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
= "unix_getsockopt"
external set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
= "unix_setsockopt"
end
let getsockopt fd opt = SO.get SO.bool fd opt
let setsockopt fd opt v = SO.set SO.bool fd opt v
let getsockopt_int fd opt = SO.get SO.int fd opt
let setsockopt_int fd opt v = SO.set SO.int fd opt v
let getsockopt_optint fd opt = SO.get SO.optint fd opt
let setsockopt_optint fd opt v = SO.set SO.optint fd opt v
let getsockopt_float fd opt = SO.get SO.float fd opt
let setsockopt_float fd opt v = SO.set SO.float fd opt v
let getsockopt_error fd = SO.get SO.error fd SO_ERROR
type host_entry =
{ h_name : string;
h_aliases : string array;
h_addrtype : socket_domain;
h_addr_list : inet_addr array }
type protocol_entry =
{ p_name : string;
p_aliases : string array;
p_proto : int }
type service_entry =
{ s_name : string;
s_aliases : string array;
s_port : int;
s_proto : string }
external gethostname : unit -> string = "unix_gethostname"
external gethostbyname : string -> host_entry = "unix_gethostbyname"
external gethostbyaddr : inet_addr -> host_entry = "unix_gethostbyaddr"
external getprotobyname : string -> protocol_entry
= "unix_getprotobyname"
external getprotobynumber : int -> protocol_entry
= "unix_getprotobynumber"
external getservbyname : string -> string -> service_entry
= "unix_getservbyname"
external getservbyport : int -> string -> service_entry
= "unix_getservbyport"
type addr_info =
{ ai_family : socket_domain;
ai_socktype : socket_type;
ai_protocol : int;
ai_addr : sockaddr;
ai_canonname : string }
type getaddrinfo_option =
AI_FAMILY of socket_domain
| AI_SOCKTYPE of socket_type
| AI_PROTOCOL of int
| AI_NUMERICHOST
| AI_CANONNAME
| AI_PASSIVE
external getaddrinfo_system
: string -> string -> getaddrinfo_option list -> addr_info list
= "unix_getaddrinfo"
let getaddrinfo_emulation node service opts =
Parse options
let opt_socktype = ref None
and opt_protocol = ref 0
and opt_passive = ref false in
List.iter
(function AI_SOCKTYPE s -> opt_socktype := Some s
| AI_PROTOCOL p -> opt_protocol := p
| AI_PASSIVE -> opt_passive := true
| _ -> ())
opts;
(* Determine socket types and port numbers *)
let get_port ty kind =
if service = "" then [ty, 0] else
try
[ty, int_of_string service]
with Failure _ ->
try
[ty, (getservbyname service kind).s_port]
with Not_found -> []
in
let ports =
match !opt_socktype with
| None ->
get_port SOCK_STREAM "tcp" @ get_port SOCK_DGRAM "udp"
| Some SOCK_STREAM ->
get_port SOCK_STREAM "tcp"
| Some SOCK_DGRAM ->
get_port SOCK_DGRAM "udp"
| Some ty ->
if service = "" then [ty, 0] else [] in
(* Determine IP addresses *)
let addresses =
if node = "" then
if List.mem AI_PASSIVE opts
then [inet_addr_any, "0.0.0.0"]
else [inet_addr_loopback, "127.0.0.1"]
else
try
[inet_addr_of_string node, node]
with Failure _ ->
try
let he = gethostbyname node in
List.map
(fun a -> (a, he.h_name))
(Array.to_list he.h_addr_list)
with Not_found ->
[] in
(* Cross-product of addresses and ports *)
List.flatten
(List.map
(fun (ty, port) ->
List.map
(fun (addr, name) ->
{ ai_family = PF_INET;
ai_socktype = ty;
ai_protocol = !opt_protocol;
ai_addr = ADDR_INET(addr, port);
ai_canonname = name })
addresses)
ports)
let getaddrinfo node service opts =
try
List.rev(getaddrinfo_system node service opts)
with Invalid_argument _ ->
getaddrinfo_emulation node service opts
type name_info =
{ ni_hostname : string;
ni_service : string }
type getnameinfo_option =
NI_NOFQDN
| NI_NUMERICHOST
| NI_NAMEREQD
| NI_NUMERICSERV
| NI_DGRAM
external getnameinfo_system
: sockaddr -> getnameinfo_option list -> name_info
= "unix_getnameinfo"
let getnameinfo_emulation addr opts =
match addr with
| ADDR_UNIX f ->
{ ni_hostname = ""; ni_service = f } (* why not? *)
| ADDR_INET(a, p) ->
let hostname =
try
if List.mem NI_NUMERICHOST opts then raise Not_found;
(gethostbyaddr a).h_name
with Not_found ->
if List.mem NI_NAMEREQD opts then raise Not_found;
string_of_inet_addr a in
let service =
try
if List.mem NI_NUMERICSERV opts then raise Not_found;
let kind = if List.mem NI_DGRAM opts then "udp" else "tcp" in
(getservbyport p kind).s_name
with Not_found ->
string_of_int p in
{ ni_hostname = hostname; ni_service = service }
let getnameinfo addr opts =
try
getnameinfo_system addr opts
with Invalid_argument _ ->
getnameinfo_emulation addr opts
type terminal_io = {
mutable c_ignbrk: bool;
mutable c_brkint: bool;
mutable c_ignpar: bool;
mutable c_parmrk: bool;
mutable c_inpck: bool;
mutable c_istrip: bool;
mutable c_inlcr: bool;
mutable c_igncr: bool;
mutable c_icrnl: bool;
mutable c_ixon: bool;
mutable c_ixoff: bool;
mutable c_opost: bool;
mutable c_obaud: int;
mutable c_ibaud: int;
mutable c_csize: int;
mutable c_cstopb: int;
mutable c_cread: bool;
mutable c_parenb: bool;
mutable c_parodd: bool;
mutable c_hupcl: bool;
mutable c_clocal: bool;
mutable c_isig: bool;
mutable c_icanon: bool;
mutable c_noflsh: bool;
mutable c_echo: bool;
mutable c_echoe: bool;
mutable c_echok: bool;
mutable c_echonl: bool;
mutable c_vintr: char;
mutable c_vquit: char;
mutable c_verase: char;
mutable c_vkill: char;
mutable c_veof: char;
mutable c_veol: char;
mutable c_vmin: int;
mutable c_vtime: int;
mutable c_vstart: char;
mutable c_vstop: char
}
external tcgetattr: file_descr -> terminal_io = "unix_tcgetattr"
type setattr_when = TCSANOW | TCSADRAIN | TCSAFLUSH
external tcsetattr: file_descr -> setattr_when -> terminal_io -> unit
= "unix_tcsetattr"
external tcsendbreak: file_descr -> int -> unit = "unix_tcsendbreak"
external tcdrain: file_descr -> unit = "unix_tcdrain"
type flush_queue = TCIFLUSH | TCOFLUSH | TCIOFLUSH
external tcflush: file_descr -> flush_queue -> unit = "unix_tcflush"
type flow_action = TCOOFF | TCOON | TCIOFF | TCION
external tcflow: file_descr -> flow_action -> unit = "unix_tcflow"
external setsid : unit -> int = "unix_setsid"
(* High-level process management (system, popen) *)
let rec waitpid_non_intr pid =
try waitpid [] pid
with Unix_error (EINTR, _, _) -> waitpid_non_intr pid
external sys_exit : int -> 'a = "caml_sys_exit"
let system cmd =
match fork() with
0 -> begin try
execv "/bin/sh" [| "/bin/sh"; "-c"; cmd |]
with _ ->
sys_exit 127
end
| id -> snd(waitpid_non_intr id)
let rec safe_dup fd =
let new_fd = dup fd in
if new_fd >= 3 then
new_fd
else begin
let res = safe_dup fd in
close new_fd;
res
end
let safe_close fd =
try close fd with Unix_error(_,_,_) -> ()
let perform_redirections new_stdin new_stdout new_stderr =
let newnewstdin = safe_dup new_stdin in
let newnewstdout = safe_dup new_stdout in
let newnewstderr = safe_dup new_stderr in
safe_close new_stdin;
safe_close new_stdout;
safe_close new_stderr;
dup2 newnewstdin stdin; close newnewstdin;
dup2 newnewstdout stdout; close newnewstdout;
dup2 newnewstderr stderr; close newnewstderr
let create_process cmd args new_stdin new_stdout new_stderr =
match fork() with
0 ->
begin try
perform_redirections new_stdin new_stdout new_stderr;
execvp cmd args
with _ ->
sys_exit 127
end
| id -> id
let create_process_env cmd args env new_stdin new_stdout new_stderr =
match fork() with
0 ->
begin try
perform_redirections new_stdin new_stdout new_stderr;
execvpe cmd args env
with _ ->
sys_exit 127
end
| id -> id
type popen_process =
Process of in_channel * out_channel
| Process_in of in_channel
| Process_out of out_channel
| Process_full of in_channel * out_channel * in_channel
let popen_processes = (Hashtbl.create 7 : (popen_process, int) Hashtbl.t)
let open_proc cmd proc input output toclose =
let cloexec = List.for_all try_set_close_on_exec toclose in
match fork() with
0 -> begin try
if input <> stdin then begin dup2 input stdin; close input end;
if output <> stdout then begin dup2 output stdout; close output end;
if not cloexec then List.iter close toclose;
execv "/bin/sh" [| "/bin/sh"; "-c"; cmd |]
with _ -> sys_exit 127
end
| id -> Hashtbl.add popen_processes proc id
let open_process_in cmd =
let (in_read, in_write) = pipe() in
let inchan = in_channel_of_descr in_read in
begin
try
open_proc cmd (Process_in inchan) stdin in_write [in_read];
with e ->
close_in inchan;
close in_write;
raise e
end;
close in_write;
inchan
let open_process_out cmd =
let (out_read, out_write) = pipe() in
let outchan = out_channel_of_descr out_write in
begin
try
open_proc cmd (Process_out outchan) out_read stdout [out_write];
with e ->
close_out outchan;
close out_read;
raise e
end;
close out_read;
outchan
let open_process cmd =
let (in_read, in_write) = pipe() in
let fds_to_close = ref [in_read;in_write] in
try
let (out_read, out_write) = pipe() in
fds_to_close := [in_read;in_write;out_read;out_write];
let inchan = in_channel_of_descr in_read in
let outchan = out_channel_of_descr out_write in
open_proc cmd (Process(inchan, outchan)) out_read in_write
[in_read; out_write];
close out_read;
close in_write;
(inchan, outchan)
with e ->
List.iter close !fds_to_close;
raise e
let open_proc_full cmd env proc input output error toclose =
let cloexec = List.for_all try_set_close_on_exec toclose in
match fork() with
0 -> begin try
dup2 input stdin; close input;
dup2 output stdout; close output;
dup2 error stderr; close error;
if not cloexec then List.iter close toclose;
execve "/bin/sh" [| "/bin/sh"; "-c"; cmd |] env
with _ -> sys_exit 127
end
| id -> Hashtbl.add popen_processes proc id
let open_process_full cmd env =
let (in_read, in_write) = pipe() in
let fds_to_close = ref [in_read;in_write] in
try
let (out_read, out_write) = pipe() in
fds_to_close := out_read::out_write:: !fds_to_close;
let (err_read, err_write) = pipe() in
fds_to_close := err_read::err_write:: !fds_to_close;
let inchan = in_channel_of_descr in_read in
let outchan = out_channel_of_descr out_write in
let errchan = in_channel_of_descr err_read in
open_proc_full cmd env (Process_full(inchan, outchan, errchan))
out_read in_write err_write [in_read; out_write; err_read];
close out_read;
close in_write;
close err_write;
(inchan, outchan, errchan)
with e ->
List.iter close !fds_to_close;
raise e
let find_proc_id fun_name proc =
try
let pid = Hashtbl.find popen_processes proc in
Hashtbl.remove popen_processes proc;
pid
with Not_found ->
raise(Unix_error(EBADF, fun_name, ""))
let close_process_in inchan =
let pid = find_proc_id "close_process_in" (Process_in inchan) in
close_in inchan;
snd(waitpid_non_intr pid)
let close_process_out outchan =
let pid = find_proc_id "close_process_out" (Process_out outchan) in
close_out outchan;
snd(waitpid_non_intr pid)
let close_process (inchan, outchan) =
let pid = find_proc_id "close_process" (Process(inchan, outchan)) in
close_in inchan;
begin try close_out outchan with Sys_error _ -> () end;
snd(waitpid_non_intr pid)
let close_process_full (inchan, outchan, errchan) =
let pid =
find_proc_id "close_process_full"
(Process_full(inchan, outchan, errchan)) in
close_in inchan;
begin try close_out outchan with Sys_error _ -> () end;
close_in errchan;
snd(waitpid_non_intr pid)
(* High-level network functions *)
let open_connection sockaddr =
let sock =
socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
try
connect sock sockaddr;
ignore(try_set_close_on_exec sock);
(in_channel_of_descr sock, out_channel_of_descr sock)
with exn ->
close sock; raise exn
let shutdown_connection inchan =
shutdown (descr_of_in_channel inchan) SHUTDOWN_SEND
let rec accept_non_intr s =
try accept s
with Unix_error (EINTR, _, _) -> accept_non_intr s
let establish_server server_fun sockaddr =
let sock =
socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
setsockopt sock SO_REUSEADDR true;
bind sock sockaddr;
listen sock 5;
while true do
let (s, caller) = accept_non_intr sock in
The " double fork " trick , the process which calls server_fun will not
leave a zombie process
leave a zombie process *)
match fork() with
0 -> if fork() <> 0 then sys_exit 0;
(* The son exits, the grandson works *)
close sock;
ignore(try_set_close_on_exec s);
let inchan = in_channel_of_descr s in
let outchan = out_channel_of_descr s in
server_fun inchan outchan;
Do not close inchan nor outchan , as the server_fun could
have done it already , and we are about to exit anyway
( PR#3794 )
have done it already, and we are about to exit anyway
(PR#3794) *)
exit 0
| id -> close s; ignore(waitpid_non_intr id) (* Reclaim the son *)
done
| null | https://raw.githubusercontent.com/ocsigen/ocaml-eliom/497c6707f477cb3086dc6d8124384e74a8c379ae/otherlibs/unix/unix.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Period
Current value of the timer
Determine socket types and port numbers
Determine IP addresses
Cross-product of addresses and ports
why not?
High-level process management (system, popen)
High-level network functions
The son exits, the grandson works
Reclaim the son | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
type error =
E2BIG
| EACCES
| EAGAIN
| EBADF
| EBUSY
| ECHILD
| EDEADLK
| EDOM
| EEXIST
| EFAULT
| EFBIG
| EINTR
| EINVAL
| EIO
| EISDIR
| EMFILE
| EMLINK
| ENAMETOOLONG
| ENFILE
| ENODEV
| ENOENT
| ENOEXEC
| ENOLCK
| ENOMEM
| ENOSPC
| ENOSYS
| ENOTDIR
| ENOTEMPTY
| ENOTTY
| ENXIO
| EPERM
| EPIPE
| ERANGE
| EROFS
| ESPIPE
| ESRCH
| EXDEV
| EWOULDBLOCK
| EINPROGRESS
| EALREADY
| ENOTSOCK
| EDESTADDRREQ
| EMSGSIZE
| EPROTOTYPE
| ENOPROTOOPT
| EPROTONOSUPPORT
| ESOCKTNOSUPPORT
| EOPNOTSUPP
| EPFNOSUPPORT
| EAFNOSUPPORT
| EADDRINUSE
| EADDRNOTAVAIL
| ENETDOWN
| ENETUNREACH
| ENETRESET
| ECONNABORTED
| ECONNRESET
| ENOBUFS
| EISCONN
| ENOTCONN
| ESHUTDOWN
| ETOOMANYREFS
| ETIMEDOUT
| ECONNREFUSED
| EHOSTDOWN
| EHOSTUNREACH
| ELOOP
| EOVERFLOW
| EUNKNOWNERR of int
exception Unix_error of error * string * string
let _ = Callback.register_exception "Unix.Unix_error"
(Unix_error(E2BIG, "", ""))
external error_message : error -> string = "unix_error_message"
let () =
Printexc.register_printer
(function
| Unix_error (e, s, s') ->
let msg = match e with
| E2BIG -> "E2BIG"
| EACCES -> "EACCES"
| EAGAIN -> "EAGAIN"
| EBADF -> "EBADF"
| EBUSY -> "EBUSY"
| ECHILD -> "ECHILD"
| EDEADLK -> "EDEADLK"
| EDOM -> "EDOM"
| EEXIST -> "EEXIST"
| EFAULT -> "EFAULT"
| EFBIG -> "EFBIG"
| EINTR -> "EINTR"
| EINVAL -> "EINVAL"
| EIO -> "EIO"
| EISDIR -> "EISDIR"
| EMFILE -> "EMFILE"
| EMLINK -> "EMLINK"
| ENAMETOOLONG -> "ENAMETOOLONG"
| ENFILE -> "ENFILE"
| ENODEV -> "ENODEV"
| ENOENT -> "ENOENT"
| ENOEXEC -> "ENOEXEC"
| ENOLCK -> "ENOLCK"
| ENOMEM -> "ENOMEM"
| ENOSPC -> "ENOSPC"
| ENOSYS -> "ENOSYS"
| ENOTDIR -> "ENOTDIR"
| ENOTEMPTY -> "ENOTEMPTY"
| ENOTTY -> "ENOTTY"
| ENXIO -> "ENXIO"
| EPERM -> "EPERM"
| EPIPE -> "EPIPE"
| ERANGE -> "ERANGE"
| EROFS -> "EROFS"
| ESPIPE -> "ESPIPE"
| ESRCH -> "ESRCH"
| EXDEV -> "EXDEV"
| EWOULDBLOCK -> "EWOULDBLOCK"
| EINPROGRESS -> "EINPROGRESS"
| EALREADY -> "EALREADY"
| ENOTSOCK -> "ENOTSOCK"
| EDESTADDRREQ -> "EDESTADDRREQ"
| EMSGSIZE -> "EMSGSIZE"
| EPROTOTYPE -> "EPROTOTYPE"
| ENOPROTOOPT -> "ENOPROTOOPT"
| EPROTONOSUPPORT -> "EPROTONOSUPPORT"
| ESOCKTNOSUPPORT -> "ESOCKTNOSUPPORT"
| EOPNOTSUPP -> "EOPNOTSUPP"
| EPFNOSUPPORT -> "EPFNOSUPPORT"
| EAFNOSUPPORT -> "EAFNOSUPPORT"
| EADDRINUSE -> "EADDRINUSE"
| EADDRNOTAVAIL -> "EADDRNOTAVAIL"
| ENETDOWN -> "ENETDOWN"
| ENETUNREACH -> "ENETUNREACH"
| ENETRESET -> "ENETRESET"
| ECONNABORTED -> "ECONNABORTED"
| ECONNRESET -> "ECONNRESET"
| ENOBUFS -> "ENOBUFS"
| EISCONN -> "EISCONN"
| ENOTCONN -> "ENOTCONN"
| ESHUTDOWN -> "ESHUTDOWN"
| ETOOMANYREFS -> "ETOOMANYREFS"
| ETIMEDOUT -> "ETIMEDOUT"
| ECONNREFUSED -> "ECONNREFUSED"
| EHOSTDOWN -> "EHOSTDOWN"
| EHOSTUNREACH -> "EHOSTUNREACH"
| ELOOP -> "ELOOP"
| EOVERFLOW -> "EOVERFLOW"
| EUNKNOWNERR x -> Printf.sprintf "EUNKNOWNERR %d" x in
Some (Printf.sprintf "Unix.Unix_error(Unix.%s, %S, %S)" msg s s')
| _ -> None)
let handle_unix_error f arg =
try
f arg
with Unix_error(err, fun_name, arg) ->
prerr_string Sys.argv.(0);
prerr_string ": \"";
prerr_string fun_name;
prerr_string "\" failed";
if String.length arg > 0 then begin
prerr_string " on \"";
prerr_string arg;
prerr_string "\""
end;
prerr_string ": ";
prerr_endline (error_message err);
exit 2
external environment : unit -> string array = "unix_environment"
external getenv: string -> string = "caml_sys_getenv"
external putenv: string -> string -> unit = "unix_putenv"
type process_status =
WEXITED of int
| WSIGNALED of int
| WSTOPPED of int
type wait_flag =
WNOHANG
| WUNTRACED
external execv : string -> string array -> 'a = "unix_execv"
external execve : string -> string array -> string array -> 'a = "unix_execve"
external execvp : string -> string array -> 'a = "unix_execvp"
external execvpe : string -> string array -> string array -> 'a = "unix_execvpe"
external fork : unit -> int = "unix_fork"
external wait : unit -> int * process_status = "unix_wait"
external waitpid : wait_flag list -> int -> int * process_status
= "unix_waitpid"
external getpid : unit -> int = "unix_getpid"
external getppid : unit -> int = "unix_getppid"
external nice : int -> int = "unix_nice"
type file_descr = int
let stdin = 0
let stdout = 1
let stderr = 2
type open_flag =
O_RDONLY
| O_WRONLY
| O_RDWR
| O_NONBLOCK
| O_APPEND
| O_CREAT
| O_TRUNC
| O_EXCL
| O_NOCTTY
| O_DSYNC
| O_SYNC
| O_RSYNC
| O_SHARE_DELETE
| O_CLOEXEC
type file_perm = int
external openfile : string -> open_flag list -> file_perm -> file_descr
= "unix_open"
external close : file_descr -> unit = "unix_close"
external unsafe_read : file_descr -> bytes -> int -> int -> int
= "unix_read"
external unsafe_write : file_descr -> bytes -> int -> int -> int = "unix_write"
external unsafe_single_write : file_descr -> bytes -> int -> int -> int
= "unix_single_write"
let read fd buf ofs len =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "Unix.read"
else unsafe_read fd buf ofs len
let write fd buf ofs len =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "Unix.write"
else unsafe_write fd buf ofs len
write misbehaves because it attempts to write all data by making repeated
calls to the Unix write function ( see comment in write.c and unix.mli ) .
single_write fixes this by never calling write twice .
calls to the Unix write function (see comment in write.c and unix.mli).
single_write fixes this by never calling write twice. *)
let single_write fd buf ofs len =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "Unix.single_write"
else unsafe_single_write fd buf ofs len
let write_substring fd buf ofs len =
write fd (Bytes.unsafe_of_string buf) ofs len
let single_write_substring fd buf ofs len =
single_write fd (Bytes.unsafe_of_string buf) ofs len
external in_channel_of_descr : file_descr -> in_channel
= "caml_ml_open_descriptor_in"
external out_channel_of_descr : file_descr -> out_channel
= "caml_ml_open_descriptor_out"
external descr_of_in_channel : in_channel -> file_descr
= "caml_channel_descriptor"
external descr_of_out_channel : out_channel -> file_descr
= "caml_channel_descriptor"
type seek_command =
SEEK_SET
| SEEK_CUR
| SEEK_END
external lseek : file_descr -> int -> seek_command -> int = "unix_lseek"
external truncate : string -> int -> unit = "unix_truncate"
external ftruncate : file_descr -> int -> unit = "unix_ftruncate"
type file_kind =
S_REG
| S_DIR
| S_CHR
| S_BLK
| S_LNK
| S_FIFO
| S_SOCK
type stats =
{ st_dev : int;
st_ino : int;
st_kind : file_kind;
st_perm : file_perm;
st_nlink : int;
st_uid : int;
st_gid : int;
st_rdev : int;
st_size : int;
st_atime : float;
st_mtime : float;
st_ctime : float }
external stat : string -> stats = "unix_stat"
external lstat : string -> stats = "unix_lstat"
external fstat : file_descr -> stats = "unix_fstat"
external isatty : file_descr -> bool = "unix_isatty"
external unlink : string -> unit = "unix_unlink"
external rename : string -> string -> unit = "unix_rename"
external link : string -> string -> unit = "unix_link"
module LargeFile =
struct
external lseek : file_descr -> int64 -> seek_command -> int64
= "unix_lseek_64"
external truncate : string -> int64 -> unit = "unix_truncate_64"
external ftruncate : file_descr -> int64 -> unit = "unix_ftruncate_64"
type stats =
{ st_dev : int;
st_ino : int;
st_kind : file_kind;
st_perm : file_perm;
st_nlink : int;
st_uid : int;
st_gid : int;
st_rdev : int;
st_size : int64;
st_atime : float;
st_mtime : float;
st_ctime : float;
}
external stat : string -> stats = "unix_stat_64"
external lstat : string -> stats = "unix_lstat_64"
external fstat : file_descr -> stats = "unix_fstat_64"
end
type access_permission =
R_OK
| W_OK
| X_OK
| F_OK
external chmod : string -> file_perm -> unit = "unix_chmod"
external fchmod : file_descr -> file_perm -> unit = "unix_fchmod"
external chown : string -> int -> int -> unit = "unix_chown"
external fchown : file_descr -> int -> int -> unit = "unix_fchown"
external umask : int -> int = "unix_umask"
external access : string -> access_permission list -> unit = "unix_access"
external dup : file_descr -> file_descr = "unix_dup"
external dup2 : file_descr -> file_descr -> unit = "unix_dup2"
external set_nonblock : file_descr -> unit = "unix_set_nonblock"
external clear_nonblock : file_descr -> unit = "unix_clear_nonblock"
external set_close_on_exec : file_descr -> unit = "unix_set_close_on_exec"
external clear_close_on_exec : file_descr -> unit = "unix_clear_close_on_exec"
FD_CLOEXEC should be supported on all Unix systems these days ,
but just in case ...
but just in case... *)
let try_set_close_on_exec fd =
try set_close_on_exec fd; true with Invalid_argument _ -> false
external mkdir : string -> file_perm -> unit = "unix_mkdir"
external rmdir : string -> unit = "unix_rmdir"
external chdir : string -> unit = "unix_chdir"
external getcwd : unit -> string = "unix_getcwd"
external chroot : string -> unit = "unix_chroot"
type dir_handle
external opendir : string -> dir_handle = "unix_opendir"
external readdir : dir_handle -> string = "unix_readdir"
external rewinddir : dir_handle -> unit = "unix_rewinddir"
external closedir : dir_handle -> unit = "unix_closedir"
external pipe : unit -> file_descr * file_descr = "unix_pipe"
external symlink : ?to_dir:bool -> string -> string -> unit = "unix_symlink"
external has_symlink : unit -> bool = "unix_has_symlink"
external readlink : string -> string = "unix_readlink"
external mkfifo : string -> file_perm -> unit = "unix_mkfifo"
external select :
file_descr list -> file_descr list -> file_descr list -> float ->
file_descr list * file_descr list * file_descr list = "unix_select"
type lock_command =
F_ULOCK
| F_LOCK
| F_TLOCK
| F_TEST
| F_RLOCK
| F_TRLOCK
external lockf : file_descr -> lock_command -> int -> unit = "unix_lockf"
external kill : int -> int -> unit = "unix_kill"
type sigprocmask_command = SIG_SETMASK | SIG_BLOCK | SIG_UNBLOCK
external sigprocmask: sigprocmask_command -> int list -> int list
= "unix_sigprocmask"
external sigpending: unit -> int list = "unix_sigpending"
external sigsuspend: int list -> unit = "unix_sigsuspend"
let pause() =
let sigs = sigprocmask SIG_BLOCK [] in sigsuspend sigs
type process_times =
{ tms_utime : float;
tms_stime : float;
tms_cutime : float;
tms_cstime : float }
type tm =
{ tm_sec : int;
tm_min : int;
tm_hour : int;
tm_mday : int;
tm_mon : int;
tm_year : int;
tm_wday : int;
tm_yday : int;
tm_isdst : bool }
external time : unit -> float = "unix_time"
external gettimeofday : unit -> float = "unix_gettimeofday"
external gmtime : float -> tm = "unix_gmtime"
external localtime : float -> tm = "unix_localtime"
external mktime : tm -> float * tm = "unix_mktime"
external alarm : int -> int = "unix_alarm"
external sleepf : float -> unit = "unix_sleep"
let sleep duration = sleepf (float duration)
external times : unit -> process_times = "unix_times"
external utimes : string -> float -> float -> unit = "unix_utimes"
type interval_timer =
ITIMER_REAL
| ITIMER_VIRTUAL
| ITIMER_PROF
type interval_timer_status =
external getitimer: interval_timer -> interval_timer_status = "unix_getitimer"
external setitimer:
interval_timer -> interval_timer_status -> interval_timer_status
= "unix_setitimer"
external getuid : unit -> int = "unix_getuid"
external geteuid : unit -> int = "unix_geteuid"
external setuid : int -> unit = "unix_setuid"
external getgid : unit -> int = "unix_getgid"
external getegid : unit -> int = "unix_getegid"
external setgid : int -> unit = "unix_setgid"
external getgroups : unit -> int array = "unix_getgroups"
external setgroups : int array -> unit = "unix_setgroups"
external initgroups : string -> int -> unit = "unix_initgroups"
type passwd_entry =
{ pw_name : string;
pw_passwd : string;
pw_uid : int;
pw_gid : int;
pw_gecos : string;
pw_dir : string;
pw_shell : string }
type group_entry =
{ gr_name : string;
gr_passwd : string;
gr_gid : int;
gr_mem : string array }
external getlogin : unit -> string = "unix_getlogin"
external getpwnam : string -> passwd_entry = "unix_getpwnam"
external getgrnam : string -> group_entry = "unix_getgrnam"
external getpwuid : int -> passwd_entry = "unix_getpwuid"
external getgrgid : int -> group_entry = "unix_getgrgid"
type inet_addr = string
let is_inet6_addr s = String.length s = 16
external inet_addr_of_string : string -> inet_addr
= "unix_inet_addr_of_string"
external string_of_inet_addr : inet_addr -> string
= "unix_string_of_inet_addr"
let inet_addr_any = inet_addr_of_string "0.0.0.0"
let inet_addr_loopback = inet_addr_of_string "127.0.0.1"
let inet6_addr_any =
try inet_addr_of_string "::" with Failure _ -> inet_addr_any
let inet6_addr_loopback =
try inet_addr_of_string "::1" with Failure _ -> inet_addr_loopback
type socket_domain =
PF_UNIX
| PF_INET
| PF_INET6
type socket_type =
SOCK_STREAM
| SOCK_DGRAM
| SOCK_RAW
| SOCK_SEQPACKET
type sockaddr =
ADDR_UNIX of string
| ADDR_INET of inet_addr * int
let domain_of_sockaddr = function
ADDR_UNIX _ -> PF_UNIX
| ADDR_INET(a, _) -> if is_inet6_addr a then PF_INET6 else PF_INET
type shutdown_command =
SHUTDOWN_RECEIVE
| SHUTDOWN_SEND
| SHUTDOWN_ALL
type msg_flag =
MSG_OOB
| MSG_DONTROUTE
| MSG_PEEK
external socket : socket_domain -> socket_type -> int -> file_descr
= "unix_socket"
external socketpair :
socket_domain -> socket_type -> int -> file_descr * file_descr
= "unix_socketpair"
external accept : file_descr -> file_descr * sockaddr = "unix_accept"
external bind : file_descr -> sockaddr -> unit = "unix_bind"
external connect : file_descr -> sockaddr -> unit = "unix_connect"
external listen : file_descr -> int -> unit = "unix_listen"
external shutdown : file_descr -> shutdown_command -> unit = "unix_shutdown"
external getsockname : file_descr -> sockaddr = "unix_getsockname"
external getpeername : file_descr -> sockaddr = "unix_getpeername"
external unsafe_recv :
file_descr -> bytes -> int -> int -> msg_flag list -> int
= "unix_recv"
external unsafe_recvfrom :
file_descr -> bytes -> int -> int -> msg_flag list -> int * sockaddr
= "unix_recvfrom"
external unsafe_send :
file_descr -> bytes -> int -> int -> msg_flag list -> int
= "unix_send"
external unsafe_sendto :
file_descr -> bytes -> int -> int -> msg_flag list -> sockaddr -> int
= "unix_sendto" "unix_sendto_native"
let recv fd buf ofs len flags =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "Unix.recv"
else unsafe_recv fd buf ofs len flags
let recvfrom fd buf ofs len flags =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "Unix.recvfrom"
else unsafe_recvfrom fd buf ofs len flags
let send fd buf ofs len flags =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "Unix.send"
else unsafe_send fd buf ofs len flags
let sendto fd buf ofs len flags addr =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "Unix.sendto"
else unsafe_sendto fd buf ofs len flags addr
let send_substring fd buf ofs len flags =
send fd (Bytes.unsafe_of_string buf) ofs len flags
let sendto_substring fd buf ofs len flags addr =
sendto fd (Bytes.unsafe_of_string buf) ofs len flags addr
type socket_bool_option =
SO_DEBUG
| SO_BROADCAST
| SO_REUSEADDR
| SO_KEEPALIVE
| SO_DONTROUTE
| SO_OOBINLINE
| SO_ACCEPTCONN
| TCP_NODELAY
| IPV6_ONLY
type socket_int_option =
SO_SNDBUF
| SO_RCVBUF
| SO_ERROR
| SO_TYPE
| SO_RCVLOWAT
| SO_SNDLOWAT
type socket_optint_option = SO_LINGER
type socket_float_option =
SO_RCVTIMEO
| SO_SNDTIMEO
type socket_error_option = SO_ERROR
module SO: sig
type ('opt, 'v) t
val bool: (socket_bool_option, bool) t
val int: (socket_int_option, int) t
val optint: (socket_optint_option, int option) t
val float: (socket_float_option, float) t
val error: (socket_error_option, error option) t
val get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
val set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
end = struct
type ('opt, 'v) t = int
let bool = 0
let int = 1
let optint = 2
let float = 3
let error = 4
external get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
= "unix_getsockopt"
external set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
= "unix_setsockopt"
end
let getsockopt fd opt = SO.get SO.bool fd opt
let setsockopt fd opt v = SO.set SO.bool fd opt v
let getsockopt_int fd opt = SO.get SO.int fd opt
let setsockopt_int fd opt v = SO.set SO.int fd opt v
let getsockopt_optint fd opt = SO.get SO.optint fd opt
let setsockopt_optint fd opt v = SO.set SO.optint fd opt v
let getsockopt_float fd opt = SO.get SO.float fd opt
let setsockopt_float fd opt v = SO.set SO.float fd opt v
let getsockopt_error fd = SO.get SO.error fd SO_ERROR
type host_entry =
{ h_name : string;
h_aliases : string array;
h_addrtype : socket_domain;
h_addr_list : inet_addr array }
type protocol_entry =
{ p_name : string;
p_aliases : string array;
p_proto : int }
type service_entry =
{ s_name : string;
s_aliases : string array;
s_port : int;
s_proto : string }
external gethostname : unit -> string = "unix_gethostname"
external gethostbyname : string -> host_entry = "unix_gethostbyname"
external gethostbyaddr : inet_addr -> host_entry = "unix_gethostbyaddr"
external getprotobyname : string -> protocol_entry
= "unix_getprotobyname"
external getprotobynumber : int -> protocol_entry
= "unix_getprotobynumber"
external getservbyname : string -> string -> service_entry
= "unix_getservbyname"
external getservbyport : int -> string -> service_entry
= "unix_getservbyport"
type addr_info =
{ ai_family : socket_domain;
ai_socktype : socket_type;
ai_protocol : int;
ai_addr : sockaddr;
ai_canonname : string }
type getaddrinfo_option =
AI_FAMILY of socket_domain
| AI_SOCKTYPE of socket_type
| AI_PROTOCOL of int
| AI_NUMERICHOST
| AI_CANONNAME
| AI_PASSIVE
external getaddrinfo_system
: string -> string -> getaddrinfo_option list -> addr_info list
= "unix_getaddrinfo"
let getaddrinfo_emulation node service opts =
Parse options
let opt_socktype = ref None
and opt_protocol = ref 0
and opt_passive = ref false in
List.iter
(function AI_SOCKTYPE s -> opt_socktype := Some s
| AI_PROTOCOL p -> opt_protocol := p
| AI_PASSIVE -> opt_passive := true
| _ -> ())
opts;
let get_port ty kind =
if service = "" then [ty, 0] else
try
[ty, int_of_string service]
with Failure _ ->
try
[ty, (getservbyname service kind).s_port]
with Not_found -> []
in
let ports =
match !opt_socktype with
| None ->
get_port SOCK_STREAM "tcp" @ get_port SOCK_DGRAM "udp"
| Some SOCK_STREAM ->
get_port SOCK_STREAM "tcp"
| Some SOCK_DGRAM ->
get_port SOCK_DGRAM "udp"
| Some ty ->
if service = "" then [ty, 0] else [] in
let addresses =
if node = "" then
if List.mem AI_PASSIVE opts
then [inet_addr_any, "0.0.0.0"]
else [inet_addr_loopback, "127.0.0.1"]
else
try
[inet_addr_of_string node, node]
with Failure _ ->
try
let he = gethostbyname node in
List.map
(fun a -> (a, he.h_name))
(Array.to_list he.h_addr_list)
with Not_found ->
[] in
List.flatten
(List.map
(fun (ty, port) ->
List.map
(fun (addr, name) ->
{ ai_family = PF_INET;
ai_socktype = ty;
ai_protocol = !opt_protocol;
ai_addr = ADDR_INET(addr, port);
ai_canonname = name })
addresses)
ports)
let getaddrinfo node service opts =
try
List.rev(getaddrinfo_system node service opts)
with Invalid_argument _ ->
getaddrinfo_emulation node service opts
type name_info =
{ ni_hostname : string;
ni_service : string }
type getnameinfo_option =
NI_NOFQDN
| NI_NUMERICHOST
| NI_NAMEREQD
| NI_NUMERICSERV
| NI_DGRAM
external getnameinfo_system
: sockaddr -> getnameinfo_option list -> name_info
= "unix_getnameinfo"
let getnameinfo_emulation addr opts =
match addr with
| ADDR_UNIX f ->
| ADDR_INET(a, p) ->
let hostname =
try
if List.mem NI_NUMERICHOST opts then raise Not_found;
(gethostbyaddr a).h_name
with Not_found ->
if List.mem NI_NAMEREQD opts then raise Not_found;
string_of_inet_addr a in
let service =
try
if List.mem NI_NUMERICSERV opts then raise Not_found;
let kind = if List.mem NI_DGRAM opts then "udp" else "tcp" in
(getservbyport p kind).s_name
with Not_found ->
string_of_int p in
{ ni_hostname = hostname; ni_service = service }
let getnameinfo addr opts =
try
getnameinfo_system addr opts
with Invalid_argument _ ->
getnameinfo_emulation addr opts
type terminal_io = {
mutable c_ignbrk: bool;
mutable c_brkint: bool;
mutable c_ignpar: bool;
mutable c_parmrk: bool;
mutable c_inpck: bool;
mutable c_istrip: bool;
mutable c_inlcr: bool;
mutable c_igncr: bool;
mutable c_icrnl: bool;
mutable c_ixon: bool;
mutable c_ixoff: bool;
mutable c_opost: bool;
mutable c_obaud: int;
mutable c_ibaud: int;
mutable c_csize: int;
mutable c_cstopb: int;
mutable c_cread: bool;
mutable c_parenb: bool;
mutable c_parodd: bool;
mutable c_hupcl: bool;
mutable c_clocal: bool;
mutable c_isig: bool;
mutable c_icanon: bool;
mutable c_noflsh: bool;
mutable c_echo: bool;
mutable c_echoe: bool;
mutable c_echok: bool;
mutable c_echonl: bool;
mutable c_vintr: char;
mutable c_vquit: char;
mutable c_verase: char;
mutable c_vkill: char;
mutable c_veof: char;
mutable c_veol: char;
mutable c_vmin: int;
mutable c_vtime: int;
mutable c_vstart: char;
mutable c_vstop: char
}
external tcgetattr: file_descr -> terminal_io = "unix_tcgetattr"
type setattr_when = TCSANOW | TCSADRAIN | TCSAFLUSH
external tcsetattr: file_descr -> setattr_when -> terminal_io -> unit
= "unix_tcsetattr"
external tcsendbreak: file_descr -> int -> unit = "unix_tcsendbreak"
external tcdrain: file_descr -> unit = "unix_tcdrain"
type flush_queue = TCIFLUSH | TCOFLUSH | TCIOFLUSH
external tcflush: file_descr -> flush_queue -> unit = "unix_tcflush"
type flow_action = TCOOFF | TCOON | TCIOFF | TCION
external tcflow: file_descr -> flow_action -> unit = "unix_tcflow"
external setsid : unit -> int = "unix_setsid"
let rec waitpid_non_intr pid =
try waitpid [] pid
with Unix_error (EINTR, _, _) -> waitpid_non_intr pid
external sys_exit : int -> 'a = "caml_sys_exit"
let system cmd =
match fork() with
0 -> begin try
execv "/bin/sh" [| "/bin/sh"; "-c"; cmd |]
with _ ->
sys_exit 127
end
| id -> snd(waitpid_non_intr id)
let rec safe_dup fd =
let new_fd = dup fd in
if new_fd >= 3 then
new_fd
else begin
let res = safe_dup fd in
close new_fd;
res
end
let safe_close fd =
try close fd with Unix_error(_,_,_) -> ()
let perform_redirections new_stdin new_stdout new_stderr =
let newnewstdin = safe_dup new_stdin in
let newnewstdout = safe_dup new_stdout in
let newnewstderr = safe_dup new_stderr in
safe_close new_stdin;
safe_close new_stdout;
safe_close new_stderr;
dup2 newnewstdin stdin; close newnewstdin;
dup2 newnewstdout stdout; close newnewstdout;
dup2 newnewstderr stderr; close newnewstderr
let create_process cmd args new_stdin new_stdout new_stderr =
match fork() with
0 ->
begin try
perform_redirections new_stdin new_stdout new_stderr;
execvp cmd args
with _ ->
sys_exit 127
end
| id -> id
let create_process_env cmd args env new_stdin new_stdout new_stderr =
match fork() with
0 ->
begin try
perform_redirections new_stdin new_stdout new_stderr;
execvpe cmd args env
with _ ->
sys_exit 127
end
| id -> id
type popen_process =
Process of in_channel * out_channel
| Process_in of in_channel
| Process_out of out_channel
| Process_full of in_channel * out_channel * in_channel
let popen_processes = (Hashtbl.create 7 : (popen_process, int) Hashtbl.t)
let open_proc cmd proc input output toclose =
let cloexec = List.for_all try_set_close_on_exec toclose in
match fork() with
0 -> begin try
if input <> stdin then begin dup2 input stdin; close input end;
if output <> stdout then begin dup2 output stdout; close output end;
if not cloexec then List.iter close toclose;
execv "/bin/sh" [| "/bin/sh"; "-c"; cmd |]
with _ -> sys_exit 127
end
| id -> Hashtbl.add popen_processes proc id
let open_process_in cmd =
let (in_read, in_write) = pipe() in
let inchan = in_channel_of_descr in_read in
begin
try
open_proc cmd (Process_in inchan) stdin in_write [in_read];
with e ->
close_in inchan;
close in_write;
raise e
end;
close in_write;
inchan
let open_process_out cmd =
let (out_read, out_write) = pipe() in
let outchan = out_channel_of_descr out_write in
begin
try
open_proc cmd (Process_out outchan) out_read stdout [out_write];
with e ->
close_out outchan;
close out_read;
raise e
end;
close out_read;
outchan
let open_process cmd =
let (in_read, in_write) = pipe() in
let fds_to_close = ref [in_read;in_write] in
try
let (out_read, out_write) = pipe() in
fds_to_close := [in_read;in_write;out_read;out_write];
let inchan = in_channel_of_descr in_read in
let outchan = out_channel_of_descr out_write in
open_proc cmd (Process(inchan, outchan)) out_read in_write
[in_read; out_write];
close out_read;
close in_write;
(inchan, outchan)
with e ->
List.iter close !fds_to_close;
raise e
let open_proc_full cmd env proc input output error toclose =
let cloexec = List.for_all try_set_close_on_exec toclose in
match fork() with
0 -> begin try
dup2 input stdin; close input;
dup2 output stdout; close output;
dup2 error stderr; close error;
if not cloexec then List.iter close toclose;
execve "/bin/sh" [| "/bin/sh"; "-c"; cmd |] env
with _ -> sys_exit 127
end
| id -> Hashtbl.add popen_processes proc id
let open_process_full cmd env =
let (in_read, in_write) = pipe() in
let fds_to_close = ref [in_read;in_write] in
try
let (out_read, out_write) = pipe() in
fds_to_close := out_read::out_write:: !fds_to_close;
let (err_read, err_write) = pipe() in
fds_to_close := err_read::err_write:: !fds_to_close;
let inchan = in_channel_of_descr in_read in
let outchan = out_channel_of_descr out_write in
let errchan = in_channel_of_descr err_read in
open_proc_full cmd env (Process_full(inchan, outchan, errchan))
out_read in_write err_write [in_read; out_write; err_read];
close out_read;
close in_write;
close err_write;
(inchan, outchan, errchan)
with e ->
List.iter close !fds_to_close;
raise e
let find_proc_id fun_name proc =
try
let pid = Hashtbl.find popen_processes proc in
Hashtbl.remove popen_processes proc;
pid
with Not_found ->
raise(Unix_error(EBADF, fun_name, ""))
let close_process_in inchan =
let pid = find_proc_id "close_process_in" (Process_in inchan) in
close_in inchan;
snd(waitpid_non_intr pid)
let close_process_out outchan =
let pid = find_proc_id "close_process_out" (Process_out outchan) in
close_out outchan;
snd(waitpid_non_intr pid)
let close_process (inchan, outchan) =
let pid = find_proc_id "close_process" (Process(inchan, outchan)) in
close_in inchan;
begin try close_out outchan with Sys_error _ -> () end;
snd(waitpid_non_intr pid)
let close_process_full (inchan, outchan, errchan) =
let pid =
find_proc_id "close_process_full"
(Process_full(inchan, outchan, errchan)) in
close_in inchan;
begin try close_out outchan with Sys_error _ -> () end;
close_in errchan;
snd(waitpid_non_intr pid)
let open_connection sockaddr =
let sock =
socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
try
connect sock sockaddr;
ignore(try_set_close_on_exec sock);
(in_channel_of_descr sock, out_channel_of_descr sock)
with exn ->
close sock; raise exn
let shutdown_connection inchan =
shutdown (descr_of_in_channel inchan) SHUTDOWN_SEND
let rec accept_non_intr s =
try accept s
with Unix_error (EINTR, _, _) -> accept_non_intr s
let establish_server server_fun sockaddr =
let sock =
socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
setsockopt sock SO_REUSEADDR true;
bind sock sockaddr;
listen sock 5;
while true do
let (s, caller) = accept_non_intr sock in
The " double fork " trick , the process which calls server_fun will not
leave a zombie process
leave a zombie process *)
match fork() with
0 -> if fork() <> 0 then sys_exit 0;
close sock;
ignore(try_set_close_on_exec s);
let inchan = in_channel_of_descr s in
let outchan = out_channel_of_descr s in
server_fun inchan outchan;
Do not close inchan nor outchan , as the server_fun could
have done it already , and we are about to exit anyway
( PR#3794 )
have done it already, and we are about to exit anyway
(PR#3794) *)
exit 0
done
|
d9bc771b415d75c6e3230133bb9decb90899f582623a241bc45411f54a909aa0 | ml4tp/tcoq | stm.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
let pr_err s = Printf.eprintf "%s] %s\n" (System.process_id ()) s; flush stderr
let prerr_endline s = if false then begin pr_err (s ()) end else ()
let prerr_debug s = if !Flags.debug then begin pr_err (s ()) end else ()
Opening ppvernac below aliases , see PR#185
let pp_to_richpp = Richpp.richpp_of_pp
let str_to_richpp = Richpp.richpp_of_string
open Vernacexpr
open CErrors
open Pp
open Names
open Util
open Ppvernac
open Vernac_classifier
open Feedback
module Hooks = struct
let process_error, process_error_hook = Hook.make ()
let interp, interp_hook = Hook.make ()
let with_fail, with_fail_hook = Hook.make ()
let state_computed, state_computed_hook = Hook.make
~default:(fun state_id ~in_cache ->
feedback ~id:(State state_id) Processed) ()
let state_ready, state_ready_hook = Hook.make
~default:(fun state_id -> ()) ()
let forward_feedback, forward_feedback_hook =
let m = Mutex.create () in
Hook.make ~default:(function
| { id = id; route; contents } ->
try Mutex.lock m; feedback ~id:id ~route contents; Mutex.unlock m
with e -> Mutex.unlock m; raise e) ()
let parse_error, parse_error_hook = Hook.make
~default:(fun id loc msg ->
feedback ~id (Message(Error, Some loc, pp_to_richpp msg))) ()
let execution_error, execution_error_hook = Hook.make
~default:(fun state_id loc msg ->
feedback ~id:(State state_id) (Message(Error, Some loc, pp_to_richpp msg))) ()
let unreachable_state, unreachable_state_hook = Hook.make
~default:(fun _ _ -> ()) ()
let tactic_being_run, tactic_being_run_hook = Hook.make
~default:(fun _ -> ()) ()
include Hook
enables : Hooks.(call foo args )
let call = get
let call_process_error_once =
let processed : unit Exninfo.t = Exninfo.make () in
fun (_, info as ei) ->
match Exninfo.get info processed with
| Some _ -> ei
| None ->
let e, info = call process_error ei in
let info = Exninfo.add info processed () in
e, info
end
(* During interactive use we cache more states so that Undoing is fast *)
let interactive () =
if !Flags.ide_slave || !Flags.print_emacs || not !Flags.batch_mode then `Yes
else `No
let async_proofs_workers_extra_env = ref [||]
type aast = {
verbose : bool;
loc : Loc.t;
indentation : int;
strlen : int;
mutable expr : vernac_expr; (* mutable: Proof using hinted by aux file *)
}
let pr_ast { expr; indentation } = int indentation ++ str " " ++ pr_vernac expr
let default_proof_mode () = Proof_global.get_default_proof_mode_name ()
(* Commands piercing opaque *)
let may_pierce_opaque = function
| { expr = VernacPrint _ } -> true
| { expr = VernacExtend (("Extraction",_), _) } -> true
| { expr = VernacExtend (("SeparateExtraction",_), _) } -> true
| { expr = VernacExtend (("ExtractionLibrary",_), _) } -> true
| { expr = VernacExtend (("RecursiveExtractionLibrary",_), _) } -> true
| { expr = VernacExtend (("ExtractionConstant",_), _) } -> true
| { expr = VernacExtend (("ExtractionInlinedConstant",_), _) } -> true
| { expr = VernacExtend (("ExtractionInductive",_), _) } -> true
| _ -> false
Wrapper for Vernacentries.interp to set the feedback i d
let vernac_interp ?proof id ?route { verbose; loc; expr } =
let rec internal_command = function
| VernacResetName _ | VernacResetInitial | VernacBack _
| VernacBackTo _ | VernacRestart | VernacUndo _ | VernacUndoTo _
| VernacBacktrack _ | VernacAbortAll | VernacAbort _ -> true
| VernacTime (_,e) | VernacTimeout (_,e) | VernacRedirect (_,(_,e)) -> internal_command e
| _ -> false in
if internal_command expr then begin
prerr_endline (fun () -> "ignoring " ^ Pp.string_of_ppcmds(pr_vernac expr))
end else begin
set_id_for_feedback ?route (State id);
Aux_file.record_in_aux_set_at loc;
prerr_endline (fun () -> "interpreting " ^ Pp.string_of_ppcmds(pr_vernac expr));
try Hooks.(call interp ?verbosely:(Some verbose) ?proof (loc, expr))
with e ->
let e = CErrors.push e in
iraise Hooks.(call_process_error_once e)
end
Wrapper for Vernac.parse_sentence to set the feedback i d
let indentation_of_string s =
let len = String.length s in
let rec aux n i precise =
if i >= len then 0, precise, len
else
match s.[i] with
| ' ' | '\t' -> aux (succ n) (succ i) precise
| '\n' | '\r' -> aux 0 (succ i) true
| _ -> n, precise, len in
aux 0 0 false
let vernac_parse ?(indlen_prev=fun() -> 0) ?newtip ?route eid s =
let feedback_id =
if Option.is_empty newtip then Edit eid
else State (Option.get newtip) in
let indentation, precise, strlen = indentation_of_string s in
let indentation =
if precise then indentation else indlen_prev () + indentation in
set_id_for_feedback ?route feedback_id;
let pa = Pcoq.Gram.parsable (Stream.of_string s) in
Flags.with_option Flags.we_are_parsing (fun () ->
try
match Pcoq.Gram.entry_parse Pcoq.main_entry pa with
| None -> raise (Invalid_argument "vernac_parse")
| Some (loc, ast) -> indentation, strlen, loc, ast
with e when CErrors.noncritical e ->
let (e, info) = CErrors.push e in
let loc = Option.default Loc.ghost (Loc.get_loc info) in
Hooks.(call parse_error feedback_id loc (iprint (e, info)));
iraise (e, info))
()
let pr_open_cur_subgoals () =
try Printer.pr_open_subgoals ()
with Proof_global.NoCurrentProof -> Pp.str ""
let update_global_env () =
if Proof_global.there_are_pending_proofs () then
Proof_global.update_global_env ()
module Vcs_ = Vcs.Make(Stateid.Self)
type future_proof = Proof_global.closed_proof_output Future.computation
type proof_mode = string
type depth = int
type cancel_switch = bool ref
type branch_type =
[ `Master
| `Proof of proof_mode * depth
| `Edit of
proof_mode * Stateid.t * Stateid.t * vernac_qed_type * Vcs_.Branch.t ]
(* TODO 8.7 : split commands and tactics, since this type is too messy now *)
type cmd_t = {
ctac : bool; (* is a tactic *)
ceff : bool; (* is a side-effecting command in the middle of a proof *)
cast : aast;
cids : Id.t list;
cblock : proof_block_name option;
cqueue : [ `MainQueue
| `TacQueue of solving_tac * anon_abstracting_tac * cancel_switch
| `QueryQueue of cancel_switch
| `SkipQueue ] }
type fork_t = aast * Vcs_.Branch.t * Vernacexpr.opacity_guarantee * Id.t list
type qed_t = {
qast : aast;
keep : vernac_qed_type;
mutable fproof : (future_proof * cancel_switch) option;
brname : Vcs_.Branch.t;
brinfo : branch_type Vcs_.branch_info
}
type seff_t = aast option
type alias_t = Stateid.t * aast
type transaction =
| Cmd of cmd_t
| Fork of fork_t
| Qed of qed_t
| Sideff of seff_t
| Alias of alias_t
| Noop
type step =
[ `Cmd of cmd_t
| `Fork of fork_t * Stateid.t option
| `Qed of qed_t * Stateid.t
| `Sideff of [ `Ast of aast * Stateid.t | `Id of Stateid.t ]
| `Alias of alias_t ]
type visit = { step : step; next : Stateid.t }
let mkTransTac cast cblock cqueue =
Cmd { ctac = true; cast; cblock; cqueue; cids = []; ceff = false }
let mkTransCmd cast cids ceff cqueue =
Cmd { ctac = false; cast; cblock = None; cqueue; cids; ceff }
(* Parts of the system state that are morally part of the proof state *)
let summary_pstate = [ Evarutil.meta_counter_summary_name;
Evd.evar_counter_summary_name;
"program-tcc-table" ]
type cached_state =
| Empty
| Error of Exninfo.iexn
| Valid of state
TODO : inline records in OCaml 4.03
summary
proof : Proof_global.state; (* proof state *)
is the state trimmed down ( )
}
type branch = Vcs_.Branch.t * branch_type Vcs_.branch_info
type backup = { mine : branch; others : branch list }
TODO : Make this record private to VCS
mutable n_reached : int; (* debug cache: how many times was computed *)
mutable n_goals : int; (* open goals: indentation *)
mutable state : cached_state; (* state value *)
mutable vcs_backup : 'vcs option * backup option;
}
let default_info () =
{ n_reached = 0; n_goals = 0; state = Empty; vcs_backup = None,None }
module DynBlockData : Dyn.S = Dyn.Make(struct end)
Clusters of nodes implemented as Dag properties . While Dag and impose
* no constraint on properties , here we impose boxes to be non overlapping .
* Such invariant makes sense for the current kinds of boxes ( proof blocks and
* entire proofs ) but may make no sense and dropped / refined in the future .
* Such invariant is useful to detect broken proof block detection code
* no constraint on properties, here we impose boxes to be non overlapping.
* Such invariant makes sense for the current kinds of boxes (proof blocks and
* entire proofs) but may make no sense and dropped/refined in the future.
* Such invariant is useful to detect broken proof block detection code *)
type box =
| ProofTask of pt
| ProofBlock of static_block_declaration * proof_block_name
TODO : inline records in OCaml 4.03
lemma : Stateid.t;
qed : Stateid.t;
}
and static_block_declaration = {
block_start : Stateid.t;
block_stop : Stateid.t;
dynamic_switch : Stateid.t;
carry_on_data : DynBlockData.t;
}
Functions that work on a Vcs with a specific branch type
module Vcs_aux : sig
val proof_nesting : (branch_type, 't,'i,'c) Vcs_.t -> int
val find_proof_at_depth :
(branch_type, 't, 'i,'c) Vcs_.t -> int ->
Vcs_.Branch.t * branch_type Vcs_.branch_info
exception Expired
val visit : (branch_type, transaction,'i,'c) Vcs_.t -> Vcs_.Dag.node -> visit
end = struct (* {{{ *)
let proof_nesting vcs =
List.fold_left max 0
(List.map_filter
(function
| { Vcs_.kind = `Proof (_,n) } -> Some n
| { Vcs_.kind = `Edit _ } -> Some 1
| _ -> None)
(List.map (Vcs_.get_branch vcs) (Vcs_.branches vcs)))
let find_proof_at_depth vcs pl =
try List.find (function
| _, { Vcs_.kind = `Proof(m, n) } -> Int.equal n pl
| _, { Vcs_.kind = `Edit _ } -> anomaly(Pp.str "find_proof_at_depth")
| _ -> false)
(List.map (fun h -> h, Vcs_.get_branch vcs h) (Vcs_.branches vcs))
with Not_found -> failwith "find_proof_at_depth"
exception Expired
let visit vcs id =
if Stateid.equal id Stateid.initial then
anomaly(Pp.str "Visiting the initial state id")
else if Stateid.equal id Stateid.dummy then
anomaly(Pp.str "Visiting the dummy state id")
else
try
match Vcs_.Dag.from_node (Vcs_.dag vcs) id with
| [n, Cmd x] -> { step = `Cmd x; next = n }
| [n, Alias x] -> { step = `Alias x; next = n }
| [n, Fork x] -> { step = `Fork (x,None); next = n }
| [n, Fork x; p, Noop] -> { step = `Fork (x,Some p); next = n }
| [p, Noop; n, Fork x] -> { step = `Fork (x,Some p); next = n }
| [n, Qed x; p, Noop]
| [p, Noop; n, Qed x] -> { step = `Qed (x,p); next = n }
| [n, Sideff None; p, Noop]
| [p, Noop; n, Sideff None]-> { step = `Sideff (`Id p); next = n }
| [n, Sideff (Some x); p, Noop]
| [p, Noop; n, Sideff (Some x)]-> { step = `Sideff(`Ast (x,p)); next = n }
| [n, Sideff (Some x)]-> {step = `Sideff(`Ast (x,Stateid.dummy)); next=n}
| _ -> anomaly (Pp.str ("Malformed VCS at node "^Stateid.to_string id))
with Not_found -> raise Expired
end (* }}} *)
(*************************** THE DOCUMENT *************************************)
(******************************************************************************)
Imperative wrap around VCS to obtain _ the _ VCS that is the
* representation of the document Coq is currently processing
* representation of the document Coq is currently processing *)
module VCS : sig
exception Expired
module Branch : (module type of Vcs_.Branch with type t = Vcs_.Branch.t)
type id = Stateid.t
type 'branch_type branch_info = 'branch_type Vcs_.branch_info = {
kind : [> `Master] as 'branch_type;
root : id;
pos : id;
}
type vcs = (branch_type, transaction, vcs state_info, box) Vcs_.t
val init : id -> unit
val current_branch : unit -> Branch.t
val checkout : Branch.t -> unit
val branches : unit -> Branch.t list
val get_branch : Branch.t -> branch_type branch_info
val get_branch_pos : Branch.t -> id
val new_node : ?id:Stateid.t -> unit -> id
val merge : id -> ours:transaction -> ?into:Branch.t -> Branch.t -> unit
val rewrite_merge : id -> ours:transaction -> at:id -> Branch.t -> unit
val delete_branch : Branch.t -> unit
val commit : id -> transaction -> unit
val mk_branch_name : aast -> Branch.t
val edit_branch : Branch.t
val branch : ?root:id -> ?pos:id -> Branch.t -> branch_type -> unit
val reset_branch : Branch.t -> id -> unit
val reachable : id -> Stateid.Set.t
val cur_tip : unit -> id
val get_info : id -> vcs state_info
val reached : id -> unit
val goals : id -> int -> unit
val set_state : id -> cached_state -> unit
val get_state : id -> cached_state
(* cuts from start -> stop, raising Expired if some nodes are not there *)
val slice : block_start:id -> block_stop:id -> vcs
val nodes_in_slice : block_start:id -> block_stop:id -> Stateid.t list
val create_proof_task_box : id list -> qed:id -> block_start:id -> unit
val create_proof_block : static_block_declaration -> string -> unit
val box_of : id -> box list
val delete_boxes_of : id -> unit
val proof_task_box_of : id -> pt option
val proof_nesting : unit -> int
val checkout_shallowest_proof_branch : unit -> unit
val propagate_sideff : replay:aast option -> unit
val gc : unit -> unit
val visit : id -> visit
val print : ?now:bool -> unit -> unit
val backup : unit -> vcs
val restore : vcs -> unit
end = struct (* {{{ *)
include Vcs_
exception Expired = Vcs_aux.Expired
open Printf
let print_dag vcs () =
let fname =
"stm_" ^ Str.global_replace (Str.regexp " ") "_" (System.process_id ()) in
let string_of_transaction = function
| Cmd { cast = t } | Fork (t, _,_,_) ->
(try Pp.string_of_ppcmds (pr_ast t) with _ -> "ERR")
| Sideff (Some t) ->
sprintf "Sideff(%s)"
(try Pp.string_of_ppcmds (pr_ast t) with _ -> "ERR")
| Sideff None -> "EnvChange"
| Noop -> " "
| Alias (id,_) -> sprintf "Alias(%s)" (Stateid.to_string id)
| Qed { qast } -> string_of_ppcmds (pr_ast qast) in
let is_green id =
match get_info vcs id with
| Some { state = Valid _ } -> true
| _ -> false in
let is_red id =
match get_info vcs id with
| Some { state = Error _ } -> true
| _ -> false in
let head = current_branch vcs in
let heads =
List.map (fun x -> x, (get_branch vcs x).pos) (branches vcs) in
let graph = dag vcs in
let quote s =
Str.global_replace (Str.regexp "\n") "<BR/>"
(Str.global_replace (Str.regexp "<") "<"
(Str.global_replace (Str.regexp ">") ">"
(Str.global_replace (Str.regexp "\"") """
(Str.global_replace (Str.regexp "&") "&"
(String.sub s 0 (min (String.length s) 20)))))) in
let fname_dot, fname_ps =
let f = "/tmp/" ^ Filename.basename fname in
f ^ ".dot", f ^ ".pdf" in
let node id = "s" ^ Stateid.to_string id in
let edge tr =
sprintf "<<FONT POINT-SIZE=\"12\" FACE=\"sans\">%s</FONT>>"
(quote (string_of_transaction tr)) in
let node_info id =
match get_info vcs id with
| None -> ""
| Some info ->
sprintf "<<FONT POINT-SIZE=\"12\">%s</FONT>" (Stateid.to_string id) ^
sprintf " <FONT POINT-SIZE=\"11\">r:%d g:%d</FONT>>"
info.n_reached info.n_goals in
let color id =
if is_red id then "red" else if is_green id then "green" else "white" in
let nodefmt oc id =
fprintf oc "%s [label=%s,style=filled,fillcolor=%s];\n"
(node id) (node_info id) (color id) in
let ids = ref Stateid.Set.empty in
let boxes = ref [] in
(* Fill in *)
Dag.iter graph (fun from _ _ l ->
ids := Stateid.Set.add from !ids;
List.iter (fun box -> boxes := box :: !boxes)
(Dag.property_of graph from);
List.iter (fun (dest, _) ->
ids := Stateid.Set.add dest !ids;
List.iter (fun box -> boxes := box :: !boxes)
(Dag.property_of graph dest))
l);
boxes := CList.sort_uniquize Dag.Property.compare !boxes;
let oc = open_out fname_dot in
output_string oc "digraph states {\n";
Dag.iter graph (fun from cf _ l ->
List.iter (fun (dest, trans) ->
fprintf oc "%s -> %s [xlabel=%s,labelfloat=true];\n"
(node from) (node dest) (edge trans)) l
);
let contains b1 b2 =
Stateid.Set.subset
(Dag.Property.having_it b2) (Dag.Property.having_it b1) in
let same_box = Dag.Property.equal in
let outerboxes boxes =
List.filter (fun b ->
not (List.exists (fun b1 ->
not (same_box b1 b) && contains b1 b) boxes)
) boxes in
let rec rec_print b =
boxes := CList.remove same_box b !boxes;
let sub_boxes = List.filter (contains b) (outerboxes !boxes) in
fprintf oc "subgraph cluster_%s {\n" (Dag.Property.to_string b);
List.iter rec_print sub_boxes;
Stateid.Set.iter (fun id ->
if Stateid.Set.mem id !ids then begin
ids := Stateid.Set.remove id !ids;
nodefmt oc id
end)
(Dag.Property.having_it b);
match Dag.Property.data b with
| ProofBlock ({ dynamic_switch = id }, lbl) ->
fprintf oc "label=\"%s (test:%s)\";\n" lbl (Stateid.to_string id);
fprintf oc "color=red; }\n"
| ProofTask _ -> fprintf oc "color=blue; }\n"
in
List.iter rec_print (outerboxes !boxes);
Stateid.Set.iter (nodefmt oc) !ids;
List.iteri (fun i (b,id) ->
let shape = if Branch.equal head b then "box3d" else "box" in
fprintf oc "b%d -> %s;\n" i (node id);
fprintf oc "b%d [shape=%s,label=\"%s\"];\n" i shape
(Branch.to_string b);
) heads;
output_string oc "}\n";
close_out oc;
ignore(Sys.command
("dot -Tpdf -Gcharset=latin1 " ^ fname_dot ^ " -o" ^ fname_ps))
type vcs = (branch_type, transaction, vcs state_info, box) t
let vcs : vcs ref = ref (empty Stateid.dummy)
let init id =
vcs := empty id;
vcs := set_info !vcs id (default_info ())
let current_branch () = current_branch !vcs
let checkout head = vcs := checkout !vcs head
let branches () = branches !vcs
let get_branch head = get_branch !vcs head
let get_branch_pos head = (get_branch head).pos
let new_node ?(id=Stateid.fresh ()) () =
assert(Vcs_.get_info !vcs id = None);
vcs := set_info !vcs id (default_info ());
id
let merge id ~ours ?into branch =
vcs := merge !vcs id ~ours ~theirs:Noop ?into branch
let delete_branch branch = vcs := delete_branch !vcs branch
let reset_branch branch id = vcs := reset_branch !vcs branch id
let commit id t = vcs := commit !vcs id t
let rewrite_merge id ~ours ~at branch =
vcs := rewrite_merge !vcs id ~ours ~theirs:Noop ~at branch
let reachable id = reachable !vcs id
let mk_branch_name { expr = x } = Branch.make
(match x with
| VernacDefinition (_,((_,i),_),_) -> string_of_id i
| VernacStartTheoremProof (_,[Some ((_,i),_),_],_) -> string_of_id i
| _ -> "branch")
let edit_branch = Branch.make "edit"
let branch ?root ?pos name kind = vcs := branch !vcs ?root ?pos name kind
let get_info id =
match get_info !vcs id with
| Some x -> x
| None -> raise Vcs_aux.Expired
let set_state id s =
(get_info id).state <- s;
if Flags.async_proofs_is_master () then Hooks.(call state_ready id)
let get_state id = (get_info id).state
let reached id =
let info = get_info id in
info.n_reached <- info.n_reached + 1
let goals id n = (get_info id).n_goals <- n
let cur_tip () = get_branch_pos (current_branch ())
let proof_nesting () = Vcs_aux.proof_nesting !vcs
let checkout_shallowest_proof_branch () =
if List.mem edit_branch (Vcs_.branches !vcs) then begin
checkout edit_branch;
match get_branch edit_branch with
| { kind = `Edit (mode, _,_,_,_) } -> Proof_global.activate_proof_mode mode
| _ -> assert false
end else
let pl = proof_nesting () in
try
let branch, mode = match Vcs_aux.find_proof_at_depth !vcs pl with
| h, { Vcs_.kind = `Proof (m, _) } -> h, m | _ -> assert false in
checkout branch;
prerr_endline (fun () -> "mode:" ^ mode);
Proof_global.activate_proof_mode mode
with Failure _ ->
checkout Branch.master;
Proof_global.disactivate_current_proof_mode ()
(* copies the transaction on every open branch *)
let propagate_sideff ~replay:t =
List.iter (fun b ->
checkout b;
let id = new_node () in
merge id ~ours:(Sideff t) ~into:b Branch.master)
(List.filter (fun b -> not (Branch.equal b Branch.master)) (branches ()))
let visit id = Vcs_aux.visit !vcs id
let nodes_in_slice ~block_start ~block_stop =
let rec aux id =
if Stateid.equal id block_start then [] else
match visit id with
| { next = n; step = `Cmd x } -> (id,Cmd x) :: aux n
| { next = n; step = `Alias x } -> (id,Alias x) :: aux n
| { next = n; step = `Sideff (`Ast (x,_)) } ->
(id,Sideff (Some x)) :: aux n
| _ -> anomaly(str("Cannot slice from "^ Stateid.to_string block_start ^
" to "^Stateid.to_string block_stop))
in aux block_stop
let slice ~block_start ~block_stop =
let l = nodes_in_slice ~block_start ~block_stop in
let copy_info v id =
Vcs_.set_info v id
{ (get_info id) with state = Empty; vcs_backup = None,None } in
let copy_info_w_state v id =
Vcs_.set_info v id { (get_info id) with vcs_backup = None,None } in
let copy_proof_blockes v =
let nodes = Vcs_.Dag.all_nodes (Vcs_.dag v) in
let props =
Stateid.Set.fold (fun n pl -> Vcs_.property_of !vcs n @ pl) nodes [] in
let props = CList.sort_uniquize Vcs_.Dag.Property.compare props in
List.fold_left (fun v p ->
Vcs_.create_property v
(Stateid.Set.elements (Vcs_.Dag.Property.having_it p))
(Vcs_.Dag.Property.data p)) v props
in
let v = Vcs_.empty block_start in
let v = copy_info v block_start in
let v = List.fold_right (fun (id,tr) v ->
let v = Vcs_.commit v id tr in
let v = copy_info v id in
v) l v in
(* Stm should have reached the beginning of proof *)
assert (match (get_info block_start).state with Valid _ -> true | _ -> false);
We put in the new dag the most recent state known to master
let rec fill id =
match (get_info id).state with
| Empty | Error _ -> fill (Vcs_aux.visit v id).next
| Valid _ -> copy_info_w_state v id in
let v = fill block_stop in
We put in the new dag the first state ( since Qed shall run on it ,
* see check_task_aux )
* see check_task_aux) *)
let v = copy_info_w_state v block_start in
copy_proof_blockes v
let nodes_in_slice ~block_start ~block_stop =
List.rev (List.map fst (nodes_in_slice ~block_start ~block_stop))
let topo_invariant l =
let all = List.fold_right Stateid.Set.add l Stateid.Set.empty in
List.for_all
(fun x ->
let props = property_of !vcs x in
let sets = List.map Dag.Property.having_it props in
List.for_all (fun s -> Stateid.Set.(subset s all || subset all s)) sets)
l
let create_proof_task_box l ~qed ~block_start:lemma =
if not (topo_invariant l) then anomaly (str "overlapping boxes");
vcs := create_property !vcs l (ProofTask { qed; lemma })
let create_proof_block ({ block_start; block_stop} as decl) name =
let l = nodes_in_slice ~block_start ~block_stop in
if not (topo_invariant l) then anomaly (str "overlapping boxes");
vcs := create_property !vcs l (ProofBlock (decl, name))
let box_of id = List.map Dag.Property.data (property_of !vcs id)
let delete_boxes_of id =
List.iter (fun x -> vcs := delete_property !vcs x) (property_of !vcs id)
let proof_task_box_of id =
match
CList.map_filter (function ProofTask x -> Some x | _ -> None) (box_of id)
with
| [] -> None
| [x] -> Some x
| _ -> anomaly (str "node with more than 1 proof task box")
let gc () =
let old_vcs = !vcs in
let new_vcs, erased_nodes = gc old_vcs in
Stateid.Set.iter (fun id ->
match (Vcs_aux.visit old_vcs id).step with
| `Qed ({ fproof = Some (_, cancel_switch) }, _)
| `Cmd { cqueue = `TacQueue (_,_,cancel_switch) }
| `Cmd { cqueue = `QueryQueue cancel_switch } ->
cancel_switch := true
| _ -> ())
erased_nodes;
vcs := new_vcs
module NB : sig (* Non blocking Sys.command *)
val command : now:bool -> (unit -> unit) -> unit
end = struct
let m = Mutex.create ()
let c = Condition.create ()
let job = ref None
let worker = ref None
let set_last_job j =
Mutex.lock m;
job := Some j;
Condition.signal c;
Mutex.unlock m
let get_last_job () =
Mutex.lock m;
while Option.is_empty !job do Condition.wait c m; done;
match !job with
| None -> assert false
| Some x -> job := None; Mutex.unlock m; x
let run_command () =
try while true do get_last_job () () done
with e -> () (* No failure *)
let command ~now job =
if now then job ()
else begin
set_last_job job;
if Option.is_empty !worker then
worker := Some (Thread.create run_command ())
end
end
let print ?(now=false) () =
if not !Flags.debug && not now then () else NB.command ~now (print_dag !vcs)
let backup () = !vcs
let restore v = vcs := v
end (* }}} *)
let state_of_id id =
try match (VCS.get_info id).state with
| Valid s -> `Valid (Some s)
| Error (e,_) -> `Error e
| Empty -> `Valid None
with VCS.Expired -> `Expired
* * * * * A cache : fills in the nodes of the VCS document with their value * * * * *
module State : sig
(** The function is from unit, so it uses the current state to define
a new one. I.e. one may been to install the right state before
defining a new one.
Warning: an optimization in installed_cached requires that state
modifying functions are always executed using this wrapper. *)
val define :
?safe_id:Stateid.t ->
?redefine:bool -> ?cache:Summary.marshallable ->
?feedback_processed:bool -> (unit -> unit) -> Stateid.t -> unit
val fix_exn_ref : (iexn -> iexn) ref
val install_cached : Stateid.t -> unit
val is_cached : ?cache:Summary.marshallable -> Stateid.t -> bool
val is_cached_and_valid : ?cache:Summary.marshallable -> Stateid.t -> bool
val exn_on : Stateid.t -> valid:Stateid.t -> iexn -> iexn
(* to send states across worker/master *)
type frozen_state
val get_cached : Stateid.t -> frozen_state
val same_env : frozen_state -> frozen_state -> bool
type proof_part
type partial_state =
[ `Full of frozen_state
| `Proof of Stateid.t * proof_part ]
val proof_part_of_frozen : frozen_state -> proof_part
val assign : Stateid.t -> partial_state -> unit
end = struct (* {{{ *)
cur_id holds Stateid.dummy in case the last attempt to define a state
* failed , so the global state may contain garbage
* failed, so the global state may contain garbage *)
let cur_id = ref Stateid.dummy
let fix_exn_ref = ref (fun x -> x)
(* helpers *)
let freeze_global_state marshallable =
{ system = States.freeze ~marshallable;
proof = Proof_global.freeze ~marshallable;
shallow = (marshallable = `Shallow) }
let unfreeze_global_state { system; proof } =
States.unfreeze system; Proof_global.unfreeze proof
(* hack to make futures functional *)
let () = Future.set_freeze
(fun () -> Obj.magic (freeze_global_state `No, !cur_id))
(fun t -> let s,i = Obj.magic t in unfreeze_global_state s; cur_id := i)
type frozen_state = state
type proof_part =
Proof_global.state * Summary.frozen_bits (* only meta counters *)
type partial_state =
[ `Full of frozen_state
| `Proof of Stateid.t * proof_part ]
let proof_part_of_frozen { proof; system } =
proof,
Summary.project_summary (States.summary_of_state system) summary_pstate
let freeze marshallable id =
VCS.set_state id (Valid (freeze_global_state marshallable))
let freeze_invalid id iexn = VCS.set_state id (Error iexn)
let is_cached ?(cache=`No) id only_valid =
if Stateid.equal id !cur_id then
try match VCS.get_info id with
| { state = Empty } when cache = `Yes -> freeze `No id; true
| { state = Empty } when cache = `Shallow -> freeze `Shallow id; true
| _ -> true
with VCS.Expired -> false
else
try match VCS.get_info id with
| { state = Empty } -> false
| { state = Valid _ } -> true
| { state = Error _ } -> not only_valid
with VCS.Expired -> false
let is_cached_and_valid ?cache id = is_cached ?cache id true
let is_cached ?cache id = is_cached ?cache id false
let install_cached id =
match VCS.get_info id with
| { state = Valid s } ->
if Stateid.equal id !cur_id then () (* optimization *)
else begin unfreeze_global_state s; cur_id := id end
| { state = Error ie } -> cur_id := id; Exninfo.iraise ie
| _ ->
coqc has a 1 slot cache and only for valid states
if interactive () = `No && Stateid.equal id !cur_id then ()
else anomaly (str "installing a non cached state")
let get_cached id =
try match VCS.get_info id with
| { state = Valid s } -> s
| _ -> anomaly (str "not a cached state")
with VCS.Expired -> anomaly (str "not a cached state (expired)")
let assign id what =
if VCS.get_state id <> Empty then () else
try match what with
| `Full s ->
let s =
try
let prev = (VCS.visit id).next in
if is_cached_and_valid prev
then { s with proof =
Proof_global.copy_terminators
~src:(get_cached prev).proof ~tgt:s.proof }
else s
with VCS.Expired -> s in
VCS.set_state id (Valid s)
| `Proof(ontop,(pstate,counters)) ->
if is_cached_and_valid ontop then
let s = get_cached ontop in
let s = { s with proof =
Proof_global.copy_terminators ~src:s.proof ~tgt:pstate } in
let s = { s with system =
States.replace_summary s.system
(Summary.surgery_summary
(States.summary_of_state s.system)
counters) } in
VCS.set_state id (Valid s)
with VCS.Expired -> ()
let exn_on id ~valid (e, info) =
match Stateid.get info with
| Some _ -> (e, info)
| None ->
let loc = Option.default Loc.ghost (Loc.get_loc info) in
let (e, info) = Hooks.(call_process_error_once (e, info)) in
Hooks.(call execution_error id loc (iprint (e, info)));
(e, Stateid.add info ~valid id)
let same_env { system = s1 } { system = s2 } =
let s1 = States.summary_of_state s1 in
let e1 = Summary.project_summary s1 [Global.global_env_summary_name] in
let s2 = States.summary_of_state s2 in
let e2 = Summary.project_summary s2 [Global.global_env_summary_name] in
Summary.pointer_equal e1 e2
let define ?safe_id ?(redefine=false) ?(cache=`No) ?(feedback_processed=true)
f id
=
feedback ~id:(State id) (ProcessingIn !Flags.async_proofs_worker_id);
let str_id = Stateid.to_string id in
if is_cached id && not redefine then
anomaly (str"defining state "++str str_id++str" twice");
try
prerr_endline (fun () -> "defining "^str_id^" (cache="^
if cache = `Yes then "Y)" else if cache = `Shallow then "S)" else "N)");
let good_id = match safe_id with None -> !cur_id | Some id -> id in
fix_exn_ref := exn_on id ~valid:good_id;
f ();
fix_exn_ref := (fun x -> x);
if cache = `Yes then freeze `No id
else if cache = `Shallow then freeze `Shallow id;
prerr_endline (fun () -> "setting cur id to "^str_id);
cur_id := id;
if feedback_processed then
Hooks.(call state_computed id ~in_cache:false);
VCS.reached id;
if Proof_global.there_are_pending_proofs () then
VCS.goals id (Proof_global.get_open_goals ())
with e ->
let (e, info) = CErrors.push e in
let good_id = !cur_id in
cur_id := Stateid.dummy;
VCS.reached id;
let ie =
match Stateid.get info, safe_id with
| None, None -> (exn_on id ~valid:good_id (e, info))
| None, Some good_id -> (exn_on id ~valid:good_id (e, info))
| Some _, None -> (e, info)
| Some (_,at), Some id -> (e, Stateid.add info ~valid:id at) in
if cache = `Yes || cache = `Shallow then freeze_invalid id ie;
Hooks.(call unreachable_state id ie);
Exninfo.iraise ie
end (* }}} *)
(****************************** CRUFT *****************************************)
(******************************************************************************)
(* The backtrack module simulates the classic behavior of a linear document *)
module Backtrack : sig
val record : unit -> unit
val backto : Stateid.t -> unit
val back_safe : unit -> unit
we could navigate the dag , but this ways easy
val branches_of : Stateid.t -> backup
(* To be installed during initialization *)
val undo_vernac_classifier : vernac_expr -> vernac_classification
end = struct (* {{{ *)
let record () =
List.iter (fun current_branch ->
let mine = current_branch, VCS.get_branch current_branch in
let info = VCS.get_info (VCS.get_branch_pos current_branch) in
let others =
CList.map_filter (fun b ->
if Vcs_.Branch.equal b current_branch then None
else Some(b, VCS.get_branch b)) (VCS.branches ()) in
let backup = if fst info.vcs_backup <> None then fst info.vcs_backup
else Some (VCS.backup ()) in
let branches = if snd info.vcs_backup <> None then snd info.vcs_backup
else Some { mine; others } in
info.vcs_backup <- backup, branches)
[VCS.current_branch (); VCS.Branch.master]
let backto oid =
let info = VCS.get_info oid in
match info.vcs_backup with
| None, _ ->
anomaly(str"Backtrack.backto "++str(Stateid.to_string oid)++
str": a state with no vcs_backup")
| Some vcs, _ -> VCS.restore vcs
let branches_of id =
let info = VCS.get_info id in
match info.vcs_backup with
| _, None ->
anomaly(str"Backtrack.branches_of "++str(Stateid.to_string id)++
str": a state with no vcs_backup")
| _, Some x -> x
let rec fold_until f acc id =
let next acc =
if id = Stateid.initial then raise Not_found
else fold_until f acc (VCS.visit id).next in
let info = VCS.get_info id in
match info.vcs_backup with
| None, _ -> next acc
| Some vcs, _ ->
let ids, tactic, undo =
if id = Stateid.initial || id = Stateid.dummy then [],false,0 else
match VCS.visit id with
| { step = `Fork ((_,_,_,l),_) } -> l, false,0
| { step = `Cmd { cids = l; ctac } } -> l, ctac,0
| { step = `Alias (_,{ expr = VernacUndo n}) } -> [], false, n
| _ -> [],false,0 in
match f acc (id, vcs, ids, tactic, undo) with
| `Stop x -> x
| `Cont acc -> next acc
let back_safe () =
let id =
fold_until (fun n (id,_,_,_,_) ->
if n >= 0 && State.is_cached_and_valid id then `Stop id else `Cont (succ n))
0 (VCS.get_branch_pos (VCS.current_branch ())) in
backto id
let undo_vernac_classifier v =
try
match v with
| VernacResetInitial ->
VtStm (VtBack Stateid.initial, true), VtNow
| VernacResetName (_,name) ->
let id = VCS.get_branch_pos (VCS.current_branch ()) in
(try
let oid =
fold_until (fun b (id,_,label,_,_) ->
if b then `Stop id else `Cont (List.mem name label))
false id in
VtStm (VtBack oid, true), VtNow
with Not_found ->
VtStm (VtBack id, true), VtNow)
| VernacBack n ->
let id = VCS.get_branch_pos (VCS.current_branch ()) in
let oid = fold_until (fun n (id,_,_,_,_) ->
if Int.equal n 0 then `Stop id else `Cont (n-1)) n id in
VtStm (VtBack oid, true), VtNow
| VernacUndo n ->
let id = VCS.get_branch_pos (VCS.current_branch ()) in
let oid = fold_until (fun n (id,_,_,tactic,undo) ->
let value = (if tactic then 1 else 0) - undo in
if Int.equal n 0 then `Stop id else `Cont (n-value)) n id in
VtStm (VtBack oid, true), VtLater
| VernacUndoTo _
| VernacRestart as e ->
let m = match e with VernacUndoTo m -> m | _ -> 0 in
let id = VCS.get_branch_pos (VCS.current_branch ()) in
let vcs =
match (VCS.get_info id).vcs_backup with
| None, _ -> anomaly(str"Backtrack: tip with no vcs_backup")
| Some vcs, _ -> vcs in
let cb, _ =
try Vcs_aux.find_proof_at_depth vcs (Vcs_aux.proof_nesting vcs)
with Failure _ -> raise Proof_global.NoCurrentProof in
let n = fold_until (fun n (_,vcs,_,_,_) ->
if List.mem cb (Vcs_.branches vcs) then `Cont (n+1) else `Stop n)
0 id in
let oid = fold_until (fun n (id,_,_,_,_) ->
if Int.equal n 0 then `Stop id else `Cont (n-1)) (n-m-1) id in
VtStm (VtBack oid, true), VtLater
| VernacAbortAll ->
let id = VCS.get_branch_pos (VCS.current_branch ()) in
let oid = fold_until (fun () (id,vcs,_,_,_) ->
match Vcs_.branches vcs with [_] -> `Stop id | _ -> `Cont ())
() id in
VtStm (VtBack oid, true), VtLater
| VernacBacktrack (id,_,_)
| VernacBackTo id ->
VtStm (VtBack (Stateid.of_int id), not !Flags.print_emacs), VtNow
| _ -> VtUnknown, VtNow
with
| Not_found ->
CErrors.errorlabstrm "undo_vernac_classifier"
(str "Cannot undo")
end (* }}} *)
let hints = ref Aux_file.empty_aux_file
let set_compilation_hints file =
hints := Aux_file.load_aux_file_for file
let get_hint_ctx loc =
let s = Aux_file.get !hints loc "context_used" in
match Str.split (Str.regexp ";") s with
| ids :: _ ->
let ids = List.map Names.Id.of_string (Str.split (Str.regexp " ") ids) in
let ids = List.map (fun id -> Loc.ghost, id) ids in
begin match ids with
| [] -> SsEmpty
| x :: xs ->
List.fold_left (fun a x -> SsUnion (SsSingl x,a)) (SsSingl x) xs
end
| _ -> raise Not_found
let get_hint_bp_time proof_name =
try float_of_string (Aux_file.get !hints Loc.ghost proof_name)
with Not_found -> 1.0
let record_pb_time proof_name loc time =
let proof_build_time = Printf.sprintf "%.3f" time in
Aux_file.record_in_aux_at loc "proof_build_time" proof_build_time;
if proof_name <> "" then begin
Aux_file.record_in_aux_at Loc.ghost proof_name proof_build_time;
hints := Aux_file.set !hints Loc.ghost proof_name proof_build_time
end
exception RemoteException of std_ppcmds
let _ = CErrors.register_handler (function
| RemoteException ppcmd -> ppcmd
| _ -> raise Unhandled)
(****************** proof structure for error recovery ************************)
(******************************************************************************)
type document_node = {
indentation : int;
ast : Vernacexpr.vernac_expr;
id : Stateid.t;
}
type document_view = {
entry_point : document_node;
prev_node : document_node -> document_node option;
}
type static_block_detection =
document_view -> static_block_declaration option
type recovery_action = {
base_state : Stateid.t;
goals_to_admit : Goal.goal list;
recovery_command : Vernacexpr.vernac_expr option;
}
type dynamic_block_error_recovery =
static_block_declaration -> [ `ValidBlock of recovery_action | `Leaks ]
let proof_block_delimiters = ref []
let register_proof_block_delimiter name static dynamic =
if List.mem_assoc name !proof_block_delimiters then
CErrors.errorlabstrm "STM" (str "Duplicate block delimiter " ++ str name);
proof_block_delimiters := (name, (static,dynamic)) :: !proof_block_delimiters
let mk_doc_node id = function
| { step = `Cmd { ctac; cast = { indentation; expr }}; next } when ctac ->
Some { indentation; ast = expr; id }
| { step = `Sideff (`Ast ({ indentation; expr }, _)); next } ->
Some { indentation; ast = expr; id }
| _ -> None
let prev_node { id } =
let id = (VCS.visit id).next in
mk_doc_node id (VCS.visit id)
let cur_node id = mk_doc_node id (VCS.visit id)
let is_block_name_enabled name =
match !Flags.async_proofs_tac_error_resilience with
| `None -> false
| `All -> true
| `Only l -> List.mem name l
let detect_proof_block id name =
let name = match name with None -> "indent" | Some x -> x in
if is_block_name_enabled name &&
(Flags.async_proofs_is_master () || Flags.async_proofs_is_worker ())
then (
match cur_node id with
| None -> ()
| Some entry_point -> try
let static, _ = List.assoc name !proof_block_delimiters in
begin match static { prev_node; entry_point } with
| None -> ()
| Some ({ block_start; block_stop } as decl) ->
VCS.create_proof_block decl name
end
with Not_found ->
CErrors.errorlabstrm "STM"
(str "Unknown proof block delimiter " ++ str name)
)
(****************************** THE SCHEDULER *********************************)
(******************************************************************************)
module rec ProofTask : sig
type competence = Stateid.t list
type task_build_proof = {
t_exn_info : Stateid.t * Stateid.t;
t_start : Stateid.t;
t_stop : Stateid.t;
t_drop : bool;
t_states : competence;
t_assign : Proof_global.closed_proof_output Future.assignement -> unit;
t_loc : Loc.t;
t_uuid : Future.UUID.t;
t_name : string }
type task =
| BuildProof of task_build_proof
| States of Stateid.t list
type request =
| ReqBuildProof of (Future.UUID.t,VCS.vcs) Stateid.request * bool * competence
| ReqStates of Stateid.t list
include AsyncTaskQueue.Task
with type task := task
and type competence := competence
and type request := request
val build_proof_here :
drop_pt:bool ->
Stateid.t * Stateid.t -> Loc.t -> Stateid.t ->
Proof_global.closed_proof_output Future.computation
(* If set, only tasks overlapping with this list are processed *)
val set_perspective : Stateid.t list -> unit
end = struct (* {{{ *)
let forward_feedback msg = Hooks.(call forward_feedback msg)
type competence = Stateid.t list
type task_build_proof = {
t_exn_info : Stateid.t * Stateid.t;
t_start : Stateid.t;
t_stop : Stateid.t;
t_drop : bool;
t_states : competence;
t_assign : Proof_global.closed_proof_output Future.assignement -> unit;
t_loc : Loc.t;
t_uuid : Future.UUID.t;
t_name : string }
type task =
| BuildProof of task_build_proof
| States of Stateid.t list
type request =
| ReqBuildProof of (Future.UUID.t,VCS.vcs) Stateid.request * bool * competence
| ReqStates of Stateid.t list
type error = {
e_error_at : Stateid.t;
e_safe_id : Stateid.t;
e_msg : std_ppcmds;
e_safe_states : Stateid.t list }
type response =
| RespBuiltProof of Proof_global.closed_proof_output * float
| RespError of error
| RespStates of (Stateid.t * State.partial_state) list
| RespDone
let name = ref "proofworker"
let extra_env () = !async_proofs_workers_extra_env
let perspective = ref []
let set_perspective l = perspective := l
let task_match age t =
match age, t with
| `Fresh, BuildProof { t_states } ->
not !Flags.async_proofs_full ||
List.exists (fun x -> CList.mem_f Stateid.equal x !perspective) t_states
| `Old my_states, States l ->
List.for_all (fun x -> CList.mem_f Stateid.equal x my_states) l
| _ -> false
let name_of_task = function
| BuildProof t -> "proof: " ^ t.t_name
| States l -> "states: " ^ String.concat "," (List.map Stateid.to_string l)
let name_of_request = function
| ReqBuildProof(r,_,_) -> "proof: " ^ r.Stateid.name
| ReqStates l -> "states: "^String.concat "," (List.map Stateid.to_string l)
let request_of_task age = function
| States l -> Some (ReqStates l)
| BuildProof {
t_exn_info;t_start;t_stop;t_loc;t_uuid;t_name;t_states;t_drop
} ->
assert(age = `Fresh);
try Some (ReqBuildProof ({
Stateid.exn_info = t_exn_info;
stop = t_stop;
document = VCS.slice ~block_start:t_start ~block_stop:t_stop;
loc = t_loc;
uuid = t_uuid;
name = t_name }, t_drop, t_states))
with VCS.Expired -> None
let use_response (s : competence AsyncTaskQueue.worker_status) t r =
match s, t, r with
| `Old c, States _, RespStates l ->
List.iter (fun (id,s) -> State.assign id s) l; `End
| `Fresh, BuildProof { t_assign; t_loc; t_name; t_states; t_drop },
RespBuiltProof (pl, time) ->
feedback (InProgress ~-1);
t_assign (`Val pl);
record_pb_time t_name t_loc time;
if !Flags.async_proofs_full || t_drop
then `Stay(t_states,[States t_states])
else `End
| `Fresh, BuildProof { t_assign; t_loc; t_name; t_states },
RespError { e_error_at; e_safe_id = valid; e_msg; e_safe_states } ->
feedback (InProgress ~-1);
let info = Stateid.add ~valid Exninfo.null e_error_at in
let e = (RemoteException e_msg, info) in
t_assign (`Exn e);
`Stay(t_states,[States e_safe_states])
| _ -> assert false
let on_task_cancellation_or_expiration_or_slave_death = function
| None -> ()
| Some (States _) -> ()
| Some (BuildProof { t_start = start; t_assign }) ->
let s = "Worker dies or task expired" in
let info = Stateid.add ~valid:start Exninfo.null start in
let e = (RemoteException (strbrk s), info) in
t_assign (`Exn e);
Hooks.(call execution_error start Loc.ghost (strbrk s));
feedback (InProgress ~-1)
let build_proof_here ~drop_pt (id,valid) loc eop =
Future.create (State.exn_on id ~valid) (fun () ->
let wall_clock1 = Unix.gettimeofday () in
if !Flags.batch_mode then Reach.known_state ~cache:`No eop
else Reach.known_state ~cache:`Shallow eop;
let wall_clock2 = Unix.gettimeofday () in
Aux_file.record_in_aux_at loc "proof_build_time"
(Printf.sprintf "%.3f" (wall_clock2 -. wall_clock1));
let p = Proof_global.return_proof ~allow_partial:drop_pt () in
if drop_pt then feedback ~id:(State id) Complete;
p)
let perform_buildp { Stateid.exn_info; stop; document; loc } drop my_states =
try
VCS.restore document;
VCS.print ();
let proof, future_proof, time =
let wall_clock = Unix.gettimeofday () in
let fp = build_proof_here ~drop_pt:drop exn_info loc stop in
let proof = Future.force fp in
proof, fp, Unix.gettimeofday () -. wall_clock in
(* We typecheck the proof with the kernel (in the worker) to spot
* the few errors tactics don't catch, like the "fix" tactic building
* a bad fixpoint *)
let fix_exn = Future.fix_exn_of future_proof in
if not drop then begin
let checked_proof = Future.chain ~pure:false future_proof (fun p ->
let pobject, _ =
Proof_global.close_future_proof stop (Future.from_val ~fix_exn p) in
The one sent by master is an InvalidKey
Lemmas.(standard_proof_terminator [] (mk_hook (fun _ _ -> ()))) in
vernac_interp stop
~proof:(pobject, terminator)
{ verbose = false; loc; indentation = 0; strlen = 0;
expr = (VernacEndProof (Proved (Opaque None,None))) }) in
ignore(Future.join checked_proof);
end;
RespBuiltProof(proof,time)
with
| e when CErrors.noncritical e || e = Stack_overflow ->
let (e, info) = CErrors.push e in
(* This can happen if the proof is broken. The error has also been
* signalled as a feedback, hence we can silently recover *)
let e_error_at, e_safe_id = match Stateid.get info with
| Some (safe, err) -> err, safe
| None -> Stateid.dummy, Stateid.dummy in
let e_msg = iprint (e, info) in
prerr_endline (fun () -> "failed with the following exception:");
prerr_endline (fun () -> string_of_ppcmds e_msg);
let e_safe_states = List.filter State.is_cached_and_valid my_states in
RespError { e_error_at; e_safe_id; e_msg; e_safe_states }
let perform_states query =
if query = [] then [] else
let is_tac e = match classify_vernac e with
| VtProofStep _, _ -> true
| _ -> false
in
let initial =
let rec aux id =
try match VCS.visit id with { next } -> aux next
with VCS.Expired -> id in
aux (List.hd query) in
let get_state seen id =
let prev =
try
let { next = prev; step } = VCS.visit id in
if State.is_cached_and_valid prev && List.mem prev seen
then Some (prev, State.get_cached prev, step)
else None
with VCS.Expired -> None in
let this =
if State.is_cached_and_valid id then Some (State.get_cached id) else None in
match prev, this with
| _, None -> None
| Some (prev, o, `Cmd { cast = { expr }}), Some n
when is_tac expr && State.same_env o n -> (* A pure tactic *)
Some (id, `Proof (prev, State.proof_part_of_frozen n))
| Some _, Some s ->
msg_debug (str "STM: sending back a fat state");
Some (id, `Full s)
| _, Some s -> Some (id, `Full s) in
let rec aux seen = function
| [] -> []
| id :: rest ->
match get_state seen id with
| None -> aux seen rest
| Some stuff -> stuff :: aux (id :: seen) rest in
aux [initial] query
let perform = function
| ReqBuildProof (bp,drop,states) -> perform_buildp bp drop states
| ReqStates sl -> RespStates (perform_states sl)
let on_marshal_error s = function
| States _ -> msg_error(strbrk("Marshalling error: "^s^". "^
"The system state could not be sent to the master process."))
| BuildProof { t_exn_info; t_stop; t_assign; t_loc; t_drop = drop_pt } ->
msg_error(strbrk("Marshalling error: "^s^". "^
"The system state could not be sent to the worker process. "^
"Falling back to local, lazy, evaluation."));
t_assign(`Comp(build_proof_here ~drop_pt t_exn_info t_loc t_stop));
feedback (InProgress ~-1)
end (* }}} *)
(* Slave processes (if initialized, otherwise local lazy evaluation) *)
and Slaves : sig
(* (eventually) remote calls *)
val build_proof :
loc:Loc.t -> drop_pt:bool ->
exn_info:(Stateid.t * Stateid.t) -> block_start:Stateid.t -> block_stop:Stateid.t ->
name:string -> future_proof * cancel_switch
(* blocking function that waits for the task queue to be empty *)
val wait_all_done : unit -> unit
(* initialize the whole machinery (optional) *)
val init : unit -> unit
type 'a tasks = (('a,VCS.vcs) Stateid.request * bool) list
val dump_snapshot : unit -> Future.UUID.t tasks
val check_task : string -> int tasks -> int -> bool
val info_tasks : 'a tasks -> (string * float * int) list
val finish_task :
string ->
Library.seg_univ -> Library.seg_discharge -> Library.seg_proofs ->
int tasks -> int -> Library.seg_univ
val cancel_worker : WorkerPool.worker_id -> unit
val reset_task_queue : unit -> unit
val set_perspective : Stateid.t list -> unit
end = struct (* {{{ *)
module TaskQueue = AsyncTaskQueue.MakeQueue(ProofTask)
let queue = ref None
let init () =
if Flags.async_proofs_is_master () then
queue := Some (TaskQueue.create !Flags.async_proofs_n_workers)
else
queue := Some (TaskQueue.create 0)
let check_task_aux extra name l i =
let { Stateid.stop; document; loc; name = r_name }, drop = List.nth l i in
Flags.if_verbose msg_info
(str(Printf.sprintf "Checking task %d (%s%s) of %s" i r_name extra name));
VCS.restore document;
let start =
let rec aux cur =
try aux (VCS.visit cur).next
with VCS.Expired -> cur in
aux stop in
try
Reach.known_state ~cache:`No stop;
if drop then
let _proof = Proof_global.return_proof ~allow_partial:true () in
`OK_ADMITTED
else begin
(* The original terminator, a hook, has not been saved in the .vio*)
Proof_global.set_terminator
(Lemmas.standard_proof_terminator []
(Lemmas.mk_hook (fun _ _ -> ())));
let proof =
Proof_global.close_proof ~keep_body_ucst_separate:true (fun x -> x) in
(* We jump at the beginning since the kernel handles side effects by also
* looking at the ones that happen to be present in the current env *)
Reach.known_state ~cache:`No start;
vernac_interp stop ~proof
{ verbose = false; loc; indentation = 0; strlen = 0;
expr = (VernacEndProof (Proved (Opaque None,None))) };
`OK proof
end
with e ->
let (e, info) = CErrors.push e in
(try match Stateid.get info with
| None ->
msg_error (
str"File " ++ str name ++ str ": proof of " ++ str r_name ++
spc () ++ iprint (e, info))
| Some (_, cur) ->
match VCS.visit cur with
| { step = `Cmd { cast = { loc } } }
| { step = `Fork (( { loc }, _, _, _), _) }
| { step = `Qed ( { qast = { loc } }, _) }
| { step = `Sideff (`Ast ( { loc }, _)) } ->
let start, stop = Loc.unloc loc in
msg_error (
str"File " ++ str name ++ str ": proof of " ++ str r_name ++
str ": chars " ++ int start ++ str "-" ++ int stop ++
spc () ++ iprint (e, info))
| _ ->
msg_error (
str"File " ++ str name ++ str ": proof of " ++ str r_name ++
spc () ++ iprint (e, info))
with e ->
msg_error (str"unable to print error message: " ++
str (Printexc.to_string e)));
if drop then `ERROR_ADMITTED else `ERROR
let finish_task name (u,cst,_) d p l i =
let { Stateid.uuid = bucket }, drop = List.nth l i in
let bucket_name =
if bucket < 0 then (assert drop; ", no bucket")
else Printf.sprintf ", bucket %d" bucket in
match check_task_aux bucket_name name l i with
| `ERROR -> exit 1
| `ERROR_ADMITTED -> u, cst, false
| `OK_ADMITTED -> u, cst, false
| `OK (po,_) ->
let discharge c = List.fold_right Cooking.cook_constr d.(bucket) c in
let con =
Nametab.locate_constant
(Libnames.qualid_of_ident po.Proof_global.id) in
let c = Global.lookup_constant con in
let o = match c.Declarations.const_body with
| Declarations.OpaqueDef o -> o
| _ -> assert false in
let uc =
Option.get
(Opaqueproof.get_constraints (Global.opaque_tables ()) o) in
let pr =
Future.from_val (Option.get (Global.body_of_constant_body c)) in
let uc =
Future.chain
~greedy:true ~pure:true uc Univ.hcons_universe_context_set in
let pr = Future.chain ~greedy:true ~pure:true pr discharge in
let pr = Future.chain ~greedy:true ~pure:true pr Constr.hcons in
Future.sink pr;
let extra = Future.join uc in
u.(bucket) <- uc;
p.(bucket) <- pr;
u, Univ.ContextSet.union cst extra, false
let check_task name l i =
match check_task_aux "" name l i with
| `OK _ | `OK_ADMITTED -> true
| `ERROR | `ERROR_ADMITTED -> false
let info_tasks l =
CList.map_i (fun i ({ Stateid.loc; name }, _) ->
let time1 =
try float_of_string (Aux_file.get !hints loc "proof_build_time")
with Not_found -> 0.0 in
let time2 =
try float_of_string (Aux_file.get !hints loc "proof_check_time")
with Not_found -> 0.0 in
name, max (time1 +. time2) 0.0001,i) 0 l
let set_perspective idl =
ProofTask.set_perspective idl;
TaskQueue.broadcast (Option.get !queue);
let open ProofTask in
let overlap s1 s2 =
List.exists (fun x -> CList.mem_f Stateid.equal x s2) s1 in
let overlap_rel s1 s2 =
match overlap s1 idl, overlap s2 idl with
| true, true | false, false -> 0
| true, false -> -1
| false, true -> 1 in
TaskQueue.set_order (Option.get !queue) (fun task1 task2 ->
match task1, task2 with
| BuildProof { t_states = s1 },
BuildProof { t_states = s2 } -> overlap_rel s1 s2
| _ -> 0)
let build_proof ~loc ~drop_pt ~exn_info ~block_start ~block_stop ~name:pname =
let id, valid as t_exn_info = exn_info in
let cancel_switch = ref false in
if TaskQueue.n_workers (Option.get !queue) = 0 then
if !Flags.compilation_mode = Flags.BuildVio then begin
let f,assign =
Future.create_delegate ~blocking:true ~name:pname (State.exn_on id ~valid) in
let t_uuid = Future.uuid f in
let task = ProofTask.(BuildProof {
t_exn_info; t_start = block_start; t_stop = block_stop; t_drop = drop_pt;
t_assign = assign; t_loc = loc; t_uuid; t_name = pname;
t_states = VCS.nodes_in_slice ~block_start ~block_stop }) in
TaskQueue.enqueue_task (Option.get !queue) (task,cancel_switch);
f, cancel_switch
end else
ProofTask.build_proof_here ~drop_pt t_exn_info loc block_stop, cancel_switch
else
let f, t_assign = Future.create_delegate ~name:pname (State.exn_on id ~valid) in
let t_uuid = Future.uuid f in
feedback (InProgress 1);
let task = ProofTask.(BuildProof {
t_exn_info; t_start = block_start; t_stop = block_stop; t_assign; t_drop = drop_pt;
t_loc = loc; t_uuid; t_name = pname;
t_states = VCS.nodes_in_slice ~block_start ~block_stop }) in
TaskQueue.enqueue_task (Option.get !queue) (task,cancel_switch);
f, cancel_switch
let wait_all_done () = TaskQueue.join (Option.get !queue)
let cancel_worker n = TaskQueue.cancel_worker (Option.get !queue) n
(* For external users this name is nicer than request *)
type 'a tasks = (('a,VCS.vcs) Stateid.request * bool) list
let dump_snapshot () =
let tasks = TaskQueue.snapshot (Option.get !queue) in
let reqs =
CList.map_filter
ProofTask.(fun x ->
match request_of_task `Fresh x with
| Some (ReqBuildProof (r, b, _)) -> Some(r, b)
| _ -> None)
tasks in
prerr_endline (fun () -> Printf.sprintf "dumping %d tasks\n" (List.length reqs));
reqs
let reset_task_queue () = TaskQueue.clear (Option.get !queue)
end (* }}} *)
and TacTask : sig
type output = Constr.constr * Evd.evar_universe_context
type task = {
t_state : Stateid.t;
t_state_fb : Stateid.t;
t_assign : output Future.assignement -> unit;
t_ast : int * aast;
t_goal : Goal.goal;
t_kill : unit -> unit;
t_name : string }
exception NoProgress
include AsyncTaskQueue.Task with type task := task
end = struct (* {{{ *)
type output = Constr.constr * Evd.evar_universe_context
let forward_feedback msg = Hooks.(call forward_feedback msg)
type task = {
t_state : Stateid.t;
t_state_fb : Stateid.t;
t_assign : output Future.assignement -> unit;
t_ast : int * aast;
t_goal : Goal.goal;
t_kill : unit -> unit;
t_name : string }
type request = {
r_state : Stateid.t;
r_state_fb : Stateid.t;
r_document : VCS.vcs option;
r_ast : int * aast;
r_goal : Goal.goal;
r_name : string }
type response =
| RespBuiltSubProof of output
| RespError of std_ppcmds
| RespNoProgress
exception NoProgress
let name = ref "tacworker"
let extra_env () = [||]
type competence = unit
let task_match _ _ = true
(* run by the master, on a thread *)
let request_of_task age { t_state; t_state_fb; t_ast; t_goal; t_name } =
try Some {
r_state = t_state;
r_state_fb = t_state_fb;
r_document =
if age <> `Fresh then None
else Some (VCS.slice ~block_start:t_state ~block_stop:t_state);
r_ast = t_ast;
r_goal = t_goal;
r_name = t_name }
with VCS.Expired -> None
let use_response _ { t_assign; t_state; t_state_fb; t_kill } resp =
match resp with
| RespBuiltSubProof o -> t_assign (`Val o); `Stay ((),[])
| RespNoProgress ->
let e = (NoProgress, Exninfo.null) in
t_assign (`Exn e);
t_kill ();
`Stay ((),[])
| RespError msg ->
let e = (RemoteException msg, Exninfo.null) in
t_assign (`Exn e);
t_kill ();
`Stay ((),[])
let on_marshal_error err { t_name } =
pr_err ("Fatal marshal error: " ^ t_name );
flush_all (); exit 1
let on_task_cancellation_or_expiration_or_slave_death = function
| Some { t_kill } -> t_kill ()
| _ -> ()
let command_focus = Proof.new_focus_kind ()
let focus_cond = Proof.no_cond command_focus
let perform { r_state = id; r_state_fb; r_document = vcs; r_ast; r_goal } =
Option.iter VCS.restore vcs;
try
Reach.known_state ~cache:`No id;
Future.purify (fun () ->
let _,_,_,_,sigma0 = Proof.proof (Proof_global.give_me_the_proof ()) in
let g = Evd.find sigma0 r_goal in
if not (
Evarutil.is_ground_term sigma0 Evd.(evar_concl g) &&
List.for_all (Context.Named.Declaration.for_all (Evarutil.is_ground_term sigma0))
Evd.(evar_context g))
then
CErrors.errorlabstrm "STM" (strbrk("the par: goal selector supports ground "^
"goals only"))
else begin
let (i, ast) = r_ast in
Proof_global.simple_with_current_proof (fun _ p -> Proof.focus focus_cond () i p);
vernac_interp r_state_fb ast;
let _,_,_,_,sigma = Proof.proof (Proof_global.give_me_the_proof ()) in
match Evd.(evar_body (find sigma r_goal)) with
| Evd.Evar_empty -> RespNoProgress
| Evd.Evar_defined t ->
let t = Evarutil.nf_evar sigma t in
if Evarutil.is_ground_term sigma t then
RespBuiltSubProof (t, Evd.evar_universe_context sigma)
else CErrors.errorlabstrm "STM" (str"The solution is not ground")
end) ()
with e when CErrors.noncritical e -> RespError (CErrors.print e)
let name_of_task { t_name } = t_name
let name_of_request { r_name } = r_name
end (* }}} *)
and Partac : sig
val vernac_interp :
solve:bool -> abstract:bool -> cancel_switch ->
int -> Stateid.t -> Stateid.t -> aast ->
unit
end = struct (* {{{ *)
module TaskQueue = AsyncTaskQueue.MakeQueue(TacTask)
let vernac_interp ~solve ~abstract cancel nworkers safe_id id
{ indentation; verbose; loc; expr = e; strlen }
=
let e, time, fail =
let rec find ~time ~fail = function
| VernacTime (_,e) -> find ~time:true ~fail e
| VernacRedirect (_,(_,e)) -> find ~time ~fail e
| VernacFail e -> find ~time ~fail:true e
| e -> e, time, fail in find ~time:false ~fail:false e in
Hooks.call Hooks.with_fail fail (fun () ->
(if time then System.with_time !Flags.time else (fun x -> x)) (fun () ->
ignore(TaskQueue.with_n_workers nworkers (fun queue ->
Proof_global.with_current_proof (fun _ p ->
let goals, _, _, _, _ = Proof.proof p in
let open TacTask in
let res = CList.map_i (fun i g ->
let f, assign =
Future.create_delegate
~name:(Printf.sprintf "subgoal %d" i)
(State.exn_on id ~valid:safe_id) in
let t_ast = (i, { indentation; verbose; loc; expr = e; strlen }) in
let t_name = Goal.uid g in
TaskQueue.enqueue_task queue
({ t_state = safe_id; t_state_fb = id;
t_assign = assign; t_ast; t_goal = g; t_name;
t_kill = (fun () -> if solve then TaskQueue.cancel_all queue) },
cancel);
g,f)
1 goals in
TaskQueue.join queue;
let assign_tac : unit Proofview.tactic =
Proofview.(Goal.nf_enter { Goal.enter = fun g ->
let gid = Goal.goal g in
let f =
try List.assoc gid res
with Not_found -> CErrors.anomaly(str"Partac: wrong focus") in
if not (Future.is_over f) then
(* One has failed and cancelled the others, but not this one *)
if solve then Tacticals.New.tclZEROMSG
(str"Interrupted by the failure of another goal")
else tclUNIT ()
else
let open Notations in
try
let pt, uc = Future.join f in
prerr_endline (fun () -> string_of_ppcmds(hov 0 (
str"g=" ++ int (Evar.repr gid) ++ spc () ++
str"t=" ++ (Printer.pr_constr pt) ++ spc () ++
str"uc=" ++ Evd.pr_evar_universe_context uc)));
(if abstract then Tactics.tclABSTRACT None else (fun x -> x))
(V82.tactic (Refiner.tclPUSHEVARUNIVCONTEXT uc) <*>
Tactics.exact_no_check pt)
with TacTask.NoProgress ->
if solve then Tacticals.New.tclSOLVE [] else tclUNIT ()
})
in
Proof.run_tactic (Global.env()) assign_tac p)))) ())
end (* }}} *)
and QueryTask : sig
type task = { t_where : Stateid.t; t_for : Stateid.t ; t_what : aast }
include AsyncTaskQueue.Task with type task := task
end = struct (* {{{ *)
type task =
{ t_where : Stateid.t; t_for : Stateid.t ; t_what : aast }
type request =
{ r_where : Stateid.t ; r_for : Stateid.t ; r_what : aast; r_doc : VCS.vcs }
type response = unit
let name = ref "queryworker"
let extra_env _ = [||]
type competence = unit
let task_match _ _ = true
let request_of_task _ { t_where; t_what; t_for } =
try Some {
r_where = t_where;
r_for = t_for;
r_doc = VCS.slice ~block_start:t_where ~block_stop:t_where;
r_what = t_what }
with VCS.Expired -> None
let use_response _ _ _ = `End
let on_marshal_error _ _ =
pr_err ("Fatal marshal error in query");
flush_all (); exit 1
let on_task_cancellation_or_expiration_or_slave_death _ = ()
let forward_feedback msg = Hooks.(call forward_feedback msg)
let perform { r_where; r_doc; r_what; r_for } =
VCS.restore r_doc;
VCS.print ();
Reach.known_state ~cache:`No r_where;
try
vernac_interp r_for { r_what with verbose = true };
feedback ~id:(State r_for) Processed
with e when CErrors.noncritical e ->
let e = CErrors.push e in
let msg = pp_to_richpp (iprint e) in
feedback ~id:(State r_for) (Message (Error, None, msg))
let name_of_task { t_what } = string_of_ppcmds (pr_ast t_what)
let name_of_request { r_what } = string_of_ppcmds (pr_ast r_what)
end (* }}} *)
and Query : sig
val init : unit -> unit
val vernac_interp : cancel_switch -> Stateid.t -> Stateid.t -> aast -> unit
end = struct (* {{{ *)
module TaskQueue = AsyncTaskQueue.MakeQueue(QueryTask)
let queue = ref None
let vernac_interp switch prev id q =
assert(TaskQueue.n_workers (Option.get !queue) > 0);
TaskQueue.enqueue_task (Option.get !queue)
QueryTask.({ t_where = prev; t_for = id; t_what = q }, switch)
let init () = queue := Some (TaskQueue.create
(if !Flags.async_proofs_full then 1 else 0))
end (* }}} *)
(* Runs all transactions needed to reach a state *)
and Reach : sig
val known_state :
?redefine_qed:bool -> cache:Summary.marshallable -> Stateid.t -> unit
end = struct (* {{{ *)
let pstate = summary_pstate
let async_policy () =
let open Flags in
if is_universe_polymorphism () then false
else if interactive () = `Yes then
(async_proofs_is_master () || !async_proofs_mode = APonLazy)
else
(!compilation_mode = BuildVio || !async_proofs_mode <> APoff)
let delegate name =
get_hint_bp_time name >= !Flags.async_proofs_delegation_threshold
|| !Flags.compilation_mode = Flags.BuildVio
|| !Flags.async_proofs_full
let warn_deprecated_nested_proofs =
CWarnings.create ~name:"deprecated-nested-proofs" ~category:"deprecated"
(fun () ->
strbrk ("Nested proofs are deprecated and will "^
"stop working in a future Coq version"))
let collect_proof keep cur hd brkind id =
prerr_endline (fun () -> "Collecting proof ending at "^Stateid.to_string id);
let no_name = "" in
let name = function
| [] -> no_name
| id :: _ -> Id.to_string id in
let loc = (snd cur).loc in
let rec is_defined_expr = function
| VernacEndProof (Proved ((Transparent|Opaque (Some _)),_)) -> true
| VernacTime (_, e) -> is_defined_expr e
| VernacRedirect (_, (_, e)) -> is_defined_expr e
| VernacTimeout (_, e) -> is_defined_expr e
| _ -> false in
let is_defined = function
| _, { expr = e } -> is_defined_expr e in
let proof_using_ast = function
| Some (_, ({ expr = VernacProof(_,Some _) } as v)) -> Some v
| _ -> None in
let has_proof_using x = proof_using_ast x <> None in
let proof_no_using = function
| Some (_, ({ expr = VernacProof(t,None) } as v)) -> t,v
| _ -> assert false in
let has_proof_no_using = function
| Some (_, { expr = VernacProof(_,None) }) -> true
| _ -> false in
let too_complex_to_delegate = function
| { expr = (VernacDeclareModule _
| VernacDefineModule _
| VernacDeclareModuleType _
| VernacInclude _) } -> true
| { expr = (VernacRequire _ | VernacImport _) } -> true
| ast -> may_pierce_opaque ast in
let parent = function Some (p, _) -> p | None -> assert false in
let is_empty = function `Async(_,_,[],_,_) | `MaybeASync(_,_,[],_,_) -> true | _ -> false in
let rec collect last accn id =
let view = VCS.visit id in
match view.step with
| (`Sideff (`Ast(x,_)) | `Cmd { cast = x })
when too_complex_to_delegate x -> `Sync(no_name,None,`Print)
| `Cmd { cast = x } -> collect (Some (id,x)) (id::accn) view.next
| `Sideff (`Ast(x,_)) -> collect (Some (id,x)) (id::accn) view.next
(* An Alias could jump everywhere... we hope we can ignore it*)
| `Alias _ -> `Sync (no_name,None,`Alias)
| `Fork((_,_,_,_::_::_), _) ->
`Sync (no_name,proof_using_ast last,`MutualProofs)
| `Fork((_,_,Doesn'tGuaranteeOpacity,_), _) ->
`Sync (no_name,proof_using_ast last,`Doesn'tGuaranteeOpacity)
| `Fork((_,hd',GuaranteesOpacity,ids), _) when has_proof_using last ->
assert (VCS.Branch.equal hd hd' || VCS.Branch.equal hd VCS.edit_branch);
let name = name ids in
`ASync (parent last,proof_using_ast last,accn,name,delegate name)
| `Fork((_, hd', GuaranteesOpacity, ids), _) when
has_proof_no_using last && not (State.is_cached_and_valid (parent last)) &&
!Flags.compilation_mode = Flags.BuildVio ->
assert (VCS.Branch.equal hd hd'||VCS.Branch.equal hd VCS.edit_branch);
(try
let name, hint = name ids, get_hint_ctx loc in
let t, v = proof_no_using last in
v.expr <- VernacProof(t, Some hint);
`ASync (parent last,proof_using_ast last,accn,name,delegate name)
with Not_found ->
let name = name ids in
`MaybeASync (parent last, None, accn, name, delegate name))
| `Fork((_, hd', GuaranteesOpacity, ids), _) ->
assert (VCS.Branch.equal hd hd' || VCS.Branch.equal hd VCS.edit_branch);
let name = name ids in
`MaybeASync (parent last, None, accn, name, delegate name)
| `Sideff _ ->
warn_deprecated_nested_proofs ();
`Sync (no_name,None,`NestedProof)
| _ -> `Sync (no_name,None,`Unknown) in
let make_sync why = function
| `Sync(name,pua,_) -> `Sync (name,pua,why)
| `MaybeASync(_,pua,_,name,_) -> `Sync (name,pua,why)
| `ASync(_,pua,_,name,_) -> `Sync (name,pua,why) in
let check_policy rc = if async_policy () then rc else make_sync `Policy rc in
match cur, (VCS.visit id).step, brkind with
| (parent, { expr = VernacExactProof _ }), `Fork _, _ ->
`Sync (no_name,None,`Immediate)
| _, _, { VCS.kind = `Edit _ } -> check_policy (collect (Some cur) [] id)
| _ ->
if is_defined cur then `Sync (no_name,None,`Transparent)
else if keep == VtDrop then `Sync (no_name,None,`Aborted)
else
let rc = collect (Some cur) [] id in
if is_empty rc then make_sync `AlreadyEvaluated rc
else if (keep == VtKeep || keep == VtKeepAsAxiom) &&
(not(State.is_cached_and_valid id) || !Flags.async_proofs_full)
then check_policy rc
else make_sync `AlreadyEvaluated rc
let string_of_reason = function
| `Transparent -> "non opaque"
| `AlreadyEvaluated -> "proof already evaluated"
| `Policy -> "policy"
| `NestedProof -> "contains nested proof"
| `Immediate -> "proof term given explicitly"
| `Aborted -> "aborted proof"
| `Doesn'tGuaranteeOpacity -> "not a simple opaque lemma"
| `MutualProofs -> "block of mutually recursive proofs"
| `Alias -> "contains Undo-like command"
| `Print -> "contains Print-like command"
| `NoPU_NoHint_NoES -> "no 'Proof using..', no .aux file, inside a section"
| `Unknown -> "unsupported case"
let log_string s = prerr_debug (fun () -> "STM: " ^ s)
let log_processing_async id name = log_string Printf.(sprintf
"%s: proof %s: asynch" (Stateid.to_string id) name
)
let log_processing_sync id name reason = log_string Printf.(sprintf
"%s: proof %s: synch (cause: %s)"
(Stateid.to_string id) name (string_of_reason reason)
)
let wall_clock_last_fork = ref 0.0
let known_state ?(redefine_qed=false) ~cache id =
let error_absorbing_tactic id blockname exn =
We keep the static / dynamic part of block detection separate , since
the static part could be performed earlier . As of today there is
no advantage in doing so since no UI can exploit such piece of info
the static part could be performed earlier. As of today there is
no advantage in doing so since no UI can exploit such piece of info *)
detect_proof_block id blockname;
let boxes = VCS.box_of id in
let valid_boxes = CList.map_filter (function
| ProofBlock ({ block_stop } as decl, name) when Stateid.equal block_stop id ->
Some (decl, name)
| _ -> None) boxes in
assert(List.length valid_boxes < 2);
if valid_boxes = [] then iraise exn
else
let decl, name = List.hd valid_boxes in
try
let _, dynamic_check = List.assoc name !proof_block_delimiters in
match dynamic_check decl with
| `Leaks -> iraise exn
| `ValidBlock { base_state; goals_to_admit; recovery_command } -> begin
let tac =
let open Proofview.Notations in
Proofview.Goal.nf_enter { enter = fun gl ->
if CList.mem_f Evar.equal
(Proofview.Goal.goal gl) goals_to_admit then
Proofview.give_up else Proofview.tclUNIT ()
} in
match (VCS.get_info base_state).state with
| Valid { proof } ->
Proof_global.unfreeze proof;
Proof_global.with_current_proof (fun _ p ->
feedback ~id:(State id) Feedback.AddedAxiom;
fst (Pfedit.solve Vernacexpr.SelectAll None tac p), ());
Option.iter (fun expr -> vernac_interp id {
verbose = true; loc = Loc.ghost; expr; indentation = 0;
strlen = 0 })
recovery_command
| _ -> assert false
end
with Not_found ->
CErrors.errorlabstrm "STM"
(str "Unknown proof block delimiter " ++ str name)
in
(* Absorb tactic errors from f () *)
let resilient_tactic id blockname f =
if !Flags.async_proofs_tac_error_resilience = `None ||
(Flags.async_proofs_is_master () &&
!Flags.async_proofs_mode = Flags.APoff)
then f ()
else
try f ()
with e when CErrors.noncritical e ->
let ie = CErrors.push e in
error_absorbing_tactic id blockname ie in
(* Absorb errors from f x *)
let resilient_command f x =
if not !Flags.async_proofs_cmd_error_resilience ||
(Flags.async_proofs_is_master () &&
!Flags.async_proofs_mode = Flags.APoff)
then f x
else
try f x
with e when CErrors.noncritical e -> () in
(* ugly functions to process nested lemmas, i.e. hard to reproduce
* side effects *)
let cherry_pick_non_pstate () =
Summary.freeze_summary ~marshallable:`No ~complement:true pstate,
Lib.freeze ~marshallable:`No in
let inject_non_pstate (s,l) =
Summary.unfreeze_summary s; Lib.unfreeze l; update_global_env ()
in
let rec pure_cherry_pick_non_pstate safe_id id = Future.purify (fun id ->
prerr_endline (fun () -> "cherry-pick non pstate " ^ Stateid.to_string id);
reach ~safe_id id;
cherry_pick_non_pstate ()) id
traverses the dag backward from nodes being already calculated
and reach ?safe_id ?(redefine_qed=false) ?(cache=cache) id =
prerr_endline (fun () -> "reaching: " ^ Stateid.to_string id);
if not redefine_qed && State.is_cached ~cache id then begin
Hooks.(call state_computed id ~in_cache:true);
prerr_endline (fun () -> "reached (cache)");
State.install_cached id
end else
let step, cache_step, feedback_processed =
let view = VCS.visit id in
match view.step with
| `Alias (id,_) -> (fun () ->
reach view.next; reach id
), cache, true
| `Cmd { cast = x; cqueue = `SkipQueue } -> (fun () ->
reach view.next), cache, true
| `Cmd { cast = x; cqueue = `TacQueue (solve,abstract,cancel); cblock } ->
(fun () ->
resilient_tactic id cblock (fun () ->
reach ~cache:`Shallow view.next;
Hooks.(call tactic_being_run true);
Partac.vernac_interp ~solve ~abstract
cancel !Flags.async_proofs_n_tacworkers view.next id x;
Hooks.(call tactic_being_run false))
), cache, true
| `Cmd { cast = x; cqueue = `QueryQueue cancel }
when Flags.async_proofs_is_master () -> (fun () ->
reach view.next;
Query.vernac_interp cancel view.next id x
), cache, false
| `Cmd { cast = x; ceff = eff; ctac = true; cblock } -> (fun () ->
resilient_tactic id cblock (fun () ->
reach view.next;
Hooks.(call tactic_being_run true);
vernac_interp id x;
Hooks.(call tactic_being_run false));
if eff then update_global_env ()
), (if eff then `Yes else cache), true
| `Cmd { cast = x; ceff = eff } -> (fun () ->
(match !Flags.async_proofs_mode with
| Flags.APon | Flags.APonLazy ->
resilient_command reach view.next
| Flags.APoff -> reach view.next);
vernac_interp id x;
if eff then update_global_env ()
), (if eff then `Yes else cache), true
| `Fork ((x,_,_,_), None) -> (fun () ->
resilient_command reach view.next;
vernac_interp id x;
wall_clock_last_fork := Unix.gettimeofday ()
), `Yes, true
| `Fork ((x,_,_,_), Some prev) -> (fun () -> (* nested proof *)
reach ~cache:`Shallow prev;
reach view.next;
(try vernac_interp id x;
with e when CErrors.noncritical e ->
let (e, info) = CErrors.push e in
let info = Stateid.add info ~valid:prev id in
iraise (e, info));
wall_clock_last_fork := Unix.gettimeofday ()
), `Yes, true
| `Qed ({ qast = x; keep; brinfo; brname } as qed, eop) ->
let rec aux = function
| `ASync (block_start, pua, nodes, name, delegate) -> (fun () ->
assert(keep == VtKeep || keep == VtKeepAsAxiom);
let drop_pt = keep == VtKeepAsAxiom in
let block_stop, exn_info, loc = eop, (id, eop), x.loc in
log_processing_async id name;
VCS.create_proof_task_box nodes ~qed:id ~block_start;
begin match brinfo, qed.fproof with
| { VCS.kind = `Edit _ }, None -> assert false
| { VCS.kind = `Edit (_,_,_, okeep, _) }, Some (ofp, cancel) ->
assert(redefine_qed = true);
if okeep != keep then
msg_error(strbrk("The command closing the proof changed. "
^"The kernel cannot take this into account and will "
^(if keep == VtKeep then "not check " else "reject ")
^"the "^(if keep == VtKeep then "new" else "incomplete")
^" proof. Reprocess the command declaring "
^"the proof's statement to avoid that."));
let fp, cancel =
Slaves.build_proof
~loc ~drop_pt ~exn_info ~block_start ~block_stop ~name in
Future.replace ofp fp;
qed.fproof <- Some (fp, cancel);
We do n't generate a new state , but we still need
* to install the right one
* to install the right one *)
State.install_cached id
| { VCS.kind = `Proof _ }, Some _ -> assert false
| { VCS.kind = `Proof _ }, None ->
reach ~cache:`Shallow block_start;
let fp, cancel =
if delegate then
Slaves.build_proof
~loc ~drop_pt ~exn_info ~block_start ~block_stop ~name
else
ProofTask.build_proof_here
~drop_pt exn_info loc block_stop, ref false
in
qed.fproof <- Some (fp, cancel);
let proof =
Proof_global.close_future_proof ~feedback_id:id fp in
if not delegate then ignore(Future.compute fp);
reach view.next;
vernac_interp id ~proof x;
feedback ~id:(State id) Incomplete
| { VCS.kind = `Master }, _ -> assert false
end;
Proof_global.discard_all ()
), (if redefine_qed then `No else `Yes), true
| `Sync (name, _, `Immediate) -> (fun () ->
reach eop; vernac_interp id x; Proof_global.discard_all ()
), `Yes, true
| `Sync (name, pua, reason) -> (fun () ->
log_processing_sync id name reason;
reach eop;
let wall_clock = Unix.gettimeofday () in
record_pb_time name x.loc (wall_clock -. !wall_clock_last_fork);
let proof =
match keep with
| VtDrop -> None
| VtKeepAsAxiom ->
let ctx = Evd.empty_evar_universe_context in
let fp = Future.from_val ([],ctx) in
qed.fproof <- Some (fp, ref false); None
| VtKeep ->
Some(Proof_global.close_proof
~keep_body_ucst_separate:false
(State.exn_on id ~valid:eop)) in
if keep != VtKeepAsAxiom then
reach view.next;
let wall_clock2 = Unix.gettimeofday () in
vernac_interp id ?proof x;
let wall_clock3 = Unix.gettimeofday () in
Aux_file.record_in_aux_at x.loc "proof_check_time"
(Printf.sprintf "%.3f" (wall_clock3 -. wall_clock2));
Proof_global.discard_all ()
), `Yes, true
| `MaybeASync (start, pua, nodes, name, delegate) -> (fun () ->
reach ~cache:`Shallow start;
(* no sections *)
if List.is_empty (Environ.named_context (Global.env ()))
then pi1 (aux (`ASync (start, pua, nodes, name, delegate))) ()
else pi1 (aux (`Sync (name, pua, `NoPU_NoHint_NoES))) ()
), (if redefine_qed then `No else `Yes), true
in
aux (collect_proof keep (view.next, x) brname brinfo eop)
| `Sideff (`Ast (x,_)) -> (fun () ->
reach view.next; vernac_interp id x; update_global_env ()
), cache, true
| `Sideff (`Id origin) -> (fun () ->
reach view.next;
inject_non_pstate (pure_cherry_pick_non_pstate view.next origin);
), cache, true
in
let cache_step =
if !Flags.async_proofs_cache = Some Flags.Force then `Yes
else cache_step in
State.define ?safe_id
~cache:cache_step ~redefine:redefine_qed ~feedback_processed step id;
prerr_endline (fun () -> "reached: "^ Stateid.to_string id) in
reach ~redefine_qed id
end (* }}} *)
(********************************* STM API ************************************)
(******************************************************************************)
let init () =
VCS.init Stateid.initial;
set_undo_classifier Backtrack.undo_vernac_classifier;
State.define ~cache:`Yes (fun () -> ()) Stateid.initial;
Backtrack.record ();
Slaves.init ();
if Flags.async_proofs_is_master () then begin
prerr_endline (fun () -> "Initializing workers");
Query.init ();
let opts = match !Flags.async_proofs_private_flags with
| None -> []
| Some s -> Str.split_delim (Str.regexp ",") s in
begin try
let env_opt = Str.regexp "^extra-env=" in
let env = List.find (fun s -> Str.string_match env_opt s 0) opts in
async_proofs_workers_extra_env := Array.of_list
(Str.split_delim (Str.regexp ";") (Str.replace_first env_opt "" env))
with Not_found -> () end;
end
let observe id =
let vcs = VCS.backup () in
try
Reach.known_state ~cache:(interactive ()) id;
VCS.print ()
with e ->
let e = CErrors.push e in
VCS.print ();
VCS.restore vcs;
iraise e
let finish ?(print_goals=false) () =
let head = VCS.current_branch () in
observe (VCS.get_branch_pos head);
if print_goals then msg_notice (pr_open_cur_subgoals ());
VCS.print ();
(* Some commands may by side effect change the proof mode *)
match VCS.get_branch head with
| { VCS.kind = `Edit (mode,_,_,_,_) } -> Proof_global.activate_proof_mode mode
| { VCS.kind = `Proof (mode, _) } -> Proof_global.activate_proof_mode mode
| _ -> ()
let wait () =
Slaves.wait_all_done ();
VCS.print ()
let rec join_admitted_proofs id =
if Stateid.equal id Stateid.initial then () else
let view = VCS.visit id in
match view.step with
| `Qed ({ keep = VtKeepAsAxiom; fproof = Some (fp,_) },_) ->
ignore(Future.force fp);
join_admitted_proofs view.next
| _ -> join_admitted_proofs view.next
let join () =
finish ();
wait ();
prerr_endline (fun () -> "Joining the environment");
Global.join_safe_environment ();
prerr_endline (fun () -> "Joining Admitted proofs");
join_admitted_proofs (VCS.get_branch_pos (VCS.current_branch ()));
VCS.print ();
VCS.print ()
let dump_snapshot () = Slaves.dump_snapshot (), RemoteCounter.snapshot ()
type document = VCS.vcs
type tasks = int Slaves.tasks * RemoteCounter.remote_counters_status
let check_task name (tasks,rcbackup) i =
RemoteCounter.restore rcbackup;
let vcs = VCS.backup () in
try
let rc = Future.purify (Slaves.check_task name tasks) i in
VCS.restore vcs;
rc
with e when CErrors.noncritical e -> VCS.restore vcs; false
let info_tasks (tasks,_) = Slaves.info_tasks tasks
let finish_tasks name u d p (t,rcbackup as tasks) =
RemoteCounter.restore rcbackup;
let finish_task u (_,_,i) =
let vcs = VCS.backup () in
let u = Future.purify (Slaves.finish_task name u d p t) i in
VCS.restore vcs;
u in
try
let u, a, _ = List.fold_left finish_task u (info_tasks tasks) in
(u,a,true), p
with e ->
let e = CErrors.push e in
msg_error (str"File " ++ str name ++ str ":" ++ spc () ++ iprint e);
exit 1
let merge_proof_branch ~valid ?id qast keep brname =
let brinfo = VCS.get_branch brname in
let qed fproof = { qast; keep; brname; brinfo; fproof } in
match brinfo with
| { VCS.kind = `Proof _ } ->
VCS.checkout VCS.Branch.master;
let id = VCS.new_node ?id () in
VCS.merge id ~ours:(Qed (qed None)) brname;
VCS.delete_branch brname;
VCS.propagate_sideff None;
`Ok
| { VCS.kind = `Edit (mode, qed_id, master_id, _,_) } ->
let ofp =
match VCS.visit qed_id with
| { step = `Qed ({ fproof }, _) } -> fproof
| _ -> assert false in
VCS.rewrite_merge qed_id ~ours:(Qed (qed ofp)) ~at:master_id brname;
VCS.delete_branch brname;
VCS.gc ();
Reach.known_state ~redefine_qed:true ~cache:`No qed_id;
VCS.checkout VCS.Branch.master;
`Unfocus qed_id
| { VCS.kind = `Master } ->
iraise (State.exn_on ~valid Stateid.dummy (Proof_global.NoCurrentProof, Exninfo.null))
(* When tty is true, this code also does some of the job of the user interface:
jump back to a state that is valid *)
let handle_failure (e, info) vcs tty =
if e = CErrors.Drop then iraise (e, info) else
match Stateid.get info with
| None ->
VCS.restore vcs;
VCS.print ();
if tty && interactive () = `Yes then begin
Hopefully the 1 to last state is valid
Backtrack.back_safe ();
VCS.checkout_shallowest_proof_branch ();
end;
VCS.print ();
anomaly(str"error with no safe_id attached:" ++ spc() ++
CErrors.iprint_no_report (e, info))
| Some (safe_id, id) ->
prerr_endline (fun () -> "Failed at state " ^ Stateid.to_string id);
VCS.restore vcs;
if tty && interactive () = `Yes then begin
(* We stay on a valid state *)
Backtrack.backto safe_id;
VCS.checkout_shallowest_proof_branch ();
Reach.known_state ~cache:(interactive ()) safe_id;
end;
VCS.print ();
iraise (e, info)
let snapshot_vio ldir long_f_dot_vo =
finish ();
if List.length (VCS.branches ()) > 1 then
CErrors.errorlabstrm "stm" (str"Cannot dump a vio with open proofs");
Library.save_library_to ~todo:(dump_snapshot ()) ldir long_f_dot_vo
(Global.opaque_tables ())
let reset_task_queue = Slaves.reset_task_queue
(* Document building *)
let process_transaction ?(newtip=Stateid.fresh ()) ~tty
({ verbose; loc; expr } as x) c =
prerr_endline (fun () -> "{{{ processing: "^ string_of_ppcmds (pr_ast x));
let vcs = VCS.backup () in
try
let head = VCS.current_branch () in
VCS.checkout head;
let rc = begin
prerr_endline (fun () ->
" classified as: " ^ string_of_vernac_classification c);
let (vt, vw) = c in
Ptcoq.show_vernac_typ_exp vt expr;
match c with
(* PG stuff *)
| VtStm(VtPG,false), VtNow -> vernac_interp Stateid.dummy x; `Ok
| VtStm(VtPG,_), _ -> anomaly(str "PG command in script or VtLater")
(* Joining various parts of the document *)
| VtStm (VtJoinDocument, b), VtNow -> join (); `Ok
| VtStm (VtFinish, b), VtNow -> finish (); `Ok
| VtStm (VtWait, b), VtNow -> finish (); wait (); `Ok
| VtStm (VtPrintDag, b), VtNow ->
VCS.print ~now:true (); `Ok
| VtStm (VtObserve id, b), VtNow -> observe id; `Ok
| VtStm ((VtObserve _ | VtFinish | VtJoinDocument
|VtPrintDag |VtWait),_), VtLater ->
anomaly(str"classifier: join actions cannot be classified as VtLater")
(* Back *)
| VtStm (VtBack oid, true), w ->
let id = VCS.new_node ~id:newtip () in
let { mine; others } = Backtrack.branches_of oid in
let valid = VCS.get_branch_pos head in
List.iter (fun branch ->
if not (List.mem_assoc branch (mine::others)) then
ignore(merge_proof_branch ~valid x VtDrop branch))
(VCS.branches ());
VCS.checkout_shallowest_proof_branch ();
let head = VCS.current_branch () in
List.iter (fun b ->
if not(VCS.Branch.equal b head) then begin
VCS.checkout b;
VCS.commit (VCS.new_node ()) (Alias (oid,x));
end)
(VCS.branches ());
VCS.checkout_shallowest_proof_branch ();
VCS.commit id (Alias (oid,x));
Backtrack.record (); if w == VtNow then finish (); `Ok
| VtStm (VtBack id, false), VtNow ->
prerr_endline (fun () -> "undo to state " ^ Stateid.to_string id);
Backtrack.backto id;
VCS.checkout_shallowest_proof_branch ();
Reach.known_state ~cache:(interactive ()) id; `Ok
| VtStm (VtBack id, false), VtLater ->
anomaly(str"classifier: VtBack + VtLater must imply part_of_script")
(* Query *)
| VtQuery (false,(report_id,route)), VtNow when tty = true ->
finish ();
(try Future.purify (vernac_interp report_id ~route)
{x with verbose = true }
with e when CErrors.noncritical e ->
let e = CErrors.push e in
iraise (State.exn_on ~valid:Stateid.dummy report_id e)); `Ok
| VtQuery (false,(report_id,route)), VtNow ->
(try vernac_interp report_id ~route x
with e ->
let e = CErrors.push e in
iraise (State.exn_on ~valid:Stateid.dummy report_id e)); `Ok
| VtQuery (true,(report_id,_)), w ->
assert(Stateid.equal report_id Stateid.dummy);
let id = VCS.new_node ~id:newtip () in
let queue =
if !Flags.async_proofs_full then `QueryQueue (ref false)
else if Flags.(!compilation_mode = BuildVio) &&
VCS.((get_branch head).kind = `Master) &&
may_pierce_opaque x
then `SkipQueue
else `MainQueue in
VCS.commit id (mkTransCmd x [] false queue);
Backtrack.record (); if w == VtNow then finish (); `Ok
| VtQuery (false,_), VtLater ->
anomaly(str"classifier: VtQuery + VtLater must imply part_of_script")
(* Proof *)
| VtStartProof (mode, guarantee, names), w ->
let id = VCS.new_node ~id:newtip () in
let bname = VCS.mk_branch_name x in
VCS.checkout VCS.Branch.master;
if VCS.Branch.equal head VCS.Branch.master then begin
VCS.commit id (Fork (x, bname, guarantee, names));
VCS.branch bname (`Proof (mode, VCS.proof_nesting () + 1))
end else begin
VCS.branch bname (`Proof (mode, VCS.proof_nesting () + 1));
VCS.merge id ~ours:(Fork (x, bname, guarantee, names)) head
end;
Proof_global.activate_proof_mode mode;
Backtrack.record (); if w == VtNow then finish (); `Ok
| VtProofMode _, VtLater ->
anomaly(str"VtProofMode must be executed VtNow")
| VtProofMode mode, VtNow ->
let id = VCS.new_node ~id:newtip () in
VCS.commit id (mkTransCmd x [] false `MainQueue);
List.iter
(fun bn -> match VCS.get_branch bn with
| { VCS.root; kind = `Master; pos } -> ()
| { VCS.root; kind = `Proof(_,d); pos } ->
VCS.delete_branch bn;
VCS.branch ~root ~pos bn (`Proof(mode,d))
| { VCS.root; kind = `Edit(_,f,q,k,ob); pos } ->
VCS.delete_branch bn;
VCS.branch ~root ~pos bn (`Edit(mode,f,q,k,ob)))
(VCS.branches ());
VCS.checkout_shallowest_proof_branch ();
Backtrack.record ();
finish ();
`Ok
| VtProofStep { parallel; proof_block_detection = cblock }, w ->
let id = VCS.new_node ~id:newtip () in
let queue =
match parallel with
| `Yes(solve,abstract) -> `TacQueue (solve, abstract, ref false)
| `No -> `MainQueue in
VCS.commit id (mkTransTac x cblock queue);
Static proof block detection delayed until an error really occurs .
If / when and UI will make something useful with this piece of info ,
detection should occur here .
detect_proof_block i d cblock ;
If/when and UI will make something useful with this piece of info,
detection should occur here.
detect_proof_block id cblock; *)
Backtrack.record (); if w == VtNow then finish (); `Ok
| VtQed keep, w ->
let valid = VCS.get_branch_pos head in
let rc = merge_proof_branch ~valid ~id:newtip x keep head in
VCS.checkout_shallowest_proof_branch ();
Backtrack.record (); if w == VtNow then finish ();
rc
(* Side effect on all branches *)
| VtUnknown, _ when expr = VernacToplevelControl Drop ->
vernac_interp (VCS.get_branch_pos head) x; `Ok
| VtSideff l, w ->
let in_proof = not (VCS.Branch.equal head VCS.Branch.master) in
let id = VCS.new_node ~id:newtip () in
VCS.checkout VCS.Branch.master;
VCS.commit id (mkTransCmd x l in_proof `MainQueue);
We ca n't replay a Definition since universes may be differently
* inferred . This holds in Coq > = 8.5
* inferred. This holds in Coq >= 8.5 *)
let replay = match x.expr with
| VernacDefinition(_, _, DefineBody _) -> None
| _ -> Some x in
VCS.propagate_sideff ~replay;
VCS.checkout_shallowest_proof_branch ();
Backtrack.record (); if w == VtNow then finish (); `Ok
Unknown : we execute it , check for open goals and propagate sideeff
| VtUnknown, VtNow ->
let in_proof = not (VCS.Branch.equal head VCS.Branch.master) in
let id = VCS.new_node ~id:newtip () in
let head_id = VCS.get_branch_pos head in
Reach.known_state ~cache:`Yes head_id; (* ensure it is ok *)
let step () =
VCS.checkout VCS.Branch.master;
let mid = VCS.get_branch_pos VCS.Branch.master in
Reach.known_state ~cache:(interactive ()) mid;
vernac_interp id x;
Vernac x may or may not start a proof
if not in_proof && Proof_global.there_are_pending_proofs () then
begin
let bname = VCS.mk_branch_name x in
let rec opacity_of_produced_term = function
This AST is ambiguous , hence we check it dynamically
| VernacInstance (false, _,_ , None, _) -> GuaranteesOpacity
| VernacLocal (_,e) -> opacity_of_produced_term e
| _ -> Doesn'tGuaranteeOpacity in
VCS.commit id (Fork (x,bname,opacity_of_produced_term x.expr,[]));
let proof_mode = default_proof_mode () in
VCS.branch bname (`Proof (proof_mode, VCS.proof_nesting () + 1));
Proof_global.activate_proof_mode proof_mode;
Ptcoq.begin_proof_nonstd expr;
end else begin
VCS.commit id (mkTransCmd x [] in_proof `MainQueue);
(* We hope it can be replayed, but we can't really know *)
VCS.propagate_sideff ~replay:(Some x);
VCS.checkout_shallowest_proof_branch ();
end in
State.define ~safe_id:head_id ~cache:`Yes step id;
Backtrack.record (); `Ok
| VtUnknown, VtLater ->
anomaly(str"classifier: VtUnknown must imply VtNow")
end in
(* Proof General *)
begin match expr with
| VernacStm (PGLast _) ->
if not (VCS.Branch.equal head VCS.Branch.master) then
vernac_interp Stateid.dummy
{ verbose = true; loc = Loc.ghost; indentation = 0; strlen = 0;
expr = VernacShow (ShowGoal OpenSubgoals) }
| _ -> ()
end;
prerr_endline (fun () -> "processed }}}");
VCS.print ();
rc
with e ->
let e = CErrors.push e in
handle_failure e vcs tty
let get_ast id =
match VCS.visit id with
| { step = `Cmd { cast = { loc; expr } } }
| { step = `Fork (({ loc; expr }, _, _, _), _) }
| { step = `Qed ({ qast = { loc; expr } }, _) } ->
Some (expr, loc)
| _ -> None
let stop_worker n = Slaves.cancel_worker n
You may need to know the len + indentation of previous command to compute
* the indentation of the current one .
* Eg . foo . bar .
* Here bar is indented of the indentation of foo + its strlen ( 4 )
* the indentation of the current one.
* Eg. foo. bar.
* Here bar is indented of the indentation of foo + its strlen (4) *)
let ind_len_of id =
if Stateid.equal id Stateid.initial then 0
else match (VCS.visit id).step with
| `Cmd { ctac = true; cast = { indentation; strlen } } ->
indentation + strlen
| _ -> 0
let add ~ontop ?newtip ?(check=ignore) verb eid s =
let cur_tip = VCS.cur_tip () in
if not (Stateid.equal ontop cur_tip) then
(* For now, arbitrary edits should be announced with edit_at *)
anomaly(str"Not yet implemented, the GUI should not try this");
let indentation, strlen, loc, ast =
vernac_parse ~indlen_prev:(fun () -> ind_len_of ontop) ?newtip eid s in
CWarnings.set_current_loc loc;
check(loc,ast);
let clas = classify_vernac ast in
let aast = { verbose = verb; indentation; strlen; loc; expr = ast } in
match process_transaction ?newtip ~tty:false aast clas with
| `Ok -> VCS.cur_tip (), `NewTip
| `Unfocus qed_id -> qed_id, `Unfocus (VCS.cur_tip ())
let set_perspective id_list = Slaves.set_perspective id_list
type focus = {
start : Stateid.t;
stop : Stateid.t;
tip : Stateid.t
}
let query ~at ?(report_with=(Stateid.dummy,default_route)) s =
Future.purify (fun s ->
if Stateid.equal at Stateid.dummy then finish ()
else Reach.known_state ~cache:`Yes at;
let newtip, route = report_with in
let indentation, strlen, loc, ast = vernac_parse ~newtip ~route 0 s in
CWarnings.set_current_loc loc;
let clas = classify_vernac ast in
let aast = { verbose = true; indentation; strlen; loc; expr = ast } in
match clas with
| VtStm (w,_), _ ->
ignore(process_transaction ~tty:false aast (VtStm (w,false), VtNow))
| _ ->
ignore(process_transaction
~tty:false aast (VtQuery (false,report_with), VtNow)))
s
let edit_at id =
if Stateid.equal id Stateid.dummy then anomaly(str"edit_at dummy") else
let vcs = VCS.backup () in
let on_cur_branch id =
let rec aux cur =
if id = cur then true
else match VCS.visit cur with
| { step = `Fork _ } -> false
| { next } -> aux next in
aux (VCS.get_branch_pos (VCS.current_branch ())) in
let rec is_pure_aux id =
let view = VCS.visit id in
match view.step with
| `Cmd _ -> is_pure_aux view.next
| `Fork _ -> true
| _ -> false in
let is_pure id =
match (VCS.visit id).step with
| `Qed (_,last_step) -> is_pure_aux last_step
| _ -> assert false
in
let is_ancestor_of_cur_branch id =
Stateid.Set.mem id
(VCS.reachable (VCS.get_branch_pos (VCS.current_branch ()))) in
let has_failed qed_id =
match VCS.visit qed_id with
| { step = `Qed ({ fproof = Some (fp,_) }, _) } -> Future.is_exn fp
| _ -> false in
let rec master_for_br root tip =
if Stateid.equal tip Stateid.initial then tip else
match VCS.visit tip with
| { step = (`Fork _ | `Qed _) } -> tip
| { step = `Sideff (`Ast(_,id)) } -> id
| { step = `Sideff _ } -> tip
| { next } -> master_for_br root next in
let reopen_branch start at_id mode qed_id tip old_branch =
let master_id, cancel_switch, keep =
(* Hum, this should be the real start_id in the cluster and not next *)
match VCS.visit qed_id with
| { step = `Qed ({ fproof = Some (_,cs); keep },_) } -> start, cs, keep
| _ -> anomaly (str "ProofTask not ending with Qed") in
VCS.branch ~root:master_id ~pos:id
VCS.edit_branch (`Edit (mode, qed_id, master_id, keep, old_branch));
VCS.delete_boxes_of id;
cancel_switch := true;
Reach.known_state ~cache:(interactive ()) id;
VCS.checkout_shallowest_proof_branch ();
`Focus { stop = qed_id; start = master_id; tip } in
let no_edit = function
| `Edit (pm, _,_,_,_) -> `Proof(pm,1)
| x -> x in
let backto id bn =
List.iter VCS.delete_branch (VCS.branches ());
let ancestors = VCS.reachable id in
let { mine = brname, brinfo; others } = Backtrack.branches_of id in
List.iter (fun (name,{ VCS.kind = k; root; pos }) ->
if not(VCS.Branch.equal name VCS.Branch.master) &&
Stateid.Set.mem root ancestors then
VCS.branch ~root ~pos name k)
others;
VCS.reset_branch VCS.Branch.master (master_for_br brinfo.VCS.root id);
VCS.branch ~root:brinfo.VCS.root ~pos:brinfo.VCS.pos
(Option.default brname bn)
(no_edit brinfo.VCS.kind);
VCS.delete_boxes_of id;
VCS.gc ();
VCS.print ();
if not !Flags.async_proofs_full then
Reach.known_state ~cache:(interactive ()) id;
VCS.checkout_shallowest_proof_branch ();
`NewTip in
try
let rc =
let focused = List.exists ((=) VCS.edit_branch) (VCS.branches ()) in
let branch_info =
match snd (VCS.get_info id).vcs_backup with
| Some{ mine = bn, { VCS.kind = `Proof(m,_) }} -> Some(m,bn)
| Some{ mine = _, { VCS.kind = `Edit(m,_,_,_,bn) }} -> Some (m,bn)
| _ -> None in
match focused, VCS.proof_task_box_of id, branch_info with
| _, Some _, None -> assert false
| false, Some { qed = qed_id ; lemma = start }, Some(mode,bn) ->
let tip = VCS.cur_tip () in
if has_failed qed_id && is_pure qed_id && not !Flags.async_proofs_never_reopen_branch
then reopen_branch start id mode qed_id tip bn
else backto id (Some bn)
| true, Some { qed = qed_id }, Some(mode,bn) ->
if on_cur_branch id then begin
assert false
end else if is_ancestor_of_cur_branch id then begin
backto id (Some bn)
end else begin
anomaly(str"Cannot leave an `Edit branch open")
end
| true, None, _ ->
if on_cur_branch id then begin
VCS.reset_branch (VCS.current_branch ()) id;
Reach.known_state ~cache:(interactive ()) id;
VCS.checkout_shallowest_proof_branch ();
`NewTip
end else if is_ancestor_of_cur_branch id then begin
backto id None
end else begin
anomaly(str"Cannot leave an `Edit branch open")
end
| false, None, Some(_,bn) -> backto id (Some bn)
| false, None, None -> backto id None
in
VCS.print ();
rc
with e ->
let (e, info) = CErrors.push e in
match Stateid.get info with
| None ->
VCS.print ();
anomaly (str ("edit_at "^Stateid.to_string id^": ") ++
CErrors.print_no_report e)
| Some (_, id) ->
prerr_endline (fun () -> "Failed at state " ^ Stateid.to_string id);
VCS.restore vcs;
VCS.print ();
iraise (e, info)
let backup () = VCS.backup ()
let restore d = VCS.restore d
* * * * * * * * * * * * * * * * * * * * * * TTY API ( PG , coqtop , coqc ) * * * * * * * * * * * * * * * * * * * * * * * * * *
(******************************************************************************)
let interp verb (loc,e) =
let clas = classify_vernac e in
let aast = { verbose = verb; indentation = 0; strlen = 0; loc; expr = e } in
let rc = process_transaction ~tty:true aast clas in
if rc <> `Ok then anomaly(str"tty loop can't be mixed with the STM protocol");
if interactive () = `Yes ||
(!Flags.async_proofs_mode = Flags.APoff &&
!Flags.compilation_mode = Flags.BuildVo) then
let vcs = VCS.backup () in
let print_goals =
verb && match clas with
| VtQuery _, _ -> false
| (VtProofStep _ | VtStm (VtBack _, _) | VtStartProof _), _ -> true
| _ -> not !Flags.coqtop_ui in
try finish ~print_goals ()
with e ->
let e = CErrors.push e in
handle_failure e vcs true
let finish () = finish ()
let get_current_state () = VCS.cur_tip ()
let current_proof_depth () =
let head = VCS.current_branch () in
match VCS.get_branch head with
| { VCS.kind = `Master } -> 0
| { VCS.pos = cur; VCS.kind = (`Proof _ | `Edit _); VCS.root = root } ->
let rec distance root =
if Stateid.equal cur root then 0
else 1 + distance (VCS.visit cur).next in
distance cur
let unmangle n =
let n = VCS.Branch.to_string n in
let idx = String.index n '_' + 1 in
Names.id_of_string (String.sub n idx (String.length n - idx))
let proofname b = match VCS.get_branch b with
| { VCS.kind = (`Proof _| `Edit _) } -> Some b
| _ -> None
let get_all_proof_names () =
List.map unmangle (List.map_filter proofname (VCS.branches ()))
let get_current_proof_name () =
Option.map unmangle (proofname (VCS.current_branch ()))
let get_script prf =
let branch, test =
match prf with
| None -> VCS.Branch.master, fun _ -> true
| Some name -> VCS.current_branch (),fun nl -> nl=[] || List.mem name nl in
let rec find acc id =
if Stateid.equal id Stateid.initial ||
Stateid.equal id Stateid.dummy then acc else
let view = VCS.visit id in
match view.step with
| `Fork((_,_,_,ns), _) when test ns -> acc
| `Qed (qed, proof) -> find [qed.qast.expr, (VCS.get_info id).n_goals] proof
| `Sideff (`Ast (x,_)) ->
find ((x.expr, (VCS.get_info id).n_goals)::acc) view.next
| `Sideff (`Id id) -> find acc id
| `Cmd {cast = x; ctac} when ctac -> (* skip non-tactics *)
find ((x.expr, (VCS.get_info id).n_goals)::acc) view.next
| `Cmd _ -> find acc view.next
| `Alias (id,_) -> find acc id
| `Fork _ -> find acc view.next
in
find [] (VCS.get_branch_pos branch)
indentation code for Show Script , initially contributed
by
by D. de Rauglaudre *)
let indent_script_item ((ng1,ngl1),nl,beginend,ppl) (cmd,ng) =
(* ng1 : number of goals remaining at the current level (before cmd)
ngl1 : stack of previous levels with their remaining goals
ng : number of goals after the execution of cmd
beginend : special indentation stack for { } *)
let ngprev = List.fold_left (+) ng1 ngl1 in
let new_ngl =
if ng > ngprev then
(* We've branched *)
(ng - ngprev + 1, ng1 - 1 :: ngl1)
else if ng < ngprev then
A subgoal have been solved . Let 's compute the new current level
by discarding all levels with 0 remaining goals .
by discarding all levels with 0 remaining goals. *)
let rec loop = function
| (0, ng2::ngl2) -> loop (ng2,ngl2)
| p -> p
in loop (ng1-1, ngl1)
else
(* Standard case, same goal number as before *)
(ng1, ngl1)
in
When a subgoal have been solved , separate this block by an empty line
let new_nl = (ng < ngprev)
in
(* Indentation depth *)
let ind = List.length ngl1
in
(* Some special handling of bullets and { }, to get a nicer display *)
let pred n = max 0 (n-1) in
let ind, nl, new_beginend = match cmd with
| VernacSubproof _ -> pred ind, nl, (pred ind)::beginend
| VernacEndSubproof -> List.hd beginend, false, List.tl beginend
| VernacBullet _ -> pred ind, nl, beginend
| _ -> ind, nl, beginend
in
let pp =
(if nl then fnl () else mt ()) ++
(hov (ind+1) (str (String.make ind ' ') ++ Ppvernac.pr_vernac cmd))
in
(new_ngl, new_nl, new_beginend, pp :: ppl)
let show_script ?proof () =
try
let prf =
try match proof with
| None -> Some (Pfedit.get_current_proof_name ())
| Some (p,_) -> Some (p.Proof_global.id)
with Proof_global.NoCurrentProof -> None
in
let cmds = get_script prf in
let _,_,_,indented_cmds =
List.fold_left indent_script_item ((1,[]),false,[],[]) cmds
in
let indented_cmds = List.rev (indented_cmds) in
msg_notice (v 0 (prlist_with_sep fnl (fun x -> x) indented_cmds))
with Vcs_aux.Expired -> ()
(* Export hooks *)
let state_computed_hook = Hooks.state_computed_hook
let state_ready_hook = Hooks.state_ready_hook
let parse_error_hook = Hooks.parse_error_hook
let execution_error_hook = Hooks.execution_error_hook
let forward_feedback_hook = Hooks.forward_feedback_hook
let process_error_hook = Hooks.process_error_hook
let interp_hook = Hooks.interp_hook
let with_fail_hook = Hooks.with_fail_hook
let unreachable_state_hook = Hooks.unreachable_state_hook
let get_fix_exn () = !State.fix_exn_ref
let tactic_being_run_hook = Hooks.tactic_being_run_hook
vim : set = marker :
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/stm/stm.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
During interactive use we cache more states so that Undoing is fast
mutable: Proof using hinted by aux file
Commands piercing opaque
TODO 8.7 : split commands and tactics, since this type is too messy now
is a tactic
is a side-effecting command in the middle of a proof
Parts of the system state that are morally part of the proof state
proof state
debug cache: how many times was computed
open goals: indentation
state value
{{{
}}}
************************** THE DOCUMENT ************************************
****************************************************************************
cuts from start -> stop, raising Expired if some nodes are not there
{{{
Fill in
copies the transaction on every open branch
Stm should have reached the beginning of proof
Non blocking Sys.command
No failure
}}}
* The function is from unit, so it uses the current state to define
a new one. I.e. one may been to install the right state before
defining a new one.
Warning: an optimization in installed_cached requires that state
modifying functions are always executed using this wrapper.
to send states across worker/master
{{{
helpers
hack to make futures functional
only meta counters
optimization
}}}
***************************** CRUFT ****************************************
****************************************************************************
The backtrack module simulates the classic behavior of a linear document
To be installed during initialization
{{{
}}}
***************** proof structure for error recovery ***********************
****************************************************************************
***************************** THE SCHEDULER ********************************
****************************************************************************
If set, only tasks overlapping with this list are processed
{{{
We typecheck the proof with the kernel (in the worker) to spot
* the few errors tactics don't catch, like the "fix" tactic building
* a bad fixpoint
This can happen if the proof is broken. The error has also been
* signalled as a feedback, hence we can silently recover
A pure tactic
}}}
Slave processes (if initialized, otherwise local lazy evaluation)
(eventually) remote calls
blocking function that waits for the task queue to be empty
initialize the whole machinery (optional)
{{{
The original terminator, a hook, has not been saved in the .vio
We jump at the beginning since the kernel handles side effects by also
* looking at the ones that happen to be present in the current env
For external users this name is nicer than request
}}}
{{{
run by the master, on a thread
}}}
{{{
One has failed and cancelled the others, but not this one
}}}
{{{
}}}
{{{
}}}
Runs all transactions needed to reach a state
{{{
An Alias could jump everywhere... we hope we can ignore it
Absorb tactic errors from f ()
Absorb errors from f x
ugly functions to process nested lemmas, i.e. hard to reproduce
* side effects
nested proof
no sections
}}}
******************************** STM API ***********************************
****************************************************************************
Some commands may by side effect change the proof mode
When tty is true, this code also does some of the job of the user interface:
jump back to a state that is valid
We stay on a valid state
Document building
PG stuff
Joining various parts of the document
Back
Query
Proof
Side effect on all branches
ensure it is ok
We hope it can be replayed, but we can't really know
Proof General
For now, arbitrary edits should be announced with edit_at
Hum, this should be the real start_id in the cluster and not next
****************************************************************************
skip non-tactics
ng1 : number of goals remaining at the current level (before cmd)
ngl1 : stack of previous levels with their remaining goals
ng : number of goals after the execution of cmd
beginend : special indentation stack for { }
We've branched
Standard case, same goal number as before
Indentation depth
Some special handling of bullets and { }, to get a nicer display
Export hooks | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
let pr_err s = Printf.eprintf "%s] %s\n" (System.process_id ()) s; flush stderr
let prerr_endline s = if false then begin pr_err (s ()) end else ()
let prerr_debug s = if !Flags.debug then begin pr_err (s ()) end else ()
Opening ppvernac below aliases , see PR#185
let pp_to_richpp = Richpp.richpp_of_pp
let str_to_richpp = Richpp.richpp_of_string
open Vernacexpr
open CErrors
open Pp
open Names
open Util
open Ppvernac
open Vernac_classifier
open Feedback
module Hooks = struct
let process_error, process_error_hook = Hook.make ()
let interp, interp_hook = Hook.make ()
let with_fail, with_fail_hook = Hook.make ()
let state_computed, state_computed_hook = Hook.make
~default:(fun state_id ~in_cache ->
feedback ~id:(State state_id) Processed) ()
let state_ready, state_ready_hook = Hook.make
~default:(fun state_id -> ()) ()
let forward_feedback, forward_feedback_hook =
let m = Mutex.create () in
Hook.make ~default:(function
| { id = id; route; contents } ->
try Mutex.lock m; feedback ~id:id ~route contents; Mutex.unlock m
with e -> Mutex.unlock m; raise e) ()
let parse_error, parse_error_hook = Hook.make
~default:(fun id loc msg ->
feedback ~id (Message(Error, Some loc, pp_to_richpp msg))) ()
let execution_error, execution_error_hook = Hook.make
~default:(fun state_id loc msg ->
feedback ~id:(State state_id) (Message(Error, Some loc, pp_to_richpp msg))) ()
let unreachable_state, unreachable_state_hook = Hook.make
~default:(fun _ _ -> ()) ()
let tactic_being_run, tactic_being_run_hook = Hook.make
~default:(fun _ -> ()) ()
include Hook
enables : Hooks.(call foo args )
let call = get
let call_process_error_once =
let processed : unit Exninfo.t = Exninfo.make () in
fun (_, info as ei) ->
match Exninfo.get info processed with
| Some _ -> ei
| None ->
let e, info = call process_error ei in
let info = Exninfo.add info processed () in
e, info
end
let interactive () =
if !Flags.ide_slave || !Flags.print_emacs || not !Flags.batch_mode then `Yes
else `No
let async_proofs_workers_extra_env = ref [||]
type aast = {
verbose : bool;
loc : Loc.t;
indentation : int;
strlen : int;
}
let pr_ast { expr; indentation } = int indentation ++ str " " ++ pr_vernac expr
let default_proof_mode () = Proof_global.get_default_proof_mode_name ()
let may_pierce_opaque = function
| { expr = VernacPrint _ } -> true
| { expr = VernacExtend (("Extraction",_), _) } -> true
| { expr = VernacExtend (("SeparateExtraction",_), _) } -> true
| { expr = VernacExtend (("ExtractionLibrary",_), _) } -> true
| { expr = VernacExtend (("RecursiveExtractionLibrary",_), _) } -> true
| { expr = VernacExtend (("ExtractionConstant",_), _) } -> true
| { expr = VernacExtend (("ExtractionInlinedConstant",_), _) } -> true
| { expr = VernacExtend (("ExtractionInductive",_), _) } -> true
| _ -> false
Wrapper for Vernacentries.interp to set the feedback i d
let vernac_interp ?proof id ?route { verbose; loc; expr } =
let rec internal_command = function
| VernacResetName _ | VernacResetInitial | VernacBack _
| VernacBackTo _ | VernacRestart | VernacUndo _ | VernacUndoTo _
| VernacBacktrack _ | VernacAbortAll | VernacAbort _ -> true
| VernacTime (_,e) | VernacTimeout (_,e) | VernacRedirect (_,(_,e)) -> internal_command e
| _ -> false in
if internal_command expr then begin
prerr_endline (fun () -> "ignoring " ^ Pp.string_of_ppcmds(pr_vernac expr))
end else begin
set_id_for_feedback ?route (State id);
Aux_file.record_in_aux_set_at loc;
prerr_endline (fun () -> "interpreting " ^ Pp.string_of_ppcmds(pr_vernac expr));
try Hooks.(call interp ?verbosely:(Some verbose) ?proof (loc, expr))
with e ->
let e = CErrors.push e in
iraise Hooks.(call_process_error_once e)
end
Wrapper for Vernac.parse_sentence to set the feedback i d
let indentation_of_string s =
let len = String.length s in
let rec aux n i precise =
if i >= len then 0, precise, len
else
match s.[i] with
| ' ' | '\t' -> aux (succ n) (succ i) precise
| '\n' | '\r' -> aux 0 (succ i) true
| _ -> n, precise, len in
aux 0 0 false
let vernac_parse ?(indlen_prev=fun() -> 0) ?newtip ?route eid s =
let feedback_id =
if Option.is_empty newtip then Edit eid
else State (Option.get newtip) in
let indentation, precise, strlen = indentation_of_string s in
let indentation =
if precise then indentation else indlen_prev () + indentation in
set_id_for_feedback ?route feedback_id;
let pa = Pcoq.Gram.parsable (Stream.of_string s) in
Flags.with_option Flags.we_are_parsing (fun () ->
try
match Pcoq.Gram.entry_parse Pcoq.main_entry pa with
| None -> raise (Invalid_argument "vernac_parse")
| Some (loc, ast) -> indentation, strlen, loc, ast
with e when CErrors.noncritical e ->
let (e, info) = CErrors.push e in
let loc = Option.default Loc.ghost (Loc.get_loc info) in
Hooks.(call parse_error feedback_id loc (iprint (e, info)));
iraise (e, info))
()
let pr_open_cur_subgoals () =
try Printer.pr_open_subgoals ()
with Proof_global.NoCurrentProof -> Pp.str ""
let update_global_env () =
if Proof_global.there_are_pending_proofs () then
Proof_global.update_global_env ()
module Vcs_ = Vcs.Make(Stateid.Self)
type future_proof = Proof_global.closed_proof_output Future.computation
type proof_mode = string
type depth = int
type cancel_switch = bool ref
type branch_type =
[ `Master
| `Proof of proof_mode * depth
| `Edit of
proof_mode * Stateid.t * Stateid.t * vernac_qed_type * Vcs_.Branch.t ]
type cmd_t = {
cast : aast;
cids : Id.t list;
cblock : proof_block_name option;
cqueue : [ `MainQueue
| `TacQueue of solving_tac * anon_abstracting_tac * cancel_switch
| `QueryQueue of cancel_switch
| `SkipQueue ] }
type fork_t = aast * Vcs_.Branch.t * Vernacexpr.opacity_guarantee * Id.t list
type qed_t = {
qast : aast;
keep : vernac_qed_type;
mutable fproof : (future_proof * cancel_switch) option;
brname : Vcs_.Branch.t;
brinfo : branch_type Vcs_.branch_info
}
type seff_t = aast option
type alias_t = Stateid.t * aast
type transaction =
| Cmd of cmd_t
| Fork of fork_t
| Qed of qed_t
| Sideff of seff_t
| Alias of alias_t
| Noop
type step =
[ `Cmd of cmd_t
| `Fork of fork_t * Stateid.t option
| `Qed of qed_t * Stateid.t
| `Sideff of [ `Ast of aast * Stateid.t | `Id of Stateid.t ]
| `Alias of alias_t ]
type visit = { step : step; next : Stateid.t }
let mkTransTac cast cblock cqueue =
Cmd { ctac = true; cast; cblock; cqueue; cids = []; ceff = false }
let mkTransCmd cast cids ceff cqueue =
Cmd { ctac = false; cast; cblock = None; cqueue; cids; ceff }
let summary_pstate = [ Evarutil.meta_counter_summary_name;
Evd.evar_counter_summary_name;
"program-tcc-table" ]
type cached_state =
| Empty
| Error of Exninfo.iexn
| Valid of state
TODO : inline records in OCaml 4.03
summary
is the state trimmed down ( )
}
type branch = Vcs_.Branch.t * branch_type Vcs_.branch_info
type backup = { mine : branch; others : branch list }
TODO : Make this record private to VCS
mutable vcs_backup : 'vcs option * backup option;
}
let default_info () =
{ n_reached = 0; n_goals = 0; state = Empty; vcs_backup = None,None }
module DynBlockData : Dyn.S = Dyn.Make(struct end)
Clusters of nodes implemented as Dag properties . While Dag and impose
* no constraint on properties , here we impose boxes to be non overlapping .
* Such invariant makes sense for the current kinds of boxes ( proof blocks and
* entire proofs ) but may make no sense and dropped / refined in the future .
* Such invariant is useful to detect broken proof block detection code
* no constraint on properties, here we impose boxes to be non overlapping.
* Such invariant makes sense for the current kinds of boxes (proof blocks and
* entire proofs) but may make no sense and dropped/refined in the future.
* Such invariant is useful to detect broken proof block detection code *)
type box =
| ProofTask of pt
| ProofBlock of static_block_declaration * proof_block_name
TODO : inline records in OCaml 4.03
lemma : Stateid.t;
qed : Stateid.t;
}
and static_block_declaration = {
block_start : Stateid.t;
block_stop : Stateid.t;
dynamic_switch : Stateid.t;
carry_on_data : DynBlockData.t;
}
Functions that work on a Vcs with a specific branch type
module Vcs_aux : sig
val proof_nesting : (branch_type, 't,'i,'c) Vcs_.t -> int
val find_proof_at_depth :
(branch_type, 't, 'i,'c) Vcs_.t -> int ->
Vcs_.Branch.t * branch_type Vcs_.branch_info
exception Expired
val visit : (branch_type, transaction,'i,'c) Vcs_.t -> Vcs_.Dag.node -> visit
let proof_nesting vcs =
List.fold_left max 0
(List.map_filter
(function
| { Vcs_.kind = `Proof (_,n) } -> Some n
| { Vcs_.kind = `Edit _ } -> Some 1
| _ -> None)
(List.map (Vcs_.get_branch vcs) (Vcs_.branches vcs)))
let find_proof_at_depth vcs pl =
try List.find (function
| _, { Vcs_.kind = `Proof(m, n) } -> Int.equal n pl
| _, { Vcs_.kind = `Edit _ } -> anomaly(Pp.str "find_proof_at_depth")
| _ -> false)
(List.map (fun h -> h, Vcs_.get_branch vcs h) (Vcs_.branches vcs))
with Not_found -> failwith "find_proof_at_depth"
exception Expired
let visit vcs id =
if Stateid.equal id Stateid.initial then
anomaly(Pp.str "Visiting the initial state id")
else if Stateid.equal id Stateid.dummy then
anomaly(Pp.str "Visiting the dummy state id")
else
try
match Vcs_.Dag.from_node (Vcs_.dag vcs) id with
| [n, Cmd x] -> { step = `Cmd x; next = n }
| [n, Alias x] -> { step = `Alias x; next = n }
| [n, Fork x] -> { step = `Fork (x,None); next = n }
| [n, Fork x; p, Noop] -> { step = `Fork (x,Some p); next = n }
| [p, Noop; n, Fork x] -> { step = `Fork (x,Some p); next = n }
| [n, Qed x; p, Noop]
| [p, Noop; n, Qed x] -> { step = `Qed (x,p); next = n }
| [n, Sideff None; p, Noop]
| [p, Noop; n, Sideff None]-> { step = `Sideff (`Id p); next = n }
| [n, Sideff (Some x); p, Noop]
| [p, Noop; n, Sideff (Some x)]-> { step = `Sideff(`Ast (x,p)); next = n }
| [n, Sideff (Some x)]-> {step = `Sideff(`Ast (x,Stateid.dummy)); next=n}
| _ -> anomaly (Pp.str ("Malformed VCS at node "^Stateid.to_string id))
with Not_found -> raise Expired
Imperative wrap around VCS to obtain _ the _ VCS that is the
* representation of the document Coq is currently processing
* representation of the document Coq is currently processing *)
module VCS : sig
exception Expired
module Branch : (module type of Vcs_.Branch with type t = Vcs_.Branch.t)
type id = Stateid.t
type 'branch_type branch_info = 'branch_type Vcs_.branch_info = {
kind : [> `Master] as 'branch_type;
root : id;
pos : id;
}
type vcs = (branch_type, transaction, vcs state_info, box) Vcs_.t
val init : id -> unit
val current_branch : unit -> Branch.t
val checkout : Branch.t -> unit
val branches : unit -> Branch.t list
val get_branch : Branch.t -> branch_type branch_info
val get_branch_pos : Branch.t -> id
val new_node : ?id:Stateid.t -> unit -> id
val merge : id -> ours:transaction -> ?into:Branch.t -> Branch.t -> unit
val rewrite_merge : id -> ours:transaction -> at:id -> Branch.t -> unit
val delete_branch : Branch.t -> unit
val commit : id -> transaction -> unit
val mk_branch_name : aast -> Branch.t
val edit_branch : Branch.t
val branch : ?root:id -> ?pos:id -> Branch.t -> branch_type -> unit
val reset_branch : Branch.t -> id -> unit
val reachable : id -> Stateid.Set.t
val cur_tip : unit -> id
val get_info : id -> vcs state_info
val reached : id -> unit
val goals : id -> int -> unit
val set_state : id -> cached_state -> unit
val get_state : id -> cached_state
val slice : block_start:id -> block_stop:id -> vcs
val nodes_in_slice : block_start:id -> block_stop:id -> Stateid.t list
val create_proof_task_box : id list -> qed:id -> block_start:id -> unit
val create_proof_block : static_block_declaration -> string -> unit
val box_of : id -> box list
val delete_boxes_of : id -> unit
val proof_task_box_of : id -> pt option
val proof_nesting : unit -> int
val checkout_shallowest_proof_branch : unit -> unit
val propagate_sideff : replay:aast option -> unit
val gc : unit -> unit
val visit : id -> visit
val print : ?now:bool -> unit -> unit
val backup : unit -> vcs
val restore : vcs -> unit
include Vcs_
exception Expired = Vcs_aux.Expired
open Printf
let print_dag vcs () =
let fname =
"stm_" ^ Str.global_replace (Str.regexp " ") "_" (System.process_id ()) in
let string_of_transaction = function
| Cmd { cast = t } | Fork (t, _,_,_) ->
(try Pp.string_of_ppcmds (pr_ast t) with _ -> "ERR")
| Sideff (Some t) ->
sprintf "Sideff(%s)"
(try Pp.string_of_ppcmds (pr_ast t) with _ -> "ERR")
| Sideff None -> "EnvChange"
| Noop -> " "
| Alias (id,_) -> sprintf "Alias(%s)" (Stateid.to_string id)
| Qed { qast } -> string_of_ppcmds (pr_ast qast) in
let is_green id =
match get_info vcs id with
| Some { state = Valid _ } -> true
| _ -> false in
let is_red id =
match get_info vcs id with
| Some { state = Error _ } -> true
| _ -> false in
let head = current_branch vcs in
let heads =
List.map (fun x -> x, (get_branch vcs x).pos) (branches vcs) in
let graph = dag vcs in
let quote s =
Str.global_replace (Str.regexp "\n") "<BR/>"
(Str.global_replace (Str.regexp "<") "<"
(Str.global_replace (Str.regexp ">") ">"
(Str.global_replace (Str.regexp "\"") """
(Str.global_replace (Str.regexp "&") "&"
(String.sub s 0 (min (String.length s) 20)))))) in
let fname_dot, fname_ps =
let f = "/tmp/" ^ Filename.basename fname in
f ^ ".dot", f ^ ".pdf" in
let node id = "s" ^ Stateid.to_string id in
let edge tr =
sprintf "<<FONT POINT-SIZE=\"12\" FACE=\"sans\">%s</FONT>>"
(quote (string_of_transaction tr)) in
let node_info id =
match get_info vcs id with
| None -> ""
| Some info ->
sprintf "<<FONT POINT-SIZE=\"12\">%s</FONT>" (Stateid.to_string id) ^
sprintf " <FONT POINT-SIZE=\"11\">r:%d g:%d</FONT>>"
info.n_reached info.n_goals in
let color id =
if is_red id then "red" else if is_green id then "green" else "white" in
let nodefmt oc id =
fprintf oc "%s [label=%s,style=filled,fillcolor=%s];\n"
(node id) (node_info id) (color id) in
let ids = ref Stateid.Set.empty in
let boxes = ref [] in
Dag.iter graph (fun from _ _ l ->
ids := Stateid.Set.add from !ids;
List.iter (fun box -> boxes := box :: !boxes)
(Dag.property_of graph from);
List.iter (fun (dest, _) ->
ids := Stateid.Set.add dest !ids;
List.iter (fun box -> boxes := box :: !boxes)
(Dag.property_of graph dest))
l);
boxes := CList.sort_uniquize Dag.Property.compare !boxes;
let oc = open_out fname_dot in
output_string oc "digraph states {\n";
Dag.iter graph (fun from cf _ l ->
List.iter (fun (dest, trans) ->
fprintf oc "%s -> %s [xlabel=%s,labelfloat=true];\n"
(node from) (node dest) (edge trans)) l
);
let contains b1 b2 =
Stateid.Set.subset
(Dag.Property.having_it b2) (Dag.Property.having_it b1) in
let same_box = Dag.Property.equal in
let outerboxes boxes =
List.filter (fun b ->
not (List.exists (fun b1 ->
not (same_box b1 b) && contains b1 b) boxes)
) boxes in
let rec rec_print b =
boxes := CList.remove same_box b !boxes;
let sub_boxes = List.filter (contains b) (outerboxes !boxes) in
fprintf oc "subgraph cluster_%s {\n" (Dag.Property.to_string b);
List.iter rec_print sub_boxes;
Stateid.Set.iter (fun id ->
if Stateid.Set.mem id !ids then begin
ids := Stateid.Set.remove id !ids;
nodefmt oc id
end)
(Dag.Property.having_it b);
match Dag.Property.data b with
| ProofBlock ({ dynamic_switch = id }, lbl) ->
fprintf oc "label=\"%s (test:%s)\";\n" lbl (Stateid.to_string id);
fprintf oc "color=red; }\n"
| ProofTask _ -> fprintf oc "color=blue; }\n"
in
List.iter rec_print (outerboxes !boxes);
Stateid.Set.iter (nodefmt oc) !ids;
List.iteri (fun i (b,id) ->
let shape = if Branch.equal head b then "box3d" else "box" in
fprintf oc "b%d -> %s;\n" i (node id);
fprintf oc "b%d [shape=%s,label=\"%s\"];\n" i shape
(Branch.to_string b);
) heads;
output_string oc "}\n";
close_out oc;
ignore(Sys.command
("dot -Tpdf -Gcharset=latin1 " ^ fname_dot ^ " -o" ^ fname_ps))
type vcs = (branch_type, transaction, vcs state_info, box) t
let vcs : vcs ref = ref (empty Stateid.dummy)
let init id =
vcs := empty id;
vcs := set_info !vcs id (default_info ())
let current_branch () = current_branch !vcs
let checkout head = vcs := checkout !vcs head
let branches () = branches !vcs
let get_branch head = get_branch !vcs head
let get_branch_pos head = (get_branch head).pos
let new_node ?(id=Stateid.fresh ()) () =
assert(Vcs_.get_info !vcs id = None);
vcs := set_info !vcs id (default_info ());
id
let merge id ~ours ?into branch =
vcs := merge !vcs id ~ours ~theirs:Noop ?into branch
let delete_branch branch = vcs := delete_branch !vcs branch
let reset_branch branch id = vcs := reset_branch !vcs branch id
let commit id t = vcs := commit !vcs id t
let rewrite_merge id ~ours ~at branch =
vcs := rewrite_merge !vcs id ~ours ~theirs:Noop ~at branch
let reachable id = reachable !vcs id
let mk_branch_name { expr = x } = Branch.make
(match x with
| VernacDefinition (_,((_,i),_),_) -> string_of_id i
| VernacStartTheoremProof (_,[Some ((_,i),_),_],_) -> string_of_id i
| _ -> "branch")
let edit_branch = Branch.make "edit"
let branch ?root ?pos name kind = vcs := branch !vcs ?root ?pos name kind
let get_info id =
match get_info !vcs id with
| Some x -> x
| None -> raise Vcs_aux.Expired
let set_state id s =
(get_info id).state <- s;
if Flags.async_proofs_is_master () then Hooks.(call state_ready id)
let get_state id = (get_info id).state
let reached id =
let info = get_info id in
info.n_reached <- info.n_reached + 1
let goals id n = (get_info id).n_goals <- n
let cur_tip () = get_branch_pos (current_branch ())
let proof_nesting () = Vcs_aux.proof_nesting !vcs
let checkout_shallowest_proof_branch () =
if List.mem edit_branch (Vcs_.branches !vcs) then begin
checkout edit_branch;
match get_branch edit_branch with
| { kind = `Edit (mode, _,_,_,_) } -> Proof_global.activate_proof_mode mode
| _ -> assert false
end else
let pl = proof_nesting () in
try
let branch, mode = match Vcs_aux.find_proof_at_depth !vcs pl with
| h, { Vcs_.kind = `Proof (m, _) } -> h, m | _ -> assert false in
checkout branch;
prerr_endline (fun () -> "mode:" ^ mode);
Proof_global.activate_proof_mode mode
with Failure _ ->
checkout Branch.master;
Proof_global.disactivate_current_proof_mode ()
let propagate_sideff ~replay:t =
List.iter (fun b ->
checkout b;
let id = new_node () in
merge id ~ours:(Sideff t) ~into:b Branch.master)
(List.filter (fun b -> not (Branch.equal b Branch.master)) (branches ()))
let visit id = Vcs_aux.visit !vcs id
let nodes_in_slice ~block_start ~block_stop =
let rec aux id =
if Stateid.equal id block_start then [] else
match visit id with
| { next = n; step = `Cmd x } -> (id,Cmd x) :: aux n
| { next = n; step = `Alias x } -> (id,Alias x) :: aux n
| { next = n; step = `Sideff (`Ast (x,_)) } ->
(id,Sideff (Some x)) :: aux n
| _ -> anomaly(str("Cannot slice from "^ Stateid.to_string block_start ^
" to "^Stateid.to_string block_stop))
in aux block_stop
let slice ~block_start ~block_stop =
let l = nodes_in_slice ~block_start ~block_stop in
let copy_info v id =
Vcs_.set_info v id
{ (get_info id) with state = Empty; vcs_backup = None,None } in
let copy_info_w_state v id =
Vcs_.set_info v id { (get_info id) with vcs_backup = None,None } in
let copy_proof_blockes v =
let nodes = Vcs_.Dag.all_nodes (Vcs_.dag v) in
let props =
Stateid.Set.fold (fun n pl -> Vcs_.property_of !vcs n @ pl) nodes [] in
let props = CList.sort_uniquize Vcs_.Dag.Property.compare props in
List.fold_left (fun v p ->
Vcs_.create_property v
(Stateid.Set.elements (Vcs_.Dag.Property.having_it p))
(Vcs_.Dag.Property.data p)) v props
in
let v = Vcs_.empty block_start in
let v = copy_info v block_start in
let v = List.fold_right (fun (id,tr) v ->
let v = Vcs_.commit v id tr in
let v = copy_info v id in
v) l v in
assert (match (get_info block_start).state with Valid _ -> true | _ -> false);
We put in the new dag the most recent state known to master
let rec fill id =
match (get_info id).state with
| Empty | Error _ -> fill (Vcs_aux.visit v id).next
| Valid _ -> copy_info_w_state v id in
let v = fill block_stop in
We put in the new dag the first state ( since Qed shall run on it ,
* see check_task_aux )
* see check_task_aux) *)
let v = copy_info_w_state v block_start in
copy_proof_blockes v
let nodes_in_slice ~block_start ~block_stop =
List.rev (List.map fst (nodes_in_slice ~block_start ~block_stop))
let topo_invariant l =
let all = List.fold_right Stateid.Set.add l Stateid.Set.empty in
List.for_all
(fun x ->
let props = property_of !vcs x in
let sets = List.map Dag.Property.having_it props in
List.for_all (fun s -> Stateid.Set.(subset s all || subset all s)) sets)
l
let create_proof_task_box l ~qed ~block_start:lemma =
if not (topo_invariant l) then anomaly (str "overlapping boxes");
vcs := create_property !vcs l (ProofTask { qed; lemma })
let create_proof_block ({ block_start; block_stop} as decl) name =
let l = nodes_in_slice ~block_start ~block_stop in
if not (topo_invariant l) then anomaly (str "overlapping boxes");
vcs := create_property !vcs l (ProofBlock (decl, name))
let box_of id = List.map Dag.Property.data (property_of !vcs id)
let delete_boxes_of id =
List.iter (fun x -> vcs := delete_property !vcs x) (property_of !vcs id)
let proof_task_box_of id =
match
CList.map_filter (function ProofTask x -> Some x | _ -> None) (box_of id)
with
| [] -> None
| [x] -> Some x
| _ -> anomaly (str "node with more than 1 proof task box")
let gc () =
let old_vcs = !vcs in
let new_vcs, erased_nodes = gc old_vcs in
Stateid.Set.iter (fun id ->
match (Vcs_aux.visit old_vcs id).step with
| `Qed ({ fproof = Some (_, cancel_switch) }, _)
| `Cmd { cqueue = `TacQueue (_,_,cancel_switch) }
| `Cmd { cqueue = `QueryQueue cancel_switch } ->
cancel_switch := true
| _ -> ())
erased_nodes;
vcs := new_vcs
val command : now:bool -> (unit -> unit) -> unit
end = struct
let m = Mutex.create ()
let c = Condition.create ()
let job = ref None
let worker = ref None
let set_last_job j =
Mutex.lock m;
job := Some j;
Condition.signal c;
Mutex.unlock m
let get_last_job () =
Mutex.lock m;
while Option.is_empty !job do Condition.wait c m; done;
match !job with
| None -> assert false
| Some x -> job := None; Mutex.unlock m; x
let run_command () =
try while true do get_last_job () () done
let command ~now job =
if now then job ()
else begin
set_last_job job;
if Option.is_empty !worker then
worker := Some (Thread.create run_command ())
end
end
let print ?(now=false) () =
if not !Flags.debug && not now then () else NB.command ~now (print_dag !vcs)
let backup () = !vcs
let restore v = vcs := v
let state_of_id id =
try match (VCS.get_info id).state with
| Valid s -> `Valid (Some s)
| Error (e,_) -> `Error e
| Empty -> `Valid None
with VCS.Expired -> `Expired
* * * * * A cache : fills in the nodes of the VCS document with their value * * * * *
module State : sig
val define :
?safe_id:Stateid.t ->
?redefine:bool -> ?cache:Summary.marshallable ->
?feedback_processed:bool -> (unit -> unit) -> Stateid.t -> unit
val fix_exn_ref : (iexn -> iexn) ref
val install_cached : Stateid.t -> unit
val is_cached : ?cache:Summary.marshallable -> Stateid.t -> bool
val is_cached_and_valid : ?cache:Summary.marshallable -> Stateid.t -> bool
val exn_on : Stateid.t -> valid:Stateid.t -> iexn -> iexn
type frozen_state
val get_cached : Stateid.t -> frozen_state
val same_env : frozen_state -> frozen_state -> bool
type proof_part
type partial_state =
[ `Full of frozen_state
| `Proof of Stateid.t * proof_part ]
val proof_part_of_frozen : frozen_state -> proof_part
val assign : Stateid.t -> partial_state -> unit
cur_id holds Stateid.dummy in case the last attempt to define a state
* failed , so the global state may contain garbage
* failed, so the global state may contain garbage *)
let cur_id = ref Stateid.dummy
let fix_exn_ref = ref (fun x -> x)
let freeze_global_state marshallable =
{ system = States.freeze ~marshallable;
proof = Proof_global.freeze ~marshallable;
shallow = (marshallable = `Shallow) }
let unfreeze_global_state { system; proof } =
States.unfreeze system; Proof_global.unfreeze proof
let () = Future.set_freeze
(fun () -> Obj.magic (freeze_global_state `No, !cur_id))
(fun t -> let s,i = Obj.magic t in unfreeze_global_state s; cur_id := i)
type frozen_state = state
type proof_part =
type partial_state =
[ `Full of frozen_state
| `Proof of Stateid.t * proof_part ]
let proof_part_of_frozen { proof; system } =
proof,
Summary.project_summary (States.summary_of_state system) summary_pstate
let freeze marshallable id =
VCS.set_state id (Valid (freeze_global_state marshallable))
let freeze_invalid id iexn = VCS.set_state id (Error iexn)
let is_cached ?(cache=`No) id only_valid =
if Stateid.equal id !cur_id then
try match VCS.get_info id with
| { state = Empty } when cache = `Yes -> freeze `No id; true
| { state = Empty } when cache = `Shallow -> freeze `Shallow id; true
| _ -> true
with VCS.Expired -> false
else
try match VCS.get_info id with
| { state = Empty } -> false
| { state = Valid _ } -> true
| { state = Error _ } -> not only_valid
with VCS.Expired -> false
let is_cached_and_valid ?cache id = is_cached ?cache id true
let is_cached ?cache id = is_cached ?cache id false
let install_cached id =
match VCS.get_info id with
| { state = Valid s } ->
else begin unfreeze_global_state s; cur_id := id end
| { state = Error ie } -> cur_id := id; Exninfo.iraise ie
| _ ->
coqc has a 1 slot cache and only for valid states
if interactive () = `No && Stateid.equal id !cur_id then ()
else anomaly (str "installing a non cached state")
let get_cached id =
try match VCS.get_info id with
| { state = Valid s } -> s
| _ -> anomaly (str "not a cached state")
with VCS.Expired -> anomaly (str "not a cached state (expired)")
let assign id what =
if VCS.get_state id <> Empty then () else
try match what with
| `Full s ->
let s =
try
let prev = (VCS.visit id).next in
if is_cached_and_valid prev
then { s with proof =
Proof_global.copy_terminators
~src:(get_cached prev).proof ~tgt:s.proof }
else s
with VCS.Expired -> s in
VCS.set_state id (Valid s)
| `Proof(ontop,(pstate,counters)) ->
if is_cached_and_valid ontop then
let s = get_cached ontop in
let s = { s with proof =
Proof_global.copy_terminators ~src:s.proof ~tgt:pstate } in
let s = { s with system =
States.replace_summary s.system
(Summary.surgery_summary
(States.summary_of_state s.system)
counters) } in
VCS.set_state id (Valid s)
with VCS.Expired -> ()
let exn_on id ~valid (e, info) =
match Stateid.get info with
| Some _ -> (e, info)
| None ->
let loc = Option.default Loc.ghost (Loc.get_loc info) in
let (e, info) = Hooks.(call_process_error_once (e, info)) in
Hooks.(call execution_error id loc (iprint (e, info)));
(e, Stateid.add info ~valid id)
let same_env { system = s1 } { system = s2 } =
let s1 = States.summary_of_state s1 in
let e1 = Summary.project_summary s1 [Global.global_env_summary_name] in
let s2 = States.summary_of_state s2 in
let e2 = Summary.project_summary s2 [Global.global_env_summary_name] in
Summary.pointer_equal e1 e2
let define ?safe_id ?(redefine=false) ?(cache=`No) ?(feedback_processed=true)
f id
=
feedback ~id:(State id) (ProcessingIn !Flags.async_proofs_worker_id);
let str_id = Stateid.to_string id in
if is_cached id && not redefine then
anomaly (str"defining state "++str str_id++str" twice");
try
prerr_endline (fun () -> "defining "^str_id^" (cache="^
if cache = `Yes then "Y)" else if cache = `Shallow then "S)" else "N)");
let good_id = match safe_id with None -> !cur_id | Some id -> id in
fix_exn_ref := exn_on id ~valid:good_id;
f ();
fix_exn_ref := (fun x -> x);
if cache = `Yes then freeze `No id
else if cache = `Shallow then freeze `Shallow id;
prerr_endline (fun () -> "setting cur id to "^str_id);
cur_id := id;
if feedback_processed then
Hooks.(call state_computed id ~in_cache:false);
VCS.reached id;
if Proof_global.there_are_pending_proofs () then
VCS.goals id (Proof_global.get_open_goals ())
with e ->
let (e, info) = CErrors.push e in
let good_id = !cur_id in
cur_id := Stateid.dummy;
VCS.reached id;
let ie =
match Stateid.get info, safe_id with
| None, None -> (exn_on id ~valid:good_id (e, info))
| None, Some good_id -> (exn_on id ~valid:good_id (e, info))
| Some _, None -> (e, info)
| Some (_,at), Some id -> (e, Stateid.add info ~valid:id at) in
if cache = `Yes || cache = `Shallow then freeze_invalid id ie;
Hooks.(call unreachable_state id ie);
Exninfo.iraise ie
module Backtrack : sig
val record : unit -> unit
val backto : Stateid.t -> unit
val back_safe : unit -> unit
we could navigate the dag , but this ways easy
val branches_of : Stateid.t -> backup
val undo_vernac_classifier : vernac_expr -> vernac_classification
let record () =
List.iter (fun current_branch ->
let mine = current_branch, VCS.get_branch current_branch in
let info = VCS.get_info (VCS.get_branch_pos current_branch) in
let others =
CList.map_filter (fun b ->
if Vcs_.Branch.equal b current_branch then None
else Some(b, VCS.get_branch b)) (VCS.branches ()) in
let backup = if fst info.vcs_backup <> None then fst info.vcs_backup
else Some (VCS.backup ()) in
let branches = if snd info.vcs_backup <> None then snd info.vcs_backup
else Some { mine; others } in
info.vcs_backup <- backup, branches)
[VCS.current_branch (); VCS.Branch.master]
let backto oid =
let info = VCS.get_info oid in
match info.vcs_backup with
| None, _ ->
anomaly(str"Backtrack.backto "++str(Stateid.to_string oid)++
str": a state with no vcs_backup")
| Some vcs, _ -> VCS.restore vcs
let branches_of id =
let info = VCS.get_info id in
match info.vcs_backup with
| _, None ->
anomaly(str"Backtrack.branches_of "++str(Stateid.to_string id)++
str": a state with no vcs_backup")
| _, Some x -> x
let rec fold_until f acc id =
let next acc =
if id = Stateid.initial then raise Not_found
else fold_until f acc (VCS.visit id).next in
let info = VCS.get_info id in
match info.vcs_backup with
| None, _ -> next acc
| Some vcs, _ ->
let ids, tactic, undo =
if id = Stateid.initial || id = Stateid.dummy then [],false,0 else
match VCS.visit id with
| { step = `Fork ((_,_,_,l),_) } -> l, false,0
| { step = `Cmd { cids = l; ctac } } -> l, ctac,0
| { step = `Alias (_,{ expr = VernacUndo n}) } -> [], false, n
| _ -> [],false,0 in
match f acc (id, vcs, ids, tactic, undo) with
| `Stop x -> x
| `Cont acc -> next acc
let back_safe () =
let id =
fold_until (fun n (id,_,_,_,_) ->
if n >= 0 && State.is_cached_and_valid id then `Stop id else `Cont (succ n))
0 (VCS.get_branch_pos (VCS.current_branch ())) in
backto id
let undo_vernac_classifier v =
try
match v with
| VernacResetInitial ->
VtStm (VtBack Stateid.initial, true), VtNow
| VernacResetName (_,name) ->
let id = VCS.get_branch_pos (VCS.current_branch ()) in
(try
let oid =
fold_until (fun b (id,_,label,_,_) ->
if b then `Stop id else `Cont (List.mem name label))
false id in
VtStm (VtBack oid, true), VtNow
with Not_found ->
VtStm (VtBack id, true), VtNow)
| VernacBack n ->
let id = VCS.get_branch_pos (VCS.current_branch ()) in
let oid = fold_until (fun n (id,_,_,_,_) ->
if Int.equal n 0 then `Stop id else `Cont (n-1)) n id in
VtStm (VtBack oid, true), VtNow
| VernacUndo n ->
let id = VCS.get_branch_pos (VCS.current_branch ()) in
let oid = fold_until (fun n (id,_,_,tactic,undo) ->
let value = (if tactic then 1 else 0) - undo in
if Int.equal n 0 then `Stop id else `Cont (n-value)) n id in
VtStm (VtBack oid, true), VtLater
| VernacUndoTo _
| VernacRestart as e ->
let m = match e with VernacUndoTo m -> m | _ -> 0 in
let id = VCS.get_branch_pos (VCS.current_branch ()) in
let vcs =
match (VCS.get_info id).vcs_backup with
| None, _ -> anomaly(str"Backtrack: tip with no vcs_backup")
| Some vcs, _ -> vcs in
let cb, _ =
try Vcs_aux.find_proof_at_depth vcs (Vcs_aux.proof_nesting vcs)
with Failure _ -> raise Proof_global.NoCurrentProof in
let n = fold_until (fun n (_,vcs,_,_,_) ->
if List.mem cb (Vcs_.branches vcs) then `Cont (n+1) else `Stop n)
0 id in
let oid = fold_until (fun n (id,_,_,_,_) ->
if Int.equal n 0 then `Stop id else `Cont (n-1)) (n-m-1) id in
VtStm (VtBack oid, true), VtLater
| VernacAbortAll ->
let id = VCS.get_branch_pos (VCS.current_branch ()) in
let oid = fold_until (fun () (id,vcs,_,_,_) ->
match Vcs_.branches vcs with [_] -> `Stop id | _ -> `Cont ())
() id in
VtStm (VtBack oid, true), VtLater
| VernacBacktrack (id,_,_)
| VernacBackTo id ->
VtStm (VtBack (Stateid.of_int id), not !Flags.print_emacs), VtNow
| _ -> VtUnknown, VtNow
with
| Not_found ->
CErrors.errorlabstrm "undo_vernac_classifier"
(str "Cannot undo")
let hints = ref Aux_file.empty_aux_file
let set_compilation_hints file =
hints := Aux_file.load_aux_file_for file
let get_hint_ctx loc =
let s = Aux_file.get !hints loc "context_used" in
match Str.split (Str.regexp ";") s with
| ids :: _ ->
let ids = List.map Names.Id.of_string (Str.split (Str.regexp " ") ids) in
let ids = List.map (fun id -> Loc.ghost, id) ids in
begin match ids with
| [] -> SsEmpty
| x :: xs ->
List.fold_left (fun a x -> SsUnion (SsSingl x,a)) (SsSingl x) xs
end
| _ -> raise Not_found
let get_hint_bp_time proof_name =
try float_of_string (Aux_file.get !hints Loc.ghost proof_name)
with Not_found -> 1.0
let record_pb_time proof_name loc time =
let proof_build_time = Printf.sprintf "%.3f" time in
Aux_file.record_in_aux_at loc "proof_build_time" proof_build_time;
if proof_name <> "" then begin
Aux_file.record_in_aux_at Loc.ghost proof_name proof_build_time;
hints := Aux_file.set !hints Loc.ghost proof_name proof_build_time
end
exception RemoteException of std_ppcmds
let _ = CErrors.register_handler (function
| RemoteException ppcmd -> ppcmd
| _ -> raise Unhandled)
type document_node = {
indentation : int;
ast : Vernacexpr.vernac_expr;
id : Stateid.t;
}
type document_view = {
entry_point : document_node;
prev_node : document_node -> document_node option;
}
type static_block_detection =
document_view -> static_block_declaration option
type recovery_action = {
base_state : Stateid.t;
goals_to_admit : Goal.goal list;
recovery_command : Vernacexpr.vernac_expr option;
}
type dynamic_block_error_recovery =
static_block_declaration -> [ `ValidBlock of recovery_action | `Leaks ]
let proof_block_delimiters = ref []
let register_proof_block_delimiter name static dynamic =
if List.mem_assoc name !proof_block_delimiters then
CErrors.errorlabstrm "STM" (str "Duplicate block delimiter " ++ str name);
proof_block_delimiters := (name, (static,dynamic)) :: !proof_block_delimiters
let mk_doc_node id = function
| { step = `Cmd { ctac; cast = { indentation; expr }}; next } when ctac ->
Some { indentation; ast = expr; id }
| { step = `Sideff (`Ast ({ indentation; expr }, _)); next } ->
Some { indentation; ast = expr; id }
| _ -> None
let prev_node { id } =
let id = (VCS.visit id).next in
mk_doc_node id (VCS.visit id)
let cur_node id = mk_doc_node id (VCS.visit id)
let is_block_name_enabled name =
match !Flags.async_proofs_tac_error_resilience with
| `None -> false
| `All -> true
| `Only l -> List.mem name l
let detect_proof_block id name =
let name = match name with None -> "indent" | Some x -> x in
if is_block_name_enabled name &&
(Flags.async_proofs_is_master () || Flags.async_proofs_is_worker ())
then (
match cur_node id with
| None -> ()
| Some entry_point -> try
let static, _ = List.assoc name !proof_block_delimiters in
begin match static { prev_node; entry_point } with
| None -> ()
| Some ({ block_start; block_stop } as decl) ->
VCS.create_proof_block decl name
end
with Not_found ->
CErrors.errorlabstrm "STM"
(str "Unknown proof block delimiter " ++ str name)
)
module rec ProofTask : sig
type competence = Stateid.t list
type task_build_proof = {
t_exn_info : Stateid.t * Stateid.t;
t_start : Stateid.t;
t_stop : Stateid.t;
t_drop : bool;
t_states : competence;
t_assign : Proof_global.closed_proof_output Future.assignement -> unit;
t_loc : Loc.t;
t_uuid : Future.UUID.t;
t_name : string }
type task =
| BuildProof of task_build_proof
| States of Stateid.t list
type request =
| ReqBuildProof of (Future.UUID.t,VCS.vcs) Stateid.request * bool * competence
| ReqStates of Stateid.t list
include AsyncTaskQueue.Task
with type task := task
and type competence := competence
and type request := request
val build_proof_here :
drop_pt:bool ->
Stateid.t * Stateid.t -> Loc.t -> Stateid.t ->
Proof_global.closed_proof_output Future.computation
val set_perspective : Stateid.t list -> unit
let forward_feedback msg = Hooks.(call forward_feedback msg)
type competence = Stateid.t list
type task_build_proof = {
t_exn_info : Stateid.t * Stateid.t;
t_start : Stateid.t;
t_stop : Stateid.t;
t_drop : bool;
t_states : competence;
t_assign : Proof_global.closed_proof_output Future.assignement -> unit;
t_loc : Loc.t;
t_uuid : Future.UUID.t;
t_name : string }
type task =
| BuildProof of task_build_proof
| States of Stateid.t list
type request =
| ReqBuildProof of (Future.UUID.t,VCS.vcs) Stateid.request * bool * competence
| ReqStates of Stateid.t list
type error = {
e_error_at : Stateid.t;
e_safe_id : Stateid.t;
e_msg : std_ppcmds;
e_safe_states : Stateid.t list }
type response =
| RespBuiltProof of Proof_global.closed_proof_output * float
| RespError of error
| RespStates of (Stateid.t * State.partial_state) list
| RespDone
let name = ref "proofworker"
let extra_env () = !async_proofs_workers_extra_env
let perspective = ref []
let set_perspective l = perspective := l
let task_match age t =
match age, t with
| `Fresh, BuildProof { t_states } ->
not !Flags.async_proofs_full ||
List.exists (fun x -> CList.mem_f Stateid.equal x !perspective) t_states
| `Old my_states, States l ->
List.for_all (fun x -> CList.mem_f Stateid.equal x my_states) l
| _ -> false
let name_of_task = function
| BuildProof t -> "proof: " ^ t.t_name
| States l -> "states: " ^ String.concat "," (List.map Stateid.to_string l)
let name_of_request = function
| ReqBuildProof(r,_,_) -> "proof: " ^ r.Stateid.name
| ReqStates l -> "states: "^String.concat "," (List.map Stateid.to_string l)
let request_of_task age = function
| States l -> Some (ReqStates l)
| BuildProof {
t_exn_info;t_start;t_stop;t_loc;t_uuid;t_name;t_states;t_drop
} ->
assert(age = `Fresh);
try Some (ReqBuildProof ({
Stateid.exn_info = t_exn_info;
stop = t_stop;
document = VCS.slice ~block_start:t_start ~block_stop:t_stop;
loc = t_loc;
uuid = t_uuid;
name = t_name }, t_drop, t_states))
with VCS.Expired -> None
let use_response (s : competence AsyncTaskQueue.worker_status) t r =
match s, t, r with
| `Old c, States _, RespStates l ->
List.iter (fun (id,s) -> State.assign id s) l; `End
| `Fresh, BuildProof { t_assign; t_loc; t_name; t_states; t_drop },
RespBuiltProof (pl, time) ->
feedback (InProgress ~-1);
t_assign (`Val pl);
record_pb_time t_name t_loc time;
if !Flags.async_proofs_full || t_drop
then `Stay(t_states,[States t_states])
else `End
| `Fresh, BuildProof { t_assign; t_loc; t_name; t_states },
RespError { e_error_at; e_safe_id = valid; e_msg; e_safe_states } ->
feedback (InProgress ~-1);
let info = Stateid.add ~valid Exninfo.null e_error_at in
let e = (RemoteException e_msg, info) in
t_assign (`Exn e);
`Stay(t_states,[States e_safe_states])
| _ -> assert false
let on_task_cancellation_or_expiration_or_slave_death = function
| None -> ()
| Some (States _) -> ()
| Some (BuildProof { t_start = start; t_assign }) ->
let s = "Worker dies or task expired" in
let info = Stateid.add ~valid:start Exninfo.null start in
let e = (RemoteException (strbrk s), info) in
t_assign (`Exn e);
Hooks.(call execution_error start Loc.ghost (strbrk s));
feedback (InProgress ~-1)
let build_proof_here ~drop_pt (id,valid) loc eop =
Future.create (State.exn_on id ~valid) (fun () ->
let wall_clock1 = Unix.gettimeofday () in
if !Flags.batch_mode then Reach.known_state ~cache:`No eop
else Reach.known_state ~cache:`Shallow eop;
let wall_clock2 = Unix.gettimeofday () in
Aux_file.record_in_aux_at loc "proof_build_time"
(Printf.sprintf "%.3f" (wall_clock2 -. wall_clock1));
let p = Proof_global.return_proof ~allow_partial:drop_pt () in
if drop_pt then feedback ~id:(State id) Complete;
p)
let perform_buildp { Stateid.exn_info; stop; document; loc } drop my_states =
try
VCS.restore document;
VCS.print ();
let proof, future_proof, time =
let wall_clock = Unix.gettimeofday () in
let fp = build_proof_here ~drop_pt:drop exn_info loc stop in
let proof = Future.force fp in
proof, fp, Unix.gettimeofday () -. wall_clock in
let fix_exn = Future.fix_exn_of future_proof in
if not drop then begin
let checked_proof = Future.chain ~pure:false future_proof (fun p ->
let pobject, _ =
Proof_global.close_future_proof stop (Future.from_val ~fix_exn p) in
The one sent by master is an InvalidKey
Lemmas.(standard_proof_terminator [] (mk_hook (fun _ _ -> ()))) in
vernac_interp stop
~proof:(pobject, terminator)
{ verbose = false; loc; indentation = 0; strlen = 0;
expr = (VernacEndProof (Proved (Opaque None,None))) }) in
ignore(Future.join checked_proof);
end;
RespBuiltProof(proof,time)
with
| e when CErrors.noncritical e || e = Stack_overflow ->
let (e, info) = CErrors.push e in
let e_error_at, e_safe_id = match Stateid.get info with
| Some (safe, err) -> err, safe
| None -> Stateid.dummy, Stateid.dummy in
let e_msg = iprint (e, info) in
prerr_endline (fun () -> "failed with the following exception:");
prerr_endline (fun () -> string_of_ppcmds e_msg);
let e_safe_states = List.filter State.is_cached_and_valid my_states in
RespError { e_error_at; e_safe_id; e_msg; e_safe_states }
let perform_states query =
if query = [] then [] else
let is_tac e = match classify_vernac e with
| VtProofStep _, _ -> true
| _ -> false
in
let initial =
let rec aux id =
try match VCS.visit id with { next } -> aux next
with VCS.Expired -> id in
aux (List.hd query) in
let get_state seen id =
let prev =
try
let { next = prev; step } = VCS.visit id in
if State.is_cached_and_valid prev && List.mem prev seen
then Some (prev, State.get_cached prev, step)
else None
with VCS.Expired -> None in
let this =
if State.is_cached_and_valid id then Some (State.get_cached id) else None in
match prev, this with
| _, None -> None
| Some (prev, o, `Cmd { cast = { expr }}), Some n
Some (id, `Proof (prev, State.proof_part_of_frozen n))
| Some _, Some s ->
msg_debug (str "STM: sending back a fat state");
Some (id, `Full s)
| _, Some s -> Some (id, `Full s) in
let rec aux seen = function
| [] -> []
| id :: rest ->
match get_state seen id with
| None -> aux seen rest
| Some stuff -> stuff :: aux (id :: seen) rest in
aux [initial] query
let perform = function
| ReqBuildProof (bp,drop,states) -> perform_buildp bp drop states
| ReqStates sl -> RespStates (perform_states sl)
let on_marshal_error s = function
| States _ -> msg_error(strbrk("Marshalling error: "^s^". "^
"The system state could not be sent to the master process."))
| BuildProof { t_exn_info; t_stop; t_assign; t_loc; t_drop = drop_pt } ->
msg_error(strbrk("Marshalling error: "^s^". "^
"The system state could not be sent to the worker process. "^
"Falling back to local, lazy, evaluation."));
t_assign(`Comp(build_proof_here ~drop_pt t_exn_info t_loc t_stop));
feedback (InProgress ~-1)
and Slaves : sig
val build_proof :
loc:Loc.t -> drop_pt:bool ->
exn_info:(Stateid.t * Stateid.t) -> block_start:Stateid.t -> block_stop:Stateid.t ->
name:string -> future_proof * cancel_switch
val wait_all_done : unit -> unit
val init : unit -> unit
type 'a tasks = (('a,VCS.vcs) Stateid.request * bool) list
val dump_snapshot : unit -> Future.UUID.t tasks
val check_task : string -> int tasks -> int -> bool
val info_tasks : 'a tasks -> (string * float * int) list
val finish_task :
string ->
Library.seg_univ -> Library.seg_discharge -> Library.seg_proofs ->
int tasks -> int -> Library.seg_univ
val cancel_worker : WorkerPool.worker_id -> unit
val reset_task_queue : unit -> unit
val set_perspective : Stateid.t list -> unit
module TaskQueue = AsyncTaskQueue.MakeQueue(ProofTask)
let queue = ref None
let init () =
if Flags.async_proofs_is_master () then
queue := Some (TaskQueue.create !Flags.async_proofs_n_workers)
else
queue := Some (TaskQueue.create 0)
let check_task_aux extra name l i =
let { Stateid.stop; document; loc; name = r_name }, drop = List.nth l i in
Flags.if_verbose msg_info
(str(Printf.sprintf "Checking task %d (%s%s) of %s" i r_name extra name));
VCS.restore document;
let start =
let rec aux cur =
try aux (VCS.visit cur).next
with VCS.Expired -> cur in
aux stop in
try
Reach.known_state ~cache:`No stop;
if drop then
let _proof = Proof_global.return_proof ~allow_partial:true () in
`OK_ADMITTED
else begin
Proof_global.set_terminator
(Lemmas.standard_proof_terminator []
(Lemmas.mk_hook (fun _ _ -> ())));
let proof =
Proof_global.close_proof ~keep_body_ucst_separate:true (fun x -> x) in
Reach.known_state ~cache:`No start;
vernac_interp stop ~proof
{ verbose = false; loc; indentation = 0; strlen = 0;
expr = (VernacEndProof (Proved (Opaque None,None))) };
`OK proof
end
with e ->
let (e, info) = CErrors.push e in
(try match Stateid.get info with
| None ->
msg_error (
str"File " ++ str name ++ str ": proof of " ++ str r_name ++
spc () ++ iprint (e, info))
| Some (_, cur) ->
match VCS.visit cur with
| { step = `Cmd { cast = { loc } } }
| { step = `Fork (( { loc }, _, _, _), _) }
| { step = `Qed ( { qast = { loc } }, _) }
| { step = `Sideff (`Ast ( { loc }, _)) } ->
let start, stop = Loc.unloc loc in
msg_error (
str"File " ++ str name ++ str ": proof of " ++ str r_name ++
str ": chars " ++ int start ++ str "-" ++ int stop ++
spc () ++ iprint (e, info))
| _ ->
msg_error (
str"File " ++ str name ++ str ": proof of " ++ str r_name ++
spc () ++ iprint (e, info))
with e ->
msg_error (str"unable to print error message: " ++
str (Printexc.to_string e)));
if drop then `ERROR_ADMITTED else `ERROR
let finish_task name (u,cst,_) d p l i =
let { Stateid.uuid = bucket }, drop = List.nth l i in
let bucket_name =
if bucket < 0 then (assert drop; ", no bucket")
else Printf.sprintf ", bucket %d" bucket in
match check_task_aux bucket_name name l i with
| `ERROR -> exit 1
| `ERROR_ADMITTED -> u, cst, false
| `OK_ADMITTED -> u, cst, false
| `OK (po,_) ->
let discharge c = List.fold_right Cooking.cook_constr d.(bucket) c in
let con =
Nametab.locate_constant
(Libnames.qualid_of_ident po.Proof_global.id) in
let c = Global.lookup_constant con in
let o = match c.Declarations.const_body with
| Declarations.OpaqueDef o -> o
| _ -> assert false in
let uc =
Option.get
(Opaqueproof.get_constraints (Global.opaque_tables ()) o) in
let pr =
Future.from_val (Option.get (Global.body_of_constant_body c)) in
let uc =
Future.chain
~greedy:true ~pure:true uc Univ.hcons_universe_context_set in
let pr = Future.chain ~greedy:true ~pure:true pr discharge in
let pr = Future.chain ~greedy:true ~pure:true pr Constr.hcons in
Future.sink pr;
let extra = Future.join uc in
u.(bucket) <- uc;
p.(bucket) <- pr;
u, Univ.ContextSet.union cst extra, false
let check_task name l i =
match check_task_aux "" name l i with
| `OK _ | `OK_ADMITTED -> true
| `ERROR | `ERROR_ADMITTED -> false
let info_tasks l =
CList.map_i (fun i ({ Stateid.loc; name }, _) ->
let time1 =
try float_of_string (Aux_file.get !hints loc "proof_build_time")
with Not_found -> 0.0 in
let time2 =
try float_of_string (Aux_file.get !hints loc "proof_check_time")
with Not_found -> 0.0 in
name, max (time1 +. time2) 0.0001,i) 0 l
let set_perspective idl =
ProofTask.set_perspective idl;
TaskQueue.broadcast (Option.get !queue);
let open ProofTask in
let overlap s1 s2 =
List.exists (fun x -> CList.mem_f Stateid.equal x s2) s1 in
let overlap_rel s1 s2 =
match overlap s1 idl, overlap s2 idl with
| true, true | false, false -> 0
| true, false -> -1
| false, true -> 1 in
TaskQueue.set_order (Option.get !queue) (fun task1 task2 ->
match task1, task2 with
| BuildProof { t_states = s1 },
BuildProof { t_states = s2 } -> overlap_rel s1 s2
| _ -> 0)
let build_proof ~loc ~drop_pt ~exn_info ~block_start ~block_stop ~name:pname =
let id, valid as t_exn_info = exn_info in
let cancel_switch = ref false in
if TaskQueue.n_workers (Option.get !queue) = 0 then
if !Flags.compilation_mode = Flags.BuildVio then begin
let f,assign =
Future.create_delegate ~blocking:true ~name:pname (State.exn_on id ~valid) in
let t_uuid = Future.uuid f in
let task = ProofTask.(BuildProof {
t_exn_info; t_start = block_start; t_stop = block_stop; t_drop = drop_pt;
t_assign = assign; t_loc = loc; t_uuid; t_name = pname;
t_states = VCS.nodes_in_slice ~block_start ~block_stop }) in
TaskQueue.enqueue_task (Option.get !queue) (task,cancel_switch);
f, cancel_switch
end else
ProofTask.build_proof_here ~drop_pt t_exn_info loc block_stop, cancel_switch
else
let f, t_assign = Future.create_delegate ~name:pname (State.exn_on id ~valid) in
let t_uuid = Future.uuid f in
feedback (InProgress 1);
let task = ProofTask.(BuildProof {
t_exn_info; t_start = block_start; t_stop = block_stop; t_assign; t_drop = drop_pt;
t_loc = loc; t_uuid; t_name = pname;
t_states = VCS.nodes_in_slice ~block_start ~block_stop }) in
TaskQueue.enqueue_task (Option.get !queue) (task,cancel_switch);
f, cancel_switch
let wait_all_done () = TaskQueue.join (Option.get !queue)
let cancel_worker n = TaskQueue.cancel_worker (Option.get !queue) n
type 'a tasks = (('a,VCS.vcs) Stateid.request * bool) list
let dump_snapshot () =
let tasks = TaskQueue.snapshot (Option.get !queue) in
let reqs =
CList.map_filter
ProofTask.(fun x ->
match request_of_task `Fresh x with
| Some (ReqBuildProof (r, b, _)) -> Some(r, b)
| _ -> None)
tasks in
prerr_endline (fun () -> Printf.sprintf "dumping %d tasks\n" (List.length reqs));
reqs
let reset_task_queue () = TaskQueue.clear (Option.get !queue)
and TacTask : sig
type output = Constr.constr * Evd.evar_universe_context
type task = {
t_state : Stateid.t;
t_state_fb : Stateid.t;
t_assign : output Future.assignement -> unit;
t_ast : int * aast;
t_goal : Goal.goal;
t_kill : unit -> unit;
t_name : string }
exception NoProgress
include AsyncTaskQueue.Task with type task := task
type output = Constr.constr * Evd.evar_universe_context
let forward_feedback msg = Hooks.(call forward_feedback msg)
type task = {
t_state : Stateid.t;
t_state_fb : Stateid.t;
t_assign : output Future.assignement -> unit;
t_ast : int * aast;
t_goal : Goal.goal;
t_kill : unit -> unit;
t_name : string }
type request = {
r_state : Stateid.t;
r_state_fb : Stateid.t;
r_document : VCS.vcs option;
r_ast : int * aast;
r_goal : Goal.goal;
r_name : string }
type response =
| RespBuiltSubProof of output
| RespError of std_ppcmds
| RespNoProgress
exception NoProgress
let name = ref "tacworker"
let extra_env () = [||]
type competence = unit
let task_match _ _ = true
let request_of_task age { t_state; t_state_fb; t_ast; t_goal; t_name } =
try Some {
r_state = t_state;
r_state_fb = t_state_fb;
r_document =
if age <> `Fresh then None
else Some (VCS.slice ~block_start:t_state ~block_stop:t_state);
r_ast = t_ast;
r_goal = t_goal;
r_name = t_name }
with VCS.Expired -> None
let use_response _ { t_assign; t_state; t_state_fb; t_kill } resp =
match resp with
| RespBuiltSubProof o -> t_assign (`Val o); `Stay ((),[])
| RespNoProgress ->
let e = (NoProgress, Exninfo.null) in
t_assign (`Exn e);
t_kill ();
`Stay ((),[])
| RespError msg ->
let e = (RemoteException msg, Exninfo.null) in
t_assign (`Exn e);
t_kill ();
`Stay ((),[])
let on_marshal_error err { t_name } =
pr_err ("Fatal marshal error: " ^ t_name );
flush_all (); exit 1
let on_task_cancellation_or_expiration_or_slave_death = function
| Some { t_kill } -> t_kill ()
| _ -> ()
let command_focus = Proof.new_focus_kind ()
let focus_cond = Proof.no_cond command_focus
let perform { r_state = id; r_state_fb; r_document = vcs; r_ast; r_goal } =
Option.iter VCS.restore vcs;
try
Reach.known_state ~cache:`No id;
Future.purify (fun () ->
let _,_,_,_,sigma0 = Proof.proof (Proof_global.give_me_the_proof ()) in
let g = Evd.find sigma0 r_goal in
if not (
Evarutil.is_ground_term sigma0 Evd.(evar_concl g) &&
List.for_all (Context.Named.Declaration.for_all (Evarutil.is_ground_term sigma0))
Evd.(evar_context g))
then
CErrors.errorlabstrm "STM" (strbrk("the par: goal selector supports ground "^
"goals only"))
else begin
let (i, ast) = r_ast in
Proof_global.simple_with_current_proof (fun _ p -> Proof.focus focus_cond () i p);
vernac_interp r_state_fb ast;
let _,_,_,_,sigma = Proof.proof (Proof_global.give_me_the_proof ()) in
match Evd.(evar_body (find sigma r_goal)) with
| Evd.Evar_empty -> RespNoProgress
| Evd.Evar_defined t ->
let t = Evarutil.nf_evar sigma t in
if Evarutil.is_ground_term sigma t then
RespBuiltSubProof (t, Evd.evar_universe_context sigma)
else CErrors.errorlabstrm "STM" (str"The solution is not ground")
end) ()
with e when CErrors.noncritical e -> RespError (CErrors.print e)
let name_of_task { t_name } = t_name
let name_of_request { r_name } = r_name
and Partac : sig
val vernac_interp :
solve:bool -> abstract:bool -> cancel_switch ->
int -> Stateid.t -> Stateid.t -> aast ->
unit
module TaskQueue = AsyncTaskQueue.MakeQueue(TacTask)
let vernac_interp ~solve ~abstract cancel nworkers safe_id id
{ indentation; verbose; loc; expr = e; strlen }
=
let e, time, fail =
let rec find ~time ~fail = function
| VernacTime (_,e) -> find ~time:true ~fail e
| VernacRedirect (_,(_,e)) -> find ~time ~fail e
| VernacFail e -> find ~time ~fail:true e
| e -> e, time, fail in find ~time:false ~fail:false e in
Hooks.call Hooks.with_fail fail (fun () ->
(if time then System.with_time !Flags.time else (fun x -> x)) (fun () ->
ignore(TaskQueue.with_n_workers nworkers (fun queue ->
Proof_global.with_current_proof (fun _ p ->
let goals, _, _, _, _ = Proof.proof p in
let open TacTask in
let res = CList.map_i (fun i g ->
let f, assign =
Future.create_delegate
~name:(Printf.sprintf "subgoal %d" i)
(State.exn_on id ~valid:safe_id) in
let t_ast = (i, { indentation; verbose; loc; expr = e; strlen }) in
let t_name = Goal.uid g in
TaskQueue.enqueue_task queue
({ t_state = safe_id; t_state_fb = id;
t_assign = assign; t_ast; t_goal = g; t_name;
t_kill = (fun () -> if solve then TaskQueue.cancel_all queue) },
cancel);
g,f)
1 goals in
TaskQueue.join queue;
let assign_tac : unit Proofview.tactic =
Proofview.(Goal.nf_enter { Goal.enter = fun g ->
let gid = Goal.goal g in
let f =
try List.assoc gid res
with Not_found -> CErrors.anomaly(str"Partac: wrong focus") in
if not (Future.is_over f) then
if solve then Tacticals.New.tclZEROMSG
(str"Interrupted by the failure of another goal")
else tclUNIT ()
else
let open Notations in
try
let pt, uc = Future.join f in
prerr_endline (fun () -> string_of_ppcmds(hov 0 (
str"g=" ++ int (Evar.repr gid) ++ spc () ++
str"t=" ++ (Printer.pr_constr pt) ++ spc () ++
str"uc=" ++ Evd.pr_evar_universe_context uc)));
(if abstract then Tactics.tclABSTRACT None else (fun x -> x))
(V82.tactic (Refiner.tclPUSHEVARUNIVCONTEXT uc) <*>
Tactics.exact_no_check pt)
with TacTask.NoProgress ->
if solve then Tacticals.New.tclSOLVE [] else tclUNIT ()
})
in
Proof.run_tactic (Global.env()) assign_tac p)))) ())
and QueryTask : sig
type task = { t_where : Stateid.t; t_for : Stateid.t ; t_what : aast }
include AsyncTaskQueue.Task with type task := task
type task =
{ t_where : Stateid.t; t_for : Stateid.t ; t_what : aast }
type request =
{ r_where : Stateid.t ; r_for : Stateid.t ; r_what : aast; r_doc : VCS.vcs }
type response = unit
let name = ref "queryworker"
let extra_env _ = [||]
type competence = unit
let task_match _ _ = true
let request_of_task _ { t_where; t_what; t_for } =
try Some {
r_where = t_where;
r_for = t_for;
r_doc = VCS.slice ~block_start:t_where ~block_stop:t_where;
r_what = t_what }
with VCS.Expired -> None
let use_response _ _ _ = `End
let on_marshal_error _ _ =
pr_err ("Fatal marshal error in query");
flush_all (); exit 1
let on_task_cancellation_or_expiration_or_slave_death _ = ()
let forward_feedback msg = Hooks.(call forward_feedback msg)
let perform { r_where; r_doc; r_what; r_for } =
VCS.restore r_doc;
VCS.print ();
Reach.known_state ~cache:`No r_where;
try
vernac_interp r_for { r_what with verbose = true };
feedback ~id:(State r_for) Processed
with e when CErrors.noncritical e ->
let e = CErrors.push e in
let msg = pp_to_richpp (iprint e) in
feedback ~id:(State r_for) (Message (Error, None, msg))
let name_of_task { t_what } = string_of_ppcmds (pr_ast t_what)
let name_of_request { r_what } = string_of_ppcmds (pr_ast r_what)
and Query : sig
val init : unit -> unit
val vernac_interp : cancel_switch -> Stateid.t -> Stateid.t -> aast -> unit
module TaskQueue = AsyncTaskQueue.MakeQueue(QueryTask)
let queue = ref None
let vernac_interp switch prev id q =
assert(TaskQueue.n_workers (Option.get !queue) > 0);
TaskQueue.enqueue_task (Option.get !queue)
QueryTask.({ t_where = prev; t_for = id; t_what = q }, switch)
let init () = queue := Some (TaskQueue.create
(if !Flags.async_proofs_full then 1 else 0))
and Reach : sig
val known_state :
?redefine_qed:bool -> cache:Summary.marshallable -> Stateid.t -> unit
let pstate = summary_pstate
let async_policy () =
let open Flags in
if is_universe_polymorphism () then false
else if interactive () = `Yes then
(async_proofs_is_master () || !async_proofs_mode = APonLazy)
else
(!compilation_mode = BuildVio || !async_proofs_mode <> APoff)
let delegate name =
get_hint_bp_time name >= !Flags.async_proofs_delegation_threshold
|| !Flags.compilation_mode = Flags.BuildVio
|| !Flags.async_proofs_full
let warn_deprecated_nested_proofs =
CWarnings.create ~name:"deprecated-nested-proofs" ~category:"deprecated"
(fun () ->
strbrk ("Nested proofs are deprecated and will "^
"stop working in a future Coq version"))
let collect_proof keep cur hd brkind id =
prerr_endline (fun () -> "Collecting proof ending at "^Stateid.to_string id);
let no_name = "" in
let name = function
| [] -> no_name
| id :: _ -> Id.to_string id in
let loc = (snd cur).loc in
let rec is_defined_expr = function
| VernacEndProof (Proved ((Transparent|Opaque (Some _)),_)) -> true
| VernacTime (_, e) -> is_defined_expr e
| VernacRedirect (_, (_, e)) -> is_defined_expr e
| VernacTimeout (_, e) -> is_defined_expr e
| _ -> false in
let is_defined = function
| _, { expr = e } -> is_defined_expr e in
let proof_using_ast = function
| Some (_, ({ expr = VernacProof(_,Some _) } as v)) -> Some v
| _ -> None in
let has_proof_using x = proof_using_ast x <> None in
let proof_no_using = function
| Some (_, ({ expr = VernacProof(t,None) } as v)) -> t,v
| _ -> assert false in
let has_proof_no_using = function
| Some (_, { expr = VernacProof(_,None) }) -> true
| _ -> false in
let too_complex_to_delegate = function
| { expr = (VernacDeclareModule _
| VernacDefineModule _
| VernacDeclareModuleType _
| VernacInclude _) } -> true
| { expr = (VernacRequire _ | VernacImport _) } -> true
| ast -> may_pierce_opaque ast in
let parent = function Some (p, _) -> p | None -> assert false in
let is_empty = function `Async(_,_,[],_,_) | `MaybeASync(_,_,[],_,_) -> true | _ -> false in
let rec collect last accn id =
let view = VCS.visit id in
match view.step with
| (`Sideff (`Ast(x,_)) | `Cmd { cast = x })
when too_complex_to_delegate x -> `Sync(no_name,None,`Print)
| `Cmd { cast = x } -> collect (Some (id,x)) (id::accn) view.next
| `Sideff (`Ast(x,_)) -> collect (Some (id,x)) (id::accn) view.next
| `Alias _ -> `Sync (no_name,None,`Alias)
| `Fork((_,_,_,_::_::_), _) ->
`Sync (no_name,proof_using_ast last,`MutualProofs)
| `Fork((_,_,Doesn'tGuaranteeOpacity,_), _) ->
`Sync (no_name,proof_using_ast last,`Doesn'tGuaranteeOpacity)
| `Fork((_,hd',GuaranteesOpacity,ids), _) when has_proof_using last ->
assert (VCS.Branch.equal hd hd' || VCS.Branch.equal hd VCS.edit_branch);
let name = name ids in
`ASync (parent last,proof_using_ast last,accn,name,delegate name)
| `Fork((_, hd', GuaranteesOpacity, ids), _) when
has_proof_no_using last && not (State.is_cached_and_valid (parent last)) &&
!Flags.compilation_mode = Flags.BuildVio ->
assert (VCS.Branch.equal hd hd'||VCS.Branch.equal hd VCS.edit_branch);
(try
let name, hint = name ids, get_hint_ctx loc in
let t, v = proof_no_using last in
v.expr <- VernacProof(t, Some hint);
`ASync (parent last,proof_using_ast last,accn,name,delegate name)
with Not_found ->
let name = name ids in
`MaybeASync (parent last, None, accn, name, delegate name))
| `Fork((_, hd', GuaranteesOpacity, ids), _) ->
assert (VCS.Branch.equal hd hd' || VCS.Branch.equal hd VCS.edit_branch);
let name = name ids in
`MaybeASync (parent last, None, accn, name, delegate name)
| `Sideff _ ->
warn_deprecated_nested_proofs ();
`Sync (no_name,None,`NestedProof)
| _ -> `Sync (no_name,None,`Unknown) in
let make_sync why = function
| `Sync(name,pua,_) -> `Sync (name,pua,why)
| `MaybeASync(_,pua,_,name,_) -> `Sync (name,pua,why)
| `ASync(_,pua,_,name,_) -> `Sync (name,pua,why) in
let check_policy rc = if async_policy () then rc else make_sync `Policy rc in
match cur, (VCS.visit id).step, brkind with
| (parent, { expr = VernacExactProof _ }), `Fork _, _ ->
`Sync (no_name,None,`Immediate)
| _, _, { VCS.kind = `Edit _ } -> check_policy (collect (Some cur) [] id)
| _ ->
if is_defined cur then `Sync (no_name,None,`Transparent)
else if keep == VtDrop then `Sync (no_name,None,`Aborted)
else
let rc = collect (Some cur) [] id in
if is_empty rc then make_sync `AlreadyEvaluated rc
else if (keep == VtKeep || keep == VtKeepAsAxiom) &&
(not(State.is_cached_and_valid id) || !Flags.async_proofs_full)
then check_policy rc
else make_sync `AlreadyEvaluated rc
let string_of_reason = function
| `Transparent -> "non opaque"
| `AlreadyEvaluated -> "proof already evaluated"
| `Policy -> "policy"
| `NestedProof -> "contains nested proof"
| `Immediate -> "proof term given explicitly"
| `Aborted -> "aborted proof"
| `Doesn'tGuaranteeOpacity -> "not a simple opaque lemma"
| `MutualProofs -> "block of mutually recursive proofs"
| `Alias -> "contains Undo-like command"
| `Print -> "contains Print-like command"
| `NoPU_NoHint_NoES -> "no 'Proof using..', no .aux file, inside a section"
| `Unknown -> "unsupported case"
let log_string s = prerr_debug (fun () -> "STM: " ^ s)
let log_processing_async id name = log_string Printf.(sprintf
"%s: proof %s: asynch" (Stateid.to_string id) name
)
let log_processing_sync id name reason = log_string Printf.(sprintf
"%s: proof %s: synch (cause: %s)"
(Stateid.to_string id) name (string_of_reason reason)
)
let wall_clock_last_fork = ref 0.0
let known_state ?(redefine_qed=false) ~cache id =
let error_absorbing_tactic id blockname exn =
We keep the static / dynamic part of block detection separate , since
the static part could be performed earlier . As of today there is
no advantage in doing so since no UI can exploit such piece of info
the static part could be performed earlier. As of today there is
no advantage in doing so since no UI can exploit such piece of info *)
detect_proof_block id blockname;
let boxes = VCS.box_of id in
let valid_boxes = CList.map_filter (function
| ProofBlock ({ block_stop } as decl, name) when Stateid.equal block_stop id ->
Some (decl, name)
| _ -> None) boxes in
assert(List.length valid_boxes < 2);
if valid_boxes = [] then iraise exn
else
let decl, name = List.hd valid_boxes in
try
let _, dynamic_check = List.assoc name !proof_block_delimiters in
match dynamic_check decl with
| `Leaks -> iraise exn
| `ValidBlock { base_state; goals_to_admit; recovery_command } -> begin
let tac =
let open Proofview.Notations in
Proofview.Goal.nf_enter { enter = fun gl ->
if CList.mem_f Evar.equal
(Proofview.Goal.goal gl) goals_to_admit then
Proofview.give_up else Proofview.tclUNIT ()
} in
match (VCS.get_info base_state).state with
| Valid { proof } ->
Proof_global.unfreeze proof;
Proof_global.with_current_proof (fun _ p ->
feedback ~id:(State id) Feedback.AddedAxiom;
fst (Pfedit.solve Vernacexpr.SelectAll None tac p), ());
Option.iter (fun expr -> vernac_interp id {
verbose = true; loc = Loc.ghost; expr; indentation = 0;
strlen = 0 })
recovery_command
| _ -> assert false
end
with Not_found ->
CErrors.errorlabstrm "STM"
(str "Unknown proof block delimiter " ++ str name)
in
let resilient_tactic id blockname f =
if !Flags.async_proofs_tac_error_resilience = `None ||
(Flags.async_proofs_is_master () &&
!Flags.async_proofs_mode = Flags.APoff)
then f ()
else
try f ()
with e when CErrors.noncritical e ->
let ie = CErrors.push e in
error_absorbing_tactic id blockname ie in
let resilient_command f x =
if not !Flags.async_proofs_cmd_error_resilience ||
(Flags.async_proofs_is_master () &&
!Flags.async_proofs_mode = Flags.APoff)
then f x
else
try f x
with e when CErrors.noncritical e -> () in
let cherry_pick_non_pstate () =
Summary.freeze_summary ~marshallable:`No ~complement:true pstate,
Lib.freeze ~marshallable:`No in
let inject_non_pstate (s,l) =
Summary.unfreeze_summary s; Lib.unfreeze l; update_global_env ()
in
let rec pure_cherry_pick_non_pstate safe_id id = Future.purify (fun id ->
prerr_endline (fun () -> "cherry-pick non pstate " ^ Stateid.to_string id);
reach ~safe_id id;
cherry_pick_non_pstate ()) id
traverses the dag backward from nodes being already calculated
and reach ?safe_id ?(redefine_qed=false) ?(cache=cache) id =
prerr_endline (fun () -> "reaching: " ^ Stateid.to_string id);
if not redefine_qed && State.is_cached ~cache id then begin
Hooks.(call state_computed id ~in_cache:true);
prerr_endline (fun () -> "reached (cache)");
State.install_cached id
end else
let step, cache_step, feedback_processed =
let view = VCS.visit id in
match view.step with
| `Alias (id,_) -> (fun () ->
reach view.next; reach id
), cache, true
| `Cmd { cast = x; cqueue = `SkipQueue } -> (fun () ->
reach view.next), cache, true
| `Cmd { cast = x; cqueue = `TacQueue (solve,abstract,cancel); cblock } ->
(fun () ->
resilient_tactic id cblock (fun () ->
reach ~cache:`Shallow view.next;
Hooks.(call tactic_being_run true);
Partac.vernac_interp ~solve ~abstract
cancel !Flags.async_proofs_n_tacworkers view.next id x;
Hooks.(call tactic_being_run false))
), cache, true
| `Cmd { cast = x; cqueue = `QueryQueue cancel }
when Flags.async_proofs_is_master () -> (fun () ->
reach view.next;
Query.vernac_interp cancel view.next id x
), cache, false
| `Cmd { cast = x; ceff = eff; ctac = true; cblock } -> (fun () ->
resilient_tactic id cblock (fun () ->
reach view.next;
Hooks.(call tactic_being_run true);
vernac_interp id x;
Hooks.(call tactic_being_run false));
if eff then update_global_env ()
), (if eff then `Yes else cache), true
| `Cmd { cast = x; ceff = eff } -> (fun () ->
(match !Flags.async_proofs_mode with
| Flags.APon | Flags.APonLazy ->
resilient_command reach view.next
| Flags.APoff -> reach view.next);
vernac_interp id x;
if eff then update_global_env ()
), (if eff then `Yes else cache), true
| `Fork ((x,_,_,_), None) -> (fun () ->
resilient_command reach view.next;
vernac_interp id x;
wall_clock_last_fork := Unix.gettimeofday ()
), `Yes, true
reach ~cache:`Shallow prev;
reach view.next;
(try vernac_interp id x;
with e when CErrors.noncritical e ->
let (e, info) = CErrors.push e in
let info = Stateid.add info ~valid:prev id in
iraise (e, info));
wall_clock_last_fork := Unix.gettimeofday ()
), `Yes, true
| `Qed ({ qast = x; keep; brinfo; brname } as qed, eop) ->
let rec aux = function
| `ASync (block_start, pua, nodes, name, delegate) -> (fun () ->
assert(keep == VtKeep || keep == VtKeepAsAxiom);
let drop_pt = keep == VtKeepAsAxiom in
let block_stop, exn_info, loc = eop, (id, eop), x.loc in
log_processing_async id name;
VCS.create_proof_task_box nodes ~qed:id ~block_start;
begin match brinfo, qed.fproof with
| { VCS.kind = `Edit _ }, None -> assert false
| { VCS.kind = `Edit (_,_,_, okeep, _) }, Some (ofp, cancel) ->
assert(redefine_qed = true);
if okeep != keep then
msg_error(strbrk("The command closing the proof changed. "
^"The kernel cannot take this into account and will "
^(if keep == VtKeep then "not check " else "reject ")
^"the "^(if keep == VtKeep then "new" else "incomplete")
^" proof. Reprocess the command declaring "
^"the proof's statement to avoid that."));
let fp, cancel =
Slaves.build_proof
~loc ~drop_pt ~exn_info ~block_start ~block_stop ~name in
Future.replace ofp fp;
qed.fproof <- Some (fp, cancel);
We do n't generate a new state , but we still need
* to install the right one
* to install the right one *)
State.install_cached id
| { VCS.kind = `Proof _ }, Some _ -> assert false
| { VCS.kind = `Proof _ }, None ->
reach ~cache:`Shallow block_start;
let fp, cancel =
if delegate then
Slaves.build_proof
~loc ~drop_pt ~exn_info ~block_start ~block_stop ~name
else
ProofTask.build_proof_here
~drop_pt exn_info loc block_stop, ref false
in
qed.fproof <- Some (fp, cancel);
let proof =
Proof_global.close_future_proof ~feedback_id:id fp in
if not delegate then ignore(Future.compute fp);
reach view.next;
vernac_interp id ~proof x;
feedback ~id:(State id) Incomplete
| { VCS.kind = `Master }, _ -> assert false
end;
Proof_global.discard_all ()
), (if redefine_qed then `No else `Yes), true
| `Sync (name, _, `Immediate) -> (fun () ->
reach eop; vernac_interp id x; Proof_global.discard_all ()
), `Yes, true
| `Sync (name, pua, reason) -> (fun () ->
log_processing_sync id name reason;
reach eop;
let wall_clock = Unix.gettimeofday () in
record_pb_time name x.loc (wall_clock -. !wall_clock_last_fork);
let proof =
match keep with
| VtDrop -> None
| VtKeepAsAxiom ->
let ctx = Evd.empty_evar_universe_context in
let fp = Future.from_val ([],ctx) in
qed.fproof <- Some (fp, ref false); None
| VtKeep ->
Some(Proof_global.close_proof
~keep_body_ucst_separate:false
(State.exn_on id ~valid:eop)) in
if keep != VtKeepAsAxiom then
reach view.next;
let wall_clock2 = Unix.gettimeofday () in
vernac_interp id ?proof x;
let wall_clock3 = Unix.gettimeofday () in
Aux_file.record_in_aux_at x.loc "proof_check_time"
(Printf.sprintf "%.3f" (wall_clock3 -. wall_clock2));
Proof_global.discard_all ()
), `Yes, true
| `MaybeASync (start, pua, nodes, name, delegate) -> (fun () ->
reach ~cache:`Shallow start;
if List.is_empty (Environ.named_context (Global.env ()))
then pi1 (aux (`ASync (start, pua, nodes, name, delegate))) ()
else pi1 (aux (`Sync (name, pua, `NoPU_NoHint_NoES))) ()
), (if redefine_qed then `No else `Yes), true
in
aux (collect_proof keep (view.next, x) brname brinfo eop)
| `Sideff (`Ast (x,_)) -> (fun () ->
reach view.next; vernac_interp id x; update_global_env ()
), cache, true
| `Sideff (`Id origin) -> (fun () ->
reach view.next;
inject_non_pstate (pure_cherry_pick_non_pstate view.next origin);
), cache, true
in
let cache_step =
if !Flags.async_proofs_cache = Some Flags.Force then `Yes
else cache_step in
State.define ?safe_id
~cache:cache_step ~redefine:redefine_qed ~feedback_processed step id;
prerr_endline (fun () -> "reached: "^ Stateid.to_string id) in
reach ~redefine_qed id
let init () =
VCS.init Stateid.initial;
set_undo_classifier Backtrack.undo_vernac_classifier;
State.define ~cache:`Yes (fun () -> ()) Stateid.initial;
Backtrack.record ();
Slaves.init ();
if Flags.async_proofs_is_master () then begin
prerr_endline (fun () -> "Initializing workers");
Query.init ();
let opts = match !Flags.async_proofs_private_flags with
| None -> []
| Some s -> Str.split_delim (Str.regexp ",") s in
begin try
let env_opt = Str.regexp "^extra-env=" in
let env = List.find (fun s -> Str.string_match env_opt s 0) opts in
async_proofs_workers_extra_env := Array.of_list
(Str.split_delim (Str.regexp ";") (Str.replace_first env_opt "" env))
with Not_found -> () end;
end
let observe id =
let vcs = VCS.backup () in
try
Reach.known_state ~cache:(interactive ()) id;
VCS.print ()
with e ->
let e = CErrors.push e in
VCS.print ();
VCS.restore vcs;
iraise e
let finish ?(print_goals=false) () =
let head = VCS.current_branch () in
observe (VCS.get_branch_pos head);
if print_goals then msg_notice (pr_open_cur_subgoals ());
VCS.print ();
match VCS.get_branch head with
| { VCS.kind = `Edit (mode,_,_,_,_) } -> Proof_global.activate_proof_mode mode
| { VCS.kind = `Proof (mode, _) } -> Proof_global.activate_proof_mode mode
| _ -> ()
let wait () =
Slaves.wait_all_done ();
VCS.print ()
let rec join_admitted_proofs id =
if Stateid.equal id Stateid.initial then () else
let view = VCS.visit id in
match view.step with
| `Qed ({ keep = VtKeepAsAxiom; fproof = Some (fp,_) },_) ->
ignore(Future.force fp);
join_admitted_proofs view.next
| _ -> join_admitted_proofs view.next
let join () =
finish ();
wait ();
prerr_endline (fun () -> "Joining the environment");
Global.join_safe_environment ();
prerr_endline (fun () -> "Joining Admitted proofs");
join_admitted_proofs (VCS.get_branch_pos (VCS.current_branch ()));
VCS.print ();
VCS.print ()
let dump_snapshot () = Slaves.dump_snapshot (), RemoteCounter.snapshot ()
type document = VCS.vcs
type tasks = int Slaves.tasks * RemoteCounter.remote_counters_status
let check_task name (tasks,rcbackup) i =
RemoteCounter.restore rcbackup;
let vcs = VCS.backup () in
try
let rc = Future.purify (Slaves.check_task name tasks) i in
VCS.restore vcs;
rc
with e when CErrors.noncritical e -> VCS.restore vcs; false
let info_tasks (tasks,_) = Slaves.info_tasks tasks
let finish_tasks name u d p (t,rcbackup as tasks) =
RemoteCounter.restore rcbackup;
let finish_task u (_,_,i) =
let vcs = VCS.backup () in
let u = Future.purify (Slaves.finish_task name u d p t) i in
VCS.restore vcs;
u in
try
let u, a, _ = List.fold_left finish_task u (info_tasks tasks) in
(u,a,true), p
with e ->
let e = CErrors.push e in
msg_error (str"File " ++ str name ++ str ":" ++ spc () ++ iprint e);
exit 1
let merge_proof_branch ~valid ?id qast keep brname =
let brinfo = VCS.get_branch brname in
let qed fproof = { qast; keep; brname; brinfo; fproof } in
match brinfo with
| { VCS.kind = `Proof _ } ->
VCS.checkout VCS.Branch.master;
let id = VCS.new_node ?id () in
VCS.merge id ~ours:(Qed (qed None)) brname;
VCS.delete_branch brname;
VCS.propagate_sideff None;
`Ok
| { VCS.kind = `Edit (mode, qed_id, master_id, _,_) } ->
let ofp =
match VCS.visit qed_id with
| { step = `Qed ({ fproof }, _) } -> fproof
| _ -> assert false in
VCS.rewrite_merge qed_id ~ours:(Qed (qed ofp)) ~at:master_id brname;
VCS.delete_branch brname;
VCS.gc ();
Reach.known_state ~redefine_qed:true ~cache:`No qed_id;
VCS.checkout VCS.Branch.master;
`Unfocus qed_id
| { VCS.kind = `Master } ->
iraise (State.exn_on ~valid Stateid.dummy (Proof_global.NoCurrentProof, Exninfo.null))
let handle_failure (e, info) vcs tty =
if e = CErrors.Drop then iraise (e, info) else
match Stateid.get info with
| None ->
VCS.restore vcs;
VCS.print ();
if tty && interactive () = `Yes then begin
Hopefully the 1 to last state is valid
Backtrack.back_safe ();
VCS.checkout_shallowest_proof_branch ();
end;
VCS.print ();
anomaly(str"error with no safe_id attached:" ++ spc() ++
CErrors.iprint_no_report (e, info))
| Some (safe_id, id) ->
prerr_endline (fun () -> "Failed at state " ^ Stateid.to_string id);
VCS.restore vcs;
if tty && interactive () = `Yes then begin
Backtrack.backto safe_id;
VCS.checkout_shallowest_proof_branch ();
Reach.known_state ~cache:(interactive ()) safe_id;
end;
VCS.print ();
iraise (e, info)
let snapshot_vio ldir long_f_dot_vo =
finish ();
if List.length (VCS.branches ()) > 1 then
CErrors.errorlabstrm "stm" (str"Cannot dump a vio with open proofs");
Library.save_library_to ~todo:(dump_snapshot ()) ldir long_f_dot_vo
(Global.opaque_tables ())
let reset_task_queue = Slaves.reset_task_queue
let process_transaction ?(newtip=Stateid.fresh ()) ~tty
({ verbose; loc; expr } as x) c =
prerr_endline (fun () -> "{{{ processing: "^ string_of_ppcmds (pr_ast x));
let vcs = VCS.backup () in
try
let head = VCS.current_branch () in
VCS.checkout head;
let rc = begin
prerr_endline (fun () ->
" classified as: " ^ string_of_vernac_classification c);
let (vt, vw) = c in
Ptcoq.show_vernac_typ_exp vt expr;
match c with
| VtStm(VtPG,false), VtNow -> vernac_interp Stateid.dummy x; `Ok
| VtStm(VtPG,_), _ -> anomaly(str "PG command in script or VtLater")
| VtStm (VtJoinDocument, b), VtNow -> join (); `Ok
| VtStm (VtFinish, b), VtNow -> finish (); `Ok
| VtStm (VtWait, b), VtNow -> finish (); wait (); `Ok
| VtStm (VtPrintDag, b), VtNow ->
VCS.print ~now:true (); `Ok
| VtStm (VtObserve id, b), VtNow -> observe id; `Ok
| VtStm ((VtObserve _ | VtFinish | VtJoinDocument
|VtPrintDag |VtWait),_), VtLater ->
anomaly(str"classifier: join actions cannot be classified as VtLater")
| VtStm (VtBack oid, true), w ->
let id = VCS.new_node ~id:newtip () in
let { mine; others } = Backtrack.branches_of oid in
let valid = VCS.get_branch_pos head in
List.iter (fun branch ->
if not (List.mem_assoc branch (mine::others)) then
ignore(merge_proof_branch ~valid x VtDrop branch))
(VCS.branches ());
VCS.checkout_shallowest_proof_branch ();
let head = VCS.current_branch () in
List.iter (fun b ->
if not(VCS.Branch.equal b head) then begin
VCS.checkout b;
VCS.commit (VCS.new_node ()) (Alias (oid,x));
end)
(VCS.branches ());
VCS.checkout_shallowest_proof_branch ();
VCS.commit id (Alias (oid,x));
Backtrack.record (); if w == VtNow then finish (); `Ok
| VtStm (VtBack id, false), VtNow ->
prerr_endline (fun () -> "undo to state " ^ Stateid.to_string id);
Backtrack.backto id;
VCS.checkout_shallowest_proof_branch ();
Reach.known_state ~cache:(interactive ()) id; `Ok
| VtStm (VtBack id, false), VtLater ->
anomaly(str"classifier: VtBack + VtLater must imply part_of_script")
| VtQuery (false,(report_id,route)), VtNow when tty = true ->
finish ();
(try Future.purify (vernac_interp report_id ~route)
{x with verbose = true }
with e when CErrors.noncritical e ->
let e = CErrors.push e in
iraise (State.exn_on ~valid:Stateid.dummy report_id e)); `Ok
| VtQuery (false,(report_id,route)), VtNow ->
(try vernac_interp report_id ~route x
with e ->
let e = CErrors.push e in
iraise (State.exn_on ~valid:Stateid.dummy report_id e)); `Ok
| VtQuery (true,(report_id,_)), w ->
assert(Stateid.equal report_id Stateid.dummy);
let id = VCS.new_node ~id:newtip () in
let queue =
if !Flags.async_proofs_full then `QueryQueue (ref false)
else if Flags.(!compilation_mode = BuildVio) &&
VCS.((get_branch head).kind = `Master) &&
may_pierce_opaque x
then `SkipQueue
else `MainQueue in
VCS.commit id (mkTransCmd x [] false queue);
Backtrack.record (); if w == VtNow then finish (); `Ok
| VtQuery (false,_), VtLater ->
anomaly(str"classifier: VtQuery + VtLater must imply part_of_script")
| VtStartProof (mode, guarantee, names), w ->
let id = VCS.new_node ~id:newtip () in
let bname = VCS.mk_branch_name x in
VCS.checkout VCS.Branch.master;
if VCS.Branch.equal head VCS.Branch.master then begin
VCS.commit id (Fork (x, bname, guarantee, names));
VCS.branch bname (`Proof (mode, VCS.proof_nesting () + 1))
end else begin
VCS.branch bname (`Proof (mode, VCS.proof_nesting () + 1));
VCS.merge id ~ours:(Fork (x, bname, guarantee, names)) head
end;
Proof_global.activate_proof_mode mode;
Backtrack.record (); if w == VtNow then finish (); `Ok
| VtProofMode _, VtLater ->
anomaly(str"VtProofMode must be executed VtNow")
| VtProofMode mode, VtNow ->
let id = VCS.new_node ~id:newtip () in
VCS.commit id (mkTransCmd x [] false `MainQueue);
List.iter
(fun bn -> match VCS.get_branch bn with
| { VCS.root; kind = `Master; pos } -> ()
| { VCS.root; kind = `Proof(_,d); pos } ->
VCS.delete_branch bn;
VCS.branch ~root ~pos bn (`Proof(mode,d))
| { VCS.root; kind = `Edit(_,f,q,k,ob); pos } ->
VCS.delete_branch bn;
VCS.branch ~root ~pos bn (`Edit(mode,f,q,k,ob)))
(VCS.branches ());
VCS.checkout_shallowest_proof_branch ();
Backtrack.record ();
finish ();
`Ok
| VtProofStep { parallel; proof_block_detection = cblock }, w ->
let id = VCS.new_node ~id:newtip () in
let queue =
match parallel with
| `Yes(solve,abstract) -> `TacQueue (solve, abstract, ref false)
| `No -> `MainQueue in
VCS.commit id (mkTransTac x cblock queue);
Static proof block detection delayed until an error really occurs .
If / when and UI will make something useful with this piece of info ,
detection should occur here .
detect_proof_block i d cblock ;
If/when and UI will make something useful with this piece of info,
detection should occur here.
detect_proof_block id cblock; *)
Backtrack.record (); if w == VtNow then finish (); `Ok
| VtQed keep, w ->
let valid = VCS.get_branch_pos head in
let rc = merge_proof_branch ~valid ~id:newtip x keep head in
VCS.checkout_shallowest_proof_branch ();
Backtrack.record (); if w == VtNow then finish ();
rc
| VtUnknown, _ when expr = VernacToplevelControl Drop ->
vernac_interp (VCS.get_branch_pos head) x; `Ok
| VtSideff l, w ->
let in_proof = not (VCS.Branch.equal head VCS.Branch.master) in
let id = VCS.new_node ~id:newtip () in
VCS.checkout VCS.Branch.master;
VCS.commit id (mkTransCmd x l in_proof `MainQueue);
We ca n't replay a Definition since universes may be differently
* inferred . This holds in Coq > = 8.5
* inferred. This holds in Coq >= 8.5 *)
let replay = match x.expr with
| VernacDefinition(_, _, DefineBody _) -> None
| _ -> Some x in
VCS.propagate_sideff ~replay;
VCS.checkout_shallowest_proof_branch ();
Backtrack.record (); if w == VtNow then finish (); `Ok
Unknown : we execute it , check for open goals and propagate sideeff
| VtUnknown, VtNow ->
let in_proof = not (VCS.Branch.equal head VCS.Branch.master) in
let id = VCS.new_node ~id:newtip () in
let head_id = VCS.get_branch_pos head in
let step () =
VCS.checkout VCS.Branch.master;
let mid = VCS.get_branch_pos VCS.Branch.master in
Reach.known_state ~cache:(interactive ()) mid;
vernac_interp id x;
Vernac x may or may not start a proof
if not in_proof && Proof_global.there_are_pending_proofs () then
begin
let bname = VCS.mk_branch_name x in
let rec opacity_of_produced_term = function
This AST is ambiguous , hence we check it dynamically
| VernacInstance (false, _,_ , None, _) -> GuaranteesOpacity
| VernacLocal (_,e) -> opacity_of_produced_term e
| _ -> Doesn'tGuaranteeOpacity in
VCS.commit id (Fork (x,bname,opacity_of_produced_term x.expr,[]));
let proof_mode = default_proof_mode () in
VCS.branch bname (`Proof (proof_mode, VCS.proof_nesting () + 1));
Proof_global.activate_proof_mode proof_mode;
Ptcoq.begin_proof_nonstd expr;
end else begin
VCS.commit id (mkTransCmd x [] in_proof `MainQueue);
VCS.propagate_sideff ~replay:(Some x);
VCS.checkout_shallowest_proof_branch ();
end in
State.define ~safe_id:head_id ~cache:`Yes step id;
Backtrack.record (); `Ok
| VtUnknown, VtLater ->
anomaly(str"classifier: VtUnknown must imply VtNow")
end in
begin match expr with
| VernacStm (PGLast _) ->
if not (VCS.Branch.equal head VCS.Branch.master) then
vernac_interp Stateid.dummy
{ verbose = true; loc = Loc.ghost; indentation = 0; strlen = 0;
expr = VernacShow (ShowGoal OpenSubgoals) }
| _ -> ()
end;
prerr_endline (fun () -> "processed }}}");
VCS.print ();
rc
with e ->
let e = CErrors.push e in
handle_failure e vcs tty
let get_ast id =
match VCS.visit id with
| { step = `Cmd { cast = { loc; expr } } }
| { step = `Fork (({ loc; expr }, _, _, _), _) }
| { step = `Qed ({ qast = { loc; expr } }, _) } ->
Some (expr, loc)
| _ -> None
let stop_worker n = Slaves.cancel_worker n
You may need to know the len + indentation of previous command to compute
* the indentation of the current one .
* Eg . foo . bar .
* Here bar is indented of the indentation of foo + its strlen ( 4 )
* the indentation of the current one.
* Eg. foo. bar.
* Here bar is indented of the indentation of foo + its strlen (4) *)
let ind_len_of id =
if Stateid.equal id Stateid.initial then 0
else match (VCS.visit id).step with
| `Cmd { ctac = true; cast = { indentation; strlen } } ->
indentation + strlen
| _ -> 0
let add ~ontop ?newtip ?(check=ignore) verb eid s =
let cur_tip = VCS.cur_tip () in
if not (Stateid.equal ontop cur_tip) then
anomaly(str"Not yet implemented, the GUI should not try this");
let indentation, strlen, loc, ast =
vernac_parse ~indlen_prev:(fun () -> ind_len_of ontop) ?newtip eid s in
CWarnings.set_current_loc loc;
check(loc,ast);
let clas = classify_vernac ast in
let aast = { verbose = verb; indentation; strlen; loc; expr = ast } in
match process_transaction ?newtip ~tty:false aast clas with
| `Ok -> VCS.cur_tip (), `NewTip
| `Unfocus qed_id -> qed_id, `Unfocus (VCS.cur_tip ())
let set_perspective id_list = Slaves.set_perspective id_list
type focus = {
start : Stateid.t;
stop : Stateid.t;
tip : Stateid.t
}
let query ~at ?(report_with=(Stateid.dummy,default_route)) s =
Future.purify (fun s ->
if Stateid.equal at Stateid.dummy then finish ()
else Reach.known_state ~cache:`Yes at;
let newtip, route = report_with in
let indentation, strlen, loc, ast = vernac_parse ~newtip ~route 0 s in
CWarnings.set_current_loc loc;
let clas = classify_vernac ast in
let aast = { verbose = true; indentation; strlen; loc; expr = ast } in
match clas with
| VtStm (w,_), _ ->
ignore(process_transaction ~tty:false aast (VtStm (w,false), VtNow))
| _ ->
ignore(process_transaction
~tty:false aast (VtQuery (false,report_with), VtNow)))
s
let edit_at id =
if Stateid.equal id Stateid.dummy then anomaly(str"edit_at dummy") else
let vcs = VCS.backup () in
let on_cur_branch id =
let rec aux cur =
if id = cur then true
else match VCS.visit cur with
| { step = `Fork _ } -> false
| { next } -> aux next in
aux (VCS.get_branch_pos (VCS.current_branch ())) in
let rec is_pure_aux id =
let view = VCS.visit id in
match view.step with
| `Cmd _ -> is_pure_aux view.next
| `Fork _ -> true
| _ -> false in
let is_pure id =
match (VCS.visit id).step with
| `Qed (_,last_step) -> is_pure_aux last_step
| _ -> assert false
in
let is_ancestor_of_cur_branch id =
Stateid.Set.mem id
(VCS.reachable (VCS.get_branch_pos (VCS.current_branch ()))) in
let has_failed qed_id =
match VCS.visit qed_id with
| { step = `Qed ({ fproof = Some (fp,_) }, _) } -> Future.is_exn fp
| _ -> false in
let rec master_for_br root tip =
if Stateid.equal tip Stateid.initial then tip else
match VCS.visit tip with
| { step = (`Fork _ | `Qed _) } -> tip
| { step = `Sideff (`Ast(_,id)) } -> id
| { step = `Sideff _ } -> tip
| { next } -> master_for_br root next in
let reopen_branch start at_id mode qed_id tip old_branch =
let master_id, cancel_switch, keep =
match VCS.visit qed_id with
| { step = `Qed ({ fproof = Some (_,cs); keep },_) } -> start, cs, keep
| _ -> anomaly (str "ProofTask not ending with Qed") in
VCS.branch ~root:master_id ~pos:id
VCS.edit_branch (`Edit (mode, qed_id, master_id, keep, old_branch));
VCS.delete_boxes_of id;
cancel_switch := true;
Reach.known_state ~cache:(interactive ()) id;
VCS.checkout_shallowest_proof_branch ();
`Focus { stop = qed_id; start = master_id; tip } in
let no_edit = function
| `Edit (pm, _,_,_,_) -> `Proof(pm,1)
| x -> x in
let backto id bn =
List.iter VCS.delete_branch (VCS.branches ());
let ancestors = VCS.reachable id in
let { mine = brname, brinfo; others } = Backtrack.branches_of id in
List.iter (fun (name,{ VCS.kind = k; root; pos }) ->
if not(VCS.Branch.equal name VCS.Branch.master) &&
Stateid.Set.mem root ancestors then
VCS.branch ~root ~pos name k)
others;
VCS.reset_branch VCS.Branch.master (master_for_br brinfo.VCS.root id);
VCS.branch ~root:brinfo.VCS.root ~pos:brinfo.VCS.pos
(Option.default brname bn)
(no_edit brinfo.VCS.kind);
VCS.delete_boxes_of id;
VCS.gc ();
VCS.print ();
if not !Flags.async_proofs_full then
Reach.known_state ~cache:(interactive ()) id;
VCS.checkout_shallowest_proof_branch ();
`NewTip in
try
let rc =
let focused = List.exists ((=) VCS.edit_branch) (VCS.branches ()) in
let branch_info =
match snd (VCS.get_info id).vcs_backup with
| Some{ mine = bn, { VCS.kind = `Proof(m,_) }} -> Some(m,bn)
| Some{ mine = _, { VCS.kind = `Edit(m,_,_,_,bn) }} -> Some (m,bn)
| _ -> None in
match focused, VCS.proof_task_box_of id, branch_info with
| _, Some _, None -> assert false
| false, Some { qed = qed_id ; lemma = start }, Some(mode,bn) ->
let tip = VCS.cur_tip () in
if has_failed qed_id && is_pure qed_id && not !Flags.async_proofs_never_reopen_branch
then reopen_branch start id mode qed_id tip bn
else backto id (Some bn)
| true, Some { qed = qed_id }, Some(mode,bn) ->
if on_cur_branch id then begin
assert false
end else if is_ancestor_of_cur_branch id then begin
backto id (Some bn)
end else begin
anomaly(str"Cannot leave an `Edit branch open")
end
| true, None, _ ->
if on_cur_branch id then begin
VCS.reset_branch (VCS.current_branch ()) id;
Reach.known_state ~cache:(interactive ()) id;
VCS.checkout_shallowest_proof_branch ();
`NewTip
end else if is_ancestor_of_cur_branch id then begin
backto id None
end else begin
anomaly(str"Cannot leave an `Edit branch open")
end
| false, None, Some(_,bn) -> backto id (Some bn)
| false, None, None -> backto id None
in
VCS.print ();
rc
with e ->
let (e, info) = CErrors.push e in
match Stateid.get info with
| None ->
VCS.print ();
anomaly (str ("edit_at "^Stateid.to_string id^": ") ++
CErrors.print_no_report e)
| Some (_, id) ->
prerr_endline (fun () -> "Failed at state " ^ Stateid.to_string id);
VCS.restore vcs;
VCS.print ();
iraise (e, info)
let backup () = VCS.backup ()
let restore d = VCS.restore d
* * * * * * * * * * * * * * * * * * * * * * TTY API ( PG , coqtop , coqc ) * * * * * * * * * * * * * * * * * * * * * * * * * *
let interp verb (loc,e) =
let clas = classify_vernac e in
let aast = { verbose = verb; indentation = 0; strlen = 0; loc; expr = e } in
let rc = process_transaction ~tty:true aast clas in
if rc <> `Ok then anomaly(str"tty loop can't be mixed with the STM protocol");
if interactive () = `Yes ||
(!Flags.async_proofs_mode = Flags.APoff &&
!Flags.compilation_mode = Flags.BuildVo) then
let vcs = VCS.backup () in
let print_goals =
verb && match clas with
| VtQuery _, _ -> false
| (VtProofStep _ | VtStm (VtBack _, _) | VtStartProof _), _ -> true
| _ -> not !Flags.coqtop_ui in
try finish ~print_goals ()
with e ->
let e = CErrors.push e in
handle_failure e vcs true
let finish () = finish ()
let get_current_state () = VCS.cur_tip ()
let current_proof_depth () =
let head = VCS.current_branch () in
match VCS.get_branch head with
| { VCS.kind = `Master } -> 0
| { VCS.pos = cur; VCS.kind = (`Proof _ | `Edit _); VCS.root = root } ->
let rec distance root =
if Stateid.equal cur root then 0
else 1 + distance (VCS.visit cur).next in
distance cur
let unmangle n =
let n = VCS.Branch.to_string n in
let idx = String.index n '_' + 1 in
Names.id_of_string (String.sub n idx (String.length n - idx))
let proofname b = match VCS.get_branch b with
| { VCS.kind = (`Proof _| `Edit _) } -> Some b
| _ -> None
let get_all_proof_names () =
List.map unmangle (List.map_filter proofname (VCS.branches ()))
let get_current_proof_name () =
Option.map unmangle (proofname (VCS.current_branch ()))
let get_script prf =
let branch, test =
match prf with
| None -> VCS.Branch.master, fun _ -> true
| Some name -> VCS.current_branch (),fun nl -> nl=[] || List.mem name nl in
let rec find acc id =
if Stateid.equal id Stateid.initial ||
Stateid.equal id Stateid.dummy then acc else
let view = VCS.visit id in
match view.step with
| `Fork((_,_,_,ns), _) when test ns -> acc
| `Qed (qed, proof) -> find [qed.qast.expr, (VCS.get_info id).n_goals] proof
| `Sideff (`Ast (x,_)) ->
find ((x.expr, (VCS.get_info id).n_goals)::acc) view.next
| `Sideff (`Id id) -> find acc id
find ((x.expr, (VCS.get_info id).n_goals)::acc) view.next
| `Cmd _ -> find acc view.next
| `Alias (id,_) -> find acc id
| `Fork _ -> find acc view.next
in
find [] (VCS.get_branch_pos branch)
indentation code for Show Script , initially contributed
by
by D. de Rauglaudre *)
let indent_script_item ((ng1,ngl1),nl,beginend,ppl) (cmd,ng) =
let ngprev = List.fold_left (+) ng1 ngl1 in
let new_ngl =
if ng > ngprev then
(ng - ngprev + 1, ng1 - 1 :: ngl1)
else if ng < ngprev then
A subgoal have been solved . Let 's compute the new current level
by discarding all levels with 0 remaining goals .
by discarding all levels with 0 remaining goals. *)
let rec loop = function
| (0, ng2::ngl2) -> loop (ng2,ngl2)
| p -> p
in loop (ng1-1, ngl1)
else
(ng1, ngl1)
in
When a subgoal have been solved , separate this block by an empty line
let new_nl = (ng < ngprev)
in
let ind = List.length ngl1
in
let pred n = max 0 (n-1) in
let ind, nl, new_beginend = match cmd with
| VernacSubproof _ -> pred ind, nl, (pred ind)::beginend
| VernacEndSubproof -> List.hd beginend, false, List.tl beginend
| VernacBullet _ -> pred ind, nl, beginend
| _ -> ind, nl, beginend
in
let pp =
(if nl then fnl () else mt ()) ++
(hov (ind+1) (str (String.make ind ' ') ++ Ppvernac.pr_vernac cmd))
in
(new_ngl, new_nl, new_beginend, pp :: ppl)
let show_script ?proof () =
try
let prf =
try match proof with
| None -> Some (Pfedit.get_current_proof_name ())
| Some (p,_) -> Some (p.Proof_global.id)
with Proof_global.NoCurrentProof -> None
in
let cmds = get_script prf in
let _,_,_,indented_cmds =
List.fold_left indent_script_item ((1,[]),false,[],[]) cmds
in
let indented_cmds = List.rev (indented_cmds) in
msg_notice (v 0 (prlist_with_sep fnl (fun x -> x) indented_cmds))
with Vcs_aux.Expired -> ()
let state_computed_hook = Hooks.state_computed_hook
let state_ready_hook = Hooks.state_ready_hook
let parse_error_hook = Hooks.parse_error_hook
let execution_error_hook = Hooks.execution_error_hook
let forward_feedback_hook = Hooks.forward_feedback_hook
let process_error_hook = Hooks.process_error_hook
let interp_hook = Hooks.interp_hook
let with_fail_hook = Hooks.with_fail_hook
let unreachable_state_hook = Hooks.unreachable_state_hook
let get_fix_exn () = !State.fix_exn_ref
let tactic_being_run_hook = Hooks.tactic_being_run_hook
vim : set = marker :
|
f5be52901434a00ceaeb6a0d4cdb5134395548e74a512212a6d089a488b57d79 | tsloughter/kuberl | kuberl_v1beta1_cluster_role_binding.erl | -module(kuberl_v1beta1_cluster_role_binding).
-export([encode/1]).
-export_type([kuberl_v1beta1_cluster_role_binding/0]).
-type kuberl_v1beta1_cluster_role_binding() ::
#{ 'apiVersion' => binary(),
'kind' => binary(),
'metadata' => kuberl_v1_object_meta:kuberl_v1_object_meta(),
'roleRef' := kuberl_v1beta1_role_ref:kuberl_v1beta1_role_ref(),
'subjects' => list()
}.
encode(#{ 'apiVersion' := ApiVersion,
'kind' := Kind,
'metadata' := Metadata,
'roleRef' := RoleRef,
'subjects' := Subjects
}) ->
#{ 'apiVersion' => ApiVersion,
'kind' => Kind,
'metadata' => Metadata,
'roleRef' => RoleRef,
'subjects' => Subjects
}.
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1beta1_cluster_role_binding.erl | erlang | -module(kuberl_v1beta1_cluster_role_binding).
-export([encode/1]).
-export_type([kuberl_v1beta1_cluster_role_binding/0]).
-type kuberl_v1beta1_cluster_role_binding() ::
#{ 'apiVersion' => binary(),
'kind' => binary(),
'metadata' => kuberl_v1_object_meta:kuberl_v1_object_meta(),
'roleRef' := kuberl_v1beta1_role_ref:kuberl_v1beta1_role_ref(),
'subjects' => list()
}.
encode(#{ 'apiVersion' := ApiVersion,
'kind' := Kind,
'metadata' := Metadata,
'roleRef' := RoleRef,
'subjects' := Subjects
}) ->
#{ 'apiVersion' => ApiVersion,
'kind' => Kind,
'metadata' => Metadata,
'roleRef' => RoleRef,
'subjects' => Subjects
}.
| |
e3d6a96e4c5b58759fde31e572ca661a5a219be394dbd688d153eff39b9a4c0d | blindglobe/common-lisp-stat | dists.lsp | ;;; -*- mode: lisp -*-
Copyright ( c ) 2005 - -2008 , by < >
;;; See COPYRIGHT file for any additional restrictions (BSD license).
Since 1991 , ANSI was finally finished . Edited for ANSI Common Lisp .
;;; dists -- Lisp-Stat interface to basic probability distribution routines
;;;
Copyright ( c ) 1991 , by . Permission is granted for
;;; unrestricted use.
(in-package :lisp-stat-probability)
;;; This stuff needs to be improved. We really could use something
;;; like the R libraries, but of course in a better packaged manner.
;;; Currently, there is a function for everything. Probably better to
;;; simplify by thinking about a more generic approach, distribution
;;; being specified by keyword.
(defun set-seed (x)
"stupid dummy function, need to implement rng seeding tool."
(values x))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; CFFI support for Probability Distributions
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; C-callable uniform generator
;;;
(defcfun ("register_uni" register-uni)
:void (f :pointer))
(defcallback ccl-uni :int () (ccl-store-double (random 1.0)) 0)
(register-uni (callback ccl-uni))
(defun one-uniform-rand () (random 1.0))
;;;
;;; Log-gamma function
;;;
(defcfun ("ccl_gamma" ccl-base-log-gamma)
:double (x :double))
(defun base-log-gamma (x)
(ccl-base-log-gamma (float x 1d0)))
;;;
;;; Normal distribution
;;;
(defcfun ("ccl_normalcdf" ccl-base-normal-cdf)
:double (x :double))
(defun base-normal-cdf (x)
(ccl-base-normal-cdf (float x 1d0)))
(defcfun ("ccl_normalquant" ccl-base-normal-quant)
:double (x :double))
(defun base-normal-quant (x)
(ccl-base-normal-quant (float x 1d0)))
(defcfun ("ccl_normaldens" ccl-base-normal-dens)
:double (x :double))
(defun base-normal-dens (x)
(ccl-base-normal-dens (float x 1d0)))
(defcfun ("ccl_normalrand" one-normal-rand)
:float)
(defcfun ("ccl_bnormcdf" ccl-base-bivnorm-cdf)
:double (x :double) (y :double) (z :double))
(defun base-bivnorm-cdf (x y z)
(ccl-base-bivnorm-cdf (float x 1d0) (float y 1d0) (float z 1d0)))
;;;
;;; Cauchy distribution
;;;
(defcfun ("ccl_cauchycdf" ccl-base-cauchy-cdf)
:double (x :double))
(defun base-cauchy-cdf (x)
(ccl-base-cauchy-cdf (float x 1d0)))
(defcfun ("ccl_cauchyquant" ccl-base-cauchy-quant)
:double (x :double))
(defun base-cauchy-quant (x)
(ccl-base-cauchy-quant (float x 1d0)))
(defcfun ("ccl_cauchydens" ccl-base-cauchy-dens)
:double (x :double))
(defun base-cauchy-dens (x)
(ccl-base-cauchy-dens (float x 1d0)))
(defcfun ("ccl_cauchyrand" one-cauchy-rand)
:double)
;;;;
Gamma distribution
;;;;
(defcfun ("ccl_gammacdf" ccl-base-gamma-cdf)
:double (x :double) (y :double))
(defun base-gamma-cdf (x y)
(ccl-base-gamma-cdf (float x 1d0) (float y 1d0)))
(defcfun ("ccl_gammaquant" ccl-base-gamma-quant)
:double (x :double) (y :double))
(defun base-gamma-quant (x y)
(ccl-base-gamma-quant (float x 1d0) (float y 1d0)))
(defcfun ("ccl_gammadens" ccl-base-gamma-dens)
:double (x :double) (y :double))
(defun base-gamma-dens (x y)
(ccl-base-gamma-dens (float x 1d0) (float y 1d0)))
(defcfun ("ccl_gammarand" ccl-gamma-rand)
:double (x :double))
(defun one-gamma-rand (x)
(ccl-gamma-rand (float x 1d0)))
;;;;
;;;; Chi-square distribution
;;;;
(defcfun ("ccl_chisqcdf" ccl-base-chisq-cdf)
:double (x :double) (y :double))
(defun base-chisq-cdf (x y)
(ccl-base-chisq-cdf (float x 1d0) (float y 1d0)))
(defcfun ("ccl_chisqquant" ccl-base-chisq-quant)
:double (x :double) (y :double))
(defun base-chisq-quant (x y)
(ccl-base-chisq-quant (float x 1d0) (float y 1d0)))
(defcfun ("ccl_chisqdens" ccl-base-chisq-dens)
:double (x :double) (y :double))
(defun base-chisq-dens (x y)
(ccl-base-chisq-dens (float x 1d0) (float y 1d0)))
(defcfun ("ccl_chisqrand" ccl-chisq-rand)
:double (x :double))
(defun one-chisq-rand (x)
(ccl-chisq-rand (float x 1d0)))
;;;;
;;;; Beta distribution
;;;;
(defcfun ("ccl_betacdf" ccl-base-beta-cdf)
:double (x :double) (y :double) (z :double))
(defun base-beta-cdf (x y z)
(ccl-base-beta-cdf (float x 1d0) (float y 1d0) (float z 1d0)))
(defcfun ("ccl_betaquant" ccl-base-beta-quant)
:double (x :double) (y :double) (z :double))
(defun base-beta-quant (x y z)
(ccl-base-beta-quant (float x 1d0) (float y 1d0) (float z 1d0)))
(defcfun ("ccl_betadens" ccl-base-beta-dens)
:double (x :double) (y :double) (z :double))
(defun base-beta-dens (x y z)
(ccl-base-beta-dens (float x 1d0) (float y 1d0) (float z 1d0)))
(defcfun ("ccl_betarand" ccl-beta-rand)
:double (x :double) (y :double))
(defun one-beta-rand (x y)
(ccl-beta-rand (float x 1d0) (float y 1d0)))
;;;;
;;;; t distribution
;;;;
(defcfun ("ccl_tcdf" ccl-base-t-cdf)
:double (x :double) (y :double))
(defun base-t-cdf (x y)
(ccl-base-t-cdf (float x 1d0) (float y 1d0)))
(defcfun ("ccl_tquant" ccl-base-t-quant)
:double (x :double) (y :double))
(defun base-t-quant (x y)
(ccl-base-t-quant (float x 1d0) (float y 1d0)))
(defcfun ("ccl_tdens" ccl-base-t-dens)
:double (x :double) (y :double))
(defun base-t-dens (x y)
(ccl-base-t-dens (float x 1d0) (float y 1d0)))
(defcfun ("ccl_trand" ccl-t-rand)
:double (x :double))
(defun one-t-rand (x)
(ccl-t-rand (float x 1d0)))
;;;;
;;;; F distribution
;;;;
(defcfun ("ccl_fcdf" ccl-base-f-cdf)
:double (x :double) (y :double) (z :double))
(defun base-f-cdf (x y z)
(ccl-base-f-cdf (float x 1d0) (float y 1d0) (float z 1d0)))
(defcfun ("ccl_fquant" ccl-base-f-quant)
:double (x :double) (y :double) (z :double))
(defun base-f-quant (x y z)
(ccl-base-f-quant (float x 1d0) (float y 1d0) (float z 1d0)))
(defcfun ("ccl_fdens" ccl-base-f-dens)
:double (x :double) (y :double) (z :double))
(defun base-f-dens (x y z)
(ccl-base-f-dens (float x 1d0) (float y 1d0) (float z 1d0)))
(defcfun ("ccl_frand" ccl-f-rand)
:double (x :double) (y :double))
(defun one-f-rand (x y) (ccl-f-rand (float x 1d0) (float y 1d0)))
;;;;
Poisson distribution
;;;;
(defcfun ("ccl_poissoncdf" ccl-base-poisson-cdf)
:double (x :double) (y :double))
(defun base-poisson-cdf (x y)
(ccl-base-poisson-cdf (float x 1d0) (float y 1d0)))
(defcfun ("ccl_poissonquant" ccl-base-poisson-quant)
:int (x :double) (y :double))
(defun base-poisson-quant (x y)
(ccl-base-poisson-quant (float x 1d0) (float y 1d0)))
(defcfun ("ccl_poissonpmf" ccl-base-poisson-pmf)
:double (x :int) (y :double))
(defun base-poisson-pmf (x y)
(ccl-base-poisson-pmf x (float y 1d0)))
(defcfun ("ccl_poissonrand" ccl-poisson-rand)
:int (x :double))
(defun one-poisson-rand (x)
(ccl-poisson-rand (float x 1d0)))
;;;;
Binomial distribution
;;;;
(defcfun ("ccl_binomialcdf" ccl-base-binomial-cdf)
:double (x :double) (y :int) (z :double))
(defun base-binomial-cdf (x y z)
(ccl-base-binomial-cdf (float x 1d0) y (float z 1d0)))
(defcfun ("ccl_binomialquant" ccl-base-binomial-quant)
:int (x :double) (y :int) (z :double))
(defun base-binomial-quant (x y z)
(ccl-base-binomial-quant (float x 1d0) y (float z 1d0)))
(defcfun ("ccl_binomialpmf" ccl-base-binomial-pmf)
:double (x :int) (y :int) (z :double))
(defun base-binomial-pmf (x y z)
(ccl-base-binomial-pmf x y (float z 1d0)))
(defcfun ("ccl_binomialrand" ccl-binomial-rand)
:int (x :int) (y :double))
(defun one-binomial-rand (x y)
(ccl-binomial-rand x (float y 1d0)))
;;; definitions though macros
(defmacro defbaserand (name onefun &rest args)
`(defun ,name (n ,@args)
(let ((result nil))
(dotimes (i n result)
(declare (fixnum i) (inline ,onefun))
(setf result (cons (,onefun ,@args) result))))))
(defbaserand base-uniform-rand one-uniform-rand)
(defbaserand base-normal-rand one-normal-rand)
(defbaserand base-cauchy-rand one-cauchy-rand)
(defbaserand base-gamma-rand one-gamma-rand a)
(defbaserand base-chisq-rand one-chisq-rand df)
(defbaserand base-beta-rand one-beta-rand a b)
(defbaserand base-t-rand one-t-rand df)
(defbaserand base-f-rand one-f-rand ndf ddf)
(defbaserand base-poisson-rand one-poisson-rand a)
(defbaserand base-binomial-rand one-binomial-rand a b)
(make-rv-function log-gamma base-log-gamma x)
(make-rv-function uniform-rand base-uniform-rand n)
(make-rv-function normal-cdf base-normal-cdf x)
(make-rv-function normal-quant base-normal-quant p)
(make-rv-function normal-dens base-normal-dens x)
(make-rv-function normal-rand base-normal-rand n)
(make-rv-function bivnorm-cdf base-bivnorm-cdf x y r)
(make-rv-function cauchy-cdf base-cauchy-cdf x)
(make-rv-function cauchy-quant base-cauchy-quant p)
(make-rv-function cauchy-dens base-cauchy-dens x)
(make-rv-function cauchy-rand base-cauchy-rand n)
(make-rv-function gamma-cdf base-gamma-cdf x a)
(make-rv-function gamma-quant base-gamma-quant p a)
(make-rv-function gamma-dens base-gamma-dens x a)
(make-rv-function gamma-rand base-gamma-rand n a)
(make-rv-function chisq-cdf base-chisq-cdf x df)
(make-rv-function chisq-quant base-chisq-quant p df)
(make-rv-function chisq-dens base-chisq-dens x df)
(make-rv-function chisq-rand base-chisq-rand n df)
(make-rv-function beta-cdf base-beta-cdf x a b)
(make-rv-function beta-quant base-beta-quant p a b)
(make-rv-function beta-dens base-beta-dens x a b)
(make-rv-function beta-rand base-beta-rand n a b)
(make-rv-function t-cdf base-t-cdf x df)
(make-rv-function t-quant base-t-quant p df)
(make-rv-function t-dens base-t-dens x df)
(make-rv-function t-rand base-t-rand n df)
(make-rv-function f-cdf base-f-cdf x ndf ddf)
(make-rv-function f-quant base-f-quant p ndf ddf)
(make-rv-function f-dens base-f-dens x ndf ddf)
(make-rv-function f-rand base-f-rand n ndf ddf)
(make-rv-function poisson-cdf base-poisson-cdf x a)
(make-rv-function poisson-quant base-poisson-quant p a)
(make-rv-function poisson-pmf base-poisson-pmf x a)
(make-rv-function poisson-rand base-poisson-rand n a)
(make-rv-function binomial-cdf base-binomial-cdf x a b)
(make-rv-function binomial-quant base-binomial-quant p a b)
(make-rv-function binomial-pmf base-binomial-pmf x a b)
(make-rv-function binomial-rand base-binomial-rand n a b)
;;;;
;;;; Documentation
;;;;
(setf (documentation 'bivnorm-cdf 'function)
"Args: (x y r)
Returns the value of the standard bivariate normal distribution function
with correlation R at (X, Y). Vectorized.")
(setf (documentation 'normal-cdf 'function)
"Args: (x)
Returns the value of the standard normal distribution function at X.
Vectorized.")
(setf (documentation 'beta-cdf 'function)
"Args: (x alpha beta)
Returns the value of the Beta(ALPHA, BETA) distribution function at X.
Vectorized.")
(setf (documentation 'gamma-cdf 'function)
"Args: (x alpha)
Returns the value of the Gamma(alpha, 1) distribution function at X.
Vectorized.")
(setf (documentation 'chisq-cdf 'function)
"Args: (x df)
Returns the value of the Chi-Square(DF) distribution function at X. Vectorized.")
(setf (documentation 't-cdf 'function)
"Args: (x df)
Returns the value of the T(DF) distribution function at X. Vectorized.")
(setf (documentation 'f-cdf 'function)
"Args: (x ndf ddf)
Returns the value of the F(NDF, DDF) distribution function at X. Vectorized.")
(setf (documentation 'cauchy-cdf 'function)
"Args: (x)
Returns the value of the standard Cauchy distribution function at X.
Vectorized.")
(setf (documentation 'log-gamma 'function)
"Args: (x)
Returns the log gamma function of X. Vectorized.")
(setf (documentation 'normal-quant 'function)
"Args (p)
Returns the P-th quantile of the standard normal distribution. Vectorized.")
(setf (documentation 'cauchy-quant 'function)
"Args (p)
Returns the P-th quantile(s) of the standard Cauchy distribution. Vectorized.")
(setf (documentation 'beta-quant 'function)
"Args: (p alpha beta)
Returns the P-th quantile of the Beta(ALPHA, BETA) distribution. Vectorized.")
(setf (documentation 'gamma-quant 'function)
"Args: (p alpha)
Returns the P-th quantile of the Gamma(ALPHA, 1) distribution. Vectorized.")
(setf (documentation 'chisq-quant 'function)
"Args: (p df)
Returns the P-th quantile of the Chi-Square(DF) distribution. Vectorized.")
(setf (documentation 't-quant 'function)
"Args: (p df)
Returns the P-th quantile of the T(DF) distribution. Vectorized.")
(setf (documentation 'f-quant 'function)
"Args: (p ndf ddf)
Returns the P-th quantile of the F(NDF, DDF) distribution. Vectorized.")
(setf (documentation 'normal-dens 'function)
"Args: (x)
Returns the density at X of the standard normal distribution. Vectorized.")
(setf (documentation 'cauchy-dens 'function)
"Args: (x)
Returns the density at X of the standard Cauchy distribution. Vectorized.")
(setf (documentation 'beta-dens 'function)
"Args: (x alpha beta)
Returns the density at X of the Beta(ALPHA, BETA) distribution. Vectorized.")
(setf (documentation 'gamma-dens 'function)
"Args: (x alpha)
Returns the density at X of the Gamma(ALPHA, 1) distribution. Vectorized.")
(setf (documentation 'chisq-dens 'function)
"Args: (x alpha)
Returns the density at X of the Chi-Square(DF) distribution. Vectorized.")
(setf (documentation 't-dens 'function)
"Args: (x alpha)
Returns the density at X of the T(DF) distribution. Vectorized.")
(setf (documentation 'f-dens 'function)
"Args: (x ndf ddf)
Returns the density at X of the F(NDF, DDF) distribution. Vectorized.")
(setf (documentation 'uniform-rand 'function)
"Args: (n)
Returns a list of N uniform random variables from the range (0, 1).
Vectorized.")
(setf (documentation 'normal-rand 'function)
"Args: (n)
Returns a list of N standard normal random numbers. Vectorized.")
(setf (documentation 'cauchy-rand 'function)
"Args: (n)
Returns a list of N standard Cauchy random numbers. Vectorized.")
(setf (documentation 't-rand 'function)
"Args: (n df)
Returns a list of N T(DF) random variables. Vectorized.")
(setf (documentation 'f-rand 'function)
"Args: (n ndf ddf)
Returns a list of N F(NDF, DDF) random variables. Vectorized.")
(setf (documentation 'gamma-rand 'function)
"Args: (n a)
Returns a list of N Gamma(A, 1) random variables. Vectorized.")
(setf (documentation 'chisq-rand 'function)
"Args: (n df)
Returns a list of N Chi-Square(DF) random variables. Vectorized.")
(setf (documentation 'beta-rand 'function)
"Args: (n a b)
Returns a list of N beta(A, B) random variables. Vectorized.")
(setf (documentation 'binomial-cdf 'function)
"Args (x n p)
Returns value of the Binomial(N, P) distribution function at X. Vectorized.")
(setf (documentation 'poisson-cdf 'function)
"Args (x mu)
Returns value of the Poisson(MU) distribution function at X. Vectorized.")
(setf (documentation 'binomial-pmf 'function)
"Args (k n p)
Returns value of the Binomial(N, P) pmf function at integer K. Vectorized.")
(setf (documentation 'poisson-pmf 'function)
"Args (k mu)
Returns value of the Poisson(MU) pmf function at integer K. Vectorized.")
(setf (documentation 'binomial-quant 'function)
"Args: (x n p)
Returns x-th quantile (left continuous inverse) of Binomial(N, P) cdf.
Vectorized.")
(setf (documentation 'poisson-quant 'function)
"Args: (x mu)
Returns x-th quantile (left continuous inverse) of Poisson(MU) cdf.
Vectorized.")
(setf (documentation 'binomial-rand 'function)
"Args: (k n p)
Returns list of K draws from the Binomial(N, P) distribution. Vectorized.")
(setf (documentation 'poisson-rand 'function)
"Args: (k mu)
Returns list of K draws from the Poisson(MU) distribution. Vectorized.")
| null | https://raw.githubusercontent.com/blindglobe/common-lisp-stat/0c657e10a4ee7e8d4ef3737f8c2d4e62abace2d8/src/numerics/dists.lsp | lisp | -*- mode: lisp -*-
See COPYRIGHT file for any additional restrictions (BSD license).
dists -- Lisp-Stat interface to basic probability distribution routines
unrestricted use.
This stuff needs to be improved. We really could use something
like the R libraries, but of course in a better packaged manner.
Currently, there is a function for everything. Probably better to
simplify by thinking about a more generic approach, distribution
being specified by keyword.
CFFI support for Probability Distributions
C-callable uniform generator
Log-gamma function
Normal distribution
Cauchy distribution
Chi-square distribution
Beta distribution
t distribution
F distribution
definitions though macros
Documentation
|
Copyright ( c ) 2005 - -2008 , by < >
Since 1991 , ANSI was finally finished . Edited for ANSI Common Lisp .
Copyright ( c ) 1991 , by . Permission is granted for
(in-package :lisp-stat-probability)
(defun set-seed (x)
"stupid dummy function, need to implement rng seeding tool."
(values x))
(defcfun ("register_uni" register-uni)
:void (f :pointer))
(defcallback ccl-uni :int () (ccl-store-double (random 1.0)) 0)
(register-uni (callback ccl-uni))
(defun one-uniform-rand () (random 1.0))
(defcfun ("ccl_gamma" ccl-base-log-gamma)
:double (x :double))
(defun base-log-gamma (x)
(ccl-base-log-gamma (float x 1d0)))
(defcfun ("ccl_normalcdf" ccl-base-normal-cdf)
:double (x :double))
(defun base-normal-cdf (x)
(ccl-base-normal-cdf (float x 1d0)))
(defcfun ("ccl_normalquant" ccl-base-normal-quant)
:double (x :double))
(defun base-normal-quant (x)
(ccl-base-normal-quant (float x 1d0)))
(defcfun ("ccl_normaldens" ccl-base-normal-dens)
:double (x :double))
(defun base-normal-dens (x)
(ccl-base-normal-dens (float x 1d0)))
(defcfun ("ccl_normalrand" one-normal-rand)
:float)
(defcfun ("ccl_bnormcdf" ccl-base-bivnorm-cdf)
:double (x :double) (y :double) (z :double))
(defun base-bivnorm-cdf (x y z)
(ccl-base-bivnorm-cdf (float x 1d0) (float y 1d0) (float z 1d0)))
(defcfun ("ccl_cauchycdf" ccl-base-cauchy-cdf)
:double (x :double))
(defun base-cauchy-cdf (x)
(ccl-base-cauchy-cdf (float x 1d0)))
(defcfun ("ccl_cauchyquant" ccl-base-cauchy-quant)
:double (x :double))
(defun base-cauchy-quant (x)
(ccl-base-cauchy-quant (float x 1d0)))
(defcfun ("ccl_cauchydens" ccl-base-cauchy-dens)
:double (x :double))
(defun base-cauchy-dens (x)
(ccl-base-cauchy-dens (float x 1d0)))
(defcfun ("ccl_cauchyrand" one-cauchy-rand)
:double)
Gamma distribution
(defcfun ("ccl_gammacdf" ccl-base-gamma-cdf)
:double (x :double) (y :double))
(defun base-gamma-cdf (x y)
(ccl-base-gamma-cdf (float x 1d0) (float y 1d0)))
(defcfun ("ccl_gammaquant" ccl-base-gamma-quant)
:double (x :double) (y :double))
(defun base-gamma-quant (x y)
(ccl-base-gamma-quant (float x 1d0) (float y 1d0)))
(defcfun ("ccl_gammadens" ccl-base-gamma-dens)
:double (x :double) (y :double))
(defun base-gamma-dens (x y)
(ccl-base-gamma-dens (float x 1d0) (float y 1d0)))
(defcfun ("ccl_gammarand" ccl-gamma-rand)
:double (x :double))
(defun one-gamma-rand (x)
(ccl-gamma-rand (float x 1d0)))
(defcfun ("ccl_chisqcdf" ccl-base-chisq-cdf)
:double (x :double) (y :double))
(defun base-chisq-cdf (x y)
(ccl-base-chisq-cdf (float x 1d0) (float y 1d0)))
(defcfun ("ccl_chisqquant" ccl-base-chisq-quant)
:double (x :double) (y :double))
(defun base-chisq-quant (x y)
(ccl-base-chisq-quant (float x 1d0) (float y 1d0)))
(defcfun ("ccl_chisqdens" ccl-base-chisq-dens)
:double (x :double) (y :double))
(defun base-chisq-dens (x y)
(ccl-base-chisq-dens (float x 1d0) (float y 1d0)))
(defcfun ("ccl_chisqrand" ccl-chisq-rand)
:double (x :double))
(defun one-chisq-rand (x)
(ccl-chisq-rand (float x 1d0)))
(defcfun ("ccl_betacdf" ccl-base-beta-cdf)
:double (x :double) (y :double) (z :double))
(defun base-beta-cdf (x y z)
(ccl-base-beta-cdf (float x 1d0) (float y 1d0) (float z 1d0)))
(defcfun ("ccl_betaquant" ccl-base-beta-quant)
:double (x :double) (y :double) (z :double))
(defun base-beta-quant (x y z)
(ccl-base-beta-quant (float x 1d0) (float y 1d0) (float z 1d0)))
(defcfun ("ccl_betadens" ccl-base-beta-dens)
:double (x :double) (y :double) (z :double))
(defun base-beta-dens (x y z)
(ccl-base-beta-dens (float x 1d0) (float y 1d0) (float z 1d0)))
(defcfun ("ccl_betarand" ccl-beta-rand)
:double (x :double) (y :double))
(defun one-beta-rand (x y)
(ccl-beta-rand (float x 1d0) (float y 1d0)))
(defcfun ("ccl_tcdf" ccl-base-t-cdf)
:double (x :double) (y :double))
(defun base-t-cdf (x y)
(ccl-base-t-cdf (float x 1d0) (float y 1d0)))
(defcfun ("ccl_tquant" ccl-base-t-quant)
:double (x :double) (y :double))
(defun base-t-quant (x y)
(ccl-base-t-quant (float x 1d0) (float y 1d0)))
(defcfun ("ccl_tdens" ccl-base-t-dens)
:double (x :double) (y :double))
(defun base-t-dens (x y)
(ccl-base-t-dens (float x 1d0) (float y 1d0)))
(defcfun ("ccl_trand" ccl-t-rand)
:double (x :double))
(defun one-t-rand (x)
(ccl-t-rand (float x 1d0)))
(defcfun ("ccl_fcdf" ccl-base-f-cdf)
:double (x :double) (y :double) (z :double))
(defun base-f-cdf (x y z)
(ccl-base-f-cdf (float x 1d0) (float y 1d0) (float z 1d0)))
(defcfun ("ccl_fquant" ccl-base-f-quant)
:double (x :double) (y :double) (z :double))
(defun base-f-quant (x y z)
(ccl-base-f-quant (float x 1d0) (float y 1d0) (float z 1d0)))
(defcfun ("ccl_fdens" ccl-base-f-dens)
:double (x :double) (y :double) (z :double))
(defun base-f-dens (x y z)
(ccl-base-f-dens (float x 1d0) (float y 1d0) (float z 1d0)))
(defcfun ("ccl_frand" ccl-f-rand)
:double (x :double) (y :double))
(defun one-f-rand (x y) (ccl-f-rand (float x 1d0) (float y 1d0)))
Poisson distribution
(defcfun ("ccl_poissoncdf" ccl-base-poisson-cdf)
:double (x :double) (y :double))
(defun base-poisson-cdf (x y)
(ccl-base-poisson-cdf (float x 1d0) (float y 1d0)))
(defcfun ("ccl_poissonquant" ccl-base-poisson-quant)
:int (x :double) (y :double))
(defun base-poisson-quant (x y)
(ccl-base-poisson-quant (float x 1d0) (float y 1d0)))
(defcfun ("ccl_poissonpmf" ccl-base-poisson-pmf)
:double (x :int) (y :double))
(defun base-poisson-pmf (x y)
(ccl-base-poisson-pmf x (float y 1d0)))
(defcfun ("ccl_poissonrand" ccl-poisson-rand)
:int (x :double))
(defun one-poisson-rand (x)
(ccl-poisson-rand (float x 1d0)))
Binomial distribution
(defcfun ("ccl_binomialcdf" ccl-base-binomial-cdf)
:double (x :double) (y :int) (z :double))
(defun base-binomial-cdf (x y z)
(ccl-base-binomial-cdf (float x 1d0) y (float z 1d0)))
(defcfun ("ccl_binomialquant" ccl-base-binomial-quant)
:int (x :double) (y :int) (z :double))
(defun base-binomial-quant (x y z)
(ccl-base-binomial-quant (float x 1d0) y (float z 1d0)))
(defcfun ("ccl_binomialpmf" ccl-base-binomial-pmf)
:double (x :int) (y :int) (z :double))
(defun base-binomial-pmf (x y z)
(ccl-base-binomial-pmf x y (float z 1d0)))
(defcfun ("ccl_binomialrand" ccl-binomial-rand)
:int (x :int) (y :double))
(defun one-binomial-rand (x y)
(ccl-binomial-rand x (float y 1d0)))
(defmacro defbaserand (name onefun &rest args)
`(defun ,name (n ,@args)
(let ((result nil))
(dotimes (i n result)
(declare (fixnum i) (inline ,onefun))
(setf result (cons (,onefun ,@args) result))))))
(defbaserand base-uniform-rand one-uniform-rand)
(defbaserand base-normal-rand one-normal-rand)
(defbaserand base-cauchy-rand one-cauchy-rand)
(defbaserand base-gamma-rand one-gamma-rand a)
(defbaserand base-chisq-rand one-chisq-rand df)
(defbaserand base-beta-rand one-beta-rand a b)
(defbaserand base-t-rand one-t-rand df)
(defbaserand base-f-rand one-f-rand ndf ddf)
(defbaserand base-poisson-rand one-poisson-rand a)
(defbaserand base-binomial-rand one-binomial-rand a b)
(make-rv-function log-gamma base-log-gamma x)
(make-rv-function uniform-rand base-uniform-rand n)
(make-rv-function normal-cdf base-normal-cdf x)
(make-rv-function normal-quant base-normal-quant p)
(make-rv-function normal-dens base-normal-dens x)
(make-rv-function normal-rand base-normal-rand n)
(make-rv-function bivnorm-cdf base-bivnorm-cdf x y r)
(make-rv-function cauchy-cdf base-cauchy-cdf x)
(make-rv-function cauchy-quant base-cauchy-quant p)
(make-rv-function cauchy-dens base-cauchy-dens x)
(make-rv-function cauchy-rand base-cauchy-rand n)
(make-rv-function gamma-cdf base-gamma-cdf x a)
(make-rv-function gamma-quant base-gamma-quant p a)
(make-rv-function gamma-dens base-gamma-dens x a)
(make-rv-function gamma-rand base-gamma-rand n a)
(make-rv-function chisq-cdf base-chisq-cdf x df)
(make-rv-function chisq-quant base-chisq-quant p df)
(make-rv-function chisq-dens base-chisq-dens x df)
(make-rv-function chisq-rand base-chisq-rand n df)
(make-rv-function beta-cdf base-beta-cdf x a b)
(make-rv-function beta-quant base-beta-quant p a b)
(make-rv-function beta-dens base-beta-dens x a b)
(make-rv-function beta-rand base-beta-rand n a b)
(make-rv-function t-cdf base-t-cdf x df)
(make-rv-function t-quant base-t-quant p df)
(make-rv-function t-dens base-t-dens x df)
(make-rv-function t-rand base-t-rand n df)
(make-rv-function f-cdf base-f-cdf x ndf ddf)
(make-rv-function f-quant base-f-quant p ndf ddf)
(make-rv-function f-dens base-f-dens x ndf ddf)
(make-rv-function f-rand base-f-rand n ndf ddf)
(make-rv-function poisson-cdf base-poisson-cdf x a)
(make-rv-function poisson-quant base-poisson-quant p a)
(make-rv-function poisson-pmf base-poisson-pmf x a)
(make-rv-function poisson-rand base-poisson-rand n a)
(make-rv-function binomial-cdf base-binomial-cdf x a b)
(make-rv-function binomial-quant base-binomial-quant p a b)
(make-rv-function binomial-pmf base-binomial-pmf x a b)
(make-rv-function binomial-rand base-binomial-rand n a b)
(setf (documentation 'bivnorm-cdf 'function)
"Args: (x y r)
Returns the value of the standard bivariate normal distribution function
with correlation R at (X, Y). Vectorized.")
(setf (documentation 'normal-cdf 'function)
"Args: (x)
Returns the value of the standard normal distribution function at X.
Vectorized.")
(setf (documentation 'beta-cdf 'function)
"Args: (x alpha beta)
Returns the value of the Beta(ALPHA, BETA) distribution function at X.
Vectorized.")
(setf (documentation 'gamma-cdf 'function)
"Args: (x alpha)
Returns the value of the Gamma(alpha, 1) distribution function at X.
Vectorized.")
(setf (documentation 'chisq-cdf 'function)
"Args: (x df)
Returns the value of the Chi-Square(DF) distribution function at X. Vectorized.")
(setf (documentation 't-cdf 'function)
"Args: (x df)
Returns the value of the T(DF) distribution function at X. Vectorized.")
(setf (documentation 'f-cdf 'function)
"Args: (x ndf ddf)
Returns the value of the F(NDF, DDF) distribution function at X. Vectorized.")
(setf (documentation 'cauchy-cdf 'function)
"Args: (x)
Returns the value of the standard Cauchy distribution function at X.
Vectorized.")
(setf (documentation 'log-gamma 'function)
"Args: (x)
Returns the log gamma function of X. Vectorized.")
(setf (documentation 'normal-quant 'function)
"Args (p)
Returns the P-th quantile of the standard normal distribution. Vectorized.")
(setf (documentation 'cauchy-quant 'function)
"Args (p)
Returns the P-th quantile(s) of the standard Cauchy distribution. Vectorized.")
(setf (documentation 'beta-quant 'function)
"Args: (p alpha beta)
Returns the P-th quantile of the Beta(ALPHA, BETA) distribution. Vectorized.")
(setf (documentation 'gamma-quant 'function)
"Args: (p alpha)
Returns the P-th quantile of the Gamma(ALPHA, 1) distribution. Vectorized.")
(setf (documentation 'chisq-quant 'function)
"Args: (p df)
Returns the P-th quantile of the Chi-Square(DF) distribution. Vectorized.")
(setf (documentation 't-quant 'function)
"Args: (p df)
Returns the P-th quantile of the T(DF) distribution. Vectorized.")
(setf (documentation 'f-quant 'function)
"Args: (p ndf ddf)
Returns the P-th quantile of the F(NDF, DDF) distribution. Vectorized.")
(setf (documentation 'normal-dens 'function)
"Args: (x)
Returns the density at X of the standard normal distribution. Vectorized.")
(setf (documentation 'cauchy-dens 'function)
"Args: (x)
Returns the density at X of the standard Cauchy distribution. Vectorized.")
(setf (documentation 'beta-dens 'function)
"Args: (x alpha beta)
Returns the density at X of the Beta(ALPHA, BETA) distribution. Vectorized.")
(setf (documentation 'gamma-dens 'function)
"Args: (x alpha)
Returns the density at X of the Gamma(ALPHA, 1) distribution. Vectorized.")
(setf (documentation 'chisq-dens 'function)
"Args: (x alpha)
Returns the density at X of the Chi-Square(DF) distribution. Vectorized.")
(setf (documentation 't-dens 'function)
"Args: (x alpha)
Returns the density at X of the T(DF) distribution. Vectorized.")
(setf (documentation 'f-dens 'function)
"Args: (x ndf ddf)
Returns the density at X of the F(NDF, DDF) distribution. Vectorized.")
(setf (documentation 'uniform-rand 'function)
"Args: (n)
Returns a list of N uniform random variables from the range (0, 1).
Vectorized.")
(setf (documentation 'normal-rand 'function)
"Args: (n)
Returns a list of N standard normal random numbers. Vectorized.")
(setf (documentation 'cauchy-rand 'function)
"Args: (n)
Returns a list of N standard Cauchy random numbers. Vectorized.")
(setf (documentation 't-rand 'function)
"Args: (n df)
Returns a list of N T(DF) random variables. Vectorized.")
(setf (documentation 'f-rand 'function)
"Args: (n ndf ddf)
Returns a list of N F(NDF, DDF) random variables. Vectorized.")
(setf (documentation 'gamma-rand 'function)
"Args: (n a)
Returns a list of N Gamma(A, 1) random variables. Vectorized.")
(setf (documentation 'chisq-rand 'function)
"Args: (n df)
Returns a list of N Chi-Square(DF) random variables. Vectorized.")
(setf (documentation 'beta-rand 'function)
"Args: (n a b)
Returns a list of N beta(A, B) random variables. Vectorized.")
(setf (documentation 'binomial-cdf 'function)
"Args (x n p)
Returns value of the Binomial(N, P) distribution function at X. Vectorized.")
(setf (documentation 'poisson-cdf 'function)
"Args (x mu)
Returns value of the Poisson(MU) distribution function at X. Vectorized.")
(setf (documentation 'binomial-pmf 'function)
"Args (k n p)
Returns value of the Binomial(N, P) pmf function at integer K. Vectorized.")
(setf (documentation 'poisson-pmf 'function)
"Args (k mu)
Returns value of the Poisson(MU) pmf function at integer K. Vectorized.")
(setf (documentation 'binomial-quant 'function)
"Args: (x n p)
Returns x-th quantile (left continuous inverse) of Binomial(N, P) cdf.
Vectorized.")
(setf (documentation 'poisson-quant 'function)
"Args: (x mu)
Returns x-th quantile (left continuous inverse) of Poisson(MU) cdf.
Vectorized.")
(setf (documentation 'binomial-rand 'function)
"Args: (k n p)
Returns list of K draws from the Binomial(N, P) distribution. Vectorized.")
(setf (documentation 'poisson-rand 'function)
"Args: (k mu)
Returns list of K draws from the Poisson(MU) distribution. Vectorized.")
|
f3d7048bc8ff755f952b7a4581343026c44921957cd1501cc96d41d52a060ff5 | FundingCircle/fc4-framework | renderer.clj | (ns fc4.integrations.structurizr.express.renderer
(:require [clj-chrome-devtools.automation :as a :refer [automation?]]
[clj-chrome-devtools.impl.connection :refer [connect connection? make-ws-client]]
[clojure.java.io :refer [file]]
[clojure.spec.alpha :as s]
[clojure.string :as str :refer [blank? ends-with? includes? join starts-with?]]
[cognitect.anomalies :as anom]
[fc4.image-utils :refer [png-data-uri->bytes]]
[fc4.integrations.structurizr.express.renderer.png :as png]
[fc4.integrations.structurizr.express.renderer.svg :as svg]
[fc4.integrations.structurizr.express.spec] ;; for side effects
[fc4.io.util :refer [debug? debug]]
[fc4.rendering :as r :refer [Renderer]]
[fc4.util :refer [fault with-timeout]]
[fc4.yaml :as yaml]
This project does n’t use Timbre , but clj - chrome - devtools does and we need to config it
[taoensso.timbre :as devtools-logger]))
;; Some of the functions include some type hints or type casts. These are to prevent reflection, but
;; not for the usual reason of improving performance. In this case, some of the reflection leads to
classes that violate some kind of boundary introduced in Java 9/10/11 and yield an ominous
;; message printed to stdout (or maybe stderr).
Configure Jetty logging so that log messages are not output to stderr , distracting the CLI UX .
( clj - chrome - devtools uses Jetty ’s WebSocket client , via gniazdo , to communicate with Chromium . )
;; I found this approach here: #issuecomment-375295195
(System/setProperty "org.eclipse.jetty.util.log.announce" "false")
(System/setProperty "org.eclipse.jetty.util.log.class" "org.eclipse.jetty.util.log.StdErrLog")
; Valid levels: ALL, DEBUG, INFO, WARN, OFF
; You’d think we’d want to use INFO or WARN by default, but sadly even those levels *always* output
; some stuff — stuff that I don’t want end-users to have to see. So here we are.
(System/setProperty "org.eclipse.jetty.LEVEL" (if @debug? "ALL" "OFF"))
; clj-chrome-devtools logs :info records as a matter of course when WebSocket connections connect,
; close, etc. We don’t want our users to see them.
(devtools-logger/set-level! (if @debug? :debug :warn))
;; The private functions that accept a clj-chrome-devtools automation context
;; are stateful in that they expect the page to be in a certain state before they are called.
;;
;; Therefore these functions must be called in a specific order:
;;
1 . load - structurizr - express
2 . set - yaml - and - update - diagram
3 . extract - diagram and/or extract - key
(def ^:private doc-separator "---\n")
(s/def ::headless boolean?)
(s/def ::structurizr-express-url string?)
(s/def ::debug-port nat-int?)
(s/def ::debug-conn-timeout-ms nat-int?)
(s/def ::opts (s/keys :opt-un [::headless ::structurizr-express-url]))
(s/def ::browser #(instance? Process %))
(s/def ::conn connection?)
(s/def ::automation automation?)
(s/def ::prepped-yaml
(s/and string?
(complement blank?)
#(starts-with? % doc-separator)
#(not (re-seq #"[^\\]`" %))))
(defn- chromium-path
[]
(let [user-home (System/getProperty "user.home")
mac-chromium-path "Applications/Chromium.app/Contents/MacOS/Chromium"
mac-chrome-path "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"]
(->> (filter #(.canExecute (file %))
On MacOS , prefer a browser installed in a user ’s home directory to one
;; installed system-wide.
(file user-home mac-chromium-path)
(file user-home mac-chrome-path)
(file "/" mac-chromium-path)
(file "/" mac-chrome-path)
Debian
"/usr/sbin/chromium" ; Arch
Alpine
Debian
(first)
(str))))
(defn- chromium-opts
[opts]
(let [{:keys [headless debug-port]} opts]
[(chromium-path) ;; TODO: handle this being nil — here, or somewhere else, maybe start-browser
(str "--remote-debugging-port=" debug-port)
(if headless "--headless" "")
; So as to ensure that tabs from the prior session aren’t restored.
"--incognito"
; Needed when running as root, which happens sometimes. And when not running as root, this is
; also OK for our purposes.
"--no-sandbox"
;; We used to include --disable-dev-shm-usage as recommended here:
;; #tips but when
we switched our CI jobs from a custom Debian Docker image to an image maintained by CircleCI
( with Chrome rather than Chromium , and a newer version of Chrome , and maybe even a different
version of Debian , I do n’t know ) the browser started crashing on launch . I then determined
;; that the crash did not occur when I removed --disable-dev-shm-usage. When I do so the tests
all still seem to pass , including the test of the distribution package , so it * seems * as
;; though we can do without this flag. (Interestingly, the crash did _not_ occur when running
;; the tests via the source code, rather only when testing the distribution packages. I don’t
;; have a clue as to why.)
]))
(defn- start-browser
[opts]
(let [co (chromium-opts opts)]
(debug "Starting browser with options:" co)
(.exec (Runtime/getRuntime) ^"[Ljava.lang.String;" (into-array co))))
(defn- prep-yaml
"Structurizr Express will only recognize the YAML as YAML and parse it if
it begins with the YAML document separator. If this isn’t present, it will
assume that the diagram definition string is JSON and will fail."
[yaml]
(as-> (yaml/split-file yaml) it
(::yaml/main it)
un - escaped backticks interfere when passing YAML in to JS runtime
(str doc-separator it)))
(s/fdef prep-yaml
:args (s/cat :yaml string?)
:ret ::prepped-yaml)
(defn- load-structurizr-express
[automation url]
(debug "Loading Structurizr Express from" url)
(let [page (a/to automation url)]
(if (includes? (:document-url page) "chrome-error")
(fault "Could not load Structurizr Express (unknown error; possible connectivity problem)")
(when-not (a/visible automation (a/sel1 automation "svg"))
(fault "Could not load Structurizr Express (svg node not found)")))))
(s/fdef load-structurizr-express
:args (s/cat :automation ::automation
:url string?)
:ret (s/or :success nil?
:failure ::anom/anomaly))
(defn- set-yaml-and-update-diagram
[automation yaml]
(debug "Setting YAML and updating diagram...")
I ’m not 100 % sure but I suspect it ’s important to call hasErrorMessages ( ) after
renderExpressDefinition so that the JS runtime finishes the execution of
;; renderExpressDefinition before this (clj) function returns. Before I added the hasErrorMessages
;; call, I was getting errors when subsequently calling exportCurrentDiagramToPNG, and I think
;; they were due to the YAML not actually being fully “set” yet. Honestly I’m not entirely sure.
(a/evaluate automation (str "const diagramYaml = `" yaml "`;\n"
"structurizr.scripting.renderExpressDefinition(diagramYaml);"))
(when-let [errs (seq (a/evaluate automation "structurizrExpress.getErrorMessages();"))]
(fault (str "Error occurred while rendering; errors were found in the diagram definition: "
(join "; " (map :message errs))))))
(s/fdef set-yaml-and-update-diagram
:args (s/cat :automation ::automation
:diagram-yaml ::prepped-yaml)
:ret (s/or :success nil?
:failure ::anom/anomaly))
(defn- extract-diagram-png
"Returns a PNG image of the current diagram. set-yaml-and-update-diagram must have already been
called."
[automation]
(debug "Extracting diagram as PNG...")
(let [main (png-data-uri->bytes
(a/evaluate automation "structurizr.scripting.exportCurrentDiagramToPNG();"))
key (png-data-uri->bytes
(a/evaluate automation "structurizr.scripting.exportCurrentDiagramKeyToPNG();"))]
#:fc4.rendering.png{:main main
:key key
:conjoined (png/conjoin main key)}))
(defn- extract-diagram-svg
"Returns an SVG image of the current diagram. set-yaml-and-update-diagram must have already been
called."
[automation]
(debug "Extracting diagram as SVG...")
(let [main (svg/cleanup (a/evaluate automation "structurizr.scripting.exportCurrentDiagramToSVG();"))
key (svg/cleanup (a/evaluate automation "structurizr.scripting.exportCurrentDiagramKeyToSVG();"))]
#:fc4.rendering.svg{:main main
:key key
:conjoined (svg/conjoin main key)}))
(defn- do-render
"Renders a Structurizr Express diagram as PNG and/or SVG images. Not entirely pure; communicates
with a child process to perform the rendering."
[diagram-yaml automation {:keys [structurizr-express-url timeout-ms output-formats] :as opts}]
{:pre [(not (ends-with? diagram-yaml ".yaml"))
(not (ends-with? diagram-yaml ".yml"))
(seq output-formats)]}
(debug "Rendering with options:" opts)
(try
(with-timeout timeout-ms
(or (load-structurizr-express automation structurizr-express-url)
(set-yaml-and-update-diagram automation (prep-yaml diagram-yaml))
{::r/images (merge {}
(when (contains? output-formats :png)
{::r/png (extract-diagram-png automation)})
(when (contains? output-formats :svg)
{::r/svg (extract-diagram-svg automation)}))}))
(catch Exception e
(fault (str e)))))
; This spec is here mainly for documentation and instrumentation. I don’t
; recommend using it for generative/property testing, mainly because rendering
; is currently quite slow (~1–3s on my system) and it performs network I/O.
(s/fdef do-render
:args (s/cat :diagram :structurizr/diagram-yaml-str
:automation ::automation
:opts ::opts)
:ret (s/or :success ::r/success-result
:failure ::r/failure-result))
(defn- do-close
[browser conn]
TODO : log something , in both catch forms , once we choose a logging library / approach
(try (.close conn) (catch Exception _))
(try (.destroy browser) (catch Exception _)))
(defrecord StructurizrExpressRenderer [browser conn automation opts]
Renderer
(render [renderer diagram-yaml] (do-render diagram-yaml automation opts))
(render [renderer diagram-yaml options] (do-render diagram-yaml automation (merge opts options)))
java.io.Closeable
(close [renderer] (do-close browser conn)))
(def default-opts
{; This is used for testing; in normal usage by end-users, this is overridden by a value supplied
; via tools.cli as specified in fc4.io.cli.main (that value may itself be a default)
:structurizr-express-url ":8080/express"
:timeout-ms 30000
:headless true
:debug-port 9222
:debug-conn-timeout-ms 30000
:output-formats #{:png}})
(def ws-client-opts
"Options for make-ws-client."
The default of 1 MB is too low .
:max-msg-size-mb (* 1024 1024 10)})
(defn make-renderer
"Creates a StructurizrExpressRenderer. It’s VERY important to call .close on the StructurizrExpressRenderer at some
point — best way to ensure that is to call this function using with-open."
([]
(make-renderer {}))
([opts]
(let [{:keys [debug-port
debug-conn-timeout-ms]
:as full-opts} (merge default-opts opts)
_ (debug "Creating renderer with options:" full-opts)
browser (start-browser full-opts)
conn (try (connect "localhost" debug-port debug-conn-timeout-ms (make-ws-client ws-client-opts))
(catch Exception e
(.destroy browser)
(throw e)))
automation (a/create-automation conn)]
(->StructurizrExpressRenderer browser conn automation full-opts))))
; This spec is here mainly for documentation and instrumentation. I don’t
; recommend using it for generative/property testing, mainly because rendering
; is currently quite slow (~1–3s on my system) and it performs network I/O.
(s/fdef make-renderer
:args (s/? ::opts)
:ret (s/and #(instance? StructurizrExpressRenderer %)
(s/keys :req-un [::browser ::conn ::automation])))
| null | https://raw.githubusercontent.com/FundingCircle/fc4-framework/674af39e7edb2cbfd3e1941e6abe80fd87d93bed/src/fc4/integrations/structurizr/express/renderer.clj | clojure | for side effects
Some of the functions include some type hints or type casts. These are to prevent reflection, but
not for the usual reason of improving performance. In this case, some of the reflection leads to
message printed to stdout (or maybe stderr).
I found this approach here: #issuecomment-375295195
Valid levels: ALL, DEBUG, INFO, WARN, OFF
You’d think we’d want to use INFO or WARN by default, but sadly even those levels *always* output
some stuff — stuff that I don’t want end-users to have to see. So here we are.
clj-chrome-devtools logs :info records as a matter of course when WebSocket connections connect,
close, etc. We don’t want our users to see them.
The private functions that accept a clj-chrome-devtools automation context
are stateful in that they expect the page to be in a certain state before they are called.
Therefore these functions must be called in a specific order:
installed system-wide.
Arch
TODO: handle this being nil — here, or somewhere else, maybe start-browser
So as to ensure that tabs from the prior session aren’t restored.
Needed when running as root, which happens sometimes. And when not running as root, this is
also OK for our purposes.
We used to include --disable-dev-shm-usage as recommended here:
#tips but when
that the crash did not occur when I removed --disable-dev-shm-usage. When I do so the tests
though we can do without this flag. (Interestingly, the crash did _not_ occur when running
the tests via the source code, rather only when testing the distribution packages. I don’t
have a clue as to why.)
renderExpressDefinition before this (clj) function returns. Before I added the hasErrorMessages
call, I was getting errors when subsequently calling exportCurrentDiagramToPNG, and I think
they were due to the YAML not actually being fully “set” yet. Honestly I’m not entirely sure.
communicates
This spec is here mainly for documentation and instrumentation. I don’t
recommend using it for generative/property testing, mainly because rendering
is currently quite slow (~1–3s on my system) and it performs network I/O.
This is used for testing; in normal usage by end-users, this is overridden by a value supplied
via tools.cli as specified in fc4.io.cli.main (that value may itself be a default)
This spec is here mainly for documentation and instrumentation. I don’t
recommend using it for generative/property testing, mainly because rendering
is currently quite slow (~1–3s on my system) and it performs network I/O. | (ns fc4.integrations.structurizr.express.renderer
(:require [clj-chrome-devtools.automation :as a :refer [automation?]]
[clj-chrome-devtools.impl.connection :refer [connect connection? make-ws-client]]
[clojure.java.io :refer [file]]
[clojure.spec.alpha :as s]
[clojure.string :as str :refer [blank? ends-with? includes? join starts-with?]]
[cognitect.anomalies :as anom]
[fc4.image-utils :refer [png-data-uri->bytes]]
[fc4.integrations.structurizr.express.renderer.png :as png]
[fc4.integrations.structurizr.express.renderer.svg :as svg]
[fc4.io.util :refer [debug? debug]]
[fc4.rendering :as r :refer [Renderer]]
[fc4.util :refer [fault with-timeout]]
[fc4.yaml :as yaml]
This project does n’t use Timbre , but clj - chrome - devtools does and we need to config it
[taoensso.timbre :as devtools-logger]))
classes that violate some kind of boundary introduced in Java 9/10/11 and yield an ominous
Configure Jetty logging so that log messages are not output to stderr , distracting the CLI UX .
( clj - chrome - devtools uses Jetty ’s WebSocket client , via gniazdo , to communicate with Chromium . )
(System/setProperty "org.eclipse.jetty.util.log.announce" "false")
(System/setProperty "org.eclipse.jetty.util.log.class" "org.eclipse.jetty.util.log.StdErrLog")
(System/setProperty "org.eclipse.jetty.LEVEL" (if @debug? "ALL" "OFF"))
(devtools-logger/set-level! (if @debug? :debug :warn))
1 . load - structurizr - express
2 . set - yaml - and - update - diagram
3 . extract - diagram and/or extract - key
(def ^:private doc-separator "---\n")
(s/def ::headless boolean?)
(s/def ::structurizr-express-url string?)
(s/def ::debug-port nat-int?)
(s/def ::debug-conn-timeout-ms nat-int?)
(s/def ::opts (s/keys :opt-un [::headless ::structurizr-express-url]))
(s/def ::browser #(instance? Process %))
(s/def ::conn connection?)
(s/def ::automation automation?)
(s/def ::prepped-yaml
(s/and string?
(complement blank?)
#(starts-with? % doc-separator)
#(not (re-seq #"[^\\]`" %))))
(defn- chromium-path
[]
(let [user-home (System/getProperty "user.home")
mac-chromium-path "Applications/Chromium.app/Contents/MacOS/Chromium"
mac-chrome-path "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"]
(->> (filter #(.canExecute (file %))
On MacOS , prefer a browser installed in a user ’s home directory to one
(file user-home mac-chromium-path)
(file user-home mac-chrome-path)
(file "/" mac-chromium-path)
(file "/" mac-chrome-path)
Debian
Alpine
Debian
(first)
(str))))
(defn- chromium-opts
[opts]
(let [{:keys [headless debug-port]} opts]
(str "--remote-debugging-port=" debug-port)
(if headless "--headless" "")
"--incognito"
"--no-sandbox"
we switched our CI jobs from a custom Debian Docker image to an image maintained by CircleCI
( with Chrome rather than Chromium , and a newer version of Chrome , and maybe even a different
version of Debian , I do n’t know ) the browser started crashing on launch . I then determined
all still seem to pass , including the test of the distribution package , so it * seems * as
]))
(defn- start-browser
[opts]
(let [co (chromium-opts opts)]
(debug "Starting browser with options:" co)
(.exec (Runtime/getRuntime) ^"[Ljava.lang.String;" (into-array co))))
(defn- prep-yaml
"Structurizr Express will only recognize the YAML as YAML and parse it if
it begins with the YAML document separator. If this isn’t present, it will
assume that the diagram definition string is JSON and will fail."
[yaml]
(as-> (yaml/split-file yaml) it
(::yaml/main it)
un - escaped backticks interfere when passing YAML in to JS runtime
(str doc-separator it)))
(s/fdef prep-yaml
:args (s/cat :yaml string?)
:ret ::prepped-yaml)
(defn- load-structurizr-express
[automation url]
(debug "Loading Structurizr Express from" url)
(let [page (a/to automation url)]
(if (includes? (:document-url page) "chrome-error")
(fault "Could not load Structurizr Express (unknown error; possible connectivity problem)")
(when-not (a/visible automation (a/sel1 automation "svg"))
(fault "Could not load Structurizr Express (svg node not found)")))))
(s/fdef load-structurizr-express
:args (s/cat :automation ::automation
:url string?)
:ret (s/or :success nil?
:failure ::anom/anomaly))
(defn- set-yaml-and-update-diagram
[automation yaml]
(debug "Setting YAML and updating diagram...")
I ’m not 100 % sure but I suspect it ’s important to call hasErrorMessages ( ) after
renderExpressDefinition so that the JS runtime finishes the execution of
(a/evaluate automation (str "const diagramYaml = `" yaml "`;\n"
"structurizr.scripting.renderExpressDefinition(diagramYaml);"))
(when-let [errs (seq (a/evaluate automation "structurizrExpress.getErrorMessages();"))]
(fault (str "Error occurred while rendering; errors were found in the diagram definition: "
(join "; " (map :message errs))))))
(s/fdef set-yaml-and-update-diagram
:args (s/cat :automation ::automation
:diagram-yaml ::prepped-yaml)
:ret (s/or :success nil?
:failure ::anom/anomaly))
(defn- extract-diagram-png
"Returns a PNG image of the current diagram. set-yaml-and-update-diagram must have already been
called."
[automation]
(debug "Extracting diagram as PNG...")
(let [main (png-data-uri->bytes
(a/evaluate automation "structurizr.scripting.exportCurrentDiagramToPNG();"))
key (png-data-uri->bytes
(a/evaluate automation "structurizr.scripting.exportCurrentDiagramKeyToPNG();"))]
#:fc4.rendering.png{:main main
:key key
:conjoined (png/conjoin main key)}))
(defn- extract-diagram-svg
"Returns an SVG image of the current diagram. set-yaml-and-update-diagram must have already been
called."
[automation]
(debug "Extracting diagram as SVG...")
(let [main (svg/cleanup (a/evaluate automation "structurizr.scripting.exportCurrentDiagramToSVG();"))
key (svg/cleanup (a/evaluate automation "structurizr.scripting.exportCurrentDiagramKeyToSVG();"))]
#:fc4.rendering.svg{:main main
:key key
:conjoined (svg/conjoin main key)}))
(defn- do-render
with a child process to perform the rendering."
[diagram-yaml automation {:keys [structurizr-express-url timeout-ms output-formats] :as opts}]
{:pre [(not (ends-with? diagram-yaml ".yaml"))
(not (ends-with? diagram-yaml ".yml"))
(seq output-formats)]}
(debug "Rendering with options:" opts)
(try
(with-timeout timeout-ms
(or (load-structurizr-express automation structurizr-express-url)
(set-yaml-and-update-diagram automation (prep-yaml diagram-yaml))
{::r/images (merge {}
(when (contains? output-formats :png)
{::r/png (extract-diagram-png automation)})
(when (contains? output-formats :svg)
{::r/svg (extract-diagram-svg automation)}))}))
(catch Exception e
(fault (str e)))))
(s/fdef do-render
:args (s/cat :diagram :structurizr/diagram-yaml-str
:automation ::automation
:opts ::opts)
:ret (s/or :success ::r/success-result
:failure ::r/failure-result))
(defn- do-close
[browser conn]
TODO : log something , in both catch forms , once we choose a logging library / approach
(try (.close conn) (catch Exception _))
(try (.destroy browser) (catch Exception _)))
(defrecord StructurizrExpressRenderer [browser conn automation opts]
Renderer
(render [renderer diagram-yaml] (do-render diagram-yaml automation opts))
(render [renderer diagram-yaml options] (do-render diagram-yaml automation (merge opts options)))
java.io.Closeable
(close [renderer] (do-close browser conn)))
(def default-opts
:structurizr-express-url ":8080/express"
:timeout-ms 30000
:headless true
:debug-port 9222
:debug-conn-timeout-ms 30000
:output-formats #{:png}})
(def ws-client-opts
"Options for make-ws-client."
The default of 1 MB is too low .
:max-msg-size-mb (* 1024 1024 10)})
(defn make-renderer
"Creates a StructurizrExpressRenderer. It’s VERY important to call .close on the StructurizrExpressRenderer at some
point — best way to ensure that is to call this function using with-open."
([]
(make-renderer {}))
([opts]
(let [{:keys [debug-port
debug-conn-timeout-ms]
:as full-opts} (merge default-opts opts)
_ (debug "Creating renderer with options:" full-opts)
browser (start-browser full-opts)
conn (try (connect "localhost" debug-port debug-conn-timeout-ms (make-ws-client ws-client-opts))
(catch Exception e
(.destroy browser)
(throw e)))
automation (a/create-automation conn)]
(->StructurizrExpressRenderer browser conn automation full-opts))))
(s/fdef make-renderer
:args (s/? ::opts)
:ret (s/and #(instance? StructurizrExpressRenderer %)
(s/keys :req-un [::browser ::conn ::automation])))
|
1cfc0648d98526f52af5f47d323472c3edc6830b7bbb02a415ac61085076eb6b | ekmett/ersatz | Problem.hs | # LANGUAGE CPP #
{-# LANGUAGE Rank2Types #-}
# LANGUAGE TypeFamilies #
# LANGUAGE PatternGuards #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE Trustworthy #
{-# LANGUAGE ConstraintKinds #-}
# OPTIONS_HADDOCK not - home #
--------------------------------------------------------------------
-- |
Copyright : © 2010 - 2014 , 2013
-- License : BSD3
Maintainer : < >
-- Stability : experimental
-- Portability: non-portable
--
--------------------------------------------------------------------
module Ersatz.Problem
(
-- * SAT
SAT(SAT)
, HasSAT(..)
, MonadSAT
, runSAT, runSAT', dimacsSAT
, literalExists
, assertFormula
, generateLiteral
-- * QSAT
, QSAT(QSAT)
, HasQSAT(..)
, MonadQSAT
, runQSAT, runQSAT', qdimacsQSAT
, literalForall
-- * DIMACS pretty printing
, DIMACS(..)
, QDIMACS(..)
, WDIMACS(..)
, dimacs, qdimacs, wdimacs
) where
import Data.ByteString.Builder
import Control.Lens
import Control.Monad.State
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as Lazy
import Data.Default
import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as HashMap
import Data.Int
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import qualified Data.List as List
import Ersatz.Internal.Formula
import Ersatz.Internal.Literal
import Ersatz.Internal.StableName
import System.IO.Unsafe
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
#if !(MIN_VERSION_base(4,11,0))
import Data.Semigroup (Semigroup(..))
#endif
-- | Constraint synonym for types that carry a SAT state.
type MonadSAT s m = (HasSAT s, MonadState s m)
-- | Constraint synonym for types that carry a QSAT state.
type MonadQSAT s m = (HasQSAT s, MonadState s m)
------------------------------------------------------------------------------
-- SAT Problems
------------------------------------------------------------------------------
data SAT = SAT
{ _lastAtom :: {-# UNPACK #-} !Int -- ^ The id of the last atom allocated
, _formula :: !Formula -- ^ a set of clauses to assert
, _stableMap :: !(HashMap (StableName ()) Literal) -- ^ a mapping used during 'Bit' expansion
}
class HasSAT s where
sat :: Lens' s SAT
lastAtom :: Lens' s Int
lastAtom f = sat $ \ (SAT a b c) -> fmap (\a' -> SAT a' b c) (f a)
formula :: Lens' s Formula
formula f = sat $ \ (SAT a b c) -> fmap (\b' -> SAT a b' c) (f b)
stableMap :: Lens' s (HashMap (StableName ()) Literal)
stableMap f = sat $ \ (SAT a b c) -> SAT a b <$> f c
instance HasSAT SAT where
sat = id
instance Show SAT where
showsPrec p bf = showParen (p > 10)
$ showString "SAT " . showsPrec 11 (bf^.lastAtom)
. showChar ' ' . showsPrec 11 (bf^.formula)
. showString " mempty"
instance Default SAT where
The literal 1 is dedicated for the True constant .
def = SAT 1 (formulaLiteral literalTrue) HashMap.empty
-- | Run a 'SAT'-generating state computation. Useful e.g. in ghci for
disambiguating the type of a ' MonadSAT ' value .
runSAT :: StateT SAT m a -> m (a, SAT)
runSAT s = runStateT s def
-- | Run a 'SAT'-generating state computation in the 'Identity' monad. Useful
e.g. in ghci for disambiguating the type of a ' MonadSAT ' value .
runSAT' :: StateT SAT Identity a -> (a, SAT)
runSAT' = runIdentity . runSAT
-- | Run a 'SAT'-generating state computation and return the respective
-- 'DIMACS' output. Useful for testing and debugging.
dimacsSAT :: StateT SAT Identity a -> Lazy.ByteString
dimacsSAT = toLazyByteString . dimacs . snd . runSAT'
literalExists :: MonadSAT s m => m Literal
literalExists = fmap Literal $ lastAtom <+= 1
# INLINE literalExists #
assertFormula :: MonadSAT s m => Formula -> m ()
assertFormula xs = formula <>= xs
# INLINE assertFormula #
generateLiteral :: MonadSAT s m => a -> (Literal -> m ()) -> m Literal
generateLiteral a f = do
let sn = unsafePerformIO (makeStableName' a)
use (stableMap.at sn) >>= \ ml -> case ml of
Just l -> return l
Nothing -> do
l <- literalExists
stableMap.at sn ?= l
f l
return l
{-# INLINE generateLiteral #-}
------------------------------------------------------------------------------
-- QSAT Problems
------------------------------------------------------------------------------
-- | A (quantified) boolean formula.
data QSAT = QSAT
{ _universals :: !IntSet -- ^ a set indicating which literals are universally quantified
, _qsatSat :: SAT -- ^ The rest of the information, in 'SAT'
} deriving Show
class HasSAT t => HasQSAT t where
qsat :: Lens' t QSAT
universals :: Lens' t IntSet
universals f = qsat ago where
ago (QSAT u s) = f u <&> \u' -> QSAT u' s
instance HasSAT QSAT where
sat f (QSAT u s) = QSAT u <$> f s
instance HasQSAT QSAT where
qsat = id
instance Default QSAT where
def = QSAT IntSet.empty def
-- | Run a 'QSAT'-generating state computation. Useful e.g. in ghci for
disambiguating the type of a ' MonadState ' , ' HasQSAT ' value .
runQSAT :: StateT QSAT m a -> m (a, QSAT)
runQSAT s = runStateT s def
-- | Run a 'QSAT'-generating state computation in the 'Identity' monad. Useful
e.g. in ghci for disambiguating the type of a ' MonadState ' , ' HasQSAT ' value .
runQSAT' :: StateT QSAT Identity a -> (a, QSAT)
runQSAT' = runIdentity . runQSAT
-- | Run a 'QSAT'-generating state computation and return the respective
-- 'QDIMACS' output. Useful for testing and debugging.
qdimacsQSAT :: StateT QSAT Identity a -> Lazy.ByteString
qdimacsQSAT = toLazyByteString . qdimacs . snd . runQSAT'
literalForall :: MonadQSAT s m => m Literal
literalForall = do
l <- lastAtom <+= 1
universals.contains l .= True
return $ Literal l
# INLINE literalForall #
------------------------------------------------------------------------------
-- Printing SATs
------------------------------------------------------------------------------
-- | DIMACS file format pretty printer
--
-- This is used to generate the problem statement for a given 'SAT' 'Ersatz.Solver.Solver'.
--
class DIMACS t where
dimacsComments :: t -> [ByteString]
dimacsNumVariables :: t -> Int
dimacsClauses :: t -> Seq IntSet
-- | QDIMACS file format pretty printer
--
-- This is used to generate the problem statement for a given 'QSAT' 'Ersatz.Solver.Solver'.
--
class QDIMACS t where
qdimacsComments :: t -> [ByteString]
qdimacsNumVariables :: t -> Int
qdimacsQuantified :: t -> [Quant]
qdimacsClauses :: t -> Seq IntSet
-- | WDIMACS file format pretty printer
--
This is used to generate the problem statement for a given ' MaxSAT ' ' Ersatz . Solver . Solver ' ( TODO ) .
/
class WDIMACS t where
wdimacsComments :: t -> [ByteString]
wdimacsNumVariables :: t -> Int
^ Specified to be 1 ≤ n < 2 ^ 63
wdimacsClauses :: t -> Seq (Int64, IntSet)
-- | Generate a 'Builder' out of a 'DIMACS' problem.
dimacs :: DIMACS t => t -> Builder
dimacs t = comments <> problem <> clauses
where
comments = foldMap bComment (dimacsComments t)
problem = bLine [ string7 "p cnf"
, intDec (dimacsNumVariables t)
, intDec (Seq.length tClauses)
]
clauses = foldMap bClause tClauses
tClauses = dimacsClauses t
-- | Generate a 'Builder' out of a 'QDIMACS' problem.
qdimacs :: QDIMACS t => t -> Builder
qdimacs t = comments <> problem <> quantified <> clauses
where
comments = foldMap bComment (qdimacsComments t)
problem = bLine [ string7 "p cnf"
, intDec (qdimacsNumVariables t)
, intDec (Seq.length tClauses)
]
quantified = foldMap go tQuantGroups
where go ls = bLine0 (q (head ls) : map (intDec . getQuant) ls)
q Exists{} = char7 'e'
q Forall{} = char7 'a'
clauses = foldMap bClause tClauses
tQuantGroups = List.groupBy eqQuant (qdimacsQuantified t)
where
eqQuant :: Quant -> Quant -> Bool
eqQuant Exists{} Exists{} = True
eqQuant Forall{} Forall{} = True
eqQuant _ _ = False
tClauses = qdimacsClauses t
-- | Generate a 'Builder' out of a 'WDIMACS' problem.
wdimacs :: WDIMACS t => t -> Builder
wdimacs t = comments <> problem <> clauses
where
comments = foldMap bComment (wdimacsComments t)
problem = bLine [ string7 "p wcnf"
, intDec (wdimacsNumVariables t)
, intDec (Seq.length tClauses)
, int64Dec (wdimacsTopWeight t)
]
clauses = foldMap (uncurry bWClause) tClauses
tClauses = wdimacsClauses t
bComment :: ByteString -> Builder
bComment bs = bLine [ char7 'c', byteString bs ]
bClause :: IntSet -> Builder
bClause = IntSet.foldl' ( \ e i -> intDec i <> char7 ' ' <> e ) ( char7 '0' <> char7 '\n' )
bWClause :: Int64 -> IntSet -> Builder
bWClause w ls = bLine0 (int64Dec w : map intDec (IntSet.toList ls))
bLine0 :: [Builder] -> Builder
bLine0 = bLine . (++ [char7 '0'])
bLine :: [Builder] -> Builder
bLine bs = mconcat (List.intersperse (char7 ' ') bs) <> char7 '\n'
-- | An explicit prenex quantifier
data Quant
= Exists { getQuant :: {-# UNPACK #-} !Int }
| Forall { getQuant :: {-# UNPACK #-} !Int }
instance DIMACS SAT where
dimacsComments _ = []
dimacsNumVariables s = s^.lastAtom
dimacsClauses = satClauses
instance QDIMACS QSAT where
qdimacsComments _ = []
qdimacsNumVariables q = q^.lastAtom + padding
where
-- "The innermost quantified set is always of type 'e'" per QDIMACS
-- standard. Add an existential atom if the last one is universal.
padding
| Just (i, _) <- IntSet.maxView (q^.universals), i == q^.lastAtom = 1
| otherwise = 0
-- "Unbound atoms are to be considered as being existentially quantified in
the first ( i.e. , the outermost ) quantified set . " per QDIMACS standard .
-- Skip the implicit first existentials.
qdimacsQuantified q
| IntSet.null (q^.universals) = []
| otherwise = quants [head qUniversals..lastAtom'] qUniversals
where
lastAtom' = qdimacsNumVariables q
qUniversals = IntSet.toAscList (q^.universals)
quants :: [Int] -> [Int] -> [Quant]
quants [] _ = []
quants (i:is) [] = Exists i : quants is []
quants (i:is) jjs@(j:js)
| i == j = Forall i : quants is js
| otherwise = Exists i : quants is jjs
qdimacsClauses = satClauses
-- | the name is wrong (Does it return Clauses? No - it returns IntSets.)
-- and it means extra work (traversing, and re-building, the full collection).
-- Or is this fused away (because of Coercible)?
satClauses :: HasSAT s => s -> Seq IntSet
satClauses s = fmap clauseSet (formulaSet (s^.formula))
| null | https://raw.githubusercontent.com/ekmett/ersatz/2218d30818141957957b1533118dd34bd60df245/src/Ersatz/Problem.hs | haskell | # LANGUAGE Rank2Types #
# LANGUAGE OverloadedStrings #
# LANGUAGE ConstraintKinds #
------------------------------------------------------------------
|
License : BSD3
Stability : experimental
Portability: non-portable
------------------------------------------------------------------
* SAT
* QSAT
* DIMACS pretty printing
| Constraint synonym for types that carry a SAT state.
| Constraint synonym for types that carry a QSAT state.
----------------------------------------------------------------------------
SAT Problems
----------------------------------------------------------------------------
# UNPACK #
^ The id of the last atom allocated
^ a set of clauses to assert
^ a mapping used during 'Bit' expansion
| Run a 'SAT'-generating state computation. Useful e.g. in ghci for
| Run a 'SAT'-generating state computation in the 'Identity' monad. Useful
| Run a 'SAT'-generating state computation and return the respective
'DIMACS' output. Useful for testing and debugging.
# INLINE generateLiteral #
----------------------------------------------------------------------------
QSAT Problems
----------------------------------------------------------------------------
| A (quantified) boolean formula.
^ a set indicating which literals are universally quantified
^ The rest of the information, in 'SAT'
| Run a 'QSAT'-generating state computation. Useful e.g. in ghci for
| Run a 'QSAT'-generating state computation in the 'Identity' monad. Useful
| Run a 'QSAT'-generating state computation and return the respective
'QDIMACS' output. Useful for testing and debugging.
----------------------------------------------------------------------------
Printing SATs
----------------------------------------------------------------------------
| DIMACS file format pretty printer
This is used to generate the problem statement for a given 'SAT' 'Ersatz.Solver.Solver'.
| QDIMACS file format pretty printer
This is used to generate the problem statement for a given 'QSAT' 'Ersatz.Solver.Solver'.
| WDIMACS file format pretty printer
| Generate a 'Builder' out of a 'DIMACS' problem.
| Generate a 'Builder' out of a 'QDIMACS' problem.
| Generate a 'Builder' out of a 'WDIMACS' problem.
| An explicit prenex quantifier
# UNPACK #
# UNPACK #
"The innermost quantified set is always of type 'e'" per QDIMACS
standard. Add an existential atom if the last one is universal.
"Unbound atoms are to be considered as being existentially quantified in
Skip the implicit first existentials.
| the name is wrong (Does it return Clauses? No - it returns IntSets.)
and it means extra work (traversing, and re-building, the full collection).
Or is this fused away (because of Coercible)? | # LANGUAGE CPP #
# LANGUAGE TypeFamilies #
# LANGUAGE PatternGuards #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE Trustworthy #
# OPTIONS_HADDOCK not - home #
Copyright : © 2010 - 2014 , 2013
Maintainer : < >
module Ersatz.Problem
(
SAT(SAT)
, HasSAT(..)
, MonadSAT
, runSAT, runSAT', dimacsSAT
, literalExists
, assertFormula
, generateLiteral
, QSAT(QSAT)
, HasQSAT(..)
, MonadQSAT
, runQSAT, runQSAT', qdimacsQSAT
, literalForall
, DIMACS(..)
, QDIMACS(..)
, WDIMACS(..)
, dimacs, qdimacs, wdimacs
) where
import Data.ByteString.Builder
import Control.Lens
import Control.Monad.State
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as Lazy
import Data.Default
import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as HashMap
import Data.Int
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import qualified Data.List as List
import Ersatz.Internal.Formula
import Ersatz.Internal.Literal
import Ersatz.Internal.StableName
import System.IO.Unsafe
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
#if !(MIN_VERSION_base(4,11,0))
import Data.Semigroup (Semigroup(..))
#endif
type MonadSAT s m = (HasSAT s, MonadState s m)
type MonadQSAT s m = (HasQSAT s, MonadState s m)
data SAT = SAT
}
class HasSAT s where
sat :: Lens' s SAT
lastAtom :: Lens' s Int
lastAtom f = sat $ \ (SAT a b c) -> fmap (\a' -> SAT a' b c) (f a)
formula :: Lens' s Formula
formula f = sat $ \ (SAT a b c) -> fmap (\b' -> SAT a b' c) (f b)
stableMap :: Lens' s (HashMap (StableName ()) Literal)
stableMap f = sat $ \ (SAT a b c) -> SAT a b <$> f c
instance HasSAT SAT where
sat = id
instance Show SAT where
showsPrec p bf = showParen (p > 10)
$ showString "SAT " . showsPrec 11 (bf^.lastAtom)
. showChar ' ' . showsPrec 11 (bf^.formula)
. showString " mempty"
instance Default SAT where
The literal 1 is dedicated for the True constant .
def = SAT 1 (formulaLiteral literalTrue) HashMap.empty
disambiguating the type of a ' MonadSAT ' value .
runSAT :: StateT SAT m a -> m (a, SAT)
runSAT s = runStateT s def
e.g. in ghci for disambiguating the type of a ' MonadSAT ' value .
runSAT' :: StateT SAT Identity a -> (a, SAT)
runSAT' = runIdentity . runSAT
dimacsSAT :: StateT SAT Identity a -> Lazy.ByteString
dimacsSAT = toLazyByteString . dimacs . snd . runSAT'
literalExists :: MonadSAT s m => m Literal
literalExists = fmap Literal $ lastAtom <+= 1
# INLINE literalExists #
assertFormula :: MonadSAT s m => Formula -> m ()
assertFormula xs = formula <>= xs
# INLINE assertFormula #
generateLiteral :: MonadSAT s m => a -> (Literal -> m ()) -> m Literal
generateLiteral a f = do
let sn = unsafePerformIO (makeStableName' a)
use (stableMap.at sn) >>= \ ml -> case ml of
Just l -> return l
Nothing -> do
l <- literalExists
stableMap.at sn ?= l
f l
return l
data QSAT = QSAT
} deriving Show
class HasSAT t => HasQSAT t where
qsat :: Lens' t QSAT
universals :: Lens' t IntSet
universals f = qsat ago where
ago (QSAT u s) = f u <&> \u' -> QSAT u' s
instance HasSAT QSAT where
sat f (QSAT u s) = QSAT u <$> f s
instance HasQSAT QSAT where
qsat = id
instance Default QSAT where
def = QSAT IntSet.empty def
disambiguating the type of a ' MonadState ' , ' HasQSAT ' value .
runQSAT :: StateT QSAT m a -> m (a, QSAT)
runQSAT s = runStateT s def
e.g. in ghci for disambiguating the type of a ' MonadState ' , ' HasQSAT ' value .
runQSAT' :: StateT QSAT Identity a -> (a, QSAT)
runQSAT' = runIdentity . runQSAT
qdimacsQSAT :: StateT QSAT Identity a -> Lazy.ByteString
qdimacsQSAT = toLazyByteString . qdimacs . snd . runQSAT'
literalForall :: MonadQSAT s m => m Literal
literalForall = do
l <- lastAtom <+= 1
universals.contains l .= True
return $ Literal l
# INLINE literalForall #
class DIMACS t where
dimacsComments :: t -> [ByteString]
dimacsNumVariables :: t -> Int
dimacsClauses :: t -> Seq IntSet
class QDIMACS t where
qdimacsComments :: t -> [ByteString]
qdimacsNumVariables :: t -> Int
qdimacsQuantified :: t -> [Quant]
qdimacsClauses :: t -> Seq IntSet
This is used to generate the problem statement for a given ' MaxSAT ' ' Ersatz . Solver . Solver ' ( TODO ) .
/
class WDIMACS t where
wdimacsComments :: t -> [ByteString]
wdimacsNumVariables :: t -> Int
^ Specified to be 1 ≤ n < 2 ^ 63
wdimacsClauses :: t -> Seq (Int64, IntSet)
dimacs :: DIMACS t => t -> Builder
dimacs t = comments <> problem <> clauses
where
comments = foldMap bComment (dimacsComments t)
problem = bLine [ string7 "p cnf"
, intDec (dimacsNumVariables t)
, intDec (Seq.length tClauses)
]
clauses = foldMap bClause tClauses
tClauses = dimacsClauses t
qdimacs :: QDIMACS t => t -> Builder
qdimacs t = comments <> problem <> quantified <> clauses
where
comments = foldMap bComment (qdimacsComments t)
problem = bLine [ string7 "p cnf"
, intDec (qdimacsNumVariables t)
, intDec (Seq.length tClauses)
]
quantified = foldMap go tQuantGroups
where go ls = bLine0 (q (head ls) : map (intDec . getQuant) ls)
q Exists{} = char7 'e'
q Forall{} = char7 'a'
clauses = foldMap bClause tClauses
tQuantGroups = List.groupBy eqQuant (qdimacsQuantified t)
where
eqQuant :: Quant -> Quant -> Bool
eqQuant Exists{} Exists{} = True
eqQuant Forall{} Forall{} = True
eqQuant _ _ = False
tClauses = qdimacsClauses t
wdimacs :: WDIMACS t => t -> Builder
wdimacs t = comments <> problem <> clauses
where
comments = foldMap bComment (wdimacsComments t)
problem = bLine [ string7 "p wcnf"
, intDec (wdimacsNumVariables t)
, intDec (Seq.length tClauses)
, int64Dec (wdimacsTopWeight t)
]
clauses = foldMap (uncurry bWClause) tClauses
tClauses = wdimacsClauses t
bComment :: ByteString -> Builder
bComment bs = bLine [ char7 'c', byteString bs ]
bClause :: IntSet -> Builder
bClause = IntSet.foldl' ( \ e i -> intDec i <> char7 ' ' <> e ) ( char7 '0' <> char7 '\n' )
bWClause :: Int64 -> IntSet -> Builder
bWClause w ls = bLine0 (int64Dec w : map intDec (IntSet.toList ls))
bLine0 :: [Builder] -> Builder
bLine0 = bLine . (++ [char7 '0'])
bLine :: [Builder] -> Builder
bLine bs = mconcat (List.intersperse (char7 ' ') bs) <> char7 '\n'
data Quant
instance DIMACS SAT where
dimacsComments _ = []
dimacsNumVariables s = s^.lastAtom
dimacsClauses = satClauses
instance QDIMACS QSAT where
qdimacsComments _ = []
qdimacsNumVariables q = q^.lastAtom + padding
where
padding
| Just (i, _) <- IntSet.maxView (q^.universals), i == q^.lastAtom = 1
| otherwise = 0
the first ( i.e. , the outermost ) quantified set . " per QDIMACS standard .
qdimacsQuantified q
| IntSet.null (q^.universals) = []
| otherwise = quants [head qUniversals..lastAtom'] qUniversals
where
lastAtom' = qdimacsNumVariables q
qUniversals = IntSet.toAscList (q^.universals)
quants :: [Int] -> [Int] -> [Quant]
quants [] _ = []
quants (i:is) [] = Exists i : quants is []
quants (i:is) jjs@(j:js)
| i == j = Forall i : quants is js
| otherwise = Exists i : quants is jjs
qdimacsClauses = satClauses
satClauses :: HasSAT s => s -> Seq IntSet
satClauses s = fmap clauseSet (formulaSet (s^.formula))
|
649b4786b16139be8a79edfcfbaa7b5a997c2818a0c914554dd783e91767e5bd | aspiwack/porcupine | Locations.hs | module Data.Locations
( module Data.Locations.Loc
, module Data.Locations.LocationTree
, module Data.Locations.LocVariable
, module Data.Locations.Mappings
, module Data.Locations.VirtualFile
, module Data.Locations.SerializationMethod
, module Data.Locations.LogAndErrors
) where
import Data.Locations.Loc
import Data.Locations.LocationTree
import Data.Locations.LocVariable
import Data.Locations.LogAndErrors
import Data.Locations.Mappings
import Data.Locations.SerializationMethod
import Data.Locations.VirtualFile
| null | https://raw.githubusercontent.com/aspiwack/porcupine/23dcba1523626af0fdf6085f4107987d4bf718d7/porcupine-core/src/Data/Locations.hs | haskell | module Data.Locations
( module Data.Locations.Loc
, module Data.Locations.LocationTree
, module Data.Locations.LocVariable
, module Data.Locations.Mappings
, module Data.Locations.VirtualFile
, module Data.Locations.SerializationMethod
, module Data.Locations.LogAndErrors
) where
import Data.Locations.Loc
import Data.Locations.LocationTree
import Data.Locations.LocVariable
import Data.Locations.LogAndErrors
import Data.Locations.Mappings
import Data.Locations.SerializationMethod
import Data.Locations.VirtualFile
| |
72db7eee8f81a79710ba2ee68453b3a98412718b1645cc8bbde272fd8583ebe1 | shirok/WiLiKi | core.scm | ;; test wiliki.core
(use gauche.test)
(test-start "core")
(use wiliki.core)
(test-module 'wiliki.core)
(test* "constructor" '<wiliki>
(class-name (class-of (make <wiliki>))))
;; more tests to come...
(test-end)
| null | https://raw.githubusercontent.com/shirok/WiLiKi/5fce918ed5b3f9c69cd2972c418bd72cbc0b1fe5/test/core.scm | scheme | test wiliki.core
more tests to come... |
(use gauche.test)
(test-start "core")
(use wiliki.core)
(test-module 'wiliki.core)
(test* "constructor" '<wiliki>
(class-name (class-of (make <wiliki>))))
(test-end)
|
18db7cc2a1bf88ee3a257d0967b059c493de2696f7e987af62ac1850e964bdd7 | tonyvanriet/clj-slack-client | groups.clj | (ns clj-slack-client.groups
(:require [clj-slack-client.web :as web])
(:refer-clojure :exclude [list]))
(def api-module "groups")
(defn- call
([method-name token]
(web/call-and-get-response (str api-module "." method-name) {:token token}))
([method-name token channel]
(web/call-and-get-response (str api-module "." method-name)
{:token token :channel channel}))
([method-name token channel options]
(web/call-and-get-response (str api-module "." method-name)
(merge {:token token :channel channel}
options))))
(defn archive
"Archives a private channel. Callable by workspace and user."
[token channel]
(call "archive" token channel))
(defn create
"Creates a private channel. Callable by workspace and user."
([token channel-name]
(create token channel-name false))
([token channel-name validate]
(web/call-and-get-response "create"
{:token token :name channel-name
:validate validate})))
(defn create-child
"Clones and archives a private channel. Accessible by user and workspcae
tokens."
[token channel]
(call "createChild" token channel))
(defn history
"Fetches history of messages and events from a private channel.
Callable by bot, user, and workspace tokens."
([token channel]
(history token channel {}))
([token channel options]
(call "history" token channel options)))
(defn info
"Gets information about a private channel. Acessible by all token types."
([token channel]
(token channel false))
([token channel include-locale]
(call "info" token channel include-locale)))
(defn invite
"Invites a user to a private channel. Accessible by workspace
and user tokens."
[token channel user]
(call "invite" token channel {:user user}))
(defn kick
"Removes a user from a private channel. Callable by user and
workspace tokens."
[token channel user]
(call "kick" token channel {:user user}))
(defn leave
"Leaves a private channel. Only callable by user."
[token channel]
(call "leave" token channel))
(defn list
"Lists all private channels that the calling user has access to.
Callable by all token types."
([token]
(call "list" token))
([token options]
(web/call-and-get-response "groups.list" {:token token})))
(defn mark
"Sets the read cursor in a private channel. Callable by
bot and user token types."
[token channel time-stamp]
(call "mark" token channel {:ts time-stamp}))
(defn open
"Opens a private channel. Callable by bot and user tokens."
[token channel]
(call "open" token channel))
(defn rename
"Renames a private channel. Supported by user and workspace
token types."
([token channel new-name]
(rename token channel new-name false))
([token channel new-name validate]
(call "rename" token channel {:name new-name :validate validate})))
(defn replies
"Retrieve a thread of messages posted to a private channel.
Accessible by user and workspace tokens."
[token channel time-stamp]
(call "replies" token channel {:ts time-stamp}))
(defn set-purpose
"Sets the purpose for a private channel. Supported by all token types."
[token channel purpose]
(call "setPurpose" token channel {:purpose purpose}))
(defn set-topic
"Sets the topic for a private channel. Supported by all token types."
[token channel topic]
(call "setPurpose" token channel {:topic topic}))
(defn unarchive
"Unarchives a private channel. Accessible by workspack and user types."
[token channel]
(call "unarchive" token channel))
| null | https://raw.githubusercontent.com/tonyvanriet/clj-slack-client/6783f003ab93adae057890421622eb5e61ab033d/src/clj_slack_client/groups.clj | clojure | (ns clj-slack-client.groups
(:require [clj-slack-client.web :as web])
(:refer-clojure :exclude [list]))
(def api-module "groups")
(defn- call
([method-name token]
(web/call-and-get-response (str api-module "." method-name) {:token token}))
([method-name token channel]
(web/call-and-get-response (str api-module "." method-name)
{:token token :channel channel}))
([method-name token channel options]
(web/call-and-get-response (str api-module "." method-name)
(merge {:token token :channel channel}
options))))
(defn archive
"Archives a private channel. Callable by workspace and user."
[token channel]
(call "archive" token channel))
(defn create
"Creates a private channel. Callable by workspace and user."
([token channel-name]
(create token channel-name false))
([token channel-name validate]
(web/call-and-get-response "create"
{:token token :name channel-name
:validate validate})))
(defn create-child
"Clones and archives a private channel. Accessible by user and workspcae
tokens."
[token channel]
(call "createChild" token channel))
(defn history
"Fetches history of messages and events from a private channel.
Callable by bot, user, and workspace tokens."
([token channel]
(history token channel {}))
([token channel options]
(call "history" token channel options)))
(defn info
"Gets information about a private channel. Acessible by all token types."
([token channel]
(token channel false))
([token channel include-locale]
(call "info" token channel include-locale)))
(defn invite
"Invites a user to a private channel. Accessible by workspace
and user tokens."
[token channel user]
(call "invite" token channel {:user user}))
(defn kick
"Removes a user from a private channel. Callable by user and
workspace tokens."
[token channel user]
(call "kick" token channel {:user user}))
(defn leave
"Leaves a private channel. Only callable by user."
[token channel]
(call "leave" token channel))
(defn list
"Lists all private channels that the calling user has access to.
Callable by all token types."
([token]
(call "list" token))
([token options]
(web/call-and-get-response "groups.list" {:token token})))
(defn mark
"Sets the read cursor in a private channel. Callable by
bot and user token types."
[token channel time-stamp]
(call "mark" token channel {:ts time-stamp}))
(defn open
"Opens a private channel. Callable by bot and user tokens."
[token channel]
(call "open" token channel))
(defn rename
"Renames a private channel. Supported by user and workspace
token types."
([token channel new-name]
(rename token channel new-name false))
([token channel new-name validate]
(call "rename" token channel {:name new-name :validate validate})))
(defn replies
"Retrieve a thread of messages posted to a private channel.
Accessible by user and workspace tokens."
[token channel time-stamp]
(call "replies" token channel {:ts time-stamp}))
(defn set-purpose
"Sets the purpose for a private channel. Supported by all token types."
[token channel purpose]
(call "setPurpose" token channel {:purpose purpose}))
(defn set-topic
"Sets the topic for a private channel. Supported by all token types."
[token channel topic]
(call "setPurpose" token channel {:topic topic}))
(defn unarchive
"Unarchives a private channel. Accessible by workspack and user types."
[token channel]
(call "unarchive" token channel))
| |
5bb71f3e097d622c2d2cd3510582491b297933538c11ef0fdebffa5c3f0e2bd3 | mfelleisen/Acquire | xrun.rkt | #lang racket
;; ---------------------------------------------------------------------------------------------------
;; a generic script generator
;; generated script runs client on specified in<n>.xml files
;; and compares the expected XML output with outN.xml
;; via some xml-diff checker
(provide main test-directory xml-diff xclient)
;; systems require:
;; it relies on a script in xdiff-xml that compares XML outputs in the
;; context of SwDev projects
(define test-directory (make-parameter #f))
(define xml-diff (make-parameter #f))
(define xclient (make-parameter #f))
;; ---------------------------------------------------------------------------------------------------
;; implementation
(define (main . x)
(define files
(parameterize ((current-directory (test-directory)))
(for/list ((f (directory-list)) #:when (regexp-match #px"in(\\d).xml$" (path->string f)))
(second (regexp-match #px"in(\\d).xml$" (path->string f))))))
(for ((n files))
(test n)))
;; String [Nat] -> Boolean
(define (test n)
(displayln "-----------------------------------------------------------------------------")
(printf "testing in~a.xml, out~a.xml\n" n n)
(define client (format (xclient) (test-directory) n))
(define xdiff (format (xml-diff) (test-directory) n))
(system (format "~a | ~a " client xdiff))
(void))
| null | https://raw.githubusercontent.com/mfelleisen/Acquire/5b39df6c757c7c1cafd7ff198641c99d30072b91/xrun.rkt | racket | ---------------------------------------------------------------------------------------------------
a generic script generator
generated script runs client on specified in<n>.xml files
and compares the expected XML output with outN.xml
via some xml-diff checker
systems require:
it relies on a script in xdiff-xml that compares XML outputs in the
context of SwDev projects
---------------------------------------------------------------------------------------------------
implementation
String [Nat] -> Boolean | #lang racket
(provide main test-directory xml-diff xclient)
(define test-directory (make-parameter #f))
(define xml-diff (make-parameter #f))
(define xclient (make-parameter #f))
(define (main . x)
(define files
(parameterize ((current-directory (test-directory)))
(for/list ((f (directory-list)) #:when (regexp-match #px"in(\\d).xml$" (path->string f)))
(second (regexp-match #px"in(\\d).xml$" (path->string f))))))
(for ((n files))
(test n)))
(define (test n)
(displayln "-----------------------------------------------------------------------------")
(printf "testing in~a.xml, out~a.xml\n" n n)
(define client (format (xclient) (test-directory) n))
(define xdiff (format (xml-diff) (test-directory) n))
(system (format "~a | ~a " client xdiff))
(void))
|
789c83d7a38978b392500b07b64e075af64437ef6d937c23314850142f7e056f | joodie/flutter | html4.clj | (ns flutter.html4
"convenience functions providing all the standard HTML fields"
(:use flutter.core
flutter.html4.input-fields
flutter.html4.select
flutter.html4.text-area))
(defn wrap-html4-fields
"Provides all the HTML 4 form fields in a sane way. Includes
wrap-basic-input-fields, wrap-html4-input-fields,
wrap-radio-and-checkbox, wrap-select and wrap-text-area"
[f]
(-> f
wrap-basic-input-fields
wrap-html4-input-fields
wrap-radio-and-checkbox
wrap-select
wrap-text-area))
(def html4-fields
^{:doc "wrap-html4-fields, pre-wrapped in the core `field'"}
(wrap-html4-fields field))
| null | https://raw.githubusercontent.com/joodie/flutter/336e40386ff4e79ce9243ec8690e2a62c41f80a3/src/flutter/html4.clj | clojure | (ns flutter.html4
"convenience functions providing all the standard HTML fields"
(:use flutter.core
flutter.html4.input-fields
flutter.html4.select
flutter.html4.text-area))
(defn wrap-html4-fields
"Provides all the HTML 4 form fields in a sane way. Includes
wrap-basic-input-fields, wrap-html4-input-fields,
wrap-radio-and-checkbox, wrap-select and wrap-text-area"
[f]
(-> f
wrap-basic-input-fields
wrap-html4-input-fields
wrap-radio-and-checkbox
wrap-select
wrap-text-area))
(def html4-fields
^{:doc "wrap-html4-fields, pre-wrapped in the core `field'"}
(wrap-html4-fields field))
| |
8e44d624004308441c5ea8b62e6078cf9a2f702fbac7dcc6936f8d8f1cf2ad53 | CloudI/CloudI | folsom_ewma.erl | %%%
Copyright 2011 , Boundary
%%%
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.
%%%
%%%-------------------------------------------------------------------
File : folsom_ewma.erl
@author < >
%%% @doc
based on
%%% references:
%%%
%%%
%%% @end
%%%-----------------------------------------------------------------
-module(folsom_ewma).
-define(INSTANT_ALPHA, 1).
-define(M1_ALPHA, 1 - math:exp(-5 / 60.0)).
-define(M5_ALPHA, 1 - math:exp(-5 / 60.0 / 5)).
-define(M15_ALPHA, 1 - math:exp(-5 / 60.0 / 15)).
-define(D1_ALPHA, 1 - math:exp(-5 / 60.0 / 1440)).
-record(ewma, {
alpha,
interval = 5, % seconds
initialized = false,
rate = 0,
total = 0
}).
-export([update/2,
new/2,
rate/1,
tick/1,
instant_ewma/0,
one_minute_ewma/0,
five_minute_ewma/0,
fifteen_minute_ewma/0,
one_day_ewma/0]).
% API
instant_ewma() ->
new(?INSTANT_ALPHA, 5).
one_minute_ewma() ->
new(?M1_ALPHA, 5).
five_minute_ewma() ->
new(?M5_ALPHA, 5).
fifteen_minute_ewma() ->
new(?M15_ALPHA, 5).
one_day_ewma() ->
new(?D1_ALPHA, 5).
new(Alpha, Interval) ->
#ewma{alpha = Alpha, interval = Interval}.
update(#ewma{total = Total} = EWMA, Value) ->
EWMA#ewma{total = Total + Value}.
tick(#ewma{total = Total, rate = _Rate, initialized = _Init, interval = Interval, alpha = ?INSTANT_ALPHA} = EWMA) ->
InstantRate = Total / Interval,
EWMA#ewma{rate = InstantRate, total = 0};
tick(#ewma{total = Total, rate = Rate, initialized = Init, interval = Interval, alpha = Alpha} = EWMA) ->
InstantRate = Total / Interval,
Rate1 = rate_calc(Init, Alpha, Rate, InstantRate),
EWMA#ewma{rate = Rate1, initialized = true, total = 0}.
rate(#ewma{rate = Rate}) ->
Rate.
% Internal API
rate_calc(true, Alpha, Rate, InstantRate) ->
Rate1 = Rate + (Alpha * (InstantRate - Rate)),
Rate1;
rate_calc(false, _, _, InstantRate) ->
InstantRate.
| null | https://raw.githubusercontent.com/CloudI/CloudI/3e45031c7ee3e974ead2612ea7dd06c9edf973c9/src/external/cloudi_x_folsom/src/folsom_ewma.erl | erlang |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------------------------------
@doc
references:
@end
-----------------------------------------------------------------
seconds
API
Internal API | Copyright 2011 , Boundary
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
File : folsom_ewma.erl
@author < >
based on
-module(folsom_ewma).
-define(INSTANT_ALPHA, 1).
-define(M1_ALPHA, 1 - math:exp(-5 / 60.0)).
-define(M5_ALPHA, 1 - math:exp(-5 / 60.0 / 5)).
-define(M15_ALPHA, 1 - math:exp(-5 / 60.0 / 15)).
-define(D1_ALPHA, 1 - math:exp(-5 / 60.0 / 1440)).
-record(ewma, {
alpha,
initialized = false,
rate = 0,
total = 0
}).
-export([update/2,
new/2,
rate/1,
tick/1,
instant_ewma/0,
one_minute_ewma/0,
five_minute_ewma/0,
fifteen_minute_ewma/0,
one_day_ewma/0]).
instant_ewma() ->
new(?INSTANT_ALPHA, 5).
one_minute_ewma() ->
new(?M1_ALPHA, 5).
five_minute_ewma() ->
new(?M5_ALPHA, 5).
fifteen_minute_ewma() ->
new(?M15_ALPHA, 5).
one_day_ewma() ->
new(?D1_ALPHA, 5).
new(Alpha, Interval) ->
#ewma{alpha = Alpha, interval = Interval}.
update(#ewma{total = Total} = EWMA, Value) ->
EWMA#ewma{total = Total + Value}.
tick(#ewma{total = Total, rate = _Rate, initialized = _Init, interval = Interval, alpha = ?INSTANT_ALPHA} = EWMA) ->
InstantRate = Total / Interval,
EWMA#ewma{rate = InstantRate, total = 0};
tick(#ewma{total = Total, rate = Rate, initialized = Init, interval = Interval, alpha = Alpha} = EWMA) ->
InstantRate = Total / Interval,
Rate1 = rate_calc(Init, Alpha, Rate, InstantRate),
EWMA#ewma{rate = Rate1, initialized = true, total = 0}.
rate(#ewma{rate = Rate}) ->
Rate.
rate_calc(true, Alpha, Rate, InstantRate) ->
Rate1 = Rate + (Alpha * (InstantRate - Rate)),
Rate1;
rate_calc(false, _, _, InstantRate) ->
InstantRate.
|
02f5b87736b6b5708e30926369925fc908393b5e18ff5991b5edccf0dae0eac4 | xmonad/xmonad | Screen.hs | # LANGUAGE ScopedTypeVariables #
module Properties.Screen where
import Utils
import Test.QuickCheck
import Instances
import Control.Applicative
import XMonad.StackSet hiding (filter)
import XMonad.Operations
import Graphics.X11.Xlib.Types (Dimension)
import Graphics.X11 (Rectangle(Rectangle))
import XMonad.Layout
prop_screens (x :: T) = n `elem` screens x
where
n = current x
-- screens makes sense
prop_screens_works (x :: T) = screens x == current x : visible x
------------------------------------------------------------------------
-- Hints
prop_resize_inc (Positive inc_w,Positive inc_h) b@(w,h) =
w' `mod` inc_w == 0 && h' `mod` inc_h == 0
where (w',h') = applyResizeIncHint a b
a = (inc_w,inc_h)
prop_resize_inc_extra ((NonNegative inc_w)) b@(w,h) =
(w,h) == (w',h')
where (w',h') = applyResizeIncHint a b
a = (-inc_w,0::Dimension)-- inc_h)
prop_resize_max (Positive inc_w,Positive inc_h) b@(w,h) =
w' <= inc_w && h' <= inc_h
where (w',h') = applyMaxSizeHint a b
a = (inc_w,inc_h)
prop_resize_max_extra ((NonNegative inc_w)) b@(w,h) =
(w,h) == (w',h')
where (w',h') = applyMaxSizeHint a b
a = (-inc_w,0::Dimension)-- inc_h)
prop_aspect_hint_shrink hint (w,h) = case applyAspectHint hint (w,h) of
(w',h') -> w' <= w && h' <= h
-- applyAspectHint does nothing when the supplied (x,y) fits
-- the desired range
prop_aspect_fits =
forAll ((,,,) <$> pos <*> pos <*> pos <*> pos) $ \ (x,y,a,b) ->
let f = applyAspectHint ((x, y+a), (x+b, y))
in noOverflows (*) x (y+a) && noOverflows (*) (x+b) y
==> f (x,y) == (x,y)
where pos = choose (0, 65535)
prop_point_within r@(Rectangle x y w h) =
forAll ((,) <$>
choose (0, fromIntegral w - 1) <*>
choose (0, fromIntegral h - 1)) $
\(dx,dy) ->
and [ dx > 0, dy > 0,
noOverflows (\ a b -> a + abs b) x w,
noOverflows (\ a b -> a + abs b) y h ]
==> pointWithin (x+dx) (y+dy) r
prop_point_within_mirror r (x,y) = pointWithin x y r == pointWithin y x (mirrorRect r)
| null | https://raw.githubusercontent.com/xmonad/xmonad/45a89130d96bfb4fe449e438e5436b73ca4ab4ed/tests/Properties/Screen.hs | haskell | screens makes sense
----------------------------------------------------------------------
Hints
inc_h)
inc_h)
applyAspectHint does nothing when the supplied (x,y) fits
the desired range | # LANGUAGE ScopedTypeVariables #
module Properties.Screen where
import Utils
import Test.QuickCheck
import Instances
import Control.Applicative
import XMonad.StackSet hiding (filter)
import XMonad.Operations
import Graphics.X11.Xlib.Types (Dimension)
import Graphics.X11 (Rectangle(Rectangle))
import XMonad.Layout
prop_screens (x :: T) = n `elem` screens x
where
n = current x
prop_screens_works (x :: T) = screens x == current x : visible x
prop_resize_inc (Positive inc_w,Positive inc_h) b@(w,h) =
w' `mod` inc_w == 0 && h' `mod` inc_h == 0
where (w',h') = applyResizeIncHint a b
a = (inc_w,inc_h)
prop_resize_inc_extra ((NonNegative inc_w)) b@(w,h) =
(w,h) == (w',h')
where (w',h') = applyResizeIncHint a b
prop_resize_max (Positive inc_w,Positive inc_h) b@(w,h) =
w' <= inc_w && h' <= inc_h
where (w',h') = applyMaxSizeHint a b
a = (inc_w,inc_h)
prop_resize_max_extra ((NonNegative inc_w)) b@(w,h) =
(w,h) == (w',h')
where (w',h') = applyMaxSizeHint a b
prop_aspect_hint_shrink hint (w,h) = case applyAspectHint hint (w,h) of
(w',h') -> w' <= w && h' <= h
prop_aspect_fits =
forAll ((,,,) <$> pos <*> pos <*> pos <*> pos) $ \ (x,y,a,b) ->
let f = applyAspectHint ((x, y+a), (x+b, y))
in noOverflows (*) x (y+a) && noOverflows (*) (x+b) y
==> f (x,y) == (x,y)
where pos = choose (0, 65535)
prop_point_within r@(Rectangle x y w h) =
forAll ((,) <$>
choose (0, fromIntegral w - 1) <*>
choose (0, fromIntegral h - 1)) $
\(dx,dy) ->
and [ dx > 0, dy > 0,
noOverflows (\ a b -> a + abs b) x w,
noOverflows (\ a b -> a + abs b) y h ]
==> pointWithin (x+dx) (y+dy) r
prop_point_within_mirror r (x,y) = pointWithin x y r == pointWithin y x (mirrorRect r)
|
95e85eaa95e5c86efc43dd7bbafeeee71b158a2062797d9031bed7f6da1566a3 | rystsov/fast-jepsen | db.clj | (ns mongo-http.db
"API to work with MongoDB via an exposed HTTP interface"
(:use clojure.tools.logging)
(:require
[clojure.tools.logging :refer [debug info warn]]
[clj-http.client :as client]
[clojure.data.json :as json]))
(defn primary
"Returns a node name (string) of a current primary"
[host]
(let [response (client/get
(str "http://" host ":8000/primary")
{ :as :json,
:socket-timeout 1000 ;; in milliseconds
:conn-timeout 1000 ;; in milliseconds
:accept :json})]
(if (= (:status response) 200)
(:primary (:body response))
(throw (Exception. (str "Got" (:status response) " status code :( expected 200"))))))
(defn create [host key write-id value]
"Creates a new record & returns it or throws an exception
The record has the following form:
{ :key \"...\", :value \"...\" }"
(let [response (client/post
(str "http://" host ":8000/create")
{ :as :json,
:body (json/write-str {:key key :writeID write-id :value value})
:content-type :json
:socket-timeout 1000 ;; in milliseconds
:conn-timeout 1000 ;; in milliseconds
:accept :json})]
(if (= (:status response) 200)
(:body response)
(throw (Exception. (str "Got" (:status response) " status code :( expected 200"))))))
(defn overwrite
"Overwrites the current record and returns it"
[host key write-id value]
(let [response (client/post
(str "http://" host ":8000/overwrite")
{ :as :json,
:body (json/write-str {:key key :writeID write-id :value value})
:content-type :json
:socket-timeout 1000 ;; in milliseconds
:conn-timeout 1000 ;; in milliseconds
:accept :json})]
(if (= (:status response) 200)
(:body response)
(throw (Exception. (str "Got" (:status response) " status code :( expected 200"))))))
(defn cas
"Overwrites the current record if it's writeID is prev-write-id"
[host key prev-write-id write-id value]
(let [response (client/post
(str "http://" host ":8000/cas")
{ :as :json,
:body (json/write-str { :key key
:prevWriteID prev-write-id
:writeID write-id
:value value })
:content-type :json
:socket-timeout 1000
:conn-timeout 1000
:accept :json})]
(if (= (:status response) 200)
(:body response)
(throw (Exception. (str "Got" (:status response) " status code :( expected 200"))))))
(defn read [host key]
(let [response (client/get
(str "http://" host ":8000/read/" key)
{ :as :json,
:socket-timeout 1000 ;; in milliseconds
:conn-timeout 1000 ;; in milliseconds
:accept :json})]
(if (= (:status response) 200)
{ :write-id (:writeID (:body response))
:value (:value (:body response))}
(throw (Exception. (str "Got" (:status response) " status code :( expected 200")))))) | null | https://raw.githubusercontent.com/rystsov/fast-jepsen/1a7c5e93cdc9cb8bfb29eda8f0079277375e108d/jepsen/src/src/mongo_http/db.clj | clojure | in milliseconds
in milliseconds
in milliseconds
in milliseconds
in milliseconds
in milliseconds
in milliseconds
in milliseconds | (ns mongo-http.db
"API to work with MongoDB via an exposed HTTP interface"
(:use clojure.tools.logging)
(:require
[clojure.tools.logging :refer [debug info warn]]
[clj-http.client :as client]
[clojure.data.json :as json]))
(defn primary
"Returns a node name (string) of a current primary"
[host]
(let [response (client/get
(str "http://" host ":8000/primary")
{ :as :json,
:accept :json})]
(if (= (:status response) 200)
(:primary (:body response))
(throw (Exception. (str "Got" (:status response) " status code :( expected 200"))))))
(defn create [host key write-id value]
"Creates a new record & returns it or throws an exception
The record has the following form:
{ :key \"...\", :value \"...\" }"
(let [response (client/post
(str "http://" host ":8000/create")
{ :as :json,
:body (json/write-str {:key key :writeID write-id :value value})
:content-type :json
:accept :json})]
(if (= (:status response) 200)
(:body response)
(throw (Exception. (str "Got" (:status response) " status code :( expected 200"))))))
(defn overwrite
"Overwrites the current record and returns it"
[host key write-id value]
(let [response (client/post
(str "http://" host ":8000/overwrite")
{ :as :json,
:body (json/write-str {:key key :writeID write-id :value value})
:content-type :json
:accept :json})]
(if (= (:status response) 200)
(:body response)
(throw (Exception. (str "Got" (:status response) " status code :( expected 200"))))))
(defn cas
"Overwrites the current record if it's writeID is prev-write-id"
[host key prev-write-id write-id value]
(let [response (client/post
(str "http://" host ":8000/cas")
{ :as :json,
:body (json/write-str { :key key
:prevWriteID prev-write-id
:writeID write-id
:value value })
:content-type :json
:socket-timeout 1000
:conn-timeout 1000
:accept :json})]
(if (= (:status response) 200)
(:body response)
(throw (Exception. (str "Got" (:status response) " status code :( expected 200"))))))
(defn read [host key]
(let [response (client/get
(str "http://" host ":8000/read/" key)
{ :as :json,
:accept :json})]
(if (= (:status response) 200)
{ :write-id (:writeID (:body response))
:value (:value (:body response))}
(throw (Exception. (str "Got" (:status response) " status code :( expected 200")))))) |
863af31335d3ee0d6b7307e174b37afe76d8a7e6add8c98e44ca46ad66423a4b | ocaml-multicore/tezos | size.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2021 - 2022 Nomadic Labs < >
(* *)
(* 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. *)
(* *)
(*****************************************************************************)
open Protocol
type t = int
type micheline_size = {traversal : t; int_bytes : t; string_bytes : t}
(* ------------------------------------------------------------------------- *)
(* encoding *)
let encoding : t Data_encoding.encoding =
let open Data_encoding in
conv (fun i -> Int64.of_int i) (fun l -> Int64.to_int l) int64
let micheline_size_encoding : micheline_size Data_encoding.encoding =
let open Data_encoding in
conv
(fun {traversal; int_bytes; string_bytes} ->
(traversal, int_bytes, string_bytes))
(fun (traversal, int_bytes, string_bytes) ->
{traversal; int_bytes; string_bytes})
(tup3 encoding encoding encoding)
(* ------------------------------------------------------------------------- *)
let zero = 0
let one = 1
let add = ( + )
let sub = ( - )
let mul = ( * )
let div = ( / )
let max x y = if x < y then y else x
let min x y = if x < y then x else y
(* can't be bothered to do it well *)
let rec pow x i = if i = 0 then 1 else x * pow x (i - 1)
module Ops = struct
let ( * ) = mul
let ( / ) = div
let ( + ) = add
let ( - ) = sub
let ( ** ) = pow
end
let compare = Stdlib.compare
let equal = ( = )
let lt = ( < )
let leq = ( <= )
let pp = Format.pp_print_int
let pp_micheline_size fmtr {traversal; int_bytes; string_bytes} =
Format.fprintf
fmtr
"@[{ traversal = %a;@; int_bytes = %a;@; string_bytes = %a;@,}@]"
pp
traversal
pp
int_bytes
pp
string_bytes
let show = string_of_int
let to_float = float_of_int
let of_float = int_of_float
let to_int x = x
let of_int x = x
let log2 x = Z.log2 (Z.of_int x)
let unit : t = 1
let integer (i : 'a Alpha_context.Script_int.num) : t =
Z.numbits (Alpha_context.Script_int.to_zint i) / 8
let string = String.length
let script_string = Alpha_context.Script_string.length
let bytes (b : Bytes.t) : t = Bytes.length b
let mutez (_tez : Alpha_context.Tez.tez) : t =
Up to now , mutez are stored on 8 bytes ( int64 ) .
8
let bool (_ : bool) : t = 1
let signature (_signature : Script_typed_ir.Script_signature.t) : t =
Script_typed_ir.Script_signature.size
let key_hash (_keyhash : Signature.public_key_hash) : t =
Signature.Public_key_hash.size
let public_key (public_key : Signature.public_key) : t =
Signature.Public_key.size public_key
let chain_id (_chain_id : Script_typed_ir.Script_chain_id.t) : t =
Script_typed_ir.Script_chain_id.size
let address (addr : Script_typed_ir.address) : t =
let entrypoint = addr.entrypoint in
Signature.Public_key_hash.size
+ String.length (Alpha_context.Entrypoint.to_string entrypoint)
let list (list : 'a Script_typed_ir.boxed_list) : t =
list.Script_typed_ir.length
let set (set : 'a Script_typed_ir.set) : t =
let res = Alpha_context.Script_int.to_int (Script_set.size set) in
match res with None -> assert false | Some x -> x
let map (map : ('a, 'b) Script_typed_ir.map) : t =
let res = Alpha_context.Script_int.to_int (Script_map.size map) in
match res with None -> assert false | Some x -> x
let timestamp (tstamp : Alpha_context.Script_timestamp.t) : t =
Z.numbits (Alpha_context.Script_timestamp.to_zint tstamp) / 8
(* ------------------------------------------------------------------------- *)
Micheline / Michelson - related
let micheline_zero = {traversal = 0; int_bytes = 0; string_bytes = 0}
let ( ++ ) x y =
{
traversal = Ops.(x.traversal + y.traversal);
int_bytes = Ops.(x.int_bytes + y.int_bytes);
string_bytes = Ops.(x.string_bytes + y.string_bytes);
}
let node leaves =
let r = List.fold_left ( ++ ) micheline_zero leaves in
{r with traversal = Ops.(r.traversal + 1)}
let rec of_micheline (x : ('a, 'b) Micheline.node) =
match x with
| Micheline.Int (_loc, z) ->
let int_bytes = integer (Alpha_context.Script_int.of_zint z) in
{traversal = 1; int_bytes; string_bytes = 0}
| Micheline.String (_loc, s) ->
let string_bytes = String.length s in
{traversal = 1; int_bytes = 0; string_bytes}
| Micheline.Bytes (_loc, b) ->
let string_bytes = bytes b in
{traversal = 1; int_bytes = 0; string_bytes}
| Micheline.Prim (_loc, _prim, subterms, _annot) ->
node (List.map of_micheline subterms)
| Micheline.Seq (_loc, subterms) -> node (List.map of_micheline subterms)
let of_encoded_value :
type a. Alpha_context.t -> a Script_typed_ir.ty -> a -> micheline_size =
fun (type a) ctxt (ty : a Script_typed_ir.ty) (v : a) ->
let open Script_ir_translator in
let script_res = Lwt_main.run (unparse_data ctxt Optimized ty v) in
match script_res with
| Ok (node, _ctxt) -> of_micheline node
| Error _ -> Stdlib.failwith "sizeof: could not unparse"
(* ------------------------------------------------------------------------- *)
(* Sapling-related *)
let sapling_transaction_inputs : Alpha_context.Sapling.transaction -> t =
fun tx -> List.length tx.Tezos_sapling.Core.Client.UTXO.inputs
let sapling_transaction_outputs : Alpha_context.Sapling.transaction -> t =
fun tx -> List.length tx.Tezos_sapling.Core.Client.UTXO.outputs
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_alpha/lib_benchmarks_proto/size.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
-------------------------------------------------------------------------
encoding
-------------------------------------------------------------------------
can't be bothered to do it well
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Sapling-related | Copyright ( c ) 2021 - 2022 Nomadic Labs < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Protocol
type t = int
type micheline_size = {traversal : t; int_bytes : t; string_bytes : t}
let encoding : t Data_encoding.encoding =
let open Data_encoding in
conv (fun i -> Int64.of_int i) (fun l -> Int64.to_int l) int64
let micheline_size_encoding : micheline_size Data_encoding.encoding =
let open Data_encoding in
conv
(fun {traversal; int_bytes; string_bytes} ->
(traversal, int_bytes, string_bytes))
(fun (traversal, int_bytes, string_bytes) ->
{traversal; int_bytes; string_bytes})
(tup3 encoding encoding encoding)
let zero = 0
let one = 1
let add = ( + )
let sub = ( - )
let mul = ( * )
let div = ( / )
let max x y = if x < y then y else x
let min x y = if x < y then x else y
let rec pow x i = if i = 0 then 1 else x * pow x (i - 1)
module Ops = struct
let ( * ) = mul
let ( / ) = div
let ( + ) = add
let ( - ) = sub
let ( ** ) = pow
end
let compare = Stdlib.compare
let equal = ( = )
let lt = ( < )
let leq = ( <= )
let pp = Format.pp_print_int
let pp_micheline_size fmtr {traversal; int_bytes; string_bytes} =
Format.fprintf
fmtr
"@[{ traversal = %a;@; int_bytes = %a;@; string_bytes = %a;@,}@]"
pp
traversal
pp
int_bytes
pp
string_bytes
let show = string_of_int
let to_float = float_of_int
let of_float = int_of_float
let to_int x = x
let of_int x = x
let log2 x = Z.log2 (Z.of_int x)
let unit : t = 1
let integer (i : 'a Alpha_context.Script_int.num) : t =
Z.numbits (Alpha_context.Script_int.to_zint i) / 8
let string = String.length
let script_string = Alpha_context.Script_string.length
let bytes (b : Bytes.t) : t = Bytes.length b
let mutez (_tez : Alpha_context.Tez.tez) : t =
Up to now , mutez are stored on 8 bytes ( int64 ) .
8
let bool (_ : bool) : t = 1
let signature (_signature : Script_typed_ir.Script_signature.t) : t =
Script_typed_ir.Script_signature.size
let key_hash (_keyhash : Signature.public_key_hash) : t =
Signature.Public_key_hash.size
let public_key (public_key : Signature.public_key) : t =
Signature.Public_key.size public_key
let chain_id (_chain_id : Script_typed_ir.Script_chain_id.t) : t =
Script_typed_ir.Script_chain_id.size
let address (addr : Script_typed_ir.address) : t =
let entrypoint = addr.entrypoint in
Signature.Public_key_hash.size
+ String.length (Alpha_context.Entrypoint.to_string entrypoint)
let list (list : 'a Script_typed_ir.boxed_list) : t =
list.Script_typed_ir.length
let set (set : 'a Script_typed_ir.set) : t =
let res = Alpha_context.Script_int.to_int (Script_set.size set) in
match res with None -> assert false | Some x -> x
let map (map : ('a, 'b) Script_typed_ir.map) : t =
let res = Alpha_context.Script_int.to_int (Script_map.size map) in
match res with None -> assert false | Some x -> x
let timestamp (tstamp : Alpha_context.Script_timestamp.t) : t =
Z.numbits (Alpha_context.Script_timestamp.to_zint tstamp) / 8
Micheline / Michelson - related
let micheline_zero = {traversal = 0; int_bytes = 0; string_bytes = 0}
let ( ++ ) x y =
{
traversal = Ops.(x.traversal + y.traversal);
int_bytes = Ops.(x.int_bytes + y.int_bytes);
string_bytes = Ops.(x.string_bytes + y.string_bytes);
}
let node leaves =
let r = List.fold_left ( ++ ) micheline_zero leaves in
{r with traversal = Ops.(r.traversal + 1)}
let rec of_micheline (x : ('a, 'b) Micheline.node) =
match x with
| Micheline.Int (_loc, z) ->
let int_bytes = integer (Alpha_context.Script_int.of_zint z) in
{traversal = 1; int_bytes; string_bytes = 0}
| Micheline.String (_loc, s) ->
let string_bytes = String.length s in
{traversal = 1; int_bytes = 0; string_bytes}
| Micheline.Bytes (_loc, b) ->
let string_bytes = bytes b in
{traversal = 1; int_bytes = 0; string_bytes}
| Micheline.Prim (_loc, _prim, subterms, _annot) ->
node (List.map of_micheline subterms)
| Micheline.Seq (_loc, subterms) -> node (List.map of_micheline subterms)
let of_encoded_value :
type a. Alpha_context.t -> a Script_typed_ir.ty -> a -> micheline_size =
fun (type a) ctxt (ty : a Script_typed_ir.ty) (v : a) ->
let open Script_ir_translator in
let script_res = Lwt_main.run (unparse_data ctxt Optimized ty v) in
match script_res with
| Ok (node, _ctxt) -> of_micheline node
| Error _ -> Stdlib.failwith "sizeof: could not unparse"
let sapling_transaction_inputs : Alpha_context.Sapling.transaction -> t =
fun tx -> List.length tx.Tezos_sapling.Core.Client.UTXO.inputs
let sapling_transaction_outputs : Alpha_context.Sapling.transaction -> t =
fun tx -> List.length tx.Tezos_sapling.Core.Client.UTXO.outputs
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.