_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
11e774a7ba80a69f882ca0451b7c5e68e85edce9b7d7e763c543a8383487bb73
billstclair/trubanc-lisp
cookies.lisp
-*- Mode : LISP ; Syntax : COMMON - LISP ; Package : DRAKMA ; Base : 10 -*- $ Header : /usr / local / cvsrep / drakma / cookies.lisp , v 1.15 2008/01/14 01:57:01 edi Exp $ Copyright ( c ) 2006 - 2009 , Dr. . All rights reserved . ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :drakma) (defclass cookie () ((name :initarg :name :initform (cookie-error nil "A cookie must have a name.") :accessor cookie-name :documentation "The name of the cookie.") (value :initarg :value :initform "" :accessor cookie-value :documentation "The cookie's value.") (domain :initarg :domain :initform (cookie-error nil "A cookie must have a domain.") :accessor cookie-domain :documentation "The domain the cookie is valid for.") (path :initarg :path :initform "/" :accessor cookie-path :documentation "The path prefix the cookie is valid for.") (expires :initarg :expires :initform nil :accessor cookie-expires :documentation "When the cookie expires. A Lisp universal time or NIL.") (securep :initarg :securep :initform nil :accessor cookie-securep :documentation "Whether the cookie must only be transmitted over secure connections.") (http-only-p :initarg :http-only-p :initform nil :accessor cookie-http-only-p :documentation "Whether the cookie should not be accessible from Javascript. This is a Microsoft extension that has been implemented in Firefox as well. See <-us/library/ms533046.aspx>.")) (:documentation "Elements of this class represent HTTP cookies.")) (defun render-cookie-date (time) "Returns a string representation of the universal time TIME which can be used for cookie headers." (multiple-value-bind (second minute hour date month year weekday) (decode-universal-time time 0) (format nil "~A, ~2,'0d-~2,'0d-~4,'0d ~2,'0d:~2,'0d:~2,'0d GMT" (aref #("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun") weekday) date month year hour minute second))) (defmethod print-object ((cookie cookie) stream) "Prints a representation of COOKIE similar to a `Set-Cookie' header." (print-unreadable-object (cookie stream :type t) (with-slots (name value expires path domain securep http-only-p) cookie (format stream "~A~@[=~A~]~@[; expires=~A~]~@[; path=~A~]~@[; domain=~A~]~@[; secure~]~@[; HttpOnly~]" name (and (plusp (length value)) value) (and expires (render-cookie-date expires)) path domain securep http-only-p)))) (defun normalize-cookie-domain (domain) "Adds a dot at the beginning of the string DOMAIN unless there is already one." (cond ((starts-with-p domain ".") domain) (t (format nil ".~A" domain)))) (defun valid-cookie-domain-p (domain) "Checks if the string DOMAIN contains enough dots to be acceptable. If *ALLOW-DOTLESS-COOKIE-DOMAINS-P* is non-NIL, every domain name is considered acceptable." (or *allow-dotless-cookie-domains-p* (string-equal domain "localhost") (> (count #\. (normalize-cookie-domain domain) :test #'char=) 1))) (defun cookie-domain-matches (domain uri) "Checks if the domain DOMAIN \(a string) matches the \(PURI) URI URI." (ends-with-p (normalize-cookie-domain (uri-host uri)) (normalize-cookie-domain domain))) (defun send-cookie-p (cookie uri force-ssl) "Checks if the cookie COOKIE should be sent to the server depending on the \(PURI) URI URI and the value of FORCE-SSL \(as in HTTP-REQUEST)." (and ;; check domain (cookie-domain-matches (cookie-domain cookie) uri) ;; check path (starts-with-p (uri-path uri) (cookie-path cookie)) ;; check expiry date (let ((expires (cookie-expires cookie))) (or (null expires) (> expires (get-universal-time)))) ;; check if connection must be secure (or (null (cookie-securep cookie)) force-ssl (eq (uri-scheme uri) :https)))) (defun check-cookie (cookie) "Checks if the slots of the COOKIE object COOKIE have valid values and raises a corresponding error of type COOKIE-ERROR otherwise." (with-slots (name value domain path expires) cookie (unless (and (stringp name) (plusp (length name))) (cookie-error cookie "Cookie name ~S must be a non-empty string." name)) (unless (stringp value) (cookie-error cookie "Cookie value ~S must be a non-empty string." value)) (unless (valid-cookie-domain-p domain) (cookie-error cookie "Invalid cookie domain ~S." domain)) (unless (and (stringp path) (plusp (length path))) (cookie-error cookie "Cookie path ~S must be a non-empty string." path)) (unless (or (null expires) (and (integerp expires) (plusp expires))) (cookie-error cookie "Cookie expiry ~S should have been NIL or a universal time." expires)))) (defmethod initialize-instance :after ((cookie cookie) &rest initargs) "Check cookie validity after creation." (declare (ignore initargs)) (check-cookie cookie)) (defmethod (setf cookie-name) :after (new-value (cookie cookie)) "Check cookie validity after name change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-value) :after (new-value (cookie cookie)) "Check cookie validity after value change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-domain) :after (new-value (cookie cookie)) "Check cookie validity after domain change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-path) :after (new-value (cookie cookie)) "Check cookie validity after path change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-expires) :after (new-value (cookie cookie)) "Check cookie validity after expiry change." (declare (ignore new-value)) (check-cookie cookie)) (defun cookie= (cookie1 cookie2) "Returns true if the cookies COOKIE1 and COOKIE2 are equal. Two cookies are considered to be equal if name and path are equal." (and (string= (cookie-name cookie1) (cookie-name cookie2)) (string= (cookie-path cookie1) (cookie-path cookie2)))) (defclass cookie-jar () ((cookies :initarg :cookies :initform nil :accessor cookie-jar-cookies :documentation "A list of the cookies in this cookie jar.")) (:documentation "A COOKIE-JAR object is a collection of cookies.")) (defmethod print-object ((cookie-jar cookie-jar) stream) "Print a cookie jar, showing the number of cookies it contains." (print-unreadable-object (cookie-jar stream :type t :identity t) (format stream "(with ~A cookie~:P)" (length (cookie-jar-cookies cookie-jar))))) (defun parse-cookie-date (string) "Parses a cookie expiry date and returns it as a Lisp universal time. Currently understands the following formats: \"Wed, 06-Feb-2008 21:01:38 GMT\" \"Wed, 06-Feb-08 21:01:38 GMT\" \"Tue Feb 13 08:00:00 2007 GMT\" \"Wednesday, 07-February-2027 08:55:23 GMT\" \"Wed, 07-02-2017 10:34:45 GMT\" Instead of \"GMT\" time zone abbreviations like \"CEST\" and UTC offsets like \"GMT-01:30\" are also allowed." ;; it seems like everybody and their sister invents their own format ;; for this, so (as there's no real standard for it) we'll have to ;; make this function more flexible once we come across something ;; new; as an alternative we could use net-telent-date, but it also ;; fails to parse some of the stuff you encounter in the wild; or we could try to employ CL - PPCRE , but that 'd add a new dependency ;; without making this code much cleaner (handler-case (let* ((last-space-pos (or (position #\Space string :test #'char= :from-end t) (cookie-date-parse-error "Can't parse cookie date ~S, no space found." string))) (time-zone-string (subseq string (1+ last-space-pos))) (time-zone (interpret-as-time-zone time-zone-string)) second minute hour day month year) (dolist (part (rest (split-string (subseq string 0 last-space-pos)))) (when (and day month) (cond ((every #'digit-char-p part) (when year (cookie-date-parse-error "Can't parse cookie date ~S, confused by ~S part." string part)) (setq year (parse-integer part))) ((= (count #\: part :test #'char=) 2) (let ((h-m-s (mapcar #'safe-parse-integer (split-string part ":")))) (setq hour (first h-m-s) minute (second h-m-s) second (third h-m-s)))) (t (cookie-date-parse-error "Can't parse cookie date ~S, confused by ~S part." string part)))) (cond ((null day) (unless (setq day (safe-parse-integer part)) (setq month (interpret-as-month part)))) ((null month) (setq month (interpret-as-month part))))) (unless (and second minute hour day month year) (cookie-date-parse-error "Can't parse cookie date ~S, component missing." string)) (when (< year 100) (setq year (+ year 2000))) (encode-universal-time second minute hour day month year time-zone)) (cookie-date-parse-error (condition) (cond (*ignore-unparseable-cookie-dates-p* (drakma-warn "~A" condition) nil) (t (error condition)))))) (defun parse-set-cookie (string) "Parses the `Set-Cookie' header line STRING and returns a list of three-element lists where each one contains the name of the cookie, the value of the cookie, and an attribute/value list for the optional cookie parameters." (with-sequence-from-string (stream string) (loop with *current-error-message* = (format nil "While parsing cookie header ~S:" string) for first = t then nil for next = (and (skip-whitespace stream) (or first (assert-char stream #\,)) (skip-whitespace stream) (skip-more-commas stream)) for name/value = (and next (read-name-value-pair stream :cookie-syntax t)) for parameters = (and name/value (read-name-value-pairs stream :value-required-p nil :cookie-syntax t)) while name/value collect (list (car name/value) (cdr name/value) parameters)))) (defun get-cookies (headers uri) "Returns a list of COOKIE objects corresponding to the `Set-Cookie' header as found in HEADERS \(an alist as returned by HTTP-REQUEST). Collects only cookies which match the domain of the \(PURI) URI URI." (loop with set-cookie-header = (header-value :set-cookie headers) with parsed-cookies = (and set-cookie-header (parse-set-cookie set-cookie-header)) for (name value parameters) in parsed-cookies for expires = (parameter-value "expires" parameters) for domain = (or (parameter-value "domain" parameters) (uri-host uri)) when (and (valid-cookie-domain-p domain) (cookie-domain-matches domain uri)) collect (make-instance 'cookie :name name :value value :path (or (parameter-value "path" parameters) (uri-path uri) "/") :expires (and expires (plusp (length expires)) (parse-cookie-date expires)) :domain domain :securep (not (not (parameter-present-p "secure" parameters))) :http-only-p (not (not (parameter-present-p "HttpOnly" parameters)))))) (defun update-cookies (new-cookies cookie-jar) "Updates the cookies in COOKIE-JAR by replacing those which are equal to a cookie in \(the list) NEW-COOKIES with the corresponding `new' cookie and adding those which are really new." (setf (cookie-jar-cookies cookie-jar) (let ((updated-cookies (loop for old-cookie in (cookie-jar-cookies cookie-jar) collect (or (find old-cookie new-cookies :test #'cookie=) old-cookie)))) (union updated-cookies (set-difference new-cookies updated-cookies)))) cookie-jar) (defun delete-old-cookies (cookie-jar) "Removes all cookies from COOKIE-JAR which have either expired or which don't have an expiry date." (setf (cookie-jar-cookies cookie-jar) (loop with now = (get-universal-time) for cookie in (cookie-jar-cookies cookie-jar) for expires = (cookie-expires cookie) unless (or (null expires) (< expires now)) collect cookie)) cookie-jar)
null
https://raw.githubusercontent.com/billstclair/trubanc-lisp/5436d2eca5b1ed10bc47eec7080f6cb90f98ca65/systems/drakma-1.0.0/cookies.lisp
lisp
Syntax : COMMON - LISP ; Package : DRAKMA ; Base : 10 -*- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. check domain check path check expiry date check if connection must be secure it seems like everybody and their sister invents their own format for this, so (as there's no real standard for it) we'll have to make this function more flexible once we come across something new; as an alternative we could use net-telent-date, but it also fails to parse some of the stuff you encounter in the wild; or we without making this code much cleaner
$ Header : /usr / local / cvsrep / drakma / cookies.lisp , v 1.15 2008/01/14 01:57:01 edi Exp $ Copyright ( c ) 2006 - 2009 , Dr. . All rights reserved . DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , (in-package :drakma) (defclass cookie () ((name :initarg :name :initform (cookie-error nil "A cookie must have a name.") :accessor cookie-name :documentation "The name of the cookie.") (value :initarg :value :initform "" :accessor cookie-value :documentation "The cookie's value.") (domain :initarg :domain :initform (cookie-error nil "A cookie must have a domain.") :accessor cookie-domain :documentation "The domain the cookie is valid for.") (path :initarg :path :initform "/" :accessor cookie-path :documentation "The path prefix the cookie is valid for.") (expires :initarg :expires :initform nil :accessor cookie-expires :documentation "When the cookie expires. A Lisp universal time or NIL.") (securep :initarg :securep :initform nil :accessor cookie-securep :documentation "Whether the cookie must only be transmitted over secure connections.") (http-only-p :initarg :http-only-p :initform nil :accessor cookie-http-only-p :documentation "Whether the cookie should not be accessible from Javascript. This is a Microsoft extension that has been implemented in Firefox as well. See <-us/library/ms533046.aspx>.")) (:documentation "Elements of this class represent HTTP cookies.")) (defun render-cookie-date (time) "Returns a string representation of the universal time TIME which can be used for cookie headers." (multiple-value-bind (second minute hour date month year weekday) (decode-universal-time time 0) (format nil "~A, ~2,'0d-~2,'0d-~4,'0d ~2,'0d:~2,'0d:~2,'0d GMT" (aref #("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun") weekday) date month year hour minute second))) (defmethod print-object ((cookie cookie) stream) "Prints a representation of COOKIE similar to a `Set-Cookie' header." (print-unreadable-object (cookie stream :type t) (with-slots (name value expires path domain securep http-only-p) cookie (format stream "~A~@[=~A~]~@[; expires=~A~]~@[; path=~A~]~@[; domain=~A~]~@[; secure~]~@[; HttpOnly~]" name (and (plusp (length value)) value) (and expires (render-cookie-date expires)) path domain securep http-only-p)))) (defun normalize-cookie-domain (domain) "Adds a dot at the beginning of the string DOMAIN unless there is already one." (cond ((starts-with-p domain ".") domain) (t (format nil ".~A" domain)))) (defun valid-cookie-domain-p (domain) "Checks if the string DOMAIN contains enough dots to be acceptable. If *ALLOW-DOTLESS-COOKIE-DOMAINS-P* is non-NIL, every domain name is considered acceptable." (or *allow-dotless-cookie-domains-p* (string-equal domain "localhost") (> (count #\. (normalize-cookie-domain domain) :test #'char=) 1))) (defun cookie-domain-matches (domain uri) "Checks if the domain DOMAIN \(a string) matches the \(PURI) URI URI." (ends-with-p (normalize-cookie-domain (uri-host uri)) (normalize-cookie-domain domain))) (defun send-cookie-p (cookie uri force-ssl) "Checks if the cookie COOKIE should be sent to the server depending on the \(PURI) URI URI and the value of FORCE-SSL \(as in HTTP-REQUEST)." (cookie-domain-matches (cookie-domain cookie) uri) (starts-with-p (uri-path uri) (cookie-path cookie)) (let ((expires (cookie-expires cookie))) (or (null expires) (> expires (get-universal-time)))) (or (null (cookie-securep cookie)) force-ssl (eq (uri-scheme uri) :https)))) (defun check-cookie (cookie) "Checks if the slots of the COOKIE object COOKIE have valid values and raises a corresponding error of type COOKIE-ERROR otherwise." (with-slots (name value domain path expires) cookie (unless (and (stringp name) (plusp (length name))) (cookie-error cookie "Cookie name ~S must be a non-empty string." name)) (unless (stringp value) (cookie-error cookie "Cookie value ~S must be a non-empty string." value)) (unless (valid-cookie-domain-p domain) (cookie-error cookie "Invalid cookie domain ~S." domain)) (unless (and (stringp path) (plusp (length path))) (cookie-error cookie "Cookie path ~S must be a non-empty string." path)) (unless (or (null expires) (and (integerp expires) (plusp expires))) (cookie-error cookie "Cookie expiry ~S should have been NIL or a universal time." expires)))) (defmethod initialize-instance :after ((cookie cookie) &rest initargs) "Check cookie validity after creation." (declare (ignore initargs)) (check-cookie cookie)) (defmethod (setf cookie-name) :after (new-value (cookie cookie)) "Check cookie validity after name change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-value) :after (new-value (cookie cookie)) "Check cookie validity after value change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-domain) :after (new-value (cookie cookie)) "Check cookie validity after domain change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-path) :after (new-value (cookie cookie)) "Check cookie validity after path change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-expires) :after (new-value (cookie cookie)) "Check cookie validity after expiry change." (declare (ignore new-value)) (check-cookie cookie)) (defun cookie= (cookie1 cookie2) "Returns true if the cookies COOKIE1 and COOKIE2 are equal. Two cookies are considered to be equal if name and path are equal." (and (string= (cookie-name cookie1) (cookie-name cookie2)) (string= (cookie-path cookie1) (cookie-path cookie2)))) (defclass cookie-jar () ((cookies :initarg :cookies :initform nil :accessor cookie-jar-cookies :documentation "A list of the cookies in this cookie jar.")) (:documentation "A COOKIE-JAR object is a collection of cookies.")) (defmethod print-object ((cookie-jar cookie-jar) stream) "Print a cookie jar, showing the number of cookies it contains." (print-unreadable-object (cookie-jar stream :type t :identity t) (format stream "(with ~A cookie~:P)" (length (cookie-jar-cookies cookie-jar))))) (defun parse-cookie-date (string) "Parses a cookie expiry date and returns it as a Lisp universal time. Currently understands the following formats: \"Wed, 06-Feb-2008 21:01:38 GMT\" \"Wed, 06-Feb-08 21:01:38 GMT\" \"Tue Feb 13 08:00:00 2007 GMT\" \"Wednesday, 07-February-2027 08:55:23 GMT\" \"Wed, 07-02-2017 10:34:45 GMT\" Instead of \"GMT\" time zone abbreviations like \"CEST\" and UTC offsets like \"GMT-01:30\" are also allowed." could try to employ CL - PPCRE , but that 'd add a new dependency (handler-case (let* ((last-space-pos (or (position #\Space string :test #'char= :from-end t) (cookie-date-parse-error "Can't parse cookie date ~S, no space found." string))) (time-zone-string (subseq string (1+ last-space-pos))) (time-zone (interpret-as-time-zone time-zone-string)) second minute hour day month year) (dolist (part (rest (split-string (subseq string 0 last-space-pos)))) (when (and day month) (cond ((every #'digit-char-p part) (when year (cookie-date-parse-error "Can't parse cookie date ~S, confused by ~S part." string part)) (setq year (parse-integer part))) ((= (count #\: part :test #'char=) 2) (let ((h-m-s (mapcar #'safe-parse-integer (split-string part ":")))) (setq hour (first h-m-s) minute (second h-m-s) second (third h-m-s)))) (t (cookie-date-parse-error "Can't parse cookie date ~S, confused by ~S part." string part)))) (cond ((null day) (unless (setq day (safe-parse-integer part)) (setq month (interpret-as-month part)))) ((null month) (setq month (interpret-as-month part))))) (unless (and second minute hour day month year) (cookie-date-parse-error "Can't parse cookie date ~S, component missing." string)) (when (< year 100) (setq year (+ year 2000))) (encode-universal-time second minute hour day month year time-zone)) (cookie-date-parse-error (condition) (cond (*ignore-unparseable-cookie-dates-p* (drakma-warn "~A" condition) nil) (t (error condition)))))) (defun parse-set-cookie (string) "Parses the `Set-Cookie' header line STRING and returns a list of three-element lists where each one contains the name of the cookie, the value of the cookie, and an attribute/value list for the optional cookie parameters." (with-sequence-from-string (stream string) (loop with *current-error-message* = (format nil "While parsing cookie header ~S:" string) for first = t then nil for next = (and (skip-whitespace stream) (or first (assert-char stream #\,)) (skip-whitespace stream) (skip-more-commas stream)) for name/value = (and next (read-name-value-pair stream :cookie-syntax t)) for parameters = (and name/value (read-name-value-pairs stream :value-required-p nil :cookie-syntax t)) while name/value collect (list (car name/value) (cdr name/value) parameters)))) (defun get-cookies (headers uri) "Returns a list of COOKIE objects corresponding to the `Set-Cookie' header as found in HEADERS \(an alist as returned by HTTP-REQUEST). Collects only cookies which match the domain of the \(PURI) URI URI." (loop with set-cookie-header = (header-value :set-cookie headers) with parsed-cookies = (and set-cookie-header (parse-set-cookie set-cookie-header)) for (name value parameters) in parsed-cookies for expires = (parameter-value "expires" parameters) for domain = (or (parameter-value "domain" parameters) (uri-host uri)) when (and (valid-cookie-domain-p domain) (cookie-domain-matches domain uri)) collect (make-instance 'cookie :name name :value value :path (or (parameter-value "path" parameters) (uri-path uri) "/") :expires (and expires (plusp (length expires)) (parse-cookie-date expires)) :domain domain :securep (not (not (parameter-present-p "secure" parameters))) :http-only-p (not (not (parameter-present-p "HttpOnly" parameters)))))) (defun update-cookies (new-cookies cookie-jar) "Updates the cookies in COOKIE-JAR by replacing those which are equal to a cookie in \(the list) NEW-COOKIES with the corresponding `new' cookie and adding those which are really new." (setf (cookie-jar-cookies cookie-jar) (let ((updated-cookies (loop for old-cookie in (cookie-jar-cookies cookie-jar) collect (or (find old-cookie new-cookies :test #'cookie=) old-cookie)))) (union updated-cookies (set-difference new-cookies updated-cookies)))) cookie-jar) (defun delete-old-cookies (cookie-jar) "Removes all cookies from COOKIE-JAR which have either expired or which don't have an expiry date." (setf (cookie-jar-cookies cookie-jar) (loop with now = (get-universal-time) for cookie in (cookie-jar-cookies cookie-jar) for expires = (cookie-expires cookie) unless (or (null expires) (< expires now)) collect cookie)) cookie-jar)
50aff8ae6a0d0d5c045476efc935c864431c85becfdd82d04d2611f237b18f44
ekmett/rounded
Unsafe.hs
# LANGUAGE ForeignFunctionInterface # ----------------------------------------------------------------------------- -- | -- Module : Numeric.MPFR.Raw.Unsafe Copyright : ( C ) 2012 - 2014 , ( C ) 2013 - 2019 -- License : BSD3 Maintainer : < > -- Stability : experimental -- Portability : non-portable -- This module contains FFI imports as unsafe ccalls . ---------------------------------------------------------------------------- module Numeric.MPFR.Raw.Unsafe where import Foreign.C (CInt(..), CIntMax(..), CSize(..), CChar(..), CLong(..)) import GHC.Exts (Ptr) import Numeric.LongDouble (LongDouble) import Numeric.GMP.Types (MPZ, MPQ) import Numeric.MPFR.Types foreign import ccall unsafe "mpfr_init2" mpfr_init2 :: Ptr MPFR -> MPFRPrec -> IO () foreign import ccall unsafe "mpfr_clear" mpfr_clear :: Ptr MPFR -> IO () foreign import ccall unsafe "mpfr_sgn" mpfr_sgn :: Ptr MPFR -> IO CInt foreign import ccall unsafe "mpfr_get_d" mpfr_get_d :: Ptr MPFR -> MPFRRnd -> IO Double foreign import ccall unsafe "wrapped_mpfr_get_z" wrapped_mpfr_get_z :: Ptr MPZ -> Ptr MPFR -> MPFRRnd -> Ptr CInt -> IO CInt foreign import ccall unsafe "mpfr_get_str" mpfr_get_str :: Ptr CChar -> Ptr MPFRExp -> Int -> CSize -> Ptr MPFR -> MPFRRnd -> IO (Ptr CChar) foreign import ccall unsafe "mpfr_free_str" mpfr_free_str :: Ptr CChar -> IO () foreign import ccall unsafe "mpfr_set_z" mpfr_set_z :: Ptr MPFR -> Ptr MPZ -> MPFRRnd -> IO CInt foreign import ccall unsafe "__gmpfr_set_sj" mpfr_set_sj :: Ptr MPFR -> CIntMax -> MPFRRnd -> IO CInt foreign import ccall unsafe "mpfr_set_q" mpfr_set_q :: Ptr MPFR -> Ptr MPQ -> MPFRRnd -> IO CInt foreign import ccall unsafe "mpfr_set_d" mpfr_set_d :: Ptr MPFR -> Double -> MPFRRnd -> IO CInt foreign import ccall unsafe "wrapped_mpfr_get_z_2exp" wrapped_mpfr_get_z_2exp :: Ptr MPZ -> Ptr MPFR -> Ptr CInt -> IO MPFRExp foreign import ccall unsafe "mpfr_set_z_2exp" mpfr_set_z_2exp :: Ptr MPFR -> Ptr MPZ -> MPFRExp -> MPFRRnd -> IO CInt type Test = Ptr MPFR -> IO CInt foreign import ccall unsafe "mpfr_inf_p" mpfr_inf_p :: Test foreign import ccall unsafe "mpfr_integer_p" mpfr_integer_p :: Test foreign import ccall unsafe "mpfr_nan_p" mpfr_nan_p :: Test foreign import ccall unsafe "mpfr_number_p" mpfr_number_p :: Test foreign import ccall unsafe "mpfr_regular_p" mpfr_regular_p :: Test foreign import ccall unsafe "mpfr_signbit" mpfr_signbit :: Test foreign import ccall unsafe "mpfr_zero_p" mpfr_zero_p :: Test type Fits = Ptr MPFR -> MPFRRnd -> IO CInt foreign import ccall unsafe "mpfr_fits_intmax_p" mpfr_fits_intmax_p :: Fits foreign import ccall unsafe "mpfr_fits_sint_p" mpfr_fits_sint_p :: Fits foreign import ccall unsafe "mpfr_fits_slong_p" mpfr_fits_slong_p :: Fits foreign import ccall unsafe "mpfr_fits_sshort_p" mpfr_fits_sshort_p :: Fits foreign import ccall unsafe "mpfr_fits_uintmax_p" mpfr_fits_uintmax_p :: Fits foreign import ccall unsafe "mpfr_fits_uint_p" mpfr_fits_uint_p :: Fits foreign import ccall unsafe "mpfr_fits_ulong_p" mpfr_fits_ulong_p :: Fits foreign import ccall unsafe "mpfr_fits_ushort_p" mpfr_fits_ushort_p :: Fits type Constant = Ptr MPFR -> MPFRRnd -> IO CInt foreign import ccall unsafe "mpfr_const_pi" mpfr_const_pi :: Constant foreign import ccall unsafe "mpfr_const_log2" mpfr_const_log2 :: Constant foreign import ccall unsafe "mpfr_const_euler" mpfr_const_euler :: Constant foreign import ccall unsafe "mpfr_const_catalan" mpfr_const_catalan :: Constant type Unary = Ptr MPFR -> Ptr MPFR -> MPFRRnd -> IO CInt foreign import ccall unsafe "mpfr_abs" mpfr_abs :: Unary foreign import ccall unsafe "mpfr_acos" mpfr_acos :: Unary foreign import ccall unsafe "mpfr_acosh" mpfr_acosh :: Unary foreign import ccall unsafe "mpfr_ai" mpfr_ai :: Unary foreign import ccall unsafe "mpfr_asin" mpfr_asin :: Unary foreign import ccall unsafe "mpfr_asinh" mpfr_asinh :: Unary foreign import ccall unsafe "mpfr_atan" mpfr_atan :: Unary foreign import ccall unsafe "mpfr_atanh" mpfr_atanh :: Unary foreign import ccall unsafe "mpfr_cbrt" mpfr_cbrt :: Unary foreign import ccall unsafe "mpfr_cos" mpfr_cos :: Unary foreign import ccall unsafe "mpfr_cosh" mpfr_cosh :: Unary foreign import ccall unsafe "mpfr_cot" mpfr_cot :: Unary foreign import ccall unsafe "mpfr_coth" mpfr_coth :: Unary foreign import ccall unsafe "mpfr_csc" mpfr_csc :: Unary foreign import ccall unsafe "mpfr_csch" mpfr_csch :: Unary foreign import ccall unsafe "mpfr_digamma" mpfr_digamma :: Unary foreign import ccall unsafe "mpfr_eint" mpfr_eint :: Unary foreign import ccall unsafe "mpfr_erf" mpfr_erf :: Unary foreign import ccall unsafe "mpfr_erfc" mpfr_erfc :: Unary foreign import ccall unsafe "mpfr_exp" mpfr_exp :: Unary foreign import ccall unsafe "mpfr_exp10" mpfr_exp10 :: Unary foreign import ccall unsafe "mpfr_exp2" mpfr_exp2 :: Unary foreign import ccall unsafe "mpfr_expm1" mpfr_expm1 :: Unary foreign import ccall unsafe "mpfr_frac" mpfr_frac :: Unary foreign import ccall unsafe "mpfr_gamma" mpfr_gamma :: Unary foreign import ccall unsafe "mpfr_j0" mpfr_j0 :: Unary foreign import ccall unsafe "mpfr_j1" mpfr_j1 :: Unary foreign import ccall unsafe "mpfr_li2" mpfr_li2 :: Unary foreign import ccall unsafe "mpfr_lngamma" mpfr_lngamma :: Unary foreign import ccall unsafe "mpfr_log" mpfr_log :: Unary foreign import ccall unsafe "mpfr_log10" mpfr_log10 :: Unary foreign import ccall unsafe "mpfr_log1p" mpfr_log1p :: Unary foreign import ccall unsafe "mpfr_log2" mpfr_log2 :: Unary foreign import ccall unsafe "mpfr_neg" mpfr_neg :: Unary foreign import ccall unsafe "mpfr_rec_sqrt" mpfr_rec_sqrt :: Unary foreign import ccall unsafe "mpfr_rint" mpfr_rint :: Unary foreign import ccall unsafe "mpfr_rint_ceil" mpfr_rint_ceil :: Unary foreign import ccall unsafe "mpfr_rint_floor" mpfr_rint_floor :: Unary foreign import ccall unsafe "mpfr_rint_round" mpfr_rint_round :: Unary foreign import ccall unsafe "mpfr_rint_roundeven" mpfr_rint_roundeven :: Unary foreign import ccall unsafe "mpfr_rint_trunc" mpfr_rint_trunc :: Unary foreign import ccall unsafe "mpfr_sec" mpfr_sec :: Unary foreign import ccall unsafe "mpfr_sech" mpfr_sech :: Unary foreign import ccall unsafe "mpfr_set" mpfr_set :: Unary foreign import ccall unsafe "mpfr_sin" mpfr_sin :: Unary foreign import ccall unsafe "mpfr_sinh" mpfr_sinh :: Unary foreign import ccall unsafe "mpfr_sqr" mpfr_sqr :: Unary foreign import ccall unsafe "mpfr_sqrt" mpfr_sqrt :: Unary foreign import ccall unsafe "mpfr_tan" mpfr_tan :: Unary foreign import ccall unsafe "mpfr_tanh" mpfr_tanh :: Unary foreign import ccall unsafe "mpfr_y0" mpfr_y0 :: Unary foreign import ccall unsafe "mpfr_y1" mpfr_y1 :: Unary foreign import ccall unsafe "mpfr_zeta" mpfr_zeta :: Unary type Unary' = Ptr MPFR -> Ptr MPFR -> IO CInt foreign import ccall unsafe "mpfr_ceil" mpfr_ceil :: Unary' foreign import ccall unsafe "mpfr_floor" mpfr_floor :: Unary' foreign import ccall unsafe "mpfr_trunc" mpfr_trunc :: Unary' type Binary = Ptr MPFR -> Ptr MPFR -> Ptr MPFR -> MPFRRnd -> IO CInt foreign import ccall unsafe "mpfr_add" mpfr_add :: Binary foreign import ccall unsafe "mpfr_agm" mpfr_agm :: Binary foreign import ccall unsafe "mpfr_atan2" mpfr_atan2 :: Binary foreign import ccall unsafe "mpfr_copysign" mpfr_copysign :: Binary foreign import ccall unsafe "mpfr_dim" mpfr_dim :: Binary foreign import ccall unsafe "mpfr_div" mpfr_div :: Binary foreign import ccall unsafe "mpfr_fmod" mpfr_fmod :: Binary foreign import ccall unsafe "mpfr_hypot" mpfr_hypot :: Binary foreign import ccall unsafe "mpfr_max" mpfr_max :: Binary foreign import ccall unsafe "mpfr_min" mpfr_min :: Binary foreign import ccall unsafe "mpfr_mul" mpfr_mul :: Binary foreign import ccall unsafe "mpfr_pow" mpfr_pow :: Binary foreign import ccall unsafe "mpfr_sub" mpfr_sub :: Binary foreign import ccall unsafe "mpfr_beta" mpfr_beta :: Binary foreign import ccall unsafe "mpfr_gamma_inc" mpfr_gamma_inc :: Binary type DualOutput = Ptr MPFR -> Ptr MPFR -> Ptr MPFR -> MPFRRnd -> IO CInt foreign import ccall unsafe "mpfr_modf" mpfr_modf :: DualOutput foreign import ccall unsafe "mpfr_sin_cos" mpfr_sin_cos :: DualOutput foreign import ccall unsafe "mpfr_sinh_cosh" mpfr_sinh_cosh :: DualOutput type Comparison = Ptr MPFR -> Ptr MPFR -> IO CInt foreign import ccall unsafe "mpfr_cmp" mpfr_cmp :: Comparison foreign import ccall unsafe "mpfr_equal_p" mpfr_equal_p :: Comparison foreign import ccall unsafe "mpfr_greaterequal_p" mpfr_greaterequal_p :: Comparison foreign import ccall unsafe "mpfr_greater_p" mpfr_greater_p :: Comparison foreign import ccall unsafe "mpfr_lessequal_p" mpfr_lessequal_p :: Comparison foreign import ccall unsafe "mpfr_lessgreater_p" mpfr_lessgreater_p :: Comparison foreign import ccall unsafe "mpfr_less_p" mpfr_less_p :: Comparison foreign import ccall unsafe "mpfr_unordered_p" mpfr_unordered_p :: Comparison foreign import ccall unsafe "mpfr_nextabove" mpfr_nextabove :: Ptr MPFR -> IO () foreign import ccall unsafe "mpfr_nextbelow" mpfr_nextbelow :: Ptr MPFR -> IO () foreign import ccall unsafe "wrapped_mpfr_get_ld" wrapped_mpfr_get_ld :: Ptr LongDouble -> Ptr MPFR -> MPFRRnd -> Ptr CInt -> IO CInt foreign import ccall unsafe "wrapped_mpfr_get_ld_2exp" wrapped_mpfr_get_ld_2exp :: Ptr LongDouble -> Ptr CLong -> Ptr MPFR -> MPFRRnd -> Ptr CInt -> IO CInt foreign import ccall unsafe "wrapped_mpfr_set_ld" wrapped_mpfr_set_ld :: Ptr MPFR -> Ptr LongDouble -> MPFRRnd -> Ptr CInt -> IO CInt foreign import ccall unsafe "wrapped_mpfr_cmp_ld" wrapped_mpfr_cmp_ld :: Ptr MPFR -> Ptr LongDouble -> IO CInt
null
https://raw.githubusercontent.com/ekmett/rounded/c468acd3933c9fdcbb1bb66c53ab203f1ea41f0a/src/Numeric/MPFR/Raw/Unsafe.hs
haskell
--------------------------------------------------------------------------- | Module : Numeric.MPFR.Raw.Unsafe License : BSD3 Stability : experimental Portability : non-portable --------------------------------------------------------------------------
# LANGUAGE ForeignFunctionInterface # Copyright : ( C ) 2012 - 2014 , ( C ) 2013 - 2019 Maintainer : < > This module contains FFI imports as unsafe ccalls . module Numeric.MPFR.Raw.Unsafe where import Foreign.C (CInt(..), CIntMax(..), CSize(..), CChar(..), CLong(..)) import GHC.Exts (Ptr) import Numeric.LongDouble (LongDouble) import Numeric.GMP.Types (MPZ, MPQ) import Numeric.MPFR.Types foreign import ccall unsafe "mpfr_init2" mpfr_init2 :: Ptr MPFR -> MPFRPrec -> IO () foreign import ccall unsafe "mpfr_clear" mpfr_clear :: Ptr MPFR -> IO () foreign import ccall unsafe "mpfr_sgn" mpfr_sgn :: Ptr MPFR -> IO CInt foreign import ccall unsafe "mpfr_get_d" mpfr_get_d :: Ptr MPFR -> MPFRRnd -> IO Double foreign import ccall unsafe "wrapped_mpfr_get_z" wrapped_mpfr_get_z :: Ptr MPZ -> Ptr MPFR -> MPFRRnd -> Ptr CInt -> IO CInt foreign import ccall unsafe "mpfr_get_str" mpfr_get_str :: Ptr CChar -> Ptr MPFRExp -> Int -> CSize -> Ptr MPFR -> MPFRRnd -> IO (Ptr CChar) foreign import ccall unsafe "mpfr_free_str" mpfr_free_str :: Ptr CChar -> IO () foreign import ccall unsafe "mpfr_set_z" mpfr_set_z :: Ptr MPFR -> Ptr MPZ -> MPFRRnd -> IO CInt foreign import ccall unsafe "__gmpfr_set_sj" mpfr_set_sj :: Ptr MPFR -> CIntMax -> MPFRRnd -> IO CInt foreign import ccall unsafe "mpfr_set_q" mpfr_set_q :: Ptr MPFR -> Ptr MPQ -> MPFRRnd -> IO CInt foreign import ccall unsafe "mpfr_set_d" mpfr_set_d :: Ptr MPFR -> Double -> MPFRRnd -> IO CInt foreign import ccall unsafe "wrapped_mpfr_get_z_2exp" wrapped_mpfr_get_z_2exp :: Ptr MPZ -> Ptr MPFR -> Ptr CInt -> IO MPFRExp foreign import ccall unsafe "mpfr_set_z_2exp" mpfr_set_z_2exp :: Ptr MPFR -> Ptr MPZ -> MPFRExp -> MPFRRnd -> IO CInt type Test = Ptr MPFR -> IO CInt foreign import ccall unsafe "mpfr_inf_p" mpfr_inf_p :: Test foreign import ccall unsafe "mpfr_integer_p" mpfr_integer_p :: Test foreign import ccall unsafe "mpfr_nan_p" mpfr_nan_p :: Test foreign import ccall unsafe "mpfr_number_p" mpfr_number_p :: Test foreign import ccall unsafe "mpfr_regular_p" mpfr_regular_p :: Test foreign import ccall unsafe "mpfr_signbit" mpfr_signbit :: Test foreign import ccall unsafe "mpfr_zero_p" mpfr_zero_p :: Test type Fits = Ptr MPFR -> MPFRRnd -> IO CInt foreign import ccall unsafe "mpfr_fits_intmax_p" mpfr_fits_intmax_p :: Fits foreign import ccall unsafe "mpfr_fits_sint_p" mpfr_fits_sint_p :: Fits foreign import ccall unsafe "mpfr_fits_slong_p" mpfr_fits_slong_p :: Fits foreign import ccall unsafe "mpfr_fits_sshort_p" mpfr_fits_sshort_p :: Fits foreign import ccall unsafe "mpfr_fits_uintmax_p" mpfr_fits_uintmax_p :: Fits foreign import ccall unsafe "mpfr_fits_uint_p" mpfr_fits_uint_p :: Fits foreign import ccall unsafe "mpfr_fits_ulong_p" mpfr_fits_ulong_p :: Fits foreign import ccall unsafe "mpfr_fits_ushort_p" mpfr_fits_ushort_p :: Fits type Constant = Ptr MPFR -> MPFRRnd -> IO CInt foreign import ccall unsafe "mpfr_const_pi" mpfr_const_pi :: Constant foreign import ccall unsafe "mpfr_const_log2" mpfr_const_log2 :: Constant foreign import ccall unsafe "mpfr_const_euler" mpfr_const_euler :: Constant foreign import ccall unsafe "mpfr_const_catalan" mpfr_const_catalan :: Constant type Unary = Ptr MPFR -> Ptr MPFR -> MPFRRnd -> IO CInt foreign import ccall unsafe "mpfr_abs" mpfr_abs :: Unary foreign import ccall unsafe "mpfr_acos" mpfr_acos :: Unary foreign import ccall unsafe "mpfr_acosh" mpfr_acosh :: Unary foreign import ccall unsafe "mpfr_ai" mpfr_ai :: Unary foreign import ccall unsafe "mpfr_asin" mpfr_asin :: Unary foreign import ccall unsafe "mpfr_asinh" mpfr_asinh :: Unary foreign import ccall unsafe "mpfr_atan" mpfr_atan :: Unary foreign import ccall unsafe "mpfr_atanh" mpfr_atanh :: Unary foreign import ccall unsafe "mpfr_cbrt" mpfr_cbrt :: Unary foreign import ccall unsafe "mpfr_cos" mpfr_cos :: Unary foreign import ccall unsafe "mpfr_cosh" mpfr_cosh :: Unary foreign import ccall unsafe "mpfr_cot" mpfr_cot :: Unary foreign import ccall unsafe "mpfr_coth" mpfr_coth :: Unary foreign import ccall unsafe "mpfr_csc" mpfr_csc :: Unary foreign import ccall unsafe "mpfr_csch" mpfr_csch :: Unary foreign import ccall unsafe "mpfr_digamma" mpfr_digamma :: Unary foreign import ccall unsafe "mpfr_eint" mpfr_eint :: Unary foreign import ccall unsafe "mpfr_erf" mpfr_erf :: Unary foreign import ccall unsafe "mpfr_erfc" mpfr_erfc :: Unary foreign import ccall unsafe "mpfr_exp" mpfr_exp :: Unary foreign import ccall unsafe "mpfr_exp10" mpfr_exp10 :: Unary foreign import ccall unsafe "mpfr_exp2" mpfr_exp2 :: Unary foreign import ccall unsafe "mpfr_expm1" mpfr_expm1 :: Unary foreign import ccall unsafe "mpfr_frac" mpfr_frac :: Unary foreign import ccall unsafe "mpfr_gamma" mpfr_gamma :: Unary foreign import ccall unsafe "mpfr_j0" mpfr_j0 :: Unary foreign import ccall unsafe "mpfr_j1" mpfr_j1 :: Unary foreign import ccall unsafe "mpfr_li2" mpfr_li2 :: Unary foreign import ccall unsafe "mpfr_lngamma" mpfr_lngamma :: Unary foreign import ccall unsafe "mpfr_log" mpfr_log :: Unary foreign import ccall unsafe "mpfr_log10" mpfr_log10 :: Unary foreign import ccall unsafe "mpfr_log1p" mpfr_log1p :: Unary foreign import ccall unsafe "mpfr_log2" mpfr_log2 :: Unary foreign import ccall unsafe "mpfr_neg" mpfr_neg :: Unary foreign import ccall unsafe "mpfr_rec_sqrt" mpfr_rec_sqrt :: Unary foreign import ccall unsafe "mpfr_rint" mpfr_rint :: Unary foreign import ccall unsafe "mpfr_rint_ceil" mpfr_rint_ceil :: Unary foreign import ccall unsafe "mpfr_rint_floor" mpfr_rint_floor :: Unary foreign import ccall unsafe "mpfr_rint_round" mpfr_rint_round :: Unary foreign import ccall unsafe "mpfr_rint_roundeven" mpfr_rint_roundeven :: Unary foreign import ccall unsafe "mpfr_rint_trunc" mpfr_rint_trunc :: Unary foreign import ccall unsafe "mpfr_sec" mpfr_sec :: Unary foreign import ccall unsafe "mpfr_sech" mpfr_sech :: Unary foreign import ccall unsafe "mpfr_set" mpfr_set :: Unary foreign import ccall unsafe "mpfr_sin" mpfr_sin :: Unary foreign import ccall unsafe "mpfr_sinh" mpfr_sinh :: Unary foreign import ccall unsafe "mpfr_sqr" mpfr_sqr :: Unary foreign import ccall unsafe "mpfr_sqrt" mpfr_sqrt :: Unary foreign import ccall unsafe "mpfr_tan" mpfr_tan :: Unary foreign import ccall unsafe "mpfr_tanh" mpfr_tanh :: Unary foreign import ccall unsafe "mpfr_y0" mpfr_y0 :: Unary foreign import ccall unsafe "mpfr_y1" mpfr_y1 :: Unary foreign import ccall unsafe "mpfr_zeta" mpfr_zeta :: Unary type Unary' = Ptr MPFR -> Ptr MPFR -> IO CInt foreign import ccall unsafe "mpfr_ceil" mpfr_ceil :: Unary' foreign import ccall unsafe "mpfr_floor" mpfr_floor :: Unary' foreign import ccall unsafe "mpfr_trunc" mpfr_trunc :: Unary' type Binary = Ptr MPFR -> Ptr MPFR -> Ptr MPFR -> MPFRRnd -> IO CInt foreign import ccall unsafe "mpfr_add" mpfr_add :: Binary foreign import ccall unsafe "mpfr_agm" mpfr_agm :: Binary foreign import ccall unsafe "mpfr_atan2" mpfr_atan2 :: Binary foreign import ccall unsafe "mpfr_copysign" mpfr_copysign :: Binary foreign import ccall unsafe "mpfr_dim" mpfr_dim :: Binary foreign import ccall unsafe "mpfr_div" mpfr_div :: Binary foreign import ccall unsafe "mpfr_fmod" mpfr_fmod :: Binary foreign import ccall unsafe "mpfr_hypot" mpfr_hypot :: Binary foreign import ccall unsafe "mpfr_max" mpfr_max :: Binary foreign import ccall unsafe "mpfr_min" mpfr_min :: Binary foreign import ccall unsafe "mpfr_mul" mpfr_mul :: Binary foreign import ccall unsafe "mpfr_pow" mpfr_pow :: Binary foreign import ccall unsafe "mpfr_sub" mpfr_sub :: Binary foreign import ccall unsafe "mpfr_beta" mpfr_beta :: Binary foreign import ccall unsafe "mpfr_gamma_inc" mpfr_gamma_inc :: Binary type DualOutput = Ptr MPFR -> Ptr MPFR -> Ptr MPFR -> MPFRRnd -> IO CInt foreign import ccall unsafe "mpfr_modf" mpfr_modf :: DualOutput foreign import ccall unsafe "mpfr_sin_cos" mpfr_sin_cos :: DualOutput foreign import ccall unsafe "mpfr_sinh_cosh" mpfr_sinh_cosh :: DualOutput type Comparison = Ptr MPFR -> Ptr MPFR -> IO CInt foreign import ccall unsafe "mpfr_cmp" mpfr_cmp :: Comparison foreign import ccall unsafe "mpfr_equal_p" mpfr_equal_p :: Comparison foreign import ccall unsafe "mpfr_greaterequal_p" mpfr_greaterequal_p :: Comparison foreign import ccall unsafe "mpfr_greater_p" mpfr_greater_p :: Comparison foreign import ccall unsafe "mpfr_lessequal_p" mpfr_lessequal_p :: Comparison foreign import ccall unsafe "mpfr_lessgreater_p" mpfr_lessgreater_p :: Comparison foreign import ccall unsafe "mpfr_less_p" mpfr_less_p :: Comparison foreign import ccall unsafe "mpfr_unordered_p" mpfr_unordered_p :: Comparison foreign import ccall unsafe "mpfr_nextabove" mpfr_nextabove :: Ptr MPFR -> IO () foreign import ccall unsafe "mpfr_nextbelow" mpfr_nextbelow :: Ptr MPFR -> IO () foreign import ccall unsafe "wrapped_mpfr_get_ld" wrapped_mpfr_get_ld :: Ptr LongDouble -> Ptr MPFR -> MPFRRnd -> Ptr CInt -> IO CInt foreign import ccall unsafe "wrapped_mpfr_get_ld_2exp" wrapped_mpfr_get_ld_2exp :: Ptr LongDouble -> Ptr CLong -> Ptr MPFR -> MPFRRnd -> Ptr CInt -> IO CInt foreign import ccall unsafe "wrapped_mpfr_set_ld" wrapped_mpfr_set_ld :: Ptr MPFR -> Ptr LongDouble -> MPFRRnd -> Ptr CInt -> IO CInt foreign import ccall unsafe "wrapped_mpfr_cmp_ld" wrapped_mpfr_cmp_ld :: Ptr MPFR -> Ptr LongDouble -> IO CInt
6a5cb6bee60214616c2573a2c5a54340e7231c0c3d977b22e8bdc5608018aa2f
fccm/OCamlSDL2
sdlinit.mli
OCamlSDL2 - An OCaml interface to the SDL2 library Copyright ( C ) 2013 This software is provided " AS - IS " , without any express or implied warranty . In no event will the authors be held liable for any damages arising from the use of this software . Permission is granted to anyone to use this software for any purpose , including commercial applications , and to alter it and redistribute it freely . Copyright (C) 2013 Florent Monnier This software is provided "AS-IS", without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely. *) (** Initialisation *) type subsystem = [ | `TIMER | `AUDIO | `VIDEO | `JOYSTICK | `HAPTIC | `GAMECONTROLLER | `EVENTS ] external init : [< subsystem | `EVERYTHING | `NOPARACHUTE ] list -> unit = "caml_SDL_Init" (** {{:}api doc} *) external init_subsystem : subsystem list -> unit = "caml_SDL_InitSubSystem" * { { : }
null
https://raw.githubusercontent.com/fccm/OCamlSDL2/73a378d63db7fc1dfba0148225e3f4ab9cffd953/src/sdlinit.mli
ocaml
* Initialisation * {{:}api doc}
OCamlSDL2 - An OCaml interface to the SDL2 library Copyright ( C ) 2013 This software is provided " AS - IS " , without any express or implied warranty . In no event will the authors be held liable for any damages arising from the use of this software . Permission is granted to anyone to use this software for any purpose , including commercial applications , and to alter it and redistribute it freely . Copyright (C) 2013 Florent Monnier This software is provided "AS-IS", without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely. *) type subsystem = [ | `TIMER | `AUDIO | `VIDEO | `JOYSTICK | `HAPTIC | `GAMECONTROLLER | `EVENTS ] external init : [< subsystem | `EVERYTHING | `NOPARACHUTE ] list -> unit = "caml_SDL_Init" external init_subsystem : subsystem list -> unit = "caml_SDL_InitSubSystem" * { { : }
d7204b423d45d3dc9f62101e1cbfb2c82f24cb0c8eefc192ced4ef0c114b5b2d
yav/hobbit
CheckDefs.hs
-- XXX: this needs to be fixed -- perhaps moved earlier in the compiler pipeline. module CheckDefs(checkDefs) where import AST(ADT,ADT'(..),ADTCtr'(..),poly) import AST.SIL import qualified BDD import qualified Pass import Error import PP import Utils import Data.List import Data.Word import MonadLib type M = ReaderT [ADT] (WriterT [Warning] Id) checkDefs :: [ADT] -> [Decl] -> Pass.Pass () checkDefs adts ds = Pass.warn ws >> return () where ws = map show $ snd $ runId $ runWriterT $ runReaderT adts $ mapM_ (`decl` true) ds -- Data structures ------------------------------------------------------------- type Prop = Or newtype Or = Or [And] data And = And [(Name,Name)] -- variable matches constructor [(Name,BDD.Pat)] -- variable matches bin. pat. false = Or [] true = Or [And [] []] Or p \/ Or q = Or (p ++ q) Or p /\ Or q = Or $ concatMap normAnd [ And (as ++ cs) (bs ++ ds) | And as bs <- p, And cs ds <- q ] x `bis` p = Or [And [] [(x,p)]] x `is` c = isOneOf x [c] x `isOneOf` cs = Or [ And [(x,c)] [] | c <- cs ] Or p `andNot` (x,cs) = Or (filter ok p) where ok (And as _) = all notContr as notContr (y,c) = (x /= y) || (c `notElem` cs) normAnd (And as bs) = case And # forEach (regroup as) reA <# forEach (regroup bs) reB of Nothing -> [] Just a -> [a] where reA (x,c:cs) | all (c ==) cs = Just (x,c) | otherwise = Nothing reA (_,[]) = "reA" `bug` "regroup returned []?" reB (x,ps) | BDD.willAlwaysFail p = Nothing | otherwise = Just (x,p) where p = foldr1 BDD.pAnd ps isFalse (Or []) = True isFalse _ = False -- Analysis -------------------------------------------------------------------- expr (Atom _) _ = return false expr (Con _ _) _ = return false expr (Prim _ _) _ = return false expr (App _ _) _ = return false -- syntactic not semantic! expr (Do s) f = stmt s f expr (CommE e) f = comm expr e f stmt (Call _ _) _ = return false stmt (LetM b s1 s2) f = do ws <- getWarns (stmt s1 f) -- Note: we commit report (varName b) ws stmt s2 f stmt (PrimS _ _) _ = return false stmt (CommS s) f = comm stmt s f comm :: (a -> Or -> M Or) -> Comm a -> Or -> M Or comm how (Let d e) facts = decl d facts >> how e facts -- Note: we assume that the alternatives do not overlap -- a switch can fail if: -- * a value does not match any of the ctrs, OR * a value matches one of the ctrs , and its body fails comm how (Switch x as) facts = do (cs,fs) <- unzip # forEach as (\a -> alt how x a facts) return (foldl (\/) (facts `andNot` (x,cs)) fs) -- Note: we assume that the alternatives do not overlap -- a swicth can fail if: -- * the pattern does not match any of the cases (is in all complements), OR -- * matches a branch, which itself fails comm how (BSwitch x as) facts = do (ns,fs) <- unzip # forEach as (\a -> balt how x a facts) return (foldl (\/) (foldl (/\) facts ns) fs) comm _ (Raise _) facts = return facts comm how (Handle e1 e2) facts = do canFail <- how e1 facts if isFalse canFail then do warn "Unreachable" -- XXX: How to report? return false else how e2 (canFail /\ facts) returns : ( the name of the constructor , how to fail if ctr matches ) alt how x (Case c e) facts = do let facts' = (x `is` c) /\ facts if isFalse facts' then do warn "Trivial failure (1)" -- XXX: Report return (c, facts') else do canFail <- how e facts' return (c, canFail) balt how (Lit (Int n)) (BCase p e) facts | pN `BDD.willMatchIf` p = do canFail <- how e facts return (false,canFail) | otherwise = do warn "Trivial failure (2)" return (true, false) where pN = BDD.pInt (BDD.width p) (fromIntegral n) -- returns: (the complement of the case, how to fail if pattern matches) balt how (Var x) (BCase p e) facts = do let itIs = x `bis` p orNot = x `bis` BDD.pNot p facts' = itIs /\ facts if isFalse facts' then do warn "Trivial failure (3)" -- XXX: Report return (orNot, facts') else do canFail <- how e facts' return (orNot, canFail) decl (AVal b e) facts = report (varName b) =<< getWarns (expr e facts) decl (Cyc _) _ = "decl" `unexpected` "Cyc" decl (Area {}) _ = return () decl (AFun f) facts = funDecl f facts decl (Rec fs) facts = forEach_ fs $ \f -> decl (AFun f) facts funDecl f facts = do fs <- forEach (funArgs f) ctrs ws <- getWarns $ expr (funDef f) (foldl (/\) facts fs) report (funName f) ws where ctrs (Bind x t) = do cs <- getCtrsT t return $ case cs of Just cs -> x `isOneOf` cs Nothing -> true Monad ----------------------------------------------------------------------- getCtrsT :: SimpleType -> M (Maybe [Name]) getCtrsT t = do as <- ask return $ case find ((t ==) . adtName) as of Just a -> Just (map toCon (adtCtrs a)) Nothing -> Nothing where toCon c = UName (acName (poly c)) data Warning = Msg String | Fail Prop | In Name [Warning] warn :: String -> M () warn msg = put [Msg msg] getWarns :: M a -> M (a,[Warning]) getWarns m = collect m report x (canFail,ws) | isFalse canFail = when (not (null ws)) (put [In x ws]) | otherwise = put [In x (Fail canFail : ws)] instance Show Warning where show = prShow instance Pr Warning where pr (In x ws) = text "In the definition of" <+> pr x <> colon $$ nest 2 (vcat (map pr ws)) pr (Msg s) = text s pr (Fail p) = text "Fails when:" $$ nest 2 (pr p) instance Show Prop where show = prShow instance Pr Or where pr (Or []) = text "(never)" pr (Or [a]) = pr a pr (Or (a:as)) = fsep ( text (replicate (length pre) ' ') <+> pr a : map ((text pre <+>) . pr) as ) where pre = "or" instance Pr And where pr p@(And as bs ) = case roots of [ ] - > text " ( always ) " as - > fsep ( punctuate ( text " , and " ) ( map prRoot as ) ) where prRoot r = fsep [ name r < + > text " is " , nest 2 ( ppAnd p r ) ] roots = filter isRoot ( map fst as + + map fst bs ) isRoot ( Fld _ _ _ ) = False isRoot _ = True pr p@(And as bs) = case roots of [] -> text "(always)" as -> fsep (punctuate (text ", and") (map prRoot as)) where prRoot r = fsep [name r <+> text "is", nest 2 (ppAnd p r) ] roots = filter isRoot (map fst as ++ map fst bs) isRoot (Fld _ _ _) = False isRoot _ = True -} pr (And as bs) = vcat (punctuate (text ", and") ds) where ds = [ name x <+> text "matches ctr." <+> pr c | (x,c) <- as ] ++ map prBin bs prBin (x,p) = name x <+> descr where descr | length pos <= length neg = fsep [ text "is of the form" , nest 2 (vcat pos) ] | otherwise = fsep [ text "is not of the form", nest 2 (vcat neg) ] where pos = showBin p neg = showBin (BDD.pNot p) showBin b = [ char 'B' <> text x | x <- BDD.showPat b ] name (Arg f x) = text "the" <+> text (say (x+1)) <+> text "argument of" <+> name f name (Fld x c n) = text "the" <+> text (say (n+1)) <+> text "field of" <+> name x <+> parens (text "if" <+> name x <+> text "is of the form" <+> pr c) name x = quotes (pr x) XXX : 11,12 say :: Word32 -> String say x = let xs = show x in xs ++ suff (last xs) where suff '1' = "st" suff '2' = "nd" suff '3' = "rd" suff _ = "th"
null
https://raw.githubusercontent.com/yav/hobbit/31414ba1188f4b39620c2553b45b9e4d4aa40169/src/CheckDefs.hs
haskell
XXX: this needs to be fixed perhaps moved earlier in the compiler pipeline. Data structures ------------------------------------------------------------- variable matches constructor variable matches bin. pat. Analysis -------------------------------------------------------------------- syntactic not semantic! Note: we commit Note: we assume that the alternatives do not overlap a switch can fail if: * a value does not match any of the ctrs, OR Note: we assume that the alternatives do not overlap a swicth can fail if: * the pattern does not match any of the cases (is in all complements), OR * matches a branch, which itself fails XXX: How to report? XXX: Report returns: (the complement of the case, how to fail if pattern matches) XXX: Report ---------------------------------------------------------------------
module CheckDefs(checkDefs) where import AST(ADT,ADT'(..),ADTCtr'(..),poly) import AST.SIL import qualified BDD import qualified Pass import Error import PP import Utils import Data.List import Data.Word import MonadLib type M = ReaderT [ADT] (WriterT [Warning] Id) checkDefs :: [ADT] -> [Decl] -> Pass.Pass () checkDefs adts ds = Pass.warn ws >> return () where ws = map show $ snd $ runId $ runWriterT $ runReaderT adts $ mapM_ (`decl` true) ds type Prop = Or newtype Or = Or [And] false = Or [] true = Or [And [] []] Or p \/ Or q = Or (p ++ q) Or p /\ Or q = Or $ concatMap normAnd [ And (as ++ cs) (bs ++ ds) | And as bs <- p, And cs ds <- q ] x `bis` p = Or [And [] [(x,p)]] x `is` c = isOneOf x [c] x `isOneOf` cs = Or [ And [(x,c)] [] | c <- cs ] Or p `andNot` (x,cs) = Or (filter ok p) where ok (And as _) = all notContr as notContr (y,c) = (x /= y) || (c `notElem` cs) normAnd (And as bs) = case And # forEach (regroup as) reA <# forEach (regroup bs) reB of Nothing -> [] Just a -> [a] where reA (x,c:cs) | all (c ==) cs = Just (x,c) | otherwise = Nothing reA (_,[]) = "reA" `bug` "regroup returned []?" reB (x,ps) | BDD.willAlwaysFail p = Nothing | otherwise = Just (x,p) where p = foldr1 BDD.pAnd ps isFalse (Or []) = True isFalse _ = False expr (Atom _) _ = return false expr (Con _ _) _ = return false expr (Prim _ _) _ = return false expr (Do s) f = stmt s f expr (CommE e) f = comm expr e f stmt (Call _ _) _ = return false report (varName b) ws stmt s2 f stmt (PrimS _ _) _ = return false stmt (CommS s) f = comm stmt s f comm :: (a -> Or -> M Or) -> Comm a -> Or -> M Or comm how (Let d e) facts = decl d facts >> how e facts * a value matches one of the ctrs , and its body fails comm how (Switch x as) facts = do (cs,fs) <- unzip # forEach as (\a -> alt how x a facts) return (foldl (\/) (facts `andNot` (x,cs)) fs) comm how (BSwitch x as) facts = do (ns,fs) <- unzip # forEach as (\a -> balt how x a facts) return (foldl (\/) (foldl (/\) facts ns) fs) comm _ (Raise _) facts = return facts comm how (Handle e1 e2) facts = do canFail <- how e1 facts if isFalse canFail return false else how e2 (canFail /\ facts) returns : ( the name of the constructor , how to fail if ctr matches ) alt how x (Case c e) facts = do let facts' = (x `is` c) /\ facts if isFalse facts' return (c, facts') else do canFail <- how e facts' return (c, canFail) balt how (Lit (Int n)) (BCase p e) facts | pN `BDD.willMatchIf` p = do canFail <- how e facts return (false,canFail) | otherwise = do warn "Trivial failure (2)" return (true, false) where pN = BDD.pInt (BDD.width p) (fromIntegral n) balt how (Var x) (BCase p e) facts = do let itIs = x `bis` p orNot = x `bis` BDD.pNot p facts' = itIs /\ facts if isFalse facts' return (orNot, facts') else do canFail <- how e facts' return (orNot, canFail) decl (AVal b e) facts = report (varName b) =<< getWarns (expr e facts) decl (Cyc _) _ = "decl" `unexpected` "Cyc" decl (Area {}) _ = return () decl (AFun f) facts = funDecl f facts decl (Rec fs) facts = forEach_ fs $ \f -> decl (AFun f) facts funDecl f facts = do fs <- forEach (funArgs f) ctrs ws <- getWarns $ expr (funDef f) (foldl (/\) facts fs) report (funName f) ws where ctrs (Bind x t) = do cs <- getCtrsT t return $ case cs of Just cs -> x `isOneOf` cs Nothing -> true getCtrsT :: SimpleType -> M (Maybe [Name]) getCtrsT t = do as <- ask return $ case find ((t ==) . adtName) as of Just a -> Just (map toCon (adtCtrs a)) Nothing -> Nothing where toCon c = UName (acName (poly c)) data Warning = Msg String | Fail Prop | In Name [Warning] warn :: String -> M () warn msg = put [Msg msg] getWarns :: M a -> M (a,[Warning]) getWarns m = collect m report x (canFail,ws) | isFalse canFail = when (not (null ws)) (put [In x ws]) | otherwise = put [In x (Fail canFail : ws)] instance Show Warning where show = prShow instance Pr Warning where pr (In x ws) = text "In the definition of" <+> pr x <> colon $$ nest 2 (vcat (map pr ws)) pr (Msg s) = text s pr (Fail p) = text "Fails when:" $$ nest 2 (pr p) instance Show Prop where show = prShow instance Pr Or where pr (Or []) = text "(never)" pr (Or [a]) = pr a pr (Or (a:as)) = fsep ( text (replicate (length pre) ' ') <+> pr a : map ((text pre <+>) . pr) as ) where pre = "or" instance Pr And where pr p@(And as bs ) = case roots of [ ] - > text " ( always ) " as - > fsep ( punctuate ( text " , and " ) ( map prRoot as ) ) where prRoot r = fsep [ name r < + > text " is " , nest 2 ( ppAnd p r ) ] roots = filter isRoot ( map fst as + + map fst bs ) isRoot ( Fld _ _ _ ) = False isRoot _ = True pr p@(And as bs) = case roots of [] -> text "(always)" as -> fsep (punctuate (text ", and") (map prRoot as)) where prRoot r = fsep [name r <+> text "is", nest 2 (ppAnd p r) ] roots = filter isRoot (map fst as ++ map fst bs) isRoot (Fld _ _ _) = False isRoot _ = True -} pr (And as bs) = vcat (punctuate (text ", and") ds) where ds = [ name x <+> text "matches ctr." <+> pr c | (x,c) <- as ] ++ map prBin bs prBin (x,p) = name x <+> descr where descr | length pos <= length neg = fsep [ text "is of the form" , nest 2 (vcat pos) ] | otherwise = fsep [ text "is not of the form", nest 2 (vcat neg) ] where pos = showBin p neg = showBin (BDD.pNot p) showBin b = [ char 'B' <> text x | x <- BDD.showPat b ] name (Arg f x) = text "the" <+> text (say (x+1)) <+> text "argument of" <+> name f name (Fld x c n) = text "the" <+> text (say (n+1)) <+> text "field of" <+> name x <+> parens (text "if" <+> name x <+> text "is of the form" <+> pr c) name x = quotes (pr x) XXX : 11,12 say :: Word32 -> String say x = let xs = show x in xs ++ suff (last xs) where suff '1' = "st" suff '2' = "nd" suff '3' = "rd" suff _ = "th"
a0121acbfb2bf3227edefd428a407aa82e779ca20dcad4c5d72d7e41acc79123
ninenines/cowboy
rest_pastebin_app.erl
%% Feel free to use, reuse and abuse the code in this file. @private -module(rest_pastebin_app). -behaviour(application). %% API. -export([start/2]). -export([stop/1]). %% API. start(_Type, _Args) -> Dispatch = cowboy_router:compile([ {'_', [ {"/[:paste_id]", toppage_h, []} ]} ]), {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ env => #{dispatch => Dispatch} }), rest_pastebin_sup:start_link(). stop(_State) -> ok = cowboy:stop_listener(http).
null
https://raw.githubusercontent.com/ninenines/cowboy/8795233c57f1f472781a22ffbf186ce38cc5b049/examples/rest_pastebin/src/rest_pastebin_app.erl
erlang
Feel free to use, reuse and abuse the code in this file. API. API.
@private -module(rest_pastebin_app). -behaviour(application). -export([start/2]). -export([stop/1]). start(_Type, _Args) -> Dispatch = cowboy_router:compile([ {'_', [ {"/[:paste_id]", toppage_h, []} ]} ]), {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ env => #{dispatch => Dispatch} }), rest_pastebin_sup:start_link(). stop(_State) -> ok = cowboy:stop_listener(http).
e30854519d094557b45ffae20b5804e2e26977149caf0b485bb86769a4a6a4b2
jyh/metaprl
tacticals_boot.mli
x * Some basic tacticals . * * ---------------------------------------------------------------- * * This file is part of MetaPRL , a modular , higher order * logical framework that provides a logical programming * environment for OCaml and other languages . * * See the file doc / htmlman / default.html or visit / * for more information . * * Copyright ( C ) 1998 , Cornell University * * 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. , 675 Mass Ave , Cambridge , , USA . * * Author : * * Some basic tacticals. * * ---------------------------------------------------------------- * * This file is part of MetaPRL, a modular, higher order * logical framework that provides a logical programming * environment for OCaml and other languages. * * See the file doc/htmlman/default.html or visit / * for more information. * * Copyright (C) 1998 Jason Hickey, Cornell University * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * * Author: Jason Hickey * *) open Tactic_boot_sig open Tactic_boot module Tacticals : TacticalsSig with module TacticalsTypes = TacticInternalType (* * -*- * Local Variables: * Caml-master: "editor.run" * End: * -*- *)
null
https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/tactics/proof/tacticals_boot.mli
ocaml
* -*- * Local Variables: * Caml-master: "editor.run" * End: * -*-
x * Some basic tacticals . * * ---------------------------------------------------------------- * * This file is part of MetaPRL , a modular , higher order * logical framework that provides a logical programming * environment for OCaml and other languages . * * See the file doc / htmlman / default.html or visit / * for more information . * * Copyright ( C ) 1998 , Cornell University * * 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. , 675 Mass Ave , Cambridge , , USA . * * Author : * * Some basic tacticals. * * ---------------------------------------------------------------- * * This file is part of MetaPRL, a modular, higher order * logical framework that provides a logical programming * environment for OCaml and other languages. * * See the file doc/htmlman/default.html or visit / * for more information. * * Copyright (C) 1998 Jason Hickey, Cornell University * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * * Author: Jason Hickey * *) open Tactic_boot_sig open Tactic_boot module Tacticals : TacticalsSig with module TacticalsTypes = TacticInternalType
e4fac24b69d5b2e48bb87284282b0b2a4ed965048ca0b7a1f5894f028248f91e
chrisdone/prana
Compat.hs
# LANGUAGE CPP # | Compatibility between GHC API versions . module Intero.Compat ( ghc_getModuleGraph , ghc_getInfo , ghc_defaultDynFlags , ghc_topSortModuleGraph , ghc_mkWarn , ghc_mkErr , ghc_errMsg , ghc_warnMsg , ghc_tyConFlavour , StageReaderName , StageReaderRdrName , StageReaderId ) where #if __GLASGOW_HASKELL__ > 800 import TyCoRep #endif import TyCon #if __GLASGOW_HASKELL__ > 802 import CmdLineParser #endif #if __GLASGOW_HASKELL__ >= 800 import qualified Data.Graph as SCC #else import qualified Digraph as SCC #endif import DynFlags import GHC ghc_tyConFlavour :: TyCon -> String #if __GLASGOW_HASKELL__ > 802 ghc_tyConFlavour n = if tyConFlavour n == ClassFlavour then "class" else "" #else #if __GLASGOW_HASKELL__ > 800 ghc_tyConFlavour = tyConFlavour #else ghc_tyConFlavour _ = "" #endif #endif ghc_defaultDynFlags :: Settings -> DynFlags #if __GLASGOW_HASKELL__ <= 802 ghc_defaultDynFlags = defaultDynFlags #else ghc_defaultDynFlags s = defaultDynFlags s mempty #endif ghc_getInfo :: GhcMonad m => Bool -> Name -> m (Maybe (TyThing, Fixity, [ClsInst], [FamInst])) #if __GLASGOW_HASKELL__ <= 802 ghc_getInfo = getInfo #else ghc_getInfo x y = fmap (fmap (\(a,b,c,d,_) -> (a,b,c,d))) (getInfo x y) #endif ghc_getModuleGraph :: GhcMonad m => m [ModSummary] #if __GLASGOW_HASKELL__ <= 802 ghc_getModuleGraph = GHC.getModuleGraph #else ghc_getModuleGraph = fmap mgModSummaries GHC.getModuleGraph #endif ghc_topSortModuleGraph :: Bool -> [ModSummary] -> Maybe ModuleName -> [SCC.SCC ModSummary] #if __GLASGOW_HASKELL__ <= 802 ghc_topSortModuleGraph = GHC.topSortModuleGraph #else ghc_topSortModuleGraph bool sums may = GHC.topSortModuleGraph bool (mkModuleGraph sums) may #endif #if __GLASGOW_HASKELL__ <= 802 type StageReaderName = Name #else type StageReaderName = GhcRn #endif #if __GLASGOW_HASKELL__ <= 802 type StageReaderRdrName = RdrName #else type StageReaderRdrName = GhcPs #endif #if __GLASGOW_HASKELL__ <= 802 type StageReaderId = Id #else type StageReaderId = GhcTc #endif #if __GLASGOW_HASKELL__ > 802 ghc_mkWarn :: Located String -> Warn ghc_mkWarn = Warn CmdLineParser.NoReason #else ghc_mkWarn :: a -> a ghc_mkWarn = id #endif #if __GLASGOW_HASKELL__ > 802 ghc_mkErr :: Located String -> Err ghc_mkErr = Err #else ghc_mkErr :: a -> a ghc_mkErr = id #endif #if __GLASGOW_HASKELL__ > 802 ghc_errMsg :: Err -> Located String ghc_errMsg = errMsg #else ghc_errMsg :: a -> a ghc_errMsg = id #endif #if __GLASGOW_HASKELL__ > 802 ghc_warnMsg :: Warn -> Located String ghc_warnMsg = warnMsg #else ghc_warnMsg :: a -> a ghc_warnMsg = id #endif
null
https://raw.githubusercontent.com/chrisdone/prana/f2e45538937d326aff562b6d49296eaedd015662/prana-ghc/app/Intero/Compat.hs
haskell
# LANGUAGE CPP # | Compatibility between GHC API versions . module Intero.Compat ( ghc_getModuleGraph , ghc_getInfo , ghc_defaultDynFlags , ghc_topSortModuleGraph , ghc_mkWarn , ghc_mkErr , ghc_errMsg , ghc_warnMsg , ghc_tyConFlavour , StageReaderName , StageReaderRdrName , StageReaderId ) where #if __GLASGOW_HASKELL__ > 800 import TyCoRep #endif import TyCon #if __GLASGOW_HASKELL__ > 802 import CmdLineParser #endif #if __GLASGOW_HASKELL__ >= 800 import qualified Data.Graph as SCC #else import qualified Digraph as SCC #endif import DynFlags import GHC ghc_tyConFlavour :: TyCon -> String #if __GLASGOW_HASKELL__ > 802 ghc_tyConFlavour n = if tyConFlavour n == ClassFlavour then "class" else "" #else #if __GLASGOW_HASKELL__ > 800 ghc_tyConFlavour = tyConFlavour #else ghc_tyConFlavour _ = "" #endif #endif ghc_defaultDynFlags :: Settings -> DynFlags #if __GLASGOW_HASKELL__ <= 802 ghc_defaultDynFlags = defaultDynFlags #else ghc_defaultDynFlags s = defaultDynFlags s mempty #endif ghc_getInfo :: GhcMonad m => Bool -> Name -> m (Maybe (TyThing, Fixity, [ClsInst], [FamInst])) #if __GLASGOW_HASKELL__ <= 802 ghc_getInfo = getInfo #else ghc_getInfo x y = fmap (fmap (\(a,b,c,d,_) -> (a,b,c,d))) (getInfo x y) #endif ghc_getModuleGraph :: GhcMonad m => m [ModSummary] #if __GLASGOW_HASKELL__ <= 802 ghc_getModuleGraph = GHC.getModuleGraph #else ghc_getModuleGraph = fmap mgModSummaries GHC.getModuleGraph #endif ghc_topSortModuleGraph :: Bool -> [ModSummary] -> Maybe ModuleName -> [SCC.SCC ModSummary] #if __GLASGOW_HASKELL__ <= 802 ghc_topSortModuleGraph = GHC.topSortModuleGraph #else ghc_topSortModuleGraph bool sums may = GHC.topSortModuleGraph bool (mkModuleGraph sums) may #endif #if __GLASGOW_HASKELL__ <= 802 type StageReaderName = Name #else type StageReaderName = GhcRn #endif #if __GLASGOW_HASKELL__ <= 802 type StageReaderRdrName = RdrName #else type StageReaderRdrName = GhcPs #endif #if __GLASGOW_HASKELL__ <= 802 type StageReaderId = Id #else type StageReaderId = GhcTc #endif #if __GLASGOW_HASKELL__ > 802 ghc_mkWarn :: Located String -> Warn ghc_mkWarn = Warn CmdLineParser.NoReason #else ghc_mkWarn :: a -> a ghc_mkWarn = id #endif #if __GLASGOW_HASKELL__ > 802 ghc_mkErr :: Located String -> Err ghc_mkErr = Err #else ghc_mkErr :: a -> a ghc_mkErr = id #endif #if __GLASGOW_HASKELL__ > 802 ghc_errMsg :: Err -> Located String ghc_errMsg = errMsg #else ghc_errMsg :: a -> a ghc_errMsg = id #endif #if __GLASGOW_HASKELL__ > 802 ghc_warnMsg :: Warn -> Located String ghc_warnMsg = warnMsg #else ghc_warnMsg :: a -> a ghc_warnMsg = id #endif
350ba5cf3ceca29d995c6d4d7171bb12f1bfa8c41d1403e278c0e6e570482fd2
bpiel/guildsman
utils.cljs
(ns ^:figwheel-no-load figwheel.client.utils (:require [clojure.string :as string] [goog.string :as gstring] [goog.object :as gobj] [cljs.reader :refer [read-string]] [cljs.pprint :refer [pprint]] [goog.userAgent.product :as product]) (:import [goog] [goog.async Deferred] [goog.string StringBuffer])) ;; don't auto reload this file it will mess up the debug printing (def ^:dynamic *print-debug* false) (defn html-env? [] (not (nil? goog/global.document))) (defn react-native-env? [] (and (exists? goog/global.navigator) (= goog/global.navigator.product "ReactNative"))) (defn node-env? [] (not (nil? goog/nodeGlobalRequire))) (defn html-or-react-native-env? [] (or (html-env?) (react-native-env?))) (defn worker-env? [] (and (nil? goog/global.document) (exists? js/self) (exists? (.-importScripts js/self)))) (defn host-env? [] (cond (node-env?) :node (html-env?) :html (react-native-env?) :react-native (worker-env?) :worker)) (defn base-url-path [] (string/replace goog/basePath #"(.*)goog/" "$1")) ;; Custom Event must exist before calling this (defn create-custom-event [event-name data] (if-not product/IE (js/CustomEvent. event-name (js-obj "detail" data)) ;; in windows world ;; this will probably not work at some point in newer versions of IE (let [event (js/document.createEvent "CustomEvent")] (.. event (initCustomEvent event-name false false data)) event))) actually we should probably lift the event system here off the DOM so that we work well in Node and other environments (defn dispatch-custom-event [event-name data] (when (and (html-env?) (gobj/get js/window "CustomEvent") (js* "typeof document !== 'undefined'")) (.dispatchEvent (.-body js/document) (create-custom-event event-name data)))) (defn debug-prn [o] (when *print-debug* (let [o (if (or (map? o) (seq? o)) (prn-str o) o)] (.log js/console o)))) (defn log ([x] (log :info x)) ([level arg] (let [f (condp = (if (html-or-react-native-env?) level :info) :warn #(.warn js/console %) :debug #(.debug js/console %) :error #(.error js/console %) #(.log js/console %))] (f arg)))) (defn eval-helper [code {:keys [eval-fn] :as opts}] (if eval-fn (eval-fn code opts) (js* "eval(~{code})"))) (defn pprint-to-string [x] (let [sb (StringBuffer.) sbw (StringBufferWriter. sb)] (pprint x sbw) (gstring/trimRight (str sb)))) ;; Deferred helpers that focus on guaranteed successful side effects ;; not very monadic but it meets our needs (defn liftContD "chains an async action on to a deferred Must provide a goog.async.Deferred and action function that takes an initial value and a continuation fn to call with the result" [deferred f] (.then deferred (fn [val] (let [new-def (Deferred.)] (f val #(.callback new-def %)) new-def)))) (defn mapConcatD "maps an async action across a collection and chains the results onto a deferred" [deferred f coll] (let [results (atom [])] (.then (reduce (fn [defr v] (liftContD defr (fn [_ fin] (f v (fn [v] (swap! results conj v) (fin v)))))) deferred coll) (fn [_] (.succeed Deferred @results))))) ;; persistent storage of configuration keys (defonce local-persistent-config (let [a (atom {})] (when (exists? js/localStorage) (add-watch a :sync-local-storage (fn [_ _ _ n] (mapv (fn [[ky v]] (.setItem js/localStorage (name ky) (pr-str v))) n)))) a)) (defn persistent-config-set! "Set a local value on a key that in a browser will persist even when the browser gets reloaded." [ky v] (swap! local-persistent-config assoc ky v)) (defn persistent-config-get ([ky not-found] (try (cond (contains? @local-persistent-config ky) (get @local-persistent-config ky) (and (exists? js/localStorage) (.getItem js/localStorage (name ky))) (let [v (read-string (.getItem js/localStorage (name ky)))] (persistent-config-set! ky v) v) :else not-found) (catch js/Error e not-found))) ([ky] (persistent-config-get ky nil)))
null
https://raw.githubusercontent.com/bpiel/guildsman/59c9a7459de19525cfc54112f02127e0777a00ce/resources/public/js/compiled/out/figwheel/client/utils.cljs
clojure
don't auto reload this file it will mess up the debug printing Custom Event must exist before calling this in windows world this will probably not work at some point in Deferred helpers that focus on guaranteed successful side effects not very monadic but it meets our needs persistent storage of configuration keys
(ns ^:figwheel-no-load figwheel.client.utils (:require [clojure.string :as string] [goog.string :as gstring] [goog.object :as gobj] [cljs.reader :refer [read-string]] [cljs.pprint :refer [pprint]] [goog.userAgent.product :as product]) (:import [goog] [goog.async Deferred] [goog.string StringBuffer])) (def ^:dynamic *print-debug* false) (defn html-env? [] (not (nil? goog/global.document))) (defn react-native-env? [] (and (exists? goog/global.navigator) (= goog/global.navigator.product "ReactNative"))) (defn node-env? [] (not (nil? goog/nodeGlobalRequire))) (defn html-or-react-native-env? [] (or (html-env?) (react-native-env?))) (defn worker-env? [] (and (nil? goog/global.document) (exists? js/self) (exists? (.-importScripts js/self)))) (defn host-env? [] (cond (node-env?) :node (html-env?) :html (react-native-env?) :react-native (worker-env?) :worker)) (defn base-url-path [] (string/replace goog/basePath #"(.*)goog/" "$1")) (defn create-custom-event [event-name data] (if-not product/IE (js/CustomEvent. event-name (js-obj "detail" data)) newer versions of IE (let [event (js/document.createEvent "CustomEvent")] (.. event (initCustomEvent event-name false false data)) event))) actually we should probably lift the event system here off the DOM so that we work well in Node and other environments (defn dispatch-custom-event [event-name data] (when (and (html-env?) (gobj/get js/window "CustomEvent") (js* "typeof document !== 'undefined'")) (.dispatchEvent (.-body js/document) (create-custom-event event-name data)))) (defn debug-prn [o] (when *print-debug* (let [o (if (or (map? o) (seq? o)) (prn-str o) o)] (.log js/console o)))) (defn log ([x] (log :info x)) ([level arg] (let [f (condp = (if (html-or-react-native-env?) level :info) :warn #(.warn js/console %) :debug #(.debug js/console %) :error #(.error js/console %) #(.log js/console %))] (f arg)))) (defn eval-helper [code {:keys [eval-fn] :as opts}] (if eval-fn (eval-fn code opts) (js* "eval(~{code})"))) (defn pprint-to-string [x] (let [sb (StringBuffer.) sbw (StringBufferWriter. sb)] (pprint x sbw) (gstring/trimRight (str sb)))) (defn liftContD "chains an async action on to a deferred Must provide a goog.async.Deferred and action function that takes an initial value and a continuation fn to call with the result" [deferred f] (.then deferred (fn [val] (let [new-def (Deferred.)] (f val #(.callback new-def %)) new-def)))) (defn mapConcatD "maps an async action across a collection and chains the results onto a deferred" [deferred f coll] (let [results (atom [])] (.then (reduce (fn [defr v] (liftContD defr (fn [_ fin] (f v (fn [v] (swap! results conj v) (fin v)))))) deferred coll) (fn [_] (.succeed Deferred @results))))) (defonce local-persistent-config (let [a (atom {})] (when (exists? js/localStorage) (add-watch a :sync-local-storage (fn [_ _ _ n] (mapv (fn [[ky v]] (.setItem js/localStorage (name ky) (pr-str v))) n)))) a)) (defn persistent-config-set! "Set a local value on a key that in a browser will persist even when the browser gets reloaded." [ky v] (swap! local-persistent-config assoc ky v)) (defn persistent-config-get ([ky not-found] (try (cond (contains? @local-persistent-config ky) (get @local-persistent-config ky) (and (exists? js/localStorage) (.getItem js/localStorage (name ky))) (let [v (read-string (.getItem js/localStorage (name ky)))] (persistent-config-set! ky v) v) :else not-found) (catch js/Error e not-found))) ([ky] (persistent-config-get ky nil)))
d879146514572845f6e10630798d1086f026afdcb03c50d04a0562e13d4135df
hkuplg/fcore
Simplify.hs
# LANGUAGE TypeOperators , FlexibleInstances , MultiParamTypeClasses , RankNTypes # # OPTIONS_GHC -Wall # | Module : Simplify Description : The simplifier turns SystemFI into Core . Copyright : ( c ) 2014—2015 The F2J Project Developers ( given in AUTHORS.txt ) License : BSD3 Maintainer : < > , < > Stability : experimental Portability : portable The simplifier translates System F with intersection types to vanilla System F. Module : Simplify Description : The simplifier turns SystemFI into Core. Copyright : (c) 2014—2015 The F2J Project Developers (given in AUTHORS.txt) License : BSD3 Maintainer : Zhiyuan Shi <>, Haoyuan Zhang <> Stability : experimental Portability : portable The simplifier translates System F with intersection types to vanilla System F. -} module Simplify ( simplify , simplify' ) where import qualified SimplifyImpl as Impl import Core import qualified SystemFI as FI import Unsafe.Coerce (unsafeCoerce) simplify :: FI.FExp -> Expr t e simplify = Impl.simplify simplify' :: FI.Expr t e -> Expr t e simplify' = Impl.dedeBruE 0 [] 0 [] . Impl.transExpr 0 0 . unsafeCoerce
null
https://raw.githubusercontent.com/hkuplg/fcore/e27b6dec5bfd319edb8c3e90d94a993bcc7b4c95/frontend/simplify/Simplify.hs
haskell
# LANGUAGE TypeOperators , FlexibleInstances , MultiParamTypeClasses , RankNTypes # # OPTIONS_GHC -Wall # | Module : Simplify Description : The simplifier turns SystemFI into Core . Copyright : ( c ) 2014—2015 The F2J Project Developers ( given in AUTHORS.txt ) License : BSD3 Maintainer : < > , < > Stability : experimental Portability : portable The simplifier translates System F with intersection types to vanilla System F. Module : Simplify Description : The simplifier turns SystemFI into Core. Copyright : (c) 2014—2015 The F2J Project Developers (given in AUTHORS.txt) License : BSD3 Maintainer : Zhiyuan Shi <>, Haoyuan Zhang <> Stability : experimental Portability : portable The simplifier translates System F with intersection types to vanilla System F. -} module Simplify ( simplify , simplify' ) where import qualified SimplifyImpl as Impl import Core import qualified SystemFI as FI import Unsafe.Coerce (unsafeCoerce) simplify :: FI.FExp -> Expr t e simplify = Impl.simplify simplify' :: FI.Expr t e -> Expr t e simplify' = Impl.dedeBruE 0 [] 0 [] . Impl.transExpr 0 0 . unsafeCoerce
a4fb1ac2d43ee41f28cfe6df69d1c3fcfffe1d690ae792c34959cb8f7849d781
klutometis/clrs
fibonacci.scm
(define (fibonacci-heap-change-key! heap node k) (let ((key (fibonacci-node-key node))) (cond ((= k key)) ((< k key) (fibonacci-heap-decrease-key! heap node k)) (else (let ((children (children node))) (for-each (cut cut! heap <> node) children) (set-fibonacci-node-key! node k) (let ((parent (fibonacci-node-parent node))) (if parent (begin (cut! heap node parent) (cascading-cut! heap parent)))))))))
null
https://raw.githubusercontent.com/klutometis/clrs/f85a8f0036f0946c9e64dde3259a19acc62b74a1/20/fibonacci.scm
scheme
(define (fibonacci-heap-change-key! heap node k) (let ((key (fibonacci-node-key node))) (cond ((= k key)) ((< k key) (fibonacci-heap-decrease-key! heap node k)) (else (let ((children (children node))) (for-each (cut cut! heap <> node) children) (set-fibonacci-node-key! node k) (let ((parent (fibonacci-node-parent node))) (if parent (begin (cut! heap node parent) (cascading-cut! heap parent)))))))))
fb9b3b048d6361baef9bc18578c91d92cc7e0097fec9bcac400fe13a81944da4
TeMPOraL/alice
local-config-template.lisp
(in-package #:alice) ;; basic configuration (setf *pushover-token* "insert token" *pushover-admin-user* "insert pushover user / group key for admin (for emergency / debug notifications)" *wolfram-app-id* "insert app id" *mailgun-domain* "insert mailgun domain" *mailgun-key* "insert mailgun key" *github-token* "insert github token here" *gdziepaczka-token* "insert gdziepaczka.pl token here" *kdbot-notification-email* "insert notification e-mail here" *server* "irc.freenode.net" *nick* "Alice_M" *password* "insert password" *autojoin-channels* '("#hackerspace-krk" "#TRC") *excluded-from-replying-to* '("excluded-nick-1" "excluded-nick-2") *remote-admin-allowed-users-alist* '(("user" . "pass") ("user2" . "pass2"))) alternative notifications to memos - specify nick and alternative notification function (setf (gethash "ShanghaiDoll" *user-notification-medium*) (make-pushover-notifier "insert pushover user or group key") (gethash "HouraiDoll" *user-notification-medium*) (make-email-notifier "insert e-mail address"))
null
https://raw.githubusercontent.com/TeMPOraL/alice/4621a53ccd459bebf0b34c531dab49f7b42f35c7/local-config-template.lisp
lisp
basic configuration
(in-package #:alice) (setf *pushover-token* "insert token" *pushover-admin-user* "insert pushover user / group key for admin (for emergency / debug notifications)" *wolfram-app-id* "insert app id" *mailgun-domain* "insert mailgun domain" *mailgun-key* "insert mailgun key" *github-token* "insert github token here" *gdziepaczka-token* "insert gdziepaczka.pl token here" *kdbot-notification-email* "insert notification e-mail here" *server* "irc.freenode.net" *nick* "Alice_M" *password* "insert password" *autojoin-channels* '("#hackerspace-krk" "#TRC") *excluded-from-replying-to* '("excluded-nick-1" "excluded-nick-2") *remote-admin-allowed-users-alist* '(("user" . "pass") ("user2" . "pass2"))) alternative notifications to memos - specify nick and alternative notification function (setf (gethash "ShanghaiDoll" *user-notification-medium*) (make-pushover-notifier "insert pushover user or group key") (gethash "HouraiDoll" *user-notification-medium*) (make-email-notifier "insert e-mail address"))
e29bf2f2dfa31432e3672dd8c4d2a55df96c6ddf6d465ec79e75e795eb4b1f9b
the-little-typer/pie
print-gui.rkt
#lang racket/base (require racket/function racket/list racket/match) (require "pie-styles.rkt" "../basics.rkt" "../resugar.rkt") (require racket/gui framework) (require pict) (provide pie-feedback%) (define indentation (make-parameter 0)) (define-syntax indented (syntax-rules () [(_ i e ...) (parameterize ([indentation (+ i (indentation))]) (begin e ...))])) (define pie-feedback% (class (pie-styles-mixin color:text%) (super-new [auto-wrap #t]) (init-field [status 'unknown]) (define ok (colorize (text "✔" "DejaVu Sans Mono" (current-pie-gui-font-size)) "darkgreen")) (define incomplete (let* ([mark (colorize (text "?" (cons 'bold "DejaVu Sans Mono") (current-pie-gui-font-size)) "white")] [size (max (pict-width mark) (pict-height mark))]) (cc-superimpose (filled-rounded-rectangle size size #:color "gold" #:draw-border? #f) mark))) (define bad (colorize (text "✖" "DejaVu Sans Mono" (current-pie-gui-font-size)) "red")) (define/public (set-status s) (set! status s) (send this invalidate-bitmap-cache) (define c (send this get-canvas)) (when c (send c refresh))) (define (status-pict) (match status ['ok ok] ['incomplete incomplete] ['bad bad] [_ (blank)])) (define/override (on-paint before? dc left top right bottom dx dy draw-caret) (super on-paint before? dc left top right bottom dx dy draw-caret) (define pict (status-pict)) (define c (send this get-canvas)) (when c (define w (send c get-width)) (draw-pict pict dc (- w (pict-width pict) 25 (send c horizontal-inset)) (+ 5 (send c vertical-inset))))) (define-syntax unlocked (syntax-rules () [(_ e ...) (let ((locked? (send this is-locked?))) (dynamic-wind (thunk (when locked? (send this lock #f))) (thunk e ...) (thunk (when locked? (send this lock #t)))))])) (define/public (set-error e) (unlocked (send this reset) (send this change-style (send this text-style)) (send this insert (exn-message e) 0 (send this last-position))) (send this scroll-to-position 0)) (define/public (reset) (unlocked (send this insert "" 0 (send this last-position)) (send this change-style (send this text-style)))) (define/public (spaces n) (send this change-style (send this text-style)) (send this insert (build-string n (lambda (i) #\space)))) (define/public (space) (spaces 1)) (define/public (indent) (spaces (indentation))) (define/public (start-line) (indent)) (define/public (terpri) (send this change-style (send this text-style)) (send this insert "\n") (start-line)) (define (l) (send this change-style (send this parenthesis-style)) (send this insert "(") (send this change-style (send this text-style))) (define (r) (send this change-style (send this parenthesis-style)) (send this insert ")") (send this change-style (send this text-style))) (define-syntax parens (syntax-rules () ((_ e ...) (begin (l) (indented 1 e ...) (r))))) (define-syntax η (syntax-rules () [(η x) (lambda () (x))])) (define (top-binder? sym) (and (symbol? sym) (or (eqv? sym 'Pi) (eqv? sym 'Π) (eqv? sym 'Sigma) (eqv? sym 'Σ)))) (define (ind? sym) (and (symbol? sym) (let ([str (symbol->string sym)]) (and (>= (string-length str) 4) (string=? (substring str 0 4) "ind-"))))) (define (sep s op args) (match args ['() (void)] [(list b) (op b)] [(cons b bs) (op b) (s) (sep s op bs)])) (define (vsep op args) (sep (η terpri) op args)) (define (hsep op args) (sep (η space) op args)) (define (annots bindings) (define (print-binding b) (match b [(list x ty) (parens (print-var x) (space) (indented (+ (string-length (symbol->string x)) 2) (print-pie ty)))])) (vsep print-binding bindings)) (define (atomic? x) (match x [(? symbol?) #t] [(? number?) #t] [(list 'quote _) #t] [_ #f])) (define/public (print-tycon c) (send this change-style (send this type-constructor-style)) (send this insert (symbol->string c)) (send this change-style (send this text-style))) (define/public (print-con c) (send this change-style (send this data-constructor-style)) (send this insert (symbol->string c)) (send this change-style (send this text-style))) (define/public (print-atom c) (send this change-style (send this data-constructor-style)) (send this insert "'") (send this insert (symbol->string c)) (send this change-style (send this text-style))) (define/public (print-lit x) (send this change-style (send this data-constructor-style)) (send this insert (format "~a" x)) (send this change-style (send this text-style))) (define/public (print-elim c) (send this change-style (send this keyword-style)) (send this insert (symbol->string c)) (send this change-style (send this text-style))) (define/public (print-var c) (send this change-style (send this var-style)) (send this insert (symbol->string c)) (send this change-style (send this text-style))) (define (elim? x) (if (memv x '(which-Nat ind-Nat iter-Nat rec-Nat ind-Vec head tail car cdr ind-Absurd the)) #t #f)) (define (tycon? x) (if (memv x '(U Π Pi Σ Sigma Nat Atom Absurd Trivial Pair -> Vec List Either)) #t #f)) (define (con? x) (if (memv x '(cons λ lambda add1 zero :: vec:: nil vecnil sole left right)) #t #f)) (define (print-pie expr) ;; Always display something, even if the print code is borked (with-handlers ([exn:fail? (lambda (e) (displayln (exn-message e)) (send this insert (format "~a" expr)))]) (match expr [(list (and b (or 'Π 'Σ)) bindings body) (parens (print-tycon b) (spaces 1) (indented (add1 (string-length (symbol->string b))) (parens (annots bindings))) (terpri) (print-pie body))] [(list (or 'lambda 'λ) (list-rest args) body) (parens (print-con 'λ) (space) (parens (hsep (lambda (x) (print-var x)) args)) (indented 1 (terpri) (print-pie body)))] [(cons '-> (app reverse (cons ret (app reverse args)))) (parens (print-tycon '->) (if (andmap atomic? args) (begin (space) (hsep print-pie args)) (indented 3 (space) (vsep (lambda (x) (print-pie x)) args))) (indented 1 (terpri) (print-pie ret)) )] [(list 'quote x) (print-atom x)] [(list 'TODO loc ty) (print-elim 'TODO)] [(cons (? elim? e) args) (parens (print-elim e) (space) (match args [(list) (void)] [(cons target others) (indented (+ (string-length (symbol->string e)) 1) (print-pie target)) (when (pair? others) (indented 2 (terpri) (vsep (lambda (x) (print-pie x)) others)))]))] [(cons (? con? c) args) (parens (print-con c) (space) (match args [(list) (void)] [(list (? atomic? arg)) (print-pie arg)] [(list arg) (indented 2 (terpri) (print-pie arg))] [(cons fst others) (indented (+ (string-length (symbol->string c)) 1) (print-pie fst)) (indented 2 (terpri) (vsep (lambda (x) (print-pie x)) others))]))] [(list-rest (? symbol? op) (? atomic? arg) args) #:when (and (< (length args) 20) (andmap atomic? args)) (parens (hsep (lambda (x) (print-pie x)) (cons op (cons arg args))))] [(list-rest (? symbol? op) arg args) (parens (print-pie op) (space) (indented (add1 (string-length (symbol->string op))) (print-pie arg)) (indented 1 (when (pair? args) (terpri) (vsep (lambda (x) (print-pie x)) args))))] [(list-rest op args) (parens (print-pie op) (indented 1 (terpri) (vsep (lambda (x) (print-pie x)) args)))] [(? con? c) (print-con c)] [(? tycon? t) (print-tycon t)] [(? symbol? x) (print-var x)] [(? number? n) (print-lit n)] [other (send this insert (format "OOPS[~a]" other))]))) (define/public (pprint-pie expr (description "")) (unlocked (start-line) (indented (string-length description) (when (not (string=? description "")) (send this change-style (send this text-style)) (send this insert description)) (print-pie (resugar expr)))) (send this scroll-to-position 0)) (define/public (pprint-message msg) (unlocked (start-line) (for ([part msg]) (cond [(string? part) (send this change-style (send this text-style)) (send this insert part)] [else (indented 2 (terpri) (print-pie (resugar part))) (terpri)]))) (send this scroll-to-position 0)) (send this lock #t)))
null
https://raw.githubusercontent.com/the-little-typer/pie/a698d4cacd6823b5161221596d34bd17ce5282b8/gui/print-gui.rkt
racket
Always display something, even if the print code is borked
#lang racket/base (require racket/function racket/list racket/match) (require "pie-styles.rkt" "../basics.rkt" "../resugar.rkt") (require racket/gui framework) (require pict) (provide pie-feedback%) (define indentation (make-parameter 0)) (define-syntax indented (syntax-rules () [(_ i e ...) (parameterize ([indentation (+ i (indentation))]) (begin e ...))])) (define pie-feedback% (class (pie-styles-mixin color:text%) (super-new [auto-wrap #t]) (init-field [status 'unknown]) (define ok (colorize (text "✔" "DejaVu Sans Mono" (current-pie-gui-font-size)) "darkgreen")) (define incomplete (let* ([mark (colorize (text "?" (cons 'bold "DejaVu Sans Mono") (current-pie-gui-font-size)) "white")] [size (max (pict-width mark) (pict-height mark))]) (cc-superimpose (filled-rounded-rectangle size size #:color "gold" #:draw-border? #f) mark))) (define bad (colorize (text "✖" "DejaVu Sans Mono" (current-pie-gui-font-size)) "red")) (define/public (set-status s) (set! status s) (send this invalidate-bitmap-cache) (define c (send this get-canvas)) (when c (send c refresh))) (define (status-pict) (match status ['ok ok] ['incomplete incomplete] ['bad bad] [_ (blank)])) (define/override (on-paint before? dc left top right bottom dx dy draw-caret) (super on-paint before? dc left top right bottom dx dy draw-caret) (define pict (status-pict)) (define c (send this get-canvas)) (when c (define w (send c get-width)) (draw-pict pict dc (- w (pict-width pict) 25 (send c horizontal-inset)) (+ 5 (send c vertical-inset))))) (define-syntax unlocked (syntax-rules () [(_ e ...) (let ((locked? (send this is-locked?))) (dynamic-wind (thunk (when locked? (send this lock #f))) (thunk e ...) (thunk (when locked? (send this lock #t)))))])) (define/public (set-error e) (unlocked (send this reset) (send this change-style (send this text-style)) (send this insert (exn-message e) 0 (send this last-position))) (send this scroll-to-position 0)) (define/public (reset) (unlocked (send this insert "" 0 (send this last-position)) (send this change-style (send this text-style)))) (define/public (spaces n) (send this change-style (send this text-style)) (send this insert (build-string n (lambda (i) #\space)))) (define/public (space) (spaces 1)) (define/public (indent) (spaces (indentation))) (define/public (start-line) (indent)) (define/public (terpri) (send this change-style (send this text-style)) (send this insert "\n") (start-line)) (define (l) (send this change-style (send this parenthesis-style)) (send this insert "(") (send this change-style (send this text-style))) (define (r) (send this change-style (send this parenthesis-style)) (send this insert ")") (send this change-style (send this text-style))) (define-syntax parens (syntax-rules () ((_ e ...) (begin (l) (indented 1 e ...) (r))))) (define-syntax η (syntax-rules () [(η x) (lambda () (x))])) (define (top-binder? sym) (and (symbol? sym) (or (eqv? sym 'Pi) (eqv? sym 'Π) (eqv? sym 'Sigma) (eqv? sym 'Σ)))) (define (ind? sym) (and (symbol? sym) (let ([str (symbol->string sym)]) (and (>= (string-length str) 4) (string=? (substring str 0 4) "ind-"))))) (define (sep s op args) (match args ['() (void)] [(list b) (op b)] [(cons b bs) (op b) (s) (sep s op bs)])) (define (vsep op args) (sep (η terpri) op args)) (define (hsep op args) (sep (η space) op args)) (define (annots bindings) (define (print-binding b) (match b [(list x ty) (parens (print-var x) (space) (indented (+ (string-length (symbol->string x)) 2) (print-pie ty)))])) (vsep print-binding bindings)) (define (atomic? x) (match x [(? symbol?) #t] [(? number?) #t] [(list 'quote _) #t] [_ #f])) (define/public (print-tycon c) (send this change-style (send this type-constructor-style)) (send this insert (symbol->string c)) (send this change-style (send this text-style))) (define/public (print-con c) (send this change-style (send this data-constructor-style)) (send this insert (symbol->string c)) (send this change-style (send this text-style))) (define/public (print-atom c) (send this change-style (send this data-constructor-style)) (send this insert "'") (send this insert (symbol->string c)) (send this change-style (send this text-style))) (define/public (print-lit x) (send this change-style (send this data-constructor-style)) (send this insert (format "~a" x)) (send this change-style (send this text-style))) (define/public (print-elim c) (send this change-style (send this keyword-style)) (send this insert (symbol->string c)) (send this change-style (send this text-style))) (define/public (print-var c) (send this change-style (send this var-style)) (send this insert (symbol->string c)) (send this change-style (send this text-style))) (define (elim? x) (if (memv x '(which-Nat ind-Nat iter-Nat rec-Nat ind-Vec head tail car cdr ind-Absurd the)) #t #f)) (define (tycon? x) (if (memv x '(U Π Pi Σ Sigma Nat Atom Absurd Trivial Pair -> Vec List Either)) #t #f)) (define (con? x) (if (memv x '(cons λ lambda add1 zero :: vec:: nil vecnil sole left right)) #t #f)) (define (print-pie expr) (with-handlers ([exn:fail? (lambda (e) (displayln (exn-message e)) (send this insert (format "~a" expr)))]) (match expr [(list (and b (or 'Π 'Σ)) bindings body) (parens (print-tycon b) (spaces 1) (indented (add1 (string-length (symbol->string b))) (parens (annots bindings))) (terpri) (print-pie body))] [(list (or 'lambda 'λ) (list-rest args) body) (parens (print-con 'λ) (space) (parens (hsep (lambda (x) (print-var x)) args)) (indented 1 (terpri) (print-pie body)))] [(cons '-> (app reverse (cons ret (app reverse args)))) (parens (print-tycon '->) (if (andmap atomic? args) (begin (space) (hsep print-pie args)) (indented 3 (space) (vsep (lambda (x) (print-pie x)) args))) (indented 1 (terpri) (print-pie ret)) )] [(list 'quote x) (print-atom x)] [(list 'TODO loc ty) (print-elim 'TODO)] [(cons (? elim? e) args) (parens (print-elim e) (space) (match args [(list) (void)] [(cons target others) (indented (+ (string-length (symbol->string e)) 1) (print-pie target)) (when (pair? others) (indented 2 (terpri) (vsep (lambda (x) (print-pie x)) others)))]))] [(cons (? con? c) args) (parens (print-con c) (space) (match args [(list) (void)] [(list (? atomic? arg)) (print-pie arg)] [(list arg) (indented 2 (terpri) (print-pie arg))] [(cons fst others) (indented (+ (string-length (symbol->string c)) 1) (print-pie fst)) (indented 2 (terpri) (vsep (lambda (x) (print-pie x)) others))]))] [(list-rest (? symbol? op) (? atomic? arg) args) #:when (and (< (length args) 20) (andmap atomic? args)) (parens (hsep (lambda (x) (print-pie x)) (cons op (cons arg args))))] [(list-rest (? symbol? op) arg args) (parens (print-pie op) (space) (indented (add1 (string-length (symbol->string op))) (print-pie arg)) (indented 1 (when (pair? args) (terpri) (vsep (lambda (x) (print-pie x)) args))))] [(list-rest op args) (parens (print-pie op) (indented 1 (terpri) (vsep (lambda (x) (print-pie x)) args)))] [(? con? c) (print-con c)] [(? tycon? t) (print-tycon t)] [(? symbol? x) (print-var x)] [(? number? n) (print-lit n)] [other (send this insert (format "OOPS[~a]" other))]))) (define/public (pprint-pie expr (description "")) (unlocked (start-line) (indented (string-length description) (when (not (string=? description "")) (send this change-style (send this text-style)) (send this insert description)) (print-pie (resugar expr)))) (send this scroll-to-position 0)) (define/public (pprint-message msg) (unlocked (start-line) (for ([part msg]) (cond [(string? part) (send this change-style (send this text-style)) (send this insert part)] [else (indented 2 (terpri) (print-pie (resugar part))) (terpri)]))) (send this scroll-to-position 0)) (send this lock #t)))
446a4274a2524bdf7afe5e654314ccb8dd72742de2e62ca4f965b213ec58f43d
B-Lang-org/bsc
SpeedyString.hs
{-# LANGUAGE DeriveDataTypeable #-} module SpeedyString(SString, toString, fromString, (++), concat, filter) where import Prelude hiding((++), concat, filter) import qualified Prelude((++), filter) import IOMutVar(MutableVar, newVar, readVar, writeVar) import System.IO.Unsafe(unsafePerformIO) import qualified Data.IntMap as M import qualified NotSoSpeedyString import ErrorUtil (internalError) import qualified Data.Generics as Generic data SString = SString !Int -- unique id deriving (Generic.Data, Generic.Typeable) instance Eq SString where (SString i) == (SString i') = i == i' note that is not the usual string ordering instance Ord SString where compare (SString i) (SString i') = compare i i' instance Show SString where show = show . toString -- public toString :: SString -> String toString (SString id) = unsafePerformIO $ do m <- readVar strings return $ M.findWithDefault err id m fromString :: String -> SString fromString s = unsafePerformIO $ do m <- readVar sstrings return $ maybe (newSString s) id $ M.lookup (hashStr s) m >>= lookup s (++) :: SString -> SString -> SString s ++ s' = fromString $ (toString s) Prelude.++ (toString s') concat :: [SString] -> SString concat = fromString . concatMap toString filter :: (Char -> Bool) -> SString -> SString filter pred s = fromString $ Prelude.filter pred (toString s) -- private newSString :: String -> SString newSString s = unsafePerformIO $ do id <- freshInt let ss = SString id sm <- readVar strings ssm <- readVar sstrings writeVar strings $ M.insert id s sm writeVar sstrings $ M.insertWith (Prelude.++) (hashStr s) [(s,ss)] ssm return ss err :: a err = internalError "SpeedyString: inconsistent representation" --toNotSoSpeedyString :: SString -> NotSoSpeedyString.SString toNotSoSpeedyString speedy = ( toString speedy ) fromNotSoSpeedyString : : NotSoSpeedyString . SString - > SString fromNotSoSpeedyString not_so_speedy = fromString ( NotSoSpeedyString.toString not_so_speedy ) -- internal representation strings :: MutableVar (M.IntMap String) strings = unsafePerformIO $ newVar (M.empty) sstrings :: MutableVar (M.IntMap [(String, SString)]) sstrings = unsafePerformIO $ newVar (M.empty) string hash function , stolen from FString hashStr :: String -> Int hashStr s = f s 0 where f "" r = r f (c:cs) r = f cs (r*16+r+fromEnum c) -- unique id factory nextInt :: MutableVar Int nextInt = unsafePerformIO $ (newVar 0) freshInt :: IO Int freshInt = do fresh <- readVar nextInt writeVar nextInt (fresh + 1) return fresh
null
https://raw.githubusercontent.com/B-Lang-org/bsc/bd141b505394edc5a4bdd3db442a9b0a8c101f0f/src/comp/SpeedyString.hs
haskell
# LANGUAGE DeriveDataTypeable # unique id public private toNotSoSpeedyString :: SString -> NotSoSpeedyString.SString internal representation unique id factory
module SpeedyString(SString, toString, fromString, (++), concat, filter) where import Prelude hiding((++), concat, filter) import qualified Prelude((++), filter) import IOMutVar(MutableVar, newVar, readVar, writeVar) import System.IO.Unsafe(unsafePerformIO) import qualified Data.IntMap as M import qualified NotSoSpeedyString import ErrorUtil (internalError) import qualified Data.Generics as Generic deriving (Generic.Data, Generic.Typeable) instance Eq SString where (SString i) == (SString i') = i == i' note that is not the usual string ordering instance Ord SString where compare (SString i) (SString i') = compare i i' instance Show SString where show = show . toString toString :: SString -> String toString (SString id) = unsafePerformIO $ do m <- readVar strings return $ M.findWithDefault err id m fromString :: String -> SString fromString s = unsafePerformIO $ do m <- readVar sstrings return $ maybe (newSString s) id $ M.lookup (hashStr s) m >>= lookup s (++) :: SString -> SString -> SString s ++ s' = fromString $ (toString s) Prelude.++ (toString s') concat :: [SString] -> SString concat = fromString . concatMap toString filter :: (Char -> Bool) -> SString -> SString filter pred s = fromString $ Prelude.filter pred (toString s) newSString :: String -> SString newSString s = unsafePerformIO $ do id <- freshInt let ss = SString id sm <- readVar strings ssm <- readVar sstrings writeVar strings $ M.insert id s sm writeVar sstrings $ M.insertWith (Prelude.++) (hashStr s) [(s,ss)] ssm return ss err :: a err = internalError "SpeedyString: inconsistent representation" toNotSoSpeedyString speedy = ( toString speedy ) fromNotSoSpeedyString : : NotSoSpeedyString . SString - > SString fromNotSoSpeedyString not_so_speedy = fromString ( NotSoSpeedyString.toString not_so_speedy ) strings :: MutableVar (M.IntMap String) strings = unsafePerformIO $ newVar (M.empty) sstrings :: MutableVar (M.IntMap [(String, SString)]) sstrings = unsafePerformIO $ newVar (M.empty) string hash function , stolen from FString hashStr :: String -> Int hashStr s = f s 0 where f "" r = r f (c:cs) r = f cs (r*16+r+fromEnum c) nextInt :: MutableVar Int nextInt = unsafePerformIO $ (newVar 0) freshInt :: IO Int freshInt = do fresh <- readVar nextInt writeVar nextInt (fresh + 1) return fresh
87e4faf7a096ea250cb9115acf8cda5b5927c26c9086e877a9433a9dffd255ab
emqx/emqx
emqx_conf.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(emqx_conf). -compile({no_auto_import, [get/1, get/2]}). -include_lib("emqx/include/logger.hrl"). -include_lib("hocon/include/hoconsc.hrl"). -export([add_handler/2, remove_handler/1]). -export([get/1, get/2, get_raw/1, get_raw/2, get_all/1]). -export([get_by_node/2, get_by_node/3]). -export([update/3, update/4]). -export([remove/2, remove/3]). -export([reset/2, reset/3]). -export([dump_schema/1, dump_schema/3]). -export([schema_module/0]). -export([gen_example_conf/4]). %% for rpc -export([get_node_and_config/1]). %% API %% @doc Adds a new config handler to emqx_config_handler. -spec add_handler(emqx_config:config_key_path(), module()) -> ok. add_handler(ConfKeyPath, HandlerName) -> emqx_config_handler:add_handler(ConfKeyPath, HandlerName). %% @doc remove config handler from emqx_config_handler. -spec remove_handler(emqx_config:config_key_path()) -> ok. remove_handler(ConfKeyPath) -> emqx_config_handler:remove_handler(ConfKeyPath). -spec get(emqx_map_lib:config_key_path()) -> term(). get(KeyPath) -> emqx:get_config(KeyPath). -spec get(emqx_map_lib:config_key_path(), term()) -> term(). get(KeyPath, Default) -> emqx:get_config(KeyPath, Default). -spec get_raw(emqx_map_lib:config_key_path(), term()) -> term(). get_raw(KeyPath, Default) -> emqx_config:get_raw(KeyPath, Default). -spec get_raw(emqx_map_lib:config_key_path()) -> term(). get_raw(KeyPath) -> emqx_config:get_raw(KeyPath). %% @doc Returns all values in the cluster. -spec get_all(emqx_map_lib:config_key_path()) -> #{node() => term()}. get_all(KeyPath) -> {ResL, []} = emqx_conf_proto_v2:get_all(KeyPath), maps:from_list(ResL). @doc Returns the specified node 's KeyPath , or exception if not found -spec get_by_node(node(), emqx_map_lib:config_key_path()) -> term(). get_by_node(Node, KeyPath) when Node =:= node() -> emqx:get_config(KeyPath); get_by_node(Node, KeyPath) -> emqx_conf_proto_v2:get_config(Node, KeyPath). @doc Returns the specified node 's KeyPath , or the default value if not found -spec get_by_node(node(), emqx_map_lib:config_key_path(), term()) -> term(). get_by_node(Node, KeyPath, Default) when Node =:= node() -> emqx:get_config(KeyPath, Default); get_by_node(Node, KeyPath, Default) -> emqx_conf_proto_v2:get_config(Node, KeyPath, Default). @doc Returns the specified node 's KeyPath , or config_not_found if key path not found -spec get_node_and_config(emqx_map_lib:config_key_path()) -> term(). get_node_and_config(KeyPath) -> {node(), emqx:get_config(KeyPath, config_not_found)}. @doc Update all value of key path in cluster-override.conf or local-override.conf . -spec update( emqx_map_lib:config_key_path(), emqx_config:update_request(), emqx_config:update_opts() ) -> {ok, emqx_config:update_result()} | {error, emqx_config:update_error()}. update(KeyPath, UpdateReq, Opts) -> emqx_conf_proto_v2:update(KeyPath, UpdateReq, Opts). @doc Update the specified node 's key path in local-override.conf . -spec update( node(), emqx_map_lib:config_key_path(), emqx_config:update_request(), emqx_config:update_opts() ) -> {ok, emqx_config:update_result()} | {error, emqx_config:update_error()} | emqx_rpc:badrpc(). update(Node, KeyPath, UpdateReq, Opts0) when Node =:= node() -> emqx:update_config(KeyPath, UpdateReq, Opts0#{override_to => local}); update(Node, KeyPath, UpdateReq, Opts) -> emqx_conf_proto_v2:update(Node, KeyPath, UpdateReq, Opts). @doc remove all value of key path in cluster-override.conf or local-override.conf . -spec remove(emqx_map_lib:config_key_path(), emqx_config:update_opts()) -> {ok, emqx_config:update_result()} | {error, emqx_config:update_error()}. remove(KeyPath, Opts) -> emqx_conf_proto_v2:remove_config(KeyPath, Opts). @doc remove the specified node 's key path in local-override.conf . -spec remove(node(), emqx_map_lib:config_key_path(), emqx_config:update_opts()) -> {ok, emqx_config:update_result()} | {error, emqx_config:update_error()}. remove(Node, KeyPath, Opts) when Node =:= node() -> emqx:remove_config(KeyPath, Opts#{override_to => local}); remove(Node, KeyPath, Opts) -> emqx_conf_proto_v2:remove_config(Node, KeyPath, Opts). @doc reset all value of key path in cluster-override.conf or local-override.conf . -spec reset(emqx_map_lib:config_key_path(), emqx_config:update_opts()) -> {ok, emqx_config:update_result()} | {error, emqx_config:update_error()}. reset(KeyPath, Opts) -> emqx_conf_proto_v2:reset(KeyPath, Opts). @doc reset the specified node 's key path in local-override.conf . -spec reset(node(), emqx_map_lib:config_key_path(), emqx_config:update_opts()) -> {ok, emqx_config:update_result()} | {error, emqx_config:update_error()}. reset(Node, KeyPath, Opts) when Node =:= node() -> emqx:reset_config(KeyPath, Opts#{override_to => local}); reset(Node, KeyPath, Opts) -> emqx_conf_proto_v2:reset(Node, KeyPath, Opts). %% @doc Called from build script. -spec dump_schema(file:name_all()) -> ok. dump_schema(Dir) -> I18nFile = emqx_dashboard:i18n_file(), dump_schema(Dir, emqx_conf_schema, I18nFile). dump_schema(Dir, SchemaModule, I18nFile) -> lists:foreach( fun(Lang) -> gen_config_md(Dir, I18nFile, SchemaModule, Lang), gen_api_schema_json(Dir, I18nFile, Lang), ExampleDir = filename:join(filename:dirname(filename:dirname(I18nFile)), "etc"), gen_example_conf(ExampleDir, I18nFile, SchemaModule, Lang) end, [en, zh] ), gen_schema_json(Dir, I18nFile, SchemaModule). %% for scripts/spellcheck. gen_schema_json(Dir, I18nFile, SchemaModule) -> SchemaJsonFile = filename:join([Dir, "schema.json"]), io:format(user, "===< Generating: ~s~n", [SchemaJsonFile]), Opts = #{desc_file => I18nFile, lang => "en"}, JsonMap = hocon_schema_json:gen(SchemaModule, Opts), IoData = jsx:encode(JsonMap, [space, {indent, 4}]), ok = file:write_file(SchemaJsonFile, IoData). gen_api_schema_json(Dir, I18nFile, Lang) -> emqx_dashboard:init_i18n(I18nFile, Lang), gen_api_schema_json_hotconf(Dir, Lang), gen_api_schema_json_bridge(Dir, Lang), emqx_dashboard:clear_i18n(). gen_api_schema_json_hotconf(Dir, Lang) -> SchemaInfo = #{title => <<"EMQX Hot Conf API Schema">>, version => <<"0.1.0">>}, File = schema_filename(Dir, "hot-config-schema-", Lang), ok = do_gen_api_schema_json(File, emqx_mgmt_api_configs, SchemaInfo). gen_api_schema_json_bridge(Dir, Lang) -> SchemaInfo = #{title => <<"EMQX Data Bridge API Schema">>, version => <<"0.1.0">>}, File = schema_filename(Dir, "bridge-api-", Lang), ok = do_gen_api_schema_json(File, emqx_bridge_api, SchemaInfo). schema_filename(Dir, Prefix, Lang) -> Filename = Prefix ++ atom_to_list(Lang) ++ ".json", filename:join([Dir, Filename]). gen_config_md(Dir, I18nFile, SchemaModule, Lang0) -> Lang = atom_to_list(Lang0), SchemaMdFile = filename:join([Dir, "config-" ++ Lang ++ ".md"]), io:format(user, "===< Generating: ~s~n", [SchemaMdFile]), ok = gen_doc(SchemaMdFile, SchemaModule, I18nFile, Lang). gen_example_conf(Dir, I18nFile, SchemaModule, Lang0) -> Lang = atom_to_list(Lang0), SchemaMdFile = filename:join([Dir, "emqx.conf." ++ Lang ++ ".example"]), io:format(user, "===< Generating: ~s~n", [SchemaMdFile]), ok = gen_example(SchemaMdFile, SchemaModule, I18nFile, Lang). %% @doc return the root schema module. -spec schema_module() -> module(). schema_module() -> case os:getenv("SCHEMA_MOD") of false -> emqx_conf_schema; Value -> list_to_existing_atom(Value) end. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- -spec gen_doc(file:name_all(), module(), file:name_all(), string()) -> ok. gen_doc(File, SchemaModule, I18nFile, Lang) -> Version = emqx_release:version(), Title = "# " ++ emqx_release:description() ++ " Configuration\n\n" ++ "<!--" ++ Version ++ "-->", BodyFile = filename:join([rel, "emqx_conf.template." ++ Lang ++ ".md"]), {ok, Body} = file:read_file(BodyFile), Opts = #{title => Title, body => Body, desc_file => I18nFile, lang => Lang}, Doc = hocon_schema_md:gen(SchemaModule, Opts), file:write_file(File, Doc). gen_example(File, SchemaModule, I18nFile, Lang) -> Opts = #{ title => <<"EMQX Configuration Example">>, body => <<"">>, desc_file => I18nFile, lang => Lang }, Example = hocon_schema_example:gen(SchemaModule, Opts), file:write_file(File, Example). %% Only gen hot_conf schema, not all configuration fields. do_gen_api_schema_json(File, SchemaMod, SchemaInfo) -> io:format(user, "===< Generating: ~s~n", [File]), {ApiSpec0, Components0} = emqx_dashboard_swagger:spec( SchemaMod, #{schema_converter => fun hocon_schema_to_spec/2} ), ApiSpec = lists:foldl( fun({Path, Spec, _, _}, Acc) -> NewSpec = maps:fold( fun(Method, #{responses := Responses}, SubAcc) -> case Responses of #{ <<"200">> := #{ <<"content">> := #{ <<"application/json">> := #{<<"schema">> := Schema} } } } -> SubAcc#{Method => Schema}; _ -> SubAcc end end, #{}, Spec ), Acc#{list_to_atom(Path) => NewSpec} end, #{}, ApiSpec0 ), Components = lists:foldl(fun(M, Acc) -> maps:merge(M, Acc) end, #{}, Components0), IoData = jsx:encode( #{ info => SchemaInfo, paths => ApiSpec, components => #{schemas => Components} }, [space, {indent, 4}] ), file:write_file(File, IoData). -define(INIT_SCHEMA, #{ fields => #{}, translations => #{}, validations => [], namespace => undefined }). -define(TO_REF(_N_, _F_), iolist_to_binary([to_bin(_N_), ".", to_bin(_F_)])). -define(TO_COMPONENTS_SCHEMA(_M_, _F_), iolist_to_binary([ <<"#/components/schemas/">>, ?TO_REF(emqx_dashboard_swagger:namespace(_M_), _F_) ]) ). hocon_schema_to_spec(?R_REF(Module, StructName), _LocalModule) -> {#{<<"$ref">> => ?TO_COMPONENTS_SCHEMA(Module, StructName)}, [{Module, StructName}]}; hocon_schema_to_spec(?REF(StructName), LocalModule) -> {#{<<"$ref">> => ?TO_COMPONENTS_SCHEMA(LocalModule, StructName)}, [{LocalModule, StructName}]}; hocon_schema_to_spec(Type, LocalModule) when ?IS_TYPEREFL(Type) -> {typename_to_spec(typerefl:name(Type), LocalModule), []}; hocon_schema_to_spec(?ARRAY(Item), LocalModule) -> {Schema, Refs} = hocon_schema_to_spec(Item, LocalModule), {#{type => array, items => Schema}, Refs}; hocon_schema_to_spec(?ENUM(Items), _LocalModule) -> {#{type => enum, symbols => Items}, []}; hocon_schema_to_spec(?MAP(Name, Type), LocalModule) -> {Schema, SubRefs} = hocon_schema_to_spec(Type, LocalModule), { #{ <<"type">> => object, <<"properties">> => #{<<"$", (to_bin(Name))/binary>> => Schema} }, SubRefs }; hocon_schema_to_spec(?UNION(Types), LocalModule) -> {OneOf, Refs} = lists:foldl( fun(Type, {Acc, RefsAcc}) -> {Schema, SubRefs} = hocon_schema_to_spec(Type, LocalModule), {[Schema | Acc], SubRefs ++ RefsAcc} end, {[], []}, hoconsc:union_members(Types) ), {#{<<"oneOf">> => OneOf}, Refs}; hocon_schema_to_spec(Atom, _LocalModule) when is_atom(Atom) -> {#{type => enum, symbols => [Atom]}, []}. typename_to_spec("user_id_type()", _Mod) -> #{type => enum, symbols => [clientid, username]}; typename_to_spec("term()", _Mod) -> #{type => string}; typename_to_spec("boolean()", _Mod) -> #{type => boolean}; typename_to_spec("binary()", _Mod) -> #{type => string}; typename_to_spec("float()", _Mod) -> #{type => number}; typename_to_spec("integer()", _Mod) -> #{type => number}; typename_to_spec("non_neg_integer()", _Mod) -> #{type => number, minimum => 1}; typename_to_spec("number()", _Mod) -> #{type => number}; typename_to_spec("string()", _Mod) -> #{type => string}; typename_to_spec("atom()", _Mod) -> #{type => string}; typename_to_spec("duration()", _Mod) -> #{type => duration}; typename_to_spec("duration_s()", _Mod) -> #{type => duration}; typename_to_spec("duration_ms()", _Mod) -> #{type => duration}; typename_to_spec("percent()", _Mod) -> #{type => percent}; typename_to_spec("file()", _Mod) -> #{type => string}; typename_to_spec("ip_port()", _Mod) -> #{type => ip_port}; typename_to_spec("url()", _Mod) -> #{type => url}; typename_to_spec("bytesize()", _Mod) -> #{type => 'byteSize'}; typename_to_spec("wordsize()", _Mod) -> #{type => 'byteSize'}; typename_to_spec("qos()", _Mod) -> #{type => enum, symbols => [0, 1, 2]}; typename_to_spec("comma_separated_list()", _Mod) -> #{type => comma_separated_string}; typename_to_spec("comma_separated_atoms()", _Mod) -> #{type => comma_separated_string}; typename_to_spec("pool_type()", _Mod) -> #{type => enum, symbols => [random, hash]}; typename_to_spec("log_level()", _Mod) -> #{ type => enum, symbols => [ debug, info, notice, warning, error, critical, alert, emergency, all ] }; typename_to_spec("rate()", _Mod) -> #{type => string}; typename_to_spec("capacity()", _Mod) -> #{type => string}; typename_to_spec("burst_rate()", _Mod) -> #{type => string}; typename_to_spec("failure_strategy()", _Mod) -> #{type => enum, symbols => [force, drop, throw]}; typename_to_spec("initial()", _Mod) -> #{type => string}; typename_to_spec("map()", _Mod) -> #{type => object}; typename_to_spec("#{" ++ _, Mod) -> typename_to_spec("map()", Mod); typename_to_spec(Name, Mod) -> Spec = range(Name), Spec1 = remote_module_type(Spec, Name, Mod), Spec2 = typerefl_array(Spec1, Name, Mod), Spec3 = integer(Spec2, Name), default_type(Spec3). default_type(nomatch) -> #{type => string}; default_type(Type) -> Type. range(Name) -> case string:split(Name, "..") of 1 .. 10 1 .. inf -inf .. 10 [MinStr, MaxStr] -> Schema = #{type => number}, Schema1 = add_integer_prop(Schema, minimum, MinStr), add_integer_prop(Schema1, maximum, MaxStr); _ -> nomatch end. %% Module:Type remote_module_type(nomatch, Name, Mod) -> case string:split(Name, ":") of [_Module, Type] -> typename_to_spec(Type, Mod); _ -> nomatch end; remote_module_type(Spec, _Name, _Mod) -> Spec. %% [string()] or [integer()] or [xxx]. typerefl_array(nomatch, Name, Mod) -> case string:trim(Name, leading, "[") of Name -> nomatch; Name1 -> case string:trim(Name1, trailing, "]") of Name1 -> notmatch; Name2 -> Schema = typename_to_spec(Name2, Mod), #{type => array, items => Schema} end end; typerefl_array(Spec, _Name, _Mod) -> Spec. %% integer(1) integer(nomatch, Name) -> case string:to_integer(Name) of {Int, []} -> #{type => enum, symbols => [Int], default => Int}; _ -> nomatch end; integer(Spec, _Name) -> Spec. add_integer_prop(Schema, Key, Value) -> case string:to_integer(Value) of {error, no_integer} -> Schema; {Int, []} when Key =:= minimum -> Schema#{Key => Int}; {Int, []} -> Schema#{Key => Int} end. to_bin(List) when is_list(List) -> case io_lib:printable_list(List) of true -> unicode:characters_to_binary(List); false -> List end; to_bin(Boolean) when is_boolean(Boolean) -> Boolean; to_bin(Atom) when is_atom(Atom) -> atom_to_binary(Atom, utf8); to_bin(X) -> X.
null
https://raw.githubusercontent.com/emqx/emqx/73d5592b5af0cbbf347e5dc2b9b865b41228249f/apps/emqx_conf/src/emqx_conf.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. -------------------------------------------------------------------- for rpc API @doc Adds a new config handler to emqx_config_handler. @doc remove config handler from emqx_config_handler. @doc Returns all values in the cluster. @doc Called from build script. for scripts/spellcheck. @doc return the root schema module. -------------------------------------------------------------------- -------------------------------------------------------------------- Only gen hot_conf schema, not all configuration fields. Module:Type [string()] or [integer()] or [xxx]. integer(1)
Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_conf). -compile({no_auto_import, [get/1, get/2]}). -include_lib("emqx/include/logger.hrl"). -include_lib("hocon/include/hoconsc.hrl"). -export([add_handler/2, remove_handler/1]). -export([get/1, get/2, get_raw/1, get_raw/2, get_all/1]). -export([get_by_node/2, get_by_node/3]). -export([update/3, update/4]). -export([remove/2, remove/3]). -export([reset/2, reset/3]). -export([dump_schema/1, dump_schema/3]). -export([schema_module/0]). -export([gen_example_conf/4]). -export([get_node_and_config/1]). -spec add_handler(emqx_config:config_key_path(), module()) -> ok. add_handler(ConfKeyPath, HandlerName) -> emqx_config_handler:add_handler(ConfKeyPath, HandlerName). -spec remove_handler(emqx_config:config_key_path()) -> ok. remove_handler(ConfKeyPath) -> emqx_config_handler:remove_handler(ConfKeyPath). -spec get(emqx_map_lib:config_key_path()) -> term(). get(KeyPath) -> emqx:get_config(KeyPath). -spec get(emqx_map_lib:config_key_path(), term()) -> term(). get(KeyPath, Default) -> emqx:get_config(KeyPath, Default). -spec get_raw(emqx_map_lib:config_key_path(), term()) -> term(). get_raw(KeyPath, Default) -> emqx_config:get_raw(KeyPath, Default). -spec get_raw(emqx_map_lib:config_key_path()) -> term(). get_raw(KeyPath) -> emqx_config:get_raw(KeyPath). -spec get_all(emqx_map_lib:config_key_path()) -> #{node() => term()}. get_all(KeyPath) -> {ResL, []} = emqx_conf_proto_v2:get_all(KeyPath), maps:from_list(ResL). @doc Returns the specified node 's KeyPath , or exception if not found -spec get_by_node(node(), emqx_map_lib:config_key_path()) -> term(). get_by_node(Node, KeyPath) when Node =:= node() -> emqx:get_config(KeyPath); get_by_node(Node, KeyPath) -> emqx_conf_proto_v2:get_config(Node, KeyPath). @doc Returns the specified node 's KeyPath , or the default value if not found -spec get_by_node(node(), emqx_map_lib:config_key_path(), term()) -> term(). get_by_node(Node, KeyPath, Default) when Node =:= node() -> emqx:get_config(KeyPath, Default); get_by_node(Node, KeyPath, Default) -> emqx_conf_proto_v2:get_config(Node, KeyPath, Default). @doc Returns the specified node 's KeyPath , or config_not_found if key path not found -spec get_node_and_config(emqx_map_lib:config_key_path()) -> term(). get_node_and_config(KeyPath) -> {node(), emqx:get_config(KeyPath, config_not_found)}. @doc Update all value of key path in cluster-override.conf or local-override.conf . -spec update( emqx_map_lib:config_key_path(), emqx_config:update_request(), emqx_config:update_opts() ) -> {ok, emqx_config:update_result()} | {error, emqx_config:update_error()}. update(KeyPath, UpdateReq, Opts) -> emqx_conf_proto_v2:update(KeyPath, UpdateReq, Opts). @doc Update the specified node 's key path in local-override.conf . -spec update( node(), emqx_map_lib:config_key_path(), emqx_config:update_request(), emqx_config:update_opts() ) -> {ok, emqx_config:update_result()} | {error, emqx_config:update_error()} | emqx_rpc:badrpc(). update(Node, KeyPath, UpdateReq, Opts0) when Node =:= node() -> emqx:update_config(KeyPath, UpdateReq, Opts0#{override_to => local}); update(Node, KeyPath, UpdateReq, Opts) -> emqx_conf_proto_v2:update(Node, KeyPath, UpdateReq, Opts). @doc remove all value of key path in cluster-override.conf or local-override.conf . -spec remove(emqx_map_lib:config_key_path(), emqx_config:update_opts()) -> {ok, emqx_config:update_result()} | {error, emqx_config:update_error()}. remove(KeyPath, Opts) -> emqx_conf_proto_v2:remove_config(KeyPath, Opts). @doc remove the specified node 's key path in local-override.conf . -spec remove(node(), emqx_map_lib:config_key_path(), emqx_config:update_opts()) -> {ok, emqx_config:update_result()} | {error, emqx_config:update_error()}. remove(Node, KeyPath, Opts) when Node =:= node() -> emqx:remove_config(KeyPath, Opts#{override_to => local}); remove(Node, KeyPath, Opts) -> emqx_conf_proto_v2:remove_config(Node, KeyPath, Opts). @doc reset all value of key path in cluster-override.conf or local-override.conf . -spec reset(emqx_map_lib:config_key_path(), emqx_config:update_opts()) -> {ok, emqx_config:update_result()} | {error, emqx_config:update_error()}. reset(KeyPath, Opts) -> emqx_conf_proto_v2:reset(KeyPath, Opts). @doc reset the specified node 's key path in local-override.conf . -spec reset(node(), emqx_map_lib:config_key_path(), emqx_config:update_opts()) -> {ok, emqx_config:update_result()} | {error, emqx_config:update_error()}. reset(Node, KeyPath, Opts) when Node =:= node() -> emqx:reset_config(KeyPath, Opts#{override_to => local}); reset(Node, KeyPath, Opts) -> emqx_conf_proto_v2:reset(Node, KeyPath, Opts). -spec dump_schema(file:name_all()) -> ok. dump_schema(Dir) -> I18nFile = emqx_dashboard:i18n_file(), dump_schema(Dir, emqx_conf_schema, I18nFile). dump_schema(Dir, SchemaModule, I18nFile) -> lists:foreach( fun(Lang) -> gen_config_md(Dir, I18nFile, SchemaModule, Lang), gen_api_schema_json(Dir, I18nFile, Lang), ExampleDir = filename:join(filename:dirname(filename:dirname(I18nFile)), "etc"), gen_example_conf(ExampleDir, I18nFile, SchemaModule, Lang) end, [en, zh] ), gen_schema_json(Dir, I18nFile, SchemaModule). gen_schema_json(Dir, I18nFile, SchemaModule) -> SchemaJsonFile = filename:join([Dir, "schema.json"]), io:format(user, "===< Generating: ~s~n", [SchemaJsonFile]), Opts = #{desc_file => I18nFile, lang => "en"}, JsonMap = hocon_schema_json:gen(SchemaModule, Opts), IoData = jsx:encode(JsonMap, [space, {indent, 4}]), ok = file:write_file(SchemaJsonFile, IoData). gen_api_schema_json(Dir, I18nFile, Lang) -> emqx_dashboard:init_i18n(I18nFile, Lang), gen_api_schema_json_hotconf(Dir, Lang), gen_api_schema_json_bridge(Dir, Lang), emqx_dashboard:clear_i18n(). gen_api_schema_json_hotconf(Dir, Lang) -> SchemaInfo = #{title => <<"EMQX Hot Conf API Schema">>, version => <<"0.1.0">>}, File = schema_filename(Dir, "hot-config-schema-", Lang), ok = do_gen_api_schema_json(File, emqx_mgmt_api_configs, SchemaInfo). gen_api_schema_json_bridge(Dir, Lang) -> SchemaInfo = #{title => <<"EMQX Data Bridge API Schema">>, version => <<"0.1.0">>}, File = schema_filename(Dir, "bridge-api-", Lang), ok = do_gen_api_schema_json(File, emqx_bridge_api, SchemaInfo). schema_filename(Dir, Prefix, Lang) -> Filename = Prefix ++ atom_to_list(Lang) ++ ".json", filename:join([Dir, Filename]). gen_config_md(Dir, I18nFile, SchemaModule, Lang0) -> Lang = atom_to_list(Lang0), SchemaMdFile = filename:join([Dir, "config-" ++ Lang ++ ".md"]), io:format(user, "===< Generating: ~s~n", [SchemaMdFile]), ok = gen_doc(SchemaMdFile, SchemaModule, I18nFile, Lang). gen_example_conf(Dir, I18nFile, SchemaModule, Lang0) -> Lang = atom_to_list(Lang0), SchemaMdFile = filename:join([Dir, "emqx.conf." ++ Lang ++ ".example"]), io:format(user, "===< Generating: ~s~n", [SchemaMdFile]), ok = gen_example(SchemaMdFile, SchemaModule, I18nFile, Lang). -spec schema_module() -> module(). schema_module() -> case os:getenv("SCHEMA_MOD") of false -> emqx_conf_schema; Value -> list_to_existing_atom(Value) end. Internal functions -spec gen_doc(file:name_all(), module(), file:name_all(), string()) -> ok. gen_doc(File, SchemaModule, I18nFile, Lang) -> Version = emqx_release:version(), Title = "# " ++ emqx_release:description() ++ " Configuration\n\n" ++ "<!--" ++ Version ++ "-->", BodyFile = filename:join([rel, "emqx_conf.template." ++ Lang ++ ".md"]), {ok, Body} = file:read_file(BodyFile), Opts = #{title => Title, body => Body, desc_file => I18nFile, lang => Lang}, Doc = hocon_schema_md:gen(SchemaModule, Opts), file:write_file(File, Doc). gen_example(File, SchemaModule, I18nFile, Lang) -> Opts = #{ title => <<"EMQX Configuration Example">>, body => <<"">>, desc_file => I18nFile, lang => Lang }, Example = hocon_schema_example:gen(SchemaModule, Opts), file:write_file(File, Example). do_gen_api_schema_json(File, SchemaMod, SchemaInfo) -> io:format(user, "===< Generating: ~s~n", [File]), {ApiSpec0, Components0} = emqx_dashboard_swagger:spec( SchemaMod, #{schema_converter => fun hocon_schema_to_spec/2} ), ApiSpec = lists:foldl( fun({Path, Spec, _, _}, Acc) -> NewSpec = maps:fold( fun(Method, #{responses := Responses}, SubAcc) -> case Responses of #{ <<"200">> := #{ <<"content">> := #{ <<"application/json">> := #{<<"schema">> := Schema} } } } -> SubAcc#{Method => Schema}; _ -> SubAcc end end, #{}, Spec ), Acc#{list_to_atom(Path) => NewSpec} end, #{}, ApiSpec0 ), Components = lists:foldl(fun(M, Acc) -> maps:merge(M, Acc) end, #{}, Components0), IoData = jsx:encode( #{ info => SchemaInfo, paths => ApiSpec, components => #{schemas => Components} }, [space, {indent, 4}] ), file:write_file(File, IoData). -define(INIT_SCHEMA, #{ fields => #{}, translations => #{}, validations => [], namespace => undefined }). -define(TO_REF(_N_, _F_), iolist_to_binary([to_bin(_N_), ".", to_bin(_F_)])). -define(TO_COMPONENTS_SCHEMA(_M_, _F_), iolist_to_binary([ <<"#/components/schemas/">>, ?TO_REF(emqx_dashboard_swagger:namespace(_M_), _F_) ]) ). hocon_schema_to_spec(?R_REF(Module, StructName), _LocalModule) -> {#{<<"$ref">> => ?TO_COMPONENTS_SCHEMA(Module, StructName)}, [{Module, StructName}]}; hocon_schema_to_spec(?REF(StructName), LocalModule) -> {#{<<"$ref">> => ?TO_COMPONENTS_SCHEMA(LocalModule, StructName)}, [{LocalModule, StructName}]}; hocon_schema_to_spec(Type, LocalModule) when ?IS_TYPEREFL(Type) -> {typename_to_spec(typerefl:name(Type), LocalModule), []}; hocon_schema_to_spec(?ARRAY(Item), LocalModule) -> {Schema, Refs} = hocon_schema_to_spec(Item, LocalModule), {#{type => array, items => Schema}, Refs}; hocon_schema_to_spec(?ENUM(Items), _LocalModule) -> {#{type => enum, symbols => Items}, []}; hocon_schema_to_spec(?MAP(Name, Type), LocalModule) -> {Schema, SubRefs} = hocon_schema_to_spec(Type, LocalModule), { #{ <<"type">> => object, <<"properties">> => #{<<"$", (to_bin(Name))/binary>> => Schema} }, SubRefs }; hocon_schema_to_spec(?UNION(Types), LocalModule) -> {OneOf, Refs} = lists:foldl( fun(Type, {Acc, RefsAcc}) -> {Schema, SubRefs} = hocon_schema_to_spec(Type, LocalModule), {[Schema | Acc], SubRefs ++ RefsAcc} end, {[], []}, hoconsc:union_members(Types) ), {#{<<"oneOf">> => OneOf}, Refs}; hocon_schema_to_spec(Atom, _LocalModule) when is_atom(Atom) -> {#{type => enum, symbols => [Atom]}, []}. typename_to_spec("user_id_type()", _Mod) -> #{type => enum, symbols => [clientid, username]}; typename_to_spec("term()", _Mod) -> #{type => string}; typename_to_spec("boolean()", _Mod) -> #{type => boolean}; typename_to_spec("binary()", _Mod) -> #{type => string}; typename_to_spec("float()", _Mod) -> #{type => number}; typename_to_spec("integer()", _Mod) -> #{type => number}; typename_to_spec("non_neg_integer()", _Mod) -> #{type => number, minimum => 1}; typename_to_spec("number()", _Mod) -> #{type => number}; typename_to_spec("string()", _Mod) -> #{type => string}; typename_to_spec("atom()", _Mod) -> #{type => string}; typename_to_spec("duration()", _Mod) -> #{type => duration}; typename_to_spec("duration_s()", _Mod) -> #{type => duration}; typename_to_spec("duration_ms()", _Mod) -> #{type => duration}; typename_to_spec("percent()", _Mod) -> #{type => percent}; typename_to_spec("file()", _Mod) -> #{type => string}; typename_to_spec("ip_port()", _Mod) -> #{type => ip_port}; typename_to_spec("url()", _Mod) -> #{type => url}; typename_to_spec("bytesize()", _Mod) -> #{type => 'byteSize'}; typename_to_spec("wordsize()", _Mod) -> #{type => 'byteSize'}; typename_to_spec("qos()", _Mod) -> #{type => enum, symbols => [0, 1, 2]}; typename_to_spec("comma_separated_list()", _Mod) -> #{type => comma_separated_string}; typename_to_spec("comma_separated_atoms()", _Mod) -> #{type => comma_separated_string}; typename_to_spec("pool_type()", _Mod) -> #{type => enum, symbols => [random, hash]}; typename_to_spec("log_level()", _Mod) -> #{ type => enum, symbols => [ debug, info, notice, warning, error, critical, alert, emergency, all ] }; typename_to_spec("rate()", _Mod) -> #{type => string}; typename_to_spec("capacity()", _Mod) -> #{type => string}; typename_to_spec("burst_rate()", _Mod) -> #{type => string}; typename_to_spec("failure_strategy()", _Mod) -> #{type => enum, symbols => [force, drop, throw]}; typename_to_spec("initial()", _Mod) -> #{type => string}; typename_to_spec("map()", _Mod) -> #{type => object}; typename_to_spec("#{" ++ _, Mod) -> typename_to_spec("map()", Mod); typename_to_spec(Name, Mod) -> Spec = range(Name), Spec1 = remote_module_type(Spec, Name, Mod), Spec2 = typerefl_array(Spec1, Name, Mod), Spec3 = integer(Spec2, Name), default_type(Spec3). default_type(nomatch) -> #{type => string}; default_type(Type) -> Type. range(Name) -> case string:split(Name, "..") of 1 .. 10 1 .. inf -inf .. 10 [MinStr, MaxStr] -> Schema = #{type => number}, Schema1 = add_integer_prop(Schema, minimum, MinStr), add_integer_prop(Schema1, maximum, MaxStr); _ -> nomatch end. remote_module_type(nomatch, Name, Mod) -> case string:split(Name, ":") of [_Module, Type] -> typename_to_spec(Type, Mod); _ -> nomatch end; remote_module_type(Spec, _Name, _Mod) -> Spec. typerefl_array(nomatch, Name, Mod) -> case string:trim(Name, leading, "[") of Name -> nomatch; Name1 -> case string:trim(Name1, trailing, "]") of Name1 -> notmatch; Name2 -> Schema = typename_to_spec(Name2, Mod), #{type => array, items => Schema} end end; typerefl_array(Spec, _Name, _Mod) -> Spec. integer(nomatch, Name) -> case string:to_integer(Name) of {Int, []} -> #{type => enum, symbols => [Int], default => Int}; _ -> nomatch end; integer(Spec, _Name) -> Spec. add_integer_prop(Schema, Key, Value) -> case string:to_integer(Value) of {error, no_integer} -> Schema; {Int, []} when Key =:= minimum -> Schema#{Key => Int}; {Int, []} -> Schema#{Key => Int} end. to_bin(List) when is_list(List) -> case io_lib:printable_list(List) of true -> unicode:characters_to_binary(List); false -> List end; to_bin(Boolean) when is_boolean(Boolean) -> Boolean; to_bin(Atom) when is_atom(Atom) -> atom_to_binary(Atom, utf8); to_bin(X) -> X.
bb5da43aca1bd8c4dc604733f5fc81dc8db4147514b4893d44a47fab4055115e
census-instrumentation/opencensus-erlang
oc_tag_ctx_header.erl
%%%------------------------------------------------------------------------- Copyright 2018 , OpenCensus Authors Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% @doc Functions to support sending tags over http as an http header %% @end %%%------------------------------------------------------------------------- -module(oc_tag_ctx_header). -export([field_name/0, encode/1, decode/1, format_error/1]). -include("opencensus.hrl"). field_name() -> <<"tracestate">>. -spec encode(oc_tags:tags()) -> maybe(iodata()). encode(Tags) when map_size(Tags) =:= 0 -> <<"0">>; encode(Tags) -> {ok, IOList} = oc_tag_ctx_binary:encode(Tags), base64:encode_to_string(iolist_to_binary(IOList)). -spec decode(iodata()) -> {ok, oc_tags:tags()} | {error, any()}. decode("0") -> {ok, oc_tags:new()}; decode(<<"0">>) -> {ok, oc_tags:new()}; decode(Thing) -> try base64:decode(iolist_to_binary(Thing)) of Data -> oc_tag_ctx_binary:decode(Data) catch _:_ -> {error, {?MODULE, base64_decode_failed}} end. format_error(base64_decode_failed) -> "invalid tag context: tag context header value not base64 encoded".
null
https://raw.githubusercontent.com/census-instrumentation/opencensus-erlang/7fb276ff73d677c00458922c9180df634f45e018/src/oc_tag_ctx_header.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 Functions to support sending tags over http as an http header @end -------------------------------------------------------------------------
Copyright 2018 , OpenCensus Authors Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(oc_tag_ctx_header). -export([field_name/0, encode/1, decode/1, format_error/1]). -include("opencensus.hrl"). field_name() -> <<"tracestate">>. -spec encode(oc_tags:tags()) -> maybe(iodata()). encode(Tags) when map_size(Tags) =:= 0 -> <<"0">>; encode(Tags) -> {ok, IOList} = oc_tag_ctx_binary:encode(Tags), base64:encode_to_string(iolist_to_binary(IOList)). -spec decode(iodata()) -> {ok, oc_tags:tags()} | {error, any()}. decode("0") -> {ok, oc_tags:new()}; decode(<<"0">>) -> {ok, oc_tags:new()}; decode(Thing) -> try base64:decode(iolist_to_binary(Thing)) of Data -> oc_tag_ctx_binary:decode(Data) catch _:_ -> {error, {?MODULE, base64_decode_failed}} end. format_error(base64_decode_failed) -> "invalid tag context: tag context header value not base64 encoded".
66448b317b44df6a567c3b0194b0c64bce38afcd13cd3dd77ea461080b64e3c0
jrh13/hol-light
pa_j_3.1x_6.02.1.ml
(* ------------------------------------------------------------------------- *) (* New version. *) (* ------------------------------------------------------------------------- *) (* camlp5r *) $ I d : pa_o.ml , v 6.33 2010 - 11 - 16 16:48:21 deraugla Exp $ Copyright ( c ) INRIA 2007 - 2010 #load "pa_extend.cmo"; #load "q_MLast.cmo"; #load "pa_reloc.cmo"; open Pcaml; Pcaml.syntax_name.val := "OCaml"; Pcaml.no_constructors_arity.val := True; (* ------------------------------------------------------------------------- *) (* The main/reloc.ml file. *) (* ------------------------------------------------------------------------- *) (* camlp5r *) $ I d : reloc.ml , v 6.16 2010 - 11 - 21 17:17:45 deraugla Exp $ Copyright ( c ) INRIA 2007 - 2010 #load "pa_macro.cmo"; open MLast; value option_map f = fun [ Some x -> Some (f x) | None -> None ] ; value vala_map f = IFNDEF STRICT THEN fun x -> f x ELSE fun [ Ploc.VaAnt s -> Ploc.VaAnt s | Ploc.VaVal x -> Ploc.VaVal (f x) ] END ; value class_infos_map floc f x = {ciLoc = floc x.ciLoc; ciVir = x.ciVir; ciPrm = let (x1, x2) = x.ciPrm in (floc x1, x2); ciNam = x.ciNam; ciExp = f x.ciExp} ; value anti_loc qloc sh loc loc1 = (* ...<:expr<.....$lid:...xxxxxxxx...$...>>... |..|-----------------------------------| qloc <-----> sh |.........|------------| loc |..|------| loc1 *) let sh1 = Ploc.first_pos qloc + sh in let sh2 = sh1 + Ploc.first_pos loc in let line_nb_qloc = Ploc.line_nb qloc in let line_nb_loc = Ploc.line_nb loc in let line_nb_loc1 = Ploc.line_nb loc1 in if line_nb_qloc < 0 || line_nb_loc < 0 || line_nb_loc1 < 0 then Ploc.make_unlined (sh2 + Ploc.first_pos loc1, sh2 + Ploc.last_pos loc1) else Ploc.make_loc (Ploc.file_name loc) (line_nb_qloc + line_nb_loc + line_nb_loc1 - 2) (if line_nb_loc1 = 1 then if line_nb_loc = 1 then Ploc.bol_pos qloc else sh1 + Ploc.bol_pos loc else sh2 + Ploc.bol_pos loc1) (sh2 + Ploc.first_pos loc1, sh2 + Ploc.last_pos loc1) "" ; value rec reloc_ctyp floc sh = self where rec self = fun [ TyAcc loc x1 x2 -> let loc = floc loc in TyAcc loc (self x1) (self x2) | TyAli loc x1 x2 -> let loc = floc loc in TyAli loc (self x1) (self x2) | TyAny loc -> let loc = floc loc in TyAny loc | TyApp loc x1 x2 -> let loc = floc loc in TyApp loc (self x1) (self x2) | TyArr loc x1 x2 -> let loc = floc loc in TyArr loc (self x1) (self x2) | TyCls loc x1 -> let loc = floc loc in TyCls loc x1 | TyLab loc x1 x2 -> let loc = floc loc in TyLab loc x1 (self x2) | TyLid loc x1 -> let loc = floc loc in TyLid loc x1 | TyMan loc x1 x2 x3 -> let loc = floc loc in TyMan loc (self x1) x2 (self x3) | TyObj loc x1 x2 -> let loc = floc loc in TyObj loc (vala_map (List.map (fun (x1, x2) -> (x1, self x2))) x1) x2 | TyOlb loc x1 x2 -> let loc = floc loc in TyOlb loc x1 (self x2) | TyPck loc x1 -> let loc = floc loc in TyPck loc (reloc_module_type floc sh x1) | TyPol loc x1 x2 -> let loc = floc loc in TyPol loc x1 (self x2) | TyPot loc x1 x2 -> let loc = floc loc in TyPot loc x1 (self x2) | TyQuo loc x1 -> let loc = floc loc in TyQuo loc x1 | TyRec loc x1 -> let loc = floc loc in TyRec loc (vala_map (List.map (fun (loc, x1, x2, x3) -> (floc loc, x1, x2, self x3))) x1) | TySum loc x1 -> let loc = floc loc in TySum loc (vala_map (List.map (fun (loc, x1, x2, x3) -> (floc loc, x1, vala_map (List.map self) x2, option_map self x3))) x1) | TyTup loc x1 -> let loc = floc loc in TyTup loc (vala_map (List.map self) x1) | TyUid loc x1 -> let loc = floc loc in TyUid loc x1 | TyVrn loc x1 x2 -> let loc = floc loc in TyVrn loc (vala_map (List.map (reloc_poly_variant floc sh)) x1) x2 | IFDEF STRICT THEN TyXtr loc x1 x2 -> let loc = floc loc in TyXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_poly_variant floc sh = fun [ PvTag loc x1 x2 x3 -> let loc = floc loc in PvTag loc x1 x2 (vala_map (List.map (reloc_ctyp floc sh)) x3) | PvInh loc x1 -> let loc = floc loc in PvInh loc (reloc_ctyp floc sh x1) ] and reloc_patt floc sh = self where rec self = fun [ PaAcc loc x1 x2 -> let loc = floc loc in PaAcc loc (self x1) (self x2) | PaAli loc x1 x2 -> let loc = floc loc in PaAli loc (self x1) (self x2) | PaAnt loc x1 -> let new_floc loc1 = anti_loc (floc loc) sh loc loc1 in reloc_patt new_floc sh x1 | PaAny loc -> let loc = floc loc in PaAny loc | PaApp loc x1 x2 -> let loc = floc loc in PaApp loc (self x1) (self x2) | PaArr loc x1 -> let loc = floc loc in PaArr loc (vala_map (List.map self) x1) | PaChr loc x1 -> let loc = floc loc in PaChr loc x1 | PaFlo loc x1 -> let loc = floc loc in PaFlo loc x1 | PaInt loc x1 x2 -> let loc = floc loc in PaInt loc x1 x2 | PaLab loc x1 x2 -> let loc = floc loc in PaLab loc (self x1) (vala_map (option_map self) x2) | PaLaz loc x1 -> let loc = floc loc in PaLaz loc (self x1) | PaLid loc x1 -> let loc = floc loc in PaLid loc x1 | PaNty loc x1 -> let loc = floc loc in PaNty loc x1 | PaOlb loc x1 x2 -> let loc = floc loc in PaOlb loc (self x1) (vala_map (option_map (reloc_expr floc sh)) x2) | PaOrp loc x1 x2 -> let loc = floc loc in PaOrp loc (self x1) (self x2) | PaRec loc x1 -> let loc = floc loc in PaRec loc (vala_map (List.map (fun (x1, x2) -> (self x1, self x2))) x1) | PaRng loc x1 x2 -> let loc = floc loc in PaRng loc (self x1) (self x2) | PaStr loc x1 -> let loc = floc loc in PaStr loc x1 | PaTup loc x1 -> let loc = floc loc in PaTup loc (vala_map (List.map self) x1) | PaTyc loc x1 x2 -> let loc = floc loc in PaTyc loc (self x1) (reloc_ctyp floc sh x2) | PaTyp loc x1 -> let loc = floc loc in PaTyp loc x1 | PaUid loc x1 -> let loc = floc loc in PaUid loc x1 | PaUnp loc x1 x2 -> let loc = floc loc in PaUnp loc x1 (option_map (reloc_module_type floc sh) x2) | PaVrn loc x1 -> let loc = floc loc in PaVrn loc x1 | IFDEF STRICT THEN PaXtr loc x1 x2 -> let loc = floc loc in PaXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_expr floc sh = self where rec self = fun [ ExAcc loc x1 x2 -> let loc = floc loc in ExAcc loc (self x1) (self x2) | ExAnt loc x1 -> let new_floc loc1 = anti_loc (floc loc) sh loc loc1 in reloc_expr new_floc sh x1 | ExApp loc x1 x2 -> let loc = floc loc in ExApp loc (self x1) (self x2) | ExAre loc x1 x2 -> let loc = floc loc in ExAre loc (self x1) (self x2) | ExArr loc x1 -> let loc = floc loc in ExArr loc (vala_map (List.map self) x1) | ExAsr loc x1 -> let loc = floc loc in ExAsr loc (self x1) | ExAss loc x1 x2 -> let loc = floc loc in ExAss loc (self x1) (self x2) | ExBae loc x1 x2 -> let loc = floc loc in ExBae loc (self x1) (vala_map (List.map self) x2) | ExChr loc x1 -> let loc = floc loc in ExChr loc x1 | ExCoe loc x1 x2 x3 -> let loc = floc loc in ExCoe loc (self x1) (option_map (reloc_ctyp floc sh) x2) (reloc_ctyp floc sh x3) | ExFlo loc x1 -> let loc = floc loc in ExFlo loc x1 | ExFor loc x1 x2 x3 x4 x5 -> let loc = floc loc in ExFor loc x1 (self x2) (self x3) x4 (vala_map (List.map self) x5) | ExFun loc x1 -> let loc = floc loc in ExFun loc (vala_map (List.map (fun (x1, x2, x3) -> (reloc_patt floc sh x1, vala_map (option_map self) x2, self x3))) x1) | ExIfe loc x1 x2 x3 -> let loc = floc loc in ExIfe loc (self x1) (self x2) (self x3) | ExInt loc x1 x2 -> let loc = floc loc in ExInt loc x1 x2 | ExLab loc x1 -> let loc = floc loc in ExLab loc (vala_map (List.map (fun (x1, x2) -> (reloc_patt floc sh x1, vala_map (option_map self) x2))) x1) | ExLaz loc x1 -> let loc = floc loc in ExLaz loc (self x1) | ExLet loc x1 x2 x3 -> let loc = floc loc in ExLet loc x1 (vala_map (List.map (fun (x1, x2) -> (reloc_patt floc sh x1, self x2))) x2) (self x3) | ExLid loc x1 -> let loc = floc loc in ExLid loc x1 | ExLmd loc x1 x2 x3 -> let loc = floc loc in ExLmd loc x1 (reloc_module_expr floc sh x2) (self x3) | ExMat loc x1 x2 -> let loc = floc loc in ExMat loc (self x1) (vala_map (List.map (fun (x1, x2, x3) -> (reloc_patt floc sh x1, vala_map (option_map self) x2, self x3))) x2) | ExNew loc x1 -> let loc = floc loc in ExNew loc x1 | ExObj loc x1 x2 -> let loc = floc loc in ExObj loc (vala_map (option_map (reloc_patt floc sh)) x1) (vala_map (List.map (reloc_class_str_item floc sh)) x2) | ExOlb loc x1 x2 -> let loc = floc loc in ExOlb loc (reloc_patt floc sh x1) (vala_map (option_map self) x2) | ExOvr loc x1 -> let loc = floc loc in ExOvr loc (vala_map (List.map (fun (x1, x2) -> (x1, self x2))) x1) | ExPck loc x1 x2 -> let loc = floc loc in ExPck loc (reloc_module_expr floc sh x1) (option_map (reloc_module_type floc sh) x2) | ExRec loc x1 x2 -> let loc = floc loc in ExRec loc (vala_map (List.map (fun (x1, x2) -> (reloc_patt floc sh x1, self x2))) x1) (option_map self x2) | ExSeq loc x1 -> let loc = floc loc in ExSeq loc (vala_map (List.map self) x1) | ExSnd loc x1 x2 -> let loc = floc loc in ExSnd loc (self x1) x2 | ExSte loc x1 x2 -> let loc = floc loc in ExSte loc (self x1) (self x2) | ExStr loc x1 -> let loc = floc loc in ExStr loc x1 | ExTry loc x1 x2 -> let loc = floc loc in ExTry loc (self x1) (vala_map (List.map (fun (x1, x2, x3) -> (reloc_patt floc sh x1, vala_map (option_map self) x2, self x3))) x2) | ExTup loc x1 -> let loc = floc loc in ExTup loc (vala_map (List.map self) x1) | ExTyc loc x1 x2 -> let loc = floc loc in ExTyc loc (self x1) (reloc_ctyp floc sh x2) | ExUid loc x1 -> let loc = floc loc in ExUid loc x1 | ExVrn loc x1 -> let loc = floc loc in ExVrn loc x1 | ExWhi loc x1 x2 -> let loc = floc loc in ExWhi loc (self x1) (vala_map (List.map self) x2) | IFDEF STRICT THEN ExXtr loc x1 x2 -> let loc = floc loc in ExXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_module_type floc sh = self where rec self = fun [ MtAcc loc x1 x2 -> let loc = floc loc in MtAcc loc (self x1) (self x2) | MtApp loc x1 x2 -> let loc = floc loc in MtApp loc (self x1) (self x2) | MtFun loc x1 x2 x3 -> let loc = floc loc in MtFun loc x1 (self x2) (self x3) | MtLid loc x1 -> let loc = floc loc in MtLid loc x1 | MtQuo loc x1 -> let loc = floc loc in MtQuo loc x1 | MtSig loc x1 -> let loc = floc loc in MtSig loc (vala_map (List.map (reloc_sig_item floc sh)) x1) | MtTyo loc x1 -> let loc = floc loc in MtTyo loc (reloc_module_expr floc sh x1) | MtUid loc x1 -> let loc = floc loc in MtUid loc x1 | MtWit loc x1 x2 -> let loc = floc loc in MtWit loc (self x1) (vala_map (List.map (reloc_with_constr floc sh)) x2) | IFDEF STRICT THEN MtXtr loc x1 x2 -> let loc = floc loc in MtXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_sig_item floc sh = self where rec self = fun [ SgCls loc x1 -> let loc = floc loc in SgCls loc (vala_map (List.map (class_infos_map floc (reloc_class_type floc sh))) x1) | SgClt loc x1 -> let loc = floc loc in SgClt loc (vala_map (List.map (class_infos_map floc (reloc_class_type floc sh))) x1) | SgDcl loc x1 -> let loc = floc loc in SgDcl loc (vala_map (List.map self) x1) | SgDir loc x1 x2 -> let loc = floc loc in SgDir loc x1 (vala_map (option_map (reloc_expr floc sh)) x2) | SgExc loc x1 x2 -> let loc = floc loc in SgExc loc x1 (vala_map (List.map (reloc_ctyp floc sh)) x2) | SgExt loc x1 x2 x3 -> let loc = floc loc in SgExt loc x1 (reloc_ctyp floc sh x2) x3 | SgInc loc x1 -> let loc = floc loc in SgInc loc (reloc_module_type floc sh x1) | SgMod loc x1 x2 -> let loc = floc loc in SgMod loc x1 (vala_map (List.map (fun (x1, x2) -> (x1, reloc_module_type floc sh x2))) x2) | SgMty loc x1 x2 -> let loc = floc loc in SgMty loc x1 (reloc_module_type floc sh x2) | SgOpn loc x1 -> let loc = floc loc in SgOpn loc x1 | SgTyp loc x1 -> let loc = floc loc in SgTyp loc (vala_map (List.map (reloc_type_decl floc sh)) x1) | SgUse loc x1 x2 -> let loc = floc loc in SgUse loc x1 (vala_map (List.map (fun (x1, loc) -> (self x1, floc loc))) x2) | SgVal loc x1 x2 -> let loc = floc loc in SgVal loc x1 (reloc_ctyp floc sh x2) | IFDEF STRICT THEN SgXtr loc x1 x2 -> let loc = floc loc in SgXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_with_constr floc sh = fun [ WcMod loc x1 x2 -> let loc = floc loc in WcMod loc x1 (reloc_module_expr floc sh x2) | WcMos loc x1 x2 -> let loc = floc loc in WcMos loc x1 (reloc_module_expr floc sh x2) | WcTyp loc x1 x2 x3 x4 -> let loc = floc loc in WcTyp loc x1 x2 x3 (reloc_ctyp floc sh x4) | WcTys loc x1 x2 x3 -> let loc = floc loc in WcTys loc x1 x2 (reloc_ctyp floc sh x3) ] and reloc_module_expr floc sh = self where rec self = fun [ MeAcc loc x1 x2 -> let loc = floc loc in MeAcc loc (self x1) (self x2) | MeApp loc x1 x2 -> let loc = floc loc in MeApp loc (self x1) (self x2) | MeFun loc x1 x2 x3 -> let loc = floc loc in MeFun loc x1 (reloc_module_type floc sh x2) (self x3) | MeStr loc x1 -> let loc = floc loc in MeStr loc (vala_map (List.map (reloc_str_item floc sh)) x1) | MeTyc loc x1 x2 -> let loc = floc loc in MeTyc loc (self x1) (reloc_module_type floc sh x2) | MeUid loc x1 -> let loc = floc loc in MeUid loc x1 | MeUnp loc x1 x2 -> let loc = floc loc in MeUnp loc (reloc_expr floc sh x1) (option_map (reloc_module_type floc sh) x2) | IFDEF STRICT THEN MeXtr loc x1 x2 -> let loc = floc loc in MeXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_str_item floc sh = self where rec self = fun [ StCls loc x1 -> let loc = floc loc in StCls loc (vala_map (List.map (class_infos_map floc (reloc_class_expr floc sh))) x1) | StClt loc x1 -> let loc = floc loc in StClt loc (vala_map (List.map (class_infos_map floc (reloc_class_type floc sh))) x1) | StDcl loc x1 -> let loc = floc loc in StDcl loc (vala_map (List.map self) x1) | StDir loc x1 x2 -> let loc = floc loc in StDir loc x1 (vala_map (option_map (reloc_expr floc sh)) x2) | StExc loc x1 x2 x3 -> let loc = floc loc in StExc loc x1 (vala_map (List.map (reloc_ctyp floc sh)) x2) x3 | StExp loc x1 -> let loc = floc loc in StExp loc (reloc_expr floc sh x1) | StExt loc x1 x2 x3 -> let loc = floc loc in StExt loc x1 (reloc_ctyp floc sh x2) x3 | StInc loc x1 -> let loc = floc loc in StInc loc (reloc_module_expr floc sh x1) | StMod loc x1 x2 -> let loc = floc loc in StMod loc x1 (vala_map (List.map (fun (x1, x2) -> (x1, reloc_module_expr floc sh x2))) x2) | StMty loc x1 x2 -> let loc = floc loc in StMty loc x1 (reloc_module_type floc sh x2) | StOpn loc x1 -> let loc = floc loc in StOpn loc x1 | StTyp loc x1 -> let loc = floc loc in StTyp loc (vala_map (List.map (reloc_type_decl floc sh)) x1) | StUse loc x1 x2 -> let loc = floc loc in StUse loc x1 (vala_map (List.map (fun (x1, loc) -> (self x1, floc loc))) x2) | StVal loc x1 x2 -> let loc = floc loc in StVal loc x1 (vala_map (List.map (fun (x1, x2) -> (reloc_patt floc sh x1, reloc_expr floc sh x2))) x2) | IFDEF STRICT THEN StXtr loc x1 x2 -> let loc = floc loc in StXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_type_decl floc sh x = {tdNam = vala_map (fun (loc, x1) -> (floc loc, x1)) x.tdNam; tdPrm = x.tdPrm; tdPrv = x.tdPrv; tdDef = reloc_ctyp floc sh x.tdDef; tdCon = vala_map (List.map (fun (x1, x2) -> (reloc_ctyp floc sh x1, reloc_ctyp floc sh x2))) x.tdCon} and reloc_class_type floc sh = self where rec self = fun [ CtAcc loc x1 x2 -> let loc = floc loc in CtAcc loc (self x1) (self x2) | CtApp loc x1 x2 -> let loc = floc loc in CtApp loc (self x1) (self x2) | CtCon loc x1 x2 -> let loc = floc loc in CtCon loc (self x1) (vala_map (List.map (reloc_ctyp floc sh)) x2) | CtFun loc x1 x2 -> let loc = floc loc in CtFun loc (reloc_ctyp floc sh x1) (self x2) | CtIde loc x1 -> let loc = floc loc in CtIde loc x1 | CtSig loc x1 x2 -> let loc = floc loc in CtSig loc (vala_map (option_map (reloc_ctyp floc sh)) x1) (vala_map (List.map (reloc_class_sig_item floc sh)) x2) | IFDEF STRICT THEN CtXtr loc x1 x2 -> let loc = floc loc in CtXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_class_sig_item floc sh = self where rec self = fun [ CgCtr loc x1 x2 -> let loc = floc loc in CgCtr loc (reloc_ctyp floc sh x1) (reloc_ctyp floc sh x2) | CgDcl loc x1 -> let loc = floc loc in CgDcl loc (vala_map (List.map self) x1) | CgInh loc x1 -> let loc = floc loc in CgInh loc (reloc_class_type floc sh x1) | CgMth loc x1 x2 x3 -> let loc = floc loc in CgMth loc x1 x2 (reloc_ctyp floc sh x3) | CgVal loc x1 x2 x3 -> let loc = floc loc in CgVal loc x1 x2 (reloc_ctyp floc sh x3) | CgVir loc x1 x2 x3 -> let loc = floc loc in CgVir loc x1 x2 (reloc_ctyp floc sh x3) ] and reloc_class_expr floc sh = self where rec self = fun [ CeApp loc x1 x2 -> let loc = floc loc in CeApp loc (self x1) (reloc_expr floc sh x2) | CeCon loc x1 x2 -> let loc = floc loc in CeCon loc x1 (vala_map (List.map (reloc_ctyp floc sh)) x2) | CeFun loc x1 x2 -> let loc = floc loc in CeFun loc (reloc_patt floc sh x1) (self x2) | CeLet loc x1 x2 x3 -> let loc = floc loc in CeLet loc x1 (vala_map (List.map (fun (x1, x2) -> (reloc_patt floc sh x1, reloc_expr floc sh x2))) x2) (self x3) | CeStr loc x1 x2 -> let loc = floc loc in CeStr loc (vala_map (option_map (reloc_patt floc sh)) x1) (vala_map (List.map (reloc_class_str_item floc sh)) x2) | CeTyc loc x1 x2 -> let loc = floc loc in CeTyc loc (self x1) (reloc_class_type floc sh x2) | IFDEF STRICT THEN CeXtr loc x1 x2 -> let loc = floc loc in CeXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_class_str_item floc sh = self where rec self = fun [ CrCtr loc x1 x2 -> let loc = floc loc in CrCtr loc (reloc_ctyp floc sh x1) (reloc_ctyp floc sh x2) | CrDcl loc x1 -> let loc = floc loc in CrDcl loc (vala_map (List.map self) x1) | CrInh loc x1 x2 -> let loc = floc loc in CrInh loc (reloc_class_expr floc sh x1) x2 | CrIni loc x1 -> let loc = floc loc in CrIni loc (reloc_expr floc sh x1) | CrMth loc x1 x2 x3 x4 x5 -> let loc = floc loc in CrMth loc x1 x2 x3 (vala_map (option_map (reloc_ctyp floc sh)) x4) (reloc_expr floc sh x5) | CrVal loc x1 x2 x3 x4 -> let loc = floc loc in CrVal loc x1 x2 x3 (reloc_expr floc sh x4) | CrVav loc x1 x2 x3 -> let loc = floc loc in CrVav loc x1 x2 (reloc_ctyp floc sh x3) | CrVir loc x1 x2 x3 -> let loc = floc loc in CrVir loc x1 x2 (reloc_ctyp floc sh x3) ] ; (* Equality over syntax trees *) value eq_expr x y = reloc_expr (fun _ -> Ploc.dummy) 0 x = reloc_expr (fun _ -> Ploc.dummy) 0 y ; value eq_patt x y = reloc_patt (fun _ -> Ploc.dummy) 0 x = reloc_patt (fun _ -> Ploc.dummy) 0 y ; value eq_ctyp x y = reloc_ctyp (fun _ -> Ploc.dummy) 0 x = reloc_ctyp (fun _ -> Ploc.dummy) 0 y ; value eq_str_item x y = reloc_str_item (fun _ -> Ploc.dummy) 0 x = reloc_str_item (fun _ -> Ploc.dummy) 0 y ; value eq_sig_item x y = reloc_sig_item (fun _ -> Ploc.dummy) 0 x = reloc_sig_item (fun _ -> Ploc.dummy) 0 y ; value eq_module_expr x y = reloc_module_expr (fun _ -> Ploc.dummy) 0 x = reloc_module_expr (fun _ -> Ploc.dummy) 0 y ; value eq_module_type x y = reloc_module_type (fun _ -> Ploc.dummy) 0 x = reloc_module_type (fun _ -> Ploc.dummy) 0 y ; value eq_class_sig_item x y = reloc_class_sig_item (fun _ -> Ploc.dummy) 0 x = reloc_class_sig_item (fun _ -> Ploc.dummy) 0 y ; value eq_class_str_item x y = reloc_class_str_item (fun _ -> Ploc.dummy) 0 x = reloc_class_str_item (fun _ -> Ploc.dummy) 0 y ; value eq_class_type x y = reloc_class_type (fun _ -> Ploc.dummy) 0 x = reloc_class_type (fun _ -> Ploc.dummy) 0 y ; value eq_class_expr x y = reloc_class_expr (fun _ -> Ploc.dummy) 0 x = reloc_class_expr (fun _ -> Ploc.dummy) 0 y ; (* ------------------------------------------------------------------------- *) (* Now the lexer. *) (* ------------------------------------------------------------------------- *) (* camlp5r *) $ I d : plexer.ml , v 6.11 2010 - 10 - 04 20:14:58 deraugla Exp $ Copyright ( c ) INRIA 2007 - 2010 #load "pa_lexer.cmo"; (* ------------------------------------------------------------------------- *) Added by as a backdoor to change lexical conventions . (* ------------------------------------------------------------------------- *) value jrh_lexer = ref False; open Versdep; value no_quotations = ref False; value error_on_unknown_keywords = ref False; value dollar_for_antiquotation = ref True; value specific_space_dot = ref False; value force_antiquot_loc = ref False; type context = { after_space : mutable bool; dollar_for_antiquotation : bool; specific_space_dot : bool; find_kwd : string -> string; line_cnt : int -> char -> unit; set_line_nb : unit -> unit; make_lined_loc : (int * int) -> string -> Ploc.t } ; value err ctx loc msg = Ploc.raise (ctx.make_lined_loc loc "") (Plexing.Error msg) ; (* ------------------------------------------------------------------------- *) 's hack to make the case distinction " unmixed " versus " mixed " (* ------------------------------------------------------------------------- *) value is_uppercase s = String.uppercase s = s; value is_only_lowercase s = String.lowercase s = s && not(is_uppercase s); value jrh_identifier find_kwd id = let jflag = jrh_lexer.val in if id = "set_jrh_lexer" then (let _ = jrh_lexer.val := True in ("",find_kwd "true")) else if id = "unset_jrh_lexer" then (let _ = jrh_lexer.val := False in ("",find_kwd "false")) else try ("", find_kwd id) with [ Not_found -> if not(jflag) then if is_uppercase (String.sub id 0 1) then ("UIDENT", id) else ("LIDENT", id) else if is_uppercase (String.sub id 0 1) && is_only_lowercase (String.sub id 1 (String.length id - 1)) * * * * : 's alternative version then ( " UIDENT " , i d ) else if is_uppercase ( String.sub i d 0 1 ) then ( " " , " _ _ uc_"^id ) else ( " " , i d ) ] ; * * * * then ("UIDENT", id) else if is_uppercase (String.sub id 0 1) then ("LIDENT", "__uc_"^id) else ("LIDENT", id)]; *****) then ("UIDENT", id) else ("LIDENT", id)]; (* ------------------------------------------------------------------------- *) (* Back to original file with the mod of using the above. *) (* ------------------------------------------------------------------------- *) value keyword_or_error ctx loc s = try ("", ctx.find_kwd s) with [ Not_found -> if error_on_unknown_keywords.val then err ctx loc ("illegal token: " ^ s) else ("", s) ] ; value stream_peek_nth n strm = loop n (Stream.npeek n strm) where rec loop n = fun [ [] -> None | [x] -> if n == 1 then Some x else None | [_ :: l] -> loop (n - 1) l ] ; value utf8_lexing = ref False; value misc_letter buf strm = if utf8_lexing.val then match strm with lexer [ '\128'-'\225' | '\227'-'\255' ] else match strm with lexer [ '\128'-'\255' ] ; value misc_punct buf strm = if utf8_lexing.val then match strm with lexer [ '\226' _ _ ] else match strm with parser [] ; value rec ident = lexer [ [ 'A'-'Z' | 'a'-'z' | '0'-'9' | '_' | ''' | misc_letter ] ident! | ] ; value rec ident2 = lexer [ [ '!' | '?' | '~' | '=' | '@' | '^' | '&' | '+' | '-' | '*' | '/' | '%' | '.' | ':' | '<' | '>' | '|' | '$' | misc_punct ] ident2! | ] ; value rec ident3 = lexer [ [ '0'-'9' | 'A'-'Z' | 'a'-'z' | '_' | '!' | '%' | '&' | '*' | '+' | '-' | '.' | '/' | ':' | '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' | ''' | '$' | '\128'-'\255' ] ident3! | ] ; value binary = lexer [ '0' | '1' ]; value octal = lexer [ '0'-'7' ]; value decimal = lexer [ '0'-'9' ]; value hexa = lexer [ '0'-'9' | 'a'-'f' | 'A'-'F' ]; value end_integer = lexer [ "l"/ -> ("INT_l", $buf) | "L"/ -> ("INT_L", $buf) | "n"/ -> ("INT_n", $buf) | -> ("INT", $buf) ] ; value rec digits_under kind = lexer [ kind (digits_under kind)! | "_" (digits_under kind)! | end_integer ] ; value digits kind = lexer [ kind (digits_under kind)! | -> raise (Stream.Error "ill-formed integer constant") ] ; value rec decimal_digits_under = lexer [ [ '0'-'9' | '_' ] decimal_digits_under! | ] ; value exponent_part = lexer [ [ 'e' | 'E' ] [ '+' | '-' | ] '0'-'9' ? "ill-formed floating-point constant" decimal_digits_under! ] ; value number = lexer [ decimal_digits_under "." decimal_digits_under! exponent_part -> ("FLOAT", $buf) | decimal_digits_under "." decimal_digits_under! -> ("FLOAT", $buf) | decimal_digits_under exponent_part -> ("FLOAT", $buf) | decimal_digits_under end_integer! ] ; value char_after_bslash = lexer [ "'"/ | _ [ "'"/ | _ [ "'"/ | ] ] ] ; value char ctx bp = lexer [ "\\" _ char_after_bslash! | "\\" -> err ctx (bp, $pos) "char not terminated" | ?= [ _ '''] _! "'"/ ] ; value any ctx buf = parser bp [: `c :] -> do { ctx.line_cnt bp c; $add c } ; value rec string ctx bp = lexer [ "\""/ | "\\" (any ctx) (string ctx bp)! | (any ctx) (string ctx bp)! | -> err ctx (bp, $pos) "string not terminated" ] ; value rec qstring ctx bp = lexer [ "`"/ | (any ctx) (qstring ctx bp)! | -> err ctx (bp, $pos) "quotation not terminated" ] ; value comment ctx bp = comment where rec comment = lexer [ "*)" | "*" comment! | "(*" comment! comment! | "(" comment! | "\"" (string ctx bp)! [ -> $add "\"" ] comment! | "'*)" | "'*" comment! | "'" (any ctx) comment! | (any ctx) comment! | -> err ctx (bp, $pos) "comment not terminated" ] ; value rec quotation ctx bp = lexer [ ">>"/ | ">" (quotation ctx bp)! | "<<" (quotation ctx bp)! [ -> $add ">>" ]! (quotation ctx bp)! | "<:" ident! "<" (quotation ctx bp)! [ -> $add ">>" ]! (quotation ctx bp)! | "<:" ident! (quotation ctx bp)! | "<" (quotation ctx bp)! | "\\"/ [ '>' | '<' | '\\' ] (quotation ctx bp)! | "\\" (quotation ctx bp)! | (any ctx) (quotation ctx bp)! | -> err ctx (bp, $pos) "quotation not terminated" ] ; value less_expected = "character '<' expected"; value less ctx bp buf strm = if no_quotations.val then match strm with lexer [ [ -> $add "<" ] ident2! -> keyword_or_error ctx (bp, $pos) $buf ] else match strm with lexer [ "<"/ (quotation ctx bp) -> ("QUOTATION", ":" ^ $buf) | ":"/ ident! "<"/ ? less_expected [ -> $add ":" ]! (quotation ctx bp) -> ("QUOTATION", $buf) | ":"/ ident! ":<"/ ? less_expected [ -> $add "@" ]! (quotation ctx bp) -> ("QUOTATION", $buf) | [ -> $add "<" ] ident2! -> keyword_or_error ctx (bp, $pos) $buf ] ; value rec antiquot_rest ctx bp = lexer [ "$"/ | "\\"/ (any ctx) (antiquot_rest ctx bp)! | (any ctx) (antiquot_rest ctx bp)! | -> err ctx (bp, $pos) "antiquotation not terminated" ] ; value rec antiquot ctx bp = lexer [ "$"/ -> ":" ^ $buf | [ 'a'-'z' | 'A'-'Z' | '0'-'9' | '!' | '_' ] (antiquot ctx bp)! | ":" (antiquot_rest ctx bp)! -> $buf | "\\"/ (any ctx) (antiquot_rest ctx bp)! -> ":" ^ $buf | (any ctx) (antiquot_rest ctx bp)! -> ":" ^ $buf | -> err ctx (bp, $pos) "antiquotation not terminated" ] ; value antiloc bp ep s = Printf.sprintf "%d,%d:%s" bp ep s; value rec antiquot_loc ctx bp = lexer [ "$"/ -> antiloc bp $pos (":" ^ $buf) | [ 'a'-'z' | 'A'-'Z' | '0'-'9' | '!' | '_' ] (antiquot_loc ctx bp)! | ":" (antiquot_rest ctx bp)! -> antiloc bp $pos $buf | "\\"/ (any ctx) (antiquot_rest ctx bp)! -> antiloc bp $pos (":" ^ $buf) | (any ctx) (antiquot_rest ctx bp)! -> antiloc bp $pos (":" ^ $buf) | -> err ctx (bp, $pos) "antiquotation not terminated" ] ; value dollar ctx bp buf strm = if not no_quotations.val && ctx.dollar_for_antiquotation then ("ANTIQUOT", antiquot ctx bp buf strm) else if force_antiquot_loc.val then ("ANTIQUOT_LOC", antiquot_loc ctx bp buf strm) else match strm with lexer [ [ -> $add "$" ] ident2! -> ("", $buf) ] ; - specific case for QUESTIONIDENT and QUESTIONIDENTCOLON input expr patt ----- ---- ---- ? $ abc : d$ ? abc : d ? abc ? $ abc : d$ : ? abc : d : ? abc : ? ? : d ? ? : ? : d : ? : input expr patt ----- ---- ---- ?$abc:d$ ?abc:d ?abc ?$abc:d$: ?abc:d: ?abc: ?$d$ ?:d ? ?$d$: ?:d: ?: *) ANTIQUOT_LOC - specific case for QUESTIONIDENT and QUESTIONIDENTCOLON input expr patt ----- ---- ---- ? $ abc : d$ ? 8,13 : abc : d ? abc ? $ abc : d$ : ? 8,13 : abc : d : ? abc : ? ? 8,9::d ? ? : ? 8,9::d : ? : input expr patt ----- ---- ---- ?$abc:d$ ?8,13:abc:d ?abc ?$abc:d$: ?8,13:abc:d: ?abc: ?$d$ ?8,9::d ? ?$d$: ?8,9::d: ?: *) value question ctx bp buf strm = if ctx.dollar_for_antiquotation then match strm with parser [ [: `'$'; s = antiquot ctx bp $empty; `':' :] -> ("ANTIQUOT", "?" ^ s ^ ":") | [: `'$'; s = antiquot ctx bp $empty :] -> ("ANTIQUOT", "?" ^ s) | [: :] -> match strm with lexer [ ident2! -> keyword_or_error ctx (bp, $pos) $buf ] ] else if force_antiquot_loc.val then match strm with parser [ [: `'$'; s = antiquot_loc ctx bp $empty; `':' :] -> ("ANTIQUOT_LOC", "?" ^ s ^ ":") | [: `'$'; s = antiquot_loc ctx bp $empty :] -> ("ANTIQUOT_LOC", "?" ^ s) | [: :] -> match strm with lexer [ ident2! -> keyword_or_error ctx (bp, $pos) $buf ] ] else match strm with lexer [ ident2! -> keyword_or_error ctx (bp, $pos) $buf ] ; value tilde ctx bp buf strm = if ctx.dollar_for_antiquotation then match strm with parser [ [: `'$'; s = antiquot ctx bp $empty; `':' :] -> ("ANTIQUOT", "~" ^ s ^ ":") | [: `'$'; s = antiquot ctx bp $empty :] -> ("ANTIQUOT", "~" ^ s) | [: :] -> match strm with lexer [ ident2! -> keyword_or_error ctx (bp, $pos) $buf ] ] else if force_antiquot_loc.val then match strm with parser [ [: `'$'; s = antiquot_loc ctx bp $empty; `':' :] -> ("ANTIQUOT_LOC", "~" ^ s ^ ":") | [: `'$'; s = antiquot_loc ctx bp $empty :] -> ("ANTIQUOT_LOC", "~" ^ s) | [: :] -> match strm with lexer [ ident2! -> keyword_or_error ctx (bp, $pos) $buf ] ] else match strm with lexer [ ident2! -> keyword_or_error ctx (bp, $pos) $buf ] ; value tildeident = lexer [ ":"/ -> ("TILDEIDENTCOLON", $buf) | -> ("TILDEIDENT", $buf) ] ; value questionident = lexer [ ":"/ -> ("QUESTIONIDENTCOLON", $buf) | -> ("QUESTIONIDENT", $buf) ] ; value rec linedir n s = match stream_peek_nth n s with [ Some (' ' | '\t') -> linedir (n + 1) s | Some ('0'..'9') -> linedir_digits (n + 1) s | _ -> False ] and linedir_digits n s = match stream_peek_nth n s with [ Some ('0'..'9') -> linedir_digits (n + 1) s | _ -> linedir_quote n s ] and linedir_quote n s = match stream_peek_nth n s with [ Some (' ' | '\t') -> linedir_quote (n + 1) s | Some '"' -> True | _ -> False ] ; value rec any_to_nl = lexer [ "\r" | "\n" | _ any_to_nl! | ] ; value next_token_after_spaces ctx bp = lexer [ 'A'-'Z' ident! -> let id = $buf in jrh_identifier ctx.find_kwd id * * * * * * * * * : original was try ( " " , ctx.find_kwd i d ) with [ Not_found - > ( " UIDENT " , i d ) ] * * * * * * * * try ("", ctx.find_kwd id) with [ Not_found -> ("UIDENT", id) ] *********) | [ 'a'-'z' | '_' | misc_letter ] ident! -> let id = $buf in jrh_identifier ctx.find_kwd id * * * * * * * * * : original was try ( " " , ctx.find_kwd i d ) with [ Not_found - > ( " " , i d ) ] * * * * * * * * try ("", ctx.find_kwd id) with [ Not_found -> ("LIDENT", id) ] *********) | '1'-'9' number! | "0" [ 'o' | 'O' ] (digits octal)! | "0" [ 'x' | 'X' ] (digits hexa)! | "0" [ 'b' | 'B' ] (digits binary)! | "0" number! | "'"/ ?= [ '\\' 'a'-'z' 'a'-'z' ] -> keyword_or_error ctx (bp, $pos) "'" | "'"/ (char ctx bp) -> ("CHAR", $buf) | "'" -> keyword_or_error ctx (bp, $pos) "'" | "\""/ (string ctx bp)! -> ("STRING", $buf) * * Line added by * * | "`"/ (qstring ctx bp)! -> ("QUOTATION", "tot:" ^ $buf) | "$"/ (dollar ctx bp)! | [ '!' | '=' | '@' | '^' | '&' | '+' | '-' | '*' | '/' | '%' ] ident2! -> keyword_or_error ctx (bp, $pos) $buf | "~"/ 'a'-'z' ident! tildeident! | "~"/ '_' ident! tildeident! | "~" (tilde ctx bp) | "?"/ 'a'-'z' ident! questionident! | "?" (question ctx bp)! | "<"/ (less ctx bp)! | ":]" -> keyword_or_error ctx (bp, $pos) $buf | "::" -> keyword_or_error ctx (bp, $pos) $buf | ":=" -> keyword_or_error ctx (bp, $pos) $buf | ":>" -> keyword_or_error ctx (bp, $pos) $buf | ":" -> keyword_or_error ctx (bp, $pos) $buf | ">]" -> keyword_or_error ctx (bp, $pos) $buf | ">}" -> keyword_or_error ctx (bp, $pos) $buf | ">" ident2! -> keyword_or_error ctx (bp, $pos) $buf | "|]" -> keyword_or_error ctx (bp, $pos) $buf | "|}" -> keyword_or_error ctx (bp, $pos) $buf | "|" ident2! -> keyword_or_error ctx (bp, $pos) $buf | "[" ?= [ "<<" | "<:" ] -> keyword_or_error ctx (bp, $pos) $buf | "[|" -> keyword_or_error ctx (bp, $pos) $buf | "[<" -> keyword_or_error ctx (bp, $pos) $buf | "[:" -> keyword_or_error ctx (bp, $pos) $buf | "[" -> keyword_or_error ctx (bp, $pos) $buf | "{" ?= [ "<<" | "<:" ] -> keyword_or_error ctx (bp, $pos) $buf | "{|" -> keyword_or_error ctx (bp, $pos) $buf | "{<" -> keyword_or_error ctx (bp, $pos) $buf | "{:" -> keyword_or_error ctx (bp, $pos) $buf | "{" -> keyword_or_error ctx (bp, $pos) $buf | ".." -> keyword_or_error ctx (bp, $pos) ".." | "." -> let id = if ctx.specific_space_dot && ctx.after_space then " ." else "." in keyword_or_error ctx (bp, $pos) id | ";;" -> keyword_or_error ctx (bp, $pos) ";;" | ";" -> keyword_or_error ctx (bp, $pos) ";" | misc_punct ident2! -> keyword_or_error ctx (bp, $pos) $buf | "\\"/ ident3! -> ("LIDENT", $buf) | (any ctx) -> keyword_or_error ctx (bp, $pos) $buf ] ; value get_comment buf strm = $buf; value rec next_token ctx buf = parser bp [ [: `('\n' | '\r' as c); s :] ep -> do { if c = '\n' then incr Plexing.line_nb.val else (); Plexing.bol_pos.val.val := ep; ctx.set_line_nb (); ctx.after_space := True; next_token ctx ($add c) s } | [: `(' ' | '\t' | '\026' | '\012' as c); s :] -> do { ctx.after_space := True; next_token ctx ($add c) s } | [: `'#' when bp = Plexing.bol_pos.val.val; s :] -> let comm = get_comment buf () in if linedir 1 s then do { let buf = any_to_nl ($add '#') s in incr Plexing.line_nb.val; Plexing.bol_pos.val.val := Stream.count s; ctx.set_line_nb (); ctx.after_space := True; next_token ctx buf s } else let loc = ctx.make_lined_loc (bp, bp + 1) comm in (keyword_or_error ctx (bp, bp + 1) "#", loc) | [: `'('; a = parser [ [: `'*'; buf = comment ctx bp ($add "(*") !; s :] -> do { ctx.set_line_nb (); ctx.after_space := True; next_token ctx buf s } | [: :] ep -> let loc = ctx.make_lined_loc (bp, ep) $buf in (keyword_or_error ctx (bp, ep) "(", loc) ] ! :] -> a | [: comm = get_comment buf; tok = next_token_after_spaces ctx bp $empty :] ep -> let loc = ctx.make_lined_loc (bp, max (bp + 1) ep) comm in (tok, loc) | [: comm = get_comment buf; _ = Stream.empty :] -> let loc = ctx.make_lined_loc (bp, bp + 1) comm in (("EOI", ""), loc) ] ; value next_token_fun ctx glexr (cstrm, s_line_nb, s_bol_pos) = try do { match Plexing.restore_lexing_info.val with [ Some (line_nb, bol_pos) -> do { s_line_nb.val := line_nb; s_bol_pos.val := bol_pos; Plexing.restore_lexing_info.val := None; } | None -> () ]; Plexing.line_nb.val := s_line_nb; Plexing.bol_pos.val := s_bol_pos; let comm_bp = Stream.count cstrm in ctx.set_line_nb (); ctx.after_space := False; let (r, loc) = next_token ctx $empty cstrm in match glexr.val.Plexing.tok_comm with [ Some list -> if Ploc.first_pos loc > comm_bp then let comm_loc = Ploc.make_unlined (comm_bp, Ploc.last_pos loc) in glexr.val.Plexing.tok_comm := Some [comm_loc :: list] else () | None -> () ]; (r, loc) } with [ Stream.Error str -> err ctx (Stream.count cstrm, Stream.count cstrm + 1) str ] ; value func kwd_table glexr = let ctx = let line_nb = ref 0 in let bol_pos = ref 0 in {after_space = False; dollar_for_antiquotation = dollar_for_antiquotation.val; specific_space_dot = specific_space_dot.val; find_kwd = Hashtbl.find kwd_table; line_cnt bp1 c = match c with [ '\n' | '\r' -> do { if c = '\n' then incr Plexing.line_nb.val else (); Plexing.bol_pos.val.val := bp1 + 1; } | c -> () ]; set_line_nb () = do { line_nb.val := Plexing.line_nb.val.val; bol_pos.val := Plexing.bol_pos.val.val; }; make_lined_loc loc comm = Ploc.make_loc Plexing.input_file.val line_nb.val bol_pos.val loc comm} in Plexing.lexer_func_of_parser (next_token_fun ctx glexr) ; value rec check_keyword_stream = parser [: _ = check $empty; _ = Stream.empty :] -> True and check = lexer [ [ 'A'-'Z' | 'a'-'z' | misc_letter ] check_ident! | [ '!' | '?' | '~' | '=' | '@' | '^' | '&' | '+' | '-' | '*' | '/' | '%' | '.' ] check_ident2! | "$" check_ident2! | "<" ?= [ ":" | "<" ] | "<" check_ident2! | ":]" | "::" | ":=" | ":>" | ":" | ">]" | ">}" | ">" check_ident2! | "|]" | "|}" | "|" check_ident2! | "[" ?= [ "<<" | "<:" ] | "[|" | "[<" | "[:" | "[" | "{" ?= [ "<<" | "<:" ] | "{|" | "{<" | "{:" | "{" | ";;" | ";" | misc_punct check_ident2! | _ ] and check_ident = lexer [ [ 'A'-'Z' | 'a'-'z' | '0'-'9' | '_' | ''' | misc_letter ] check_ident! | ] and check_ident2 = lexer [ [ '!' | '?' | '~' | '=' | '@' | '^' | '&' | '+' | '-' | '*' | '/' | '%' | '.' | ':' | '<' | '>' | '|' | misc_punct ] check_ident2! | ] ; value check_keyword s = try check_keyword_stream (Stream.of_string s) with _ -> False ; value error_no_respect_rules p_con p_prm = raise (Plexing.Error ("the token " ^ (if p_con = "" then "\"" ^ p_prm ^ "\"" else if p_prm = "" then p_con else p_con ^ " \"" ^ p_prm ^ "\"") ^ " does not respect Plexer rules")) ; value error_ident_and_keyword p_con p_prm = raise (Plexing.Error ("the token \"" ^ p_prm ^ "\" is used as " ^ p_con ^ " and as keyword")) ; value using_token kwd_table ident_table (p_con, p_prm) = match p_con with [ "" -> if not (hashtbl_mem kwd_table p_prm) then if check_keyword p_prm then if hashtbl_mem ident_table p_prm then error_ident_and_keyword (Hashtbl.find ident_table p_prm) p_prm else Hashtbl.add kwd_table p_prm p_prm else error_no_respect_rules p_con p_prm else () | "LIDENT" -> if p_prm = "" then () else match p_prm.[0] with [ 'A'..'Z' -> error_no_respect_rules p_con p_prm | _ -> if hashtbl_mem kwd_table p_prm then error_ident_and_keyword p_con p_prm else Hashtbl.add ident_table p_prm p_con ] | "UIDENT" -> if p_prm = "" then () else match p_prm.[0] with [ 'a'..'z' -> error_no_respect_rules p_con p_prm | _ -> if hashtbl_mem kwd_table p_prm then error_ident_and_keyword p_con p_prm else Hashtbl.add ident_table p_prm p_con ] | "TILDEIDENT" | "TILDEIDENTCOLON" | "QUESTIONIDENT" | "QUESTIONIDENTCOLON" | "INT" | "INT_l" | "INT_L" | "INT_n" | "FLOAT" | "CHAR" | "STRING" | "QUOTATION" | "ANTIQUOT" | "ANTIQUOT_LOC" | "EOI" -> () | _ -> raise (Plexing.Error ("the constructor \"" ^ p_con ^ "\" is not recognized by Plexer")) ] ; value removing_token kwd_table ident_table (p_con, p_prm) = match p_con with [ "" -> Hashtbl.remove kwd_table p_prm | "LIDENT" | "UIDENT" -> if p_prm <> "" then Hashtbl.remove ident_table p_prm else () | _ -> () ] ; value text = fun [ ("", t) -> "'" ^ t ^ "'" | ("LIDENT", "") -> "lowercase identifier" | ("LIDENT", t) -> "'" ^ t ^ "'" | ("UIDENT", "") -> "uppercase identifier" | ("UIDENT", t) -> "'" ^ t ^ "'" | ("INT", "") -> "integer" | ("INT", s) -> "'" ^ s ^ "'" | ("FLOAT", "") -> "float" | ("STRING", "") -> "string" | ("CHAR", "") -> "char" | ("QUOTATION", "") -> "quotation" | ("ANTIQUOT", k) -> "antiquot \"" ^ k ^ "\"" | ("EOI", "") -> "end of input" | (con, "") -> con | (con, prm) -> con ^ " \"" ^ prm ^ "\"" ] ; value eq_before_colon p e = loop 0 where rec loop i = if i == String.length e then failwith "Internal error in Plexer: incorrect ANTIQUOT" else if i == String.length p then e.[i] == ':' else if p.[i] == e.[i] then loop (i + 1) else False ; value after_colon e = try let i = String.index e ':' in String.sub e (i + 1) (String.length e - i - 1) with [ Not_found -> "" ] ; value after_colon_except_last e = try let i = String.index e ':' in String.sub e (i + 1) (String.length e - i - 2) with [ Not_found -> "" ] ; value tok_match = fun [ ("ANTIQUOT", p_prm) -> if p_prm <> "" && (p_prm.[0] = '~' || p_prm.[0] = '?') then if p_prm.[String.length p_prm - 1] = ':' then let p_prm = String.sub p_prm 0 (String.length p_prm - 1) in fun [ ("ANTIQUOT", prm) -> if prm <> "" && prm.[String.length prm - 1] = ':' then if eq_before_colon p_prm prm then after_colon_except_last prm else raise Stream.Failure else raise Stream.Failure | _ -> raise Stream.Failure ] else fun [ ("ANTIQUOT", prm) -> if prm <> "" && prm.[String.length prm - 1] = ':' then raise Stream.Failure else if eq_before_colon p_prm prm then after_colon prm else raise Stream.Failure | _ -> raise Stream.Failure ] else fun [ ("ANTIQUOT", prm) when eq_before_colon p_prm prm -> after_colon prm | _ -> raise Stream.Failure ] | tok -> Plexing.default_match tok ] ; value gmake () = let kwd_table = Hashtbl.create 301 in let id_table = Hashtbl.create 301 in let glexr = ref {Plexing.tok_func = fun []; tok_using = fun []; tok_removing = fun []; tok_match = fun []; tok_text = fun []; tok_comm = None} in let glex = {Plexing.tok_func = func kwd_table glexr; tok_using = using_token kwd_table id_table; tok_removing = removing_token kwd_table id_table; tok_match = tok_match; tok_text = text; tok_comm = None} in do { glexr.val := glex; glex } ; (* ------------------------------------------------------------------------- *) (* Back to etc/pa_o.ml *) (* ------------------------------------------------------------------------- *) do { let odfa = dollar_for_antiquotation.val in dollar_for_antiquotation.val := False; Grammar.Unsafe.gram_reinit gram (gmake ()); dollar_for_antiquotation.val := odfa; Grammar.Unsafe.clear_entry interf; Grammar.Unsafe.clear_entry implem; Grammar.Unsafe.clear_entry top_phrase; Grammar.Unsafe.clear_entry use_file; Grammar.Unsafe.clear_entry module_type; Grammar.Unsafe.clear_entry module_expr; Grammar.Unsafe.clear_entry sig_item; Grammar.Unsafe.clear_entry str_item; Grammar.Unsafe.clear_entry signature; Grammar.Unsafe.clear_entry structure; Grammar.Unsafe.clear_entry expr; Grammar.Unsafe.clear_entry patt; Grammar.Unsafe.clear_entry ctyp; Grammar.Unsafe.clear_entry let_binding; Grammar.Unsafe.clear_entry type_decl; Grammar.Unsafe.clear_entry constructor_declaration; Grammar.Unsafe.clear_entry label_declaration; Grammar.Unsafe.clear_entry match_case; Grammar.Unsafe.clear_entry with_constr; Grammar.Unsafe.clear_entry poly_variant; Grammar.Unsafe.clear_entry class_type; Grammar.Unsafe.clear_entry class_expr; Grammar.Unsafe.clear_entry class_sig_item; Grammar.Unsafe.clear_entry class_str_item }; Pcaml.parse_interf.val := Grammar.Entry.parse interf; Pcaml.parse_implem.val := Grammar.Entry.parse implem; value mklistexp loc last = loop True where rec loop top = fun [ [] -> match last with [ Some e -> e | None -> <:expr< [] >> ] | [e1 :: el] -> let loc = if top then loc else Ploc.encl (MLast.loc_of_expr e1) loc in <:expr< [$e1$ :: $loop False el$] >> ] ; value mklistpat loc last = loop True where rec loop top = fun [ [] -> match last with [ Some p -> p | None -> <:patt< [] >> ] | [p1 :: pl] -> let loc = if top then loc else Ploc.encl (MLast.loc_of_patt p1) loc in <:patt< [$p1$ :: $loop False pl$] >> ] ; * * pulled this outside so user can add new infixes here too * * value ht = Hashtbl.create 73; * * And added all the new HOL Light infixes here already * * value is_operator = do { let ct = Hashtbl.create 73 in List.iter (fun x -> Hashtbl.add ht x True) ["asr"; "land"; "lor"; "lsl"; "lsr"; "lxor"; "mod"; "or"; "o"; "upto"; "F_F"; "THENC"; "THEN"; "THENL"; "ORELSE"; "ORELSEC"; "THEN_TCL"; "ORELSE_TCL"]; List.iter (fun x -> Hashtbl.add ct x True) ['!'; '&'; '*'; '+'; '-'; '/'; ':'; '<'; '='; '>'; '@'; '^'; '|'; '~'; '?'; '%'; '.'; '$']; fun x -> try Hashtbl.find ht x with [ Not_found -> try Hashtbl.find ct x.[0] with _ -> False ] }; * * added this so parenthesised operators undergo same mapping * * value translate_operator = fun s -> match s with [ "THEN" -> "then_" | "THENC" -> "thenc_" | "THENL" -> "thenl_" | "ORELSE" -> "orelse_" | "ORELSEC" -> "orelsec_" | "THEN_TCL" -> "then_tcl_" | "ORELSE_TCL" -> "orelse_tcl_" | "F_F" -> "f_f_" | _ -> s]; value operator_rparen = Grammar.Entry.of_parser gram "operator_rparen" (fun strm -> match Stream.npeek 2 strm with [ [("", s); ("", ")")] when is_operator s -> do { Stream.junk strm; Stream.junk strm; translate_operator s } | _ -> raise Stream.Failure ]) ; value check_not_part_of_patt = Grammar.Entry.of_parser gram "check_not_part_of_patt" (fun strm -> let tok = match Stream.npeek 4 strm with [ [("LIDENT", _); tok :: _] -> tok | [("", "("); ("", s); ("", ")"); tok] when is_operator s -> tok | _ -> raise Stream.Failure ] in match tok with [ ("", "," | "as" | "|" | "::") -> raise Stream.Failure | _ -> () ]) ; value symbolchar = let list = ['!'; '$'; '%'; '&'; '*'; '+'; '-'; '.'; '/'; ':'; '<'; '='; '>'; '?'; '@'; '^'; '|'; '~'] in loop where rec loop s i = if i == String.length s then True else if List.mem s.[i] list then loop s (i + 1) else False ; value prefixop = let list = ['!'; '?'; '~'] in let excl = ["!="; "??"; "?!"] in Grammar.Entry.of_parser gram "prefixop" (parser [: `("", x) when not (List.mem x excl) && String.length x >= 2 && List.mem x.[0] list && symbolchar x 1 :] -> x) ; value infixop0 = let list = ['='; '<'; '>'; '|'; '&'; '$'] in let excl = ["<-"; "||"; "&&"] in Grammar.Entry.of_parser gram "infixop0" (parser [: `("", x) when not (List.mem x excl) && (x = "$" || String.length x >= 2) && List.mem x.[0] list && symbolchar x 1 :] -> x) ; value infixop1 = let list = ['@'; '^'] in Grammar.Entry.of_parser gram "infixop1" (parser [: `("", x) when String.length x >= 2 && List.mem x.[0] list && symbolchar x 1 :] -> x) ; value infixop2 = let list = ['+'; '-'] in Grammar.Entry.of_parser gram "infixop2" (parser [: `("", x) when x <> "->" && String.length x >= 2 && List.mem x.[0] list && symbolchar x 1 :] -> x) ; value infixop3 = let list = ['*'; '/'; '%'] in Grammar.Entry.of_parser gram "infixop3" (parser [: `("", x) when String.length x >= 2 && List.mem x.[0] list && symbolchar x 1 :] -> x) ; value infixop4 = Grammar.Entry.of_parser gram "infixop4" (parser [: `("", x) when String.length x >= 3 && x.[0] == '*' && x.[1] == '*' && symbolchar x 2 :] -> x) ; value test_constr_decl = Grammar.Entry.of_parser gram "test_constr_decl" (fun strm -> match Stream.npeek 1 strm with [ [("UIDENT", _)] -> match Stream.npeek 2 strm with [ [_; ("", ".")] -> raise Stream.Failure | [_; ("", "(")] -> raise Stream.Failure | [_ :: _] -> () | _ -> raise Stream.Failure ] | [("", "|")] -> () | _ -> raise Stream.Failure ]) ; value stream_peek_nth n strm = loop n (Stream.npeek n strm) where rec loop n = fun [ [] -> None | [x] -> if n == 1 then Some x else None | [_ :: l] -> loop (n - 1) l ] ; horrible hack to be able to parse value test_ctyp_minusgreater = Grammar.Entry.of_parser gram "test_ctyp_minusgreater" (fun strm -> let rec skip_simple_ctyp n = match stream_peek_nth n strm with [ Some ("", "->") -> n | Some ("", "[" | "[<") -> skip_simple_ctyp (ignore_upto "]" (n + 1) + 1) | Some ("", "(") -> skip_simple_ctyp (ignore_upto ")" (n + 1) + 1) | Some ("", "as" | "'" | ":" | "*" | "." | "#" | "<" | ">" | ".." | ";" | "_") -> skip_simple_ctyp (n + 1) | Some ("QUESTIONIDENT" | "LIDENT" | "UIDENT", _) -> skip_simple_ctyp (n + 1) | Some _ | None -> raise Stream.Failure ] and ignore_upto end_kwd n = match stream_peek_nth n strm with [ Some ("", prm) when prm = end_kwd -> n | Some ("", "[" | "[<") -> ignore_upto end_kwd (ignore_upto "]" (n + 1) + 1) | Some ("", "(") -> ignore_upto end_kwd (ignore_upto ")" (n + 1) + 1) | Some _ -> ignore_upto end_kwd (n + 1) | None -> raise Stream.Failure ] in match Stream.peek strm with [ Some (("", "[") | ("LIDENT" | "UIDENT", _)) -> skip_simple_ctyp 1 | Some ("", "object") -> raise Stream.Failure | _ -> 1 ]) ; value test_label_eq = Grammar.Entry.of_parser gram "test_label_eq" (test 1 where rec test lev strm = match stream_peek_nth lev strm with [ Some (("UIDENT", _) | ("LIDENT", _) | ("", ".")) -> test (lev + 1) strm | Some ("ANTIQUOT_LOC", _) -> () | Some ("", "=") -> () | _ -> raise Stream.Failure ]) ; value test_typevar_list_dot = Grammar.Entry.of_parser gram "test_typevar_list_dot" (let rec test lev strm = match stream_peek_nth lev strm with [ Some ("", "'") -> test2 (lev + 1) strm | Some ("", ".") -> () | _ -> raise Stream.Failure ] and test2 lev strm = match stream_peek_nth lev strm with [ Some ("UIDENT" | "LIDENT", _) -> test (lev + 1) strm | _ -> raise Stream.Failure ] in test 1) ; value e_phony = Grammar.Entry.of_parser gram "e_phony" (parser []) ; value p_phony = Grammar.Entry.of_parser gram "p_phony" (parser []) ; value constr_arity = ref [("Some", 1); ("Match_Failure", 1)]; value rec is_expr_constr_call = fun [ <:expr< $uid:_$ >> -> True | <:expr< $uid:_$.$e$ >> -> is_expr_constr_call e | <:expr< $e$ $_$ >> -> is_expr_constr_call e | _ -> False ] ; value rec constr_expr_arity loc = fun [ <:expr< $uid:c$ >> -> try List.assoc c constr_arity.val with [ Not_found -> 0 ] | <:expr< $uid:_$.$e$ >> -> constr_expr_arity loc e | _ -> 1 ] ; value rec constr_patt_arity loc = fun [ <:patt< $uid:c$ >> -> try List.assoc c constr_arity.val with [ Not_found -> 0 ] | <:patt< $uid:_$.$p$ >> -> constr_patt_arity loc p | _ -> 1 ] ; value get_seq = fun [ <:expr< do { $list:el$ } >> -> el | e -> [e] ] ; value mem_tvar s tpl = List.exists (fun (t, _) -> Pcaml.unvala t = Some s) tpl ; value choose_tvar tpl = let rec find_alpha v = let s = String.make 1 v in if mem_tvar s tpl then if v = 'z' then None else find_alpha (Char.chr (Char.code v + 1)) else Some (String.make 1 v) in let rec make_n n = let v = "a" ^ string_of_int n in if mem_tvar v tpl then make_n (succ n) else v in match find_alpha 'a' with [ Some x -> x | None -> make_n 1 ] ; value quotation_content s = do { loop 0 where rec loop i = if i = String.length s then ("", s) else if s.[i] = ':' || s.[i] = '@' then let i = i + 1 in (String.sub s 0 i, String.sub s i (String.length s - i)) else loop (i + 1) }; value concat_comm loc e = let loc = Ploc.with_comment loc (Ploc.comment loc ^ Ploc.comment (MLast.loc_of_expr e)) in let floc = let first = ref True in fun loc1 -> if first.val then do {first.val := False; loc} else loc1 in reloc_expr floc 0 e ; EXTEND GLOBAL: sig_item str_item ctyp patt expr module_type module_expr signature structure class_type class_expr class_sig_item class_str_item let_binding type_decl constructor_declaration label_declaration match_case with_constr poly_variant; module_expr: [ [ "functor"; "("; i = V UIDENT "uid" ""; ":"; t = module_type; ")"; "->"; me = SELF -> <:module_expr< functor ( $_uid:i$ : $t$ ) -> $me$ >> | "struct"; st = structure; "end" -> <:module_expr< struct $_list:st$ end >> ] | [ me1 = SELF; "."; me2 = SELF -> <:module_expr< $me1$ . $me2$ >> ] | [ me1 = SELF; "("; me2 = SELF; ")" -> <:module_expr< $me1$ $me2$ >> ] | [ i = mod_expr_ident -> i | "("; "val"; e = expr; ":"; mt = module_type; ")" -> <:module_expr< (value $e$ : $mt$) >> | "("; "val"; e = expr; ")" -> <:module_expr< (value $e$) >> | "("; me = SELF; ":"; mt = module_type; ")" -> <:module_expr< ( $me$ : $mt$ ) >> | "("; me = SELF; ")" -> <:module_expr< $me$ >> ] ] ; structure: [ [ st = V (LIST0 [ s = str_item; OPT ";;" -> s ]) -> st ] ] ; mod_expr_ident: [ LEFTA [ i = SELF; "."; j = SELF -> <:module_expr< $i$ . $j$ >> ] | [ i = V UIDENT -> <:module_expr< $_uid:i$ >> ] ] ; str_item: [ "top" [ "exception"; (_, c, tl, _) = constructor_declaration; b = rebind_exn -> <:str_item< exception $_uid:c$ of $_list:tl$ = $_list:b$ >> | "external"; i = V LIDENT "lid" ""; ":"; t = ctyp; "="; pd = V (LIST1 STRING) -> <:str_item< external $_lid:i$ : $t$ = $_list:pd$ >> | "external"; "("; i = operator_rparen; ":"; t = ctyp; "="; pd = V (LIST1 STRING) -> <:str_item< external $lid:i$ : $t$ = $_list:pd$ >> | "include"; me = module_expr -> <:str_item< include $me$ >> | "module"; r = V (FLAG "rec"); l = V (LIST1 mod_binding SEP "and") -> <:str_item< module $_flag:r$ $_list:l$ >> | "module"; "type"; i = V UIDENT "uid" ""; "="; mt = module_type -> <:str_item< module type $_uid:i$ = $mt$ >> | "open"; i = V mod_ident "list" "" -> <:str_item< open $_:i$ >> | "type"; tdl = V (LIST1 type_decl SEP "and") -> <:str_item< type $_list:tdl$ >> | "let"; r = V (FLAG "rec"); l = V (LIST1 let_binding SEP "and"); "in"; x = expr -> let e = <:expr< let $_flag:r$ $_list:l$ in $x$ >> in <:str_item< $exp:e$ >> | "let"; r = V (FLAG "rec"); l = V (LIST1 let_binding SEP "and") -> match l with [ <:vala< [(p, e)] >> -> match p with [ <:patt< _ >> -> <:str_item< $exp:e$ >> | _ -> <:str_item< value $_flag:r$ $_list:l$ >> ] | _ -> <:str_item< value $_flag:r$ $_list:l$ >> ] | "let"; "module"; m = V UIDENT; mb = mod_fun_binding; "in"; e = expr -> <:str_item< let module $_uid:m$ = $mb$ in $e$ >> | e = expr -> <:str_item< $exp:e$ >> ] ] ; rebind_exn: [ [ "="; sl = V mod_ident "list" -> sl | -> <:vala< [] >> ] ] ; mod_binding: [ [ i = V UIDENT; me = mod_fun_binding -> (i, me) ] ] ; mod_fun_binding: [ RIGHTA [ "("; m = UIDENT; ":"; mt = module_type; ")"; mb = SELF -> <:module_expr< functor ( $uid:m$ : $mt$ ) -> $mb$ >> | ":"; mt = module_type; "="; me = module_expr -> <:module_expr< ( $me$ : $mt$ ) >> | "="; me = module_expr -> <:module_expr< $me$ >> ] ] ; (* Module types *) module_type: [ [ "functor"; "("; i = V UIDENT "uid" ""; ":"; t = SELF; ")"; "->"; mt = SELF -> <:module_type< functor ( $_uid:i$ : $t$ ) -> $mt$ >> ] | [ mt = SELF; "with"; wcl = V (LIST1 with_constr SEP "and") -> <:module_type< $mt$ with $_list:wcl$ >> ] | [ "sig"; sg = signature; "end" -> <:module_type< sig $_list:sg$ end >> | "module"; "type"; "of"; me = module_expr -> <:module_type< module type of $me$ >> | i = mod_type_ident -> i | "("; mt = SELF; ")" -> <:module_type< $mt$ >> ] ] ; signature: [ [ sg = V (LIST0 [ s = sig_item; OPT ";;" -> s ]) -> sg ] ] ; mod_type_ident: [ LEFTA [ m1 = SELF; "."; m2 = SELF -> <:module_type< $m1$ . $m2$ >> | m1 = SELF; "("; m2 = SELF; ")" -> <:module_type< $m1$ $m2$ >> ] | [ m = V UIDENT -> <:module_type< $_uid:m$ >> | m = V LIDENT -> <:module_type< $_lid:m$ >> ] ] ; sig_item: [ "top" [ "exception"; (_, c, tl, _) = constructor_declaration -> <:sig_item< exception $_uid:c$ of $_list:tl$ >> | "external"; i = V LIDENT "lid" ""; ":"; t = ctyp; "="; pd = V (LIST1 STRING) -> <:sig_item< external $_lid:i$ : $t$ = $_list:pd$ >> | "external"; "("; i = operator_rparen; ":"; t = ctyp; "="; pd = V (LIST1 STRING) -> <:sig_item< external $lid:i$ : $t$ = $_list:pd$ >> | "include"; mt = module_type -> <:sig_item< include $mt$ >> | "module"; rf = V (FLAG "rec"); l = V (LIST1 mod_decl_binding SEP "and") -> <:sig_item< module $_flag:rf$ $_list:l$ >> | "module"; "type"; i = V UIDENT "uid" ""; "="; mt = module_type -> <:sig_item< module type $_uid:i$ = $mt$ >> | "module"; "type"; i = V UIDENT "uid" "" -> <:sig_item< module type $_uid:i$ = 'abstract >> | "open"; i = V mod_ident "list" "" -> <:sig_item< open $_:i$ >> | "type"; tdl = V (LIST1 type_decl SEP "and") -> <:sig_item< type $_list:tdl$ >> | "val"; i = V LIDENT "lid" ""; ":"; t = ctyp -> <:sig_item< value $_lid:i$ : $t$ >> | "val"; "("; i = operator_rparen; ":"; t = ctyp -> <:sig_item< value $lid:i$ : $t$ >> ] ] ; mod_decl_binding: [ [ i = V UIDENT; mt = module_declaration -> (i, mt) ] ] ; module_declaration: [ RIGHTA [ ":"; mt = module_type -> <:module_type< $mt$ >> | "("; i = UIDENT; ":"; t = module_type; ")"; mt = SELF -> <:module_type< functor ( $uid:i$ : $t$ ) -> $mt$ >> ] ] ; (* "with" constraints (additional type equations over signature components) *) with_constr: [ [ "type"; tpl = V type_parameters "list"; i = V mod_ident ""; "="; pf = V (FLAG "private"); t = ctyp -> <:with_constr< type $_:i$ $_list:tpl$ = $_flag:pf$ $t$ >> | "type"; tpl = V type_parameters "list"; i = V mod_ident ""; ":="; t = ctyp -> <:with_constr< type $_:i$ $_list:tpl$ := $t$ >> | "module"; i = V mod_ident ""; "="; me = module_expr -> <:with_constr< module $_:i$ = $me$ >> | "module"; i = V mod_ident ""; ":="; me = module_expr -> <:with_constr< module $_:i$ := $me$ >> ] ] ; Core expressions expr: [ "top" RIGHTA [ e1 = SELF; ";"; e2 = SELF -> <:expr< do { $list:[e1 :: get_seq e2]$ } >> | e1 = SELF; ";" -> e1 | el = V e_phony "list" -> <:expr< do { $_list:el$ } >> ] | "expr1" [ "let"; o = V (FLAG "rec"); l = V (LIST1 let_binding SEP "and"); "in"; x = expr LEVEL "top" -> <:expr< let $_flag:o$ $_list:l$ in $x$ >> | "let"; "module"; m = V UIDENT; mb = mod_fun_binding; "in"; e = expr LEVEL "top" -> <:expr< let module $_uid:m$ = $mb$ in $e$ >> | "function"; OPT "|"; l = V (LIST1 match_case SEP "|") -> <:expr< fun [ $_list:l$ ] >> | "fun"; p = patt LEVEL "simple"; (eo, e) = fun_def -> <:expr< fun [$p$ $opt:eo$ -> $e$] >> | "match"; e = SELF; "with"; OPT "|"; l = V (LIST1 match_case SEP "|") -> <:expr< match $e$ with [ $_list:l$ ] >> | "try"; e = SELF; "with"; OPT "|"; l = V (LIST1 match_case SEP "|") -> <:expr< try $e$ with [ $_list:l$ ] >> | "if"; e1 = SELF; "then"; e2 = expr LEVEL "expr1"; "else"; e3 = expr LEVEL "expr1" -> <:expr< if $e1$ then $e2$ else $e3$ >> | "if"; e1 = SELF; "then"; e2 = expr LEVEL "expr1" -> <:expr< if $e1$ then $e2$ else () >> | "for"; i = V LIDENT; "="; e1 = SELF; df = V direction_flag "to"; e2 = SELF; "do"; e = V SELF "list"; "done" -> let el = Pcaml.vala_map get_seq e in <:expr< for $_lid:i$ = $e1$ $_to:df$ $e2$ do { $_list:el$ } >> | "while"; e1 = SELF; "do"; e2 = V SELF "list"; "done" -> let el = Pcaml.vala_map get_seq e2 in <:expr< while $e1$ do { $_list:el$ } >> ] | [ e = SELF; ","; el = LIST1 NEXT SEP "," -> <:expr< ( $list:[e :: el]$ ) >> ] | ":=" NONA [ e1 = SELF; ":="; e2 = expr LEVEL "expr1" -> <:expr< $e1$.val := $e2$ >> | e1 = SELF; "<-"; e2 = expr LEVEL "expr1" -> <:expr< $e1$ := $e2$ >> ] | "||" RIGHTA [ e1 = SELF; "or"; e2 = SELF -> <:expr< $lid:"or"$ $e1$ $e2$ >> | e1 = SELF; "||"; e2 = SELF -> <:expr< $e1$ || $e2$ >> ] | "&&" RIGHTA [ e1 = SELF; "&"; e2 = SELF -> <:expr< $lid:"&"$ $e1$ $e2$ >> | e1 = SELF; "&&"; e2 = SELF -> <:expr< $e1$ && $e2$ >> ] | "<" LEFTA [ e1 = SELF; "<"; e2 = SELF -> <:expr< $e1$ < $e2$ >> | e1 = SELF; ">"; e2 = SELF -> <:expr< $e1$ > $e2$ >> | e1 = SELF; "<="; e2 = SELF -> <:expr< $e1$ <= $e2$ >> | e1 = SELF; ">="; e2 = SELF -> <:expr< $e1$ >= $e2$ >> | e1 = SELF; "="; e2 = SELF -> <:expr< $e1$ = $e2$ >> | e1 = SELF; "<>"; e2 = SELF -> <:expr< $e1$ <> $e2$ >> | e1 = SELF; "=="; e2 = SELF -> <:expr< $e1$ == $e2$ >> | e1 = SELF; "!="; e2 = SELF -> <:expr< $e1$ != $e2$ >> | e1 = SELF; op = infixop0; e2 = SELF -> <:expr< $lid:op$ $e1$ $e2$ >> ] | "^" RIGHTA [ e1 = SELF; "^"; e2 = SELF -> <:expr< $e1$ ^ $e2$ >> | e1 = SELF; "@"; e2 = SELF -> <:expr< $e1$ @ $e2$ >> | e1 = SELF; op = infixop1; e2 = SELF -> <:expr< $lid:op$ $e1$ $e2$ >> ] | RIGHTA [ e1 = SELF; "::"; e2 = SELF -> <:expr< [$e1$ :: $e2$] >> ] | "+" LEFTA [ e1 = SELF; "+"; e2 = SELF -> <:expr< $e1$ + $e2$ >> | e1 = SELF; "-"; e2 = SELF -> <:expr< $e1$ - $e2$ >> | e1 = SELF; op = infixop2; e2 = SELF -> <:expr< $lid:op$ $e1$ $e2$ >> ] | "*" LEFTA [ e1 = SELF; "*"; e2 = SELF -> <:expr< $e1$ * $e2$ >> | e1 = SELF; "/"; e2 = SELF -> <:expr< $e1$ / $e2$ >> | e1 = SELF; "%"; e2 = SELF -> <:expr< $lid:"%"$ $e1$ $e2$ >> | e1 = SELF; "land"; e2 = SELF -> <:expr< $e1$ land $e2$ >> | e1 = SELF; "lor"; e2 = SELF -> <:expr< $e1$ lor $e2$ >> | e1 = SELF; "lxor"; e2 = SELF -> <:expr< $e1$ lxor $e2$ >> | e1 = SELF; "mod"; e2 = SELF -> <:expr< $e1$ mod $e2$ >> | e1 = SELF; op = infixop3; e2 = SELF -> <:expr< $lid:op$ $e1$ $e2$ >> ] | "**" RIGHTA [ e1 = SELF; "**"; e2 = SELF -> <:expr< $e1$ ** $e2$ >> | e1 = SELF; "asr"; e2 = SELF -> <:expr< $e1$ asr $e2$ >> | e1 = SELF; "lsl"; e2 = SELF -> <:expr< $e1$ lsl $e2$ >> | e1 = SELF; "lsr"; e2 = SELF -> <:expr< $e1$ lsr $e2$ >> | e1 = SELF; op = infixop4; e2 = SELF -> <:expr< $lid:op$ $e1$ $e2$ >> ] | "unary minus" NONA [ "-"; e = SELF -> <:expr< - $e$ >> | "-."; e = SELF -> <:expr< -. $e$ >> ] | "apply" LEFTA [ e1 = SELF; e2 = SELF -> let (e1, e2) = if is_expr_constr_call e1 then match e1 with [ <:expr< $e11$ $e12$ >> -> (e11, <:expr< $e12$ $e2$ >>) | _ -> (e1, e2) ] else (e1, e2) in match constr_expr_arity loc e1 with [ 1 -> <:expr< $e1$ $e2$ >> | _ -> match e2 with [ <:expr< ( $list:el$ ) >> -> List.fold_left (fun e1 e2 -> <:expr< $e1$ $e2$ >>) e1 el | _ -> <:expr< $e1$ $e2$ >> ] ] | "assert"; e = SELF -> <:expr< assert $e$ >> | "lazy"; e = SELF -> <:expr< lazy ($e$) >> ] | "." LEFTA [ e1 = SELF; "."; "("; op = operator_rparen -> <:expr< $e1$ .( $lid:op$ ) >> | e1 = SELF; "."; "("; e2 = SELF; ")" -> <:expr< $e1$ .( $e2$ ) >> | e1 = SELF; "."; "["; e2 = SELF; "]" -> <:expr< $e1$ .[ $e2$ ] >> | e = SELF; "."; "{"; el = V (LIST1 expr LEVEL "+" SEP ","); "}" -> <:expr< $e$ .{ $_list:el$ } >> | e1 = SELF; "."; e2 = SELF -> let rec loop m = fun [ <:expr< $x$ . $y$ >> -> loop <:expr< $m$ . $x$ >> y | e -> <:expr< $m$ . $e$ >> ] in loop e1 e2 ] | "~-" NONA [ "!"; e = SELF -> <:expr< $e$ . val >> | "~-"; e = SELF -> <:expr< ~- $e$ >> | "~-."; e = SELF -> <:expr< ~-. $e$ >> | f = prefixop; e = SELF -> <:expr< $lid:f$ $e$ >> ] | "simple" LEFTA [ s = V INT -> <:expr< $_int:s$ >> | s = V INT_l -> <:expr< $_int32:s$ >> | s = V INT_L -> <:expr< $_int64:s$ >> | s = V INT_n -> <:expr< $_nativeint:s$ >> | s = V FLOAT -> <:expr< $_flo:s$ >> | s = V STRING -> <:expr< $_str:s$ >> | c = V CHAR -> <:expr< $_chr:c$ >> | UIDENT "True" -> <:expr< True_ >> | UIDENT "False" -> <:expr< False_ >> | i = expr_ident -> i | "false" -> <:expr< False >> | "true" -> <:expr< True >> | "["; "]" -> <:expr< [] >> | "["; el = expr1_semi_list; "]" -> <:expr< $mklistexp loc None el$ >> | "[|"; "|]" -> <:expr< [| |] >> | "[|"; el = V expr1_semi_list "list"; "|]" -> <:expr< [| $_list:el$ |] >> | "{"; test_label_eq; lel = V lbl_expr_list "list"; "}" -> <:expr< { $_list:lel$ } >> | "{"; e = expr LEVEL "."; "with"; lel = V lbl_expr_list "list"; "}" -> <:expr< { ($e$) with $_list:lel$ } >> | "("; ")" -> <:expr< () >> | "("; "module"; me = module_expr; ":"; mt = module_type; ")" -> <:expr< (module $me$ : $mt$) >> | "("; "module"; me = module_expr; ")" -> <:expr< (module $me$) >> | "("; op = operator_rparen -> <:expr< $lid:op$ >> | "("; el = V e_phony "list"; ")" -> <:expr< ($_list:el$) >> | "("; e = SELF; ":"; t = ctyp; ")" -> <:expr< ($e$ : $t$) >> | "("; e = SELF; ")" -> concat_comm loc <:expr< $e$ >> | "begin"; e = SELF; "end" -> concat_comm loc <:expr< $e$ >> | "begin"; "end" -> <:expr< () >> | x = QUOTATION -> let con = quotation_content x in Pcaml.handle_expr_quotation loc con ] ] ; let_binding: [ [ p = val_ident; e = fun_binding -> (p, e) | p = patt; "="; e = expr -> (p, e) | p = patt; ":"; t = poly_type; "="; e = expr -> (<:patt< ($p$ : $t$) >>, e) ] ] ; * * added the " translate_operator " here * * val_ident: [ [ check_not_part_of_patt; s = LIDENT -> <:patt< $lid:s$ >> | check_not_part_of_patt; "("; s = ANY; ")" -> let s' = translate_operator s in <:patt< $lid:s'$ >> ] ] ; fun_binding: [ RIGHTA [ p = patt LEVEL "simple"; e = SELF -> <:expr< fun $p$ -> $e$ >> | "="; e = expr -> <:expr< $e$ >> | ":"; t = poly_type; "="; e = expr -> <:expr< ($e$ : $t$) >> ] ] ; match_case: [ [ x1 = patt; w = V (OPT [ "when"; e = expr -> e ]); "->"; x2 = expr -> (x1, w, x2) ] ] ; lbl_expr_list: [ [ le = lbl_expr; ";"; lel = SELF -> [le :: lel] | le = lbl_expr; ";" -> [le] | le = lbl_expr -> [le] ] ] ; lbl_expr: [ [ i = patt_label_ident; "="; e = expr LEVEL "expr1" -> (i, e) ] ] ; expr1_semi_list: [ [ el = LIST1 (expr LEVEL "expr1") SEP ";" OPT_SEP -> el ] ] ; fun_def: [ RIGHTA [ p = patt LEVEL "simple"; (eo, e) = SELF -> (None, <:expr< fun [ $p$ $opt:eo$ -> $e$ ] >>) | eo = OPT [ "when"; e = expr -> e ]; "->"; e = expr -> (eo, <:expr< $e$ >>) ] ] ; expr_ident: [ RIGHTA [ i = V LIDENT -> <:expr< $_lid:i$ >> | i = V UIDENT -> <:expr< $_uid:i$ >> | i = V UIDENT; "."; j = SELF -> let rec loop m = fun [ <:expr< $x$ . $y$ >> -> loop <:expr< $m$ . $x$ >> y | e -> <:expr< $m$ . $e$ >> ] in loop <:expr< $_uid:i$ >> j | i = V UIDENT; "."; "("; j = operator_rparen -> <:expr< $_uid:i$ . $lid:j$ >> ] ] ; (* Patterns *) patt: [ LEFTA [ p1 = SELF; "as"; i = LIDENT -> <:patt< ($p1$ as $lid:i$) >> ] | LEFTA [ p1 = SELF; "|"; p2 = SELF -> <:patt< $p1$ | $p2$ >> ] | [ p = SELF; ","; pl = LIST1 NEXT SEP "," -> <:patt< ( $list:[p :: pl]$) >> ] | NONA [ p1 = SELF; ".."; p2 = SELF -> <:patt< $p1$ .. $p2$ >> ] | RIGHTA [ p1 = SELF; "::"; p2 = SELF -> <:patt< [$p1$ :: $p2$] >> ] | LEFTA [ p1 = SELF; p2 = SELF -> let (p1, p2) = match p1 with [ <:patt< $p11$ $p12$ >> -> (p11, <:patt< $p12$ $p2$ >>) | _ -> (p1, p2) ] in match constr_patt_arity loc p1 with [ 1 -> <:patt< $p1$ $p2$ >> | n -> let p2 = match p2 with [ <:patt< _ >> when n > 1 -> let pl = loop n where rec loop n = if n = 0 then [] else [<:patt< _ >> :: loop (n - 1)] in <:patt< ( $list:pl$ ) >> | _ -> p2 ] in match p2 with [ <:patt< ( $list:pl$ ) >> -> List.fold_left (fun p1 p2 -> <:patt< $p1$ $p2$ >>) p1 pl | _ -> <:patt< $p1$ $p2$ >> ] ] | "lazy"; p = SELF -> <:patt< lazy $p$ >> ] | LEFTA [ p1 = SELF; "."; p2 = SELF -> <:patt< $p1$ . $p2$ >> ] | "simple" [ s = V LIDENT -> <:patt< $_lid:s$ >> | s = V UIDENT -> <:patt< $_uid:s$ >> | s = V INT -> <:patt< $_int:s$ >> | s = V INT_l -> <:patt< $_int32:s$ >> | s = V INT_L -> <:patt< $_int64:s$ >> | s = V INT_n -> <:patt< $_nativeint:s$ >> | "-"; s = INT -> <:patt< $int:"-" ^ s$ >> | "-"; s = FLOAT -> <:patt< $flo:"-" ^ s$ >> | s = V FLOAT -> <:patt< $_flo:s$ >> | s = V STRING -> <:patt< $_str:s$ >> | s = V CHAR -> <:patt< $_chr:s$ >> | UIDENT "True" -> <:patt< True_ >> | UIDENT "False" -> <:patt< False_ >> | "false" -> <:patt< False >> | "true" -> <:patt< True >> | "["; "]" -> <:patt< [] >> | "["; pl = patt_semi_list; "]" -> <:patt< $mklistpat loc None pl$ >> | "[|"; "|]" -> <:patt< [| |] >> | "[|"; pl = V patt_semi_list "list"; "|]" -> <:patt< [| $_list:pl$ |] >> | "{"; lpl = V lbl_patt_list "list"; "}" -> <:patt< { $_list:lpl$ } >> | "("; ")" -> <:patt< () >> | "("; op = operator_rparen -> <:patt< $lid:op$ >> | "("; pl = V p_phony "list"; ")" -> <:patt< ($_list:pl$) >> | "("; p = SELF; ":"; t = ctyp; ")" -> <:patt< ($p$ : $t$) >> | "("; p = SELF; ")" -> <:patt< $p$ >> | "("; "type"; s = V LIDENT; ")" -> <:patt< (type $_lid:s$) >> | "("; "module"; s = V UIDENT; ":"; mt = module_type; ")" -> <:patt< (module $_uid:s$ : $mt$) >> | "("; "module"; s = V UIDENT; ")" -> <:patt< (module $_uid:s$) >> | "_" -> <:patt< _ >> | x = QUOTATION -> let con = quotation_content x in Pcaml.handle_patt_quotation loc con ] ] ; patt_semi_list: [ [ p = patt; ";"; pl = SELF -> [p :: pl] | p = patt; ";" -> [p] | p = patt -> [p] ] ] ; lbl_patt_list: [ [ le = lbl_patt; ";"; lel = SELF -> [le :: lel] | le = lbl_patt; ";" -> [le] | le = lbl_patt -> [le] ] ] ; lbl_patt: [ [ i = patt_label_ident; "="; p = patt -> (i, p) ] ] ; patt_label_ident: [ LEFTA [ p1 = SELF; "."; p2 = SELF -> <:patt< $p1$ . $p2$ >> ] | RIGHTA [ i = UIDENT -> <:patt< $uid:i$ >> | i = LIDENT -> <:patt< $lid:i$ >> ] ] ; (* Type declaration *) type_decl: [ [ tpl = type_parameters; n = V type_patt; "="; pf = V (FLAG "private"); tk = type_kind; cl = V (LIST0 constrain) -> <:type_decl< $_tp:n$ $list:tpl$ = $_priv:pf$ $tk$ $_list:cl$ >> | tpl = type_parameters; n = V type_patt; cl = V (LIST0 constrain) -> let tk = <:ctyp< '$choose_tvar tpl$ >> in <:type_decl< $_tp:n$ $list:tpl$ = $tk$ $_list:cl$ >> ] ] ; type_patt: [ [ n = V LIDENT -> (loc, n) ] ] ; constrain: [ [ "constraint"; t1 = ctyp; "="; t2 = ctyp -> (t1, t2) ] ] ; type_kind: [ [ test_constr_decl; OPT "|"; cdl = LIST1 constructor_declaration SEP "|" -> <:ctyp< [ $list:cdl$ ] >> | t = ctyp -> <:ctyp< $t$ >> | t = ctyp; "="; pf = FLAG "private"; "{"; ldl = V label_declarations "list"; "}" -> <:ctyp< $t$ == $priv:pf$ { $_list:ldl$ } >> | t = ctyp; "="; pf = FLAG "private"; OPT "|"; cdl = LIST1 constructor_declaration SEP "|" -> <:ctyp< $t$ == $priv:pf$ [ $list:cdl$ ] >> | "{"; ldl = V label_declarations "list"; "}" -> <:ctyp< { $_list:ldl$ } >> ] ] ; type_parameters: [ [ -> (* empty *) [] | tp = type_parameter -> [tp] | "("; tpl = LIST1 type_parameter SEP ","; ")" -> tpl ] ] ; type_parameter: [ [ "+"; p = V simple_type_parameter -> (p, Some True) | "-"; p = V simple_type_parameter -> (p, Some False) | p = V simple_type_parameter -> (p, None) ] ] ; simple_type_parameter: [ [ "'"; i = ident -> Some i | "_" -> None ] ] ; constructor_declaration: [ [ ci = cons_ident; "of"; cal = V (LIST1 (ctyp LEVEL "apply") SEP "*") -> (loc, ci, cal, None) | ci = cons_ident; ":"; cal = V (LIST1 (ctyp LEVEL "apply") SEP "*"); "->"; t = ctyp -> (loc, ci, cal, Some t) | ci = cons_ident; ":"; cal = V (LIST1 (ctyp LEVEL "apply") SEP "*") -> let t = match cal with [ <:vala< [t] >> -> t | <:vala< [t :: tl] >> -> <:ctyp< ($list:[t :: tl]$) >> | _ -> assert False ] in (loc, ci, <:vala< [] >>, Some t) | ci = cons_ident -> (loc, ci, <:vala< [] >>, None) ] ] ; cons_ident: [ [ i = V UIDENT "uid" "" -> i | UIDENT "True" -> <:vala< "True_" >> | UIDENT "False" -> <:vala< "False_" >> ] ] ; label_declarations: [ [ ld = label_declaration; ";"; ldl = SELF -> [ld :: ldl] | ld = label_declaration; ";" -> [ld] | ld = label_declaration -> [ld] ] ] ; label_declaration: [ [ i = LIDENT; ":"; t = poly_type -> (loc, i, False, t) | "mutable"; i = LIDENT; ":"; t = poly_type -> (loc, i, True, t) ] ] ; Core types ctyp: [ [ t1 = SELF; "as"; "'"; i = ident -> <:ctyp< $t1$ as '$i$ >> ] | "arrow" RIGHTA [ t1 = SELF; "->"; t2 = SELF -> <:ctyp< $t1$ -> $t2$ >> ] | "star" [ t = SELF; "*"; tl = LIST1 (ctyp LEVEL "apply") SEP "*" -> <:ctyp< ( $list:[t :: tl]$ ) >> ] | "apply" [ t1 = SELF; t2 = SELF -> <:ctyp< $t2$ $t1$ >> ] | "ctyp2" [ t1 = SELF; "."; t2 = SELF -> <:ctyp< $t1$ . $t2$ >> | t1 = SELF; "("; t2 = SELF; ")" -> <:ctyp< $t1$ $t2$ >> ] | "simple" [ "'"; i = V ident "" -> <:ctyp< '$_:i$ >> | "_" -> <:ctyp< _ >> | i = V LIDENT -> <:ctyp< $_lid:i$ >> | i = V UIDENT -> <:ctyp< $_uid:i$ >> | "("; "module"; mt = module_type; ")" -> <:ctyp< module $mt$ >> | "("; t = SELF; ","; tl = LIST1 ctyp SEP ","; ")"; i = ctyp LEVEL "ctyp2" -> List.fold_left (fun c a -> <:ctyp< $c$ $a$ >>) i [t :: tl] | "("; t = SELF; ")" -> <:ctyp< $t$ >> ] ] ; (* Identifiers *) ident: [ [ i = LIDENT -> i | i = UIDENT -> i ] ] ; mod_ident: [ RIGHTA [ i = UIDENT -> [i] | i = LIDENT -> [i] | i = UIDENT; "."; j = SELF -> [i :: j] ] ] ; (* Miscellaneous *) direction_flag: [ [ "to" -> True | "downto" -> False ] ] ; (* Objects and Classes *) str_item: [ [ "class"; cd = V (LIST1 class_declaration SEP "and") -> <:str_item< class $_list:cd$ >> | "class"; "type"; ctd = V (LIST1 class_type_declaration SEP "and") -> <:str_item< class type $_list:ctd$ >> ] ] ; sig_item: [ [ "class"; cd = V (LIST1 class_description SEP "and") -> <:sig_item< class $_list:cd$ >> | "class"; "type"; ctd = V (LIST1 class_type_declaration SEP "and") -> <:sig_item< class type $_list:ctd$ >> ] ] ; (* Class expressions *) class_declaration: [ [ vf = V (FLAG "virtual"); ctp = class_type_parameters; i = V LIDENT; cfb = class_fun_binding -> {MLast.ciLoc = loc; MLast.ciVir = vf; MLast.ciPrm = ctp; MLast.ciNam = i; MLast.ciExp = cfb} ] ] ; class_fun_binding: [ [ "="; ce = class_expr -> ce | ":"; ct = class_type; "="; ce = class_expr -> <:class_expr< ($ce$ : $ct$) >> | p = patt LEVEL "simple"; cfb = SELF -> <:class_expr< fun $p$ -> $cfb$ >> ] ] ; class_type_parameters: [ [ -> (loc, <:vala< [] >>) | "["; tpl = V (LIST1 type_parameter SEP ","); "]" -> (loc, tpl) ] ] ; class_fun_def: [ [ p = patt LEVEL "simple"; "->"; ce = class_expr -> <:class_expr< fun $p$ -> $ce$ >> | p = patt LEVEL "simple"; cfd = SELF -> <:class_expr< fun $p$ -> $cfd$ >> ] ] ; class_expr: [ "top" [ "fun"; cfd = class_fun_def -> cfd | "let"; rf = V (FLAG "rec"); lb = V (LIST1 let_binding SEP "and"); "in"; ce = SELF -> <:class_expr< let $_flag:rf$ $_list:lb$ in $ce$ >> ] | "apply" LEFTA [ ce = SELF; e = expr LEVEL "label" -> <:class_expr< $ce$ $e$ >> ] | "simple" [ "["; ct = ctyp; ","; ctcl = LIST1 ctyp SEP ","; "]"; ci = class_longident -> <:class_expr< [ $list:[ct :: ctcl]$ ] $list:ci$ >> | "["; ct = ctyp; "]"; ci = class_longident -> <:class_expr< [ $ct$ ] $list:ci$ >> | ci = class_longident -> <:class_expr< $list:ci$ >> | "object"; cspo = V (OPT class_self_patt); cf = V class_structure "list"; "end" -> <:class_expr< object $_opt:cspo$ $_list:cf$ end >> | "("; ce = SELF; ":"; ct = class_type; ")" -> <:class_expr< ($ce$ : $ct$) >> | "("; ce = SELF; ")" -> ce ] ] ; class_structure: [ [ cf = LIST0 class_str_item -> cf ] ] ; class_self_patt: [ [ "("; p = patt; ")" -> p | "("; p = patt; ":"; t = ctyp; ")" -> <:patt< ($p$ : $t$) >> ] ] ; class_str_item: [ [ "inherit"; ce = class_expr; pb = V (OPT [ "as"; i = LIDENT -> i ]) -> <:class_str_item< inherit $ce$ $_opt:pb$ >> | "val"; ov = V (FLAG "!") "!"; mf = V (FLAG "mutable"); lab = V LIDENT "lid" ""; e = cvalue_binding -> <:class_str_item< value $_!:ov$ $_flag:mf$ $_lid:lab$ = $e$ >> | "val"; ov = V (FLAG "!") "!"; mf = V (FLAG "mutable"); "virtual"; lab = V LIDENT "lid" ""; ":"; t = ctyp -> if Pcaml.unvala ov then Ploc.raise loc (Stream.Error "virtual value cannot override") else <:class_str_item< value virtual $_flag:mf$ $_lid:lab$ : $t$ >> | "val"; "virtual"; mf = V (FLAG "mutable"); lab = V LIDENT "lid" ""; ":"; t = ctyp -> <:class_str_item< value virtual $_flag:mf$ $_lid:lab$ : $t$ >> | "method"; "private"; "virtual"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_str_item< method virtual private $_lid:l$ : $t$ >> | "method"; "virtual"; "private"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_str_item< method virtual private $_lid:l$ : $t$ >> | "method"; "virtual"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_str_item< method virtual $_lid:l$ : $t$ >> | "method"; ov = V (FLAG "!") "!"; "private"; l = V LIDENT "lid" ""; ":"; t = poly_type; "="; e = expr -> <:class_str_item< method $_!:ov$ private $_lid:l$ : $t$ = $e$ >> | "method"; ov = V (FLAG "!") "!"; "private"; l = V LIDENT "lid" ""; sb = fun_binding -> <:class_str_item< method $_!:ov$ private $_lid:l$ = $sb$ >> | "method"; ov = V (FLAG "!") "!"; l = V LIDENT "lid" ""; ":"; t = poly_type; "="; e = expr -> <:class_str_item< method $_!:ov$ $_lid:l$ : $t$ = $e$ >> | "method"; ov = V (FLAG "!") "!"; l = V LIDENT "lid" ""; sb = fun_binding -> <:class_str_item< method $_!:ov$ $_lid:l$ = $sb$ >> | "constraint"; t1 = ctyp; "="; t2 = ctyp -> <:class_str_item< type $t1$ = $t2$ >> | "initializer"; se = expr -> <:class_str_item< initializer $se$ >> ] ] ; cvalue_binding: [ [ "="; e = expr -> e | ":"; t = ctyp; "="; e = expr -> <:expr< ($e$ : $t$) >> | ":"; t = ctyp; ":>"; t2 = ctyp; "="; e = expr -> <:expr< ($e$ : $t$ :> $t2$) >> | ":>"; t = ctyp; "="; e = expr -> <:expr< ($e$ :> $t$) >> ] ] ; label: [ [ i = LIDENT -> i ] ] ; (* Class types *) class_type: [ [ test_ctyp_minusgreater; t = ctyp LEVEL "star"; "->"; ct = SELF -> <:class_type< [ $t$ ] -> $ct$ >> | cs = class_signature -> cs ] ] ; class_signature: [ [ "["; tl = LIST1 ctyp SEP ","; "]"; id = SELF -> <:class_type< $id$ [ $list:tl$ ] >> | "object"; cst = V (OPT class_self_type); csf = V (LIST0 class_sig_item); "end" -> <:class_type< object $_opt:cst$ $_list:csf$ end >> ] | [ ct1 = SELF; "."; ct2 = SELF -> <:class_type< $ct1$ . $ct2$ >> | ct1 = SELF; "("; ct2 = SELF; ")" -> <:class_type< $ct1$ $ct2$ >> ] | [ i = V LIDENT -> <:class_type< $_id: i$ >> | i = V UIDENT -> <:class_type< $_id: i$ >> ] ] ; class_self_type: [ [ "("; t = ctyp; ")" -> t ] ] ; class_sig_item: [ [ "inherit"; cs = class_signature -> <:class_sig_item< inherit $cs$ >> | "val"; mf = V (FLAG "mutable"); l = V LIDENT "lid" ""; ":"; t = ctyp -> <:class_sig_item< value $_flag:mf$ $_lid:l$ : $t$ >> | "method"; "private"; "virtual"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_sig_item< method virtual private $_lid:l$ : $t$ >> | "method"; "virtual"; "private"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_sig_item< method virtual private $_lid:l$ : $t$ >> | "method"; "virtual"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_sig_item< method virtual $_lid:l$ : $t$ >> | "method"; "private"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_sig_item< method private $_lid:l$ : $t$ >> | "method"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_sig_item< method $_lid:l$ : $t$ >> | "constraint"; t1 = ctyp; "="; t2 = ctyp -> <:class_sig_item< type $t1$ = $t2$ >> ] ] ; class_description: [ [ vf = V (FLAG "virtual"); ctp = class_type_parameters; n = V LIDENT; ":"; ct = class_type -> {MLast.ciLoc = loc; MLast.ciVir = vf; MLast.ciPrm = ctp; MLast.ciNam = n; MLast.ciExp = ct} ] ] ; class_type_declaration: [ [ vf = V (FLAG "virtual"); ctp = class_type_parameters; n = V LIDENT; "="; cs = class_signature -> {MLast.ciLoc = loc; MLast.ciVir = vf; MLast.ciPrm = ctp; MLast.ciNam = n; MLast.ciExp = cs} ] ] ; (* Expressions *) expr: LEVEL "simple" [ LEFTA [ "new"; i = V class_longident "list" -> <:expr< new $_list:i$ >> | "object"; cspo = V (OPT class_self_patt); cf = V class_structure "list"; "end" -> <:expr< object $_opt:cspo$ $_list:cf$ end >> ] ] ; expr: LEVEL "." [ [ e = SELF; "#"; lab = V LIDENT "lid" -> <:expr< $e$ # $_lid:lab$ >> ] ] ; expr: LEVEL "simple" [ [ "("; e = SELF; ":"; t = ctyp; ":>"; t2 = ctyp; ")" -> <:expr< ($e$ : $t$ :> $t2$) >> | "("; e = SELF; ":>"; t = ctyp; ")" -> <:expr< ($e$ :> $t$) >> | "{<"; ">}" -> <:expr< {< >} >> | "{<"; fel = V field_expr_list "list"; ">}" -> <:expr< {< $_list:fel$ >} >> ] ] ; field_expr_list: [ [ l = label; "="; e = expr LEVEL "expr1"; ";"; fel = SELF -> [(l, e) :: fel] | l = label; "="; e = expr LEVEL "expr1"; ";" -> [(l, e)] | l = label; "="; e = expr LEVEL "expr1" -> [(l, e)] ] ] ; Core types ctyp: LEVEL "simple" [ [ "#"; id = V class_longident "list" -> <:ctyp< # $_list:id$ >> | "<"; ml = V meth_list "list"; v = V (FLAG ".."); ">" -> <:ctyp< < $_list:ml$ $_flag:v$ > >> | "<"; ".."; ">" -> <:ctyp< < .. > >> | "<"; ">" -> <:ctyp< < > >> ] ] ; meth_list: [ [ f = field; ";"; ml = SELF -> [f :: ml] | f = field; ";" -> [f] | f = field -> [f] ] ] ; field: [ [ lab = LIDENT; ":"; t = poly_type -> (lab, t) ] ] ; (* Polymorphic types *) typevar: [ [ "'"; i = ident -> i ] ] ; poly_type: [ [ "type"; nt = LIST1 LIDENT; "."; ct = ctyp -> <:ctyp< type $list:nt$ . $ct$ >> | test_typevar_list_dot; tpl = LIST1 typevar; "."; t2 = ctyp -> <:ctyp< ! $list:tpl$ . $t2$ >> | t = ctyp -> t ] ] ; (* Identifiers *) class_longident: [ [ m = UIDENT; "."; l = SELF -> [m :: l] | i = LIDENT -> [i] ] ] ; (* Labels *) ctyp: AFTER "arrow" [ NONA [ i = V LIDENT; ":"; t = SELF -> <:ctyp< ~$_:i$: $t$ >> | i = V QUESTIONIDENTCOLON; t = SELF -> <:ctyp< ?$_:i$: $t$ >> | i = V QUESTIONIDENT; ":"; t = SELF -> <:ctyp< ?$_:i$: $t$ >> ] ] ; ctyp: LEVEL "simple" [ [ "["; OPT "|"; rfl = V (LIST1 poly_variant SEP "|"); "]" -> <:ctyp< [ = $_list:rfl$ ] >> | "["; ">"; "]" -> <:ctyp< [ > $list:[]$ ] >> | "["; ">"; OPT "|"; rfl = V (LIST1 poly_variant SEP "|"); "]" -> <:ctyp< [ > $_list:rfl$ ] >> | "[<"; OPT "|"; rfl = V (LIST1 poly_variant SEP "|"); "]" -> <:ctyp< [ < $_list:rfl$ ] >> | "[<"; OPT "|"; rfl = V (LIST1 poly_variant SEP "|"); ">"; ntl = V (LIST1 name_tag); "]" -> <:ctyp< [ < $_list:rfl$ > $_list:ntl$ ] >> ] ] ; poly_variant: [ [ "`"; i = V ident "" -> <:poly_variant< ` $_:i$ >> | "`"; i = V ident ""; "of"; ao = V (FLAG "&"); l = V (LIST1 ctyp SEP "&") -> <:poly_variant< `$_:i$ of $_flag:ao$ $_list:l$ >> | t = ctyp -> <:poly_variant< $t$ >> ] ] ; name_tag: [ [ "`"; i = ident -> i ] ] ; expr: LEVEL "expr1" [ [ "fun"; p = labeled_patt; (eo, e) = fun_def -> <:expr< fun [ $p$ $opt:eo$ -> $e$ ] >> ] ] ; expr: AFTER "apply" [ "label" [ i = V TILDEIDENTCOLON; e = SELF -> <:expr< ~{$_:i$ = $e$} >> | i = V TILDEIDENT -> <:expr< ~{$_:i$} >> | i = V QUESTIONIDENTCOLON; e = SELF -> <:expr< ?{$_:i$ = $e$} >> | i = V QUESTIONIDENT -> <:expr< ?{$_:i$} >> ] ] ; expr: LEVEL "simple" [ [ "`"; s = V ident "" -> <:expr< ` $_:s$ >> ] ] ; fun_def: [ [ p = labeled_patt; (eo, e) = SELF -> (None, <:expr< fun [ $p$ $opt:eo$ -> $e$ ] >>) ] ] ; fun_binding: [ [ p = labeled_patt; e = SELF -> <:expr< fun $p$ -> $e$ >> ] ] ; patt: LEVEL "simple" [ [ "`"; s = V ident "" -> <:patt< ` $_:s$ >> | "#"; t = V mod_ident "list" "" -> <:patt< # $_list:t$ >> | p = labeled_patt -> p ] ] ; labeled_patt: [ [ i = V TILDEIDENTCOLON; p = patt LEVEL "simple" -> <:patt< ~{$_:i$ = $p$} >> | i = V TILDEIDENT -> <:patt< ~{$_:i$} >> | "~"; "("; i = LIDENT; ")" -> <:patt< ~{$lid:i$} >> | "~"; "("; i = LIDENT; ":"; t = ctyp; ")" -> <:patt< ~{$lid:i$ : $t$} >> | i = V QUESTIONIDENTCOLON; j = LIDENT -> <:patt< ?{$_:i$ = ?{$lid:j$}} >> | i = V QUESTIONIDENTCOLON; "_" -> <:patt< ?{$_:i$} >> | i = V QUESTIONIDENTCOLON; "("; p = patt; "="; e = expr; ")" -> <:patt< ?{$_:i$ = ?{$p$ = $e$}} >> | i = V QUESTIONIDENTCOLON; "("; p = patt; ":"; t = ctyp; ")" -> <:patt< ?{$_:i$ = ?{$p$ : $t$}} >> | i = V QUESTIONIDENTCOLON; "("; p = patt; ":"; t = ctyp; "="; e = expr; ")" -> <:patt< ?{$_:i$ = ?{$p$ : $t$ = $e$}} >> | i = V QUESTIONIDENTCOLON; "("; p = patt; ")" -> <:patt< ?{$_:i$ = ?{$p$}} >> | i = V QUESTIONIDENT -> <:patt< ?{$_:i$} >> | "?"; "("; i = LIDENT; "="; e = expr; ")" -> <:patt< ?{$lid:i$ = $e$} >> | "?"; "("; i = LIDENT; ":"; t = ctyp; "="; e = expr; ")" -> <:patt< ?{$lid:i$ : $t$ = $e$} >> | "?"; "("; i = LIDENT; ")" -> <:patt< ?{$lid:i$} >> | "?"; "("; i = LIDENT; ":"; t = ctyp; ")" -> <:patt< ?{$lid:i$ : $t$} >> ] ] ; class_type: [ [ i = LIDENT; ":"; t = ctyp LEVEL "apply"; "->"; ct = SELF -> <:class_type< [ ~$i$: $t$ ] -> $ct$ >> | i = V QUESTIONIDENTCOLON; t = ctyp LEVEL "apply"; "->"; ct = SELF -> <:class_type< [ ?$_:i$: $t$ ] -> $ct$ >> | i = V QUESTIONIDENT; ":"; t = ctyp LEVEL "apply"; "->"; ct = SELF -> <:class_type< [ ?$_:i$: $t$ ] -> $ct$ >> ] ] ; class_fun_binding: [ [ p = labeled_patt; cfb = SELF -> <:class_expr< fun $p$ -> $cfb$ >> ] ] ; class_fun_def: [ [ p = labeled_patt; "->"; ce = class_expr -> <:class_expr< fun $p$ -> $ce$ >> | p = labeled_patt; cfd = SELF -> <:class_expr< fun $p$ -> $cfd$ >> ] ] ; END; (* Main entry points *) EXTEND GLOBAL: interf implem use_file top_phrase expr patt; interf: [ [ si = sig_item_semi; (sil, stopped) = SELF -> ([si :: sil], stopped) | "#"; n = LIDENT; dp = OPT expr; ";;" -> ([(<:sig_item< # $lid:n$ $opt:dp$ >>, loc)], None) | EOI -> ([], Some loc) ] ] ; sig_item_semi: [ [ si = sig_item; OPT ";;" -> (si, loc) ] ] ; implem: [ [ si = str_item_semi; (sil, stopped) = SELF -> ([si :: sil], stopped) | "#"; n = LIDENT; dp = OPT expr; ";;" -> ([(<:str_item< # $lid:n$ $opt:dp$ >>, loc)], None) | EOI -> ([], Some loc) ] ] ; str_item_semi: [ [ si = str_item; OPT ";;" -> (si, loc) ] ] ; top_phrase: [ [ ph = phrase; ";;" -> Some ph | EOI -> None ] ] ; use_file: [ [ si = str_item; OPT ";;"; (sil, stopped) = SELF -> ([si :: sil], stopped) | "#"; n = LIDENT; dp = OPT expr; ";;" -> ([<:str_item< # $lid:n$ $opt:dp$ >>], True) | EOI -> ([], False) ] ] ; phrase: [ [ sti = str_item -> sti | "#"; n = LIDENT; dp = OPT expr -> <:str_item< # $lid:n$ $opt:dp$ >> ] ] ; END; Pcaml.add_option "-no_quot" (Arg.Set no_quotations) "Don't parse quotations, allowing to use, e.g. \"<:>\" as token"; (* ------------------------------------------------------------------------- *) Added by * * * (* ------------------------------------------------------------------------- *) EXTEND expr: AFTER "<" [[ f = expr; "o"; g = expr -> <:expr< ((o $f$) $g$) >> | f = expr; "upto"; g = expr -> <:expr< ((upto $f$) $g$) >> | f = expr; "F_F"; g = expr -> <:expr< ((f_f_ $f$) $g$) >> | f = expr; "THENC"; g = expr -> <:expr< ((thenc_ $f$) $g$) >> | f = expr; "THEN"; g = expr -> <:expr< ((then_ $f$) $g$) >> | f = expr; "THENL"; g = expr -> <:expr< ((thenl_ $f$) $g$) >> | f = expr; "ORELSE"; g = expr -> <:expr< ((orelse_ $f$) $g$) >> | f = expr; "ORELSEC"; g = expr -> <:expr< ((orelsec_ $f$) $g$) >> | f = expr; "THEN_TCL"; g = expr -> <:expr< ((then_tcl_ $f$) $g$) >> | f = expr; "ORELSE_TCL"; g = expr -> <:expr< ((orelse_tcl_ $f$) $g$) >> ]]; END; EXTEND top_phrase: [ [ sti = str_item; ";;" -> match sti with [ <:str_item< $exp:e$ >> -> Some <:str_item< value it = $e$ >> | x -> Some x ] ] ] ; END;
null
https://raw.githubusercontent.com/jrh13/hol-light/ea44a4cacd238d7fa5a397f043f3e3321eb66543/pa_j_3.1x_6.02.1.ml
ocaml
------------------------------------------------------------------------- New version. ------------------------------------------------------------------------- camlp5r ------------------------------------------------------------------------- The main/reloc.ml file. ------------------------------------------------------------------------- camlp5r ...<:expr<.....$lid:...xxxxxxxx...$...>>... |..|-----------------------------------| qloc <-----> sh |.........|------------| loc |..|------| loc1 Equality over syntax trees ------------------------------------------------------------------------- Now the lexer. ------------------------------------------------------------------------- camlp5r ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- Back to original file with the mod of using the above. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Back to etc/pa_o.ml ------------------------------------------------------------------------- Module types "with" constraints (additional type equations over signature components) Patterns Type declaration empty Identifiers Miscellaneous Objects and Classes Class expressions Class types Expressions Polymorphic types Identifiers Labels Main entry points ------------------------------------------------------------------------- -------------------------------------------------------------------------
$ I d : pa_o.ml , v 6.33 2010 - 11 - 16 16:48:21 deraugla Exp $ Copyright ( c ) INRIA 2007 - 2010 #load "pa_extend.cmo"; #load "q_MLast.cmo"; #load "pa_reloc.cmo"; open Pcaml; Pcaml.syntax_name.val := "OCaml"; Pcaml.no_constructors_arity.val := True; $ I d : reloc.ml , v 6.16 2010 - 11 - 21 17:17:45 deraugla Exp $ Copyright ( c ) INRIA 2007 - 2010 #load "pa_macro.cmo"; open MLast; value option_map f = fun [ Some x -> Some (f x) | None -> None ] ; value vala_map f = IFNDEF STRICT THEN fun x -> f x ELSE fun [ Ploc.VaAnt s -> Ploc.VaAnt s | Ploc.VaVal x -> Ploc.VaVal (f x) ] END ; value class_infos_map floc f x = {ciLoc = floc x.ciLoc; ciVir = x.ciVir; ciPrm = let (x1, x2) = x.ciPrm in (floc x1, x2); ciNam = x.ciNam; ciExp = f x.ciExp} ; value anti_loc qloc sh loc loc1 = let sh1 = Ploc.first_pos qloc + sh in let sh2 = sh1 + Ploc.first_pos loc in let line_nb_qloc = Ploc.line_nb qloc in let line_nb_loc = Ploc.line_nb loc in let line_nb_loc1 = Ploc.line_nb loc1 in if line_nb_qloc < 0 || line_nb_loc < 0 || line_nb_loc1 < 0 then Ploc.make_unlined (sh2 + Ploc.first_pos loc1, sh2 + Ploc.last_pos loc1) else Ploc.make_loc (Ploc.file_name loc) (line_nb_qloc + line_nb_loc + line_nb_loc1 - 2) (if line_nb_loc1 = 1 then if line_nb_loc = 1 then Ploc.bol_pos qloc else sh1 + Ploc.bol_pos loc else sh2 + Ploc.bol_pos loc1) (sh2 + Ploc.first_pos loc1, sh2 + Ploc.last_pos loc1) "" ; value rec reloc_ctyp floc sh = self where rec self = fun [ TyAcc loc x1 x2 -> let loc = floc loc in TyAcc loc (self x1) (self x2) | TyAli loc x1 x2 -> let loc = floc loc in TyAli loc (self x1) (self x2) | TyAny loc -> let loc = floc loc in TyAny loc | TyApp loc x1 x2 -> let loc = floc loc in TyApp loc (self x1) (self x2) | TyArr loc x1 x2 -> let loc = floc loc in TyArr loc (self x1) (self x2) | TyCls loc x1 -> let loc = floc loc in TyCls loc x1 | TyLab loc x1 x2 -> let loc = floc loc in TyLab loc x1 (self x2) | TyLid loc x1 -> let loc = floc loc in TyLid loc x1 | TyMan loc x1 x2 x3 -> let loc = floc loc in TyMan loc (self x1) x2 (self x3) | TyObj loc x1 x2 -> let loc = floc loc in TyObj loc (vala_map (List.map (fun (x1, x2) -> (x1, self x2))) x1) x2 | TyOlb loc x1 x2 -> let loc = floc loc in TyOlb loc x1 (self x2) | TyPck loc x1 -> let loc = floc loc in TyPck loc (reloc_module_type floc sh x1) | TyPol loc x1 x2 -> let loc = floc loc in TyPol loc x1 (self x2) | TyPot loc x1 x2 -> let loc = floc loc in TyPot loc x1 (self x2) | TyQuo loc x1 -> let loc = floc loc in TyQuo loc x1 | TyRec loc x1 -> let loc = floc loc in TyRec loc (vala_map (List.map (fun (loc, x1, x2, x3) -> (floc loc, x1, x2, self x3))) x1) | TySum loc x1 -> let loc = floc loc in TySum loc (vala_map (List.map (fun (loc, x1, x2, x3) -> (floc loc, x1, vala_map (List.map self) x2, option_map self x3))) x1) | TyTup loc x1 -> let loc = floc loc in TyTup loc (vala_map (List.map self) x1) | TyUid loc x1 -> let loc = floc loc in TyUid loc x1 | TyVrn loc x1 x2 -> let loc = floc loc in TyVrn loc (vala_map (List.map (reloc_poly_variant floc sh)) x1) x2 | IFDEF STRICT THEN TyXtr loc x1 x2 -> let loc = floc loc in TyXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_poly_variant floc sh = fun [ PvTag loc x1 x2 x3 -> let loc = floc loc in PvTag loc x1 x2 (vala_map (List.map (reloc_ctyp floc sh)) x3) | PvInh loc x1 -> let loc = floc loc in PvInh loc (reloc_ctyp floc sh x1) ] and reloc_patt floc sh = self where rec self = fun [ PaAcc loc x1 x2 -> let loc = floc loc in PaAcc loc (self x1) (self x2) | PaAli loc x1 x2 -> let loc = floc loc in PaAli loc (self x1) (self x2) | PaAnt loc x1 -> let new_floc loc1 = anti_loc (floc loc) sh loc loc1 in reloc_patt new_floc sh x1 | PaAny loc -> let loc = floc loc in PaAny loc | PaApp loc x1 x2 -> let loc = floc loc in PaApp loc (self x1) (self x2) | PaArr loc x1 -> let loc = floc loc in PaArr loc (vala_map (List.map self) x1) | PaChr loc x1 -> let loc = floc loc in PaChr loc x1 | PaFlo loc x1 -> let loc = floc loc in PaFlo loc x1 | PaInt loc x1 x2 -> let loc = floc loc in PaInt loc x1 x2 | PaLab loc x1 x2 -> let loc = floc loc in PaLab loc (self x1) (vala_map (option_map self) x2) | PaLaz loc x1 -> let loc = floc loc in PaLaz loc (self x1) | PaLid loc x1 -> let loc = floc loc in PaLid loc x1 | PaNty loc x1 -> let loc = floc loc in PaNty loc x1 | PaOlb loc x1 x2 -> let loc = floc loc in PaOlb loc (self x1) (vala_map (option_map (reloc_expr floc sh)) x2) | PaOrp loc x1 x2 -> let loc = floc loc in PaOrp loc (self x1) (self x2) | PaRec loc x1 -> let loc = floc loc in PaRec loc (vala_map (List.map (fun (x1, x2) -> (self x1, self x2))) x1) | PaRng loc x1 x2 -> let loc = floc loc in PaRng loc (self x1) (self x2) | PaStr loc x1 -> let loc = floc loc in PaStr loc x1 | PaTup loc x1 -> let loc = floc loc in PaTup loc (vala_map (List.map self) x1) | PaTyc loc x1 x2 -> let loc = floc loc in PaTyc loc (self x1) (reloc_ctyp floc sh x2) | PaTyp loc x1 -> let loc = floc loc in PaTyp loc x1 | PaUid loc x1 -> let loc = floc loc in PaUid loc x1 | PaUnp loc x1 x2 -> let loc = floc loc in PaUnp loc x1 (option_map (reloc_module_type floc sh) x2) | PaVrn loc x1 -> let loc = floc loc in PaVrn loc x1 | IFDEF STRICT THEN PaXtr loc x1 x2 -> let loc = floc loc in PaXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_expr floc sh = self where rec self = fun [ ExAcc loc x1 x2 -> let loc = floc loc in ExAcc loc (self x1) (self x2) | ExAnt loc x1 -> let new_floc loc1 = anti_loc (floc loc) sh loc loc1 in reloc_expr new_floc sh x1 | ExApp loc x1 x2 -> let loc = floc loc in ExApp loc (self x1) (self x2) | ExAre loc x1 x2 -> let loc = floc loc in ExAre loc (self x1) (self x2) | ExArr loc x1 -> let loc = floc loc in ExArr loc (vala_map (List.map self) x1) | ExAsr loc x1 -> let loc = floc loc in ExAsr loc (self x1) | ExAss loc x1 x2 -> let loc = floc loc in ExAss loc (self x1) (self x2) | ExBae loc x1 x2 -> let loc = floc loc in ExBae loc (self x1) (vala_map (List.map self) x2) | ExChr loc x1 -> let loc = floc loc in ExChr loc x1 | ExCoe loc x1 x2 x3 -> let loc = floc loc in ExCoe loc (self x1) (option_map (reloc_ctyp floc sh) x2) (reloc_ctyp floc sh x3) | ExFlo loc x1 -> let loc = floc loc in ExFlo loc x1 | ExFor loc x1 x2 x3 x4 x5 -> let loc = floc loc in ExFor loc x1 (self x2) (self x3) x4 (vala_map (List.map self) x5) | ExFun loc x1 -> let loc = floc loc in ExFun loc (vala_map (List.map (fun (x1, x2, x3) -> (reloc_patt floc sh x1, vala_map (option_map self) x2, self x3))) x1) | ExIfe loc x1 x2 x3 -> let loc = floc loc in ExIfe loc (self x1) (self x2) (self x3) | ExInt loc x1 x2 -> let loc = floc loc in ExInt loc x1 x2 | ExLab loc x1 -> let loc = floc loc in ExLab loc (vala_map (List.map (fun (x1, x2) -> (reloc_patt floc sh x1, vala_map (option_map self) x2))) x1) | ExLaz loc x1 -> let loc = floc loc in ExLaz loc (self x1) | ExLet loc x1 x2 x3 -> let loc = floc loc in ExLet loc x1 (vala_map (List.map (fun (x1, x2) -> (reloc_patt floc sh x1, self x2))) x2) (self x3) | ExLid loc x1 -> let loc = floc loc in ExLid loc x1 | ExLmd loc x1 x2 x3 -> let loc = floc loc in ExLmd loc x1 (reloc_module_expr floc sh x2) (self x3) | ExMat loc x1 x2 -> let loc = floc loc in ExMat loc (self x1) (vala_map (List.map (fun (x1, x2, x3) -> (reloc_patt floc sh x1, vala_map (option_map self) x2, self x3))) x2) | ExNew loc x1 -> let loc = floc loc in ExNew loc x1 | ExObj loc x1 x2 -> let loc = floc loc in ExObj loc (vala_map (option_map (reloc_patt floc sh)) x1) (vala_map (List.map (reloc_class_str_item floc sh)) x2) | ExOlb loc x1 x2 -> let loc = floc loc in ExOlb loc (reloc_patt floc sh x1) (vala_map (option_map self) x2) | ExOvr loc x1 -> let loc = floc loc in ExOvr loc (vala_map (List.map (fun (x1, x2) -> (x1, self x2))) x1) | ExPck loc x1 x2 -> let loc = floc loc in ExPck loc (reloc_module_expr floc sh x1) (option_map (reloc_module_type floc sh) x2) | ExRec loc x1 x2 -> let loc = floc loc in ExRec loc (vala_map (List.map (fun (x1, x2) -> (reloc_patt floc sh x1, self x2))) x1) (option_map self x2) | ExSeq loc x1 -> let loc = floc loc in ExSeq loc (vala_map (List.map self) x1) | ExSnd loc x1 x2 -> let loc = floc loc in ExSnd loc (self x1) x2 | ExSte loc x1 x2 -> let loc = floc loc in ExSte loc (self x1) (self x2) | ExStr loc x1 -> let loc = floc loc in ExStr loc x1 | ExTry loc x1 x2 -> let loc = floc loc in ExTry loc (self x1) (vala_map (List.map (fun (x1, x2, x3) -> (reloc_patt floc sh x1, vala_map (option_map self) x2, self x3))) x2) | ExTup loc x1 -> let loc = floc loc in ExTup loc (vala_map (List.map self) x1) | ExTyc loc x1 x2 -> let loc = floc loc in ExTyc loc (self x1) (reloc_ctyp floc sh x2) | ExUid loc x1 -> let loc = floc loc in ExUid loc x1 | ExVrn loc x1 -> let loc = floc loc in ExVrn loc x1 | ExWhi loc x1 x2 -> let loc = floc loc in ExWhi loc (self x1) (vala_map (List.map self) x2) | IFDEF STRICT THEN ExXtr loc x1 x2 -> let loc = floc loc in ExXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_module_type floc sh = self where rec self = fun [ MtAcc loc x1 x2 -> let loc = floc loc in MtAcc loc (self x1) (self x2) | MtApp loc x1 x2 -> let loc = floc loc in MtApp loc (self x1) (self x2) | MtFun loc x1 x2 x3 -> let loc = floc loc in MtFun loc x1 (self x2) (self x3) | MtLid loc x1 -> let loc = floc loc in MtLid loc x1 | MtQuo loc x1 -> let loc = floc loc in MtQuo loc x1 | MtSig loc x1 -> let loc = floc loc in MtSig loc (vala_map (List.map (reloc_sig_item floc sh)) x1) | MtTyo loc x1 -> let loc = floc loc in MtTyo loc (reloc_module_expr floc sh x1) | MtUid loc x1 -> let loc = floc loc in MtUid loc x1 | MtWit loc x1 x2 -> let loc = floc loc in MtWit loc (self x1) (vala_map (List.map (reloc_with_constr floc sh)) x2) | IFDEF STRICT THEN MtXtr loc x1 x2 -> let loc = floc loc in MtXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_sig_item floc sh = self where rec self = fun [ SgCls loc x1 -> let loc = floc loc in SgCls loc (vala_map (List.map (class_infos_map floc (reloc_class_type floc sh))) x1) | SgClt loc x1 -> let loc = floc loc in SgClt loc (vala_map (List.map (class_infos_map floc (reloc_class_type floc sh))) x1) | SgDcl loc x1 -> let loc = floc loc in SgDcl loc (vala_map (List.map self) x1) | SgDir loc x1 x2 -> let loc = floc loc in SgDir loc x1 (vala_map (option_map (reloc_expr floc sh)) x2) | SgExc loc x1 x2 -> let loc = floc loc in SgExc loc x1 (vala_map (List.map (reloc_ctyp floc sh)) x2) | SgExt loc x1 x2 x3 -> let loc = floc loc in SgExt loc x1 (reloc_ctyp floc sh x2) x3 | SgInc loc x1 -> let loc = floc loc in SgInc loc (reloc_module_type floc sh x1) | SgMod loc x1 x2 -> let loc = floc loc in SgMod loc x1 (vala_map (List.map (fun (x1, x2) -> (x1, reloc_module_type floc sh x2))) x2) | SgMty loc x1 x2 -> let loc = floc loc in SgMty loc x1 (reloc_module_type floc sh x2) | SgOpn loc x1 -> let loc = floc loc in SgOpn loc x1 | SgTyp loc x1 -> let loc = floc loc in SgTyp loc (vala_map (List.map (reloc_type_decl floc sh)) x1) | SgUse loc x1 x2 -> let loc = floc loc in SgUse loc x1 (vala_map (List.map (fun (x1, loc) -> (self x1, floc loc))) x2) | SgVal loc x1 x2 -> let loc = floc loc in SgVal loc x1 (reloc_ctyp floc sh x2) | IFDEF STRICT THEN SgXtr loc x1 x2 -> let loc = floc loc in SgXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_with_constr floc sh = fun [ WcMod loc x1 x2 -> let loc = floc loc in WcMod loc x1 (reloc_module_expr floc sh x2) | WcMos loc x1 x2 -> let loc = floc loc in WcMos loc x1 (reloc_module_expr floc sh x2) | WcTyp loc x1 x2 x3 x4 -> let loc = floc loc in WcTyp loc x1 x2 x3 (reloc_ctyp floc sh x4) | WcTys loc x1 x2 x3 -> let loc = floc loc in WcTys loc x1 x2 (reloc_ctyp floc sh x3) ] and reloc_module_expr floc sh = self where rec self = fun [ MeAcc loc x1 x2 -> let loc = floc loc in MeAcc loc (self x1) (self x2) | MeApp loc x1 x2 -> let loc = floc loc in MeApp loc (self x1) (self x2) | MeFun loc x1 x2 x3 -> let loc = floc loc in MeFun loc x1 (reloc_module_type floc sh x2) (self x3) | MeStr loc x1 -> let loc = floc loc in MeStr loc (vala_map (List.map (reloc_str_item floc sh)) x1) | MeTyc loc x1 x2 -> let loc = floc loc in MeTyc loc (self x1) (reloc_module_type floc sh x2) | MeUid loc x1 -> let loc = floc loc in MeUid loc x1 | MeUnp loc x1 x2 -> let loc = floc loc in MeUnp loc (reloc_expr floc sh x1) (option_map (reloc_module_type floc sh) x2) | IFDEF STRICT THEN MeXtr loc x1 x2 -> let loc = floc loc in MeXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_str_item floc sh = self where rec self = fun [ StCls loc x1 -> let loc = floc loc in StCls loc (vala_map (List.map (class_infos_map floc (reloc_class_expr floc sh))) x1) | StClt loc x1 -> let loc = floc loc in StClt loc (vala_map (List.map (class_infos_map floc (reloc_class_type floc sh))) x1) | StDcl loc x1 -> let loc = floc loc in StDcl loc (vala_map (List.map self) x1) | StDir loc x1 x2 -> let loc = floc loc in StDir loc x1 (vala_map (option_map (reloc_expr floc sh)) x2) | StExc loc x1 x2 x3 -> let loc = floc loc in StExc loc x1 (vala_map (List.map (reloc_ctyp floc sh)) x2) x3 | StExp loc x1 -> let loc = floc loc in StExp loc (reloc_expr floc sh x1) | StExt loc x1 x2 x3 -> let loc = floc loc in StExt loc x1 (reloc_ctyp floc sh x2) x3 | StInc loc x1 -> let loc = floc loc in StInc loc (reloc_module_expr floc sh x1) | StMod loc x1 x2 -> let loc = floc loc in StMod loc x1 (vala_map (List.map (fun (x1, x2) -> (x1, reloc_module_expr floc sh x2))) x2) | StMty loc x1 x2 -> let loc = floc loc in StMty loc x1 (reloc_module_type floc sh x2) | StOpn loc x1 -> let loc = floc loc in StOpn loc x1 | StTyp loc x1 -> let loc = floc loc in StTyp loc (vala_map (List.map (reloc_type_decl floc sh)) x1) | StUse loc x1 x2 -> let loc = floc loc in StUse loc x1 (vala_map (List.map (fun (x1, loc) -> (self x1, floc loc))) x2) | StVal loc x1 x2 -> let loc = floc loc in StVal loc x1 (vala_map (List.map (fun (x1, x2) -> (reloc_patt floc sh x1, reloc_expr floc sh x2))) x2) | IFDEF STRICT THEN StXtr loc x1 x2 -> let loc = floc loc in StXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_type_decl floc sh x = {tdNam = vala_map (fun (loc, x1) -> (floc loc, x1)) x.tdNam; tdPrm = x.tdPrm; tdPrv = x.tdPrv; tdDef = reloc_ctyp floc sh x.tdDef; tdCon = vala_map (List.map (fun (x1, x2) -> (reloc_ctyp floc sh x1, reloc_ctyp floc sh x2))) x.tdCon} and reloc_class_type floc sh = self where rec self = fun [ CtAcc loc x1 x2 -> let loc = floc loc in CtAcc loc (self x1) (self x2) | CtApp loc x1 x2 -> let loc = floc loc in CtApp loc (self x1) (self x2) | CtCon loc x1 x2 -> let loc = floc loc in CtCon loc (self x1) (vala_map (List.map (reloc_ctyp floc sh)) x2) | CtFun loc x1 x2 -> let loc = floc loc in CtFun loc (reloc_ctyp floc sh x1) (self x2) | CtIde loc x1 -> let loc = floc loc in CtIde loc x1 | CtSig loc x1 x2 -> let loc = floc loc in CtSig loc (vala_map (option_map (reloc_ctyp floc sh)) x1) (vala_map (List.map (reloc_class_sig_item floc sh)) x2) | IFDEF STRICT THEN CtXtr loc x1 x2 -> let loc = floc loc in CtXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_class_sig_item floc sh = self where rec self = fun [ CgCtr loc x1 x2 -> let loc = floc loc in CgCtr loc (reloc_ctyp floc sh x1) (reloc_ctyp floc sh x2) | CgDcl loc x1 -> let loc = floc loc in CgDcl loc (vala_map (List.map self) x1) | CgInh loc x1 -> let loc = floc loc in CgInh loc (reloc_class_type floc sh x1) | CgMth loc x1 x2 x3 -> let loc = floc loc in CgMth loc x1 x2 (reloc_ctyp floc sh x3) | CgVal loc x1 x2 x3 -> let loc = floc loc in CgVal loc x1 x2 (reloc_ctyp floc sh x3) | CgVir loc x1 x2 x3 -> let loc = floc loc in CgVir loc x1 x2 (reloc_ctyp floc sh x3) ] and reloc_class_expr floc sh = self where rec self = fun [ CeApp loc x1 x2 -> let loc = floc loc in CeApp loc (self x1) (reloc_expr floc sh x2) | CeCon loc x1 x2 -> let loc = floc loc in CeCon loc x1 (vala_map (List.map (reloc_ctyp floc sh)) x2) | CeFun loc x1 x2 -> let loc = floc loc in CeFun loc (reloc_patt floc sh x1) (self x2) | CeLet loc x1 x2 x3 -> let loc = floc loc in CeLet loc x1 (vala_map (List.map (fun (x1, x2) -> (reloc_patt floc sh x1, reloc_expr floc sh x2))) x2) (self x3) | CeStr loc x1 x2 -> let loc = floc loc in CeStr loc (vala_map (option_map (reloc_patt floc sh)) x1) (vala_map (List.map (reloc_class_str_item floc sh)) x2) | CeTyc loc x1 x2 -> let loc = floc loc in CeTyc loc (self x1) (reloc_class_type floc sh x2) | IFDEF STRICT THEN CeXtr loc x1 x2 -> let loc = floc loc in CeXtr loc x1 (option_map (vala_map self) x2) END ] and reloc_class_str_item floc sh = self where rec self = fun [ CrCtr loc x1 x2 -> let loc = floc loc in CrCtr loc (reloc_ctyp floc sh x1) (reloc_ctyp floc sh x2) | CrDcl loc x1 -> let loc = floc loc in CrDcl loc (vala_map (List.map self) x1) | CrInh loc x1 x2 -> let loc = floc loc in CrInh loc (reloc_class_expr floc sh x1) x2 | CrIni loc x1 -> let loc = floc loc in CrIni loc (reloc_expr floc sh x1) | CrMth loc x1 x2 x3 x4 x5 -> let loc = floc loc in CrMth loc x1 x2 x3 (vala_map (option_map (reloc_ctyp floc sh)) x4) (reloc_expr floc sh x5) | CrVal loc x1 x2 x3 x4 -> let loc = floc loc in CrVal loc x1 x2 x3 (reloc_expr floc sh x4) | CrVav loc x1 x2 x3 -> let loc = floc loc in CrVav loc x1 x2 (reloc_ctyp floc sh x3) | CrVir loc x1 x2 x3 -> let loc = floc loc in CrVir loc x1 x2 (reloc_ctyp floc sh x3) ] ; value eq_expr x y = reloc_expr (fun _ -> Ploc.dummy) 0 x = reloc_expr (fun _ -> Ploc.dummy) 0 y ; value eq_patt x y = reloc_patt (fun _ -> Ploc.dummy) 0 x = reloc_patt (fun _ -> Ploc.dummy) 0 y ; value eq_ctyp x y = reloc_ctyp (fun _ -> Ploc.dummy) 0 x = reloc_ctyp (fun _ -> Ploc.dummy) 0 y ; value eq_str_item x y = reloc_str_item (fun _ -> Ploc.dummy) 0 x = reloc_str_item (fun _ -> Ploc.dummy) 0 y ; value eq_sig_item x y = reloc_sig_item (fun _ -> Ploc.dummy) 0 x = reloc_sig_item (fun _ -> Ploc.dummy) 0 y ; value eq_module_expr x y = reloc_module_expr (fun _ -> Ploc.dummy) 0 x = reloc_module_expr (fun _ -> Ploc.dummy) 0 y ; value eq_module_type x y = reloc_module_type (fun _ -> Ploc.dummy) 0 x = reloc_module_type (fun _ -> Ploc.dummy) 0 y ; value eq_class_sig_item x y = reloc_class_sig_item (fun _ -> Ploc.dummy) 0 x = reloc_class_sig_item (fun _ -> Ploc.dummy) 0 y ; value eq_class_str_item x y = reloc_class_str_item (fun _ -> Ploc.dummy) 0 x = reloc_class_str_item (fun _ -> Ploc.dummy) 0 y ; value eq_class_type x y = reloc_class_type (fun _ -> Ploc.dummy) 0 x = reloc_class_type (fun _ -> Ploc.dummy) 0 y ; value eq_class_expr x y = reloc_class_expr (fun _ -> Ploc.dummy) 0 x = reloc_class_expr (fun _ -> Ploc.dummy) 0 y ; $ I d : plexer.ml , v 6.11 2010 - 10 - 04 20:14:58 deraugla Exp $ Copyright ( c ) INRIA 2007 - 2010 #load "pa_lexer.cmo"; Added by as a backdoor to change lexical conventions . value jrh_lexer = ref False; open Versdep; value no_quotations = ref False; value error_on_unknown_keywords = ref False; value dollar_for_antiquotation = ref True; value specific_space_dot = ref False; value force_antiquot_loc = ref False; type context = { after_space : mutable bool; dollar_for_antiquotation : bool; specific_space_dot : bool; find_kwd : string -> string; line_cnt : int -> char -> unit; set_line_nb : unit -> unit; make_lined_loc : (int * int) -> string -> Ploc.t } ; value err ctx loc msg = Ploc.raise (ctx.make_lined_loc loc "") (Plexing.Error msg) ; 's hack to make the case distinction " unmixed " versus " mixed " value is_uppercase s = String.uppercase s = s; value is_only_lowercase s = String.lowercase s = s && not(is_uppercase s); value jrh_identifier find_kwd id = let jflag = jrh_lexer.val in if id = "set_jrh_lexer" then (let _ = jrh_lexer.val := True in ("",find_kwd "true")) else if id = "unset_jrh_lexer" then (let _ = jrh_lexer.val := False in ("",find_kwd "false")) else try ("", find_kwd id) with [ Not_found -> if not(jflag) then if is_uppercase (String.sub id 0 1) then ("UIDENT", id) else ("LIDENT", id) else if is_uppercase (String.sub id 0 1) && is_only_lowercase (String.sub id 1 (String.length id - 1)) * * * * : 's alternative version then ( " UIDENT " , i d ) else if is_uppercase ( String.sub i d 0 1 ) then ( " " , " _ _ uc_"^id ) else ( " " , i d ) ] ; * * * * then ("UIDENT", id) else if is_uppercase (String.sub id 0 1) then ("LIDENT", "__uc_"^id) else ("LIDENT", id)]; *****) then ("UIDENT", id) else ("LIDENT", id)]; value keyword_or_error ctx loc s = try ("", ctx.find_kwd s) with [ Not_found -> if error_on_unknown_keywords.val then err ctx loc ("illegal token: " ^ s) else ("", s) ] ; value stream_peek_nth n strm = loop n (Stream.npeek n strm) where rec loop n = fun [ [] -> None | [x] -> if n == 1 then Some x else None | [_ :: l] -> loop (n - 1) l ] ; value utf8_lexing = ref False; value misc_letter buf strm = if utf8_lexing.val then match strm with lexer [ '\128'-'\225' | '\227'-'\255' ] else match strm with lexer [ '\128'-'\255' ] ; value misc_punct buf strm = if utf8_lexing.val then match strm with lexer [ '\226' _ _ ] else match strm with parser [] ; value rec ident = lexer [ [ 'A'-'Z' | 'a'-'z' | '0'-'9' | '_' | ''' | misc_letter ] ident! | ] ; value rec ident2 = lexer [ [ '!' | '?' | '~' | '=' | '@' | '^' | '&' | '+' | '-' | '*' | '/' | '%' | '.' | ':' | '<' | '>' | '|' | '$' | misc_punct ] ident2! | ] ; value rec ident3 = lexer [ [ '0'-'9' | 'A'-'Z' | 'a'-'z' | '_' | '!' | '%' | '&' | '*' | '+' | '-' | '.' | '/' | ':' | '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' | ''' | '$' | '\128'-'\255' ] ident3! | ] ; value binary = lexer [ '0' | '1' ]; value octal = lexer [ '0'-'7' ]; value decimal = lexer [ '0'-'9' ]; value hexa = lexer [ '0'-'9' | 'a'-'f' | 'A'-'F' ]; value end_integer = lexer [ "l"/ -> ("INT_l", $buf) | "L"/ -> ("INT_L", $buf) | "n"/ -> ("INT_n", $buf) | -> ("INT", $buf) ] ; value rec digits_under kind = lexer [ kind (digits_under kind)! | "_" (digits_under kind)! | end_integer ] ; value digits kind = lexer [ kind (digits_under kind)! | -> raise (Stream.Error "ill-formed integer constant") ] ; value rec decimal_digits_under = lexer [ [ '0'-'9' | '_' ] decimal_digits_under! | ] ; value exponent_part = lexer [ [ 'e' | 'E' ] [ '+' | '-' | ] '0'-'9' ? "ill-formed floating-point constant" decimal_digits_under! ] ; value number = lexer [ decimal_digits_under "." decimal_digits_under! exponent_part -> ("FLOAT", $buf) | decimal_digits_under "." decimal_digits_under! -> ("FLOAT", $buf) | decimal_digits_under exponent_part -> ("FLOAT", $buf) | decimal_digits_under end_integer! ] ; value char_after_bslash = lexer [ "'"/ | _ [ "'"/ | _ [ "'"/ | ] ] ] ; value char ctx bp = lexer [ "\\" _ char_after_bslash! | "\\" -> err ctx (bp, $pos) "char not terminated" | ?= [ _ '''] _! "'"/ ] ; value any ctx buf = parser bp [: `c :] -> do { ctx.line_cnt bp c; $add c } ; value rec string ctx bp = lexer [ "\""/ | "\\" (any ctx) (string ctx bp)! | (any ctx) (string ctx bp)! | -> err ctx (bp, $pos) "string not terminated" ] ; value rec qstring ctx bp = lexer [ "`"/ | (any ctx) (qstring ctx bp)! | -> err ctx (bp, $pos) "quotation not terminated" ] ; value comment ctx bp = comment where rec comment = lexer [ "*)" | "*" comment! | "(*" comment! comment! | "(" comment! | "\"" (string ctx bp)! [ -> $add "\"" ] comment! | "'*)" | "'*" comment! | "'" (any ctx) comment! | (any ctx) comment! | -> err ctx (bp, $pos) "comment not terminated" ] ; value rec quotation ctx bp = lexer [ ">>"/ | ">" (quotation ctx bp)! | "<<" (quotation ctx bp)! [ -> $add ">>" ]! (quotation ctx bp)! | "<:" ident! "<" (quotation ctx bp)! [ -> $add ">>" ]! (quotation ctx bp)! | "<:" ident! (quotation ctx bp)! | "<" (quotation ctx bp)! | "\\"/ [ '>' | '<' | '\\' ] (quotation ctx bp)! | "\\" (quotation ctx bp)! | (any ctx) (quotation ctx bp)! | -> err ctx (bp, $pos) "quotation not terminated" ] ; value less_expected = "character '<' expected"; value less ctx bp buf strm = if no_quotations.val then match strm with lexer [ [ -> $add "<" ] ident2! -> keyword_or_error ctx (bp, $pos) $buf ] else match strm with lexer [ "<"/ (quotation ctx bp) -> ("QUOTATION", ":" ^ $buf) | ":"/ ident! "<"/ ? less_expected [ -> $add ":" ]! (quotation ctx bp) -> ("QUOTATION", $buf) | ":"/ ident! ":<"/ ? less_expected [ -> $add "@" ]! (quotation ctx bp) -> ("QUOTATION", $buf) | [ -> $add "<" ] ident2! -> keyword_or_error ctx (bp, $pos) $buf ] ; value rec antiquot_rest ctx bp = lexer [ "$"/ | "\\"/ (any ctx) (antiquot_rest ctx bp)! | (any ctx) (antiquot_rest ctx bp)! | -> err ctx (bp, $pos) "antiquotation not terminated" ] ; value rec antiquot ctx bp = lexer [ "$"/ -> ":" ^ $buf | [ 'a'-'z' | 'A'-'Z' | '0'-'9' | '!' | '_' ] (antiquot ctx bp)! | ":" (antiquot_rest ctx bp)! -> $buf | "\\"/ (any ctx) (antiquot_rest ctx bp)! -> ":" ^ $buf | (any ctx) (antiquot_rest ctx bp)! -> ":" ^ $buf | -> err ctx (bp, $pos) "antiquotation not terminated" ] ; value antiloc bp ep s = Printf.sprintf "%d,%d:%s" bp ep s; value rec antiquot_loc ctx bp = lexer [ "$"/ -> antiloc bp $pos (":" ^ $buf) | [ 'a'-'z' | 'A'-'Z' | '0'-'9' | '!' | '_' ] (antiquot_loc ctx bp)! | ":" (antiquot_rest ctx bp)! -> antiloc bp $pos $buf | "\\"/ (any ctx) (antiquot_rest ctx bp)! -> antiloc bp $pos (":" ^ $buf) | (any ctx) (antiquot_rest ctx bp)! -> antiloc bp $pos (":" ^ $buf) | -> err ctx (bp, $pos) "antiquotation not terminated" ] ; value dollar ctx bp buf strm = if not no_quotations.val && ctx.dollar_for_antiquotation then ("ANTIQUOT", antiquot ctx bp buf strm) else if force_antiquot_loc.val then ("ANTIQUOT_LOC", antiquot_loc ctx bp buf strm) else match strm with lexer [ [ -> $add "$" ] ident2! -> ("", $buf) ] ; - specific case for QUESTIONIDENT and QUESTIONIDENTCOLON input expr patt ----- ---- ---- ? $ abc : d$ ? abc : d ? abc ? $ abc : d$ : ? abc : d : ? abc : ? ? : d ? ? : ? : d : ? : input expr patt ----- ---- ---- ?$abc:d$ ?abc:d ?abc ?$abc:d$: ?abc:d: ?abc: ?$d$ ?:d ? ?$d$: ?:d: ?: *) ANTIQUOT_LOC - specific case for QUESTIONIDENT and QUESTIONIDENTCOLON input expr patt ----- ---- ---- ? $ abc : d$ ? 8,13 : abc : d ? abc ? $ abc : d$ : ? 8,13 : abc : d : ? abc : ? ? 8,9::d ? ? : ? 8,9::d : ? : input expr patt ----- ---- ---- ?$abc:d$ ?8,13:abc:d ?abc ?$abc:d$: ?8,13:abc:d: ?abc: ?$d$ ?8,9::d ? ?$d$: ?8,9::d: ?: *) value question ctx bp buf strm = if ctx.dollar_for_antiquotation then match strm with parser [ [: `'$'; s = antiquot ctx bp $empty; `':' :] -> ("ANTIQUOT", "?" ^ s ^ ":") | [: `'$'; s = antiquot ctx bp $empty :] -> ("ANTIQUOT", "?" ^ s) | [: :] -> match strm with lexer [ ident2! -> keyword_or_error ctx (bp, $pos) $buf ] ] else if force_antiquot_loc.val then match strm with parser [ [: `'$'; s = antiquot_loc ctx bp $empty; `':' :] -> ("ANTIQUOT_LOC", "?" ^ s ^ ":") | [: `'$'; s = antiquot_loc ctx bp $empty :] -> ("ANTIQUOT_LOC", "?" ^ s) | [: :] -> match strm with lexer [ ident2! -> keyword_or_error ctx (bp, $pos) $buf ] ] else match strm with lexer [ ident2! -> keyword_or_error ctx (bp, $pos) $buf ] ; value tilde ctx bp buf strm = if ctx.dollar_for_antiquotation then match strm with parser [ [: `'$'; s = antiquot ctx bp $empty; `':' :] -> ("ANTIQUOT", "~" ^ s ^ ":") | [: `'$'; s = antiquot ctx bp $empty :] -> ("ANTIQUOT", "~" ^ s) | [: :] -> match strm with lexer [ ident2! -> keyword_or_error ctx (bp, $pos) $buf ] ] else if force_antiquot_loc.val then match strm with parser [ [: `'$'; s = antiquot_loc ctx bp $empty; `':' :] -> ("ANTIQUOT_LOC", "~" ^ s ^ ":") | [: `'$'; s = antiquot_loc ctx bp $empty :] -> ("ANTIQUOT_LOC", "~" ^ s) | [: :] -> match strm with lexer [ ident2! -> keyword_or_error ctx (bp, $pos) $buf ] ] else match strm with lexer [ ident2! -> keyword_or_error ctx (bp, $pos) $buf ] ; value tildeident = lexer [ ":"/ -> ("TILDEIDENTCOLON", $buf) | -> ("TILDEIDENT", $buf) ] ; value questionident = lexer [ ":"/ -> ("QUESTIONIDENTCOLON", $buf) | -> ("QUESTIONIDENT", $buf) ] ; value rec linedir n s = match stream_peek_nth n s with [ Some (' ' | '\t') -> linedir (n + 1) s | Some ('0'..'9') -> linedir_digits (n + 1) s | _ -> False ] and linedir_digits n s = match stream_peek_nth n s with [ Some ('0'..'9') -> linedir_digits (n + 1) s | _ -> linedir_quote n s ] and linedir_quote n s = match stream_peek_nth n s with [ Some (' ' | '\t') -> linedir_quote (n + 1) s | Some '"' -> True | _ -> False ] ; value rec any_to_nl = lexer [ "\r" | "\n" | _ any_to_nl! | ] ; value next_token_after_spaces ctx bp = lexer [ 'A'-'Z' ident! -> let id = $buf in jrh_identifier ctx.find_kwd id * * * * * * * * * : original was try ( " " , ctx.find_kwd i d ) with [ Not_found - > ( " UIDENT " , i d ) ] * * * * * * * * try ("", ctx.find_kwd id) with [ Not_found -> ("UIDENT", id) ] *********) | [ 'a'-'z' | '_' | misc_letter ] ident! -> let id = $buf in jrh_identifier ctx.find_kwd id * * * * * * * * * : original was try ( " " , ctx.find_kwd i d ) with [ Not_found - > ( " " , i d ) ] * * * * * * * * try ("", ctx.find_kwd id) with [ Not_found -> ("LIDENT", id) ] *********) | '1'-'9' number! | "0" [ 'o' | 'O' ] (digits octal)! | "0" [ 'x' | 'X' ] (digits hexa)! | "0" [ 'b' | 'B' ] (digits binary)! | "0" number! | "'"/ ?= [ '\\' 'a'-'z' 'a'-'z' ] -> keyword_or_error ctx (bp, $pos) "'" | "'"/ (char ctx bp) -> ("CHAR", $buf) | "'" -> keyword_or_error ctx (bp, $pos) "'" | "\""/ (string ctx bp)! -> ("STRING", $buf) * * Line added by * * | "`"/ (qstring ctx bp)! -> ("QUOTATION", "tot:" ^ $buf) | "$"/ (dollar ctx bp)! | [ '!' | '=' | '@' | '^' | '&' | '+' | '-' | '*' | '/' | '%' ] ident2! -> keyword_or_error ctx (bp, $pos) $buf | "~"/ 'a'-'z' ident! tildeident! | "~"/ '_' ident! tildeident! | "~" (tilde ctx bp) | "?"/ 'a'-'z' ident! questionident! | "?" (question ctx bp)! | "<"/ (less ctx bp)! | ":]" -> keyword_or_error ctx (bp, $pos) $buf | "::" -> keyword_or_error ctx (bp, $pos) $buf | ":=" -> keyword_or_error ctx (bp, $pos) $buf | ":>" -> keyword_or_error ctx (bp, $pos) $buf | ":" -> keyword_or_error ctx (bp, $pos) $buf | ">]" -> keyword_or_error ctx (bp, $pos) $buf | ">}" -> keyword_or_error ctx (bp, $pos) $buf | ">" ident2! -> keyword_or_error ctx (bp, $pos) $buf | "|]" -> keyword_or_error ctx (bp, $pos) $buf | "|}" -> keyword_or_error ctx (bp, $pos) $buf | "|" ident2! -> keyword_or_error ctx (bp, $pos) $buf | "[" ?= [ "<<" | "<:" ] -> keyword_or_error ctx (bp, $pos) $buf | "[|" -> keyword_or_error ctx (bp, $pos) $buf | "[<" -> keyword_or_error ctx (bp, $pos) $buf | "[:" -> keyword_or_error ctx (bp, $pos) $buf | "[" -> keyword_or_error ctx (bp, $pos) $buf | "{" ?= [ "<<" | "<:" ] -> keyword_or_error ctx (bp, $pos) $buf | "{|" -> keyword_or_error ctx (bp, $pos) $buf | "{<" -> keyword_or_error ctx (bp, $pos) $buf | "{:" -> keyword_or_error ctx (bp, $pos) $buf | "{" -> keyword_or_error ctx (bp, $pos) $buf | ".." -> keyword_or_error ctx (bp, $pos) ".." | "." -> let id = if ctx.specific_space_dot && ctx.after_space then " ." else "." in keyword_or_error ctx (bp, $pos) id | ";;" -> keyword_or_error ctx (bp, $pos) ";;" | ";" -> keyword_or_error ctx (bp, $pos) ";" | misc_punct ident2! -> keyword_or_error ctx (bp, $pos) $buf | "\\"/ ident3! -> ("LIDENT", $buf) | (any ctx) -> keyword_or_error ctx (bp, $pos) $buf ] ; value get_comment buf strm = $buf; value rec next_token ctx buf = parser bp [ [: `('\n' | '\r' as c); s :] ep -> do { if c = '\n' then incr Plexing.line_nb.val else (); Plexing.bol_pos.val.val := ep; ctx.set_line_nb (); ctx.after_space := True; next_token ctx ($add c) s } | [: `(' ' | '\t' | '\026' | '\012' as c); s :] -> do { ctx.after_space := True; next_token ctx ($add c) s } | [: `'#' when bp = Plexing.bol_pos.val.val; s :] -> let comm = get_comment buf () in if linedir 1 s then do { let buf = any_to_nl ($add '#') s in incr Plexing.line_nb.val; Plexing.bol_pos.val.val := Stream.count s; ctx.set_line_nb (); ctx.after_space := True; next_token ctx buf s } else let loc = ctx.make_lined_loc (bp, bp + 1) comm in (keyword_or_error ctx (bp, bp + 1) "#", loc) | [: `'('; a = parser [ [: `'*'; buf = comment ctx bp ($add "(*") !; s :] -> do { ctx.set_line_nb (); ctx.after_space := True; next_token ctx buf s } | [: :] ep -> let loc = ctx.make_lined_loc (bp, ep) $buf in (keyword_or_error ctx (bp, ep) "(", loc) ] ! :] -> a | [: comm = get_comment buf; tok = next_token_after_spaces ctx bp $empty :] ep -> let loc = ctx.make_lined_loc (bp, max (bp + 1) ep) comm in (tok, loc) | [: comm = get_comment buf; _ = Stream.empty :] -> let loc = ctx.make_lined_loc (bp, bp + 1) comm in (("EOI", ""), loc) ] ; value next_token_fun ctx glexr (cstrm, s_line_nb, s_bol_pos) = try do { match Plexing.restore_lexing_info.val with [ Some (line_nb, bol_pos) -> do { s_line_nb.val := line_nb; s_bol_pos.val := bol_pos; Plexing.restore_lexing_info.val := None; } | None -> () ]; Plexing.line_nb.val := s_line_nb; Plexing.bol_pos.val := s_bol_pos; let comm_bp = Stream.count cstrm in ctx.set_line_nb (); ctx.after_space := False; let (r, loc) = next_token ctx $empty cstrm in match glexr.val.Plexing.tok_comm with [ Some list -> if Ploc.first_pos loc > comm_bp then let comm_loc = Ploc.make_unlined (comm_bp, Ploc.last_pos loc) in glexr.val.Plexing.tok_comm := Some [comm_loc :: list] else () | None -> () ]; (r, loc) } with [ Stream.Error str -> err ctx (Stream.count cstrm, Stream.count cstrm + 1) str ] ; value func kwd_table glexr = let ctx = let line_nb = ref 0 in let bol_pos = ref 0 in {after_space = False; dollar_for_antiquotation = dollar_for_antiquotation.val; specific_space_dot = specific_space_dot.val; find_kwd = Hashtbl.find kwd_table; line_cnt bp1 c = match c with [ '\n' | '\r' -> do { if c = '\n' then incr Plexing.line_nb.val else (); Plexing.bol_pos.val.val := bp1 + 1; } | c -> () ]; set_line_nb () = do { line_nb.val := Plexing.line_nb.val.val; bol_pos.val := Plexing.bol_pos.val.val; }; make_lined_loc loc comm = Ploc.make_loc Plexing.input_file.val line_nb.val bol_pos.val loc comm} in Plexing.lexer_func_of_parser (next_token_fun ctx glexr) ; value rec check_keyword_stream = parser [: _ = check $empty; _ = Stream.empty :] -> True and check = lexer [ [ 'A'-'Z' | 'a'-'z' | misc_letter ] check_ident! | [ '!' | '?' | '~' | '=' | '@' | '^' | '&' | '+' | '-' | '*' | '/' | '%' | '.' ] check_ident2! | "$" check_ident2! | "<" ?= [ ":" | "<" ] | "<" check_ident2! | ":]" | "::" | ":=" | ":>" | ":" | ">]" | ">}" | ">" check_ident2! | "|]" | "|}" | "|" check_ident2! | "[" ?= [ "<<" | "<:" ] | "[|" | "[<" | "[:" | "[" | "{" ?= [ "<<" | "<:" ] | "{|" | "{<" | "{:" | "{" | ";;" | ";" | misc_punct check_ident2! | _ ] and check_ident = lexer [ [ 'A'-'Z' | 'a'-'z' | '0'-'9' | '_' | ''' | misc_letter ] check_ident! | ] and check_ident2 = lexer [ [ '!' | '?' | '~' | '=' | '@' | '^' | '&' | '+' | '-' | '*' | '/' | '%' | '.' | ':' | '<' | '>' | '|' | misc_punct ] check_ident2! | ] ; value check_keyword s = try check_keyword_stream (Stream.of_string s) with _ -> False ; value error_no_respect_rules p_con p_prm = raise (Plexing.Error ("the token " ^ (if p_con = "" then "\"" ^ p_prm ^ "\"" else if p_prm = "" then p_con else p_con ^ " \"" ^ p_prm ^ "\"") ^ " does not respect Plexer rules")) ; value error_ident_and_keyword p_con p_prm = raise (Plexing.Error ("the token \"" ^ p_prm ^ "\" is used as " ^ p_con ^ " and as keyword")) ; value using_token kwd_table ident_table (p_con, p_prm) = match p_con with [ "" -> if not (hashtbl_mem kwd_table p_prm) then if check_keyword p_prm then if hashtbl_mem ident_table p_prm then error_ident_and_keyword (Hashtbl.find ident_table p_prm) p_prm else Hashtbl.add kwd_table p_prm p_prm else error_no_respect_rules p_con p_prm else () | "LIDENT" -> if p_prm = "" then () else match p_prm.[0] with [ 'A'..'Z' -> error_no_respect_rules p_con p_prm | _ -> if hashtbl_mem kwd_table p_prm then error_ident_and_keyword p_con p_prm else Hashtbl.add ident_table p_prm p_con ] | "UIDENT" -> if p_prm = "" then () else match p_prm.[0] with [ 'a'..'z' -> error_no_respect_rules p_con p_prm | _ -> if hashtbl_mem kwd_table p_prm then error_ident_and_keyword p_con p_prm else Hashtbl.add ident_table p_prm p_con ] | "TILDEIDENT" | "TILDEIDENTCOLON" | "QUESTIONIDENT" | "QUESTIONIDENTCOLON" | "INT" | "INT_l" | "INT_L" | "INT_n" | "FLOAT" | "CHAR" | "STRING" | "QUOTATION" | "ANTIQUOT" | "ANTIQUOT_LOC" | "EOI" -> () | _ -> raise (Plexing.Error ("the constructor \"" ^ p_con ^ "\" is not recognized by Plexer")) ] ; value removing_token kwd_table ident_table (p_con, p_prm) = match p_con with [ "" -> Hashtbl.remove kwd_table p_prm | "LIDENT" | "UIDENT" -> if p_prm <> "" then Hashtbl.remove ident_table p_prm else () | _ -> () ] ; value text = fun [ ("", t) -> "'" ^ t ^ "'" | ("LIDENT", "") -> "lowercase identifier" | ("LIDENT", t) -> "'" ^ t ^ "'" | ("UIDENT", "") -> "uppercase identifier" | ("UIDENT", t) -> "'" ^ t ^ "'" | ("INT", "") -> "integer" | ("INT", s) -> "'" ^ s ^ "'" | ("FLOAT", "") -> "float" | ("STRING", "") -> "string" | ("CHAR", "") -> "char" | ("QUOTATION", "") -> "quotation" | ("ANTIQUOT", k) -> "antiquot \"" ^ k ^ "\"" | ("EOI", "") -> "end of input" | (con, "") -> con | (con, prm) -> con ^ " \"" ^ prm ^ "\"" ] ; value eq_before_colon p e = loop 0 where rec loop i = if i == String.length e then failwith "Internal error in Plexer: incorrect ANTIQUOT" else if i == String.length p then e.[i] == ':' else if p.[i] == e.[i] then loop (i + 1) else False ; value after_colon e = try let i = String.index e ':' in String.sub e (i + 1) (String.length e - i - 1) with [ Not_found -> "" ] ; value after_colon_except_last e = try let i = String.index e ':' in String.sub e (i + 1) (String.length e - i - 2) with [ Not_found -> "" ] ; value tok_match = fun [ ("ANTIQUOT", p_prm) -> if p_prm <> "" && (p_prm.[0] = '~' || p_prm.[0] = '?') then if p_prm.[String.length p_prm - 1] = ':' then let p_prm = String.sub p_prm 0 (String.length p_prm - 1) in fun [ ("ANTIQUOT", prm) -> if prm <> "" && prm.[String.length prm - 1] = ':' then if eq_before_colon p_prm prm then after_colon_except_last prm else raise Stream.Failure else raise Stream.Failure | _ -> raise Stream.Failure ] else fun [ ("ANTIQUOT", prm) -> if prm <> "" && prm.[String.length prm - 1] = ':' then raise Stream.Failure else if eq_before_colon p_prm prm then after_colon prm else raise Stream.Failure | _ -> raise Stream.Failure ] else fun [ ("ANTIQUOT", prm) when eq_before_colon p_prm prm -> after_colon prm | _ -> raise Stream.Failure ] | tok -> Plexing.default_match tok ] ; value gmake () = let kwd_table = Hashtbl.create 301 in let id_table = Hashtbl.create 301 in let glexr = ref {Plexing.tok_func = fun []; tok_using = fun []; tok_removing = fun []; tok_match = fun []; tok_text = fun []; tok_comm = None} in let glex = {Plexing.tok_func = func kwd_table glexr; tok_using = using_token kwd_table id_table; tok_removing = removing_token kwd_table id_table; tok_match = tok_match; tok_text = text; tok_comm = None} in do { glexr.val := glex; glex } ; do { let odfa = dollar_for_antiquotation.val in dollar_for_antiquotation.val := False; Grammar.Unsafe.gram_reinit gram (gmake ()); dollar_for_antiquotation.val := odfa; Grammar.Unsafe.clear_entry interf; Grammar.Unsafe.clear_entry implem; Grammar.Unsafe.clear_entry top_phrase; Grammar.Unsafe.clear_entry use_file; Grammar.Unsafe.clear_entry module_type; Grammar.Unsafe.clear_entry module_expr; Grammar.Unsafe.clear_entry sig_item; Grammar.Unsafe.clear_entry str_item; Grammar.Unsafe.clear_entry signature; Grammar.Unsafe.clear_entry structure; Grammar.Unsafe.clear_entry expr; Grammar.Unsafe.clear_entry patt; Grammar.Unsafe.clear_entry ctyp; Grammar.Unsafe.clear_entry let_binding; Grammar.Unsafe.clear_entry type_decl; Grammar.Unsafe.clear_entry constructor_declaration; Grammar.Unsafe.clear_entry label_declaration; Grammar.Unsafe.clear_entry match_case; Grammar.Unsafe.clear_entry with_constr; Grammar.Unsafe.clear_entry poly_variant; Grammar.Unsafe.clear_entry class_type; Grammar.Unsafe.clear_entry class_expr; Grammar.Unsafe.clear_entry class_sig_item; Grammar.Unsafe.clear_entry class_str_item }; Pcaml.parse_interf.val := Grammar.Entry.parse interf; Pcaml.parse_implem.val := Grammar.Entry.parse implem; value mklistexp loc last = loop True where rec loop top = fun [ [] -> match last with [ Some e -> e | None -> <:expr< [] >> ] | [e1 :: el] -> let loc = if top then loc else Ploc.encl (MLast.loc_of_expr e1) loc in <:expr< [$e1$ :: $loop False el$] >> ] ; value mklistpat loc last = loop True where rec loop top = fun [ [] -> match last with [ Some p -> p | None -> <:patt< [] >> ] | [p1 :: pl] -> let loc = if top then loc else Ploc.encl (MLast.loc_of_patt p1) loc in <:patt< [$p1$ :: $loop False pl$] >> ] ; * * pulled this outside so user can add new infixes here too * * value ht = Hashtbl.create 73; * * And added all the new HOL Light infixes here already * * value is_operator = do { let ct = Hashtbl.create 73 in List.iter (fun x -> Hashtbl.add ht x True) ["asr"; "land"; "lor"; "lsl"; "lsr"; "lxor"; "mod"; "or"; "o"; "upto"; "F_F"; "THENC"; "THEN"; "THENL"; "ORELSE"; "ORELSEC"; "THEN_TCL"; "ORELSE_TCL"]; List.iter (fun x -> Hashtbl.add ct x True) ['!'; '&'; '*'; '+'; '-'; '/'; ':'; '<'; '='; '>'; '@'; '^'; '|'; '~'; '?'; '%'; '.'; '$']; fun x -> try Hashtbl.find ht x with [ Not_found -> try Hashtbl.find ct x.[0] with _ -> False ] }; * * added this so parenthesised operators undergo same mapping * * value translate_operator = fun s -> match s with [ "THEN" -> "then_" | "THENC" -> "thenc_" | "THENL" -> "thenl_" | "ORELSE" -> "orelse_" | "ORELSEC" -> "orelsec_" | "THEN_TCL" -> "then_tcl_" | "ORELSE_TCL" -> "orelse_tcl_" | "F_F" -> "f_f_" | _ -> s]; value operator_rparen = Grammar.Entry.of_parser gram "operator_rparen" (fun strm -> match Stream.npeek 2 strm with [ [("", s); ("", ")")] when is_operator s -> do { Stream.junk strm; Stream.junk strm; translate_operator s } | _ -> raise Stream.Failure ]) ; value check_not_part_of_patt = Grammar.Entry.of_parser gram "check_not_part_of_patt" (fun strm -> let tok = match Stream.npeek 4 strm with [ [("LIDENT", _); tok :: _] -> tok | [("", "("); ("", s); ("", ")"); tok] when is_operator s -> tok | _ -> raise Stream.Failure ] in match tok with [ ("", "," | "as" | "|" | "::") -> raise Stream.Failure | _ -> () ]) ; value symbolchar = let list = ['!'; '$'; '%'; '&'; '*'; '+'; '-'; '.'; '/'; ':'; '<'; '='; '>'; '?'; '@'; '^'; '|'; '~'] in loop where rec loop s i = if i == String.length s then True else if List.mem s.[i] list then loop s (i + 1) else False ; value prefixop = let list = ['!'; '?'; '~'] in let excl = ["!="; "??"; "?!"] in Grammar.Entry.of_parser gram "prefixop" (parser [: `("", x) when not (List.mem x excl) && String.length x >= 2 && List.mem x.[0] list && symbolchar x 1 :] -> x) ; value infixop0 = let list = ['='; '<'; '>'; '|'; '&'; '$'] in let excl = ["<-"; "||"; "&&"] in Grammar.Entry.of_parser gram "infixop0" (parser [: `("", x) when not (List.mem x excl) && (x = "$" || String.length x >= 2) && List.mem x.[0] list && symbolchar x 1 :] -> x) ; value infixop1 = let list = ['@'; '^'] in Grammar.Entry.of_parser gram "infixop1" (parser [: `("", x) when String.length x >= 2 && List.mem x.[0] list && symbolchar x 1 :] -> x) ; value infixop2 = let list = ['+'; '-'] in Grammar.Entry.of_parser gram "infixop2" (parser [: `("", x) when x <> "->" && String.length x >= 2 && List.mem x.[0] list && symbolchar x 1 :] -> x) ; value infixop3 = let list = ['*'; '/'; '%'] in Grammar.Entry.of_parser gram "infixop3" (parser [: `("", x) when String.length x >= 2 && List.mem x.[0] list && symbolchar x 1 :] -> x) ; value infixop4 = Grammar.Entry.of_parser gram "infixop4" (parser [: `("", x) when String.length x >= 3 && x.[0] == '*' && x.[1] == '*' && symbolchar x 2 :] -> x) ; value test_constr_decl = Grammar.Entry.of_parser gram "test_constr_decl" (fun strm -> match Stream.npeek 1 strm with [ [("UIDENT", _)] -> match Stream.npeek 2 strm with [ [_; ("", ".")] -> raise Stream.Failure | [_; ("", "(")] -> raise Stream.Failure | [_ :: _] -> () | _ -> raise Stream.Failure ] | [("", "|")] -> () | _ -> raise Stream.Failure ]) ; value stream_peek_nth n strm = loop n (Stream.npeek n strm) where rec loop n = fun [ [] -> None | [x] -> if n == 1 then Some x else None | [_ :: l] -> loop (n - 1) l ] ; horrible hack to be able to parse value test_ctyp_minusgreater = Grammar.Entry.of_parser gram "test_ctyp_minusgreater" (fun strm -> let rec skip_simple_ctyp n = match stream_peek_nth n strm with [ Some ("", "->") -> n | Some ("", "[" | "[<") -> skip_simple_ctyp (ignore_upto "]" (n + 1) + 1) | Some ("", "(") -> skip_simple_ctyp (ignore_upto ")" (n + 1) + 1) | Some ("", "as" | "'" | ":" | "*" | "." | "#" | "<" | ">" | ".." | ";" | "_") -> skip_simple_ctyp (n + 1) | Some ("QUESTIONIDENT" | "LIDENT" | "UIDENT", _) -> skip_simple_ctyp (n + 1) | Some _ | None -> raise Stream.Failure ] and ignore_upto end_kwd n = match stream_peek_nth n strm with [ Some ("", prm) when prm = end_kwd -> n | Some ("", "[" | "[<") -> ignore_upto end_kwd (ignore_upto "]" (n + 1) + 1) | Some ("", "(") -> ignore_upto end_kwd (ignore_upto ")" (n + 1) + 1) | Some _ -> ignore_upto end_kwd (n + 1) | None -> raise Stream.Failure ] in match Stream.peek strm with [ Some (("", "[") | ("LIDENT" | "UIDENT", _)) -> skip_simple_ctyp 1 | Some ("", "object") -> raise Stream.Failure | _ -> 1 ]) ; value test_label_eq = Grammar.Entry.of_parser gram "test_label_eq" (test 1 where rec test lev strm = match stream_peek_nth lev strm with [ Some (("UIDENT", _) | ("LIDENT", _) | ("", ".")) -> test (lev + 1) strm | Some ("ANTIQUOT_LOC", _) -> () | Some ("", "=") -> () | _ -> raise Stream.Failure ]) ; value test_typevar_list_dot = Grammar.Entry.of_parser gram "test_typevar_list_dot" (let rec test lev strm = match stream_peek_nth lev strm with [ Some ("", "'") -> test2 (lev + 1) strm | Some ("", ".") -> () | _ -> raise Stream.Failure ] and test2 lev strm = match stream_peek_nth lev strm with [ Some ("UIDENT" | "LIDENT", _) -> test (lev + 1) strm | _ -> raise Stream.Failure ] in test 1) ; value e_phony = Grammar.Entry.of_parser gram "e_phony" (parser []) ; value p_phony = Grammar.Entry.of_parser gram "p_phony" (parser []) ; value constr_arity = ref [("Some", 1); ("Match_Failure", 1)]; value rec is_expr_constr_call = fun [ <:expr< $uid:_$ >> -> True | <:expr< $uid:_$.$e$ >> -> is_expr_constr_call e | <:expr< $e$ $_$ >> -> is_expr_constr_call e | _ -> False ] ; value rec constr_expr_arity loc = fun [ <:expr< $uid:c$ >> -> try List.assoc c constr_arity.val with [ Not_found -> 0 ] | <:expr< $uid:_$.$e$ >> -> constr_expr_arity loc e | _ -> 1 ] ; value rec constr_patt_arity loc = fun [ <:patt< $uid:c$ >> -> try List.assoc c constr_arity.val with [ Not_found -> 0 ] | <:patt< $uid:_$.$p$ >> -> constr_patt_arity loc p | _ -> 1 ] ; value get_seq = fun [ <:expr< do { $list:el$ } >> -> el | e -> [e] ] ; value mem_tvar s tpl = List.exists (fun (t, _) -> Pcaml.unvala t = Some s) tpl ; value choose_tvar tpl = let rec find_alpha v = let s = String.make 1 v in if mem_tvar s tpl then if v = 'z' then None else find_alpha (Char.chr (Char.code v + 1)) else Some (String.make 1 v) in let rec make_n n = let v = "a" ^ string_of_int n in if mem_tvar v tpl then make_n (succ n) else v in match find_alpha 'a' with [ Some x -> x | None -> make_n 1 ] ; value quotation_content s = do { loop 0 where rec loop i = if i = String.length s then ("", s) else if s.[i] = ':' || s.[i] = '@' then let i = i + 1 in (String.sub s 0 i, String.sub s i (String.length s - i)) else loop (i + 1) }; value concat_comm loc e = let loc = Ploc.with_comment loc (Ploc.comment loc ^ Ploc.comment (MLast.loc_of_expr e)) in let floc = let first = ref True in fun loc1 -> if first.val then do {first.val := False; loc} else loc1 in reloc_expr floc 0 e ; EXTEND GLOBAL: sig_item str_item ctyp patt expr module_type module_expr signature structure class_type class_expr class_sig_item class_str_item let_binding type_decl constructor_declaration label_declaration match_case with_constr poly_variant; module_expr: [ [ "functor"; "("; i = V UIDENT "uid" ""; ":"; t = module_type; ")"; "->"; me = SELF -> <:module_expr< functor ( $_uid:i$ : $t$ ) -> $me$ >> | "struct"; st = structure; "end" -> <:module_expr< struct $_list:st$ end >> ] | [ me1 = SELF; "."; me2 = SELF -> <:module_expr< $me1$ . $me2$ >> ] | [ me1 = SELF; "("; me2 = SELF; ")" -> <:module_expr< $me1$ $me2$ >> ] | [ i = mod_expr_ident -> i | "("; "val"; e = expr; ":"; mt = module_type; ")" -> <:module_expr< (value $e$ : $mt$) >> | "("; "val"; e = expr; ")" -> <:module_expr< (value $e$) >> | "("; me = SELF; ":"; mt = module_type; ")" -> <:module_expr< ( $me$ : $mt$ ) >> | "("; me = SELF; ")" -> <:module_expr< $me$ >> ] ] ; structure: [ [ st = V (LIST0 [ s = str_item; OPT ";;" -> s ]) -> st ] ] ; mod_expr_ident: [ LEFTA [ i = SELF; "."; j = SELF -> <:module_expr< $i$ . $j$ >> ] | [ i = V UIDENT -> <:module_expr< $_uid:i$ >> ] ] ; str_item: [ "top" [ "exception"; (_, c, tl, _) = constructor_declaration; b = rebind_exn -> <:str_item< exception $_uid:c$ of $_list:tl$ = $_list:b$ >> | "external"; i = V LIDENT "lid" ""; ":"; t = ctyp; "="; pd = V (LIST1 STRING) -> <:str_item< external $_lid:i$ : $t$ = $_list:pd$ >> | "external"; "("; i = operator_rparen; ":"; t = ctyp; "="; pd = V (LIST1 STRING) -> <:str_item< external $lid:i$ : $t$ = $_list:pd$ >> | "include"; me = module_expr -> <:str_item< include $me$ >> | "module"; r = V (FLAG "rec"); l = V (LIST1 mod_binding SEP "and") -> <:str_item< module $_flag:r$ $_list:l$ >> | "module"; "type"; i = V UIDENT "uid" ""; "="; mt = module_type -> <:str_item< module type $_uid:i$ = $mt$ >> | "open"; i = V mod_ident "list" "" -> <:str_item< open $_:i$ >> | "type"; tdl = V (LIST1 type_decl SEP "and") -> <:str_item< type $_list:tdl$ >> | "let"; r = V (FLAG "rec"); l = V (LIST1 let_binding SEP "and"); "in"; x = expr -> let e = <:expr< let $_flag:r$ $_list:l$ in $x$ >> in <:str_item< $exp:e$ >> | "let"; r = V (FLAG "rec"); l = V (LIST1 let_binding SEP "and") -> match l with [ <:vala< [(p, e)] >> -> match p with [ <:patt< _ >> -> <:str_item< $exp:e$ >> | _ -> <:str_item< value $_flag:r$ $_list:l$ >> ] | _ -> <:str_item< value $_flag:r$ $_list:l$ >> ] | "let"; "module"; m = V UIDENT; mb = mod_fun_binding; "in"; e = expr -> <:str_item< let module $_uid:m$ = $mb$ in $e$ >> | e = expr -> <:str_item< $exp:e$ >> ] ] ; rebind_exn: [ [ "="; sl = V mod_ident "list" -> sl | -> <:vala< [] >> ] ] ; mod_binding: [ [ i = V UIDENT; me = mod_fun_binding -> (i, me) ] ] ; mod_fun_binding: [ RIGHTA [ "("; m = UIDENT; ":"; mt = module_type; ")"; mb = SELF -> <:module_expr< functor ( $uid:m$ : $mt$ ) -> $mb$ >> | ":"; mt = module_type; "="; me = module_expr -> <:module_expr< ( $me$ : $mt$ ) >> | "="; me = module_expr -> <:module_expr< $me$ >> ] ] ; module_type: [ [ "functor"; "("; i = V UIDENT "uid" ""; ":"; t = SELF; ")"; "->"; mt = SELF -> <:module_type< functor ( $_uid:i$ : $t$ ) -> $mt$ >> ] | [ mt = SELF; "with"; wcl = V (LIST1 with_constr SEP "and") -> <:module_type< $mt$ with $_list:wcl$ >> ] | [ "sig"; sg = signature; "end" -> <:module_type< sig $_list:sg$ end >> | "module"; "type"; "of"; me = module_expr -> <:module_type< module type of $me$ >> | i = mod_type_ident -> i | "("; mt = SELF; ")" -> <:module_type< $mt$ >> ] ] ; signature: [ [ sg = V (LIST0 [ s = sig_item; OPT ";;" -> s ]) -> sg ] ] ; mod_type_ident: [ LEFTA [ m1 = SELF; "."; m2 = SELF -> <:module_type< $m1$ . $m2$ >> | m1 = SELF; "("; m2 = SELF; ")" -> <:module_type< $m1$ $m2$ >> ] | [ m = V UIDENT -> <:module_type< $_uid:m$ >> | m = V LIDENT -> <:module_type< $_lid:m$ >> ] ] ; sig_item: [ "top" [ "exception"; (_, c, tl, _) = constructor_declaration -> <:sig_item< exception $_uid:c$ of $_list:tl$ >> | "external"; i = V LIDENT "lid" ""; ":"; t = ctyp; "="; pd = V (LIST1 STRING) -> <:sig_item< external $_lid:i$ : $t$ = $_list:pd$ >> | "external"; "("; i = operator_rparen; ":"; t = ctyp; "="; pd = V (LIST1 STRING) -> <:sig_item< external $lid:i$ : $t$ = $_list:pd$ >> | "include"; mt = module_type -> <:sig_item< include $mt$ >> | "module"; rf = V (FLAG "rec"); l = V (LIST1 mod_decl_binding SEP "and") -> <:sig_item< module $_flag:rf$ $_list:l$ >> | "module"; "type"; i = V UIDENT "uid" ""; "="; mt = module_type -> <:sig_item< module type $_uid:i$ = $mt$ >> | "module"; "type"; i = V UIDENT "uid" "" -> <:sig_item< module type $_uid:i$ = 'abstract >> | "open"; i = V mod_ident "list" "" -> <:sig_item< open $_:i$ >> | "type"; tdl = V (LIST1 type_decl SEP "and") -> <:sig_item< type $_list:tdl$ >> | "val"; i = V LIDENT "lid" ""; ":"; t = ctyp -> <:sig_item< value $_lid:i$ : $t$ >> | "val"; "("; i = operator_rparen; ":"; t = ctyp -> <:sig_item< value $lid:i$ : $t$ >> ] ] ; mod_decl_binding: [ [ i = V UIDENT; mt = module_declaration -> (i, mt) ] ] ; module_declaration: [ RIGHTA [ ":"; mt = module_type -> <:module_type< $mt$ >> | "("; i = UIDENT; ":"; t = module_type; ")"; mt = SELF -> <:module_type< functor ( $uid:i$ : $t$ ) -> $mt$ >> ] ] ; with_constr: [ [ "type"; tpl = V type_parameters "list"; i = V mod_ident ""; "="; pf = V (FLAG "private"); t = ctyp -> <:with_constr< type $_:i$ $_list:tpl$ = $_flag:pf$ $t$ >> | "type"; tpl = V type_parameters "list"; i = V mod_ident ""; ":="; t = ctyp -> <:with_constr< type $_:i$ $_list:tpl$ := $t$ >> | "module"; i = V mod_ident ""; "="; me = module_expr -> <:with_constr< module $_:i$ = $me$ >> | "module"; i = V mod_ident ""; ":="; me = module_expr -> <:with_constr< module $_:i$ := $me$ >> ] ] ; Core expressions expr: [ "top" RIGHTA [ e1 = SELF; ";"; e2 = SELF -> <:expr< do { $list:[e1 :: get_seq e2]$ } >> | e1 = SELF; ";" -> e1 | el = V e_phony "list" -> <:expr< do { $_list:el$ } >> ] | "expr1" [ "let"; o = V (FLAG "rec"); l = V (LIST1 let_binding SEP "and"); "in"; x = expr LEVEL "top" -> <:expr< let $_flag:o$ $_list:l$ in $x$ >> | "let"; "module"; m = V UIDENT; mb = mod_fun_binding; "in"; e = expr LEVEL "top" -> <:expr< let module $_uid:m$ = $mb$ in $e$ >> | "function"; OPT "|"; l = V (LIST1 match_case SEP "|") -> <:expr< fun [ $_list:l$ ] >> | "fun"; p = patt LEVEL "simple"; (eo, e) = fun_def -> <:expr< fun [$p$ $opt:eo$ -> $e$] >> | "match"; e = SELF; "with"; OPT "|"; l = V (LIST1 match_case SEP "|") -> <:expr< match $e$ with [ $_list:l$ ] >> | "try"; e = SELF; "with"; OPT "|"; l = V (LIST1 match_case SEP "|") -> <:expr< try $e$ with [ $_list:l$ ] >> | "if"; e1 = SELF; "then"; e2 = expr LEVEL "expr1"; "else"; e3 = expr LEVEL "expr1" -> <:expr< if $e1$ then $e2$ else $e3$ >> | "if"; e1 = SELF; "then"; e2 = expr LEVEL "expr1" -> <:expr< if $e1$ then $e2$ else () >> | "for"; i = V LIDENT; "="; e1 = SELF; df = V direction_flag "to"; e2 = SELF; "do"; e = V SELF "list"; "done" -> let el = Pcaml.vala_map get_seq e in <:expr< for $_lid:i$ = $e1$ $_to:df$ $e2$ do { $_list:el$ } >> | "while"; e1 = SELF; "do"; e2 = V SELF "list"; "done" -> let el = Pcaml.vala_map get_seq e2 in <:expr< while $e1$ do { $_list:el$ } >> ] | [ e = SELF; ","; el = LIST1 NEXT SEP "," -> <:expr< ( $list:[e :: el]$ ) >> ] | ":=" NONA [ e1 = SELF; ":="; e2 = expr LEVEL "expr1" -> <:expr< $e1$.val := $e2$ >> | e1 = SELF; "<-"; e2 = expr LEVEL "expr1" -> <:expr< $e1$ := $e2$ >> ] | "||" RIGHTA [ e1 = SELF; "or"; e2 = SELF -> <:expr< $lid:"or"$ $e1$ $e2$ >> | e1 = SELF; "||"; e2 = SELF -> <:expr< $e1$ || $e2$ >> ] | "&&" RIGHTA [ e1 = SELF; "&"; e2 = SELF -> <:expr< $lid:"&"$ $e1$ $e2$ >> | e1 = SELF; "&&"; e2 = SELF -> <:expr< $e1$ && $e2$ >> ] | "<" LEFTA [ e1 = SELF; "<"; e2 = SELF -> <:expr< $e1$ < $e2$ >> | e1 = SELF; ">"; e2 = SELF -> <:expr< $e1$ > $e2$ >> | e1 = SELF; "<="; e2 = SELF -> <:expr< $e1$ <= $e2$ >> | e1 = SELF; ">="; e2 = SELF -> <:expr< $e1$ >= $e2$ >> | e1 = SELF; "="; e2 = SELF -> <:expr< $e1$ = $e2$ >> | e1 = SELF; "<>"; e2 = SELF -> <:expr< $e1$ <> $e2$ >> | e1 = SELF; "=="; e2 = SELF -> <:expr< $e1$ == $e2$ >> | e1 = SELF; "!="; e2 = SELF -> <:expr< $e1$ != $e2$ >> | e1 = SELF; op = infixop0; e2 = SELF -> <:expr< $lid:op$ $e1$ $e2$ >> ] | "^" RIGHTA [ e1 = SELF; "^"; e2 = SELF -> <:expr< $e1$ ^ $e2$ >> | e1 = SELF; "@"; e2 = SELF -> <:expr< $e1$ @ $e2$ >> | e1 = SELF; op = infixop1; e2 = SELF -> <:expr< $lid:op$ $e1$ $e2$ >> ] | RIGHTA [ e1 = SELF; "::"; e2 = SELF -> <:expr< [$e1$ :: $e2$] >> ] | "+" LEFTA [ e1 = SELF; "+"; e2 = SELF -> <:expr< $e1$ + $e2$ >> | e1 = SELF; "-"; e2 = SELF -> <:expr< $e1$ - $e2$ >> | e1 = SELF; op = infixop2; e2 = SELF -> <:expr< $lid:op$ $e1$ $e2$ >> ] | "*" LEFTA [ e1 = SELF; "*"; e2 = SELF -> <:expr< $e1$ * $e2$ >> | e1 = SELF; "/"; e2 = SELF -> <:expr< $e1$ / $e2$ >> | e1 = SELF; "%"; e2 = SELF -> <:expr< $lid:"%"$ $e1$ $e2$ >> | e1 = SELF; "land"; e2 = SELF -> <:expr< $e1$ land $e2$ >> | e1 = SELF; "lor"; e2 = SELF -> <:expr< $e1$ lor $e2$ >> | e1 = SELF; "lxor"; e2 = SELF -> <:expr< $e1$ lxor $e2$ >> | e1 = SELF; "mod"; e2 = SELF -> <:expr< $e1$ mod $e2$ >> | e1 = SELF; op = infixop3; e2 = SELF -> <:expr< $lid:op$ $e1$ $e2$ >> ] | "**" RIGHTA [ e1 = SELF; "**"; e2 = SELF -> <:expr< $e1$ ** $e2$ >> | e1 = SELF; "asr"; e2 = SELF -> <:expr< $e1$ asr $e2$ >> | e1 = SELF; "lsl"; e2 = SELF -> <:expr< $e1$ lsl $e2$ >> | e1 = SELF; "lsr"; e2 = SELF -> <:expr< $e1$ lsr $e2$ >> | e1 = SELF; op = infixop4; e2 = SELF -> <:expr< $lid:op$ $e1$ $e2$ >> ] | "unary minus" NONA [ "-"; e = SELF -> <:expr< - $e$ >> | "-."; e = SELF -> <:expr< -. $e$ >> ] | "apply" LEFTA [ e1 = SELF; e2 = SELF -> let (e1, e2) = if is_expr_constr_call e1 then match e1 with [ <:expr< $e11$ $e12$ >> -> (e11, <:expr< $e12$ $e2$ >>) | _ -> (e1, e2) ] else (e1, e2) in match constr_expr_arity loc e1 with [ 1 -> <:expr< $e1$ $e2$ >> | _ -> match e2 with [ <:expr< ( $list:el$ ) >> -> List.fold_left (fun e1 e2 -> <:expr< $e1$ $e2$ >>) e1 el | _ -> <:expr< $e1$ $e2$ >> ] ] | "assert"; e = SELF -> <:expr< assert $e$ >> | "lazy"; e = SELF -> <:expr< lazy ($e$) >> ] | "." LEFTA [ e1 = SELF; "."; "("; op = operator_rparen -> <:expr< $e1$ .( $lid:op$ ) >> | e1 = SELF; "."; "("; e2 = SELF; ")" -> <:expr< $e1$ .( $e2$ ) >> | e1 = SELF; "."; "["; e2 = SELF; "]" -> <:expr< $e1$ .[ $e2$ ] >> | e = SELF; "."; "{"; el = V (LIST1 expr LEVEL "+" SEP ","); "}" -> <:expr< $e$ .{ $_list:el$ } >> | e1 = SELF; "."; e2 = SELF -> let rec loop m = fun [ <:expr< $x$ . $y$ >> -> loop <:expr< $m$ . $x$ >> y | e -> <:expr< $m$ . $e$ >> ] in loop e1 e2 ] | "~-" NONA [ "!"; e = SELF -> <:expr< $e$ . val >> | "~-"; e = SELF -> <:expr< ~- $e$ >> | "~-."; e = SELF -> <:expr< ~-. $e$ >> | f = prefixop; e = SELF -> <:expr< $lid:f$ $e$ >> ] | "simple" LEFTA [ s = V INT -> <:expr< $_int:s$ >> | s = V INT_l -> <:expr< $_int32:s$ >> | s = V INT_L -> <:expr< $_int64:s$ >> | s = V INT_n -> <:expr< $_nativeint:s$ >> | s = V FLOAT -> <:expr< $_flo:s$ >> | s = V STRING -> <:expr< $_str:s$ >> | c = V CHAR -> <:expr< $_chr:c$ >> | UIDENT "True" -> <:expr< True_ >> | UIDENT "False" -> <:expr< False_ >> | i = expr_ident -> i | "false" -> <:expr< False >> | "true" -> <:expr< True >> | "["; "]" -> <:expr< [] >> | "["; el = expr1_semi_list; "]" -> <:expr< $mklistexp loc None el$ >> | "[|"; "|]" -> <:expr< [| |] >> | "[|"; el = V expr1_semi_list "list"; "|]" -> <:expr< [| $_list:el$ |] >> | "{"; test_label_eq; lel = V lbl_expr_list "list"; "}" -> <:expr< { $_list:lel$ } >> | "{"; e = expr LEVEL "."; "with"; lel = V lbl_expr_list "list"; "}" -> <:expr< { ($e$) with $_list:lel$ } >> | "("; ")" -> <:expr< () >> | "("; "module"; me = module_expr; ":"; mt = module_type; ")" -> <:expr< (module $me$ : $mt$) >> | "("; "module"; me = module_expr; ")" -> <:expr< (module $me$) >> | "("; op = operator_rparen -> <:expr< $lid:op$ >> | "("; el = V e_phony "list"; ")" -> <:expr< ($_list:el$) >> | "("; e = SELF; ":"; t = ctyp; ")" -> <:expr< ($e$ : $t$) >> | "("; e = SELF; ")" -> concat_comm loc <:expr< $e$ >> | "begin"; e = SELF; "end" -> concat_comm loc <:expr< $e$ >> | "begin"; "end" -> <:expr< () >> | x = QUOTATION -> let con = quotation_content x in Pcaml.handle_expr_quotation loc con ] ] ; let_binding: [ [ p = val_ident; e = fun_binding -> (p, e) | p = patt; "="; e = expr -> (p, e) | p = patt; ":"; t = poly_type; "="; e = expr -> (<:patt< ($p$ : $t$) >>, e) ] ] ; * * added the " translate_operator " here * * val_ident: [ [ check_not_part_of_patt; s = LIDENT -> <:patt< $lid:s$ >> | check_not_part_of_patt; "("; s = ANY; ")" -> let s' = translate_operator s in <:patt< $lid:s'$ >> ] ] ; fun_binding: [ RIGHTA [ p = patt LEVEL "simple"; e = SELF -> <:expr< fun $p$ -> $e$ >> | "="; e = expr -> <:expr< $e$ >> | ":"; t = poly_type; "="; e = expr -> <:expr< ($e$ : $t$) >> ] ] ; match_case: [ [ x1 = patt; w = V (OPT [ "when"; e = expr -> e ]); "->"; x2 = expr -> (x1, w, x2) ] ] ; lbl_expr_list: [ [ le = lbl_expr; ";"; lel = SELF -> [le :: lel] | le = lbl_expr; ";" -> [le] | le = lbl_expr -> [le] ] ] ; lbl_expr: [ [ i = patt_label_ident; "="; e = expr LEVEL "expr1" -> (i, e) ] ] ; expr1_semi_list: [ [ el = LIST1 (expr LEVEL "expr1") SEP ";" OPT_SEP -> el ] ] ; fun_def: [ RIGHTA [ p = patt LEVEL "simple"; (eo, e) = SELF -> (None, <:expr< fun [ $p$ $opt:eo$ -> $e$ ] >>) | eo = OPT [ "when"; e = expr -> e ]; "->"; e = expr -> (eo, <:expr< $e$ >>) ] ] ; expr_ident: [ RIGHTA [ i = V LIDENT -> <:expr< $_lid:i$ >> | i = V UIDENT -> <:expr< $_uid:i$ >> | i = V UIDENT; "."; j = SELF -> let rec loop m = fun [ <:expr< $x$ . $y$ >> -> loop <:expr< $m$ . $x$ >> y | e -> <:expr< $m$ . $e$ >> ] in loop <:expr< $_uid:i$ >> j | i = V UIDENT; "."; "("; j = operator_rparen -> <:expr< $_uid:i$ . $lid:j$ >> ] ] ; patt: [ LEFTA [ p1 = SELF; "as"; i = LIDENT -> <:patt< ($p1$ as $lid:i$) >> ] | LEFTA [ p1 = SELF; "|"; p2 = SELF -> <:patt< $p1$ | $p2$ >> ] | [ p = SELF; ","; pl = LIST1 NEXT SEP "," -> <:patt< ( $list:[p :: pl]$) >> ] | NONA [ p1 = SELF; ".."; p2 = SELF -> <:patt< $p1$ .. $p2$ >> ] | RIGHTA [ p1 = SELF; "::"; p2 = SELF -> <:patt< [$p1$ :: $p2$] >> ] | LEFTA [ p1 = SELF; p2 = SELF -> let (p1, p2) = match p1 with [ <:patt< $p11$ $p12$ >> -> (p11, <:patt< $p12$ $p2$ >>) | _ -> (p1, p2) ] in match constr_patt_arity loc p1 with [ 1 -> <:patt< $p1$ $p2$ >> | n -> let p2 = match p2 with [ <:patt< _ >> when n > 1 -> let pl = loop n where rec loop n = if n = 0 then [] else [<:patt< _ >> :: loop (n - 1)] in <:patt< ( $list:pl$ ) >> | _ -> p2 ] in match p2 with [ <:patt< ( $list:pl$ ) >> -> List.fold_left (fun p1 p2 -> <:patt< $p1$ $p2$ >>) p1 pl | _ -> <:patt< $p1$ $p2$ >> ] ] | "lazy"; p = SELF -> <:patt< lazy $p$ >> ] | LEFTA [ p1 = SELF; "."; p2 = SELF -> <:patt< $p1$ . $p2$ >> ] | "simple" [ s = V LIDENT -> <:patt< $_lid:s$ >> | s = V UIDENT -> <:patt< $_uid:s$ >> | s = V INT -> <:patt< $_int:s$ >> | s = V INT_l -> <:patt< $_int32:s$ >> | s = V INT_L -> <:patt< $_int64:s$ >> | s = V INT_n -> <:patt< $_nativeint:s$ >> | "-"; s = INT -> <:patt< $int:"-" ^ s$ >> | "-"; s = FLOAT -> <:patt< $flo:"-" ^ s$ >> | s = V FLOAT -> <:patt< $_flo:s$ >> | s = V STRING -> <:patt< $_str:s$ >> | s = V CHAR -> <:patt< $_chr:s$ >> | UIDENT "True" -> <:patt< True_ >> | UIDENT "False" -> <:patt< False_ >> | "false" -> <:patt< False >> | "true" -> <:patt< True >> | "["; "]" -> <:patt< [] >> | "["; pl = patt_semi_list; "]" -> <:patt< $mklistpat loc None pl$ >> | "[|"; "|]" -> <:patt< [| |] >> | "[|"; pl = V patt_semi_list "list"; "|]" -> <:patt< [| $_list:pl$ |] >> | "{"; lpl = V lbl_patt_list "list"; "}" -> <:patt< { $_list:lpl$ } >> | "("; ")" -> <:patt< () >> | "("; op = operator_rparen -> <:patt< $lid:op$ >> | "("; pl = V p_phony "list"; ")" -> <:patt< ($_list:pl$) >> | "("; p = SELF; ":"; t = ctyp; ")" -> <:patt< ($p$ : $t$) >> | "("; p = SELF; ")" -> <:patt< $p$ >> | "("; "type"; s = V LIDENT; ")" -> <:patt< (type $_lid:s$) >> | "("; "module"; s = V UIDENT; ":"; mt = module_type; ")" -> <:patt< (module $_uid:s$ : $mt$) >> | "("; "module"; s = V UIDENT; ")" -> <:patt< (module $_uid:s$) >> | "_" -> <:patt< _ >> | x = QUOTATION -> let con = quotation_content x in Pcaml.handle_patt_quotation loc con ] ] ; patt_semi_list: [ [ p = patt; ";"; pl = SELF -> [p :: pl] | p = patt; ";" -> [p] | p = patt -> [p] ] ] ; lbl_patt_list: [ [ le = lbl_patt; ";"; lel = SELF -> [le :: lel] | le = lbl_patt; ";" -> [le] | le = lbl_patt -> [le] ] ] ; lbl_patt: [ [ i = patt_label_ident; "="; p = patt -> (i, p) ] ] ; patt_label_ident: [ LEFTA [ p1 = SELF; "."; p2 = SELF -> <:patt< $p1$ . $p2$ >> ] | RIGHTA [ i = UIDENT -> <:patt< $uid:i$ >> | i = LIDENT -> <:patt< $lid:i$ >> ] ] ; type_decl: [ [ tpl = type_parameters; n = V type_patt; "="; pf = V (FLAG "private"); tk = type_kind; cl = V (LIST0 constrain) -> <:type_decl< $_tp:n$ $list:tpl$ = $_priv:pf$ $tk$ $_list:cl$ >> | tpl = type_parameters; n = V type_patt; cl = V (LIST0 constrain) -> let tk = <:ctyp< '$choose_tvar tpl$ >> in <:type_decl< $_tp:n$ $list:tpl$ = $tk$ $_list:cl$ >> ] ] ; type_patt: [ [ n = V LIDENT -> (loc, n) ] ] ; constrain: [ [ "constraint"; t1 = ctyp; "="; t2 = ctyp -> (t1, t2) ] ] ; type_kind: [ [ test_constr_decl; OPT "|"; cdl = LIST1 constructor_declaration SEP "|" -> <:ctyp< [ $list:cdl$ ] >> | t = ctyp -> <:ctyp< $t$ >> | t = ctyp; "="; pf = FLAG "private"; "{"; ldl = V label_declarations "list"; "}" -> <:ctyp< $t$ == $priv:pf$ { $_list:ldl$ } >> | t = ctyp; "="; pf = FLAG "private"; OPT "|"; cdl = LIST1 constructor_declaration SEP "|" -> <:ctyp< $t$ == $priv:pf$ [ $list:cdl$ ] >> | "{"; ldl = V label_declarations "list"; "}" -> <:ctyp< { $_list:ldl$ } >> ] ] ; type_parameters: | tp = type_parameter -> [tp] | "("; tpl = LIST1 type_parameter SEP ","; ")" -> tpl ] ] ; type_parameter: [ [ "+"; p = V simple_type_parameter -> (p, Some True) | "-"; p = V simple_type_parameter -> (p, Some False) | p = V simple_type_parameter -> (p, None) ] ] ; simple_type_parameter: [ [ "'"; i = ident -> Some i | "_" -> None ] ] ; constructor_declaration: [ [ ci = cons_ident; "of"; cal = V (LIST1 (ctyp LEVEL "apply") SEP "*") -> (loc, ci, cal, None) | ci = cons_ident; ":"; cal = V (LIST1 (ctyp LEVEL "apply") SEP "*"); "->"; t = ctyp -> (loc, ci, cal, Some t) | ci = cons_ident; ":"; cal = V (LIST1 (ctyp LEVEL "apply") SEP "*") -> let t = match cal with [ <:vala< [t] >> -> t | <:vala< [t :: tl] >> -> <:ctyp< ($list:[t :: tl]$) >> | _ -> assert False ] in (loc, ci, <:vala< [] >>, Some t) | ci = cons_ident -> (loc, ci, <:vala< [] >>, None) ] ] ; cons_ident: [ [ i = V UIDENT "uid" "" -> i | UIDENT "True" -> <:vala< "True_" >> | UIDENT "False" -> <:vala< "False_" >> ] ] ; label_declarations: [ [ ld = label_declaration; ";"; ldl = SELF -> [ld :: ldl] | ld = label_declaration; ";" -> [ld] | ld = label_declaration -> [ld] ] ] ; label_declaration: [ [ i = LIDENT; ":"; t = poly_type -> (loc, i, False, t) | "mutable"; i = LIDENT; ":"; t = poly_type -> (loc, i, True, t) ] ] ; Core types ctyp: [ [ t1 = SELF; "as"; "'"; i = ident -> <:ctyp< $t1$ as '$i$ >> ] | "arrow" RIGHTA [ t1 = SELF; "->"; t2 = SELF -> <:ctyp< $t1$ -> $t2$ >> ] | "star" [ t = SELF; "*"; tl = LIST1 (ctyp LEVEL "apply") SEP "*" -> <:ctyp< ( $list:[t :: tl]$ ) >> ] | "apply" [ t1 = SELF; t2 = SELF -> <:ctyp< $t2$ $t1$ >> ] | "ctyp2" [ t1 = SELF; "."; t2 = SELF -> <:ctyp< $t1$ . $t2$ >> | t1 = SELF; "("; t2 = SELF; ")" -> <:ctyp< $t1$ $t2$ >> ] | "simple" [ "'"; i = V ident "" -> <:ctyp< '$_:i$ >> | "_" -> <:ctyp< _ >> | i = V LIDENT -> <:ctyp< $_lid:i$ >> | i = V UIDENT -> <:ctyp< $_uid:i$ >> | "("; "module"; mt = module_type; ")" -> <:ctyp< module $mt$ >> | "("; t = SELF; ","; tl = LIST1 ctyp SEP ","; ")"; i = ctyp LEVEL "ctyp2" -> List.fold_left (fun c a -> <:ctyp< $c$ $a$ >>) i [t :: tl] | "("; t = SELF; ")" -> <:ctyp< $t$ >> ] ] ; ident: [ [ i = LIDENT -> i | i = UIDENT -> i ] ] ; mod_ident: [ RIGHTA [ i = UIDENT -> [i] | i = LIDENT -> [i] | i = UIDENT; "."; j = SELF -> [i :: j] ] ] ; direction_flag: [ [ "to" -> True | "downto" -> False ] ] ; str_item: [ [ "class"; cd = V (LIST1 class_declaration SEP "and") -> <:str_item< class $_list:cd$ >> | "class"; "type"; ctd = V (LIST1 class_type_declaration SEP "and") -> <:str_item< class type $_list:ctd$ >> ] ] ; sig_item: [ [ "class"; cd = V (LIST1 class_description SEP "and") -> <:sig_item< class $_list:cd$ >> | "class"; "type"; ctd = V (LIST1 class_type_declaration SEP "and") -> <:sig_item< class type $_list:ctd$ >> ] ] ; class_declaration: [ [ vf = V (FLAG "virtual"); ctp = class_type_parameters; i = V LIDENT; cfb = class_fun_binding -> {MLast.ciLoc = loc; MLast.ciVir = vf; MLast.ciPrm = ctp; MLast.ciNam = i; MLast.ciExp = cfb} ] ] ; class_fun_binding: [ [ "="; ce = class_expr -> ce | ":"; ct = class_type; "="; ce = class_expr -> <:class_expr< ($ce$ : $ct$) >> | p = patt LEVEL "simple"; cfb = SELF -> <:class_expr< fun $p$ -> $cfb$ >> ] ] ; class_type_parameters: [ [ -> (loc, <:vala< [] >>) | "["; tpl = V (LIST1 type_parameter SEP ","); "]" -> (loc, tpl) ] ] ; class_fun_def: [ [ p = patt LEVEL "simple"; "->"; ce = class_expr -> <:class_expr< fun $p$ -> $ce$ >> | p = patt LEVEL "simple"; cfd = SELF -> <:class_expr< fun $p$ -> $cfd$ >> ] ] ; class_expr: [ "top" [ "fun"; cfd = class_fun_def -> cfd | "let"; rf = V (FLAG "rec"); lb = V (LIST1 let_binding SEP "and"); "in"; ce = SELF -> <:class_expr< let $_flag:rf$ $_list:lb$ in $ce$ >> ] | "apply" LEFTA [ ce = SELF; e = expr LEVEL "label" -> <:class_expr< $ce$ $e$ >> ] | "simple" [ "["; ct = ctyp; ","; ctcl = LIST1 ctyp SEP ","; "]"; ci = class_longident -> <:class_expr< [ $list:[ct :: ctcl]$ ] $list:ci$ >> | "["; ct = ctyp; "]"; ci = class_longident -> <:class_expr< [ $ct$ ] $list:ci$ >> | ci = class_longident -> <:class_expr< $list:ci$ >> | "object"; cspo = V (OPT class_self_patt); cf = V class_structure "list"; "end" -> <:class_expr< object $_opt:cspo$ $_list:cf$ end >> | "("; ce = SELF; ":"; ct = class_type; ")" -> <:class_expr< ($ce$ : $ct$) >> | "("; ce = SELF; ")" -> ce ] ] ; class_structure: [ [ cf = LIST0 class_str_item -> cf ] ] ; class_self_patt: [ [ "("; p = patt; ")" -> p | "("; p = patt; ":"; t = ctyp; ")" -> <:patt< ($p$ : $t$) >> ] ] ; class_str_item: [ [ "inherit"; ce = class_expr; pb = V (OPT [ "as"; i = LIDENT -> i ]) -> <:class_str_item< inherit $ce$ $_opt:pb$ >> | "val"; ov = V (FLAG "!") "!"; mf = V (FLAG "mutable"); lab = V LIDENT "lid" ""; e = cvalue_binding -> <:class_str_item< value $_!:ov$ $_flag:mf$ $_lid:lab$ = $e$ >> | "val"; ov = V (FLAG "!") "!"; mf = V (FLAG "mutable"); "virtual"; lab = V LIDENT "lid" ""; ":"; t = ctyp -> if Pcaml.unvala ov then Ploc.raise loc (Stream.Error "virtual value cannot override") else <:class_str_item< value virtual $_flag:mf$ $_lid:lab$ : $t$ >> | "val"; "virtual"; mf = V (FLAG "mutable"); lab = V LIDENT "lid" ""; ":"; t = ctyp -> <:class_str_item< value virtual $_flag:mf$ $_lid:lab$ : $t$ >> | "method"; "private"; "virtual"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_str_item< method virtual private $_lid:l$ : $t$ >> | "method"; "virtual"; "private"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_str_item< method virtual private $_lid:l$ : $t$ >> | "method"; "virtual"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_str_item< method virtual $_lid:l$ : $t$ >> | "method"; ov = V (FLAG "!") "!"; "private"; l = V LIDENT "lid" ""; ":"; t = poly_type; "="; e = expr -> <:class_str_item< method $_!:ov$ private $_lid:l$ : $t$ = $e$ >> | "method"; ov = V (FLAG "!") "!"; "private"; l = V LIDENT "lid" ""; sb = fun_binding -> <:class_str_item< method $_!:ov$ private $_lid:l$ = $sb$ >> | "method"; ov = V (FLAG "!") "!"; l = V LIDENT "lid" ""; ":"; t = poly_type; "="; e = expr -> <:class_str_item< method $_!:ov$ $_lid:l$ : $t$ = $e$ >> | "method"; ov = V (FLAG "!") "!"; l = V LIDENT "lid" ""; sb = fun_binding -> <:class_str_item< method $_!:ov$ $_lid:l$ = $sb$ >> | "constraint"; t1 = ctyp; "="; t2 = ctyp -> <:class_str_item< type $t1$ = $t2$ >> | "initializer"; se = expr -> <:class_str_item< initializer $se$ >> ] ] ; cvalue_binding: [ [ "="; e = expr -> e | ":"; t = ctyp; "="; e = expr -> <:expr< ($e$ : $t$) >> | ":"; t = ctyp; ":>"; t2 = ctyp; "="; e = expr -> <:expr< ($e$ : $t$ :> $t2$) >> | ":>"; t = ctyp; "="; e = expr -> <:expr< ($e$ :> $t$) >> ] ] ; label: [ [ i = LIDENT -> i ] ] ; class_type: [ [ test_ctyp_minusgreater; t = ctyp LEVEL "star"; "->"; ct = SELF -> <:class_type< [ $t$ ] -> $ct$ >> | cs = class_signature -> cs ] ] ; class_signature: [ [ "["; tl = LIST1 ctyp SEP ","; "]"; id = SELF -> <:class_type< $id$ [ $list:tl$ ] >> | "object"; cst = V (OPT class_self_type); csf = V (LIST0 class_sig_item); "end" -> <:class_type< object $_opt:cst$ $_list:csf$ end >> ] | [ ct1 = SELF; "."; ct2 = SELF -> <:class_type< $ct1$ . $ct2$ >> | ct1 = SELF; "("; ct2 = SELF; ")" -> <:class_type< $ct1$ $ct2$ >> ] | [ i = V LIDENT -> <:class_type< $_id: i$ >> | i = V UIDENT -> <:class_type< $_id: i$ >> ] ] ; class_self_type: [ [ "("; t = ctyp; ")" -> t ] ] ; class_sig_item: [ [ "inherit"; cs = class_signature -> <:class_sig_item< inherit $cs$ >> | "val"; mf = V (FLAG "mutable"); l = V LIDENT "lid" ""; ":"; t = ctyp -> <:class_sig_item< value $_flag:mf$ $_lid:l$ : $t$ >> | "method"; "private"; "virtual"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_sig_item< method virtual private $_lid:l$ : $t$ >> | "method"; "virtual"; "private"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_sig_item< method virtual private $_lid:l$ : $t$ >> | "method"; "virtual"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_sig_item< method virtual $_lid:l$ : $t$ >> | "method"; "private"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_sig_item< method private $_lid:l$ : $t$ >> | "method"; l = V LIDENT "lid" ""; ":"; t = poly_type -> <:class_sig_item< method $_lid:l$ : $t$ >> | "constraint"; t1 = ctyp; "="; t2 = ctyp -> <:class_sig_item< type $t1$ = $t2$ >> ] ] ; class_description: [ [ vf = V (FLAG "virtual"); ctp = class_type_parameters; n = V LIDENT; ":"; ct = class_type -> {MLast.ciLoc = loc; MLast.ciVir = vf; MLast.ciPrm = ctp; MLast.ciNam = n; MLast.ciExp = ct} ] ] ; class_type_declaration: [ [ vf = V (FLAG "virtual"); ctp = class_type_parameters; n = V LIDENT; "="; cs = class_signature -> {MLast.ciLoc = loc; MLast.ciVir = vf; MLast.ciPrm = ctp; MLast.ciNam = n; MLast.ciExp = cs} ] ] ; expr: LEVEL "simple" [ LEFTA [ "new"; i = V class_longident "list" -> <:expr< new $_list:i$ >> | "object"; cspo = V (OPT class_self_patt); cf = V class_structure "list"; "end" -> <:expr< object $_opt:cspo$ $_list:cf$ end >> ] ] ; expr: LEVEL "." [ [ e = SELF; "#"; lab = V LIDENT "lid" -> <:expr< $e$ # $_lid:lab$ >> ] ] ; expr: LEVEL "simple" [ [ "("; e = SELF; ":"; t = ctyp; ":>"; t2 = ctyp; ")" -> <:expr< ($e$ : $t$ :> $t2$) >> | "("; e = SELF; ":>"; t = ctyp; ")" -> <:expr< ($e$ :> $t$) >> | "{<"; ">}" -> <:expr< {< >} >> | "{<"; fel = V field_expr_list "list"; ">}" -> <:expr< {< $_list:fel$ >} >> ] ] ; field_expr_list: [ [ l = label; "="; e = expr LEVEL "expr1"; ";"; fel = SELF -> [(l, e) :: fel] | l = label; "="; e = expr LEVEL "expr1"; ";" -> [(l, e)] | l = label; "="; e = expr LEVEL "expr1" -> [(l, e)] ] ] ; Core types ctyp: LEVEL "simple" [ [ "#"; id = V class_longident "list" -> <:ctyp< # $_list:id$ >> | "<"; ml = V meth_list "list"; v = V (FLAG ".."); ">" -> <:ctyp< < $_list:ml$ $_flag:v$ > >> | "<"; ".."; ">" -> <:ctyp< < .. > >> | "<"; ">" -> <:ctyp< < > >> ] ] ; meth_list: [ [ f = field; ";"; ml = SELF -> [f :: ml] | f = field; ";" -> [f] | f = field -> [f] ] ] ; field: [ [ lab = LIDENT; ":"; t = poly_type -> (lab, t) ] ] ; typevar: [ [ "'"; i = ident -> i ] ] ; poly_type: [ [ "type"; nt = LIST1 LIDENT; "."; ct = ctyp -> <:ctyp< type $list:nt$ . $ct$ >> | test_typevar_list_dot; tpl = LIST1 typevar; "."; t2 = ctyp -> <:ctyp< ! $list:tpl$ . $t2$ >> | t = ctyp -> t ] ] ; class_longident: [ [ m = UIDENT; "."; l = SELF -> [m :: l] | i = LIDENT -> [i] ] ] ; ctyp: AFTER "arrow" [ NONA [ i = V LIDENT; ":"; t = SELF -> <:ctyp< ~$_:i$: $t$ >> | i = V QUESTIONIDENTCOLON; t = SELF -> <:ctyp< ?$_:i$: $t$ >> | i = V QUESTIONIDENT; ":"; t = SELF -> <:ctyp< ?$_:i$: $t$ >> ] ] ; ctyp: LEVEL "simple" [ [ "["; OPT "|"; rfl = V (LIST1 poly_variant SEP "|"); "]" -> <:ctyp< [ = $_list:rfl$ ] >> | "["; ">"; "]" -> <:ctyp< [ > $list:[]$ ] >> | "["; ">"; OPT "|"; rfl = V (LIST1 poly_variant SEP "|"); "]" -> <:ctyp< [ > $_list:rfl$ ] >> | "[<"; OPT "|"; rfl = V (LIST1 poly_variant SEP "|"); "]" -> <:ctyp< [ < $_list:rfl$ ] >> | "[<"; OPT "|"; rfl = V (LIST1 poly_variant SEP "|"); ">"; ntl = V (LIST1 name_tag); "]" -> <:ctyp< [ < $_list:rfl$ > $_list:ntl$ ] >> ] ] ; poly_variant: [ [ "`"; i = V ident "" -> <:poly_variant< ` $_:i$ >> | "`"; i = V ident ""; "of"; ao = V (FLAG "&"); l = V (LIST1 ctyp SEP "&") -> <:poly_variant< `$_:i$ of $_flag:ao$ $_list:l$ >> | t = ctyp -> <:poly_variant< $t$ >> ] ] ; name_tag: [ [ "`"; i = ident -> i ] ] ; expr: LEVEL "expr1" [ [ "fun"; p = labeled_patt; (eo, e) = fun_def -> <:expr< fun [ $p$ $opt:eo$ -> $e$ ] >> ] ] ; expr: AFTER "apply" [ "label" [ i = V TILDEIDENTCOLON; e = SELF -> <:expr< ~{$_:i$ = $e$} >> | i = V TILDEIDENT -> <:expr< ~{$_:i$} >> | i = V QUESTIONIDENTCOLON; e = SELF -> <:expr< ?{$_:i$ = $e$} >> | i = V QUESTIONIDENT -> <:expr< ?{$_:i$} >> ] ] ; expr: LEVEL "simple" [ [ "`"; s = V ident "" -> <:expr< ` $_:s$ >> ] ] ; fun_def: [ [ p = labeled_patt; (eo, e) = SELF -> (None, <:expr< fun [ $p$ $opt:eo$ -> $e$ ] >>) ] ] ; fun_binding: [ [ p = labeled_patt; e = SELF -> <:expr< fun $p$ -> $e$ >> ] ] ; patt: LEVEL "simple" [ [ "`"; s = V ident "" -> <:patt< ` $_:s$ >> | "#"; t = V mod_ident "list" "" -> <:patt< # $_list:t$ >> | p = labeled_patt -> p ] ] ; labeled_patt: [ [ i = V TILDEIDENTCOLON; p = patt LEVEL "simple" -> <:patt< ~{$_:i$ = $p$} >> | i = V TILDEIDENT -> <:patt< ~{$_:i$} >> | "~"; "("; i = LIDENT; ")" -> <:patt< ~{$lid:i$} >> | "~"; "("; i = LIDENT; ":"; t = ctyp; ")" -> <:patt< ~{$lid:i$ : $t$} >> | i = V QUESTIONIDENTCOLON; j = LIDENT -> <:patt< ?{$_:i$ = ?{$lid:j$}} >> | i = V QUESTIONIDENTCOLON; "_" -> <:patt< ?{$_:i$} >> | i = V QUESTIONIDENTCOLON; "("; p = patt; "="; e = expr; ")" -> <:patt< ?{$_:i$ = ?{$p$ = $e$}} >> | i = V QUESTIONIDENTCOLON; "("; p = patt; ":"; t = ctyp; ")" -> <:patt< ?{$_:i$ = ?{$p$ : $t$}} >> | i = V QUESTIONIDENTCOLON; "("; p = patt; ":"; t = ctyp; "="; e = expr; ")" -> <:patt< ?{$_:i$ = ?{$p$ : $t$ = $e$}} >> | i = V QUESTIONIDENTCOLON; "("; p = patt; ")" -> <:patt< ?{$_:i$ = ?{$p$}} >> | i = V QUESTIONIDENT -> <:patt< ?{$_:i$} >> | "?"; "("; i = LIDENT; "="; e = expr; ")" -> <:patt< ?{$lid:i$ = $e$} >> | "?"; "("; i = LIDENT; ":"; t = ctyp; "="; e = expr; ")" -> <:patt< ?{$lid:i$ : $t$ = $e$} >> | "?"; "("; i = LIDENT; ")" -> <:patt< ?{$lid:i$} >> | "?"; "("; i = LIDENT; ":"; t = ctyp; ")" -> <:patt< ?{$lid:i$ : $t$} >> ] ] ; class_type: [ [ i = LIDENT; ":"; t = ctyp LEVEL "apply"; "->"; ct = SELF -> <:class_type< [ ~$i$: $t$ ] -> $ct$ >> | i = V QUESTIONIDENTCOLON; t = ctyp LEVEL "apply"; "->"; ct = SELF -> <:class_type< [ ?$_:i$: $t$ ] -> $ct$ >> | i = V QUESTIONIDENT; ":"; t = ctyp LEVEL "apply"; "->"; ct = SELF -> <:class_type< [ ?$_:i$: $t$ ] -> $ct$ >> ] ] ; class_fun_binding: [ [ p = labeled_patt; cfb = SELF -> <:class_expr< fun $p$ -> $cfb$ >> ] ] ; class_fun_def: [ [ p = labeled_patt; "->"; ce = class_expr -> <:class_expr< fun $p$ -> $ce$ >> | p = labeled_patt; cfd = SELF -> <:class_expr< fun $p$ -> $cfd$ >> ] ] ; END; EXTEND GLOBAL: interf implem use_file top_phrase expr patt; interf: [ [ si = sig_item_semi; (sil, stopped) = SELF -> ([si :: sil], stopped) | "#"; n = LIDENT; dp = OPT expr; ";;" -> ([(<:sig_item< # $lid:n$ $opt:dp$ >>, loc)], None) | EOI -> ([], Some loc) ] ] ; sig_item_semi: [ [ si = sig_item; OPT ";;" -> (si, loc) ] ] ; implem: [ [ si = str_item_semi; (sil, stopped) = SELF -> ([si :: sil], stopped) | "#"; n = LIDENT; dp = OPT expr; ";;" -> ([(<:str_item< # $lid:n$ $opt:dp$ >>, loc)], None) | EOI -> ([], Some loc) ] ] ; str_item_semi: [ [ si = str_item; OPT ";;" -> (si, loc) ] ] ; top_phrase: [ [ ph = phrase; ";;" -> Some ph | EOI -> None ] ] ; use_file: [ [ si = str_item; OPT ";;"; (sil, stopped) = SELF -> ([si :: sil], stopped) | "#"; n = LIDENT; dp = OPT expr; ";;" -> ([<:str_item< # $lid:n$ $opt:dp$ >>], True) | EOI -> ([], False) ] ] ; phrase: [ [ sti = str_item -> sti | "#"; n = LIDENT; dp = OPT expr -> <:str_item< # $lid:n$ $opt:dp$ >> ] ] ; END; Pcaml.add_option "-no_quot" (Arg.Set no_quotations) "Don't parse quotations, allowing to use, e.g. \"<:>\" as token"; Added by * * * EXTEND expr: AFTER "<" [[ f = expr; "o"; g = expr -> <:expr< ((o $f$) $g$) >> | f = expr; "upto"; g = expr -> <:expr< ((upto $f$) $g$) >> | f = expr; "F_F"; g = expr -> <:expr< ((f_f_ $f$) $g$) >> | f = expr; "THENC"; g = expr -> <:expr< ((thenc_ $f$) $g$) >> | f = expr; "THEN"; g = expr -> <:expr< ((then_ $f$) $g$) >> | f = expr; "THENL"; g = expr -> <:expr< ((thenl_ $f$) $g$) >> | f = expr; "ORELSE"; g = expr -> <:expr< ((orelse_ $f$) $g$) >> | f = expr; "ORELSEC"; g = expr -> <:expr< ((orelsec_ $f$) $g$) >> | f = expr; "THEN_TCL"; g = expr -> <:expr< ((then_tcl_ $f$) $g$) >> | f = expr; "ORELSE_TCL"; g = expr -> <:expr< ((orelse_tcl_ $f$) $g$) >> ]]; END; EXTEND top_phrase: [ [ sti = str_item; ";;" -> match sti with [ <:str_item< $exp:e$ >> -> Some <:str_item< value it = $e$ >> | x -> Some x ] ] ] ; END;
2ff7a504354575bd7fa452df16a74dc671ef904aca84d50b37a0712f230df954
ahungry/defjs
package.lisp
defjs - Common Lisp REPL fun in Javascript Copyright ( C ) 2014 ;; ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see </>. package.lisp (defpackage #:defjs (:use #:cl #:bordeaux-threads #:parenscript #:clws #:hunchentoot #:cl-who #:glyphs) (:export #:main #:defjs #:dojs #:loader #:get-loader #:page-js #:start-websocket-server #:*js*))
null
https://raw.githubusercontent.com/ahungry/defjs/655d04b1164cd2008db0eae848a8621ebbdd0161/package.lisp
lisp
This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>.
defjs - Common Lisp REPL fun in Javascript Copyright ( C ) 2014 it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License package.lisp (defpackage #:defjs (:use #:cl #:bordeaux-threads #:parenscript #:clws #:hunchentoot #:cl-who #:glyphs) (:export #:main #:defjs #:dojs #:loader #:get-loader #:page-js #:start-websocket-server #:*js*))
a69a7675b06f20fd60ea3cd920a854814fdce19eb862a00079bb404880a5f838
circuithub/rel8
Order.hs
# language DerivingStrategies # # language GeneralizedNewtypeDeriving # # language StandaloneKindSignatures # module Rel8.Order ( Order(..) ) where -- base import Data.Functor.Contravariant ( Contravariant ) import Data.Kind ( Type ) import Prelude -- contravariant import Data.Functor.Contravariant.Divisible ( Decidable, Divisible ) -- opaleye import qualified Opaleye.Order as Opaleye | An ordering expression for Primitive orderings are defined with -- 'Rel8.asc' and 'Rel8.desc', and you can combine @Order@ via its various -- instances. -- -- A common pattern is to use '<>' to combine multiple orderings in sequence, -- and 'Data.Functor.Contravariant.>$<' to select individual columns. type Order :: Type -> Type newtype Order a = Order (Opaleye.Order a) deriving newtype (Contravariant, Divisible, Decidable, Semigroup, Monoid)
null
https://raw.githubusercontent.com/circuithub/rel8/2e82fccb02470198297f4a71b9da8f535d8029b1/src/Rel8/Order.hs
haskell
base contravariant opaleye 'Rel8.asc' and 'Rel8.desc', and you can combine @Order@ via its various instances. A common pattern is to use '<>' to combine multiple orderings in sequence, and 'Data.Functor.Contravariant.>$<' to select individual columns.
# language DerivingStrategies # # language GeneralizedNewtypeDeriving # # language StandaloneKindSignatures # module Rel8.Order ( Order(..) ) where import Data.Functor.Contravariant ( Contravariant ) import Data.Kind ( Type ) import Prelude import Data.Functor.Contravariant.Divisible ( Decidable, Divisible ) import qualified Opaleye.Order as Opaleye | An ordering expression for Primitive orderings are defined with type Order :: Type -> Type newtype Order a = Order (Opaleye.Order a) deriving newtype (Contravariant, Divisible, Decidable, Semigroup, Monoid)
dfd4cb35afa77e461a7d63126aaedc0b2cb34253e641c7fa821e718a3bd20a09
madgen/exalog
Foreign.hs
# LANGUAGE DataKinds # module Fixture.Foreign -- Leq100 ( programLeq100 , initLeq100EDB , leq100Pred , leq100Tuples PrefixOf , programPrefixOf , initPrefixOfEDB , prefixOfPred , prefixOfTuples Cartesian , programCartesian23 , initCartesian23EDB , cartesian23Pred , cartesian23Tuples -- Impure , programImpure , initImpureEDB , impurePred , impureTuples ) where import Protolude hiding (isPrefixOf, Set) import Data.Maybe (fromJust) import qualified Data.Text as Text import qualified Data.List.NonEmpty as NE import qualified Data.Vector.Sized as V import Data.Singletons.TypeLits import Language.Exalog.Core import Language.Exalog.ForeignFunction import Language.Exalog.KnowledgeBase.Class import Language.Exalog.KnowledgeBase.Knowledge import Language.Exalog.KnowledgeBase.Set import Language.Exalog.SrcLoc import Fixture.Util -------------------------------------------------------------------------------- -- leq100 Fixture -------------------------------------------------------------------------------- srcPred :: Predicate 1 'ABase srcPred = Predicate (PredABase NoSpan) "src" SNat Logical leqPred :: Predicate 2 'ABase leqPred = Predicate (PredABase NoSpan) "<" SNat (Extralogical $ liftPredicate ((<) :: Int -> Int -> Bool)) leq100Pred :: Predicate 1 'ABase leq100Pred = Predicate (PredABase NoSpan) "leq100" SNat Logical src :: Term -> Literal 'ABase src t = lit srcPred $ fromJust $ V.fromList [ t ] leq :: Term -> Term -> Literal 'ABase leq t t' = lit leqPred $ fromJust $ V.fromList [ t, t' ] leq100 :: Term -> Literal 'ABase leq100 t = lit leq100Pred $ fromJust $ V.fromList [ t ] - src("10 " ) . - src("99 " ) . - src("100 " ) . - src("3000 " ) . - leq100(X ) : - src(X ) , X < 100 . - src("10"). - src("99"). - src("100"). - src("3000"). - leq100(X) :- src(X), X < 100. -} programLeq100 :: Program 'ABase programLeq100 = Program (ProgABase NoSpan) (Stratum <$> [ [ Clause (ClABase NoSpan) (leq100 (tvar "X")) $ NE.fromList [ src (tvar "X") , leq (tvar "X") (tsym (100 :: Int)) ] ] ]) [ PredicateBox leq100Pred ] srcTuples :: [ V.Vector 1 Int ] srcTuples = fromJust . V.fromList <$> [ [ 10 ], [ 99 ], [ 100 ], [ 3000 ] ] initLeq100EDB :: Set 'ABase initLeq100EDB = fromList $ Knowledge KnowABase srcPred . fmap symbol <$> srcTuples leq100Tuples :: [ V.Vector 1 Sym ] leq100Tuples = fmap symbol . fromJust . V.fromList <$> ([ [ 10 ], [ 99 ] ] :: [ [ Int ] ]) -------------------------------------------------------------------------------- -- prefixOf Fixture -------------------------------------------------------------------------------- src2Pred :: Predicate 1 'ABase src2Pred = Predicate (PredABase NoSpan) "src2" SNat Logical isPrefixOfPred :: Predicate 2 'ABase isPrefixOfPred = Predicate (PredABase NoSpan) "isPrefixOf" SNat (Extralogical $ liftPredicate (Text.isPrefixOf :: Text -> Text -> Bool)) prefixOfPred :: Predicate 2 'ABase prefixOfPred = Predicate (PredABase NoSpan) "prefixOf" SNat Logical src2 :: Term -> Literal 'ABase src2 t = lit src2Pred $ fromJust $ V.fromList [ t ] isPrefixOf :: Term -> Term -> Literal 'ABase isPrefixOf t t' = lit isPrefixOfPred $ fromJust $ V.fromList [ t, t' ] prefixOf :: Term -> Term -> Literal 'ABase prefixOf t t' = lit prefixOfPred $ fromJust $ V.fromList [ t, t' ] - src2 ( " " ) . - src2("Mis " ) . - src2("Andrew " ) . - src2("Mistral " ) . - src2("Mistral " ) . - prefixOf(X , Y ) : - src(X ) , src(Y ) , isPrefixOf(X , Y ) . - src2(""). - src2("Mis"). - src2("Andrew"). - src2("Mistral"). - src2("Mistral Contrastin"). - prefixOf(X,Y) :- src(X), src(Y), isPrefixOf(X,Y). -} programPrefixOf :: Program 'ABase programPrefixOf = Program (ProgABase NoSpan) (Stratum <$> [ [ Clause (ClABase NoSpan) (prefixOf (tvar "X") (tvar "Y")) $ NE.fromList [ src2 (tvar "X") , src2 (tvar "Y") , tvar "X" `isPrefixOf` tvar "Y" ] ] ]) [ PredicateBox prefixOfPred ] src2Tuples :: [ V.Vector 1 Text ] src2Tuples = fromJust . V.fromList <$> ([ [ "" ], [ "Mis" ], [ "Andrew" ], [ "Mistral" ], [ "Mistral Contrastin" ] ] :: [ [ Text ] ]) initPrefixOfEDB :: Set 'ABase initPrefixOfEDB = fromList $ Knowledge KnowABase src2Pred . fmap symbol <$> src2Tuples prefixOfTuples :: [ V.Vector 2 Sym ] prefixOfTuples = fmap symbol . fromJust . V.fromList <$> ([ [ "", "" ], [ "", "Mis" ], [ "", "Andrew" ], [ "", "Mistral" ], [ "", "Mistral Contrastin" ] , [ "Mis", "Mis" ], [ "Mis", "Mistral" ], [ "Mis", "Mistral Contrastin" ] , [ "Andrew", "Andrew" ] , [ "Mistral", "Mistral" ], [ "Mistral", "Mistral Contrastin" ] , [ "Mistral Contrastin", "Mistral Contrastin" ] ] :: [ [ Text ] ]) -------------------------------------------------------------------------------- -- cartesian Fixture -------------------------------------------------------------------------------- cart :: Int -> Int -> [ (Int, Int) ] cart n m = [ (i,j) | i <- [1..n], j <- [1..m] ] cartesianPred :: Predicate 4 'ABase cartesianPred = Predicate (PredABase NoSpan) "cartesian" SNat (Extralogical $ liftFunction cart) cartesian23Pred :: Predicate 2 'ABase cartesian23Pred = Predicate (PredABase NoSpan) "cartesian23" SNat Logical cartesian :: Term -> Term -> Term -> Term -> Literal 'ABase cartesian t t' t'' t''' = lit cartesianPred $ fromJust $ V.fromList [ t, t', t'', t''' ] cartesian23 :: Term -> Term -> Literal 'ABase cartesian23 t t' = lit cartesian23Pred $ fromJust $ V.fromList [ t, t' ] {- - cartesian23(X,Y) :- cartesian(2,3,X,Y). -} programCartesian23 :: Program 'ABase programCartesian23 = Program (ProgABase NoSpan) (Stratum <$> [ [ Clause (ClABase NoSpan) (cartesian23 (tvar "X") (tvar "Y")) $ NE.fromList [ cartesian (tsym (2 :: Int)) (tsym (3 :: Int)) (tvar "X") (tvar "Y") ] ] ]) [ PredicateBox cartesian23Pred ] initCartesian23EDB :: Set 'ABase initCartesian23EDB = fromList [ ] cartesian23Tuples :: [ V.Vector 2 Sym ] cartesian23Tuples = fmap symbol . fromJust . V.fromList <$> ([ [ 1, 1 ] , [ 1, 2 ], [ 1, 3] , [ 2, 1 ] , [ 2, 2 ], [ 2, 3 ] ] :: [ [ Int ] ]) -------------------------------------------------------------------------------- -- Non-pure fixture -------------------------------------------------------------------------------- impureIDForeign :: Int -> Foreign Int impureIDForeign = pure impureIDPred :: Predicate 2 'ABase impureIDPred = Predicate (PredABase NoSpan) "impureID" SNat (Extralogical $ liftFunctionME impureIDForeign) impureID :: Term -> Term -> Literal 'ABase impureID t t' = lit impureIDPred $ fromJust $ V.fromList [ t, t' ] impureFinForeign :: Int -> Foreign [ Int ] impureFinForeign i = pure [0..i] impureFinPred :: Predicate 2 'ABase impureFinPred = Predicate (PredABase NoSpan) "impureFin" SNat (Extralogical $ liftFunctionME impureFinForeign) impureFin :: Term -> Term -> Literal 'ABase impureFin t t' = lit impureFinPred $ fromJust $ V.fromList [ t, t' ] impureEvenForeign :: Int -> Foreign Bool impureEvenForeign = pure . even impureEvenPred :: Predicate 1 'ABase impureEvenPred = Predicate (PredABase NoSpan) "impureEven" SNat (Extralogical $ liftPredicateME impureEvenForeign) impureEven :: Term -> Literal 'ABase impureEven t = lit impureEvenPred $ fromJust $ V.fromList [ t ] impurePred :: Predicate 1 'ABase impurePred = Predicate (PredABase NoSpan) "impure" SNat Logical impure :: Term -> Literal 'ABase impure t = lit impurePred $ fromJust $ V.fromList [ t ] programImpure :: Program 'ABase programImpure = Program (ProgABase NoSpan) (Stratum <$> [ [ Clause (ClABase NoSpan) (impure (tvar "Y")) $ NE.fromList [ impureFin (tsym (10 :: Int)) (tvar "X") , impureEven (tvar "X") , impureID (tvar "X") (tvar "Y")] ] ]) [ PredicateBox impurePred ] initImpureEDB :: Set 'ABase initImpureEDB = fromList [ ] impureTuples :: [ V.Vector 1 Sym ] impureTuples = fmap symbol . fromJust . V.fromList <$> ([ [ 0 ], [ 2 ], [ 4 ], [ 6 ], [ 8 ], [ 10 ] ] :: [ [ Int ] ])
null
https://raw.githubusercontent.com/madgen/exalog/7d169b066c5c08f2b8e44f5e078df264731ac177/fixtures/Fixture/Foreign.hs
haskell
Leq100 Impure ------------------------------------------------------------------------------ leq100 Fixture ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ prefixOf Fixture ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ cartesian Fixture ------------------------------------------------------------------------------ - cartesian23(X,Y) :- cartesian(2,3,X,Y). ------------------------------------------------------------------------------ Non-pure fixture ------------------------------------------------------------------------------
# LANGUAGE DataKinds # module Fixture.Foreign ( programLeq100 , initLeq100EDB , leq100Pred , leq100Tuples PrefixOf , programPrefixOf , initPrefixOfEDB , prefixOfPred , prefixOfTuples Cartesian , programCartesian23 , initCartesian23EDB , cartesian23Pred , cartesian23Tuples , programImpure , initImpureEDB , impurePred , impureTuples ) where import Protolude hiding (isPrefixOf, Set) import Data.Maybe (fromJust) import qualified Data.Text as Text import qualified Data.List.NonEmpty as NE import qualified Data.Vector.Sized as V import Data.Singletons.TypeLits import Language.Exalog.Core import Language.Exalog.ForeignFunction import Language.Exalog.KnowledgeBase.Class import Language.Exalog.KnowledgeBase.Knowledge import Language.Exalog.KnowledgeBase.Set import Language.Exalog.SrcLoc import Fixture.Util srcPred :: Predicate 1 'ABase srcPred = Predicate (PredABase NoSpan) "src" SNat Logical leqPred :: Predicate 2 'ABase leqPred = Predicate (PredABase NoSpan) "<" SNat (Extralogical $ liftPredicate ((<) :: Int -> Int -> Bool)) leq100Pred :: Predicate 1 'ABase leq100Pred = Predicate (PredABase NoSpan) "leq100" SNat Logical src :: Term -> Literal 'ABase src t = lit srcPred $ fromJust $ V.fromList [ t ] leq :: Term -> Term -> Literal 'ABase leq t t' = lit leqPred $ fromJust $ V.fromList [ t, t' ] leq100 :: Term -> Literal 'ABase leq100 t = lit leq100Pred $ fromJust $ V.fromList [ t ] - src("10 " ) . - src("99 " ) . - src("100 " ) . - src("3000 " ) . - leq100(X ) : - src(X ) , X < 100 . - src("10"). - src("99"). - src("100"). - src("3000"). - leq100(X) :- src(X), X < 100. -} programLeq100 :: Program 'ABase programLeq100 = Program (ProgABase NoSpan) (Stratum <$> [ [ Clause (ClABase NoSpan) (leq100 (tvar "X")) $ NE.fromList [ src (tvar "X") , leq (tvar "X") (tsym (100 :: Int)) ] ] ]) [ PredicateBox leq100Pred ] srcTuples :: [ V.Vector 1 Int ] srcTuples = fromJust . V.fromList <$> [ [ 10 ], [ 99 ], [ 100 ], [ 3000 ] ] initLeq100EDB :: Set 'ABase initLeq100EDB = fromList $ Knowledge KnowABase srcPred . fmap symbol <$> srcTuples leq100Tuples :: [ V.Vector 1 Sym ] leq100Tuples = fmap symbol . fromJust . V.fromList <$> ([ [ 10 ], [ 99 ] ] :: [ [ Int ] ]) src2Pred :: Predicate 1 'ABase src2Pred = Predicate (PredABase NoSpan) "src2" SNat Logical isPrefixOfPred :: Predicate 2 'ABase isPrefixOfPred = Predicate (PredABase NoSpan) "isPrefixOf" SNat (Extralogical $ liftPredicate (Text.isPrefixOf :: Text -> Text -> Bool)) prefixOfPred :: Predicate 2 'ABase prefixOfPred = Predicate (PredABase NoSpan) "prefixOf" SNat Logical src2 :: Term -> Literal 'ABase src2 t = lit src2Pred $ fromJust $ V.fromList [ t ] isPrefixOf :: Term -> Term -> Literal 'ABase isPrefixOf t t' = lit isPrefixOfPred $ fromJust $ V.fromList [ t, t' ] prefixOf :: Term -> Term -> Literal 'ABase prefixOf t t' = lit prefixOfPred $ fromJust $ V.fromList [ t, t' ] - src2 ( " " ) . - src2("Mis " ) . - src2("Andrew " ) . - src2("Mistral " ) . - src2("Mistral " ) . - prefixOf(X , Y ) : - src(X ) , src(Y ) , isPrefixOf(X , Y ) . - src2(""). - src2("Mis"). - src2("Andrew"). - src2("Mistral"). - src2("Mistral Contrastin"). - prefixOf(X,Y) :- src(X), src(Y), isPrefixOf(X,Y). -} programPrefixOf :: Program 'ABase programPrefixOf = Program (ProgABase NoSpan) (Stratum <$> [ [ Clause (ClABase NoSpan) (prefixOf (tvar "X") (tvar "Y")) $ NE.fromList [ src2 (tvar "X") , src2 (tvar "Y") , tvar "X" `isPrefixOf` tvar "Y" ] ] ]) [ PredicateBox prefixOfPred ] src2Tuples :: [ V.Vector 1 Text ] src2Tuples = fromJust . V.fromList <$> ([ [ "" ], [ "Mis" ], [ "Andrew" ], [ "Mistral" ], [ "Mistral Contrastin" ] ] :: [ [ Text ] ]) initPrefixOfEDB :: Set 'ABase initPrefixOfEDB = fromList $ Knowledge KnowABase src2Pred . fmap symbol <$> src2Tuples prefixOfTuples :: [ V.Vector 2 Sym ] prefixOfTuples = fmap symbol . fromJust . V.fromList <$> ([ [ "", "" ], [ "", "Mis" ], [ "", "Andrew" ], [ "", "Mistral" ], [ "", "Mistral Contrastin" ] , [ "Mis", "Mis" ], [ "Mis", "Mistral" ], [ "Mis", "Mistral Contrastin" ] , [ "Andrew", "Andrew" ] , [ "Mistral", "Mistral" ], [ "Mistral", "Mistral Contrastin" ] , [ "Mistral Contrastin", "Mistral Contrastin" ] ] :: [ [ Text ] ]) cart :: Int -> Int -> [ (Int, Int) ] cart n m = [ (i,j) | i <- [1..n], j <- [1..m] ] cartesianPred :: Predicate 4 'ABase cartesianPred = Predicate (PredABase NoSpan) "cartesian" SNat (Extralogical $ liftFunction cart) cartesian23Pred :: Predicate 2 'ABase cartesian23Pred = Predicate (PredABase NoSpan) "cartesian23" SNat Logical cartesian :: Term -> Term -> Term -> Term -> Literal 'ABase cartesian t t' t'' t''' = lit cartesianPred $ fromJust $ V.fromList [ t, t', t'', t''' ] cartesian23 :: Term -> Term -> Literal 'ABase cartesian23 t t' = lit cartesian23Pred $ fromJust $ V.fromList [ t, t' ] programCartesian23 :: Program 'ABase programCartesian23 = Program (ProgABase NoSpan) (Stratum <$> [ [ Clause (ClABase NoSpan) (cartesian23 (tvar "X") (tvar "Y")) $ NE.fromList [ cartesian (tsym (2 :: Int)) (tsym (3 :: Int)) (tvar "X") (tvar "Y") ] ] ]) [ PredicateBox cartesian23Pred ] initCartesian23EDB :: Set 'ABase initCartesian23EDB = fromList [ ] cartesian23Tuples :: [ V.Vector 2 Sym ] cartesian23Tuples = fmap symbol . fromJust . V.fromList <$> ([ [ 1, 1 ] , [ 1, 2 ], [ 1, 3] , [ 2, 1 ] , [ 2, 2 ], [ 2, 3 ] ] :: [ [ Int ] ]) impureIDForeign :: Int -> Foreign Int impureIDForeign = pure impureIDPred :: Predicate 2 'ABase impureIDPred = Predicate (PredABase NoSpan) "impureID" SNat (Extralogical $ liftFunctionME impureIDForeign) impureID :: Term -> Term -> Literal 'ABase impureID t t' = lit impureIDPred $ fromJust $ V.fromList [ t, t' ] impureFinForeign :: Int -> Foreign [ Int ] impureFinForeign i = pure [0..i] impureFinPred :: Predicate 2 'ABase impureFinPred = Predicate (PredABase NoSpan) "impureFin" SNat (Extralogical $ liftFunctionME impureFinForeign) impureFin :: Term -> Term -> Literal 'ABase impureFin t t' = lit impureFinPred $ fromJust $ V.fromList [ t, t' ] impureEvenForeign :: Int -> Foreign Bool impureEvenForeign = pure . even impureEvenPred :: Predicate 1 'ABase impureEvenPred = Predicate (PredABase NoSpan) "impureEven" SNat (Extralogical $ liftPredicateME impureEvenForeign) impureEven :: Term -> Literal 'ABase impureEven t = lit impureEvenPred $ fromJust $ V.fromList [ t ] impurePred :: Predicate 1 'ABase impurePred = Predicate (PredABase NoSpan) "impure" SNat Logical impure :: Term -> Literal 'ABase impure t = lit impurePred $ fromJust $ V.fromList [ t ] programImpure :: Program 'ABase programImpure = Program (ProgABase NoSpan) (Stratum <$> [ [ Clause (ClABase NoSpan) (impure (tvar "Y")) $ NE.fromList [ impureFin (tsym (10 :: Int)) (tvar "X") , impureEven (tvar "X") , impureID (tvar "X") (tvar "Y")] ] ]) [ PredicateBox impurePred ] initImpureEDB :: Set 'ABase initImpureEDB = fromList [ ] impureTuples :: [ V.Vector 1 Sym ] impureTuples = fmap symbol . fromJust . V.fromList <$> ([ [ 0 ], [ 2 ], [ 4 ], [ 6 ], [ 8 ], [ 10 ] ] :: [ [ Int ] ])
d7b1b54ecd130666ae93a76a2d690bed4bea2264f1865796e164585738f715bd
ferdinand-beyer/init
build.clj
(ns build (:require [clojure.tools.build.api :as b])) (def lib 'init/todo-app) (def version (format "1.0.%s" (b/git-count-revs nil))) (def class-dir "target/classes") (def basis (b/create-basis)) (def uber-file (format "target/%s-%s-standalone.jar" (name lib) version)) (defn clean [_] (b/delete {:path "target"})) (defn uber [_] (clean nil) (println "Compiling Clojure code...") (b/compile-clj {:basis basis :class-dir class-dir}) (println "Copying resources...") (b/copy-dir {:src-dirs ["resources"] :target-dir class-dir}) (println "Building uberjar...") (b/uber {:class-dir class-dir :uber-file uber-file :basis basis :main 'todo-app.main}))
null
https://raw.githubusercontent.com/ferdinand-beyer/init/62414dae2b7af6ea2e3036db0b2f6e2bdf3d8e65/examples/todo-app/build.clj
clojure
(ns build (:require [clojure.tools.build.api :as b])) (def lib 'init/todo-app) (def version (format "1.0.%s" (b/git-count-revs nil))) (def class-dir "target/classes") (def basis (b/create-basis)) (def uber-file (format "target/%s-%s-standalone.jar" (name lib) version)) (defn clean [_] (b/delete {:path "target"})) (defn uber [_] (clean nil) (println "Compiling Clojure code...") (b/compile-clj {:basis basis :class-dir class-dir}) (println "Copying resources...") (b/copy-dir {:src-dirs ["resources"] :target-dir class-dir}) (println "Building uberjar...") (b/uber {:class-dir class-dir :uber-file uber-file :basis basis :main 'todo-app.main}))
5e39b39222ce69e31116a50f0a9e94229832da51c845c2043963e73841a89b7d
cardmagic/lucash
lmsort.scm
;;; list merge & list merge-sort -*- Scheme -*- Copyright ( c ) 1998 by . ;;; This code is open-source; see the end of the file for porting and ;;; more copyright information. ;;; Exports: ;;; (list-merge < lis lis) -> list ;;; (list-merge! < lis lis) -> list ;;; (list-merge-sort < lis) -> list ;;; (list-merge-sort! < lis) -> list ;;; A stable list merge sort of my own device Two variants : pure & destructive ;;; ;;; This list merge sort is opportunistic (a "natural" sort) -- it exploits ;;; existing order in the input set. Instead of recursing all the way down to ;;; individual elements, the leaves of the merge tree are maximal contiguous ;;; runs of elements from the input list. So the algorithm does very well on ;;; data that is mostly ordered, with a best-case time of O(n) when the input ;;; list is already completely sorted. In any event, worst-case time is O(n lg n ) . ;;; ;;; The destructive variant is "in place," meaning that it allocates no new ;;; cons cells at all; it just rearranges the pairs of the input list with ;;; SET-CDR! to order it. ;;; ;;; The interesting control structure is the combination recursion/iteration ;;; of the core GROW function that does an "opportunistic" DFS walk of the ;;; merge tree, adaptively subdividing in response to the length of the ;;; merges, without requiring any auxiliary data structures beyond the recursion stack . It 's actually quite simple -- ten lines of code . ;;; -Olin Shivers 10/20/98 ( ( ( var - list mv - exp ) ... ) body ... ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; A LET * form that handles multiple values . Move this into the two clients ;;; if you don't have a module system handy to restrict its visibility... (define-syntax mlet ; Multiple-value LET* (syntax-rules () ((mlet ((() exp) rest ...) body ...) (begin exp (mlet (rest ...) body ...))) ((mlet (((var) exp) rest ...) body ...) (let ((var exp)) (mlet (rest ...) body ...))) ((mlet ((vars exp) rest ...) body ...) (call-with-values (lambda () exp) (lambda vars (mlet (rest ...) body ...)))) ((mlet () body ...) (begin body ...)))) ;;; (list-merge-sort < lis) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; A natural, stable list merge sort. ;;; - natural: picks off maximal contiguous runs of pre-ordered data. ;;; - stable: won't invert the order of equal elements in the input list. (define (list-merge-sort elt< lis) ;; (getrun lis) -> run runlen rest ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Pick a run of non - decreasing data off of non - empty list LIS . ;; Return the length of this run, and the following list. (define (getrun lis) (let lp ((ans '()) (i 1) (prev (car lis)) (xs (cdr lis))) (if (pair? xs) (let ((x (car xs))) (if (elt< x prev) (values (append-reverse ans (cons prev '())) i xs) (lp (cons prev ans) (+ i 1) x (cdr xs)))) (values (append-reverse ans (cons prev '())) i xs)))) (define (append-reverse rev-head tail) (let lp ((rev-head rev-head) (tail tail)) (if (null-list? rev-head) tail (lp (cdr rev-head) (cons (car rev-head) tail))))) (define (null-list? l) (cond ((pair? l) #f) ((null? l) #t) (else (error "null-list?: argument out of domain" l)))) ;; (merge a b) -> list ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; List merge -- stably merge lists A (length > 0) & B (length > 0). ;; This version requires up to |a|+|b| stack frames. (define (merge a b) (let recur ((x (car a)) (a a) (y (car b)) (b b)) (if (elt< y x) (cons y (let ((b (cdr b))) (if (pair? b) (recur x a (car b) b) a))) (cons x (let ((a (cdr a))) (if (pair? a) (recur (car a) a y b) b)))))) ;; (grow s ls ls2 u lw) -> [a la unused] ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; The core routine . Read the next 20 lines of comments & all is obvious . - S is a sorted list of length LS > 1 . - LS2 is some power of two < = LS . ;; - U is an unsorted list. ;; - LW is a positive integer. Starting with S , and taking data from U as needed , produce a sorted list of * at least * length LW , if there 's enough data ( LW < = LS + length(U ) ) , or use all of U if not . ;; GROW takes maximal contiguous runs of data from U at a time ; it is allowed to return a list * longer * than LW if it gets lucky ;; with a long run. ;; The key idea : If you want a merge operation to " pay for itself , " the two ;; lists being merged should be about the same length. Remember that. ;; ;; Returns: ;; - A: The result list ;; - LA: The length of the result list - UNUSED : The unused tail of U. (define (grow s ls ls2 u lw) ; The core of the sort algorithm. Met quota or out of data ? (values s ls u) ; If so, we're done. (mlet (((ls2) (let lp ((ls2 ls2)) (let ((ls2*2 (+ ls2 ls2))) (if (<= ls2*2 ls) (lp ls2*2) ls2)))) LS2 is now the largest power of two < = LS . ( Just think of it as being roughly LS . ) ((r lr u2) (getrun u)) ; Get a run, then ((t lt u3) (grow r lr 1 u2 ls2))) ; grow it up to be T. (grow (merge s t) (+ ls lt) ; Merge S & T, (+ ls2 ls2) u3 lw)))) ; and loop. Note : ( LENGTH ) or any constant guaranteed to be greater can be used in place of INFINITY . (if (pair? lis) ; Don't sort an empty list. (mlet (((r lr tail) (getrun lis)) ; Pick off an initial run, ((infinity) #o100000000) ; then grow it up maximally. ((a la v) (grow r lr 1 tail infinity))) a) '())) ;;; (list-merge-sort! < lis) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; A natural, stable, destructive, in-place list merge sort. ;;; - natural: picks off maximal contiguous runs of pre-ordered data. ;;; - stable: won't invert the order of equal elements in the input list. ;;; - destructive, in-place: this routine allocates no extra working memory; ;;; it simply rearranges the list with SET-CDR! operations. (define (list-merge-sort! elt< lis) ;; (getrun lis) -> runlen last rest ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Pick a run of non - decreasing data off of non - empty list LIS . ;; Return the length of this run, the last cons cell of the run, ;; and the following list. (define (getrun lis) (let lp ((lis lis) (x (car lis)) (i 1) (next (cdr lis))) (if (pair? next) (let ((y (car next))) (if (elt< y x) (values i lis next) (lp next y (+ i 1) (cdr next)))) (values i lis next)))) ( merge ! a enda b endb ) - > [ m endm ] ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Destructively and stably merge non - empty lists A & B. The last cons of A is . ( The cdr of can be non - nil . ) the last cons of B is . ( The cdr of ENDB can be non - nil . ) ;; Return the first and last cons cells of the merged list . ;; This routine is iterative & in-place: it runs in constant stack and ;; doesn't allocate any cons cells. It is also tedious but simple; don't ;; bother reading it unless necessary. (define (merge! a enda b endb) The logic of these two loops is completely driven by these invariants : ;; SCAN-A: (CDR PREV) = A. X = (CAR A). Y = (CAR B). SCAN - B : ( CDR PREV ) = = ( CAR A ) . Y = ( CAR B ) . (letrec ((scan-a (lambda (prev x a y b) ; Zip down A until we (cond ((elt< y x) ; find an elt > (CAR B). (set-cdr! prev b) (let ((next-b (cdr b))) (if (eq? b endb) (begin (set-cdr! b a) enda) ; Done. (scan-b b x a (car next-b) next-b)))) ((eq? a enda) (maybe-set-cdr! a b) endb) ; Done. (else (let ((next-a (cdr a))) ; Continue scan. (scan-a a (car next-a) next-a y b)))))) (scan-b (lambda (prev x a y b) ; Zip down B while its (cond ((elt< y x) ; elts are < (CAR A). (if (eq? b endb) (begin (set-cdr! b a) enda) ; Done. (let ((next-b (cdr b))) ; Continue scan. (scan-b b x a (car next-b) next-b)))) (else (set-cdr! prev a) (if (eq? a enda) (begin (maybe-set-cdr! a b) endb) ; Done. (let ((next-a (cdr a))) (scan-a a (car next-a) next-a y b))))))) ;; This guy only writes if he has to. Called at most once. ;; Pointer equality rules; pure languages are for momma's boys. (maybe-set-cdr! (lambda (pair val) (if (not (eq? (cdr pair) val)) (set-cdr! pair val))))) (let ((x (car a)) (y (car b))) (if (elt< y x) ;; B starts the answer list. (values b (if (eq? b endb) (begin (set-cdr! b a) enda) (let ((next-b (cdr b))) (scan-b b x a (car next-b) next-b)))) ;; A starts the answer list. (values a (if (eq? a enda) (begin (maybe-set-cdr! a b) endb) (let ((next-a (cdr a))) (scan-a a (car next-a) next-a y b)))))))) ;; (grow s ends ls ls2 u lw) -> [a enda la unused] ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; The core routine. - S is a sorted list of length LS > 1 , with final cons cell ENDS . ;; (CDR ENDS) doesn't have to be nil. - LS2 is some power of two < = LS . ;; - U is an unsorted list. ;; - LW is a positive integer. Starting with S , and taking data from U as needed , produce a sorted list of * at least * length LW , if there 's enough data ( LW < = LS + length(U ) ) , or use all of U if not . ;; GROW takes maximal contiguous runs of data from U at a time ; it is allowed to return a list * longer * than LW if it gets lucky ;; with a long run. ;; The key idea : If you want a merge operation to " pay for itself , " the two ;; lists being merged should be about the same length. Remember that. ;; ;; Returns: ;; - A: The result list (not properly terminated) ;; - ENDA: The last cons cell of the result list. ;; - LA: The length of the result list - UNUSED : The unused tail of U. (define (grow s ends ls ls2 u lw) (if (and (pair? u) (< ls lw)) We have n't met the LW quota but there 's still some U data to use . (mlet (((ls2) (let lp ((ls2 ls2)) (let ((ls2*2 (+ ls2 ls2))) (if (<= ls2*2 ls) (lp ls2*2) ls2)))) LS2 is now the largest power of two < = LS . ( Just think of it as being roughly LS . ) Get a run from U ; ((t endt lt u3) (grow u endr lr 1 u2 ls2)) ; grow it up to be T. ((st end-st) (merge! s ends t endt))) ; Merge S & T, (grow st end-st (+ ls lt) (+ ls2 ls2) u3 lw)) ; then loop. Done -- met LW quota or ran out of data . Note : ( LENGTH ) or any constant guaranteed to be greater can be used in place of INFINITY . (if (pair? lis) (mlet (((lr endr rest) (getrun lis)) ; Pick off an initial run. ((infinity) #o100000000) ; Then grow it up maximally. ((a enda la v) (grow lis endr lr 1 rest infinity))) (set-cdr! enda '()) ; Nil-terminate answer. a) ; We're done. '())) ; Don't sort an empty list. ;;; Merge ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; These two merge procedures are stable -- ties favor list A. (define (list-merge < a b) (cond ((not (pair? a)) b) ((not (pair? b)) a) (else (let recur ((x (car a)) (a a) ; A is a pair; X = (CAR A). (y (car b)) (b b)) ; B is a pair; Y = (CAR B). (if (< y x) (let ((b (cdr b))) (if (pair? b) (cons y (recur x a (car b) b)) (cons y a))) (let ((a (cdr a))) (if (pair? a) (cons x (recur (car a) a y b)) (cons x b)))))))) ;;; This destructive merge does as few SET-CDR!s as it can -- for example, if ;;; the list is already sorted, it does no SET-CDR!s at all. It is also ;;; iterative, running in constant stack. (define (list-merge! < a b) The logic of these two loops is completely driven by these invariants : ;; SCAN-A: (CDR PREV) = A. X = (CAR A). Y = (CAR B). SCAN - B : ( CDR PREV ) = = ( CAR A ) . Y = ( CAR B ) . (letrec ((scan-a (lambda (prev a x b y) ; Zip down A doing (if (< y x) ; no SET-CDR!s until (let ((next-b (cdr b))) ; we hit a B elt that (set-cdr! prev b) ; has to be inserted. (if (pair? next-b) (scan-b b a x next-b (car next-b)) (set-cdr! b a))) (let ((next-a (cdr a))) (if (pair? next-a) (scan-a a next-a (car next-a) b y) (set-cdr! a b)))))) (scan-b (lambda (prev a x b y) ; Zip down B doing (if (< y x) ; no SET-CDR!s until (let ((next-b (cdr b))) ; we hit an A elt that (if (pair? next-b) ; has to be (scan-b b a x next-b (car next-b)) ; inserted. (set-cdr! b a))) (let ((next-a (cdr a))) (set-cdr! prev a) (if (pair? next-a) (scan-a a next-a (car next-a) b y) (set-cdr! a b))))))) (cond ((not (pair? a)) b) ((not (pair? b)) a) ;; B starts the answer list. ((< (car b) (car a)) (let ((next-b (cdr b))) (if (null? next-b) (set-cdr! b a) (scan-b b a (car a) next-b (car next-b)))) b) ;; A starts the answer list. (else (let ((next-a (cdr a))) (if (null? next-a) (set-cdr! a b) (scan-a a next-a (car next-a) b (car b)))) a)))) ;;; Copyright ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; This code is Copyright ( c ) 1998 by . ;;; The terms are: You may do as you please with this code, as long as ;;; you do not delete this notice or hold me responsible for any outcome ;;; related to its use. ;;; ;;; Blah blah blah. ;;; Code tuning & porting ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; This is very portable code . It 's R4RS with the following exceptions : - The R5RS multiple - value VALUES & CALL - WITH - VALUES procedures for ;;; handling multiple-value return. ;;; ;;; This code is *tightly* bummed as far as I can go in portable Scheme. ;;; ;;; - The fixnum arithmetic in LIST-MERGE-SORT! and COUNTED-LIST-MERGE! ;;; that could be safely switched over to unsafe, fixnum-specific ops, if you 're sure that 2*maxlen is a fixnum , where maxlen is the length ;;; of the longest list you could ever have. ;;; ;;; - I typically write my code in a style such that every CAR and CDR ;;; application is protected by an upstream PAIR?. This is the case in this ;;; code, so all the CAR's and CDR's could safely switched over to unsafe ;;; versions. But check over the code before you do it, in case the source ;;; has been altered since I wrote this.
null
https://raw.githubusercontent.com/cardmagic/lucash/0452d410430d12140c14948f7f583624f819cdad/reference/scsh-0.6.6/scheme/sort/lmsort.scm
scheme
list merge & list merge-sort -*- Scheme -*- This code is open-source; see the end of the file for porting and more copyright information. Exports: (list-merge < lis lis) -> list (list-merge! < lis lis) -> list (list-merge-sort < lis) -> list (list-merge-sort! < lis) -> list A stable list merge sort of my own device This list merge sort is opportunistic (a "natural" sort) -- it exploits existing order in the input set. Instead of recursing all the way down to individual elements, the leaves of the merge tree are maximal contiguous runs of elements from the input list. So the algorithm does very well on data that is mostly ordered, with a best-case time of O(n) when the input list is already completely sorted. In any event, worst-case time is The destructive variant is "in place," meaning that it allocates no new cons cells at all; it just rearranges the pairs of the input list with SET-CDR! to order it. The interesting control structure is the combination recursion/iteration of the core GROW function that does an "opportunistic" DFS walk of the merge tree, adaptively subdividing in response to the length of the merges, without requiring any auxiliary data structures beyond the -Olin Shivers 10/20/98 if you don't have a module system handy to restrict its visibility... Multiple-value LET* (list-merge-sort < lis) A natural, stable list merge sort. - natural: picks off maximal contiguous runs of pre-ordered data. - stable: won't invert the order of equal elements in the input list. (getrun lis) -> run runlen rest Return the length of this run, and the following list. (merge a b) -> list List merge -- stably merge lists A (length > 0) & B (length > 0). This version requires up to |a|+|b| stack frames. (grow s ls ls2 u lw) -> [a la unused] - U is an unsorted list. - LW is a positive integer. with a long run. lists being merged should be about the same length. Remember that. Returns: - A: The result list - LA: The length of the result list The core of the sort algorithm. If so, we're done. Get a run, then grow it up to be T. Merge S & T, and loop. Don't sort an empty list. Pick off an initial run, then grow it up maximally. (list-merge-sort! < lis) A natural, stable, destructive, in-place list merge sort. - natural: picks off maximal contiguous runs of pre-ordered data. - stable: won't invert the order of equal elements in the input list. - destructive, in-place: this routine allocates no extra working memory; it simply rearranges the list with SET-CDR! operations. (getrun lis) -> runlen last rest Return the length of this run, the last cons cell of the run, and the following list. This routine is iterative & in-place: it runs in constant stack and doesn't allocate any cons cells. It is also tedious but simple; don't bother reading it unless necessary. SCAN-A: (CDR PREV) = A. X = (CAR A). Y = (CAR B). Zip down A until we find an elt > (CAR B). Done. Done. Continue scan. Zip down B while its elts are < (CAR A). Done. Continue scan. Done. This guy only writes if he has to. Called at most once. Pointer equality rules; pure languages are for momma's boys. B starts the answer list. A starts the answer list. (grow s ends ls ls2 u lw) -> [a enda la unused] The core routine. (CDR ENDS) doesn't have to be nil. - U is an unsorted list. - LW is a positive integer. with a long run. lists being merged should be about the same length. Remember that. Returns: - A: The result list (not properly terminated) - ENDA: The last cons cell of the result list. - LA: The length of the result list grow it up to be T. Merge S & T, then loop. Pick off an initial run. Then grow it up maximally. Nil-terminate answer. We're done. Don't sort an empty list. Merge A is a pair; X = (CAR A). B is a pair; Y = (CAR B). This destructive merge does as few SET-CDR!s as it can -- for example, if the list is already sorted, it does no SET-CDR!s at all. It is also iterative, running in constant stack. SCAN-A: (CDR PREV) = A. X = (CAR A). Y = (CAR B). Zip down A doing no SET-CDR!s until we hit a B elt that has to be inserted. Zip down B doing no SET-CDR!s until we hit an A elt that has to be inserted. B starts the answer list. A starts the answer list. Copyright This code is The terms are: You may do as you please with this code, as long as you do not delete this notice or hold me responsible for any outcome related to its use. Blah blah blah. Code tuning & porting handling multiple-value return. This code is *tightly* bummed as far as I can go in portable Scheme. - The fixnum arithmetic in LIST-MERGE-SORT! and COUNTED-LIST-MERGE! that could be safely switched over to unsafe, fixnum-specific ops, of the longest list you could ever have. - I typically write my code in a style such that every CAR and CDR application is protected by an upstream PAIR?. This is the case in this code, so all the CAR's and CDR's could safely switched over to unsafe versions. But check over the code before you do it, in case the source has been altered since I wrote this.
Copyright ( c ) 1998 by . Two variants : pure & destructive O(n lg n ) . recursion stack . It 's actually quite simple -- ten lines of code . ( ( ( var - list mv - exp ) ... ) body ... ) A LET * form that handles multiple values . Move this into the two clients (syntax-rules () ((mlet ((() exp) rest ...) body ...) (begin exp (mlet (rest ...) body ...))) ((mlet (((var) exp) rest ...) body ...) (let ((var exp)) (mlet (rest ...) body ...))) ((mlet ((vars exp) rest ...) body ...) (call-with-values (lambda () exp) (lambda vars (mlet (rest ...) body ...)))) ((mlet () body ...) (begin body ...)))) (define (list-merge-sort elt< lis) Pick a run of non - decreasing data off of non - empty list LIS . (define (getrun lis) (let lp ((ans '()) (i 1) (prev (car lis)) (xs (cdr lis))) (if (pair? xs) (let ((x (car xs))) (if (elt< x prev) (values (append-reverse ans (cons prev '())) i xs) (lp (cons prev ans) (+ i 1) x (cdr xs)))) (values (append-reverse ans (cons prev '())) i xs)))) (define (append-reverse rev-head tail) (let lp ((rev-head rev-head) (tail tail)) (if (null-list? rev-head) tail (lp (cdr rev-head) (cons (car rev-head) tail))))) (define (null-list? l) (cond ((pair? l) #f) ((null? l) #t) (else (error "null-list?: argument out of domain" l)))) (define (merge a b) (let recur ((x (car a)) (a a) (y (car b)) (b b)) (if (elt< y x) (cons y (let ((b (cdr b))) (if (pair? b) (recur x a (car b) b) a))) (cons x (let ((a (cdr a))) (if (pair? a) (recur (car a) a y b) b)))))) The core routine . Read the next 20 lines of comments & all is obvious . - S is a sorted list of length LS > 1 . - LS2 is some power of two < = LS . Starting with S , and taking data from U as needed , produce a sorted list of * at least * length LW , if there 's enough data ( LW < = LS + length(U ) ) , or use all of U if not . it is allowed to return a list * longer * than LW if it gets lucky The key idea : If you want a merge operation to " pay for itself , " the two - UNUSED : The unused tail of U. Met quota or out of data ? (mlet (((ls2) (let lp ((ls2 ls2)) (let ((ls2*2 (+ ls2 ls2))) (if (<= ls2*2 ls) (lp ls2*2) ls2)))) LS2 is now the largest power of two < = LS . ( Just think of it as being roughly LS . ) Note : ( LENGTH ) or any constant guaranteed to be greater can be used in place of INFINITY . ((a la v) (grow r lr 1 tail infinity))) a) '())) (define (list-merge-sort! elt< lis) Pick a run of non - decreasing data off of non - empty list LIS . (define (getrun lis) (let lp ((lis lis) (x (car lis)) (i 1) (next (cdr lis))) (if (pair? next) (let ((y (car next))) (if (elt< y x) (values i lis next) (lp next y (+ i 1) (cdr next)))) (values i lis next)))) ( merge ! a enda b endb ) - > [ m endm ] Destructively and stably merge non - empty lists A & B. The last cons of A is . ( The cdr of can be non - nil . ) the last cons of B is . ( The cdr of ENDB can be non - nil . ) Return the first and last cons cells of the merged list . (define (merge! a enda b endb) The logic of these two loops is completely driven by these invariants : SCAN - B : ( CDR PREV ) = = ( CAR A ) . Y = ( CAR B ) . (set-cdr! prev b) (let ((next-b (cdr b))) (if (eq? b endb) (scan-b b x a (car next-b) next-b)))) (scan-a a (car next-a) next-a y b)))))) (if (eq? b endb) (scan-b b x a (car next-b) next-b)))) (else (set-cdr! prev a) (if (eq? a enda) (let ((next-a (cdr a))) (scan-a a (car next-a) next-a y b))))))) (maybe-set-cdr! (lambda (pair val) (if (not (eq? (cdr pair) val)) (set-cdr! pair val))))) (let ((x (car a)) (y (car b))) (if (elt< y x) (values b (if (eq? b endb) (begin (set-cdr! b a) enda) (let ((next-b (cdr b))) (scan-b b x a (car next-b) next-b)))) (values a (if (eq? a enda) (begin (maybe-set-cdr! a b) endb) (let ((next-a (cdr a))) (scan-a a (car next-a) next-a y b)))))))) - S is a sorted list of length LS > 1 , with final cons cell ENDS . - LS2 is some power of two < = LS . Starting with S , and taking data from U as needed , produce a sorted list of * at least * length LW , if there 's enough data ( LW < = LS + length(U ) ) , or use all of U if not . it is allowed to return a list * longer * than LW if it gets lucky The key idea : If you want a merge operation to " pay for itself , " the two - UNUSED : The unused tail of U. (define (grow s ends ls ls2 u lw) (if (and (pair? u) (< ls lw)) We have n't met the LW quota but there 's still some U data to use . (mlet (((ls2) (let lp ((ls2 ls2)) (let ((ls2*2 (+ ls2 ls2))) (if (<= ls2*2 ls) (lp ls2*2) ls2)))) LS2 is now the largest power of two < = LS . ( Just think of it as being roughly LS . ) Done -- met LW quota or ran out of data . Note : ( LENGTH ) or any constant guaranteed to be greater can be used in place of INFINITY . (if (pair? lis) ((a enda la v) (grow lis endr lr 1 rest infinity))) These two merge procedures are stable -- ties favor list A. (define (list-merge < a b) (cond ((not (pair? a)) b) ((not (pair? b)) a) (if (< y x) (let ((b (cdr b))) (if (pair? b) (cons y (recur x a (car b) b)) (cons y a))) (let ((a (cdr a))) (if (pair? a) (cons x (recur (car a) a y b)) (cons x b)))))))) (define (list-merge! < a b) The logic of these two loops is completely driven by these invariants : SCAN - B : ( CDR PREV ) = = ( CAR A ) . Y = ( CAR B ) . (if (pair? next-b) (scan-b b a x next-b (car next-b)) (set-cdr! b a))) (let ((next-a (cdr a))) (if (pair? next-a) (scan-a a next-a (car next-a) b y) (set-cdr! a b)))))) (set-cdr! b a))) (let ((next-a (cdr a))) (set-cdr! prev a) (if (pair? next-a) (scan-a a next-a (car next-a) b y) (set-cdr! a b))))))) (cond ((not (pair? a)) b) ((not (pair? b)) a) ((< (car b) (car a)) (let ((next-b (cdr b))) (if (null? next-b) (set-cdr! b a) (scan-b b a (car a) next-b (car next-b)))) b) (else (let ((next-a (cdr a))) (if (null? next-a) (set-cdr! a b) (scan-a a next-a (car next-a) b (car b)))) a)))) Copyright ( c ) 1998 by . This is very portable code . It 's R4RS with the following exceptions : - The R5RS multiple - value VALUES & CALL - WITH - VALUES procedures for if you 're sure that 2*maxlen is a fixnum , where maxlen is the length
2a37aeea100316420c967ac01da7d8bcc84c3e367de339feb5b50b6f219b899e
robrix/sequoia
Value.hs
# LANGUAGE UndecidableInstances # module Sequoia.Profunctor.Value ( -- * Value profunctor type (∘)(..) -- * Value abstraction , Value(..) -- * Construction , idV , constV -- * Coercion , _V ) where import Control.Category (Category) import Data.Distributive import Data.Functor.Identity import Data.Functor.Rep as Co import Data.Profunctor import Data.Profunctor.Rep as Pro import Data.Profunctor.Sieve import Data.Profunctor.Traversing import Fresnel.Iso import Sequoia.Monad.Run -- Value profunctor newtype e ∘ a = V (e -> a) deriving (Applicative, Category, Choice, Closed, Cochoice, Pro.Corepresentable, Costrong, Functor, Mapping, Monad, MonadRun, Profunctor, Co.Representable, Pro.Representable, Strong, Traversing) instance Distributive ((∘) e) where distribute = distributeRep collect = collectRep instance Sieve (∘) Identity where sieve = rmap Identity . flip (∘) instance Cosieve (∘) Identity where cosieve = lmap runIdentity . flip (∘) instance Value (∘) where inV = V e ∘ V v = v e -- Value abstraction class Profunctor v => Value v where inV :: (e -> a) -> v e a (∘) :: e -> (v e a -> a) infixl 9 ∘ -- Construction idV :: Value v => e `v` e idV = inV id constV :: Value v => a -> e `v` a constV = inV . const -- Coercion _V :: Iso (e ∘ a) (e' ∘ a') (e -> a) (e' -> a') _V = coerced
null
https://raw.githubusercontent.com/robrix/sequoia/1895ab90eb2fd7332ffb901fd8d932ad7637a695/src/Sequoia/Profunctor/Value.hs
haskell
* Value profunctor * Value abstraction * Construction * Coercion Value profunctor Value abstraction Construction Coercion
# LANGUAGE UndecidableInstances # module Sequoia.Profunctor.Value type (∘)(..) , Value(..) , idV , constV , _V ) where import Control.Category (Category) import Data.Distributive import Data.Functor.Identity import Data.Functor.Rep as Co import Data.Profunctor import Data.Profunctor.Rep as Pro import Data.Profunctor.Sieve import Data.Profunctor.Traversing import Fresnel.Iso import Sequoia.Monad.Run newtype e ∘ a = V (e -> a) deriving (Applicative, Category, Choice, Closed, Cochoice, Pro.Corepresentable, Costrong, Functor, Mapping, Monad, MonadRun, Profunctor, Co.Representable, Pro.Representable, Strong, Traversing) instance Distributive ((∘) e) where distribute = distributeRep collect = collectRep instance Sieve (∘) Identity where sieve = rmap Identity . flip (∘) instance Cosieve (∘) Identity where cosieve = lmap runIdentity . flip (∘) instance Value (∘) where inV = V e ∘ V v = v e class Profunctor v => Value v where inV :: (e -> a) -> v e a (∘) :: e -> (v e a -> a) infixl 9 ∘ idV :: Value v => e `v` e idV = inV id constV :: Value v => a -> e `v` a constV = inV . const _V :: Iso (e ∘ a) (e' ∘ a') (e -> a) (e' -> a') _V = coerced
990a0def9d9313b2a603cd687da5926b21294e2f3ef439d7ac74fb5a455f545a
mflatt/macro-dsl-tutorial
house-4.rkt
#lang racket (require "form-4.rkt") (form Box1HouseOwning [hasSoldHouse "Did you sell a house in 2010?" boolean] (when hasSoldHouse [sellingPrice "Price the house was sold for:" money] [privateDebt "Private debts for the sold house:" money] [valueResidue "Value residue:" money (- sellingPrice privateDebt)]))
null
https://raw.githubusercontent.com/mflatt/macro-dsl-tutorial/76e979d24c2e05bd1457e3a859645cddfee0cbd1/ql/house-4.rkt
racket
#lang racket (require "form-4.rkt") (form Box1HouseOwning [hasSoldHouse "Did you sell a house in 2010?" boolean] (when hasSoldHouse [sellingPrice "Price the house was sold for:" money] [privateDebt "Private debts for the sold house:" money] [valueResidue "Value residue:" money (- sellingPrice privateDebt)]))
2ebadca19488c8f7e0a562fa2d35f96b27b61c674c75f44887a82af021a48629
Chattered/proplcf
Bootstrap.hs
-- | Just enough theorems to get us going with conversions, proven using a tree -- notation that allows us to make assumptions. module Bootstrap where import Data.Foldable import Data.List import Utils | Proof terms with assumptions . In the notes , we write to denote a proof -- with conclusion P and assumptions Γ. Proofs are not guaranteed to be valid, and -- are pushed through the kernel via verify. data Proof a = Assume (Term a) | UseTheorem (Theorem a) | MP (Proof a) (Proof a) deriving Eq -- | sequent (Γ ⊢ P) yields (Γ, P) sequent :: (Ord a, Show a) => Proof a -> ([Term a], Term a) sequent (Assume a) = ([a], a) sequent (UseTheorem t) = ([], termOfTheorem t) sequent (MP pr pr') = let (asms,c) = sequent pr' in case sequent pr of (asms', p :=>: q) | p == c -> (nub $ sort $ asms ++ asms', q) | otherwise -> error ("MP: " ++ show [p :=>: q, c]) (_, imp) -> error ("MP: " ++ show [imp, c]) -- | concl (Γ ⊢ P) yields P concl :: (Ord a, Show a) => Proof a -> Term a concl = snd . sequent -- | concl (Γ ⊢ P) yields Γ assms :: (Ord a, Show a) => Proof a -> [Term a] assms = fst . sequent u :: Term () x :: Term Two y :: Term Two u = pure () (x,y) = (pure X, pure Y) -- | ⊢ P → P truthThm :: Theorem () truthThm = let step1 = inst2 u (truth ()) axiom1 step2 = inst3 u (truth ()) u axiom2 step3 = mp step2 step1 step4 = inst2 u u axiom1 in mp step3 step4 -- | discharge P (Γ ⊢ R) yields (Γ - {P} ⊢ P → R). This is mechanics of the deduction -- theorem. discharge :: (Ord a, Show a) => Term a -> Proof a -> Proof a discharge asm = d where d pr@(Assume t) | t == asm = UseTheorem (inst (const t) truthThm) | otherwise = MP (UseTheorem (inst2 (concl pr) asm axiom1)) pr d pr@(UseTheorem t) = MP (UseTheorem (inst2 (concl pr) asm axiom1)) pr d (MP imp p) = let p' = concl p in case concl imp of p'' :=>: r' | p' == p''-> MP (MP (UseTheorem (inst3 asm p' r' axiom2)) (d imp)) (d p) _ -> error ("Discharge MP:" ++ show [concl imp, p']) | Verify a proof . If there is only one assumption remaining , we automatically -- discharge it. verify :: (Ord a, Show a) => Proof a -> Theorem a verify proof = let v (UseTheorem t) = t v (MP pr pr') = mp (v pr) (v pr') in case assms proof of [] -> v proof [a] -> v (discharge a proof) as -> error errorMsg where errorMsg = "Undischarged assumptions:\n" ++ unlines [ " " ++ show a | a <- as ] -- | matchMPInst (P → Q) (Γ ⊢ P') inst -- attempts to match P with P', instantiates any remaining variables with inst, and -- then applies MP. matchMPInst :: (Eq a, Ord b, Show b) => Theorem a -> Proof b -> (a -> Term b) -> Proof b matchMPInst imp ant inst = let antT = concl ant in case termOfTheorem imp of p :=>: q -> case match p antT of Just insts -> MP (UseTheorem $ instM inst insts imp) ant _ -> error "MATCH MP: No match" _ -> error "MATCH MP" -- | matchMP without any instantiation. All theorems and proofs must be drawn from -- the same alphabet. matchMP :: (Ord a, Show a) => Theorem a -> Proof a -> Proof a matchMP imp ant = matchMPInst imp ant pure -- | ⊢ ¬P → P → ⊥ lemma1 :: Theorem Two lemma1 = let step1 = UseTheorem (inst2 (Not x) (Not (false Y)) axiom1) step2 = Assume (Not x) step3 = MP step1 step2 step4 = matchMP axiom3 step3 in verify step4 | ⊢ ( ¬P → ¬Q ) - > ( ¬P → Q ) → P -- | Mendelson's axiom3. mendelson :: Theorem Two mendelson = let step1 = Assume (Not x :=>: Not y) step2 = Assume (Not x :=>: y) step3 = Assume (Not x) step4 = MP step1 step3 step5 = MP step2 step3 step6 = matchMP lemma1 step4 step7 = MP step6 step5 step8 = discharge (Not x) step7 step9 = matchMP axiom3 step8 step10 = UseTheorem (inst1 y truthThm) step11 = MP step9 step10 step12 = discharge (concl step2) step11 in verify step12 -- | ⊢ ¬¬P → P dblNegElim :: Theorem () dblNegElim = let step1 = Assume (Not (Not u)) step2 = Assume (Not u :=>: Not (Not u)) step3 = MP (UseTheorem (inst2 u (Not u) mendelson)) step2 step4 = UseTheorem (inst1 (Not u) truthThm) step5 = MP step3 step4 step6 = discharge (concl step2) step5 step7 = UseTheorem (inst2 (Not (Not u)) (Not u) axiom1) step8 = MP step7 step1 step9 = MP step6 step8 in verify step9 -- | ⊢ P → ¬¬P dblNegIntro :: Theorem () dblNegIntro = let step1 = UseTheorem (inst1 (Not u) dblNegElim) step2 = MP (UseTheorem (inst2 (Not (Not u)) u axiom3)) step1 in verify step2 | ⊢ ( P → Q ) → ¬Q → ¬P mt :: Theorem Two mt = let step1 = Assume (x :=>: y) step2 = Assume (Not (Not x)) step3 = MP (UseTheorem (inst1 x dblNegElim)) step2 step4 = MP step1 step3 step5 = MP (UseTheorem (inst1 y dblNegIntro)) step4 step6 = discharge (concl step2) step5 step7 = matchMP axiom3 step6 in verify step7 -- | ⊢ P → ¬P → Q notElim :: Theorem Two notElim = let step1 = Assume x step2 = Assume (Not x) step3 = UseTheorem (inst2 x (Not y) axiom1) step4 = MP step3 step1 step5 = matchMP mt step4 step6 = MP step5 step2 step7 = MP (UseTheorem (inst1 y dblNegElim)) step6 step8 = discharge (concl step2) step7 in verify step8 | ⊢ ( P → Q ) → ( ¬P → Q ) → Q cases :: Theorem Two cases = let step1 = Assume (x :=>: y) step2 = Assume (Not x :=>: y) step3 = matchMP mt step1 step4 = matchMP mt step2 step5 = Assume (Not y) step6 = MP step4 step5 step7 = MP (UseTheorem (inst1 x dblNegElim)) step6 step8 = discharge (concl step5) step7 step9 = matchMP mendelson step3 step10 = MP step9 step8 step11 = discharge (concl step2) step10 in verify step11 | ⊢ ( P → ¬P ) → ¬P contra :: Theorem () contra = let step1 = Assume (u :=>: Not u) step2 = Assume u step3 = MP step1 step2 step4 = discharge (concl step2) step3 step5 = Assume (Not u) step6 = discharge (concl step5) step5 step7 = MP (UseTheorem (inst2 u (Not u) cases)) step4 step8 = MP step7 step6 in verify step8 | ⊢ ( ¬P → P ) → P contra2 :: Theorem () contra2 = let step1 = Assume (Not u :=>: u) step2 = Assume (Not u) step3 = MP step1 step2 step4 = matchMP dblNegIntro step3 step5 = discharge (concl step2) step4 step6 = matchMP contra step5 step7 = matchMP dblNegElim step6 in verify step7 -- | ⊢ P ∧ Q → P conj1 :: Theorem Two conj1 = let step1 = Assume x step2 = Assume (Not x) step3 = UseTheorem (inst2 x (Not y) notElim) step4 = MP step3 step1 step5 = MP step4 step2 step6 = discharge (concl step1) step5 step7 = UseTheorem (inst2 (concl step6) x notElim) step8 = MP step7 step6 step9 = Assume (x /\ y) step10 = MP step8 step9 step11 = discharge (concl step2) step10 step12 = MP (UseTheorem (inst1 x contra2)) step11 in verify step12 -- | ⊢ P ∧ Q → Q conj2 :: Theorem Two conj2 = let step1 = Assume x step2 = Assume (Not y) step3 = discharge (concl step1) step2 step4 = UseTheorem (inst2 (concl step3) y notElim) step5 = MP step4 step3 step6 = Assume (x /\ y) step7 = MP step5 step6 step8 = discharge (concl step2) step7 step9 = MP (UseTheorem (inst1 y contra2)) step8 in verify step9 -- | ⊢ P → Q → P ∧ Q conjI :: Theorem Two conjI = let step1 = Assume x step2 = Assume y step3 = Assume (x :=>: Not y) step4 = MP step3 step1 step5 = UseTheorem (inst2 (concl step2) (Not (concl step3)) notElim) step6 = MP step5 step2 step7 = MP step6 step4 step8 = discharge (concl step3) step7 step9 = MP (UseTheorem (inst1 (x :=>: Not y) contra)) step8 step10 = discharge (concl step2) step9 in verify step10 p :: Term Three q :: Term Three r :: Term Three (p,q,r) = (Var P, Var Q, Var R) | ⊢ ( P → Q → R ) ( Q → P → R ) swapT :: Theorem Three swapT = let step1 = UseTheorem lemma step2 = UseTheorem (inst3 q p r lemma) step3 = UseTheorem (inst2 (concl step1) (concl step2) conjI ) step4 = MP step3 step1 step5 = MP step4 step2 in verify step5 where lemma = let step1 = Assume p step2 = Assume q step3 = Assume (p :=>: q :=>: r) step4 = MP step3 step1 step5 = MP step4 step2 step6 = discharge (concl step1) step5 step7 = discharge (concl step2) step6 in verify step7 -- | ⊦ (P → Q → R) ↔ (P /\ Q → R) uncurry :: Theorem Three uncurry = let step1 = Assume (p :=>: q :=>: r) step2 = Assume (p /\ q) step3 = MP (UseTheorem (inst2 p q conj1)) step2 step4 = MP (UseTheorem (inst2 p q conj2)) step2 step5 = MP step1 step3 step6 = MP step5 step4 step7 = discharge (concl step2) step6 step8 = discharge (concl step1) step7 step9 = Assume (p /\ q :=>: r) step10 = Assume p step11 = Assume q step12 = matchMP (inst2 p q conjI) step10 step13 = MP step12 step11 step14 = MP step9 step13 step15 = discharge (concl step11) step14 step16 = discharge (concl step10) step15 step17 = discharge (concl step9) step16 step18 = UseTheorem (inst2 (concl step8) (concl step17) conjI) step19 = MP step18 step8 step20 = MP step19 step17 in verify step20 -- | ⊢ (X ↔ Y) → X → Y eqMP :: Theorem Two eqMP = let step1 = Assume (x <=> y) step2 = Assume x step3 = matchMP conj1 step1 step4 = MP step3 step2 step5 = discharge (concl step2) step4 in verify step5 -- | ⊢ (X ↔ X) reflEq :: Theorem () reflEq = let step1 = UseTheorem (inst2 (truth ()) (truth ()) conjI) step2 = UseTheorem truthThm step3 = MP step1 step2 step4 = MP step3 step2 in verify step4 | ⊢ ( X ↔ Y ) ( Y ↔ X ) symEq :: Theorem Two symEq = let step1 = UseTheorem lemma step2 = UseTheorem (inst2 y x lemma) step3 = UseTheorem (inst2 (concl (step1)) (concl (step2)) conjI) step4 = MP step3 step1 step5 = MP step4 step2 in verify step5 where lemma = let step1 = Assume (x <=> y) step2 = Assume y step3 = matchMP conj2 step1 step4 = MP step3 step2 step5 = discharge (concl step2) step4 step6 = Assume x step7 = matchMP conj1 step1 step8 = MP step7 step6 step9 = discharge (concl step6) step8 step10 = UseTheorem (inst2 (concl (step5)) (concl (step9)) conjI) step11 = MP step10 step5 step12 = MP step11 step9 in verify step12 -- | ⊢ (X ↔ Y) → (Y ↔ Z) → (X ↔ Z) trans :: Theorem Three trans = let step1 = Assume (p <=> q) step2 = Assume (q <=> r) step3 = Assume p step4 = MP (UseTheorem (inst2 (p :=>: q) (q :=>: p) conj1)) step1 step5 = MP (UseTheorem (inst2 (q :=>: r) (r :=>: q) conj1)) step2 step6 = MP step4 step3 step7 = MP step5 step6 step8 = discharge (concl step3) step7 step9 = Assume r step10 = MP (UseTheorem (inst2 (p :=>: q) (q :=>: p) conj2)) step1 step11 = MP (UseTheorem (inst2 (q :=>: r) (r :=>: q) conj2)) step2 step12 = MP step11 step9 step13 = MP step10 step12 step14 = discharge (concl step9) step13 step15 = UseTheorem (inst2 (concl step8) (concl step14) conjI) step16 = MP step15 step8 step17 = MP step16 step14 step18 = discharge (concl step2) step17 in verify step18 | reflect ( ⊢ ( X ↔ Y ) → φ(X ) → ψ(X ) ) yields ⊢ ( X ↔ Y ) → φ(X , Y ) ↔ ψ(X , Y ) reflect :: (Ord a, Show a) => Theorem a -> Theorem a reflect thm = let (xv:yv:_) = toList thm (x,y) = (pure xv, pure yv) step1 = UseTheorem thm step2 = UseTheorem (instM pure [(xv,y),(yv,x)] thm) step3 = Assume (x <=> y) step4 = MP step1 step3 step5 = UseTheorem (inst2 ((x <=> y) :=>: (y <=> x)) ((y <=> x) :=>: (x <=> y)) conj1) step6 = MP step5 (UseTheorem (inst2 x y symEq)) step7 = MP step6 step3 step8 = MP step2 step7 step9 = UseTheorem (inst2 (concl step4) (concl step8) conjI) step10 = MP step9 step4 step11 = MP step10 step8 in verify step11 -- | ⊢ (X ↔ Y) → (X → P ↔ Y → P) substLeft :: Theorem Three substLeft = reflect lemma where lemma = let step1 = Assume (p <=> q) step2 = Assume (p :=>: r) step3 = Assume q step4 = UseTheorem (inst2 (p :=>: q) (q :=>: p) conj2) step5 = MP step4 step1 step6 = MP step5 step3 step7 = MP step2 step6 step8 = discharge (concl step3) step7 step9 = discharge (concl step2) step8 in verify step9 -- | ⊢ (X ↔ Y) → (P → X ↔ P → Y) substRight :: Theorem Three substRight = reflect lemma where lemma = let step1 = Assume (p <=> q) step2 = Assume (r :=>: p) step3 = Assume r step4 = MP step2 step3 step5 = UseTheorem (inst2 (p :=>: q) (q :=>: p) conj1) step6 = MP step5 step1 step7 = MP step6 step4 step8 = discharge (concl step3) step7 step9 = discharge (concl step2) step8 in verify step9 | ⊢ ( X ↔ Y ) → ( ¬X ↔ ¬Y ) substNot :: Theorem Two substNot = reflect lemma where lemma = let step1 = Assume (x <=> y) step2 = matchMP conj2 step1 step3 = matchMP mt step2 in verify step3
null
https://raw.githubusercontent.com/Chattered/proplcf/dddfb1f5717207c3c65bc6a31619d04db3c14c09/Bootstrap.hs
haskell
| Just enough theorems to get us going with conversions, proven using a tree notation that allows us to make assumptions. with conclusion P and assumptions Γ. Proofs are not guaranteed to be valid, and are pushed through the kernel via verify. | sequent (Γ ⊢ P) yields (Γ, P) | concl (Γ ⊢ P) yields P | concl (Γ ⊢ P) yields Γ | ⊢ P → P | discharge P (Γ ⊢ R) yields (Γ - {P} ⊢ P → R). This is mechanics of the deduction theorem. discharge it. | matchMPInst (P → Q) (Γ ⊢ P') inst attempts to match P with P', instantiates any remaining variables with inst, and then applies MP. | matchMP without any instantiation. All theorems and proofs must be drawn from the same alphabet. | ⊢ ¬P → P → ⊥ | Mendelson's axiom3. | ⊢ ¬¬P → P | ⊢ P → ¬¬P | ⊢ P → ¬P → Q | ⊢ P ∧ Q → P | ⊢ P ∧ Q → Q | ⊢ P → Q → P ∧ Q | ⊦ (P → Q → R) ↔ (P /\ Q → R) | ⊢ (X ↔ Y) → X → Y | ⊢ (X ↔ X) | ⊢ (X ↔ Y) → (Y ↔ Z) → (X ↔ Z) | ⊢ (X ↔ Y) → (X → P ↔ Y → P) | ⊢ (X ↔ Y) → (P → X ↔ P → Y)
module Bootstrap where import Data.Foldable import Data.List import Utils | Proof terms with assumptions . In the notes , we write to denote a proof data Proof a = Assume (Term a) | UseTheorem (Theorem a) | MP (Proof a) (Proof a) deriving Eq sequent :: (Ord a, Show a) => Proof a -> ([Term a], Term a) sequent (Assume a) = ([a], a) sequent (UseTheorem t) = ([], termOfTheorem t) sequent (MP pr pr') = let (asms,c) = sequent pr' in case sequent pr of (asms', p :=>: q) | p == c -> (nub $ sort $ asms ++ asms', q) | otherwise -> error ("MP: " ++ show [p :=>: q, c]) (_, imp) -> error ("MP: " ++ show [imp, c]) concl :: (Ord a, Show a) => Proof a -> Term a concl = snd . sequent assms :: (Ord a, Show a) => Proof a -> [Term a] assms = fst . sequent u :: Term () x :: Term Two y :: Term Two u = pure () (x,y) = (pure X, pure Y) truthThm :: Theorem () truthThm = let step1 = inst2 u (truth ()) axiom1 step2 = inst3 u (truth ()) u axiom2 step3 = mp step2 step1 step4 = inst2 u u axiom1 in mp step3 step4 discharge :: (Ord a, Show a) => Term a -> Proof a -> Proof a discharge asm = d where d pr@(Assume t) | t == asm = UseTheorem (inst (const t) truthThm) | otherwise = MP (UseTheorem (inst2 (concl pr) asm axiom1)) pr d pr@(UseTheorem t) = MP (UseTheorem (inst2 (concl pr) asm axiom1)) pr d (MP imp p) = let p' = concl p in case concl imp of p'' :=>: r' | p' == p''-> MP (MP (UseTheorem (inst3 asm p' r' axiom2)) (d imp)) (d p) _ -> error ("Discharge MP:" ++ show [concl imp, p']) | Verify a proof . If there is only one assumption remaining , we automatically verify :: (Ord a, Show a) => Proof a -> Theorem a verify proof = let v (UseTheorem t) = t v (MP pr pr') = mp (v pr) (v pr') in case assms proof of [] -> v proof [a] -> v (discharge a proof) as -> error errorMsg where errorMsg = "Undischarged assumptions:\n" ++ unlines [ " " ++ show a | a <- as ] matchMPInst :: (Eq a, Ord b, Show b) => Theorem a -> Proof b -> (a -> Term b) -> Proof b matchMPInst imp ant inst = let antT = concl ant in case termOfTheorem imp of p :=>: q -> case match p antT of Just insts -> MP (UseTheorem $ instM inst insts imp) ant _ -> error "MATCH MP: No match" _ -> error "MATCH MP" matchMP :: (Ord a, Show a) => Theorem a -> Proof a -> Proof a matchMP imp ant = matchMPInst imp ant pure lemma1 :: Theorem Two lemma1 = let step1 = UseTheorem (inst2 (Not x) (Not (false Y)) axiom1) step2 = Assume (Not x) step3 = MP step1 step2 step4 = matchMP axiom3 step3 in verify step4 | ⊢ ( ¬P → ¬Q ) - > ( ¬P → Q ) → P mendelson :: Theorem Two mendelson = let step1 = Assume (Not x :=>: Not y) step2 = Assume (Not x :=>: y) step3 = Assume (Not x) step4 = MP step1 step3 step5 = MP step2 step3 step6 = matchMP lemma1 step4 step7 = MP step6 step5 step8 = discharge (Not x) step7 step9 = matchMP axiom3 step8 step10 = UseTheorem (inst1 y truthThm) step11 = MP step9 step10 step12 = discharge (concl step2) step11 in verify step12 dblNegElim :: Theorem () dblNegElim = let step1 = Assume (Not (Not u)) step2 = Assume (Not u :=>: Not (Not u)) step3 = MP (UseTheorem (inst2 u (Not u) mendelson)) step2 step4 = UseTheorem (inst1 (Not u) truthThm) step5 = MP step3 step4 step6 = discharge (concl step2) step5 step7 = UseTheorem (inst2 (Not (Not u)) (Not u) axiom1) step8 = MP step7 step1 step9 = MP step6 step8 in verify step9 dblNegIntro :: Theorem () dblNegIntro = let step1 = UseTheorem (inst1 (Not u) dblNegElim) step2 = MP (UseTheorem (inst2 (Not (Not u)) u axiom3)) step1 in verify step2 | ⊢ ( P → Q ) → ¬Q → ¬P mt :: Theorem Two mt = let step1 = Assume (x :=>: y) step2 = Assume (Not (Not x)) step3 = MP (UseTheorem (inst1 x dblNegElim)) step2 step4 = MP step1 step3 step5 = MP (UseTheorem (inst1 y dblNegIntro)) step4 step6 = discharge (concl step2) step5 step7 = matchMP axiom3 step6 in verify step7 notElim :: Theorem Two notElim = let step1 = Assume x step2 = Assume (Not x) step3 = UseTheorem (inst2 x (Not y) axiom1) step4 = MP step3 step1 step5 = matchMP mt step4 step6 = MP step5 step2 step7 = MP (UseTheorem (inst1 y dblNegElim)) step6 step8 = discharge (concl step2) step7 in verify step8 | ⊢ ( P → Q ) → ( ¬P → Q ) → Q cases :: Theorem Two cases = let step1 = Assume (x :=>: y) step2 = Assume (Not x :=>: y) step3 = matchMP mt step1 step4 = matchMP mt step2 step5 = Assume (Not y) step6 = MP step4 step5 step7 = MP (UseTheorem (inst1 x dblNegElim)) step6 step8 = discharge (concl step5) step7 step9 = matchMP mendelson step3 step10 = MP step9 step8 step11 = discharge (concl step2) step10 in verify step11 | ⊢ ( P → ¬P ) → ¬P contra :: Theorem () contra = let step1 = Assume (u :=>: Not u) step2 = Assume u step3 = MP step1 step2 step4 = discharge (concl step2) step3 step5 = Assume (Not u) step6 = discharge (concl step5) step5 step7 = MP (UseTheorem (inst2 u (Not u) cases)) step4 step8 = MP step7 step6 in verify step8 | ⊢ ( ¬P → P ) → P contra2 :: Theorem () contra2 = let step1 = Assume (Not u :=>: u) step2 = Assume (Not u) step3 = MP step1 step2 step4 = matchMP dblNegIntro step3 step5 = discharge (concl step2) step4 step6 = matchMP contra step5 step7 = matchMP dblNegElim step6 in verify step7 conj1 :: Theorem Two conj1 = let step1 = Assume x step2 = Assume (Not x) step3 = UseTheorem (inst2 x (Not y) notElim) step4 = MP step3 step1 step5 = MP step4 step2 step6 = discharge (concl step1) step5 step7 = UseTheorem (inst2 (concl step6) x notElim) step8 = MP step7 step6 step9 = Assume (x /\ y) step10 = MP step8 step9 step11 = discharge (concl step2) step10 step12 = MP (UseTheorem (inst1 x contra2)) step11 in verify step12 conj2 :: Theorem Two conj2 = let step1 = Assume x step2 = Assume (Not y) step3 = discharge (concl step1) step2 step4 = UseTheorem (inst2 (concl step3) y notElim) step5 = MP step4 step3 step6 = Assume (x /\ y) step7 = MP step5 step6 step8 = discharge (concl step2) step7 step9 = MP (UseTheorem (inst1 y contra2)) step8 in verify step9 conjI :: Theorem Two conjI = let step1 = Assume x step2 = Assume y step3 = Assume (x :=>: Not y) step4 = MP step3 step1 step5 = UseTheorem (inst2 (concl step2) (Not (concl step3)) notElim) step6 = MP step5 step2 step7 = MP step6 step4 step8 = discharge (concl step3) step7 step9 = MP (UseTheorem (inst1 (x :=>: Not y) contra)) step8 step10 = discharge (concl step2) step9 in verify step10 p :: Term Three q :: Term Three r :: Term Three (p,q,r) = (Var P, Var Q, Var R) | ⊢ ( P → Q → R ) ( Q → P → R ) swapT :: Theorem Three swapT = let step1 = UseTheorem lemma step2 = UseTheorem (inst3 q p r lemma) step3 = UseTheorem (inst2 (concl step1) (concl step2) conjI ) step4 = MP step3 step1 step5 = MP step4 step2 in verify step5 where lemma = let step1 = Assume p step2 = Assume q step3 = Assume (p :=>: q :=>: r) step4 = MP step3 step1 step5 = MP step4 step2 step6 = discharge (concl step1) step5 step7 = discharge (concl step2) step6 in verify step7 uncurry :: Theorem Three uncurry = let step1 = Assume (p :=>: q :=>: r) step2 = Assume (p /\ q) step3 = MP (UseTheorem (inst2 p q conj1)) step2 step4 = MP (UseTheorem (inst2 p q conj2)) step2 step5 = MP step1 step3 step6 = MP step5 step4 step7 = discharge (concl step2) step6 step8 = discharge (concl step1) step7 step9 = Assume (p /\ q :=>: r) step10 = Assume p step11 = Assume q step12 = matchMP (inst2 p q conjI) step10 step13 = MP step12 step11 step14 = MP step9 step13 step15 = discharge (concl step11) step14 step16 = discharge (concl step10) step15 step17 = discharge (concl step9) step16 step18 = UseTheorem (inst2 (concl step8) (concl step17) conjI) step19 = MP step18 step8 step20 = MP step19 step17 in verify step20 eqMP :: Theorem Two eqMP = let step1 = Assume (x <=> y) step2 = Assume x step3 = matchMP conj1 step1 step4 = MP step3 step2 step5 = discharge (concl step2) step4 in verify step5 reflEq :: Theorem () reflEq = let step1 = UseTheorem (inst2 (truth ()) (truth ()) conjI) step2 = UseTheorem truthThm step3 = MP step1 step2 step4 = MP step3 step2 in verify step4 | ⊢ ( X ↔ Y ) ( Y ↔ X ) symEq :: Theorem Two symEq = let step1 = UseTheorem lemma step2 = UseTheorem (inst2 y x lemma) step3 = UseTheorem (inst2 (concl (step1)) (concl (step2)) conjI) step4 = MP step3 step1 step5 = MP step4 step2 in verify step5 where lemma = let step1 = Assume (x <=> y) step2 = Assume y step3 = matchMP conj2 step1 step4 = MP step3 step2 step5 = discharge (concl step2) step4 step6 = Assume x step7 = matchMP conj1 step1 step8 = MP step7 step6 step9 = discharge (concl step6) step8 step10 = UseTheorem (inst2 (concl (step5)) (concl (step9)) conjI) step11 = MP step10 step5 step12 = MP step11 step9 in verify step12 trans :: Theorem Three trans = let step1 = Assume (p <=> q) step2 = Assume (q <=> r) step3 = Assume p step4 = MP (UseTheorem (inst2 (p :=>: q) (q :=>: p) conj1)) step1 step5 = MP (UseTheorem (inst2 (q :=>: r) (r :=>: q) conj1)) step2 step6 = MP step4 step3 step7 = MP step5 step6 step8 = discharge (concl step3) step7 step9 = Assume r step10 = MP (UseTheorem (inst2 (p :=>: q) (q :=>: p) conj2)) step1 step11 = MP (UseTheorem (inst2 (q :=>: r) (r :=>: q) conj2)) step2 step12 = MP step11 step9 step13 = MP step10 step12 step14 = discharge (concl step9) step13 step15 = UseTheorem (inst2 (concl step8) (concl step14) conjI) step16 = MP step15 step8 step17 = MP step16 step14 step18 = discharge (concl step2) step17 in verify step18 | reflect ( ⊢ ( X ↔ Y ) → φ(X ) → ψ(X ) ) yields ⊢ ( X ↔ Y ) → φ(X , Y ) ↔ ψ(X , Y ) reflect :: (Ord a, Show a) => Theorem a -> Theorem a reflect thm = let (xv:yv:_) = toList thm (x,y) = (pure xv, pure yv) step1 = UseTheorem thm step2 = UseTheorem (instM pure [(xv,y),(yv,x)] thm) step3 = Assume (x <=> y) step4 = MP step1 step3 step5 = UseTheorem (inst2 ((x <=> y) :=>: (y <=> x)) ((y <=> x) :=>: (x <=> y)) conj1) step6 = MP step5 (UseTheorem (inst2 x y symEq)) step7 = MP step6 step3 step8 = MP step2 step7 step9 = UseTheorem (inst2 (concl step4) (concl step8) conjI) step10 = MP step9 step4 step11 = MP step10 step8 in verify step11 substLeft :: Theorem Three substLeft = reflect lemma where lemma = let step1 = Assume (p <=> q) step2 = Assume (p :=>: r) step3 = Assume q step4 = UseTheorem (inst2 (p :=>: q) (q :=>: p) conj2) step5 = MP step4 step1 step6 = MP step5 step3 step7 = MP step2 step6 step8 = discharge (concl step3) step7 step9 = discharge (concl step2) step8 in verify step9 substRight :: Theorem Three substRight = reflect lemma where lemma = let step1 = Assume (p <=> q) step2 = Assume (r :=>: p) step3 = Assume r step4 = MP step2 step3 step5 = UseTheorem (inst2 (p :=>: q) (q :=>: p) conj1) step6 = MP step5 step1 step7 = MP step6 step4 step8 = discharge (concl step3) step7 step9 = discharge (concl step2) step8 in verify step9 | ⊢ ( X ↔ Y ) → ( ¬X ↔ ¬Y ) substNot :: Theorem Two substNot = reflect lemma where lemma = let step1 = Assume (x <=> y) step2 = matchMP conj2 step1 step3 = matchMP mt step2 in verify step3
a7d8e41d870799a0d9801fa4eb50d6d1ba4f72d0f9d2df83163489b71b0cc62b
tarides/dune-release
prompt.ml
type answer = Yes | No open Bos_setup.R.Infix let ask_yes_no f ~default_answer = let options : ('a, Format.formatter, unit, unit) format4 = match default_answer with Yes -> " [Y/n]" | No -> " [y/N]" in App_log.question (fun l -> f (fun ?header ?tags fmt -> l ?header ?tags (fmt ^^ options))) let rec loop_yes_no ~question ~default_answer = ask_yes_no question ~default_answer; match String.lowercase_ascii (read_line ()) with | "" when default_answer = Yes -> true | "" when default_answer = No -> false | "y" | "yes" -> true | "n" | "no" -> false | _ -> App_log.unhappy (fun l -> l "Please answer with \"y\" for yes, \"n\" for no or just hit enter \ for the default"); loop_yes_no ~question ~default_answer let confirm ~question ~yes ~default_answer = if yes then true else loop_yes_no ~question ~default_answer let confirm_or_abort ~question ~yes ~default_answer = if confirm ~question ~yes ~default_answer then Ok () else Error (`Msg "Aborting on user demand") let rec try_again ?(limit = 1) ~question ~yes ~default_answer f = match f () with | Ok x -> Ok x | Error (`Msg err) when limit > 0 -> App_log.unhappy (fun l -> l "%s" err); confirm_or_abort ~yes ~question ~default_answer >>= fun () -> try_again ~limit:(limit - 1) ~question ~yes ~default_answer f | Error x -> Error x let ask ~question ~default_answer = let pp_default fmt default = match default with | Some default -> Fmt.pf fmt "[press ENTER to use '%a']" Fmt.(styled `Bold string) default | None -> () in App_log.question (fun l -> l "%s%a" question pp_default default_answer) let rec loop ~question ~default_answer = ask ~question ~default_answer; let answer = match read_line () with | "" -> None | s -> Some s | exception End_of_file -> None in match (answer, default_answer) with | Some s, _ -> s | None, Some default -> default | None, None -> App_log.unhappy (fun l -> l "dune-release needs an answer to proceed."); loop ~question ~default_answer let user_input ?default_answer ~question () = loop ~question ~default_answer
null
https://raw.githubusercontent.com/tarides/dune-release/6bfed0f299b82c0931c78d4e216fd0efedff0673/lib/prompt.ml
ocaml
type answer = Yes | No open Bos_setup.R.Infix let ask_yes_no f ~default_answer = let options : ('a, Format.formatter, unit, unit) format4 = match default_answer with Yes -> " [Y/n]" | No -> " [y/N]" in App_log.question (fun l -> f (fun ?header ?tags fmt -> l ?header ?tags (fmt ^^ options))) let rec loop_yes_no ~question ~default_answer = ask_yes_no question ~default_answer; match String.lowercase_ascii (read_line ()) with | "" when default_answer = Yes -> true | "" when default_answer = No -> false | "y" | "yes" -> true | "n" | "no" -> false | _ -> App_log.unhappy (fun l -> l "Please answer with \"y\" for yes, \"n\" for no or just hit enter \ for the default"); loop_yes_no ~question ~default_answer let confirm ~question ~yes ~default_answer = if yes then true else loop_yes_no ~question ~default_answer let confirm_or_abort ~question ~yes ~default_answer = if confirm ~question ~yes ~default_answer then Ok () else Error (`Msg "Aborting on user demand") let rec try_again ?(limit = 1) ~question ~yes ~default_answer f = match f () with | Ok x -> Ok x | Error (`Msg err) when limit > 0 -> App_log.unhappy (fun l -> l "%s" err); confirm_or_abort ~yes ~question ~default_answer >>= fun () -> try_again ~limit:(limit - 1) ~question ~yes ~default_answer f | Error x -> Error x let ask ~question ~default_answer = let pp_default fmt default = match default with | Some default -> Fmt.pf fmt "[press ENTER to use '%a']" Fmt.(styled `Bold string) default | None -> () in App_log.question (fun l -> l "%s%a" question pp_default default_answer) let rec loop ~question ~default_answer = ask ~question ~default_answer; let answer = match read_line () with | "" -> None | s -> Some s | exception End_of_file -> None in match (answer, default_answer) with | Some s, _ -> s | None, Some default -> default | None, None -> App_log.unhappy (fun l -> l "dune-release needs an answer to proceed."); loop ~question ~default_answer let user_input ?default_answer ~question () = loop ~question ~default_answer
a79f90496d1a33ec5f2fb8c51f14a710a0192e2cf84720df2d64876132e49486
pirapira/coq2rust
modops.mli
(************************************************************************) 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 *) (************************************************************************) (*i*) open Names open Cic open Environ (*i*) (* Various operations on modules and module types *) val module_type_of_module : module_path option -> module_body -> module_type_body val is_functor : ('ty,'a) functorize -> bool val destr_functor : ('ty,'a) functorize -> MBId.t * 'ty * ('ty,'a) functorize (* adds a module and its components, but not the constraints *) val add_module : module_body -> env -> env val add_module_type : module_path -> module_type_body -> env -> env val strengthen : module_type_body -> module_path -> module_type_body val subst_and_strengthen : module_body -> module_path -> module_body val error_incompatible_modtypes : module_type_body -> module_type_body -> 'a val error_not_match : label -> structure_field_body -> 'a val error_with_module : unit -> 'a val error_no_such_label : label -> 'a val error_no_such_label_sub : label -> module_path -> 'a val error_not_a_constant : label -> 'a val error_not_a_module : label -> 'a
null
https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/checker/modops.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** i i Various operations on modules and module types adds a module and its components, but not the constraints
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Names open Cic open Environ val module_type_of_module : module_path option -> module_body -> module_type_body val is_functor : ('ty,'a) functorize -> bool val destr_functor : ('ty,'a) functorize -> MBId.t * 'ty * ('ty,'a) functorize val add_module : module_body -> env -> env val add_module_type : module_path -> module_type_body -> env -> env val strengthen : module_type_body -> module_path -> module_type_body val subst_and_strengthen : module_body -> module_path -> module_body val error_incompatible_modtypes : module_type_body -> module_type_body -> 'a val error_not_match : label -> structure_field_body -> 'a val error_with_module : unit -> 'a val error_no_such_label : label -> 'a val error_no_such_label_sub : label -> module_path -> 'a val error_not_a_constant : label -> 'a val error_not_a_module : label -> 'a
6229c91d8c97dab983456f88981c3c425cacfe9e7620a61579ebdbf4b54764f4
Chouser/spread
spread.clj
(ns us.chouser.spread (:require [clojure.core.reducers :as r])) (defn ^:private collect-expr "Conj expr onto the vector exprs, unless expr is a literal map that can be merged into a existing map at the end of the vector." [exprs expr] (if (and (map? (peek exprs)) (map? expr)) (conj (pop exprs) (merge (peek exprs) expr)) (conj exprs expr))) (defn ^:private first= [x expr] (and (seq? expr) (= x (first expr)))) (defn ^:private map-exprs "Convert the given macro invocation form into a vector of expressions that evaluate to maps. Bare symbols are converted to maps with one entry with a val of the symbol and a key converted by key-fn." [form key-fn] (loop [[k maybe-val :as args] (rest form), maps []] (cond (empty? args) maps (symbol? k) (recur (next args) (collect-expr maps {(key-fn k) k})) (first= `unquote-splicing k) (recur (next args) (collect-expr maps (second k))) (first= `unquote k) (recur (nnext args) (collect-expr maps {(second k) maybe-val})) (next args) (recur (nnext args) (collect-expr maps {k maybe-val})) :else (throw (ex-info (format "No value supplied for key %s" (pr-str k)) {:id ::no-value :key k :form form}))))) (defn ^:private build-map [form key-fn] (let [maps (map-exprs form key-fn) m (first maps)] (cond (next maps) `(into {} (r/mapcat seq [~@maps])) (map? m) m (seq maps) `(into {} ~m) :else {}))) (defmacro k. [& args] (build-map &form keyword)) (defmacro keys. [& args] (build-map &form keyword)) (defmacro strs. [& args] (build-map &form str)) (defmacro syms. [& args] (build-map &form (partial list 'quote)))
null
https://raw.githubusercontent.com/Chouser/spread/43f72129703eea7624d4d7fe1429367dcce7d289/src/us/chouser/spread.clj
clojure
(ns us.chouser.spread (:require [clojure.core.reducers :as r])) (defn ^:private collect-expr "Conj expr onto the vector exprs, unless expr is a literal map that can be merged into a existing map at the end of the vector." [exprs expr] (if (and (map? (peek exprs)) (map? expr)) (conj (pop exprs) (merge (peek exprs) expr)) (conj exprs expr))) (defn ^:private first= [x expr] (and (seq? expr) (= x (first expr)))) (defn ^:private map-exprs "Convert the given macro invocation form into a vector of expressions that evaluate to maps. Bare symbols are converted to maps with one entry with a val of the symbol and a key converted by key-fn." [form key-fn] (loop [[k maybe-val :as args] (rest form), maps []] (cond (empty? args) maps (symbol? k) (recur (next args) (collect-expr maps {(key-fn k) k})) (first= `unquote-splicing k) (recur (next args) (collect-expr maps (second k))) (first= `unquote k) (recur (nnext args) (collect-expr maps {(second k) maybe-val})) (next args) (recur (nnext args) (collect-expr maps {k maybe-val})) :else (throw (ex-info (format "No value supplied for key %s" (pr-str k)) {:id ::no-value :key k :form form}))))) (defn ^:private build-map [form key-fn] (let [maps (map-exprs form key-fn) m (first maps)] (cond (next maps) `(into {} (r/mapcat seq [~@maps])) (map? m) m (seq maps) `(into {} ~m) :else {}))) (defmacro k. [& args] (build-map &form keyword)) (defmacro keys. [& args] (build-map &form keyword)) (defmacro strs. [& args] (build-map &form str)) (defmacro syms. [& args] (build-map &form (partial list 'quote)))
43f187ce4a844730a800660baa3a06e79dce4f93c835d0716052f5904ef6358e
dwayne/haskell-programming
doesItCompile.hs
-- N.B. Yes = it squawks, No = it doesn't squawk i.e. it works 1 bigNum = (^) 5 $ 10 wahoo = bigNum $ 10 -- Yes, because we're trying to apply a number to a number is one possile fix 2 x = print y = print "woohoo!" z = x "hello world" -- No 3 a = (+) b = 5 c = b 10 d = c 200 Yes , because b is not a function that takes two args b = a -- is one possible fix 4 a = 12 + b b = 10000 * c Yes , because c is not defined ( assuming 3 was not defined in this file ) c = 1 -- is one possible fix
null
https://raw.githubusercontent.com/dwayne/haskell-programming/d08679e76cfd39985fa2ee3cd89d55c9aedfb531/ch5/doesItCompile.hs
haskell
N.B. Yes = it squawks, No = it doesn't squawk i.e. it works Yes, because we're trying to apply a number to a number No is one possible fix is one possible fix
1 bigNum = (^) 5 $ 10 wahoo = bigNum $ 10 is one possile fix 2 x = print y = print "woohoo!" z = x "hello world" 3 a = (+) b = 5 c = b 10 d = c 200 Yes , because b is not a function that takes two args 4 a = 12 + b b = 10000 * c Yes , because c is not defined ( assuming 3 was not defined in this file )
22b3cb165569fcb23e3d6b0e654b274eafaec6625089cb3cbd0f42a5bb118755
project-oak/hafnium-verification
cFrontend_errors.ml
* 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 . * 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! IStd module F = Format module L = Logging type exception_details = { msg: string ; position: Logging.ocaml_pos ; source_range: Clang_ast_t.source_range ; ast_node: string option } exception Unimplemented of exception_details exception IncorrectAssumption of exception_details exception Invalid_declaration let unimplemented position source_range ?ast_node fmt = F.kasprintf (fun msg -> raise (Unimplemented {msg; position; source_range; ast_node})) fmt let incorrect_assumption position source_range ?ast_node fmt = F.kasprintf (fun msg -> raise (IncorrectAssumption {msg; position; source_range; ast_node})) fmt let protect ~f ~recover ~pp_context (trans_unit_ctx : CFrontend_config.translation_unit_context) = let log_and_recover ~print fmt = recover () ; (if print then L.internal_error else L.(debug Capture Quiet)) ("%a@\n" ^^ fmt) pp_context () in try f () with Always keep going in case of known limitations of the frontend , crash otherwise ( by not catching the exception ) unless ` --keep - going ` was passed . Print errors we should fix ( t21762295 ) to the console . catching the exception) unless `--keep-going` was passed. Print errors we should fix (t21762295) to the console. *) | Unimplemented e -> ClangLogging.log_caught_exception trans_unit_ctx "Unimplemented" e.position e.source_range e.ast_node ; log_and_recover ~print:false "Unimplemented feature:@\n %s@\n" e.msg | IncorrectAssumption e -> (* FIXME(t21762295): we do not expect this to happen but it does *) ClangLogging.log_caught_exception trans_unit_ctx "IncorrectAssumption" e.position e.source_range e.ast_node ; log_and_recover ~print:true "Known incorrect assumption in the frontend: %s@\n" e.msg | exn -> let trace = Backtrace.get () in IExn.reraise_if exn ~f:(fun () -> L.internal_error "%a: %a@\n%!" pp_context () Exn.pp exn ; not Config.keep_going ) ; log_and_recover ~print:true "Frontend error: %a@\nBacktrace:@\n%s" Exn.pp exn (Backtrace.to_string trace)
null
https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/clang/cFrontend_errors.ml
ocaml
FIXME(t21762295): we do not expect this to happen but it does
* 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 . * 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! IStd module F = Format module L = Logging type exception_details = { msg: string ; position: Logging.ocaml_pos ; source_range: Clang_ast_t.source_range ; ast_node: string option } exception Unimplemented of exception_details exception IncorrectAssumption of exception_details exception Invalid_declaration let unimplemented position source_range ?ast_node fmt = F.kasprintf (fun msg -> raise (Unimplemented {msg; position; source_range; ast_node})) fmt let incorrect_assumption position source_range ?ast_node fmt = F.kasprintf (fun msg -> raise (IncorrectAssumption {msg; position; source_range; ast_node})) fmt let protect ~f ~recover ~pp_context (trans_unit_ctx : CFrontend_config.translation_unit_context) = let log_and_recover ~print fmt = recover () ; (if print then L.internal_error else L.(debug Capture Quiet)) ("%a@\n" ^^ fmt) pp_context () in try f () with Always keep going in case of known limitations of the frontend , crash otherwise ( by not catching the exception ) unless ` --keep - going ` was passed . Print errors we should fix ( t21762295 ) to the console . catching the exception) unless `--keep-going` was passed. Print errors we should fix (t21762295) to the console. *) | Unimplemented e -> ClangLogging.log_caught_exception trans_unit_ctx "Unimplemented" e.position e.source_range e.ast_node ; log_and_recover ~print:false "Unimplemented feature:@\n %s@\n" e.msg | IncorrectAssumption e -> ClangLogging.log_caught_exception trans_unit_ctx "IncorrectAssumption" e.position e.source_range e.ast_node ; log_and_recover ~print:true "Known incorrect assumption in the frontend: %s@\n" e.msg | exn -> let trace = Backtrace.get () in IExn.reraise_if exn ~f:(fun () -> L.internal_error "%a: %a@\n%!" pp_context () Exn.pp exn ; not Config.keep_going ) ; log_and_recover ~print:true "Frontend error: %a@\nBacktrace:@\n%s" Exn.pp exn (Backtrace.to_string trace)
2113a919ec19ea9e12a6207798a98ab96e71e0767870b2fefe23d4984f480508
mhaemmerle/grimoire
session.clj
(ns grimoire.session (:use [lamina core executor] grimoire.registry) (:import (org.jboss.netty.util HashedWheelTimer Timeout TimerTask) (java.util.concurrent TimeUnit)) (:require [grimoire.config :as config] [grimoire.node :as node] [grimoire.storage :as storage] [grimoire.user :as user] [grimoire.game :as game] [grimoire.session-store :as store] [grimoire.util :as util] [clojure.tools.logging :as log])) (defonce ^:private ^HashedWheelTimer hashed-wheel-timer (HashedWheelTimer.)) (defn get-expire-time [] (+ (System/currentTimeMillis) (:session-timeout config/system))) (defn- get-request-channel [user-id] (let [session (store/get user-id)] (:request-channel @session))) (defn- enqueue-event [user-id event] (enqueue (get-request-channel user-id) event)) (defn- close-request-channel [user-id] (let [session (store/get user-id) request-channel (:request-channel @session)] (close request-channel))) (defn get-event-channel [user-id] (let [session (store/get user-id) event-channel (:event-channel @session)] (if (or (nil? event-channel) (closed? event-channel)) (let [new-event-channel (channel)] (swap! session assoc :event-channel new-event-channel) new-event-channel) event-channel))) ;; {:keys [async?] :or {:async? false} :as options} (defmacro build-pipeline [& tasks] (let [channel (gensym 'channel)] `(fn [~channel value#] (run-pipeline value# {:error-handler #(error ~channel %)} ~@(map (fn [s] `(fn [event#] (task (~s ~channel event#)))) tasks))))) ;; (util/log-with-thread "generic-event-stage - start sleep") ( Thread / sleep 5000 ) ;; (util/log-with-thread "generic-event-stage - done sleeping") (defn- handle-game-event [{:keys [user-id payload args] :as event}] (let [session (store/get user-id) result-map (apply (game/get-update-function payload) (:state @session) args)] (swap! session assoc :state (:state result-map)) (assoc event :response (:response result-map)))) (declare periodic-save) (defn- handle-system-event [{:keys [user-id payload args] :as event}] (log/info "handle-system-event" event) (let [session (store/get user-id)] (case (:action payload) :periodic-save ((partial periodic-save session) args) nil))) (defn- handle-event [event] (log/info "handle-event" event) (case (:type event) :game (handle-game-event event) :system (handle-system-event event) event)) (defn- process-event [ch event] (log/info "process-event" ch event) (try (handle-event event) (catch Exception e (close ch) (ground ch) (log/error "pipeline_error" e) {:type :error :receiver (:receiver event) :error {:error (.getMessage e)}}))) (defn- reply [{:keys [type receiver response error] :as event}] (case type :game (if (:close? event) (enqueue-and-close receiver response) (enqueue receiver response)) :error (enqueue-and-close receiver error) event)) FIXME completely broken (defn- receive-in-order-with-pipeline [ch] (receive-in-order ch (fn [event] (run-pipeline event {:error-handler #(error ch %)} ;; watch for async tags #(process-event ch %) reply)))) (defn enqueue-game-event [user-id action response-channel] (if-let [session (store/get user-id)] (let [receiver (or response-channel (:event-channel @session)) request-channel (:request-channel @session)] (if (closed? request-channel) (enqueue-and-close receiver {:error "request_channel_is_closed"}) (enqueue request-channel {:type :game :user-id user-id :receiver receiver :close? true :reload-on-error? true :payload action :args nil}))) (throw (Exception. (format "session_not_running, args=[%s]" user-id))))) (defn- clean-timeouts [session] (doseq [timeout-type [:session-timeout :save-timeout]] (try (.cancel ^Timeout (timeout-type @session)) (catch Exception e (log/error "clean-timeouts" (.getMessage e))) (finally (swap! session assoc timeout-type nil))))) (defn- save-to-storage [user-id state] (log/info "save-to-storage" user-id) (let [user-json (user/to-json state)] (storage/put-data user-id user-json))) (defn- safe-close-channel [ch] (when-not (nil? ch) (try (close ch) (catch Exception e (log/error "safe-close-channel" (.getMessage e)))))) (defn- clean [user-id] (log/info "clean" user-id) (let [session (store/get user-id) channel-keys [:remote-channel :event-channel]] (doseq [channel-key channel-keys] (safe-close-channel (channel-key @session))) (clean-timeouts session) (store/remove user-id) (deregister *client* user-id)) nil) (defn- reset [user-id] ;; instead of resetting the session on the setup call ;; why not do it instantly? ) (defn- should-save? [state] (let [answer (> (:updated-at state) (:saved-at state))] (log/info "should-save?" answer) answer)) (defn- stop [user-id] (log/info "stop" user-id) (let [session (store/get user-id) state (:state @session) request-channel (:request-channel @session)] (close request-channel) (clean-timeouts session) (when (should-save? state) (try (save-to-storage user-id (assoc state :saved-at (System/currentTimeMillis))) (catch Exception e (log/error "stop" (.getMessage e) user-id)))) (clean user-id) nil)) (defn- get-timeout [delay timeout-fn] (let [timer-task (reify org.jboss.netty.util.TimerTask (^void run [this ^Timeout timeout] (timeout-fn timeout)))] (.newTimeout hashed-wheel-timer timer-task delay (TimeUnit/MILLISECONDS)))) (defn- renew-timeout [user-id delay timeout-type timeout-fn] (log/info "renew-timeout" user-id timeout-type timeout-fn) (let [session (store/get user-id)] (.cancel ^Timeout (timeout-type @session)) (swap! session assoc timeout-type (get-timeout delay (partial timeout-fn user-id))))) (defn- session-timeout-handler [user-id ^:Timeout timeout] (log/info "session-timeout-handler" user-id timeout) (future (stop user-id))) (declare save-timeout-handler) (defn- periodic-save [session user-id] (log/info "periodic-save" user-id) (let [new-state (assoc (:state @session) :saved-at (System/currentTimeMillis)) save-interval (config/system :save-interval)] (save-to-storage user-id new-state) (swap! session assoc :state new-state))) (defn- save-timeout-handler [user-id ^:Timeout timeout] (log/info "save-timeout-handler") (let [state (:state @(store/get user-id)) save-interval (config/system :save-interval)] (renew-timeout user-id save-interval :save-timeout save-timeout-handler) (when (should-save? state) (enqueue-event user-id {:type :system :user-id user-id :reload-on-error false :payload {:action :periodic-save} :args [user-id]})))) (defn handle-remote-message [msg] (log/info "handle-remote-message" msg)) (defn- start [user-id state] (log/info "start") (let [remote-channel (named-channel (keyword (str user-id)) nil) request-channel (channel) session-timeout (get-timeout (config/system :session-timeout) (partial session-timeout-handler user-id)) save-timeout (get-timeout (config/system :save-interval) (partial save-timeout-handler user-id)) session (atom {:state state :request-channel request-channel :event-channel nil :remote-channel remote-channel :session-timeout session-timeout :save-timeout save-timeout})] (receive-in-order-with-pipeline request-channel) (store/put user-id session) (receive-all remote-channel handle-remote-message)) nil) (defn- try-restart [user-id] (log/info "try-testart") (let [session (store/get user-id) request-channel (:request-channel @session)] (if (closed? request-channel) (let [new-request-channel (channel)] (receive-in-order-with-pipeline new-request-channel) (swap! session assoc :request-channel new-request-channel) (user/to-json (:state @session))) (throw (Exception. (format "session_still_running, args=[%s]" user-id)))))) (defn- load-user [user-id] (log/info "load-user") (let [result (storage/get-data user-id)] (if (nil? result) (user/new user-id) (user/from-json result)))) (defn- load-and-start [user-id] (log/info "load-and-start") (register *client* user-id (get-expire-time) (node/get-node-name)) (try (let [state (load-user user-id)] (start user-id state) (user/to-json state)) (catch Exception e (log/error "setup_failed" (.getMessage e) user-id) (clean user-id) (throw (Exception. (format "session_start_failed, args=[%s]" user-id)))))) (defn setup [user-id] (log/info "setup" user-id) (let [e (store/exists? user-id) r (registered? *client* user-id) l (local? *client* user-id)] (log/info "setup" e r l) (if (and e r l) (try-restart user-id) (load-and-start user-id)))) (defn run-bench [] (log/info "run-bench" (node/get-node-id)) ( let [ runs 1000 (let [runs 10 ;; global-start (* (node/get-node-id) runs)] global-start (* 0 runs)] ( Thread / sleep 5000 ) (dotimes [j runs] (let [batch-size 100 start (+ global-start (* j batch-size)) end (+ start batch-size) the-range (range start end)] (time (doseq [i the-range] (setup i)))) (log/info "num-sessions" (store/num-sessions)) ( Thread / sleep 1000 ) )))
null
https://raw.githubusercontent.com/mhaemmerle/grimoire/1fe3506838ec125888fe9241bb14ad57018c3835/src/grimoire/session.clj
clojure
{:keys [async?] :or {:async? false} :as options} (util/log-with-thread "generic-event-stage - start sleep") (util/log-with-thread "generic-event-stage - done sleeping") watch for async tags instead of resetting the session on the setup call why not do it instantly? global-start (* (node/get-node-id) runs)]
(ns grimoire.session (:use [lamina core executor] grimoire.registry) (:import (org.jboss.netty.util HashedWheelTimer Timeout TimerTask) (java.util.concurrent TimeUnit)) (:require [grimoire.config :as config] [grimoire.node :as node] [grimoire.storage :as storage] [grimoire.user :as user] [grimoire.game :as game] [grimoire.session-store :as store] [grimoire.util :as util] [clojure.tools.logging :as log])) (defonce ^:private ^HashedWheelTimer hashed-wheel-timer (HashedWheelTimer.)) (defn get-expire-time [] (+ (System/currentTimeMillis) (:session-timeout config/system))) (defn- get-request-channel [user-id] (let [session (store/get user-id)] (:request-channel @session))) (defn- enqueue-event [user-id event] (enqueue (get-request-channel user-id) event)) (defn- close-request-channel [user-id] (let [session (store/get user-id) request-channel (:request-channel @session)] (close request-channel))) (defn get-event-channel [user-id] (let [session (store/get user-id) event-channel (:event-channel @session)] (if (or (nil? event-channel) (closed? event-channel)) (let [new-event-channel (channel)] (swap! session assoc :event-channel new-event-channel) new-event-channel) event-channel))) (defmacro build-pipeline [& tasks] (let [channel (gensym 'channel)] `(fn [~channel value#] (run-pipeline value# {:error-handler #(error ~channel %)} ~@(map (fn [s] `(fn [event#] (task (~s ~channel event#)))) tasks))))) ( Thread / sleep 5000 ) (defn- handle-game-event [{:keys [user-id payload args] :as event}] (let [session (store/get user-id) result-map (apply (game/get-update-function payload) (:state @session) args)] (swap! session assoc :state (:state result-map)) (assoc event :response (:response result-map)))) (declare periodic-save) (defn- handle-system-event [{:keys [user-id payload args] :as event}] (log/info "handle-system-event" event) (let [session (store/get user-id)] (case (:action payload) :periodic-save ((partial periodic-save session) args) nil))) (defn- handle-event [event] (log/info "handle-event" event) (case (:type event) :game (handle-game-event event) :system (handle-system-event event) event)) (defn- process-event [ch event] (log/info "process-event" ch event) (try (handle-event event) (catch Exception e (close ch) (ground ch) (log/error "pipeline_error" e) {:type :error :receiver (:receiver event) :error {:error (.getMessage e)}}))) (defn- reply [{:keys [type receiver response error] :as event}] (case type :game (if (:close? event) (enqueue-and-close receiver response) (enqueue receiver response)) :error (enqueue-and-close receiver error) event)) FIXME completely broken (defn- receive-in-order-with-pipeline [ch] (receive-in-order ch (fn [event] (run-pipeline event {:error-handler #(error ch %)} #(process-event ch %) reply)))) (defn enqueue-game-event [user-id action response-channel] (if-let [session (store/get user-id)] (let [receiver (or response-channel (:event-channel @session)) request-channel (:request-channel @session)] (if (closed? request-channel) (enqueue-and-close receiver {:error "request_channel_is_closed"}) (enqueue request-channel {:type :game :user-id user-id :receiver receiver :close? true :reload-on-error? true :payload action :args nil}))) (throw (Exception. (format "session_not_running, args=[%s]" user-id))))) (defn- clean-timeouts [session] (doseq [timeout-type [:session-timeout :save-timeout]] (try (.cancel ^Timeout (timeout-type @session)) (catch Exception e (log/error "clean-timeouts" (.getMessage e))) (finally (swap! session assoc timeout-type nil))))) (defn- save-to-storage [user-id state] (log/info "save-to-storage" user-id) (let [user-json (user/to-json state)] (storage/put-data user-id user-json))) (defn- safe-close-channel [ch] (when-not (nil? ch) (try (close ch) (catch Exception e (log/error "safe-close-channel" (.getMessage e)))))) (defn- clean [user-id] (log/info "clean" user-id) (let [session (store/get user-id) channel-keys [:remote-channel :event-channel]] (doseq [channel-key channel-keys] (safe-close-channel (channel-key @session))) (clean-timeouts session) (store/remove user-id) (deregister *client* user-id)) nil) (defn- reset [user-id] ) (defn- should-save? [state] (let [answer (> (:updated-at state) (:saved-at state))] (log/info "should-save?" answer) answer)) (defn- stop [user-id] (log/info "stop" user-id) (let [session (store/get user-id) state (:state @session) request-channel (:request-channel @session)] (close request-channel) (clean-timeouts session) (when (should-save? state) (try (save-to-storage user-id (assoc state :saved-at (System/currentTimeMillis))) (catch Exception e (log/error "stop" (.getMessage e) user-id)))) (clean user-id) nil)) (defn- get-timeout [delay timeout-fn] (let [timer-task (reify org.jboss.netty.util.TimerTask (^void run [this ^Timeout timeout] (timeout-fn timeout)))] (.newTimeout hashed-wheel-timer timer-task delay (TimeUnit/MILLISECONDS)))) (defn- renew-timeout [user-id delay timeout-type timeout-fn] (log/info "renew-timeout" user-id timeout-type timeout-fn) (let [session (store/get user-id)] (.cancel ^Timeout (timeout-type @session)) (swap! session assoc timeout-type (get-timeout delay (partial timeout-fn user-id))))) (defn- session-timeout-handler [user-id ^:Timeout timeout] (log/info "session-timeout-handler" user-id timeout) (future (stop user-id))) (declare save-timeout-handler) (defn- periodic-save [session user-id] (log/info "periodic-save" user-id) (let [new-state (assoc (:state @session) :saved-at (System/currentTimeMillis)) save-interval (config/system :save-interval)] (save-to-storage user-id new-state) (swap! session assoc :state new-state))) (defn- save-timeout-handler [user-id ^:Timeout timeout] (log/info "save-timeout-handler") (let [state (:state @(store/get user-id)) save-interval (config/system :save-interval)] (renew-timeout user-id save-interval :save-timeout save-timeout-handler) (when (should-save? state) (enqueue-event user-id {:type :system :user-id user-id :reload-on-error false :payload {:action :periodic-save} :args [user-id]})))) (defn handle-remote-message [msg] (log/info "handle-remote-message" msg)) (defn- start [user-id state] (log/info "start") (let [remote-channel (named-channel (keyword (str user-id)) nil) request-channel (channel) session-timeout (get-timeout (config/system :session-timeout) (partial session-timeout-handler user-id)) save-timeout (get-timeout (config/system :save-interval) (partial save-timeout-handler user-id)) session (atom {:state state :request-channel request-channel :event-channel nil :remote-channel remote-channel :session-timeout session-timeout :save-timeout save-timeout})] (receive-in-order-with-pipeline request-channel) (store/put user-id session) (receive-all remote-channel handle-remote-message)) nil) (defn- try-restart [user-id] (log/info "try-testart") (let [session (store/get user-id) request-channel (:request-channel @session)] (if (closed? request-channel) (let [new-request-channel (channel)] (receive-in-order-with-pipeline new-request-channel) (swap! session assoc :request-channel new-request-channel) (user/to-json (:state @session))) (throw (Exception. (format "session_still_running, args=[%s]" user-id)))))) (defn- load-user [user-id] (log/info "load-user") (let [result (storage/get-data user-id)] (if (nil? result) (user/new user-id) (user/from-json result)))) (defn- load-and-start [user-id] (log/info "load-and-start") (register *client* user-id (get-expire-time) (node/get-node-name)) (try (let [state (load-user user-id)] (start user-id state) (user/to-json state)) (catch Exception e (log/error "setup_failed" (.getMessage e) user-id) (clean user-id) (throw (Exception. (format "session_start_failed, args=[%s]" user-id)))))) (defn setup [user-id] (log/info "setup" user-id) (let [e (store/exists? user-id) r (registered? *client* user-id) l (local? *client* user-id)] (log/info "setup" e r l) (if (and e r l) (try-restart user-id) (load-and-start user-id)))) (defn run-bench [] (log/info "run-bench" (node/get-node-id)) ( let [ runs 1000 (let [runs 10 global-start (* 0 runs)] ( Thread / sleep 5000 ) (dotimes [j runs] (let [batch-size 100 start (+ global-start (* j batch-size)) end (+ start batch-size) the-range (range start end)] (time (doseq [i the-range] (setup i)))) (log/info "num-sessions" (store/num-sessions)) ( Thread / sleep 1000 ) )))
508ef22350ac1afe69c42b29c77c3ca6c5fb018e91288d6ae3c87dbb699d0f5f
lucywang000/clj-statecharts
delayed.cljc
(ns statecharts.delayed (:require [clojure.walk :refer [postwalk]] [statecharts.utils :as u])) (defprotocol IScheduler (schedule [this fsm state event delay]) (unschedule [this fsm state event])) (defn scheduler? [x] (satisfies? IScheduler x)) (def path-placeholder [:<path>]) (defn delay-fn-id [d] (if (int? d) d #?(:cljs (aget d "name") :clj (str (type d))))) (defn generate-delayed-events [delay txs] (let [event [:fsm/delay path-placeholder ;; When the delay is a context function, after each ;; reload its value of change, causing the delayed ;; event can't find a match in :on keys. To cope with ;; this we extract the function name as the event ;; element instead. (delay-fn-id delay)]] ( def vd1 delay ) {:entry {:action :fsm/schedule-event :event-delay delay :event event} :exit {:action :fsm/unschedule-event :event event} :on [event (mapv #(dissoc % :delay) txs)]})) #_(generate-delayed-events 1000 [{:delay 1000 :target :s1 :guard :g1} {:delay 1000 :target :s2}]) #_(group-by odd? [1 2 3]) ;; statecharts.impl/T_DelayedTransition ;; => #_[:map [:entry] [:exit] [:on]] (defn derived-delay-info [delayed-transitions] (doseq [dt delayed-transitions] (assert (contains? dt :delay) (str "no :delay key found in" dt))) (->> delayed-transitions (group-by :delay) ;; TODO: the transition's entry/exit shall be grouped by delay, ;; otherwise a delay with multiple targets (e.g. with guards) ;; would result in multiple entry/exit events. (map (fn [[delay txs]] (generate-delayed-events delay txs))) (reduce (fn [accu curr] (merge-with conj accu curr)) {:entry [] :exit [] :on []}))) #_(derived-delay-info [:s1] [{:delay 1000 :target :s1 :guard :g1} {:delay 2000 :target :s2}]) (defn insert-delayed-transitions "Translate delayed transitions into internal entry/exit actions and transitions." [node] ;; node (let [after (:after node)] (if-not after node (let [{:keys [entry exit on]} (derived-delay-info after) on (into {} on) vconcat (fn [xs ys] (-> (concat xs ys) vec))] (-> node (update :entry vconcat entry) (update :exit vconcat exit) (update :on merge on)))))) (defn replace-path [path form] (if (nil? form) form (postwalk (fn [x] x (if (= x path-placeholder) path x)) form))) (defn replace-delayed-place-holder ([fsm] (replace-delayed-place-holder fsm [])) ([node path] (let [replace-path (partial replace-path path)] (cond-> node (:on node) (update :on replace-path) (:entry node) (update :entry replace-path) (:exit node) (update :exit replace-path) (:states node) (update :states (fn [states] (u/map-kv (fn [id node] [id (replace-delayed-place-holder node (conj path id))]) states))))))) #_(replace-delayed-place-holder {:on {[:fsm/delay [:<path>] 1000] :s2} :states {:s3 {:on {[:fsm/delay [:<path>] 1000] :s2} :entry [{:fsm/type :schedule-event :fsm/delay 1000 :fsm/event [:fsm/delay [:<path>] 1000]}]}} :entry [{:fsm/type :schedule-event :fsm/delay 1000 :fsm/event [:fsm/delay [:<path>] 1000]}]} [:root])
null
https://raw.githubusercontent.com/lucywang000/clj-statecharts/60a0ce554cf8f07d88962e2f1ba960ed64773080/src/statecharts/delayed.cljc
clojure
When the delay is a context function, after each reload its value of change, causing the delayed event can't find a match in :on keys. To cope with this we extract the function name as the event element instead. statecharts.impl/T_DelayedTransition => TODO: the transition's entry/exit shall be grouped by delay, otherwise a delay with multiple targets (e.g. with guards) would result in multiple entry/exit events. node
(ns statecharts.delayed (:require [clojure.walk :refer [postwalk]] [statecharts.utils :as u])) (defprotocol IScheduler (schedule [this fsm state event delay]) (unschedule [this fsm state event])) (defn scheduler? [x] (satisfies? IScheduler x)) (def path-placeholder [:<path>]) (defn delay-fn-id [d] (if (int? d) d #?(:cljs (aget d "name") :clj (str (type d))))) (defn generate-delayed-events [delay txs] (let [event [:fsm/delay path-placeholder (delay-fn-id delay)]] ( def vd1 delay ) {:entry {:action :fsm/schedule-event :event-delay delay :event event} :exit {:action :fsm/unschedule-event :event event} :on [event (mapv #(dissoc % :delay) txs)]})) #_(generate-delayed-events 1000 [{:delay 1000 :target :s1 :guard :g1} {:delay 1000 :target :s2}]) #_(group-by odd? [1 2 3]) #_[:map [:entry] [:exit] [:on]] (defn derived-delay-info [delayed-transitions] (doseq [dt delayed-transitions] (assert (contains? dt :delay) (str "no :delay key found in" dt))) (->> delayed-transitions (group-by :delay) (map (fn [[delay txs]] (generate-delayed-events delay txs))) (reduce (fn [accu curr] (merge-with conj accu curr)) {:entry [] :exit [] :on []}))) #_(derived-delay-info [:s1] [{:delay 1000 :target :s1 :guard :g1} {:delay 2000 :target :s2}]) (defn insert-delayed-transitions "Translate delayed transitions into internal entry/exit actions and transitions." [node] (let [after (:after node)] (if-not after node (let [{:keys [entry exit on]} (derived-delay-info after) on (into {} on) vconcat (fn [xs ys] (-> (concat xs ys) vec))] (-> node (update :entry vconcat entry) (update :exit vconcat exit) (update :on merge on)))))) (defn replace-path [path form] (if (nil? form) form (postwalk (fn [x] x (if (= x path-placeholder) path x)) form))) (defn replace-delayed-place-holder ([fsm] (replace-delayed-place-holder fsm [])) ([node path] (let [replace-path (partial replace-path path)] (cond-> node (:on node) (update :on replace-path) (:entry node) (update :entry replace-path) (:exit node) (update :exit replace-path) (:states node) (update :states (fn [states] (u/map-kv (fn [id node] [id (replace-delayed-place-holder node (conj path id))]) states))))))) #_(replace-delayed-place-holder {:on {[:fsm/delay [:<path>] 1000] :s2} :states {:s3 {:on {[:fsm/delay [:<path>] 1000] :s2} :entry [{:fsm/type :schedule-event :fsm/delay 1000 :fsm/event [:fsm/delay [:<path>] 1000]}]}} :entry [{:fsm/type :schedule-event :fsm/delay 1000 :fsm/event [:fsm/delay [:<path>] 1000]}]} [:root])
be2536c7c097035cf0993ac859694ebce5d2bfabb0120f45d78a8bbc72b48376
serokell/edna
Handlers.hs
SPDX - FileCopyrightText : 2021 > -- SPDX - License - Identifier : AGPL-3.0 - or - later module Edna.Web.Handlers ( ednaHandlers ) where import Servant.API.Generic (ToServant) import Servant.Server.Generic (AsServerT, genericServerT) import qualified Edna.Dashboard.Web.API as Dashboard import qualified Edna.Library.Web.API as Library import qualified Edna.Upload.Web.API as Upload import Edna.Setup (Edna) import Edna.Web.API (EdnaEndpoints(..)) type EdnaHandlers m = ToServant EdnaEndpoints (AsServerT m) -- | Server handler implementation for Edna API. ednaHandlers :: EdnaHandlers Edna ednaHandlers = genericServerT EdnaEndpoints { eeFileUploadEndpoints = Upload.fileUploadEndpoints , eeProjectEndpoints = Library.projectEndpoints , eeMethodologyEndpoints = Library.methodologyEndpoints , eeCompoundEndpoints = Library.compoundEndpoints , eeTargetEndpoints = Library.targetEndpoints , eeDashboardEndpoints = Dashboard.dashboardEndpoints }
null
https://raw.githubusercontent.com/serokell/edna/2ef945254631e469e8b1e9be6027367a9c593fa5/backend/src/Edna/Web/Handlers.hs
haskell
| Server handler implementation for Edna API.
SPDX - FileCopyrightText : 2021 > SPDX - License - Identifier : AGPL-3.0 - or - later module Edna.Web.Handlers ( ednaHandlers ) where import Servant.API.Generic (ToServant) import Servant.Server.Generic (AsServerT, genericServerT) import qualified Edna.Dashboard.Web.API as Dashboard import qualified Edna.Library.Web.API as Library import qualified Edna.Upload.Web.API as Upload import Edna.Setup (Edna) import Edna.Web.API (EdnaEndpoints(..)) type EdnaHandlers m = ToServant EdnaEndpoints (AsServerT m) ednaHandlers :: EdnaHandlers Edna ednaHandlers = genericServerT EdnaEndpoints { eeFileUploadEndpoints = Upload.fileUploadEndpoints , eeProjectEndpoints = Library.projectEndpoints , eeMethodologyEndpoints = Library.methodologyEndpoints , eeCompoundEndpoints = Library.compoundEndpoints , eeTargetEndpoints = Library.targetEndpoints , eeDashboardEndpoints = Dashboard.dashboardEndpoints }
c91a7bdebc81d17ff9a2a93e331d4d51bed2de980e358f2c5105d9f9adb5dbb0
hspec/hspec
ResultSpec.hs
# LANGUAGE RecordWildCards # module Test.Hspec.Core.Runner.ResultSpec (spec) where import Prelude () import Helper import Test.Hspec.Core.Format import Test.Hspec.Core.Runner.Result spec :: Spec spec = do describe "Summary" $ do let summary :: Summary summary = toSummary $ toSpecResult [item Success, item failure] it "can be deconstructed via accessor functions" $ do (summaryExamples &&& summaryFailures) summary `shouldBe` (2, 1) it "can be deconstructed via pattern matching" $ do let Summary examples failures = summary (examples, failures) `shouldBe` (2, 1) it "can be deconstructed via RecordWildCards" $ do let Summary{..} = summary (summaryExamples, summaryFailures) `shouldBe` (2, 1) describe "specResultSuccess" $ do context "when all spec items passed" $ do it "returns True" $ do specResultSuccess (toSpecResult [item Success]) `shouldBe` True context "with a failed spec item" $ do it "returns False" $ do specResultSuccess (toSpecResult [item Success, item failure]) `shouldBe` False context "with an empty result list" $ do it "returns True" $ do specResultSuccess (toSpecResult []) `shouldBe` True where failure = Failure Nothing NoReason item result = (([], ""), Item Nothing 0 "" result)
null
https://raw.githubusercontent.com/hspec/hspec/a344c428bb28d1a0787792d9befdbb8c8ec2381c/hspec-core/test/Test/Hspec/Core/Runner/ResultSpec.hs
haskell
# LANGUAGE RecordWildCards # module Test.Hspec.Core.Runner.ResultSpec (spec) where import Prelude () import Helper import Test.Hspec.Core.Format import Test.Hspec.Core.Runner.Result spec :: Spec spec = do describe "Summary" $ do let summary :: Summary summary = toSummary $ toSpecResult [item Success, item failure] it "can be deconstructed via accessor functions" $ do (summaryExamples &&& summaryFailures) summary `shouldBe` (2, 1) it "can be deconstructed via pattern matching" $ do let Summary examples failures = summary (examples, failures) `shouldBe` (2, 1) it "can be deconstructed via RecordWildCards" $ do let Summary{..} = summary (summaryExamples, summaryFailures) `shouldBe` (2, 1) describe "specResultSuccess" $ do context "when all spec items passed" $ do it "returns True" $ do specResultSuccess (toSpecResult [item Success]) `shouldBe` True context "with a failed spec item" $ do it "returns False" $ do specResultSuccess (toSpecResult [item Success, item failure]) `shouldBe` False context "with an empty result list" $ do it "returns True" $ do specResultSuccess (toSpecResult []) `shouldBe` True where failure = Failure Nothing NoReason item result = (([], ""), Item Nothing 0 "" result)
8cf63efde31b6df487efcc229802e4b2ec3247a033d7ca08d4afd0c09550f6c0
hexlet-basics/exercises-clojure
index.clj
;BEGIN (def result ((fn [x y] (/ (+ x y) 2)) 2 4)) (println result) ;END
null
https://raw.githubusercontent.com/hexlet-basics/exercises-clojure/c5e884e3e65573ef1ff466e5bd29f44dd3e366d5/modules/15-definitions/25-definitions-lambda-call/index.clj
clojure
BEGIN END
(def result ((fn [x y] (/ (+ x y) 2)) 2 4)) (println result)
db509b61454b6fb4f294a98b2d697a438fe65c8eddb966f079e0ab802351da9e
mirage/io-page
config.ml
open Mirage let io_page = foreign "Unikernel.Make" (console @-> job) let () = register "io-page" ~packages:[ package "io-page" ] [ io_page $ default_console ]
null
https://raw.githubusercontent.com/mirage/io-page/cc82c9cbd1e1caf7c40e12891b9e668d94b06b88/unikernel/config.ml
ocaml
open Mirage let io_page = foreign "Unikernel.Make" (console @-> job) let () = register "io-page" ~packages:[ package "io-page" ] [ io_page $ default_console ]
0838ae2ff07091db1f89ad7533f8a807076af3dfb5128da44e8ea9c1f9844a13
tidalcycles/tidal-fuzz-completer
listen.hs
import Sound.OSC.FD as O import Control.Concurrent import Control.Concurrent.MVar import qualified Network.Socket as N import qualified Sound.Tidal.Tempo as Tempo -listener/wiki -listener/wiki -} import Sound.Tidal.Ngrams import Sound.Tidal.Types import Sound.Tidal.Tokeniser import System.Environment data State = State {sLocal :: UDP, sRemote :: N.SockAddr } listenPort = 9999 remotePort = 8888 main :: IO () main = listen listen :: IO () listen = do -- listen (remote_addr:_) <- N.getAddrInfo Nothing (Just "127.0.0.1") Nothing local <- udpServer "127.0.0.1" listenPort putStrLn $ "Listening for OSC commands on port " ++ show listenPort putStrLn $ "Sending replies to port " ++ show remotePort let (N.SockAddrInet _ a) = N.addrAddress remote_addr remote = N.SockAddrInet (fromIntegral remotePort) a st = State local remote loop st where loop st = wait for , read and act on OSC message m <- recvMessage (sLocal st) st' <- act st m loop st' act :: State -> Maybe O.Message -> IO State act st (Just (Message "/subseq" [ASCII_String a_code])) = do r <- openUDP "127.0.0.1" remotePort putStrLn $ "Received osc message from atom" -- sendMessage r $ Message "/reply" [string "['jux', 'rev', 'sound', '\"bd sn\"']"] -- sendMessage r $ Message "/reply" [string "[\"jux\", \"rev\", \"sound\", \"'bd sn cp hh'\"]"] -- sendMessage r $ Message "/reply" [string "[\" (#) (every (fast '3 4 5' 1) rev $ jux $ rev $ sound $ 'bd sn cp hh'\"]"] codeOut <- returnFunc let replace = map (\c -> if c=='\"' then '\''; else c) putStrLn $ " [ \ " " + + replace ( sCode codeOut ) + + " \ " ] " sendMessage r $ Message "/reply" [string ("[\"" ++ replace (sCode codeOut) ++ "\"]")] do O.sendTo ( sLocal st ) ( O.p_message " /pong " [ ] ) ( sRemote st ) return st act st Nothing = do putStrLn "not a message?" return st act st (Just m) = do putStrLn $ "Unhandled message: " ++ show m return st returnFunc = do aha <- Sound.Tidal.Types.wWalk $ Sig [] $ Pattern Osc let replace = map ( - > if c=='\ " ' then ' \ '' ; else c ) return aha sCode :: Code -> String sCode = show replaceChar i o = map (\c -> if c==i then o; else c)
null
https://raw.githubusercontent.com/tidalcycles/tidal-fuzz-completer/82fde69132fa234b7c9ca9b243c153e44fbfad46/src/listen.hs
haskell
listen sendMessage r $ Message "/reply" [string "['jux', 'rev', 'sound', '\"bd sn\"']"] sendMessage r $ Message "/reply" [string "[\"jux\", \"rev\", \"sound\", \"'bd sn cp hh'\"]"] sendMessage r $ Message "/reply" [string "[\" (#) (every (fast '3 4 5' 1) rev $ jux $ rev $ sound $ 'bd sn cp hh'\"]"]
import Sound.OSC.FD as O import Control.Concurrent import Control.Concurrent.MVar import qualified Network.Socket as N import qualified Sound.Tidal.Tempo as Tempo -listener/wiki -listener/wiki -} import Sound.Tidal.Ngrams import Sound.Tidal.Types import Sound.Tidal.Tokeniser import System.Environment data State = State {sLocal :: UDP, sRemote :: N.SockAddr } listenPort = 9999 remotePort = 8888 main :: IO () main = listen listen :: IO () (remote_addr:_) <- N.getAddrInfo Nothing (Just "127.0.0.1") Nothing local <- udpServer "127.0.0.1" listenPort putStrLn $ "Listening for OSC commands on port " ++ show listenPort putStrLn $ "Sending replies to port " ++ show remotePort let (N.SockAddrInet _ a) = N.addrAddress remote_addr remote = N.SockAddrInet (fromIntegral remotePort) a st = State local remote loop st where loop st = wait for , read and act on OSC message m <- recvMessage (sLocal st) st' <- act st m loop st' act :: State -> Maybe O.Message -> IO State act st (Just (Message "/subseq" [ASCII_String a_code])) = do r <- openUDP "127.0.0.1" remotePort putStrLn $ "Received osc message from atom" codeOut <- returnFunc let replace = map (\c -> if c=='\"' then '\''; else c) putStrLn $ " [ \ " " + + replace ( sCode codeOut ) + + " \ " ] " sendMessage r $ Message "/reply" [string ("[\"" ++ replace (sCode codeOut) ++ "\"]")] do O.sendTo ( sLocal st ) ( O.p_message " /pong " [ ] ) ( sRemote st ) return st act st Nothing = do putStrLn "not a message?" return st act st (Just m) = do putStrLn $ "Unhandled message: " ++ show m return st returnFunc = do aha <- Sound.Tidal.Types.wWalk $ Sig [] $ Pattern Osc let replace = map ( - > if c=='\ " ' then ' \ '' ; else c ) return aha sCode :: Code -> String sCode = show replaceChar i o = map (\c -> if c==i then o; else c)
098e6b3ce80732b99b1897a017a93dce144c20e5336495d7a50db8ebe30acc41
scymtym/architecture.builder-protocol
mixins.lisp
;;;; mixins.lisp --- Mixin classes for builder classes. ;;;; Copyright ( C ) 2016 , 2018 , 2019 Jan Moringen ;;;; Author : < > (cl:in-package #:architecture.builder-protocol) ;;; `delegating-mixin' (defclass delegating-mixin () ((target :initarg :target :reader target :accessor %target :documentation "Stores the builder to which `make-node', `relate', etc. calls should be delegated.")) (:default-initargs :target (error "~@<Missing required initarg for class ~S: ~S.~@:>" 'delegating-mixin :target)) (:documentation "Intended to be mixed into builder classes that delegate certain operations to a \"target\" builder.")) ;;; `forwarding-mixin' ;;; ;;; A delegating builder mixin that forwards all (un)builder protocol ;;; calls to the target builder. (defclass forwarding-mixin (delegating-mixin) () (:documentation "Intended to be mixed into builder classes that delegate all operations to a \"target\" builder.")) ;;; `prepare' and `wrap' cannot be delegated naively all other methods ;;; can. (defmethod prepare ((builder forwarding-mixin)) ;; The target builder's `prepare' method is allowed to return a new ;; builder object. (let* ((target (target builder)) (new-target (prepare target))) (unless (eq new-target target) (setf (%target builder) new-target))) builder) (defmethod wrap ((builder forwarding-mixin) (function t)) ;; Let the target builder perform its wrapping action but make sure ;; to perform an "inner" wrapping using BUILDER. Otherwise, ;; intercepting `make-node', `relate', etc. calls wouldn't work if ;; the target builder, for example, binds `*builder*'. (let ((target (target builder))) (wrap target (lambda (new-target) (unless (eq new-target target) (setf (%target builder) new-target)) (values-list (call-next-method)))))) (macrolet ((define-delegation (name (&rest args)) (let* ((&rest-position (position '&rest args)) (args1 (subseq args 0 &rest-position)) (rest (when &rest-position (nth (1+ &rest-position) args))) (rest-args (when &rest-position (subseq args &rest-position))) (specializers (map 'list (rcurry #'list 't) args1))) `(defmethod ,name ((builder forwarding-mixin) ,@specializers ,@rest-args) ,(if rest `(apply #',name (target builder) ,@args1 ,rest) `(,name (target builder) ,@args1)))))) (define-delegation finish (result)) (define-delegation make-node (kind &rest initargs &key &allow-other-keys)) (define-delegation finish-node (kind node)) (define-delegation relate (relation left right &rest args &key &allow-other-keys)) (define-delegation node-kind (node)) (define-delegation node-initargs (node)) (define-delegation node-relations (node)) (define-delegation node-relation (relation node)) (define-delegation walk-nodes (function root))) ;;; Delayed nodes represent calls to `make-node', `relate', ;;; etc. Delayed nodes can be constructed in any order (parents before ;;; children, children before parents or some combination). The nodes ;;; form a tree that can be walked in an arbitrary order. (defstruct (argumented (:constructor nil) (:predicate nil) (:copier nil)) (arguments () :type list :read-only t)) (defstruct (delayed-node (:include argumented) (:constructor make-delayed-node (kind arguments)) (:copier nil)) (kind nil :read-only t) (relations () :type list)) (defstruct (delayed-relation (:include argumented) (:constructor make-delayed-relation (kind node arguments)) (:copier nil)) (kind nil :read-only t) (node nil :read-only t)) ;;; `delaying-mixin' ;;; ;;; Builds a complete tree of delayed nodes. (defclass delaying-mixin () () (:documentation "This class is intended to be mixed into builder classes that have to construct a tree of delayed nodes before doing their respective actual processing.")) (defmethod make-node ((builder delaying-mixin) (kind t) &rest initargs &key) (make-delayed-node kind initargs)) (defmethod relate ((builder delaying-mixin) (relation t) (left t) (right t) &rest args &key) (push (make-delayed-relation relation right args) (delayed-node-relations left)) left) ;;; `order-forcing-mixin' (defclass order-forcing-mixin (delegating-mixin) () (:documentation "This class is intended to be mixed into builder classes that have to process nodes in a particular order. In combination with `delaying-mixin', this makes the builder independent of the order of the original `make-node' and `relate' calls.")) (defmethod finish ((builder order-forcing-mixin) (result cons)) (let ((target (target builder)) (visit (builder-visit-function builder))) (with-builder (target) (apply #'values (funcall visit (first result)) (rest result)))))
null
https://raw.githubusercontent.com/scymtym/architecture.builder-protocol/a48abddff7f6e0779b89666f46ab87ef918488f0/src/mixins.lisp
lisp
mixins.lisp --- Mixin classes for builder classes. `delegating-mixin' `forwarding-mixin' A delegating builder mixin that forwards all (un)builder protocol calls to the target builder. `prepare' and `wrap' cannot be delegated naively all other methods can. The target builder's `prepare' method is allowed to return a new builder object. Let the target builder perform its wrapping action but make sure to perform an "inner" wrapping using BUILDER. Otherwise, intercepting `make-node', `relate', etc. calls wouldn't work if the target builder, for example, binds `*builder*'. Delayed nodes represent calls to `make-node', `relate', etc. Delayed nodes can be constructed in any order (parents before children, children before parents or some combination). The nodes form a tree that can be walked in an arbitrary order. `delaying-mixin' Builds a complete tree of delayed nodes. `order-forcing-mixin'
Copyright ( C ) 2016 , 2018 , 2019 Jan Moringen Author : < > (cl:in-package #:architecture.builder-protocol) (defclass delegating-mixin () ((target :initarg :target :reader target :accessor %target :documentation "Stores the builder to which `make-node', `relate', etc. calls should be delegated.")) (:default-initargs :target (error "~@<Missing required initarg for class ~S: ~S.~@:>" 'delegating-mixin :target)) (:documentation "Intended to be mixed into builder classes that delegate certain operations to a \"target\" builder.")) (defclass forwarding-mixin (delegating-mixin) () (:documentation "Intended to be mixed into builder classes that delegate all operations to a \"target\" builder.")) (defmethod prepare ((builder forwarding-mixin)) (let* ((target (target builder)) (new-target (prepare target))) (unless (eq new-target target) (setf (%target builder) new-target))) builder) (defmethod wrap ((builder forwarding-mixin) (function t)) (let ((target (target builder))) (wrap target (lambda (new-target) (unless (eq new-target target) (setf (%target builder) new-target)) (values-list (call-next-method)))))) (macrolet ((define-delegation (name (&rest args)) (let* ((&rest-position (position '&rest args)) (args1 (subseq args 0 &rest-position)) (rest (when &rest-position (nth (1+ &rest-position) args))) (rest-args (when &rest-position (subseq args &rest-position))) (specializers (map 'list (rcurry #'list 't) args1))) `(defmethod ,name ((builder forwarding-mixin) ,@specializers ,@rest-args) ,(if rest `(apply #',name (target builder) ,@args1 ,rest) `(,name (target builder) ,@args1)))))) (define-delegation finish (result)) (define-delegation make-node (kind &rest initargs &key &allow-other-keys)) (define-delegation finish-node (kind node)) (define-delegation relate (relation left right &rest args &key &allow-other-keys)) (define-delegation node-kind (node)) (define-delegation node-initargs (node)) (define-delegation node-relations (node)) (define-delegation node-relation (relation node)) (define-delegation walk-nodes (function root))) (defstruct (argumented (:constructor nil) (:predicate nil) (:copier nil)) (arguments () :type list :read-only t)) (defstruct (delayed-node (:include argumented) (:constructor make-delayed-node (kind arguments)) (:copier nil)) (kind nil :read-only t) (relations () :type list)) (defstruct (delayed-relation (:include argumented) (:constructor make-delayed-relation (kind node arguments)) (:copier nil)) (kind nil :read-only t) (node nil :read-only t)) (defclass delaying-mixin () () (:documentation "This class is intended to be mixed into builder classes that have to construct a tree of delayed nodes before doing their respective actual processing.")) (defmethod make-node ((builder delaying-mixin) (kind t) &rest initargs &key) (make-delayed-node kind initargs)) (defmethod relate ((builder delaying-mixin) (relation t) (left t) (right t) &rest args &key) (push (make-delayed-relation relation right args) (delayed-node-relations left)) left) (defclass order-forcing-mixin (delegating-mixin) () (:documentation "This class is intended to be mixed into builder classes that have to process nodes in a particular order. In combination with `delaying-mixin', this makes the builder independent of the order of the original `make-node' and `relate' calls.")) (defmethod finish ((builder order-forcing-mixin) (result cons)) (let ((target (target builder)) (visit (builder-visit-function builder))) (with-builder (target) (apply #'values (funcall visit (first result)) (rest result)))))
d7c0ee118bcd9e45a9a8654c368669b8da9ed0dea1d0b64eb59f8ac761e62a52
modular-macros/ocaml-macros
t04.ml
(** Testing display of inline record. @test_types_display *) module A = struct type a = A of {lbl:int} end module type E = sig exception E of {lbl:int} end module E_bis= struct exception E of {lbl:int} end
null
https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/testsuite/tests/tool-ocamldoc/t04.ml
ocaml
* Testing display of inline record. @test_types_display
module A = struct type a = A of {lbl:int} end module type E = sig exception E of {lbl:int} end module E_bis= struct exception E of {lbl:int} end
b2a98cf675fb41c028f30d23afef491f255125d1a292d0d017fe0ee87c12eb36
jasongilman/crdt-edit
runner.clj
(ns crdt-edit.runner (:require [crdt-edit.system :as system] [clojure.tools.cli :as cli]) (:import java.net.InetAddress) (:gen-class)) (def cli-options ;; An option with a required argument [["-p" "--port PORT" "Port number" :id :port :default 3000 :parse-fn #(Integer/parseInt %) :validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]] ["-i" "--ip-address IP" "Current IP Address" :id :ip-address] ["-s" "--site SITE" "Site" :id :site :default (keyword (.getHostAddress (InetAddress/getLocalHost))) :parse-fn keyword] ;; A boolean option defaulting to nil ["-h" "--help"]]) (defn -main [& args] (let [{{:keys [port site ip-address]} :options} (cli/parse-opts args cli-options) system (system/start (system/create site port ip-address []))] (println "Running...")))
null
https://raw.githubusercontent.com/jasongilman/crdt-edit/2b8126632bc7f204cb3979e9c51f7ab363704f29/src/crdt_edit/runner.clj
clojure
An option with a required argument A boolean option defaulting to nil
(ns crdt-edit.runner (:require [crdt-edit.system :as system] [clojure.tools.cli :as cli]) (:import java.net.InetAddress) (:gen-class)) (def cli-options [["-p" "--port PORT" "Port number" :id :port :default 3000 :parse-fn #(Integer/parseInt %) :validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]] ["-i" "--ip-address IP" "Current IP Address" :id :ip-address] ["-s" "--site SITE" "Site" :id :site :default (keyword (.getHostAddress (InetAddress/getLocalHost))) :parse-fn keyword] ["-h" "--help"]]) (defn -main [& args] (let [{{:keys [port site ip-address]} :options} (cli/parse-opts args cli-options) system (system/start (system/create site port ip-address []))] (println "Running...")))
7176ccfc7aeab6f41e3037191107e7ed08a7e2d36d7f903222ed014fd14a1970
bitblaze-fuzzball/fuzzball
options_solver.mli
Copyright ( C ) BitBlaze , 2009 - 2011 , and copyright ( C ) 2010 Ensighta Security Inc. All rights reserved . Copyright (C) BitBlaze, 2009-2011, and copyright (C) 2010 Ensighta Security Inc. All rights reserved. *) val solver_cmdline_opts : (string * Arg.spec * string) list val solvers_table : (string, (string -> Query_engine.query_engine option)) Hashtbl.t val construct_solver : string -> Query_engine.query_engine val apply_solver_cmdline_opts : Fragment_machine.fragment_machine -> unit
null
https://raw.githubusercontent.com/bitblaze-fuzzball/fuzzball/b9a617b45e68fa732f1357fedc08a2a10f87a62c/execution/options_solver.mli
ocaml
Copyright ( C ) BitBlaze , 2009 - 2011 , and copyright ( C ) 2010 Ensighta Security Inc. All rights reserved . Copyright (C) BitBlaze, 2009-2011, and copyright (C) 2010 Ensighta Security Inc. All rights reserved. *) val solver_cmdline_opts : (string * Arg.spec * string) list val solvers_table : (string, (string -> Query_engine.query_engine option)) Hashtbl.t val construct_solver : string -> Query_engine.query_engine val apply_solver_cmdline_opts : Fragment_machine.fragment_machine -> unit
3658664a10b2fdeb7e58fd59b539a78320d573017ef9415c448e73c53d60bb4f
albertoruiz/easyVision
GNS.hs
module Contours.GNS( GN, prepareGNS, prepareGNP, stepGN, stepGN', featF, mktP, featRS) where import Util.Geometry import Contours.Base import Contours.Fourier import Util.Homogeneous import Numeric.LinearAlgebra import Numeric.LinearAlgebra.Util(col,(?),(¿),diagl) import Util.Misc(rotateLeft,degree) import Vision(kgen , projectionAt',cameraModelOrigin ) import Util.Rotation import Numeric.GSL.Differentiation import Contours.Resample featF :: Double -> (Int -> Complex Double) -> (Int -> Double) featF a fou = h where g = normalizeStart ((*cis a) . fou) h k = (sel . g) j where j = sgn * ((k + 2) `div` 4) sel | odd k = imagPart | otherwise = realPart sgn | (k+2) `mod` 4 > 1 = -1 | otherwise = 1 feat :: Polyline -> Int -> Double feat cont = featF 0 fou where fou = fourierPL cont type GN = (Vector Double, Matrix Double, Polyline -> Vector Double) prepareGNS :: Int -> Polyline -> GN prepareGNS n prt = (f0,j0,fun) where fun tgt = fromList (map (feat tgt) dimfeat) f0 = fun prt trans k xs = feat (transPol (mktP xs) prt) k j0 = jacobian (map trans dimfeat) zerot dimfeat = [0..n] zerot = replicate 8 0 stepGN :: GN -> Polyline -> (Polyline,Double) stepGN (f0,j0,fun) tgt = (res, norm2 err) where err = fun tgt - f0 dx = (trans j0 <> j0) <\> (trans j0 <> err) res = transPol (inv (mktP (toList dx))) tgt type M = Matrix Double type V = Vector Double stepGN' :: GN -> (Polyline, M, V, Double) -> (Polyline, M, V, Double) stepGN' (f0,j0,fun) (t,h,err,_) = (t', h', err', norm2 err') where dx = (trans j0 <> j0) <\> (trans j0 <> err) dh = mktP (toList dx) t' = transPol (inv dh) t h' = h <> dh err' = fun t' - f0 -------------------------------------------------------------------------------- jacobian :: [[Double] -> Double] -> [Double] -> Matrix Double jacobian fs xs = fromLists $ map (\f -> gradient f xs) fs gradient f v = [partialDerivative k f v | k <- [0 .. length v -1]] partialDerivative n f v = fst (derivCentral 0.01 g (v!!n)) where g x = f (concat [a,x:b]) (a,_:b) = splitAt n v -------------------------------------------------------------------------------- mktP [a,d,c,b,e,f,g,h] = (3><3) [ 1+a, c, e, b , 1+d, f, g , h, 1] :: Matrix Double -------------------------------------------------------------------------------- refinePose : : Int - > Matrix Double - > Polyline - > Polyline - > [ Matrix Double ] refinePose n cam0 tgt prt = map model ( iterate work zerot ) where model = projectionAt ' ( cameraModelOrigin Nothing cam0 ) . fromList zerot = replicate 6 0 hfeats c = [ \h - > feat ( transPol h c ) k | k < - [ 0 .. n ] ] f0 = fromList $ map ( $ ident 3 ) ( ) feats = map ( . ( ( < > diagl[-1,1,1 ] ) . ( ¿ [ 0,1,3 ] ) . model ) ) ( hfeats prt ) fun xs = fromList $ map ( $ xs ) feats jac = jacobian feats work ( + ) xs ( toList dxs ) where err = f0 - fun xs j = jac xs dxs = ( trans j < > j ) < \ > ( trans j < > err ) xs ' = zipWith ( + ) xs ( toList dxs ) info = ( ( f0 - fun xs - j<>dxs ) , ( f0 - fun xs ' ) ) refinePose :: Int -> Matrix Double -> Polyline -> Polyline -> [Matrix Double] refinePose n cam0 tgt prt = map model (iterate work zerot) where model = projectionAt' (cameraModelOrigin Nothing cam0) . fromList zerot = replicate 6 0 hfeats c = [ \h -> feat (transPol h c) k | k <- [0..n] ] f0 = fromList $ map ($ ident 3) (hfeats tgt) feats = map (. ((<> diagl[-1,1,1]) . (¿[0,1,3]) . model)) (hfeats prt) fun xs = fromList $ map ($ xs) feats jac = jacobian feats work xs = zipWith (+) xs (toList dxs) where err = f0 - fun xs j = jac xs dxs = (trans j <> j) <\> (trans j <> err) xs' = zipWith (+) xs (toList dxs) info = (norm2 (f0 - fun xs - j<>dxs), norm2 (f0 - fun xs')) -} -------------------------------------------------------------------------------- -- resampled features featRS s c = flatten (datMat (resample s c)) prepareGNP :: Int -> Polyline -> GN prepareGNP n prt = (f0,j0,fun) where fun tgt = featRS (n `div` 2) tgt f0 = fun prt trans k xs = feat n (transPol (mktP xs) prt) k j0 = jacobian (map trans dimfeat) zerot dimfeat = [0..n-1] zerot = replicate 8 0 feat n cont = h where v = featRS (n `div` 2) cont h k = v@>k
null
https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/packages/contours/contours/src/Contours/GNS.hs
haskell
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ resampled features
module Contours.GNS( GN, prepareGNS, prepareGNP, stepGN, stepGN', featF, mktP, featRS) where import Util.Geometry import Contours.Base import Contours.Fourier import Util.Homogeneous import Numeric.LinearAlgebra import Numeric.LinearAlgebra.Util(col,(?),(¿),diagl) import Util.Misc(rotateLeft,degree) import Vision(kgen , projectionAt',cameraModelOrigin ) import Util.Rotation import Numeric.GSL.Differentiation import Contours.Resample featF :: Double -> (Int -> Complex Double) -> (Int -> Double) featF a fou = h where g = normalizeStart ((*cis a) . fou) h k = (sel . g) j where j = sgn * ((k + 2) `div` 4) sel | odd k = imagPart | otherwise = realPart sgn | (k+2) `mod` 4 > 1 = -1 | otherwise = 1 feat :: Polyline -> Int -> Double feat cont = featF 0 fou where fou = fourierPL cont type GN = (Vector Double, Matrix Double, Polyline -> Vector Double) prepareGNS :: Int -> Polyline -> GN prepareGNS n prt = (f0,j0,fun) where fun tgt = fromList (map (feat tgt) dimfeat) f0 = fun prt trans k xs = feat (transPol (mktP xs) prt) k j0 = jacobian (map trans dimfeat) zerot dimfeat = [0..n] zerot = replicate 8 0 stepGN :: GN -> Polyline -> (Polyline,Double) stepGN (f0,j0,fun) tgt = (res, norm2 err) where err = fun tgt - f0 dx = (trans j0 <> j0) <\> (trans j0 <> err) res = transPol (inv (mktP (toList dx))) tgt type M = Matrix Double type V = Vector Double stepGN' :: GN -> (Polyline, M, V, Double) -> (Polyline, M, V, Double) stepGN' (f0,j0,fun) (t,h,err,_) = (t', h', err', norm2 err') where dx = (trans j0 <> j0) <\> (trans j0 <> err) dh = mktP (toList dx) t' = transPol (inv dh) t h' = h <> dh err' = fun t' - f0 jacobian :: [[Double] -> Double] -> [Double] -> Matrix Double jacobian fs xs = fromLists $ map (\f -> gradient f xs) fs gradient f v = [partialDerivative k f v | k <- [0 .. length v -1]] partialDerivative n f v = fst (derivCentral 0.01 g (v!!n)) where g x = f (concat [a,x:b]) (a,_:b) = splitAt n v mktP [a,d,c,b,e,f,g,h] = (3><3) [ 1+a, c, e, b , 1+d, f, g , h, 1] :: Matrix Double refinePose : : Int - > Matrix Double - > Polyline - > Polyline - > [ Matrix Double ] refinePose n cam0 tgt prt = map model ( iterate work zerot ) where model = projectionAt ' ( cameraModelOrigin Nothing cam0 ) . fromList zerot = replicate 6 0 hfeats c = [ \h - > feat ( transPol h c ) k | k < - [ 0 .. n ] ] f0 = fromList $ map ( $ ident 3 ) ( ) feats = map ( . ( ( < > diagl[-1,1,1 ] ) . ( ¿ [ 0,1,3 ] ) . model ) ) ( hfeats prt ) fun xs = fromList $ map ( $ xs ) feats jac = jacobian feats work ( + ) xs ( toList dxs ) where err = f0 - fun xs j = jac xs dxs = ( trans j < > j ) < \ > ( trans j < > err ) xs ' = zipWith ( + ) xs ( toList dxs ) info = ( ( f0 - fun xs - j<>dxs ) , ( f0 - fun xs ' ) ) refinePose :: Int -> Matrix Double -> Polyline -> Polyline -> [Matrix Double] refinePose n cam0 tgt prt = map model (iterate work zerot) where model = projectionAt' (cameraModelOrigin Nothing cam0) . fromList zerot = replicate 6 0 hfeats c = [ \h -> feat (transPol h c) k | k <- [0..n] ] f0 = fromList $ map ($ ident 3) (hfeats tgt) feats = map (. ((<> diagl[-1,1,1]) . (¿[0,1,3]) . model)) (hfeats prt) fun xs = fromList $ map ($ xs) feats jac = jacobian feats work xs = zipWith (+) xs (toList dxs) where err = f0 - fun xs j = jac xs dxs = (trans j <> j) <\> (trans j <> err) xs' = zipWith (+) xs (toList dxs) info = (norm2 (f0 - fun xs - j<>dxs), norm2 (f0 - fun xs')) -} featRS s c = flatten (datMat (resample s c)) prepareGNP :: Int -> Polyline -> GN prepareGNP n prt = (f0,j0,fun) where fun tgt = featRS (n `div` 2) tgt f0 = fun prt trans k xs = feat n (transPol (mktP xs) prt) k j0 = jacobian (map trans dimfeat) zerot dimfeat = [0..n-1] zerot = replicate 8 0 feat n cont = h where v = featRS (n `div` 2) cont h k = v@>k
203d29443a212445fc403414f79b2251739f7c523e7d5fa7058c234ead3e36fd
clojure/core.typed
collatz.clj
(ns clojure.core.typed.test.collatz (:require [clojure.core.typed :refer [ann] :as t])) (ann collatz [Number -> Number]) (defn collatz [n] (cond (= 1 n) 1 (and (integer? n) (even? n)) (collatz (/ n 2)) :else (collatz (inc (* 3 n))))) (collatz 10)
null
https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.jvm/test/clojure/core/typed/test/collatz.clj
clojure
(ns clojure.core.typed.test.collatz (:require [clojure.core.typed :refer [ann] :as t])) (ann collatz [Number -> Number]) (defn collatz [n] (cond (= 1 n) 1 (and (integer? n) (even? n)) (collatz (/ n 2)) :else (collatz (inc (* 3 n))))) (collatz 10)
b5e6eb73e32e0bd31e4919d77afd056b7980a368bf2282ef22e7032254f9c49a
emotiq/emotiq
package.lisp
(defpackage :emotiq/model/wallet (:use :cl) (:nicknames :model/wallet) (:export #:mock #:transactions #:recovery-phrase #:get-wallet #:enumerate-wallets #:get-wallet-addresses) (:export #:enumerate-dictionaries #:get-dictionary))
null
https://raw.githubusercontent.com/emotiq/emotiq/9af78023f670777895a3dac29a2bbe98e19b6249/src/model/package.lisp
lisp
(defpackage :emotiq/model/wallet (:use :cl) (:nicknames :model/wallet) (:export #:mock #:transactions #:recovery-phrase #:get-wallet #:enumerate-wallets #:get-wallet-addresses) (:export #:enumerate-dictionaries #:get-dictionary))
8803230a32fd2707eb000a465e2ee2b50ded8ef17cfbde4d5acb3806d0c6fd13
Vigilans/hscc
RegexSpec.hs
module Text.Lexer.DFA.RegexSpec where import Test.Hspec import Test.QuickCheck import Text.Lexer.Regex import Text.Lexer.DFA.Regex import Text.Lexer.DFA import qualified Data.Map as M import qualified Data.Set.Monad as S regex :: Regex regex = readRegex "(a|b)*abb" regex' :: Regex regex'= augment regex state :: [Int] -> [String] -> State state c s = State { code = S.fromList c, tags = s } sA = state [1,2,3] [] sB = state [1,2,3,4] [] sC = state [1,2,3,5] [] sD = state [1,2,3,6] ["regex"] transitions = S.fromList [ (sA, 'a', sB), (sA, 'b', sA), (sB, 'a', sB), (sB, 'b', sC), (sC, 'a', sB), (sC, 'b', sD), (sD, 'a', sB), (sD, 'b', sA) ] regexDFA :: DFA regexDFA = build (transitions, sA, S.fromList [sD]) spec :: Spec spec = do let (RegexAttr{ nullable, firstpos, lastpos }, RegexPose{ followpos, leafsymb }) = regexFunction regex' describe "Regex Functions" $ do it "augmented regex is ((a|b))*abb#" $ showRegex regex' `shouldBe` "((a|b))*abb#" it "nullable, firstpos, lastpos are False, {1,2,3}, {6}" $ (nullable, firstpos, lastpos) `shouldBe` (False, S.fromList [1,2,3], S.fromList [6]) it "follow poses are [{1,2,3}, {1,2,3}, {4}, {5}, {6}, ∅]" $ S.toList <$> M.elems followpos `shouldBe` [[1,2,3], [1,2,3], [4], [5], [6], []] it "leaf symbols are [a, b, a, b, b, #]" $ showRegex <$> M.elems leafsymb `shouldBe` ["a", "b", "a", "b", "b", "#"] describe "Regex to DFA" $ do it "should be equal to hard-coded dfa" $ regex2dfa "regex" regex `shouldBe` regexDFA it "should be minimum dfa in this example" $ regex2dfa "regex" regex `shouldBe` minimize (regex2dfa "regex" regex) it "state of empty code should be the dead state" $ let dfa = regex2dfa "auto" (readRegex "auto") in eliminateDeads dfa `shouldBe` mapStates (\s -> if S.null $ code s then Empty else s) dfa
null
https://raw.githubusercontent.com/Vigilans/hscc/d612c54f9263d90fb01673aea1820a62fdf62551/test/Text/Lexer/DFA/RegexSpec.hs
haskell
module Text.Lexer.DFA.RegexSpec where import Test.Hspec import Test.QuickCheck import Text.Lexer.Regex import Text.Lexer.DFA.Regex import Text.Lexer.DFA import qualified Data.Map as M import qualified Data.Set.Monad as S regex :: Regex regex = readRegex "(a|b)*abb" regex' :: Regex regex'= augment regex state :: [Int] -> [String] -> State state c s = State { code = S.fromList c, tags = s } sA = state [1,2,3] [] sB = state [1,2,3,4] [] sC = state [1,2,3,5] [] sD = state [1,2,3,6] ["regex"] transitions = S.fromList [ (sA, 'a', sB), (sA, 'b', sA), (sB, 'a', sB), (sB, 'b', sC), (sC, 'a', sB), (sC, 'b', sD), (sD, 'a', sB), (sD, 'b', sA) ] regexDFA :: DFA regexDFA = build (transitions, sA, S.fromList [sD]) spec :: Spec spec = do let (RegexAttr{ nullable, firstpos, lastpos }, RegexPose{ followpos, leafsymb }) = regexFunction regex' describe "Regex Functions" $ do it "augmented regex is ((a|b))*abb#" $ showRegex regex' `shouldBe` "((a|b))*abb#" it "nullable, firstpos, lastpos are False, {1,2,3}, {6}" $ (nullable, firstpos, lastpos) `shouldBe` (False, S.fromList [1,2,3], S.fromList [6]) it "follow poses are [{1,2,3}, {1,2,3}, {4}, {5}, {6}, ∅]" $ S.toList <$> M.elems followpos `shouldBe` [[1,2,3], [1,2,3], [4], [5], [6], []] it "leaf symbols are [a, b, a, b, b, #]" $ showRegex <$> M.elems leafsymb `shouldBe` ["a", "b", "a", "b", "b", "#"] describe "Regex to DFA" $ do it "should be equal to hard-coded dfa" $ regex2dfa "regex" regex `shouldBe` regexDFA it "should be minimum dfa in this example" $ regex2dfa "regex" regex `shouldBe` minimize (regex2dfa "regex" regex) it "state of empty code should be the dead state" $ let dfa = regex2dfa "auto" (readRegex "auto") in eliminateDeads dfa `shouldBe` mapStates (\s -> if S.null $ code s then Empty else s) dfa
26bbbe5d3ebdf30ffd25cbda98a61408f126ed7c7e26cdeace49b37620737b50
NB-Iot/emqx-hw-coap
emqx_hw_coap_config.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2013 - 2017 EMQ Enterprise , Inc. ( ) %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module (emqx_hw_coap_config). -include("emqx_hw_coap.hrl"). -export ([register/0, unregister/0]). %%-------------------------------------------------------------------- %% API %%-------------------------------------------------------------------- register() -> clique_config:load_schema([code:priv_dir(?APP)], ?APP), register_config(). unregister() -> unregister_config(), clique_config:unload_schema(?APP). %%-------------------------------------------------------------------- %% Set ENV Register Config %%-------------------------------------------------------------------- register_config() -> Keys = keys(), [clique:register_config(Key , fun config_callback/2) || Key <- Keys], clique:register_config_whitelist(Keys, ?APP). config_callback([_, Key], Value) -> application:set_env(?APP, list_to_atom(Key), Value), " successfully\n". %%-------------------------------------------------------------------- config %%-------------------------------------------------------------------- unregister_config() -> Keys = keys(), [clique:unregister_config(Key) || Key <- Keys], clique:unregister_config_whitelist(Keys, ?APP). %%-------------------------------------------------------------------- %% Internal Functions %%-------------------------------------------------------------------- keys() -> ["coap_hw.port", "coap_hw.keepalive", "coap_hw.enable_stats", "coap_hw.certfile", "coap_hw.keyfile"].
null
https://raw.githubusercontent.com/NB-Iot/emqx-hw-coap/76436492a22eaa0cd6560b4f135275ecf16245d0/src/emqx_hw_coap_config.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. -------------------------------------------------------------------- -------------------------------------------------------------------- API -------------------------------------------------------------------- -------------------------------------------------------------------- Set ENV Register Config -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- Internal Functions --------------------------------------------------------------------
Copyright ( c ) 2013 - 2017 EMQ Enterprise , Inc. ( ) Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module (emqx_hw_coap_config). -include("emqx_hw_coap.hrl"). -export ([register/0, unregister/0]). register() -> clique_config:load_schema([code:priv_dir(?APP)], ?APP), register_config(). unregister() -> unregister_config(), clique_config:unload_schema(?APP). register_config() -> Keys = keys(), [clique:register_config(Key , fun config_callback/2) || Key <- Keys], clique:register_config_whitelist(Keys, ?APP). config_callback([_, Key], Value) -> application:set_env(?APP, list_to_atom(Key), Value), " successfully\n". config unregister_config() -> Keys = keys(), [clique:unregister_config(Key) || Key <- Keys], clique:unregister_config_whitelist(Keys, ?APP). keys() -> ["coap_hw.port", "coap_hw.keepalive", "coap_hw.enable_stats", "coap_hw.certfile", "coap_hw.keyfile"].
3697393180a7e9ad19c3e4af6903e0b1283914dad8b2c5a0a25da38a74a0c95a
rizo/snowflake-os
ICH0.ml
open PCI open AudioMixer The ' ICH0 ' sound driver two sets of port i / o spaces type io_space = { read8 : int -> int; read16 : int -> int; read32 : int -> int32; write8 : int -> int -> unit; write16 : int -> int -> unit; write32 : int -> int32 -> unit; } let make_io_space resource = { read8 = AddressSpace.read8 resource; read16 = AddressSpace.read16 resource; read32 = AddressSpace.read32 resource; write8 = AddressSpace.write8 resource; write16 = AddressSpace.write16 resource; write32 = AddressSpace.write32 resource; } module R = struct let reset = 0x00 let mute = [0x02; 0x04; 0x18] let bdl_offset = 0x10 let last_valid = 0x15 let current = 0x14 let control = 0x1B let status = 0x16 let sample_rate = 0x2C end let num_buffers = 32 in samples , which are 16 - bit let create device = let module C = struct open Bigarray open BlockIO (* set up our i/o spaces *) let nambar = make_io_space device.resources.(0) let nabmbar = make_io_space device.resources.(1) create DMA buffers and buffer descriptor list let buffers = Array.init num_buffers begin fun _ -> Array1.create int8_unsigned c_layout (buffer_size * 2) end let bdl = Array1.create int32 c_layout (num_buffers * 2) (* some helper functions rarely used *) let get_bit io_space addr bit = io_space.read8 addr land (1 lsl bit) <> 0 let set_bit io_space addr bit = io_space.write8 addr (io_space.read8 addr lor (1 lsl bit)) let clear_bit io_space addr bit = io_space.write8 addr (io_space.read8 addr land (lnot (1 lsl bit))) (* get buffer descriptor pointers *) let last_valid () = nabmbar.read8 R.last_valid let current () = nabmbar.read8 R.current let next_buffer buffer = (buffer + 1) mod num_buffers (* isr & output routines *) let m = Mutex.create() let cv = Condition.create() let isr () = if next_buffer (last_valid ()) <> current () then begin clear the interrupt , by writing ' 1 ' to bit 3 nabmbar.write16 R.status (nabmbar.read16 R.status lor 8); Mutex.lock m; Condition.signal cv; Mutex.unlock m; end let output block_input = (* the length = total size of input - current position *) let len = Array1.dim block_input.data in (*let samples = Array1.dim block_input.data - block_input.pos in*) let rec loop () = if block_input.pos >= len then begin (* we've finished! *) Vt100.printf " no more audio\n " ; end else begin (* we can shuffle more data into the card *) Mutex.lock m; while next_buffer (last_valid ()) = current () do (* wait for a free buffer *) Condition.wait cv m; done; Mutex.unlock m; (* get the next buffer *) let ix = next_buffer (last_valid ()) in let buffer = buffers.(ix) in (* copy data into the buffer *) let size = min (buffer_size * 2) (len - block_input.pos) in if size < (buffer_size * 2) then BlockIO.blit block_input (Array1.sub buffer 0 size) else BlockIO.blit block_input buffer; (* send the command byte and size (in samples) *) bdl.{2*ix+1} <- Int32.logor 0x8000_0000l (Int32.of_int (size lsr 1)); nabmbar.write8 R.last_valid ix; loop () end in loop () end in (* init the device *) for i = 0 to num_buffers - 1 do C.bdl.{2*i} <- Asm.address C.buffers.(i); C.bdl.{2*i+1} <- Int32.zero done; reset PCM out C.clear_bit C.nabmbar R.control 0; C.clear_bit C.nabmbar R.control 4; C.clear_bit C.nabmbar R.control 3; C.clear_bit C.nabmbar R.control 2; C.set_bit C.nabmbar R.control 1; while C.get_bit C.nabmbar R.control 1 do () done; (* reset and unmute the audio device *) C.nambar.write16 R.reset 1; List.iter begin fun x -> C.nambar.write16 x 0 end R.mute; (* program the buffer descriptor list *) C.nabmbar.write32 R.bdl_offset (Asm.address C.bdl); C.nabmbar.write8 R.last_valid (C.nabmbar.read8 R.current); set sample rate to 44100 hertz ( more common then default of 48000 ) C.nambar.write16 R.sample_rate 44100; (* register an interrupt handler *) Interrupts.create device.request_line C.isr; C.set_bit C.nabmbar R.control 4; (* interrupts for buffer completion *) Vt100.printf "ich0: on request line %02X\n" device.request_line; (* start output *) C.nabmbar.write8 R.control (C.nabmbar.read8 R.control lor 1); (* register with the audio mixer *) let sample_rate = C.nambar.read16 R.sample_rate in Vt100.printf "ich0: sample rate = %d\n" sample_rate; AudioMixer.register_device { format = 16, sample_rate, 2; output = C.output; } let init () = DeviceManager.add_driver "intel ac'97" create 0x8086 0x2415; (* -ons/kernel/drivers/audio/ac97/ichaudio/ichaudio.c *) DeviceManager.add_driver "intel ac'97" create 0x8086 0x293E
null
https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/kernel/ICH0.ml
ocaml
set up our i/o spaces some helper functions rarely used get buffer descriptor pointers isr & output routines the length = total size of input - current position let samples = Array1.dim block_input.data - block_input.pos in we've finished! we can shuffle more data into the card wait for a free buffer get the next buffer copy data into the buffer send the command byte and size (in samples) init the device reset and unmute the audio device program the buffer descriptor list register an interrupt handler interrupts for buffer completion start output register with the audio mixer -ons/kernel/drivers/audio/ac97/ichaudio/ichaudio.c
open PCI open AudioMixer The ' ICH0 ' sound driver two sets of port i / o spaces type io_space = { read8 : int -> int; read16 : int -> int; read32 : int -> int32; write8 : int -> int -> unit; write16 : int -> int -> unit; write32 : int -> int32 -> unit; } let make_io_space resource = { read8 = AddressSpace.read8 resource; read16 = AddressSpace.read16 resource; read32 = AddressSpace.read32 resource; write8 = AddressSpace.write8 resource; write16 = AddressSpace.write16 resource; write32 = AddressSpace.write32 resource; } module R = struct let reset = 0x00 let mute = [0x02; 0x04; 0x18] let bdl_offset = 0x10 let last_valid = 0x15 let current = 0x14 let control = 0x1B let status = 0x16 let sample_rate = 0x2C end let num_buffers = 32 in samples , which are 16 - bit let create device = let module C = struct open Bigarray open BlockIO let nambar = make_io_space device.resources.(0) let nabmbar = make_io_space device.resources.(1) create DMA buffers and buffer descriptor list let buffers = Array.init num_buffers begin fun _ -> Array1.create int8_unsigned c_layout (buffer_size * 2) end let bdl = Array1.create int32 c_layout (num_buffers * 2) let get_bit io_space addr bit = io_space.read8 addr land (1 lsl bit) <> 0 let set_bit io_space addr bit = io_space.write8 addr (io_space.read8 addr lor (1 lsl bit)) let clear_bit io_space addr bit = io_space.write8 addr (io_space.read8 addr land (lnot (1 lsl bit))) let last_valid () = nabmbar.read8 R.last_valid let current () = nabmbar.read8 R.current let next_buffer buffer = (buffer + 1) mod num_buffers let m = Mutex.create() let cv = Condition.create() let isr () = if next_buffer (last_valid ()) <> current () then begin clear the interrupt , by writing ' 1 ' to bit 3 nabmbar.write16 R.status (nabmbar.read16 R.status lor 8); Mutex.lock m; Condition.signal cv; Mutex.unlock m; end let output block_input = let len = Array1.dim block_input.data in let rec loop () = if block_input.pos >= len then begin Vt100.printf " no more audio\n " ; end else begin Mutex.lock m; while next_buffer (last_valid ()) = current () do Condition.wait cv m; done; Mutex.unlock m; let ix = next_buffer (last_valid ()) in let buffer = buffers.(ix) in let size = min (buffer_size * 2) (len - block_input.pos) in if size < (buffer_size * 2) then BlockIO.blit block_input (Array1.sub buffer 0 size) else BlockIO.blit block_input buffer; bdl.{2*ix+1} <- Int32.logor 0x8000_0000l (Int32.of_int (size lsr 1)); nabmbar.write8 R.last_valid ix; loop () end in loop () end in for i = 0 to num_buffers - 1 do C.bdl.{2*i} <- Asm.address C.buffers.(i); C.bdl.{2*i+1} <- Int32.zero done; reset PCM out C.clear_bit C.nabmbar R.control 0; C.clear_bit C.nabmbar R.control 4; C.clear_bit C.nabmbar R.control 3; C.clear_bit C.nabmbar R.control 2; C.set_bit C.nabmbar R.control 1; while C.get_bit C.nabmbar R.control 1 do () done; C.nambar.write16 R.reset 1; List.iter begin fun x -> C.nambar.write16 x 0 end R.mute; C.nabmbar.write32 R.bdl_offset (Asm.address C.bdl); C.nabmbar.write8 R.last_valid (C.nabmbar.read8 R.current); set sample rate to 44100 hertz ( more common then default of 48000 ) C.nambar.write16 R.sample_rate 44100; Interrupts.create device.request_line C.isr; Vt100.printf "ich0: on request line %02X\n" device.request_line; C.nabmbar.write8 R.control (C.nabmbar.read8 R.control lor 1); let sample_rate = C.nambar.read16 R.sample_rate in Vt100.printf "ich0: sample rate = %d\n" sample_rate; AudioMixer.register_device { format = 16, sample_rate, 2; output = C.output; } let init () = DeviceManager.add_driver "intel ac'97" create 0x8086 0x293E
f285ae3bc8bb89ee2f32e853d8e31b81b80d8defc5d45c4dce3fac98c29c0bde
remyzorg/pendulum
player.ml
open Firebug Jsoo boilerplate code module Dom_html = struct include Dom_html open Js class type _mediaElement = object inherit mediaElement method onprogress : (_mediaElement t, mouseEvent t) event_listener writeonly_prop method ontimeupdate : (_mediaElement t, mouseEvent t) event_listener writeonly_prop method onplay : (_mediaElement t, mouseEvent t) event_listener writeonly_prop method onpause : (_mediaElement t, mouseEvent t) event_listener writeonly_prop method onloadeddata : (_mediaElement t, mouseEvent t) event_listener writeonly_prop end module Coerce = struct include CoerceTo let unsafeCoerce tag (e : #element t) = Js.some (Js.Unsafe.coerce e) let media : #element t -> _mediaElement t opt = fun e -> unsafeCoerce "media" e end end let error f = Printf.ksprintf (fun s -> Firebug.console##error (Js.string s); failwith s) f let debug f = Printf.ksprintf (fun s -> Firebug.console##log(Js.string s)) f let alert f = Printf.ksprintf (fun s -> Dom_html.window##alert(Js.string s); failwith s) f let (@>) s coerce = Js.Opt.get (coerce @@ Dom_html.getElementById s) (fun () -> error "can't find element %s" s) let str s = Js.some @@ Js.string s (* ======================== *) let ftime_to_min_sec t = let sec = int_of_float t in let min = sec / 60 in let sec = sec mod 60 in (min, sec) let max_slide = 1000. let set_visible b elt = let visibility = if b then "visible" else "hidden" in elt##.style##.visibility := Js.string visibility (* Updates the progress bar value proportionnaly to current time *) let update_slider slider media = slider##.value := Js.string @@ Format.sprintf "%0.f" ( if media##.duration = 0. then 0. else media##.currentTime /. media##.duration *. max_slide) (* Updates the time of the current position of the cursor over it *) let update_slider_value slider_value media slider = let min, sec = ftime_to_min_sec @@ ((Js.parseFloat slider##.value) /. max_slide *. media##.duration) in set_visible true slider_value; let padding = Format.sprintf "%0.fpx" (Js.parseFloat slider##.value /. max_slide *. (float_of_int slider##.scrollWidth)) in slider_value##.style##.marginLeft := Js.string padding; slider_value##.textContent := Js.some @@ Js.string @@ Format.sprintf "%2dmin%2ds" min sec (* Sets the current time of the media tag in proportion *) let update_media media slider = media##.currentTime := (Js.parseFloat slider##.value) /. max_slide *. media##.duration (* Apply the state switching to the video by calling pause/play action *) let update_state state media button = if state then media##play else media##pause (* Update the displayed current time *) let update_time_a media time_a = let cmin, csec = ftime_to_min_sec media##.currentTime in let tmin, tsec = ftime_to_min_sec media##.duration in time_a##.textContent := str @@ Format.sprintf "%2d:%0d / %0d:%0d" cmin csec tmin tsec Switch the text on the button let update_content elt b = elt##.textContent := Js.some @@ Js.string @@ if b then "Pause" else "Play" open Dom_html (* The reactive program of the player *) let%sync reactive_player ~animate ~obj = element (play_pause : buttonElement Js.t); element (progress_bar : inputElement Js.t); element (media : _mediaElement Js.t); element (time_a : anchorElement Js.t); element (slider_value : anchorElement Js.t); let seeking = () in let state = Js.to_bool media##.autoplay in (* carry the state of the video (true if playing) *) !(update_content play_pause (pre state)); (* update the button at start-up *) loop ( (* handle the different possibles actions : *) present play_pause##onclick (emit state (not !!state)) || present state !(update_state !!state media play_pause) || present state !(update_content play_pause !!state) ; pause) || loop ( (* while the user moves the cursor, display the time over it *) present progress_bar##oninput !(update_slider_value slider_value media progress_bar); pause ) || loop ( await progress_bar##onmousedown; (* When mouse button is down *) trap t' ( (* open an escape block with exception t' *) loop ( (* every instant, *) emit seeking; (* emits the blocking signal *) present progress_bar##onmouseup ( (* if the button is released*) !(set_visible false slider_value; (* stop displaying the time over the cursor *) update_media media progress_bar); (* set the current time of the video *) exit t' (* leave the escape block and stop this behavior *) ); pause)); pause) || loop ( present media##ontimeupdate ( (* everying instants the video updates *) present seeking nothing (* if the blocking signal is present, do nothing *) !(update_slider progress_bar media) (* else, update the progress bar with the current time of the video*) || !(update_time_a media time_a) (* update the display of the current time *) ); pause) let main _ = let open Dom_html in let play_button = "reactiveplayer_play" @> Coerce.button in let progress_bar = "reactiveplayer_progress" @> Coerce.input in let media = "reactiveplayer_media" @> Coerce.media in let time = "reactiveplayer_timetxt" @> Coerce.a in let range_value = "reactiveplayer_range_value" @> Coerce.a in Initialize the player program , with the js elements as inputs setters function have ' _ ' to avoid the unused warning , as long as we do n't use them : Signals and _ react function are implicitely triggered by the generated code of the program setters function have '_' to avoid the unused warning, as long as we don't use them : Signals and _react function are implicitely triggered by the generated code of the program *) ignore @@ reactive_player#create (play_button, progress_bar, media, time, range_value); Js._false let () = Dom_html.(window##.onload := handler main)
null
https://raw.githubusercontent.com/remyzorg/pendulum/a532681c6f99d77129e31fbe27cc56c396a7c63c/examples/player/player.ml
ocaml
======================== Updates the progress bar value proportionnaly to current time Updates the time of the current position of the cursor over it Sets the current time of the media tag in proportion Apply the state switching to the video by calling pause/play action Update the displayed current time The reactive program of the player carry the state of the video (true if playing) update the button at start-up handle the different possibles actions : while the user moves the cursor, display the time over it When mouse button is down open an escape block with exception t' every instant, emits the blocking signal if the button is released stop displaying the time over the cursor set the current time of the video leave the escape block and stop this behavior everying instants the video updates if the blocking signal is present, do nothing else, update the progress bar with the current time of the video update the display of the current time
open Firebug Jsoo boilerplate code module Dom_html = struct include Dom_html open Js class type _mediaElement = object inherit mediaElement method onprogress : (_mediaElement t, mouseEvent t) event_listener writeonly_prop method ontimeupdate : (_mediaElement t, mouseEvent t) event_listener writeonly_prop method onplay : (_mediaElement t, mouseEvent t) event_listener writeonly_prop method onpause : (_mediaElement t, mouseEvent t) event_listener writeonly_prop method onloadeddata : (_mediaElement t, mouseEvent t) event_listener writeonly_prop end module Coerce = struct include CoerceTo let unsafeCoerce tag (e : #element t) = Js.some (Js.Unsafe.coerce e) let media : #element t -> _mediaElement t opt = fun e -> unsafeCoerce "media" e end end let error f = Printf.ksprintf (fun s -> Firebug.console##error (Js.string s); failwith s) f let debug f = Printf.ksprintf (fun s -> Firebug.console##log(Js.string s)) f let alert f = Printf.ksprintf (fun s -> Dom_html.window##alert(Js.string s); failwith s) f let (@>) s coerce = Js.Opt.get (coerce @@ Dom_html.getElementById s) (fun () -> error "can't find element %s" s) let str s = Js.some @@ Js.string s let ftime_to_min_sec t = let sec = int_of_float t in let min = sec / 60 in let sec = sec mod 60 in (min, sec) let max_slide = 1000. let set_visible b elt = let visibility = if b then "visible" else "hidden" in elt##.style##.visibility := Js.string visibility let update_slider slider media = slider##.value := Js.string @@ Format.sprintf "%0.f" ( if media##.duration = 0. then 0. else media##.currentTime /. media##.duration *. max_slide) let update_slider_value slider_value media slider = let min, sec = ftime_to_min_sec @@ ((Js.parseFloat slider##.value) /. max_slide *. media##.duration) in set_visible true slider_value; let padding = Format.sprintf "%0.fpx" (Js.parseFloat slider##.value /. max_slide *. (float_of_int slider##.scrollWidth)) in slider_value##.style##.marginLeft := Js.string padding; slider_value##.textContent := Js.some @@ Js.string @@ Format.sprintf "%2dmin%2ds" min sec let update_media media slider = media##.currentTime := (Js.parseFloat slider##.value) /. max_slide *. media##.duration let update_state state media button = if state then media##play else media##pause let update_time_a media time_a = let cmin, csec = ftime_to_min_sec media##.currentTime in let tmin, tsec = ftime_to_min_sec media##.duration in time_a##.textContent := str @@ Format.sprintf "%2d:%0d / %0d:%0d" cmin csec tmin tsec Switch the text on the button let update_content elt b = elt##.textContent := Js.some @@ Js.string @@ if b then "Pause" else "Play" open Dom_html let%sync reactive_player ~animate ~obj = element (play_pause : buttonElement Js.t); element (progress_bar : inputElement Js.t); element (media : _mediaElement Js.t); element (time_a : anchorElement Js.t); element (slider_value : anchorElement Js.t); let seeking = () in present play_pause##onclick (emit state (not !!state)) || present state !(update_state !!state media play_pause) || present state !(update_content play_pause !!state) ; pause) present progress_bar##oninput !(update_slider_value slider_value media progress_bar); pause ) || loop ( ); pause)); pause) || loop ( || ); pause) let main _ = let open Dom_html in let play_button = "reactiveplayer_play" @> Coerce.button in let progress_bar = "reactiveplayer_progress" @> Coerce.input in let media = "reactiveplayer_media" @> Coerce.media in let time = "reactiveplayer_timetxt" @> Coerce.a in let range_value = "reactiveplayer_range_value" @> Coerce.a in Initialize the player program , with the js elements as inputs setters function have ' _ ' to avoid the unused warning , as long as we do n't use them : Signals and _ react function are implicitely triggered by the generated code of the program setters function have '_' to avoid the unused warning, as long as we don't use them : Signals and _react function are implicitely triggered by the generated code of the program *) ignore @@ reactive_player#create (play_button, progress_bar, media, time, range_value); Js._false let () = Dom_html.(window##.onload := handler main)
42c8bb5bf69c23c452dd098a638dd830ba33ab7b0a1e04b18e0248c2e7e2c6ac
ml4tp/tcoq
tacworkertop.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 *) (************************************************************************) module W = AsyncTaskQueue.MakeWorker(Stm.TacTask) let () = Coqtop.toploop_init := (fun args -> Flags.make_silent true; W.init_stdout (); CoqworkmgrApi.init !Flags.async_proofs_worker_priority; args) let () = Coqtop.toploop_run := W.main_loop
null
https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/stm/tacworkertop.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 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * module W = AsyncTaskQueue.MakeWorker(Stm.TacTask) let () = Coqtop.toploop_init := (fun args -> Flags.make_silent true; W.init_stdout (); CoqworkmgrApi.init !Flags.async_proofs_worker_priority; args) let () = Coqtop.toploop_run := W.main_loop
5425364c2da23e9b329e7d6c25b54c8d6263cfb9f8a0c6d1d8016c82e9611fbb
ravichugh/djs
test00.ml
let _ :: {(= v 3)} = js_plus (1, 2) in let _ :: {(= v (+ 1 2))} = js_plus (1, 2) in let _ :: {(= (tag v) "number")} = js_plus (1, 2) in let _ :: Num = js_plus (1, 2) in let _ :: {(integer v)} = js_plus (1, 2) in let _ :: Int = js_plus (1, 2) in 0
null
https://raw.githubusercontent.com/ravichugh/djs/c4a13e06adb3e0945f39966523a4d944448c1941/tests/functional/numbers/test00.ml
ocaml
let _ :: {(= v 3)} = js_plus (1, 2) in let _ :: {(= v (+ 1 2))} = js_plus (1, 2) in let _ :: {(= (tag v) "number")} = js_plus (1, 2) in let _ :: Num = js_plus (1, 2) in let _ :: {(integer v)} = js_plus (1, 2) in let _ :: Int = js_plus (1, 2) in 0
ad04139cc092ec7726e7afb5765e5139f10f6f98e81fcbd7be38a8bf10813ee6
j-mie6/ParsleyHaskell
Machine.hs
| Module : Parsley . Internal . Backend . Machine Description : The implementation of the low level parsing machinery is found here License : BSD-3 - Clause Maintainer : : unstable @since 0.1.0.0 Module : Parsley.Internal.Backend.Machine Description : The implementation of the low level parsing machinery is found here License : BSD-3-Clause Maintainer : Jamie Willis Stability : unstable @since 0.1.0.0 -} module Parsley.Internal.Backend.Machine ( Input, eval, module Parsley.Internal.Backend.Machine.Types.Coins, module Parsley.Internal.Backend.Machine.Instructions, module Parsley.Internal.Backend.Machine.Defunc, module Parsley.Internal.Backend.Machine.Identifiers, module Parsley.Internal.Backend.Machine.LetBindings ) where import Data.Array.Unboxed (UArray) import Data.ByteString (ByteString) import Data.Dependent.Map (DMap) import Data.Text (Text) import Parsley.Internal.Backend.Machine.Defunc (user) import Parsley.Internal.Backend.Machine.Identifiers import Parsley.Internal.Backend.Machine.InputOps (InputPrep(..)) import Parsley.Internal.Backend.Machine.Instructions import Parsley.Internal.Backend.Machine.LetBindings (LetBinding, makeLetBinding, newMeta) import Parsley.Internal.Backend.Machine.Ops (Ops) import Parsley.Internal.Backend.Machine.Types.Coins (Coins(..), zero, minCoins, maxCoins, plus, plus1, minus, plusNotReclaim) import Parsley.Internal.Common.Utils (Code) import Parsley.Internal.Core.InputTypes import Parsley.Internal.Trace (Trace) import qualified Data.ByteString.Lazy as Lazy (ByteString) import qualified Parsley.Internal.Backend.Machine.Eval as Eval (eval) | This function is exposed to parsley itself and is used to generate the Haskell code for a parser . @since 0.1.0.0 This function is exposed to parsley itself and is used to generate the Haskell code for a parser. @since 0.1.0.0 -} eval :: forall input a. (Input input, Trace) => Code input -> (LetBinding input a a, DMap MVar (LetBinding input a)) -> Code (Maybe a) eval input (toplevel, bindings) = Eval.eval (prepare input) toplevel bindings | This class is exposed to parsley itself and is used to denote which types may be used as input for a parser . @since 0.1.0.0 This class is exposed to parsley itself and is used to denote which types may be used as input for a parser. @since 0.1.0.0 -} class (InputPrep input, Ops input) => Input input instance Input [Char] instance Input (UArray Int Char) instance Input Text16 instance Input ByteString instance Input CharList instance Input Text --instance Input CacheText instance Input Lazy.ByteString --instance Input Lazy.ByteString instance Input Stream
null
https://raw.githubusercontent.com/j-mie6/ParsleyHaskell/045ab78ed7af0cbb52cf8b42b6aeef5dd7f91ab2/parsley-core/src/ghc-8.10%2B/Parsley/Internal/Backend/Machine.hs
haskell
instance Input CacheText instance Input Lazy.ByteString
| Module : Parsley . Internal . Backend . Machine Description : The implementation of the low level parsing machinery is found here License : BSD-3 - Clause Maintainer : : unstable @since 0.1.0.0 Module : Parsley.Internal.Backend.Machine Description : The implementation of the low level parsing machinery is found here License : BSD-3-Clause Maintainer : Jamie Willis Stability : unstable @since 0.1.0.0 -} module Parsley.Internal.Backend.Machine ( Input, eval, module Parsley.Internal.Backend.Machine.Types.Coins, module Parsley.Internal.Backend.Machine.Instructions, module Parsley.Internal.Backend.Machine.Defunc, module Parsley.Internal.Backend.Machine.Identifiers, module Parsley.Internal.Backend.Machine.LetBindings ) where import Data.Array.Unboxed (UArray) import Data.ByteString (ByteString) import Data.Dependent.Map (DMap) import Data.Text (Text) import Parsley.Internal.Backend.Machine.Defunc (user) import Parsley.Internal.Backend.Machine.Identifiers import Parsley.Internal.Backend.Machine.InputOps (InputPrep(..)) import Parsley.Internal.Backend.Machine.Instructions import Parsley.Internal.Backend.Machine.LetBindings (LetBinding, makeLetBinding, newMeta) import Parsley.Internal.Backend.Machine.Ops (Ops) import Parsley.Internal.Backend.Machine.Types.Coins (Coins(..), zero, minCoins, maxCoins, plus, plus1, minus, plusNotReclaim) import Parsley.Internal.Common.Utils (Code) import Parsley.Internal.Core.InputTypes import Parsley.Internal.Trace (Trace) import qualified Data.ByteString.Lazy as Lazy (ByteString) import qualified Parsley.Internal.Backend.Machine.Eval as Eval (eval) | This function is exposed to parsley itself and is used to generate the Haskell code for a parser . @since 0.1.0.0 This function is exposed to parsley itself and is used to generate the Haskell code for a parser. @since 0.1.0.0 -} eval :: forall input a. (Input input, Trace) => Code input -> (LetBinding input a a, DMap MVar (LetBinding input a)) -> Code (Maybe a) eval input (toplevel, bindings) = Eval.eval (prepare input) toplevel bindings | This class is exposed to parsley itself and is used to denote which types may be used as input for a parser . @since 0.1.0.0 This class is exposed to parsley itself and is used to denote which types may be used as input for a parser. @since 0.1.0.0 -} class (InputPrep input, Ops input) => Input input instance Input [Char] instance Input (UArray Int Char) instance Input Text16 instance Input ByteString instance Input CharList instance Input Text instance Input Lazy.ByteString instance Input Stream
82f1815a5a1b526b1a81ef2dc61ac0f1dffa76164e610855b403b8731a1d8159
huangjs/cl
ztpmv.lisp
;;; Compiled by f2cl version: ( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ " " f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ " " f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ " " f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ " " f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ " " f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ " " macros.l , v 1.112 2009/01/08 12:57:19 " ) Using Lisp CMU Common Lisp 19f ( 19F ) ;;; ;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) ;;; (:coerce-assigns :as-needed) (:array-type ':array) ;;; (:array-slicing t) (:declare-common nil) ;;; (:float-format double-float)) (in-package :blas) (let* ((zero (f2cl-lib:cmplx 0.0 0.0))) (declare (type (f2cl-lib:complex16) zero) (ignorable zero)) (defun ztpmv (uplo trans diag n ap x incx) (declare (type (array f2cl-lib:complex16 (*)) x ap) (type (f2cl-lib:integer4) incx n) (type (simple-array character (*)) diag trans uplo)) (f2cl-lib:with-multi-array-data ((uplo character uplo-%data% uplo-%offset%) (trans character trans-%data% trans-%offset%) (diag character diag-%data% diag-%offset%) (ap f2cl-lib:complex16 ap-%data% ap-%offset%) (x f2cl-lib:complex16 x-%data% x-%offset%)) (prog ((noconj nil) (nounit nil) (i 0) (info 0) (ix 0) (j 0) (jx 0) (k 0) (kk 0) (kx 0) (temp #C(0.0 0.0))) (declare (type f2cl-lib:logical noconj nounit) (type (f2cl-lib:integer4) i info ix j jx k kk kx) (type (f2cl-lib:complex16) temp)) (setf info 0) (cond ((and (not (lsame uplo "U")) (not (lsame uplo "L"))) (setf info 1)) ((and (not (lsame trans "N")) (not (lsame trans "T")) (not (lsame trans "C"))) (setf info 2)) ((and (not (lsame diag "U")) (not (lsame diag "N"))) (setf info 3)) ((< n 0) (setf info 4)) ((= incx 0) (setf info 7))) (cond ((/= info 0) (xerbla "ZTPMV " info) (go end_label))) (if (= n 0) (go end_label)) (setf noconj (lsame trans "T")) (setf nounit (lsame diag "N")) (cond ((<= incx 0) (setf kx (f2cl-lib:int-sub 1 (f2cl-lib:int-mul (f2cl-lib:int-sub n 1) incx)))) ((/= incx 1) (setf kx 1))) (cond ((lsame trans "N") (cond ((lsame uplo "U") (setf kk 1) (cond ((= incx 1) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (cond ((/= (f2cl-lib:fref x (j) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (setf k kk) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) nil) (tagbody (setf (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf k (f2cl-lib:int-add k 1)) label10)) (if nounit (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-sub (f2cl-lib:int-add kk j) 1)) ((1 *)) ap-%offset%)))))) (setf kk (f2cl-lib:int-add kk j)) label20))) (t (setf jx kx) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (cond ((/= (f2cl-lib:fref x (jx) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix kx) (f2cl-lib:fdo (k kk (f2cl-lib:int-add k 1)) ((> k (f2cl-lib:int-add kk j (f2cl-lib:int-sub 2))) nil) (tagbody (setf (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf ix (f2cl-lib:int-add ix incx)) label30)) (if nounit (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-sub (f2cl-lib:int-add kk j) 1)) ((1 *)) ap-%offset%)))))) (setf jx (f2cl-lib:int-add jx incx)) (setf kk (f2cl-lib:int-add kk j)) label40))))) (t (setf kk (the f2cl-lib:integer4 (truncate (* n (+ n 1)) 2))) (cond ((= incx 1) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (cond ((/= (f2cl-lib:fref x (j) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (setf k kk) (f2cl-lib:fdo (i n (f2cl-lib:int-add i (f2cl-lib:int-sub 1))) ((> i (f2cl-lib:int-add j 1)) nil) (tagbody (setf (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf k (f2cl-lib:int-sub k 1)) label50)) (if nounit (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-add (f2cl-lib:int-sub kk n) j)) ((1 *)) ap-%offset%)))))) (setf kk (f2cl-lib:int-sub kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label60))) (t (setf kx (f2cl-lib:int-add kx (f2cl-lib:int-mul (f2cl-lib:int-sub n 1) incx))) (setf jx kx) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (cond ((/= (f2cl-lib:fref x (jx) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix kx) (f2cl-lib:fdo (k kk (f2cl-lib:int-add k (f2cl-lib:int-sub 1))) ((> k (f2cl-lib:int-add kk (f2cl-lib:int-sub (f2cl-lib:int-add n (f2cl-lib:int-sub (f2cl-lib:int-add j 1)))))) nil) (tagbody (setf (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf ix (f2cl-lib:int-sub ix incx)) label70)) (if nounit (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-add (f2cl-lib:int-sub kk n) j)) ((1 *)) ap-%offset%)))))) (setf jx (f2cl-lib:int-sub jx incx)) (setf kk (f2cl-lib:int-sub kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label80))))))) (t (cond ((lsame uplo "U") (setf kk (the f2cl-lib:integer4 (truncate (* n (+ n 1)) 2))) (cond ((= incx 1) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (setf k (f2cl-lib:int-sub kk 1)) (cond (noconj (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (f2cl-lib:fdo (i (f2cl-lib:int-add j (f2cl-lib:int-sub 1)) (f2cl-lib:int-add i (f2cl-lib:int-sub 1))) ((> i 1) nil) (tagbody (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%)))) (setf k (f2cl-lib:int-sub k 1)) label90))) (t (if nounit (setf temp (* temp (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%))))) (f2cl-lib:fdo (i (f2cl-lib:int-add j (f2cl-lib:int-sub 1)) (f2cl-lib:int-add i (f2cl-lib:int-sub 1))) ((> i 1) nil) (tagbody (setf temp (+ temp (* (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)) (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%)))) (setf k (f2cl-lib:int-sub k 1)) label100)))) (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) temp) (setf kk (f2cl-lib:int-sub kk j)) label110))) (t (setf jx (f2cl-lib:int-add kx (f2cl-lib:int-mul (f2cl-lib:int-sub n 1) incx))) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix jx) (cond (noconj (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (f2cl-lib:fdo (k (f2cl-lib:int-add kk (f2cl-lib:int-sub 1)) (f2cl-lib:int-add k (f2cl-lib:int-sub 1))) ((> k (f2cl-lib:int-add kk (f2cl-lib:int-sub j) 1)) nil) (tagbody (setf ix (f2cl-lib:int-sub ix incx)) (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%)))) label120))) (t (if nounit (setf temp (* temp (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%))))) (f2cl-lib:fdo (k (f2cl-lib:int-add kk (f2cl-lib:int-sub 1)) (f2cl-lib:int-add k (f2cl-lib:int-sub 1))) ((> k (f2cl-lib:int-add kk (f2cl-lib:int-sub j) 1)) nil) (tagbody (setf ix (f2cl-lib:int-sub ix incx)) (setf temp (+ temp (* (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)) (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%)))) label130)))) (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) temp) (setf jx (f2cl-lib:int-sub jx incx)) (setf kk (f2cl-lib:int-sub kk j)) label140))))) (t (setf kk 1) (cond ((= incx 1) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (setf k (f2cl-lib:int-add kk 1)) (cond (noconj (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (f2cl-lib:fdo (i (f2cl-lib:int-add j 1) (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%)))) (setf k (f2cl-lib:int-add k 1)) label150))) (t (if nounit (setf temp (* temp (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%))))) (f2cl-lib:fdo (i (f2cl-lib:int-add j 1) (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf temp (+ temp (* (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)) (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%)))) (setf k (f2cl-lib:int-add k 1)) label160)))) (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) temp) (setf kk (f2cl-lib:int-add kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label170))) (t (setf jx kx) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix jx) (cond (noconj (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (f2cl-lib:fdo (k (f2cl-lib:int-add kk 1) (f2cl-lib:int-add k 1)) ((> k (f2cl-lib:int-add kk n (f2cl-lib:int-sub j))) nil) (tagbody (setf ix (f2cl-lib:int-add ix incx)) (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%)))) label180))) (t (if nounit (setf temp (* temp (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%))))) (f2cl-lib:fdo (k (f2cl-lib:int-add kk 1) (f2cl-lib:int-add k 1)) ((> k (f2cl-lib:int-add kk n (f2cl-lib:int-sub j))) nil) (tagbody (setf ix (f2cl-lib:int-add ix incx)) (setf temp (+ temp (* (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)) (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%)))) label190)))) (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) temp) (setf jx (f2cl-lib:int-add jx incx)) (setf kk (f2cl-lib:int-add kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label200)))))))) (go end_label) end_label (return (values nil nil nil nil nil nil nil)))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::ztpmv fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((simple-array character (1)) (simple-array character (1)) (simple-array character (1)) (fortran-to-lisp::integer4) (array fortran-to-lisp::complex16 (*)) (array fortran-to-lisp::complex16 (*)) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil nil nil nil) :calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
null
https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/maxima/share/lapack/blas/ztpmv.lisp
lisp
Compiled by f2cl version: Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) (:coerce-assigns :as-needed) (:array-type ':array) (:array-slicing t) (:declare-common nil) (:float-format double-float))
( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ " " f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ " " f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ " " f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ " " f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ " " f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ " " macros.l , v 1.112 2009/01/08 12:57:19 " ) Using Lisp CMU Common Lisp 19f ( 19F ) (in-package :blas) (let* ((zero (f2cl-lib:cmplx 0.0 0.0))) (declare (type (f2cl-lib:complex16) zero) (ignorable zero)) (defun ztpmv (uplo trans diag n ap x incx) (declare (type (array f2cl-lib:complex16 (*)) x ap) (type (f2cl-lib:integer4) incx n) (type (simple-array character (*)) diag trans uplo)) (f2cl-lib:with-multi-array-data ((uplo character uplo-%data% uplo-%offset%) (trans character trans-%data% trans-%offset%) (diag character diag-%data% diag-%offset%) (ap f2cl-lib:complex16 ap-%data% ap-%offset%) (x f2cl-lib:complex16 x-%data% x-%offset%)) (prog ((noconj nil) (nounit nil) (i 0) (info 0) (ix 0) (j 0) (jx 0) (k 0) (kk 0) (kx 0) (temp #C(0.0 0.0))) (declare (type f2cl-lib:logical noconj nounit) (type (f2cl-lib:integer4) i info ix j jx k kk kx) (type (f2cl-lib:complex16) temp)) (setf info 0) (cond ((and (not (lsame uplo "U")) (not (lsame uplo "L"))) (setf info 1)) ((and (not (lsame trans "N")) (not (lsame trans "T")) (not (lsame trans "C"))) (setf info 2)) ((and (not (lsame diag "U")) (not (lsame diag "N"))) (setf info 3)) ((< n 0) (setf info 4)) ((= incx 0) (setf info 7))) (cond ((/= info 0) (xerbla "ZTPMV " info) (go end_label))) (if (= n 0) (go end_label)) (setf noconj (lsame trans "T")) (setf nounit (lsame diag "N")) (cond ((<= incx 0) (setf kx (f2cl-lib:int-sub 1 (f2cl-lib:int-mul (f2cl-lib:int-sub n 1) incx)))) ((/= incx 1) (setf kx 1))) (cond ((lsame trans "N") (cond ((lsame uplo "U") (setf kk 1) (cond ((= incx 1) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (cond ((/= (f2cl-lib:fref x (j) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (setf k kk) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) nil) (tagbody (setf (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf k (f2cl-lib:int-add k 1)) label10)) (if nounit (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-sub (f2cl-lib:int-add kk j) 1)) ((1 *)) ap-%offset%)))))) (setf kk (f2cl-lib:int-add kk j)) label20))) (t (setf jx kx) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (cond ((/= (f2cl-lib:fref x (jx) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix kx) (f2cl-lib:fdo (k kk (f2cl-lib:int-add k 1)) ((> k (f2cl-lib:int-add kk j (f2cl-lib:int-sub 2))) nil) (tagbody (setf (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf ix (f2cl-lib:int-add ix incx)) label30)) (if nounit (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-sub (f2cl-lib:int-add kk j) 1)) ((1 *)) ap-%offset%)))))) (setf jx (f2cl-lib:int-add jx incx)) (setf kk (f2cl-lib:int-add kk j)) label40))))) (t (setf kk (the f2cl-lib:integer4 (truncate (* n (+ n 1)) 2))) (cond ((= incx 1) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (cond ((/= (f2cl-lib:fref x (j) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (setf k kk) (f2cl-lib:fdo (i n (f2cl-lib:int-add i (f2cl-lib:int-sub 1))) ((> i (f2cl-lib:int-add j 1)) nil) (tagbody (setf (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf k (f2cl-lib:int-sub k 1)) label50)) (if nounit (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-add (f2cl-lib:int-sub kk n) j)) ((1 *)) ap-%offset%)))))) (setf kk (f2cl-lib:int-sub kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label60))) (t (setf kx (f2cl-lib:int-add kx (f2cl-lib:int-mul (f2cl-lib:int-sub n 1) incx))) (setf jx kx) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (cond ((/= (f2cl-lib:fref x (jx) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix kx) (f2cl-lib:fdo (k kk (f2cl-lib:int-add k (f2cl-lib:int-sub 1))) ((> k (f2cl-lib:int-add kk (f2cl-lib:int-sub (f2cl-lib:int-add n (f2cl-lib:int-sub (f2cl-lib:int-add j 1)))))) nil) (tagbody (setf (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf ix (f2cl-lib:int-sub ix incx)) label70)) (if nounit (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-add (f2cl-lib:int-sub kk n) j)) ((1 *)) ap-%offset%)))))) (setf jx (f2cl-lib:int-sub jx incx)) (setf kk (f2cl-lib:int-sub kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label80))))))) (t (cond ((lsame uplo "U") (setf kk (the f2cl-lib:integer4 (truncate (* n (+ n 1)) 2))) (cond ((= incx 1) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (setf k (f2cl-lib:int-sub kk 1)) (cond (noconj (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (f2cl-lib:fdo (i (f2cl-lib:int-add j (f2cl-lib:int-sub 1)) (f2cl-lib:int-add i (f2cl-lib:int-sub 1))) ((> i 1) nil) (tagbody (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%)))) (setf k (f2cl-lib:int-sub k 1)) label90))) (t (if nounit (setf temp (* temp (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%))))) (f2cl-lib:fdo (i (f2cl-lib:int-add j (f2cl-lib:int-sub 1)) (f2cl-lib:int-add i (f2cl-lib:int-sub 1))) ((> i 1) nil) (tagbody (setf temp (+ temp (* (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)) (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%)))) (setf k (f2cl-lib:int-sub k 1)) label100)))) (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) temp) (setf kk (f2cl-lib:int-sub kk j)) label110))) (t (setf jx (f2cl-lib:int-add kx (f2cl-lib:int-mul (f2cl-lib:int-sub n 1) incx))) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix jx) (cond (noconj (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (f2cl-lib:fdo (k (f2cl-lib:int-add kk (f2cl-lib:int-sub 1)) (f2cl-lib:int-add k (f2cl-lib:int-sub 1))) ((> k (f2cl-lib:int-add kk (f2cl-lib:int-sub j) 1)) nil) (tagbody (setf ix (f2cl-lib:int-sub ix incx)) (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%)))) label120))) (t (if nounit (setf temp (* temp (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%))))) (f2cl-lib:fdo (k (f2cl-lib:int-add kk (f2cl-lib:int-sub 1)) (f2cl-lib:int-add k (f2cl-lib:int-sub 1))) ((> k (f2cl-lib:int-add kk (f2cl-lib:int-sub j) 1)) nil) (tagbody (setf ix (f2cl-lib:int-sub ix incx)) (setf temp (+ temp (* (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)) (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%)))) label130)))) (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) temp) (setf jx (f2cl-lib:int-sub jx incx)) (setf kk (f2cl-lib:int-sub kk j)) label140))))) (t (setf kk 1) (cond ((= incx 1) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (setf k (f2cl-lib:int-add kk 1)) (cond (noconj (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (f2cl-lib:fdo (i (f2cl-lib:int-add j 1) (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%)))) (setf k (f2cl-lib:int-add k 1)) label150))) (t (if nounit (setf temp (* temp (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%))))) (f2cl-lib:fdo (i (f2cl-lib:int-add j 1) (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf temp (+ temp (* (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)) (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%)))) (setf k (f2cl-lib:int-add k 1)) label160)))) (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) temp) (setf kk (f2cl-lib:int-add kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label170))) (t (setf jx kx) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix jx) (cond (noconj (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (f2cl-lib:fdo (k (f2cl-lib:int-add kk 1) (f2cl-lib:int-add k 1)) ((> k (f2cl-lib:int-add kk n (f2cl-lib:int-sub j))) nil) (tagbody (setf ix (f2cl-lib:int-add ix incx)) (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%)))) label180))) (t (if nounit (setf temp (* temp (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%))))) (f2cl-lib:fdo (k (f2cl-lib:int-add kk 1) (f2cl-lib:int-add k 1)) ((> k (f2cl-lib:int-add kk n (f2cl-lib:int-sub j))) nil) (tagbody (setf ix (f2cl-lib:int-add ix incx)) (setf temp (+ temp (* (f2cl-lib:dconjg (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)) (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%)))) label190)))) (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) temp) (setf jx (f2cl-lib:int-add jx incx)) (setf kk (f2cl-lib:int-add kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label200)))))))) (go end_label) end_label (return (values nil nil nil nil nil nil nil)))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::ztpmv fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((simple-array character (1)) (simple-array character (1)) (simple-array character (1)) (fortran-to-lisp::integer4) (array fortran-to-lisp::complex16 (*)) (array fortran-to-lisp::complex16 (*)) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil nil nil nil) :calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
e63701f93eec6d20f8dfb84ce6fbaf0f926f828b2b5d67d6d96d744f968ffaa2
karimarttila/clojure
user.clj
(ns user (:require [integrant.repl :refer [reset]] ;[integrant.repl :refer [clear go halt prep init reset reset-all]] [integrant.repl.state :as state] [simpleserver.core :as core])) (integrant.repl/set-prep! core/system-config-start) (defn system [] (or state/system (throw (ex-info "System not running" {})))) (defn env [] (:backend/env (system))) (defn service [] (:service (env))) (defn my-dummy-reset [] (reset)) NOTE : In Cursive , Integrant hot keys are : ;; M-h: go ;; M-j: reset ;; M-k: halt In Calva the Integrant hot keys are : ;; ctlr+T alt+h: go ;; M-j: reset ;; ctlr+T alt+k: halt (comment (user/system) (user/env) ; alt+j hotkey in Cursive (integrant.repl/reset) )
null
https://raw.githubusercontent.com/karimarttila/clojure/8fa3b9b6504389619bc9af014f48848e104376ba/webstore-demo/re-frame-demo/src/clj/user.clj
clojure
[integrant.repl :refer [clear go halt prep init reset reset-all]] M-h: go M-j: reset M-k: halt ctlr+T alt+h: go M-j: reset ctlr+T alt+k: halt alt+j hotkey in Cursive
(ns user (:require [integrant.repl :refer [reset]] [integrant.repl.state :as state] [simpleserver.core :as core])) (integrant.repl/set-prep! core/system-config-start) (defn system [] (or state/system (throw (ex-info "System not running" {})))) (defn env [] (:backend/env (system))) (defn service [] (:service (env))) (defn my-dummy-reset [] (reset)) NOTE : In Cursive , Integrant hot keys are : In Calva the Integrant hot keys are : (comment (user/system) (user/env) (integrant.repl/reset) )
b52dcba0399b660a3623c489c52abc918398b17c0c4dab14db60769f40a75066
manuel-serrano/hop
cps.scm
;*=====================================================================*/ * serrano / prgm / project / hop / hop / js2scheme / cps.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : We d Sep 11 14:30:38 2013 * / * Last change : Fri Jan 13 13:51:21 2023 ( serrano ) * / * Copyright : 2013 - 23 * / ;* ------------------------------------------------------------- */ ;* JavaScript CPS transformation */ ;* ------------------------------------------------------------- */ ;* -international.org/ecma-262/6.0/#sec-14.4 */ ;* ------------------------------------------------------------- */ * This module implements the JavaScript CPS transformation needed * / ;* for generators. Only generator function are modified. */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module __js2scheme_cps (import __js2scheme_ast __js2scheme_dump __js2scheme_compile __js2scheme_stage __js2scheme_syntax __js2scheme_alpha __js2scheme_utils) (include "ast.sch" "usage.sch") (static (final-class %J2STail::J2SReturn) (final-class KDeclInfo (free::bool (default #f)) (def::bool (default #f)) (color::int (default -1)))) (cond-expand (bigloo-debug (static (abstract-class Kont (node::obj read-only) (link::obj read-only) (proc::procedure read-only) (name::bstring read-only (default ""))) (class KontStmt::Kont) (class KontExpr::Kont) (class KontExpr*::Kont)))) (export j2s-cps-stage)) ;*---------------------------------------------------------------------*/ * - stage ... * / ;*---------------------------------------------------------------------*/ (define j2s-cps-stage (instantiate::J2SStageProc (name "cps") (comment "transform generator in CPS") (proc j2s-cps))) ;*---------------------------------------------------------------------*/ * ... * / ;*---------------------------------------------------------------------*/ (define (j2s-cps this conf) (when (isa? this J2SProgram) (with-access::J2SProgram this (headers decls nodes) (for-each (lambda (o) (cps-fun! o (lambda (n) n) conf)) headers) (for-each (lambda (o) (cps-fun! o (lambda (n) n) conf)) decls) (for-each (lambda (o) (cps-fun! o (lambda (n) n) conf)) nodes))) this) ;*---------------------------------------------------------------------*/ ;* kid ... */ ;*---------------------------------------------------------------------*/ (define (kid n::J2SNode) n) ;*---------------------------------------------------------------------*/ ;* kid? ... */ ;*---------------------------------------------------------------------*/ (define (kid? obj) (cond-expand (bigloo-debug (with-access::Kont obj (proc) (eq? proc kid))) (else (eq? obj kid)))) ;*---------------------------------------------------------------------*/ * KontStmt ... * / ;*---------------------------------------------------------------------*/ (define-macro (KontStmt proc node link . name) (cond-expand (bigloo-debug `(instantiate::KontStmt (proc ,proc) (node ,node) (link ,link) (name ,(if (pair? name) (string-append "[" (car name) "]") "")))) (else proc))) ;*---------------------------------------------------------------------*/ ;* KontExpr ... */ ;*---------------------------------------------------------------------*/ (define-macro (KontExpr proc node link . name) (cond-expand (bigloo-debug `(instantiate::KontExpr (proc ,proc) (node ,node) (link ,link) (name ,(if (pair? name) (string-append "[" (car name) "]") "")))) (else proc))) ;*---------------------------------------------------------------------*/ * * ... * / ;*---------------------------------------------------------------------*/ (define-macro (KontExpr* proc node link . name) (cond-expand (bigloo-debug `(instantiate::KontExpr* (proc ,proc) (node ,node) (link ,link) (name ,(if (pair? name) (string-append "[" (car name) "]") "")))) (else proc))) ;*---------------------------------------------------------------------*/ ;* J2SKontCall ... */ ;*---------------------------------------------------------------------*/ (define-macro (J2SKontCall kdecl . args) `(J2SMethodCall (J2SRef ,kdecl) (list ,(if (pair? args) (car args) `(J2SHopRef '%gen))) (J2SHopRef '%yield) (J2SHopRef '%this) ,@(if (pair? args) (cdr args) '()))) ;*---------------------------------------------------------------------*/ ;* kcall ... */ ;*---------------------------------------------------------------------*/ (define-expander kcall (lambda (x e) (match-case x ((?kcall ?kont ?arg) (cond-expand (bigloo-debug (e `(with-access::Kont ,kont (proc name) (let ((res (proc ,arg))) (if (or (isa? res J2SStmt) (and (isa? res J2SExpr) (isa? ,kont KontExpr))) res (kont-call-error ,kont res ',(cer x))))) e)) (else (e `(,kont ,arg) e)))) (else (error "kcall" "bad form" x))))) ;*---------------------------------------------------------------------*/ ;* ktrampoline ... */ ;* ------------------------------------------------------------- */ ;* This function is only to reduce the number of generated */ ;* continuations. Using it is optional. */ ;* ------------------------------------------------------------- */ ;* If a continuation merely jump to another continuation, return */ ;* that trampoline continuation. */ ;*---------------------------------------------------------------------*/ (define (ktrampoline body::J2SStmt) (define (ishopref? expr i) (when (isa? expr J2SHopRef) (with-access::J2SHopRef expr (id) (eq? id id)))) (define (iskontcall? expr) (when (isa? expr J2SCall) (with-access::J2SCall expr (fun thisargs args) (when (and (pair? thisargs) (null? (cdr thisargs)) (pair? args) (null? (cdr args))) (and (ishopref? (car thisargs) '%gen) (ishopref? (car args) '%this)))))) (when (isa? body J2SSeq) (with-access::J2SSeq body (nodes) (when (and (pair? nodes) (pair? (cdr nodes)) (null? (cddr nodes))) (when (isa? (car nodes) J2SNop) (when (isa? (cadr nodes) J2SReturn) (with-access::J2SReturn (cadr nodes) (expr) (when (iskontcall? expr) (with-access::J2SCall expr (fun thisargs) (when (isa? fun J2SRef) expr)))))))))) ;*---------------------------------------------------------------------*/ ;* assert-kont ... */ ;*---------------------------------------------------------------------*/ (define-expander assert-kont (lambda (x e) (cond-expand (bigloo-debug (match-case x ((?- ?kont ?type ?node) (e `(unless (isa? ,kont ,type) (kont-error ,kont ,type ,node ',(cer x))) e)) (else (error "assert-kont" "bad form" x) #f))) (else #t)))) ;*---------------------------------------------------------------------*/ ;* kont-debug */ ;*---------------------------------------------------------------------*/ (cond-expand (bigloo-debug (define (kont-debug kont #!optional (max-depth 20)) (if (isa? kont Kont) (with-access::Kont kont (node link) (let loop ((link link) (stack '()) (depth max-depth)) (if (and link (>fx depth 0)) (with-access::Kont link (link name node) (loop link (cons (format "~a kont: ~a ~a ~a" (typeof node) (typeof link) name (if (>fx (bigloo-debug) 2) (call-with-output-string (lambda (p) (display " ") (display (j2s->sexp node) p) (newline p))) "")) stack) (-fx depth 1))) (reverse! stack)))))))) ;*---------------------------------------------------------------------*/ ;* kont-error ... */ ;*---------------------------------------------------------------------*/ (cond-expand (bigloo-debug ;;; (define (kont-error kont type node loc) (raise (instantiate::&error (obj (typeof kont)) (msg (format "Not a `~s' continuation" (class-name type))) (proc (format "cps ::~a" (typeof node))) (fname (cadr loc)) (location (caddr loc)) (stack (if (isa? kont Kont) (with-access::Kont kont (node link) (let loop ((link link) (stack '())) (if link (with-access::Kont link (link name node) (loop link (cons (format "~a kont: ~a ~a ~a" (typeof node) (typeof link) name (if (>fx (bigloo-debug) 2) (call-with-output-string (lambda (p) (display " ") (display (j2s->sexp node) p) (newline p))) "")) stack))) (reverse! stack)))) (get-trace-stack)))))))) (cond-expand (bigloo-debug ;;; (define (kont-call-error kont node loc) (raise (instantiate::&error (obj (with-access::Kont kont (node) (typeof node))) (msg (format "~a returns `~a' expression" (typeof kont) (typeof node))) (proc (with-access::Kont kont (name) name)) (fname (cadr loc)) (location (caddr loc)) (stack (if (isa? kont Kont) (with-access::Kont kont (node link) (let loop ((link link) (stack '())) (if link (with-access::Kont link (link name node) (loop link (cons (format "~a kont: ~a ~a ~a" (typeof node) (typeof link) name (if (>fx (bigloo-debug) 2) (call-with-output-string (lambda (p) (display " ") (display (j2s->sexp node) p) (newline p))) "")) stack))) (reverse! stack)))) (get-trace-stack)))))))) ;*---------------------------------------------------------------------*/ ;* cps-fun! ::J2SNode ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (cps-fun! this::J2SNode r::procedure conf) (call-default-walker)) ;*---------------------------------------------------------------------*/ ;* cps-fun! ::J2SFun ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (cps-fun! this::J2SFun r::procedure conf) (with-access::J2SFun this (generator body name constrsize loc decl params thisp argumentsp %info) (if generator (let ((k (KontStmt kid this #f "J2SFun")) (ydstar (has-yield*? body))) (set! body (blockify body (cps body k r '() '() this conf))) (let ((temps (delete-duplicates! (collect-temps* this) eq?))) ;; collect all locals used in the generator (for-each (lambda (d) (with-access::J2SDecl d (%info) (set! %info (instantiate::KDeclInfo)))) temps) ;; cps has introduced new closures, the variable "escape" ;; property must be recomputed. (mark-free body '()) (if (config-get conf :optim-cps-closure-alloc #f) (begin ;; mark the generator arguments (for-each (lambda (d) (when (isa? d J2SDecl) (mark-def! d))) (cons* decl thisp argumentsp params)) ;; retain free variables (let ((frees (filter is-free? temps))) (let* ((temps (filter (lambda (d) (or (is-def? d) (if (decl-usage-has? d '(assig)) (begin (mark-ignored! d) #f) #t))) frees)) (sz (length temps))) ;; color the continuation variables (set! constrsize (kont-color temps ydstar)) ;; allocate temporaries (kont-alloc-temp! this (filter (lambda (d) (with-access::J2SDecl d (%info) (with-access::KDeclInfo %info (def) (not def)))) temps)) this))) (begin (set! constrsize 0) this)))) (begin (cps-fun! body r conf) this)))) ;*---------------------------------------------------------------------*/ ;* SeqBlock ... */ ;*---------------------------------------------------------------------*/ (define (SeqBlock this::J2SSeq n m) (let ((res (dup this))) (with-access::J2SSeq res (nodes) (if (or (eq? (object-class m) J2SSeq) (eq? (object-class m) J2SBlock)) (with-access::J2SSeq m ((seq nodes)) (set! nodes (cons n seq))) (set! nodes (list n m)))) res)) ;*---------------------------------------------------------------------*/ ;* dup ... */ ;*---------------------------------------------------------------------*/ (define (dup this::J2SNode) (let* ((clazz (object-class this)) (ctor (class-constructor clazz)) (inst ((class-allocator clazz))) (fields (class-all-fields clazz))) ;; instance fields (let loop ((i (-fx (vector-length fields) 1))) (when (>=fx i 0) (let* ((f (vector-ref-ur fields i)) (v ((class-field-accessor f) this))) ((class-field-mutator f) inst v) (loop (-fx i 1))))) ;; constructor (when (procedure? ctor) ctor inst) inst)) ;*---------------------------------------------------------------------*/ ;* dup-assig ... */ ;*---------------------------------------------------------------------*/ (define (dup-assig this l r) (let ((n (dup this))) (with-access::J2SAssig n (lhs rhs) (set! lhs l) (set! rhs r) n))) ;*---------------------------------------------------------------------*/ ;* blockify ... */ ;*---------------------------------------------------------------------*/ (define (blockify::J2SBlock block::J2SBlock stmt::J2SStmt) (if (isa? stmt J2SBlock) stmt (duplicate::J2SBlock block (nodes (list stmt))))) ;*---------------------------------------------------------------------*/ ;* cps* ... */ ;*---------------------------------------------------------------------*/ (define (cps*::J2SNode nodes::pair-nil k* r* kbreaks kcontinues fun conf) (assert-kont k* KontExpr* nodes) (let loop ((nodes nodes) (knodes '())) (if (null? nodes) (kcall k* (reverse! knodes)) (cps (car nodes) (KontExpr (lambda (kexpr::J2SExpr) (loop (cdr nodes) (cons kexpr knodes))) nodes k*) r* kbreaks kcontinues fun conf)))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SNode ... */ ;*---------------------------------------------------------------------*/ (define-generic (cps::J2SNode this::J2SNode k r kbreaks::pair-nil kcontinues::pair-nil fun::J2SFun conf) (warning "cps: should not be here " (typeof this)) (kcall k this)) ;*---------------------------------------------------------------------*/ * cps : : ... * / ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SYield k r kbreaks kcontinues fun conf) (define (stmtify n) (if (isa? n J2SStmt) n (with-access::J2SExpr n (loc) (J2SStmtExpr n)))) (define (make-yield-kont k loc) (let ((arg (J2SParam '(call ref) (gensym '%arg) :vtype 'any)) (exn (J2SParam '(ref) (gensym '%exn) :vtype 'bool))) (J2SKont arg exn (r (J2SIf (J2SBinary 'eq? (J2SRef exn) (J2SBool #t)) (J2SThrow (J2SRef arg)) (stmtify (kcall k (J2SRef arg)))))))) (define (make-yield*-kont k loc) (let ((arg (J2SParam '(call ref) (gensym '%arg) :vtype 'any)) (exn (J2SParam '(ref) (gensym '%exn) :vtype 'bool))) (J2SKont arg exn (stmtify (kcall k (J2SRef arg)))))) (with-access::J2SYield this (loc expr generator) (let ((kont (if generator (make-yield*-kont k loc) (make-yield-kont k loc)))) (cps expr (KontExpr (lambda (kexpr::J2SExpr) (J2SReturnYield kexpr kont generator)) this k) r kbreaks kcontinues fun conf)))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SReturn ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SReturn k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SReturn this (loc expr) (cps expr (KontExpr (lambda (kexpr::J2SExpr) (J2SReturnYield kexpr (J2SUndefined) #f)) this k) r kbreaks kcontinues fun conf))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SExpr ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SExpr k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (kcall k this)) ;*---------------------------------------------------------------------*/ ;* cps ::J2SLiteral ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SLiteral k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (kcall k this)) ;*---------------------------------------------------------------------*/ ;* cps ::J2SFun ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SFun k r breaks kcontinues fun conf) (assert-kont k KontExpr this) (kcall k (cps-fun! this r conf))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SRef ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SRef k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (kcall k this)) ;*---------------------------------------------------------------------*/ ;* cps ::J2SParen ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SParen k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (with-access::J2SParen this (expr) (cps expr k r kbreaks kcontinues fun conf))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SUnary ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SUnary k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (with-access::J2SUnary this (expr) (cps expr (KontExpr (lambda (kexpr::J2SExpr) (kcall k (duplicate::J2SUnary this (expr kexpr)))) this k) r kbreaks kcontinues fun conf))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SBinary ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SBinary k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (with-access::J2SBinary this (lhs rhs loc op) (case op ((OR OR*) (cps lhs (KontExpr (lambda (klhs::J2SExpr) (cps (J2SCond klhs klhs rhs) (KontExpr (lambda (krhs::J2SExpr) (kcall k krhs)) this k) r kbreaks kcontinues fun conf)) this k) r kbreaks kcontinues fun conf)) ((&&) (cps (J2SCond lhs rhs (J2SBool #f)) k r kbreaks kcontinues fun conf)) (else (cps lhs (KontExpr (lambda (klhs::J2SExpr) (cps rhs (KontExpr (lambda (krhs::J2SExpr) (kcall k (duplicate::J2SBinary this (lhs klhs) (rhs krhs)))) this k) r kbreaks kcontinues fun conf)) this k) r kbreaks kcontinues fun conf))))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SSequence ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SSequence k r kbreaks kcontinues fun conf) (define (seqify this kar kdr) (if (isa? kdr J2SSequence) (with-access::J2SSequence kdr (exprs) (duplicate::J2SSequence this (exprs (cons kar exprs)))) (duplicate::J2SSequence this (exprs (list kar kdr))))) (assert-kont k KontExpr this) (with-access::J2SSequence this (exprs loc) (cond ((null? exprs) (kcall k this)) ((null? (cdr exprs)) (cps (car exprs) k r kbreaks kcontinues fun conf)) (else (cps (car exprs) (KontExpr (lambda (kar::J2SExpr) (cps (duplicate::J2SSequence this (exprs (cdr exprs))) (KontExpr (lambda (kdr::J2SExpr) (kcall k (seqify this kar kdr))) this k) r kbreaks kcontinues fun conf)) this k) r kbreaks kcontinues fun conf))))) ;*---------------------------------------------------------------------*/ ;* cps ::%J2STail ... */ ;* ------------------------------------------------------------- */ * J2STail are introduced by the CPS conversion of loops . * / ;*---------------------------------------------------------------------*/ (define-method (cps this::%J2STail k r kbreaks kcontinues fun conf) (with-access::%J2STail this (loc expr) this)) ;*---------------------------------------------------------------------*/ ;* cps ::J2SNop ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SNop k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (kcall k this)) ;*---------------------------------------------------------------------*/ * cps : : ... * / ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SStmtExpr k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SStmtExpr this (loc expr) (cps expr (KontExpr (lambda (kexpr::J2SExpr) (kcall k (J2SStmtExpr kexpr))) this k "expr") r kbreaks kcontinues fun conf))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SSeq ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SSeq k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SSeq this (loc nodes) (if (null? nodes) (kcall k this) (let loop ((walk nodes)) (if (null? (cdr walk)) (cps (car walk) k r kbreaks kcontinues fun conf) (cps (car walk) (KontStmt (lambda (n) (SeqBlock this n (loop (cdr walk)))) this k) r kbreaks kcontinues fun conf)))))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SIf ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SIf k r kbreaks kcontinues fun conf) (define (cps-if-tramp this tramp) (with-access::J2SIf this (loc test then else) (let ((kont (KontStmt (lambda (n) (J2SSeq n (J2SReturn #t tramp fun))) this k))) (cps test (KontExpr (lambda (ktest::J2SExpr) (duplicate::J2SIf this (test ktest) (then (cps then kont r kbreaks kcontinues fun conf)) (else (cps else kont r kbreaks kcontinues fun conf)))) this k) r kbreaks kcontinues fun conf)))) (define (cps-if-cont this kbody) (with-access::J2SIf this (loc test then else) (let* ((name (gensym '%kif)) (endloc (node-endloc this)) (kyield (J2SParam '(ref) '%yield :vtype 'any)) (kthis (J2SParam '(ref) '%this :vtype 'any)) (kfun (J2SArrowKont name (list kyield kthis) (J2SBlock kbody))) (kdecl (J2SLetOpt '(call) name kfun)) (kont (KontStmt (lambda (n) (J2SSeq n (J2SReturn #t (J2SKontCall kdecl) fun))) this k)) (endloc (node-endloc this))) (cps test (KontExpr (lambda (ktest::J2SExpr) (J2SLetRecBlock #f (list kdecl) (duplicate::J2SIf this (test ktest) (then (cps then kont r kbreaks kcontinues fun conf)) (else (cps else kont r kbreaks kcontinues fun conf))))) this k) r kbreaks kcontinues fun conf)))) (assert-kont k KontStmt this) (with-access::J2SIf this (loc test then else) (let* ((kbody (kcall k (J2SNop))) (tramp (ktrampoline kbody))) (if tramp ;; optimized version without new continuation (cps-if-tramp this tramp) normat (cps-if-cont this kbody))))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SDecl ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SDecl k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (kcall k this)) ;*---------------------------------------------------------------------*/ ;* cps ::J2SDeclInit ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SDeclInit k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SDeclInit this (val) (if (not (j2s-let-opt? this)) (kcall k this) (cps val (KontExpr (lambda (kval::J2SExpr) ;; must reuse the existing binding ;; in order to preserve the AST inner pointers (set! val kval) (kcall k this)) this k) r kbreaks kcontinues fun conf)))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SDeclFun ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SDeclFun k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SDeclFun this (val) (cps-fun! val r conf) (kcall k this))) ;*---------------------------------------------------------------------*/ * cps : : J2SVarDecls ... * / ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SVarDecls k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SVarDecls this (decls) (map! (lambda (decl) (cps decl k r kbreaks kcontinues fun conf)) decls) (kcall k this))) ;*---------------------------------------------------------------------*/ ;* cps ::j2SLetBlock ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SLetBlock k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SLetBlock this (rec loc endloc decls nodes) (cond ((not rec) (let loop ((decls decls)) (if (null? decls) (cps (duplicate::J2SBlock this (nodes nodes)) k r kbreaks kcontinues fun conf) (with-access::J2SDecl (car decls) (scope) (set! scope 'kont) (cps (car decls) (KontStmt (lambda (ndecl::J2SStmt) (J2SLetRecBlock #f (list ndecl) (loop (cdr decls)))) this k) r kbreaks kcontinues fun conf))))) ((not (any (lambda (d) (or (not (isa? d J2SDeclInit)) (with-access::J2SDeclInit d (val) (yield-expr? val kbreaks kcontinues)))) decls)) (J2SLetBlock decls (cps (duplicate::J2SBlock this (nodes nodes)) k r kbreaks kcontinues fun conf))) (else (let* ((ndecls (map (lambda (d) (if (isa? d J2SDeclInit) (with-access::J2SDeclInit d (loc) (duplicate::J2SDeclInit d (key (ast-decl-key)) (val (J2SUndefined)))) d)) decls)) (olds (filter (lambda (d) (isa? d J2SDeclInit)) decls)) (news (filter (lambda (d) (isa? d J2SDeclInit)) ndecls)) (assigs (filter-map (lambda (d nd) (when (isa? d J2SDeclInit) (with-access::J2SDeclInit d (loc val) (J2SStmtExpr (J2SAssig (J2SRef nd) (j2s-alpha val olds news)))))) decls ndecls)) (anodes (map (lambda (n) (j2s-alpha n olds news)) nodes))) (cps (J2SLetRecBlock* #f ndecls (cons (J2SSeq* assigs) anodes)) k r kbreaks kcontinues fun conf)))))) ;*---------------------------------------------------------------------*/ * cps : : ... * / ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SBindExit k r kbreaks kcontinues fun conf) (define (make-kont-fun-call loc decl) (J2SKontCall decl)) (assert-kont k KontExpr this) (with-access::J2SBindExit this (stmt lbl loc) (cond ((not (yield-expr? this kbreaks kcontinues)) (set! stmt (cps-fun! stmt r conf)) (kcall k this)) (lbl in order to inline code generator , the j2sreturn CPS ;; transformation must know how to map its lbl to a contination (error "cps" "generator cannot use inline expression" loc)) (else (cps stmt (KontStmt (lambda (kstmt::J2SStmt) (set! stmt kstmt) (kcall k this)) this k) r kbreaks kcontinues fun conf))))) ;*---------------------------------------------------------------------*/ * cps : : ... * / ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SFor k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SFor this (loc init test incr body id) (cond ((yield-expr? init kbreaks kcontinues) (let ((i init)) (set! init (J2SNop)) (cps (J2SSeq (J2SStmtExpr i) this) k r kbreaks kcontinues fun conf))) ((let* ((cell (cons this #t)) (kbreaks+ (cons cell kbreaks)) (kcontinues+ (cons cell kcontinues))) (or (yield-expr? test kbreaks kcontinues) (yield-expr? incr kbreaks kcontinues) (yield-expr? body kbreaks+ kcontinues+))) ;; K( for( ; test; incr ) body ) ;; --> ;; (letrec ((for (lambda () (K (if test (begin body incr (for))))))) ;; (for)) ;; If break is used ( let ( ( kfun ( function ( ) ( K ( js - undefined ) ) ) ) ) ( ( ( for ( lambda ( ) ( ( if test ( begin body incr ( for ) ) ) ) ) ) ) ;; (for))) ;; If continue is used ( let ( ( kfun ( function ( ) ( K ( js - undefined ) ) ) ) ) ( ( ( for ( lambda ( ) ( ( if test ( begin body incr ( for ) ) ) ) ) ) ) ;; (for))) ;; (let* ((fname (gensym '%kfor)) (bname (gensym '%kbreak)) (cname (gensym '%kcontinue)) (endloc (node-endloc this)) (block (J2SBlock)) (fyield (J2SParam '(ref) '%yield :vtype 'any)) (fthis (J2SParam '(ref) '%this :vtype 'any)) (for (J2SArrowKont fname (list fyield fthis) block)) (decl (J2SLetOpt '(call) fname for)) (byield (J2SParam '(ref) '%yield :vtype 'any)) (bthis (J2SParam '(ref) '%this :vtype 'any)) (break (J2SArrowKont bname (list byield bthis) (J2SBlock (kcall k (J2SStmtExpr (J2SUndefined)))))) (fbody (J2SBlock (J2SStmtExpr incr) (%J2STail (J2SKontCall decl) fun))) (cyield (J2SParam '(ref) '%yield :vtype 'any)) (cthis (J2SParam '(ref) '%this :vtype 'any)) (conti (J2SArrowKont cname (list cyield cthis) (blockify fbody (cps fbody (KontStmt kid this k) r kbreaks kcontinues fun conf)))) (bdecl (J2SLetOpt '(call) bname break)) (cdecl (J2SLetOpt '(call) cname conti)) (then (J2SBlock body (%J2STail (J2SKontCall cdecl) fun))) (stop (J2SBlock (%J2STail (J2SKontCall bdecl) fun))) (node (J2SIf test then stop))) (with-access::J2SBlock block (nodes) (set! nodes (list (cps node (KontStmt kid this k) r (cons (cons this bdecl) kbreaks) (cons (cons this cdecl) kcontinues) fun conf)))) (J2SLetBlock (list decl bdecl cdecl) (if (isa? init J2SExpr) (J2SStmtExpr init) init) (%J2STail (J2SKontCall decl) fun)))) (else (set! init (cps-fun! init r conf)) (set! test (cps-fun! test r conf)) (set! incr (cps-fun! incr r conf)) (set! body (cps-fun! body r conf)) (kcall k this))))) ;*---------------------------------------------------------------------*/ * cps : : ... * / ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SForIn k r kbreaks kcontinues fun conf) (define (cps-for-in this::J2SForIn) (with-access::J2SForIn this (loc lhs obj body) (let* ((v (gensym '%kkeys)) (l (gensym '%klen)) (i (gensym '%ki)) (endloc (node-endloc this)) (keys (J2SLetOptVtype 'array '(ref) v (J2SCall (J2SAccess (J2SUnresolvedRef 'Object) (J2SString "keys")) obj))) (len (J2SLetOpt '(ref) l (J2SAccess (J2SRef keys) (J2SString "length")))) (idx (J2SLetOpt '(assig ref) i (J2SNumber 0))) (for (J2SFor (J2SUndefined) (J2SBinary '< (J2SRef idx) (J2SRef len)) (J2SPostfix '++ (J2SRef idx) (J2SBinary '+ (J2SRef idx) (J2SNumber 1))) (J2SBlock (J2SStmtExpr (J2SAssig lhs (J2SAccess (J2SRef keys) (J2SRef idx)))) body)))) (J2SLetBlock (list keys len idx) (cps for k r kbreaks kcontinues fun conf))))) (define (cps-for-of this::J2SForIn) (with-access::J2SForIn this (loc op lhs obj body) (let* ((o (gensym '%kobj)) (f (gensym '%kfun)) (i (gensym '%kit)) (n (gensym '%knext)) (v (gensym '%kval)) (endloc (node-endloc this)) (kobj (J2SLetOpt '(ref) o obj)) (kfun (J2SLetOpt '(ref) f (J2SAccess (J2SRef kobj) (J2SAccess (J2SUnresolvedRef 'Symbol) (J2SString "iterator"))))) (kit (J2SLetOpt '(ref) i (J2SKontCall kfun (J2SRef kobj)))) (knext (J2SLetOpt '(ref) n (J2SAccess (J2SRef kit) (J2SString "next")))) (kval (J2SLetOpt '(ref assig) v (J2SKontCall knext (J2SRef kit)))) (for (J2SFor (J2SUndefined) (J2SUnary '! (J2SAccess (J2SRef kval) (J2SString "done"))) (J2SAssig (J2SRef kval) (J2SCall (J2SAccess (J2SRef kit) (J2SString "next")))) (J2SBlock (J2SStmtExpr (J2SAssig lhs (J2SAccess (J2SRef kval) (J2SString "value")))) body)))) (J2SLetBlock (list kobj kfun kit knext kval) (cps for k r kbreaks kcontinues fun conf))))) (assert-kont k KontStmt this) (with-access::J2SForIn this (loc lhs obj body op) (cond ((yield-expr? obj kbreaks kcontinues) (cps obj (KontExpr (lambda (kobj) (cps (duplicate::J2SForIn this (obj kobj)) k r kbreaks kcontinues fun conf)) this k) r kbreaks kcontinues fun conf)) ((let* ((cell (cons this #t)) (kbreaks+ (cons cell kbreaks)) (kcontinues+ (cons cell kcontinues))) (yield-expr? body kbreaks+ kcontinues+)) (if (eq? op 'in) (cps-for-in this) (cps-for-of this))) (else (set! lhs (cps-fun! lhs r conf)) (set! body (cps-fun! body r conf)) (kcall k this))))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SWhile ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SWhile k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SWhile this (test body loc) (let* ((kname (gensym '%kwhile)) (bname (gensym '%kbreak)) (cname (gensym '%kcontinue)) (endloc (node-endloc this)) (block (J2SBlock)) (wyield (J2SParam '(ref) '%yield :vtype 'any)) (warg (J2SParam '(ref) '%this :vtype 'any)) (while (J2SArrowKont kname (list wyield warg) block)) (wdecl (J2SLetOpt '(call) kname while)) (barg (J2SParam '(ref) '%this :vtype 'any)) (byield (J2SParam '(ref) '%yield :vtype 'any)) (break (J2SArrowKont bname (list byield barg) (J2SBlock (kcall k (J2SStmtExpr (J2SUndefined)))))) (fbody (J2SBlock (J2SReturn #t (J2SKontCall wdecl) fun))) (cyield (J2SParam '(ref) '%yield :vtype 'any)) (carg (J2SParam '(ref) '%this :vtype 'any)) (conti (J2SArrowKont cname (list cyield carg) fbody)) (bdecl (J2SLetOpt '(call) bname break)) (cdecl (J2SLetOpt '(call) cname conti)) (then (J2SBlock body (%J2STail (J2SKontCall wdecl) fun))) (else (J2SBlock (%J2STail (J2SKontCall bdecl) fun))) (node (J2SIf test then else))) (with-access::J2SBlock block (nodes) (set! nodes (list (cps node (KontStmt kid this k) r (cons (cons this bdecl) kbreaks) (cons (cons this cdecl) kcontinues) fun conf)))) (J2SLetBlock (list wdecl bdecl cdecl) (J2SReturn #t (J2SKontCall wdecl) fun))))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SDo ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SDo k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SDo this (test body loc) (let* ((name (gensym '%kdo)) (bname (gensym '%kbreak)) (cname (gensym '%kcontinue)) (tname (gensym '%ktmp)) (endloc (node-endloc this)) (block (J2SBlock)) (wyield (J2SParam '(ref) '%yield :vtype 'any)) (wthis (J2SParam '(ref) '%this :vtype 'any)) (while (J2SArrowKont name (list wyield wthis) block)) (decl (J2SLetOpt '(call) name while)) (declv (J2SLetOpt '(assig ref) tname (J2SBool #t))) (cyield (J2SParam '(ref) '%yield :vtype 'any)) (cthis (J2SParam '(ref) '%this :vtype 'any)) (conti (J2SArrowKont name (list cyield cthis) (J2SBlock (cps (J2SIf (J2SCond test (J2SRef declv) (J2SBool #f)) (%J2STail (J2SKontCall decl) fun) (J2SNop)) k r kbreaks kcontinues fun conf)))) (cdecl (J2SLetOpt '(call) cname conti)) (byield (J2SParam '(ref) '%yield :vtype 'any)) (bthis (J2SParam '(ref) '%this :vtype 'any)) (break (J2SArrowKont name (list byield bthis) (J2SBlock (J2SStmtExpr (J2SAssig (J2SRef declv) (J2SBool #f))) (%J2STail (J2SKontCall cdecl) fun)))) (bdecl (J2SLetOpt '(call) bname break)) (else (J2SBlock (%J2STail (J2SKontCall bdecl) fun))) (sbody (J2SSeq body (%J2STail (J2SKontCall cdecl) fun)))) (with-access::J2SBlock block (nodes) (set! nodes (list (cps sbody (KontStmt kid this k) r (cons (cons this bdecl) kbreaks) (cons (cons this cdecl) kcontinues) fun conf)))) (J2SLetBlock (list declv decl bdecl cdecl) (J2SReturn #t (J2SKontCall decl) fun))))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SBreak ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SBreak k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SBreak this (loc target) (cond ((assq target kbreaks) => (lambda (c) (let ((kont (cdr c))) (J2SReturn #t (J2SKontCall kont) fun)))) (else (kcall k this))))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SContinue ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SContinue k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SContinue this (loc target) (cond ((assq target kcontinues) => (lambda (c) (let ((kont (cdr c))) (J2SReturn #t (J2SKontCall kont) fun)))) (else (kcall k this))))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SAssig ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SAssig k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (with-access::J2SAssig this (lhs rhs) (cps lhs (KontExpr (lambda (klhs::J2SExpr) (cps rhs (KontExpr (lambda (krhs::J2SExpr) (kcall k (dup-assig this klhs krhs))) this k) r kbreaks kcontinues fun conf)) this k) r kbreaks kcontinues fun conf))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SDProducer ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SDProducer k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (with-access::J2SDProducer this (expr) (cps expr (KontExpr (lambda (kexpr::J2SExpr) (kcall k (duplicate::J2SDProducer this (expr kexpr)))) this k) r kbreaks kcontinues fun conf))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SCall ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SCall k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (with-access::J2SCall this ((callee fun) args) (cond ((yield-expr? callee kbreaks kcontinues) (cps callee (KontExpr (lambda (kfun::J2SExpr) (set! callee kfun) (cps this k r kbreaks kcontinues fun conf)) this k) r kbreaks kcontinues fun conf)) ((any (lambda (e) (yield-expr? e kbreaks kcontinues)) args) (cps-fun! callee r conf) (cps* args (KontExpr* (lambda (kargs::pair-nil) (set! args kargs) (cps this k r kbreaks kcontinues fun conf)) args k) r kbreaks kcontinues fun conf)) (else (cps-fun! callee r conf) (for-each (lambda (n) (cps-fun! n r conf)) args) (kcall k this))))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SArray ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SArray k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (with-access::J2SArray this (exprs) (if (any (lambda (e) (yield-expr? e kbreaks kcontinues)) exprs) (cps* exprs (KontExpr* (lambda (kexprs::pair-nil) (set! exprs kexprs) (cps this k r kbreaks kcontinues fun conf)) exprs k) r kbreaks kcontinues fun conf) (begin (set! exprs (map! (lambda (n) (cps-fun! n r conf)) exprs )) (kcall k this))))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SCond ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SCond k r kbreaks kcontinues fun conf) (define (make-kont-decl loc endloc k) (assert-kont k KontExpr this) (let* ((name (gensym '%kcond)) (arg (J2SParam '(call ref) (gensym '%arg) :vtype 'any)) (kyield (J2SParam '(ref) '%yield :vtype 'any)) (kthis (J2SParam '(ref) '%this :vtype 'any)) (kfun (J2SArrowKont name (list kyield kthis arg) (J2SBlock (kcall k (J2SRef arg)))))) (J2SLetOpt '(call) name kfun))) (define (make-kont-fun-call loc decl expr) (J2SKontCall decl (J2SHopRef '%gen) expr)) (assert-kont k KontExpr this) (with-access::J2SCond this (test then else loc) (cond ((yield-expr? test kbreaks kcontinues) (cps test (KontExpr (lambda (ktest::J2SExpr) (set! test ktest) (cps this k r kbreaks kcontinues fun conf)) this k "test") r kbreaks kcontinues fun conf)) ((or (yield-expr? then kbreaks kcontinues) (yield-expr? else kbreaks kcontinues)) (let* ((endloc (node-endloc this)) (decl (make-kont-decl loc endloc k)) (kc (lambda (b) (J2SReturn #t (make-kont-fun-call loc decl b) fun))) (kif (J2SIf (cps-fun! test r conf) (cps then (KontExpr kc this k) r kbreaks kcontinues fun conf) (cps else (KontExpr kc this k) r kbreaks kcontinues fun conf)))) (J2SLetBlock (list decl) kif))) (else (set! test (cps-fun! test r conf)) (set! then (cps-fun! then r conf)) (set! else (cps-fun! else r conf)) (kcall k this))))) ;*---------------------------------------------------------------------*/ ;* cps ::J2STry ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2STry k r kbreaks kcontinues fun conf) (define (Catch loc endloc declc::J2SDecl param) (J2SCatch param (J2SBlock (%J2STail (J2SKontCall declc (J2SHopRef '%gen) (J2SRef param)) fun)))) (define (FinallyCatch finally k r kbreaks kcontinues fun) (with-access::J2SNode finally (loc) (let ((eparam (J2SParam '(ref) (gensym '%exc) :vtype 'any))) (J2SCatch eparam (cps finally (KontStmt (lambda (n) (J2SSeq n (J2SThrow (J2SRef eparam)))) this k) r kbreaks kcontinues fun conf))))) (define (FinallyCatchThrow finally k r kbreaks kcontinues fun) (with-access::J2SNode finally (loc) (let ((eparam (J2SParam '(ref) (gensym '%exc) :vtype 'any))) (J2SCatch eparam (cps finally (KontStmt (lambda (n) (J2SSeq n (J2SThrow (J2SRef eparam)))) this k) r kbreaks kcontinues fun conf))))) (define (cps-try-catch this body catch loc) ;; try/catch only (let* ((endloc (node-endloc this)) (cname (gensym '%kcatch)) (cyield (J2SParam '(ref) '%yield :vtype 'any)) (cthis (J2SParam '(ref) '%this :vtype 'any)) (catch (with-access::J2SCatch catch (param (cbody body)) (J2SArrowKont cname (list cyield cthis param) (J2SBlock (cps cbody k r kbreaks kcontinues fun conf))))) (declc (J2SLetOpt '(call) cname catch)) (eparam (J2SParam '(ref) (gensym '%exc) :vtype 'any))) (J2SLetBlock (list declc) (J2STry (blockify body (cps body k (lambda (n) (r (J2STry (blockify body n) (Catch loc endloc declc eparam)))) kbreaks kcontinues fun conf)) (Catch loc endloc declc eparam))))) (define (cps-try-finally-gen this body finally loc) (let* ((endloc (node-endloc this)) (gen (J2SFun* (gensym '%trybody) '() (J2SBlock))) (mark (J2SLetOpt '(ref) (gensym '%mark) (J2SPragma '(cons #f #f)))) (gbody (J2SBlock body (J2SReturn #t (J2SRef mark)))) (declg (J2SLetOpt '(ref assig) (gensym '%gen) (J2SCall gen))) (gval (J2SLetOpt '(ref assig) (gensym '%yield*) (J2SYield (J2SRef declg) gen)))) (with-access::J2SFun gen (body) (set! body gbody)) (J2STry (cps (J2SLetRecBlock #f (list mark declg) (J2SLetRecBlock #f (list gval) finally (J2SIf (J2SBinary/type '!== 'bool (J2SRef gval) (J2SRef mark)) (J2SReturn #f (J2SRef gval)) (J2SNop)))) k (lambda (n) (r (J2STry (blockify body n) (FinallyCatch finally k r kbreaks kcontinues fun)))) kbreaks kcontinues fun conf) (FinallyCatch finally k r kbreaks kcontinues fun)))) (define (cps-try-finally-explicit this body finally loc) (let* ((endloc (node-endloc finally)) (gen (J2SFun* (gensym '%gen) '() (J2SBlock))) (gbody (J2SBlock body (J2SReturn #t (J2SUndefined) gen))) (declg (J2SLetOpt '(ref assig) (gensym '%gen) (J2SCall gen))) (decln (J2SLetOpt '(ref assig) (gensym '%next) (J2SCall (J2SAccess (J2SRef declg) (J2SString "next")))))) (with-access::J2SFun gen (body) (set! body gbody)) (J2STry (cps (J2SLetBlock (list declg) (J2SLetBlock (list decln) (J2SWhile (J2SUnary/type '! 'bool (J2SAccess (J2SRef decln) (J2SString "done"))) (J2SSeq (J2SStmtExpr (J2SYield (J2SAccess (J2SRef decln) (J2SString "value")) #f)) (J2SStmtExpr (J2SAssig (J2SRef decln) (J2SCall (J2SAccess (J2SRef declg) (J2SString "next"))))))) (J2SSeq finally (J2SAccess (J2SRef decln) (J2SString "value"))))) k r kbreaks kcontinues fun conf) (FinallyCatch finally k r kbreaks kcontinues fun)))) (define (cps-try-finally-tmp this body finally loc) (J2STry (blockify body (cps (J2SSeq body finally) k (lambda (n) (r (J2STry (blockify body n) (FinallyCatch finally k r kbreaks kcontinues fun) (cps finally k r kbreaks kcontinues fun conf)))) kbreaks kcontinues fun conf)) (FinallyCatch finally k r kbreaks kcontinues fun) (cps finally k r kbreaks kcontinues fun conf))) (define (cps-try-finally-throw this body finally loc) (let ((eparam (J2SParam '(ref) (gensym '%exc) :vtype 'any)) (ret (J2SLetOpt '(ref assig) (gensym '%ret) (J2SBool #f))) (exn (J2SLetOpt '(ref assig) (gensym '%exn) (J2SBool #f))) (val (J2SLetOpt '(ref assig) (gensym '%val) (J2SUndefined))) (endloc (node-endloc finally))) (cps (J2SLetBlock (list ret exn val) (J2STry (retthrow! body ret '()) (J2SCatch eparam (J2SBlock (J2SStmtExpr (J2SAssig (J2SRef val) (J2SRef eparam))) (if (J2SUnary/type '! 'bool (J2SRef ret)) (J2SStmtExpr (J2SAssig (J2SRef exn) (J2SBool #t))) (J2SNop))))) finally (J2SIf (J2SRef ret) (J2SReturn #f (J2SRef val) fun) (J2SNop)) (J2SIf (J2SRef exn) (J2SThrow (J2SRef val)) (J2SNop))) k r kbreaks kcontinues fun conf))) (define (cps-try-catch-finally this body catch finally loc) ;; try/catch/finally (cps (J2STry (blockify body (J2STry body catch (J2SNop))) (J2SNop) finally) k r kbreaks kcontinues fun conf)) (assert-kont k KontStmt this) (with-access::J2STry this (loc body catch finally) (cond ((and (isa? catch J2SNop) (isa? finally J2SNop)) (cps body k r kbreaks kcontinues fun conf)) ((isa? finally J2SNop) (cps-try-catch this body catch loc)) ((isa? catch J2SNop) (cps-try-finally-throw this body finally loc)) (else (cps-try-catch-finally this body catch finally loc))))) ;*---------------------------------------------------------------------*/ * cps : : J2SThrow ... * / ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SThrow k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SThrow this (loc expr) (if (yield-expr? expr kbreaks kcontinues) (cps expr (KontExpr (lambda (kexpr::J2SExpr) (kcall k (J2SThrow kexpr))) this k) r kbreaks kcontinues fun conf) (begin (set! expr (cps-fun! expr r conf)) (kcall k this))))) ;*---------------------------------------------------------------------*/ ;* cps ::J2SSwitch ... */ ;*---------------------------------------------------------------------*/ (define-method (cps this::J2SSwitch k r kbreaks kcontinues fun conf) (define (switch->if key tmp clause) (with-access::J2SCase clause (loc expr body) (if (isa? clause J2SDefault) body (let ((endloc (node-endloc body))) (J2SIf (J2SBinary 'OR (J2SRef tmp) (J2SBinary '=== (J2SRef key) expr)) (J2SBlock (J2SStmtExpr (J2SAssig (J2SRef tmp) (J2SBool #t))) body) (J2SNop)))))) (assert-kont k KontStmt this) (with-access::J2SSwitch this (loc key cases need-bind-exit-break) (cond ((yield-expr? key kbreaks kcontinues) (cps key (KontExpr (lambda (kkey::J2SExpr) (with-access::J2SSwitch this (key) ;; if here a duplication is preferred to ;; a mutation, don't forget to update the ;; kbreaks set otherwise J2SBreak will be ;; badly compiled (set! key kkey) (cps this k r kbreaks kcontinues fun conf))) this k) r kbreaks kcontinues fun conf)) ((not (any (lambda (c) (yield-expr? c kbreaks kcontinues)) cases)) (set! key (cps-fun! key r conf)) (for-each (lambda (clause) (with-access::J2SCase clause (expr body) (set! expr (cps-fun! expr r conf)) (set! body (cps-fun! body r conf)))) cases) (kcall k this)) (else (set! key (cps-fun! key r conf)) (let* ((v (gensym '%kkey)) (t (gensym '%ktmp)) (key (J2SLetOpt '(ref) v key)) (tmp (J2SLetOpt '(assig ref) t (J2SBool #f))) (seq (J2SSeq* (map (lambda (clause) (switch->if key tmp clause)) cases))) (endloc (node-endloc this))) (if need-bind-exit-break (let* ((bname (gensym '%kbreak)) (byield (J2SParam '(ref) '%yield :vtype 'any)) (bthis (J2SParam '(ref) '%this :vtype 'any)) (break (J2SArrowKont bname (list byield bthis) (J2SBlock (J2SBlock (kcall k (J2SStmtExpr (J2SUndefined))))))) (bdecl (J2SLetOpt '(call) bname break))) (J2SLetBlock (list key tmp bdecl) (cps seq k r (cons (cons this bdecl) kbreaks) kcontinues fun conf))) (J2SLetBlock (list key tmp) (cps seq k r kbreaks kcontinues fun conf)))))))) ;*---------------------------------------------------------------------*/ ;* has-yield*? ... */ ;*---------------------------------------------------------------------*/ (define (has-yield*? this) (any (lambda (n) (cond ((isa? n J2SYield) (with-access::J2SYield n (generator) generator)) ((isa? n J2SReturnYield) (with-access::J2SReturnYield n (generator) generator)))) (yield-expr* this '() '() '()))) ;*---------------------------------------------------------------------*/ ;* yield-expr? ... */ ;*---------------------------------------------------------------------*/ (define (yield-expr? this kbreaks kcontinues) (pair? (yield-expr* this kbreaks kcontinues '()))) ;*---------------------------------------------------------------------*/ ;* yield-expr* ::J2SNode ... */ ;* ------------------------------------------------------------- */ * Returns # t iff a statement contains a YIELD . Otherwise * / ;* returns #f. */ ;*---------------------------------------------------------------------*/ (define-walk-method (yield-expr* this::J2SNode kbreaks kcontinues localrets) (call-default-walker)) ;*---------------------------------------------------------------------*/ * yield - expr * : : ... * / ;*---------------------------------------------------------------------*/ (define-walk-method (yield-expr* this::J2SYield kbreaks kcontinues localrets) (list this)) ;*---------------------------------------------------------------------*/ ;* yield-expr* ::J2SReturn ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (yield-expr* this::J2SReturn kbreaks kcontinues localrets) (with-access::J2SReturn this (from) (cond ((memq from localrets) '()) (else (list this))))) ;*---------------------------------------------------------------------*/ * yield - expr * : : ... * / ;*---------------------------------------------------------------------*/ (define-walk-method (yield-expr* this::J2SReturnYield kbreaks kcontinues localrets) (list this)) ;*---------------------------------------------------------------------*/ * yield - expr * : : ... * / ;*---------------------------------------------------------------------*/ (define-walk-method (yield-expr* this::J2SBindExit kbreaks kcontinues localrets) (with-access::J2SBindExit this (stmt) (yield-expr* stmt kbreaks kcontinues (cons this localrets)))) ;*---------------------------------------------------------------------*/ ;* yield-expr* ::J2SBreak ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (yield-expr* this::J2SBreak kbreaks kcontinues localrets) (with-access::J2SBreak this (target) (if (assq target kbreaks) (list this) '()))) ;*---------------------------------------------------------------------*/ ;* yield-expr* ::J2SContinue ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (yield-expr* this::J2SContinue kbreaks kcontinues localrets) (with-access::J2SContinue this (target) (if (assq target kcontinues) (list this) '()))) ;*---------------------------------------------------------------------*/ ;* yield-expr* ::J2SFun ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (yield-expr* this::J2SFun kbreaks kcontinues localrets) '()) ;*---------------------------------------------------------------------*/ ;* yield-expr* ::J2SCase ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (yield-expr* this::J2SCase kbreaks kcontinues localrets) (with-access::J2SCase this (expr body) (append (yield-expr* expr kbreaks kcontinues localrets) (yield-expr* body kbreaks kcontinues localrets)))) ;*---------------------------------------------------------------------*/ ;* retthrow! ::J2SNode ... */ ;* ------------------------------------------------------------- */ ;* Replace untail return (those of the inlined function) with */ ;* an exit. */ ;*---------------------------------------------------------------------*/ (define-walk-method (retthrow! this::J2SNode decl env) (call-default-walker)) ;*---------------------------------------------------------------------*/ ;* retthrow! ::J2SReturn ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (retthrow! this::J2SReturn decl env) (with-access::J2SReturn this (tail exit from expr loc from) (if (and (not exit) (not (memq from env))) (J2SSeq (J2SStmtExpr (J2SAssig (J2SRef decl) (J2SBool #t))) (J2SThrow (retthrow! expr decl env)) this) (begin (set! expr (retthrow! expr decl env)) this)))) ;*---------------------------------------------------------------------*/ ;* retthrow! ::J2SFun ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (retthrow! this::J2SFun decl env) this) ;*---------------------------------------------------------------------*/ ;* retthrow! ::J2SMethod ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (retthrow! this::J2SMethod decl env) this) ;*---------------------------------------------------------------------*/ ;* collect-temps* ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (collect-temps* this::J2SNode) (call-default-walker)) ;*---------------------------------------------------------------------*/ ;* is-global-or-fun? ... */ ;*---------------------------------------------------------------------*/ (define (is-global-or-fun? decl) (define (is-fun-decl? decl) (when (isa? decl J2SDeclInit) (with-access::J2SDeclInit decl (val) (when (isa? val J2SFun) (not (decl-usage-has? decl '(assig))))))) (with-access::J2SDecl decl (scope) (or (isa? decl J2SDeclExtern) (memq scope '(%scope global tls)) (is-fun-decl? decl)))) ;*---------------------------------------------------------------------*/ ;* collect-temps* ::J2SRef ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (collect-temps* this::J2SRef) (with-access::J2SRef this (decl loc) (if (is-global-or-fun? decl) '() (list decl)))) ;*---------------------------------------------------------------------*/ ;* mark-def! ... */ ;*---------------------------------------------------------------------*/ (define (mark-def!::J2SDecl d) (with-access::J2SDecl d (%info) (when (isa? %info KDeclInfo) (with-access::KDeclInfo %info (def) (set! def #t)))) d) ;*---------------------------------------------------------------------*/ ;* mark-ignored! ... */ ;*---------------------------------------------------------------------*/ (define (mark-ignored!::J2SDecl d) (with-access::J2SDecl d (%info) (set! %info #f)) d) ;*---------------------------------------------------------------------*/ ;* is-free? ... */ ;*---------------------------------------------------------------------*/ (define (is-free? d) (when (isa? d J2SDecl) (with-access::J2SDecl d (%info) (when (isa? %info KDeclInfo) (with-access::KDeclInfo %info (free) free))))) ;*---------------------------------------------------------------------*/ ;* is-def? ... */ ;*---------------------------------------------------------------------*/ (define (is-def? d) (when (isa? d J2SDecl) (with-access::J2SDecl d (%info) (when (isa? %info KDeclInfo) (with-access::KDeclInfo %info (def) def))))) ;*---------------------------------------------------------------------*/ ;* mark-free ::J2SNode ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (mark-free this::J2SNode env) (call-default-walker)) ;*---------------------------------------------------------------------*/ ;* mark-free ::J2SRef ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (mark-free this::J2SRef env) (with-access::J2SRef this (decl loc) (with-access::J2SDecl decl (scope %info id escape) (unless (is-global-or-fun? decl) (with-access::KDeclInfo %info (free) (unless (or free (memq decl env)) (set! escape #t) (set! free #t))))))) ;*---------------------------------------------------------------------*/ ;* mark-free ::J2SKont ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (mark-free this::J2SKont env) (with-access::J2SKont this (body param exn loc) (let ((nenv (list (mark-def! param) (mark-def! exn)))) (mark-free body nenv)))) ;*---------------------------------------------------------------------*/ ;* mark-free ::J2SFun ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (mark-free this::J2SFun env) (with-access::J2SFun this (decl params thisp argumentsp body) (let* ((envp (map! mark-def! params)) (enva (if argumentsp (cons (mark-def! argumentsp) envp) envp)) (envt (if thisp (cons (mark-def! thisp) enva) enva)) (nenv (append (if decl (cons (mark-def! decl) envt) envt) env))) (mark-free body nenv)))) ;*---------------------------------------------------------------------*/ * mark - free : : ... * / ;*---------------------------------------------------------------------*/ (define-walk-method (mark-free this::J2SLetBlock env) (with-access::J2SLetBlock this (decls nodes) (let ((nenv (append (map! mark-def! decls) env))) (for-each (lambda (d) (when (isa? d J2SDeclInit) (with-access::J2SDeclInit d (val) (mark-free val nenv)))) decls) (for-each (lambda (node) (mark-free node nenv)) nodes)))) ;*---------------------------------------------------------------------*/ ;* mark-free ::J2SBlock ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (mark-free this::J2SBlock env) (with-access::J2SBlock this (nodes) (let loop ((env env) (nodes nodes)) (when (pair? nodes) (let ((n (car nodes))) (cond ((isa? n J2SDeclInit) (with-access::J2SDeclInit n (val) (let ((nenv (cons (mark-def! n) env))) (mark-free val nenv) (loop nenv (cdr nodes))))) ((isa? n J2SDecl) (let ((nenv (cons (mark-def! n) env))) (loop nenv (cdr nodes)))) (else (mark-free n env) (loop env (cdr nodes))))))))) ;*---------------------------------------------------------------------*/ ;* mark-free ::J2SCatch ... */ ;*---------------------------------------------------------------------*/ (define-method (mark-free this::J2SCatch env) (with-access::J2SCatch this (param body) (let ((nenv (cons (mark-def! param) env))) (mark-free body nenv)))) ;*---------------------------------------------------------------------*/ ;* kont-color ... */ ;*---------------------------------------------------------------------*/ (define (kont-color::long use has-yield*::bool) (let ((len (length use))) (for-each (lambda (d c) (with-access::J2SDecl d (id %info) (with-access::KDeclInfo %info (color) (set! color c)))) use (iota len (if has-yield* 2 0))) (+fx len (if has-yield* 2 0)))) ;*---------------------------------------------------------------------*/ ;* alloc-temp ... */ ;*---------------------------------------------------------------------*/ (define (alloc-temp p) (when (isa? p J2SDecl) (with-access::J2SDecl p (%info loc id) (when (isa? %info KDeclInfo) (with-access::KDeclInfo %info (free color) (when free (when (=fx color -1) (error "alloc-temp" (format "wrong color (~s)" id) loc)) (J2SStmtExpr (J2SAssig (J2SKontRef '%gen color id) (J2SRef p))))))))) ;*---------------------------------------------------------------------*/ ;* kont-alloc-temp! ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (kont-alloc-temp! this::J2SNode extra) (with-trace 'cps (typeof this) (call-default-walker))) ;*---------------------------------------------------------------------*/ ;* kont-alloc-temp! ::J2SKont ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (kont-alloc-temp! this::J2SKont extra) (with-access::J2SKont this (param exn body loc) (if (or (is-free? param) (is-free? exn)) (let ((endloc (node-endloc body))) (set! body (J2SBlock* (append (filter-map alloc-temp (list param exn)) (list (kont-alloc-temp! body extra))))) this) (call-default-walker)))) ;*---------------------------------------------------------------------*/ ;* kont-alloc-temp! ::J2SFun ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (kont-alloc-temp! this::J2SFun extra) (with-access::J2SFun this (generator body decl thisp params argumentsp %info loc name) (with-trace 'cps "j2sfun" (let ((temps (append (if generator extra '()) (cons* decl thisp argumentsp params)))) ;* (tprint " FUN=" name " " generator " tmps=" */ ;* (filter-map (lambda (p) */ ;* (when (isa? p J2SDecl) */ ;* (with-access::J2SDecl p (id %info) */ * ( when ( isa ? % info ) * / ;* id)))) */ ;* temps)) */ (if (any is-free? temps) (with-access::J2SBlock body (endloc) (set! body (J2SBlock ;; this block will have to be move before the ;; generator is created, see scheme-fun (J2SBlock* (filter-map alloc-temp temps)) (kont-alloc-temp! body extra))) this) (call-default-walker)))))) ;*---------------------------------------------------------------------*/ ;* kont-alloc-temp! ::J2SRef ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (kont-alloc-temp! this::J2SRef extra) (with-trace 'cps (typeof this) (with-access::J2SRef this (decl loc) (with-access::J2SDecl decl (%info id) (if (isa? %info KDeclInfo) (with-access::KDeclInfo %info (color free) (if free (begin (when (=fx color -1) (error "kont-alloc-temp!" (format "wrong color (~s)" id) loc)) (J2SKontRef '%gen color id)) this)) this))))) ;*---------------------------------------------------------------------*/ ;* kont-alloc-temp! ::J2SDeclInit ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (kont-alloc-temp! this::J2SDeclInit extra) (with-trace 'cps (typeof this) (with-access::J2SDeclInit this (val %info loc id) (trace-item "val=" (typeof val)) (set! val (kont-alloc-temp! val extra)) (when (isa? %info KDeclInfo) (with-access::KDeclInfo %info (color free) (when free (when (=fx color -1) (error "kont-alloc-temp!" (format "wrong color (~s)" id) loc)) (set! val (J2SSequence (J2SAssig (J2SKontRef '%gen color id) val) (J2SUndefined)))))) this)))
null
https://raw.githubusercontent.com/manuel-serrano/hop/48dcc32fab96323bbafb18bfbe30ede33d5f49fd/js2scheme/cps.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * JavaScript CPS transformation */ * ------------------------------------------------------------- */ * -international.org/ecma-262/6.0/#sec-14.4 */ * ------------------------------------------------------------- */ * for generators. Only generator function are modified. */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * kid ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * kid? ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * KontExpr ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * J2SKontCall ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * kcall ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * ktrampoline ... */ * ------------------------------------------------------------- */ * This function is only to reduce the number of generated */ * continuations. Using it is optional. */ * ------------------------------------------------------------- */ * If a continuation merely jump to another continuation, return */ * that trampoline continuation. */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * assert-kont ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * kont-debug */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * kont-error ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps-fun! ::J2SNode ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps-fun! ::J2SFun ... */ *---------------------------------------------------------------------*/ collect all locals used in the generator cps has introduced new closures, the variable "escape" property must be recomputed. mark the generator arguments retain free variables color the continuation variables allocate temporaries *---------------------------------------------------------------------*/ * SeqBlock ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * dup ... */ *---------------------------------------------------------------------*/ instance fields constructor *---------------------------------------------------------------------*/ * dup-assig ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * blockify ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps* ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SNode ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SReturn ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SExpr ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SLiteral ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SFun ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SRef ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SParen ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SUnary ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SBinary ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SSequence ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::%J2STail ... */ * ------------------------------------------------------------- */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SNop ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SSeq ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SIf ... */ *---------------------------------------------------------------------*/ optimized version without new continuation *---------------------------------------------------------------------*/ * cps ::J2SDecl ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SDeclInit ... */ *---------------------------------------------------------------------*/ must reuse the existing binding in order to preserve the AST inner pointers *---------------------------------------------------------------------*/ * cps ::J2SDeclFun ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::j2SLetBlock ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ transformation must know how to map its lbl to a contination *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ K( for( ; test; incr ) body ) --> (letrec ((for (lambda () (K (if test (begin body incr (for))))))) (for)) If break is used (for))) If continue is used (for))) *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SWhile ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SDo ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SBreak ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SContinue ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SAssig ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SDProducer ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SCall ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SArray ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SCond ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2STry ... */ *---------------------------------------------------------------------*/ try/catch only try/catch/finally *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cps ::J2SSwitch ... */ *---------------------------------------------------------------------*/ if here a duplication is preferred to a mutation, don't forget to update the kbreaks set otherwise J2SBreak will be badly compiled *---------------------------------------------------------------------*/ * has-yield*? ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * yield-expr? ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * yield-expr* ::J2SNode ... */ * ------------------------------------------------------------- */ * returns #f. */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * yield-expr* ::J2SReturn ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * yield-expr* ::J2SBreak ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * yield-expr* ::J2SContinue ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * yield-expr* ::J2SFun ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * yield-expr* ::J2SCase ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * retthrow! ::J2SNode ... */ * ------------------------------------------------------------- */ * Replace untail return (those of the inlined function) with */ * an exit. */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * retthrow! ::J2SReturn ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * retthrow! ::J2SFun ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * retthrow! ::J2SMethod ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * collect-temps* ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * is-global-or-fun? ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * collect-temps* ::J2SRef ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * mark-def! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * mark-ignored! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * is-free? ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * is-def? ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * mark-free ::J2SNode ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * mark-free ::J2SRef ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * mark-free ::J2SKont ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * mark-free ::J2SFun ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * mark-free ::J2SBlock ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * mark-free ::J2SCatch ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * kont-color ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * alloc-temp ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * kont-alloc-temp! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * kont-alloc-temp! ::J2SKont ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * kont-alloc-temp! ::J2SFun ... */ *---------------------------------------------------------------------*/ * (tprint " FUN=" name " " generator " tmps=" */ * (filter-map (lambda (p) */ * (when (isa? p J2SDecl) */ * (with-access::J2SDecl p (id %info) */ * id)))) */ * temps)) */ this block will have to be move before the generator is created, see scheme-fun *---------------------------------------------------------------------*/ * kont-alloc-temp! ::J2SRef ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * kont-alloc-temp! ::J2SDeclInit ... */ *---------------------------------------------------------------------*/
* serrano / prgm / project / hop / hop / js2scheme / cps.scm * / * Author : * / * Creation : We d Sep 11 14:30:38 2013 * / * Last change : Fri Jan 13 13:51:21 2023 ( serrano ) * / * Copyright : 2013 - 23 * / * This module implements the JavaScript CPS transformation needed * / (module __js2scheme_cps (import __js2scheme_ast __js2scheme_dump __js2scheme_compile __js2scheme_stage __js2scheme_syntax __js2scheme_alpha __js2scheme_utils) (include "ast.sch" "usage.sch") (static (final-class %J2STail::J2SReturn) (final-class KDeclInfo (free::bool (default #f)) (def::bool (default #f)) (color::int (default -1)))) (cond-expand (bigloo-debug (static (abstract-class Kont (node::obj read-only) (link::obj read-only) (proc::procedure read-only) (name::bstring read-only (default ""))) (class KontStmt::Kont) (class KontExpr::Kont) (class KontExpr*::Kont)))) (export j2s-cps-stage)) * - stage ... * / (define j2s-cps-stage (instantiate::J2SStageProc (name "cps") (comment "transform generator in CPS") (proc j2s-cps))) * ... * / (define (j2s-cps this conf) (when (isa? this J2SProgram) (with-access::J2SProgram this (headers decls nodes) (for-each (lambda (o) (cps-fun! o (lambda (n) n) conf)) headers) (for-each (lambda (o) (cps-fun! o (lambda (n) n) conf)) decls) (for-each (lambda (o) (cps-fun! o (lambda (n) n) conf)) nodes))) this) (define (kid n::J2SNode) n) (define (kid? obj) (cond-expand (bigloo-debug (with-access::Kont obj (proc) (eq? proc kid))) (else (eq? obj kid)))) * KontStmt ... * / (define-macro (KontStmt proc node link . name) (cond-expand (bigloo-debug `(instantiate::KontStmt (proc ,proc) (node ,node) (link ,link) (name ,(if (pair? name) (string-append "[" (car name) "]") "")))) (else proc))) (define-macro (KontExpr proc node link . name) (cond-expand (bigloo-debug `(instantiate::KontExpr (proc ,proc) (node ,node) (link ,link) (name ,(if (pair? name) (string-append "[" (car name) "]") "")))) (else proc))) * * ... * / (define-macro (KontExpr* proc node link . name) (cond-expand (bigloo-debug `(instantiate::KontExpr* (proc ,proc) (node ,node) (link ,link) (name ,(if (pair? name) (string-append "[" (car name) "]") "")))) (else proc))) (define-macro (J2SKontCall kdecl . args) `(J2SMethodCall (J2SRef ,kdecl) (list ,(if (pair? args) (car args) `(J2SHopRef '%gen))) (J2SHopRef '%yield) (J2SHopRef '%this) ,@(if (pair? args) (cdr args) '()))) (define-expander kcall (lambda (x e) (match-case x ((?kcall ?kont ?arg) (cond-expand (bigloo-debug (e `(with-access::Kont ,kont (proc name) (let ((res (proc ,arg))) (if (or (isa? res J2SStmt) (and (isa? res J2SExpr) (isa? ,kont KontExpr))) res (kont-call-error ,kont res ',(cer x))))) e)) (else (e `(,kont ,arg) e)))) (else (error "kcall" "bad form" x))))) (define (ktrampoline body::J2SStmt) (define (ishopref? expr i) (when (isa? expr J2SHopRef) (with-access::J2SHopRef expr (id) (eq? id id)))) (define (iskontcall? expr) (when (isa? expr J2SCall) (with-access::J2SCall expr (fun thisargs args) (when (and (pair? thisargs) (null? (cdr thisargs)) (pair? args) (null? (cdr args))) (and (ishopref? (car thisargs) '%gen) (ishopref? (car args) '%this)))))) (when (isa? body J2SSeq) (with-access::J2SSeq body (nodes) (when (and (pair? nodes) (pair? (cdr nodes)) (null? (cddr nodes))) (when (isa? (car nodes) J2SNop) (when (isa? (cadr nodes) J2SReturn) (with-access::J2SReturn (cadr nodes) (expr) (when (iskontcall? expr) (with-access::J2SCall expr (fun thisargs) (when (isa? fun J2SRef) expr)))))))))) (define-expander assert-kont (lambda (x e) (cond-expand (bigloo-debug (match-case x ((?- ?kont ?type ?node) (e `(unless (isa? ,kont ,type) (kont-error ,kont ,type ,node ',(cer x))) e)) (else (error "assert-kont" "bad form" x) #f))) (else #t)))) (cond-expand (bigloo-debug (define (kont-debug kont #!optional (max-depth 20)) (if (isa? kont Kont) (with-access::Kont kont (node link) (let loop ((link link) (stack '()) (depth max-depth)) (if (and link (>fx depth 0)) (with-access::Kont link (link name node) (loop link (cons (format "~a kont: ~a ~a ~a" (typeof node) (typeof link) name (if (>fx (bigloo-debug) 2) (call-with-output-string (lambda (p) (display " ") (display (j2s->sexp node) p) (newline p))) "")) stack) (-fx depth 1))) (reverse! stack)))))))) (cond-expand (bigloo-debug (define (kont-error kont type node loc) (raise (instantiate::&error (obj (typeof kont)) (msg (format "Not a `~s' continuation" (class-name type))) (proc (format "cps ::~a" (typeof node))) (fname (cadr loc)) (location (caddr loc)) (stack (if (isa? kont Kont) (with-access::Kont kont (node link) (let loop ((link link) (stack '())) (if link (with-access::Kont link (link name node) (loop link (cons (format "~a kont: ~a ~a ~a" (typeof node) (typeof link) name (if (>fx (bigloo-debug) 2) (call-with-output-string (lambda (p) (display " ") (display (j2s->sexp node) p) (newline p))) "")) stack))) (reverse! stack)))) (get-trace-stack)))))))) (cond-expand (bigloo-debug (define (kont-call-error kont node loc) (raise (instantiate::&error (obj (with-access::Kont kont (node) (typeof node))) (msg (format "~a returns `~a' expression" (typeof kont) (typeof node))) (proc (with-access::Kont kont (name) name)) (fname (cadr loc)) (location (caddr loc)) (stack (if (isa? kont Kont) (with-access::Kont kont (node link) (let loop ((link link) (stack '())) (if link (with-access::Kont link (link name node) (loop link (cons (format "~a kont: ~a ~a ~a" (typeof node) (typeof link) name (if (>fx (bigloo-debug) 2) (call-with-output-string (lambda (p) (display " ") (display (j2s->sexp node) p) (newline p))) "")) stack))) (reverse! stack)))) (get-trace-stack)))))))) (define-walk-method (cps-fun! this::J2SNode r::procedure conf) (call-default-walker)) (define-walk-method (cps-fun! this::J2SFun r::procedure conf) (with-access::J2SFun this (generator body name constrsize loc decl params thisp argumentsp %info) (if generator (let ((k (KontStmt kid this #f "J2SFun")) (ydstar (has-yield*? body))) (set! body (blockify body (cps body k r '() '() this conf))) (let ((temps (delete-duplicates! (collect-temps* this) eq?))) (for-each (lambda (d) (with-access::J2SDecl d (%info) (set! %info (instantiate::KDeclInfo)))) temps) (mark-free body '()) (if (config-get conf :optim-cps-closure-alloc #f) (begin (for-each (lambda (d) (when (isa? d J2SDecl) (mark-def! d))) (cons* decl thisp argumentsp params)) (let ((frees (filter is-free? temps))) (let* ((temps (filter (lambda (d) (or (is-def? d) (if (decl-usage-has? d '(assig)) (begin (mark-ignored! d) #f) #t))) frees)) (sz (length temps))) (set! constrsize (kont-color temps ydstar)) (kont-alloc-temp! this (filter (lambda (d) (with-access::J2SDecl d (%info) (with-access::KDeclInfo %info (def) (not def)))) temps)) this))) (begin (set! constrsize 0) this)))) (begin (cps-fun! body r conf) this)))) (define (SeqBlock this::J2SSeq n m) (let ((res (dup this))) (with-access::J2SSeq res (nodes) (if (or (eq? (object-class m) J2SSeq) (eq? (object-class m) J2SBlock)) (with-access::J2SSeq m ((seq nodes)) (set! nodes (cons n seq))) (set! nodes (list n m)))) res)) (define (dup this::J2SNode) (let* ((clazz (object-class this)) (ctor (class-constructor clazz)) (inst ((class-allocator clazz))) (fields (class-all-fields clazz))) (let loop ((i (-fx (vector-length fields) 1))) (when (>=fx i 0) (let* ((f (vector-ref-ur fields i)) (v ((class-field-accessor f) this))) ((class-field-mutator f) inst v) (loop (-fx i 1))))) (when (procedure? ctor) ctor inst) inst)) (define (dup-assig this l r) (let ((n (dup this))) (with-access::J2SAssig n (lhs rhs) (set! lhs l) (set! rhs r) n))) (define (blockify::J2SBlock block::J2SBlock stmt::J2SStmt) (if (isa? stmt J2SBlock) stmt (duplicate::J2SBlock block (nodes (list stmt))))) (define (cps*::J2SNode nodes::pair-nil k* r* kbreaks kcontinues fun conf) (assert-kont k* KontExpr* nodes) (let loop ((nodes nodes) (knodes '())) (if (null? nodes) (kcall k* (reverse! knodes)) (cps (car nodes) (KontExpr (lambda (kexpr::J2SExpr) (loop (cdr nodes) (cons kexpr knodes))) nodes k*) r* kbreaks kcontinues fun conf)))) (define-generic (cps::J2SNode this::J2SNode k r kbreaks::pair-nil kcontinues::pair-nil fun::J2SFun conf) (warning "cps: should not be here " (typeof this)) (kcall k this)) * cps : : ... * / (define-method (cps this::J2SYield k r kbreaks kcontinues fun conf) (define (stmtify n) (if (isa? n J2SStmt) n (with-access::J2SExpr n (loc) (J2SStmtExpr n)))) (define (make-yield-kont k loc) (let ((arg (J2SParam '(call ref) (gensym '%arg) :vtype 'any)) (exn (J2SParam '(ref) (gensym '%exn) :vtype 'bool))) (J2SKont arg exn (r (J2SIf (J2SBinary 'eq? (J2SRef exn) (J2SBool #t)) (J2SThrow (J2SRef arg)) (stmtify (kcall k (J2SRef arg)))))))) (define (make-yield*-kont k loc) (let ((arg (J2SParam '(call ref) (gensym '%arg) :vtype 'any)) (exn (J2SParam '(ref) (gensym '%exn) :vtype 'bool))) (J2SKont arg exn (stmtify (kcall k (J2SRef arg)))))) (with-access::J2SYield this (loc expr generator) (let ((kont (if generator (make-yield*-kont k loc) (make-yield-kont k loc)))) (cps expr (KontExpr (lambda (kexpr::J2SExpr) (J2SReturnYield kexpr kont generator)) this k) r kbreaks kcontinues fun conf)))) (define-method (cps this::J2SReturn k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SReturn this (loc expr) (cps expr (KontExpr (lambda (kexpr::J2SExpr) (J2SReturnYield kexpr (J2SUndefined) #f)) this k) r kbreaks kcontinues fun conf))) (define-method (cps this::J2SExpr k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (kcall k this)) (define-method (cps this::J2SLiteral k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (kcall k this)) (define-method (cps this::J2SFun k r breaks kcontinues fun conf) (assert-kont k KontExpr this) (kcall k (cps-fun! this r conf))) (define-method (cps this::J2SRef k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (kcall k this)) (define-method (cps this::J2SParen k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (with-access::J2SParen this (expr) (cps expr k r kbreaks kcontinues fun conf))) (define-method (cps this::J2SUnary k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (with-access::J2SUnary this (expr) (cps expr (KontExpr (lambda (kexpr::J2SExpr) (kcall k (duplicate::J2SUnary this (expr kexpr)))) this k) r kbreaks kcontinues fun conf))) (define-method (cps this::J2SBinary k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (with-access::J2SBinary this (lhs rhs loc op) (case op ((OR OR*) (cps lhs (KontExpr (lambda (klhs::J2SExpr) (cps (J2SCond klhs klhs rhs) (KontExpr (lambda (krhs::J2SExpr) (kcall k krhs)) this k) r kbreaks kcontinues fun conf)) this k) r kbreaks kcontinues fun conf)) ((&&) (cps (J2SCond lhs rhs (J2SBool #f)) k r kbreaks kcontinues fun conf)) (else (cps lhs (KontExpr (lambda (klhs::J2SExpr) (cps rhs (KontExpr (lambda (krhs::J2SExpr) (kcall k (duplicate::J2SBinary this (lhs klhs) (rhs krhs)))) this k) r kbreaks kcontinues fun conf)) this k) r kbreaks kcontinues fun conf))))) (define-method (cps this::J2SSequence k r kbreaks kcontinues fun conf) (define (seqify this kar kdr) (if (isa? kdr J2SSequence) (with-access::J2SSequence kdr (exprs) (duplicate::J2SSequence this (exprs (cons kar exprs)))) (duplicate::J2SSequence this (exprs (list kar kdr))))) (assert-kont k KontExpr this) (with-access::J2SSequence this (exprs loc) (cond ((null? exprs) (kcall k this)) ((null? (cdr exprs)) (cps (car exprs) k r kbreaks kcontinues fun conf)) (else (cps (car exprs) (KontExpr (lambda (kar::J2SExpr) (cps (duplicate::J2SSequence this (exprs (cdr exprs))) (KontExpr (lambda (kdr::J2SExpr) (kcall k (seqify this kar kdr))) this k) r kbreaks kcontinues fun conf)) this k) r kbreaks kcontinues fun conf))))) * J2STail are introduced by the CPS conversion of loops . * / (define-method (cps this::%J2STail k r kbreaks kcontinues fun conf) (with-access::%J2STail this (loc expr) this)) (define-method (cps this::J2SNop k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (kcall k this)) * cps : : ... * / (define-method (cps this::J2SStmtExpr k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SStmtExpr this (loc expr) (cps expr (KontExpr (lambda (kexpr::J2SExpr) (kcall k (J2SStmtExpr kexpr))) this k "expr") r kbreaks kcontinues fun conf))) (define-method (cps this::J2SSeq k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SSeq this (loc nodes) (if (null? nodes) (kcall k this) (let loop ((walk nodes)) (if (null? (cdr walk)) (cps (car walk) k r kbreaks kcontinues fun conf) (cps (car walk) (KontStmt (lambda (n) (SeqBlock this n (loop (cdr walk)))) this k) r kbreaks kcontinues fun conf)))))) (define-method (cps this::J2SIf k r kbreaks kcontinues fun conf) (define (cps-if-tramp this tramp) (with-access::J2SIf this (loc test then else) (let ((kont (KontStmt (lambda (n) (J2SSeq n (J2SReturn #t tramp fun))) this k))) (cps test (KontExpr (lambda (ktest::J2SExpr) (duplicate::J2SIf this (test ktest) (then (cps then kont r kbreaks kcontinues fun conf)) (else (cps else kont r kbreaks kcontinues fun conf)))) this k) r kbreaks kcontinues fun conf)))) (define (cps-if-cont this kbody) (with-access::J2SIf this (loc test then else) (let* ((name (gensym '%kif)) (endloc (node-endloc this)) (kyield (J2SParam '(ref) '%yield :vtype 'any)) (kthis (J2SParam '(ref) '%this :vtype 'any)) (kfun (J2SArrowKont name (list kyield kthis) (J2SBlock kbody))) (kdecl (J2SLetOpt '(call) name kfun)) (kont (KontStmt (lambda (n) (J2SSeq n (J2SReturn #t (J2SKontCall kdecl) fun))) this k)) (endloc (node-endloc this))) (cps test (KontExpr (lambda (ktest::J2SExpr) (J2SLetRecBlock #f (list kdecl) (duplicate::J2SIf this (test ktest) (then (cps then kont r kbreaks kcontinues fun conf)) (else (cps else kont r kbreaks kcontinues fun conf))))) this k) r kbreaks kcontinues fun conf)))) (assert-kont k KontStmt this) (with-access::J2SIf this (loc test then else) (let* ((kbody (kcall k (J2SNop))) (tramp (ktrampoline kbody))) (if tramp (cps-if-tramp this tramp) normat (cps-if-cont this kbody))))) (define-method (cps this::J2SDecl k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (kcall k this)) (define-method (cps this::J2SDeclInit k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SDeclInit this (val) (if (not (j2s-let-opt? this)) (kcall k this) (cps val (KontExpr (lambda (kval::J2SExpr) (set! val kval) (kcall k this)) this k) r kbreaks kcontinues fun conf)))) (define-method (cps this::J2SDeclFun k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SDeclFun this (val) (cps-fun! val r conf) (kcall k this))) * cps : : J2SVarDecls ... * / (define-method (cps this::J2SVarDecls k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SVarDecls this (decls) (map! (lambda (decl) (cps decl k r kbreaks kcontinues fun conf)) decls) (kcall k this))) (define-method (cps this::J2SLetBlock k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SLetBlock this (rec loc endloc decls nodes) (cond ((not rec) (let loop ((decls decls)) (if (null? decls) (cps (duplicate::J2SBlock this (nodes nodes)) k r kbreaks kcontinues fun conf) (with-access::J2SDecl (car decls) (scope) (set! scope 'kont) (cps (car decls) (KontStmt (lambda (ndecl::J2SStmt) (J2SLetRecBlock #f (list ndecl) (loop (cdr decls)))) this k) r kbreaks kcontinues fun conf))))) ((not (any (lambda (d) (or (not (isa? d J2SDeclInit)) (with-access::J2SDeclInit d (val) (yield-expr? val kbreaks kcontinues)))) decls)) (J2SLetBlock decls (cps (duplicate::J2SBlock this (nodes nodes)) k r kbreaks kcontinues fun conf))) (else (let* ((ndecls (map (lambda (d) (if (isa? d J2SDeclInit) (with-access::J2SDeclInit d (loc) (duplicate::J2SDeclInit d (key (ast-decl-key)) (val (J2SUndefined)))) d)) decls)) (olds (filter (lambda (d) (isa? d J2SDeclInit)) decls)) (news (filter (lambda (d) (isa? d J2SDeclInit)) ndecls)) (assigs (filter-map (lambda (d nd) (when (isa? d J2SDeclInit) (with-access::J2SDeclInit d (loc val) (J2SStmtExpr (J2SAssig (J2SRef nd) (j2s-alpha val olds news)))))) decls ndecls)) (anodes (map (lambda (n) (j2s-alpha n olds news)) nodes))) (cps (J2SLetRecBlock* #f ndecls (cons (J2SSeq* assigs) anodes)) k r kbreaks kcontinues fun conf)))))) * cps : : ... * / (define-method (cps this::J2SBindExit k r kbreaks kcontinues fun conf) (define (make-kont-fun-call loc decl) (J2SKontCall decl)) (assert-kont k KontExpr this) (with-access::J2SBindExit this (stmt lbl loc) (cond ((not (yield-expr? this kbreaks kcontinues)) (set! stmt (cps-fun! stmt r conf)) (kcall k this)) (lbl in order to inline code generator , the j2sreturn CPS (error "cps" "generator cannot use inline expression" loc)) (else (cps stmt (KontStmt (lambda (kstmt::J2SStmt) (set! stmt kstmt) (kcall k this)) this k) r kbreaks kcontinues fun conf))))) * cps : : ... * / (define-method (cps this::J2SFor k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SFor this (loc init test incr body id) (cond ((yield-expr? init kbreaks kcontinues) (let ((i init)) (set! init (J2SNop)) (cps (J2SSeq (J2SStmtExpr i) this) k r kbreaks kcontinues fun conf))) ((let* ((cell (cons this #t)) (kbreaks+ (cons cell kbreaks)) (kcontinues+ (cons cell kcontinues))) (or (yield-expr? test kbreaks kcontinues) (yield-expr? incr kbreaks kcontinues) (yield-expr? body kbreaks+ kcontinues+))) ( let ( ( kfun ( function ( ) ( K ( js - undefined ) ) ) ) ) ( ( ( for ( lambda ( ) ( ( if test ( begin body incr ( for ) ) ) ) ) ) ) ( let ( ( kfun ( function ( ) ( K ( js - undefined ) ) ) ) ) ( ( ( for ( lambda ( ) ( ( if test ( begin body incr ( for ) ) ) ) ) ) ) (let* ((fname (gensym '%kfor)) (bname (gensym '%kbreak)) (cname (gensym '%kcontinue)) (endloc (node-endloc this)) (block (J2SBlock)) (fyield (J2SParam '(ref) '%yield :vtype 'any)) (fthis (J2SParam '(ref) '%this :vtype 'any)) (for (J2SArrowKont fname (list fyield fthis) block)) (decl (J2SLetOpt '(call) fname for)) (byield (J2SParam '(ref) '%yield :vtype 'any)) (bthis (J2SParam '(ref) '%this :vtype 'any)) (break (J2SArrowKont bname (list byield bthis) (J2SBlock (kcall k (J2SStmtExpr (J2SUndefined)))))) (fbody (J2SBlock (J2SStmtExpr incr) (%J2STail (J2SKontCall decl) fun))) (cyield (J2SParam '(ref) '%yield :vtype 'any)) (cthis (J2SParam '(ref) '%this :vtype 'any)) (conti (J2SArrowKont cname (list cyield cthis) (blockify fbody (cps fbody (KontStmt kid this k) r kbreaks kcontinues fun conf)))) (bdecl (J2SLetOpt '(call) bname break)) (cdecl (J2SLetOpt '(call) cname conti)) (then (J2SBlock body (%J2STail (J2SKontCall cdecl) fun))) (stop (J2SBlock (%J2STail (J2SKontCall bdecl) fun))) (node (J2SIf test then stop))) (with-access::J2SBlock block (nodes) (set! nodes (list (cps node (KontStmt kid this k) r (cons (cons this bdecl) kbreaks) (cons (cons this cdecl) kcontinues) fun conf)))) (J2SLetBlock (list decl bdecl cdecl) (if (isa? init J2SExpr) (J2SStmtExpr init) init) (%J2STail (J2SKontCall decl) fun)))) (else (set! init (cps-fun! init r conf)) (set! test (cps-fun! test r conf)) (set! incr (cps-fun! incr r conf)) (set! body (cps-fun! body r conf)) (kcall k this))))) * cps : : ... * / (define-method (cps this::J2SForIn k r kbreaks kcontinues fun conf) (define (cps-for-in this::J2SForIn) (with-access::J2SForIn this (loc lhs obj body) (let* ((v (gensym '%kkeys)) (l (gensym '%klen)) (i (gensym '%ki)) (endloc (node-endloc this)) (keys (J2SLetOptVtype 'array '(ref) v (J2SCall (J2SAccess (J2SUnresolvedRef 'Object) (J2SString "keys")) obj))) (len (J2SLetOpt '(ref) l (J2SAccess (J2SRef keys) (J2SString "length")))) (idx (J2SLetOpt '(assig ref) i (J2SNumber 0))) (for (J2SFor (J2SUndefined) (J2SBinary '< (J2SRef idx) (J2SRef len)) (J2SPostfix '++ (J2SRef idx) (J2SBinary '+ (J2SRef idx) (J2SNumber 1))) (J2SBlock (J2SStmtExpr (J2SAssig lhs (J2SAccess (J2SRef keys) (J2SRef idx)))) body)))) (J2SLetBlock (list keys len idx) (cps for k r kbreaks kcontinues fun conf))))) (define (cps-for-of this::J2SForIn) (with-access::J2SForIn this (loc op lhs obj body) (let* ((o (gensym '%kobj)) (f (gensym '%kfun)) (i (gensym '%kit)) (n (gensym '%knext)) (v (gensym '%kval)) (endloc (node-endloc this)) (kobj (J2SLetOpt '(ref) o obj)) (kfun (J2SLetOpt '(ref) f (J2SAccess (J2SRef kobj) (J2SAccess (J2SUnresolvedRef 'Symbol) (J2SString "iterator"))))) (kit (J2SLetOpt '(ref) i (J2SKontCall kfun (J2SRef kobj)))) (knext (J2SLetOpt '(ref) n (J2SAccess (J2SRef kit) (J2SString "next")))) (kval (J2SLetOpt '(ref assig) v (J2SKontCall knext (J2SRef kit)))) (for (J2SFor (J2SUndefined) (J2SUnary '! (J2SAccess (J2SRef kval) (J2SString "done"))) (J2SAssig (J2SRef kval) (J2SCall (J2SAccess (J2SRef kit) (J2SString "next")))) (J2SBlock (J2SStmtExpr (J2SAssig lhs (J2SAccess (J2SRef kval) (J2SString "value")))) body)))) (J2SLetBlock (list kobj kfun kit knext kval) (cps for k r kbreaks kcontinues fun conf))))) (assert-kont k KontStmt this) (with-access::J2SForIn this (loc lhs obj body op) (cond ((yield-expr? obj kbreaks kcontinues) (cps obj (KontExpr (lambda (kobj) (cps (duplicate::J2SForIn this (obj kobj)) k r kbreaks kcontinues fun conf)) this k) r kbreaks kcontinues fun conf)) ((let* ((cell (cons this #t)) (kbreaks+ (cons cell kbreaks)) (kcontinues+ (cons cell kcontinues))) (yield-expr? body kbreaks+ kcontinues+)) (if (eq? op 'in) (cps-for-in this) (cps-for-of this))) (else (set! lhs (cps-fun! lhs r conf)) (set! body (cps-fun! body r conf)) (kcall k this))))) (define-method (cps this::J2SWhile k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SWhile this (test body loc) (let* ((kname (gensym '%kwhile)) (bname (gensym '%kbreak)) (cname (gensym '%kcontinue)) (endloc (node-endloc this)) (block (J2SBlock)) (wyield (J2SParam '(ref) '%yield :vtype 'any)) (warg (J2SParam '(ref) '%this :vtype 'any)) (while (J2SArrowKont kname (list wyield warg) block)) (wdecl (J2SLetOpt '(call) kname while)) (barg (J2SParam '(ref) '%this :vtype 'any)) (byield (J2SParam '(ref) '%yield :vtype 'any)) (break (J2SArrowKont bname (list byield barg) (J2SBlock (kcall k (J2SStmtExpr (J2SUndefined)))))) (fbody (J2SBlock (J2SReturn #t (J2SKontCall wdecl) fun))) (cyield (J2SParam '(ref) '%yield :vtype 'any)) (carg (J2SParam '(ref) '%this :vtype 'any)) (conti (J2SArrowKont cname (list cyield carg) fbody)) (bdecl (J2SLetOpt '(call) bname break)) (cdecl (J2SLetOpt '(call) cname conti)) (then (J2SBlock body (%J2STail (J2SKontCall wdecl) fun))) (else (J2SBlock (%J2STail (J2SKontCall bdecl) fun))) (node (J2SIf test then else))) (with-access::J2SBlock block (nodes) (set! nodes (list (cps node (KontStmt kid this k) r (cons (cons this bdecl) kbreaks) (cons (cons this cdecl) kcontinues) fun conf)))) (J2SLetBlock (list wdecl bdecl cdecl) (J2SReturn #t (J2SKontCall wdecl) fun))))) (define-method (cps this::J2SDo k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SDo this (test body loc) (let* ((name (gensym '%kdo)) (bname (gensym '%kbreak)) (cname (gensym '%kcontinue)) (tname (gensym '%ktmp)) (endloc (node-endloc this)) (block (J2SBlock)) (wyield (J2SParam '(ref) '%yield :vtype 'any)) (wthis (J2SParam '(ref) '%this :vtype 'any)) (while (J2SArrowKont name (list wyield wthis) block)) (decl (J2SLetOpt '(call) name while)) (declv (J2SLetOpt '(assig ref) tname (J2SBool #t))) (cyield (J2SParam '(ref) '%yield :vtype 'any)) (cthis (J2SParam '(ref) '%this :vtype 'any)) (conti (J2SArrowKont name (list cyield cthis) (J2SBlock (cps (J2SIf (J2SCond test (J2SRef declv) (J2SBool #f)) (%J2STail (J2SKontCall decl) fun) (J2SNop)) k r kbreaks kcontinues fun conf)))) (cdecl (J2SLetOpt '(call) cname conti)) (byield (J2SParam '(ref) '%yield :vtype 'any)) (bthis (J2SParam '(ref) '%this :vtype 'any)) (break (J2SArrowKont name (list byield bthis) (J2SBlock (J2SStmtExpr (J2SAssig (J2SRef declv) (J2SBool #f))) (%J2STail (J2SKontCall cdecl) fun)))) (bdecl (J2SLetOpt '(call) bname break)) (else (J2SBlock (%J2STail (J2SKontCall bdecl) fun))) (sbody (J2SSeq body (%J2STail (J2SKontCall cdecl) fun)))) (with-access::J2SBlock block (nodes) (set! nodes (list (cps sbody (KontStmt kid this k) r (cons (cons this bdecl) kbreaks) (cons (cons this cdecl) kcontinues) fun conf)))) (J2SLetBlock (list declv decl bdecl cdecl) (J2SReturn #t (J2SKontCall decl) fun))))) (define-method (cps this::J2SBreak k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SBreak this (loc target) (cond ((assq target kbreaks) => (lambda (c) (let ((kont (cdr c))) (J2SReturn #t (J2SKontCall kont) fun)))) (else (kcall k this))))) (define-method (cps this::J2SContinue k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SContinue this (loc target) (cond ((assq target kcontinues) => (lambda (c) (let ((kont (cdr c))) (J2SReturn #t (J2SKontCall kont) fun)))) (else (kcall k this))))) (define-method (cps this::J2SAssig k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (with-access::J2SAssig this (lhs rhs) (cps lhs (KontExpr (lambda (klhs::J2SExpr) (cps rhs (KontExpr (lambda (krhs::J2SExpr) (kcall k (dup-assig this klhs krhs))) this k) r kbreaks kcontinues fun conf)) this k) r kbreaks kcontinues fun conf))) (define-method (cps this::J2SDProducer k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (with-access::J2SDProducer this (expr) (cps expr (KontExpr (lambda (kexpr::J2SExpr) (kcall k (duplicate::J2SDProducer this (expr kexpr)))) this k) r kbreaks kcontinues fun conf))) (define-method (cps this::J2SCall k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (with-access::J2SCall this ((callee fun) args) (cond ((yield-expr? callee kbreaks kcontinues) (cps callee (KontExpr (lambda (kfun::J2SExpr) (set! callee kfun) (cps this k r kbreaks kcontinues fun conf)) this k) r kbreaks kcontinues fun conf)) ((any (lambda (e) (yield-expr? e kbreaks kcontinues)) args) (cps-fun! callee r conf) (cps* args (KontExpr* (lambda (kargs::pair-nil) (set! args kargs) (cps this k r kbreaks kcontinues fun conf)) args k) r kbreaks kcontinues fun conf)) (else (cps-fun! callee r conf) (for-each (lambda (n) (cps-fun! n r conf)) args) (kcall k this))))) (define-method (cps this::J2SArray k r kbreaks kcontinues fun conf) (assert-kont k KontExpr this) (with-access::J2SArray this (exprs) (if (any (lambda (e) (yield-expr? e kbreaks kcontinues)) exprs) (cps* exprs (KontExpr* (lambda (kexprs::pair-nil) (set! exprs kexprs) (cps this k r kbreaks kcontinues fun conf)) exprs k) r kbreaks kcontinues fun conf) (begin (set! exprs (map! (lambda (n) (cps-fun! n r conf)) exprs )) (kcall k this))))) (define-method (cps this::J2SCond k r kbreaks kcontinues fun conf) (define (make-kont-decl loc endloc k) (assert-kont k KontExpr this) (let* ((name (gensym '%kcond)) (arg (J2SParam '(call ref) (gensym '%arg) :vtype 'any)) (kyield (J2SParam '(ref) '%yield :vtype 'any)) (kthis (J2SParam '(ref) '%this :vtype 'any)) (kfun (J2SArrowKont name (list kyield kthis arg) (J2SBlock (kcall k (J2SRef arg)))))) (J2SLetOpt '(call) name kfun))) (define (make-kont-fun-call loc decl expr) (J2SKontCall decl (J2SHopRef '%gen) expr)) (assert-kont k KontExpr this) (with-access::J2SCond this (test then else loc) (cond ((yield-expr? test kbreaks kcontinues) (cps test (KontExpr (lambda (ktest::J2SExpr) (set! test ktest) (cps this k r kbreaks kcontinues fun conf)) this k "test") r kbreaks kcontinues fun conf)) ((or (yield-expr? then kbreaks kcontinues) (yield-expr? else kbreaks kcontinues)) (let* ((endloc (node-endloc this)) (decl (make-kont-decl loc endloc k)) (kc (lambda (b) (J2SReturn #t (make-kont-fun-call loc decl b) fun))) (kif (J2SIf (cps-fun! test r conf) (cps then (KontExpr kc this k) r kbreaks kcontinues fun conf) (cps else (KontExpr kc this k) r kbreaks kcontinues fun conf)))) (J2SLetBlock (list decl) kif))) (else (set! test (cps-fun! test r conf)) (set! then (cps-fun! then r conf)) (set! else (cps-fun! else r conf)) (kcall k this))))) (define-method (cps this::J2STry k r kbreaks kcontinues fun conf) (define (Catch loc endloc declc::J2SDecl param) (J2SCatch param (J2SBlock (%J2STail (J2SKontCall declc (J2SHopRef '%gen) (J2SRef param)) fun)))) (define (FinallyCatch finally k r kbreaks kcontinues fun) (with-access::J2SNode finally (loc) (let ((eparam (J2SParam '(ref) (gensym '%exc) :vtype 'any))) (J2SCatch eparam (cps finally (KontStmt (lambda (n) (J2SSeq n (J2SThrow (J2SRef eparam)))) this k) r kbreaks kcontinues fun conf))))) (define (FinallyCatchThrow finally k r kbreaks kcontinues fun) (with-access::J2SNode finally (loc) (let ((eparam (J2SParam '(ref) (gensym '%exc) :vtype 'any))) (J2SCatch eparam (cps finally (KontStmt (lambda (n) (J2SSeq n (J2SThrow (J2SRef eparam)))) this k) r kbreaks kcontinues fun conf))))) (define (cps-try-catch this body catch loc) (let* ((endloc (node-endloc this)) (cname (gensym '%kcatch)) (cyield (J2SParam '(ref) '%yield :vtype 'any)) (cthis (J2SParam '(ref) '%this :vtype 'any)) (catch (with-access::J2SCatch catch (param (cbody body)) (J2SArrowKont cname (list cyield cthis param) (J2SBlock (cps cbody k r kbreaks kcontinues fun conf))))) (declc (J2SLetOpt '(call) cname catch)) (eparam (J2SParam '(ref) (gensym '%exc) :vtype 'any))) (J2SLetBlock (list declc) (J2STry (blockify body (cps body k (lambda (n) (r (J2STry (blockify body n) (Catch loc endloc declc eparam)))) kbreaks kcontinues fun conf)) (Catch loc endloc declc eparam))))) (define (cps-try-finally-gen this body finally loc) (let* ((endloc (node-endloc this)) (gen (J2SFun* (gensym '%trybody) '() (J2SBlock))) (mark (J2SLetOpt '(ref) (gensym '%mark) (J2SPragma '(cons #f #f)))) (gbody (J2SBlock body (J2SReturn #t (J2SRef mark)))) (declg (J2SLetOpt '(ref assig) (gensym '%gen) (J2SCall gen))) (gval (J2SLetOpt '(ref assig) (gensym '%yield*) (J2SYield (J2SRef declg) gen)))) (with-access::J2SFun gen (body) (set! body gbody)) (J2STry (cps (J2SLetRecBlock #f (list mark declg) (J2SLetRecBlock #f (list gval) finally (J2SIf (J2SBinary/type '!== 'bool (J2SRef gval) (J2SRef mark)) (J2SReturn #f (J2SRef gval)) (J2SNop)))) k (lambda (n) (r (J2STry (blockify body n) (FinallyCatch finally k r kbreaks kcontinues fun)))) kbreaks kcontinues fun conf) (FinallyCatch finally k r kbreaks kcontinues fun)))) (define (cps-try-finally-explicit this body finally loc) (let* ((endloc (node-endloc finally)) (gen (J2SFun* (gensym '%gen) '() (J2SBlock))) (gbody (J2SBlock body (J2SReturn #t (J2SUndefined) gen))) (declg (J2SLetOpt '(ref assig) (gensym '%gen) (J2SCall gen))) (decln (J2SLetOpt '(ref assig) (gensym '%next) (J2SCall (J2SAccess (J2SRef declg) (J2SString "next")))))) (with-access::J2SFun gen (body) (set! body gbody)) (J2STry (cps (J2SLetBlock (list declg) (J2SLetBlock (list decln) (J2SWhile (J2SUnary/type '! 'bool (J2SAccess (J2SRef decln) (J2SString "done"))) (J2SSeq (J2SStmtExpr (J2SYield (J2SAccess (J2SRef decln) (J2SString "value")) #f)) (J2SStmtExpr (J2SAssig (J2SRef decln) (J2SCall (J2SAccess (J2SRef declg) (J2SString "next"))))))) (J2SSeq finally (J2SAccess (J2SRef decln) (J2SString "value"))))) k r kbreaks kcontinues fun conf) (FinallyCatch finally k r kbreaks kcontinues fun)))) (define (cps-try-finally-tmp this body finally loc) (J2STry (blockify body (cps (J2SSeq body finally) k (lambda (n) (r (J2STry (blockify body n) (FinallyCatch finally k r kbreaks kcontinues fun) (cps finally k r kbreaks kcontinues fun conf)))) kbreaks kcontinues fun conf)) (FinallyCatch finally k r kbreaks kcontinues fun) (cps finally k r kbreaks kcontinues fun conf))) (define (cps-try-finally-throw this body finally loc) (let ((eparam (J2SParam '(ref) (gensym '%exc) :vtype 'any)) (ret (J2SLetOpt '(ref assig) (gensym '%ret) (J2SBool #f))) (exn (J2SLetOpt '(ref assig) (gensym '%exn) (J2SBool #f))) (val (J2SLetOpt '(ref assig) (gensym '%val) (J2SUndefined))) (endloc (node-endloc finally))) (cps (J2SLetBlock (list ret exn val) (J2STry (retthrow! body ret '()) (J2SCatch eparam (J2SBlock (J2SStmtExpr (J2SAssig (J2SRef val) (J2SRef eparam))) (if (J2SUnary/type '! 'bool (J2SRef ret)) (J2SStmtExpr (J2SAssig (J2SRef exn) (J2SBool #t))) (J2SNop))))) finally (J2SIf (J2SRef ret) (J2SReturn #f (J2SRef val) fun) (J2SNop)) (J2SIf (J2SRef exn) (J2SThrow (J2SRef val)) (J2SNop))) k r kbreaks kcontinues fun conf))) (define (cps-try-catch-finally this body catch finally loc) (cps (J2STry (blockify body (J2STry body catch (J2SNop))) (J2SNop) finally) k r kbreaks kcontinues fun conf)) (assert-kont k KontStmt this) (with-access::J2STry this (loc body catch finally) (cond ((and (isa? catch J2SNop) (isa? finally J2SNop)) (cps body k r kbreaks kcontinues fun conf)) ((isa? finally J2SNop) (cps-try-catch this body catch loc)) ((isa? catch J2SNop) (cps-try-finally-throw this body finally loc)) (else (cps-try-catch-finally this body catch finally loc))))) * cps : : J2SThrow ... * / (define-method (cps this::J2SThrow k r kbreaks kcontinues fun conf) (assert-kont k KontStmt this) (with-access::J2SThrow this (loc expr) (if (yield-expr? expr kbreaks kcontinues) (cps expr (KontExpr (lambda (kexpr::J2SExpr) (kcall k (J2SThrow kexpr))) this k) r kbreaks kcontinues fun conf) (begin (set! expr (cps-fun! expr r conf)) (kcall k this))))) (define-method (cps this::J2SSwitch k r kbreaks kcontinues fun conf) (define (switch->if key tmp clause) (with-access::J2SCase clause (loc expr body) (if (isa? clause J2SDefault) body (let ((endloc (node-endloc body))) (J2SIf (J2SBinary 'OR (J2SRef tmp) (J2SBinary '=== (J2SRef key) expr)) (J2SBlock (J2SStmtExpr (J2SAssig (J2SRef tmp) (J2SBool #t))) body) (J2SNop)))))) (assert-kont k KontStmt this) (with-access::J2SSwitch this (loc key cases need-bind-exit-break) (cond ((yield-expr? key kbreaks kcontinues) (cps key (KontExpr (lambda (kkey::J2SExpr) (with-access::J2SSwitch this (key) (set! key kkey) (cps this k r kbreaks kcontinues fun conf))) this k) r kbreaks kcontinues fun conf)) ((not (any (lambda (c) (yield-expr? c kbreaks kcontinues)) cases)) (set! key (cps-fun! key r conf)) (for-each (lambda (clause) (with-access::J2SCase clause (expr body) (set! expr (cps-fun! expr r conf)) (set! body (cps-fun! body r conf)))) cases) (kcall k this)) (else (set! key (cps-fun! key r conf)) (let* ((v (gensym '%kkey)) (t (gensym '%ktmp)) (key (J2SLetOpt '(ref) v key)) (tmp (J2SLetOpt '(assig ref) t (J2SBool #f))) (seq (J2SSeq* (map (lambda (clause) (switch->if key tmp clause)) cases))) (endloc (node-endloc this))) (if need-bind-exit-break (let* ((bname (gensym '%kbreak)) (byield (J2SParam '(ref) '%yield :vtype 'any)) (bthis (J2SParam '(ref) '%this :vtype 'any)) (break (J2SArrowKont bname (list byield bthis) (J2SBlock (J2SBlock (kcall k (J2SStmtExpr (J2SUndefined))))))) (bdecl (J2SLetOpt '(call) bname break))) (J2SLetBlock (list key tmp bdecl) (cps seq k r (cons (cons this bdecl) kbreaks) kcontinues fun conf))) (J2SLetBlock (list key tmp) (cps seq k r kbreaks kcontinues fun conf)))))))) (define (has-yield*? this) (any (lambda (n) (cond ((isa? n J2SYield) (with-access::J2SYield n (generator) generator)) ((isa? n J2SReturnYield) (with-access::J2SReturnYield n (generator) generator)))) (yield-expr* this '() '() '()))) (define (yield-expr? this kbreaks kcontinues) (pair? (yield-expr* this kbreaks kcontinues '()))) * Returns # t iff a statement contains a YIELD . Otherwise * / (define-walk-method (yield-expr* this::J2SNode kbreaks kcontinues localrets) (call-default-walker)) * yield - expr * : : ... * / (define-walk-method (yield-expr* this::J2SYield kbreaks kcontinues localrets) (list this)) (define-walk-method (yield-expr* this::J2SReturn kbreaks kcontinues localrets) (with-access::J2SReturn this (from) (cond ((memq from localrets) '()) (else (list this))))) * yield - expr * : : ... * / (define-walk-method (yield-expr* this::J2SReturnYield kbreaks kcontinues localrets) (list this)) * yield - expr * : : ... * / (define-walk-method (yield-expr* this::J2SBindExit kbreaks kcontinues localrets) (with-access::J2SBindExit this (stmt) (yield-expr* stmt kbreaks kcontinues (cons this localrets)))) (define-walk-method (yield-expr* this::J2SBreak kbreaks kcontinues localrets) (with-access::J2SBreak this (target) (if (assq target kbreaks) (list this) '()))) (define-walk-method (yield-expr* this::J2SContinue kbreaks kcontinues localrets) (with-access::J2SContinue this (target) (if (assq target kcontinues) (list this) '()))) (define-walk-method (yield-expr* this::J2SFun kbreaks kcontinues localrets) '()) (define-walk-method (yield-expr* this::J2SCase kbreaks kcontinues localrets) (with-access::J2SCase this (expr body) (append (yield-expr* expr kbreaks kcontinues localrets) (yield-expr* body kbreaks kcontinues localrets)))) (define-walk-method (retthrow! this::J2SNode decl env) (call-default-walker)) (define-walk-method (retthrow! this::J2SReturn decl env) (with-access::J2SReturn this (tail exit from expr loc from) (if (and (not exit) (not (memq from env))) (J2SSeq (J2SStmtExpr (J2SAssig (J2SRef decl) (J2SBool #t))) (J2SThrow (retthrow! expr decl env)) this) (begin (set! expr (retthrow! expr decl env)) this)))) (define-walk-method (retthrow! this::J2SFun decl env) this) (define-walk-method (retthrow! this::J2SMethod decl env) this) (define-walk-method (collect-temps* this::J2SNode) (call-default-walker)) (define (is-global-or-fun? decl) (define (is-fun-decl? decl) (when (isa? decl J2SDeclInit) (with-access::J2SDeclInit decl (val) (when (isa? val J2SFun) (not (decl-usage-has? decl '(assig))))))) (with-access::J2SDecl decl (scope) (or (isa? decl J2SDeclExtern) (memq scope '(%scope global tls)) (is-fun-decl? decl)))) (define-walk-method (collect-temps* this::J2SRef) (with-access::J2SRef this (decl loc) (if (is-global-or-fun? decl) '() (list decl)))) (define (mark-def!::J2SDecl d) (with-access::J2SDecl d (%info) (when (isa? %info KDeclInfo) (with-access::KDeclInfo %info (def) (set! def #t)))) d) (define (mark-ignored!::J2SDecl d) (with-access::J2SDecl d (%info) (set! %info #f)) d) (define (is-free? d) (when (isa? d J2SDecl) (with-access::J2SDecl d (%info) (when (isa? %info KDeclInfo) (with-access::KDeclInfo %info (free) free))))) (define (is-def? d) (when (isa? d J2SDecl) (with-access::J2SDecl d (%info) (when (isa? %info KDeclInfo) (with-access::KDeclInfo %info (def) def))))) (define-walk-method (mark-free this::J2SNode env) (call-default-walker)) (define-walk-method (mark-free this::J2SRef env) (with-access::J2SRef this (decl loc) (with-access::J2SDecl decl (scope %info id escape) (unless (is-global-or-fun? decl) (with-access::KDeclInfo %info (free) (unless (or free (memq decl env)) (set! escape #t) (set! free #t))))))) (define-walk-method (mark-free this::J2SKont env) (with-access::J2SKont this (body param exn loc) (let ((nenv (list (mark-def! param) (mark-def! exn)))) (mark-free body nenv)))) (define-walk-method (mark-free this::J2SFun env) (with-access::J2SFun this (decl params thisp argumentsp body) (let* ((envp (map! mark-def! params)) (enva (if argumentsp (cons (mark-def! argumentsp) envp) envp)) (envt (if thisp (cons (mark-def! thisp) enva) enva)) (nenv (append (if decl (cons (mark-def! decl) envt) envt) env))) (mark-free body nenv)))) * mark - free : : ... * / (define-walk-method (mark-free this::J2SLetBlock env) (with-access::J2SLetBlock this (decls nodes) (let ((nenv (append (map! mark-def! decls) env))) (for-each (lambda (d) (when (isa? d J2SDeclInit) (with-access::J2SDeclInit d (val) (mark-free val nenv)))) decls) (for-each (lambda (node) (mark-free node nenv)) nodes)))) (define-walk-method (mark-free this::J2SBlock env) (with-access::J2SBlock this (nodes) (let loop ((env env) (nodes nodes)) (when (pair? nodes) (let ((n (car nodes))) (cond ((isa? n J2SDeclInit) (with-access::J2SDeclInit n (val) (let ((nenv (cons (mark-def! n) env))) (mark-free val nenv) (loop nenv (cdr nodes))))) ((isa? n J2SDecl) (let ((nenv (cons (mark-def! n) env))) (loop nenv (cdr nodes)))) (else (mark-free n env) (loop env (cdr nodes))))))))) (define-method (mark-free this::J2SCatch env) (with-access::J2SCatch this (param body) (let ((nenv (cons (mark-def! param) env))) (mark-free body nenv)))) (define (kont-color::long use has-yield*::bool) (let ((len (length use))) (for-each (lambda (d c) (with-access::J2SDecl d (id %info) (with-access::KDeclInfo %info (color) (set! color c)))) use (iota len (if has-yield* 2 0))) (+fx len (if has-yield* 2 0)))) (define (alloc-temp p) (when (isa? p J2SDecl) (with-access::J2SDecl p (%info loc id) (when (isa? %info KDeclInfo) (with-access::KDeclInfo %info (free color) (when free (when (=fx color -1) (error "alloc-temp" (format "wrong color (~s)" id) loc)) (J2SStmtExpr (J2SAssig (J2SKontRef '%gen color id) (J2SRef p))))))))) (define-walk-method (kont-alloc-temp! this::J2SNode extra) (with-trace 'cps (typeof this) (call-default-walker))) (define-walk-method (kont-alloc-temp! this::J2SKont extra) (with-access::J2SKont this (param exn body loc) (if (or (is-free? param) (is-free? exn)) (let ((endloc (node-endloc body))) (set! body (J2SBlock* (append (filter-map alloc-temp (list param exn)) (list (kont-alloc-temp! body extra))))) this) (call-default-walker)))) (define-walk-method (kont-alloc-temp! this::J2SFun extra) (with-access::J2SFun this (generator body decl thisp params argumentsp %info loc name) (with-trace 'cps "j2sfun" (let ((temps (append (if generator extra '()) (cons* decl thisp argumentsp params)))) * ( when ( isa ? % info ) * / (if (any is-free? temps) (with-access::J2SBlock body (endloc) (set! body (J2SBlock (J2SBlock* (filter-map alloc-temp temps)) (kont-alloc-temp! body extra))) this) (call-default-walker)))))) (define-walk-method (kont-alloc-temp! this::J2SRef extra) (with-trace 'cps (typeof this) (with-access::J2SRef this (decl loc) (with-access::J2SDecl decl (%info id) (if (isa? %info KDeclInfo) (with-access::KDeclInfo %info (color free) (if free (begin (when (=fx color -1) (error "kont-alloc-temp!" (format "wrong color (~s)" id) loc)) (J2SKontRef '%gen color id)) this)) this))))) (define-walk-method (kont-alloc-temp! this::J2SDeclInit extra) (with-trace 'cps (typeof this) (with-access::J2SDeclInit this (val %info loc id) (trace-item "val=" (typeof val)) (set! val (kont-alloc-temp! val extra)) (when (isa? %info KDeclInfo) (with-access::KDeclInfo %info (color free) (when free (when (=fx color -1) (error "kont-alloc-temp!" (format "wrong color (~s)" id) loc)) (set! val (J2SSequence (J2SAssig (J2SKontRef '%gen color id) val) (J2SUndefined)))))) this)))
cb4c6f58feb45a96ec993594e243d18460f565f0eb101313fa18846b39d5bd48
footprintanalytics/footprint-web
fingerprinters_test.clj
(ns metabase.sync.analyze.fingerprint.fingerprinters-test (:require [cheshire.core :as json] [clojure.string :as str] [clojure.test :refer :all] [metabase.models.field :as field :refer [Field]] [metabase.models.interface :as mi] [metabase.sync.analyze.fingerprint.fingerprinters :as fingerprinters] [metabase.test :as mt] [schema.core :as s] [toucan.db :as db])) (deftest fingerprint-temporal-values-test ;; we want to test h2 and postgres, because h2 doesn't ;; support overriding the timezone for a session / report (mt/test-drivers #{:h2 :postgres} (doseq [tz ["UTC" nil]] (mt/with-temporary-setting-values [report-timezone tz] (mt/with-database-timezone-id "UTC" (mt/with-everything-store (is (= {:global {:distinct-count 4 :nil% 0.5} :type {:type/DateTime {:earliest "2013-01-01" :latest "2018-01-01"}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/DateTime})) [#t "2013" nil #t "2018" nil nil #t "2015"]))) (testing "handle ChronoLocalDateTime" (is (= {:global {:distinct-count 2 :nil% 0.0} :type {:type/DateTime {:earliest "2013-01-01T20:04:00Z" :latest "2018-01-01T04:04:00Z"}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Temporal})) [(java.time.LocalDateTime/of 2013 01 01 20 04 0 0) (java.time.LocalDateTime/of 2018 01 01 04 04 0 0)])))) (testing "handle comparing explicit Instant with ChronoLocalDateTime" (is (= {:global {:distinct-count 2 :nil% 0.0} :type {:type/DateTime {:earliest "2007-12-03T10:15:30Z" :latest "2018-01-01T04:04:00Z"}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Temporal})) [(java.time.Instant/parse "2007-12-03T10:15:30.00Z") (java.time.LocalDateTime/of 2018 01 01 04 04 0 0)])))) (testing "mixing numbers and strings" (is (= {:global {:distinct-count 2 :nil% 0.0} :type {:type/DateTime {:earliest "1970-01-01T00:00:01.234Z" :latest "2007-12-03T10:15:30Z"}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Temporal})) ["2007-12-03T10:15:30.00Z" 1234])))) (testing "nil temporal values" (is (= {:global {:distinct-count 1 :nil% 1.0} :type {:type/DateTime {:earliest nil :latest nil}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/DateTime})) (repeat 10 nil))))) (testing "handle all supported types" (is (= {:global {:distinct-count 5 :nil% 0.0} :type {:type/DateTime {:earliest "1970-01-01T00:00:01.234Z" :latest "2020-07-06T20:25:33.36Z"}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Temporal})) [(java.time.LocalDateTime/of 2013 01 01 20 04 0 0) ; LocalDateTime 1234 ; int 1594067133360 ; long "2007-12-03T10:15:30.00Z" ; string (java.time.ZonedDateTime/of 2016 01 01 20 04 0 0 (java.time.ZoneOffset/UTC))])))))))))) (deftest disambiguate-test (testing "We should correctly disambiguate multiple competing multimethods (DateTime and FK in this case)" (let [field {:base_type :type/DateTime :semantic_type :type/FK}] (is (= [:type/DateTime :Semantic/* :type/FK] ((.dispatchFn ^clojure.lang.MultiFn fingerprinters/fingerprinter) field))) (is (= {:global {:distinct-count 3 :nil% 0.0} :type {:type/DateTime {:earliest "2013-01-01" :latest "2018-01-01"}}} (transduce identity (fingerprinters/fingerprinter field) [#t "2013" #t "2018" #t "2015"])))))) (deftest fingerprint-numeric-values-test (is (= {:global {:distinct-count 3 :nil% 0.0} :type {:type/Number {:avg 2.0 :min 1.0 :max 3.0 :q1 1.25 :q3 2.75 :sd 1.0}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Number})) [1.0 2.0 3.0]))) (testing "We should robustly survive weird values such as NaN, Infinity, and nil" (is (= {:global {:distinct-count 7 :nil% 0.25} :type {:type/Number {:avg 2.0 :min 1.0 :max 3.0 :q1 1.25 :q3 2.75 :sd 1.0}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Number})) [1.0 2.0 3.0 Double/NaN Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY nil nil]))))) (deftest fingerprint-string-values-test (is (= {:global {:distinct-count 5 :nil% 0.0} :type {:type/Text {:percent-json 0.2 :percent-url 0.0 :percent-email 0.0 :percent-state 0.0 :average-length 6.4}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Text})) ["metabase" "more" "like" "metabae" "[1, 2, 3]"]))) (let [truncated-json (subs (json/generate-string (vec (range 50))) 0 30)] (is (= {:global {:distinct-count 5 :nil% 0.0} :type {:type/Text {:percent-json 0.2 :percent-url 0.0 :percent-email 0.0 :percent-state 0.0 :average-length 10.6}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Text})) ["metabase" "more" "like" "metabae" truncated-json]))))) (deftest fingerprints-in-db-test (mt/test-drivers (mt/normal-drivers) (testing "Fingerprints should actually get saved with the correct values" (testing "Text fingerprints" (is (schema= {:global {:distinct-count (s/eq 100) :nil% (s/eq 0.0)} :type {:type/Text {:percent-json (s/eq 0.0) :percent-url (s/eq 0.0) :percent-email (s/eq 0.0) :percent-state (s/eq 0.0) :average-length (s/pred #(< 15 % 16) "between 15 and 16")}}} (db/select-one-field :fingerprint Field :id (mt/id :venues :name))))) (testing "date fingerprints" (is (schema= {:global {:distinct-count (s/eq 618) :nil% (s/eq 0.0)} :type {:type/DateTime {:earliest (s/pred #(str/starts-with? % "2013-01-03")) :latest (s/pred #(str/starts-with? % "2015-12-29"))}}} (db/select-one-field :fingerprint Field :id (mt/id :checkins :date))))) (testing "number fingerprints" (is (schema= {:global {:distinct-count (s/eq 4) :nil% (s/eq 0.0)} :type {:type/Number {:min (s/eq 1.0) :q1 (s/pred #(< 1.44 % 1.46) "approx 1.4591129021415095") :q3 (s/pred #(< 2.4 % 2.5) "approx 2.493086095768049") :max (s/eq 4.0) :sd (s/pred #(< 0.76 % 0.78) "between 0.76 and 0.78") :avg (s/eq 2.03)}}} (db/select-one-field :fingerprint Field :id (mt/id :venues :price)))))))) (deftest valid-serialized-json?-test (testing "recognizes substrings of json" (let [partial-json (fn [x] (let [json (json/generate-string x)] (subs json 0 (/ (count json) 2))))] (is (#'fingerprinters/valid-serialized-json? (partial-json [1 2 3]))) (is (#'fingerprinters/valid-serialized-json? (partial-json {:a 1 :b 2}))) (is (#'fingerprinters/valid-serialized-json? (partial-json [{:a 2}]))) (is (#'fingerprinters/valid-serialized-json? (partial-json [true true]))) (is (not (#'fingerprinters/valid-serialized-json? "bob"))) (is (not (#'fingerprinters/valid-serialized-json? "[bob]"))))))
null
https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/sync/analyze/fingerprint/fingerprinters_test.clj
clojure
we want to test h2 and postgres, because h2 doesn't support overriding the timezone for a session / report LocalDateTime int long string
(ns metabase.sync.analyze.fingerprint.fingerprinters-test (:require [cheshire.core :as json] [clojure.string :as str] [clojure.test :refer :all] [metabase.models.field :as field :refer [Field]] [metabase.models.interface :as mi] [metabase.sync.analyze.fingerprint.fingerprinters :as fingerprinters] [metabase.test :as mt] [schema.core :as s] [toucan.db :as db])) (deftest fingerprint-temporal-values-test (mt/test-drivers #{:h2 :postgres} (doseq [tz ["UTC" nil]] (mt/with-temporary-setting-values [report-timezone tz] (mt/with-database-timezone-id "UTC" (mt/with-everything-store (is (= {:global {:distinct-count 4 :nil% 0.5} :type {:type/DateTime {:earliest "2013-01-01" :latest "2018-01-01"}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/DateTime})) [#t "2013" nil #t "2018" nil nil #t "2015"]))) (testing "handle ChronoLocalDateTime" (is (= {:global {:distinct-count 2 :nil% 0.0} :type {:type/DateTime {:earliest "2013-01-01T20:04:00Z" :latest "2018-01-01T04:04:00Z"}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Temporal})) [(java.time.LocalDateTime/of 2013 01 01 20 04 0 0) (java.time.LocalDateTime/of 2018 01 01 04 04 0 0)])))) (testing "handle comparing explicit Instant with ChronoLocalDateTime" (is (= {:global {:distinct-count 2 :nil% 0.0} :type {:type/DateTime {:earliest "2007-12-03T10:15:30Z" :latest "2018-01-01T04:04:00Z"}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Temporal})) [(java.time.Instant/parse "2007-12-03T10:15:30.00Z") (java.time.LocalDateTime/of 2018 01 01 04 04 0 0)])))) (testing "mixing numbers and strings" (is (= {:global {:distinct-count 2 :nil% 0.0} :type {:type/DateTime {:earliest "1970-01-01T00:00:01.234Z" :latest "2007-12-03T10:15:30Z"}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Temporal})) ["2007-12-03T10:15:30.00Z" 1234])))) (testing "nil temporal values" (is (= {:global {:distinct-count 1 :nil% 1.0} :type {:type/DateTime {:earliest nil :latest nil}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/DateTime})) (repeat 10 nil))))) (testing "handle all supported types" (is (= {:global {:distinct-count 5 :nil% 0.0} :type {:type/DateTime {:earliest "1970-01-01T00:00:01.234Z" :latest "2020-07-06T20:25:33.36Z"}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Temporal})) (java.time.ZonedDateTime/of 2016 01 01 20 04 0 0 (java.time.ZoneOffset/UTC))])))))))))) (deftest disambiguate-test (testing "We should correctly disambiguate multiple competing multimethods (DateTime and FK in this case)" (let [field {:base_type :type/DateTime :semantic_type :type/FK}] (is (= [:type/DateTime :Semantic/* :type/FK] ((.dispatchFn ^clojure.lang.MultiFn fingerprinters/fingerprinter) field))) (is (= {:global {:distinct-count 3 :nil% 0.0} :type {:type/DateTime {:earliest "2013-01-01" :latest "2018-01-01"}}} (transduce identity (fingerprinters/fingerprinter field) [#t "2013" #t "2018" #t "2015"])))))) (deftest fingerprint-numeric-values-test (is (= {:global {:distinct-count 3 :nil% 0.0} :type {:type/Number {:avg 2.0 :min 1.0 :max 3.0 :q1 1.25 :q3 2.75 :sd 1.0}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Number})) [1.0 2.0 3.0]))) (testing "We should robustly survive weird values such as NaN, Infinity, and nil" (is (= {:global {:distinct-count 7 :nil% 0.25} :type {:type/Number {:avg 2.0 :min 1.0 :max 3.0 :q1 1.25 :q3 2.75 :sd 1.0}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Number})) [1.0 2.0 3.0 Double/NaN Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY nil nil]))))) (deftest fingerprint-string-values-test (is (= {:global {:distinct-count 5 :nil% 0.0} :type {:type/Text {:percent-json 0.2 :percent-url 0.0 :percent-email 0.0 :percent-state 0.0 :average-length 6.4}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Text})) ["metabase" "more" "like" "metabae" "[1, 2, 3]"]))) (let [truncated-json (subs (json/generate-string (vec (range 50))) 0 30)] (is (= {:global {:distinct-count 5 :nil% 0.0} :type {:type/Text {:percent-json 0.2 :percent-url 0.0 :percent-email 0.0 :percent-state 0.0 :average-length 10.6}}} (transduce identity (fingerprinters/fingerprinter (mi/instance Field {:base_type :type/Text})) ["metabase" "more" "like" "metabae" truncated-json]))))) (deftest fingerprints-in-db-test (mt/test-drivers (mt/normal-drivers) (testing "Fingerprints should actually get saved with the correct values" (testing "Text fingerprints" (is (schema= {:global {:distinct-count (s/eq 100) :nil% (s/eq 0.0)} :type {:type/Text {:percent-json (s/eq 0.0) :percent-url (s/eq 0.0) :percent-email (s/eq 0.0) :percent-state (s/eq 0.0) :average-length (s/pred #(< 15 % 16) "between 15 and 16")}}} (db/select-one-field :fingerprint Field :id (mt/id :venues :name))))) (testing "date fingerprints" (is (schema= {:global {:distinct-count (s/eq 618) :nil% (s/eq 0.0)} :type {:type/DateTime {:earliest (s/pred #(str/starts-with? % "2013-01-03")) :latest (s/pred #(str/starts-with? % "2015-12-29"))}}} (db/select-one-field :fingerprint Field :id (mt/id :checkins :date))))) (testing "number fingerprints" (is (schema= {:global {:distinct-count (s/eq 4) :nil% (s/eq 0.0)} :type {:type/Number {:min (s/eq 1.0) :q1 (s/pred #(< 1.44 % 1.46) "approx 1.4591129021415095") :q3 (s/pred #(< 2.4 % 2.5) "approx 2.493086095768049") :max (s/eq 4.0) :sd (s/pred #(< 0.76 % 0.78) "between 0.76 and 0.78") :avg (s/eq 2.03)}}} (db/select-one-field :fingerprint Field :id (mt/id :venues :price)))))))) (deftest valid-serialized-json?-test (testing "recognizes substrings of json" (let [partial-json (fn [x] (let [json (json/generate-string x)] (subs json 0 (/ (count json) 2))))] (is (#'fingerprinters/valid-serialized-json? (partial-json [1 2 3]))) (is (#'fingerprinters/valid-serialized-json? (partial-json {:a 1 :b 2}))) (is (#'fingerprinters/valid-serialized-json? (partial-json [{:a 2}]))) (is (#'fingerprinters/valid-serialized-json? (partial-json [true true]))) (is (not (#'fingerprinters/valid-serialized-json? "bob"))) (is (not (#'fingerprinters/valid-serialized-json? "[bob]"))))))
23a264d2e274b5b04707d22a611efede94f57d6f1ac59795596666d73de2f212
TyOverby/mono
v2.ml
open Core open Async open Private_ssl.V2 type addr = [ `OpenSSL of Ipaddr_sexp.t * int * Ssl.Config.t | `TCP of Ipaddr_sexp.t * int | `Unix_domain_socket of string ] [@@deriving sexp_of] let connect ?interrupt dst = match dst with | `TCP (ip, port) -> let endp = Host_and_port.create ~host:(Ipaddr.to_string ip) ~port in Tcp.connect ?interrupt (Tcp.Where_to_connect.of_host_and_port endp) >>= fun (_, rd, wr) -> return (rd, wr) | `OpenSSL (ip, port, cfg) -> let endp = Host_and_port.create ~host:(Ipaddr.to_string ip) ~port in Tcp.connect ?interrupt (Tcp.Where_to_connect.of_host_and_port endp) >>= fun (_, rd, wr) -> Ssl.connect ~cfg rd wr | `Unix_domain_socket file -> Tcp.connect ?interrupt (Tcp.Where_to_connect.of_file file) >>= fun (_, rd, wr) -> return (rd, wr) let with_connection ?interrupt dst f = match dst with | `TCP (ip, port) -> let endp = Host_and_port.create ~host:(Ipaddr.to_string ip) ~port in Tcp.with_connection ?interrupt (Tcp.Where_to_connect.of_host_and_port endp) (fun _ rd wr -> f rd wr) | `OpenSSL (ip, port, cfg) -> let endp = Host_and_port.create ~host:(Ipaddr.to_string ip) ~port in Tcp.with_connection ?interrupt (Tcp.Where_to_connect.of_host_and_port endp) (fun _ rd wr -> Ssl.connect ~cfg rd wr >>= fun (rd, wr) -> Monitor.protect (fun () -> f rd wr) ~finally:(fun () -> Deferred.all_unit [ Reader.close rd; Writer.close wr ])) | `Unix_domain_socket file -> Tcp.with_connection ?interrupt (Tcp.Where_to_connect.of_file file) (fun _ rd wr -> f rd wr) type trust_chain = [ `Ca_file of string | `Ca_path of string | `Search_file_first_then_path of [ `File of string ] * [ `Path of string ] ] [@@deriving sexp] type openssl = [ `OpenSSL of [ `Crt_file_path of string ] * [ `Key_file_path of string ] ] [@@deriving sexp] type requires_async_ssl = [ openssl | `OpenSSL_with_trust_chain of openssl * trust_chain ] [@@deriving sexp] type server = [ `TCP | requires_async_ssl ] [@@deriving sexp] let serve ?max_connections ?backlog ?buffer_age_limit ~on_handler_error mode where_to_listen handle_request = let handle_client handle_request sock rd wr = match mode with | `TCP -> handle_request sock rd wr | #requires_async_ssl as async_ssl -> let crt_file, key_file, ca_file, ca_path = match async_ssl with | `OpenSSL (`Crt_file_path crt_file, `Key_file_path key_file) -> (crt_file, key_file, None, None) | `OpenSSL_with_trust_chain (`OpenSSL (`Crt_file_path crt, `Key_file_path key), trust_chain) -> let ca_file, ca_path = match trust_chain with | `Ca_file ca_file -> (Some ca_file, None) | `Ca_path ca_path -> (None, Some ca_path) | `Search_file_first_then_path (`File ca_file, `Path ca_path) -> (Some ca_file, Some ca_path) in (crt, key, ca_file, ca_path) in let cfg = Ssl.Config.create ?ca_file ?ca_path ~crt_file ~key_file () in Ssl.listen cfg rd wr >>= fun (rd, wr) -> Monitor.protect (fun () -> handle_request sock rd wr) ~finally:(fun () -> Deferred.all_unit [ Reader.close rd; Writer.close wr ]) in Tcp.Server.create ?max_connections ?backlog ?buffer_age_limit ~on_handler_error where_to_listen (handle_client handle_request) type ssl_version = Ssl.version [@@deriving sexp] type ssl_opt = Ssl.opt [@@deriving sexp] type ssl_conn = Ssl.connection [@@deriving sexp_of] type allowed_ciphers = [ `Only of string list | `Openssl_default | `Secure ] [@@deriving sexp] type verify_mode = Ssl.verify_mode [@@deriving sexp_of] type session = Ssl.session [@@deriving sexp_of] module Ssl = struct module Config = Ssl.Config end
null
https://raw.githubusercontent.com/TyOverby/mono/8d6b3484d5db63f2f5472c7367986ea30290764d/vendor/mirage-ocaml-conduit/src/conduit-async/v2.ml
ocaml
open Core open Async open Private_ssl.V2 type addr = [ `OpenSSL of Ipaddr_sexp.t * int * Ssl.Config.t | `TCP of Ipaddr_sexp.t * int | `Unix_domain_socket of string ] [@@deriving sexp_of] let connect ?interrupt dst = match dst with | `TCP (ip, port) -> let endp = Host_and_port.create ~host:(Ipaddr.to_string ip) ~port in Tcp.connect ?interrupt (Tcp.Where_to_connect.of_host_and_port endp) >>= fun (_, rd, wr) -> return (rd, wr) | `OpenSSL (ip, port, cfg) -> let endp = Host_and_port.create ~host:(Ipaddr.to_string ip) ~port in Tcp.connect ?interrupt (Tcp.Where_to_connect.of_host_and_port endp) >>= fun (_, rd, wr) -> Ssl.connect ~cfg rd wr | `Unix_domain_socket file -> Tcp.connect ?interrupt (Tcp.Where_to_connect.of_file file) >>= fun (_, rd, wr) -> return (rd, wr) let with_connection ?interrupt dst f = match dst with | `TCP (ip, port) -> let endp = Host_and_port.create ~host:(Ipaddr.to_string ip) ~port in Tcp.with_connection ?interrupt (Tcp.Where_to_connect.of_host_and_port endp) (fun _ rd wr -> f rd wr) | `OpenSSL (ip, port, cfg) -> let endp = Host_and_port.create ~host:(Ipaddr.to_string ip) ~port in Tcp.with_connection ?interrupt (Tcp.Where_to_connect.of_host_and_port endp) (fun _ rd wr -> Ssl.connect ~cfg rd wr >>= fun (rd, wr) -> Monitor.protect (fun () -> f rd wr) ~finally:(fun () -> Deferred.all_unit [ Reader.close rd; Writer.close wr ])) | `Unix_domain_socket file -> Tcp.with_connection ?interrupt (Tcp.Where_to_connect.of_file file) (fun _ rd wr -> f rd wr) type trust_chain = [ `Ca_file of string | `Ca_path of string | `Search_file_first_then_path of [ `File of string ] * [ `Path of string ] ] [@@deriving sexp] type openssl = [ `OpenSSL of [ `Crt_file_path of string ] * [ `Key_file_path of string ] ] [@@deriving sexp] type requires_async_ssl = [ openssl | `OpenSSL_with_trust_chain of openssl * trust_chain ] [@@deriving sexp] type server = [ `TCP | requires_async_ssl ] [@@deriving sexp] let serve ?max_connections ?backlog ?buffer_age_limit ~on_handler_error mode where_to_listen handle_request = let handle_client handle_request sock rd wr = match mode with | `TCP -> handle_request sock rd wr | #requires_async_ssl as async_ssl -> let crt_file, key_file, ca_file, ca_path = match async_ssl with | `OpenSSL (`Crt_file_path crt_file, `Key_file_path key_file) -> (crt_file, key_file, None, None) | `OpenSSL_with_trust_chain (`OpenSSL (`Crt_file_path crt, `Key_file_path key), trust_chain) -> let ca_file, ca_path = match trust_chain with | `Ca_file ca_file -> (Some ca_file, None) | `Ca_path ca_path -> (None, Some ca_path) | `Search_file_first_then_path (`File ca_file, `Path ca_path) -> (Some ca_file, Some ca_path) in (crt, key, ca_file, ca_path) in let cfg = Ssl.Config.create ?ca_file ?ca_path ~crt_file ~key_file () in Ssl.listen cfg rd wr >>= fun (rd, wr) -> Monitor.protect (fun () -> handle_request sock rd wr) ~finally:(fun () -> Deferred.all_unit [ Reader.close rd; Writer.close wr ]) in Tcp.Server.create ?max_connections ?backlog ?buffer_age_limit ~on_handler_error where_to_listen (handle_client handle_request) type ssl_version = Ssl.version [@@deriving sexp] type ssl_opt = Ssl.opt [@@deriving sexp] type ssl_conn = Ssl.connection [@@deriving sexp_of] type allowed_ciphers = [ `Only of string list | `Openssl_default | `Secure ] [@@deriving sexp] type verify_mode = Ssl.verify_mode [@@deriving sexp_of] type session = Ssl.session [@@deriving sexp_of] module Ssl = struct module Config = Ssl.Config end
f1b1bdeeef75c04f0272c79fefc9865f0f44c61ccc9c69b5e5caa3c038e8ba9b
dbuenzli/lit
check.ml
---------------------------------------------------------------------------- Copyright ( c ) 2007 , . All rights reserved . Distributed under a BSD license , see .. /LICENSE . ---------------------------------------------------------------------------- Copyright (c) 2007, Daniel C. Bünzli. All rights reserved. Distributed under a BSD license, see ../LICENSE. ----------------------------------------------------------------------------*) module Safe = struct let pr = Format.sprintf let inv = invalid_arg let eq f a v v' = if v <> v' then inv (pr "%s (%s) not = %s" a (f v) (f v')) let gt f a v l = if v <= l then inv (pr "%s (%s) not > %s" a (f v) (f l)) let geq f a v l = if v < l then inv (pr "%s (%s) not >= %s" a (f v) (f l)) let lt f a v u = if v >= u then inv (pr "%s (%s) not < %s" a (f v) (f u)) let leq f a v u = if v > u then inv (pr "%s (%s) not < %s" a (f v) (f u)) let range f a v l u = if v < l || u < v then inv ((pr "%s (%s) not in [%s;%s]") a (f v) (f l) (f u)) let ieq a v v' = if v <> v' then inv (pr "%s (%d) not = %d" a v v') let igt a v l = if v <= l then inv (pr "%s (%d) not > %d" a v l) let igeq a v l = if v < l then inv (pr "%s (%d) not >= %d" a v l) let ilt a v u = if v >= u then inv (pr "%s (%d) not < %d" a v u) let ileq a v u = if v > u then inv (pr "%s (%d) not <= %d" a v u) let irange a v l u = if v < l || u < v then inv (pr "%s (%d) not in [%d;%d]" a v l u) let is_range = function | None -> () | Some (a,b) -> if (a < 0 || b < 0 || b < a) then inv (pr "invalid range (%d,%d)" a b) let spec f k k' = if k <> k' then inv (pr "specialisation error, value is %s cast is %s" (f k) (f k')) end module Unsafe = struct let eq f a v v' = () let gt f a v l = () let geq f a v l = () let lt f a v u = () let leq f a v u = () let range f a v l u = () let ieq a v v' = () let igt a v l = () let igeq a v l = () let ilt a v u = () let ileq a v u = () let irange a v l u = () let is_range r = () let spec f k k' = () end include Safe
null
https://raw.githubusercontent.com/dbuenzli/lit/4058b8a133cd51d3bf756c66b9ab620e39e1d2c4/attic/check.ml
ocaml
---------------------------------------------------------------------------- Copyright ( c ) 2007 , . All rights reserved . Distributed under a BSD license , see .. /LICENSE . ---------------------------------------------------------------------------- Copyright (c) 2007, Daniel C. Bünzli. All rights reserved. Distributed under a BSD license, see ../LICENSE. ----------------------------------------------------------------------------*) module Safe = struct let pr = Format.sprintf let inv = invalid_arg let eq f a v v' = if v <> v' then inv (pr "%s (%s) not = %s" a (f v) (f v')) let gt f a v l = if v <= l then inv (pr "%s (%s) not > %s" a (f v) (f l)) let geq f a v l = if v < l then inv (pr "%s (%s) not >= %s" a (f v) (f l)) let lt f a v u = if v >= u then inv (pr "%s (%s) not < %s" a (f v) (f u)) let leq f a v u = if v > u then inv (pr "%s (%s) not < %s" a (f v) (f u)) let range f a v l u = if v < l || u < v then inv ((pr "%s (%s) not in [%s;%s]") a (f v) (f l) (f u)) let ieq a v v' = if v <> v' then inv (pr "%s (%d) not = %d" a v v') let igt a v l = if v <= l then inv (pr "%s (%d) not > %d" a v l) let igeq a v l = if v < l then inv (pr "%s (%d) not >= %d" a v l) let ilt a v u = if v >= u then inv (pr "%s (%d) not < %d" a v u) let ileq a v u = if v > u then inv (pr "%s (%d) not <= %d" a v u) let irange a v l u = if v < l || u < v then inv (pr "%s (%d) not in [%d;%d]" a v l u) let is_range = function | None -> () | Some (a,b) -> if (a < 0 || b < 0 || b < a) then inv (pr "invalid range (%d,%d)" a b) let spec f k k' = if k <> k' then inv (pr "specialisation error, value is %s cast is %s" (f k) (f k')) end module Unsafe = struct let eq f a v v' = () let gt f a v l = () let geq f a v l = () let lt f a v u = () let leq f a v u = () let range f a v l u = () let ieq a v v' = () let igt a v l = () let igeq a v l = () let ilt a v u = () let ileq a v u = () let irange a v l u = () let is_range r = () let spec f k k' = () end include Safe
3cb222625691298281e8cb66894a99349377b3a76ffd3e9726fbe50798aff685
lispnik/cl-http
dom-server.lisp
;;; -*- Package: ("HTTP"); -*- (in-package "HTTP") "<DOCUMENTATION> <DESCRIPTION> server interface to generation functions <P> they will attempt to serve in the form which the client accepts. which means xml-capable clients get xml, html-capable get the xml restyled to html elements... see <A HREF='/Doc/FILE?PATHNAME=Source;XML:dom-exports.lisp'>dom-exports.lisp</A> for the url exports. " (defMethod dom-documentation-response (datum stream (mime-type (eql :xml)) &aux (xmlp::*print-readably* t)) (princ (make-instance 'xmlp::document :doctype nil :element (xmlp:dom-element datum :DOM)) stream)) (defMethod dom-documentation-response (datum stream (mime-type (eql :html)) &aux (xmlp::*print-readably* t) element) ;; html is printed with the default namespace set so as to leave the tokens unqualified. (setf element (xmlp:dom-element datum :HTML)) (typecase element (xmlp:element (xmlp:with-default-namespace xmlp::*html-package* (print-object element stream)) element) (t (call-next-method)))) (defMethod dom-documentation-response (datum stream (mime-type t)) (xml-1.0:with-element ('html :stream stream) (xml-1.0:with-element ('head :stream stream) (xml-1.0:with-element ('title :stream stream) (write-string "error..." stream))) (xml-1.0:with-element ('body :stream stream) (format stream "can't generate documentation for (~s ~s ~s)" datum stream mime-type)))) (defMethod dom-documentation-response ((datum string) stream (mime-type (eql :xml))) (XML-1.0:with-xml-document ('error :stream stream) (xml-1.0:with-element ('error :stream stream) (write-string datum stream)))) (defMethod dom-documentation-response ((datum string) stream (mime-type (eql :html))) (xml-1.0:with-element ('html :stream stream) (xml-1.0:with-element ('head :stream stream) (xml-1.0:with-element ('title :stream stream) (write-string "error..." stream))) (xml-1.0:with-element ('body :stream stream) (write-string datum stream)))) (defMethod dom-document-source-file ((pathname pathname) (stream stream) (mime-type (eql :html)) &aux (eof (gensym "EOF"))) (with-open-file (input pathname :direction :input) (xml-1.0:with-element ('html :stream stream) (xml-1.0:with-element ('head :stream stream) (xml-1.0:with-element ('title :stream stream) (write-string (pathname-name pathname) stream))) (xml-1.0:with-element ('body :stream stream) (do ((form (read input nil eof) (read input nil eof))) ((eq form eof)) (typecase form (string (write-string form stream)) (t (xml-1.0:with-element ('pre :stream stream) (pprint form stream))))))))) (defMethod dom-document-source-file ((pathname pathname) (stream stream) (mime-type (eql :xml)) &aux (eof (gensym "EOF"))) (with-open-file (input pathname :direction :input) (XML-1.0:with-xml-document ('source-file :stream stream) (do ((form (read input nil eof) (read input nil eof))) ((eq form eof)) (typecase form (string (write-string form stream)) (t (xml-1.0:with-element ('pre :stream stream) (pprint form stream)))))))) "XML"
null
https://raw.githubusercontent.com/lispnik/cl-http/84391892d88c505aed705762a153eb65befb6409/contrib/janderson/xml-1999-05-03/dom-server.lisp
lisp
-*- Package: ("HTTP"); -*- XML:dom-exports.lisp'>dom-exports.lisp</A> html is printed with the default namespace set so as to leave the tokens unqualified.
(in-package "HTTP") "<DOCUMENTATION> <DESCRIPTION> server interface to generation functions <P> they will attempt to serve in the form which the client accepts. which means xml-capable clients get xml, html-capable get the xml restyled to html elements... for the url exports. " (defMethod dom-documentation-response (datum stream (mime-type (eql :xml)) &aux (xmlp::*print-readably* t)) (princ (make-instance 'xmlp::document :doctype nil :element (xmlp:dom-element datum :DOM)) stream)) (defMethod dom-documentation-response (datum stream (mime-type (eql :html)) &aux (xmlp::*print-readably* t) element) (setf element (xmlp:dom-element datum :HTML)) (typecase element (xmlp:element (xmlp:with-default-namespace xmlp::*html-package* (print-object element stream)) element) (t (call-next-method)))) (defMethod dom-documentation-response (datum stream (mime-type t)) (xml-1.0:with-element ('html :stream stream) (xml-1.0:with-element ('head :stream stream) (xml-1.0:with-element ('title :stream stream) (write-string "error..." stream))) (xml-1.0:with-element ('body :stream stream) (format stream "can't generate documentation for (~s ~s ~s)" datum stream mime-type)))) (defMethod dom-documentation-response ((datum string) stream (mime-type (eql :xml))) (XML-1.0:with-xml-document ('error :stream stream) (xml-1.0:with-element ('error :stream stream) (write-string datum stream)))) (defMethod dom-documentation-response ((datum string) stream (mime-type (eql :html))) (xml-1.0:with-element ('html :stream stream) (xml-1.0:with-element ('head :stream stream) (xml-1.0:with-element ('title :stream stream) (write-string "error..." stream))) (xml-1.0:with-element ('body :stream stream) (write-string datum stream)))) (defMethod dom-document-source-file ((pathname pathname) (stream stream) (mime-type (eql :html)) &aux (eof (gensym "EOF"))) (with-open-file (input pathname :direction :input) (xml-1.0:with-element ('html :stream stream) (xml-1.0:with-element ('head :stream stream) (xml-1.0:with-element ('title :stream stream) (write-string (pathname-name pathname) stream))) (xml-1.0:with-element ('body :stream stream) (do ((form (read input nil eof) (read input nil eof))) ((eq form eof)) (typecase form (string (write-string form stream)) (t (xml-1.0:with-element ('pre :stream stream) (pprint form stream))))))))) (defMethod dom-document-source-file ((pathname pathname) (stream stream) (mime-type (eql :xml)) &aux (eof (gensym "EOF"))) (with-open-file (input pathname :direction :input) (XML-1.0:with-xml-document ('source-file :stream stream) (do ((form (read input nil eof) (read input nil eof))) ((eq form eof)) (typecase form (string (write-string form stream)) (t (xml-1.0:with-element ('pre :stream stream) (pprint form stream)))))))) "XML"
1bb13f2fce9e7651623438f09613660ec7d1b6fcb7b7d9cf54beac7f8fd61c3d
kennytilton/cells
observer.lisp
;; -*- mode: Lisp; Syntax: Common-Lisp; Package: triple-cells; -*- ;;; ;;; Copyright ( c ) 2008 by . ;;; (in-package :3c) (defmacro make-observer (id form) `(call-make-observer ,id '(lambda (s p new-value prior-value prior-value?) (declare (ignorable s p new-value prior-value prior-value?)) ,form))) (defun call-make-observer (id observer) (add-triple id !ccc:observer-id-rule (mk-upi (prin1-to-string observer))) (setf (3c-observer id) (eval observer))) ;; while we're at it --- 3cell observation -------------------------------------------------------- (defun cell-observe-change (cell s p new-value prior-value prior-value?) (cond (cell (loop for observer in (get-triples-list :s cell :p !ccc:observer-is) do (funcall (3c-observer (object observer)) s p new-value prior-value prior-value?))) (p (loop for observer in (get-triples-list :s p :p !ccc:observer-id-rule) do (funcall (3c-observer-from-rule-triple observer) s p new-value prior-value prior-value?))))) ( defun cell - observe - change ( cell s p new - value prior - value prior - value ? ) ;;; (trc "observing" p new-value) ( if ( get - triple : s cell :p ! : observer - is ) ; just need one to decide to schedule ;;; (let ((o (new-blank-node))) ;; o = observation, an instance of a cell to be observed and its parameters ( add - triple o ! : obs - s cell ) ( add - triple o ! : obs - p cell ) ( add - triple o ! : obs - new - value ( mk - upi new - value ) ) ( add - triple o ! : obs - prior - value ( mk - upi prior - value ) ) ( add - triple o ! : obs - prior - value ? ( mk - upi prior - value ? ) ) ( add - triple ! : obs - queue ( mk - upi ( get - internal - real - time ) ) o ) ) ( trc " unobserved " s p ) ) ) ;;;(defun process-observer-queue () ;;; (index-new-triples) ( let ( ( oq ( get - triples - list : s ! : obs - queue ) ) ) ;;; (loop for observation in (mapcar 'object oq) for s = ( object ( get - sp observation ! : obs - s ) ) for p = ( object ( get - sp observation ! : obs - p ) ) for new - value = ( get - sp - value observation ! : obs - new - value ) for prior - value = ( get - sp - value observation ! : obs - prior - value ) for prior - value ? = ( get - sp - value observation ! : obs - prior - value ) do ( loop for observer in ( get - triples - list : s s :p ! : observer - is ) do ( funcall ( 3c - observer ( object observer ) ) s p ;;; new-value prior-value prior-value?))))) ;;; ---------------------------------------------------- (defun (setf 3c-observer) (function c-node) (assert (functionp function) () "3c-observer setf not rule: ~a ~a" (type-of function) function) (setf (gethash c-node *3c-observers*) function)) (defun 3c-observer (c-node &aux (unode (part->string c-node))) (or (gethash unode *3c-observers*) (setf (gethash unode *3c-observers*) (let ((fn$ (get-sp-value unode !ccc:observer-id-rule))) (assert fn$) (eval (read-from-string fn$)))))) (defun 3c-observer-from-rule-triple (tr) (let ((fn$ (triple-value tr))) (assert fn$) (eval (read-from-string fn$))))
null
https://raw.githubusercontent.com/kennytilton/cells/64d05c83e155d5f35b3bd115dcd07f152ef79c39/triple-cells/observer.lisp
lisp
-*- mode: Lisp; Syntax: Common-Lisp; Package: triple-cells; -*- while we're at it (trc "observing" p new-value) just need one to decide to schedule (let ((o (new-blank-node))) ;; o = observation, an instance of a cell to be observed and its parameters (defun process-observer-queue () (index-new-triples) (loop for observation in (mapcar 'object oq) new-value prior-value prior-value?))))) ----------------------------------------------------
Copyright ( c ) 2008 by . (in-package :3c) (defmacro make-observer (id form) `(call-make-observer ,id '(lambda (s p new-value prior-value prior-value?) (declare (ignorable s p new-value prior-value prior-value?)) ,form))) (defun call-make-observer (id observer) (add-triple id !ccc:observer-id-rule (mk-upi (prin1-to-string observer))) --- 3cell observation -------------------------------------------------------- (defun cell-observe-change (cell s p new-value prior-value prior-value?) (cond (cell (loop for observer in (get-triples-list :s cell :p !ccc:observer-is) do (funcall (3c-observer (object observer)) s p new-value prior-value prior-value?))) (p (loop for observer in (get-triples-list :s p :p !ccc:observer-id-rule) do (funcall (3c-observer-from-rule-triple observer) s p new-value prior-value prior-value?))))) ( defun cell - observe - change ( cell s p new - value prior - value prior - value ? ) ( add - triple o ! : obs - s cell ) ( add - triple o ! : obs - p cell ) ( add - triple o ! : obs - new - value ( mk - upi new - value ) ) ( add - triple o ! : obs - prior - value ( mk - upi prior - value ) ) ( add - triple o ! : obs - prior - value ? ( mk - upi prior - value ? ) ) ( add - triple ! : obs - queue ( mk - upi ( get - internal - real - time ) ) o ) ) ( trc " unobserved " s p ) ) ) ( let ( ( oq ( get - triples - list : s ! : obs - queue ) ) ) for s = ( object ( get - sp observation ! : obs - s ) ) for p = ( object ( get - sp observation ! : obs - p ) ) for new - value = ( get - sp - value observation ! : obs - new - value ) for prior - value = ( get - sp - value observation ! : obs - prior - value ) for prior - value ? = ( get - sp - value observation ! : obs - prior - value ) do ( loop for observer in ( get - triples - list : s s :p ! : observer - is ) do ( funcall ( 3c - observer ( object observer ) ) s p (defun (setf 3c-observer) (function c-node) (assert (functionp function) () "3c-observer setf not rule: ~a ~a" (type-of function) function) (setf (gethash c-node *3c-observers*) function)) (defun 3c-observer (c-node &aux (unode (part->string c-node))) (or (gethash unode *3c-observers*) (setf (gethash unode *3c-observers*) (let ((fn$ (get-sp-value unode !ccc:observer-id-rule))) (assert fn$) (eval (read-from-string fn$)))))) (defun 3c-observer-from-rule-triple (tr) (let ((fn$ (triple-value tr))) (assert fn$) (eval (read-from-string fn$))))
ec4be5f6297a1e6f200c5a107886a7608bc574f2c38d4cd90fd56c7ea44d5a19
ghcjs/ghcjs
t9844.hs
{-# LANGUAGE BangPatterns #-} module Main where import Debug.Trace newtype N = N Int f0 :: N -> Int f0 n = case n of !(N _) -> 0 f1 :: N -> Int f1 n = n `seq` case n of N _ -> 0 main = do print $ f0 (trace "evaluated f0" (N 1)) print $ f1 (trace "evaluated f1" (N 1))
null
https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/deSugar/t9844.hs
haskell
# LANGUAGE BangPatterns #
module Main where import Debug.Trace newtype N = N Int f0 :: N -> Int f0 n = case n of !(N _) -> 0 f1 :: N -> Int f1 n = n `seq` case n of N _ -> 0 main = do print $ f0 (trace "evaluated f0" (N 1)) print $ f1 (trace "evaluated f1" (N 1))
25daa0d8a3929e2db5e0bdb8ba2db6000cee54f2426624afb2ab2f722af0df5c
ruhatch/mirage-btrees
node.ml
module type NODE = sig type t type pointer type key type value val create : int -> t val noKeys : t -> int val setNoKeys : t -> int -> unit val minDegree : t -> int val pageSize : t -> int val leaf : t -> bool val setLeaf : t -> bool -> unit val getChild : t -> int -> pointer val setChild : t -> int -> pointer -> unit val getKey : t -> int -> key val setKey : t -> int -> key -> unit val getValue : t -> int -> value val setValue : t -> int -> value -> unit val getKeys : t -> key list val printKeys : t -> string list val getValues : t -> value list val printValues : t -> string list end module Node = struct type t = Cstruct.t type pointer = int64 type key = int type value = int64 let create length = let minDegree = (length + 2) / 36 in let node = Cstruct.create length in Cstruct.BE.set_uint16 node 0 0; Cstruct.BE.set_uint16 node 2 minDegree; Cstruct.BE.set_uint16 node 4 length; node let noKeys t = Cstruct.BE.get_uint16 t 0 let setNoKeys t n = Cstruct.BE.set_uint16 t 0 n let minDegree t = Cstruct.BE.get_uint16 t 2 let pageSize t = Cstruct.BE.get_uint16 t 4 let leaf t = match Cstruct.BE.get_uint16 t 6 with | 0 -> false | 1 -> true | _ -> failwith "Invalid node" let setLeaf t b = if b then Cstruct.BE.set_uint16 t 6 1 else Cstruct.BE.set_uint16 t 6 0 Add some bounds checking here ( children from 1 to n+1 ) let getChild t i = Cstruct.BE.get_uint64 t (18 * i - 10) let setChild t i p = Cstruct.BE.set_uint64 t (18 * i - 10) p let getKey t i = Cstruct.BE.get_uint16 t (18 * i - 2) let setKey t i p = Cstruct.BE.set_uint16 t (18 * i - 2) p let getValue t i = Cstruct.BE.get_uint64 t (18 * i) let setValue t i p = Cstruct.BE.set_uint64 t (18 * i) p let getKeys t = let rec loop = function | 0 -> [] | n -> (getKey t n) :: loop (n - 1) in loop (noKeys t) let printKeys t = List.map string_of_int (getKeys t) let getValues t = let rec loop = function | 0 -> [] | n -> (getValue t n) :: loop (n - 1) in loop (noKeys t) let printValues t = List.map Int64.to_string (getValues t) end
null
https://raw.githubusercontent.com/ruhatch/mirage-btrees/902decc6948f49034c87b5b20270a2d686476aea/lib/node.ml
ocaml
module type NODE = sig type t type pointer type key type value val create : int -> t val noKeys : t -> int val setNoKeys : t -> int -> unit val minDegree : t -> int val pageSize : t -> int val leaf : t -> bool val setLeaf : t -> bool -> unit val getChild : t -> int -> pointer val setChild : t -> int -> pointer -> unit val getKey : t -> int -> key val setKey : t -> int -> key -> unit val getValue : t -> int -> value val setValue : t -> int -> value -> unit val getKeys : t -> key list val printKeys : t -> string list val getValues : t -> value list val printValues : t -> string list end module Node = struct type t = Cstruct.t type pointer = int64 type key = int type value = int64 let create length = let minDegree = (length + 2) / 36 in let node = Cstruct.create length in Cstruct.BE.set_uint16 node 0 0; Cstruct.BE.set_uint16 node 2 minDegree; Cstruct.BE.set_uint16 node 4 length; node let noKeys t = Cstruct.BE.get_uint16 t 0 let setNoKeys t n = Cstruct.BE.set_uint16 t 0 n let minDegree t = Cstruct.BE.get_uint16 t 2 let pageSize t = Cstruct.BE.get_uint16 t 4 let leaf t = match Cstruct.BE.get_uint16 t 6 with | 0 -> false | 1 -> true | _ -> failwith "Invalid node" let setLeaf t b = if b then Cstruct.BE.set_uint16 t 6 1 else Cstruct.BE.set_uint16 t 6 0 Add some bounds checking here ( children from 1 to n+1 ) let getChild t i = Cstruct.BE.get_uint64 t (18 * i - 10) let setChild t i p = Cstruct.BE.set_uint64 t (18 * i - 10) p let getKey t i = Cstruct.BE.get_uint16 t (18 * i - 2) let setKey t i p = Cstruct.BE.set_uint16 t (18 * i - 2) p let getValue t i = Cstruct.BE.get_uint64 t (18 * i) let setValue t i p = Cstruct.BE.set_uint64 t (18 * i) p let getKeys t = let rec loop = function | 0 -> [] | n -> (getKey t n) :: loop (n - 1) in loop (noKeys t) let printKeys t = List.map string_of_int (getKeys t) let getValues t = let rec loop = function | 0 -> [] | n -> (getValue t n) :: loop (n - 1) in loop (noKeys t) let printValues t = List.map Int64.to_string (getValues t) end
e36165ffbdc266c7496461af9bee3b7ef19ecf33672e47097a00bf372c610137
mfoemmel/erlang-otp
wxListView.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2008 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% This file is generated DO NOT EDIT %% @doc See external documentation: <a href="">wxListView</a>. %% <p>This class is derived (and can use functions) from: %% <br />{@link wxControl} %% <br />{@link wxWindow} %% <br />{@link wxEvtHandler} %% </p> %% @type wxListView(). An object reference, The representation is internal %% and can be changed without notice. It can't be used for comparsion %% stored on disc or distributed for use on other nodes. -module(wxListView). -include("wxe.hrl"). -export([clearColumnImage/2,focus/2,getFirstSelected/1,getFocusedItem/1,getNextSelected/2, isSelected/2,select/2,select/3,setColumnImage/3]). %% inherited exports -export([cacheBestSize/2,captureMouse/1,center/1,center/2,centerOnParent/1, centerOnParent/2,centre/1,centre/2,centreOnParent/1,centreOnParent/2, clearBackground/1,clientToScreen/2,clientToScreen/3,close/1,close/2, connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2, destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3, enable/1,enable/2,findWindow/2,fit/1,fitInside/1,freeze/1,getAcceleratorTable/1, getBackgroundColour/1,getBackgroundStyle/1,getBestSize/1,getCaret/1, getCharHeight/1,getCharWidth/1,getChildren/1,getClientSize/1,getContainingSizer/1, getCursor/1,getDropTarget/1,getEventHandler/1,getExtraStyle/1,getFont/1, getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1, getId/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,getParent/1, getPosition/1,getRect/1,getScreenPosition/1,getScreenRect/1,getScrollPos/2, getScrollRange/2,getScrollThumb/2,getSize/1,getSizer/1,getTextExtent/2, getTextExtent/3,getToolTip/1,getUpdateRegion/1,getVirtualSize/1,getWindowStyleFlag/1, getWindowVariant/1,hasCapture/1,hasScrollbar/2,hasTransparentBackground/1, hide/1,inheritAttributes/1,initDialog/1,invalidateBestSize/1,isEnabled/1, isExposed/2,isExposed/3,isExposed/5,isRetained/1,isShown/1,isTopLevel/1, layout/1,lineDown/1,lineUp/1,lower/1,makeModal/1,makeModal/2,move/2, move/3,move/4,moveAfterInTabOrder/2,moveBeforeInTabOrder/2,navigate/1, navigate/2,pageDown/1,pageUp/1,parent_class/1,popEventHandler/1,popEventHandler/2, popupMenu/2,popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2, refreshRect/3,releaseMouse/1,removeChild/2,reparent/2,screenToClient/1, screenToClient/2,scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4, setAcceleratorTable/2,setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2, setCaret/2,setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2, setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,setFont/2, setForegroundColour/2,setHelpText/2,setId/2,setLabel/2,setMaxSize/2, setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,setOwnForegroundColour/2, setPalette/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,setScrollbar/6, setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,setSizeHints/3, setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,setSizerAndFit/3, setThemeEnabled/2,setToolTip/2,setVirtualSize/2,setVirtualSize/3, setVirtualSizeHints/2,setVirtualSizeHints/3,setVirtualSizeHints/4, setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,shouldInheritColours/1, show/1,show/2,thaw/1,transferDataFromWindow/1,transferDataToWindow/1, update/1,updateWindowUI/1,updateWindowUI/2,validate/1,warpPointer/3]). %% @hidden parent_class(wxControl) -> true; parent_class(wxWindow) -> true; parent_class(wxEvtHandler) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). @spec ( This::wxListView ( ) , Col::integer ( ) ) - > ok %% @doc See <a href="#wxlistviewclearcolumnimage">external documentation</a>. clearColumnImage(#wx_ref{type=ThisT,ref=ThisRef},Col) when is_integer(Col) -> ?CLASS(ThisT,wxListView), wxe_util:cast(?wxListView_ClearColumnImage, <<ThisRef:32/?UI,Col:32/?UI>>). @spec ( This::wxListView ( ) , Index::integer ( ) ) - > ok %% @doc See <a href="#wxlistviewfocus">external documentation</a>. focus(#wx_ref{type=ThisT,ref=ThisRef},Index) when is_integer(Index) -> ?CLASS(ThisT,wxListView), wxe_util:cast(?wxListView_Focus, <<ThisRef:32/?UI,Index:32/?UI>>). %% @spec (This::wxListView()) -> integer() %% @doc See <a href="#wxlistviewgetfirstselected">external documentation</a>. getFirstSelected(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxListView), wxe_util:call(?wxListView_GetFirstSelected, <<ThisRef:32/?UI>>). %% @spec (This::wxListView()) -> integer() %% @doc See <a href="#wxlistviewgetfocuseditem">external documentation</a>. getFocusedItem(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxListView), wxe_util:call(?wxListView_GetFocusedItem, <<ThisRef:32/?UI>>). %% @spec (This::wxListView(), Item::integer()) -> integer() %% @doc See <a href="#wxlistviewgetnextselected">external documentation</a>. getNextSelected(#wx_ref{type=ThisT,ref=ThisRef},Item) when is_integer(Item) -> ?CLASS(ThisT,wxListView), wxe_util:call(?wxListView_GetNextSelected, <<ThisRef:32/?UI,Item:32/?UI>>). @spec ( This::wxListView ( ) , Index::integer ( ) ) - > bool ( ) %% @doc See <a href="#wxlistviewisselected">external documentation</a>. isSelected(#wx_ref{type=ThisT,ref=ThisRef},Index) when is_integer(Index) -> ?CLASS(ThisT,wxListView), wxe_util:call(?wxListView_IsSelected, <<ThisRef:32/?UI,Index:32/?UI>>). %% @spec (This::wxListView(), N::integer()) -> ok %% @equiv select(This,N, []) select(This,N) when is_record(This, wx_ref),is_integer(N) -> select(This,N, []). %% @spec (This::wxListView(), N::integer(), [Option]) -> ok %% Option = {on, bool()} %% @doc See <a href="#wxlistviewselect">external documentation</a>. select(#wx_ref{type=ThisT,ref=ThisRef},N, Options) when is_integer(N),is_list(Options) -> ?CLASS(ThisT,wxListView), MOpts = fun({on, On}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(On)):32/?UI>>|Acc]; (BadOpt, _) -> erlang:error({badoption, BadOpt}) end, BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)), wxe_util:cast(?wxListView_Select, <<ThisRef:32/?UI,N:32/?UI, BinOpt/binary>>). @spec ( This::wxListView ( ) , Col::integer ( ) , Image::integer ( ) ) - > ok %% @doc See <a href="#wxlistviewsetcolumnimage">external documentation</a>. setColumnImage(#wx_ref{type=ThisT,ref=ThisRef},Col,Image) when is_integer(Col),is_integer(Image) -> ?CLASS(ThisT,wxListView), wxe_util:cast(?wxListView_SetColumnImage, <<ThisRef:32/?UI,Col:32/?UI,Image:32/?UI>>). %% From wxControl %% @hidden setLabel(This,Label) -> wxControl:setLabel(This,Label). %% @hidden getLabel(This) -> wxControl:getLabel(This). %% From wxWindow %% @hidden warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y). %% @hidden validate(This) -> wxWindow:validate(This). %% @hidden updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options). %% @hidden updateWindowUI(This) -> wxWindow:updateWindowUI(This). %% @hidden update(This) -> wxWindow:update(This). %% @hidden transferDataToWindow(This) -> wxWindow:transferDataToWindow(This). %% @hidden transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This). %% @hidden thaw(This) -> wxWindow:thaw(This). %% @hidden show(This, Options) -> wxWindow:show(This, Options). %% @hidden show(This) -> wxWindow:show(This). %% @hidden shouldInheritColours(This) -> wxWindow:shouldInheritColours(This). %% @hidden setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant). %% @hidden setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style). %% @hidden setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style). %% @hidden setVirtualSizeHints(This,MinW,MinH, Options) -> wxWindow:setVirtualSizeHints(This,MinW,MinH, Options). %% @hidden setVirtualSizeHints(This,MinW,MinH) -> wxWindow:setVirtualSizeHints(This,MinW,MinH). %% @hidden setVirtualSizeHints(This,MinSize) -> wxWindow:setVirtualSizeHints(This,MinSize). %% @hidden setVirtualSize(This,X,Y) -> wxWindow:setVirtualSize(This,X,Y). %% @hidden setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size). %% @hidden setToolTip(This,Tip) -> wxWindow:setToolTip(This,Tip). %% @hidden setThemeEnabled(This,EnableTheme) -> wxWindow:setThemeEnabled(This,EnableTheme). %% @hidden setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options). %% @hidden setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer). %% @hidden setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options). %% @hidden setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer). %% @hidden setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options). %% @hidden setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH). %% @hidden setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize). %% @hidden setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options). %% @hidden setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height). %% @hidden setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height). %% @hidden setSize(This,Rect) -> wxWindow:setSize(This,Rect). %% @hidden setScrollPos(This,Orient,Pos, Options) -> wxWindow:setScrollPos(This,Orient,Pos, Options). %% @hidden setScrollPos(This,Orient,Pos) -> wxWindow:setScrollPos(This,Orient,Pos). %% @hidden setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options). %% @hidden setScrollbar(This,Orient,Pos,ThumbVisible,Range) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range). %% @hidden setPalette(This,Pal) -> wxWindow:setPalette(This,Pal). %% @hidden setName(This,Name) -> wxWindow:setName(This,Name). %% @hidden setId(This,Winid) -> wxWindow:setId(This,Winid). %% @hidden setHelpText(This,Text) -> wxWindow:setHelpText(This,Text). %% @hidden setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour). %% @hidden setFont(This,Font) -> wxWindow:setFont(This,Font). %% @hidden setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This). %% @hidden setFocus(This) -> wxWindow:setFocus(This). %% @hidden setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle). %% @hidden setDropTarget(This,DropTarget) -> wxWindow:setDropTarget(This,DropTarget). %% @hidden setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour). %% @hidden setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font). %% @hidden setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour). %% @hidden setMinSize(This,MinSize) -> wxWindow:setMinSize(This,MinSize). %% @hidden setMaxSize(This,MaxSize) -> wxWindow:setMaxSize(This,MaxSize). %% @hidden setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor). %% @hidden setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer). %% @hidden setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height). %% @hidden setClientSize(This,Size) -> wxWindow:setClientSize(This,Size). %% @hidden setCaret(This,Caret) -> wxWindow:setCaret(This,Caret). %% @hidden setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style). %% @hidden setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour). %% @hidden setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout). %% @hidden setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel). %% @hidden scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options). %% @hidden scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy). %% @hidden scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages). %% @hidden scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines). %% @hidden screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt). %% @hidden screenToClient(This) -> wxWindow:screenToClient(This). %% @hidden reparent(This,NewParent) -> wxWindow:reparent(This,NewParent). %% @hidden removeChild(This,Child) -> wxWindow:removeChild(This,Child). %% @hidden releaseMouse(This) -> wxWindow:releaseMouse(This). %% @hidden refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options). %% @hidden refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect). %% @hidden refresh(This, Options) -> wxWindow:refresh(This, Options). %% @hidden refresh(This) -> wxWindow:refresh(This). %% @hidden raise(This) -> wxWindow:raise(This). %% @hidden popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y). %% @hidden popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options). %% @hidden popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu). %% @hidden popEventHandler(This, Options) -> wxWindow:popEventHandler(This, Options). %% @hidden popEventHandler(This) -> wxWindow:popEventHandler(This). %% @hidden pageUp(This) -> wxWindow:pageUp(This). %% @hidden pageDown(This) -> wxWindow:pageDown(This). %% @hidden navigate(This, Options) -> wxWindow:navigate(This, Options). %% @hidden navigate(This) -> wxWindow:navigate(This). %% @hidden moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win). %% @hidden moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win). %% @hidden move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options). %% @hidden move(This,X,Y) -> wxWindow:move(This,X,Y). %% @hidden move(This,Pt) -> wxWindow:move(This,Pt). %% @hidden makeModal(This, Options) -> wxWindow:makeModal(This, Options). %% @hidden makeModal(This) -> wxWindow:makeModal(This). %% @hidden lower(This) -> wxWindow:lower(This). %% @hidden lineUp(This) -> wxWindow:lineUp(This). %% @hidden lineDown(This) -> wxWindow:lineDown(This). %% @hidden layout(This) -> wxWindow:layout(This). %% @hidden isTopLevel(This) -> wxWindow:isTopLevel(This). %% @hidden isShown(This) -> wxWindow:isShown(This). %% @hidden isRetained(This) -> wxWindow:isRetained(This). %% @hidden isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H). %% @hidden isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y). %% @hidden isExposed(This,Pt) -> wxWindow:isExposed(This,Pt). %% @hidden isEnabled(This) -> wxWindow:isEnabled(This). %% @hidden invalidateBestSize(This) -> wxWindow:invalidateBestSize(This). %% @hidden initDialog(This) -> wxWindow:initDialog(This). %% @hidden inheritAttributes(This) -> wxWindow:inheritAttributes(This). %% @hidden hide(This) -> wxWindow:hide(This). %% @hidden hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This). %% @hidden hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient). %% @hidden hasCapture(This) -> wxWindow:hasCapture(This). %% @hidden getWindowVariant(This) -> wxWindow:getWindowVariant(This). %% @hidden getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This). %% @hidden getVirtualSize(This) -> wxWindow:getVirtualSize(This). %% @hidden getUpdateRegion(This) -> wxWindow:getUpdateRegion(This). %% @hidden getToolTip(This) -> wxWindow:getToolTip(This). %% @hidden getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options). %% @hidden getTextExtent(This,String) -> wxWindow:getTextExtent(This,String). %% @hidden getSizer(This) -> wxWindow:getSizer(This). %% @hidden getSize(This) -> wxWindow:getSize(This). %% @hidden getScrollThumb(This,Orient) -> wxWindow:getScrollThumb(This,Orient). %% @hidden getScrollRange(This,Orient) -> wxWindow:getScrollRange(This,Orient). %% @hidden getScrollPos(This,Orient) -> wxWindow:getScrollPos(This,Orient). %% @hidden getScreenRect(This) -> wxWindow:getScreenRect(This). %% @hidden getScreenPosition(This) -> wxWindow:getScreenPosition(This). %% @hidden getRect(This) -> wxWindow:getRect(This). %% @hidden getPosition(This) -> wxWindow:getPosition(This). %% @hidden getParent(This) -> wxWindow:getParent(This). %% @hidden getName(This) -> wxWindow:getName(This). %% @hidden getMinSize(This) -> wxWindow:getMinSize(This). %% @hidden getMaxSize(This) -> wxWindow:getMaxSize(This). %% @hidden getId(This) -> wxWindow:getId(This). %% @hidden getHelpText(This) -> wxWindow:getHelpText(This). %% @hidden getHandle(This) -> wxWindow:getHandle(This). %% @hidden getGrandParent(This) -> wxWindow:getGrandParent(This). %% @hidden getForegroundColour(This) -> wxWindow:getForegroundColour(This). %% @hidden getFont(This) -> wxWindow:getFont(This). %% @hidden getExtraStyle(This) -> wxWindow:getExtraStyle(This). %% @hidden getEventHandler(This) -> wxWindow:getEventHandler(This). %% @hidden getDropTarget(This) -> wxWindow:getDropTarget(This). %% @hidden getCursor(This) -> wxWindow:getCursor(This). %% @hidden getContainingSizer(This) -> wxWindow:getContainingSizer(This). %% @hidden getClientSize(This) -> wxWindow:getClientSize(This). %% @hidden getChildren(This) -> wxWindow:getChildren(This). %% @hidden getCharWidth(This) -> wxWindow:getCharWidth(This). %% @hidden getCharHeight(This) -> wxWindow:getCharHeight(This). %% @hidden getCaret(This) -> wxWindow:getCaret(This). %% @hidden getBestSize(This) -> wxWindow:getBestSize(This). %% @hidden getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This). %% @hidden getBackgroundColour(This) -> wxWindow:getBackgroundColour(This). %% @hidden getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This). %% @hidden freeze(This) -> wxWindow:freeze(This). %% @hidden fitInside(This) -> wxWindow:fitInside(This). %% @hidden fit(This) -> wxWindow:fit(This). %% @hidden findWindow(This,Winid) -> wxWindow:findWindow(This,Winid). %% @hidden enable(This, Options) -> wxWindow:enable(This, Options). %% @hidden enable(This) -> wxWindow:enable(This). %% @hidden disable(This) -> wxWindow:disable(This). %% @hidden destroyChildren(This) -> wxWindow:destroyChildren(This). %% @hidden convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz). %% @hidden convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz). %% @hidden close(This, Options) -> wxWindow:close(This, Options). %% @hidden close(This) -> wxWindow:close(This). %% @hidden clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y). %% @hidden clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt). %% @hidden clearBackground(This) -> wxWindow:clearBackground(This). %% @hidden centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options). %% @hidden centreOnParent(This) -> wxWindow:centreOnParent(This). %% @hidden centre(This, Options) -> wxWindow:centre(This, Options). %% @hidden centre(This) -> wxWindow:centre(This). %% @hidden centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options). %% @hidden centerOnParent(This) -> wxWindow:centerOnParent(This). %% @hidden center(This, Options) -> wxWindow:center(This, Options). %% @hidden center(This) -> wxWindow:center(This). %% @hidden captureMouse(This) -> wxWindow:captureMouse(This). %% @hidden cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size). %% From wxEvtHandler %% @hidden disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options). %% @hidden disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType). %% @hidden disconnect(This) -> wxEvtHandler:disconnect(This). %% @hidden connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options). %% @hidden connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
null
https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/wx/src/gen/wxListView.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% This file is generated DO NOT EDIT @doc See external documentation: <a href="">wxListView</a>. <p>This class is derived (and can use functions) from: <br />{@link wxControl} <br />{@link wxWindow} <br />{@link wxEvtHandler} </p> @type wxListView(). An object reference, The representation is internal and can be changed without notice. It can't be used for comparsion stored on disc or distributed for use on other nodes. inherited exports @hidden @doc See <a href="#wxlistviewclearcolumnimage">external documentation</a>. @doc See <a href="#wxlistviewfocus">external documentation</a>. @spec (This::wxListView()) -> integer() @doc See <a href="#wxlistviewgetfirstselected">external documentation</a>. @spec (This::wxListView()) -> integer() @doc See <a href="#wxlistviewgetfocuseditem">external documentation</a>. @spec (This::wxListView(), Item::integer()) -> integer() @doc See <a href="#wxlistviewgetnextselected">external documentation</a>. @doc See <a href="#wxlistviewisselected">external documentation</a>. @spec (This::wxListView(), N::integer()) -> ok @equiv select(This,N, []) @spec (This::wxListView(), N::integer(), [Option]) -> ok Option = {on, bool()} @doc See <a href="#wxlistviewselect">external documentation</a>. @doc See <a href="#wxlistviewsetcolumnimage">external documentation</a>. From wxControl @hidden @hidden From wxWindow @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden From wxEvtHandler @hidden @hidden @hidden @hidden @hidden
Copyright Ericsson AB 2008 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(wxListView). -include("wxe.hrl"). -export([clearColumnImage/2,focus/2,getFirstSelected/1,getFocusedItem/1,getNextSelected/2, isSelected/2,select/2,select/3,setColumnImage/3]). -export([cacheBestSize/2,captureMouse/1,center/1,center/2,centerOnParent/1, centerOnParent/2,centre/1,centre/2,centreOnParent/1,centreOnParent/2, clearBackground/1,clientToScreen/2,clientToScreen/3,close/1,close/2, connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2, destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3, enable/1,enable/2,findWindow/2,fit/1,fitInside/1,freeze/1,getAcceleratorTable/1, getBackgroundColour/1,getBackgroundStyle/1,getBestSize/1,getCaret/1, getCharHeight/1,getCharWidth/1,getChildren/1,getClientSize/1,getContainingSizer/1, getCursor/1,getDropTarget/1,getEventHandler/1,getExtraStyle/1,getFont/1, getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1, getId/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,getParent/1, getPosition/1,getRect/1,getScreenPosition/1,getScreenRect/1,getScrollPos/2, getScrollRange/2,getScrollThumb/2,getSize/1,getSizer/1,getTextExtent/2, getTextExtent/3,getToolTip/1,getUpdateRegion/1,getVirtualSize/1,getWindowStyleFlag/1, getWindowVariant/1,hasCapture/1,hasScrollbar/2,hasTransparentBackground/1, hide/1,inheritAttributes/1,initDialog/1,invalidateBestSize/1,isEnabled/1, isExposed/2,isExposed/3,isExposed/5,isRetained/1,isShown/1,isTopLevel/1, layout/1,lineDown/1,lineUp/1,lower/1,makeModal/1,makeModal/2,move/2, move/3,move/4,moveAfterInTabOrder/2,moveBeforeInTabOrder/2,navigate/1, navigate/2,pageDown/1,pageUp/1,parent_class/1,popEventHandler/1,popEventHandler/2, popupMenu/2,popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2, refreshRect/3,releaseMouse/1,removeChild/2,reparent/2,screenToClient/1, screenToClient/2,scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4, setAcceleratorTable/2,setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2, setCaret/2,setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2, setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,setFont/2, setForegroundColour/2,setHelpText/2,setId/2,setLabel/2,setMaxSize/2, setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,setOwnForegroundColour/2, setPalette/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,setScrollbar/6, setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,setSizeHints/3, setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,setSizerAndFit/3, setThemeEnabled/2,setToolTip/2,setVirtualSize/2,setVirtualSize/3, setVirtualSizeHints/2,setVirtualSizeHints/3,setVirtualSizeHints/4, setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,shouldInheritColours/1, show/1,show/2,thaw/1,transferDataFromWindow/1,transferDataToWindow/1, update/1,updateWindowUI/1,updateWindowUI/2,validate/1,warpPointer/3]). parent_class(wxControl) -> true; parent_class(wxWindow) -> true; parent_class(wxEvtHandler) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). @spec ( This::wxListView ( ) , Col::integer ( ) ) - > ok clearColumnImage(#wx_ref{type=ThisT,ref=ThisRef},Col) when is_integer(Col) -> ?CLASS(ThisT,wxListView), wxe_util:cast(?wxListView_ClearColumnImage, <<ThisRef:32/?UI,Col:32/?UI>>). @spec ( This::wxListView ( ) , Index::integer ( ) ) - > ok focus(#wx_ref{type=ThisT,ref=ThisRef},Index) when is_integer(Index) -> ?CLASS(ThisT,wxListView), wxe_util:cast(?wxListView_Focus, <<ThisRef:32/?UI,Index:32/?UI>>). getFirstSelected(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxListView), wxe_util:call(?wxListView_GetFirstSelected, <<ThisRef:32/?UI>>). getFocusedItem(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxListView), wxe_util:call(?wxListView_GetFocusedItem, <<ThisRef:32/?UI>>). getNextSelected(#wx_ref{type=ThisT,ref=ThisRef},Item) when is_integer(Item) -> ?CLASS(ThisT,wxListView), wxe_util:call(?wxListView_GetNextSelected, <<ThisRef:32/?UI,Item:32/?UI>>). @spec ( This::wxListView ( ) , Index::integer ( ) ) - > bool ( ) isSelected(#wx_ref{type=ThisT,ref=ThisRef},Index) when is_integer(Index) -> ?CLASS(ThisT,wxListView), wxe_util:call(?wxListView_IsSelected, <<ThisRef:32/?UI,Index:32/?UI>>). select(This,N) when is_record(This, wx_ref),is_integer(N) -> select(This,N, []). select(#wx_ref{type=ThisT,ref=ThisRef},N, Options) when is_integer(N),is_list(Options) -> ?CLASS(ThisT,wxListView), MOpts = fun({on, On}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(On)):32/?UI>>|Acc]; (BadOpt, _) -> erlang:error({badoption, BadOpt}) end, BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)), wxe_util:cast(?wxListView_Select, <<ThisRef:32/?UI,N:32/?UI, BinOpt/binary>>). @spec ( This::wxListView ( ) , Col::integer ( ) , Image::integer ( ) ) - > ok setColumnImage(#wx_ref{type=ThisT,ref=ThisRef},Col,Image) when is_integer(Col),is_integer(Image) -> ?CLASS(ThisT,wxListView), wxe_util:cast(?wxListView_SetColumnImage, <<ThisRef:32/?UI,Col:32/?UI,Image:32/?UI>>). setLabel(This,Label) -> wxControl:setLabel(This,Label). getLabel(This) -> wxControl:getLabel(This). warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y). validate(This) -> wxWindow:validate(This). updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options). updateWindowUI(This) -> wxWindow:updateWindowUI(This). update(This) -> wxWindow:update(This). transferDataToWindow(This) -> wxWindow:transferDataToWindow(This). transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This). thaw(This) -> wxWindow:thaw(This). show(This, Options) -> wxWindow:show(This, Options). show(This) -> wxWindow:show(This). shouldInheritColours(This) -> wxWindow:shouldInheritColours(This). setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant). setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style). setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style). setVirtualSizeHints(This,MinW,MinH, Options) -> wxWindow:setVirtualSizeHints(This,MinW,MinH, Options). setVirtualSizeHints(This,MinW,MinH) -> wxWindow:setVirtualSizeHints(This,MinW,MinH). setVirtualSizeHints(This,MinSize) -> wxWindow:setVirtualSizeHints(This,MinSize). setVirtualSize(This,X,Y) -> wxWindow:setVirtualSize(This,X,Y). setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size). setToolTip(This,Tip) -> wxWindow:setToolTip(This,Tip). setThemeEnabled(This,EnableTheme) -> wxWindow:setThemeEnabled(This,EnableTheme). setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options). setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer). setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options). setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer). setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options). setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH). setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize). setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options). setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height). setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height). setSize(This,Rect) -> wxWindow:setSize(This,Rect). setScrollPos(This,Orient,Pos, Options) -> wxWindow:setScrollPos(This,Orient,Pos, Options). setScrollPos(This,Orient,Pos) -> wxWindow:setScrollPos(This,Orient,Pos). setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options). setScrollbar(This,Orient,Pos,ThumbVisible,Range) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range). setPalette(This,Pal) -> wxWindow:setPalette(This,Pal). setName(This,Name) -> wxWindow:setName(This,Name). setId(This,Winid) -> wxWindow:setId(This,Winid). setHelpText(This,Text) -> wxWindow:setHelpText(This,Text). setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour). setFont(This,Font) -> wxWindow:setFont(This,Font). setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This). setFocus(This) -> wxWindow:setFocus(This). setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle). setDropTarget(This,DropTarget) -> wxWindow:setDropTarget(This,DropTarget). setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour). setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font). setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour). setMinSize(This,MinSize) -> wxWindow:setMinSize(This,MinSize). setMaxSize(This,MaxSize) -> wxWindow:setMaxSize(This,MaxSize). setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor). setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer). setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height). setClientSize(This,Size) -> wxWindow:setClientSize(This,Size). setCaret(This,Caret) -> wxWindow:setCaret(This,Caret). setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style). setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour). setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout). setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel). scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options). scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy). scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages). scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines). screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt). screenToClient(This) -> wxWindow:screenToClient(This). reparent(This,NewParent) -> wxWindow:reparent(This,NewParent). removeChild(This,Child) -> wxWindow:removeChild(This,Child). releaseMouse(This) -> wxWindow:releaseMouse(This). refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options). refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect). refresh(This, Options) -> wxWindow:refresh(This, Options). refresh(This) -> wxWindow:refresh(This). raise(This) -> wxWindow:raise(This). popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y). popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options). popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu). popEventHandler(This, Options) -> wxWindow:popEventHandler(This, Options). popEventHandler(This) -> wxWindow:popEventHandler(This). pageUp(This) -> wxWindow:pageUp(This). pageDown(This) -> wxWindow:pageDown(This). navigate(This, Options) -> wxWindow:navigate(This, Options). navigate(This) -> wxWindow:navigate(This). moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win). moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win). move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options). move(This,X,Y) -> wxWindow:move(This,X,Y). move(This,Pt) -> wxWindow:move(This,Pt). makeModal(This, Options) -> wxWindow:makeModal(This, Options). makeModal(This) -> wxWindow:makeModal(This). lower(This) -> wxWindow:lower(This). lineUp(This) -> wxWindow:lineUp(This). lineDown(This) -> wxWindow:lineDown(This). layout(This) -> wxWindow:layout(This). isTopLevel(This) -> wxWindow:isTopLevel(This). isShown(This) -> wxWindow:isShown(This). isRetained(This) -> wxWindow:isRetained(This). isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H). isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y). isExposed(This,Pt) -> wxWindow:isExposed(This,Pt). isEnabled(This) -> wxWindow:isEnabled(This). invalidateBestSize(This) -> wxWindow:invalidateBestSize(This). initDialog(This) -> wxWindow:initDialog(This). inheritAttributes(This) -> wxWindow:inheritAttributes(This). hide(This) -> wxWindow:hide(This). hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This). hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient). hasCapture(This) -> wxWindow:hasCapture(This). getWindowVariant(This) -> wxWindow:getWindowVariant(This). getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This). getVirtualSize(This) -> wxWindow:getVirtualSize(This). getUpdateRegion(This) -> wxWindow:getUpdateRegion(This). getToolTip(This) -> wxWindow:getToolTip(This). getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options). getTextExtent(This,String) -> wxWindow:getTextExtent(This,String). getSizer(This) -> wxWindow:getSizer(This). getSize(This) -> wxWindow:getSize(This). getScrollThumb(This,Orient) -> wxWindow:getScrollThumb(This,Orient). getScrollRange(This,Orient) -> wxWindow:getScrollRange(This,Orient). getScrollPos(This,Orient) -> wxWindow:getScrollPos(This,Orient). getScreenRect(This) -> wxWindow:getScreenRect(This). getScreenPosition(This) -> wxWindow:getScreenPosition(This). getRect(This) -> wxWindow:getRect(This). getPosition(This) -> wxWindow:getPosition(This). getParent(This) -> wxWindow:getParent(This). getName(This) -> wxWindow:getName(This). getMinSize(This) -> wxWindow:getMinSize(This). getMaxSize(This) -> wxWindow:getMaxSize(This). getId(This) -> wxWindow:getId(This). getHelpText(This) -> wxWindow:getHelpText(This). getHandle(This) -> wxWindow:getHandle(This). getGrandParent(This) -> wxWindow:getGrandParent(This). getForegroundColour(This) -> wxWindow:getForegroundColour(This). getFont(This) -> wxWindow:getFont(This). getExtraStyle(This) -> wxWindow:getExtraStyle(This). getEventHandler(This) -> wxWindow:getEventHandler(This). getDropTarget(This) -> wxWindow:getDropTarget(This). getCursor(This) -> wxWindow:getCursor(This). getContainingSizer(This) -> wxWindow:getContainingSizer(This). getClientSize(This) -> wxWindow:getClientSize(This). getChildren(This) -> wxWindow:getChildren(This). getCharWidth(This) -> wxWindow:getCharWidth(This). getCharHeight(This) -> wxWindow:getCharHeight(This). getCaret(This) -> wxWindow:getCaret(This). getBestSize(This) -> wxWindow:getBestSize(This). getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This). getBackgroundColour(This) -> wxWindow:getBackgroundColour(This). getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This). freeze(This) -> wxWindow:freeze(This). fitInside(This) -> wxWindow:fitInside(This). fit(This) -> wxWindow:fit(This). findWindow(This,Winid) -> wxWindow:findWindow(This,Winid). enable(This, Options) -> wxWindow:enable(This, Options). enable(This) -> wxWindow:enable(This). disable(This) -> wxWindow:disable(This). destroyChildren(This) -> wxWindow:destroyChildren(This). convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz). convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz). close(This, Options) -> wxWindow:close(This, Options). close(This) -> wxWindow:close(This). clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y). clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt). clearBackground(This) -> wxWindow:clearBackground(This). centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options). centreOnParent(This) -> wxWindow:centreOnParent(This). centre(This, Options) -> wxWindow:centre(This, Options). centre(This) -> wxWindow:centre(This). centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options). centerOnParent(This) -> wxWindow:centerOnParent(This). center(This, Options) -> wxWindow:center(This, Options). center(This) -> wxWindow:center(This). captureMouse(This) -> wxWindow:captureMouse(This). cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size). disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options). disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType). disconnect(This) -> wxEvtHandler:disconnect(This). connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options). connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
b1bb15f833813169698f96fb5fbcb965afd2c409c0ed7f44407d23a2b546ff20
danx0r/festival
singing-mode.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Festival Singing Mode ;;; Written by Carnegie Mellon University 11 - 752 - " Speech : Phonetics , Prosody , Perception and Synthesis " Spring 2001 ;;; Extended by < > , 2006 : ;;; - Slur support. - Czech support . ;;; - Some cleanup. ;;; - Print debugging information only when singing-debug is true. ;;; ;;; This code is public domain; anyone may use it freely. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (require_module 'rxp) (xml_register_id "-//SINGING//DTD SINGING mark up//EN" (path-append xml_dtd_dir "Singing.v0_1.dtd") ) (xml_register_id "-//SINGING//ENTITIES Added Latin 1 for SINGING//EN" (path-append xml_dtd_dir "sable-latin.ent") ) ;; Set this to t to enable debugging messages: (defvar singing-debug nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; XML parsing functions ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; singing_xml_targets ;; ;; This variable defines the actions that are to be taken when parsing each of our XML tags : SINGING , PITCH , DURATION , and REST . ;; ;; When we get the pitch and duration of each token, we store them ;; in features of the token. Later our intonation and duration ;; functions access these features. ;; (defvar singing_xml_elements '( ("(SINGING" (ATTLIST UTT) (set! singing_pitch_att_list nil) (set! singing_dur_att_list nil) (set! singing_global_time 0.0) (set! singing_bpm (get-bpm ATTLIST)) (set! singing_bps (/ singing_bpm 60.0)) nil) (")SINGING" (ATTLIST UTT) Synthesize the remaining tokens nil) ("(PITCH" (ATTLIST UTT) (set! singing_pitch_att_list ATTLIST) UTT) (")PITCH" (ATTLIST UTT) (let ((freq (get-freqs singing_pitch_att_list))) (if singing-debug (begin (print "freqs") (print freq))) (singing-append-feature! UTT 'freq freq)) UTT) ("(DURATION" (ATTLIST UTT) (set! singing_dur_att_list ATTLIST) UTT) (")DURATION" (ATTLIST UTT) (let ((dur (get-durs singing_dur_att_list))) (if singing-debug (begin (print "durs") (print dur))) (singing-append-feature! UTT 'dur dur)) UTT) ("(REST" (ATTLIST UTT) (let ((dur (get-durs ATTLIST))) (if singing-debug (begin (print "rest durs") (print dur))) (singing-append-feature! UTT 'rest (caar dur))) UTT) )) ;; ;; get-bpm ;; ;; Given the attribute list of a SINGING tag, returns the beats per minute of the song from the BPM parameter . ;; (define (get-bpm atts) (parse-number (car (car (cdr (assoc 'BPM atts)))))) ;; ;; get-durs ;; ;; Given the attribute list of a DURATION tag, returns a list of durations in seconds for the syllables of the word enclosed by ;; this tag. ;; It first looks for a BEATS parameter , and converts these to seconds using BPM , which was set in the SINGING tag . If this ;; is not present, it looks for the SECONDS parameter. ;; (define (get-durs atts) (let ((seconds (car (car (cdr (assoc 'SECONDS atts))))) (beats (car (car (cdr (assoc 'BEATS atts)))))) (if (equal? beats 'X) (mapcar (lambda (lst) (mapcar parse-number lst)) (string->list seconds)) (mapcar (lambda (lst) (mapcar (lambda (x) (/ (parse-number x) singing_bps)) lst)) (string->list beats))))) ;; ;; get-freqs ;; ;; Given the attribute list of a PITCH tag, returns a list of frequencies in Hertz for the syllables of the word enclosed by ;; this tag. ;; It first looks for a NOTE parameter , which can contain a MIDI ;; note of the form "C4", "D#3", or "Ab6", and if this is not present it looks for the parameter . ;; (define (get-freqs atts) (let ((freqs (car (car (cdr (assoc 'FREQ atts))))) (notes (car (car (cdr (assoc 'NOTE atts)))))) (if (equal? notes 'X) (mapcar (lambda (lst) (mapcar parse-number lst)) (string->list freqs)) (mapcar (lambda (lst) (mapcar note->freq lst)) (string->list notes))))) ;; ;; note->freq ;; ;; Converts a string representing a MIDI note such as "C4" and ;; turns it into a frequency. We use the convention that ( some call this note A3 ) . ;; (define (note->freq note) (if singing-debug (format t "note is %l\n" note)) (set! note (format nil "%s" note)) (if singing-debug (print_string note)) (let (l octave notename midinote thefreq) (set! l (string-length note)) (set! octave (substring note (- l 1) 1)) (set! notename (substring note 0 (- l 1))) (set! midinote (+ (* 12 (parse-number octave)) (notename->midioffset notename))) (set! thefreq (midinote->freq midinote)) (if singing-debug (format t "note %s freq %f\n" note thefreq)) thefreq)) ;; ;; midinote->freq ;; ;; Converts a MIDI note number (1 - 127) into a frequency. We use the convention that 69 = " A5 " = 440 Hz . ;; (define (midinote->freq midinote) (* 440.0 (pow 2.0 (/ (- midinote 69) 12)))) ;; ;; notename->midioffset ;; ;; Utility function that looks up the name of a note like "F#" and ;; returns its offset from C. ;; (define (notename->midioffset notename) (parse-number (car (cdr (assoc_string notename note_names))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Pitch modification functions ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; singing_f0_targets ;; ;; This function replaces the normal intonation function used in ;; festival. For each syllable, it extracts the frequency that was calculated from the XML tags and stored in the token this ;; syllable comes from, and sets this frequency as both the start ;; and end f0 target. Really straightforward! ;; (defvar singing-last-f0 nil) (define (singing_f0_targets utt syl) "(singing_f0_targets utt syl)" (let ((start (item.feat syl 'syllable_start)) (end (item.feat syl 'syllable_end)) (freqs (mapcar parse-number (syl->freq syl))) (durs (syl->durations syl))) (let ((total-durs (apply + durs)) (total-time (- end start)) (time start) (prev-segment (item.prev (item.relation (item.daughter1 (item.relation syl 'SylStructure)) 'Segment))) (last-f0 singing-last-f0)) (if freqs (begin (set! singing-last-f0 (car (last freqs))) (append (if (and last-f0 prev-segment (item.prev prev-segment) (string-equal (item.feat prev-segment 'name) (car (car (cdr (car (PhoneSet.description '(silences)))))))) (let ((s (item.feat prev-segment "p.end")) (e (item.feat prev-segment "end"))) (list (list (+ s (* (- e s) 0.8)) last-f0) (list (+ s (* (- e s) 0.9)) (car freqs))))) (apply append (mapcar (lambda (d f) (let ((range (* (/ d total-durs) total-time)) (old-time time)) (set! time (+ time range)) (let ((range-fraction (* 0.1 range))) (list (list (+ old-time range-fraction) f) (list (- time range-fraction) f))))) durs freqs)))))))) ;; ;; syl->freq ;; ;; Given a syllable, looks up the frequency in its token. The token ;; stores a list of all of the frequencies associated with its ;; syllables, so this syllable grabs the frequency out of the list ;; corresponding to its index within the word. (This assumes that ;; a frequency was given for each syllable, and that a token ;; corresponds directly to a word. Singing-mode is not guaranteed ;; to work at all if either of these things are not true.) ;; (define (syl->freq syl) (let ((index (item.feat syl "R:Syllable.pos_in_word")) (freqs (singing-feat syl "R:SylStructure.parent.R:Token.parent.freq"))) (nth index freqs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Duration modification functions ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; singing_duration_method ;; Calculates the duration of each phone in the utterance , in three passes . Consult the three functions it calls , below , to see what ;; each one does. ;; (define (singing_duration_method utt) (mapcar singing_adjcons_syllable (utt.relation.items utt 'Syllable)) (singing_do_initial utt (car (utt.relation.items utt 'Token))) (mapcar singing_do_syllable (utt.relation.items utt 'Syllable)) (mapcar singing_fix_segment (utt.relation.items utt 'Segment)) utt) ;; ;; singing_adjcons_syllable ;; First pass . Looks at the first phone of each syllable and ;; adjusts the starting time of this syllable such that the perceived start time of the first phone is at the beginning ;; of the originally intended start time of the syllable. ;; ;; If this is not done, telling it to say the word "ta" at time ;; 2.0 actually doesn't "sound" like it says the "t" sound until about 2.1 seconds . ;; ;; This function has a little bit of duplicated code from ;; singing_do_syllable, below - it could be modularized a little ;; better. ;; (define (singing_adjcons_syllable syl) (let ((totlen (apply + (mapcar (lambda (s) (get_avg_duration (item.feat s "name"))) (item.leafs (item.relation syl 'SylStructure))))) (syldur (apply + (syl->durations syl))) figure out the offset of the first phone (phone1 (item.daughter1 (item.relation syl 'SylStructure))) (prevsyl (item.prev (item.relation syl 'Syllable)))) (let ((offset (get_duration_offset (item.feat phone1 "name")))) (if singing-debug (format t "offset: %f\n" offset) ) (if (< syldur totlen) (set! offset (* offset (/ syldur totlen)))) (if singing-debug (format t "Want to adjust syl by %f\n" offset)) (if prevsyl (begin (item.set_feat prevsyl 'subtractoffset offset) (item.set_feat syl 'addoffset offset)))))) ;; ;; singing_do_syllable ;; Second pass . For each syllable , adds up the amount of time ;; that would normally be spent in consonants and vowels, based ;; on the average durations of these phones. Then, if the ;; intended length of this syllable is longer than this total, ;; stretch only the vowels; otherwise shrink all phones ;; proportionally. This function actually sets the "end" time ;; of each phone using a global "singing_global_time" variable. ;; ;; We also handle rests at this point, which are tagged onto the ;; end of the previous token. ;; (defvar singing-max-short-vowel-length 0.11) (define (singing_do_initial utt token) (if (equal? (item.name token) "") (let ((restlen (car (item.feat token 'rest)))) (if singing-debug (format t "restlen %l\n" restlen)) (if (> restlen 0) (let ((silence (car (car (cdr (assoc 'silences (PhoneSet.description))))))) (set! singing_global_time restlen) (item.relation.insert (utt.relation.first utt 'Segment) 'Segment (list silence (list (list "end" singing_global_time))) 'before)))))) (define (singing_do_syllable syl) (let ((conslen 0.0) (vowlen 0.0) (segments (item.leafs (item.relation syl 'SylStructure)))) ;; if there are no vowels, turn a middle consonant into a vowel; ;; hopefully this works well for languages where syllables may be ;; created by some consonants too (let ((segments* segments) (vowel-found nil)) (while (and segments* (not vowel-found)) (if (equal? "+" (item.feat (car segments*) "ph_vc")) (set! vowel-found t) (set! segments* (cdr segments*)))) (if (not vowel-found) (item.set_feat (nth (nint (/ (- (length segments) 1) 2)) segments) "singing-vc" "+"))) ;; sum up the length of all of the vowels and consonants in ;; this syllable (mapcar (lambda (s) (let ((slen (get_avg_duration (item.feat s "name")))) (if (or (equal? "+" (item.feat s "ph_vc")) (equal? "+" (item.feat s "singing-vc"))) (set! vowlen (+ vowlen slen)) (set! conslen (+ conslen slen))))) segments) (let ((totlen (+ conslen vowlen)) (syldur (apply + (syl->durations syl))) (addoffset (item.feat syl 'addoffset)) (subtractoffset (item.feat syl 'subtractoffset)) offset) (set! offset (- subtractoffset addoffset)) (if singing-debug (format t "Vowlen: %f conslen: %f totlen: %f\n" vowlen conslen totlen)) (if (< offset (/ syldur 2.0)) (begin (set! syldur (- syldur offset)) (if singing-debug (format t "Offset: %f\n" offset)))) (if singing-debug (format t "Syldur: %f\n" syldur)) (if (> totlen syldur) ;; if the total length of the average durations in the syllable is ;; greater than the total desired duration of the syllable, stretch ;; the time proportionally for each phone (let ((stretch (/ syldur totlen))) (mapcar (lambda (s) (let ((slen (* stretch (get_avg_duration (item.feat s "name"))))) (set! singing_global_time (+ slen singing_global_time)) (item.set_feat s 'end singing_global_time))) (item.leafs (item.relation syl 'SylStructure)))) ;; otherwise, stretch the vowels and not the consonants (let ((voweltime (- syldur conslen))) (let ((vowelstretch (/ voweltime vowlen)) (phones (mapcar car (car (cdar (PhoneSet.description '(phones))))))) (mapcar (lambda (s) (let ((slen (get_avg_duration (item.feat s "name")))) (if (or (equal? "+" (item.feat s "ph_vc")) (equal? "+" (item.feat s "singing-vc"))) (begin (set! slen (* vowelstretch slen)) ;; If the sound is long enough, better results ;; may be achieved by using longer versions of ;; the vowels. (if (> slen singing-max-short-vowel-length) (let ((sname (string-append (item.feat s "name") ":"))) (if (member_string sname phones) (item.set_feat s "name" sname)))))) (set! singing_global_time (+ slen singing_global_time)) (item.set_feat s 'end singing_global_time))) segments)))))) (let ((restlen (car (syl->rest syl)))) (if singing-debug (format t "restlen %l\n" restlen)) (if (> restlen 0) (let ((lastseg (item.daughtern (item.relation syl 'SylStructure))) (silence (car (car (cdr (assoc 'silences (PhoneSet.description)))))) (singing_global_time* singing_global_time)) (let ((seg (item.relation lastseg 'Segment)) (extra-pause-length 0.00001)) (set! singing_global_time (+ restlen singing_global_time)) (item.insert seg (list silence (list (list "end" singing_global_time))) 'after) ;; insert a very short extra pause to avoid after-effects, especially ;; after vowels (if (and seg (equal? (item.feat seg "ph_vc") "+") (< extra-pause-length restlen)) (item.insert seg (list silence (list (list "end" (+ singing_global_time* extra-pause-length)))) 'after))))))) ;; ;; singing_fix_segment ;; Third pass . Finds any segments ( phones ) that we did n't catch earlier ;; (say if they didn't belong to a syllable, like silence) and sets them to zero duration ;; (define (singing_fix_segment seg) (if (equal? 0.0 (item.feat seg 'end)) (if (equal? nil (item.prev seg)) (item.set_feat seg 'end 0.0) (item.set_feat seg 'end (item.feat (item.prev seg) 'end))) (if singing-debug (format t "segment: %s end: %f\n" (item.name seg) (item.feat seg 'end))))) ;; returns the duration of a syllable (stored in its token) (define (syl->durations syl) (let ((index (item.feat syl "R:Syllable.pos_in_word")) (durs (singing-feat syl "R:SylStructure.parent.R:Token.parent.dur"))) (mapcar parse-number (nth index durs)))) ;; returns the duration of the rest following a syllable (define (syl->rest syl) (let ((index (item.feat syl "R:Syllable.pos_in_word")) (durs (singing-feat syl "R:SylStructure.parent.R:Token.parent.dur")) (pauselen (singing-feat syl "R:SylStructure.parent.R:Token.parent.rest"))) (if (equal? index (- (length durs) 1)) (list (or pauselen 0.0)) (list 0.0)))) ;; get the average duration of a phone (define (get_avg_duration phone) (let ((pd (assoc_string phone phoneme_durations))) (if pd (car (cdr pd)) 0.08))) ;; get the duration offset of a phone (see the description above) (define (get_duration_offset phone) (parse-number (car (cdr (assoc_string phone phoneme_offsets*))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Other utility functions ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (char-quote string) (if (member string '("*" "+" "?" "[" "]" ".")) (string-append "[" string "]") string)) (define (split-string string separator) (if (string-matches string (string-append ".+" (char-quote separator) ".+")) (cons (string-before string separator) (split-string (string-after string separator) separator)) ;; We have to convert the weird XML attribute value type to string (list (string-append string "")))) (define (string->list string) (mapcar (lambda (s) (split-string s "+")) (split-string string ","))) (define (singing-append-feature! utt feature value) (let ((tokens (utt.relation.items utt 'Token))) (if tokens ;; we have to wrap value into a list to work around a Festival bug (item.set_feat (car (last tokens)) feature (list value)) (begin (utt.relation.append utt 'Token '("" ((name "") (whitespace "") (prepunctuation "") (punc "")))) (item.set_feat (car (last (utt.relation.items utt 'Token))) feature (list value)))))) (define (singing-feat item feature) (let ((value (item.feat item feature))) (if (equal? value 0) nil (car value)))) (define (current-language) (cadr (car (assoc 'language (voice.description current-voice))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Initializing and exiting singing mode ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; singing_init_func ;; (defvar singing_previous_eou_tree nil) (define (singing_init_func) "(singing_init_func) - Initialization for Singing mode" (if (not (symbol-bound? 'phoneme_durations)) (set! phoneme_durations '())) ;; use our intonation function (Parameter.set 'Int_Method 'General) (Parameter.set 'Int_Target_Method Int_Targets_General) (set! int_general_params `((targ_func ,singing_f0_targets))) (set! singing-last-f0 nil) ;; use our duration function (Parameter.set 'Duration_Method singing_duration_method) ;; set phoneme corrections for the current language (let ((language (cadr (assoc 'language (cadr (voice.description current-voice)))))) (set! phoneme_offsets* (cdr (assoc language phoneme_offsets)))) ;; avoid splitting to multiple utterances with insertion of unwanted pauses (set! singing_previous_eou_tree eou_tree) (set! eou_tree nil) ;; use our xml parsing function (set! singing_previous_elements xxml_elements) (set! xxml_elements singing_xml_elements)) ;; ;; singing_exit_func ;; (define (singing_exit_func) "(singing_exit_func) - Exit function for Singing mode" (set! eou_tree singing_previous_eou_tree) (set! xxml_elements singing_previous_elements)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Data tables ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar note_names '((C 0) (C# 1) (Db 1) (D 2) (D# 3) (Eb 3) (E 4) (E# 5) (Fb 4) (F 5) (F# 6) (Gb 6) (G 7) (G# 8) (Ab 8) (A 9) (A# 10) (Bb 10) (B 11) (B# 12) (Cb 11))) ;; ;; The following list contains the offset into each phone that best ;; represents the perceptual onset of the phone. This is important ;; to know to get durations right in singing. For example, if the ;; offset for "t" is .060, and you want to start a "t" sound at time 2.0 seconds , you should actually start the phone playing at time 1.940 seconds in order for it to sound like the onset of ;; the "t" is really right at 2.0. ;; ;; These were derived empically by looking at and listening to the waveforms of each phone for mwm 's voice . ;; (defvar phoneme_offsets `((english (t 0.050) (T 0.050) (d 0.090) (D 0.090) (p 0.080) (b 0.080) (k 0.090) (g 0.100) (9r 0.050) ;; r (l 0.030) (f 0.050) (v 0.050) (s 0.040) (S 0.040) (z 0.040) (Z 0.040) (n 0.040) (N 0.040) (m 0.040) (j 0.090) (E 0.0) (> 0.0) (>i 0.0) (aI 0.0) (& 0.0) (3r 0.0) (tS 0.0) (oU 0.0) (aU 0.0) (A 0.0) (ei 0.0) (iU 0.0) (U 0.0) (@ 0.0) (h 0.0) (u 0.0) (^ 0.0) (I 0.0) (dZ 0.0) (i: 0.0) (w 0.0) (pau 0.0) (brth 0.0) (h# 0.0) ))) (defvar phoneme_offsets* nil) ;; ;; Declare the new mode to Festival ;; (set! tts_text_modes (cons `(singing ;; mode name ((init_func ,singing_init_func) (exit_func ,singing_exit_func) (analysis_type xml))) tts_text_modes)) (provide 'singing-mode)
null
https://raw.githubusercontent.com/danx0r/festival/6701715566aee6519a8b7949b567f2fdad1e2772/lib/singing-mode.scm
scheme
Festival Singing Mode - Slur support. - Some cleanup. - Print debugging information only when singing-debug is true. This code is public domain; anyone may use it freely. Set this to t to enable debugging messages: XML parsing functions This variable defines the actions that are to be taken when When we get the pitch and duration of each token, we store them in features of the token. Later our intonation and duration functions access these features. get-bpm Given the attribute list of a SINGING tag, returns the beats get-durs Given the attribute list of a DURATION tag, returns a list of this tag. is not present, it looks for the SECONDS parameter. get-freqs Given the attribute list of a PITCH tag, returns a list of this tag. note of the form "C4", "D#3", or "Ab6", and if this is not note->freq Converts a string representing a MIDI note such as "C4" and turns it into a frequency. We use the convention that midinote->freq Converts a MIDI note number (1 - 127) into a frequency. We use notename->midioffset Utility function that looks up the name of a note like "F#" and returns its offset from C. Pitch modification functions singing_f0_targets This function replaces the normal intonation function used in festival. For each syllable, it extracts the frequency that syllable comes from, and sets this frequency as both the start and end f0 target. Really straightforward! syl->freq Given a syllable, looks up the frequency in its token. The token stores a list of all of the frequencies associated with its syllables, so this syllable grabs the frequency out of the list corresponding to its index within the word. (This assumes that a frequency was given for each syllable, and that a token corresponds directly to a word. Singing-mode is not guaranteed to work at all if either of these things are not true.) Duration modification functions singing_duration_method each one does. singing_adjcons_syllable adjusts the starting time of this syllable such that the of the originally intended start time of the syllable. If this is not done, telling it to say the word "ta" at time 2.0 actually doesn't "sound" like it says the "t" sound until This function has a little bit of duplicated code from singing_do_syllable, below - it could be modularized a little better. singing_do_syllable that would normally be spent in consonants and vowels, based on the average durations of these phones. Then, if the intended length of this syllable is longer than this total, stretch only the vowels; otherwise shrink all phones proportionally. This function actually sets the "end" time of each phone using a global "singing_global_time" variable. We also handle rests at this point, which are tagged onto the end of the previous token. if there are no vowels, turn a middle consonant into a vowel; hopefully this works well for languages where syllables may be created by some consonants too sum up the length of all of the vowels and consonants in this syllable if the total length of the average durations in the syllable is greater than the total desired duration of the syllable, stretch the time proportionally for each phone otherwise, stretch the vowels and not the consonants If the sound is long enough, better results may be achieved by using longer versions of the vowels. insert a very short extra pause to avoid after-effects, especially after vowels singing_fix_segment (say if they didn't belong to a syllable, like silence) and sets them returns the duration of a syllable (stored in its token) returns the duration of the rest following a syllable get the average duration of a phone get the duration offset of a phone (see the description above) Other utility functions We have to convert the weird XML attribute value type to string we have to wrap value into a list to work around a Festival bug Initializing and exiting singing mode singing_init_func use our intonation function use our duration function set phoneme corrections for the current language avoid splitting to multiple utterances with insertion of unwanted pauses use our xml parsing function singing_exit_func Data tables The following list contains the offset into each phone that best represents the perceptual onset of the phone. This is important to know to get durations right in singing. For example, if the offset for "t" is .060, and you want to start a "t" sound at the "t" is really right at 2.0. These were derived empically by looking at and listening to the r Declare the new mode to Festival mode name
Written by Carnegie Mellon University 11 - 752 - " Speech : Phonetics , Prosody , Perception and Synthesis " Spring 2001 Extended by < > , 2006 : - Czech support . (require_module 'rxp) (xml_register_id "-//SINGING//DTD SINGING mark up//EN" (path-append xml_dtd_dir "Singing.v0_1.dtd") ) (xml_register_id "-//SINGING//ENTITIES Added Latin 1 for SINGING//EN" (path-append xml_dtd_dir "sable-latin.ent") ) (defvar singing-debug nil) singing_xml_targets parsing each of our XML tags : SINGING , PITCH , DURATION , and REST . (defvar singing_xml_elements '( ("(SINGING" (ATTLIST UTT) (set! singing_pitch_att_list nil) (set! singing_dur_att_list nil) (set! singing_global_time 0.0) (set! singing_bpm (get-bpm ATTLIST)) (set! singing_bps (/ singing_bpm 60.0)) nil) (")SINGING" (ATTLIST UTT) Synthesize the remaining tokens nil) ("(PITCH" (ATTLIST UTT) (set! singing_pitch_att_list ATTLIST) UTT) (")PITCH" (ATTLIST UTT) (let ((freq (get-freqs singing_pitch_att_list))) (if singing-debug (begin (print "freqs") (print freq))) (singing-append-feature! UTT 'freq freq)) UTT) ("(DURATION" (ATTLIST UTT) (set! singing_dur_att_list ATTLIST) UTT) (")DURATION" (ATTLIST UTT) (let ((dur (get-durs singing_dur_att_list))) (if singing-debug (begin (print "durs") (print dur))) (singing-append-feature! UTT 'dur dur)) UTT) ("(REST" (ATTLIST UTT) (let ((dur (get-durs ATTLIST))) (if singing-debug (begin (print "rest durs") (print dur))) (singing-append-feature! UTT 'rest (caar dur))) UTT) )) per minute of the song from the BPM parameter . (define (get-bpm atts) (parse-number (car (car (cdr (assoc 'BPM atts)))))) durations in seconds for the syllables of the word enclosed by It first looks for a BEATS parameter , and converts these to seconds using BPM , which was set in the SINGING tag . If this (define (get-durs atts) (let ((seconds (car (car (cdr (assoc 'SECONDS atts))))) (beats (car (car (cdr (assoc 'BEATS atts)))))) (if (equal? beats 'X) (mapcar (lambda (lst) (mapcar parse-number lst)) (string->list seconds)) (mapcar (lambda (lst) (mapcar (lambda (x) (/ (parse-number x) singing_bps)) lst)) (string->list beats))))) frequencies in Hertz for the syllables of the word enclosed by It first looks for a NOTE parameter , which can contain a MIDI present it looks for the parameter . (define (get-freqs atts) (let ((freqs (car (car (cdr (assoc 'FREQ atts))))) (notes (car (car (cdr (assoc 'NOTE atts)))))) (if (equal? notes 'X) (mapcar (lambda (lst) (mapcar parse-number lst)) (string->list freqs)) (mapcar (lambda (lst) (mapcar note->freq lst)) (string->list notes))))) ( some call this note A3 ) . (define (note->freq note) (if singing-debug (format t "note is %l\n" note)) (set! note (format nil "%s" note)) (if singing-debug (print_string note)) (let (l octave notename midinote thefreq) (set! l (string-length note)) (set! octave (substring note (- l 1) 1)) (set! notename (substring note 0 (- l 1))) (set! midinote (+ (* 12 (parse-number octave)) (notename->midioffset notename))) (set! thefreq (midinote->freq midinote)) (if singing-debug (format t "note %s freq %f\n" note thefreq)) thefreq)) the convention that 69 = " A5 " = 440 Hz . (define (midinote->freq midinote) (* 440.0 (pow 2.0 (/ (- midinote 69) 12)))) (define (notename->midioffset notename) (parse-number (car (cdr (assoc_string notename note_names))))) was calculated from the XML tags and stored in the token this (defvar singing-last-f0 nil) (define (singing_f0_targets utt syl) "(singing_f0_targets utt syl)" (let ((start (item.feat syl 'syllable_start)) (end (item.feat syl 'syllable_end)) (freqs (mapcar parse-number (syl->freq syl))) (durs (syl->durations syl))) (let ((total-durs (apply + durs)) (total-time (- end start)) (time start) (prev-segment (item.prev (item.relation (item.daughter1 (item.relation syl 'SylStructure)) 'Segment))) (last-f0 singing-last-f0)) (if freqs (begin (set! singing-last-f0 (car (last freqs))) (append (if (and last-f0 prev-segment (item.prev prev-segment) (string-equal (item.feat prev-segment 'name) (car (car (cdr (car (PhoneSet.description '(silences)))))))) (let ((s (item.feat prev-segment "p.end")) (e (item.feat prev-segment "end"))) (list (list (+ s (* (- e s) 0.8)) last-f0) (list (+ s (* (- e s) 0.9)) (car freqs))))) (apply append (mapcar (lambda (d f) (let ((range (* (/ d total-durs) total-time)) (old-time time)) (set! time (+ time range)) (let ((range-fraction (* 0.1 range))) (list (list (+ old-time range-fraction) f) (list (- time range-fraction) f))))) durs freqs)))))))) (define (syl->freq syl) (let ((index (item.feat syl "R:Syllable.pos_in_word")) (freqs (singing-feat syl "R:SylStructure.parent.R:Token.parent.freq"))) (nth index freqs))) Calculates the duration of each phone in the utterance , in three passes . Consult the three functions it calls , below , to see what (define (singing_duration_method utt) (mapcar singing_adjcons_syllable (utt.relation.items utt 'Syllable)) (singing_do_initial utt (car (utt.relation.items utt 'Token))) (mapcar singing_do_syllable (utt.relation.items utt 'Syllable)) (mapcar singing_fix_segment (utt.relation.items utt 'Segment)) utt) First pass . Looks at the first phone of each syllable and perceived start time of the first phone is at the beginning about 2.1 seconds . (define (singing_adjcons_syllable syl) (let ((totlen (apply + (mapcar (lambda (s) (get_avg_duration (item.feat s "name"))) (item.leafs (item.relation syl 'SylStructure))))) (syldur (apply + (syl->durations syl))) figure out the offset of the first phone (phone1 (item.daughter1 (item.relation syl 'SylStructure))) (prevsyl (item.prev (item.relation syl 'Syllable)))) (let ((offset (get_duration_offset (item.feat phone1 "name")))) (if singing-debug (format t "offset: %f\n" offset) ) (if (< syldur totlen) (set! offset (* offset (/ syldur totlen)))) (if singing-debug (format t "Want to adjust syl by %f\n" offset)) (if prevsyl (begin (item.set_feat prevsyl 'subtractoffset offset) (item.set_feat syl 'addoffset offset)))))) Second pass . For each syllable , adds up the amount of time (defvar singing-max-short-vowel-length 0.11) (define (singing_do_initial utt token) (if (equal? (item.name token) "") (let ((restlen (car (item.feat token 'rest)))) (if singing-debug (format t "restlen %l\n" restlen)) (if (> restlen 0) (let ((silence (car (car (cdr (assoc 'silences (PhoneSet.description))))))) (set! singing_global_time restlen) (item.relation.insert (utt.relation.first utt 'Segment) 'Segment (list silence (list (list "end" singing_global_time))) 'before)))))) (define (singing_do_syllable syl) (let ((conslen 0.0) (vowlen 0.0) (segments (item.leafs (item.relation syl 'SylStructure)))) (let ((segments* segments) (vowel-found nil)) (while (and segments* (not vowel-found)) (if (equal? "+" (item.feat (car segments*) "ph_vc")) (set! vowel-found t) (set! segments* (cdr segments*)))) (if (not vowel-found) (item.set_feat (nth (nint (/ (- (length segments) 1) 2)) segments) "singing-vc" "+"))) (mapcar (lambda (s) (let ((slen (get_avg_duration (item.feat s "name")))) (if (or (equal? "+" (item.feat s "ph_vc")) (equal? "+" (item.feat s "singing-vc"))) (set! vowlen (+ vowlen slen)) (set! conslen (+ conslen slen))))) segments) (let ((totlen (+ conslen vowlen)) (syldur (apply + (syl->durations syl))) (addoffset (item.feat syl 'addoffset)) (subtractoffset (item.feat syl 'subtractoffset)) offset) (set! offset (- subtractoffset addoffset)) (if singing-debug (format t "Vowlen: %f conslen: %f totlen: %f\n" vowlen conslen totlen)) (if (< offset (/ syldur 2.0)) (begin (set! syldur (- syldur offset)) (if singing-debug (format t "Offset: %f\n" offset)))) (if singing-debug (format t "Syldur: %f\n" syldur)) (if (> totlen syldur) (let ((stretch (/ syldur totlen))) (mapcar (lambda (s) (let ((slen (* stretch (get_avg_duration (item.feat s "name"))))) (set! singing_global_time (+ slen singing_global_time)) (item.set_feat s 'end singing_global_time))) (item.leafs (item.relation syl 'SylStructure)))) (let ((voweltime (- syldur conslen))) (let ((vowelstretch (/ voweltime vowlen)) (phones (mapcar car (car (cdar (PhoneSet.description '(phones))))))) (mapcar (lambda (s) (let ((slen (get_avg_duration (item.feat s "name")))) (if (or (equal? "+" (item.feat s "ph_vc")) (equal? "+" (item.feat s "singing-vc"))) (begin (set! slen (* vowelstretch slen)) (if (> slen singing-max-short-vowel-length) (let ((sname (string-append (item.feat s "name") ":"))) (if (member_string sname phones) (item.set_feat s "name" sname)))))) (set! singing_global_time (+ slen singing_global_time)) (item.set_feat s 'end singing_global_time))) segments)))))) (let ((restlen (car (syl->rest syl)))) (if singing-debug (format t "restlen %l\n" restlen)) (if (> restlen 0) (let ((lastseg (item.daughtern (item.relation syl 'SylStructure))) (silence (car (car (cdr (assoc 'silences (PhoneSet.description)))))) (singing_global_time* singing_global_time)) (let ((seg (item.relation lastseg 'Segment)) (extra-pause-length 0.00001)) (set! singing_global_time (+ restlen singing_global_time)) (item.insert seg (list silence (list (list "end" singing_global_time))) 'after) (if (and seg (equal? (item.feat seg "ph_vc") "+") (< extra-pause-length restlen)) (item.insert seg (list silence (list (list "end" (+ singing_global_time* extra-pause-length)))) 'after))))))) Third pass . Finds any segments ( phones ) that we did n't catch earlier to zero duration (define (singing_fix_segment seg) (if (equal? 0.0 (item.feat seg 'end)) (if (equal? nil (item.prev seg)) (item.set_feat seg 'end 0.0) (item.set_feat seg 'end (item.feat (item.prev seg) 'end))) (if singing-debug (format t "segment: %s end: %f\n" (item.name seg) (item.feat seg 'end))))) (define (syl->durations syl) (let ((index (item.feat syl "R:Syllable.pos_in_word")) (durs (singing-feat syl "R:SylStructure.parent.R:Token.parent.dur"))) (mapcar parse-number (nth index durs)))) (define (syl->rest syl) (let ((index (item.feat syl "R:Syllable.pos_in_word")) (durs (singing-feat syl "R:SylStructure.parent.R:Token.parent.dur")) (pauselen (singing-feat syl "R:SylStructure.parent.R:Token.parent.rest"))) (if (equal? index (- (length durs) 1)) (list (or pauselen 0.0)) (list 0.0)))) (define (get_avg_duration phone) (let ((pd (assoc_string phone phoneme_durations))) (if pd (car (cdr pd)) 0.08))) (define (get_duration_offset phone) (parse-number (car (cdr (assoc_string phone phoneme_offsets*))))) (define (char-quote string) (if (member string '("*" "+" "?" "[" "]" ".")) (string-append "[" string "]") string)) (define (split-string string separator) (if (string-matches string (string-append ".+" (char-quote separator) ".+")) (cons (string-before string separator) (split-string (string-after string separator) separator)) (list (string-append string "")))) (define (string->list string) (mapcar (lambda (s) (split-string s "+")) (split-string string ","))) (define (singing-append-feature! utt feature value) (let ((tokens (utt.relation.items utt 'Token))) (if tokens (item.set_feat (car (last tokens)) feature (list value)) (begin (utt.relation.append utt 'Token '("" ((name "") (whitespace "") (prepunctuation "") (punc "")))) (item.set_feat (car (last (utt.relation.items utt 'Token))) feature (list value)))))) (define (singing-feat item feature) (let ((value (item.feat item feature))) (if (equal? value 0) nil (car value)))) (define (current-language) (cadr (car (assoc 'language (voice.description current-voice))))) (defvar singing_previous_eou_tree nil) (define (singing_init_func) "(singing_init_func) - Initialization for Singing mode" (if (not (symbol-bound? 'phoneme_durations)) (set! phoneme_durations '())) (Parameter.set 'Int_Method 'General) (Parameter.set 'Int_Target_Method Int_Targets_General) (set! int_general_params `((targ_func ,singing_f0_targets))) (set! singing-last-f0 nil) (Parameter.set 'Duration_Method singing_duration_method) (let ((language (cadr (assoc 'language (cadr (voice.description current-voice)))))) (set! phoneme_offsets* (cdr (assoc language phoneme_offsets)))) (set! singing_previous_eou_tree eou_tree) (set! eou_tree nil) (set! singing_previous_elements xxml_elements) (set! xxml_elements singing_xml_elements)) (define (singing_exit_func) "(singing_exit_func) - Exit function for Singing mode" (set! eou_tree singing_previous_eou_tree) (set! xxml_elements singing_previous_elements)) (defvar note_names '((C 0) (C# 1) (Db 1) (D 2) (D# 3) (Eb 3) (E 4) (E# 5) (Fb 4) (F 5) (F# 6) (Gb 6) (G 7) (G# 8) (Ab 8) (A 9) (A# 10) (Bb 10) (B 11) (B# 12) (Cb 11))) time 2.0 seconds , you should actually start the phone playing at time 1.940 seconds in order for it to sound like the onset of waveforms of each phone for mwm 's voice . (defvar phoneme_offsets `((english (t 0.050) (T 0.050) (d 0.090) (D 0.090) (p 0.080) (b 0.080) (k 0.090) (g 0.100) (l 0.030) (f 0.050) (v 0.050) (s 0.040) (S 0.040) (z 0.040) (Z 0.040) (n 0.040) (N 0.040) (m 0.040) (j 0.090) (E 0.0) (> 0.0) (>i 0.0) (aI 0.0) (& 0.0) (3r 0.0) (tS 0.0) (oU 0.0) (aU 0.0) (A 0.0) (ei 0.0) (iU 0.0) (U 0.0) (@ 0.0) (h 0.0) (u 0.0) (^ 0.0) (I 0.0) (dZ 0.0) (i: 0.0) (w 0.0) (pau 0.0) (brth 0.0) (h# 0.0) ))) (defvar phoneme_offsets* nil) (set! tts_text_modes ((init_func ,singing_init_func) (exit_func ,singing_exit_func) (analysis_type xml))) tts_text_modes)) (provide 'singing-mode)
dad7d301b2454cfe6dcc98f5d756f71af7f7a2c086416325e68c766fe8ea9d1a
yurug/ocaml4.04.0-copatterns
typemod.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. *) (* *) (**************************************************************************) open Misc open Longident open Path open Asttypes open Parsetree open Types open Format type error = Cannot_apply of module_type | Not_included of Includemod.error list | Cannot_eliminate_dependency of module_type | Signature_expected | Structure_expected of module_type | With_no_component of Longident.t | With_mismatch of Longident.t * Includemod.error list | Repeated_name of string * string | Non_generalizable of type_expr | Non_generalizable_class of Ident.t * class_declaration | Non_generalizable_module of module_type | Implementation_is_required of string | Interface_not_compiled of string | Not_allowed_in_functor_body | With_need_typeconstr | Not_a_packed_module of type_expr | Incomplete_packed_module of type_expr | Scoping_pack of Longident.t * type_expr | Recursive_module_require_explicit_type | Apply_generative | Cannot_scrape_alias of Path.t exception Error of Location.t * Env.t * error exception Error_forward of Location.error module ImplementationHooks = Misc.MakeHooks(struct type t = Typedtree.structure * Typedtree.module_coercion end) module InterfaceHooks = Misc.MakeHooks(struct type t = Typedtree.signature end) open Typedtree let fst3 (x,_,_) = x let rec path_concat head p = match p with Pident tail -> Pdot (Pident head, Ident.name tail, 0) | Pdot (pre, s, pos) -> Pdot (path_concat head pre, s, pos) | Papply _ -> assert false (* Extract a signature from a module type *) let extract_sig env loc mty = match Env.scrape_alias env mty with Mty_signature sg -> sg | Mty_alias(_, path) -> raise(Error(loc, env, Cannot_scrape_alias path)) | _ -> raise(Error(loc, env, Signature_expected)) let extract_sig_open env loc mty = match Env.scrape_alias env mty with Mty_signature sg -> sg | Mty_alias(_, path) -> raise(Error(loc, env, Cannot_scrape_alias path)) | _ -> raise(Error(loc, env, Structure_expected mty)) (* Compute the environment after opening a module *) let type_open_ ?toplevel ovf env loc lid = let path, md = Typetexp.find_module env lid.loc lid.txt in let sg = extract_sig_open env lid.loc md.md_type in path, Env.open_signature ~loc ?toplevel ovf path sg env let type_open ?toplevel env sod = let (path, newenv) = type_open_ ?toplevel sod.popen_override env sod.popen_loc sod.popen_lid in let od = { open_override = sod.popen_override; open_path = path; open_txt = sod.popen_lid; open_attributes = sod.popen_attributes; open_loc = sod.popen_loc; } in (path, newenv, od) (* Record a module type *) let rm node = Stypes.record (Stypes.Ti_mod node); node (* Forward declaration, to be filled in by type_module_type_of *) let type_module_type_of_fwd : (Env.t -> Parsetree.module_expr -> Typedtree.module_expr * Types.module_type) ref = ref (fun _env _m -> assert false) (* Merge one "with" constraint in a signature *) let rec add_rec_types env = function Sig_type(id, decl, Trec_next) :: rem -> add_rec_types (Env.add_type ~check:true id decl env) rem | _ -> env let check_type_decl env loc id row_id newdecl decl rs rem = let env = Env.add_type ~check:true id newdecl env in let env = match row_id with | None -> env | Some id -> Env.add_type ~check:true id newdecl env in let env = if rs = Trec_not then env else add_rec_types env rem in Includemod.type_declarations env id newdecl decl; Typedecl.check_coherence env loc id newdecl let update_rec_next rs rem = match rs with Trec_next -> rem | Trec_first | Trec_not -> match rem with Sig_type (id, decl, Trec_next) :: rem -> Sig_type (id, decl, rs) :: rem | Sig_module (id, mty, Trec_next) :: rem -> Sig_module (id, mty, rs) :: rem | _ -> rem let make p n i = let open Variance in set May_pos p (set May_neg n (set May_weak n (set Inj i null))) let merge_constraint initial_env loc sg constr = let lid = match constr with | Pwith_type (lid, _) | Pwith_module (lid, _) -> lid | Pwith_typesubst {ptype_name=s} | Pwith_modsubst (s, _) -> {loc = s.loc; txt=Lident s.txt} in let real_id = ref None in let rec merge env sg namelist row_id = match (sg, namelist, constr) with ([], _, _) -> raise(Error(loc, env, With_no_component lid.txt)) | (Sig_type(id, decl, rs) :: rem, [s], Pwith_type (_, ({ptype_kind = Ptype_abstract} as sdecl))) when Ident.name id = s && Typedecl.is_fixed_type sdecl -> let decl_row = { type_params = List.map (fun _ -> Btype.newgenvar()) sdecl.ptype_params; type_arity = List.length sdecl.ptype_params; type_kind = Type_abstract; type_private = Private; type_manifest = None; type_variance = List.map (fun (_, v) -> let (c, n) = match v with | Covariant -> true, false | Contravariant -> false, true | Invariant -> false, false in make (not n) (not c) false ) sdecl.ptype_params; type_loc = sdecl.ptype_loc; type_newtype_level = None; type_attributes = []; type_immediate = false; type_unboxed = unboxed_false_default_false; } and id_row = Ident.create (s^"#row") in let initial_env = Env.add_type ~check:true id_row decl_row initial_env in let tdecl = Typedecl.transl_with_constraint initial_env id (Some(Pident id_row)) decl sdecl in let newdecl = tdecl.typ_type in check_type_decl env sdecl.ptype_loc id row_id newdecl decl rs rem; let decl_row = {decl_row with type_params = newdecl.type_params} in let rs' = if rs = Trec_first then Trec_not else rs in (Pident id, lid, Twith_type tdecl), Sig_type(id_row, decl_row, rs') :: Sig_type(id, newdecl, rs) :: rem | (Sig_type(id, decl, rs) :: rem , [s], Pwith_type (_, sdecl)) when Ident.name id = s -> let tdecl = Typedecl.transl_with_constraint initial_env id None decl sdecl in let newdecl = tdecl.typ_type in check_type_decl env sdecl.ptype_loc id row_id newdecl decl rs rem; (Pident id, lid, Twith_type tdecl), Sig_type(id, newdecl, rs) :: rem | (Sig_type(id, _, _) :: rem, [s], (Pwith_type _ | Pwith_typesubst _)) when Ident.name id = s ^ "#row" -> merge env rem namelist (Some id) | (Sig_type(id, decl, rs) :: rem, [s], Pwith_typesubst sdecl) when Ident.name id = s -> (* Check as for a normal with constraint, but discard definition *) let tdecl = Typedecl.transl_with_constraint initial_env id None decl sdecl in let newdecl = tdecl.typ_type in check_type_decl env sdecl.ptype_loc id row_id newdecl decl rs rem; real_id := Some id; (Pident id, lid, Twith_typesubst tdecl), update_rec_next rs rem | (Sig_module(id, md, rs) :: rem, [s], Pwith_module (_, lid')) when Ident.name id = s -> let path, md' = Typetexp.find_module initial_env loc lid'.txt in let md'' = {md' with md_type = Mtype.remove_aliases env md'.md_type} in let newmd = Mtype.strengthen_decl ~aliasable:false env md'' path in ignore(Includemod.modtypes env newmd.md_type md.md_type); (Pident id, lid, Twith_module (path, lid')), Sig_module(id, newmd, rs) :: rem | (Sig_module(id, md, rs) :: rem, [s], Pwith_modsubst (_, lid')) when Ident.name id = s -> let path, md' = Typetexp.find_module initial_env loc lid'.txt in let newmd = Mtype.strengthen_decl ~aliasable:false env md' path in ignore(Includemod.modtypes env newmd.md_type md.md_type); real_id := Some id; (Pident id, lid, Twith_modsubst (path, lid')), update_rec_next rs rem | (Sig_module(id, md, rs) :: rem, s :: namelist, _) when Ident.name id = s -> let ((path, _path_loc, tcstr), newsg) = merge env (extract_sig env loc md.md_type) namelist None in (path_concat id path, lid, tcstr), Sig_module(id, {md with md_type=Mty_signature newsg}, rs) :: rem | (item :: rem, _, _) -> let (cstr, items) = merge (Env.add_item item env) rem namelist row_id in cstr, item :: items in try let names = Longident.flatten lid.txt in let (tcstr, sg) = merge initial_env sg names None in let sg = match names, constr with [_], Pwith_typesubst sdecl -> let id = match !real_id with None -> assert false | Some id -> id in let lid = try match sdecl.ptype_manifest with | Some {ptyp_desc = Ptyp_constr (lid, stl)} when List.length stl = List.length sdecl.ptype_params -> List.iter2 (fun x (y, _) -> match x, y with {ptyp_desc=Ptyp_var sx}, {ptyp_desc=Ptyp_var sy} when sx = sy -> () | _, _ -> raise Exit) stl sdecl.ptype_params; lid | _ -> raise Exit with Exit -> raise(Error(sdecl.ptype_loc, initial_env, With_need_typeconstr)) in let path = try Env.lookup_type lid.txt initial_env with Not_found -> assert false in let sub = Subst.add_type id path Subst.identity in Subst.signature sub sg | [_], Pwith_modsubst (_, lid) -> let id = match !real_id with None -> assert false | Some id -> id in let path = Typetexp.lookup_module initial_env loc lid.txt in let sub = Subst.add_module id path Subst.identity in Subst.signature sub sg | _ -> sg in (tcstr, sg) with Includemod.Error explanation -> raise(Error(loc, initial_env, With_mismatch(lid.txt, explanation))) (* Add recursion flags on declarations arising from a mutually recursive block. *) let map_rec fn decls rem = match decls with | [] -> rem | d1 :: dl -> fn Trec_first d1 :: map_end (fn Trec_next) dl rem let map_rec_type ~rec_flag fn decls rem = match decls with | [] -> rem | d1 :: dl -> let first = match rec_flag with | Recursive -> Trec_first | Nonrecursive -> Trec_not in fn first d1 :: map_end (fn Trec_next) dl rem let rec map_rec_type_with_row_types ~rec_flag fn decls rem = match decls with | [] -> rem | d1 :: dl -> if Btype.is_row_name (Ident.name d1.typ_id) then fn Trec_not d1 :: map_rec_type_with_row_types ~rec_flag fn dl rem else map_rec_type ~rec_flag fn decls rem (* Add type extension flags to extension contructors *) let map_ext fn exts rem = match exts with | [] -> rem | d1 :: dl -> fn Text_first d1 :: map_end (fn Text_next) dl rem Auxiliary for translating recursively - defined module types . Return a module type that approximates the shape of the given module type AST . Retain only module , type , and module type components of signatures . For types , retain only their arity , making them abstract otherwise . Return a module type that approximates the shape of the given module type AST. Retain only module, type, and module type components of signatures. For types, retain only their arity, making them abstract otherwise. *) let rec approx_modtype env smty = match smty.pmty_desc with Pmty_ident lid -> let (path, _info) = Typetexp.find_modtype env smty.pmty_loc lid.txt in Mty_ident path | Pmty_alias lid -> let path = Typetexp.lookup_module env smty.pmty_loc lid.txt in Mty_alias(Mta_absent, path) | Pmty_signature ssg -> Mty_signature(approx_sig env ssg) | Pmty_functor(param, sarg, sres) -> let arg = may_map (approx_modtype env) sarg in let (id, newenv) = Env.enter_module ~arg:true param.txt (Btype.default_mty arg) env in let res = approx_modtype newenv sres in Mty_functor(id, arg, res) | Pmty_with(sbody, _constraints) -> approx_modtype env sbody | Pmty_typeof smod -> let (_, mty) = !type_module_type_of_fwd env smod in mty | Pmty_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) and approx_module_declaration env pmd = { Types.md_type = approx_modtype env pmd.pmd_type; md_attributes = pmd.pmd_attributes; md_loc = pmd.pmd_loc; } and approx_sig env ssg = match ssg with [] -> [] | item :: srem -> match item.psig_desc with | Psig_type (rec_flag, sdecls) -> let decls = Typedecl.approx_type_decl sdecls in let rem = approx_sig env srem in map_rec_type ~rec_flag (fun rs (id, info) -> Sig_type(id, info, rs)) decls rem | Psig_module pmd -> let id = Ident.create pmd.pmd_name.txt in let md = approx_module_declaration env pmd in let newenv = Env.enter_module_declaration id md env in Sig_module(id, md, Trec_not) :: approx_sig newenv srem | Psig_recmodule sdecls -> let decls = List.map (fun pmd -> (Ident.create pmd.pmd_name.txt, approx_module_declaration env pmd) ) sdecls in let newenv = List.fold_left (fun env (id, md) -> Env.add_module_declaration ~check:false id md env) env decls in map_rec (fun rs (id, md) -> Sig_module(id, md, rs)) decls (approx_sig newenv srem) | Psig_modtype d -> let info = approx_modtype_info env d in let (id, newenv) = Env.enter_modtype d.pmtd_name.txt info env in Sig_modtype(id, info) :: approx_sig newenv srem | Psig_open sod -> let (_path, mty, _od) = type_open env sod in approx_sig mty srem | Psig_include sincl -> let smty = sincl.pincl_mod in let mty = approx_modtype env smty in let sg = Subst.signature Subst.identity (extract_sig env smty.pmty_loc mty) in let newenv = Env.add_signature sg env in sg @ approx_sig newenv srem | Psig_class sdecls | Psig_class_type sdecls -> let decls = Typeclass.approx_class_declarations env sdecls in let rem = approx_sig env srem in List.flatten (map_rec (fun rs decl -> let open Typeclass in [Sig_class_type(decl.clsty_ty_id, decl.clsty_ty_decl, rs); Sig_type(decl.clsty_obj_id, decl.clsty_obj_abbr, rs); Sig_type(decl.clsty_typesharp_id, decl.clsty_abbr, rs)]) decls [rem]) | _ -> approx_sig env srem and approx_modtype_info env sinfo = { mtd_type = may_map (approx_modtype env) sinfo.pmtd_type; mtd_attributes = sinfo.pmtd_attributes; mtd_loc = sinfo.pmtd_loc; } (* Additional validity checks on type definitions arising from recursive modules *) let check_recmod_typedecls env sdecls decls = let recmod_ids = List.map fst3 decls in List.iter2 (fun pmd (id, _, mty) -> let mty = mty.mty_type in List.iter (fun path -> Typedecl.check_recmod_typedecl env pmd.pmd_type.pmty_loc recmod_ids path (Env.find_type path env)) (Mtype.type_paths env (Pident id) mty)) sdecls decls Auxiliaries for checking uniqueness of names in signatures and structures module StringSet = Set.Make(struct type t = string let compare (x:t) y = String.compare x y end) let check cl loc set_ref name = if StringSet.mem name !set_ref then raise(Error(loc, Env.empty, Repeated_name(cl, name))) else set_ref := StringSet.add name !set_ref type names = { types: StringSet.t ref; modules: StringSet.t ref; modtypes: StringSet.t ref; typexts: StringSet.t ref; } let new_names () = { types = ref StringSet.empty; modules = ref StringSet.empty; modtypes = ref StringSet.empty; typexts = ref StringSet.empty; } let check_name check names name = check names name.loc name.txt let check_type names loc s = check "type" loc names.types s let check_module names loc s = check "module" loc names.modules s let check_modtype names loc s = check "module type" loc names.modtypes s let check_typext names loc s = check "extension constructor" loc names.typexts s let check_sig_item names loc = function | Sig_type(id, _, _) -> check_type names loc (Ident.name id) | Sig_module(id, _, _) -> check_module names loc (Ident.name id) | Sig_modtype(id, _) -> check_modtype names loc (Ident.name id) | Sig_typext(id, _, _) -> check_typext names loc (Ident.name id) | _ -> () (* Simplify multiple specifications of a value or an extension in a signature. (Other signature components, e.g. types, modules, etc, are checked for name uniqueness.) If multiple specifications with the same name, keep only the last (rightmost) one. *) let simplify_signature sg = let rec aux = function | [] -> [], StringSet.empty | (Sig_value(id, _descr) as component) :: sg -> let (sg, val_names) as k = aux sg in let name = Ident.name id in if StringSet.mem name val_names then k else (component :: sg, StringSet.add name val_names) | component :: sg -> let (sg, val_names) = aux sg in (component :: sg, val_names) in let (sg, _) = aux sg in sg (* Check and translate a module type expression *) let transl_modtype_longident loc env lid = let (path, _info) = Typetexp.find_modtype env loc lid in path let transl_module_alias loc env lid = Typetexp.lookup_module env loc lid let mkmty desc typ env loc attrs = let mty = { mty_desc = desc; mty_type = typ; mty_loc = loc; mty_env = env; mty_attributes = attrs; } in Cmt_format.add_saved_type (Cmt_format.Partial_module_type mty); mty let mksig desc env loc = let sg = { sig_desc = desc; sig_loc = loc; sig_env = env } in Cmt_format.add_saved_type (Cmt_format.Partial_signature_item sg); sg let signature sg = List.map ( fun item - > item.sig_type ) sg let rec transl_modtype env smty = let loc = smty.pmty_loc in match smty.pmty_desc with Pmty_ident lid -> let path = transl_modtype_longident loc env lid.txt in mkmty (Tmty_ident (path, lid)) (Mty_ident path) env loc smty.pmty_attributes | Pmty_alias lid -> let path = transl_module_alias loc env lid.txt in mkmty (Tmty_alias (path, lid)) (Mty_alias(Mta_absent, path)) env loc smty.pmty_attributes | Pmty_signature ssg -> let sg = transl_signature env ssg in mkmty (Tmty_signature sg) (Mty_signature sg.sig_type) env loc smty.pmty_attributes | Pmty_functor(param, sarg, sres) -> let arg = Misc.may_map (transl_modtype env) sarg in let ty_arg = Misc.may_map (fun m -> m.mty_type) arg in let (id, newenv) = Env.enter_module ~arg:true param.txt (Btype.default_mty ty_arg) env in Ctype.init_def(Ident.current_time()); (* PR#6513 *) let res = transl_modtype newenv sres in mkmty (Tmty_functor (id, param, arg, res)) (Mty_functor(id, ty_arg, res.mty_type)) env loc smty.pmty_attributes | Pmty_with(sbody, constraints) -> let body = transl_modtype env sbody in let init_sg = extract_sig env sbody.pmty_loc body.mty_type in let (rev_tcstrs, final_sg) = List.fold_left (fun (rev_tcstrs,sg) sdecl -> let (tcstr, sg) = merge_constraint env smty.pmty_loc sg sdecl in (tcstr :: rev_tcstrs, sg) ) ([],init_sg) constraints in mkmty (Tmty_with ( body, List.rev rev_tcstrs)) (Mtype.freshen (Mty_signature final_sg)) env loc smty.pmty_attributes | Pmty_typeof smod -> let env = Env.in_signature false env in let tmty, mty = !type_module_type_of_fwd env smod in mkmty (Tmty_typeof tmty) mty env loc smty.pmty_attributes | Pmty_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) and transl_signature env sg = let names = new_names () in let rec transl_sig env sg = Ctype.init_def(Ident.current_time()); match sg with [] -> [], [], env | item :: srem -> let loc = item.psig_loc in match item.psig_desc with | Psig_value sdesc -> let (tdesc, newenv) = Builtin_attributes.with_warning_attribute sdesc.pval_attributes (fun () -> Typedecl.transl_value_decl env item.psig_loc sdesc) in let (trem,rem, final_env) = transl_sig newenv srem in mksig (Tsig_value tdesc) env loc :: trem, Sig_value(tdesc.val_id, tdesc.val_val) :: rem, final_env | Psig_type (rec_flag, sdecls) -> List.iter (fun decl -> check_name check_type names decl.ptype_name) sdecls; let (decls, newenv) = Typedecl.transl_type_decl env rec_flag sdecls in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_type (rec_flag, decls)) env loc :: trem, map_rec_type_with_row_types ~rec_flag (fun rs td -> Sig_type(td.typ_id, td.typ_type, rs)) decls rem, final_env | Psig_typext styext -> List.iter (fun pext -> check_name check_typext names pext.pext_name) styext.ptyext_constructors; let (tyext, newenv) = Typedecl.transl_type_extension false env item.psig_loc styext in let (trem, rem, final_env) = transl_sig newenv srem in let constructors = tyext.tyext_constructors in mksig (Tsig_typext tyext) env loc :: trem, map_ext (fun es ext -> Sig_typext(ext.ext_id, ext.ext_type, es)) constructors rem, final_env | Psig_exception sext -> check_name check_typext names sext.pext_name; let (ext, newenv) = Typedecl.transl_exception env sext in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_exception ext) env loc :: trem, Sig_typext(ext.ext_id, ext.ext_type, Text_exception) :: rem, final_env | Psig_module pmd -> check_name check_module names pmd.pmd_name; let id = Ident.create pmd.pmd_name.txt in let tmty = Builtin_attributes.with_warning_attribute pmd.pmd_attributes (fun () -> transl_modtype env pmd.pmd_type) in let md = { md_type=tmty.mty_type; md_attributes=pmd.pmd_attributes; md_loc=pmd.pmd_loc; } in let newenv = Env.enter_module_declaration id md env in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_module {md_id=id; md_name=pmd.pmd_name; md_type=tmty; md_loc=pmd.pmd_loc; md_attributes=pmd.pmd_attributes}) env loc :: trem, Sig_module(id, md, Trec_not) :: rem, final_env | Psig_recmodule sdecls -> List.iter (fun pmd -> check_name check_module names pmd.pmd_name) sdecls; let (decls, newenv) = transl_recmodule_modtypes env sdecls in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_recmodule decls) env loc :: trem, map_rec (fun rs md -> let d = {Types.md_type = md.md_type.mty_type; md_attributes = md.md_attributes; md_loc = md.md_loc; } in Sig_module(md.md_id, d, rs)) decls rem, final_env | Psig_modtype pmtd -> let newenv, mtd, sg = Builtin_attributes.with_warning_attribute pmtd.pmtd_attributes (fun () -> transl_modtype_decl names env pmtd) in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_modtype mtd) env loc :: trem, sg :: rem, final_env | Psig_open sod -> let (_path, newenv, od) = type_open env sod in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_open od) env loc :: trem, rem, final_env | Psig_include sincl -> let smty = sincl.pincl_mod in let tmty = Builtin_attributes.with_warning_attribute sincl.pincl_attributes (fun () -> transl_modtype env smty) in let mty = tmty.mty_type in let sg = Subst.signature Subst.identity (extract_sig env smty.pmty_loc mty) in List.iter (check_sig_item names item.psig_loc) sg; let newenv = Env.add_signature sg env in let incl = { incl_mod = tmty; incl_type = sg; incl_attributes = sincl.pincl_attributes; incl_loc = sincl.pincl_loc; } in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_include incl) env loc :: trem, sg @ rem, final_env | Psig_class cl -> List.iter (fun {pci_name} -> check_name check_type names pci_name) cl; let (classes, newenv) = Typeclass.class_descriptions env cl in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_class (List.map (fun decr -> decr.Typeclass.cls_info) classes)) env loc :: trem, List.flatten (map_rec (fun rs cls -> let open Typeclass in [Sig_class(cls.cls_id, cls.cls_decl, rs); Sig_class_type(cls.cls_ty_id, cls.cls_ty_decl, rs); Sig_type(cls.cls_obj_id, cls.cls_obj_abbr, rs); Sig_type(cls.cls_typesharp_id, cls.cls_abbr, rs)]) classes [rem]), final_env | Psig_class_type cl -> List.iter (fun {pci_name} -> check_name check_type names pci_name) cl; let (classes, newenv) = Typeclass.class_type_declarations env cl in let (trem,rem, final_env) = transl_sig newenv srem in mksig (Tsig_class_type (List.map (fun decl -> decl.Typeclass.clsty_info) classes)) env loc :: trem, List.flatten (map_rec (fun rs decl -> let open Typeclass in [Sig_class_type(decl.clsty_ty_id, decl.clsty_ty_decl, rs); Sig_type(decl.clsty_obj_id, decl.clsty_obj_abbr, rs); Sig_type(decl.clsty_typesharp_id, decl.clsty_abbr, rs)]) classes [rem]), final_env | Psig_attribute x -> Builtin_attributes.warning_attribute [x]; let (trem,rem, final_env) = transl_sig env srem in mksig (Tsig_attribute x) env loc :: trem, rem, final_env | Psig_extension (ext, _attrs) -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) in let previous_saved_types = Cmt_format.get_saved_types () in Builtin_attributes.warning_enter_scope (); let (trem, rem, final_env) = transl_sig (Env.in_signature true env) sg in let rem = simplify_signature rem in let sg = { sig_items = trem; sig_type = rem; sig_final_env = final_env } in Builtin_attributes.warning_leave_scope (); Cmt_format.set_saved_types ((Cmt_format.Partial_signature sg) :: previous_saved_types); sg and transl_modtype_decl names env {pmtd_name; pmtd_type; pmtd_attributes; pmtd_loc} = check_name check_modtype names pmtd_name; let tmty = Misc.may_map (transl_modtype env) pmtd_type in let decl = { Types.mtd_type=may_map (fun t -> t.mty_type) tmty; mtd_attributes=pmtd_attributes; mtd_loc=pmtd_loc; } in let (id, newenv) = Env.enter_modtype pmtd_name.txt decl env in let mtd = { mtd_id=id; mtd_name=pmtd_name; mtd_type=tmty; mtd_attributes=pmtd_attributes; mtd_loc=pmtd_loc; } in newenv, mtd, Sig_modtype(id, decl) and transl_recmodule_modtypes env sdecls = let make_env curr = List.fold_left (fun env (id, _, mty) -> Env.add_module ~arg:true id mty env) env curr in let make_env2 curr = List.fold_left (fun env (id, _, mty) -> Env.add_module ~arg:true id mty.mty_type env) env curr in let transition env_c curr = List.map2 (fun pmd (id, id_loc, _mty) -> let tmty = Builtin_attributes.with_warning_attribute pmd.pmd_attributes (fun () -> transl_modtype env_c pmd.pmd_type) in (id, id_loc, tmty)) sdecls curr in let ids = List.map (fun x -> Ident.create x.pmd_name.txt) sdecls in let approx_env = cf # 5965 We use a dummy module type in order to detect a reference to one of the module being defined during the call to approx_modtype . It will be detected in Env.lookup_module . cf #5965 We use a dummy module type in order to detect a reference to one of the module being defined during the call to approx_modtype. It will be detected in Env.lookup_module. *) List.fold_left (fun env id -> let dummy = Mty_ident (Path.Pident (Ident.create "#recmod#")) in Env.add_module ~arg:true id dummy env ) env ids in PR#7082 let init = List.map2 (fun id pmd -> (id, pmd.pmd_name, approx_modtype approx_env pmd.pmd_type)) ids sdecls in let env0 = make_env init in let dcl1 = transition env0 init in let env1 = make_env2 dcl1 in check_recmod_typedecls env1 sdecls dcl1; let dcl2 = transition env1 dcl1 in List.iter ( fun ( i d , mty ) - > " % a : % a@. " Printtyp.ident i d Printtyp.modtype mty ) dcl2 ; List.iter (fun (id, mty) -> Format.printf "%a: %a@." Printtyp.ident id Printtyp.modtype mty) dcl2; *) let env2 = make_env2 dcl2 in check_recmod_typedecls env2 sdecls dcl2; let dcl2 = List.map2 (fun pmd (id, id_loc, mty) -> {md_id=id; md_name=id_loc; md_type=mty; md_loc=pmd.pmd_loc; md_attributes=pmd.pmd_attributes}) sdecls dcl2 in (dcl2, env2) (* Try to convert a module expression to a module path. *) exception Not_a_path let rec path_of_module mexp = match mexp.mod_desc with Tmod_ident (p,_) -> p | Tmod_apply(funct, arg, _coercion) when !Clflags.applicative_functors -> Papply(path_of_module funct, path_of_module arg) | Tmod_constraint (mexp, _, _, _) -> path_of_module mexp | _ -> raise Not_a_path let path_of_module mexp = try Some (path_of_module mexp) with Not_a_path -> None (* Check that all core type schemes in a structure are closed *) let rec closed_modtype env = function Mty_ident _ -> true | Mty_alias _ -> true | Mty_signature sg -> let env = Env.add_signature sg env in List.for_all (closed_signature_item env) sg | Mty_functor(id, param, body) -> let env = Env.add_module ~arg:true id (Btype.default_mty param) env in closed_modtype env body and closed_signature_item env = function Sig_value(_id, desc) -> Ctype.closed_schema env desc.val_type | Sig_module(_id, md, _) -> closed_modtype env md.md_type | _ -> true let check_nongen_scheme env sig_item = match sig_item with Sig_value(_id, vd) -> if not (Ctype.closed_schema env vd.val_type) then raise (Error (vd.val_loc, env, Non_generalizable vd.val_type)) | Sig_module (_id, md, _) -> if not (closed_modtype env md.md_type) then raise(Error(md.md_loc, env, Non_generalizable_module md.md_type)) | _ -> () let check_nongen_schemes env sg = List.iter (check_nongen_scheme env) sg (* Helpers for typing recursive modules *) let anchor_submodule name anchor = match anchor with None -> None | Some p -> Some(Pdot(p, name, nopos)) let anchor_recmodule id = Some (Pident id) let enrich_type_decls anchor decls oldenv newenv = match anchor with None -> newenv | Some p -> List.fold_left (fun e info -> let id = info.typ_id in let info' = Mtype.enrich_typedecl oldenv (Pdot(p, Ident.name id, nopos)) info.typ_type in Env.add_type ~check:true id info' e) oldenv decls let enrich_module_type anchor name mty env = match anchor with None -> mty | Some p -> Mtype.enrich_modtype env (Pdot(p, name, nopos)) mty let check_recmodule_inclusion env bindings = PR#4450 , PR#4470 : consider module rec X : = MOD where MOD has inferred type ACTUAL The " natural " typing condition E , X : ACTUAL |- ACTUAL < : leads to circularities through manifest types . Instead , we " unroll away " the potential circularities a finite number of times . The ( weaker ) condition we implement is : E , X : , X1 : ACTUAL , X2 : ACTUAL{X < - X1}/X1 ... Xn : ACTUAL{X < - X(n-1)}/X(n-1 ) |- ACTUAL{X < - Xn}/Xn < : DECL{X < - Xn } so that manifest types rooted at X(n+1 ) are expanded in terms of X(n ) , avoiding circularities . The strengthenings ensure that Xn.t = X(n-1).t = ... = X2.t = X1.t . N can be chosen arbitrarily ; larger values of N result in more recursive definitions being accepted . A good choice appears to be the number of mutually recursive declarations . module rec X : DECL = MOD where MOD has inferred type ACTUAL The "natural" typing condition E, X: ACTUAL |- ACTUAL <: DECL leads to circularities through manifest types. Instead, we "unroll away" the potential circularities a finite number of times. The (weaker) condition we implement is: E, X: DECL, X1: ACTUAL, X2: ACTUAL{X <- X1}/X1 ... Xn: ACTUAL{X <- X(n-1)}/X(n-1) |- ACTUAL{X <- Xn}/Xn <: DECL{X <- Xn} so that manifest types rooted at X(n+1) are expanded in terms of X(n), avoiding circularities. The strengthenings ensure that Xn.t = X(n-1).t = ... = X2.t = X1.t. N can be chosen arbitrarily; larger values of N result in more recursive definitions being accepted. A good choice appears to be the number of mutually recursive declarations. *) let subst_and_strengthen env s id mty = Mtype.strengthen ~aliasable:false env (Subst.modtype s mty) (Subst.module_path s (Pident id)) in let rec check_incl first_time n env s = if n > 0 then begin Generate fresh names Y_i for the rec . bound module idents let bindings1 = List.map (fun (id, _, _mty_decl, _modl, mty_actual, _attrs, _loc) -> (id, Ident.rename id, mty_actual)) bindings in (* Enter the Y_i in the environment with their actual types substituted by the input substitution s *) let env' = List.fold_left (fun env (id, id', mty_actual) -> let mty_actual' = if first_time then mty_actual else subst_and_strengthen env s id mty_actual in Env.add_module ~arg:false id' mty_actual' env) env bindings1 in (* Build the output substitution Y_i <- X_i *) let s' = List.fold_left (fun s (id, id', _mty_actual) -> Subst.add_module id (Pident id') s) Subst.identity bindings1 in (* Recurse with env' and s' *) check_incl false (n-1) env' s' end else begin (* Base case: check inclusion of s(mty_actual) in s(mty_decl) and insert coercion if needed *) let check_inclusion (id, id_loc, mty_decl, modl, mty_actual, attrs, loc) = let mty_decl' = Subst.modtype s mty_decl.mty_type and mty_actual' = subst_and_strengthen env s id mty_actual in let coercion = try Includemod.modtypes env mty_actual' mty_decl' with Includemod.Error msg -> raise(Error(modl.mod_loc, env, Not_included msg)) in let modl' = { mod_desc = Tmod_constraint(modl, mty_decl.mty_type, Tmodtype_explicit mty_decl, coercion); mod_type = mty_decl.mty_type; mod_env = env; mod_loc = modl.mod_loc; mod_attributes = []; } in { mb_id = id; mb_name = id_loc; mb_expr = modl'; mb_attributes = attrs; mb_loc = loc; } in List.map check_inclusion bindings end in check_incl true (List.length bindings) env Subst.identity (* Helper for unpack *) let rec package_constraints env loc mty constrs = if constrs = [] then mty else let sg = extract_sig env loc mty in let sg' = List.map (function | Sig_type (id, ({type_params=[]} as td), rs) when List.mem_assoc [Ident.name id] constrs -> let ty = List.assoc [Ident.name id] constrs in Sig_type (id, {td with type_manifest = Some ty}, rs) | Sig_module (id, md, rs) -> let rec aux = function | (m :: ((_ :: _) as l), t) :: rest when m = Ident.name id -> (l, t) :: aux rest | _ :: rest -> aux rest | [] -> [] in let md = {md with md_type = package_constraints env loc md.md_type (aux constrs) } in Sig_module (id, md, rs) | item -> item ) sg in Mty_signature sg' let modtype_of_package env loc p nl tl = try match (Env.find_modtype p env).mtd_type with | Some mty when nl <> [] -> package_constraints env loc mty (List.combine (List.map Longident.flatten nl) tl) | _ -> if nl = [] then Mty_ident p else raise(Error(loc, env, Signature_expected)) with Not_found -> let error = Typetexp.Unbound_modtype (Ctype.lid_of_path p) in raise(Typetexp.Error(loc, env, error)) let package_subtype env p1 nl1 tl1 p2 nl2 tl2 = let mkmty p nl tl = let ntl = List.filter (fun (_n,t) -> Ctype.free_variables t = []) (List.combine nl tl) in let (nl, tl) = List.split ntl in modtype_of_package env Location.none p nl tl in let mty1 = mkmty p1 nl1 tl1 and mty2 = mkmty p2 nl2 tl2 in try Includemod.modtypes env mty1 mty2 = Tcoerce_none with Includemod.Error _msg -> false raise(Error(Location.none , env , Not_included msg ) ) let () = Ctype.package_subtype := package_subtype let wrap_constraint env arg mty explicit = let coercion = try Includemod.modtypes env arg.mod_type mty with Includemod.Error msg -> raise(Error(arg.mod_loc, env, Not_included msg)) in { mod_desc = Tmod_constraint(arg, mty, explicit, coercion); mod_type = mty; mod_env = env; mod_attributes = []; mod_loc = arg.mod_loc } (* Type a module value expression *) let rec type_module ?(alias=false) sttn funct_body anchor env smod = match smod.pmod_desc with Pmod_ident lid -> let path = Typetexp.lookup_module ~load:(not alias) env smod.pmod_loc lid.txt in let md = { mod_desc = Tmod_ident (path, lid); mod_type = Mty_alias(Mta_absent, path); mod_env = env; mod_attributes = smod.pmod_attributes; mod_loc = smod.pmod_loc } in let aliasable = not (Env.is_functor_arg path env) in let md = if alias && aliasable then (Env.add_required_global (Path.head path); md) else match (Env.find_module path env).md_type with Mty_alias(_, p1) when not alias -> let p1 = Env.normalize_path (Some smod.pmod_loc) env p1 in let mty = Includemod.expand_module_alias env [] p1 in { md with mod_desc = Tmod_constraint (md, mty, Tmodtype_implicit, Tcoerce_alias (p1, Tcoerce_none)); mod_type = if sttn then Mtype.strengthen ~aliasable:true env mty p1 else mty } | mty -> let mty = if sttn then Mtype.strengthen ~aliasable env mty path else mty in { md with mod_type = mty } in rm md | Pmod_structure sstr -> let (str, sg, _finalenv) = type_structure funct_body anchor env sstr smod.pmod_loc in let md = rm { mod_desc = Tmod_structure str; mod_type = Mty_signature sg; mod_env = env; mod_attributes = smod.pmod_attributes; mod_loc = smod.pmod_loc } in let sg' = simplify_signature sg in if List.length sg' = List.length sg then md else wrap_constraint (Env.implicit_coercion env) md (Mty_signature sg') Tmodtype_implicit | Pmod_functor(name, smty, sbody) -> let mty = may_map (transl_modtype env) smty in let ty_arg = may_map (fun m -> m.mty_type) mty in let (id, newenv), funct_body = match ty_arg with None -> (Ident.create "*", env), false | Some mty -> Env.enter_module ~arg:true name.txt mty env, true in PR#6981 let body = type_module sttn funct_body None newenv sbody in rm { mod_desc = Tmod_functor(id, name, mty, body); mod_type = Mty_functor(id, ty_arg, body.mod_type); mod_env = env; mod_attributes = smod.pmod_attributes; mod_loc = smod.pmod_loc } | Pmod_apply(sfunct, sarg) -> let arg = type_module true funct_body None env sarg in let path = path_of_module arg in let funct = type_module (sttn && path <> None) funct_body None env sfunct in begin match Env.scrape_alias env funct.mod_type with Mty_functor(param, mty_param, mty_res) as mty_functor -> let generative, mty_param = (mty_param = None, Btype.default_mty mty_param) in if generative then begin if sarg.pmod_desc <> Pmod_structure [] then raise (Error (sfunct.pmod_loc, env, Apply_generative)); if funct_body && Mtype.contains_type env funct.mod_type then raise (Error (smod.pmod_loc, env, Not_allowed_in_functor_body)); end; let coercion = try Includemod.modtypes env arg.mod_type mty_param with Includemod.Error msg -> raise(Error(sarg.pmod_loc, env, Not_included msg)) in let mty_appl = match path with Some path -> Subst.modtype (Subst.add_module param path Subst.identity) mty_res | None -> if generative then mty_res else try Mtype.nondep_supertype (Env.add_module ~arg:true param arg.mod_type env) param mty_res with Not_found -> raise(Error(smod.pmod_loc, env, Cannot_eliminate_dependency mty_functor)) in rm { mod_desc = Tmod_apply(funct, arg, coercion); mod_type = mty_appl; mod_env = env; mod_attributes = smod.pmod_attributes; mod_loc = smod.pmod_loc } | Mty_alias(_, path) -> raise(Error(sfunct.pmod_loc, env, Cannot_scrape_alias path)) | _ -> raise(Error(sfunct.pmod_loc, env, Cannot_apply funct.mod_type)) end | Pmod_constraint(sarg, smty) -> let arg = type_module ~alias true funct_body anchor env sarg in let mty = transl_modtype env smty in rm {(wrap_constraint env arg mty.mty_type (Tmodtype_explicit mty)) with mod_loc = smod.pmod_loc; mod_attributes = smod.pmod_attributes; } | Pmod_unpack sexp -> if !Clflags.principal then Ctype.begin_def (); let exp = Typecore.type_exp env sexp in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_structure exp.exp_type end; let mty = match Ctype.expand_head env exp.exp_type with {desc = Tpackage (p, nl, tl)} -> if List.exists (fun t -> Ctype.free_variables t <> []) tl then raise (Error (smod.pmod_loc, env, Incomplete_packed_module exp.exp_type)); if !Clflags.principal && not (Typecore.generalizable (Btype.generic_level-1) exp.exp_type) then Location.prerr_warning smod.pmod_loc (Warnings.Not_principal "this module unpacking"); modtype_of_package env smod.pmod_loc p nl tl | {desc = Tvar _} -> raise (Typecore.Error (smod.pmod_loc, env, Typecore.Cannot_infer_signature)) | _ -> raise (Error(smod.pmod_loc, env, Not_a_packed_module exp.exp_type)) in if funct_body && Mtype.contains_type env mty then raise (Error (smod.pmod_loc, env, Not_allowed_in_functor_body)); rm { mod_desc = Tmod_unpack(exp, mty); mod_type = mty; mod_env = env; mod_attributes = smod.pmod_attributes; mod_loc = smod.pmod_loc } | Pmod_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) and type_structure ?(toplevel = false) funct_body anchor env sstr scope = let names = new_names () in let type_str_item env srem {pstr_loc = loc; pstr_desc = desc} = match desc with | Pstr_eval (sexpr, attrs) -> let expr = Builtin_attributes.with_warning_attribute attrs (fun () -> Typecore.type_expression env sexpr) in Tstr_eval (expr, attrs), [], env | Pstr_value(rec_flag, sdefs) -> let scope = match rec_flag with | Recursive -> Some (Annot.Idef {scope with Location.loc_start = loc.Location.loc_start}) | Nonrecursive -> let start = match srem with | [] -> loc.Location.loc_end | {pstr_loc = loc2} :: _ -> loc2.Location.loc_start in Some (Annot.Idef {scope with Location.loc_start = start}) in let (defs, newenv) = Typecore.type_binding env rec_flag sdefs scope in (* Note: Env.find_value does not trigger the value_used event. Values will be marked as being used during the signature inclusion test. *) Tstr_value(rec_flag, defs), List.map (fun id -> Sig_value(id, Env.find_value (Pident id) newenv)) (let_bound_idents defs), newenv | Pstr_primitive sdesc -> let (desc, newenv) = Typedecl.transl_value_decl env loc sdesc in Tstr_primitive desc, [Sig_value(desc.val_id, desc.val_val)], newenv | Pstr_type (rec_flag, sdecls) -> List.iter (fun decl -> check_name check_type names decl.ptype_name) sdecls; let (decls, newenv) = Typedecl.transl_type_decl env rec_flag sdecls in Tstr_type (rec_flag, decls), map_rec_type_with_row_types ~rec_flag (fun rs info -> Sig_type(info.typ_id, info.typ_type, rs)) decls [], enrich_type_decls anchor decls env newenv | Pstr_typext styext -> List.iter (fun pext -> check_name check_typext names pext.pext_name) styext.ptyext_constructors; let (tyext, newenv) = Typedecl.transl_type_extension true env loc styext in (Tstr_typext tyext, map_ext (fun es ext -> Sig_typext(ext.ext_id, ext.ext_type, es)) tyext.tyext_constructors [], newenv) | Pstr_exception sext -> check_name check_typext names sext.pext_name; let (ext, newenv) = Typedecl.transl_exception env sext in Tstr_exception ext, [Sig_typext(ext.ext_id, ext.ext_type, Text_exception)], newenv | Pstr_module {pmb_name = name; pmb_expr = smodl; pmb_attributes = attrs; pmb_loc; } -> check_name check_module names name; create early for PR#6752 let modl = Builtin_attributes.with_warning_attribute attrs (fun () -> type_module ~alias:true true funct_body (anchor_submodule name.txt anchor) env smodl ) in let md = { md_type = enrich_module_type anchor name.txt modl.mod_type env; md_attributes = attrs; md_loc = pmb_loc; } in let newenv = Env.enter_module_declaration id md env in Tstr_module {mb_id=id; mb_name=name; mb_expr=modl; mb_attributes=attrs; mb_loc=pmb_loc; }, [Sig_module(id, {md_type = modl.mod_type; md_attributes = attrs; md_loc = pmb_loc; }, Trec_not)], newenv | Pstr_recmodule sbind -> let sbind = List.map (function | {pmb_name = name; pmb_expr = {pmod_desc=Pmod_constraint(expr, typ)}; pmb_attributes = attrs; pmb_loc = loc; } -> name, typ, expr, attrs, loc | mb -> raise (Error (mb.pmb_expr.pmod_loc, env, Recursive_module_require_explicit_type)) ) sbind in List.iter (fun (name, _, _, _, _) -> check_name check_module names name) sbind; let (decls, newenv) = transl_recmodule_modtypes env (List.map (fun (name, smty, _smodl, attrs, loc) -> {pmd_name=name; pmd_type=smty; pmd_attributes=attrs; pmd_loc=loc}) sbind ) in let bindings1 = List.map2 (fun {md_id=id; md_type=mty} (name, _, smodl, attrs, loc) -> let modl = Builtin_attributes.with_warning_attribute attrs (fun () -> type_module true funct_body (anchor_recmodule id) newenv smodl ) in let mty' = enrich_module_type anchor (Ident.name id) modl.mod_type newenv in (id, name, mty, modl, mty', attrs, loc)) decls sbind in let newenv = (* allow aliasing recursive modules from outside *) List.fold_left (fun env md -> let mdecl = { md_type = md.md_type.mty_type; md_attributes = md.md_attributes; md_loc = md.md_loc; } in Env.add_module_declaration ~check:true md.md_id mdecl env ) env decls in let bindings2 = check_recmodule_inclusion newenv bindings1 in Tstr_recmodule bindings2, map_rec (fun rs mb -> Sig_module(mb.mb_id, { md_type=mb.mb_expr.mod_type; md_attributes=mb.mb_attributes; md_loc=mb.mb_loc; }, rs)) bindings2 [], newenv | Pstr_modtype pmtd -> (* check that it is non-abstract *) let newenv, mtd, sg = Builtin_attributes.with_warning_attribute pmtd.pmtd_attributes (fun () -> transl_modtype_decl names env pmtd) in Tstr_modtype mtd, [sg], newenv | Pstr_open sod -> let (_path, newenv, od) = type_open ~toplevel env sod in Tstr_open od, [], newenv | Pstr_class cl -> List.iter (fun {pci_name} -> check_name check_type names pci_name) cl; let (classes, new_env) = Typeclass.class_declarations env cl in Tstr_class (List.map (fun cls -> (cls.Typeclass.cls_info, cls.Typeclass.cls_pub_methods)) classes), TODO : check with why this is here Tstr_class_type ( List.map ( fun ( _ , _ , i , d , _ , _ , _ , _ , _ , _ , c ) - > ( i , c ) ) classes ) : : Tstr_type ( List.map ( fun ( _ , _ , _ , _ , i , d , _ , _ , _ , _ , _ ) - > ( i , d ) ) classes ) : : Tstr_type ( List.map ( fun ( _ , _ , _ , _ , _ , _ , i , d , _ , _ , _ ) - > ( i , d ) ) classes ) : : Tstr_class_type (List.map (fun (_,_, i, d, _,_,_,_,_,_,c) -> (i, c)) classes) :: Tstr_type (List.map (fun (_,_,_,_, i, d, _,_,_,_,_) -> (i, d)) classes) :: Tstr_type (List.map (fun (_,_,_,_,_,_, i, d, _,_,_) -> (i, d)) classes) :: *) List.flatten (map_rec (fun rs cls -> let open Typeclass in [Sig_class(cls.cls_id, cls.cls_decl, rs); Sig_class_type(cls.cls_ty_id, cls.cls_ty_decl, rs); Sig_type(cls.cls_obj_id, cls.cls_obj_abbr, rs); Sig_type(cls.cls_typesharp_id, cls.cls_abbr, rs)]) classes []), new_env | Pstr_class_type cl -> List.iter (fun {pci_name} -> check_name check_type names pci_name) cl; let (classes, new_env) = Typeclass.class_type_declarations env cl in Tstr_class_type (List.map (fun cl -> (cl.Typeclass.clsty_ty_id, cl.Typeclass.clsty_id_loc, cl.Typeclass.clsty_info)) classes), TODO : check with why this is here Tstr_type ( List.map ( fun ( _ , _ , i , d , _ , _ ) - > ( i , d ) ) classes ) : : Tstr_type ( List.map ( fun ( _ , _ , _ , _ , i , d ) - > ( i , d ) ) classes ) : : Tstr_type (List.map (fun (_, _, i, d, _, _) -> (i, d)) classes) :: Tstr_type (List.map (fun (_, _, _, _, i, d) -> (i, d)) classes) :: *) List.flatten (map_rec (fun rs decl -> let open Typeclass in [Sig_class_type(decl.clsty_ty_id, decl.clsty_ty_decl, rs); Sig_type(decl.clsty_obj_id, decl.clsty_obj_abbr, rs); Sig_type(decl.clsty_typesharp_id, decl.clsty_abbr, rs)]) classes []), new_env | Pstr_include sincl -> let smodl = sincl.pincl_mod in let modl = Builtin_attributes.with_warning_attribute sincl.pincl_attributes (fun () -> type_module true funct_body None env smodl) in (* Rename all identifiers bound by this signature to avoid clashes *) let sg = Subst.signature Subst.identity (extract_sig_open env smodl.pmod_loc modl.mod_type) in List.iter (check_sig_item names loc) sg; let new_env = Env.add_signature sg env in let incl = { incl_mod = modl; incl_type = sg; incl_attributes = sincl.pincl_attributes; incl_loc = sincl.pincl_loc; } in Tstr_include incl, sg, new_env | Pstr_extension (ext, _attrs) -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) | Pstr_attribute x -> Builtin_attributes.warning_attribute [x]; Tstr_attribute x, [], env in let rec type_struct env sstr = Ctype.init_def(Ident.current_time()); match sstr with | [] -> ([], [], env) | pstr :: srem -> let previous_saved_types = Cmt_format.get_saved_types () in let desc, sg, new_env = type_str_item env srem pstr in let str = { str_desc = desc; str_loc = pstr.pstr_loc; str_env = env } in Cmt_format.set_saved_types (Cmt_format.Partial_structure_item str :: previous_saved_types); let (str_rem, sig_rem, final_env) = type_struct new_env srem in (str :: str_rem, sg @ sig_rem, final_env) in if !Clflags.annotations then (* moved to genannot *) List.iter (function {pstr_loc = l} -> Stypes.record_phrase l) sstr; let previous_saved_types = Cmt_format.get_saved_types () in if not toplevel then Builtin_attributes.warning_enter_scope (); let (items, sg, final_env) = type_struct env sstr in let str = { str_items = items; str_type = sg; str_final_env = final_env } in if not toplevel then Builtin_attributes.warning_leave_scope (); Cmt_format.set_saved_types (Cmt_format.Partial_structure str :: previous_saved_types); str, sg, final_env let type_toplevel_phrase env s = Env.reset_required_globals (); begin let iter = Builtin_attributes.emit_external_warnings in iter.Ast_iterator.structure iter s end; let (str, sg, env) = type_structure ~toplevel:true false None env s Location.none in let (str, _coerce) = ImplementationHooks.apply_hooks { Misc.sourcefile = "//toplevel//" } (str, Tcoerce_none) in (str, sg, env) let type_module_alias = type_module ~alias:true true false None let type_module = type_module true false None let type_structure = type_structure false None (* Normalize types in a signature *) let rec normalize_modtype env = function Mty_ident _ | Mty_alias _ -> () | Mty_signature sg -> normalize_signature env sg | Mty_functor(_id, _param, body) -> normalize_modtype env body and normalize_signature env = List.iter (normalize_signature_item env) and normalize_signature_item env = function Sig_value(_id, desc) -> Ctype.normalize_type env desc.val_type | Sig_module(_id, md, _) -> normalize_modtype env md.md_type | _ -> () (* Extract the module type of a module expression *) let type_module_type_of env smod = let tmty = match smod.pmod_desc with | Pmod_ident lid -> (* turn off strengthening in this case *) let path, md = Typetexp.find_module env smod.pmod_loc lid.txt in rm { mod_desc = Tmod_ident (path, lid); mod_type = md.md_type; mod_env = env; mod_attributes = smod.pmod_attributes; mod_loc = smod.pmod_loc } | _ -> type_module env smod in let mty = tmty.mod_type in (* PR#6307: expand aliases at root and submodules *) let mty = Mtype.remove_aliases env mty in PR#5036 : must not contain non - generalized type variables if not (closed_modtype env mty) then raise(Error(smod.pmod_loc, env, Non_generalizable_module mty)); tmty, mty For let type_package env m p nl = Same as Pexp_letmodule (* remember original level *) let lv = Ctype.get_current_level () in Ctype.begin_def (); Ident.set_current_time lv; let context = Typetexp.narrow () in let modl = type_module env m in Ctype.init_def(Ident.current_time()); Typetexp.widen context; let (mp, env) = match modl.mod_desc with Tmod_ident (mp,_) -> (mp, env) | Tmod_constraint ({mod_desc=Tmod_ident (mp,_)}, _, Tmodtype_implicit, _) -> (mp, env) (* PR#6982 *) | _ -> let (id, new_env) = Env.enter_module ~arg:true "%M" modl.mod_type env in (Pident id, new_env) in let rec mkpath mp = function | Lident name -> Pdot(mp, name, nopos) | Ldot (m, name) -> Pdot(mkpath mp m, name, nopos) | _ -> assert false in let tl' = List.map (fun name -> Btype.newgenty (Tconstr (mkpath mp name,[],ref Mnil))) nl in (* go back to original level *) Ctype.end_def (); if nl = [] then (wrap_constraint env modl (Mty_ident p) Tmodtype_implicit, []) else let mty = modtype_of_package env modl.mod_loc p nl tl' in List.iter2 (fun n ty -> try Ctype.unify env ty (Ctype.newvar ()) with Ctype.Unify _ -> raise (Error(m.pmod_loc, env, Scoping_pack (n,ty)))) nl tl'; (wrap_constraint env modl mty Tmodtype_implicit, tl') (* Fill in the forward declarations *) let () = Typecore.type_module := type_module_alias; Typetexp.transl_modtype_longident := transl_modtype_longident; Typetexp.transl_modtype := transl_modtype; Typecore.type_open := type_open_ ?toplevel:None; Typecore.type_package := type_package; type_module_type_of_fwd := type_module_type_of an implementation file let type_implementation sourcefile outputprefix modulename initial_env ast = Cmt_format.clear (); try Typecore.reset_delayed_checks (); Env.reset_required_globals (); begin let iter = Builtin_attributes.emit_external_warnings in iter.Ast_iterator.structure iter ast end; let (str, sg, finalenv) = type_structure initial_env ast (Location.in_file sourcefile) in let simple_sg = simplify_signature sg in if !Clflags.print_types then begin Printtyp.wrap_printing_env initial_env (fun () -> fprintf std_formatter "%a@." Printtyp.signature simple_sg); (str, Tcoerce_none) (* result is ignored by Compile.implementation *) end else begin let sourceintf = Filename.remove_extension sourcefile ^ !Config.interface_suffix in if Sys.file_exists sourceintf then begin let intf_file = try find_in_path_uncap !Config.load_path (modulename ^ ".cmi") with Not_found -> raise(Error(Location.in_file sourcefile, Env.empty, Interface_not_compiled sourceintf)) in let dclsig = Env.read_signature modulename intf_file in let coercion = Includemod.compunit initial_env sourcefile sg intf_file dclsig in Typecore.force_delayed_checks (); (* It is important to run these checks after the inclusion test above, so that value declarations which are not used internally but exported are not reported as being unused. *) Cmt_format.save_cmt (outputprefix ^ ".cmt") modulename (Cmt_format.Implementation str) (Some sourcefile) initial_env None; (str, coercion) end else begin check_nongen_schemes finalenv sg; normalize_signature finalenv simple_sg; let coercion = Includemod.compunit initial_env sourcefile sg "(inferred signature)" simple_sg in Typecore.force_delayed_checks (); See comment above . Here the target signature contains all the value being exported . We can still capture unused declarations like " let x = true ; ; let x = 1 ; ; " , because in this case , the inferred signature contains only the last declaration . the value being exported. We can still capture unused declarations like "let x = true;; let x = 1;;", because in this case, the inferred signature contains only the last declaration. *) if not !Clflags.dont_write_files then begin let deprecated = Builtin_attributes.deprecated_of_str ast in let sg = Env.save_signature ~deprecated simple_sg modulename (outputprefix ^ ".cmi") in Cmt_format.save_cmt (outputprefix ^ ".cmt") modulename (Cmt_format.Implementation str) (Some sourcefile) initial_env (Some sg); end; (str, coercion) end end with e -> Cmt_format.save_cmt (outputprefix ^ ".cmt") modulename (Cmt_format.Partial_implementation (Array.of_list (Cmt_format.get_saved_types ()))) (Some sourcefile) initial_env None; raise e let type_implementation sourcefile outputprefix modulename initial_env ast = ImplementationHooks.apply_hooks { Misc.sourcefile } (type_implementation sourcefile outputprefix modulename initial_env ast) let save_signature modname tsg outputprefix source_file initial_env cmi = Cmt_format.save_cmt (outputprefix ^ ".cmti") modname (Cmt_format.Interface tsg) (Some source_file) initial_env (Some cmi) let type_interface sourcefile env ast = begin let iter = Builtin_attributes.emit_external_warnings in iter.Ast_iterator.signature iter ast end; InterfaceHooks.apply_hooks { Misc.sourcefile } (transl_signature env ast) " Packaging " of several compilation units into one unit having them as sub - modules . having them as sub-modules. *) let rec package_signatures subst = function [] -> [] | (name, sg) :: rem -> let sg' = Subst.signature subst sg in let oldid = Ident.create_persistent name and newid = Ident.create name in Sig_module(newid, {md_type=Mty_signature sg'; md_attributes=[]; md_loc=Location.none; }, Trec_not) :: package_signatures (Subst.add_module oldid (Pident newid) subst) rem let package_units initial_env objfiles cmifile modulename = (* Read the signatures of the units *) let units = List.map (fun f -> let pref = chop_extensions f in let modname = String.capitalize_ascii(Filename.basename pref) in let sg = Env.read_signature modname (pref ^ ".cmi") in if Filename.check_suffix f ".cmi" && not(Mtype.no_code_needed_sig Env.initial_safe_string sg) then raise(Error(Location.none, Env.empty, Implementation_is_required f)); (modname, Env.read_signature modname (pref ^ ".cmi"))) objfiles in (* Compute signature of packaged unit *) Ident.reinit(); let sg = package_signatures Subst.identity units in (* See if explicit interface is provided *) let prefix = Filename.remove_extension cmifile in let mlifile = prefix ^ !Config.interface_suffix in if Sys.file_exists mlifile then begin if not (Sys.file_exists cmifile) then begin raise(Error(Location.in_file mlifile, Env.empty, Interface_not_compiled mlifile)) end; let dclsig = Env.read_signature modulename cmifile in Cmt_format.save_cmt (prefix ^ ".cmt") modulename (Cmt_format.Packed (sg, objfiles)) None initial_env None ; Includemod.compunit initial_env "(obtained by packing)" sg mlifile dclsig end else begin (* Determine imports *) let unit_names = List.map fst units in let imports = List.filter (fun (name, _crc) -> not (List.mem name unit_names)) (Env.imports()) in (* Write packaged signature *) if not !Clflags.dont_write_files then begin let sg = Env.save_signature_with_imports ~deprecated:None sg modulename (prefix ^ ".cmi") imports in Cmt_format.save_cmt (prefix ^ ".cmt") modulename (Cmt_format.Packed (sg, objfiles)) None initial_env (Some sg) end; Tcoerce_none end (* Error report *) open Printtyp let report_error ppf = function Cannot_apply mty -> fprintf ppf "@[This module is not a functor; it has type@ %a@]" modtype mty | Not_included errs -> fprintf ppf "@[<v>Signature mismatch:@ %a@]" Includemod.report_error errs | Cannot_eliminate_dependency mty -> fprintf ppf "@[This functor has type@ %a@ \ The parameter cannot be eliminated in the result type.@ \ Please bind the argument to a module identifier.@]" modtype mty | Signature_expected -> fprintf ppf "This module type is not a signature" | Structure_expected mty -> fprintf ppf "@[This module is not a structure; it has type@ %a" modtype mty | With_no_component lid -> fprintf ppf "@[The signature constrained by `with' has no component named %a@]" longident lid | With_mismatch(lid, explanation) -> fprintf ppf "@[<v>\ @[In this `with' constraint, the new definition of %a@ \ does not match its original definition@ \ in the constrained signature:@]@ \ %a@]" longident lid Includemod.report_error explanation | Repeated_name(kind, name) -> fprintf ppf "@[Multiple definition of the %s name %s.@ \ Names must be unique in a given structure or signature.@]" kind name | Non_generalizable typ -> fprintf ppf "@[The type of this expression,@ %a,@ \ contains type variables that cannot be generalized@]" type_scheme typ | Non_generalizable_class (id, desc) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains type variables that cannot be generalized@]" (class_declaration id) desc | Non_generalizable_module mty -> fprintf ppf "@[The type of this module,@ %a,@ \ contains type variables that cannot be generalized@]" modtype mty | Implementation_is_required intf_name -> fprintf ppf "@[The interface %a@ declares values, not just types.@ \ An implementation must be provided.@]" Location.print_filename intf_name | Interface_not_compiled intf_name -> fprintf ppf "@[Could not find the .cmi file for interface@ %a.@]" Location.print_filename intf_name | Not_allowed_in_functor_body -> fprintf ppf "@[This expression creates fresh types.@ %s@]" "It is not allowed inside applicative functors." | With_need_typeconstr -> fprintf ppf "Only type constructors with identical parameters can be substituted." | Not_a_packed_module ty -> fprintf ppf "This expression is not a packed module. It has type@ %a" type_expr ty | Incomplete_packed_module ty -> fprintf ppf "The type of this packed module contains variables:@ %a" type_expr ty | Scoping_pack (lid, ty) -> fprintf ppf "The type %a in this module cannot be exported.@ " longident lid; fprintf ppf "Its type contains local dependencies:@ %a" type_expr ty | Recursive_module_require_explicit_type -> fprintf ppf "Recursive modules require an explicit module type." | Apply_generative -> fprintf ppf "This is a generative functor. It can only be applied to ()" | Cannot_scrape_alias p -> fprintf ppf "This is an alias for module %a, which is missing" path p let report_error env ppf err = Printtyp.wrap_printing_env env (fun () -> report_error ppf err) let () = Location.register_error_of_exn (function | Error (loc, env, err) -> Some (Location.error_of_printer loc (report_error env) err) | Error_forward err -> Some err | _ -> None )
null
https://raw.githubusercontent.com/yurug/ocaml4.04.0-copatterns/b3ec6a3cc203bd2cde3b618546d29e10f1102323/typing/typemod.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. ************************************************************************ Extract a signature from a module type Compute the environment after opening a module Record a module type Forward declaration, to be filled in by type_module_type_of Merge one "with" constraint in a signature Check as for a normal with constraint, but discard definition Add recursion flags on declarations arising from a mutually recursive block. Add type extension flags to extension contructors Additional validity checks on type definitions arising from recursive modules Simplify multiple specifications of a value or an extension in a signature. (Other signature components, e.g. types, modules, etc, are checked for name uniqueness.) If multiple specifications with the same name, keep only the last (rightmost) one. Check and translate a module type expression PR#6513 Try to convert a module expression to a module path. Check that all core type schemes in a structure are closed Helpers for typing recursive modules Enter the Y_i in the environment with their actual types substituted by the input substitution s Build the output substitution Y_i <- X_i Recurse with env' and s' Base case: check inclusion of s(mty_actual) in s(mty_decl) and insert coercion if needed Helper for unpack Type a module value expression Note: Env.find_value does not trigger the value_used event. Values will be marked as being used during the signature inclusion test. allow aliasing recursive modules from outside check that it is non-abstract Rename all identifiers bound by this signature to avoid clashes moved to genannot Normalize types in a signature Extract the module type of a module expression turn off strengthening in this case PR#6307: expand aliases at root and submodules remember original level PR#6982 go back to original level Fill in the forward declarations result is ignored by Compile.implementation It is important to run these checks after the inclusion test above, so that value declarations which are not used internally but exported are not reported as being unused. Read the signatures of the units Compute signature of packaged unit See if explicit interface is provided Determine imports Write packaged signature Error report
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Misc open Longident open Path open Asttypes open Parsetree open Types open Format type error = Cannot_apply of module_type | Not_included of Includemod.error list | Cannot_eliminate_dependency of module_type | Signature_expected | Structure_expected of module_type | With_no_component of Longident.t | With_mismatch of Longident.t * Includemod.error list | Repeated_name of string * string | Non_generalizable of type_expr | Non_generalizable_class of Ident.t * class_declaration | Non_generalizable_module of module_type | Implementation_is_required of string | Interface_not_compiled of string | Not_allowed_in_functor_body | With_need_typeconstr | Not_a_packed_module of type_expr | Incomplete_packed_module of type_expr | Scoping_pack of Longident.t * type_expr | Recursive_module_require_explicit_type | Apply_generative | Cannot_scrape_alias of Path.t exception Error of Location.t * Env.t * error exception Error_forward of Location.error module ImplementationHooks = Misc.MakeHooks(struct type t = Typedtree.structure * Typedtree.module_coercion end) module InterfaceHooks = Misc.MakeHooks(struct type t = Typedtree.signature end) open Typedtree let fst3 (x,_,_) = x let rec path_concat head p = match p with Pident tail -> Pdot (Pident head, Ident.name tail, 0) | Pdot (pre, s, pos) -> Pdot (path_concat head pre, s, pos) | Papply _ -> assert false let extract_sig env loc mty = match Env.scrape_alias env mty with Mty_signature sg -> sg | Mty_alias(_, path) -> raise(Error(loc, env, Cannot_scrape_alias path)) | _ -> raise(Error(loc, env, Signature_expected)) let extract_sig_open env loc mty = match Env.scrape_alias env mty with Mty_signature sg -> sg | Mty_alias(_, path) -> raise(Error(loc, env, Cannot_scrape_alias path)) | _ -> raise(Error(loc, env, Structure_expected mty)) let type_open_ ?toplevel ovf env loc lid = let path, md = Typetexp.find_module env lid.loc lid.txt in let sg = extract_sig_open env lid.loc md.md_type in path, Env.open_signature ~loc ?toplevel ovf path sg env let type_open ?toplevel env sod = let (path, newenv) = type_open_ ?toplevel sod.popen_override env sod.popen_loc sod.popen_lid in let od = { open_override = sod.popen_override; open_path = path; open_txt = sod.popen_lid; open_attributes = sod.popen_attributes; open_loc = sod.popen_loc; } in (path, newenv, od) let rm node = Stypes.record (Stypes.Ti_mod node); node let type_module_type_of_fwd : (Env.t -> Parsetree.module_expr -> Typedtree.module_expr * Types.module_type) ref = ref (fun _env _m -> assert false) let rec add_rec_types env = function Sig_type(id, decl, Trec_next) :: rem -> add_rec_types (Env.add_type ~check:true id decl env) rem | _ -> env let check_type_decl env loc id row_id newdecl decl rs rem = let env = Env.add_type ~check:true id newdecl env in let env = match row_id with | None -> env | Some id -> Env.add_type ~check:true id newdecl env in let env = if rs = Trec_not then env else add_rec_types env rem in Includemod.type_declarations env id newdecl decl; Typedecl.check_coherence env loc id newdecl let update_rec_next rs rem = match rs with Trec_next -> rem | Trec_first | Trec_not -> match rem with Sig_type (id, decl, Trec_next) :: rem -> Sig_type (id, decl, rs) :: rem | Sig_module (id, mty, Trec_next) :: rem -> Sig_module (id, mty, rs) :: rem | _ -> rem let make p n i = let open Variance in set May_pos p (set May_neg n (set May_weak n (set Inj i null))) let merge_constraint initial_env loc sg constr = let lid = match constr with | Pwith_type (lid, _) | Pwith_module (lid, _) -> lid | Pwith_typesubst {ptype_name=s} | Pwith_modsubst (s, _) -> {loc = s.loc; txt=Lident s.txt} in let real_id = ref None in let rec merge env sg namelist row_id = match (sg, namelist, constr) with ([], _, _) -> raise(Error(loc, env, With_no_component lid.txt)) | (Sig_type(id, decl, rs) :: rem, [s], Pwith_type (_, ({ptype_kind = Ptype_abstract} as sdecl))) when Ident.name id = s && Typedecl.is_fixed_type sdecl -> let decl_row = { type_params = List.map (fun _ -> Btype.newgenvar()) sdecl.ptype_params; type_arity = List.length sdecl.ptype_params; type_kind = Type_abstract; type_private = Private; type_manifest = None; type_variance = List.map (fun (_, v) -> let (c, n) = match v with | Covariant -> true, false | Contravariant -> false, true | Invariant -> false, false in make (not n) (not c) false ) sdecl.ptype_params; type_loc = sdecl.ptype_loc; type_newtype_level = None; type_attributes = []; type_immediate = false; type_unboxed = unboxed_false_default_false; } and id_row = Ident.create (s^"#row") in let initial_env = Env.add_type ~check:true id_row decl_row initial_env in let tdecl = Typedecl.transl_with_constraint initial_env id (Some(Pident id_row)) decl sdecl in let newdecl = tdecl.typ_type in check_type_decl env sdecl.ptype_loc id row_id newdecl decl rs rem; let decl_row = {decl_row with type_params = newdecl.type_params} in let rs' = if rs = Trec_first then Trec_not else rs in (Pident id, lid, Twith_type tdecl), Sig_type(id_row, decl_row, rs') :: Sig_type(id, newdecl, rs) :: rem | (Sig_type(id, decl, rs) :: rem , [s], Pwith_type (_, sdecl)) when Ident.name id = s -> let tdecl = Typedecl.transl_with_constraint initial_env id None decl sdecl in let newdecl = tdecl.typ_type in check_type_decl env sdecl.ptype_loc id row_id newdecl decl rs rem; (Pident id, lid, Twith_type tdecl), Sig_type(id, newdecl, rs) :: rem | (Sig_type(id, _, _) :: rem, [s], (Pwith_type _ | Pwith_typesubst _)) when Ident.name id = s ^ "#row" -> merge env rem namelist (Some id) | (Sig_type(id, decl, rs) :: rem, [s], Pwith_typesubst sdecl) when Ident.name id = s -> let tdecl = Typedecl.transl_with_constraint initial_env id None decl sdecl in let newdecl = tdecl.typ_type in check_type_decl env sdecl.ptype_loc id row_id newdecl decl rs rem; real_id := Some id; (Pident id, lid, Twith_typesubst tdecl), update_rec_next rs rem | (Sig_module(id, md, rs) :: rem, [s], Pwith_module (_, lid')) when Ident.name id = s -> let path, md' = Typetexp.find_module initial_env loc lid'.txt in let md'' = {md' with md_type = Mtype.remove_aliases env md'.md_type} in let newmd = Mtype.strengthen_decl ~aliasable:false env md'' path in ignore(Includemod.modtypes env newmd.md_type md.md_type); (Pident id, lid, Twith_module (path, lid')), Sig_module(id, newmd, rs) :: rem | (Sig_module(id, md, rs) :: rem, [s], Pwith_modsubst (_, lid')) when Ident.name id = s -> let path, md' = Typetexp.find_module initial_env loc lid'.txt in let newmd = Mtype.strengthen_decl ~aliasable:false env md' path in ignore(Includemod.modtypes env newmd.md_type md.md_type); real_id := Some id; (Pident id, lid, Twith_modsubst (path, lid')), update_rec_next rs rem | (Sig_module(id, md, rs) :: rem, s :: namelist, _) when Ident.name id = s -> let ((path, _path_loc, tcstr), newsg) = merge env (extract_sig env loc md.md_type) namelist None in (path_concat id path, lid, tcstr), Sig_module(id, {md with md_type=Mty_signature newsg}, rs) :: rem | (item :: rem, _, _) -> let (cstr, items) = merge (Env.add_item item env) rem namelist row_id in cstr, item :: items in try let names = Longident.flatten lid.txt in let (tcstr, sg) = merge initial_env sg names None in let sg = match names, constr with [_], Pwith_typesubst sdecl -> let id = match !real_id with None -> assert false | Some id -> id in let lid = try match sdecl.ptype_manifest with | Some {ptyp_desc = Ptyp_constr (lid, stl)} when List.length stl = List.length sdecl.ptype_params -> List.iter2 (fun x (y, _) -> match x, y with {ptyp_desc=Ptyp_var sx}, {ptyp_desc=Ptyp_var sy} when sx = sy -> () | _, _ -> raise Exit) stl sdecl.ptype_params; lid | _ -> raise Exit with Exit -> raise(Error(sdecl.ptype_loc, initial_env, With_need_typeconstr)) in let path = try Env.lookup_type lid.txt initial_env with Not_found -> assert false in let sub = Subst.add_type id path Subst.identity in Subst.signature sub sg | [_], Pwith_modsubst (_, lid) -> let id = match !real_id with None -> assert false | Some id -> id in let path = Typetexp.lookup_module initial_env loc lid.txt in let sub = Subst.add_module id path Subst.identity in Subst.signature sub sg | _ -> sg in (tcstr, sg) with Includemod.Error explanation -> raise(Error(loc, initial_env, With_mismatch(lid.txt, explanation))) let map_rec fn decls rem = match decls with | [] -> rem | d1 :: dl -> fn Trec_first d1 :: map_end (fn Trec_next) dl rem let map_rec_type ~rec_flag fn decls rem = match decls with | [] -> rem | d1 :: dl -> let first = match rec_flag with | Recursive -> Trec_first | Nonrecursive -> Trec_not in fn first d1 :: map_end (fn Trec_next) dl rem let rec map_rec_type_with_row_types ~rec_flag fn decls rem = match decls with | [] -> rem | d1 :: dl -> if Btype.is_row_name (Ident.name d1.typ_id) then fn Trec_not d1 :: map_rec_type_with_row_types ~rec_flag fn dl rem else map_rec_type ~rec_flag fn decls rem let map_ext fn exts rem = match exts with | [] -> rem | d1 :: dl -> fn Text_first d1 :: map_end (fn Text_next) dl rem Auxiliary for translating recursively - defined module types . Return a module type that approximates the shape of the given module type AST . Retain only module , type , and module type components of signatures . For types , retain only their arity , making them abstract otherwise . Return a module type that approximates the shape of the given module type AST. Retain only module, type, and module type components of signatures. For types, retain only their arity, making them abstract otherwise. *) let rec approx_modtype env smty = match smty.pmty_desc with Pmty_ident lid -> let (path, _info) = Typetexp.find_modtype env smty.pmty_loc lid.txt in Mty_ident path | Pmty_alias lid -> let path = Typetexp.lookup_module env smty.pmty_loc lid.txt in Mty_alias(Mta_absent, path) | Pmty_signature ssg -> Mty_signature(approx_sig env ssg) | Pmty_functor(param, sarg, sres) -> let arg = may_map (approx_modtype env) sarg in let (id, newenv) = Env.enter_module ~arg:true param.txt (Btype.default_mty arg) env in let res = approx_modtype newenv sres in Mty_functor(id, arg, res) | Pmty_with(sbody, _constraints) -> approx_modtype env sbody | Pmty_typeof smod -> let (_, mty) = !type_module_type_of_fwd env smod in mty | Pmty_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) and approx_module_declaration env pmd = { Types.md_type = approx_modtype env pmd.pmd_type; md_attributes = pmd.pmd_attributes; md_loc = pmd.pmd_loc; } and approx_sig env ssg = match ssg with [] -> [] | item :: srem -> match item.psig_desc with | Psig_type (rec_flag, sdecls) -> let decls = Typedecl.approx_type_decl sdecls in let rem = approx_sig env srem in map_rec_type ~rec_flag (fun rs (id, info) -> Sig_type(id, info, rs)) decls rem | Psig_module pmd -> let id = Ident.create pmd.pmd_name.txt in let md = approx_module_declaration env pmd in let newenv = Env.enter_module_declaration id md env in Sig_module(id, md, Trec_not) :: approx_sig newenv srem | Psig_recmodule sdecls -> let decls = List.map (fun pmd -> (Ident.create pmd.pmd_name.txt, approx_module_declaration env pmd) ) sdecls in let newenv = List.fold_left (fun env (id, md) -> Env.add_module_declaration ~check:false id md env) env decls in map_rec (fun rs (id, md) -> Sig_module(id, md, rs)) decls (approx_sig newenv srem) | Psig_modtype d -> let info = approx_modtype_info env d in let (id, newenv) = Env.enter_modtype d.pmtd_name.txt info env in Sig_modtype(id, info) :: approx_sig newenv srem | Psig_open sod -> let (_path, mty, _od) = type_open env sod in approx_sig mty srem | Psig_include sincl -> let smty = sincl.pincl_mod in let mty = approx_modtype env smty in let sg = Subst.signature Subst.identity (extract_sig env smty.pmty_loc mty) in let newenv = Env.add_signature sg env in sg @ approx_sig newenv srem | Psig_class sdecls | Psig_class_type sdecls -> let decls = Typeclass.approx_class_declarations env sdecls in let rem = approx_sig env srem in List.flatten (map_rec (fun rs decl -> let open Typeclass in [Sig_class_type(decl.clsty_ty_id, decl.clsty_ty_decl, rs); Sig_type(decl.clsty_obj_id, decl.clsty_obj_abbr, rs); Sig_type(decl.clsty_typesharp_id, decl.clsty_abbr, rs)]) decls [rem]) | _ -> approx_sig env srem and approx_modtype_info env sinfo = { mtd_type = may_map (approx_modtype env) sinfo.pmtd_type; mtd_attributes = sinfo.pmtd_attributes; mtd_loc = sinfo.pmtd_loc; } let check_recmod_typedecls env sdecls decls = let recmod_ids = List.map fst3 decls in List.iter2 (fun pmd (id, _, mty) -> let mty = mty.mty_type in List.iter (fun path -> Typedecl.check_recmod_typedecl env pmd.pmd_type.pmty_loc recmod_ids path (Env.find_type path env)) (Mtype.type_paths env (Pident id) mty)) sdecls decls Auxiliaries for checking uniqueness of names in signatures and structures module StringSet = Set.Make(struct type t = string let compare (x:t) y = String.compare x y end) let check cl loc set_ref name = if StringSet.mem name !set_ref then raise(Error(loc, Env.empty, Repeated_name(cl, name))) else set_ref := StringSet.add name !set_ref type names = { types: StringSet.t ref; modules: StringSet.t ref; modtypes: StringSet.t ref; typexts: StringSet.t ref; } let new_names () = { types = ref StringSet.empty; modules = ref StringSet.empty; modtypes = ref StringSet.empty; typexts = ref StringSet.empty; } let check_name check names name = check names name.loc name.txt let check_type names loc s = check "type" loc names.types s let check_module names loc s = check "module" loc names.modules s let check_modtype names loc s = check "module type" loc names.modtypes s let check_typext names loc s = check "extension constructor" loc names.typexts s let check_sig_item names loc = function | Sig_type(id, _, _) -> check_type names loc (Ident.name id) | Sig_module(id, _, _) -> check_module names loc (Ident.name id) | Sig_modtype(id, _) -> check_modtype names loc (Ident.name id) | Sig_typext(id, _, _) -> check_typext names loc (Ident.name id) | _ -> () let simplify_signature sg = let rec aux = function | [] -> [], StringSet.empty | (Sig_value(id, _descr) as component) :: sg -> let (sg, val_names) as k = aux sg in let name = Ident.name id in if StringSet.mem name val_names then k else (component :: sg, StringSet.add name val_names) | component :: sg -> let (sg, val_names) = aux sg in (component :: sg, val_names) in let (sg, _) = aux sg in sg let transl_modtype_longident loc env lid = let (path, _info) = Typetexp.find_modtype env loc lid in path let transl_module_alias loc env lid = Typetexp.lookup_module env loc lid let mkmty desc typ env loc attrs = let mty = { mty_desc = desc; mty_type = typ; mty_loc = loc; mty_env = env; mty_attributes = attrs; } in Cmt_format.add_saved_type (Cmt_format.Partial_module_type mty); mty let mksig desc env loc = let sg = { sig_desc = desc; sig_loc = loc; sig_env = env } in Cmt_format.add_saved_type (Cmt_format.Partial_signature_item sg); sg let signature sg = List.map ( fun item - > item.sig_type ) sg let rec transl_modtype env smty = let loc = smty.pmty_loc in match smty.pmty_desc with Pmty_ident lid -> let path = transl_modtype_longident loc env lid.txt in mkmty (Tmty_ident (path, lid)) (Mty_ident path) env loc smty.pmty_attributes | Pmty_alias lid -> let path = transl_module_alias loc env lid.txt in mkmty (Tmty_alias (path, lid)) (Mty_alias(Mta_absent, path)) env loc smty.pmty_attributes | Pmty_signature ssg -> let sg = transl_signature env ssg in mkmty (Tmty_signature sg) (Mty_signature sg.sig_type) env loc smty.pmty_attributes | Pmty_functor(param, sarg, sres) -> let arg = Misc.may_map (transl_modtype env) sarg in let ty_arg = Misc.may_map (fun m -> m.mty_type) arg in let (id, newenv) = Env.enter_module ~arg:true param.txt (Btype.default_mty ty_arg) env in let res = transl_modtype newenv sres in mkmty (Tmty_functor (id, param, arg, res)) (Mty_functor(id, ty_arg, res.mty_type)) env loc smty.pmty_attributes | Pmty_with(sbody, constraints) -> let body = transl_modtype env sbody in let init_sg = extract_sig env sbody.pmty_loc body.mty_type in let (rev_tcstrs, final_sg) = List.fold_left (fun (rev_tcstrs,sg) sdecl -> let (tcstr, sg) = merge_constraint env smty.pmty_loc sg sdecl in (tcstr :: rev_tcstrs, sg) ) ([],init_sg) constraints in mkmty (Tmty_with ( body, List.rev rev_tcstrs)) (Mtype.freshen (Mty_signature final_sg)) env loc smty.pmty_attributes | Pmty_typeof smod -> let env = Env.in_signature false env in let tmty, mty = !type_module_type_of_fwd env smod in mkmty (Tmty_typeof tmty) mty env loc smty.pmty_attributes | Pmty_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) and transl_signature env sg = let names = new_names () in let rec transl_sig env sg = Ctype.init_def(Ident.current_time()); match sg with [] -> [], [], env | item :: srem -> let loc = item.psig_loc in match item.psig_desc with | Psig_value sdesc -> let (tdesc, newenv) = Builtin_attributes.with_warning_attribute sdesc.pval_attributes (fun () -> Typedecl.transl_value_decl env item.psig_loc sdesc) in let (trem,rem, final_env) = transl_sig newenv srem in mksig (Tsig_value tdesc) env loc :: trem, Sig_value(tdesc.val_id, tdesc.val_val) :: rem, final_env | Psig_type (rec_flag, sdecls) -> List.iter (fun decl -> check_name check_type names decl.ptype_name) sdecls; let (decls, newenv) = Typedecl.transl_type_decl env rec_flag sdecls in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_type (rec_flag, decls)) env loc :: trem, map_rec_type_with_row_types ~rec_flag (fun rs td -> Sig_type(td.typ_id, td.typ_type, rs)) decls rem, final_env | Psig_typext styext -> List.iter (fun pext -> check_name check_typext names pext.pext_name) styext.ptyext_constructors; let (tyext, newenv) = Typedecl.transl_type_extension false env item.psig_loc styext in let (trem, rem, final_env) = transl_sig newenv srem in let constructors = tyext.tyext_constructors in mksig (Tsig_typext tyext) env loc :: trem, map_ext (fun es ext -> Sig_typext(ext.ext_id, ext.ext_type, es)) constructors rem, final_env | Psig_exception sext -> check_name check_typext names sext.pext_name; let (ext, newenv) = Typedecl.transl_exception env sext in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_exception ext) env loc :: trem, Sig_typext(ext.ext_id, ext.ext_type, Text_exception) :: rem, final_env | Psig_module pmd -> check_name check_module names pmd.pmd_name; let id = Ident.create pmd.pmd_name.txt in let tmty = Builtin_attributes.with_warning_attribute pmd.pmd_attributes (fun () -> transl_modtype env pmd.pmd_type) in let md = { md_type=tmty.mty_type; md_attributes=pmd.pmd_attributes; md_loc=pmd.pmd_loc; } in let newenv = Env.enter_module_declaration id md env in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_module {md_id=id; md_name=pmd.pmd_name; md_type=tmty; md_loc=pmd.pmd_loc; md_attributes=pmd.pmd_attributes}) env loc :: trem, Sig_module(id, md, Trec_not) :: rem, final_env | Psig_recmodule sdecls -> List.iter (fun pmd -> check_name check_module names pmd.pmd_name) sdecls; let (decls, newenv) = transl_recmodule_modtypes env sdecls in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_recmodule decls) env loc :: trem, map_rec (fun rs md -> let d = {Types.md_type = md.md_type.mty_type; md_attributes = md.md_attributes; md_loc = md.md_loc; } in Sig_module(md.md_id, d, rs)) decls rem, final_env | Psig_modtype pmtd -> let newenv, mtd, sg = Builtin_attributes.with_warning_attribute pmtd.pmtd_attributes (fun () -> transl_modtype_decl names env pmtd) in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_modtype mtd) env loc :: trem, sg :: rem, final_env | Psig_open sod -> let (_path, newenv, od) = type_open env sod in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_open od) env loc :: trem, rem, final_env | Psig_include sincl -> let smty = sincl.pincl_mod in let tmty = Builtin_attributes.with_warning_attribute sincl.pincl_attributes (fun () -> transl_modtype env smty) in let mty = tmty.mty_type in let sg = Subst.signature Subst.identity (extract_sig env smty.pmty_loc mty) in List.iter (check_sig_item names item.psig_loc) sg; let newenv = Env.add_signature sg env in let incl = { incl_mod = tmty; incl_type = sg; incl_attributes = sincl.pincl_attributes; incl_loc = sincl.pincl_loc; } in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_include incl) env loc :: trem, sg @ rem, final_env | Psig_class cl -> List.iter (fun {pci_name} -> check_name check_type names pci_name) cl; let (classes, newenv) = Typeclass.class_descriptions env cl in let (trem, rem, final_env) = transl_sig newenv srem in mksig (Tsig_class (List.map (fun decr -> decr.Typeclass.cls_info) classes)) env loc :: trem, List.flatten (map_rec (fun rs cls -> let open Typeclass in [Sig_class(cls.cls_id, cls.cls_decl, rs); Sig_class_type(cls.cls_ty_id, cls.cls_ty_decl, rs); Sig_type(cls.cls_obj_id, cls.cls_obj_abbr, rs); Sig_type(cls.cls_typesharp_id, cls.cls_abbr, rs)]) classes [rem]), final_env | Psig_class_type cl -> List.iter (fun {pci_name} -> check_name check_type names pci_name) cl; let (classes, newenv) = Typeclass.class_type_declarations env cl in let (trem,rem, final_env) = transl_sig newenv srem in mksig (Tsig_class_type (List.map (fun decl -> decl.Typeclass.clsty_info) classes)) env loc :: trem, List.flatten (map_rec (fun rs decl -> let open Typeclass in [Sig_class_type(decl.clsty_ty_id, decl.clsty_ty_decl, rs); Sig_type(decl.clsty_obj_id, decl.clsty_obj_abbr, rs); Sig_type(decl.clsty_typesharp_id, decl.clsty_abbr, rs)]) classes [rem]), final_env | Psig_attribute x -> Builtin_attributes.warning_attribute [x]; let (trem,rem, final_env) = transl_sig env srem in mksig (Tsig_attribute x) env loc :: trem, rem, final_env | Psig_extension (ext, _attrs) -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) in let previous_saved_types = Cmt_format.get_saved_types () in Builtin_attributes.warning_enter_scope (); let (trem, rem, final_env) = transl_sig (Env.in_signature true env) sg in let rem = simplify_signature rem in let sg = { sig_items = trem; sig_type = rem; sig_final_env = final_env } in Builtin_attributes.warning_leave_scope (); Cmt_format.set_saved_types ((Cmt_format.Partial_signature sg) :: previous_saved_types); sg and transl_modtype_decl names env {pmtd_name; pmtd_type; pmtd_attributes; pmtd_loc} = check_name check_modtype names pmtd_name; let tmty = Misc.may_map (transl_modtype env) pmtd_type in let decl = { Types.mtd_type=may_map (fun t -> t.mty_type) tmty; mtd_attributes=pmtd_attributes; mtd_loc=pmtd_loc; } in let (id, newenv) = Env.enter_modtype pmtd_name.txt decl env in let mtd = { mtd_id=id; mtd_name=pmtd_name; mtd_type=tmty; mtd_attributes=pmtd_attributes; mtd_loc=pmtd_loc; } in newenv, mtd, Sig_modtype(id, decl) and transl_recmodule_modtypes env sdecls = let make_env curr = List.fold_left (fun env (id, _, mty) -> Env.add_module ~arg:true id mty env) env curr in let make_env2 curr = List.fold_left (fun env (id, _, mty) -> Env.add_module ~arg:true id mty.mty_type env) env curr in let transition env_c curr = List.map2 (fun pmd (id, id_loc, _mty) -> let tmty = Builtin_attributes.with_warning_attribute pmd.pmd_attributes (fun () -> transl_modtype env_c pmd.pmd_type) in (id, id_loc, tmty)) sdecls curr in let ids = List.map (fun x -> Ident.create x.pmd_name.txt) sdecls in let approx_env = cf # 5965 We use a dummy module type in order to detect a reference to one of the module being defined during the call to approx_modtype . It will be detected in Env.lookup_module . cf #5965 We use a dummy module type in order to detect a reference to one of the module being defined during the call to approx_modtype. It will be detected in Env.lookup_module. *) List.fold_left (fun env id -> let dummy = Mty_ident (Path.Pident (Ident.create "#recmod#")) in Env.add_module ~arg:true id dummy env ) env ids in PR#7082 let init = List.map2 (fun id pmd -> (id, pmd.pmd_name, approx_modtype approx_env pmd.pmd_type)) ids sdecls in let env0 = make_env init in let dcl1 = transition env0 init in let env1 = make_env2 dcl1 in check_recmod_typedecls env1 sdecls dcl1; let dcl2 = transition env1 dcl1 in List.iter ( fun ( i d , mty ) - > " % a : % a@. " Printtyp.ident i d Printtyp.modtype mty ) dcl2 ; List.iter (fun (id, mty) -> Format.printf "%a: %a@." Printtyp.ident id Printtyp.modtype mty) dcl2; *) let env2 = make_env2 dcl2 in check_recmod_typedecls env2 sdecls dcl2; let dcl2 = List.map2 (fun pmd (id, id_loc, mty) -> {md_id=id; md_name=id_loc; md_type=mty; md_loc=pmd.pmd_loc; md_attributes=pmd.pmd_attributes}) sdecls dcl2 in (dcl2, env2) exception Not_a_path let rec path_of_module mexp = match mexp.mod_desc with Tmod_ident (p,_) -> p | Tmod_apply(funct, arg, _coercion) when !Clflags.applicative_functors -> Papply(path_of_module funct, path_of_module arg) | Tmod_constraint (mexp, _, _, _) -> path_of_module mexp | _ -> raise Not_a_path let path_of_module mexp = try Some (path_of_module mexp) with Not_a_path -> None let rec closed_modtype env = function Mty_ident _ -> true | Mty_alias _ -> true | Mty_signature sg -> let env = Env.add_signature sg env in List.for_all (closed_signature_item env) sg | Mty_functor(id, param, body) -> let env = Env.add_module ~arg:true id (Btype.default_mty param) env in closed_modtype env body and closed_signature_item env = function Sig_value(_id, desc) -> Ctype.closed_schema env desc.val_type | Sig_module(_id, md, _) -> closed_modtype env md.md_type | _ -> true let check_nongen_scheme env sig_item = match sig_item with Sig_value(_id, vd) -> if not (Ctype.closed_schema env vd.val_type) then raise (Error (vd.val_loc, env, Non_generalizable vd.val_type)) | Sig_module (_id, md, _) -> if not (closed_modtype env md.md_type) then raise(Error(md.md_loc, env, Non_generalizable_module md.md_type)) | _ -> () let check_nongen_schemes env sg = List.iter (check_nongen_scheme env) sg let anchor_submodule name anchor = match anchor with None -> None | Some p -> Some(Pdot(p, name, nopos)) let anchor_recmodule id = Some (Pident id) let enrich_type_decls anchor decls oldenv newenv = match anchor with None -> newenv | Some p -> List.fold_left (fun e info -> let id = info.typ_id in let info' = Mtype.enrich_typedecl oldenv (Pdot(p, Ident.name id, nopos)) info.typ_type in Env.add_type ~check:true id info' e) oldenv decls let enrich_module_type anchor name mty env = match anchor with None -> mty | Some p -> Mtype.enrich_modtype env (Pdot(p, name, nopos)) mty let check_recmodule_inclusion env bindings = PR#4450 , PR#4470 : consider module rec X : = MOD where MOD has inferred type ACTUAL The " natural " typing condition E , X : ACTUAL |- ACTUAL < : leads to circularities through manifest types . Instead , we " unroll away " the potential circularities a finite number of times . The ( weaker ) condition we implement is : E , X : , X1 : ACTUAL , X2 : ACTUAL{X < - X1}/X1 ... Xn : ACTUAL{X < - X(n-1)}/X(n-1 ) |- ACTUAL{X < - Xn}/Xn < : DECL{X < - Xn } so that manifest types rooted at X(n+1 ) are expanded in terms of X(n ) , avoiding circularities . The strengthenings ensure that Xn.t = X(n-1).t = ... = X2.t = X1.t . N can be chosen arbitrarily ; larger values of N result in more recursive definitions being accepted . A good choice appears to be the number of mutually recursive declarations . module rec X : DECL = MOD where MOD has inferred type ACTUAL The "natural" typing condition E, X: ACTUAL |- ACTUAL <: DECL leads to circularities through manifest types. Instead, we "unroll away" the potential circularities a finite number of times. The (weaker) condition we implement is: E, X: DECL, X1: ACTUAL, X2: ACTUAL{X <- X1}/X1 ... Xn: ACTUAL{X <- X(n-1)}/X(n-1) |- ACTUAL{X <- Xn}/Xn <: DECL{X <- Xn} so that manifest types rooted at X(n+1) are expanded in terms of X(n), avoiding circularities. The strengthenings ensure that Xn.t = X(n-1).t = ... = X2.t = X1.t. N can be chosen arbitrarily; larger values of N result in more recursive definitions being accepted. A good choice appears to be the number of mutually recursive declarations. *) let subst_and_strengthen env s id mty = Mtype.strengthen ~aliasable:false env (Subst.modtype s mty) (Subst.module_path s (Pident id)) in let rec check_incl first_time n env s = if n > 0 then begin Generate fresh names Y_i for the rec . bound module idents let bindings1 = List.map (fun (id, _, _mty_decl, _modl, mty_actual, _attrs, _loc) -> (id, Ident.rename id, mty_actual)) bindings in let env' = List.fold_left (fun env (id, id', mty_actual) -> let mty_actual' = if first_time then mty_actual else subst_and_strengthen env s id mty_actual in Env.add_module ~arg:false id' mty_actual' env) env bindings1 in let s' = List.fold_left (fun s (id, id', _mty_actual) -> Subst.add_module id (Pident id') s) Subst.identity bindings1 in check_incl false (n-1) env' s' end else begin let check_inclusion (id, id_loc, mty_decl, modl, mty_actual, attrs, loc) = let mty_decl' = Subst.modtype s mty_decl.mty_type and mty_actual' = subst_and_strengthen env s id mty_actual in let coercion = try Includemod.modtypes env mty_actual' mty_decl' with Includemod.Error msg -> raise(Error(modl.mod_loc, env, Not_included msg)) in let modl' = { mod_desc = Tmod_constraint(modl, mty_decl.mty_type, Tmodtype_explicit mty_decl, coercion); mod_type = mty_decl.mty_type; mod_env = env; mod_loc = modl.mod_loc; mod_attributes = []; } in { mb_id = id; mb_name = id_loc; mb_expr = modl'; mb_attributes = attrs; mb_loc = loc; } in List.map check_inclusion bindings end in check_incl true (List.length bindings) env Subst.identity let rec package_constraints env loc mty constrs = if constrs = [] then mty else let sg = extract_sig env loc mty in let sg' = List.map (function | Sig_type (id, ({type_params=[]} as td), rs) when List.mem_assoc [Ident.name id] constrs -> let ty = List.assoc [Ident.name id] constrs in Sig_type (id, {td with type_manifest = Some ty}, rs) | Sig_module (id, md, rs) -> let rec aux = function | (m :: ((_ :: _) as l), t) :: rest when m = Ident.name id -> (l, t) :: aux rest | _ :: rest -> aux rest | [] -> [] in let md = {md with md_type = package_constraints env loc md.md_type (aux constrs) } in Sig_module (id, md, rs) | item -> item ) sg in Mty_signature sg' let modtype_of_package env loc p nl tl = try match (Env.find_modtype p env).mtd_type with | Some mty when nl <> [] -> package_constraints env loc mty (List.combine (List.map Longident.flatten nl) tl) | _ -> if nl = [] then Mty_ident p else raise(Error(loc, env, Signature_expected)) with Not_found -> let error = Typetexp.Unbound_modtype (Ctype.lid_of_path p) in raise(Typetexp.Error(loc, env, error)) let package_subtype env p1 nl1 tl1 p2 nl2 tl2 = let mkmty p nl tl = let ntl = List.filter (fun (_n,t) -> Ctype.free_variables t = []) (List.combine nl tl) in let (nl, tl) = List.split ntl in modtype_of_package env Location.none p nl tl in let mty1 = mkmty p1 nl1 tl1 and mty2 = mkmty p2 nl2 tl2 in try Includemod.modtypes env mty1 mty2 = Tcoerce_none with Includemod.Error _msg -> false raise(Error(Location.none , env , Not_included msg ) ) let () = Ctype.package_subtype := package_subtype let wrap_constraint env arg mty explicit = let coercion = try Includemod.modtypes env arg.mod_type mty with Includemod.Error msg -> raise(Error(arg.mod_loc, env, Not_included msg)) in { mod_desc = Tmod_constraint(arg, mty, explicit, coercion); mod_type = mty; mod_env = env; mod_attributes = []; mod_loc = arg.mod_loc } let rec type_module ?(alias=false) sttn funct_body anchor env smod = match smod.pmod_desc with Pmod_ident lid -> let path = Typetexp.lookup_module ~load:(not alias) env smod.pmod_loc lid.txt in let md = { mod_desc = Tmod_ident (path, lid); mod_type = Mty_alias(Mta_absent, path); mod_env = env; mod_attributes = smod.pmod_attributes; mod_loc = smod.pmod_loc } in let aliasable = not (Env.is_functor_arg path env) in let md = if alias && aliasable then (Env.add_required_global (Path.head path); md) else match (Env.find_module path env).md_type with Mty_alias(_, p1) when not alias -> let p1 = Env.normalize_path (Some smod.pmod_loc) env p1 in let mty = Includemod.expand_module_alias env [] p1 in { md with mod_desc = Tmod_constraint (md, mty, Tmodtype_implicit, Tcoerce_alias (p1, Tcoerce_none)); mod_type = if sttn then Mtype.strengthen ~aliasable:true env mty p1 else mty } | mty -> let mty = if sttn then Mtype.strengthen ~aliasable env mty path else mty in { md with mod_type = mty } in rm md | Pmod_structure sstr -> let (str, sg, _finalenv) = type_structure funct_body anchor env sstr smod.pmod_loc in let md = rm { mod_desc = Tmod_structure str; mod_type = Mty_signature sg; mod_env = env; mod_attributes = smod.pmod_attributes; mod_loc = smod.pmod_loc } in let sg' = simplify_signature sg in if List.length sg' = List.length sg then md else wrap_constraint (Env.implicit_coercion env) md (Mty_signature sg') Tmodtype_implicit | Pmod_functor(name, smty, sbody) -> let mty = may_map (transl_modtype env) smty in let ty_arg = may_map (fun m -> m.mty_type) mty in let (id, newenv), funct_body = match ty_arg with None -> (Ident.create "*", env), false | Some mty -> Env.enter_module ~arg:true name.txt mty env, true in PR#6981 let body = type_module sttn funct_body None newenv sbody in rm { mod_desc = Tmod_functor(id, name, mty, body); mod_type = Mty_functor(id, ty_arg, body.mod_type); mod_env = env; mod_attributes = smod.pmod_attributes; mod_loc = smod.pmod_loc } | Pmod_apply(sfunct, sarg) -> let arg = type_module true funct_body None env sarg in let path = path_of_module arg in let funct = type_module (sttn && path <> None) funct_body None env sfunct in begin match Env.scrape_alias env funct.mod_type with Mty_functor(param, mty_param, mty_res) as mty_functor -> let generative, mty_param = (mty_param = None, Btype.default_mty mty_param) in if generative then begin if sarg.pmod_desc <> Pmod_structure [] then raise (Error (sfunct.pmod_loc, env, Apply_generative)); if funct_body && Mtype.contains_type env funct.mod_type then raise (Error (smod.pmod_loc, env, Not_allowed_in_functor_body)); end; let coercion = try Includemod.modtypes env arg.mod_type mty_param with Includemod.Error msg -> raise(Error(sarg.pmod_loc, env, Not_included msg)) in let mty_appl = match path with Some path -> Subst.modtype (Subst.add_module param path Subst.identity) mty_res | None -> if generative then mty_res else try Mtype.nondep_supertype (Env.add_module ~arg:true param arg.mod_type env) param mty_res with Not_found -> raise(Error(smod.pmod_loc, env, Cannot_eliminate_dependency mty_functor)) in rm { mod_desc = Tmod_apply(funct, arg, coercion); mod_type = mty_appl; mod_env = env; mod_attributes = smod.pmod_attributes; mod_loc = smod.pmod_loc } | Mty_alias(_, path) -> raise(Error(sfunct.pmod_loc, env, Cannot_scrape_alias path)) | _ -> raise(Error(sfunct.pmod_loc, env, Cannot_apply funct.mod_type)) end | Pmod_constraint(sarg, smty) -> let arg = type_module ~alias true funct_body anchor env sarg in let mty = transl_modtype env smty in rm {(wrap_constraint env arg mty.mty_type (Tmodtype_explicit mty)) with mod_loc = smod.pmod_loc; mod_attributes = smod.pmod_attributes; } | Pmod_unpack sexp -> if !Clflags.principal then Ctype.begin_def (); let exp = Typecore.type_exp env sexp in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_structure exp.exp_type end; let mty = match Ctype.expand_head env exp.exp_type with {desc = Tpackage (p, nl, tl)} -> if List.exists (fun t -> Ctype.free_variables t <> []) tl then raise (Error (smod.pmod_loc, env, Incomplete_packed_module exp.exp_type)); if !Clflags.principal && not (Typecore.generalizable (Btype.generic_level-1) exp.exp_type) then Location.prerr_warning smod.pmod_loc (Warnings.Not_principal "this module unpacking"); modtype_of_package env smod.pmod_loc p nl tl | {desc = Tvar _} -> raise (Typecore.Error (smod.pmod_loc, env, Typecore.Cannot_infer_signature)) | _ -> raise (Error(smod.pmod_loc, env, Not_a_packed_module exp.exp_type)) in if funct_body && Mtype.contains_type env mty then raise (Error (smod.pmod_loc, env, Not_allowed_in_functor_body)); rm { mod_desc = Tmod_unpack(exp, mty); mod_type = mty; mod_env = env; mod_attributes = smod.pmod_attributes; mod_loc = smod.pmod_loc } | Pmod_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) and type_structure ?(toplevel = false) funct_body anchor env sstr scope = let names = new_names () in let type_str_item env srem {pstr_loc = loc; pstr_desc = desc} = match desc with | Pstr_eval (sexpr, attrs) -> let expr = Builtin_attributes.with_warning_attribute attrs (fun () -> Typecore.type_expression env sexpr) in Tstr_eval (expr, attrs), [], env | Pstr_value(rec_flag, sdefs) -> let scope = match rec_flag with | Recursive -> Some (Annot.Idef {scope with Location.loc_start = loc.Location.loc_start}) | Nonrecursive -> let start = match srem with | [] -> loc.Location.loc_end | {pstr_loc = loc2} :: _ -> loc2.Location.loc_start in Some (Annot.Idef {scope with Location.loc_start = start}) in let (defs, newenv) = Typecore.type_binding env rec_flag sdefs scope in Tstr_value(rec_flag, defs), List.map (fun id -> Sig_value(id, Env.find_value (Pident id) newenv)) (let_bound_idents defs), newenv | Pstr_primitive sdesc -> let (desc, newenv) = Typedecl.transl_value_decl env loc sdesc in Tstr_primitive desc, [Sig_value(desc.val_id, desc.val_val)], newenv | Pstr_type (rec_flag, sdecls) -> List.iter (fun decl -> check_name check_type names decl.ptype_name) sdecls; let (decls, newenv) = Typedecl.transl_type_decl env rec_flag sdecls in Tstr_type (rec_flag, decls), map_rec_type_with_row_types ~rec_flag (fun rs info -> Sig_type(info.typ_id, info.typ_type, rs)) decls [], enrich_type_decls anchor decls env newenv | Pstr_typext styext -> List.iter (fun pext -> check_name check_typext names pext.pext_name) styext.ptyext_constructors; let (tyext, newenv) = Typedecl.transl_type_extension true env loc styext in (Tstr_typext tyext, map_ext (fun es ext -> Sig_typext(ext.ext_id, ext.ext_type, es)) tyext.tyext_constructors [], newenv) | Pstr_exception sext -> check_name check_typext names sext.pext_name; let (ext, newenv) = Typedecl.transl_exception env sext in Tstr_exception ext, [Sig_typext(ext.ext_id, ext.ext_type, Text_exception)], newenv | Pstr_module {pmb_name = name; pmb_expr = smodl; pmb_attributes = attrs; pmb_loc; } -> check_name check_module names name; create early for PR#6752 let modl = Builtin_attributes.with_warning_attribute attrs (fun () -> type_module ~alias:true true funct_body (anchor_submodule name.txt anchor) env smodl ) in let md = { md_type = enrich_module_type anchor name.txt modl.mod_type env; md_attributes = attrs; md_loc = pmb_loc; } in let newenv = Env.enter_module_declaration id md env in Tstr_module {mb_id=id; mb_name=name; mb_expr=modl; mb_attributes=attrs; mb_loc=pmb_loc; }, [Sig_module(id, {md_type = modl.mod_type; md_attributes = attrs; md_loc = pmb_loc; }, Trec_not)], newenv | Pstr_recmodule sbind -> let sbind = List.map (function | {pmb_name = name; pmb_expr = {pmod_desc=Pmod_constraint(expr, typ)}; pmb_attributes = attrs; pmb_loc = loc; } -> name, typ, expr, attrs, loc | mb -> raise (Error (mb.pmb_expr.pmod_loc, env, Recursive_module_require_explicit_type)) ) sbind in List.iter (fun (name, _, _, _, _) -> check_name check_module names name) sbind; let (decls, newenv) = transl_recmodule_modtypes env (List.map (fun (name, smty, _smodl, attrs, loc) -> {pmd_name=name; pmd_type=smty; pmd_attributes=attrs; pmd_loc=loc}) sbind ) in let bindings1 = List.map2 (fun {md_id=id; md_type=mty} (name, _, smodl, attrs, loc) -> let modl = Builtin_attributes.with_warning_attribute attrs (fun () -> type_module true funct_body (anchor_recmodule id) newenv smodl ) in let mty' = enrich_module_type anchor (Ident.name id) modl.mod_type newenv in (id, name, mty, modl, mty', attrs, loc)) decls sbind in List.fold_left (fun env md -> let mdecl = { md_type = md.md_type.mty_type; md_attributes = md.md_attributes; md_loc = md.md_loc; } in Env.add_module_declaration ~check:true md.md_id mdecl env ) env decls in let bindings2 = check_recmodule_inclusion newenv bindings1 in Tstr_recmodule bindings2, map_rec (fun rs mb -> Sig_module(mb.mb_id, { md_type=mb.mb_expr.mod_type; md_attributes=mb.mb_attributes; md_loc=mb.mb_loc; }, rs)) bindings2 [], newenv | Pstr_modtype pmtd -> let newenv, mtd, sg = Builtin_attributes.with_warning_attribute pmtd.pmtd_attributes (fun () -> transl_modtype_decl names env pmtd) in Tstr_modtype mtd, [sg], newenv | Pstr_open sod -> let (_path, newenv, od) = type_open ~toplevel env sod in Tstr_open od, [], newenv | Pstr_class cl -> List.iter (fun {pci_name} -> check_name check_type names pci_name) cl; let (classes, new_env) = Typeclass.class_declarations env cl in Tstr_class (List.map (fun cls -> (cls.Typeclass.cls_info, cls.Typeclass.cls_pub_methods)) classes), TODO : check with why this is here Tstr_class_type ( List.map ( fun ( _ , _ , i , d , _ , _ , _ , _ , _ , _ , c ) - > ( i , c ) ) classes ) : : Tstr_type ( List.map ( fun ( _ , _ , _ , _ , i , d , _ , _ , _ , _ , _ ) - > ( i , d ) ) classes ) : : Tstr_type ( List.map ( fun ( _ , _ , _ , _ , _ , _ , i , d , _ , _ , _ ) - > ( i , d ) ) classes ) : : Tstr_class_type (List.map (fun (_,_, i, d, _,_,_,_,_,_,c) -> (i, c)) classes) :: Tstr_type (List.map (fun (_,_,_,_, i, d, _,_,_,_,_) -> (i, d)) classes) :: Tstr_type (List.map (fun (_,_,_,_,_,_, i, d, _,_,_) -> (i, d)) classes) :: *) List.flatten (map_rec (fun rs cls -> let open Typeclass in [Sig_class(cls.cls_id, cls.cls_decl, rs); Sig_class_type(cls.cls_ty_id, cls.cls_ty_decl, rs); Sig_type(cls.cls_obj_id, cls.cls_obj_abbr, rs); Sig_type(cls.cls_typesharp_id, cls.cls_abbr, rs)]) classes []), new_env | Pstr_class_type cl -> List.iter (fun {pci_name} -> check_name check_type names pci_name) cl; let (classes, new_env) = Typeclass.class_type_declarations env cl in Tstr_class_type (List.map (fun cl -> (cl.Typeclass.clsty_ty_id, cl.Typeclass.clsty_id_loc, cl.Typeclass.clsty_info)) classes), TODO : check with why this is here Tstr_type ( List.map ( fun ( _ , _ , i , d , _ , _ ) - > ( i , d ) ) classes ) : : Tstr_type ( List.map ( fun ( _ , _ , _ , _ , i , d ) - > ( i , d ) ) classes ) : : Tstr_type (List.map (fun (_, _, i, d, _, _) -> (i, d)) classes) :: Tstr_type (List.map (fun (_, _, _, _, i, d) -> (i, d)) classes) :: *) List.flatten (map_rec (fun rs decl -> let open Typeclass in [Sig_class_type(decl.clsty_ty_id, decl.clsty_ty_decl, rs); Sig_type(decl.clsty_obj_id, decl.clsty_obj_abbr, rs); Sig_type(decl.clsty_typesharp_id, decl.clsty_abbr, rs)]) classes []), new_env | Pstr_include sincl -> let smodl = sincl.pincl_mod in let modl = Builtin_attributes.with_warning_attribute sincl.pincl_attributes (fun () -> type_module true funct_body None env smodl) in let sg = Subst.signature Subst.identity (extract_sig_open env smodl.pmod_loc modl.mod_type) in List.iter (check_sig_item names loc) sg; let new_env = Env.add_signature sg env in let incl = { incl_mod = modl; incl_type = sg; incl_attributes = sincl.pincl_attributes; incl_loc = sincl.pincl_loc; } in Tstr_include incl, sg, new_env | Pstr_extension (ext, _attrs) -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) | Pstr_attribute x -> Builtin_attributes.warning_attribute [x]; Tstr_attribute x, [], env in let rec type_struct env sstr = Ctype.init_def(Ident.current_time()); match sstr with | [] -> ([], [], env) | pstr :: srem -> let previous_saved_types = Cmt_format.get_saved_types () in let desc, sg, new_env = type_str_item env srem pstr in let str = { str_desc = desc; str_loc = pstr.pstr_loc; str_env = env } in Cmt_format.set_saved_types (Cmt_format.Partial_structure_item str :: previous_saved_types); let (str_rem, sig_rem, final_env) = type_struct new_env srem in (str :: str_rem, sg @ sig_rem, final_env) in if !Clflags.annotations then List.iter (function {pstr_loc = l} -> Stypes.record_phrase l) sstr; let previous_saved_types = Cmt_format.get_saved_types () in if not toplevel then Builtin_attributes.warning_enter_scope (); let (items, sg, final_env) = type_struct env sstr in let str = { str_items = items; str_type = sg; str_final_env = final_env } in if not toplevel then Builtin_attributes.warning_leave_scope (); Cmt_format.set_saved_types (Cmt_format.Partial_structure str :: previous_saved_types); str, sg, final_env let type_toplevel_phrase env s = Env.reset_required_globals (); begin let iter = Builtin_attributes.emit_external_warnings in iter.Ast_iterator.structure iter s end; let (str, sg, env) = type_structure ~toplevel:true false None env s Location.none in let (str, _coerce) = ImplementationHooks.apply_hooks { Misc.sourcefile = "//toplevel//" } (str, Tcoerce_none) in (str, sg, env) let type_module_alias = type_module ~alias:true true false None let type_module = type_module true false None let type_structure = type_structure false None let rec normalize_modtype env = function Mty_ident _ | Mty_alias _ -> () | Mty_signature sg -> normalize_signature env sg | Mty_functor(_id, _param, body) -> normalize_modtype env body and normalize_signature env = List.iter (normalize_signature_item env) and normalize_signature_item env = function Sig_value(_id, desc) -> Ctype.normalize_type env desc.val_type | Sig_module(_id, md, _) -> normalize_modtype env md.md_type | _ -> () let type_module_type_of env smod = let tmty = match smod.pmod_desc with let path, md = Typetexp.find_module env smod.pmod_loc lid.txt in rm { mod_desc = Tmod_ident (path, lid); mod_type = md.md_type; mod_env = env; mod_attributes = smod.pmod_attributes; mod_loc = smod.pmod_loc } | _ -> type_module env smod in let mty = tmty.mod_type in let mty = Mtype.remove_aliases env mty in PR#5036 : must not contain non - generalized type variables if not (closed_modtype env mty) then raise(Error(smod.pmod_loc, env, Non_generalizable_module mty)); tmty, mty For let type_package env m p nl = Same as Pexp_letmodule let lv = Ctype.get_current_level () in Ctype.begin_def (); Ident.set_current_time lv; let context = Typetexp.narrow () in let modl = type_module env m in Ctype.init_def(Ident.current_time()); Typetexp.widen context; let (mp, env) = match modl.mod_desc with Tmod_ident (mp,_) -> (mp, env) | Tmod_constraint ({mod_desc=Tmod_ident (mp,_)}, _, Tmodtype_implicit, _) | _ -> let (id, new_env) = Env.enter_module ~arg:true "%M" modl.mod_type env in (Pident id, new_env) in let rec mkpath mp = function | Lident name -> Pdot(mp, name, nopos) | Ldot (m, name) -> Pdot(mkpath mp m, name, nopos) | _ -> assert false in let tl' = List.map (fun name -> Btype.newgenty (Tconstr (mkpath mp name,[],ref Mnil))) nl in Ctype.end_def (); if nl = [] then (wrap_constraint env modl (Mty_ident p) Tmodtype_implicit, []) else let mty = modtype_of_package env modl.mod_loc p nl tl' in List.iter2 (fun n ty -> try Ctype.unify env ty (Ctype.newvar ()) with Ctype.Unify _ -> raise (Error(m.pmod_loc, env, Scoping_pack (n,ty)))) nl tl'; (wrap_constraint env modl mty Tmodtype_implicit, tl') let () = Typecore.type_module := type_module_alias; Typetexp.transl_modtype_longident := transl_modtype_longident; Typetexp.transl_modtype := transl_modtype; Typecore.type_open := type_open_ ?toplevel:None; Typecore.type_package := type_package; type_module_type_of_fwd := type_module_type_of an implementation file let type_implementation sourcefile outputprefix modulename initial_env ast = Cmt_format.clear (); try Typecore.reset_delayed_checks (); Env.reset_required_globals (); begin let iter = Builtin_attributes.emit_external_warnings in iter.Ast_iterator.structure iter ast end; let (str, sg, finalenv) = type_structure initial_env ast (Location.in_file sourcefile) in let simple_sg = simplify_signature sg in if !Clflags.print_types then begin Printtyp.wrap_printing_env initial_env (fun () -> fprintf std_formatter "%a@." Printtyp.signature simple_sg); end else begin let sourceintf = Filename.remove_extension sourcefile ^ !Config.interface_suffix in if Sys.file_exists sourceintf then begin let intf_file = try find_in_path_uncap !Config.load_path (modulename ^ ".cmi") with Not_found -> raise(Error(Location.in_file sourcefile, Env.empty, Interface_not_compiled sourceintf)) in let dclsig = Env.read_signature modulename intf_file in let coercion = Includemod.compunit initial_env sourcefile sg intf_file dclsig in Typecore.force_delayed_checks (); Cmt_format.save_cmt (outputprefix ^ ".cmt") modulename (Cmt_format.Implementation str) (Some sourcefile) initial_env None; (str, coercion) end else begin check_nongen_schemes finalenv sg; normalize_signature finalenv simple_sg; let coercion = Includemod.compunit initial_env sourcefile sg "(inferred signature)" simple_sg in Typecore.force_delayed_checks (); See comment above . Here the target signature contains all the value being exported . We can still capture unused declarations like " let x = true ; ; let x = 1 ; ; " , because in this case , the inferred signature contains only the last declaration . the value being exported. We can still capture unused declarations like "let x = true;; let x = 1;;", because in this case, the inferred signature contains only the last declaration. *) if not !Clflags.dont_write_files then begin let deprecated = Builtin_attributes.deprecated_of_str ast in let sg = Env.save_signature ~deprecated simple_sg modulename (outputprefix ^ ".cmi") in Cmt_format.save_cmt (outputprefix ^ ".cmt") modulename (Cmt_format.Implementation str) (Some sourcefile) initial_env (Some sg); end; (str, coercion) end end with e -> Cmt_format.save_cmt (outputprefix ^ ".cmt") modulename (Cmt_format.Partial_implementation (Array.of_list (Cmt_format.get_saved_types ()))) (Some sourcefile) initial_env None; raise e let type_implementation sourcefile outputprefix modulename initial_env ast = ImplementationHooks.apply_hooks { Misc.sourcefile } (type_implementation sourcefile outputprefix modulename initial_env ast) let save_signature modname tsg outputprefix source_file initial_env cmi = Cmt_format.save_cmt (outputprefix ^ ".cmti") modname (Cmt_format.Interface tsg) (Some source_file) initial_env (Some cmi) let type_interface sourcefile env ast = begin let iter = Builtin_attributes.emit_external_warnings in iter.Ast_iterator.signature iter ast end; InterfaceHooks.apply_hooks { Misc.sourcefile } (transl_signature env ast) " Packaging " of several compilation units into one unit having them as sub - modules . having them as sub-modules. *) let rec package_signatures subst = function [] -> [] | (name, sg) :: rem -> let sg' = Subst.signature subst sg in let oldid = Ident.create_persistent name and newid = Ident.create name in Sig_module(newid, {md_type=Mty_signature sg'; md_attributes=[]; md_loc=Location.none; }, Trec_not) :: package_signatures (Subst.add_module oldid (Pident newid) subst) rem let package_units initial_env objfiles cmifile modulename = let units = List.map (fun f -> let pref = chop_extensions f in let modname = String.capitalize_ascii(Filename.basename pref) in let sg = Env.read_signature modname (pref ^ ".cmi") in if Filename.check_suffix f ".cmi" && not(Mtype.no_code_needed_sig Env.initial_safe_string sg) then raise(Error(Location.none, Env.empty, Implementation_is_required f)); (modname, Env.read_signature modname (pref ^ ".cmi"))) objfiles in Ident.reinit(); let sg = package_signatures Subst.identity units in let prefix = Filename.remove_extension cmifile in let mlifile = prefix ^ !Config.interface_suffix in if Sys.file_exists mlifile then begin if not (Sys.file_exists cmifile) then begin raise(Error(Location.in_file mlifile, Env.empty, Interface_not_compiled mlifile)) end; let dclsig = Env.read_signature modulename cmifile in Cmt_format.save_cmt (prefix ^ ".cmt") modulename (Cmt_format.Packed (sg, objfiles)) None initial_env None ; Includemod.compunit initial_env "(obtained by packing)" sg mlifile dclsig end else begin let unit_names = List.map fst units in let imports = List.filter (fun (name, _crc) -> not (List.mem name unit_names)) (Env.imports()) in if not !Clflags.dont_write_files then begin let sg = Env.save_signature_with_imports ~deprecated:None sg modulename (prefix ^ ".cmi") imports in Cmt_format.save_cmt (prefix ^ ".cmt") modulename (Cmt_format.Packed (sg, objfiles)) None initial_env (Some sg) end; Tcoerce_none end open Printtyp let report_error ppf = function Cannot_apply mty -> fprintf ppf "@[This module is not a functor; it has type@ %a@]" modtype mty | Not_included errs -> fprintf ppf "@[<v>Signature mismatch:@ %a@]" Includemod.report_error errs | Cannot_eliminate_dependency mty -> fprintf ppf "@[This functor has type@ %a@ \ The parameter cannot be eliminated in the result type.@ \ Please bind the argument to a module identifier.@]" modtype mty | Signature_expected -> fprintf ppf "This module type is not a signature" | Structure_expected mty -> fprintf ppf "@[This module is not a structure; it has type@ %a" modtype mty | With_no_component lid -> fprintf ppf "@[The signature constrained by `with' has no component named %a@]" longident lid | With_mismatch(lid, explanation) -> fprintf ppf "@[<v>\ @[In this `with' constraint, the new definition of %a@ \ does not match its original definition@ \ in the constrained signature:@]@ \ %a@]" longident lid Includemod.report_error explanation | Repeated_name(kind, name) -> fprintf ppf "@[Multiple definition of the %s name %s.@ \ Names must be unique in a given structure or signature.@]" kind name | Non_generalizable typ -> fprintf ppf "@[The type of this expression,@ %a,@ \ contains type variables that cannot be generalized@]" type_scheme typ | Non_generalizable_class (id, desc) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains type variables that cannot be generalized@]" (class_declaration id) desc | Non_generalizable_module mty -> fprintf ppf "@[The type of this module,@ %a,@ \ contains type variables that cannot be generalized@]" modtype mty | Implementation_is_required intf_name -> fprintf ppf "@[The interface %a@ declares values, not just types.@ \ An implementation must be provided.@]" Location.print_filename intf_name | Interface_not_compiled intf_name -> fprintf ppf "@[Could not find the .cmi file for interface@ %a.@]" Location.print_filename intf_name | Not_allowed_in_functor_body -> fprintf ppf "@[This expression creates fresh types.@ %s@]" "It is not allowed inside applicative functors." | With_need_typeconstr -> fprintf ppf "Only type constructors with identical parameters can be substituted." | Not_a_packed_module ty -> fprintf ppf "This expression is not a packed module. It has type@ %a" type_expr ty | Incomplete_packed_module ty -> fprintf ppf "The type of this packed module contains variables:@ %a" type_expr ty | Scoping_pack (lid, ty) -> fprintf ppf "The type %a in this module cannot be exported.@ " longident lid; fprintf ppf "Its type contains local dependencies:@ %a" type_expr ty | Recursive_module_require_explicit_type -> fprintf ppf "Recursive modules require an explicit module type." | Apply_generative -> fprintf ppf "This is a generative functor. It can only be applied to ()" | Cannot_scrape_alias p -> fprintf ppf "This is an alias for module %a, which is missing" path p let report_error env ppf err = Printtyp.wrap_printing_env env (fun () -> report_error ppf err) let () = Location.register_error_of_exn (function | Error (loc, env, err) -> Some (Location.error_of_printer loc (report_error env) err) | Error_forward err -> Some err | _ -> None )
8b8b77dcb9715d0aadf9082fcd24d46521676d7bda9296755110596c78550746
mejgun/haskell-tdlib
SetChatPhoto.hs
{-# LANGUAGE OverloadedStrings #-} -- | module TD.Query.SetChatPhoto where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified TD.Data.InputChatPhoto as InputChatPhoto import qualified Utils as U -- | -- Changes the photo of a chat. Supported only for basic groups, supergroups and channels. Requires can_change_info administrator right data SetChatPhoto = SetChatPhoto { -- | New chat photo; pass null to delete the chat photo photo :: Maybe InputChatPhoto.InputChatPhoto, -- | Chat identifier chat_id :: Maybe Int } deriving (Eq) instance Show SetChatPhoto where show SetChatPhoto { photo = photo_, chat_id = chat_id_ } = "SetChatPhoto" ++ U.cc [ U.p "photo" photo_, U.p "chat_id" chat_id_ ] instance T.ToJSON SetChatPhoto where toJSON SetChatPhoto { photo = photo_, chat_id = chat_id_ } = A.object [ "@type" A..= T.String "setChatPhoto", "photo" A..= photo_, "chat_id" A..= chat_id_ ]
null
https://raw.githubusercontent.com/mejgun/haskell-tdlib/dc380d18d49eaadc386a81dc98af2ce00f8797c2/src/TD/Query/SetChatPhoto.hs
haskell
# LANGUAGE OverloadedStrings # | | Changes the photo of a chat. Supported only for basic groups, supergroups and channels. Requires can_change_info administrator right | New chat photo; pass null to delete the chat photo | Chat identifier
module TD.Query.SetChatPhoto where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified TD.Data.InputChatPhoto as InputChatPhoto import qualified Utils as U data SetChatPhoto = SetChatPhoto photo :: Maybe InputChatPhoto.InputChatPhoto, chat_id :: Maybe Int } deriving (Eq) instance Show SetChatPhoto where show SetChatPhoto { photo = photo_, chat_id = chat_id_ } = "SetChatPhoto" ++ U.cc [ U.p "photo" photo_, U.p "chat_id" chat_id_ ] instance T.ToJSON SetChatPhoto where toJSON SetChatPhoto { photo = photo_, chat_id = chat_id_ } = A.object [ "@type" A..= T.String "setChatPhoto", "photo" A..= photo_, "chat_id" A..= chat_id_ ]
0e968185a03e301d3f8903970c4cf29ffa359908c0965d526646ebd49b0ce901
ivanjovanovic/sicp
5.2.scm
(load "../common.scm") ; In order to test if machines we design are returning proper results, we are ; going to build a simulator that will run the machine. In that way, we'll see ; how our machines behave. ; ; Generally, machines will be defined by the interface of for procedures ; ; (make-machine <register-names> <operations> <controller>) ; (set-register-contents! <machine-model> <register-name> <value>) ; (get-register-content <machine-model> <register-name>) ; (start <machine-model>) one example is gcd machine ;(define gcd-machine ;(make-machine ;; registers ;'(a b t) ;; primitive operations ;(list (list 'rem remainder) (list '= =)) ;; controller ;'(test-b ;(test (op =) (reg b) (const 0)) ( branch ( label gcd - done ) ) ;(assign t (op rem) (reg a) (reg b)) ;(assign a (reg b)) ;(assign b (reg t)) ( goto ( label test - b ) ) ;gcd-done))) ; model of the machine is represented as a procedure with local state. (define (make-machine register-names ops controller-text) creating one empty machine model (for-each (lambda (register-name) ((machine 'allocate-register) register-name)) ; allocating registers in the machine register-names) ((machine 'install-operations) ops) ; passing a message to install operations ((machine 'install-instruction-sequence) ; passing a message to install instruction sequenc (assemble controller-text machine)) ; instruction sequence is converted to the machine representation machine)) ; register is a procedure with the local state and set of messages that it answers to. (define (make-register name) (let ((contents '*unassigned*)) (define (dispatch message) (cond ((eq? message 'get) contents) ((eq? message 'set) (lambda (value) (set! contents value))) (else (error "Unknown request -- REGISTER" message)))) dispatch)) (define (get-contents register) (register 'get)) (define (set-contents! register value) ((register 'set) value)) ; stack implementation as a procedure with local state (define (make-stack) (let ((s '())) (define (push x) (set! s (cons x s))) (define (pop) (if (null? s) (error "Empty stack -- POP") (let ((top (car s))) (set! s (cdr s)) top))) (define (initialize) (set! s '()) 'done) (define (dispatch message) (cond ((eq? message 'push) push) ((eq? message 'pop) (pop)) ((eq? message 'initialize) (initialize)) (else (error "Unknown request -- STACK" message)))) dispatch)) (define (pop stack) (stack 'pop)) (define (push stack value) ((stack 'push) value)) ; implementation of the model of the machine (define (make-new-machine) (let ((pc (make-register 'pc)) (flag (make-register 'flag)) (stack (make-stack)) (the-instruction-sequence '())) (let ((the-ops (list (list 'initialize-stack (lambda () (stack 'initialize))))) (register-table (list (list 'pc pc) (list 'flag flag)))) ; allocation of the new register object with the given name (define (allocate-register name) (if (assoc name register-table) (error "Multiply defined register: " name) (set! register-table (cons (list name (make-register name)) register-table))) 'register-allocated) ; get the value of the register (define (lookup-register name) (let ((val (assoc name register-table))) (if val (cadr val) (error "Unknown register: " name)))) ; run the machine (define (execute) (let ((insts (get-contents pc))) (if (null? insts) 'done (begin ((instruction-execution-proc (car insts))) (execute))))) ; external interface (define (dispatch message) (cond ((eq? message 'start) (set-contents! pc the-instruction-sequence) (execute)) ((eq? message 'install-instruction-sequence) (lambda (seq) (set! the-instruction-sequence seq))) ((eq? message 'allocate-register) allocate-register) ((eq? message 'get-register) lookup-register) ((eq? message 'install-operations) (lambda (ops) (set! the-ops (append the-ops ops)))) ((eq? message 'stack) stack) ((eq? message 'operations) the-ops) (else (error "Unknown request -- MACHINE" message)))) dispatch))) (define (start machine) (machine 'start)) (define (get-register-contents machine register-name) (get-contents (get-register machine register-name))) (define (set-register-contents! machine register-name value) (set-contents! (get-register machine register-name) value) 'done) (define (get-register machine reg-name) ((machine 'get-register) reg-name)) ; assembler is converting list of controller steps to a set of executable instructions (define (assemble controller-text machine) (extract-labels controller-text (lambda (insts labels) (update-insts! insts labels machine) insts))) (define (extract-labels text receive) (if (null? text) (receive '() '()) (extract-labels (cdr text) (lambda (insts labels) (let ((next-inst (car text))) (if (symbol? next-inst) (receive insts (cons (make-label-entry next-inst insts) labels)) (receive (cons (make-instruction next-inst) insts) labels))))))) (define (update-insts! insts labels machine) (let ((pc (get-register machine 'pc)) (flag (get-register machine 'flag)) (stack (machine 'stack)) (ops (machine 'operations))) (for-each (lambda (inst) (set-instruction-execution-proc! inst (make-execution-procedure (instruction-text inst) labels machine pc flag stack ops))) insts))) (define (make-instruction text) (cons text '())) (define (instruction-text inst) (car inst)) (define (instruction-execution-proc inst) (cdr inst)) (define (set-instruction-execution-proc! inst proc) (set-cdr! inst proc)) (define (make-label-entry label-name insts) (cons label-name insts)) (define (lookup-label labels label-name) (let ((val (assoc label-name labels))) (if val (cdr val) (error "Undefined label -- ASSEMBLE" label-name)))) ; we have to make execution procedure for every machine instruction. (define (make-execution-procedure inst labels machine pc flag stack ops) (cond ((eq? (car inst) 'assign) (make-assign inst machine labels ops pc)) ((eq? (car inst) 'test) (make-test inst machine labels ops flag pc)) ((eq? (car inst) 'branch) (make-branch inst machine labels flag pc)) ((eq? (car inst) 'goto) (make-goto inst machine labels pc)) ((eq? (car inst) 'save) (make-save inst machine stack pc)) ((eq? (car inst) 'restore) (make-restore inst machine stack pc)) ((eq? (car inst) 'perform) (make-perform inst machine labels ops pc)) (else (error "Unknown instruction type -- ASSEMBLE" inst)))) ; assignment procedure (define (make-assign inst machine labels operations pc) (let ((target (get-register machine (assign-reg-name inst))) (value-exp (assign-value-exp inst))) (let ((value-proc (if (operation-exp? value-exp) (make-operation-exp value-exp machine labels operations) (make-primitive-exp (car value-exp) machine labels)))) (lambda () ; execution procedure for assign (set-contents! target (value-proc)) (advance-pc pc))))) (define (assign-reg-name assign-instruction) (cadr assign-instruction)) (define (assign-value-exp assign-instruction) (cddr assign-instruction)) (define (advance-pc pc) (set-contents! pc (cdr (get-contents pc)))) ; testing (define (make-test inst machine labels operations flag pc) (let ((condition (test-condition inst))) (if (operation-exp? condition) (let ((condition-proc (make-operation-exp condition machine labels operations))) (lambda () (set-contents! flag (condition-proc)) (advance-pc pc))) (error "Bad TEST instruction -- ASSEMBLE" inst)))) (define (test-condition test-instruction) (cdr test-instruction)) ;branching (define (make-branch inst machine labels flag pc) (let ((dest (branch-dest inst))) (if (label-exp? dest) (let ((insts (lookup-label labels (label-exp-label dest)))) (lambda () (if (get-contents flag) (set-contents! pc insts) (advance-pc pc)))) (error "Bad BRANCH instruction -- ASSEMBLE" inst)))) (define (branch-dest branch-instruction) (cadr branch-instruction)) ; goto (define (make-goto inst machine labels pc) (let ((dest (goto-dest inst))) (cond ((label-exp? dest) (let ((insts (lookup-label labels (label-exp-label dest)))) (lambda () (set-contents! pc insts)))) ((register-exp? dest) (let ((reg (get-register machine (register-exp-reg dest)))) (lambda () (set-contents! pc (get-contents reg))))) (else (error "Bad GOTO instruction -- ASSEMBLE" inst))))) (define (goto-dest goto-instruction) (cadr goto-instruction)) ; save to stack execution procedure (define (make-save inst machine stack pc) (let ((reg (get-register machine (stack-inst-reg-name inst)))) (lambda () (push stack (get-contents reg)) (advance-pc pc)))) ; restore from stack execution procedure (define (make-restore inst machine stack pc) (let ((reg (get-register machine (stack-inst-reg-name inst)))) (lambda () (set-contents! reg (pop stack)) (advance-pc pc)))) (define (stack-inst-reg-name stack-instruction) (cadr stack-instruction)) ; perform an action (define (make-perform inst machine labels operations pc) (let ((action (perform-action inst))) (if (operation-exp? action) (let ((action-proc (make-operation-exp action machine labels operations))) (lambda () (action-proc) (advance-pc pc))) (error "Bad PERFORM instruction -- ASSEMBLE" inst)))) (define (perform-action inst) (cdr inst)) ; primitive expressions (define (make-primitive-exp exp machine labels) (cond ((constant-exp? exp) (let ((c (constant-exp-value exp))) (lambda () c))) ((label-exp? exp) (let ((insts (lookup-label labels (label-exp-label exp)))) (lambda () insts))) ((register-exp? exp) (let ((r (get-register machine (register-exp-reg exp)))) (lambda () (get-contents r)))) (else (error "Unknown expression type -- ASSEMBLE" exp)))) (define (register-exp? exp) (tagged-list? exp 'reg)) (define (register-exp-reg exp) (cadr exp)) (define (constant-exp? exp) (tagged-list? exp 'const)) (define (constant-exp-value exp) (cadr exp)) (define (label-exp? exp) (tagged-list? exp 'label)) (define (label-exp-label exp) (cadr exp)) ; operation expression (define (make-operation-exp exp machine labels operations) (let ((op (lookup-prim (operation-exp-op exp) operations)) (aprocs (map (lambda (e) (make-primitive-exp e machine labels)) (operation-exp-operands exp)))) (lambda () (output exp op aprocs) (apply op (map (lambda (p) (p)) aprocs))))) (define (operation-exp? exp) (and (pair? exp) (tagged-list? (car exp) 'op))) (define (operation-exp-op operation-exp) (cadr (car operation-exp))) (define (operation-exp-operands operation-exp) (cdr operation-exp)) (define (lookup-prim symbol operations) (let ((val (assoc symbol operations))) (if val (cadr val) (error "Unknown operation -- ASSEMBLE" symbol)))) (define (tagged-list? exp tag) (if (pair? exp) (eq? (car exp) tag) false))
null
https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/5.2/5.2.scm
scheme
In order to test if machines we design are returning proper results, we are going to build a simulator that will run the machine. In that way, we'll see how our machines behave. Generally, machines will be defined by the interface of for procedures (make-machine <register-names> <operations> <controller>) (set-register-contents! <machine-model> <register-name> <value>) (get-register-content <machine-model> <register-name>) (start <machine-model>) (define gcd-machine (make-machine registers '(a b t) primitive operations (list (list 'rem remainder) (list '= =)) controller '(test-b (test (op =) (reg b) (const 0)) (assign t (op rem) (reg a) (reg b)) (assign a (reg b)) (assign b (reg t)) gcd-done))) model of the machine is represented as a procedure with local state. allocating registers in the machine passing a message to install operations passing a message to install instruction sequenc instruction sequence is converted to the machine representation register is a procedure with the local state and set of messages that it answers to. stack implementation as a procedure with local state implementation of the model of the machine allocation of the new register object with the given name get the value of the register run the machine external interface assembler is converting list of controller steps to a set of executable instructions we have to make execution procedure for every machine instruction. assignment procedure execution procedure for assign testing branching goto save to stack execution procedure restore from stack execution procedure perform an action primitive expressions operation expression
(load "../common.scm") one example is gcd machine ( branch ( label gcd - done ) ) ( goto ( label test - b ) ) (define (make-machine register-names ops controller-text) creating one empty machine model (for-each (lambda (register-name) register-names) machine)) (define (make-register name) (let ((contents '*unassigned*)) (define (dispatch message) (cond ((eq? message 'get) contents) ((eq? message 'set) (lambda (value) (set! contents value))) (else (error "Unknown request -- REGISTER" message)))) dispatch)) (define (get-contents register) (register 'get)) (define (set-contents! register value) ((register 'set) value)) (define (make-stack) (let ((s '())) (define (push x) (set! s (cons x s))) (define (pop) (if (null? s) (error "Empty stack -- POP") (let ((top (car s))) (set! s (cdr s)) top))) (define (initialize) (set! s '()) 'done) (define (dispatch message) (cond ((eq? message 'push) push) ((eq? message 'pop) (pop)) ((eq? message 'initialize) (initialize)) (else (error "Unknown request -- STACK" message)))) dispatch)) (define (pop stack) (stack 'pop)) (define (push stack value) ((stack 'push) value)) (define (make-new-machine) (let ((pc (make-register 'pc)) (flag (make-register 'flag)) (stack (make-stack)) (the-instruction-sequence '())) (let ((the-ops (list (list 'initialize-stack (lambda () (stack 'initialize))))) (register-table (list (list 'pc pc) (list 'flag flag)))) (define (allocate-register name) (if (assoc name register-table) (error "Multiply defined register: " name) (set! register-table (cons (list name (make-register name)) register-table))) 'register-allocated) (define (lookup-register name) (let ((val (assoc name register-table))) (if val (cadr val) (error "Unknown register: " name)))) (define (execute) (let ((insts (get-contents pc))) (if (null? insts) 'done (begin ((instruction-execution-proc (car insts))) (execute))))) (define (dispatch message) (cond ((eq? message 'start) (set-contents! pc the-instruction-sequence) (execute)) ((eq? message 'install-instruction-sequence) (lambda (seq) (set! the-instruction-sequence seq))) ((eq? message 'allocate-register) allocate-register) ((eq? message 'get-register) lookup-register) ((eq? message 'install-operations) (lambda (ops) (set! the-ops (append the-ops ops)))) ((eq? message 'stack) stack) ((eq? message 'operations) the-ops) (else (error "Unknown request -- MACHINE" message)))) dispatch))) (define (start machine) (machine 'start)) (define (get-register-contents machine register-name) (get-contents (get-register machine register-name))) (define (set-register-contents! machine register-name value) (set-contents! (get-register machine register-name) value) 'done) (define (get-register machine reg-name) ((machine 'get-register) reg-name)) (define (assemble controller-text machine) (extract-labels controller-text (lambda (insts labels) (update-insts! insts labels machine) insts))) (define (extract-labels text receive) (if (null? text) (receive '() '()) (extract-labels (cdr text) (lambda (insts labels) (let ((next-inst (car text))) (if (symbol? next-inst) (receive insts (cons (make-label-entry next-inst insts) labels)) (receive (cons (make-instruction next-inst) insts) labels))))))) (define (update-insts! insts labels machine) (let ((pc (get-register machine 'pc)) (flag (get-register machine 'flag)) (stack (machine 'stack)) (ops (machine 'operations))) (for-each (lambda (inst) (set-instruction-execution-proc! inst (make-execution-procedure (instruction-text inst) labels machine pc flag stack ops))) insts))) (define (make-instruction text) (cons text '())) (define (instruction-text inst) (car inst)) (define (instruction-execution-proc inst) (cdr inst)) (define (set-instruction-execution-proc! inst proc) (set-cdr! inst proc)) (define (make-label-entry label-name insts) (cons label-name insts)) (define (lookup-label labels label-name) (let ((val (assoc label-name labels))) (if val (cdr val) (error "Undefined label -- ASSEMBLE" label-name)))) (define (make-execution-procedure inst labels machine pc flag stack ops) (cond ((eq? (car inst) 'assign) (make-assign inst machine labels ops pc)) ((eq? (car inst) 'test) (make-test inst machine labels ops flag pc)) ((eq? (car inst) 'branch) (make-branch inst machine labels flag pc)) ((eq? (car inst) 'goto) (make-goto inst machine labels pc)) ((eq? (car inst) 'save) (make-save inst machine stack pc)) ((eq? (car inst) 'restore) (make-restore inst machine stack pc)) ((eq? (car inst) 'perform) (make-perform inst machine labels ops pc)) (else (error "Unknown instruction type -- ASSEMBLE" inst)))) (define (make-assign inst machine labels operations pc) (let ((target (get-register machine (assign-reg-name inst))) (value-exp (assign-value-exp inst))) (let ((value-proc (if (operation-exp? value-exp) (make-operation-exp value-exp machine labels operations) (make-primitive-exp (car value-exp) machine labels)))) (set-contents! target (value-proc)) (advance-pc pc))))) (define (assign-reg-name assign-instruction) (cadr assign-instruction)) (define (assign-value-exp assign-instruction) (cddr assign-instruction)) (define (advance-pc pc) (set-contents! pc (cdr (get-contents pc)))) (define (make-test inst machine labels operations flag pc) (let ((condition (test-condition inst))) (if (operation-exp? condition) (let ((condition-proc (make-operation-exp condition machine labels operations))) (lambda () (set-contents! flag (condition-proc)) (advance-pc pc))) (error "Bad TEST instruction -- ASSEMBLE" inst)))) (define (test-condition test-instruction) (cdr test-instruction)) (define (make-branch inst machine labels flag pc) (let ((dest (branch-dest inst))) (if (label-exp? dest) (let ((insts (lookup-label labels (label-exp-label dest)))) (lambda () (if (get-contents flag) (set-contents! pc insts) (advance-pc pc)))) (error "Bad BRANCH instruction -- ASSEMBLE" inst)))) (define (branch-dest branch-instruction) (cadr branch-instruction)) (define (make-goto inst machine labels pc) (let ((dest (goto-dest inst))) (cond ((label-exp? dest) (let ((insts (lookup-label labels (label-exp-label dest)))) (lambda () (set-contents! pc insts)))) ((register-exp? dest) (let ((reg (get-register machine (register-exp-reg dest)))) (lambda () (set-contents! pc (get-contents reg))))) (else (error "Bad GOTO instruction -- ASSEMBLE" inst))))) (define (goto-dest goto-instruction) (cadr goto-instruction)) (define (make-save inst machine stack pc) (let ((reg (get-register machine (stack-inst-reg-name inst)))) (lambda () (push stack (get-contents reg)) (advance-pc pc)))) (define (make-restore inst machine stack pc) (let ((reg (get-register machine (stack-inst-reg-name inst)))) (lambda () (set-contents! reg (pop stack)) (advance-pc pc)))) (define (stack-inst-reg-name stack-instruction) (cadr stack-instruction)) (define (make-perform inst machine labels operations pc) (let ((action (perform-action inst))) (if (operation-exp? action) (let ((action-proc (make-operation-exp action machine labels operations))) (lambda () (action-proc) (advance-pc pc))) (error "Bad PERFORM instruction -- ASSEMBLE" inst)))) (define (perform-action inst) (cdr inst)) (define (make-primitive-exp exp machine labels) (cond ((constant-exp? exp) (let ((c (constant-exp-value exp))) (lambda () c))) ((label-exp? exp) (let ((insts (lookup-label labels (label-exp-label exp)))) (lambda () insts))) ((register-exp? exp) (let ((r (get-register machine (register-exp-reg exp)))) (lambda () (get-contents r)))) (else (error "Unknown expression type -- ASSEMBLE" exp)))) (define (register-exp? exp) (tagged-list? exp 'reg)) (define (register-exp-reg exp) (cadr exp)) (define (constant-exp? exp) (tagged-list? exp 'const)) (define (constant-exp-value exp) (cadr exp)) (define (label-exp? exp) (tagged-list? exp 'label)) (define (label-exp-label exp) (cadr exp)) (define (make-operation-exp exp machine labels operations) (let ((op (lookup-prim (operation-exp-op exp) operations)) (aprocs (map (lambda (e) (make-primitive-exp e machine labels)) (operation-exp-operands exp)))) (lambda () (output exp op aprocs) (apply op (map (lambda (p) (p)) aprocs))))) (define (operation-exp? exp) (and (pair? exp) (tagged-list? (car exp) 'op))) (define (operation-exp-op operation-exp) (cadr (car operation-exp))) (define (operation-exp-operands operation-exp) (cdr operation-exp)) (define (lookup-prim symbol operations) (let ((val (assoc symbol operations))) (if val (cadr val) (error "Unknown operation -- ASSEMBLE" symbol)))) (define (tagged-list? exp tag) (if (pair? exp) (eq? (car exp) tag) false))
370837aa15afdc9bd79ebd35aa2f3196ceeb26bf42103ed0b9f5ca57d8e5cfc3
8c6794b6/guile-tjit
t-pic-01.scm
;;; Test for deoptimization. Running procedure `loop' with small integer arguments for first time , then re - run the procedure with floating ;;; point number as arguments. (define (loop n incr) (let lp ((n n) (acc 0)) (if (< 0 n) (lp (- n 1) (+ acc incr)) acc))) (list (loop #e1e3 125) (loop #e1e3 1.25) (loop #e1e3 125) (loop #e1e3 1.25))
null
https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/test-suite/tjit/t-pic-01.scm
scheme
Test for deoptimization. Running procedure `loop' with small integer point number as arguments.
arguments for first time , then re - run the procedure with floating (define (loop n incr) (let lp ((n n) (acc 0)) (if (< 0 n) (lp (- n 1) (+ acc incr)) acc))) (list (loop #e1e3 125) (loop #e1e3 1.25) (loop #e1e3 125) (loop #e1e3 1.25))
63cc7167b73866339eec419cbf450371e9dc139cd432140eabe3676f9504c562
AccelerateHS/accelerate-examples
Step.hs
module Step ( stepRank, Update, PageGraph ) where import Page import Data.Array.Accelerate as A type PageGraph = Vector Link type Update = (PageId, Rank) - -- | Find the page rank contribution of one edge in the page graph . contribution : : Acc ( Vector Int ) -- ^ Number of outgoing links for each page . - > Acc ( Vector Rank ) -- ^ Old ranks vector . - > Exp Link -- ^ A link . - > Exp Update -- ^ New rank . contribution sizes ranks link = let ( from , to ) = unlift link : : ( Exp PageId , Exp PageId ) in lift ( to , ranks ! ( A.fromIntegral from ) / A.fromIntegral ( sizes ! ( A.fromIntegral from ) ) ) : : Exp Update -- | Updates a vector of ranks by a given vector of updates . addUpdates : : Acc ( Vector Rank ) -- ^ Old partial ranks . - > Acc ( Vector Update ) -- ^ Updates . - > Acc ( Vector Rank ) -- ^ New partial ranks . addUpdates parRanks updates = let ( to , contr ) = A.unzip updates in A.permute ( + ) parRanks ( index1 . A.fromIntegral . ( to ! ) ) contr stepRankSeq : : PageGraph - > Acc ( Vector Int ) -- Sizes . - > Acc ( Vector Rank ) -- Initial ranks . - > Acc ( Vector Rank ) -- Final ranks . stepRankSeq p sizes ranks = let zeroes : : Acc ( Vector Rank ) zeroes = A.fill ( shape ranks ) 0.0 -- Ignore shape vector . addUpdates ' : : Acc ( Vector Rank ) - > Acc ( Vector Z ) - > Acc ( Vector Update ) - > Acc ( Vector Rank ) addUpdates ' = const . addUpdates in A.collect $ A.foldSeqFlatten addUpdates ' zeroes $ A.mapSeq ( ( contribution sizes ranks ) ) ( A.toSeq ( Z : . Split ) ( use p ) ) - -- | Find the page rank contribution of one edge in the page graph. contribution :: Acc (Vector Int) -- ^ Number of outgoing links for each page. -> Acc (Vector Rank) -- ^ Old ranks vector. -> Exp Link -- ^ A link. -> Exp Update -- ^ New rank. contribution sizes ranks link = let (from, to) = unlift link :: (Exp PageId, Exp PageId) in lift (to, ranks ! index1 (A.fromIntegral from) / A.fromIntegral (sizes ! index1 (A.fromIntegral from))) :: Exp Update -- | Updates a vector of ranks by a given vector of updates. addUpdates :: Acc (Vector Rank) -- ^ Old partial ranks. -> Acc (Vector Update) -- ^ Updates. -> Acc (Vector Rank) -- ^ New partial ranks. addUpdates parRanks updates = let (to, contr) = A.unzip updates in A.permute (+) parRanks (index1 . A.fromIntegral . (to !)) contr stepRankSeq :: PageGraph -> Acc (Vector Int) -- Sizes. -> Acc (Vector Rank) -- Initial ranks. -> Acc (Vector Rank) -- Final ranks. stepRankSeq p sizes ranks = let zeroes :: Acc (Vector Rank) zeroes = A.fill (shape ranks) 0.0 -- Ignore shape vector. addUpdates' :: Acc (Vector Rank) -> Acc (Vector Z) -> Acc (Vector Update) -> Acc (Vector Rank) addUpdates' = const . addUpdates in A.collect $ A.foldSeqFlatten addUpdates' zeroes $ A.mapSeq (A.map (contribution sizes ranks)) (A.toSeq (Z :. Split) (use p)) --} | Perform one iteration step for the internal Page Rank algorithm . stepRank :: Acc PageGraph -- ^ Part of the pages graph. -> Acc (Vector Int) -- ^ Number of outgoing links for each page. -> Acc (Vector Rank) -- ^ Old ranks vector. -> Acc (Vector Rank) -- ^ Partial ranks vector -> Acc (Vector Rank) -- ^ New ranks vector. stepRank links sizes ranks parRanks = let pageCount = A.size sizes -- For every link supplied, calculate it's contribution to the page it points to. contribution :: Acc (Vector Float) contribution = A.generate (A.shape links) (\ix -> let (from, _) = unlift $ links ! ix :: (Exp PageId, Exp PageId) in ranks ! index1 (A.fromIntegral from) / A.fromIntegral (sizes ! index1 (A.fromIntegral from))) -- Add to the partial ranks the contribution of the supplied links. ranks' = A.permute (+) parRanks (\ix -> let (_, to) = unlift $ links ! ix :: (Exp PageId, Exp PageId) in Just_ (index1 (A.fromIntegral to))) contribution in ranks'
null
https://raw.githubusercontent.com/AccelerateHS/accelerate-examples/a973ee423b5eadda6ef2e2504d2383f625e49821/examples/pagerank/Step.hs
haskell
| Find the page rank contribution of one edge in the page graph . ^ Number of outgoing links for each page . ^ Old ranks vector . ^ A link . ^ New rank . | Updates a vector of ranks by a given vector of updates . ^ Old partial ranks . ^ Updates . ^ New partial ranks . Sizes . Initial ranks . Final ranks . Ignore shape vector . | Find the page rank contribution of one edge in the page graph. ^ Number of outgoing links for each page. ^ Old ranks vector. ^ A link. ^ New rank. | Updates a vector of ranks by a given vector of updates. ^ Old partial ranks. ^ Updates. ^ New partial ranks. Sizes. Initial ranks. Final ranks. Ignore shape vector. } ^ Part of the pages graph. ^ Number of outgoing links for each page. ^ Old ranks vector. ^ Partial ranks vector ^ New ranks vector. For every link supplied, calculate it's contribution to the page it points to. Add to the partial ranks the contribution of the supplied links.
module Step ( stepRank, Update, PageGraph ) where import Page import Data.Array.Accelerate as A type PageGraph = Vector Link type Update = (PageId, Rank) - contribution contribution sizes ranks link = let ( from , to ) = unlift link : : ( Exp PageId , Exp PageId ) in lift ( to , ranks ! ( A.fromIntegral from ) / A.fromIntegral ( sizes ! ( A.fromIntegral from ) ) ) : : Exp Update addUpdates addUpdates parRanks updates = let ( to , contr ) = A.unzip updates in A.permute ( + ) parRanks ( index1 . A.fromIntegral . ( to ! ) ) contr stepRankSeq : : PageGraph stepRankSeq p sizes ranks = let zeroes : : Acc ( Vector Rank ) zeroes = A.fill ( shape ranks ) 0.0 addUpdates ' : : Acc ( Vector Rank ) - > Acc ( Vector Z ) - > Acc ( Vector Update ) - > Acc ( Vector Rank ) addUpdates ' = const . addUpdates in A.collect $ A.foldSeqFlatten addUpdates ' zeroes $ A.mapSeq ( ( contribution sizes ranks ) ) ( A.toSeq ( Z : . Split ) ( use p ) ) - contribution contribution sizes ranks link = let (from, to) = unlift link :: (Exp PageId, Exp PageId) in lift (to, ranks ! index1 (A.fromIntegral from) / A.fromIntegral (sizes ! index1 (A.fromIntegral from))) :: Exp Update addUpdates addUpdates parRanks updates = let (to, contr) = A.unzip updates in A.permute (+) parRanks (index1 . A.fromIntegral . (to !)) contr stepRankSeq :: PageGraph stepRankSeq p sizes ranks = let zeroes :: Acc (Vector Rank) zeroes = A.fill (shape ranks) 0.0 addUpdates' :: Acc (Vector Rank) -> Acc (Vector Z) -> Acc (Vector Update) -> Acc (Vector Rank) addUpdates' = const . addUpdates in A.collect $ A.foldSeqFlatten addUpdates' zeroes $ A.mapSeq (A.map (contribution sizes ranks)) (A.toSeq (Z :. Split) (use p)) | Perform one iteration step for the internal Page Rank algorithm . stepRank stepRank links sizes ranks parRanks = let pageCount = A.size sizes contribution :: Acc (Vector Float) contribution = A.generate (A.shape links) (\ix -> let (from, _) = unlift $ links ! ix :: (Exp PageId, Exp PageId) in ranks ! index1 (A.fromIntegral from) / A.fromIntegral (sizes ! index1 (A.fromIntegral from))) ranks' = A.permute (+) parRanks (\ix -> let (_, to) = unlift $ links ! ix :: (Exp PageId, Exp PageId) in Just_ (index1 (A.fromIntegral to))) contribution in ranks'
d46f3c246a93a9491c07d13a16288ae68867cdfa99e7e81bc2836d0ad30d0502
softlab-ntua/bencherl
comm_server.erl
2008 - 2011 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % -2.0 % % Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. @doc : CommLayer : Management of comm_connection processes . @author < > @author < > @version $ I d : comm_server.erl 2576 2011 - 12 - 16 18:01:34Z $ -module(comm_server). -author(''). -author(''). -vsn('$Id: comm_server.erl 2576 2011-12-16 18:01:34Z $'). -behaviour(gen_component). -include("scalaris.hrl"). -ifdef(with_export_type_support). -export_type([tcp_port/0]). -endif. -export([start_link/1, init/1, on/2]). -export([send/3, tcp_options/1]). -export([unregister_connection/2, create_connection/4, set_local_address/2, get_local_address_port/0]). -type tcp_port() :: 0..65535. -type message() :: {create_connection, Address::inet:ip_address(), Port::tcp_port(), Socket::inet:socket() | notconnected, Channel::main | prio, Client::pid()} | {send, Address::inet:ip_address(), Port::tcp_port(), Pid::pid(), Message::comm:message()} | {unregister_conn, Address::inet:ip_address(), Port::tcp_port(), Client::pid()} | {set_local_address, Address::inet:ip_address(), Port::tcp_port(), Client::pid()}. %% be startable via supervisor, use gen_component -spec start_link(pid_groups:groupname()) -> {ok, pid()}. start_link(CommLayerGroup) -> gen_component:start_link(?MODULE, fun ?MODULE:on/2, [], [ {erlang_register, ?MODULE}, {pid_groups_join_as, CommLayerGroup, ?MODULE} ]). %% @doc initialize: return initial state. -spec init([]) -> null. init([]) -> _ = ets:new(?MODULE, [set, protected, named_table]), _State = null. -spec tcp_options(Channel::main | prio) -> [{term(), term()}]. tcp_options(Channel) -> TcpSendTimeout = case Channel of prio -> config:read(tcp_send_timeout); main -> infinity end, [{active, once}, {nodelay, true}, {keepalive, true}, {reuseaddr, true}, {delay_send, true}, {send_timeout, TcpSendTimeout}]. -spec send({inet:ip_address(), tcp_port(), pid()}, term(), comm:send_options()) -> ok. send({Address, Port, Pid}, Message, Options) -> ?MODULE ! {send, Address, Port, Pid, Message, Options}, ok. @doc Synchronous call to create ( or get ) a connection for the given Address+Port using Socket . -spec create_connection(Address::inet:ip_address(), Port::tcp_port(), Socket::inet:socket(), Channel::main | prio) -> pid(). create_connection(Address, Port, Socket, Channel) -> ?MODULE ! {create_connection, Address, Port, Socket, Channel, self()}, receive {create_connection_done, ConnPid} -> ConnPid end. %% @doc Synchronous call to de-register a connection with the comm server. -spec unregister_connection(inet:ip_address(), tcp_port()) -> ok. unregister_connection(Adress, Port) -> ?MODULE ! {unregister_conn, Adress, Port, self()}, receive {unregister_conn_done} -> ok end. -spec set_local_address(inet:ip_address() | undefined, tcp_port()) -> ok. set_local_address(Address, Port) -> ?MODULE ! {set_local_address, Address, Port, self()}, receive {set_local_address_done} -> ok end. %% @doc returns the local ip address and port -spec(get_local_address_port() -> {inet:ip_address(), tcp_port()} | undefined | {undefined, tcp_port()}). get_local_address_port() -> case erlang:get(local_address_port) of undefined -> case ets:lookup(?MODULE, local_address_port) of [{local_address_port, Value = {undefined, _MyPort}}] -> Value; [{local_address_port, Value}] -> erlang:put(local_address_port, Value), Value; [] -> undefined end; Value -> Value end. %% @doc Gets or creates a connection for the given Socket or address/port. %% Only a single connection to any IP+Port combination is created. %% Socket is the initial socket when a connection needs to be created. -spec get_connection(Address::inet:ip_address(), Port::tcp_port(), Socket::inet:socket() | notconnected, Channel::main | prio, Dir::'rcv' | 'send' | 'both') -> pid(). get_connection(Address, Port, Socket, Channel, Dir) -> case erlang:get({Address, Port, Channel, Dir}) of undefined -> start Erlang process responsible for the connection {ok, ConnPid} = comm_connection:start_link( pid_groups:my_groupname(), Address, Port, Socket, Channel, Dir), erlang:put({Address, Port, Channel, Dir}, ConnPid), ok; ConnPid -> ok end, ConnPid. %% @doc message handler -spec on(message(), State::null) -> null. on({create_connection, Address, Port, Socket, Channel, Client}, State) -> % helper for comm_acceptor as we need to synchronise the creation of % connections in order to prevent multiple connections to/from a single IP {Channel, Dir} = case Channel of main -> {main, 'rcv'}; prio -> {prio, 'both'} end, ConnPid = get_connection(Address, Port, Socket, Channel, Dir), Client ! {create_connection_done, ConnPid}, State; on({send, Address, Port, Pid, Message, Options}, State) -> {Channel, Dir} = case proplists:get_value(channel, Options, main) of main -> {main, 'send'}; prio -> {prio, 'both'} end, ConnPid = get_connection(Address, Port, notconnected, Channel, Dir), ConnPid ! {send, Pid, Message, Options}, State; on({unregister_conn, Address, Port, Client}, State) -> erlang:erase({Address, Port}), Client ! {unregister_conn_done}, State; on({set_local_address, Address, Port, Client}, State) -> ets:insert(?MODULE, {local_address_port, {Address, Port}}), Client ! {set_local_address_done}, State.
null
https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/scalaris/src/comm_layer/comm_server.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. be startable via supervisor, use gen_component @doc initialize: return initial state. @doc Synchronous call to de-register a connection with the comm server. @doc returns the local ip address and port @doc Gets or creates a connection for the given Socket or address/port. Only a single connection to any IP+Port combination is created. Socket is the initial socket when a connection needs to be created. @doc message handler helper for comm_acceptor as we need to synchronise the creation of connections in order to prevent multiple connections to/from a single IP
2008 - 2011 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @doc : CommLayer : Management of comm_connection processes . @author < > @author < > @version $ I d : comm_server.erl 2576 2011 - 12 - 16 18:01:34Z $ -module(comm_server). -author(''). -author(''). -vsn('$Id: comm_server.erl 2576 2011-12-16 18:01:34Z $'). -behaviour(gen_component). -include("scalaris.hrl"). -ifdef(with_export_type_support). -export_type([tcp_port/0]). -endif. -export([start_link/1, init/1, on/2]). -export([send/3, tcp_options/1]). -export([unregister_connection/2, create_connection/4, set_local_address/2, get_local_address_port/0]). -type tcp_port() :: 0..65535. -type message() :: {create_connection, Address::inet:ip_address(), Port::tcp_port(), Socket::inet:socket() | notconnected, Channel::main | prio, Client::pid()} | {send, Address::inet:ip_address(), Port::tcp_port(), Pid::pid(), Message::comm:message()} | {unregister_conn, Address::inet:ip_address(), Port::tcp_port(), Client::pid()} | {set_local_address, Address::inet:ip_address(), Port::tcp_port(), Client::pid()}. -spec start_link(pid_groups:groupname()) -> {ok, pid()}. start_link(CommLayerGroup) -> gen_component:start_link(?MODULE, fun ?MODULE:on/2, [], [ {erlang_register, ?MODULE}, {pid_groups_join_as, CommLayerGroup, ?MODULE} ]). -spec init([]) -> null. init([]) -> _ = ets:new(?MODULE, [set, protected, named_table]), _State = null. -spec tcp_options(Channel::main | prio) -> [{term(), term()}]. tcp_options(Channel) -> TcpSendTimeout = case Channel of prio -> config:read(tcp_send_timeout); main -> infinity end, [{active, once}, {nodelay, true}, {keepalive, true}, {reuseaddr, true}, {delay_send, true}, {send_timeout, TcpSendTimeout}]. -spec send({inet:ip_address(), tcp_port(), pid()}, term(), comm:send_options()) -> ok. send({Address, Port, Pid}, Message, Options) -> ?MODULE ! {send, Address, Port, Pid, Message, Options}, ok. @doc Synchronous call to create ( or get ) a connection for the given Address+Port using Socket . -spec create_connection(Address::inet:ip_address(), Port::tcp_port(), Socket::inet:socket(), Channel::main | prio) -> pid(). create_connection(Address, Port, Socket, Channel) -> ?MODULE ! {create_connection, Address, Port, Socket, Channel, self()}, receive {create_connection_done, ConnPid} -> ConnPid end. -spec unregister_connection(inet:ip_address(), tcp_port()) -> ok. unregister_connection(Adress, Port) -> ?MODULE ! {unregister_conn, Adress, Port, self()}, receive {unregister_conn_done} -> ok end. -spec set_local_address(inet:ip_address() | undefined, tcp_port()) -> ok. set_local_address(Address, Port) -> ?MODULE ! {set_local_address, Address, Port, self()}, receive {set_local_address_done} -> ok end. -spec(get_local_address_port() -> {inet:ip_address(), tcp_port()} | undefined | {undefined, tcp_port()}). get_local_address_port() -> case erlang:get(local_address_port) of undefined -> case ets:lookup(?MODULE, local_address_port) of [{local_address_port, Value = {undefined, _MyPort}}] -> Value; [{local_address_port, Value}] -> erlang:put(local_address_port, Value), Value; [] -> undefined end; Value -> Value end. -spec get_connection(Address::inet:ip_address(), Port::tcp_port(), Socket::inet:socket() | notconnected, Channel::main | prio, Dir::'rcv' | 'send' | 'both') -> pid(). get_connection(Address, Port, Socket, Channel, Dir) -> case erlang:get({Address, Port, Channel, Dir}) of undefined -> start Erlang process responsible for the connection {ok, ConnPid} = comm_connection:start_link( pid_groups:my_groupname(), Address, Port, Socket, Channel, Dir), erlang:put({Address, Port, Channel, Dir}, ConnPid), ok; ConnPid -> ok end, ConnPid. -spec on(message(), State::null) -> null. on({create_connection, Address, Port, Socket, Channel, Client}, State) -> {Channel, Dir} = case Channel of main -> {main, 'rcv'}; prio -> {prio, 'both'} end, ConnPid = get_connection(Address, Port, Socket, Channel, Dir), Client ! {create_connection_done, ConnPid}, State; on({send, Address, Port, Pid, Message, Options}, State) -> {Channel, Dir} = case proplists:get_value(channel, Options, main) of main -> {main, 'send'}; prio -> {prio, 'both'} end, ConnPid = get_connection(Address, Port, notconnected, Channel, Dir), ConnPid ! {send, Pid, Message, Options}, State; on({unregister_conn, Address, Port, Client}, State) -> erlang:erase({Address, Port}), Client ! {unregister_conn_done}, State; on({set_local_address, Address, Port, Client}, State) -> ets:insert(?MODULE, {local_address_port, {Address, Port}}), Client ! {set_local_address_done}, State.
d39101ccfb71cd10e9cdb3464ea0e37a280bedd7c2523266128235b52f42a34e
CLowcay/hgbc
CommandLine.hs
module HGBC.Config.CommandLine ( Options (..), parse, ) where import qualified Data.Text as T import HGBC.Config.Decode (decodeColorCorrection, decodeMode) import qualified Machine.GBC.Color as Color import Machine.GBC.Mode (EmulatorMode) import Options.Applicative (Parser, ParserInfo, action, auto, completeWith, eitherReader, execParser, fullDesc, header, help, helper, info, long, metavar, option, str, strArgument, switch, value, (<**>)) data Options = Options { debugMode :: Bool, debugPort :: Maybe Int, noSound :: Bool, noVsync :: Bool, stats :: Bool, scale :: Maybe Int, speed :: Maybe Double, colorCorrection :: Maybe Color.CorrectionMode, bootROM :: Maybe FilePath, mode :: Maybe EmulatorMode, filename :: FilePath } parse :: IO Options parse = execParser description description :: ParserInfo Options description = info (commandLine <**> helper) (fullDesc <> header "An emulator and debugger for the Gameboy Color") commandLine :: Parser Options commandLine = Options <$> switch (long "debug" <> help "Enable the debugger") <*> option (Just <$> auto) ( long "debug-port" <> value Nothing <> metavar "DEBUG_PORT" <> help "Port to run the debug server on" ) <*> switch (long "no-sound" <> help "Disable audio output") <*> switch (long "no-vsync" <> help "Disable vertical retrace syncrhonization") <*> switch (long "stats" <> help "Show performance information on stdout") <*> option (Just <$> auto) ( long "scale" <> value Nothing <> metavar "SCALE" <> help "Default scale factor for video output" ) <*> option (Just <$> auto) ( long "speed" <> value Nothing <> metavar "SPEED" <> help "Speed as a fraction of normal speed" ) <*> option (Just <$> eitherReader (decodeColorCorrection . T.pack)) ( long "color-correction" <> value Nothing <> metavar "CORRECTION_MODE" <> completeWith ["none", "default"] <> help "Color correction mode. Recognized values are 'none' and 'default'" ) <*> option (Just <$> str) ( long "boot-rom" <> value Nothing <> metavar "BOOT_FILE" <> action "file" <> help "Use an optional boot ROM" ) <*> option (eitherReader (decodeMode . T.pack)) ( long "mode" <> value Nothing <> metavar "MODE" <> completeWith ["dmg", "cgb", "auto"] <> help "Graphics mode at startup. Can be 'dmg', 'cgb', or 'auto' (default)." ) <*> strArgument (metavar "ROM_FILE" <> action "file" <> help "The ROM file to run")
null
https://raw.githubusercontent.com/CLowcay/hgbc/76a8cf91f3c3b160eadf019bc8fc75ef07601c2f/main/src/HGBC/Config/CommandLine.hs
haskell
module HGBC.Config.CommandLine ( Options (..), parse, ) where import qualified Data.Text as T import HGBC.Config.Decode (decodeColorCorrection, decodeMode) import qualified Machine.GBC.Color as Color import Machine.GBC.Mode (EmulatorMode) import Options.Applicative (Parser, ParserInfo, action, auto, completeWith, eitherReader, execParser, fullDesc, header, help, helper, info, long, metavar, option, str, strArgument, switch, value, (<**>)) data Options = Options { debugMode :: Bool, debugPort :: Maybe Int, noSound :: Bool, noVsync :: Bool, stats :: Bool, scale :: Maybe Int, speed :: Maybe Double, colorCorrection :: Maybe Color.CorrectionMode, bootROM :: Maybe FilePath, mode :: Maybe EmulatorMode, filename :: FilePath } parse :: IO Options parse = execParser description description :: ParserInfo Options description = info (commandLine <**> helper) (fullDesc <> header "An emulator and debugger for the Gameboy Color") commandLine :: Parser Options commandLine = Options <$> switch (long "debug" <> help "Enable the debugger") <*> option (Just <$> auto) ( long "debug-port" <> value Nothing <> metavar "DEBUG_PORT" <> help "Port to run the debug server on" ) <*> switch (long "no-sound" <> help "Disable audio output") <*> switch (long "no-vsync" <> help "Disable vertical retrace syncrhonization") <*> switch (long "stats" <> help "Show performance information on stdout") <*> option (Just <$> auto) ( long "scale" <> value Nothing <> metavar "SCALE" <> help "Default scale factor for video output" ) <*> option (Just <$> auto) ( long "speed" <> value Nothing <> metavar "SPEED" <> help "Speed as a fraction of normal speed" ) <*> option (Just <$> eitherReader (decodeColorCorrection . T.pack)) ( long "color-correction" <> value Nothing <> metavar "CORRECTION_MODE" <> completeWith ["none", "default"] <> help "Color correction mode. Recognized values are 'none' and 'default'" ) <*> option (Just <$> str) ( long "boot-rom" <> value Nothing <> metavar "BOOT_FILE" <> action "file" <> help "Use an optional boot ROM" ) <*> option (eitherReader (decodeMode . T.pack)) ( long "mode" <> value Nothing <> metavar "MODE" <> completeWith ["dmg", "cgb", "auto"] <> help "Graphics mode at startup. Can be 'dmg', 'cgb', or 'auto' (default)." ) <*> strArgument (metavar "ROM_FILE" <> action "file" <> help "The ROM file to run")
9f12f6871bed6739091c7cadab3a2305fc626b953b5b8e79113103c81e4067de
caisah/sicp-exercises-and-examples
ex.3.67.scm
;; Modify the pairs procedure so that (pairs integers integers) will produce the stream ;; of all pairs of integers (i, j) (without the condition i<=j). Hint: You will need to ;; mix in an additional stream. (define integers (cons-stream 0 (stream-map 1+ integers))) (define (all-pairs s t) (cons-stream (list (stream-car s) (stream-car t)) (interleave (interleave (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (all-pairs (stream-cdr s) (stream-cdr t))) (stream-map (lambda (x) (list x (stream-car t))) (stream-cdr s))))) (define a (all-pairs integers integers)) (stream-ref a 2) (stream-ref a 3) (stream-ref a 4) (stream-ref a 5)
null
https://raw.githubusercontent.com/caisah/sicp-exercises-and-examples/605c698d7495aa3474c2b6edcd1312cb16c5b5cb/3.5.3-exploiting_the_stream_paradigm/ex.3.67.scm
scheme
Modify the pairs procedure so that (pairs integers integers) will produce the stream of all pairs of integers (i, j) (without the condition i<=j). Hint: You will need to mix in an additional stream.
(define integers (cons-stream 0 (stream-map 1+ integers))) (define (all-pairs s t) (cons-stream (list (stream-car s) (stream-car t)) (interleave (interleave (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (all-pairs (stream-cdr s) (stream-cdr t))) (stream-map (lambda (x) (list x (stream-car t))) (stream-cdr s))))) (define a (all-pairs integers integers)) (stream-ref a 2) (stream-ref a 3) (stream-ref a 4) (stream-ref a 5)
677c4dcb3a257f9f1843ff787ba76563ef308a95b4fc6ae300fe4a3aea1fb5b1
ivanjovanovic/sicp
e-1.5.scm
Exercise 1.5 has invented a test to determine whether the interpreter he is faced with is using applicative - order evaluation or normal - order evaluation . He defines the following two procedures : ; self referencing procedure that will end up in endless recursion when evaluated. (define (p) (p)) test is procedure that has 2 branches based on input x so we can choose if we evaluate the second branch . (define (test x y) (if (= x 0) 0 y)) ; then he tests the interpreter with ( test 0 ( p ) ) ; Normal order evaluation: ; In this case operand (p) will not be evaluated until it is needed by ; some primitive operation and thus this will return 0 as result. ; ; Applicative order evaluation: ; In this case operand y will be by default evaluated and then it will ; end up in recursion since (p) points to itself.
null
https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/1.1/e-1.5.scm
scheme
self referencing procedure that will end up in endless recursion when evaluated. then he tests the interpreter with Normal order evaluation: In this case operand (p) will not be evaluated until it is needed by some primitive operation and thus this will return 0 as result. Applicative order evaluation: In this case operand y will be by default evaluated and then it will end up in recursion since (p) points to itself.
Exercise 1.5 has invented a test to determine whether the interpreter he is faced with is using applicative - order evaluation or normal - order evaluation . He defines the following two procedures : (define (p) (p)) test is procedure that has 2 branches based on input x so we can choose if we evaluate the second branch . (define (test x y) (if (= x 0) 0 y)) ( test 0 ( p ) )
2b83ce8f57b0b5c14bd5b842224079acf6e9de3fe8fa2c0483e348ef645cdc30
EFanZh/EOPL-Exercises
exercise-1.20.rkt
#lang eopl Exercise 1.20 [ ★ ] ( count - occurrences ) returns the number of occurrences of s in slist . ;; ;; > (count-occurrences 'x '((f x) y (((x z) x)))) 3 ;; > (count-occurrences 'x '((f x) y (((x z) () x)))) 3 ;; > (count-occurrences 'w '((f x) y (((x z) x)))) ;; 0 (define count-occurrences-sexp (lambda (s sexp) (if (symbol? sexp) (if (eqv? sexp s) 1 0) (count-occurrences s sexp)))) (define count-occurrences (lambda (s slist) (if (null? slist) 0 (+ (count-occurrences-sexp s (car slist)) (count-occurrences s (cdr slist)))))) (provide count-occurrences)
null
https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/solutions/exercise-1.20.rkt
racket
> (count-occurrences 'x '((f x) y (((x z) x)))) > (count-occurrences 'x '((f x) y (((x z) () x)))) > (count-occurrences 'w '((f x) y (((x z) x)))) 0
#lang eopl Exercise 1.20 [ ★ ] ( count - occurrences ) returns the number of occurrences of s in slist . 3 3 (define count-occurrences-sexp (lambda (s sexp) (if (symbol? sexp) (if (eqv? sexp s) 1 0) (count-occurrences s sexp)))) (define count-occurrences (lambda (s slist) (if (null? slist) 0 (+ (count-occurrences-sexp s (car slist)) (count-occurrences s (cdr slist)))))) (provide count-occurrences)
0784a40fae4985377eed2e1ab7690f7dc35897cdd864401824398618b832e7c8
geophf/1HaskellADay
Solution.hs
module Y2020.M10.D15.Solution where import Y2020.M10.D12.Solution -- for Country-type import Y2020.M10.D14.Solution {-- ... -- sigh. But, of course, now that I have ContinentMap, I don't want that. I want to know the continent of a given country, and I don't want to do a reverse lookup to find that continent. What I'm really after is this: --} import Data.Tuple (swap) import Data.Map (Map) import qualified Data.Map as Map type CountryMap = Map Country Continent -- But, given ContinentMap, it's 'easy' to derive CountryMap Today 's problem is for you to do so . countryMap :: ContinentMap -> CountryMap countryMap = Map.fromList . map swap . concat . map sequence . Map.toList - What is the size of the ContinentMap ? > > > countriesByContinent ( workingDir + + cbc ) > > > let m = it > > > Map.size m 7 What is the size of the CountryMap ? > > > let = countryMap m > > > Map.size cm 231 > > > take 5 $ Map.toList cm [ ( " Afghanistan","Asia"),("Albania ( Shqip\235ria)","Europe"),("Algeria","Africa " ) , ( " Andorra","Europe"),("Angola","Africa " ) ] - What is the size of the ContinentMap? >>> countriesByContinent (workingDir ++ cbc) >>> let m = it >>> Map.size m 7 What is the size of the CountryMap? >>> let cm = countryMap m >>> Map.size cm 231 >>> take 5 $ Map.toList cm [("Afghanistan","Asia"),("Albania (Shqip\235ria)","Europe"),("Algeria","Africa"), ("Andorra","Europe"),("Angola","Africa")] --}
null
https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2020/M10/D15/Solution.hs
haskell
for Country-type - ... -- sigh. But, of course, now that I have ContinentMap, I don't want that. I want to know the continent of a given country, and I don't want to do a reverse lookup to find that continent. What I'm really after is this: - But, given ContinentMap, it's 'easy' to derive CountryMap }
module Y2020.M10.D15.Solution where import Y2020.M10.D14.Solution import Data.Tuple (swap) import Data.Map (Map) import qualified Data.Map as Map type CountryMap = Map Country Continent Today 's problem is for you to do so . countryMap :: ContinentMap -> CountryMap countryMap = Map.fromList . map swap . concat . map sequence . Map.toList - What is the size of the ContinentMap ? > > > countriesByContinent ( workingDir + + cbc ) > > > let m = it > > > Map.size m 7 What is the size of the CountryMap ? > > > let = countryMap m > > > Map.size cm 231 > > > take 5 $ Map.toList cm [ ( " Afghanistan","Asia"),("Albania ( Shqip\235ria)","Europe"),("Algeria","Africa " ) , ( " Andorra","Europe"),("Angola","Africa " ) ] - What is the size of the ContinentMap? >>> countriesByContinent (workingDir ++ cbc) >>> let m = it >>> Map.size m 7 What is the size of the CountryMap? >>> let cm = countryMap m >>> Map.size cm 231 >>> take 5 $ Map.toList cm [("Afghanistan","Asia"),("Albania (Shqip\235ria)","Europe"),("Algeria","Africa"), ("Andorra","Europe"),("Angola","Africa")]
0bc7be0be16747c22592b9809d079f6801251adc1c686847895a440262d0d38a
Enecuum/Node
Validation.hs
# LANGUAGE DuplicateRecordFields # # LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # module Enecuum.TestData.Validation where import Enecuum.Prelude import Data.Validation import Control.Lens import qualified Enecuum.Language as L data ValidationRequest = ValidRequest | InvalidRequest deriving (Show, Eq, Generic, ToJSON, FromJSON) newtype ValidationResponse = ValidationResponse (Either [Text] Text) deriving (Show, Eq, Generic, Newtype, ToJSON, FromJSON) verifyRequest :: ValidationRequest -> Validation [Text] Text verifyRequest ValidRequest = _Success # "correct" verifyRequest InvalidRequest = _Failure # ["invalid"] makeResponse :: Validation [Text] Text -> ValidationResponse makeResponse = ValidationResponse . toEither acceptValidationRequest :: ValidationRequest -> L.NodeL ValidationResponse acceptValidationRequest req = pure $ makeResponse $ verifyRequest req
null
https://raw.githubusercontent.com/Enecuum/Node/3dfbc6a39c84bd45dd5f4b881e067044dde0153a/test/test-framework/Enecuum/TestData/Validation.hs
haskell
# LANGUAGE DeriveAnyClass #
# LANGUAGE DuplicateRecordFields # # LANGUAGE AllowAmbiguousTypes # # LANGUAGE DeriveGeneric # module Enecuum.TestData.Validation where import Enecuum.Prelude import Data.Validation import Control.Lens import qualified Enecuum.Language as L data ValidationRequest = ValidRequest | InvalidRequest deriving (Show, Eq, Generic, ToJSON, FromJSON) newtype ValidationResponse = ValidationResponse (Either [Text] Text) deriving (Show, Eq, Generic, Newtype, ToJSON, FromJSON) verifyRequest :: ValidationRequest -> Validation [Text] Text verifyRequest ValidRequest = _Success # "correct" verifyRequest InvalidRequest = _Failure # ["invalid"] makeResponse :: Validation [Text] Text -> ValidationResponse makeResponse = ValidationResponse . toEither acceptValidationRequest :: ValidationRequest -> L.NodeL ValidationResponse acceptValidationRequest req = pure $ makeResponse $ verifyRequest req
0a8d304c61f54eba7d62258776b510b73fca32bf80e4a05b380e36249c61a79e
TrustInSoft/tis-kernel
Aorai_test.ml
(**************************************************************************) (* *) This file is part of . (* *) is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 (* *) is released under GPLv2 (* *) (**************************************************************************) (* Small script to test that the code generated by aorai can be parsed again * by frama-c. *) open Kernel module StdString = String include Plugin.Register (struct let name = "aorai testing module" let shortname = "aorai-test" let help = "utility script for aorai regtests" end) module TestNumber = Zero (struct let option_name = "-aorai-test-number" let help = "test number when multiple tests are run over the same file" let arg_name = "n" end) module InternalWpShare = Empty_string( struct let option_name = "-aorai-test-wp-share" let help = "use custom wp share dir (when in internal plugin mode)" let arg_name = "dir" end) let tmpfile = ref (Filename.temp_file "aorai_test" ".i") let tmpfile_set = ref false let ok = ref false let () = at_exit (fun () -> if Debug.get () >= 1 || not !ok then result "Keeping temp file %s" !tmpfile else try Sys.remove !tmpfile with Sys_error _ -> ()) let set_tmpfile _ l = if not !tmpfile_set then begin let name = List.hd l in let name = Filename.basename name in let name = Filename.chop_extension name in tmpfile := (Filename.get_temp_dir_name()) ^ "/aorai_" ^ name ^ (string_of_int (TestNumber.get())) ^ ".i"; tmpfile_set := true end let () = Kernel.Files.add_set_hook set_tmpfile let is_suffix suf str = let lsuf = StdString.length suf in let lstr = StdString.length str in if lstr <= lsuf then false else let estr = StdString.sub str (lstr - lsuf) lsuf in estr = suf let extend () = let myrun = let run = !Db.Toplevel.run in fun f -> let my_project = Project.create "Reparsing" in let wp_compute_kf = Dynamic.get ~plugin:"Wp" "wp_compute_kf" Datatype.( func3 (option Kernel_function.ty) (list string) (list string) unit) in let check_auto_func kf = let name = Kernel_function.get_name kf in if Kernel_function.is_definition kf && (is_suffix "_pre_func" name || is_suffix "_post_func" name) then wp_compute_kf (Some kf) [] [] in run f; let chan = open_out !tmpfile in let fmt = Format.formatter_of_out_channel chan in File.pretty_ast ~prj:(Project.from_unique_name "aorai") ~fmt (); close_out chan; let selection = State_selection.singleton InternalWpShare.self in Project.copy ~selection my_project; Project.set_current my_project; Files.append_after [ !tmpfile ]; Constfold.off (); Ast.compute(); let wp_share = InternalWpShare.get() in if wp_share <> "" then Dynamic.Parameter.String.set "-wp-share" wp_share; Dynamic.Parameter.Int.set "-wp-verbose" 0; Globals.Functions.iter check_auto_func; File.pretty_ast (); ok:=true (* no error, we can erase the file *) in Db.Toplevel.run := myrun let () = extend ()
null
https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/aorai/tests/aorai/Aorai_test.ml
ocaml
************************************************************************ ************************************************************************ Small script to test that the code generated by aorai can be parsed again * by frama-c. no error, we can erase the file
This file is part of . is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 is released under GPLv2 open Kernel module StdString = String include Plugin.Register (struct let name = "aorai testing module" let shortname = "aorai-test" let help = "utility script for aorai regtests" end) module TestNumber = Zero (struct let option_name = "-aorai-test-number" let help = "test number when multiple tests are run over the same file" let arg_name = "n" end) module InternalWpShare = Empty_string( struct let option_name = "-aorai-test-wp-share" let help = "use custom wp share dir (when in internal plugin mode)" let arg_name = "dir" end) let tmpfile = ref (Filename.temp_file "aorai_test" ".i") let tmpfile_set = ref false let ok = ref false let () = at_exit (fun () -> if Debug.get () >= 1 || not !ok then result "Keeping temp file %s" !tmpfile else try Sys.remove !tmpfile with Sys_error _ -> ()) let set_tmpfile _ l = if not !tmpfile_set then begin let name = List.hd l in let name = Filename.basename name in let name = Filename.chop_extension name in tmpfile := (Filename.get_temp_dir_name()) ^ "/aorai_" ^ name ^ (string_of_int (TestNumber.get())) ^ ".i"; tmpfile_set := true end let () = Kernel.Files.add_set_hook set_tmpfile let is_suffix suf str = let lsuf = StdString.length suf in let lstr = StdString.length str in if lstr <= lsuf then false else let estr = StdString.sub str (lstr - lsuf) lsuf in estr = suf let extend () = let myrun = let run = !Db.Toplevel.run in fun f -> let my_project = Project.create "Reparsing" in let wp_compute_kf = Dynamic.get ~plugin:"Wp" "wp_compute_kf" Datatype.( func3 (option Kernel_function.ty) (list string) (list string) unit) in let check_auto_func kf = let name = Kernel_function.get_name kf in if Kernel_function.is_definition kf && (is_suffix "_pre_func" name || is_suffix "_post_func" name) then wp_compute_kf (Some kf) [] [] in run f; let chan = open_out !tmpfile in let fmt = Format.formatter_of_out_channel chan in File.pretty_ast ~prj:(Project.from_unique_name "aorai") ~fmt (); close_out chan; let selection = State_selection.singleton InternalWpShare.self in Project.copy ~selection my_project; Project.set_current my_project; Files.append_after [ !tmpfile ]; Constfold.off (); Ast.compute(); let wp_share = InternalWpShare.get() in if wp_share <> "" then Dynamic.Parameter.String.set "-wp-share" wp_share; Dynamic.Parameter.Int.set "-wp-verbose" 0; Globals.Functions.iter check_auto_func; File.pretty_ast (); in Db.Toplevel.run := myrun let () = extend ()
32d2d9b6b18dab27becc25be544b3717b0f5dc044cc66f1cd42c74faa061b3c2
KitchenTableCoders/immutable-stack-2
figwheel.clj
(require '[figwheel-sidecar.repl :as r] '[figwheel-sidecar.repl-api :as ra]) (ra/start-figwheel! {:figwheel-options {} :build-ids ["dev"] :all-builds [{:id "dev" :figwheel true :source-paths ["src"] :compiler {:main 'breakout2.core :asset-path "js" :output-to "resources/public/js/main.js" :output-dir "resources/public/js" :verbose true}}]}) (ra/cljs-repl)
null
https://raw.githubusercontent.com/KitchenTableCoders/immutable-stack-2/12beb62b09d3025645d83778a6963ef763ad5b96/om/breakout2/script/figwheel.clj
clojure
(require '[figwheel-sidecar.repl :as r] '[figwheel-sidecar.repl-api :as ra]) (ra/start-figwheel! {:figwheel-options {} :build-ids ["dev"] :all-builds [{:id "dev" :figwheel true :source-paths ["src"] :compiler {:main 'breakout2.core :asset-path "js" :output-to "resources/public/js/main.js" :output-dir "resources/public/js" :verbose true}}]}) (ra/cljs-repl)
7b8d8d767f422f31bdd45f04d766e6a00489289fd4850fae4ebb64e20efffeb0
fulcrologic/guardrails
utils.cljc
Copyright ( c ) . All rights reserved . ;; The use and distribution terms for this software are covered by the Eclipse Public License 2.0 ( -2.0/ ) ;; which can be found in the file LICENSE 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 ^:no-doc com.fulcrologic.guardrails.utils #?(:cljs (:require-macros com.fulcrologic.guardrails.utils)) (:require #?(:clj [clojure.stacktrace :as st]) [clojure.walk :as walk])) (defn cljs-env? [env] (boolean (:ns env))) (defn get-ns-meta [env] (if (cljs-env? env) (or (meta *ns*) (some-> env :ns :meta)) (meta *ns*))) (defn get-ns-name [env] (if (cljs-env? env) (or (.-name *ns*) (some-> env :ns :name)) (.-name *ns*))) (defn clj->cljs ([form] (clj->cljs form true)) ([form strip-core-ns] (let [ns-replacements (cond-> {"clojure.core" "cljs.core" "clojure.test" "cljs.test" "clojure.spec.alpha" "cljs.spec.alpha" "clojure.spec.test.alpha" "cljs.spec.test.alpha" "orchestra.spec.test" "orchestra-cljs.spec.test" "clojure.spec.gen.alpha" "cljs.spec.gen.alpha"} strip-core-ns (merge {"clojure.core" nil "cljs.core" nil})) replace-namespace #(if-not (qualified-symbol? %) % (let [nspace (namespace %)] (if (contains? ns-replacements nspace) (symbol (get ns-replacements nspace) (name %)) %)))] (walk/postwalk replace-namespace form)))) (defn get-file-position [env] (if (cljs-env? env) (let [{:keys [line column]} env] (str line ":" column)) TODO implement for clojure nil)) (defn get-call-context ([env] (get-call-context env nil)) ([env label] (str (when label (str label " – ")) (get-ns-name env) ":" (get-file-position env)))) (defn gen-exception [env msg] `(throw (~(if (cljs-env? env) 'js/Error. 'Exception.) ~msg))) (defn devtools-config-override [] `(let [current-config# (~'devtools.prefs/get-prefs) overrides# {:max-print-level 4 :min-expandable-sequable-count-for-well-known-types 2} left-adjust# (str "margin-left: -17px;")] (merge current-config# (into overrides# (for [k# [:header-style] :let [v# (get current-config# k#)]] [k# (str v# left-adjust#)]))))) (defn map-vals [f m] (if (nil? m) {} (reduce-kv (fn [m k v] (assoc m k (f v))) m m))) (defn map-keys [f m] (if (nil? m) {} (reduce-kv (fn [m k v] (assoc m (f k) v)) {} m))) (let [p! persistent!, t transient] ; Note `mapv`-like nil->{} semantics (defn filter-vals [pred m] (if (nil? m) {} (p! (reduce-kv (fn [m k v] (if (pred v) m (dissoc! m k))) (t m) m))))) #?(:clj (defn atom? [x] (instance? clojure.lang.Atom x)) :cljs (defn ^boolean atom? [x] (instance? Atom x))) #?(:clj (defn compiling-cljs? "Return truthy iff currently generating Cljs code." [] (when-let [n (find-ns 'cljs.analyzer)] (when-let [v (ns-resolve n '*cljs-file*)] @v)))) (defn stacktrace ([err] (stacktrace err nil)) ([err opts] #?(:cljs (str err) :clj (with-out-str (st/print-stack-trace err))))) (defn report-problem [message] #?(:clj (.println System/err message) :cljs (js/console.error message))) (defn report-exception [e message] #?(:clj (.println System/err (str message \n (.getMessage ^Exception e) "\n" (stacktrace e))) :cljs (js/console.error message e)))
null
https://raw.githubusercontent.com/fulcrologic/guardrails/17b47a7869314efbffe5dbe0c0daea7c30ed9006/src/main/com/fulcrologic/guardrails/utils.cljc
clojure
The use and distribution terms for this software are covered by the which can be found in the file LICENSE 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. Note `mapv`-like nil->{} semantics
Copyright ( c ) . All rights reserved . Eclipse Public License 2.0 ( -2.0/ ) (ns ^:no-doc com.fulcrologic.guardrails.utils #?(:cljs (:require-macros com.fulcrologic.guardrails.utils)) (:require #?(:clj [clojure.stacktrace :as st]) [clojure.walk :as walk])) (defn cljs-env? [env] (boolean (:ns env))) (defn get-ns-meta [env] (if (cljs-env? env) (or (meta *ns*) (some-> env :ns :meta)) (meta *ns*))) (defn get-ns-name [env] (if (cljs-env? env) (or (.-name *ns*) (some-> env :ns :name)) (.-name *ns*))) (defn clj->cljs ([form] (clj->cljs form true)) ([form strip-core-ns] (let [ns-replacements (cond-> {"clojure.core" "cljs.core" "clojure.test" "cljs.test" "clojure.spec.alpha" "cljs.spec.alpha" "clojure.spec.test.alpha" "cljs.spec.test.alpha" "orchestra.spec.test" "orchestra-cljs.spec.test" "clojure.spec.gen.alpha" "cljs.spec.gen.alpha"} strip-core-ns (merge {"clojure.core" nil "cljs.core" nil})) replace-namespace #(if-not (qualified-symbol? %) % (let [nspace (namespace %)] (if (contains? ns-replacements nspace) (symbol (get ns-replacements nspace) (name %)) %)))] (walk/postwalk replace-namespace form)))) (defn get-file-position [env] (if (cljs-env? env) (let [{:keys [line column]} env] (str line ":" column)) TODO implement for clojure nil)) (defn get-call-context ([env] (get-call-context env nil)) ([env label] (str (when label (str label " – ")) (get-ns-name env) ":" (get-file-position env)))) (defn gen-exception [env msg] `(throw (~(if (cljs-env? env) 'js/Error. 'Exception.) ~msg))) (defn devtools-config-override [] `(let [current-config# (~'devtools.prefs/get-prefs) overrides# {:max-print-level 4 :min-expandable-sequable-count-for-well-known-types 2} left-adjust# (str "margin-left: -17px;")] (merge current-config# (into overrides# (for [k# [:header-style] :let [v# (get current-config# k#)]] [k# (str v# left-adjust#)]))))) (defn map-vals [f m] (if (nil? m) {} (reduce-kv (fn [m k v] (assoc m k (f v))) m m))) (defn map-keys [f m] (if (nil? m) {} (reduce-kv (fn [m k v] (assoc m (f k) v)) {} m))) (defn filter-vals [pred m] (if (nil? m) {} (p! (reduce-kv (fn [m k v] (if (pred v) m (dissoc! m k))) (t m) m))))) #?(:clj (defn atom? [x] (instance? clojure.lang.Atom x)) :cljs (defn ^boolean atom? [x] (instance? Atom x))) #?(:clj (defn compiling-cljs? "Return truthy iff currently generating Cljs code." [] (when-let [n (find-ns 'cljs.analyzer)] (when-let [v (ns-resolve n '*cljs-file*)] @v)))) (defn stacktrace ([err] (stacktrace err nil)) ([err opts] #?(:cljs (str err) :clj (with-out-str (st/print-stack-trace err))))) (defn report-problem [message] #?(:clj (.println System/err message) :cljs (js/console.error message))) (defn report-exception [e message] #?(:clj (.println System/err (str message \n (.getMessage ^Exception e) "\n" (stacktrace e))) :cljs (js/console.error message e)))
c1455ee82f5113950f7aab25fb8f8714af90ea94d6afeff878a25bc70b05468d
rd--/hsc3
bufAllpassC.help.hs
-- bufAllpassC ; filtered decaying noise bursts let b = localBufId 'α' 1 44100 d = dustId 'β' ar 1 n = whiteNoiseId 'γ' ar x = decay d 0.2 * n * 0.25 in bufAllpassC b x 0.25 6
null
https://raw.githubusercontent.com/rd--/hsc3/60cb422f0e2049f00b7e15076b2667b85ad8f638/Help/Ugen/bufAllpassC.help.hs
haskell
bufAllpassC ; filtered decaying noise bursts
let b = localBufId 'α' 1 44100 d = dustId 'β' ar 1 n = whiteNoiseId 'γ' ar x = decay d 0.2 * n * 0.25 in bufAllpassC b x 0.25 6
8316f36b279d2da82ac7437e6707f7774538c12cfdcfe6b733d912c934fff6d6
ucsd-progsys/dsolve
assume.ml
let f x = assume (x > 0); assert (x > 0)
null
https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/postests/assume.ml
ocaml
let f x = assume (x > 0); assert (x > 0)
32d4b28715751a9969757b9a40cefd7b9281a274957e562dc963a5e99857ac0c
marick/structural-typing
pseudopreds.clj
(ns ^:no-doc structural-typing.guts.preds.pseudopreds "Preds that are used througout" (:use structural-typing.clojure.core) (:require [structural-typing.guts.preds.wrap :as wrap] [structural-typing.guts.expred :as expred] [structural-typing.guts.explanations :as explain] [structural-typing.assist.oopsie :as oopsie] [such.metadata :as meta] [defprecated.core :as depr]) (:refer-clojure :exclude [any?])) (defn rejects-missing-and-nil [pred] (meta/assoc pred ::special-case-handling {:reject-missing? true, :reject-nil? true})) (defn rejects-missing [pred] (meta/assoc pred ::special-case-handling {:reject-missing? true, :reject-nil? false})) (defn rejects-nil [pred] (meta/assoc pred ::special-case-handling {:reject-missing? false, :reject-nil? true})) (defn special-case-handling [pred] (meta/get pred ::special-case-handling {})) (defn rejects-missing-and-nil? [x] (= (special-case-handling x) {:reject-missing? true, :reject-nil? true})) (def reject-nil "False iff the value given is `nil`. By default, type descriptions allow nil values, following Clojure's lead. To reject nils, use type descriptions like this: (type! :X {:a [reject-nil string?]}) ... or, when checking types directly: (built-like [string? reject-nil] nil) See also [[reject-missing]] and [[required-path]]. " (-> (expred/->ExPred (comp not nil?) "reject-nil" #(explain/err:selector-at-nil (oopsie/friendly-path %))) (wrap/lift-expred [:check-nil]) rejects-nil)) (def required-path "False iff a key/path does not exist or has value `nil`. See also [[reject-missing]] and [[reject-nil]]. " ;; When called directly, it can't get a 'missing' value, so it's the same ;; as `reject-nil`. (-> (expred/->ExPred (comp not nil?) "required-path" #(explain/err:selector-at-nil (oopsie/friendly-path %))) (wrap/lift-expred [:check-nil]) rejects-missing-and-nil)) (def reject-missing "This appears in a predicate list, but it is never called directly. Its appearance means that cases like the following are rejected: user=> (type! :X {:a [string? reject-missing]}) user=> (built-like :X {}) :a does not exist user=> (type! :X {[(RANGE 0 3)] [reject-missing even?]}) user=> (built-like :X []) [0] does not exist [1] does not exist [2] does not exist See also [[reject-nil]] and [[required-path]]. " (-> (expred/->ExPred (constantly true) "reject-missing" #(boom! "reject-missing should never fail: %s")) (wrap/lift-expred []) rejects-missing)) (defn max-rejection [preds] (let [raw-data (map special-case-handling preds)] {:reject-nil? (any? true? (map :reject-nil? raw-data)) :reject-missing? (any? true? (map :reject-missing? raw-data))})) (defn without-pseudopreds [preds] (remove #(let [rejectionism (special-case-handling %)] (or (:reject-nil? rejectionism) (:reject-missing? rejectionism))) preds)) (def not-nil-fn "False iff a key/path does not exist or has value `nil`. Note: At some point in the future, this library might make a distinction between a `nil` value and a missing key. If so, this predicate will change to reject `nil` values but be silent about missing keys. See [[required-path]]. " (-> (expred/->ExPred (comp not nil?) "not-nil" #(format "%s is nil, and that makes Sir Tony Hoare sad" (oopsie/friendly-path %))) (wrap/lift-expred [:check-nil]) rejects-nil)) (depr/defn not-nil "Deprecated in favor of `required-path`, `reject-nil`, or `reject-missing`." [& args] {:deprecated {:in "2.0.0" :use-instead reject-nil}} (apply not-nil-fn args))
null
https://raw.githubusercontent.com/marick/structural-typing/9b44c303dcfd4a72c5b75ec7a1114687c809fba1/src/structural_typing/guts/preds/pseudopreds.clj
clojure
When called directly, it can't get a 'missing' value, so it's the same as `reject-nil`.
(ns ^:no-doc structural-typing.guts.preds.pseudopreds "Preds that are used througout" (:use structural-typing.clojure.core) (:require [structural-typing.guts.preds.wrap :as wrap] [structural-typing.guts.expred :as expred] [structural-typing.guts.explanations :as explain] [structural-typing.assist.oopsie :as oopsie] [such.metadata :as meta] [defprecated.core :as depr]) (:refer-clojure :exclude [any?])) (defn rejects-missing-and-nil [pred] (meta/assoc pred ::special-case-handling {:reject-missing? true, :reject-nil? true})) (defn rejects-missing [pred] (meta/assoc pred ::special-case-handling {:reject-missing? true, :reject-nil? false})) (defn rejects-nil [pred] (meta/assoc pred ::special-case-handling {:reject-missing? false, :reject-nil? true})) (defn special-case-handling [pred] (meta/get pred ::special-case-handling {})) (defn rejects-missing-and-nil? [x] (= (special-case-handling x) {:reject-missing? true, :reject-nil? true})) (def reject-nil "False iff the value given is `nil`. By default, type descriptions allow nil values, following Clojure's lead. To reject nils, use type descriptions like this: (type! :X {:a [reject-nil string?]}) ... or, when checking types directly: (built-like [string? reject-nil] nil) See also [[reject-missing]] and [[required-path]]. " (-> (expred/->ExPred (comp not nil?) "reject-nil" #(explain/err:selector-at-nil (oopsie/friendly-path %))) (wrap/lift-expred [:check-nil]) rejects-nil)) (def required-path "False iff a key/path does not exist or has value `nil`. See also [[reject-missing]] and [[reject-nil]]. " (-> (expred/->ExPred (comp not nil?) "required-path" #(explain/err:selector-at-nil (oopsie/friendly-path %))) (wrap/lift-expred [:check-nil]) rejects-missing-and-nil)) (def reject-missing "This appears in a predicate list, but it is never called directly. Its appearance means that cases like the following are rejected: user=> (type! :X {:a [string? reject-missing]}) user=> (built-like :X {}) :a does not exist user=> (type! :X {[(RANGE 0 3)] [reject-missing even?]}) user=> (built-like :X []) [0] does not exist [1] does not exist [2] does not exist See also [[reject-nil]] and [[required-path]]. " (-> (expred/->ExPred (constantly true) "reject-missing" #(boom! "reject-missing should never fail: %s")) (wrap/lift-expred []) rejects-missing)) (defn max-rejection [preds] (let [raw-data (map special-case-handling preds)] {:reject-nil? (any? true? (map :reject-nil? raw-data)) :reject-missing? (any? true? (map :reject-missing? raw-data))})) (defn without-pseudopreds [preds] (remove #(let [rejectionism (special-case-handling %)] (or (:reject-nil? rejectionism) (:reject-missing? rejectionism))) preds)) (def not-nil-fn "False iff a key/path does not exist or has value `nil`. Note: At some point in the future, this library might make a distinction between a `nil` value and a missing key. If so, this predicate will change to reject `nil` values but be silent about missing keys. See [[required-path]]. " (-> (expred/->ExPred (comp not nil?) "not-nil" #(format "%s is nil, and that makes Sir Tony Hoare sad" (oopsie/friendly-path %))) (wrap/lift-expred [:check-nil]) rejects-nil)) (depr/defn not-nil "Deprecated in favor of `required-path`, `reject-nil`, or `reject-missing`." [& args] {:deprecated {:in "2.0.0" :use-instead reject-nil}} (apply not-nil-fn args))
4b141b9590f5b4192c733b3aff9bf02b9467061dd466af3de5cfdc73bd4b0b8c
youngker/clj-opengrok
core_test.clj
(ns clj-opengrok.core-test (:require [clojure.test :refer :all] [clj-opengrok.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
null
https://raw.githubusercontent.com/youngker/clj-opengrok/120881cab93a2d88384bef99219e99c53c3307d1/test/clj_opengrok/core_test.clj
clojure
(ns clj-opengrok.core-test (:require [clojure.test :refer :all] [clj-opengrok.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
f692710954de82fbf087ee7bd8b224ee7cea878aa7bd44c6e060ca9a4e4d997d
haskell-tools/haskell-tools
Extensions.hs
-- all extensions should be matched module Language.Haskell.Tools.Refactor.Utils.Extensions ( module Language.Haskell.Tools.Refactor.Utils.Extensions , GHC.Extension(..) ) where import Data.Maybe (fromMaybe) import Control.Reference ((^.), _1, _2, _3) import Language.Haskell.Extension (KnownExtension(..)) import qualified Language.Haskell.TH.LanguageExtensions as GHC (Extension(..)) -- | Expands an extension into all the extensions it implies (keeps original as well) expandExtension :: GHC.Extension -> [GHC.Extension] expandExtension ext = ext : implied where fst' = (^. _1) :: (a,b,c) -> a snd' = (^. _2) :: (a,b,c) -> b trd' = (^. _3) :: (a,b,c) -> c implied = map trd' . filter snd' . filter ((== ext) . fst') $ impliedXFlags -- | Replaces deprecated extensions with their new counterpart replaceDeprecated :: GHC.Extension -> GHC.Extension replaceDeprecated GHC.NullaryTypeClasses = GHC.MultiParamTypeClasses replaceDeprecated x = x turnOn = True turnOff = False impliedXFlags :: [(GHC.Extension, Bool, GHC.Extension)] impliedXFlags = [ (GHC.RankNTypes, turnOn, GHC.ExplicitForAll) , (GHC.ScopedTypeVariables, turnOn, GHC.ExplicitForAll) , (GHC.LiberalTypeSynonyms, turnOn, GHC.ExplicitForAll) , (GHC.ExistentialQuantification, turnOn, GHC.ExplicitForAll) , (GHC.FlexibleInstances, turnOn, GHC.TypeSynonymInstances) , (GHC.FunctionalDependencies, turnOn, GHC.MultiParamTypeClasses) , (GHC.MultiParamTypeClasses, turnOn, GHC.ConstrainedClassMethods) , (GHC.TypeFamilyDependencies, turnOn, GHC.TypeFamilies) , (GHC.RebindableSyntax, turnOff, GHC.ImplicitPrelude) , (GHC.GADTs, turnOn, GHC.GADTSyntax) , (GHC.GADTs, turnOn, GHC.MonoLocalBinds) , (GHC.TypeFamilies, turnOn, GHC.MonoLocalBinds) , (GHC.TypeFamilies, turnOn, GHC.KindSignatures) , (GHC.PolyKinds, turnOn, GHC.KindSignatures) , (GHC.TypeInType, turnOn, GHC.DataKinds) , (GHC.TypeInType, turnOn, GHC.PolyKinds) , (GHC.TypeInType, turnOn, GHC.KindSignatures) , (GHC.AutoDeriveTypeable, turnOn, GHC.DeriveDataTypeable) , (GHC.TypeFamilies, turnOn, GHC.ExplicitNamespaces) , (GHC.TypeOperators, turnOn, GHC.ExplicitNamespaces) , (GHC.ImpredicativeTypes, turnOn, GHC.RankNTypes) , (GHC.RecordWildCards, turnOn, GHC.DisambiguateRecordFields) , (GHC.ParallelArrays, turnOn, GHC.ParallelListComp) , (GHC.JavaScriptFFI, turnOn, GHC.InterruptibleFFI) , (GHC.DeriveTraversable, turnOn, GHC.DeriveFunctor) , (GHC.DeriveTraversable, turnOn, GHC.DeriveFoldable) , (GHC.DuplicateRecordFields, turnOn, GHC.DisambiguateRecordFields) , (GHC.TemplateHaskell, turnOn, GHC.TemplateHaskellQuotes) , (GHC.Strict, turnOn, GHC.StrictData) ] | These extensions ' GHC representation name differs from their actual name irregularExtensions :: [(String,String)] irregularExtensions = [ ("CPP", "Cpp") , ("Rank2Types", "RankNTypes") , ("NamedFieldPuns", "RecordPuns") , ("GeneralisedNewtypeDeriving", "GeneralizedNewtypeDeriving") ] | extensions . -- This is a helper function for parsing extensions This way we can say . canonExt@ to parse any extension string canonExt :: String -> String canonExt x = fromMaybe x (lookup x irregularExtensions) | Serializes the extension 's GHC name into its LANGUAGE pragma name . -- Should be always used in composition with show (@seriealizeExt . show@) -- when refactoring extensions. -- This function also replaces depracted extensions with their new versions. serializeExt :: String -> String serializeExt "Cpp" = "CPP" serializeExt "Rank2Types" = "RankNTypes" serializeExt "RecordPuns" = "NamedFieldPuns" serializeExt x = x * Mapping of extensions to their GHC counterpart | Map the cabal extensions to the ones that GHC recognizes translateExtension AllowAmbiguousTypes = Just GHC.AllowAmbiguousTypes translateExtension ApplicativeDo = Just GHC.ApplicativeDo translateExtension Arrows = Just GHC.Arrows translateExtension AutoDeriveTypeable = Just GHC.AutoDeriveTypeable translateExtension BangPatterns = Just GHC.BangPatterns translateExtension BinaryLiterals = Just GHC.BinaryLiterals translateExtension CApiFFI = Just GHC.CApiFFI translateExtension ConstrainedClassMethods = Just GHC.ConstrainedClassMethods translateExtension ConstraintKinds = Just GHC.ConstraintKinds translateExtension CPP = Just GHC.Cpp translateExtension DataKinds = Just GHC.DataKinds translateExtension DatatypeContexts = Just GHC.DatatypeContexts translateExtension DefaultSignatures = Just GHC.DefaultSignatures translateExtension DeriveAnyClass = Just GHC.DeriveAnyClass translateExtension DeriveDataTypeable = Just GHC.DeriveDataTypeable translateExtension DeriveFoldable = Just GHC.DeriveFoldable translateExtension DeriveFunctor = Just GHC.DeriveFunctor translateExtension DeriveGeneric = Just GHC.DeriveGeneric translateExtension DeriveLift = Just GHC.DeriveLift translateExtension DeriveTraversable = Just GHC.DeriveTraversable translateExtension DisambiguateRecordFields = Just GHC.DisambiguateRecordFields translateExtension DoAndIfThenElse = Just GHC.DoAndIfThenElse translateExtension DoRec = Just GHC.RecursiveDo translateExtension DuplicateRecordFields = Just GHC.DuplicateRecordFields translateExtension EmptyCase = Just GHC.EmptyCase translateExtension EmptyDataDecls = Just GHC.EmptyDataDecls translateExtension ExistentialQuantification = Just GHC.ExistentialQuantification translateExtension ExplicitForAll = Just GHC.ExplicitForAll translateExtension ExplicitNamespaces = Just GHC.ExplicitNamespaces translateExtension ExtendedDefaultRules = Just GHC.ExtendedDefaultRules translateExtension FlexibleContexts = Just GHC.FlexibleContexts translateExtension FlexibleInstances = Just GHC.FlexibleInstances translateExtension ForeignFunctionInterface = Just GHC.ForeignFunctionInterface translateExtension FunctionalDependencies = Just GHC.FunctionalDependencies translateExtension GADTs = Just GHC.GADTs translateExtension GADTSyntax = Just GHC.GADTSyntax translateExtension GeneralizedNewtypeDeriving = Just GHC.GeneralizedNewtypeDeriving translateExtension GHCForeignImportPrim = Just GHC.GHCForeignImportPrim translateExtension ImplicitParams = Just GHC.ImplicitParams translateExtension ImplicitPrelude = Just GHC.ImplicitPrelude translateExtension ImpredicativeTypes = Just GHC.ImpredicativeTypes translateExtension IncoherentInstances = Just GHC.IncoherentInstances translateExtension InstanceSigs = Just GHC.InstanceSigs translateExtension InterruptibleFFI = Just GHC.InterruptibleFFI translateExtension JavaScriptFFI = Just GHC.JavaScriptFFI translateExtension KindSignatures = Just GHC.KindSignatures translateExtension LambdaCase = Just GHC.LambdaCase translateExtension LiberalTypeSynonyms = Just GHC.LiberalTypeSynonyms translateExtension MagicHash = Just GHC.MagicHash translateExtension MonadComprehensions = Just GHC.MonadComprehensions translateExtension MonadFailDesugaring = Just GHC.MonadFailDesugaring translateExtension MonoLocalBinds = Just GHC.MonoLocalBinds translateExtension MonomorphismRestriction = Just GHC.MonomorphismRestriction translateExtension MonoPatBinds = Just GHC.MonoPatBinds translateExtension MultiParamTypeClasses = Just GHC.MultiParamTypeClasses translateExtension MultiWayIf = Just GHC.MultiWayIf translateExtension NamedFieldPuns = Just GHC.RecordPuns translateExtension NamedWildCards = Just GHC.NamedWildCards translateExtension NegativeLiterals = Just GHC.NegativeLiterals translateExtension NondecreasingIndentation = Just GHC.NondecreasingIndentation translateExtension NPlusKPatterns = Just GHC.NPlusKPatterns translateExtension NullaryTypeClasses = Just GHC.NullaryTypeClasses translateExtension NumDecimals = Just GHC.NumDecimals translateExtension OverlappingInstances = Just GHC.OverlappingInstances translateExtension OverloadedLabels = Just GHC.OverloadedLabels translateExtension OverloadedLists = Just GHC.OverloadedLists translateExtension OverloadedStrings = Just GHC.OverloadedStrings translateExtension PackageImports = Just GHC.PackageImports translateExtension ParallelArrays = Just GHC.ParallelArrays translateExtension ParallelListComp = Just GHC.ParallelListComp translateExtension PartialTypeSignatures = Just GHC.PartialTypeSignatures translateExtension PatternGuards = Just GHC.PatternGuards translateExtension PatternSignatures = Just GHC.PatternSynonyms translateExtension PatternSynonyms = Just GHC.PatternSynonyms translateExtension PolyKinds = Just GHC.PolyKinds translateExtension PostfixOperators = Just GHC.PostfixOperators translateExtension QuasiQuotes = Just GHC.QuasiQuotes translateExtension RankNTypes = Just GHC.RankNTypes translateExtension RebindableSyntax = Just GHC.RebindableSyntax translateExtension RecordPuns = Just GHC.RecordPuns translateExtension RecordWildCards = Just GHC.RecordWildCards translateExtension RecursiveDo = Just GHC.RecursiveDo translateExtension RelaxedPolyRec = Just GHC.RelaxedPolyRec flip xopt_unset translateExtension RoleAnnotations = Just GHC.RoleAnnotations translateExtension ScopedTypeVariables = Just GHC.ScopedTypeVariables translateExtension StandaloneDeriving = Just GHC.StandaloneDeriving translateExtension StaticPointers = Just GHC.StaticPointers translateExtension Strict = Just GHC.Strict translateExtension StrictData = Just GHC.StrictData translateExtension TemplateHaskell = Just GHC.TemplateHaskell translateExtension TemplateHaskellQuotes = Just GHC.TemplateHaskellQuotes translateExtension TraditionalRecordSyntax = Just GHC.TraditionalRecordSyntax translateExtension TransformListComp = Just GHC.TransformListComp translateExtension TupleSections = Just GHC.TupleSections translateExtension TypeApplications = Just GHC.TypeApplications translateExtension TypeFamilies = Just GHC.TypeFamilies translateExtension TypeFamilyDependencies = Just GHC.TypeFamilyDependencies translateExtension TypeInType = Just GHC.TypeInType translateExtension TypeOperators = Just GHC.TypeOperators translateExtension TypeSynonymInstances = Just GHC.TypeSynonymInstances translateExtension UnboxedTuples = Just GHC.UnboxedTuples translateExtension UndecidableInstances = Just GHC.UndecidableInstances translateExtension UndecidableSuperClasses = Just GHC.UndecidableSuperClasses translateExtension UnicodeSyntax = Just GHC.UnicodeSyntax translateExtension UnliftedFFITypes = Just GHC.UnliftedFFITypes translateExtension ViewPatterns = Just GHC.ViewPatterns \df - > df { GHC.safeHaskell = GHC.Sf_Safe } \df - > df { GHC.safeHaskell = GHC.Sf_Safe } translateExtension Trustworthy = Nothing -- \df -> df { GHC.safeHaskell = GHC.Sf_Trustworthy } \df - > df { GHC.safeHaskell = GHC.Sf_Unsafe } translateExtension Rank2Types = Just GHC.RankNTypes translateExtension PolymorphicComponents = Just GHC.RankNTypes translateExtension Generics = Nothing -- it does nothing, deprecated extension translateExtension NewQualifiedOperators = Nothing -- it does nothing, deprecated extension not in GHC not in GHC not in GHC not in GHC
null
https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/refactor/Language/Haskell/Tools/Refactor/Utils/Extensions.hs
haskell
all extensions should be matched | Expands an extension into all the extensions it implies (keeps original as well) | Replaces deprecated extensions with their new counterpart This is a helper function for parsing extensions Should be always used in composition with show (@seriealizeExt . show@) when refactoring extensions. This function also replaces depracted extensions with their new versions. \df -> df { GHC.safeHaskell = GHC.Sf_Trustworthy } it does nothing, deprecated extension it does nothing, deprecated extension
module Language.Haskell.Tools.Refactor.Utils.Extensions ( module Language.Haskell.Tools.Refactor.Utils.Extensions , GHC.Extension(..) ) where import Data.Maybe (fromMaybe) import Control.Reference ((^.), _1, _2, _3) import Language.Haskell.Extension (KnownExtension(..)) import qualified Language.Haskell.TH.LanguageExtensions as GHC (Extension(..)) expandExtension :: GHC.Extension -> [GHC.Extension] expandExtension ext = ext : implied where fst' = (^. _1) :: (a,b,c) -> a snd' = (^. _2) :: (a,b,c) -> b trd' = (^. _3) :: (a,b,c) -> c implied = map trd' . filter snd' . filter ((== ext) . fst') $ impliedXFlags replaceDeprecated :: GHC.Extension -> GHC.Extension replaceDeprecated GHC.NullaryTypeClasses = GHC.MultiParamTypeClasses replaceDeprecated x = x turnOn = True turnOff = False impliedXFlags :: [(GHC.Extension, Bool, GHC.Extension)] impliedXFlags = [ (GHC.RankNTypes, turnOn, GHC.ExplicitForAll) , (GHC.ScopedTypeVariables, turnOn, GHC.ExplicitForAll) , (GHC.LiberalTypeSynonyms, turnOn, GHC.ExplicitForAll) , (GHC.ExistentialQuantification, turnOn, GHC.ExplicitForAll) , (GHC.FlexibleInstances, turnOn, GHC.TypeSynonymInstances) , (GHC.FunctionalDependencies, turnOn, GHC.MultiParamTypeClasses) , (GHC.MultiParamTypeClasses, turnOn, GHC.ConstrainedClassMethods) , (GHC.TypeFamilyDependencies, turnOn, GHC.TypeFamilies) , (GHC.RebindableSyntax, turnOff, GHC.ImplicitPrelude) , (GHC.GADTs, turnOn, GHC.GADTSyntax) , (GHC.GADTs, turnOn, GHC.MonoLocalBinds) , (GHC.TypeFamilies, turnOn, GHC.MonoLocalBinds) , (GHC.TypeFamilies, turnOn, GHC.KindSignatures) , (GHC.PolyKinds, turnOn, GHC.KindSignatures) , (GHC.TypeInType, turnOn, GHC.DataKinds) , (GHC.TypeInType, turnOn, GHC.PolyKinds) , (GHC.TypeInType, turnOn, GHC.KindSignatures) , (GHC.AutoDeriveTypeable, turnOn, GHC.DeriveDataTypeable) , (GHC.TypeFamilies, turnOn, GHC.ExplicitNamespaces) , (GHC.TypeOperators, turnOn, GHC.ExplicitNamespaces) , (GHC.ImpredicativeTypes, turnOn, GHC.RankNTypes) , (GHC.RecordWildCards, turnOn, GHC.DisambiguateRecordFields) , (GHC.ParallelArrays, turnOn, GHC.ParallelListComp) , (GHC.JavaScriptFFI, turnOn, GHC.InterruptibleFFI) , (GHC.DeriveTraversable, turnOn, GHC.DeriveFunctor) , (GHC.DeriveTraversable, turnOn, GHC.DeriveFoldable) , (GHC.DuplicateRecordFields, turnOn, GHC.DisambiguateRecordFields) , (GHC.TemplateHaskell, turnOn, GHC.TemplateHaskellQuotes) , (GHC.Strict, turnOn, GHC.StrictData) ] | These extensions ' GHC representation name differs from their actual name irregularExtensions :: [(String,String)] irregularExtensions = [ ("CPP", "Cpp") , ("Rank2Types", "RankNTypes") , ("NamedFieldPuns", "RecordPuns") , ("GeneralisedNewtypeDeriving", "GeneralizedNewtypeDeriving") ] | extensions . This way we can say . canonExt@ to parse any extension string canonExt :: String -> String canonExt x = fromMaybe x (lookup x irregularExtensions) | Serializes the extension 's GHC name into its LANGUAGE pragma name . serializeExt :: String -> String serializeExt "Cpp" = "CPP" serializeExt "Rank2Types" = "RankNTypes" serializeExt "RecordPuns" = "NamedFieldPuns" serializeExt x = x * Mapping of extensions to their GHC counterpart | Map the cabal extensions to the ones that GHC recognizes translateExtension AllowAmbiguousTypes = Just GHC.AllowAmbiguousTypes translateExtension ApplicativeDo = Just GHC.ApplicativeDo translateExtension Arrows = Just GHC.Arrows translateExtension AutoDeriveTypeable = Just GHC.AutoDeriveTypeable translateExtension BangPatterns = Just GHC.BangPatterns translateExtension BinaryLiterals = Just GHC.BinaryLiterals translateExtension CApiFFI = Just GHC.CApiFFI translateExtension ConstrainedClassMethods = Just GHC.ConstrainedClassMethods translateExtension ConstraintKinds = Just GHC.ConstraintKinds translateExtension CPP = Just GHC.Cpp translateExtension DataKinds = Just GHC.DataKinds translateExtension DatatypeContexts = Just GHC.DatatypeContexts translateExtension DefaultSignatures = Just GHC.DefaultSignatures translateExtension DeriveAnyClass = Just GHC.DeriveAnyClass translateExtension DeriveDataTypeable = Just GHC.DeriveDataTypeable translateExtension DeriveFoldable = Just GHC.DeriveFoldable translateExtension DeriveFunctor = Just GHC.DeriveFunctor translateExtension DeriveGeneric = Just GHC.DeriveGeneric translateExtension DeriveLift = Just GHC.DeriveLift translateExtension DeriveTraversable = Just GHC.DeriveTraversable translateExtension DisambiguateRecordFields = Just GHC.DisambiguateRecordFields translateExtension DoAndIfThenElse = Just GHC.DoAndIfThenElse translateExtension DoRec = Just GHC.RecursiveDo translateExtension DuplicateRecordFields = Just GHC.DuplicateRecordFields translateExtension EmptyCase = Just GHC.EmptyCase translateExtension EmptyDataDecls = Just GHC.EmptyDataDecls translateExtension ExistentialQuantification = Just GHC.ExistentialQuantification translateExtension ExplicitForAll = Just GHC.ExplicitForAll translateExtension ExplicitNamespaces = Just GHC.ExplicitNamespaces translateExtension ExtendedDefaultRules = Just GHC.ExtendedDefaultRules translateExtension FlexibleContexts = Just GHC.FlexibleContexts translateExtension FlexibleInstances = Just GHC.FlexibleInstances translateExtension ForeignFunctionInterface = Just GHC.ForeignFunctionInterface translateExtension FunctionalDependencies = Just GHC.FunctionalDependencies translateExtension GADTs = Just GHC.GADTs translateExtension GADTSyntax = Just GHC.GADTSyntax translateExtension GeneralizedNewtypeDeriving = Just GHC.GeneralizedNewtypeDeriving translateExtension GHCForeignImportPrim = Just GHC.GHCForeignImportPrim translateExtension ImplicitParams = Just GHC.ImplicitParams translateExtension ImplicitPrelude = Just GHC.ImplicitPrelude translateExtension ImpredicativeTypes = Just GHC.ImpredicativeTypes translateExtension IncoherentInstances = Just GHC.IncoherentInstances translateExtension InstanceSigs = Just GHC.InstanceSigs translateExtension InterruptibleFFI = Just GHC.InterruptibleFFI translateExtension JavaScriptFFI = Just GHC.JavaScriptFFI translateExtension KindSignatures = Just GHC.KindSignatures translateExtension LambdaCase = Just GHC.LambdaCase translateExtension LiberalTypeSynonyms = Just GHC.LiberalTypeSynonyms translateExtension MagicHash = Just GHC.MagicHash translateExtension MonadComprehensions = Just GHC.MonadComprehensions translateExtension MonadFailDesugaring = Just GHC.MonadFailDesugaring translateExtension MonoLocalBinds = Just GHC.MonoLocalBinds translateExtension MonomorphismRestriction = Just GHC.MonomorphismRestriction translateExtension MonoPatBinds = Just GHC.MonoPatBinds translateExtension MultiParamTypeClasses = Just GHC.MultiParamTypeClasses translateExtension MultiWayIf = Just GHC.MultiWayIf translateExtension NamedFieldPuns = Just GHC.RecordPuns translateExtension NamedWildCards = Just GHC.NamedWildCards translateExtension NegativeLiterals = Just GHC.NegativeLiterals translateExtension NondecreasingIndentation = Just GHC.NondecreasingIndentation translateExtension NPlusKPatterns = Just GHC.NPlusKPatterns translateExtension NullaryTypeClasses = Just GHC.NullaryTypeClasses translateExtension NumDecimals = Just GHC.NumDecimals translateExtension OverlappingInstances = Just GHC.OverlappingInstances translateExtension OverloadedLabels = Just GHC.OverloadedLabels translateExtension OverloadedLists = Just GHC.OverloadedLists translateExtension OverloadedStrings = Just GHC.OverloadedStrings translateExtension PackageImports = Just GHC.PackageImports translateExtension ParallelArrays = Just GHC.ParallelArrays translateExtension ParallelListComp = Just GHC.ParallelListComp translateExtension PartialTypeSignatures = Just GHC.PartialTypeSignatures translateExtension PatternGuards = Just GHC.PatternGuards translateExtension PatternSignatures = Just GHC.PatternSynonyms translateExtension PatternSynonyms = Just GHC.PatternSynonyms translateExtension PolyKinds = Just GHC.PolyKinds translateExtension PostfixOperators = Just GHC.PostfixOperators translateExtension QuasiQuotes = Just GHC.QuasiQuotes translateExtension RankNTypes = Just GHC.RankNTypes translateExtension RebindableSyntax = Just GHC.RebindableSyntax translateExtension RecordPuns = Just GHC.RecordPuns translateExtension RecordWildCards = Just GHC.RecordWildCards translateExtension RecursiveDo = Just GHC.RecursiveDo translateExtension RelaxedPolyRec = Just GHC.RelaxedPolyRec flip xopt_unset translateExtension RoleAnnotations = Just GHC.RoleAnnotations translateExtension ScopedTypeVariables = Just GHC.ScopedTypeVariables translateExtension StandaloneDeriving = Just GHC.StandaloneDeriving translateExtension StaticPointers = Just GHC.StaticPointers translateExtension Strict = Just GHC.Strict translateExtension StrictData = Just GHC.StrictData translateExtension TemplateHaskell = Just GHC.TemplateHaskell translateExtension TemplateHaskellQuotes = Just GHC.TemplateHaskellQuotes translateExtension TraditionalRecordSyntax = Just GHC.TraditionalRecordSyntax translateExtension TransformListComp = Just GHC.TransformListComp translateExtension TupleSections = Just GHC.TupleSections translateExtension TypeApplications = Just GHC.TypeApplications translateExtension TypeFamilies = Just GHC.TypeFamilies translateExtension TypeFamilyDependencies = Just GHC.TypeFamilyDependencies translateExtension TypeInType = Just GHC.TypeInType translateExtension TypeOperators = Just GHC.TypeOperators translateExtension TypeSynonymInstances = Just GHC.TypeSynonymInstances translateExtension UnboxedTuples = Just GHC.UnboxedTuples translateExtension UndecidableInstances = Just GHC.UndecidableInstances translateExtension UndecidableSuperClasses = Just GHC.UndecidableSuperClasses translateExtension UnicodeSyntax = Just GHC.UnicodeSyntax translateExtension UnliftedFFITypes = Just GHC.UnliftedFFITypes translateExtension ViewPatterns = Just GHC.ViewPatterns \df - > df { GHC.safeHaskell = GHC.Sf_Safe } \df - > df { GHC.safeHaskell = GHC.Sf_Safe } \df - > df { GHC.safeHaskell = GHC.Sf_Unsafe } translateExtension Rank2Types = Just GHC.RankNTypes translateExtension PolymorphicComponents = Just GHC.RankNTypes not in GHC not in GHC not in GHC not in GHC
e931c6f8963cc50adcc66470509da6871ce0c9e3068e620a5344759c4eaef1d7
ghcjs/ghcjs-dom
HTMLMenuElement.hs
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} module GHCJS.DOM.JSFFI.Generated.HTMLMenuElement (js_setCompact, setCompact, js_getCompact, getCompact, HTMLMenuElement(..), gTypeHTMLMenuElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import qualified Prelude (error) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull, jsUndefined) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import Data.Maybe (fromJust) import Data.Traversable (mapM) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"compact\"] = $2;" js_setCompact :: HTMLMenuElement -> Bool -> IO () | < -US/docs/Web/API/HTMLMenuElement.compact Mozilla HTMLMenuElement.compact documentation > setCompact :: (MonadIO m) => HTMLMenuElement -> Bool -> m () setCompact self val = liftIO (js_setCompact self val) foreign import javascript unsafe "($1[\"compact\"] ? 1 : 0)" js_getCompact :: HTMLMenuElement -> IO Bool | < -US/docs/Web/API/HTMLMenuElement.compact Mozilla HTMLMenuElement.compact documentation > getCompact :: (MonadIO m) => HTMLMenuElement -> m Bool getCompact self = liftIO (js_getCompact self)
null
https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/HTMLMenuElement.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # module GHCJS.DOM.JSFFI.Generated.HTMLMenuElement (js_setCompact, setCompact, js_getCompact, getCompact, HTMLMenuElement(..), gTypeHTMLMenuElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import qualified Prelude (error) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull, jsUndefined) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import Data.Maybe (fromJust) import Data.Traversable (mapM) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"compact\"] = $2;" js_setCompact :: HTMLMenuElement -> Bool -> IO () | < -US/docs/Web/API/HTMLMenuElement.compact Mozilla HTMLMenuElement.compact documentation > setCompact :: (MonadIO m) => HTMLMenuElement -> Bool -> m () setCompact self val = liftIO (js_setCompact self val) foreign import javascript unsafe "($1[\"compact\"] ? 1 : 0)" js_getCompact :: HTMLMenuElement -> IO Bool | < -US/docs/Web/API/HTMLMenuElement.compact Mozilla HTMLMenuElement.compact documentation > getCompact :: (MonadIO m) => HTMLMenuElement -> m Bool getCompact self = liftIO (js_getCompact self)
1f72b36726595038edbcb3520b02b4e46b8ff3a50ece2ec4132af5a5287975d1
spurious/chibi-scheme-mirror
numeric-tests.scm
;; these tests are only valid if chibi-scheme is compiled with full ;; numeric support (USE_BIGNUMS, USE_FLONUMS and USE_MATH) (cond-expand (modules (import (only (chibi test) test-begin test test-end))) (else #f)) (test-begin "numbers") (define (integer-neighborhoods x) (list x (+ 1 x) (+ -1 x) (- x) (- 1 x) (- -1 x))) (test '(536870912 536870913 536870911 -536870912 -536870911 -536870913) (integer-neighborhoods (expt 2 29))) (test '(1073741824 1073741825 1073741823 -1073741824 -1073741823 -1073741825) (integer-neighborhoods (expt 2 30))) (test '(2147483648 2147483649 2147483647 -2147483648 -2147483647 -2147483649) (integer-neighborhoods (expt 2 31))) (test '(4294967296 4294967297 4294967295 -4294967296 -4294967295 -4294967297) (integer-neighborhoods (expt 2 32))) (test '(4611686018427387904 4611686018427387905 4611686018427387903 -4611686018427387904 -4611686018427387903 -4611686018427387905) (integer-neighborhoods (expt 2 62))) (test '(9223372036854775808 9223372036854775809 9223372036854775807 -9223372036854775808 -9223372036854775807 -9223372036854775809) (integer-neighborhoods (expt 2 63))) (test '(18446744073709551616 18446744073709551617 18446744073709551615 -18446744073709551616 -18446744073709551615 -18446744073709551617) (integer-neighborhoods (expt 2 64))) (test '(85070591730234615865843651857942052864 85070591730234615865843651857942052865 85070591730234615865843651857942052863 -85070591730234615865843651857942052864 -85070591730234615865843651857942052863 -85070591730234615865843651857942052865) (integer-neighborhoods (expt 2 126))) (test '(170141183460469231731687303715884105728 170141183460469231731687303715884105729 170141183460469231731687303715884105727 -170141183460469231731687303715884105728 -170141183460469231731687303715884105727 -170141183460469231731687303715884105729) (integer-neighborhoods (expt 2 127))) (test '(340282366920938463463374607431768211456 340282366920938463463374607431768211457 340282366920938463463374607431768211455 -340282366920938463463374607431768211456 -340282366920938463463374607431768211455 -340282366920938463463374607431768211457) (integer-neighborhoods (expt 2 128))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (integer-arithmetic-combinations a b) (list (+ a b) (- a b) (* a b) (quotient a b) (remainder a b))) (define (sign-combinations a b) (list (integer-arithmetic-combinations a b) (integer-arithmetic-combinations (- a) b) (integer-arithmetic-combinations a (- b)) (integer-arithmetic-combinations (- a) (- b)))) ;; fix x fix (test '((1 -1 0 0 0) (1 -1 0 0 0) (-1 1 0 0 0) (-1 1 0 0 0)) (sign-combinations 0 1)) (test '((2 0 1 1 0) (0 -2 -1 -1 0) (0 2 -1 -1 0) (-2 0 1 1 0)) (sign-combinations 1 1)) (test '((59 25 714 2 8) (-25 -59 -714 -2 -8) (25 59 -714 -2 8) (-59 -25 714 2 -8)) (sign-combinations 42 17)) ;; fix x big (test '((4294967338 -4294967254 180388626432 0 42) (4294967254 -4294967338 -180388626432 0 -42) (-4294967254 4294967338 -180388626432 0 42) (-4294967338 4294967254 180388626432 0 -42)) (sign-combinations 42 (expt 2 32))) ;; big x fix (test '((4294967338 4294967254 180388626432 102261126 4) (-4294967254 -4294967338 -180388626432 -102261126 -4) (4294967254 4294967338 -180388626432 -102261126 4) (-4294967338 -4294967254 180388626432 102261126 -4)) (sign-combinations (expt 2 32) 42)) ;; big x bigger (test '((12884901889 -4294967297 36893488151714070528 0 4294967296) (4294967297 -12884901889 -36893488151714070528 0 -4294967296) (-4294967297 12884901889 -36893488151714070528 0 4294967296) (-12884901889 4294967297 36893488151714070528 0 -4294967296)) (sign-combinations (expt 2 32) (+ 1 (expt 2 33)))) (test '((18446744078004518913 -18446744069414584321 79228162514264337597838917632 0 4294967296) (18446744069414584321 -18446744078004518913 -79228162514264337597838917632 0 -4294967296) (-18446744069414584321 18446744078004518913 -79228162514264337597838917632 0 4294967296) (-18446744078004518913 18446744069414584321 79228162514264337597838917632 0 -4294967296)) (sign-combinations (expt 2 32) (+ 1 (expt 2 64)))) ;; bigger x big (test '((12884901889 4294967297 36893488151714070528 2 1) (-4294967297 -12884901889 -36893488151714070528 -2 -1) (4294967297 12884901889 -36893488151714070528 -2 1) (-12884901889 -4294967297 36893488151714070528 2 -1)) (sign-combinations (+ 1 (expt 2 33)) (expt 2 32))) (test '((18446744078004518913 18446744069414584321 79228162514264337597838917632 4294967296 1) (-18446744069414584321 -18446744078004518913 -79228162514264337597838917632 -4294967296 -1) (18446744069414584321 18446744078004518913 -79228162514264337597838917632 -4294967296 1) (-18446744078004518913 -18446744069414584321 79228162514264337597838917632 4294967296 -1)) (sign-combinations (+ 1 (expt 2 64)) (expt 2 32))) (define M7 (- (expt 2 127) 1)) (test '((170141183460469231750134047789593657344 170141183460469231713240559642174554110 3138550867693340382088035895064302439764418281874191810559 9223372036854775807 9223372036854775808) (-170141183460469231713240559642174554110 -170141183460469231750134047789593657344 -3138550867693340382088035895064302439764418281874191810559 -9223372036854775807 -9223372036854775808) (170141183460469231713240559642174554110 170141183460469231750134047789593657344 -3138550867693340382088035895064302439764418281874191810559 -9223372036854775807 9223372036854775808) (-170141183460469231750134047789593657344 -170141183460469231713240559642174554110 3138550867693340382088035895064302439764418281874191810559 9223372036854775807 -9223372036854775808)) (sign-combinations M7 (+ 1 (expt 2 64)))) (test #f (< +nan.0 +nan.0)) (test #f (<= +nan.0 +nan.0)) (test #f (= +nan.0 +nan.0)) (test #f (>= +nan.0 +nan.0)) (test #f (> +nan.0 +nan.0)) (test #f (< +inf.0 +inf.0)) (test #t (<= +inf.0 +inf.0)) (test #t (= +inf.0 +inf.0)) (test #t (>= +inf.0 +inf.0)) (test #f (> +inf.0 +inf.0)) (test #f (< -inf.0 -inf.0)) (test #t (<= -inf.0 -inf.0)) (test #t (= -inf.0 -inf.0)) (test #t (>= -inf.0 -inf.0)) (test #f (> -inf.0 -inf.0)) (test #t (< -inf.0 +inf.0)) (test #t (<= -inf.0 +inf.0)) (test #f (= -inf.0 +inf.0)) (test #f (>= -inf.0 +inf.0)) (test #f (> -inf.0 +inf.0)) (test 88962710306127702866241727433142015 (string->number "#x00112233445566778899aabbccddeeff")) (test (expt 10 154) (sqrt (expt 10 308))) (test 36893488147419103231 (- 340282366920938463463374607431768211456 340282366920938463426481119284349108225)) (cond-expand (ratios (test #t (< 1/2 1.0)) (test #t (< 1.0 3/2)) (test #t (< 1/2 1.5)) (test #t (< 1/2 2.0)) (test 1.0 (max 1/2 1.0)) (test 18446744073709551617 (numerator (/ 18446744073709551617 2))) (test "18446744073709551617/2" (number->string (/ 18446744073709551617 2))) (let ((a 1000000000000000000000000000000000000000) (b 31622776601683794000)) (test 31622776601683792639 (quotient a b)) (test 30922992657207634000 (remainder a b))) (let ((g 18446744073709551616/6148914691236517205)) (test 36893488147419103231/113427455640312821148309287786019553280 (- g (/ 9 g)))) (let ((r (/ (expt 2 61) 3))) (test 0 (- r r)) (test 2305843009213693952/3 r))) (else #f)) (test-end)
null
https://raw.githubusercontent.com/spurious/chibi-scheme-mirror/49168ab073f64a95c834b5f584a9aaea3469594d/tests/numeric-tests.scm
scheme
these tests are only valid if chibi-scheme is compiled with full numeric support (USE_BIGNUMS, USE_FLONUMS and USE_MATH) fix x fix fix x big big x fix big x bigger bigger x big
(cond-expand (modules (import (only (chibi test) test-begin test test-end))) (else #f)) (test-begin "numbers") (define (integer-neighborhoods x) (list x (+ 1 x) (+ -1 x) (- x) (- 1 x) (- -1 x))) (test '(536870912 536870913 536870911 -536870912 -536870911 -536870913) (integer-neighborhoods (expt 2 29))) (test '(1073741824 1073741825 1073741823 -1073741824 -1073741823 -1073741825) (integer-neighborhoods (expt 2 30))) (test '(2147483648 2147483649 2147483647 -2147483648 -2147483647 -2147483649) (integer-neighborhoods (expt 2 31))) (test '(4294967296 4294967297 4294967295 -4294967296 -4294967295 -4294967297) (integer-neighborhoods (expt 2 32))) (test '(4611686018427387904 4611686018427387905 4611686018427387903 -4611686018427387904 -4611686018427387903 -4611686018427387905) (integer-neighborhoods (expt 2 62))) (test '(9223372036854775808 9223372036854775809 9223372036854775807 -9223372036854775808 -9223372036854775807 -9223372036854775809) (integer-neighborhoods (expt 2 63))) (test '(18446744073709551616 18446744073709551617 18446744073709551615 -18446744073709551616 -18446744073709551615 -18446744073709551617) (integer-neighborhoods (expt 2 64))) (test '(85070591730234615865843651857942052864 85070591730234615865843651857942052865 85070591730234615865843651857942052863 -85070591730234615865843651857942052864 -85070591730234615865843651857942052863 -85070591730234615865843651857942052865) (integer-neighborhoods (expt 2 126))) (test '(170141183460469231731687303715884105728 170141183460469231731687303715884105729 170141183460469231731687303715884105727 -170141183460469231731687303715884105728 -170141183460469231731687303715884105727 -170141183460469231731687303715884105729) (integer-neighborhoods (expt 2 127))) (test '(340282366920938463463374607431768211456 340282366920938463463374607431768211457 340282366920938463463374607431768211455 -340282366920938463463374607431768211456 -340282366920938463463374607431768211455 -340282366920938463463374607431768211457) (integer-neighborhoods (expt 2 128))) (define (integer-arithmetic-combinations a b) (list (+ a b) (- a b) (* a b) (quotient a b) (remainder a b))) (define (sign-combinations a b) (list (integer-arithmetic-combinations a b) (integer-arithmetic-combinations (- a) b) (integer-arithmetic-combinations a (- b)) (integer-arithmetic-combinations (- a) (- b)))) (test '((1 -1 0 0 0) (1 -1 0 0 0) (-1 1 0 0 0) (-1 1 0 0 0)) (sign-combinations 0 1)) (test '((2 0 1 1 0) (0 -2 -1 -1 0) (0 2 -1 -1 0) (-2 0 1 1 0)) (sign-combinations 1 1)) (test '((59 25 714 2 8) (-25 -59 -714 -2 -8) (25 59 -714 -2 8) (-59 -25 714 2 -8)) (sign-combinations 42 17)) (test '((4294967338 -4294967254 180388626432 0 42) (4294967254 -4294967338 -180388626432 0 -42) (-4294967254 4294967338 -180388626432 0 42) (-4294967338 4294967254 180388626432 0 -42)) (sign-combinations 42 (expt 2 32))) (test '((4294967338 4294967254 180388626432 102261126 4) (-4294967254 -4294967338 -180388626432 -102261126 -4) (4294967254 4294967338 -180388626432 -102261126 4) (-4294967338 -4294967254 180388626432 102261126 -4)) (sign-combinations (expt 2 32) 42)) (test '((12884901889 -4294967297 36893488151714070528 0 4294967296) (4294967297 -12884901889 -36893488151714070528 0 -4294967296) (-4294967297 12884901889 -36893488151714070528 0 4294967296) (-12884901889 4294967297 36893488151714070528 0 -4294967296)) (sign-combinations (expt 2 32) (+ 1 (expt 2 33)))) (test '((18446744078004518913 -18446744069414584321 79228162514264337597838917632 0 4294967296) (18446744069414584321 -18446744078004518913 -79228162514264337597838917632 0 -4294967296) (-18446744069414584321 18446744078004518913 -79228162514264337597838917632 0 4294967296) (-18446744078004518913 18446744069414584321 79228162514264337597838917632 0 -4294967296)) (sign-combinations (expt 2 32) (+ 1 (expt 2 64)))) (test '((12884901889 4294967297 36893488151714070528 2 1) (-4294967297 -12884901889 -36893488151714070528 -2 -1) (4294967297 12884901889 -36893488151714070528 -2 1) (-12884901889 -4294967297 36893488151714070528 2 -1)) (sign-combinations (+ 1 (expt 2 33)) (expt 2 32))) (test '((18446744078004518913 18446744069414584321 79228162514264337597838917632 4294967296 1) (-18446744069414584321 -18446744078004518913 -79228162514264337597838917632 -4294967296 -1) (18446744069414584321 18446744078004518913 -79228162514264337597838917632 -4294967296 1) (-18446744078004518913 -18446744069414584321 79228162514264337597838917632 4294967296 -1)) (sign-combinations (+ 1 (expt 2 64)) (expt 2 32))) (define M7 (- (expt 2 127) 1)) (test '((170141183460469231750134047789593657344 170141183460469231713240559642174554110 3138550867693340382088035895064302439764418281874191810559 9223372036854775807 9223372036854775808) (-170141183460469231713240559642174554110 -170141183460469231750134047789593657344 -3138550867693340382088035895064302439764418281874191810559 -9223372036854775807 -9223372036854775808) (170141183460469231713240559642174554110 170141183460469231750134047789593657344 -3138550867693340382088035895064302439764418281874191810559 -9223372036854775807 9223372036854775808) (-170141183460469231750134047789593657344 -170141183460469231713240559642174554110 3138550867693340382088035895064302439764418281874191810559 9223372036854775807 -9223372036854775808)) (sign-combinations M7 (+ 1 (expt 2 64)))) (test #f (< +nan.0 +nan.0)) (test #f (<= +nan.0 +nan.0)) (test #f (= +nan.0 +nan.0)) (test #f (>= +nan.0 +nan.0)) (test #f (> +nan.0 +nan.0)) (test #f (< +inf.0 +inf.0)) (test #t (<= +inf.0 +inf.0)) (test #t (= +inf.0 +inf.0)) (test #t (>= +inf.0 +inf.0)) (test #f (> +inf.0 +inf.0)) (test #f (< -inf.0 -inf.0)) (test #t (<= -inf.0 -inf.0)) (test #t (= -inf.0 -inf.0)) (test #t (>= -inf.0 -inf.0)) (test #f (> -inf.0 -inf.0)) (test #t (< -inf.0 +inf.0)) (test #t (<= -inf.0 +inf.0)) (test #f (= -inf.0 +inf.0)) (test #f (>= -inf.0 +inf.0)) (test #f (> -inf.0 +inf.0)) (test 88962710306127702866241727433142015 (string->number "#x00112233445566778899aabbccddeeff")) (test (expt 10 154) (sqrt (expt 10 308))) (test 36893488147419103231 (- 340282366920938463463374607431768211456 340282366920938463426481119284349108225)) (cond-expand (ratios (test #t (< 1/2 1.0)) (test #t (< 1.0 3/2)) (test #t (< 1/2 1.5)) (test #t (< 1/2 2.0)) (test 1.0 (max 1/2 1.0)) (test 18446744073709551617 (numerator (/ 18446744073709551617 2))) (test "18446744073709551617/2" (number->string (/ 18446744073709551617 2))) (let ((a 1000000000000000000000000000000000000000) (b 31622776601683794000)) (test 31622776601683792639 (quotient a b)) (test 30922992657207634000 (remainder a b))) (let ((g 18446744073709551616/6148914691236517205)) (test 36893488147419103231/113427455640312821148309287786019553280 (- g (/ 9 g)))) (let ((r (/ (expt 2 61) 3))) (test 0 (- r r)) (test 2305843009213693952/3 r))) (else #f)) (test-end)
a3fda6f7ad6fa02f214976d062bd3ef656f37873881c2091c1b93d904ecc7602
jaspervdj/patat
Extended.hs
# LANGUAGE GeneralizedNewtypeDeriving # module Data.Aeson.Extended ( module Data.Aeson , FlexibleNum (..) ) where import Data.Aeson import qualified Data.Text as T import Prelude import Text.Read (readMaybe) -- | This can be parsed from a JSON string in addition to a JSON number. newtype FlexibleNum a = FlexibleNum {unFlexibleNum :: a} deriving (Show, ToJSON) instance (FromJSON a, Read a) => FromJSON (FlexibleNum a) where parseJSON (String str) = case readMaybe (T.unpack str) of Nothing -> fail $ "Could not parse " ++ T.unpack str ++ " as a number" Just x -> return (FlexibleNum x) parseJSON val = FlexibleNum <$> parseJSON val
null
https://raw.githubusercontent.com/jaspervdj/patat/9e0d0ccde9afee07ea23521546c406033afeb4f9/lib/Data/Aeson/Extended.hs
haskell
| This can be parsed from a JSON string in addition to a JSON number.
# LANGUAGE GeneralizedNewtypeDeriving # module Data.Aeson.Extended ( module Data.Aeson , FlexibleNum (..) ) where import Data.Aeson import qualified Data.Text as T import Prelude import Text.Read (readMaybe) newtype FlexibleNum a = FlexibleNum {unFlexibleNum :: a} deriving (Show, ToJSON) instance (FromJSON a, Read a) => FromJSON (FlexibleNum a) where parseJSON (String str) = case readMaybe (T.unpack str) of Nothing -> fail $ "Could not parse " ++ T.unpack str ++ " as a number" Just x -> return (FlexibleNum x) parseJSON val = FlexibleNum <$> parseJSON val
83084997dd5c0fe67e0a0783c518bd41b78eb544f2563d5603d94c0f706457c5
tweag/pirouette
Monadic.hs
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NamedFieldPuns # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # module Pirouette.SMT.Monadic ( SolverT (..), checkSat, runSolverT, solverPush, solverPop, declareDatatype, declareDatatypes, supportedUninterpretedFunction, declareRawFun, declareVariables, declareVariable, assert, assertNot, getUnsatCore, getModel, -- * Convenient re-exports Constraint (..), PureSMT.Result (..), module Base, Branch (..), ) where import Control.Applicative import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State.Class import Control.Monad.Writer import qualified Data.Map as M import ListT.Weighted (MonadWeightedList) import Pirouette.Monad import Pirouette.SMT.Base as Base import Pirouette.SMT.Constraints import Pirouette.SMT.FromTerm import Pirouette.Term.Syntax import qualified Pirouette.Term.Syntax.SystemF as R import qualified PureSMT -- OLD CODE -- | Solver monad for a specific solver, passed as a phantom type variable @s@ (refer to 'IsSolver' for more) -- to know the supported solvers. That's a phantom type variable used only to distinguish -- solver-specific operations, such as initialization newtype SolverT m a = SolverT {unSolverT :: ReaderT PureSMT.Solver m a} deriving (Functor) deriving newtype (Applicative, Monad, MonadReader PureSMT.Solver, MonadIO, MonadFail, MonadWeightedList) instance MonadTrans SolverT where lift = SolverT . lift deriving instance MonadState s m => MonadState s (SolverT m) deriving instance MonadError e m => MonadError e (SolverT m) deriving instance Alternative m => Alternative (SolverT m) deriving instance PirouetteReadDefs lang m => PirouetteReadDefs lang (SolverT m) | Runs a computation that requires a session with a solver . The first parameter is -- an action that launches a solver. Check 'cvc4_ALL_SUPPORTED' for an example. runSolverT :: forall m a. (MonadIO m) => IO PureSMT.Solver -> SolverT m a -> m a runSolverT s (SolverT comp) = liftIO s >>= runReaderT comp | Returns ' Sat ' , ' Unsat ' or ' Unknown ' for the current solver session . checkSat :: (MonadIO m) => SolverT m PureSMT.Result checkSat = do solver <- ask liftIO $ PureSMT.check solver -- | Pushes the solver context, creating a checkpoint. This is useful if you plan to execute -- many queries that share definitions. A typical use pattern would be: -- -- > declareDatatypes ... > forM _ varsAndExpr $ \(vars , expr ) - > do -- > solverPush > vars -- > assert expr -- > r <- checkSat -- > solverPop -- > return r solverPush :: (MonadIO m) => SolverT m () solverPush = do solver <- ask liftIO $ PureSMT.push solver -- | Pops the current checkpoint, check 'solverPush' for an example. solverPop :: (MonadIO m) => SolverT m () solverPop = do solver <- ask liftIO $ PureSMT.pop solver -- | Declare a single datatype in the current solver session. declareDatatype :: (LanguageSMT lang, MonadIO m) => Name -> TypeDef lang -> ExceptT String (SolverT m) [Name] declareDatatype typeName (Datatype _ typeVariables _ cstrs) = do solver <- ask (constr', _) <- runWriterT $ mapM (constructorFromPIR typeVariables) cstrs liftIO $ do PureSMT.declareDatatype solver (toSmtName typeName) (map (toSmtName . fst) typeVariables) constr' return $ typeName : map fst cstrs -- | Declare a set of datatypes (all at once) in the current solver session. declareDatatypes :: (LanguageSMT lang, MonadIO m) => [(Name, TypeDef lang)] -> ExceptT String (SolverT m) [Name] declareDatatypes [] = we need to handle this especially because SMTLIB does n't like an empty set of types pure [] declareDatatypes dts = do solver <- ask (dts', _) <- runWriterT $ forM dts $ \(typeName, Datatype _ typeVariables _ cstrs) -> do cstrs' <- mapM (constructorFromPIR typeVariables) cstrs pure (toSmtName typeName, map (toSmtName . fst) typeVariables, cstrs') liftIO $ PureSMT.declareDatatypes solver dts' return $ concat [typeName : map fst cstrs | (typeName, Datatype _ _ _ cstrs) <- dts] | Returns whether or not a function @f@ can be declared as an uninterpreted function and , -- if it can, return the type of its arguments and result. A function can be declared if its type can be translate to SmtLib , an uninterpreted function -- has no body after all, so no need to worry about it. supportedUninterpretedFunction :: (LanguageSMT lang) => FunDef lang -> Maybe ([PureSMT.SExpr], PureSMT.SExpr) supportedUninterpretedFunction FunDef {funTy} = toMaybe $ do let (args, result) = R.tyFunArgs funTy (args', _) <- runWriterT $ mapM translateType args (result', _) <- runWriterT $ translateType result return (args', result') where toMaybe = either (const Nothing) Just . runExcept -- | Declares a function with a given name, type of arguments and type of result. declareRawFun :: (MonadIO m) => Name -> ([PureSMT.SExpr], PureSMT.SExpr) -> SolverT m () declareRawFun n (args, res) = do solver <- ask void $ liftIO $ PureSMT.declareFun solver (toSmtName n) args res | Declare ( name and type ) all the variables of the environment in the SMT -- solver. This step is required before asserting constraints mentioning any of these variables. declareVariables :: (LanguageSMT lang, MonadIO m) => M.Map Name (Type lang) -> ExceptT String (SolverT m) () declareVariables = mapM_ (uncurry declareVariable) . M.toList -- | Declares a single variable in the current solver session. declareVariable :: (LanguageSMT lang, MonadIO m) => Name -> Type lang -> ExceptT String (SolverT m) () declareVariable varName varTy = do solver <- ask (tySExpr, _) <- runWriterT $ translateType varTy liftIO $ void (PureSMT.declare solver (toSmtName varName) tySExpr) | Asserts a constraint ; check ' Constraint ' for more information -- | The functions 'assert' and 'assertNot' output a boolean, stating if the constraint was fully passed to the SMT solver , -- or if a part was lost during the translation process. assert :: (MonadIO m) => PureSMT.SExpr -> SolverT m () assert expr = SolverT $ ReaderT $ \solver -> do liftIO $ PureSMT.assert solver expr assertNot :: (MonadIO m) => PureSMT.SExpr -> SolverT m () assertNot expr = SolverT $ ReaderT $ \solver -> do -- liftIO $ putStrLn $ "asserting not " ++ show expr liftIO $ PureSMT.assert solver (PureSMT.not expr) getUnsatCore :: (MonadIO m) => SolverT m [String] getUnsatCore = SolverT $ ReaderT $ \solver -> liftIO $ PureSMT.getUnsatCore solver getModel :: (MonadIO m) => [Name] -> SolverT m [(PureSMT.SExpr, PureSMT.Value)] getModel names = SolverT $ ReaderT $ \solver -> do let exprs = map (PureSMT.symbol . toSmtName) names liftIO $ PureSMT.getExprs solver exprs
null
https://raw.githubusercontent.com/tweag/pirouette/35c88ead8bc0b2222d94b1349fe42cf3ea3b1fa5/src/Pirouette/SMT/Monadic.hs
haskell
# LANGUAGE RankNTypes # * Convenient re-exports OLD CODE | Solver monad for a specific solver, passed as a phantom type variable @s@ (refer to 'IsSolver' for more) to know the supported solvers. That's a phantom type variable used only to distinguish solver-specific operations, such as initialization an action that launches a solver. Check 'cvc4_ALL_SUPPORTED' for an example. | Pushes the solver context, creating a checkpoint. This is useful if you plan to execute many queries that share definitions. A typical use pattern would be: > declareDatatypes ... > solverPush > assert expr > r <- checkSat > solverPop > return r | Pops the current checkpoint, check 'solverPush' for an example. | Declare a single datatype in the current solver session. | Declare a set of datatypes (all at once) in the current solver session. if it can, return the type of its arguments and result. has no body after all, so no need to worry about it. | Declares a function with a given name, type of arguments and type of result. solver. This step is required before asserting constraints mentioning any of these variables. | Declares a single variable in the current solver session. | The functions 'assert' and 'assertNot' output a boolean, or if a part was lost during the translation process. liftIO $ putStrLn $ "asserting not " ++ show expr
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NamedFieldPuns # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # module Pirouette.SMT.Monadic ( SolverT (..), checkSat, runSolverT, solverPush, solverPop, declareDatatype, declareDatatypes, supportedUninterpretedFunction, declareRawFun, declareVariables, declareVariable, assert, assertNot, getUnsatCore, getModel, Constraint (..), PureSMT.Result (..), module Base, Branch (..), ) where import Control.Applicative import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State.Class import Control.Monad.Writer import qualified Data.Map as M import ListT.Weighted (MonadWeightedList) import Pirouette.Monad import Pirouette.SMT.Base as Base import Pirouette.SMT.Constraints import Pirouette.SMT.FromTerm import Pirouette.Term.Syntax import qualified Pirouette.Term.Syntax.SystemF as R import qualified PureSMT newtype SolverT m a = SolverT {unSolverT :: ReaderT PureSMT.Solver m a} deriving (Functor) deriving newtype (Applicative, Monad, MonadReader PureSMT.Solver, MonadIO, MonadFail, MonadWeightedList) instance MonadTrans SolverT where lift = SolverT . lift deriving instance MonadState s m => MonadState s (SolverT m) deriving instance MonadError e m => MonadError e (SolverT m) deriving instance Alternative m => Alternative (SolverT m) deriving instance PirouetteReadDefs lang m => PirouetteReadDefs lang (SolverT m) | Runs a computation that requires a session with a solver . The first parameter is runSolverT :: forall m a. (MonadIO m) => IO PureSMT.Solver -> SolverT m a -> m a runSolverT s (SolverT comp) = liftIO s >>= runReaderT comp | Returns ' Sat ' , ' Unsat ' or ' Unknown ' for the current solver session . checkSat :: (MonadIO m) => SolverT m PureSMT.Result checkSat = do solver <- ask liftIO $ PureSMT.check solver > forM _ varsAndExpr $ \(vars , expr ) - > do > vars solverPush :: (MonadIO m) => SolverT m () solverPush = do solver <- ask liftIO $ PureSMT.push solver solverPop :: (MonadIO m) => SolverT m () solverPop = do solver <- ask liftIO $ PureSMT.pop solver declareDatatype :: (LanguageSMT lang, MonadIO m) => Name -> TypeDef lang -> ExceptT String (SolverT m) [Name] declareDatatype typeName (Datatype _ typeVariables _ cstrs) = do solver <- ask (constr', _) <- runWriterT $ mapM (constructorFromPIR typeVariables) cstrs liftIO $ do PureSMT.declareDatatype solver (toSmtName typeName) (map (toSmtName . fst) typeVariables) constr' return $ typeName : map fst cstrs declareDatatypes :: (LanguageSMT lang, MonadIO m) => [(Name, TypeDef lang)] -> ExceptT String (SolverT m) [Name] declareDatatypes [] = we need to handle this especially because SMTLIB does n't like an empty set of types pure [] declareDatatypes dts = do solver <- ask (dts', _) <- runWriterT $ forM dts $ \(typeName, Datatype _ typeVariables _ cstrs) -> do cstrs' <- mapM (constructorFromPIR typeVariables) cstrs pure (toSmtName typeName, map (toSmtName . fst) typeVariables, cstrs') liftIO $ PureSMT.declareDatatypes solver dts' return $ concat [typeName : map fst cstrs | (typeName, Datatype _ _ _ cstrs) <- dts] | Returns whether or not a function @f@ can be declared as an uninterpreted function and , A function can be declared if its type can be translate to SmtLib , an uninterpreted function supportedUninterpretedFunction :: (LanguageSMT lang) => FunDef lang -> Maybe ([PureSMT.SExpr], PureSMT.SExpr) supportedUninterpretedFunction FunDef {funTy} = toMaybe $ do let (args, result) = R.tyFunArgs funTy (args', _) <- runWriterT $ mapM translateType args (result', _) <- runWriterT $ translateType result return (args', result') where toMaybe = either (const Nothing) Just . runExcept declareRawFun :: (MonadIO m) => Name -> ([PureSMT.SExpr], PureSMT.SExpr) -> SolverT m () declareRawFun n (args, res) = do solver <- ask void $ liftIO $ PureSMT.declareFun solver (toSmtName n) args res | Declare ( name and type ) all the variables of the environment in the SMT declareVariables :: (LanguageSMT lang, MonadIO m) => M.Map Name (Type lang) -> ExceptT String (SolverT m) () declareVariables = mapM_ (uncurry declareVariable) . M.toList declareVariable :: (LanguageSMT lang, MonadIO m) => Name -> Type lang -> ExceptT String (SolverT m) () declareVariable varName varTy = do solver <- ask (tySExpr, _) <- runWriterT $ translateType varTy liftIO $ void (PureSMT.declare solver (toSmtName varName) tySExpr) | Asserts a constraint ; check ' Constraint ' for more information stating if the constraint was fully passed to the SMT solver , assert :: (MonadIO m) => PureSMT.SExpr -> SolverT m () assert expr = SolverT $ ReaderT $ \solver -> do liftIO $ PureSMT.assert solver expr assertNot :: (MonadIO m) => PureSMT.SExpr -> SolverT m () assertNot expr = SolverT $ ReaderT $ \solver -> do liftIO $ PureSMT.assert solver (PureSMT.not expr) getUnsatCore :: (MonadIO m) => SolverT m [String] getUnsatCore = SolverT $ ReaderT $ \solver -> liftIO $ PureSMT.getUnsatCore solver getModel :: (MonadIO m) => [Name] -> SolverT m [(PureSMT.SExpr, PureSMT.Value)] getModel names = SolverT $ ReaderT $ \solver -> do let exprs = map (PureSMT.symbol . toSmtName) names liftIO $ PureSMT.getExprs solver exprs
0646cf7839bff0298d790152f1e5a52c636a402fa035951fdecd2cd32e1da120
LaurentRDC/hakyll-images
Images.hs
-- | -- Module : Hakyll.Images -- Description : Hakyll utilities for image files Copyright : ( c ) , 2019 - present -- License : BSD3 -- Maintainer : -- Stability : unstable -- Portability : portable -- This package defines a few Hakyll compilers . These compilers help deal with images in the context of Hakyll programs , such as JPEG compression or image resizing . -- -- Items must be loaded before compilers can be used, like so: -- -- @ import Hakyll import Hakyll . Images ( loadImage -- , resizeImageCompiler -- ) -- -- hakyll $ do -- -- Resize all profile pictures with .png extensions to 64x48 -- match "profiles/**.png" $ do route idRoute -- compile $ loadImage > > = resizeImageCompiler 64 48 -- -- (... omitted ...) -- @ -- -- Compilers can be sequenced easily as well: -- -- @ import Hakyll import Hakyll . Images ( loadImage -- , compressJpgCompiler -- , scaleImageCompiler -- ) -- -- hakyll $ do -- -- Resize all JPEgs to fit inside of 800x600 -- Also compress to a quality of 25/100 -- match "pictures/**.jpg" $ do route idRoute -- compile $ loadImage -- >>= scaleImageCompiler 800 600 > > = compressJpgCompiler 25 -- -- (... omitted ...) -- @ module Hakyll.Images ( -- Basic types and functions Image, loadImage, -- Handling metadata module Hakyll.Images.Metadata, -- Jpg compression JpgQuality, compressJpg, compressJpgCompiler, -- Image scaling Width, Height, resize, resizeImageCompiler, scale, scaleImageCompiler, ensureFit, ensureFitCompiler, ) where import Hakyll.Images.Common import Hakyll.Images.CompressJpg import Hakyll.Images.Metadata import Hakyll.Images.Resize
null
https://raw.githubusercontent.com/LaurentRDC/hakyll-images/5f9284a97f3fc8f056a79fd5321c39e56622c93f/library/Hakyll/Images.hs
haskell
| Module : Hakyll.Images Description : Hakyll utilities for image files License : BSD3 Maintainer : Stability : unstable Portability : portable Items must be loaded before compilers can be used, like so: @ , resizeImageCompiler ) hakyll $ do Resize all profile pictures with .png extensions to 64x48 match "profiles/**.png" $ do compile $ loadImage (... omitted ...) @ Compilers can be sequenced easily as well: @ , compressJpgCompiler , scaleImageCompiler ) hakyll $ do Resize all JPEgs to fit inside of 800x600 Also compress to a quality of 25/100 match "pictures/**.jpg" $ do compile $ loadImage >>= scaleImageCompiler 800 600 (... omitted ...) @ Basic types and functions Handling metadata Jpg compression Image scaling
Copyright : ( c ) , 2019 - present This package defines a few Hakyll compilers . These compilers help deal with images in the context of Hakyll programs , such as JPEG compression or image resizing . import Hakyll import Hakyll . Images ( loadImage route idRoute > > = resizeImageCompiler 64 48 import Hakyll import Hakyll . Images ( loadImage route idRoute > > = compressJpgCompiler 25 module Hakyll.Images Image, loadImage, module Hakyll.Images.Metadata, JpgQuality, compressJpg, compressJpgCompiler, Width, Height, resize, resizeImageCompiler, scale, scaleImageCompiler, ensureFit, ensureFitCompiler, ) where import Hakyll.Images.Common import Hakyll.Images.CompressJpg import Hakyll.Images.Metadata import Hakyll.Images.Resize
6af4953a37d3886cac422055527435357b23f66954cd39827cfbb9ab2648783c
mbj/stratosphere
StreamModeDetailsProperty.hs
module Stratosphere.Kinesis.Stream.StreamModeDetailsProperty ( StreamModeDetailsProperty(..), mkStreamModeDetailsProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data StreamModeDetailsProperty = StreamModeDetailsProperty {streamMode :: (Value Prelude.Text)} mkStreamModeDetailsProperty :: Value Prelude.Text -> StreamModeDetailsProperty mkStreamModeDetailsProperty streamMode = StreamModeDetailsProperty {streamMode = streamMode} instance ToResourceProperties StreamModeDetailsProperty where toResourceProperties StreamModeDetailsProperty {..} = ResourceProperties {awsType = "AWS::Kinesis::Stream.StreamModeDetails", supportsTags = Prelude.False, properties = ["StreamMode" JSON..= streamMode]} instance JSON.ToJSON StreamModeDetailsProperty where toJSON StreamModeDetailsProperty {..} = JSON.object ["StreamMode" JSON..= streamMode] instance Property "StreamMode" StreamModeDetailsProperty where type PropertyType "StreamMode" StreamModeDetailsProperty = Value Prelude.Text set newValue StreamModeDetailsProperty {} = StreamModeDetailsProperty {streamMode = newValue, ..}
null
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/kinesis/gen/Stratosphere/Kinesis/Stream/StreamModeDetailsProperty.hs
haskell
module Stratosphere.Kinesis.Stream.StreamModeDetailsProperty ( StreamModeDetailsProperty(..), mkStreamModeDetailsProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data StreamModeDetailsProperty = StreamModeDetailsProperty {streamMode :: (Value Prelude.Text)} mkStreamModeDetailsProperty :: Value Prelude.Text -> StreamModeDetailsProperty mkStreamModeDetailsProperty streamMode = StreamModeDetailsProperty {streamMode = streamMode} instance ToResourceProperties StreamModeDetailsProperty where toResourceProperties StreamModeDetailsProperty {..} = ResourceProperties {awsType = "AWS::Kinesis::Stream.StreamModeDetails", supportsTags = Prelude.False, properties = ["StreamMode" JSON..= streamMode]} instance JSON.ToJSON StreamModeDetailsProperty where toJSON StreamModeDetailsProperty {..} = JSON.object ["StreamMode" JSON..= streamMode] instance Property "StreamMode" StreamModeDetailsProperty where type PropertyType "StreamMode" StreamModeDetailsProperty = Value Prelude.Text set newValue StreamModeDetailsProperty {} = StreamModeDetailsProperty {streamMode = newValue, ..}
113b51c5dad0a8a7d67cfecf6de3878a50d3f31ba7a8d7ffb01313b5d74457b2
HaxeFoundation/ocamllibs
tTFSwfWriter.ml
* Copyright ( C)2005 - 2014 Haxe Foundation * * 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 . * Copyright (C)2005-2014 Haxe Foundation * * 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 TTFData open Swf let num_bits x = if x = 0 then 0 else let rec loop n v = if v = 0 then n else loop (n + 1) (v lsr 1) in loop 1 (abs x) let round x = int_of_float (floor (x +. 0.5)) let to_twips v = round (v *. 20.) type ctx = { ttf : ttf; } let begin_fill = SRStyleChange { scsr_move = None; scsr_fs0 = Some(1); scsr_fs1 = None; scsr_ls = None; scsr_new_styles = None; } let end_fill = SRStyleChange { scsr_move = None; scsr_fs0 = None; scsr_fs1 = None; scsr_ls = None; scsr_new_styles = None; } let align_bits x nbits = x land ((1 lsl nbits ) - 1) let move_to ctx x y = let x = to_twips x in let y = to_twips y in let nbits = max (num_bits x) (num_bits y) in SRStyleChange { scsr_move = Some (nbits, align_bits x nbits, align_bits y nbits); scsr_fs0 = Some(1); scsr_fs1 = None; scsr_ls = None; scsr_new_styles = None; } let line_to ctx x y = let x = to_twips x in let y = to_twips y in if x = 0 && y = 0 then raise Exit; let nbits = max (num_bits x) (num_bits y) in SRStraightEdge { sser_nbits = nbits; sser_line = (if x = 0 then None else Some(align_bits x nbits)), (if y = 0 then None else Some(align_bits y nbits)); } let curve_to ctx cx cy ax ay = let cx = to_twips cx in let cy = to_twips cy in let ax = to_twips ax in let ay = to_twips ay in let nbits = max (max (num_bits cx) (num_bits cy)) (max (num_bits ax) (num_bits ay)) in SRCurvedEdge { scer_nbits = nbits; scer_cx = align_bits cx nbits; scer_cy = align_bits cy nbits; scer_ax = align_bits ax nbits; scer_ay = align_bits ay nbits; } open TTFTools let write_paths ctx paths = let scale = 1024. /. (float_of_int ctx.ttf.ttf_head.hd_units_per_em) in let srl = DynArray.create () in List.iter (fun path -> try DynArray.add srl (match path.gp_type with | 0 -> move_to ctx (path.gp_x *. scale) ((-1.) *. path.gp_y *. scale); | 1 -> line_to ctx (path.gp_x *. scale) ((-1.) *. path.gp_y *. scale); | 2 -> curve_to ctx (path.gp_cx *. scale) ((-1.) *. path.gp_cy *. scale) (path.gp_x *. scale) ((-1.) *. path.gp_y *. scale); | _ -> assert false) with Exit -> () ) paths; DynArray.add srl (end_fill); { srs_nfbits = 1; srs_nlbits = 0; srs_records = DynArray.to_list srl; } let rec write_glyph ctx key glyf = { font_char_code = key; font_shape = write_paths ctx (TTFTools.build_glyph_paths ctx.ttf true glyf); } let write_font_layout ctx lut = let scale = 1024. /. (float_of_int ctx.ttf.ttf_head.hd_units_per_em) in let hmtx = Hashtbl.fold (fun k v acc -> (k,ctx.ttf.ttf_hmtx.(v)) :: acc) lut [] in let hmtx = List.stable_sort (fun a b -> compare (fst a) (fst b)) hmtx in let hmtx = List.map (fun (k,g) -> g) hmtx in { font_ascent = round((float_of_int ctx.ttf.ttf_os2.os2_us_win_ascent) *. scale *. 20.); font_descent = round((float_of_int ctx.ttf.ttf_os2.os2_us_win_descent) *. scale *. 20.); font_leading = round(((float_of_int(ctx.ttf.ttf_os2.os2_us_win_ascent + ctx.ttf.ttf_os2.os2_us_win_descent - ctx.ttf.ttf_head.hd_units_per_em)) *. scale) *. 20.); font_glyphs_layout = Array.of_list( ExtList.List.mapi (fun i h -> { font_advance = round((float_of_int h.advance_width) *. scale *. 20.); font_bounds = {rect_nbits=0; left=0; right=0; top=0; bottom=0}; }) hmtx ); font_kerning = []; } let bi v = if v then 1 else 0 let int_from_langcode lc = match lc with | LCNone -> 0 | LCLatin -> 1 | LCJapanese -> 2 | LCKorean -> 3 | LCSimplifiedChinese -> 4 | LCTraditionalChinese -> 5 let write_font2 ch b f2 = IO.write_bits b 1 (bi true); IO.write_bits b 1 (bi f2.font_shift_jis); IO.write_bits b 1 (bi f2.font_is_small); IO.write_bits b 1 (bi f2.font_is_ansi); IO.write_bits b 1 (bi f2.font_wide_offsets); IO.write_bits b 1 (bi f2.font_wide_codes); IO.write_bits b 1 (bi f2.font_is_italic); IO.write_bits b 1 (bi f2.font_is_bold); IO.write_byte ch (int_from_langcode f2.font_language); IO.write_byte ch (String.length f2.font_name); IO.nwrite_string ch f2.font_name; IO.write_ui16 ch (Array.length f2.font_glyphs); let glyph_offset = ref (((Array.length f2.font_glyphs) * 4)+4) in Array.iter (fun g -> IO.write_i32 ch !glyph_offset; glyph_offset := !glyph_offset + SwfParser.font_shape_records_length g.font_shape; )f2.font_glyphs; IO.write_i32 ch !glyph_offset; Array.iter (fun g -> SwfParser.write_shape_without_style ch g.font_shape;) f2.font_glyphs; Array.iter (fun g -> IO.write_ui16 ch g.font_char_code; )f2.font_glyphs; IO.write_i16 ch f2.font_layout.font_ascent; IO.write_i16 ch f2.font_layout.font_descent; IO.write_i16 ch f2.font_layout.font_leading; Array.iter (fun g -> let fa = ref g.font_advance in if (!fa) < -32767 then fa := -32768;(* fix or check *) if (!fa) > 32766 then fa := 32767; IO.write_i16 ch !fa;) f2.font_layout.font_glyphs_layout; Array.iter (fun g -> SwfParser.write_rect ch g.font_bounds;) f2.font_layout.font_glyphs_layout; TODO : optional FontKerningTable let to_swf ttf config = let ctx = { ttf = ttf; } in let lut = TTFTools.build_lut ttf config.ttfc_range_str in let glyfs = Hashtbl.fold (fun k v acc -> (k,ctx.ttf.ttf_glyfs.(v)) :: acc) lut [] in let glyfs = List.stable_sort (fun a b -> compare (fst a) (fst b)) glyfs in let glyfs = List.map (fun (k,g) -> write_glyph ctx k g) glyfs in let glyfs_font_layout = write_font_layout ctx lut in let glyfs = Array.of_list glyfs in { font_shift_jis = false; font_is_small = false; font_is_ansi = false; font_wide_offsets = true; font_wide_codes = true; font_is_italic = false; font_is_bold = false; font_language = LCNone; font_name = (match config.ttfc_font_name with Some s -> s | None -> ttf.ttf_font_name); font_glyphs = glyfs; font_layout = glyfs_font_layout; } ;;
null
https://raw.githubusercontent.com/HaxeFoundation/ocamllibs/97e498e1b3bc2b3f08cfcae874b8529e4292bc3d/ttflib/tTFSwfWriter.ml
ocaml
fix or check
* Copyright ( C)2005 - 2014 Haxe Foundation * * 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 . * Copyright (C)2005-2014 Haxe Foundation * * 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 TTFData open Swf let num_bits x = if x = 0 then 0 else let rec loop n v = if v = 0 then n else loop (n + 1) (v lsr 1) in loop 1 (abs x) let round x = int_of_float (floor (x +. 0.5)) let to_twips v = round (v *. 20.) type ctx = { ttf : ttf; } let begin_fill = SRStyleChange { scsr_move = None; scsr_fs0 = Some(1); scsr_fs1 = None; scsr_ls = None; scsr_new_styles = None; } let end_fill = SRStyleChange { scsr_move = None; scsr_fs0 = None; scsr_fs1 = None; scsr_ls = None; scsr_new_styles = None; } let align_bits x nbits = x land ((1 lsl nbits ) - 1) let move_to ctx x y = let x = to_twips x in let y = to_twips y in let nbits = max (num_bits x) (num_bits y) in SRStyleChange { scsr_move = Some (nbits, align_bits x nbits, align_bits y nbits); scsr_fs0 = Some(1); scsr_fs1 = None; scsr_ls = None; scsr_new_styles = None; } let line_to ctx x y = let x = to_twips x in let y = to_twips y in if x = 0 && y = 0 then raise Exit; let nbits = max (num_bits x) (num_bits y) in SRStraightEdge { sser_nbits = nbits; sser_line = (if x = 0 then None else Some(align_bits x nbits)), (if y = 0 then None else Some(align_bits y nbits)); } let curve_to ctx cx cy ax ay = let cx = to_twips cx in let cy = to_twips cy in let ax = to_twips ax in let ay = to_twips ay in let nbits = max (max (num_bits cx) (num_bits cy)) (max (num_bits ax) (num_bits ay)) in SRCurvedEdge { scer_nbits = nbits; scer_cx = align_bits cx nbits; scer_cy = align_bits cy nbits; scer_ax = align_bits ax nbits; scer_ay = align_bits ay nbits; } open TTFTools let write_paths ctx paths = let scale = 1024. /. (float_of_int ctx.ttf.ttf_head.hd_units_per_em) in let srl = DynArray.create () in List.iter (fun path -> try DynArray.add srl (match path.gp_type with | 0 -> move_to ctx (path.gp_x *. scale) ((-1.) *. path.gp_y *. scale); | 1 -> line_to ctx (path.gp_x *. scale) ((-1.) *. path.gp_y *. scale); | 2 -> curve_to ctx (path.gp_cx *. scale) ((-1.) *. path.gp_cy *. scale) (path.gp_x *. scale) ((-1.) *. path.gp_y *. scale); | _ -> assert false) with Exit -> () ) paths; DynArray.add srl (end_fill); { srs_nfbits = 1; srs_nlbits = 0; srs_records = DynArray.to_list srl; } let rec write_glyph ctx key glyf = { font_char_code = key; font_shape = write_paths ctx (TTFTools.build_glyph_paths ctx.ttf true glyf); } let write_font_layout ctx lut = let scale = 1024. /. (float_of_int ctx.ttf.ttf_head.hd_units_per_em) in let hmtx = Hashtbl.fold (fun k v acc -> (k,ctx.ttf.ttf_hmtx.(v)) :: acc) lut [] in let hmtx = List.stable_sort (fun a b -> compare (fst a) (fst b)) hmtx in let hmtx = List.map (fun (k,g) -> g) hmtx in { font_ascent = round((float_of_int ctx.ttf.ttf_os2.os2_us_win_ascent) *. scale *. 20.); font_descent = round((float_of_int ctx.ttf.ttf_os2.os2_us_win_descent) *. scale *. 20.); font_leading = round(((float_of_int(ctx.ttf.ttf_os2.os2_us_win_ascent + ctx.ttf.ttf_os2.os2_us_win_descent - ctx.ttf.ttf_head.hd_units_per_em)) *. scale) *. 20.); font_glyphs_layout = Array.of_list( ExtList.List.mapi (fun i h -> { font_advance = round((float_of_int h.advance_width) *. scale *. 20.); font_bounds = {rect_nbits=0; left=0; right=0; top=0; bottom=0}; }) hmtx ); font_kerning = []; } let bi v = if v then 1 else 0 let int_from_langcode lc = match lc with | LCNone -> 0 | LCLatin -> 1 | LCJapanese -> 2 | LCKorean -> 3 | LCSimplifiedChinese -> 4 | LCTraditionalChinese -> 5 let write_font2 ch b f2 = IO.write_bits b 1 (bi true); IO.write_bits b 1 (bi f2.font_shift_jis); IO.write_bits b 1 (bi f2.font_is_small); IO.write_bits b 1 (bi f2.font_is_ansi); IO.write_bits b 1 (bi f2.font_wide_offsets); IO.write_bits b 1 (bi f2.font_wide_codes); IO.write_bits b 1 (bi f2.font_is_italic); IO.write_bits b 1 (bi f2.font_is_bold); IO.write_byte ch (int_from_langcode f2.font_language); IO.write_byte ch (String.length f2.font_name); IO.nwrite_string ch f2.font_name; IO.write_ui16 ch (Array.length f2.font_glyphs); let glyph_offset = ref (((Array.length f2.font_glyphs) * 4)+4) in Array.iter (fun g -> IO.write_i32 ch !glyph_offset; glyph_offset := !glyph_offset + SwfParser.font_shape_records_length g.font_shape; )f2.font_glyphs; IO.write_i32 ch !glyph_offset; Array.iter (fun g -> SwfParser.write_shape_without_style ch g.font_shape;) f2.font_glyphs; Array.iter (fun g -> IO.write_ui16 ch g.font_char_code; )f2.font_glyphs; IO.write_i16 ch f2.font_layout.font_ascent; IO.write_i16 ch f2.font_layout.font_descent; IO.write_i16 ch f2.font_layout.font_leading; Array.iter (fun g -> let fa = ref g.font_advance in if (!fa) > 32766 then fa := 32767; IO.write_i16 ch !fa;) f2.font_layout.font_glyphs_layout; Array.iter (fun g -> SwfParser.write_rect ch g.font_bounds;) f2.font_layout.font_glyphs_layout; TODO : optional FontKerningTable let to_swf ttf config = let ctx = { ttf = ttf; } in let lut = TTFTools.build_lut ttf config.ttfc_range_str in let glyfs = Hashtbl.fold (fun k v acc -> (k,ctx.ttf.ttf_glyfs.(v)) :: acc) lut [] in let glyfs = List.stable_sort (fun a b -> compare (fst a) (fst b)) glyfs in let glyfs = List.map (fun (k,g) -> write_glyph ctx k g) glyfs in let glyfs_font_layout = write_font_layout ctx lut in let glyfs = Array.of_list glyfs in { font_shift_jis = false; font_is_small = false; font_is_ansi = false; font_wide_offsets = true; font_wide_codes = true; font_is_italic = false; font_is_bold = false; font_language = LCNone; font_name = (match config.ttfc_font_name with Some s -> s | None -> ttf.ttf_font_name); font_glyphs = glyfs; font_layout = glyfs_font_layout; } ;;
d6af93ac3e29e507f550ac4c6643833696923d2f4755e8ff3b929fbf4f0d69a0
expipiplus1/vulkan
VK_EXT_acquire_xlib_display.hs
{-# language CPP #-} -- | = Name -- VK_EXT_acquire_xlib_display - instance extension -- = = VK_EXT_acquire_xlib_display -- -- [__Name String__] -- @VK_EXT_acquire_xlib_display@ -- -- [__Extension Type__] -- Instance extension -- -- [__Registered Extension Number__] 90 -- -- [__Revision__] 1 -- -- [__Extension and Version Dependencies__] -- - Requires support for Vulkan 1.0 -- -- - Requires @VK_EXT_direct_mode_display@ to be enabled -- -- [__Contact__] -- - < -Docs/issues/new?body=[VK_EXT_acquire_xlib_display ] @cubanismo%0A*Here describe the issue or question you have about the VK_EXT_acquire_xlib_display extension * > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] 2016 - 12 - 13 -- -- [__IP Status__] -- No known IP claims. -- -- [__Contributors__] -- - , Red Hat -- - , NVIDIA -- - , NVIDIA -- - , NVIDIA -- - , Valve -- - , NVIDIA -- - , Intel -- -- == Description -- -- This extension allows an application to take exclusive control on a -- display currently associated with an X11 screen. When control is -- acquired, the display will be deassociated from the X11 screen until -- control is released or the specified display connection is closed. -- Essentially, the X11 screen will behave as if the monitor has been -- unplugged until control is released. -- -- == New Commands -- -- - 'acquireXlibDisplayEXT' -- - ' getRandROutputDisplayEXT ' -- -- == New Enum Constants -- - ' ' -- -- - 'EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION' -- -- == Issues -- 1 ) Should ' acquireXlibDisplayEXT ' take an RandR display ID , or a Vulkan -- display handle as input? -- _ _ RESOLVED _ _ : A Vulkan display handle . Otherwise there would be no way -- to specify handles to displays that had been prevented from being -- included in the X11 display list by some native platform or -- vendor-specific mechanism. -- 2 ) How does an application figure out which RandR display corresponds to a Vulkan display ? -- _ _ RESOLVED _ _ : A new function , ' getRandROutputDisplayEXT ' , is introduced -- for this purpose. -- 3 ) Should ' getRandROutputDisplayEXT ' be part of this extension , or a general Vulkan \/ RandR or Vulkan extension ? -- -- __RESOLVED__: To avoid yet another extension, include it in this -- extension. -- -- == Version History -- - Revision 1 , 2016 - 12 - 13 ( ) -- -- - Initial draft -- -- == See Also -- ' acquireXlibDisplayEXT ' , ' getRandROutputDisplayEXT ' -- -- == Document Notes -- -- For more information, see the -- <-extensions/html/vkspec.html#VK_EXT_acquire_xlib_display Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_EXT_acquire_xlib_display ( acquireXlibDisplayEXT , getRandROutputDisplayEXT , EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION , pattern EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION , EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME , pattern EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME , RROutput , DisplayKHR(..) , Display ) where import Vulkan.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Control.Monad.IO.Class (MonadIO) import Data.String (IsString) import Foreign.Storable (Storable(peek)) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import Data.Word (Word64) import Control.Monad.Trans.Cont (ContT(..)) import Vulkan.NamedType ((:::)) import Vulkan.Extensions.VK_KHR_xlib_surface (Display) import Vulkan.Extensions.Handles (DisplayKHR) import Vulkan.Extensions.Handles (DisplayKHR(..)) import Vulkan.Dynamic (InstanceCmds(pVkAcquireXlibDisplayEXT)) import Vulkan.Dynamic (InstanceCmds(pVkGetRandROutputDisplayEXT)) import Vulkan.Core10.Handles (PhysicalDevice) import Vulkan.Core10.Handles (PhysicalDevice(..)) import Vulkan.Core10.Handles (PhysicalDevice(PhysicalDevice)) import Vulkan.Core10.Handles (PhysicalDevice_T) import Vulkan.Core10.Enums.Result (Result) import Vulkan.Core10.Enums.Result (Result(..)) import Vulkan.Exception (VulkanException(..)) import Vulkan.Core10.Enums.Result (Result(SUCCESS)) import Vulkan.Extensions.VK_KHR_xlib_surface (Display) import Vulkan.Extensions.Handles (DisplayKHR(..)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkAcquireXlibDisplayEXT :: FunPtr (Ptr PhysicalDevice_T -> Ptr Display -> DisplayKHR -> IO Result) -> Ptr PhysicalDevice_T -> Ptr Display -> DisplayKHR -> IO Result | vkAcquireXlibDisplayEXT - Acquire access to a VkDisplayKHR using Xlib -- -- = Description -- -- All permissions necessary to control the display are granted to the Vulkan instance associated with @physicalDevice@ until the display is released or the X11 connection specified by @dpy@ is terminated . -- Permission to access the display /may/ be temporarily revoked during -- periods when the X11 server from which control was acquired itself loses access to @display@. During such periods , operations which require -- access to the display /must/ fail with an appropriate error code. If the -- X11 server associated with @dpy@ does not own @display@, or if -- permission to access it has already been acquired by another entity, the -- call /must/ return the error code ' Vulkan . Core10.Enums . Result . ERROR_INITIALIZATION_FAILED ' . -- -- Note -- One example of when an X11 server loses access to a display is when it -- loses ownership of its virtual terminal. -- -- == Return Codes -- -- [<-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- - ' Vulkan . Core10.Enums . Result . SUCCESS ' -- -- [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- - ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY ' -- - ' Vulkan . Core10.Enums . Result . ERROR_INITIALIZATION_FAILED ' -- -- = See Also -- -- <-extensions/html/vkspec.html#VK_EXT_acquire_xlib_display VK_EXT_acquire_xlib_display>, ' Vulkan . Extensions . Handles . DisplayKHR ' , ' Vulkan . Core10.Handles . PhysicalDevice ' acquireXlibDisplayEXT :: forall io . (MonadIO io) => -- | @physicalDevice@ The physical device the display is on. -- -- #VUID-vkAcquireXlibDisplayEXT-physicalDevice-parameter# @physicalDevice@ /must/ be a valid ' Vulkan . Core10.Handles . PhysicalDevice ' handle PhysicalDevice | @dpy@ A connection to the X11 server that currently owns @display@. -- -- #VUID-vkAcquireXlibDisplayEXT-dpy-parameter# @dpy@ /must/ be a valid pointer to a ' Vulkan . Extensions . VK_KHR_xlib_surface . Display ' value ("dpy" ::: Ptr Display) | @display@ The display the caller wishes to control in Vulkan . -- -- #VUID-vkAcquireXlibDisplayEXT-display-parameter# @display@ /must/ be a valid ' Vulkan . Extensions . Handles . DisplayKHR ' handle -- -- #VUID-vkAcquireXlibDisplayEXT-display-parent# @display@ /must/ have been -- created, allocated, or retrieved from @physicalDevice@ DisplayKHR -> io () acquireXlibDisplayEXT physicalDevice dpy display = liftIO $ do let vkAcquireXlibDisplayEXTPtr = pVkAcquireXlibDisplayEXT (case physicalDevice of PhysicalDevice{instanceCmds} -> instanceCmds) unless (vkAcquireXlibDisplayEXTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkAcquireXlibDisplayEXT is null" Nothing Nothing let vkAcquireXlibDisplayEXT' = mkVkAcquireXlibDisplayEXT vkAcquireXlibDisplayEXTPtr r <- traceAroundEvent "vkAcquireXlibDisplayEXT" (vkAcquireXlibDisplayEXT' (physicalDeviceHandle (physicalDevice)) (dpy) (display)) when (r < SUCCESS) (throwIO (VulkanException r)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetRandROutputDisplayEXT :: FunPtr (Ptr PhysicalDevice_T -> Ptr Display -> RROutput -> Ptr DisplayKHR -> IO Result) -> Ptr PhysicalDevice_T -> Ptr Display -> RROutput -> Ptr DisplayKHR -> IO Result | vkGetRandROutputDisplayEXT - Query the corresponding to an -- X11 RandR Output -- -- = Description -- If there is no ' Vulkan . Extensions . Handles . DisplayKHR ' corresponding to @rrOutput@ on @physicalDevice@ , ' Vulkan . Core10.APIConstants . NULL_HANDLE ' -- /must/ be returned in @pDisplay@. -- -- == Return Codes -- -- [<-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- - ' Vulkan . Core10.Enums . Result . SUCCESS ' -- -- [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- - ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY ' -- -- = See Also -- -- <-extensions/html/vkspec.html#VK_EXT_acquire_xlib_display VK_EXT_acquire_xlib_display>, ' Vulkan . Extensions . Handles . DisplayKHR ' , ' Vulkan . Core10.Handles . PhysicalDevice ' getRandROutputDisplayEXT :: forall io . (MonadIO io) => -- | @physicalDevice@ The physical device to query the display handle on. -- -- #VUID-vkGetRandROutputDisplayEXT-physicalDevice-parameter# -- @physicalDevice@ /must/ be a valid ' Vulkan . Core10.Handles . PhysicalDevice ' handle PhysicalDevice | @dpy@ A connection to the X11 server from which @rrOutput@ was queried . -- -- #VUID-vkGetRandROutputDisplayEXT-dpy-parameter# @dpy@ /must/ be a valid pointer to a ' Vulkan . Extensions . VK_KHR_xlib_surface . Display ' value ("dpy" ::: Ptr Display) -> -- | @rrOutput@ An X11 RandR output ID. RROutput -> io (DisplayKHR) getRandROutputDisplayEXT physicalDevice dpy rrOutput = liftIO . evalContT $ do let vkGetRandROutputDisplayEXTPtr = pVkGetRandROutputDisplayEXT (case physicalDevice of PhysicalDevice{instanceCmds} -> instanceCmds) lift $ unless (vkGetRandROutputDisplayEXTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetRandROutputDisplayEXT is null" Nothing Nothing let vkGetRandROutputDisplayEXT' = mkVkGetRandROutputDisplayEXT vkGetRandROutputDisplayEXTPtr pPDisplay <- ContT $ bracket (callocBytes @DisplayKHR 8) free r <- lift $ traceAroundEvent "vkGetRandROutputDisplayEXT" (vkGetRandROutputDisplayEXT' (physicalDeviceHandle (physicalDevice)) (dpy) (rrOutput) (pPDisplay)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pDisplay <- lift $ peek @DisplayKHR pPDisplay pure $ (pDisplay) type EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION = 1 No documentation found for TopLevel " VK_EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION " pattern EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION :: forall a . Integral a => a pattern EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION = 1 type EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME = "VK_EXT_acquire_xlib_display" No documentation found for TopLevel " VK_EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME " pattern EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME = "VK_EXT_acquire_xlib_display" type RROutput = Word64
null
https://raw.githubusercontent.com/expipiplus1/vulkan/ebc0dde0bcd9cf251f18538de6524eb4f2ab3e9d/src/Vulkan/Extensions/VK_EXT_acquire_xlib_display.hs
haskell
# language CPP # | = Name [__Name String__] @VK_EXT_acquire_xlib_display@ [__Extension Type__] Instance extension [__Registered Extension Number__] [__Revision__] [__Extension and Version Dependencies__] - Requires @VK_EXT_direct_mode_display@ to be enabled [__Contact__] == Other Extension Metadata [__Last Modified Date__] [__IP Status__] No known IP claims. [__Contributors__] == Description This extension allows an application to take exclusive control on a display currently associated with an X11 screen. When control is acquired, the display will be deassociated from the X11 screen until control is released or the specified display connection is closed. Essentially, the X11 screen will behave as if the monitor has been unplugged until control is released. == New Commands - 'acquireXlibDisplayEXT' == New Enum Constants - 'EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION' == Issues display handle as input? to specify handles to displays that had been prevented from being included in the X11 display list by some native platform or vendor-specific mechanism. for this purpose. __RESOLVED__: To avoid yet another extension, include it in this extension. == Version History - Initial draft == See Also == Document Notes For more information, see the <-extensions/html/vkspec.html#VK_EXT_acquire_xlib_display Vulkan Specification> This page is a generated document. Fixes and changes should be made to the generator scripts, not directly. = Description All permissions necessary to control the display are granted to the Permission to access the display /may/ be temporarily revoked during periods when the X11 server from which control was acquired itself loses access to the display /must/ fail with an appropriate error code. If the X11 server associated with @dpy@ does not own @display@, or if permission to access it has already been acquired by another entity, the call /must/ return the error code Note loses ownership of its virtual terminal. == Return Codes [<-extensions/html/vkspec.html#fundamentals-successcodes Success>] [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] = See Also <-extensions/html/vkspec.html#VK_EXT_acquire_xlib_display VK_EXT_acquire_xlib_display>, | @physicalDevice@ The physical device the display is on. #VUID-vkAcquireXlibDisplayEXT-physicalDevice-parameter# @physicalDevice@ #VUID-vkAcquireXlibDisplayEXT-dpy-parameter# @dpy@ /must/ be a valid #VUID-vkAcquireXlibDisplayEXT-display-parameter# @display@ /must/ be a #VUID-vkAcquireXlibDisplayEXT-display-parent# @display@ /must/ have been created, allocated, or retrieved from @physicalDevice@ X11 RandR Output = Description /must/ be returned in @pDisplay@. == Return Codes [<-extensions/html/vkspec.html#fundamentals-successcodes Success>] [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] = See Also <-extensions/html/vkspec.html#VK_EXT_acquire_xlib_display VK_EXT_acquire_xlib_display>, | @physicalDevice@ The physical device to query the display handle on. #VUID-vkGetRandROutputDisplayEXT-physicalDevice-parameter# @physicalDevice@ /must/ be a valid #VUID-vkGetRandROutputDisplayEXT-dpy-parameter# @dpy@ /must/ be a valid | @rrOutput@ An X11 RandR output ID.
VK_EXT_acquire_xlib_display - instance extension = = VK_EXT_acquire_xlib_display 90 1 - Requires support for Vulkan 1.0 - < -Docs/issues/new?body=[VK_EXT_acquire_xlib_display ] @cubanismo%0A*Here describe the issue or question you have about the VK_EXT_acquire_xlib_display extension * > 2016 - 12 - 13 - , Red Hat - , NVIDIA - , NVIDIA - , NVIDIA - , Valve - , NVIDIA - , Intel - ' getRandROutputDisplayEXT ' - ' ' 1 ) Should ' acquireXlibDisplayEXT ' take an RandR display ID , or a Vulkan _ _ RESOLVED _ _ : A Vulkan display handle . Otherwise there would be no way 2 ) How does an application figure out which RandR display corresponds to a Vulkan display ? _ _ RESOLVED _ _ : A new function , ' getRandROutputDisplayEXT ' , is introduced 3 ) Should ' getRandROutputDisplayEXT ' be part of this extension , or a general Vulkan \/ RandR or Vulkan extension ? - Revision 1 , 2016 - 12 - 13 ( ) ' acquireXlibDisplayEXT ' , ' getRandROutputDisplayEXT ' module Vulkan.Extensions.VK_EXT_acquire_xlib_display ( acquireXlibDisplayEXT , getRandROutputDisplayEXT , EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION , pattern EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION , EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME , pattern EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME , RROutput , DisplayKHR(..) , Display ) where import Vulkan.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Control.Monad.IO.Class (MonadIO) import Data.String (IsString) import Foreign.Storable (Storable(peek)) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import Data.Word (Word64) import Control.Monad.Trans.Cont (ContT(..)) import Vulkan.NamedType ((:::)) import Vulkan.Extensions.VK_KHR_xlib_surface (Display) import Vulkan.Extensions.Handles (DisplayKHR) import Vulkan.Extensions.Handles (DisplayKHR(..)) import Vulkan.Dynamic (InstanceCmds(pVkAcquireXlibDisplayEXT)) import Vulkan.Dynamic (InstanceCmds(pVkGetRandROutputDisplayEXT)) import Vulkan.Core10.Handles (PhysicalDevice) import Vulkan.Core10.Handles (PhysicalDevice(..)) import Vulkan.Core10.Handles (PhysicalDevice(PhysicalDevice)) import Vulkan.Core10.Handles (PhysicalDevice_T) import Vulkan.Core10.Enums.Result (Result) import Vulkan.Core10.Enums.Result (Result(..)) import Vulkan.Exception (VulkanException(..)) import Vulkan.Core10.Enums.Result (Result(SUCCESS)) import Vulkan.Extensions.VK_KHR_xlib_surface (Display) import Vulkan.Extensions.Handles (DisplayKHR(..)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkAcquireXlibDisplayEXT :: FunPtr (Ptr PhysicalDevice_T -> Ptr Display -> DisplayKHR -> IO Result) -> Ptr PhysicalDevice_T -> Ptr Display -> DisplayKHR -> IO Result | vkAcquireXlibDisplayEXT - Acquire access to a VkDisplayKHR using Xlib Vulkan instance associated with @physicalDevice@ until the display is released or the X11 connection specified by @dpy@ is terminated . access to @display@. During such periods , operations which require ' Vulkan . Core10.Enums . Result . ERROR_INITIALIZATION_FAILED ' . One example of when an X11 server loses access to a display is when it - ' Vulkan . Core10.Enums . Result . SUCCESS ' - ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY ' - ' Vulkan . Core10.Enums . Result . ERROR_INITIALIZATION_FAILED ' ' Vulkan . Extensions . Handles . DisplayKHR ' , ' Vulkan . Core10.Handles . PhysicalDevice ' acquireXlibDisplayEXT :: forall io . (MonadIO io) /must/ be a valid ' Vulkan . Core10.Handles . PhysicalDevice ' handle PhysicalDevice | @dpy@ A connection to the X11 server that currently owns @display@. pointer to a ' Vulkan . Extensions . VK_KHR_xlib_surface . Display ' value ("dpy" ::: Ptr Display) | @display@ The display the caller wishes to control in Vulkan . valid ' Vulkan . Extensions . Handles . DisplayKHR ' handle DisplayKHR -> io () acquireXlibDisplayEXT physicalDevice dpy display = liftIO $ do let vkAcquireXlibDisplayEXTPtr = pVkAcquireXlibDisplayEXT (case physicalDevice of PhysicalDevice{instanceCmds} -> instanceCmds) unless (vkAcquireXlibDisplayEXTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkAcquireXlibDisplayEXT is null" Nothing Nothing let vkAcquireXlibDisplayEXT' = mkVkAcquireXlibDisplayEXT vkAcquireXlibDisplayEXTPtr r <- traceAroundEvent "vkAcquireXlibDisplayEXT" (vkAcquireXlibDisplayEXT' (physicalDeviceHandle (physicalDevice)) (dpy) (display)) when (r < SUCCESS) (throwIO (VulkanException r)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetRandROutputDisplayEXT :: FunPtr (Ptr PhysicalDevice_T -> Ptr Display -> RROutput -> Ptr DisplayKHR -> IO Result) -> Ptr PhysicalDevice_T -> Ptr Display -> RROutput -> Ptr DisplayKHR -> IO Result | vkGetRandROutputDisplayEXT - Query the corresponding to an If there is no ' Vulkan . Extensions . Handles . DisplayKHR ' corresponding to @rrOutput@ on @physicalDevice@ , ' Vulkan . Core10.APIConstants . NULL_HANDLE ' - ' Vulkan . Core10.Enums . Result . SUCCESS ' - ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY ' ' Vulkan . Extensions . Handles . DisplayKHR ' , ' Vulkan . Core10.Handles . PhysicalDevice ' getRandROutputDisplayEXT :: forall io . (MonadIO io) ' Vulkan . Core10.Handles . PhysicalDevice ' handle PhysicalDevice | @dpy@ A connection to the X11 server from which @rrOutput@ was queried . pointer to a ' Vulkan . Extensions . VK_KHR_xlib_surface . Display ' value ("dpy" ::: Ptr Display) RROutput -> io (DisplayKHR) getRandROutputDisplayEXT physicalDevice dpy rrOutput = liftIO . evalContT $ do let vkGetRandROutputDisplayEXTPtr = pVkGetRandROutputDisplayEXT (case physicalDevice of PhysicalDevice{instanceCmds} -> instanceCmds) lift $ unless (vkGetRandROutputDisplayEXTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetRandROutputDisplayEXT is null" Nothing Nothing let vkGetRandROutputDisplayEXT' = mkVkGetRandROutputDisplayEXT vkGetRandROutputDisplayEXTPtr pPDisplay <- ContT $ bracket (callocBytes @DisplayKHR 8) free r <- lift $ traceAroundEvent "vkGetRandROutputDisplayEXT" (vkGetRandROutputDisplayEXT' (physicalDeviceHandle (physicalDevice)) (dpy) (rrOutput) (pPDisplay)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pDisplay <- lift $ peek @DisplayKHR pPDisplay pure $ (pDisplay) type EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION = 1 No documentation found for TopLevel " VK_EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION " pattern EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION :: forall a . Integral a => a pattern EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION = 1 type EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME = "VK_EXT_acquire_xlib_display" No documentation found for TopLevel " VK_EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME " pattern EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME = "VK_EXT_acquire_xlib_display" type RROutput = Word64
7ca415e31e1035baf0bfe2acc3ebf7cfb699d0cd4db5359f32243630076dd091
chunsj/TH
generator.lisp
(declaim (optimize (speed 3) (debug 1) (safety 0))) (in-package :th) (defmethod $copy! ((generator generator) from) (let ((gen (make-instance 'generator)) (h (th-generator-copy ($handle generator) ($handle from)))) (setf ($handle gen) h) #+sbcl (sb-ext:finalize gen (lambda () (th-generator-free h))) gen)) (defmethod $seed ((generator generator)) (th-random-seed ($handle generator))) (defmethod (setf $seed) (seed (generator generator)) (th-random-manual-seed ($handle generator) (coerce seed 'integer)) seed) (defmethod $random ((generator generator)) (th-random-random ($handle generator))) (defmethod $uniform ((generator generator) a b) (th-random-uniform ($handle generator) (coerce a 'double-float) (coerce b 'double-float))) (defmethod $normal ((generator generator) mean stdev) (th-random-normal ($handle generator) (coerce mean 'double-float) (coerce stdev 'double-float))) (defmethod $exponential ((generator generator) lam) (th-random-exponential ($handle generator) (coerce lam 'double-float))) (defmethod $cauchy ((generator generator) median sigma) (th-random-cauchy ($handle generator) (coerce median 'double-float) (coerce sigma 'double-float))) (defmethod $lognormal ((generator generator) mean stdev) (th-random-log-normal ($handle generator) (coerce mean 'double-float) (coerce stdev 'double-float))) (defmethod $geometric ((generator generator) p) (th-random-geometric ($handle generator) (coerce p 'double-float))) (defmethod $bernoulli ((generator generator) p) (th-random-bernoulli ($handle generator) (coerce p 'double-float))) (defmethod $binomial ((generator generator) n p) (th-random-binomial ($handle generator) (coerce n 'integer) (coerce p 'double-float))) (defmethod $hypergeometric ((generator generator) nr nb k) (th-random-hypergeometric ($handle generator) (coerce (round nr) 'integer) (coerce (round nb) 'integer) (coerce (round k) 'integer))) (defmethod $poisson ((generator generator) mu) (th-random-poisson ($handle generator) (coerce mu 'double-float))) (defmethod $beta ((generator generator) a b) (th-random-beta ($handle generator) (coerce a 'double-float) (coerce b 'double-float))) (defmethod $gamma ((generator generator) shape scale) (th-random-gamma2 ($handle generator) (coerce shape 'double-float) (coerce scale 'double-float))) (defmethod $chisq ((generator generator) df) ($gamma generator (/ df 2.0) 2.0)) (defmethod $fdist ((generator generator) n1 n2) (/ (/ ($chisq generator n1) n1) (/ ($chisq generator n2) n2))) (defun random/random () ($random *generator*)) (defun random/uniform (a b) ($uniform *generator* a b)) (defun random/discrete-uniform (a b) (+ a (random (1+ (- b a))))) (defun random/normal (m s) ($normal *generator* m s)) (defun random/exponential (l) ($exponential *generator* l)) (defun random/cauchy (m s) ($cauchy *generator* m s)) (defun random/lognormal (m s) ($lognormal *generator* m s)) (defun random/geometric (p) ($geometric *generator* p)) (defun random/hypergeometric (nr nb k) ($hypergeometric *generator* nr nb k)) (defun random/poisson (mu) ($poisson *generator* mu)) (defun random/bernoulli (p) ($bernoulli *generator* p)) (defun random/binomial (n p) ($binomial *generator* n p)) (defun random/beta (a b) ($beta *generator* a b)) (defun random/gamma (shape scale) ($gamma *generator* shape scale)) (defun random/chisq (df) ($chisq *generator* df)) (defun random/fdist (n1 n2) ($fdist *generator* n1 n2))
null
https://raw.githubusercontent.com/chunsj/TH/890f05ab81148d9fe558be3979c30c303b448480/binding/generator.lisp
lisp
(declaim (optimize (speed 3) (debug 1) (safety 0))) (in-package :th) (defmethod $copy! ((generator generator) from) (let ((gen (make-instance 'generator)) (h (th-generator-copy ($handle generator) ($handle from)))) (setf ($handle gen) h) #+sbcl (sb-ext:finalize gen (lambda () (th-generator-free h))) gen)) (defmethod $seed ((generator generator)) (th-random-seed ($handle generator))) (defmethod (setf $seed) (seed (generator generator)) (th-random-manual-seed ($handle generator) (coerce seed 'integer)) seed) (defmethod $random ((generator generator)) (th-random-random ($handle generator))) (defmethod $uniform ((generator generator) a b) (th-random-uniform ($handle generator) (coerce a 'double-float) (coerce b 'double-float))) (defmethod $normal ((generator generator) mean stdev) (th-random-normal ($handle generator) (coerce mean 'double-float) (coerce stdev 'double-float))) (defmethod $exponential ((generator generator) lam) (th-random-exponential ($handle generator) (coerce lam 'double-float))) (defmethod $cauchy ((generator generator) median sigma) (th-random-cauchy ($handle generator) (coerce median 'double-float) (coerce sigma 'double-float))) (defmethod $lognormal ((generator generator) mean stdev) (th-random-log-normal ($handle generator) (coerce mean 'double-float) (coerce stdev 'double-float))) (defmethod $geometric ((generator generator) p) (th-random-geometric ($handle generator) (coerce p 'double-float))) (defmethod $bernoulli ((generator generator) p) (th-random-bernoulli ($handle generator) (coerce p 'double-float))) (defmethod $binomial ((generator generator) n p) (th-random-binomial ($handle generator) (coerce n 'integer) (coerce p 'double-float))) (defmethod $hypergeometric ((generator generator) nr nb k) (th-random-hypergeometric ($handle generator) (coerce (round nr) 'integer) (coerce (round nb) 'integer) (coerce (round k) 'integer))) (defmethod $poisson ((generator generator) mu) (th-random-poisson ($handle generator) (coerce mu 'double-float))) (defmethod $beta ((generator generator) a b) (th-random-beta ($handle generator) (coerce a 'double-float) (coerce b 'double-float))) (defmethod $gamma ((generator generator) shape scale) (th-random-gamma2 ($handle generator) (coerce shape 'double-float) (coerce scale 'double-float))) (defmethod $chisq ((generator generator) df) ($gamma generator (/ df 2.0) 2.0)) (defmethod $fdist ((generator generator) n1 n2) (/ (/ ($chisq generator n1) n1) (/ ($chisq generator n2) n2))) (defun random/random () ($random *generator*)) (defun random/uniform (a b) ($uniform *generator* a b)) (defun random/discrete-uniform (a b) (+ a (random (1+ (- b a))))) (defun random/normal (m s) ($normal *generator* m s)) (defun random/exponential (l) ($exponential *generator* l)) (defun random/cauchy (m s) ($cauchy *generator* m s)) (defun random/lognormal (m s) ($lognormal *generator* m s)) (defun random/geometric (p) ($geometric *generator* p)) (defun random/hypergeometric (nr nb k) ($hypergeometric *generator* nr nb k)) (defun random/poisson (mu) ($poisson *generator* mu)) (defun random/bernoulli (p) ($bernoulli *generator* p)) (defun random/binomial (n p) ($binomial *generator* n p)) (defun random/beta (a b) ($beta *generator* a b)) (defun random/gamma (shape scale) ($gamma *generator* shape scale)) (defun random/chisq (df) ($chisq *generator* df)) (defun random/fdist (n1 n2) ($fdist *generator* n1 n2))
438bafb0ded2c77ad553b05afd5ef6a426c7c0b977a78f9adb4fee0e4a19c846
satori-com/mzbench
mzb_worker_runner.erl
-module(mzb_worker_runner). -export([run_worker_script/5]). -include_lib("mzbench_language/include/mzbl_types.hrl"). -spec run_worker_script([script_expr()], worker_env() , module(), Pool :: pid(), PoolName ::string()) -> ok. run_worker_script(Script, Env, Worker, PoolPid, PoolName) -> _ = random:seed(now()), ok = mzb_metrics:notify(mzb_string:format("workers.~s.started", [PoolName]), 1), Res = eval_script(Script, Env, Worker), case Res of {ok, _} -> ok; _ -> mzb_metrics:notify(mzb_string:format("workers.~s.failed", [PoolName]), 1) end, mzb_metrics:notify(mzb_string:format("workers.~s.ended", [PoolName]), 1), PoolPid ! {worker_result, self(), Res}, ok. eval_script(Script, Env, Worker) -> %% we don't want to call terminate if init crashes %% we also don't want to call terminate if another terminate crashes case catch_init(Worker) of {ok, InitState} -> {Res, State} = catch_eval(Script, InitState, Env, Worker), catch_terminate(Res, Worker, State); {exception, Spec} -> {exception, node(), Spec, undefined} end. catch_eval(Script, State, Env, {Provider, _}) -> try {Result, ResState} = mzbl_interpreter:eval(Script, State, Env, Provider), {{ok, Result}, ResState} catch error:{mzbl_interpreter_runtime_error, {{Error, Reason}, ErrorState}} -> ST = erlang:get_stacktrace(), {{exception, {Error, Reason, ST}}, ErrorState}; C:E -> ST = erlang:get_stacktrace(), {{exception, {C, E, ST}}, unknown} end. catch_init({Provider, Worker}) -> try Provider:init(Worker) of InitialState -> {ok, InitialState} catch C:E -> {exception, {C, E, erlang:get_stacktrace()}} end. catch_terminate({ok, Res}, {WorkerProvider, _}, WorkerState) -> try WorkerProvider:terminate(Res, WorkerState), {ok, Res} catch Class:Error -> {exception, node(), {Class, Error, erlang:get_stacktrace()}, WorkerState} end; catch_terminate({exception, Spec}, _, unknown) -> %% do not call terminate in this case because worker provider %% needs it's state to call worker's terminate function {exception, node(), Spec, undefined}; catch_terminate({exception, Spec}, {WorkerProvider, _}, WorkerState) -> try WorkerProvider:terminate(Spec, WorkerState), {exception, node(), Spec, WorkerState} catch Class:Error -> ST = erlang:get_stacktrace(), {exception, node(), {Class, Error, ST}, unknown} end.
null
https://raw.githubusercontent.com/satori-com/mzbench/02be2684655cde94d537c322bb0611e258ae9718/node/apps/mzbench/src/mzb_worker_runner.erl
erlang
we don't want to call terminate if init crashes we also don't want to call terminate if another terminate crashes do not call terminate in this case because worker provider needs it's state to call worker's terminate function
-module(mzb_worker_runner). -export([run_worker_script/5]). -include_lib("mzbench_language/include/mzbl_types.hrl"). -spec run_worker_script([script_expr()], worker_env() , module(), Pool :: pid(), PoolName ::string()) -> ok. run_worker_script(Script, Env, Worker, PoolPid, PoolName) -> _ = random:seed(now()), ok = mzb_metrics:notify(mzb_string:format("workers.~s.started", [PoolName]), 1), Res = eval_script(Script, Env, Worker), case Res of {ok, _} -> ok; _ -> mzb_metrics:notify(mzb_string:format("workers.~s.failed", [PoolName]), 1) end, mzb_metrics:notify(mzb_string:format("workers.~s.ended", [PoolName]), 1), PoolPid ! {worker_result, self(), Res}, ok. eval_script(Script, Env, Worker) -> case catch_init(Worker) of {ok, InitState} -> {Res, State} = catch_eval(Script, InitState, Env, Worker), catch_terminate(Res, Worker, State); {exception, Spec} -> {exception, node(), Spec, undefined} end. catch_eval(Script, State, Env, {Provider, _}) -> try {Result, ResState} = mzbl_interpreter:eval(Script, State, Env, Provider), {{ok, Result}, ResState} catch error:{mzbl_interpreter_runtime_error, {{Error, Reason}, ErrorState}} -> ST = erlang:get_stacktrace(), {{exception, {Error, Reason, ST}}, ErrorState}; C:E -> ST = erlang:get_stacktrace(), {{exception, {C, E, ST}}, unknown} end. catch_init({Provider, Worker}) -> try Provider:init(Worker) of InitialState -> {ok, InitialState} catch C:E -> {exception, {C, E, erlang:get_stacktrace()}} end. catch_terminate({ok, Res}, {WorkerProvider, _}, WorkerState) -> try WorkerProvider:terminate(Res, WorkerState), {ok, Res} catch Class:Error -> {exception, node(), {Class, Error, erlang:get_stacktrace()}, WorkerState} end; catch_terminate({exception, Spec}, _, unknown) -> {exception, node(), Spec, undefined}; catch_terminate({exception, Spec}, {WorkerProvider, _}, WorkerState) -> try WorkerProvider:terminate(Spec, WorkerState), {exception, node(), Spec, WorkerState} catch Class:Error -> ST = erlang:get_stacktrace(), {exception, node(), {Class, Error, ST}, unknown} end.
e283c89d4d11772558e0ea4d570108b4ad4db5975f0c1503b004050d432ae115
altsun/My-Lisps
(TL) Tong chieu dai -DoanQuyen.lsp
;;;-------------------------------------------------------------------- (defun Length1(e) (vlax-curve-getDistAtParam e (vlax-curve-getEndParam e))) ;;;-------------------------------------------------------------------- (defun C:TL( / ss L e) (setq ss (ssget (list (cons 0 "LINE,ARC,CIRCLE,POLYLINE,LWPOLYLINE,ELLIPSE,SPLINE"))) L 0.0 ) (vl-load-com) (while (setq e (ssname ss 0)) (setq L (+ L (length1 e))) (ssdel e ss) ) (alert (strcat "Total length = " (rtos L))) ) ;;;--------------------------------------------------------------------
null
https://raw.githubusercontent.com/altsun/My-Lisps/85476bb09b79ef5e966402cc5158978d1cebd7eb/Common/Length/(TL)%20Tong%20chieu%20dai%20-DoanQuyen.lsp
lisp
-------------------------------------------------------------------- -------------------------------------------------------------------- --------------------------------------------------------------------
(defun Length1(e) (vlax-curve-getDistAtParam e (vlax-curve-getEndParam e))) (defun C:TL( / ss L e) (setq ss (ssget (list (cons 0 "LINE,ARC,CIRCLE,POLYLINE,LWPOLYLINE,ELLIPSE,SPLINE"))) L 0.0 ) (vl-load-com) (while (setq e (ssname ss 0)) (setq L (+ L (length1 e))) (ssdel e ss) ) (alert (strcat "Total length = " (rtos L))) )
e3f7f5cc79f561de156b78bd568c429914c783173ea27af57588f013f4b53c22
dada-lang/dada-model
smoke-test.rkt
#lang racket (require redex) (require "../dada.rkt") (dada-check-program-ok (test-program () ())) (; fn identity(x: int) -> int { x.give } dada-check-program-ok (test-program () ((hello-world (fn (() ((x int)) -> int) = (give (x)))))))
null
https://raw.githubusercontent.com/dada-lang/dada-model/8725154c144c181633c62e7c18879642f91cf98c/racket/z-tests/smoke-test.rkt
racket
fn identity(x: int) -> int { x.give }
#lang racket (require redex) (require "../dada.rkt") (dada-check-program-ok (test-program () ())) dada-check-program-ok (test-program () ((hello-world (fn (() ((x int)) -> int) = (give (x)))))))
110ae044b95db15666c52e79826dbd6247217b80779627b6dde370b21b4561d6
msakai/toysolver
build_artifacts.hs
# LANGUAGE CPP # {-# LANGUAGE OverloadedStrings #-} script for building artifacts on AppVeyor and import Turtle import qualified Control.Foldl as L import Control.Monad import Distribution.Package import Distribution.PackageDescription import Distribution.PackageDescription.Parsec import Distribution.Pretty #if MIN_VERSION_Cabal(3,8,0) import Distribution.Simple.PackageDescription (readGenericPackageDescription) #endif import Distribution.Version import Distribution.Verbosity import qualified System.Info as Info main :: IO () main = sh $ do let (package_platform, exeSuffix, archive) = case Info.os of "mingw32" -> (if Info.arch == "x86_64" then "win64" else "win32", Just "exe", archive7z) "linux" -> ("linux-" ++ Info.arch, Nothing, archiveTarXz) "darwin" -> ("macos", Nothing, archiveTarXz) _ -> error ("unknown os: " ++ Info.os) exe_files = [ "toyconvert" , "toyfmf" , "toyqbf" , "toysat" , "toysmt" , "toysolver" ] ++ [ "assign" , "htc" , "knapsack" , "nonogram" , "nqueens" , "numberlink" , "shortest-path" , "sudoku" ] let addExeSuffix name = case exeSuffix of Just s -> name <.> s Nothing -> name Just local_install_root <- fold (inproc "stack" ["path", "--local-install-root"] empty) L.head ver <- liftIO $ liftM (prettyShow . pkgVersion . package . packageDescription) $ readGenericPackageDescription silent "toysolver.cabal" let pkg :: Turtle.FilePath pkg = fromString $ "toysolver-" <> ver <> "-" <> package_platform b <- testfile pkg when b $ rmtree pkg mktree (pkg </> "bin") let binDir = fromText (lineToText local_install_root) </> "bin" forM exe_files $ \name -> do cp (binDir </> addExeSuffix name) (pkg </> "bin" </> addExeSuffix name) mktree (pkg </> "lib") let libDir = fromText (lineToText local_install_root) </> "lib" when (Info.os == "mingw32") $ do cp (libDir </> "toysat-ipasir.dll") (pkg </> "bin" </> "toysat-ipasir.dll") proc "stack" [ "exec", "--", "dlltool" , "--dllname", "toysat-ipasir.dll" , "--input-def", "app/toysat-ipasir/ipasir.def" , "--output-lib", format fp (pkg </> "lib" </> "toysat-ipasir.dll.a") ] empty return () cptree "samples" (pkg </> "samples") cp "COPYING-GPL" (pkg </> "COPYING-GPL") cp "README.md" (pkg </> "README.md") cp "INSTALL.md" (pkg </> "INSTALL.md") cp "CHANGELOG.markdown" (pkg </> "CHANGELOG.markdown") archive pkg archive7z :: Turtle.FilePath -> Shell () archive7z name = do b <- testfile (name <.> "7z") when b $ rm (name <.> "7z") proc "7z" ["a", format fp (name <.> "7z"), format fp name] empty return () archiveZip :: Turtle.FilePath -> Shell () archiveZip name = do b <- testfile (name <.> "zip") when b $ rm (name <.> "zip") proc "zip" ["-r", format fp (name <.> "zip"), format fp name] empty return () archiveTarXz :: Turtle.FilePath -> Shell () archiveTarXz name = do b <- testfile (name <.> "tar.xz") when b $ rm (name <.> "tar.xz") proc "tar" ["Jcf", format fp (name <.> "tar.xz"), format fp name] empty return ()
null
https://raw.githubusercontent.com/msakai/toysolver/5c6244e303ac3d4a87b2bf916e7c834cdab600e5/misc/build_artifacts.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE CPP # script for building artifacts on AppVeyor and import Turtle import qualified Control.Foldl as L import Control.Monad import Distribution.Package import Distribution.PackageDescription import Distribution.PackageDescription.Parsec import Distribution.Pretty #if MIN_VERSION_Cabal(3,8,0) import Distribution.Simple.PackageDescription (readGenericPackageDescription) #endif import Distribution.Version import Distribution.Verbosity import qualified System.Info as Info main :: IO () main = sh $ do let (package_platform, exeSuffix, archive) = case Info.os of "mingw32" -> (if Info.arch == "x86_64" then "win64" else "win32", Just "exe", archive7z) "linux" -> ("linux-" ++ Info.arch, Nothing, archiveTarXz) "darwin" -> ("macos", Nothing, archiveTarXz) _ -> error ("unknown os: " ++ Info.os) exe_files = [ "toyconvert" , "toyfmf" , "toyqbf" , "toysat" , "toysmt" , "toysolver" ] ++ [ "assign" , "htc" , "knapsack" , "nonogram" , "nqueens" , "numberlink" , "shortest-path" , "sudoku" ] let addExeSuffix name = case exeSuffix of Just s -> name <.> s Nothing -> name Just local_install_root <- fold (inproc "stack" ["path", "--local-install-root"] empty) L.head ver <- liftIO $ liftM (prettyShow . pkgVersion . package . packageDescription) $ readGenericPackageDescription silent "toysolver.cabal" let pkg :: Turtle.FilePath pkg = fromString $ "toysolver-" <> ver <> "-" <> package_platform b <- testfile pkg when b $ rmtree pkg mktree (pkg </> "bin") let binDir = fromText (lineToText local_install_root) </> "bin" forM exe_files $ \name -> do cp (binDir </> addExeSuffix name) (pkg </> "bin" </> addExeSuffix name) mktree (pkg </> "lib") let libDir = fromText (lineToText local_install_root) </> "lib" when (Info.os == "mingw32") $ do cp (libDir </> "toysat-ipasir.dll") (pkg </> "bin" </> "toysat-ipasir.dll") proc "stack" [ "exec", "--", "dlltool" , "--dllname", "toysat-ipasir.dll" , "--input-def", "app/toysat-ipasir/ipasir.def" , "--output-lib", format fp (pkg </> "lib" </> "toysat-ipasir.dll.a") ] empty return () cptree "samples" (pkg </> "samples") cp "COPYING-GPL" (pkg </> "COPYING-GPL") cp "README.md" (pkg </> "README.md") cp "INSTALL.md" (pkg </> "INSTALL.md") cp "CHANGELOG.markdown" (pkg </> "CHANGELOG.markdown") archive pkg archive7z :: Turtle.FilePath -> Shell () archive7z name = do b <- testfile (name <.> "7z") when b $ rm (name <.> "7z") proc "7z" ["a", format fp (name <.> "7z"), format fp name] empty return () archiveZip :: Turtle.FilePath -> Shell () archiveZip name = do b <- testfile (name <.> "zip") when b $ rm (name <.> "zip") proc "zip" ["-r", format fp (name <.> "zip"), format fp name] empty return () archiveTarXz :: Turtle.FilePath -> Shell () archiveTarXz name = do b <- testfile (name <.> "tar.xz") when b $ rm (name <.> "tar.xz") proc "tar" ["Jcf", format fp (name <.> "tar.xz"), format fp name] empty return ()
499ac35e7c3103c345439b8a2e4a7fcf8494e29716b606448879ce35cc427dde
ocsigen/ocsigen-start
demo_pgocaml_db.ml
(* This file was generated by Ocsigen Start. Feel free to use it, modify it, and redistribute it as you wish. *) open Os_db We are using PGOCaml to make type safe DB requests to Postgresql . The Makefile automatically compiles all files * _ db.ml with PGOCaml 's ppx syntax extension . The Makefile automatically compiles all files *_db.ml with PGOCaml's ppx syntax extension. *) let get () = full_transaction_block (fun dbh -> [%pgsql dbh "SELECT lastname FROM ocsigen_start.users"])
null
https://raw.githubusercontent.com/ocsigen/ocsigen-start/ec2c827682bcb1f6a60fa65ba9ca8d67d8b64429/template.distillery/demo_pgocaml_db.ml
ocaml
This file was generated by Ocsigen Start. Feel free to use it, modify it, and redistribute it as you wish.
open Os_db We are using PGOCaml to make type safe DB requests to Postgresql . The Makefile automatically compiles all files * _ db.ml with PGOCaml 's ppx syntax extension . The Makefile automatically compiles all files *_db.ml with PGOCaml's ppx syntax extension. *) let get () = full_transaction_block (fun dbh -> [%pgsql dbh "SELECT lastname FROM ocsigen_start.users"])
2cc61f712ee295449c2d191f72df740f813778565c3456d56b3b835088fb7317
Clozure/ccl-tests
imagpart.lsp
;-*- Mode: Lisp -*- Author : Created : Sun Sep 7 07:47:43 2003 Contains : Tests of IMAGPART (in-package :cl-test) (deftest imagpart.error.1 (signals-error (imagpart) program-error) t) (deftest imagpart.error.2 (signals-error (imagpart #c(1.0 2.0) nil) program-error) t) (deftest imagpart.error.3 (check-type-error #'imagpart #'numberp) nil) (deftest imagpart.1 (loop for x in *reals* for c = (complex 0 x) for ip = (imagpart c) unless (eql x ip) collect (list x c ip)) nil) (deftest imagpart.2 (loop for x in *reals* for c = (complex 1 x) for ip = (imagpart c) unless (eql x ip) collect (list x c ip)) nil) (deftest imagpart.3 (loop for x in *reals* for c = (complex x x) for ip = (imagpart c) unless (eql x ip) collect (list x c ip)) nil) (deftest imagpart.4 (loop for x in *reals* for ip = (imagpart x) unless (eql (* 0 x) ip) collect (list x ip (* 0 x))) nil)
null
https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/imagpart.lsp
lisp
-*- Mode: Lisp -*-
Author : Created : Sun Sep 7 07:47:43 2003 Contains : Tests of IMAGPART (in-package :cl-test) (deftest imagpart.error.1 (signals-error (imagpart) program-error) t) (deftest imagpart.error.2 (signals-error (imagpart #c(1.0 2.0) nil) program-error) t) (deftest imagpart.error.3 (check-type-error #'imagpart #'numberp) nil) (deftest imagpart.1 (loop for x in *reals* for c = (complex 0 x) for ip = (imagpart c) unless (eql x ip) collect (list x c ip)) nil) (deftest imagpart.2 (loop for x in *reals* for c = (complex 1 x) for ip = (imagpart c) unless (eql x ip) collect (list x c ip)) nil) (deftest imagpart.3 (loop for x in *reals* for c = (complex x x) for ip = (imagpart c) unless (eql x ip) collect (list x c ip)) nil) (deftest imagpart.4 (loop for x in *reals* for ip = (imagpart x) unless (eql (* 0 x) ip) collect (list x ip (* 0 x))) nil)
6e413a67537e160b57e5afd191fe6f2a64b57f3d72f4c7e1ae152b8a7be8761e
mirage/wodan
test_wodan.ml
* Copyright ( c ) 2013 - 2017 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2013-2017 Thomas Gazagnaire <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open Lwt.Infix module BlockCon = struct include Ramdisk let connect name = Ramdisk.connect ~name defaults to 32 K sectors ( 16MiB ) , we need more for wide inode tests Ramdisk.create ~name ~size_sectors:131072L ~sector_size:512 >|= Result.get_ok let discard _ _ _ = Lwt.return (Ok ()) end module DB_ram = Wodan_irmin.DB_BUILDER (BlockCon) (Wodan_irmin.StandardSuperblockParams) let store = Irmin_test.store ( module Wodan_irmin . Make(DB_ram ) ) ( module Irmin . Metadata . None ) let store = (module Wodan_irmin.KV_chunked (DB_ram) (Irmin.Hash.SHA1) (Irmin.Contents.String) : Irmin_test.S) let config = Wodan_irmin.config ~path:"disk.img" ~create:true () let clean () = let (module S : Irmin_test.S) = store in S.Repo.v config >>= fun repo -> S.Repo.branches repo >>= Lwt_list.iter_p (S.Branch.remove repo) let init () = Nocrypto_entropy_lwt.initialize () let stats = None let suite = { Irmin_test.name = "WODAN"; Irmin_test.layered_store = None; init; clean; config; store; stats; }
null
https://raw.githubusercontent.com/mirage/wodan/fd70abdb45fa176557178435217e0ab114e4e4d0/tests/wodan-irmin/test_wodan.ml
ocaml
* Copyright ( c ) 2013 - 2017 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2013-2017 Thomas Gazagnaire <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open Lwt.Infix module BlockCon = struct include Ramdisk let connect name = Ramdisk.connect ~name defaults to 32 K sectors ( 16MiB ) , we need more for wide inode tests Ramdisk.create ~name ~size_sectors:131072L ~sector_size:512 >|= Result.get_ok let discard _ _ _ = Lwt.return (Ok ()) end module DB_ram = Wodan_irmin.DB_BUILDER (BlockCon) (Wodan_irmin.StandardSuperblockParams) let store = Irmin_test.store ( module Wodan_irmin . Make(DB_ram ) ) ( module Irmin . Metadata . None ) let store = (module Wodan_irmin.KV_chunked (DB_ram) (Irmin.Hash.SHA1) (Irmin.Contents.String) : Irmin_test.S) let config = Wodan_irmin.config ~path:"disk.img" ~create:true () let clean () = let (module S : Irmin_test.S) = store in S.Repo.v config >>= fun repo -> S.Repo.branches repo >>= Lwt_list.iter_p (S.Branch.remove repo) let init () = Nocrypto_entropy_lwt.initialize () let stats = None let suite = { Irmin_test.name = "WODAN"; Irmin_test.layered_store = None; init; clean; config; store; stats; }
4a5707948c11b01acbe6ea3f8e3bce46dc1291f2d4772958bdf3189d43402fe0
Opetushallitus/ataru
question_util.clj
(ns ataru.applications.question-util (:require [ataru.translations.texts :refer [base-education-2nd-module-texts]] [clojure.walk :refer [keywordize-keys]] [ataru.component-data.base-education-module-2nd :refer [base-education-choice-key base-education-wrapper-key base-education-2nd-language-value-to-lang]])) (def sora-question-wrapper-label {:fi "Terveydelliset tekijät " :sv "Hälsoskäl"}) (def urheilijan-lisakysymykset-lukiokohteisiin-wrapper-key "8466feca-1993-4af3-b82c-59003ca2fd63") (def urheilija-muu-laji-label {:fi "Muu, mikä?", :sv "Annan, vad?"}) (def urheilija-paalaji-folloup-label {:fi "Päälaji", :sv "Huvudgren"}) (def lukio-kaksoistutkinto-wrapper-label {:fi "Ammatilliset opinnot lukiokoulutuksen ohella", :sv "Yrkesinriktade studier vid sidan av gymnasieutbildningen"}) (def amm-kaksoistutkinto-wrapper-label {:fi "Lukio-opinnot ammatillisen koulutuksen ohella", :sv "Gymnasiestudier vid sidan av den yrkesinriktade utbildningen"}) (def kiinnostunut-oppisopimuskoulutuksesta-wrapper-label {:fi "Oppisopimuskoulutus ", :sv "Läroavtalsutbildning"}) (def urheilijan-lisakysymykset-wrapper-label {:fi "Urheilijan lisäkysymykset ammatillisissa kohteissa", :sv "Tilläggsfrågor för idrottare i yrkesinriktade ansökningsmål"}) fixme , kysymys - id : t kohdilleen . (defn- urheilijan-lisakysymys-keys [haku-oid] (case haku-oid "1.2.246.562.29.00000000000000005368" {:keskiarvo "7b88594a-c308-41f8-bac3-2d3779ea4443" :peruskoulu "9a4de985-9a70-4de6-bfa7-0a5c2f18cb8c" :tamakausi "f944c9c3-c1f8-43c7-a27e-49d89d4e8eec" :viimekausi "e3e8b5ef-f8d9-4256-8ef6-1a52d562a370" :toissakausi "95b565ee-f64e-4805-b319-55b99bbce1a8" :sivulaji "dbfc1215-896a-47d4-bc07-b9f1494658f4" :valmentaja_nimi "a1f1147a-d466-4d98-9a62-079a42dd4089" :valmentaja_email "625fe96d-a5ff-4b3a-8ace-e36524215d1c" :valmentaja_puh "f1c5986c-bea8-44f7-8324-d1cac179e6f4" :valmennusryhma_seurajoukkue "92d579fb-dafa-4edc-9e05-8f493badc4f3" :valmennusryhma_piirijoukkue "58125631-762a-499b-a402-717778bf8233" :valmennusryhma_maajoukkue "261d7ffc-54a7-4c5c-ab80-82f7de49f648" :paalajiSeuraLiittoParent "98951abd-fdd5-46a0-8427-78fe9706d286"} {:keskiarvo "urheilija-2nd-keskiarvo" :peruskoulu "urheilija-2nd-peruskoulu" :tamakausi "urheilija-2nd-tamakausi" :viimekausi "urheilija-2nd-viimekausi" :toissakausi "urheilija-2nd-toissakausi" :sivulaji "urheilija-2nd-sivulaji" :valmentaja_nimi "urheilija-2nd-valmentaja-nimi" :valmentaja_email "urheilija-2nd-valmentaja-email" :valmentaja_puh "urheilija-2nd-valmentaja-puh" :valmennusryhma_seurajoukkue "urheilija-2nd-valmennus-seurajoukkue" :valmennusryhma_piirijoukkue "urheilija-2nd-valmennus-piirijoukkue" :valmennusryhma_maajoukkue "urheilija-2nd-valmennus-maajoukkue" :valmennusryhmatParent "84cd8829-ee39-437f-b730-9d68f0f07555" :paalaji-dropdown "urheilija-2nd-lajivalinta-dropdown" :seura "urheilija-2nd-seura" :liitto "urheilija-2nd-liitto"})) ;This should at some point be replaced by hardcoded id's for the fields. (defn assoc-deduced-vakio-answers-for-toinen-aste-application [questions application] (let [answers (:keyValues application) pohjakoulutus-vuosi-key (some->> (:tutkintovuosi-keys questions) (filter #(not (nil? (get answers (name %))))) first name) pohjakoulutus-vuosi (when pohjakoulutus-vuosi-key (get answers pohjakoulutus-vuosi-key)) pohjakoulutus-kieli-key (some->> (:tutkintokieli-keys questions) (filter #(not (nil? (get answers (name %))))) first name) pohjakoulutus-kieli-answer (when pohjakoulutus-kieli-key (get answers (name pohjakoulutus-kieli-key))) pohjakoulutus-kieli (base-education-2nd-language-value-to-lang pohjakoulutus-kieli-answer)] (update application :keyValues (fn [kv] (merge kv {"pohjakoulutus_vuosi" pohjakoulutus-vuosi "pohjakoulutus_kieli" pohjakoulutus-kieli}))))) (defn get-hakurekisteri-toinenaste-specific-questions ([form] (get-hakurekisteri-toinenaste-specific-questions form "unknown haku")) ([form haku-oid] (let [content (:content (keywordize-keys form)) base-education-options-followups (->> content (filter #(= base-education-wrapper-key (:id %))) first :children (filter #(= base-education-choice-key (:id %))) first :options (mapcat :followups)) tutkintovuosi-keys (->> base-education-options-followups (filter #(= (:year-of-graduation-question base-education-2nd-module-texts) (:label %))) (map #(keyword (:id %)))) tutkintokieli-keys (->> base-education-options-followups (filter #(= (:study-language base-education-2nd-module-texts) (:label %))) (map #(keyword (:id %)))) sora-wrapper-children (->> content (filter #(= sora-question-wrapper-label (:label %))) first :children) sora-terveys-question (get-in sora-wrapper-children [0 :id]) sora-aiempi-question (get-in sora-wrapper-children [1 :id]) kaksoistutkinto-questions (->> content (filter #(or (= lukio-kaksoistutkinto-wrapper-label (:label %)) (= amm-kaksoistutkinto-wrapper-label (:label %)))) (map #(get-in % [:children 0 :id]))) oppisopimuskoulutus-key (->> content (filter #(= kiinnostunut-oppisopimuskoulutuksesta-wrapper-label (:label %))) first :children first :id) urhelijian-ammatilliset-lisakysymykset-question (->> content (filter #(= urheilijan-lisakysymykset-wrapper-label (:label %))) first :children first) urheilija-keys (urheilijan-lisakysymys-keys haku-oid) laji-options (->> content (filter #(= urheilijan-lisakysymykset-lukiokohteisiin-wrapper-key (:id %))) first :children (filter #(= (:paalaji-dropdown urheilija-keys) (:id %))) first :options) laji-value-to-label (into {} (map (fn [laji] {(:value laji) (:label laji)}) laji-options)) muu-laji-key (->> laji-options (filter #(= urheilija-muu-laji-label (:label %))) first :followups (filter #(= urheilija-paalaji-folloup-label (:label %))) first :id)] {:tutkintovuosi-keys tutkintovuosi-keys :tutkintokieli-keys tutkintokieli-keys :sora-terveys-key sora-terveys-question :sora-aiempi-key sora-aiempi-question :kaksoistutkinto-keys kaksoistutkinto-questions :oppisopimuskoulutus-key (keyword oppisopimuskoulutus-key) :urheilijan-amm-lisakysymys-key (keyword (:id urhelijian-ammatilliset-lisakysymykset-question)) :urheilijan-amm-groups (set (:belongs-to-hakukohderyhma urhelijian-ammatilliset-lisakysymykset-question)) :urheilijan-lisakysymys-keys urheilija-keys :urheilijan-lisakysymys-laji-key-and-mapping {:laji-dropdown-key (keyword (:paalaji-dropdown urheilija-keys)) :muu-laji-key (keyword muu-laji-key) :value-to-label laji-value-to-label}})))
null
https://raw.githubusercontent.com/Opetushallitus/ataru/d92d3fcd097d3a4f535c28be17e7e189d7449451/src/clj/ataru/applications/question_util.clj
clojure
This should at some point be replaced by hardcoded id's for the fields.
(ns ataru.applications.question-util (:require [ataru.translations.texts :refer [base-education-2nd-module-texts]] [clojure.walk :refer [keywordize-keys]] [ataru.component-data.base-education-module-2nd :refer [base-education-choice-key base-education-wrapper-key base-education-2nd-language-value-to-lang]])) (def sora-question-wrapper-label {:fi "Terveydelliset tekijät " :sv "Hälsoskäl"}) (def urheilijan-lisakysymykset-lukiokohteisiin-wrapper-key "8466feca-1993-4af3-b82c-59003ca2fd63") (def urheilija-muu-laji-label {:fi "Muu, mikä?", :sv "Annan, vad?"}) (def urheilija-paalaji-folloup-label {:fi "Päälaji", :sv "Huvudgren"}) (def lukio-kaksoistutkinto-wrapper-label {:fi "Ammatilliset opinnot lukiokoulutuksen ohella", :sv "Yrkesinriktade studier vid sidan av gymnasieutbildningen"}) (def amm-kaksoistutkinto-wrapper-label {:fi "Lukio-opinnot ammatillisen koulutuksen ohella", :sv "Gymnasiestudier vid sidan av den yrkesinriktade utbildningen"}) (def kiinnostunut-oppisopimuskoulutuksesta-wrapper-label {:fi "Oppisopimuskoulutus ", :sv "Läroavtalsutbildning"}) (def urheilijan-lisakysymykset-wrapper-label {:fi "Urheilijan lisäkysymykset ammatillisissa kohteissa", :sv "Tilläggsfrågor för idrottare i yrkesinriktade ansökningsmål"}) fixme , kysymys - id : t kohdilleen . (defn- urheilijan-lisakysymys-keys [haku-oid] (case haku-oid "1.2.246.562.29.00000000000000005368" {:keskiarvo "7b88594a-c308-41f8-bac3-2d3779ea4443" :peruskoulu "9a4de985-9a70-4de6-bfa7-0a5c2f18cb8c" :tamakausi "f944c9c3-c1f8-43c7-a27e-49d89d4e8eec" :viimekausi "e3e8b5ef-f8d9-4256-8ef6-1a52d562a370" :toissakausi "95b565ee-f64e-4805-b319-55b99bbce1a8" :sivulaji "dbfc1215-896a-47d4-bc07-b9f1494658f4" :valmentaja_nimi "a1f1147a-d466-4d98-9a62-079a42dd4089" :valmentaja_email "625fe96d-a5ff-4b3a-8ace-e36524215d1c" :valmentaja_puh "f1c5986c-bea8-44f7-8324-d1cac179e6f4" :valmennusryhma_seurajoukkue "92d579fb-dafa-4edc-9e05-8f493badc4f3" :valmennusryhma_piirijoukkue "58125631-762a-499b-a402-717778bf8233" :valmennusryhma_maajoukkue "261d7ffc-54a7-4c5c-ab80-82f7de49f648" :paalajiSeuraLiittoParent "98951abd-fdd5-46a0-8427-78fe9706d286"} {:keskiarvo "urheilija-2nd-keskiarvo" :peruskoulu "urheilija-2nd-peruskoulu" :tamakausi "urheilija-2nd-tamakausi" :viimekausi "urheilija-2nd-viimekausi" :toissakausi "urheilija-2nd-toissakausi" :sivulaji "urheilija-2nd-sivulaji" :valmentaja_nimi "urheilija-2nd-valmentaja-nimi" :valmentaja_email "urheilija-2nd-valmentaja-email" :valmentaja_puh "urheilija-2nd-valmentaja-puh" :valmennusryhma_seurajoukkue "urheilija-2nd-valmennus-seurajoukkue" :valmennusryhma_piirijoukkue "urheilija-2nd-valmennus-piirijoukkue" :valmennusryhma_maajoukkue "urheilija-2nd-valmennus-maajoukkue" :valmennusryhmatParent "84cd8829-ee39-437f-b730-9d68f0f07555" :paalaji-dropdown "urheilija-2nd-lajivalinta-dropdown" :seura "urheilija-2nd-seura" :liitto "urheilija-2nd-liitto"})) (defn assoc-deduced-vakio-answers-for-toinen-aste-application [questions application] (let [answers (:keyValues application) pohjakoulutus-vuosi-key (some->> (:tutkintovuosi-keys questions) (filter #(not (nil? (get answers (name %))))) first name) pohjakoulutus-vuosi (when pohjakoulutus-vuosi-key (get answers pohjakoulutus-vuosi-key)) pohjakoulutus-kieli-key (some->> (:tutkintokieli-keys questions) (filter #(not (nil? (get answers (name %))))) first name) pohjakoulutus-kieli-answer (when pohjakoulutus-kieli-key (get answers (name pohjakoulutus-kieli-key))) pohjakoulutus-kieli (base-education-2nd-language-value-to-lang pohjakoulutus-kieli-answer)] (update application :keyValues (fn [kv] (merge kv {"pohjakoulutus_vuosi" pohjakoulutus-vuosi "pohjakoulutus_kieli" pohjakoulutus-kieli}))))) (defn get-hakurekisteri-toinenaste-specific-questions ([form] (get-hakurekisteri-toinenaste-specific-questions form "unknown haku")) ([form haku-oid] (let [content (:content (keywordize-keys form)) base-education-options-followups (->> content (filter #(= base-education-wrapper-key (:id %))) first :children (filter #(= base-education-choice-key (:id %))) first :options (mapcat :followups)) tutkintovuosi-keys (->> base-education-options-followups (filter #(= (:year-of-graduation-question base-education-2nd-module-texts) (:label %))) (map #(keyword (:id %)))) tutkintokieli-keys (->> base-education-options-followups (filter #(= (:study-language base-education-2nd-module-texts) (:label %))) (map #(keyword (:id %)))) sora-wrapper-children (->> content (filter #(= sora-question-wrapper-label (:label %))) first :children) sora-terveys-question (get-in sora-wrapper-children [0 :id]) sora-aiempi-question (get-in sora-wrapper-children [1 :id]) kaksoistutkinto-questions (->> content (filter #(or (= lukio-kaksoistutkinto-wrapper-label (:label %)) (= amm-kaksoistutkinto-wrapper-label (:label %)))) (map #(get-in % [:children 0 :id]))) oppisopimuskoulutus-key (->> content (filter #(= kiinnostunut-oppisopimuskoulutuksesta-wrapper-label (:label %))) first :children first :id) urhelijian-ammatilliset-lisakysymykset-question (->> content (filter #(= urheilijan-lisakysymykset-wrapper-label (:label %))) first :children first) urheilija-keys (urheilijan-lisakysymys-keys haku-oid) laji-options (->> content (filter #(= urheilijan-lisakysymykset-lukiokohteisiin-wrapper-key (:id %))) first :children (filter #(= (:paalaji-dropdown urheilija-keys) (:id %))) first :options) laji-value-to-label (into {} (map (fn [laji] {(:value laji) (:label laji)}) laji-options)) muu-laji-key (->> laji-options (filter #(= urheilija-muu-laji-label (:label %))) first :followups (filter #(= urheilija-paalaji-folloup-label (:label %))) first :id)] {:tutkintovuosi-keys tutkintovuosi-keys :tutkintokieli-keys tutkintokieli-keys :sora-terveys-key sora-terveys-question :sora-aiempi-key sora-aiempi-question :kaksoistutkinto-keys kaksoistutkinto-questions :oppisopimuskoulutus-key (keyword oppisopimuskoulutus-key) :urheilijan-amm-lisakysymys-key (keyword (:id urhelijian-ammatilliset-lisakysymykset-question)) :urheilijan-amm-groups (set (:belongs-to-hakukohderyhma urhelijian-ammatilliset-lisakysymykset-question)) :urheilijan-lisakysymys-keys urheilija-keys :urheilijan-lisakysymys-laji-key-and-mapping {:laji-dropdown-key (keyword (:paalaji-dropdown urheilija-keys)) :muu-laji-key (keyword muu-laji-key) :value-to-label laji-value-to-label}})))
77015f705af55a2852a08732df5d25a64981c6674f9c8229ec6547ce347d8c49
GNOME/gimp-tiny-fu
palette-export.scm
; ----------------------------------------------------------------------------- ; GIMP palette export toolkit - Written by < > ; This script includes various exporters for GIMP palettes , and other ; utility function to help in exporting to other (text-based) formats. ; See instruction on adding new exporters at the end ; ; ----------------------------------------------------------------------------- ; Numbers and Math ; ----------------------------------------------------------------------------- ; For all the opertations below, this is the order of respectable digits: (define conversion-digits (list "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z")) ; Converts a decimal number to another base. The returned number is a string (define (convert-decimal-to-base num base) (define (highest-order num base) (if (and (<= 0 num) (< num base)) 0 (+ 1 (highest-order (quotient num base) base)) ) ) (define (calc base num str) (let ((max-order (highest-order num base))) (cond ((not (= 0 max-order)) (let ((num-of-times (quotient num (inexact->exact (expt base max-order))))) (calc base (- num (* num-of-times (expt base max-order))) (string-append str (list-ref conversion-digits num-of-times))) ) ) (else (string-append str (list-ref conversion-digits num))) )) ) (calc base num "") ) ; Convert a string representation of a number in some base, to a decimal number (define (convert-base-to-decimal base num-str) (define (convert-char num-char) (if (char-numeric? num-char) (string->number (string num-char)) (+ 10 (- (char->integer num-char) (char->integer #\a))) ) ) (define (calc base num-str num) (if (equal? num-str "") num (calc base (substring num-str 1) (+ (* num base) (convert-char (string-ref num-str 0))) ) ) ) (calc base num-str 0) ) ; If a string num-str is shorter then size, pad it with pad-str in the ; begining untill it's at least size long (define (pre-pad-number num-str size pad-str) (if (< (string-length num-str) size) (pre-pad-number (string-append pad-str num-str) size pad-str) num-str ) ) ; ----------------------------------------------------------------------------- Color convertors ; ----------------------------------------------------------------------------- ; The standard way for representing a color would be a list of red green and blue ( GIMP 's default ) (define color-get-red car) (define color-get-green cadr) (define color-get-blue caddr) ; Convert a color to a hexadecimal string ' ( 255 255 255 ) = > " # ffffff " (define (color-rgb-to-hexa-decimal color) (string-append "#" (pre-pad-number (convert-decimal-to-base (color-get-red color) 16) 2 "0") (pre-pad-number (convert-decimal-to-base (color-get-green color) 16) 2 "0") (pre-pad-number (convert-decimal-to-base (color-get-blue color) 16) 2 "0") ) ) ; Convert a color to a css color ' ( 255 255 255 ) = > " rgb(255 , 255 , 255 ) " (define (color-rgb-to-css color) (string-append "rgb(" (number->string (color-get-red color)) ", " (number->string (color-get-green color)) ", " (number->string (color-get-blue color)) ")") ) ; Convert a color to a simple pair of braces with comma seperated values ' ( 255 255 255 ) = > " ( 255 , 255 , 255 ) " (define (color-rgb-to-comma-seperated-list color) (string-append "(" (number->string (color-get-red color)) ", " (number->string (color-get-green color)) ", " (number->string (color-get-blue color)) ")") ) ; ----------------------------------------------------------------------------- ; Export utils ; ----------------------------------------------------------------------------- ; List of charcters that should not appear in file names (define illegal-file-name-chars (list #\\ #\/ #\: #\* #\? #\" #\< #\> #\|)) A function to filter a list lst by a given predicate pred (define (filter pred lst) (if (null? lst) '() (if (pred (car lst)) (cons (car lst) (filter pred (cdr lst))) (filter pred (cdr lst)) ) ) ) A function to check if a certain value obj is inside a list lst (define (contained? obj lst) (member obj lst)) ; This functions filters a string to have only characters which are ; either alpha-numeric or contained in more-legal (which is a variable ; holding a list of characters) (define (clean str more-legal) (list->string (filter (lambda (ch) (or (char-alphabetic? ch) (char-numeric? ch) (contained? ch more-legal))) (string->list str))) ) ; A function that recieves the a file-name, and filters out all the ; character that shouldn't appear in file names. Then, it makes sure ; the remaining name isn't only white-spaces. If it's only ; white-spaces, the function returns false. Otherwise, it returns the ; fixed file-name (define (valid-file-name name) (let* ((clean (list->string (filter (lambda (ch) (not (contained? ch illegal-file-name-chars))) (string->list name)))) (clean-without-spaces (list->string (filter (lambda (ch) (not (char-whitespace? ch))) (string->list clean)))) ) (if (equal? clean-without-spaces "") #f clean ) ) ) ; Filters a string from all the characters which are not alpha-numeric ; (this also removes whitespaces) (define (name-alpha-numeric str) (clean str '()) ) ; This function does the same as name-alpha-numeric, with an added ; operation - it removes any numbers from the begining (define (name-standard str) (let ((cleaned (clean str '()))) (while (char-numeric? (string-ref cleaned 0)) (set! cleaned (substring cleaned 1)) ) cleaned ) ) (define name-no-conversion (lambda (obj) obj)) (define color-none (lambda (x) "")) (define name-none (lambda (x) "")) (define displayln (lambda (obj) (display obj) (display "\n"))) ; The loop for exporting all the colors (define (export-palette palette-name color-convertor name-convertor start name-pre name-after name-color-seperator color-pre color-after entry-seperator end) (define (write-color-line index) (display name-pre) (display (name-convertor (car (gimp-palette-entry-get-name palette-name index)))) (display name-after) (display name-color-seperator) (display color-pre) (display (color-convertor (car (gimp-palette-entry-get-color palette-name index)))) (display color-after) ) (let ((color-count (car (gimp-palette-get-colors palette-name))) (i 0) ) (display start) (while (< i (- color-count 1)) (begin (write-color-line i) (display entry-seperator) (set! i (+ 1 i)) ) ) (write-color-line i) (display end) ) ) (define (register-palette-exporter export-type export-name file-type description author copyright date) (script-fu-register (string-append "gimp-palette-export-" export-type) export-name description author copyright date "" SF-DIRNAME _"Folder for the output file" "" SF-STRING _"The name of the file to create (if a file with this name already exist, it will be replaced)" (string-append "palette." file-type) ) (script-fu-menu-register (string-append "gimp-palette-export-" export-type) "<Palettes>/Export as") ) (define (bad-file-name) (gimp-message (string-append _"The filename you entered is not a suitable name for a file." "\n\n" _"All characters in the name are either white-spaces or characters which can not appear in filenames."))) ; ----------------------------------------------------------------------------- ; Exporters ; ----------------------------------------------------------------------------- (define (gimp-palette-export-css directory-name file-name) (let ((valid-name (valid-file-name file-name))) (if valid-name (with-output-to-file (string-append directory-name DIR-SEPARATOR file-name) (lambda () (export-palette (car (gimp-context-get-palette)) color-rgb-to-css name-alpha-numeric ; name-convertor "/* Generated with GIMP Palette Export */\n" ; start "." ; name-pre "" ; name-after " { " ; name-color-seperator "color: " ; color-pre " }" ; color-after "\n" ; entry-seperator "" ; end ))) (bad-file-name) ) ) ) (register-palette-exporter "css" "_CSS stylesheet..." "css" (string-append _"Export the active palette as a CSS stylesheet with the color entry name as their class name, and the color itself as the color attribute") "Barak Itkin <>" "Barak Itkin" "May 15th, 2009") (define (gimp-palette-export-php directory-name file-name) (let ((valid-name (valid-file-name file-name))) (if valid-name (with-output-to-file (string-append directory-name DIR-SEPARATOR file-name) (lambda () (export-palette (car (gimp-context-get-palette)) color-rgb-to-hexa-decimal name-standard ; name-convertor "<?php\n/* Generated with GIMP Palette Export */\n$colors={\n" ; start "'" ; name-pre "'" ; name-after " => " ; name-color-seperator "'" ; color-pre "'" ; color-after ",\n" ; entry-seperator "}\n?>" ; end ))) (bad-file-name) ) ) ) (register-palette-exporter "php" "P_HP dictionary..." "php" _"Export the active palette as a PHP dictionary (name => color)" "Barak Itkin <>" "Barak Itkin" "May 15th, 2009") (define (gimp-palette-export-python directory-name file-name) (let ((valid-name (valid-file-name file-name))) (if valid-name (with-output-to-file (string-append directory-name DIR-SEPARATOR file-name) (lambda () (let ((palette-name (car (gimp-context-get-palette)))) (begin (displayln "# Generated with GIMP Palette Export") (displayln (string-append "# Based on the palette " palette-name)) (export-palette palette-name color-rgb-to-hexa-decimal name-standard ; name-convertor "colors={\n" ; start "'" ; name-pre "'" ; name-after ": " ; name-color-seperator "'" ; color-pre "'" ; color-after ",\n" ; entry-seperator "}" ; end )))) ) (bad-file-name) ) ) ) (register-palette-exporter "python" "_Python dictionary" "py" _"Export the active palette as a Python dictionary (name: color)" "Barak Itkin <>" "Barak Itkin" "May 15th, 2009") (define (gimp-palette-export-text directory-name file-name) (let ((valid-name (valid-file-name file-name))) (if valid-name (with-output-to-file (string-append directory-name DIR-SEPARATOR file-name) (lambda () (export-palette (car (gimp-context-get-palette)) color-rgb-to-hexa-decimal name-none ; name-convertor "" ; start "" ; name-pre "" ; name-after "" ; name-color-seperator "" ; color-pre "" ; color-after "\n" ; entry-seperator "" ; end ) ) ) (bad-file-name) ) ) ) (register-palette-exporter "text" "_Text file..." "txt" _"Write all the colors in a palette to a text file, one hexadecimal value per line (no names)" "Barak Itkin <>" "Barak Itkin" "May 15th, 2009") (define (gimp-palette-export-java directory-name file-name) (let ((valid-name (valid-file-name file-name))) (if valid-name (with-output-to-file (string-append directory-name DIR-SEPARATOR file-name) (lambda () (let ((palette-name (car (gimp-context-get-palette)))) (begin (displayln "") (displayln "import java.awt.Color;") (displayln "import java.util.Hashtable;") (displayln "") (displayln "// Generated with GIMP palette Export ") (displayln (string-append "// Based on the palette " palette-name)) (displayln (string-append "public class " (name-standard palette-name) " {")) (displayln "") (displayln " Hashtable<String, Color> colors;") (displayln "") (displayln (string-append " public " (name-standard palette-name) "() {")) (export-palette (car (gimp-context-get-palette)) color-rgb-to-comma-seperated-list name-no-conversion " colors = new Hashtable<String,Color>();\n" ; start " colors.put(\"" ; name-pre "\"" ; name-after ", " ; name-color-seperator "new Color" ; color-pre ");" ; color-after "\n" ; entry-seperator "\n }" ; end ) (display "\n}")))) ) (bad-file-name) ) ) ) (register-palette-exporter "java" "J_ava map..." "java" _"Export the active palette as a java.util.Hashtable<String, Color>" "Barak Itkin <>" "Barak Itkin" "May 15th, 2009")
null
https://raw.githubusercontent.com/GNOME/gimp-tiny-fu/a64d85eec23b997e535488d67f55b44395ba3f2e/scripts/palette-export.scm
scheme
----------------------------------------------------------------------------- GIMP palette export toolkit - utility function to help in exporting to other (text-based) formats. See instruction on adding new exporters at the end ----------------------------------------------------------------------------- Numbers and Math ----------------------------------------------------------------------------- For all the opertations below, this is the order of respectable digits: Converts a decimal number to another base. The returned number is a string Convert a string representation of a number in some base, to a decimal number If a string num-str is shorter then size, pad it with pad-str in the begining untill it's at least size long ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- The standard way for representing a color would be a list of red Convert a color to a hexadecimal string Convert a color to a css color Convert a color to a simple pair of braces with comma seperated values ----------------------------------------------------------------------------- Export utils ----------------------------------------------------------------------------- List of charcters that should not appear in file names This functions filters a string to have only characters which are either alpha-numeric or contained in more-legal (which is a variable holding a list of characters) A function that recieves the a file-name, and filters out all the character that shouldn't appear in file names. Then, it makes sure the remaining name isn't only white-spaces. If it's only white-spaces, the function returns false. Otherwise, it returns the fixed file-name Filters a string from all the characters which are not alpha-numeric (this also removes whitespaces) This function does the same as name-alpha-numeric, with an added operation - it removes any numbers from the begining The loop for exporting all the colors ----------------------------------------------------------------------------- Exporters ----------------------------------------------------------------------------- name-convertor start name-pre name-after name-color-seperator color-pre color-after entry-seperator end name-convertor start name-pre name-after name-color-seperator color-pre color-after entry-seperator end name-convertor start name-pre name-after name-color-seperator color-pre color-after entry-seperator end name-convertor start name-pre name-after name-color-seperator color-pre color-after entry-seperator end start name-pre name-after name-color-seperator color-pre color-after entry-seperator end
Written by < > This script includes various exporters for GIMP palettes , and other (define conversion-digits (list "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z")) (define (convert-decimal-to-base num base) (define (highest-order num base) (if (and (<= 0 num) (< num base)) 0 (+ 1 (highest-order (quotient num base) base)) ) ) (define (calc base num str) (let ((max-order (highest-order num base))) (cond ((not (= 0 max-order)) (let ((num-of-times (quotient num (inexact->exact (expt base max-order))))) (calc base (- num (* num-of-times (expt base max-order))) (string-append str (list-ref conversion-digits num-of-times))) ) ) (else (string-append str (list-ref conversion-digits num))) )) ) (calc base num "") ) (define (convert-base-to-decimal base num-str) (define (convert-char num-char) (if (char-numeric? num-char) (string->number (string num-char)) (+ 10 (- (char->integer num-char) (char->integer #\a))) ) ) (define (calc base num-str num) (if (equal? num-str "") num (calc base (substring num-str 1) (+ (* num base) (convert-char (string-ref num-str 0))) ) ) ) (calc base num-str 0) ) (define (pre-pad-number num-str size pad-str) (if (< (string-length num-str) size) (pre-pad-number (string-append pad-str num-str) size pad-str) num-str ) ) Color convertors green and blue ( GIMP 's default ) (define color-get-red car) (define color-get-green cadr) (define color-get-blue caddr) ' ( 255 255 255 ) = > " # ffffff " (define (color-rgb-to-hexa-decimal color) (string-append "#" (pre-pad-number (convert-decimal-to-base (color-get-red color) 16) 2 "0") (pre-pad-number (convert-decimal-to-base (color-get-green color) 16) 2 "0") (pre-pad-number (convert-decimal-to-base (color-get-blue color) 16) 2 "0") ) ) ' ( 255 255 255 ) = > " rgb(255 , 255 , 255 ) " (define (color-rgb-to-css color) (string-append "rgb(" (number->string (color-get-red color)) ", " (number->string (color-get-green color)) ", " (number->string (color-get-blue color)) ")") ) ' ( 255 255 255 ) = > " ( 255 , 255 , 255 ) " (define (color-rgb-to-comma-seperated-list color) (string-append "(" (number->string (color-get-red color)) ", " (number->string (color-get-green color)) ", " (number->string (color-get-blue color)) ")") ) (define illegal-file-name-chars (list #\\ #\/ #\: #\* #\? #\" #\< #\> #\|)) A function to filter a list lst by a given predicate pred (define (filter pred lst) (if (null? lst) '() (if (pred (car lst)) (cons (car lst) (filter pred (cdr lst))) (filter pred (cdr lst)) ) ) ) A function to check if a certain value obj is inside a list lst (define (contained? obj lst) (member obj lst)) (define (clean str more-legal) (list->string (filter (lambda (ch) (or (char-alphabetic? ch) (char-numeric? ch) (contained? ch more-legal))) (string->list str))) ) (define (valid-file-name name) (let* ((clean (list->string (filter (lambda (ch) (not (contained? ch illegal-file-name-chars))) (string->list name)))) (clean-without-spaces (list->string (filter (lambda (ch) (not (char-whitespace? ch))) (string->list clean)))) ) (if (equal? clean-without-spaces "") #f clean ) ) ) (define (name-alpha-numeric str) (clean str '()) ) (define (name-standard str) (let ((cleaned (clean str '()))) (while (char-numeric? (string-ref cleaned 0)) (set! cleaned (substring cleaned 1)) ) cleaned ) ) (define name-no-conversion (lambda (obj) obj)) (define color-none (lambda (x) "")) (define name-none (lambda (x) "")) (define displayln (lambda (obj) (display obj) (display "\n"))) (define (export-palette palette-name color-convertor name-convertor start name-pre name-after name-color-seperator color-pre color-after entry-seperator end) (define (write-color-line index) (display name-pre) (display (name-convertor (car (gimp-palette-entry-get-name palette-name index)))) (display name-after) (display name-color-seperator) (display color-pre) (display (color-convertor (car (gimp-palette-entry-get-color palette-name index)))) (display color-after) ) (let ((color-count (car (gimp-palette-get-colors palette-name))) (i 0) ) (display start) (while (< i (- color-count 1)) (begin (write-color-line i) (display entry-seperator) (set! i (+ 1 i)) ) ) (write-color-line i) (display end) ) ) (define (register-palette-exporter export-type export-name file-type description author copyright date) (script-fu-register (string-append "gimp-palette-export-" export-type) export-name description author copyright date "" SF-DIRNAME _"Folder for the output file" "" SF-STRING _"The name of the file to create (if a file with this name already exist, it will be replaced)" (string-append "palette." file-type) ) (script-fu-menu-register (string-append "gimp-palette-export-" export-type) "<Palettes>/Export as") ) (define (bad-file-name) (gimp-message (string-append _"The filename you entered is not a suitable name for a file." "\n\n" _"All characters in the name are either white-spaces or characters which can not appear in filenames."))) (define (gimp-palette-export-css directory-name file-name) (let ((valid-name (valid-file-name file-name))) (if valid-name (with-output-to-file (string-append directory-name DIR-SEPARATOR file-name) (lambda () (export-palette (car (gimp-context-get-palette)) color-rgb-to-css ))) (bad-file-name) ) ) ) (register-palette-exporter "css" "_CSS stylesheet..." "css" (string-append _"Export the active palette as a CSS stylesheet with the color entry name as their class name, and the color itself as the color attribute") "Barak Itkin <>" "Barak Itkin" "May 15th, 2009") (define (gimp-palette-export-php directory-name file-name) (let ((valid-name (valid-file-name file-name))) (if valid-name (with-output-to-file (string-append directory-name DIR-SEPARATOR file-name) (lambda () (export-palette (car (gimp-context-get-palette)) color-rgb-to-hexa-decimal ))) (bad-file-name) ) ) ) (register-palette-exporter "php" "P_HP dictionary..." "php" _"Export the active palette as a PHP dictionary (name => color)" "Barak Itkin <>" "Barak Itkin" "May 15th, 2009") (define (gimp-palette-export-python directory-name file-name) (let ((valid-name (valid-file-name file-name))) (if valid-name (with-output-to-file (string-append directory-name DIR-SEPARATOR file-name) (lambda () (let ((palette-name (car (gimp-context-get-palette)))) (begin (displayln "# Generated with GIMP Palette Export") (displayln (string-append "# Based on the palette " palette-name)) (export-palette palette-name color-rgb-to-hexa-decimal )))) ) (bad-file-name) ) ) ) (register-palette-exporter "python" "_Python dictionary" "py" _"Export the active palette as a Python dictionary (name: color)" "Barak Itkin <>" "Barak Itkin" "May 15th, 2009") (define (gimp-palette-export-text directory-name file-name) (let ((valid-name (valid-file-name file-name))) (if valid-name (with-output-to-file (string-append directory-name DIR-SEPARATOR file-name) (lambda () (export-palette (car (gimp-context-get-palette)) color-rgb-to-hexa-decimal ) ) ) (bad-file-name) ) ) ) (register-palette-exporter "text" "_Text file..." "txt" _"Write all the colors in a palette to a text file, one hexadecimal value per line (no names)" "Barak Itkin <>" "Barak Itkin" "May 15th, 2009") (define (gimp-palette-export-java directory-name file-name) (let ((valid-name (valid-file-name file-name))) (if valid-name (with-output-to-file (string-append directory-name DIR-SEPARATOR file-name) (lambda () (let ((palette-name (car (gimp-context-get-palette)))) (begin (displayln "") (displayln "import java.awt.Color;") (displayln "import java.util.Hashtable;") (displayln "") (displayln "// Generated with GIMP palette Export ") (displayln (string-append "// Based on the palette " palette-name)) (displayln (string-append "public class " (name-standard palette-name) " {")) (displayln "") (displayln " Hashtable<String, Color> colors;") (displayln "") (displayln (string-append " public " (name-standard palette-name) "() {")) (export-palette (car (gimp-context-get-palette)) color-rgb-to-comma-seperated-list name-no-conversion ) (display "\n}")))) ) (bad-file-name) ) ) ) (register-palette-exporter "java" "J_ava map..." "java" _"Export the active palette as a java.util.Hashtable<String, Color>" "Barak Itkin <>" "Barak Itkin" "May 15th, 2009")