_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
48a9ae8245ce90a5e822d255fb775ef649aa7a108bdf033dca99f0337081e9f8
libre-man/unix-opts
unix-opts.lisp
;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp -*- ;;; ;;; Unix-opts—a minimalistic parser of command line options. ;;; Copyright © 2015–2018 Copyright © 2018–2020 ;;; ;;; 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. (defpackage :unix-opts (:nicknames :opts) (:use #:common-lisp) (:export ;; Conditions #:unknown-option #:unknown-option-provided #:troublesome-option #:missing-arg #:missing-required-option #:arg-parser-failed ;; Restarts #:skip-option #:use-value #:reparse-arg ;; Classes #:option ;; Readers #:missing-options #:raw-arg ;; Functions #:exit #:argv #:get-opts #:describe #:make-options Macros #:define-opts) (:shadow #:describe)) (in-package #:unix-opts) (defclass option () ((name :initarg :name :accessor name :documentation "keyword that will be included in list returned by `get-opts' function if this option is given by user") (description :initarg :description :accessor description :documentation "description of the option") (short :initarg :short :accessor short :documentation "NIL or single char - short variant of the option") (long :initarg :long :accessor long :documentation "NIL or string - long variant of the option") (required :initarg :required :accessor required :initform nil :documentation "If not NIL this argument is required.") (arg-parser :initarg :arg-parser :accessor arg-parser :documentation "if not NIL, this option requires an argument, it will be parsed with this function") (meta-var :initarg :meta-var :accessor meta-var :documentation "if this option requires an argument, this is how it will be printed in option description") (default :initarg :default :accessor default :documentation "if the option is not passed this value will be used, cannot be used in combination with REQUIRED")) (:documentation "representation of an option")) (define-condition troublesome-option (simple-error) ((option :initarg :option :reader option)) (:report (lambda (c s) (format s "troublesome option: ~s" (option c)))) (:documentation "Generalization over conditions that have to do with some particular option.")) (define-condition unknown-option (troublesome-option) () (:report (lambda (c s) (format s "unknown option: ~s" (option c)))) (:documentation "This condition is thrown when parser encounters unknown (not previously defined with `define-opts') option.")) (define-condition unknown-option-provided (troublesome-option) () (:report (lambda (c s) (format s "Provided a unknown option: ~s" (option c)))) (:documentation "This condition is signaled when the restart `USE-VALUE' is called with an undefined option.")) (define-condition missing-arg (troublesome-option) () (:report (lambda (c s) (format s "missing arg for option: ~s" (option c)))) (:documentation "This condition is thrown when some option OPTION wants an argument, but there is no such argument given.")) (define-condition missing-required-option (troublesome-option) ((missing-options :initarg :missing-options :reader missing-options)) (:report (lambda (c s) (format s "missing required options: ~{\"~a\"~^, ~}" (mapcar (lambda (opt) (with-slots (short long name) opt (apply #'format nil (cond (long (list "--~A" long)) (short (list "-~A" short)) (t (list "~A" name)))))) (missing-options c))))) (:documentation "This condition is thrown when required options are missing.")) (define-condition arg-parser-failed (troublesome-option) ((raw-arg :initarg :raw-arg :reader raw-arg)) (:report (lambda (c s) (format s "argument parser failed (option: ~s, string to parse: ~s)" (option c) (raw-arg c)))) (:documentation "This condition is thrown when some option OPTION wants an argument, it's given but cannot be parsed by argument parser.")) (defparameter *options* nil "List of all defined options.") (defun make-options (opts) (mapcar #'make-option opts)) (defun make-option (args) "Register an option according to ARGS." (let ((name (getf args :name)) (description (getf args :description "?")) (short (getf args :short)) (long (getf args :long)) (arg-parser (getf args :arg-parser)) (required (getf args :required)) (default (getf args :default)) (meta-var (getf args :meta-var "ARG"))) (unless (or short long) (error "at least one form of the option must be provided")) (check-type name keyword) (check-type description string) (check-type short (or null character)) (check-type long (or null string)) (check-type arg-parser (or null function)) (check-type meta-var string) (check-type required boolean) (when required (check-type default null)) (when (and default (or (consp default) (and (not (stringp default)) (arrayp default)) (hash-table-p default) (typep default 'standard-object))) (warn "Providing mutable object as default value, please provide a function that returns a fresh instance of this object. ~ Default value of ~A was provided." default)) (make-instance 'option :name name :description description :short short :long long :required required :arg-parser arg-parser :default default :meta-var meta-var))) (defmacro define-opts (&body descriptions) "Define command line options. Arguments of this macro must be plists containing various parameters. Here we enumerate all allowed parameters: :NAME—keyword that will be included in list returned by GET-OPTS function if actual option is supplied by user. :DESCRIPTION—description of the option (it will be used in DESCRIBE function). This argument is optional, but it's recommended to supply it. :SHORT—single character, short variant of the option. You may omit this argument if you supply :LONG variant of option. :LONG—string, long variant of option. You may omit this argument if you supply :SHORT variant of option. :ARG-PARSER—if actual option must take an argument, supply this argument, it must be a function that takes a string and parses it. :META-VAR—if actual option requires an argument, this is how it will be printed in option description. :REQUIRED—whether the option is required. This only makes sense if the option takes an argument. :DEFAULT—the default value used if the option was not found. This can either be a function (which will be called to generate the default value) or a literal value. This option cannot be combined with :REQUIRED. The default value will not be provided to the :ARG-PARSER." `(progn (setf *options* (make-options (list ,@(mapcar (lambda (desc) (cons 'list desc)) descriptions)))) (values))) (defun argv () "Return a list of program's arguments, including command used to execute the program as first elements of the list. Portable across implementations." #+abcl ext:*command-line-argument-list* #+allegro (sys:command-line-arguments) #+:ccl ccl:*command-line-argument-list* #+clisp (cons *load-truename* ext:*args*) #+clozure ccl:*command-line-argument-list* #+cmu extensions:*command-line-words* #+ecl (ext:command-args) #+gcl si:*command-args* #+lispworks system:*line-arguments-list* #+sbcl sb-ext:*posix-argv*) (defun split-short-opts (arg) "Split short options, for example \"-ab\" will produce \"-a\" and \"-b\". ARG must be a string, return value is list of strings." (if (and (> (length arg) 1) (char= #\- (char arg 0)) (char/= #\- (char arg 1))) (mapcar (lambda (c) (format nil "-~c" c)) (cdr (coerce arg 'list))) (list arg))) (defun split-on-= (arg) "Split string ARG on \"=\", return value is list of strings." (if (and (> (length arg) 1) (char= #\- (char arg 0)) (char/= #\= (char arg 1))) (let ((pos (position #\= arg :test #'char=))) (if pos (list (subseq arg 0 pos) (subseq arg (1+ pos) (length arg))) (list arg))) (list arg))) (defun shortp (opt) "Predicate that checks if OPT is a short option." (and (= (length opt) 2) (char= #\- (char opt 0)) (char/= #\- (char opt 1)))) (defun longp (opt) "Predicate that checks if OPT is a long option." (and (> (length opt) 2) (char= #\- (char opt 0)) (char= #\- (char opt 1)))) (defun optionp (str) "This predicate checks if string STR is an option." (or (shortp str) (longp str))) (defun argp (str) "Check if string STR is an argument (not option)." (and (typep str 'string) (not (optionp str)))) (defun maybe-funcall (value-or-fun) (if (functionp value-or-fun) (funcall value-or-fun) value-or-fun)) (defun map-options-to-hash-table (options callback) (loop :with table = (make-hash-table) :for option :in options :when (funcall callback option) :do (setf (gethash (name option) table) option) :finally (return table))) (defun find-option (opt options) "Find option OPT and return object that represents it or NIL." (multiple-value-bind (opt key) (if (shortp opt) (values (subseq opt 1) #'short) (values (subseq opt 2) #'long)) (flet ((prefix-p (x) (let ((x (string x))) (when (>= (length x) (length opt)) (string= x opt :end1 (length opt)))))) (let* ((matches (remove-if-not #'prefix-p options :key key)) (exact-match (find-if #'(lambda (x) (string= x opt)) matches :key key))) (cond (exact-match exact-match) ((cadr matches) nil) (t (car matches))))))) (defun get-opts (&optional (options nil options-supplied-p) (defined-options *options*)) "Parse command line options. If OPTIONS is given, it should be a list to parse. If it's not given, the function will use `argv' function to get list of command line arguments. Return two values: * a list that contains keywords associated with command line options with `define-opts' macro, and * a list of free arguments. If some option requires an argument, you can use `getf' to test presence of the option and get its argument if the option is present. The parser may signal various conditions. Let's list them all specifying which restarts are available for every condition, and what kind of information the programmer can extract from the conditions. `unknown-option' is thrown when parser encounters unknown (not previously defined with `define-opts') option. Use the `option' reader to get name of the option (string). Available restarts: `use-value' (substitute the option and try again), `skip-option' (ignore the option). `missing-arg' is thrown when some option wants an argument, but there is no such argument given. Use the `option' reader to get name of the option (string). Available restarts: `use-value' (supplied value will be used), `skip-option' (ignore the option). `arg-parser-failed' is thrown when some option wants an argument, it's given but cannot be parsed by argument parser. Use the `option' reader to get name of the option (string) and `raw-arg' to get raw string representing the argument before parsing. Available restarts: `use-value' (supplied value will be used), `skip-option' (ignore the option), `reparse-arg' (supplied string will be parsed instead). `missing-required-option' is thrown when some option was required but was not given. Use the `missing-options' reader to get the list of options that are missing. Available restarts: `use-value' (supplied list of values will be used), `skip-option' (ignore all these options, effectively binding them to `nil')" (do ((tokens (mapcan #'split-short-opts (mapcan #'split-on-= (if options-supplied-p options (cdr (argv))))) (cdr tokens)) (required (map-options-to-hash-table defined-options #'required)) (default-values (map-options-to-hash-table defined-options #'default)) poption-name poption-raw poption-parser options free-args) ((and (null tokens) (null poption-name)) (progn (when (/= (hash-table-count required) 0) (let ((missing (loop :for val :being :the :hash-values :of required :collect val))) (restart-case (error 'missing-required-option :missing-options missing) (skip-option ()) (use-value (values) (loop :for option :in missing :for value :in values :do (push (name option) options) :do (push value options)))))) (loop :for option :being :the :hash-values :of default-values :do (progn (push (name option) options) (push (maybe-funcall (default option)) options))) (values (nreverse options) (nreverse free-args)))) (labels ((push-option (name value) (push name options) (push value options) (setf poption-name nil)) (process-arg (arg) (restart-case (handler-case (push-option poption-name (funcall poption-parser arg)) (error (condition) (declare (ignore condition)) (error 'arg-parser-failed :option poption-raw :raw-arg arg))) (use-value (value) (push-option poption-name value)) (skip-option () (setf poption-name nil)) (reparse-arg (str) (process-arg str)))) (process-option (opt) (let ((option (find-option opt defined-options))) (if option (progn (remhash (name option) required) (remhash (name option) default-values) (let ((parser (arg-parser option))) (if parser (setf poption-name (name option) poption-raw opt poption-parser parser) (push-option (name option) t)))) (restart-case (error 'unknown-option :option opt) (use-value (value) (if (find-option value defined-options) (process-option value) (restart-case (error 'unknown-option-provided :option value) (skip-option ())))) (skip-option ())))))) (let ((item (car tokens))) (cond ((and poption-name (argp item)) (process-arg item)) (poption-name (restart-case (error 'missing-arg :option poption-raw) (use-value (value) (push-option poption-name value) (when item (process-option item))) (skip-option () (setf poption-name nil) (when item (process-option item))))) ((string= item "--") (dolist (tok (cdr tokens)) (push tok free-args)) (setf tokens nil)) ((optionp item) (process-option item)) (t (push item free-args))))))) (defun add-text-padding (str &key padding newline) "Add padding to text STR. Every line except for the first one, will be prefixed with PADDING spaces. If NEWLINE is non-NIL, newline character will be prepended to the text making it start on the next line with padding applied to every single line." (let ((pad (make-string padding :initial-element #\Space)) (pad-next-lines (make-string (max 0 (1- padding)) :initial-element #\Space))) (with-output-to-string (s) (when newline (format s "~%~a" pad)) (map nil (lambda (x) (write-char x s) (when (char= x #\Newline) (write pad-next-lines :stream s :escape nil))) str)))) (defun print-opts (defined-options &optional (stream *standard-output*) (argument-block-width 25)) "Print info about defined options to STREAM. Every option get its own line with description. A newline is printed after the options if this part of the text is wider than ARGUMENT-BLOCK-WIDTH." (flet ((pad-right (string max-size) (concatenate 'string string (make-string (- max-size (length string)) :initial-element #\Space)))) (let* ((option-strings (mapcar (lambda (opt) (with-slots (short long description required arg-parser meta-var default) opt (let ((opts-and-meta (concatenate 'string (if short (format nil "-~c" short) "") (if (and short long) ", " "") (if long (format nil "--~a" long) "") (if arg-parser (format nil " ~a" meta-var) "") (if required (format nil " (Required)") ""))) (full-description (concatenate 'string description (if default (format nil " [Default: ~A]" (maybe-funcall default)) "")))) (cons opts-and-meta full-description)))) defined-options)) (max-opts-length (reduce #'max (mapcar (lambda (el) (length (car el))) option-strings) :initial-value 0))) (loop :for (opt-meta . opt-description) :in option-strings :for newline = (>= (length opt-meta) argument-block-width) :do (format stream " ~a~a~%" (pad-right opt-meta (+ (if newline 0 1) max-opts-length)) (add-text-padding opt-description :padding (+ 3 max-opts-length) :newline newline))) (terpri stream)))) (defun print-opts* (margin defined-options) "Return a string containing info about defined options. All options are displayed on one line, although this function tries to print it elegantly if it gets too long. MARGIN specifies margin." (let ((fill-col (- 80 margin)) (i 0) (last-newline 0)) (with-output-to-string (s) (dolist (opt defined-options) (with-slots (short long required arg-parser meta-var) opt (let ((str (format nil " [~a]" (concatenate 'string (if short (format nil "-~c" short) "") (if (and short long) "|" "") (if long (format nil "--~a" long) "") (if arg-parser (format nil " ~a" meta-var) "") (if required (format nil " (Required)") ""))))) (incf i (length str)) (when (> (- i last-newline) fill-col) (terpri s) (dotimes (x margin) (princ #\space s)) (setf last-newline i)) (princ str s))))))) (defun describe (&key prefix suffix usage-of args (stream *standard-output*) (argument-block-width 25) (defined-options *options*) (usage-of-label "Usage") (available-options-label "Available options") brief) "Return string describing options of the program that were defined with `define-opts' macro previously. You can supply PREFIX and SUFFIX arguments that will be printed before and after options respectively. If USAGE-OF is supplied, it should be a string, name of the program for \"Usage: \" section. This section is only printed if this name is given. If your program takes arguments (apart from options), you can specify how to print them in 'usage' section with ARGS option (should be a string designator). For the 'available options' block: if the text that describes how to pass the option is wider than ARGUMENT-BLOCK-WIDTH a newline is printed before the description of that option. The 'usage' section will be prefixed with the value of the key argument `usage-of-label` (default value: \"Usage\"), and the 'available options' block will starts with the value of the key argument `available-options-label' (default value: \"Available options\") on a single line If USAGE-OF is provided and BRIEF is non-NIL, the 'available options' block will be omitted from the output. The output goes to STREAM." (flet ((print-part (str) (when str (princ str stream) (terpri stream)))) (print-part prefix) (when usage-of (terpri stream) (format stream "~a: ~a~a~@[ ~a~]~%~%" usage-of-label usage-of (print-opts* (+ (length usage-of-label) (length usage-of) 2) ; colon and space defined-options) args)) (when (and (not (and usage-of brief)) defined-options) (format stream "~a:~%" available-options-label) (print-opts defined-options stream argument-block-width)) (print-part suffix))) (defun exit (&optional (status 0)) "Exit the program returning `status'." #+sbcl (sb-ext:exit :code status) #+cmu (unix:unix-exit status) #+ccl (ccl:quit status) #+ecl (ext:quit status) #+clisp (ext:exit status) #+abcl (extensions:exit :status status) #+allegro (excl:exit status :quiet t) #+lispworks (lispworks:quit :status status))
null
https://raw.githubusercontent.com/libre-man/unix-opts/0e61f34b2ecf62288437810d4abb31e572048b04/unix-opts.lisp
lisp
-*- Mode: Lisp; Syntax: ANSI-Common-Lisp -*- Unix-opts—a minimalistic parser of command line options. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the without limitation the rights to use, copy, modify, merge, publish, the following conditions: The above copyright notice and this permission notice shall be included 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 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Conditions Restarts Classes Readers Functions colon and space
Copyright © 2015–2018 Copyright © 2018–2020 " Software " ) , to deal in the Software without restriction , including distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION (defpackage :unix-opts (:nicknames :opts) (:use #:common-lisp) (:export #:unknown-option #:unknown-option-provided #:troublesome-option #:missing-arg #:missing-required-option #:arg-parser-failed #:skip-option #:use-value #:reparse-arg #:option #:missing-options #:raw-arg #:exit #:argv #:get-opts #:describe #:make-options Macros #:define-opts) (:shadow #:describe)) (in-package #:unix-opts) (defclass option () ((name :initarg :name :accessor name :documentation "keyword that will be included in list returned by `get-opts' function if this option is given by user") (description :initarg :description :accessor description :documentation "description of the option") (short :initarg :short :accessor short :documentation "NIL or single char - short variant of the option") (long :initarg :long :accessor long :documentation "NIL or string - long variant of the option") (required :initarg :required :accessor required :initform nil :documentation "If not NIL this argument is required.") (arg-parser :initarg :arg-parser :accessor arg-parser :documentation "if not NIL, this option requires an argument, it will be parsed with this function") (meta-var :initarg :meta-var :accessor meta-var :documentation "if this option requires an argument, this is how it will be printed in option description") (default :initarg :default :accessor default :documentation "if the option is not passed this value will be used, cannot be used in combination with REQUIRED")) (:documentation "representation of an option")) (define-condition troublesome-option (simple-error) ((option :initarg :option :reader option)) (:report (lambda (c s) (format s "troublesome option: ~s" (option c)))) (:documentation "Generalization over conditions that have to do with some particular option.")) (define-condition unknown-option (troublesome-option) () (:report (lambda (c s) (format s "unknown option: ~s" (option c)))) (:documentation "This condition is thrown when parser encounters unknown (not previously defined with `define-opts') option.")) (define-condition unknown-option-provided (troublesome-option) () (:report (lambda (c s) (format s "Provided a unknown option: ~s" (option c)))) (:documentation "This condition is signaled when the restart `USE-VALUE' is called with an undefined option.")) (define-condition missing-arg (troublesome-option) () (:report (lambda (c s) (format s "missing arg for option: ~s" (option c)))) (:documentation "This condition is thrown when some option OPTION wants an argument, but there is no such argument given.")) (define-condition missing-required-option (troublesome-option) ((missing-options :initarg :missing-options :reader missing-options)) (:report (lambda (c s) (format s "missing required options: ~{\"~a\"~^, ~}" (mapcar (lambda (opt) (with-slots (short long name) opt (apply #'format nil (cond (long (list "--~A" long)) (short (list "-~A" short)) (t (list "~A" name)))))) (missing-options c))))) (:documentation "This condition is thrown when required options are missing.")) (define-condition arg-parser-failed (troublesome-option) ((raw-arg :initarg :raw-arg :reader raw-arg)) (:report (lambda (c s) (format s "argument parser failed (option: ~s, string to parse: ~s)" (option c) (raw-arg c)))) (:documentation "This condition is thrown when some option OPTION wants an argument, it's given but cannot be parsed by argument parser.")) (defparameter *options* nil "List of all defined options.") (defun make-options (opts) (mapcar #'make-option opts)) (defun make-option (args) "Register an option according to ARGS." (let ((name (getf args :name)) (description (getf args :description "?")) (short (getf args :short)) (long (getf args :long)) (arg-parser (getf args :arg-parser)) (required (getf args :required)) (default (getf args :default)) (meta-var (getf args :meta-var "ARG"))) (unless (or short long) (error "at least one form of the option must be provided")) (check-type name keyword) (check-type description string) (check-type short (or null character)) (check-type long (or null string)) (check-type arg-parser (or null function)) (check-type meta-var string) (check-type required boolean) (when required (check-type default null)) (when (and default (or (consp default) (and (not (stringp default)) (arrayp default)) (hash-table-p default) (typep default 'standard-object))) (warn "Providing mutable object as default value, please provide a function that returns a fresh instance of this object. ~ Default value of ~A was provided." default)) (make-instance 'option :name name :description description :short short :long long :required required :arg-parser arg-parser :default default :meta-var meta-var))) (defmacro define-opts (&body descriptions) "Define command line options. Arguments of this macro must be plists containing various parameters. Here we enumerate all allowed parameters: :NAME—keyword that will be included in list returned by GET-OPTS function if actual option is supplied by user. :DESCRIPTION—description of the option (it will be used in DESCRIBE function). This argument is optional, but it's recommended to supply it. :SHORT—single character, short variant of the option. You may omit this argument if you supply :LONG variant of option. :LONG—string, long variant of option. You may omit this argument if you supply :SHORT variant of option. :ARG-PARSER—if actual option must take an argument, supply this argument, it must be a function that takes a string and parses it. :META-VAR—if actual option requires an argument, this is how it will be printed in option description. :REQUIRED—whether the option is required. This only makes sense if the option takes an argument. :DEFAULT—the default value used if the option was not found. This can either be a function (which will be called to generate the default value) or a literal value. This option cannot be combined with :REQUIRED. The default value will not be provided to the :ARG-PARSER." `(progn (setf *options* (make-options (list ,@(mapcar (lambda (desc) (cons 'list desc)) descriptions)))) (values))) (defun argv () "Return a list of program's arguments, including command used to execute the program as first elements of the list. Portable across implementations." #+abcl ext:*command-line-argument-list* #+allegro (sys:command-line-arguments) #+:ccl ccl:*command-line-argument-list* #+clisp (cons *load-truename* ext:*args*) #+clozure ccl:*command-line-argument-list* #+cmu extensions:*command-line-words* #+ecl (ext:command-args) #+gcl si:*command-args* #+lispworks system:*line-arguments-list* #+sbcl sb-ext:*posix-argv*) (defun split-short-opts (arg) "Split short options, for example \"-ab\" will produce \"-a\" and \"-b\". ARG must be a string, return value is list of strings." (if (and (> (length arg) 1) (char= #\- (char arg 0)) (char/= #\- (char arg 1))) (mapcar (lambda (c) (format nil "-~c" c)) (cdr (coerce arg 'list))) (list arg))) (defun split-on-= (arg) "Split string ARG on \"=\", return value is list of strings." (if (and (> (length arg) 1) (char= #\- (char arg 0)) (char/= #\= (char arg 1))) (let ((pos (position #\= arg :test #'char=))) (if pos (list (subseq arg 0 pos) (subseq arg (1+ pos) (length arg))) (list arg))) (list arg))) (defun shortp (opt) "Predicate that checks if OPT is a short option." (and (= (length opt) 2) (char= #\- (char opt 0)) (char/= #\- (char opt 1)))) (defun longp (opt) "Predicate that checks if OPT is a long option." (and (> (length opt) 2) (char= #\- (char opt 0)) (char= #\- (char opt 1)))) (defun optionp (str) "This predicate checks if string STR is an option." (or (shortp str) (longp str))) (defun argp (str) "Check if string STR is an argument (not option)." (and (typep str 'string) (not (optionp str)))) (defun maybe-funcall (value-or-fun) (if (functionp value-or-fun) (funcall value-or-fun) value-or-fun)) (defun map-options-to-hash-table (options callback) (loop :with table = (make-hash-table) :for option :in options :when (funcall callback option) :do (setf (gethash (name option) table) option) :finally (return table))) (defun find-option (opt options) "Find option OPT and return object that represents it or NIL." (multiple-value-bind (opt key) (if (shortp opt) (values (subseq opt 1) #'short) (values (subseq opt 2) #'long)) (flet ((prefix-p (x) (let ((x (string x))) (when (>= (length x) (length opt)) (string= x opt :end1 (length opt)))))) (let* ((matches (remove-if-not #'prefix-p options :key key)) (exact-match (find-if #'(lambda (x) (string= x opt)) matches :key key))) (cond (exact-match exact-match) ((cadr matches) nil) (t (car matches))))))) (defun get-opts (&optional (options nil options-supplied-p) (defined-options *options*)) "Parse command line options. If OPTIONS is given, it should be a list to parse. If it's not given, the function will use `argv' function to get list of command line arguments. Return two values: * a list that contains keywords associated with command line options with `define-opts' macro, and * a list of free arguments. If some option requires an argument, you can use `getf' to test presence of the option and get its argument if the option is present. The parser may signal various conditions. Let's list them all specifying which restarts are available for every condition, and what kind of information the programmer can extract from the conditions. `unknown-option' is thrown when parser encounters unknown (not previously defined with `define-opts') option. Use the `option' reader to get name of the option (string). Available restarts: `use-value' (substitute the option and try again), `skip-option' (ignore the option). `missing-arg' is thrown when some option wants an argument, but there is no such argument given. Use the `option' reader to get name of the option (string). Available restarts: `use-value' (supplied value will be used), `skip-option' (ignore the option). `arg-parser-failed' is thrown when some option wants an argument, it's given but cannot be parsed by argument parser. Use the `option' reader to get name of the option (string) and `raw-arg' to get raw string representing the argument before parsing. Available restarts: `use-value' (supplied value will be used), `skip-option' (ignore the option), `reparse-arg' (supplied string will be parsed instead). `missing-required-option' is thrown when some option was required but was not given. Use the `missing-options' reader to get the list of options that are missing. Available restarts: `use-value' (supplied list of values will be used), `skip-option' (ignore all these options, effectively binding them to `nil')" (do ((tokens (mapcan #'split-short-opts (mapcan #'split-on-= (if options-supplied-p options (cdr (argv))))) (cdr tokens)) (required (map-options-to-hash-table defined-options #'required)) (default-values (map-options-to-hash-table defined-options #'default)) poption-name poption-raw poption-parser options free-args) ((and (null tokens) (null poption-name)) (progn (when (/= (hash-table-count required) 0) (let ((missing (loop :for val :being :the :hash-values :of required :collect val))) (restart-case (error 'missing-required-option :missing-options missing) (skip-option ()) (use-value (values) (loop :for option :in missing :for value :in values :do (push (name option) options) :do (push value options)))))) (loop :for option :being :the :hash-values :of default-values :do (progn (push (name option) options) (push (maybe-funcall (default option)) options))) (values (nreverse options) (nreverse free-args)))) (labels ((push-option (name value) (push name options) (push value options) (setf poption-name nil)) (process-arg (arg) (restart-case (handler-case (push-option poption-name (funcall poption-parser arg)) (error (condition) (declare (ignore condition)) (error 'arg-parser-failed :option poption-raw :raw-arg arg))) (use-value (value) (push-option poption-name value)) (skip-option () (setf poption-name nil)) (reparse-arg (str) (process-arg str)))) (process-option (opt) (let ((option (find-option opt defined-options))) (if option (progn (remhash (name option) required) (remhash (name option) default-values) (let ((parser (arg-parser option))) (if parser (setf poption-name (name option) poption-raw opt poption-parser parser) (push-option (name option) t)))) (restart-case (error 'unknown-option :option opt) (use-value (value) (if (find-option value defined-options) (process-option value) (restart-case (error 'unknown-option-provided :option value) (skip-option ())))) (skip-option ())))))) (let ((item (car tokens))) (cond ((and poption-name (argp item)) (process-arg item)) (poption-name (restart-case (error 'missing-arg :option poption-raw) (use-value (value) (push-option poption-name value) (when item (process-option item))) (skip-option () (setf poption-name nil) (when item (process-option item))))) ((string= item "--") (dolist (tok (cdr tokens)) (push tok free-args)) (setf tokens nil)) ((optionp item) (process-option item)) (t (push item free-args))))))) (defun add-text-padding (str &key padding newline) "Add padding to text STR. Every line except for the first one, will be prefixed with PADDING spaces. If NEWLINE is non-NIL, newline character will be prepended to the text making it start on the next line with padding applied to every single line." (let ((pad (make-string padding :initial-element #\Space)) (pad-next-lines (make-string (max 0 (1- padding)) :initial-element #\Space))) (with-output-to-string (s) (when newline (format s "~%~a" pad)) (map nil (lambda (x) (write-char x s) (when (char= x #\Newline) (write pad-next-lines :stream s :escape nil))) str)))) (defun print-opts (defined-options &optional (stream *standard-output*) (argument-block-width 25)) "Print info about defined options to STREAM. Every option get its own line with description. A newline is printed after the options if this part of the text is wider than ARGUMENT-BLOCK-WIDTH." (flet ((pad-right (string max-size) (concatenate 'string string (make-string (- max-size (length string)) :initial-element #\Space)))) (let* ((option-strings (mapcar (lambda (opt) (with-slots (short long description required arg-parser meta-var default) opt (let ((opts-and-meta (concatenate 'string (if short (format nil "-~c" short) "") (if (and short long) ", " "") (if long (format nil "--~a" long) "") (if arg-parser (format nil " ~a" meta-var) "") (if required (format nil " (Required)") ""))) (full-description (concatenate 'string description (if default (format nil " [Default: ~A]" (maybe-funcall default)) "")))) (cons opts-and-meta full-description)))) defined-options)) (max-opts-length (reduce #'max (mapcar (lambda (el) (length (car el))) option-strings) :initial-value 0))) (loop :for (opt-meta . opt-description) :in option-strings :for newline = (>= (length opt-meta) argument-block-width) :do (format stream " ~a~a~%" (pad-right opt-meta (+ (if newline 0 1) max-opts-length)) (add-text-padding opt-description :padding (+ 3 max-opts-length) :newline newline))) (terpri stream)))) (defun print-opts* (margin defined-options) "Return a string containing info about defined options. All options are displayed on one line, although this function tries to print it elegantly if it gets too long. MARGIN specifies margin." (let ((fill-col (- 80 margin)) (i 0) (last-newline 0)) (with-output-to-string (s) (dolist (opt defined-options) (with-slots (short long required arg-parser meta-var) opt (let ((str (format nil " [~a]" (concatenate 'string (if short (format nil "-~c" short) "") (if (and short long) "|" "") (if long (format nil "--~a" long) "") (if arg-parser (format nil " ~a" meta-var) "") (if required (format nil " (Required)") ""))))) (incf i (length str)) (when (> (- i last-newline) fill-col) (terpri s) (dotimes (x margin) (princ #\space s)) (setf last-newline i)) (princ str s))))))) (defun describe (&key prefix suffix usage-of args (stream *standard-output*) (argument-block-width 25) (defined-options *options*) (usage-of-label "Usage") (available-options-label "Available options") brief) "Return string describing options of the program that were defined with `define-opts' macro previously. You can supply PREFIX and SUFFIX arguments that will be printed before and after options respectively. If USAGE-OF is supplied, it should be a string, name of the program for \"Usage: \" section. This section is only printed if this name is given. If your program takes arguments (apart from options), you can specify how to print them in 'usage' section with ARGS option (should be a string designator). For the 'available options' block: if the text that describes how to pass the option is wider than ARGUMENT-BLOCK-WIDTH a newline is printed before the description of that option. The 'usage' section will be prefixed with the value of the key argument `usage-of-label` (default value: \"Usage\"), and the 'available options' block will starts with the value of the key argument `available-options-label' (default value: \"Available options\") on a single line If USAGE-OF is provided and BRIEF is non-NIL, the 'available options' block will be omitted from the output. The output goes to STREAM." (flet ((print-part (str) (when str (princ str stream) (terpri stream)))) (print-part prefix) (when usage-of (terpri stream) (format stream "~a: ~a~a~@[ ~a~]~%~%" usage-of-label usage-of (print-opts* (+ (length usage-of-label) (length usage-of) defined-options) args)) (when (and (not (and usage-of brief)) defined-options) (format stream "~a:~%" available-options-label) (print-opts defined-options stream argument-block-width)) (print-part suffix))) (defun exit (&optional (status 0)) "Exit the program returning `status'." #+sbcl (sb-ext:exit :code status) #+cmu (unix:unix-exit status) #+ccl (ccl:quit status) #+ecl (ext:quit status) #+clisp (ext:exit status) #+abcl (extensions:exit :status status) #+allegro (excl:exit status :quiet t) #+lispworks (lispworks:quit :status status))
42f3958c0bc089d6ac198b9f0d8050e3bc521bcb17cb38acf74903e66c02be51
racket/deinprogramm
match.rkt
#lang racket/base (provide all-match-tests) (require rackunit deinprogramm/sdp/record deinprogramm/sdp/singleton deinprogramm/signature/signature-syntax (only-in deinprogramm/sdp/private/primitives match empty cons)) (define any (signature any %any)) (define-record pare kons pare? (kar any) (kdr any)) (define-record bare gons bare? (gar any) (gdr any)) (define-singleton foo-sig foo foo?) (define-singleton bar-bar bar) (define-record nullary make-nullary nullary?) (define all-match-tests (test-suite "Tests for DeinProgramm match form." (test-case "literals" (define foo (lambda (x) (match x (#t 'true) (#f 'false) ('() 'nil) ('(foo bar) 'foobar) ("foo" 'foo) ("bar" 'bar) (5 'five) (2 'two)))) (check-equal? (foo #t) 'true) (check-equal? (foo #f) 'false) (check-equal? (foo '()) 'nil) (check-equal? (foo '(foo bar)) 'foobar) (check-equal? (foo "foo") 'foo) (check-equal? (foo "bar") 'bar) (check-equal? (foo 5) 'five) (check-equal? (foo 2) 'two)) (test-case "internal define" (define foo (lambda (x) (match x (1 (define y (+ x 1)) y) ((list a b c) (define y (+ a b c)) (+ y 1))))) (check-equal? (foo 1) 2) (check-equal? (foo (list 1 2 3)) 7)) (test-case "variables" (define foo (lambda (x) (match x (#t 'true) (foo (list 'foo foo))))) (check-equal? (foo #t) 'true) (check-equal? (foo "foo") '(foo "foo"))) (test-case "lists" (define foo (lambda (x) (match x (empty 'empty) ((cons 'foo empty) 'fooempty) ((list 'foo 'bar) 'listfoobar) ((list 'bar 'foo) 'listbarfoo) ((list a b c) (list 'list a b c)) ((cons 5 b) (list 'cons5 b)) ((cons a (cons b c)) (list 'cons a b c)) ((cons a b) (list 'cons a b)) (x (list 'x x))))) (check-equal? (foo empty) 'empty) (check-equal? (foo "empty") '(x "empty")) (check-equal? (foo (list 1 2 3)) '(list 1 2 3)) (check-equal? (foo (cons 'foo empty)) 'fooempty) (check-equal? (foo (cons 1 empty)) '(cons 1 ())) (check-equal? (foo (cons 5 empty)) '(cons5 ())) (check-equal? (foo (list 1 2)) '(cons 1 2 ())) (check-equal? (match empty ((list) 'bingo)) 'bingo) (check-equal? (match (list 1) ((list) 'bingo) (foo foo)) (list 1)) (check-equal? (foo (list 'foo 'bar)) 'listfoobar) (check-equal? (foo (list 'bar 'foo)) 'listbarfoo)) (test-case "anything" (check-equal? (match 5 (_ 7)) 7) (check-equal? (match 5 (... 7)) 7) (check-equal? (match '(1 2) (_ 7)) 7) (check-equal? (match '(1 2) (... 7)) 7) (check-equal? (match #f (_ 7)) 7) (check-equal? (match #f (... 7)) 7) (check-equal? (let ((_ 5)) (match #f (_ _))) 5) (check-equal? (match #f ((kons _ _) 7) (_ 5)) 5) (check-equal? (match #f ((kons ... ...) 7) (... 5)) 5) (check-equal? (match (kons 1 2) ((kons _ _) 7) (_ 5)) 7) (check-equal? (match (kons 1 2) ((kons ... ...) 7) (... 5)) 7)) (test-case "records" (define foo (lambda (x) (match x ((cons foo empty) 'pairfoo) ((make-nullary) 'nullary) ((kons a b) (list 'kons a b)) ((gons a b) (list 'gons a b))))) (check-equal? (foo (cons foo empty)) 'pairfoo) (check-equal? (foo (make-nullary)) 'nullary) (check-equal? (foo (kons 1 2)) '(kons 1 2)) (check-equal? (foo (gons 1 2)) '(gons 1 2))) (test-case "singletons" (define f (lambda (x) (match x (foo 'foo) (bar 'bar) ((kons foo bar) 'foobar) ((kons (kons foo bar) bar) 'foobarbar) (baz baz)))) (check-equal? (f foo) 'foo) (check-equal? (f bar) 'bar) (check-equal? (f (kons foo bar)) 'foobar) (check-equal? (f (kons (kons foo bar) bar)) 'foobarbar) (check-equal? (f 'baz) 'baz))))
null
https://raw.githubusercontent.com/racket/deinprogramm/0e08f71fb1ceb3cef36e547f9f9fddbf6e58e5d6/deinprogramm/deinprogramm/sdp/tests/match.rkt
racket
#lang racket/base (provide all-match-tests) (require rackunit deinprogramm/sdp/record deinprogramm/sdp/singleton deinprogramm/signature/signature-syntax (only-in deinprogramm/sdp/private/primitives match empty cons)) (define any (signature any %any)) (define-record pare kons pare? (kar any) (kdr any)) (define-record bare gons bare? (gar any) (gdr any)) (define-singleton foo-sig foo foo?) (define-singleton bar-bar bar) (define-record nullary make-nullary nullary?) (define all-match-tests (test-suite "Tests for DeinProgramm match form." (test-case "literals" (define foo (lambda (x) (match x (#t 'true) (#f 'false) ('() 'nil) ('(foo bar) 'foobar) ("foo" 'foo) ("bar" 'bar) (5 'five) (2 'two)))) (check-equal? (foo #t) 'true) (check-equal? (foo #f) 'false) (check-equal? (foo '()) 'nil) (check-equal? (foo '(foo bar)) 'foobar) (check-equal? (foo "foo") 'foo) (check-equal? (foo "bar") 'bar) (check-equal? (foo 5) 'five) (check-equal? (foo 2) 'two)) (test-case "internal define" (define foo (lambda (x) (match x (1 (define y (+ x 1)) y) ((list a b c) (define y (+ a b c)) (+ y 1))))) (check-equal? (foo 1) 2) (check-equal? (foo (list 1 2 3)) 7)) (test-case "variables" (define foo (lambda (x) (match x (#t 'true) (foo (list 'foo foo))))) (check-equal? (foo #t) 'true) (check-equal? (foo "foo") '(foo "foo"))) (test-case "lists" (define foo (lambda (x) (match x (empty 'empty) ((cons 'foo empty) 'fooempty) ((list 'foo 'bar) 'listfoobar) ((list 'bar 'foo) 'listbarfoo) ((list a b c) (list 'list a b c)) ((cons 5 b) (list 'cons5 b)) ((cons a (cons b c)) (list 'cons a b c)) ((cons a b) (list 'cons a b)) (x (list 'x x))))) (check-equal? (foo empty) 'empty) (check-equal? (foo "empty") '(x "empty")) (check-equal? (foo (list 1 2 3)) '(list 1 2 3)) (check-equal? (foo (cons 'foo empty)) 'fooempty) (check-equal? (foo (cons 1 empty)) '(cons 1 ())) (check-equal? (foo (cons 5 empty)) '(cons5 ())) (check-equal? (foo (list 1 2)) '(cons 1 2 ())) (check-equal? (match empty ((list) 'bingo)) 'bingo) (check-equal? (match (list 1) ((list) 'bingo) (foo foo)) (list 1)) (check-equal? (foo (list 'foo 'bar)) 'listfoobar) (check-equal? (foo (list 'bar 'foo)) 'listbarfoo)) (test-case "anything" (check-equal? (match 5 (_ 7)) 7) (check-equal? (match 5 (... 7)) 7) (check-equal? (match '(1 2) (_ 7)) 7) (check-equal? (match '(1 2) (... 7)) 7) (check-equal? (match #f (_ 7)) 7) (check-equal? (match #f (... 7)) 7) (check-equal? (let ((_ 5)) (match #f (_ _))) 5) (check-equal? (match #f ((kons _ _) 7) (_ 5)) 5) (check-equal? (match #f ((kons ... ...) 7) (... 5)) 5) (check-equal? (match (kons 1 2) ((kons _ _) 7) (_ 5)) 7) (check-equal? (match (kons 1 2) ((kons ... ...) 7) (... 5)) 7)) (test-case "records" (define foo (lambda (x) (match x ((cons foo empty) 'pairfoo) ((make-nullary) 'nullary) ((kons a b) (list 'kons a b)) ((gons a b) (list 'gons a b))))) (check-equal? (foo (cons foo empty)) 'pairfoo) (check-equal? (foo (make-nullary)) 'nullary) (check-equal? (foo (kons 1 2)) '(kons 1 2)) (check-equal? (foo (gons 1 2)) '(gons 1 2))) (test-case "singletons" (define f (lambda (x) (match x (foo 'foo) (bar 'bar) ((kons foo bar) 'foobar) ((kons (kons foo bar) bar) 'foobarbar) (baz baz)))) (check-equal? (f foo) 'foo) (check-equal? (f bar) 'bar) (check-equal? (f (kons foo bar)) 'foobar) (check-equal? (f (kons (kons foo bar) bar)) 'foobarbar) (check-equal? (f 'baz) 'baz))))
daa6a36b6ca89bf2a53464406b7c1533f89f6e1e5018efe92d66a88afbe5d1ca
Ericson2314/lighthouse
Multipart.hs
-- #hide ----------------------------------------------------------------------------- -- | -- Module : Network.CGI.Multipart Copyright : ( c ) 2001,2002 ( c ) 2005 - 2006 -- License : BSD-style -- -- Maintainer : -- Stability : experimental -- Portability : non-portable -- -- Parsing of the multipart format from RFC2046. -- Partly based on code from WASHMail. -- ----------------------------------------------------------------------------- module Network.CGI.Multipart ( -- * Multi-part messages MultiPart(..), BodyPart(..), Header , parseMultipartBody, hGetMultipartBody , showMultipartBody -- * Headers , ContentType(..), ContentTransferEncoding(..) , ContentDisposition(..) , parseContentType , parseContentTransferEncoding , parseContentDisposition , getContentType , getContentTransferEncoding , getContentDisposition ) where import Control.Monad import Data.Int (Int64) import Data.List (intersperse) import Data.Maybe import System.IO (Handle) import Network.CGI.RFC822Headers import qualified Data.ByteString.Lazy.Char8 as BS import Data.ByteString.Lazy.Char8 (ByteString) -- -- * Multi-part stuff. -- data MultiPart = MultiPart [BodyPart] deriving (Show, Read, Eq, Ord) data BodyPart = BodyPart [Header] ByteString deriving (Show, Read, Eq, Ord) -- | Read a multi-part message from a 'ByteString'. parseMultipartBody :: String -- ^ Boundary -> ByteString -> MultiPart parseMultipartBody b = MultiPart . mapMaybe parseBodyPart . splitParts (BS.pack b) -- | Read a multi-part message from a 'Handle'. -- Fails on parse errors. hGetMultipartBody :: String -- ^ Boundary -> Handle -> IO MultiPart hGetMultipartBody b = liftM (parseMultipartBody b) . BS.hGetContents parseBodyPart :: ByteString -> Maybe BodyPart parseBodyPart s = do let (hdr,bdy) = splitAtEmptyLine s hs <- parseM pHeaders "<input>" (BS.unpack hdr) return $ BodyPart hs bdy showMultipartBody :: String -> MultiPart -> ByteString showMultipartBody b (MultiPart bs) = unlinesCRLF $ foldr (\x xs -> d:showBodyPart x:xs) [c,BS.empty] bs where d = BS.pack ("--" ++ b) c = BS.pack ("--" ++ b ++ "--") showBodyPart :: BodyPart -> ByteString showBodyPart (BodyPart hs c) = unlinesCRLF $ [BS.pack (n++": "++v) | (n,v) <- hs] ++ [BS.empty,c] -- -- * Splitting into multipart parts. -- -- | Split a multipart message into the multipart parts. splitParts :: ByteString -- ^ The boundary, without the initial dashes -> ByteString -> [ByteString] splitParts b = spl . dropPreamble b where spl x = case splitAtBoundary b x of Nothing -> [] Just (s1,d,s2) | isClose b d -> [s1] | otherwise -> s1:spl s2 | Drop everything up to and including the first line starting -- with the boundary. dropPreamble :: ByteString -- ^ The boundary, without the initial dashes -> ByteString -> ByteString dropPreamble b s | BS.null s = BS.empty | isBoundary b s = dropLine s | otherwise = dropPreamble b (dropLine s) | Split a string at the first boundary line . splitAtBoundary :: ByteString -- ^ The boundary, without the initial dashes -> ByteString -- ^ String to split. -> Maybe (ByteString,ByteString,ByteString) -- ^ The part before the boundary, the boundary line, -- and the part after the boundary line. The CRLF -- before and the CRLF (if any) after the boundary line -- are not included in any of the strings returned. -- Returns 'Nothing' if there is no boundary. splitAtBoundary b s = spl 0 where spl i = case findCRLF (BS.drop i s) of Nothing -> Nothing Just (j,l) | isBoundary b s2 -> Just (s1,d,s3) | otherwise -> spl (i+j+l) where s1 = BS.take (i+j) s s2 = BS.drop (i+j+l) s (d,s3) = splitAtCRLF s2 | Check whether a string starts with two dashes followed by -- the given boundary string. isBoundary :: ByteString -- ^ The boundary, without the initial dashes -> ByteString -> Bool isBoundary b s = startsWithDashes s && b `BS.isPrefixOf` BS.drop 2 s -- | Check whether a string for which 'isBoundary' returns true has two dashes after the boudary string . isClose :: ByteString -- ^ The boundary, without the initial dashes -> ByteString -> Bool isClose b s = startsWithDashes (BS.drop (2+BS.length b) s) | Checks whether a string starts with two dashes . startsWithDashes :: ByteString -> Bool startsWithDashes s = BS.pack "--" `BS.isPrefixOf` s -- * RFC 2046 CRLF -- crlf :: ByteString crlf = BS.pack "\r\n" unlinesCRLF :: [ByteString] -> ByteString unlinesCRLF = BS.concat . intersperse crlf | Drop everything up to and including the first CRLF . dropLine :: ByteString -> ByteString dropLine s = snd (splitAtCRLF s) | Split a string at the first empty line . The CRLF ( if any ) before the empty line is included in the first result . The CRLF after the -- empty line is not included in the result. -- If there is no empty line, the entire input is returned as the first result . splitAtEmptyLine :: ByteString -> (ByteString, ByteString) splitAtEmptyLine s | startsWithCRLF s = (BS.empty, dropCRLF s) | otherwise = spl 0 where spl i = case findCRLF (BS.drop i s) of Nothing -> (s, BS.empty) Just (j,l) | startsWithCRLF s2 -> (s1, dropCRLF s2) | otherwise -> spl (i+j+l) where (s1,s2) = BS.splitAt (i+j+l) s | Split a string at the first CRLF . The CRLF is not included -- in any of the returned strings. -- If there is no CRLF, the entire input is returned as the first string . splitAtCRLF :: ByteString -- ^ String to split. -> (ByteString,ByteString) splitAtCRLF s = case findCRLF s of Nothing -> (s,BS.empty) Just (i,l) -> (s1, BS.drop l s2) where (s1,s2) = BS.splitAt i s | Get the index and length of the first CRLF , if any . findCRLF :: ByteString -- ^ String to split. -> Maybe (Int64,Int64) findCRLF s = case findCRorLF s of Nothing -> Nothing Just j | BS.null (BS.drop (j+1) s) -> Just (j,1) Just j -> case (BS.index s j, BS.index s (j+1)) of ('\n','\r') -> Just (j,2) ('\r','\n') -> Just (j,2) _ -> Just (j,1) findCRorLF :: ByteString -> Maybe Int64 findCRorLF s = BS.findIndex (\c -> c == '\n' || c == '\r') s startsWithCRLF :: ByteString -> Bool startsWithCRLF s = not (BS.null s) && (c == '\n' || c == '\r') where c = BS.index s 0 -- | Drop an initial CRLF, if any. If the string is empty, -- nothing is done. If the string does not start with CRLF, the first character is dropped . dropCRLF :: ByteString -> ByteString dropCRLF s | BS.null s = BS.empty | BS.null (BS.drop 1 s) = BS.empty | c0 == '\n' && c1 == '\r' = BS.drop 2 s | c0 == '\r' && c1 == '\n' = BS.drop 2 s | otherwise = BS.drop 1 s where c0 = BS.index s 0 c1 = BS.index s 1
null
https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/ghc-6.8.2/libraries/cgi/Network/CGI/Multipart.hs
haskell
#hide --------------------------------------------------------------------------- | Module : Network.CGI.Multipart License : BSD-style Maintainer : Stability : experimental Portability : non-portable Parsing of the multipart format from RFC2046. Partly based on code from WASHMail. --------------------------------------------------------------------------- * Multi-part messages * Headers * Multi-part stuff. | Read a multi-part message from a 'ByteString'. ^ Boundary | Read a multi-part message from a 'Handle'. Fails on parse errors. ^ Boundary * Splitting into multipart parts. | Split a multipart message into the multipart parts. ^ The boundary, without the initial dashes with the boundary. ^ The boundary, without the initial dashes ^ The boundary, without the initial dashes ^ String to split. ^ The part before the boundary, the boundary line, and the part after the boundary line. The CRLF before and the CRLF (if any) after the boundary line are not included in any of the strings returned. Returns 'Nothing' if there is no boundary. the given boundary string. ^ The boundary, without the initial dashes | Check whether a string for which 'isBoundary' returns true ^ The boundary, without the initial dashes empty line is not included in the result. If there is no empty line, the entire input is returned in any of the returned strings. If there is no CRLF, the entire input is returned ^ String to split. ^ String to split. | Drop an initial CRLF, if any. If the string is empty, nothing is done. If the string does not start with CRLF,
Copyright : ( c ) 2001,2002 ( c ) 2005 - 2006 module Network.CGI.Multipart ( MultiPart(..), BodyPart(..), Header , parseMultipartBody, hGetMultipartBody , showMultipartBody , ContentType(..), ContentTransferEncoding(..) , ContentDisposition(..) , parseContentType , parseContentTransferEncoding , parseContentDisposition , getContentType , getContentTransferEncoding , getContentDisposition ) where import Control.Monad import Data.Int (Int64) import Data.List (intersperse) import Data.Maybe import System.IO (Handle) import Network.CGI.RFC822Headers import qualified Data.ByteString.Lazy.Char8 as BS import Data.ByteString.Lazy.Char8 (ByteString) data MultiPart = MultiPart [BodyPart] deriving (Show, Read, Eq, Ord) data BodyPart = BodyPart [Header] ByteString deriving (Show, Read, Eq, Ord) -> ByteString -> MultiPart parseMultipartBody b = MultiPart . mapMaybe parseBodyPart . splitParts (BS.pack b) -> Handle -> IO MultiPart hGetMultipartBody b = liftM (parseMultipartBody b) . BS.hGetContents parseBodyPart :: ByteString -> Maybe BodyPart parseBodyPart s = do let (hdr,bdy) = splitAtEmptyLine s hs <- parseM pHeaders "<input>" (BS.unpack hdr) return $ BodyPart hs bdy showMultipartBody :: String -> MultiPart -> ByteString showMultipartBody b (MultiPart bs) = unlinesCRLF $ foldr (\x xs -> d:showBodyPart x:xs) [c,BS.empty] bs where d = BS.pack ("--" ++ b) c = BS.pack ("--" ++ b ++ "--") showBodyPart :: BodyPart -> ByteString showBodyPart (BodyPart hs c) = unlinesCRLF $ [BS.pack (n++": "++v) | (n,v) <- hs] ++ [BS.empty,c] -> ByteString -> [ByteString] splitParts b = spl . dropPreamble b where spl x = case splitAtBoundary b x of Nothing -> [] Just (s1,d,s2) | isClose b d -> [s1] | otherwise -> s1:spl s2 | Drop everything up to and including the first line starting -> ByteString -> ByteString dropPreamble b s | BS.null s = BS.empty | isBoundary b s = dropLine s | otherwise = dropPreamble b (dropLine s) | Split a string at the first boundary line . -> Maybe (ByteString,ByteString,ByteString) splitAtBoundary b s = spl 0 where spl i = case findCRLF (BS.drop i s) of Nothing -> Nothing Just (j,l) | isBoundary b s2 -> Just (s1,d,s3) | otherwise -> spl (i+j+l) where s1 = BS.take (i+j) s s2 = BS.drop (i+j+l) s (d,s3) = splitAtCRLF s2 | Check whether a string starts with two dashes followed by -> ByteString -> Bool isBoundary b s = startsWithDashes s && b `BS.isPrefixOf` BS.drop 2 s has two dashes after the boudary string . -> ByteString -> Bool isClose b s = startsWithDashes (BS.drop (2+BS.length b) s) | Checks whether a string starts with two dashes . startsWithDashes :: ByteString -> Bool startsWithDashes s = BS.pack "--" `BS.isPrefixOf` s * RFC 2046 CRLF crlf :: ByteString crlf = BS.pack "\r\n" unlinesCRLF :: [ByteString] -> ByteString unlinesCRLF = BS.concat . intersperse crlf | Drop everything up to and including the first CRLF . dropLine :: ByteString -> ByteString dropLine s = snd (splitAtCRLF s) | Split a string at the first empty line . The CRLF ( if any ) before the empty line is included in the first result . The CRLF after the as the first result . splitAtEmptyLine :: ByteString -> (ByteString, ByteString) splitAtEmptyLine s | startsWithCRLF s = (BS.empty, dropCRLF s) | otherwise = spl 0 where spl i = case findCRLF (BS.drop i s) of Nothing -> (s, BS.empty) Just (j,l) | startsWithCRLF s2 -> (s1, dropCRLF s2) | otherwise -> spl (i+j+l) where (s1,s2) = BS.splitAt (i+j+l) s | Split a string at the first CRLF . The CRLF is not included as the first string . -> (ByteString,ByteString) splitAtCRLF s = case findCRLF s of Nothing -> (s,BS.empty) Just (i,l) -> (s1, BS.drop l s2) where (s1,s2) = BS.splitAt i s | Get the index and length of the first CRLF , if any . -> Maybe (Int64,Int64) findCRLF s = case findCRorLF s of Nothing -> Nothing Just j | BS.null (BS.drop (j+1) s) -> Just (j,1) Just j -> case (BS.index s j, BS.index s (j+1)) of ('\n','\r') -> Just (j,2) ('\r','\n') -> Just (j,2) _ -> Just (j,1) findCRorLF :: ByteString -> Maybe Int64 findCRorLF s = BS.findIndex (\c -> c == '\n' || c == '\r') s startsWithCRLF :: ByteString -> Bool startsWithCRLF s = not (BS.null s) && (c == '\n' || c == '\r') where c = BS.index s 0 the first character is dropped . dropCRLF :: ByteString -> ByteString dropCRLF s | BS.null s = BS.empty | BS.null (BS.drop 1 s) = BS.empty | c0 == '\n' && c1 == '\r' = BS.drop 2 s | c0 == '\r' && c1 == '\n' = BS.drop 2 s | otherwise = BS.drop 1 s where c0 = BS.index s 0 c1 = BS.index s 1
b095d9eb9b7e61b3952fb1aa9ed2586ea68b230a5315ac5071e1f81e31b8c904
GaloisInc/daedalus
ParamLL.hs
module Daedalus.ParserGen.LL.ParamLL ( cst_CLOSURE_MAX_DEPTH , cst_MAX_LOOKAHEAD_DEPTH , cst_MAX_DFA_NB_STATES , cst_OVERFLOW_CFG , cst_DEMO_MODE , cst_MAX_LLA_SIZE , flag_ONLY_STRICT_LLA ) where -- Closure params cst_CLOSURE_MAX_DEPTH :: Int cst_CLOSURE_MAX_DEPTH = 200 DFA params cst_MAX_LOOKAHEAD_DEPTH :: Int cst_MAX_LOOKAHEAD_DEPTH = 20 cst_MAX_DFA_NB_STATES :: Int cst_MAX_DFA_NB_STATES = 100 cst_OVERFLOW_CFG :: Int cst_OVERFLOW_CFG = 10 cst_DEMO_MODE :: Bool cst_DEMO_MODE = True LLA params cst_MAX_LLA_SIZE :: Int cst_MAX_LLA_SIZE = 4000 flag_ONLY_STRICT_LLA :: Bool flag_ONLY_STRICT_LLA = False
null
https://raw.githubusercontent.com/GaloisInc/daedalus/09cd9f08a7bcab7062714b77362bcbfd6212ea59/src/Daedalus/ParserGen/LL/ParamLL.hs
haskell
Closure params
module Daedalus.ParserGen.LL.ParamLL ( cst_CLOSURE_MAX_DEPTH , cst_MAX_LOOKAHEAD_DEPTH , cst_MAX_DFA_NB_STATES , cst_OVERFLOW_CFG , cst_DEMO_MODE , cst_MAX_LLA_SIZE , flag_ONLY_STRICT_LLA ) where cst_CLOSURE_MAX_DEPTH :: Int cst_CLOSURE_MAX_DEPTH = 200 DFA params cst_MAX_LOOKAHEAD_DEPTH :: Int cst_MAX_LOOKAHEAD_DEPTH = 20 cst_MAX_DFA_NB_STATES :: Int cst_MAX_DFA_NB_STATES = 100 cst_OVERFLOW_CFG :: Int cst_OVERFLOW_CFG = 10 cst_DEMO_MODE :: Bool cst_DEMO_MODE = True LLA params cst_MAX_LLA_SIZE :: Int cst_MAX_LLA_SIZE = 4000 flag_ONLY_STRICT_LLA :: Bool flag_ONLY_STRICT_LLA = False
614d8ad6155a78718cf8b3a42f7713f4a11b2393527c6da750d8d51fedb8180f
jonsterling/dreamtt
Refiner.ml
open Basis open Syntax open Effect exception TypeError open Monad.Notation (L) type tp_rule = ltp L.m type chk_rule = gtp -> ltm L.m type syn_rule = gtm L.m let with_tp kont tp = kont tp tp let inst_tp_fam : ltp -> env -> gtm -> gtp G.m = fun lfam env gtm -> let envx = Env.append env @@ `Tm gtm in G.local envx @@ Eval.eval_tp lfam let inst_tm_fam : ltm -> env -> gtm -> gtm G.m = fun lfam env gtm -> let envx = Env.append env @@ `Tm gtm in G.local envx @@ Eval.eval lfam let core = L.ret let bool : tp_rule = L.ret LBool let tt : chk_rule = function | GBool -> L.ret LTt | _ -> L.throw TypeError let ff : chk_rule = function | GBool -> L.ret LFf | _ -> L.throw TypeError (* invariant: does not return unless the list of labels has no shadowing *) type tele_rule = (string list * ltele) L.m let tl_nil : tele_rule = L.ret ([], LTlNil) let rec freshen lbl lbls = if List.mem lbl lbls then freshen (lbl ^ "'") lbls else lbl let tl_cons lbl tp_rule tele_rule = let* lbase = tp_rule in let* gbase = Eval.eval_tp lbase in L.bind_tm gbase @@ fun var -> let+ lbls, lfam = tele_rule var in let lbl' = freshen lbl lbls in lbl' :: lbls, LTlCons (lbase, lfam) let pi (base : tp_rule) (fam : gtm -> tp_rule) : tp_rule = let* lbase = base in let* gbase = Eval.eval_tp lbase in L.bind_tm gbase @@ fun var -> let+ lfam = fam var in LPi (lbase, lfam) let rcd_tp (tele : tele_rule) : tp_rule = let+ lbls, ltl = tele in LRcdTp (lbls, ltl) let lam (bdy : gtm -> chk_rule) : chk_rule = function | GPi ((gbase, lfam, env) as gfam) -> L.bind_tm gbase @@ fun var -> let+ lbdy = bdy var @<< L.global @@ inst_tp_fam lfam env var in LLam (gfam, lbdy) | _ -> L.throw TypeError let rcd (chk_map : chk_rule StringMap.t) : chk_rule = function | GRcdTp (lbls, gtl) -> let rec loop tmap lbls gtl = match lbls, gtl with | [], GTlNil -> L.ret tmap | lbl :: lbls, GTlCons (gtp, ltl, tlenv) -> begin match StringMap.find_opt lbl chk_map with | Some chk_rule -> let* ltm = chk_rule gtp in let* gtm = Eval.eval ltm in let* gtl' = L.global @@ G.local tlenv @@ L.append_tm gtm @@ Eval.eval_tele ltl in let tmap' = StringMap.add lbl ltm tmap in loop tmap' lbls gtl' | None -> L.throw TypeError end | _ -> L.throw TypeError in let* tmap = loop StringMap.empty lbls gtl in L.ret @@ LRcd (lbls, gtl, tmap) | _ -> L.throw TypeError let app (fn : syn_rule) (arg : chk_rule) : syn_rule = let* gtm0 = fn in match tp_of_gtm gtm0 with | GPi (gbase, _, _) -> let* larg = arg gbase in let* gtm1 = Eval.eval larg in L.global @@ Eval.gapp gtm0 gtm1 | _ -> L.throw TypeError let proj lbl (syn_rule : syn_rule) : syn_rule = let* gtm = syn_rule in match tp_of_gtm gtm with | GRcdTp (lbls, _) when List.mem lbl lbls -> L.global @@ Eval.gproj lbl gtm | _ -> L.throw TypeError let fst (syn_rule : syn_rule) : syn_rule = proj "fst" syn_rule let snd (syn_rule : syn_rule) : syn_rule = proj "snd" syn_rule let sg (base : tp_rule) (fam : gtm -> tp_rule) : tp_rule = rcd_tp @@ tl_cons "fst" base @@ fun var -> tl_cons "snd" (fam var) @@ fun _ -> tl_nil let pair (chk_rule0 : chk_rule) (chk_rule1 : chk_rule) : chk_rule = StringMap.empty |> StringMap.add "fst" chk_rule0 |> StringMap.add "snd" chk_rule1 |> rcd let chk_abort : chk_rule = fun _ -> let* thy = L.theory in match Logic.consistency thy with | `Inconsistent -> L.ret LAbort | `Consistent -> L.throw TypeError let rec conv_ : gtm -> chk_rule = function | GTt -> tt | GFf -> ff | GLam (_, ltm, env) -> lam @@ fun var gfib -> let* gtm = L.global @@ inst_tm_fam ltm env var in conv_ gtm gfib | GRcd (_, _, gmap) -> rcd @@ StringMap.map conv_ gmap | Glued glued -> conv_glued_ glued | GAbort -> chk_abort and conv_glued_ : (gneu, ltm) glued -> chk_rule = fun (Gl glued) gtp -> let* gtm = L.global @@ G.local glued.env @@ Eval.eval glued.part in let* () = Equate.equate_gtp gtp glued.gtp in let* thy = L.theory in if Logic.test thy [] glued.supp then conv_ gtm gtp else conv_neu_ glued.base and conv_neu_ : gneu -> ltm L.m = function | GVar lvl -> let+ env = L.env in let ix = Env.lvl_to_ix env lvl in LVar ix | GSnoc (gneu, gfrm) -> let* ltm = conv_neu_ gneu in match gfrm with | GProj lbl -> L.ret @@ LProj (lbl, ltm) | GApp arg -> let* ltm = conv_neu_ gneu in let tp_arg = tp_of_gtm arg in let* larg = conv_ arg tp_arg in L.ret @@ LApp (ltm, larg) let conv : syn_rule -> chk_rule = fun syn gtp -> let* gtm = syn in conv_ gtm gtp let fail_tp exn = L.throw exn let fail_chk exn _ = L.throw exn let fail_syn exn = L.throw exn
null
https://raw.githubusercontent.com/jonsterling/dreamtt/aa30a57ca869e91a295e586773a892c6601b5ddb/core/Refiner.ml
ocaml
invariant: does not return unless the list of labels has no shadowing
open Basis open Syntax open Effect exception TypeError open Monad.Notation (L) type tp_rule = ltp L.m type chk_rule = gtp -> ltm L.m type syn_rule = gtm L.m let with_tp kont tp = kont tp tp let inst_tp_fam : ltp -> env -> gtm -> gtp G.m = fun lfam env gtm -> let envx = Env.append env @@ `Tm gtm in G.local envx @@ Eval.eval_tp lfam let inst_tm_fam : ltm -> env -> gtm -> gtm G.m = fun lfam env gtm -> let envx = Env.append env @@ `Tm gtm in G.local envx @@ Eval.eval lfam let core = L.ret let bool : tp_rule = L.ret LBool let tt : chk_rule = function | GBool -> L.ret LTt | _ -> L.throw TypeError let ff : chk_rule = function | GBool -> L.ret LFf | _ -> L.throw TypeError type tele_rule = (string list * ltele) L.m let tl_nil : tele_rule = L.ret ([], LTlNil) let rec freshen lbl lbls = if List.mem lbl lbls then freshen (lbl ^ "'") lbls else lbl let tl_cons lbl tp_rule tele_rule = let* lbase = tp_rule in let* gbase = Eval.eval_tp lbase in L.bind_tm gbase @@ fun var -> let+ lbls, lfam = tele_rule var in let lbl' = freshen lbl lbls in lbl' :: lbls, LTlCons (lbase, lfam) let pi (base : tp_rule) (fam : gtm -> tp_rule) : tp_rule = let* lbase = base in let* gbase = Eval.eval_tp lbase in L.bind_tm gbase @@ fun var -> let+ lfam = fam var in LPi (lbase, lfam) let rcd_tp (tele : tele_rule) : tp_rule = let+ lbls, ltl = tele in LRcdTp (lbls, ltl) let lam (bdy : gtm -> chk_rule) : chk_rule = function | GPi ((gbase, lfam, env) as gfam) -> L.bind_tm gbase @@ fun var -> let+ lbdy = bdy var @<< L.global @@ inst_tp_fam lfam env var in LLam (gfam, lbdy) | _ -> L.throw TypeError let rcd (chk_map : chk_rule StringMap.t) : chk_rule = function | GRcdTp (lbls, gtl) -> let rec loop tmap lbls gtl = match lbls, gtl with | [], GTlNil -> L.ret tmap | lbl :: lbls, GTlCons (gtp, ltl, tlenv) -> begin match StringMap.find_opt lbl chk_map with | Some chk_rule -> let* ltm = chk_rule gtp in let* gtm = Eval.eval ltm in let* gtl' = L.global @@ G.local tlenv @@ L.append_tm gtm @@ Eval.eval_tele ltl in let tmap' = StringMap.add lbl ltm tmap in loop tmap' lbls gtl' | None -> L.throw TypeError end | _ -> L.throw TypeError in let* tmap = loop StringMap.empty lbls gtl in L.ret @@ LRcd (lbls, gtl, tmap) | _ -> L.throw TypeError let app (fn : syn_rule) (arg : chk_rule) : syn_rule = let* gtm0 = fn in match tp_of_gtm gtm0 with | GPi (gbase, _, _) -> let* larg = arg gbase in let* gtm1 = Eval.eval larg in L.global @@ Eval.gapp gtm0 gtm1 | _ -> L.throw TypeError let proj lbl (syn_rule : syn_rule) : syn_rule = let* gtm = syn_rule in match tp_of_gtm gtm with | GRcdTp (lbls, _) when List.mem lbl lbls -> L.global @@ Eval.gproj lbl gtm | _ -> L.throw TypeError let fst (syn_rule : syn_rule) : syn_rule = proj "fst" syn_rule let snd (syn_rule : syn_rule) : syn_rule = proj "snd" syn_rule let sg (base : tp_rule) (fam : gtm -> tp_rule) : tp_rule = rcd_tp @@ tl_cons "fst" base @@ fun var -> tl_cons "snd" (fam var) @@ fun _ -> tl_nil let pair (chk_rule0 : chk_rule) (chk_rule1 : chk_rule) : chk_rule = StringMap.empty |> StringMap.add "fst" chk_rule0 |> StringMap.add "snd" chk_rule1 |> rcd let chk_abort : chk_rule = fun _ -> let* thy = L.theory in match Logic.consistency thy with | `Inconsistent -> L.ret LAbort | `Consistent -> L.throw TypeError let rec conv_ : gtm -> chk_rule = function | GTt -> tt | GFf -> ff | GLam (_, ltm, env) -> lam @@ fun var gfib -> let* gtm = L.global @@ inst_tm_fam ltm env var in conv_ gtm gfib | GRcd (_, _, gmap) -> rcd @@ StringMap.map conv_ gmap | Glued glued -> conv_glued_ glued | GAbort -> chk_abort and conv_glued_ : (gneu, ltm) glued -> chk_rule = fun (Gl glued) gtp -> let* gtm = L.global @@ G.local glued.env @@ Eval.eval glued.part in let* () = Equate.equate_gtp gtp glued.gtp in let* thy = L.theory in if Logic.test thy [] glued.supp then conv_ gtm gtp else conv_neu_ glued.base and conv_neu_ : gneu -> ltm L.m = function | GVar lvl -> let+ env = L.env in let ix = Env.lvl_to_ix env lvl in LVar ix | GSnoc (gneu, gfrm) -> let* ltm = conv_neu_ gneu in match gfrm with | GProj lbl -> L.ret @@ LProj (lbl, ltm) | GApp arg -> let* ltm = conv_neu_ gneu in let tp_arg = tp_of_gtm arg in let* larg = conv_ arg tp_arg in L.ret @@ LApp (ltm, larg) let conv : syn_rule -> chk_rule = fun syn gtp -> let* gtm = syn in conv_ gtm gtp let fail_tp exn = L.throw exn let fail_chk exn _ = L.throw exn let fail_syn exn = L.throw exn
fe4bba2122c400875e77d0177bd6011de60ebfebadbb8b09456b5f9cc44a368d
acl2/acl2
executable.lisp
ABNF ( Augmented Backus - Naur Form ) Library ; Copyright ( C ) 2023 Kestrel Institute ( ) ; License : A 3 - clause BSD license . See the LICENSE file distributed with ACL2 . ; Author : ( ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ABNF") (include-book "../notation/concrete-syntax") (include-book "../parsing-tools/primitives-seq") (include-book "kestrel/utilities/strings/chars-codes" :dir :system) (include-book "std/io/read-file-characters" :dir :system) (local (include-book "kestrel/utilities/typed-lists/nat-list-fix-theorems" :dir :system)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defxdoc+ grammar-parser-implementation :parents (grammar-parser) :short "Implementation of the parser of ABNF grammars." :long (xdoc::topstring (xdoc::p "This is a recursive-descent, backtracking parser. There is a parsing function for every rule, and parsing functions for certain groups, options, and repetitions. There are also parameterized parsing functions for terminals (natural numbers) matching exact values, ranges, and (case-insensitively) characters.") (xdoc::h3 "Parsing Primitive") (xdoc::p "Some of the parsing functions that make up the parser are " (xdoc::seetopic "parsing-primitives-seq" "<i>Seq</i> parsing primitives") ". The remarks below apply to those functions as well.") (xdoc::h3 "Inputs and Outputs") (xdoc::p "Each of these parsing functions takes as input a list of natural numbers (i.e. terminals), and returns as outputs (i) an indication of success or failure, (ii) the tree or list of trees obtained from parsing a prefix of the input (or @('nil') if parsing fails), and (iii) the remaining suffix of the input that must still be parsed. The indication of success or failure is either @('nil') to indicate success, or a " (xdoc::seetopic "msg" "message") " to describe the failure. This is consistent with the <i>@(see Seq)</i> macros, with which these parsing functions are implemented.") (xdoc::p "The @(tsee parse-grammar) top-level function takes as input a list of natural numbers and returns as output just a tree, or @('nil') to indicate failure; this function consumes all the input, failing if there is unparsed input. The @(tsee parse-grammar-from-file) function takes as input a file name and calls @(tsee parse-grammar) on its content, returning a tree or @('nil').") (xdoc::p "Each parsing function definition is accompanied by a theorem stating that the function fixes its input list of natural numbers. The proof of each such theorem uses, as rewrite rules, the theorems for the parsing functions called by the parsing function whose theorem is being proved.") (xdoc::h3 "Disambiguation and Look-Ahead") (xdoc::p "As explained in the documentation of @(tsee parse-grammar*), the grammar of the ABNF concrete syntax [RFC:4] is ambiguous. The rule @('rulelist') allows strings `@('c-nl WSP')' either to be split into an ending @('c-nl') under a @('rule') and a starting @('WSP') under an immediately following @('(*c-wsp c-nl)'), or to be made into a @('c-wsp') in the ending part of @('elements') under the @('rule'). The same kind of choice applies when, instead of a @('rule') immediately followed by a @('(*c-wsp c-nl)'), there are two subsequent @('(*c-wsp c-nl)')s: the string `@('c-nl WSP')' can be either split between the two @('(*c-wsp c-nl)')s or put all under the first one. Indeed, expanding @('elements') in the definiens of @('rule') gives @('... *c-wsp c-nl'), which ends in the same way as the group @('(*c-wsp c-nl)'): this is why the ambiguity applies equally to a @('rule') immediately followed by a @('(*c-wsp c-nl)') and to a @('(*c-wsp c-nl)') immediately followed by a @('(*c-wsp c-nl)').") (xdoc::p "Aside from the @('rulelist') rule, the rest of the grammar is LL(*):") (xdoc::ul (xdoc::li "In the @('repeat') rule, a look-ahead of an unbounded number of @('DIGIT')s is needed to determine the alternative (the second alternative if @('\"*\"') is found after the @('DIGIT')s, otherwise the first alternative).") (xdoc::li "In the @('concatenation') rule, a look-ahead of an unbounded number of @('c-wsp')s is needed to determine where a @('concatenation') ends (it does if no @('repetition') is found after the @('c-wsp')s, otherwise the @('concatenation') continues with the found @('repetition')).")) (xdoc::p "Aside from the @('rulelist'), @('repeat'), and @('concatenation') rules, the rest of the grammar is LL(2):") (xdoc::ul (xdoc::li "In the @('defined-as') rule, a look-ahead of two symbols is needed to distinguish @('\"=\"') and @('\"=/\"').") (xdoc::li "In the @('element') rule, a look-ahead of two symbols is needed to distinguish @('num-val') and @('char-val') (the two symbols are @('\"%\"') and the one after).") (xdoc::li "In the @('char-val') rule, a look-ahead of two symbols is needed to distinguish @('case-insensitive-string') and @('case-sensitive-string') (the two symbols are @('\"%\"') and the one after).")) (xdoc::p "In each of the three rules listed above, the two choices have the first character in common. Thus, it may seem that these rules are actually LL(1), by first parsing the first character in common and then deciding how to proceed based on the next character. However, each character pair like @('\"=/\"') and @('\"%s\"') is parsed in one shot via one call to @(tsee parse-ichar2) which produces a single leaf tree with the list of those two character codes, not via two calls to @(tsee parse-ichar) which would produce two leaf trees each with a singleton list of one character code. If the rules were formulated as concatenations of single-character strings (e.g. @('\"=\" \"/\"') and @('\"%\" \"s\"')) instead, these rules would be LL(1).") (xdoc::p "Aside from the @('rulelist'), @('repeat'), @('concatenation'), @('defined-as'), @('element'), and @('char-val') rules, the rest of the grammar is LL(1).") (xdoc::p "The parser resolves the @('rulelist') ambiguity by keeping strings `@('c-nl WSP')' as @('c-wsp')s under @('rule') or under the first @('(*c-wsp c-nl)') of two subsequent @('(*c-wsp c-nl)')s, instead of splitting them into a @('c-nl') to end the @('rule') or to end the first @('(*c-wsp c-nl)') of two subsequent @('(*c-wsp c-nl)')s, and a @('WSP') to start the subsequent @('(*c-wsp c-nl)'). The decision point is when a @('c-nl') is encountered while parsing the ending @('*c-wsp') of @('elements') or while parsing the @('*c-wsp') of a @('(*c-wsp c-nl)'): should the @('*c-wsp') be considered finished and the @('c-nl') used to end the @('rule') or @('(*c-wsp c-nl)'), or should the parser attempt to extend the @('*c-wsp') with an extra @('c-wsp'), if the @('c-nl') is followed by a @('WSP')? By having @(tsee parse-*cwsp) always try the extra @('c-wsp'), we never split strings `@('c-nl WSP')'. Thus, @(tsee parse-*cwsp) tries to parse as many @('c-wsp')s as possible, like all the other @('parse-*...') parsing functions. If the @('c-nl') is not followed by a @('WSP'), the parsing of the extra @('c-wsp') fails and the only possibility left is to finish the @('*c-wsp') and use the @('c-nl') to end the @('rule') or the @('(*c-wsp c-nl)'); there is no ambiguity in this case.") (xdoc::p "The look-ahead for the LL(*), LL(2), and LL(1) rules is handled via backtracking. The amount of backtracking is expected to be small in reasonable grammars.") (xdoc::h3 "Termination") (xdoc::p "The termination of the singly recursive parsing functions (e.g. @(tsee parse-*bit)) is proved by showing that the size of the input decreases.") (xdoc::p "The termination of the mutually recursive parsing functions (i.e. @(tsee parse-alternation), @(tsee parse-concatenation), etc.) is proved via a lexicographic measure consisting of the size of the input and an ordering of the parsing functions. This is explained in the following paragraphs.") (xdoc::p "Since @(tsee parse-alternation) calls @(tsee parse-concatenation) on the same input, the size of the input alone is not sufficient to show that the mutually recursive parsing functions terminate. But @(tsee parse-concatenation) never (indirectly) calls @(tsee parse-alternation) on the same input: it has to go through @(tsee parse-group) or @(tsee parse-option), which consume a @('\"(\"') or a @('\"[\"') before calling @(tsee parse-alternation) on, therefore, a smaller input. So if we order the parsing functions, by assigning numbers to them, so that @(tsee parse-alternation) has a larger order number than @(tsee parse-concatenation), either the size of the input goes down, or it stays the same but the parsing function order number goes down. In other words, the lexicographic measure goes down.") (xdoc::p "To establish the relative ordering of the parsing functions, we look at which ones (may) call which other ones on the same input: the former must be (assigned) larger (order numbers) than the latter. Thus, we have the following ordering constraints:") (xdoc::ul (xdoc::li "@(tsee parse-alternation) must be larger than @(tsee parse-concatenation).") (xdoc::li "@(tsee parse-concatenation) must be larger than @(tsee parse-repetition).") (xdoc::li "@(tsee parse-repetition) must be larger than @(tsee parse-element). (The former calls the latter on the same input if @(tsee parse-?repeat) does not consume any input.)") (xdoc::li "@(tsee parse-element) must be larger than @(tsee parse-group).") (xdoc::li "@(tsee parse-element) must be larger than @(tsee parse-option).") (xdoc::li "@(tsee parse-alt-rest) must be larger than @(tsee parse-alt-rest-comp).") (xdoc::li "@(tsee parse-conc-rest) must be larger than @(tsee parse-conc-rest-comp).")) (xdoc::p "These constraints provide a partial order on the parsing function, which we can totalize as follows (from smallest to largest):") (xdoc::ol (xdoc::li "@(tsee parse-conc-rest-comp)") (xdoc::li "@(tsee parse-conc-rest)") (xdoc::li "@(tsee parse-alt-rest-comp)") (xdoc::li "@(tsee parse-alt-rest)") (xdoc::li "@(tsee parse-option)") (xdoc::li "@(tsee parse-group)") (xdoc::li "@(tsee parse-element)") (xdoc::li "@(tsee parse-repetition)") (xdoc::li "@(tsee parse-concatenation)") (xdoc::li "@(tsee parse-alternation)")) (xdoc::p "Note that when a smaller function calls a larger or equal function, it does so on a smaller input. In particular: @(tsee parse-group) and @(tsee parse-option) call @(tsee parse-alternation) only after consuming a @('\"(\"') or a @('\"[\"'); @(tsee parse-alt-rest-comp) calls @(tsee parse-concatenation) only after consuming at least a @('\"\/\"'); and @(tsee parse-conc-rest-comp) calls @(tsee parse-repetition) only after consuming at least one @('c-wsp'), which is never empty.") (xdoc::p "The theorems about input lengths that accompany the parsing function definitions are used in the termination proofs, both of the singly recursive functions and of the mutually recursive functions.") (xdoc::p "The termination of the mutually recursive parsing functions involves an additional complication. After @(tsee parse-alternation) calls @(tsee parse-concatenation), it may call @(tsee parse-alt-rest), which involves a proof obligation that the input to @(tsee parse-alt-rest), which is the remaining input after @(tsee parse-concatenation), has length less than or equal to the input to @(tsee parse-alternation). This is the case, because @(tsee parse-concatenation) always returns a remaining input of length less than or equal to its input. But this property can be only proved after @(tsee parse-concatenation) is admitted, that is after its (mutual) termination has been proved: for the termination proof, it is like an uninterpreted function. The same holds for the interaction between other mutually recursive parsing functions.") (xdoc::p "The known solution to the issue just discussed is to add tests saying that the remaining input of @(tsee parse-concatenation) is smaller than the initial input to @(tsee parse-alternation) (which is also the input to @(tsee parse-concatenation)). This way the termination proof can proceeed. However, since those tests are always true, they can be wrapped in @(tsee mbt), which engenders the obligation to prove that are always true, as part of guard verification (and additionally, their execution is avoided). The <i>@(see Seq)</i> macros provide operators @(':s=') and @(':w=') for this purpose (see their documentation): they generate @(tsee mbt) tests of inequalities on the lengths of inputs and remaining inputs. So we use those in our mutually recursive parsing functions.")) :order-subtopics t) (defval *grammar-parser-error-msg* :parents (grammar-parser-implementation) :short "Message for grammar parsing errors." :long (xdoc::topstring-p "This message does not carry a lot of information, but it keeps the grammar parser simpler for now.") (msg "ABNF Grammar Parser Error.~%") /// (defruled msgp-of-*grammar-parser-error-msg* (msgp *grammar-parser-error-msg*))) (define parse-in-either-range ((min1 natp) (max1 natp) (min2 natp) (max2 natp) (input nat-listp)) :guard (and (<= min1 max1) (< max1 min2) (<= min2 max2)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a natural number in one of two given ranges into a tree that matches a group consisting of an alternation of the corresponding range numeric value notations." (seq-backtrack input ((tree := (parse-in-range min1 max1 input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-in-range min2 max2 input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree)))))) :no-function t /// (fty::deffixequiv parse-in-either-range :args ((input nat-listp))) (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-in-either-range-linear :rule-classes :linear))) (define parse-*-in-either-range ((min1 natp) (max1 natp) (min2 natp) (max2 natp) (input nat-listp)) :guard (and (<= min1 max1) (< max1 min2) (<= min2 max2)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse zero or more natural numbers, each of which in one of two given ranges, into a list of trees that matches the repetition of zero or more alternations of the corresponding range numeric value notations." (seq-backtrack input ((tree := (parse-in-either-range min1 max1 min2 max2 input)) (trees := (parse-*-in-either-range min1 max1 min2 max2 input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t /// (fty::deffixequiv parse-*-in-either-range :args ((input nat-listp))) (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*-in-either-range-linear :rule-classes :linear))) (define parse-ichar ((char characterp) (input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a natural number that encodes, case-insensitively, a given character, into a tree that matches a case-insensitive character value notation that consists of that character." (b* (((mv error? nat input) (parse-any input)) ((when error?) (mv error? nil input)) ((unless (nat-match-insensitive-char-p nat char)) (mv *grammar-parser-error-msg* nil (cons nat input)))) (mv nil (tree-leafterm (list nat)) input)) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-ichar-linear :rule-classes :linear))) (define parse-ichar2 ((char1 characterp) (char2 characterp) (input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse two natural numbers that encode, case-insensitively, two given characters, into a tree that matches a case-insensitive character value notation that consists of those two characters." (b* (((mv error? nat1 input) (parse-any input)) ((when error?) (mv error? nil input)) ((unless (nat-match-insensitive-char-p nat1 char1)) (mv *grammar-parser-error-msg* nil (cons nat1 input))) ((mv error? nat2 input) (parse-any input)) ((when error?) (mv error? nil input)) ((unless (nat-match-insensitive-char-p nat2 char2)) (mv *grammar-parser-error-msg* nil (cons nat2 input)))) (mv nil (tree-leafterm (list nat1 nat2)) input)) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-ichar2-linear :rule-classes :linear))) (define parse-alpha ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a letter." (seq-backtrack input ((tree := (parse-in-range #x41 #x5a input)) (return (make-tree-nonleaf :rulename? *alpha* :branches (list (list tree))))) ((tree := (parse-in-range #x61 #x7a input)) (return (make-tree-nonleaf :rulename? *alpha* :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-alpha-linear :rule-classes :linear))) (define parse-bit ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a bit." (seq-backtrack input ((tree := (parse-ichar #\0 input)) (return (make-tree-nonleaf :rulename? *bit* :branches (list (list tree))))) ((tree := (parse-ichar #\1 input)) (return (make-tree-nonleaf :rulename? *bit* :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-bit-linear :rule-classes :linear))) (define parse-cr ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a carriage return." (seq input (tree := (parse-exact #x0d input)) (return (make-tree-nonleaf :rulename? *cr* :branches (list (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-cr-linear :rule-classes :linear))) (define parse-digit ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a decimal digit." (seq input (tree := (parse-in-range #x30 #x39 input)) (return (make-tree-nonleaf :rulename? *digit* :branches (list (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-digit-linear :rule-classes :linear))) (define parse-dquote ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a double quote." (seq input (tree := (parse-exact #x22 input)) (return (make-tree-nonleaf :rulename? *dquote* :branches (list (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dquote-linear :rule-classes :linear))) (define parse-htab ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a horizontal tab." (seq input (tree := (parse-exact #x09 input)) (return (make-tree-nonleaf :rulename? *htab* :branches (list (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-htab-linear :rule-classes :linear))) (define parse-lf ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a line feed." (seq input (tree := (parse-exact #x0a input)) (return (make-tree-nonleaf :rulename? *lf* :branches (list (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-lf-linear :rule-classes :linear))) (define parse-sp ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a space." (seq input (tree := (parse-exact #x20 input)) (return (make-tree-nonleaf :rulename? *sp* :branches (list (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-sp-linear :rule-classes :linear))) (define parse-vchar ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a visible character." (seq input (tree := (parse-in-range #x21 #x7e input)) (return (make-tree-nonleaf :rulename? *vchar* :branches (list (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-vchar-linear :rule-classes :linear))) (define parse-crlf ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a carriage return followed by a line feed." (seq input (tree-cr := (parse-cr input)) (tree-lf := (parse-lf input)) (return (make-tree-nonleaf :rulename? *crlf* :branches (list (list tree-cr) (list tree-lf))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-crlf-linear :rule-classes :linear))) (define parse-hexdig ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a hexadecimal digit." (seq-backtrack input ((tree := (parse-digit input)) (return (make-tree-nonleaf :rulename? *hexdig* :branches (list (list tree))))) ((tree := (parse-ichar #\A input)) (return (make-tree-nonleaf :rulename? *hexdig* :branches (list (list tree))))) ((tree := (parse-ichar #\B input)) (return (make-tree-nonleaf :rulename? *hexdig* :branches (list (list tree))))) ((tree := (parse-ichar #\C input)) (return (make-tree-nonleaf :rulename? *hexdig* :branches (list (list tree))))) ((tree := (parse-ichar #\D input)) (return (make-tree-nonleaf :rulename? *hexdig* :branches (list (list tree))))) ((tree := (parse-ichar #\E input)) (return (make-tree-nonleaf :rulename? *hexdig* :branches (list (list tree))))) ((tree := (parse-ichar #\F input)) (return (make-tree-nonleaf :rulename? *hexdig* :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-hexdig-linear :rule-classes :linear))) (define parse-wsp ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a space or horizontal tab." (seq-backtrack input ((tree := (parse-sp input)) (return (make-tree-nonleaf :rulename? *wsp* :branches (list (list tree))))) ((tree := (parse-htab input)) (return (make-tree-nonleaf :rulename? *wsp* :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-wsp-linear :rule-classes :linear))) (define parse-prose-val ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a prose value notation." (seq input (tree-open-angle := (parse-ichar #\< input)) (trees-text := (parse-*-in-either-range #x20 #x3d #x3f #x7e input)) (tree-close-angle := (parse-ichar #\> input)) (return (make-tree-nonleaf :rulename? *prose-val* :branches (list (list tree-open-angle) trees-text (list tree-close-angle))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-prose-val-linear :rule-classes :linear))) (define parse-*bit ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of zero or more bits." (seq-backtrack input ((tree := (parse-bit input)) (trees := (parse-*bit input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*bit-linear :rule-classes :linear))) (define parse-*digit ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of zero or more decimal digits." (seq-backtrack input ((tree := (parse-digit input)) (trees := (parse-*digit input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*digit-linear :rule-classes :linear))) (define parse-*hexdig ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of zero or more hexadecimal digits." (seq-backtrack input ((tree := (parse-hexdig input)) (trees := (parse-*hexdig input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*hexdig-linear :rule-classes :linear))) (define parse-1*bit ((input nat-listp)) :returns (mv (error? maybe-msgp) (trees (and (tree-listp trees) (implies error? (not trees)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of one or more bits." (seq input (tree := (parse-bit input)) (trees := (parse-*bit input)) (return (cons tree trees))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-1*bit-linear :rule-classes :linear))) (define parse-1*digit ((input nat-listp)) :returns (mv (error? maybe-msgp) (trees (and (tree-listp trees) (implies error? (not trees)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of one or more decimal digits." (seq input (tree := (parse-digit input)) (trees := (parse-*digit input)) (return (cons tree trees))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-1*digit-linear :rule-classes :linear))) (define parse-1*hexdig ((input nat-listp)) :returns (mv (error? maybe-msgp) (trees (and (tree-listp trees) (implies error? (not trees)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of one or more hexadecimal digits." (seq input (tree := (parse-hexdig input)) (trees := (parse-*hexdig input)) (return (cons tree trees))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-1*hexdig-linear :rule-classes :linear))) (define parse-dot-1*bit ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(\".\" 1*BIT)')." (seq input (tree := (parse-ichar #\. input)) (trees := (parse-1*bit input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dot-*1bit-linear :rule-classes :linear))) (define parse-dot-1*digit ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(\".\" 1*DIGIT)')." (seq input (tree := (parse-ichar #\. input)) (trees := (parse-1*digit input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dot-*1digit-linear :rule-classes :linear))) (define parse-dot-1*hexdig ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(\".\" 1*HEXDIG)')." (seq input (tree := (parse-ichar #\. input)) (trees := (parse-1*hexdig input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dot-*1hexdig-linear :rule-classes :linear))) (define parse-dash-1*bit ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(\"-\" 1*BIT)')." (seq input (tree := (parse-ichar #\- input)) (trees := (parse-1*bit input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dash-*1bit-linear :rule-classes :linear))) (define parse-dash-1*digit ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(\"-\" 1*DIGIT)')." (seq input (tree := (parse-ichar #\- input)) (trees := (parse-1*digit input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dash-*1digit-linear :rule-classes :linear))) (define parse-dash-1*hexdig ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(\"-\" 1*HEXDIG)')." (seq input (tree := (parse-ichar #\- input)) (trees := (parse-1*hexdig input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dash-*1hexdig-linear :rule-classes :linear))) (define parse-*-dot-1*bit ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*(\".\" 1*BIT)')." (seq-backtrack input ((tree := (parse-dot-1*bit input)) (trees := (parse-*-dot-1*bit input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*-dot-*1bit-linear :rule-classes :linear))) (define parse-*-dot-1*digit ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*(\".\" 1*DIGIT)')." (seq-backtrack input ((tree := (parse-dot-1*digit input)) (trees := (parse-*-dot-1*digit input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*-dot-*1digit-linear :rule-classes :linear))) (define parse-*-dot-1*hexdig ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*(\".\" 1*HEXDIG)')." (seq-backtrack input ((tree := (parse-dot-1*hexdig input)) (trees := (parse-*-dot-1*hexdig input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*-dot-*1hexdig-linear :rule-classes :linear))) (define parse-1*-dot-1*bit ((input nat-listp)) :returns (mv (error? maybe-msgp) (trees (and (tree-listp trees) (implies error? (not trees)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('1*(\".\" 1*BIT)')." (seq input (tree := (parse-dot-1*bit input)) (trees := (parse-*-dot-1*bit input)) (return (cons tree trees))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-1*-dot-1*bit-linear :rule-classes :linear))) (define parse-1*-dot-1*digit ((input nat-listp)) :returns (mv (error? maybe-msgp) (trees (and (tree-listp trees) (implies error? (not trees)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('1*(\".\" 1*DIGIT)')." (seq input (tree := (parse-dot-1*digit input)) (trees := (parse-*-dot-1*digit input)) (return (cons tree trees))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-1*-dot-1*digit-linear :rule-classes :linear))) (define parse-1*-dot-1*hexdig ((input nat-listp)) :returns (mv (error? maybe-msgp) (trees (and (tree-listp trees) (implies error? (not trees)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('1*(\".\" 1*HEXDIG)')." (seq input (tree := (parse-dot-1*hexdig input)) (trees := (parse-*-dot-1*hexdig input)) (return (cons tree trees))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-1*-dot-1*hexdig-linear :rule-classes :linear))) (define parse-bin-val-rest ((input nat-listp)) :returns (mv (error? not) (tree treep) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an option @('[ 1*(\".\" 1*BIT) / (\"-\" 1*BIT) ]'), which is the rest of the definiens of @('bin-val')." (seq-backtrack input ((trees := (parse-1*-dot-1*bit input)) (return (make-tree-nonleaf :rulename? nil :branches (list trees)))) ((tree := (parse-dash-1*bit input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((return-raw (mv nil (make-tree-nonleaf :rulename? nil :branches nil) (nat-list-fix input))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-bin-val-rest-linear :rule-classes :linear))) (define parse-dec-val-rest ((input nat-listp)) :returns (mv (error? not) (tree treep) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an option @('[ 1*(\".\" 1*DIGIT) / (\"-\" 1*DIGIT) ]'), which is the rest of the definiens of @('dec-val')." (seq-backtrack input ((trees := (parse-1*-dot-1*digit input)) (return (make-tree-nonleaf :rulename? nil :branches (list trees)))) ((tree := (parse-dash-1*digit input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((return-raw (mv nil (make-tree-nonleaf :rulename? nil :branches nil) (nat-list-fix input))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-dec-val-rest-linear :rule-classes :linear))) (define parse-hex-val-rest ((input nat-listp)) :returns (mv (error? not) (tree treep) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an option @('[ 1*(\".\" 1*HEXDIG) / (\"-\" 1*HEXDIG) ]'), which is the rest of the definiens of @('hex-val')." (seq-backtrack input ((trees := (parse-1*-dot-1*hexdig input)) (return (make-tree-nonleaf :rulename? nil :branches (list trees)))) ((tree := (parse-dash-1*hexdig input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((return-raw (mv nil (make-tree-nonleaf :rulename? nil :branches nil) (nat-list-fix input))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-hex-val-rest-linear :rule-classes :linear))) (define parse-bin-val ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a binary numeric value notation." (seq input (tree := (parse-ichar #\b input)) (trees := (parse-1*bit input)) (tree-rest := (parse-bin-val-rest input)) (return (make-tree-nonleaf :rulename? *bin-val* :branches (list (list tree) trees (list tree-rest))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name parse-bin-val-linear :rule-classes :linear))) (define parse-dec-val ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a decimal numeric value notation." (seq input (tree := (parse-ichar #\d input)) (trees := (parse-1*digit input)) (tree-rest := (parse-dec-val-rest input)) (return (make-tree-nonleaf :rulename? *dec-val* :branches (list (list tree) trees (list tree-rest))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dec-val-linear :rule-classes :linear))) (define parse-hex-val ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a hexadecimal numeric value notation." (seq input (tree := (parse-ichar #\x input)) (trees := (parse-1*hexdig input)) (tree-rest := (parse-hex-val-rest input)) (return (make-tree-nonleaf :rulename? *hex-val* :branches (list (list tree) trees (list tree-rest))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-hex-val-linear :rule-classes :linear))) (define parse-bin/dec/hex-val ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(bin-val / dec-val / hex-val)')." (seq-backtrack input ((tree := (parse-bin-val input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-dec-val input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-hex-val input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-bin/dec/hex-val-linear :rule-classes :linear))) (define parse-num-val ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a numeric value notation." (seq input (tree-% := (parse-ichar #\% input)) (tree-val := (parse-bin/dec/hex-val input)) (return (make-tree-nonleaf :rulename? *num-val* :branches (list (list tree-%) (list tree-val))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-num-val-linear :rule-classes :linear))) (define parse-quoted-string ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a quoted string." (seq input (tree-open-quote := (parse-dquote input)) (trees := (parse-*-in-either-range #x20 #x21 #x23 #x7e input)) (tree-close-quote := (parse-dquote input)) (return (make-tree-nonleaf :rulename? *quoted-string* :branches (list (list tree-open-quote) trees (list tree-close-quote))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-quoted-string-linear :rule-classes :linear))) (define parse-?%i ((input nat-listp)) :returns (mv (error? not) (tree treep) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an option @('[ \"%i\" ]')." (seq-backtrack input ((tree := (parse-ichar2 #\% #\i input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((return-raw (mv nil (make-tree-nonleaf :rulename? nil :branches nil) (nat-list-fix input))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-?%i-rest-linear :rule-classes :linear))) (define parse-case-insensitive-string ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a case-insensitive character value notation." (seq input (tree-%i := (parse-?%i input)) (tree-qstring := (parse-quoted-string input)) (return (make-tree-nonleaf :rulename? *case-insensitive-string* :branches (list (list tree-%i) (list tree-qstring))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-case-insensitive-string-linear :rule-classes :linear))) (define parse-case-sensitive-string ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a case-sensitive character value notation." (seq input (tree-%s := (parse-ichar2 #\% #\s input)) (tree-qstring := (parse-quoted-string input)) (return (make-tree-nonleaf :rulename? *case-sensitive-string* :branches (list (list tree-%s) (list tree-qstring))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-case-sensitive-string-linear :rule-classes :linear))) (define parse-char-val ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a character value notation." (seq-backtrack input ((tree := (parse-case-insensitive-string input)) (return (make-tree-nonleaf :rulename? *char-val* :branches (list (list tree))))) ((tree := (parse-case-sensitive-string input)) (return (make-tree-nonleaf :rulename? *char-val* :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-char-val-linear :rule-classes :linear))) (define parse-wsp/vchar ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(WSP / VCHAR)')." (seq-backtrack input ((tree := (parse-wsp input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-vchar input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-wsp/vchar-linear :rule-classes :linear))) (define parse-*wsp/vchar ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*(WSP / VCHAR)')." (seq-backtrack input ((tree := (parse-wsp/vchar input)) (trees := (parse-*wsp/vchar input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*wsp/vchar-linear :rule-classes :linear))) (define parse-comment ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a comment." (seq input (tree-semicolon := (parse-ichar #\; input)) (trees-text := (parse-*wsp/vchar input)) (tree-crlf := (parse-crlf input)) (return (make-tree-nonleaf :rulename? *comment* :branches (list (list tree-semicolon) trees-text (list tree-crlf))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-comment-linear :rule-classes :linear))) (define parse-cnl ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a comment or new line." (seq-backtrack input ((tree := (parse-comment input)) (return (make-tree-nonleaf :rulename? *c-nl* :branches (list (list tree))))) ((tree := (parse-crlf input)) (return (make-tree-nonleaf :rulename? *c-nl* :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-cnl-linear :rule-classes :linear))) (define parse-cnl-wsp ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(c-nl WSP)')." (seq input (tree-cnl := (parse-cnl input)) (tree-wsp := (parse-wsp input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree-cnl) (list tree-wsp))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-cnl-wsp-linear :rule-classes :linear))) (define parse-cwsp ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse either white space, or a comment and new line followed by white space." (seq-backtrack input ((tree := (parse-wsp input)) (return (make-tree-nonleaf :rulename? *c-wsp* :branches (list (list tree))))) ((tree := (parse-cnl-wsp input)) (return (make-tree-nonleaf :rulename? *c-wsp* :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-cwsp-linear :rule-classes :linear))) (define parse-*cwsp ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of zero or more @('c-wsp')s." (seq-backtrack input ((tree := (parse-cwsp input)) (trees := (parse-*cwsp input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*cwsp-linear :rule-classes :linear))) (define parse-1*cwsp ((input nat-listp)) :returns (mv (error? maybe-msgp) (trees (and (tree-listp trees) (implies error? (not trees)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of one or more @('c-wsp')s." (seq input (tree := (parse-cwsp input)) (trees := (parse-*cwsp input)) (return (cons tree trees))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-1*cwsp-linear :rule-classes :linear))) (define parse-*digit-star-*digit ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(*DIGIT \"*\" *DIGIT)')." (seq input (trees1 := (parse-*digit input)) (tree := (parse-ichar #\* input)) (trees2 := (parse-*digit input)) (return (make-tree-nonleaf :rulename? nil :branches (list trees1 (list tree) trees2)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-*digit-star-*digit-linear :rule-classes :linear))) (define parse-repeat ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition range." :long (xdoc::topstring-p "Since a non-empty sequence of digits matches both @('1*DIGIT') and the start of @('(*DIGIT \"*\" *DIGIT)'), the latter is tried before the former.") (seq-backtrack input ((tree := (parse-*digit-star-*digit input)) (return (make-tree-nonleaf :rulename? *repeat* :branches (list (list tree))))) ((trees := (parse-1*digit input)) (return (make-tree-nonleaf :rulename? *repeat* :branches (list trees))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-repeat-linear :rule-classes :linear))) (define parse-?repeat ((input nat-listp)) :returns (mv (error? not) (tree treep) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an optional repetition range." (seq-backtrack input ((tree := (parse-repeat input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((return-raw (mv nil (make-tree-nonleaf :rulename? nil :branches nil) (nat-list-fix input))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-?repeat-linear :rule-classes :linear))) (define parse-alpha/digit/dash ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(ALPHA / DIGIT / \"-\")')." (seq-backtrack input ((tree := (parse-alpha input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-digit input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-ichar #\- input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-alpha/digit/dash-linear :rule-classes :linear))) (define parse-*-alpha/digit/dash ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*(ALPHA / DIGIT / \"-\")')." (seq-backtrack input ((tree := (parse-alpha/digit/dash input)) (trees := (parse-*-alpha/digit/dash input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*-alpha/digit/dash-linear :rule-classes :linear))) (define parse-rulename ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a rule name." (seq input (tree := (parse-alpha input)) (trees := (parse-*-alpha/digit/dash input)) (return (make-tree-nonleaf :rulename? *rulename* :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-rulename-linear :rule-classes :linear))) (defines parse-alt/conc/rep/elem/group/option :verify-guards nil ; done below :flag-local nil (define parse-alternation ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an alternation." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-alternation") (xdoc::@def "len-of-parse-alternation-linear-1") (xdoc::@def "len-of-parse-alternation-linear-2")) (seq input (tree :s= (parse-concatenation input)) (trees := (parse-alt-rest input)) (return (make-tree-nonleaf :rulename? *alternation* :branches (list (list tree) trees)))) :measure (two-nats-measure (len input) 9) :no-function t) (define parse-concatenation ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a concatenation." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-concatenation") (xdoc::@def "len-of-parse-concatenation-linear-1") (xdoc::@def "len-of-parse-concatenation-linear-2")) (seq input (tree :s= (parse-repetition input)) (trees := (parse-conc-rest input)) (return (make-tree-nonleaf :rulename? *concatenation* :branches (list (list tree) trees)))) :measure (two-nats-measure (len input) 8) :no-function t) (define parse-repetition ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-repetition") (xdoc::@def "len-of-parse-repetition-linear-1") (xdoc::@def "len-of-parse-repetition-linear-2")) (seq input (tree-repeat := (parse-?repeat input)) (tree-element := (parse-element input)) (return (make-tree-nonleaf :rulename? *repetition* :branches (list (list tree-repeat) (list tree-element))))) :measure (two-nats-measure (len input) 7) :no-function t) (define parse-element ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an element." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-element") (xdoc::@def "len-of-parse-element-linear-1") (xdoc::@def "len-of-parse-element-linear-2")) (seq-backtrack input ((tree := (parse-rulename input)) (return (make-tree-nonleaf :rulename? *element* :branches (list (list tree))))) ((tree := (parse-group input)) (return (make-tree-nonleaf :rulename? *element* :branches (list (list tree))))) ((tree := (parse-option input)) (return (make-tree-nonleaf :rulename? *element* :branches (list (list tree))))) ((tree := (parse-char-val input)) (return (make-tree-nonleaf :rulename? *element* :branches (list (list tree))))) ((tree := (parse-num-val input)) (return (make-tree-nonleaf :rulename? *element* :branches (list (list tree))))) ((tree := (parse-prose-val input)) (return (make-tree-nonleaf :rulename? *element* :branches (list (list tree)))))) :measure (two-nats-measure (len input) 6) :no-function t) (define parse-group ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-group") (xdoc::@def "len-of-parse-group-linear-1") (xdoc::@def "len-of-parse-group-linear-2")) (seq input (tree-open-round := (parse-ichar #\( input)) (trees-open-pad := (parse-*cwsp input)) (tree-alt := (parse-alternation input)) (trees-close-pad := (parse-*cwsp input)) (tree-close-round := (parse-ichar #\) input)) (return (make-tree-nonleaf :rulename? *group* :branches (list (list tree-open-round) trees-open-pad (list tree-alt) trees-close-pad (list tree-close-round))))) :measure (two-nats-measure (len input) 5) :no-function t) (define parse-option ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an option." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-option") (xdoc::@def "len-of-parse-option-linear-1") (xdoc::@def "len-of-parse-option-linear-2")) (seq input (tree-open-square := (parse-ichar #\[ input)) (trees-open-pad := (parse-*cwsp input)) (tree-alt := (parse-alternation input)) (trees-close-pad := (parse-*cwsp input)) (tree-close-square := (parse-ichar #\] input)) (return (make-tree-nonleaf :rulename? *option* :branches (list (list tree-open-square) trees-open-pad (list tree-alt) trees-close-pad (list tree-close-square))))) :measure (two-nats-measure (len input) 4) :no-function t) (define parse-alt-rest ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*(*c-wsp \"/\" *c-wsp concatenation)'), which is the rest of the definiens of @('alternation')." :long (xdoc::topstring (xdoc::p "The linear rule below is used in the guard verification proof.") (xdoc::@def "parse-alt-rest") (xdoc::@def "len-of-parse-alt-rest-linear-1")) (seq-backtrack input ((tree :s= (parse-alt-rest-comp input)) (trees := (parse-alt-rest input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (two-nats-measure (len input) 3) :no-function t) (define parse-alt-rest-comp ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(*c-wsp \"/\" *c-wsp concatenation)'), which is a component of the rest of the definiens of @('alternation')." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-alt-rest-comp") (xdoc::@def "len-of-parse-alt-rest-comp-linear-1") (xdoc::@def "len-of-parse-alt-rest-comp-linear-2")) (seq input (trees1 := (parse-*cwsp input)) (tree-slash := (parse-ichar #\/ input)) (trees2 := (parse-*cwsp input)) (tree-conc := (parse-concatenation input)) (return (make-tree-nonleaf :rulename? nil :branches (list trees1 (list tree-slash) trees2 (list tree-conc))))) :measure (two-nats-measure (len input) 2) :no-function t) (define parse-conc-rest ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*(1*c-wsp repetition)'), which is the rest of the definiens of @('concatenation')." :long (xdoc::topstring (xdoc::p "The linear rule below is used in the guard verification proof.") (xdoc::@def "parse-conc-rest") (xdoc::@def "len-of-parse-conc-rest-linear-1")) (seq-backtrack input ((tree :s= (parse-conc-rest-comp input)) (trees := (parse-conc-rest input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (two-nats-measure (len input) 1) :no-function t) (define parse-conc-rest-comp ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(1*c-wsp repetition)'), which is a component of the rest of the definiens of @('concatenation')." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-conc-rest-comp") (xdoc::@def "len-of-parse-conc-rest-comp-linear-1") (xdoc::@def "len-of-parse-conc-rest-comp-linear-2")) (seq input (trees := (parse-1*cwsp input)) (tree := (parse-repetition input)) (return (make-tree-nonleaf :rulename? nil :branches (list trees (list tree))))) :measure (two-nats-measure (len input) 0) :no-function t) :ruler-extenders :all /// (defthm-parse-alt/conc/rep/elem/group/option-flag (defthm len-of-parse-alternation-linear-1 (<= (len (mv-nth 2 (parse-alternation input))) (len input)) :rule-classes :linear :flag parse-alternation) (defthm len-of-parse-concatenation-linear-1 (<= (len (mv-nth 2 (parse-concatenation input))) (len input)) :rule-classes :linear :flag parse-concatenation) (defthm len-of-parse-repetition-linear-1 (<= (len (mv-nth 2 (parse-repetition input))) (len input)) :rule-classes :linear :flag parse-repetition) (defthm len-of-parse-element-linear-1 (<= (len (mv-nth 2 (parse-element input))) (len input)) :rule-classes :linear :flag parse-element) (defthm len-of-parse-group-linear-1 (<= (len (mv-nth 2 (parse-group input))) (len input)) :rule-classes :linear :flag parse-group) (defthm len-of-parse-option-linear-1 (<= (len (mv-nth 2 (parse-option input))) (len input)) :rule-classes :linear :flag parse-option) (defthm len-of-parse-alt-rest-linear-1 (<= (len (mv-nth 2 (parse-alt-rest input))) (len input)) :rule-classes :linear :flag parse-alt-rest) (defthm len-of-parse-alt-rest-comp-linear-1 (<= (len (mv-nth 2 (parse-alt-rest-comp input))) (len input)) :rule-classes :linear :flag parse-alt-rest-comp) (defthm len-of-parse-conc-rest-linear-1 (<= (len (mv-nth 2 (parse-conc-rest input))) (len input)) :rule-classes :linear :flag parse-conc-rest) (defthm len-of-parse-conc-rest-comp-linear-1 (<= (len (mv-nth 2 (parse-conc-rest-comp input))) (len input)) :rule-classes :linear :flag parse-conc-rest-comp)) (defrule len-of-parse-conc-rest-comp-linear-2 (implies (not (mv-nth 0 (parse-conc-rest-comp input))) (< (len (mv-nth 2 (parse-conc-rest-comp input))) (len input))) :rule-classes :linear :expand ((parse-conc-rest-comp input))) (defrule len-of-parse-alt-rest-comp-linear-2 (implies (not (mv-nth 0 (parse-alt-rest-comp input))) (< (len (mv-nth 2 (parse-alt-rest-comp input))) (len input))) :rule-classes :linear :expand ((parse-alt-rest-comp input))) (defrule len-of-parse-option-linear-2 (implies (not (mv-nth 0 (parse-option input))) (< (len (mv-nth 2 (parse-option input))) (len input))) :rule-classes :linear :expand ((parse-option input))) (defrule len-of-parse-group-linear-2 (implies (not (mv-nth 0 (parse-group input))) (< (len (mv-nth 2 (parse-group input))) (len input))) :rule-classes :linear :expand ((parse-group input))) (defrule len-of-parse-element-linear-2 (implies (not (mv-nth 0 (parse-element input))) (< (len (mv-nth 2 (parse-element input))) (len input))) :rule-classes :linear :expand ((parse-element input))) (defrule len-of-parse-repetition-linear-2 (implies (not (mv-nth 0 (parse-repetition input))) (< (len (mv-nth 2 (parse-repetition input))) (len input))) :rule-classes :linear :expand ((parse-repetition input))) (defrule len-of-parse-concatenation-linear-2 (implies (not (mv-nth 0 (parse-concatenation input))) (< (len (mv-nth 2 (parse-concatenation input))) (len input))) :rule-classes :linear :expand ((parse-concatenation input))) (defrule len-of-parse-alternation-linear-2 (implies (not (mv-nth 0 (parse-alternation input))) (< (len (mv-nth 2 (parse-alternation input))) (len input))) :rule-classes :linear :expand ((parse-alternation input))) (verify-guards parse-alternation) (fty::deffixequiv-mutual parse-alt/conc/rep/elem/group/option :args (input))) (define parse-elements ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse the definiens of a rule." (seq input (tree := (parse-alternation input)) (trees := (parse-*cwsp input)) (return (make-tree-nonleaf :rulename? *elements* :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-elements-linear :rule-classes :linear))) (define parse-equal-/-equal-slash ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse the group @('(\"=\" / \"=/\")')." :long (xdoc::topstring-p "Since @('\"=\"') is a prefix of @('\"=/\"'), the latter is tried before the former.") (seq-backtrack input ((tree := (parse-ichar2 #\= #\/ input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-ichar #\= input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-equal-/-equal-slash-linear :rule-classes :linear))) (define parse-defined-as ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse the text between a rule name and its definiens." (seq input (trees1 := (parse-*cwsp input)) (tree := (parse-equal-/-equal-slash input)) (trees2 := (parse-*cwsp input)) (return (make-tree-nonleaf :rulename? *defined-as* :branches (list trees1 (list tree) trees2)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-defined-as-linear :rule-classes :linear))) (define parse-rule ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a rule." (seq input (tree1 := (parse-rulename input)) (tree2 := (parse-defined-as input)) (tree3 := (parse-elements input)) (tree4 := (parse-cnl input)) (return (make-tree-nonleaf :rulename? *rule* :branches (list (list tree1) (list tree2) (list tree3) (list tree4))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-rule-linear :rule-classes :linear))) (define parse-*cwsp-cnl ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(*c-wsp c-nl)')." (seq input (trees := (parse-*cwsp input)) (tree := (parse-cnl input)) (return (make-tree-nonleaf :rulename? nil :branches (list trees (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-*cwsp-cnl-linear :rule-classes :linear))) (define parse-rule-/-*cwsp-cnl ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('( rule / (*c-wsp c-nl) )')." (seq-backtrack input ((tree := (parse-rule input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-*cwsp-cnl input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-rule-/-*cwsp-cnl-linear :rule-classes :linear))) (define parse-*-rule-/-*cwsp-cnl ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*( rule / (*c-wsp c-nl) )')." (seq-backtrack input ((tree := (parse-rule-/-*cwsp-cnl input)) (trees := (parse-*-rule-/-*cwsp-cnl input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*-rule-/-*cwsp-cnl-linear :rule-classes :linear))) (define parse-rulelist ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a rule list." (seq input (tree := (parse-rule-/-*cwsp-cnl input)) (trees := (parse-*-rule-/-*cwsp-cnl input)) (return (make-tree-nonleaf :rulename? *rulelist* :branches (list (cons tree trees))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-rulelist-linear :rule-classes :linear))) (define parse-grammar ((nats nat-listp)) :returns (tree? tree-optionp) :parents (grammar-parser-implementation) :short "Parse a sequence of natural numbers into an ABNF grammar." :long (xdoc::topstring-p "This function parses the natural numbers into a list of rules, returning the corresponding parse tree, or @('nil') if parsing fails. This function also checks that there are no leftover natural numbers when parsing ends, returning @('nil') if this check fails.") (b* (((mv error? tree? rest) (parse-rulelist nats)) ((when error?) nil) ((when rest) nil)) tree?) :no-function t :hooks (:fix)) (define parse-grammar-from-file ((filename acl2::stringp) state) :returns (mv (tree? tree-optionp) state) :parents (grammar-parser-implementation) :short "Parse a file into an ABNF grammar." :long (xdoc::topstring (xdoc::p "The ABNF language consists of sequences of ASCII codes, as shown by theorem " (xdoc::seetopic "*grammar*" "@('ascii-only-*grammar*')") ". ASCII codes are octets (i.e. 8-bit bytes). Thus, instead of parsing sequences of natural numbers, we can parse sequences of characters (which are isomorphic to octets), by converting the characters to the corresponding octets. The characters can be read from a file.") (xdoc::p "This function parses the characters from a file into a grammar. If parsing fails, @('nil') is returned. If reading the characters from the file fails, @('nil') is returned.") (xdoc::p "Thus, a language definition in ABNF can be put into a file (e.g. copied and pasted from an RFC) and parsed with this function. Note that in ABNF lines are terminated by a carriage return and line feed, so the file must follow that convention. On Unix systems (e.g. Linux and macOS), this can be accomplished by writing the file in Emacs, setting the buffer's end-of-line to carriage return and line feed by calling @('set-buffer-file-coding-system') with @('dos'), and saving the file. If the file is put under a version control system, it should be forced to be treated as a text file with CRLF end-of-line (e.g. see the @('.gitattributes') file in this directory) to avoid turning carriage returns and line feeds into just line feeds across Windows and Unix platforms.") (xdoc::p "If parsing succeeds, it returns a correct parse tree for the contents of the file as a list of ABNF rules, according to the concrete syntax rules.")) (b* (((mv chars state) (read-file-characters filename state)) ((unless (character-listp chars)) (mv (hard-error 'abnf "ABNF Grammar File Reading Error." nil) state)) (nats (chars=>nats chars)) (tree? (parse-grammar nats)) ((unless tree?) (mv (hard-error 'abnf "ABNF Grammar File Parsing Error." nil) state))) (mv tree? state)) :no-function t)
null
https://raw.githubusercontent.com/acl2/acl2/221a194719d8e25fee2f9cc5ed8aabf872860254/books/kestrel/abnf/grammar-parser/executable.lisp
lisp
and input)) done below
ABNF ( Augmented Backus - Naur Form ) Library Copyright ( C ) 2023 Kestrel Institute ( ) License : A 3 - clause BSD license . See the LICENSE file distributed with ACL2 . Author : ( ) (in-package "ABNF") (include-book "../notation/concrete-syntax") (include-book "../parsing-tools/primitives-seq") (include-book "kestrel/utilities/strings/chars-codes" :dir :system) (include-book "std/io/read-file-characters" :dir :system) (local (include-book "kestrel/utilities/typed-lists/nat-list-fix-theorems" :dir :system)) (defxdoc+ grammar-parser-implementation :parents (grammar-parser) :short "Implementation of the parser of ABNF grammars." :long (xdoc::topstring (xdoc::p "This is a recursive-descent, backtracking parser. There is a parsing function for every rule, and parsing functions for certain groups, options, and repetitions. There are also parameterized parsing functions for terminals (natural numbers) matching exact values, ranges, and (case-insensitively) characters.") (xdoc::h3 "Parsing Primitive") (xdoc::p "Some of the parsing functions that make up the parser are " (xdoc::seetopic "parsing-primitives-seq" "<i>Seq</i> parsing primitives") ". The remarks below apply to those functions as well.") (xdoc::h3 "Inputs and Outputs") (xdoc::p "Each of these parsing functions takes as input a list of natural numbers (i.e. terminals), and returns as outputs (i) an indication of success or failure, (ii) the tree or list of trees obtained from parsing a prefix of the input (or @('nil') if parsing fails), and (iii) the remaining suffix of the input that must still be parsed. The indication of success or failure is either @('nil') to indicate success, or a " (xdoc::seetopic "msg" "message") " to describe the failure. This is consistent with the <i>@(see Seq)</i> macros, with which these parsing functions are implemented.") (xdoc::p "The @(tsee parse-grammar) top-level function takes as input a list of natural numbers this function consumes all the input, failing if there is unparsed input. The @(tsee parse-grammar-from-file) function takes as input a file name and calls @(tsee parse-grammar) on its content, returning a tree or @('nil').") (xdoc::p "Each parsing function definition is accompanied by a theorem stating that the function fixes its input list of natural numbers. The proof of each such theorem uses, as rewrite rules, the theorems for the parsing functions called by the parsing function whose theorem is being proved.") (xdoc::h3 "Disambiguation and Look-Ahead") (xdoc::p "As explained in the documentation of @(tsee parse-grammar*), the grammar of the ABNF concrete syntax [RFC:4] is ambiguous. The rule @('rulelist') allows strings `@('c-nl WSP')' either to be split into an ending @('c-nl') under a @('rule') and a starting @('WSP') under an immediately following @('(*c-wsp c-nl)'), or to be made into a @('c-wsp') in the ending part of @('elements') under the @('rule'). The same kind of choice applies when, instead of a @('rule') immediately followed by a @('(*c-wsp c-nl)'), there are two subsequent @('(*c-wsp c-nl)')s: the string `@('c-nl WSP')' can be either split between the two @('(*c-wsp c-nl)')s or put all under the first one. Indeed, expanding @('elements') in the definiens of @('rule') gives @('... *c-wsp c-nl'), which ends in the same way as the group @('(*c-wsp c-nl)'): this is why the ambiguity applies equally to a @('rule') immediately followed by a @('(*c-wsp c-nl)') and to a @('(*c-wsp c-nl)') immediately followed by a @('(*c-wsp c-nl)').") (xdoc::p "Aside from the @('rulelist') rule, the rest of the grammar is LL(*):") (xdoc::ul (xdoc::li "In the @('repeat') rule, a look-ahead of an unbounded number of @('DIGIT')s is needed to determine the alternative (the second alternative if @('\"*\"') is found after the @('DIGIT')s, otherwise the first alternative).") (xdoc::li "In the @('concatenation') rule, a look-ahead of an unbounded number of @('c-wsp')s is needed to determine where a @('concatenation') ends (it does if no @('repetition') is found after the @('c-wsp')s, otherwise the @('concatenation') continues with the found @('repetition')).")) (xdoc::p "Aside from the @('rulelist'), @('repeat'), and @('concatenation') rules, the rest of the grammar is LL(2):") (xdoc::ul (xdoc::li "In the @('defined-as') rule, a look-ahead of two symbols is needed to distinguish @('\"=\"') and @('\"=/\"').") (xdoc::li "In the @('element') rule, a look-ahead of two symbols is needed to distinguish @('num-val') and @('char-val') (the two symbols are @('\"%\"') and the one after).") (xdoc::li "In the @('char-val') rule, a look-ahead of two symbols is needed to distinguish @('case-insensitive-string') and @('case-sensitive-string') (the two symbols are @('\"%\"') and the one after).")) (xdoc::p "In each of the three rules listed above, the two choices have the first character in common. Thus, it may seem that these rules are actually LL(1), by first parsing the first character in common and then deciding how to proceed based on the next character. However, each character pair like @('\"=/\"') and @('\"%s\"') is parsed in one shot via one call to @(tsee parse-ichar2) which produces a single leaf tree with the list of those two character codes, not via two calls to @(tsee parse-ichar) which would produce two leaf trees each with a singleton list of one character code. If the rules were formulated as concatenations of single-character strings (e.g. @('\"=\" \"/\"') and @('\"%\" \"s\"')) instead, these rules would be LL(1).") (xdoc::p "Aside from the @('rulelist'), @('repeat'), @('concatenation'), @('defined-as'), @('element'), and @('char-val') rules, the rest of the grammar is LL(1).") (xdoc::p "The parser resolves the @('rulelist') ambiguity by keeping strings `@('c-nl WSP')' as @('c-wsp')s under @('rule') or under the first @('(*c-wsp c-nl)') of two subsequent @('(*c-wsp c-nl)')s, instead of splitting them into a @('c-nl') to end the @('rule') or to end the first @('(*c-wsp c-nl)') of two subsequent @('(*c-wsp c-nl)')s, and a @('WSP') to start the subsequent @('(*c-wsp c-nl)'). The decision point is when a @('c-nl') is encountered while parsing the ending @('*c-wsp') of @('elements') or while parsing the @('*c-wsp') of a @('(*c-wsp c-nl)'): should the @('*c-wsp') be considered finished and the @('c-nl') used to end the @('rule') or @('(*c-wsp c-nl)'), or should the parser attempt to extend the @('*c-wsp') with an extra @('c-wsp'), if the @('c-nl') is followed by a @('WSP')? By having @(tsee parse-*cwsp) always try the extra @('c-wsp'), we never split strings `@('c-nl WSP')'. Thus, @(tsee parse-*cwsp) tries to parse as many @('c-wsp')s as possible, like all the other @('parse-*...') parsing functions. If the @('c-nl') is not followed by a @('WSP'), the parsing of the extra @('c-wsp') fails and the only possibility left is to finish the @('*c-wsp') there is no ambiguity in this case.") (xdoc::p "The look-ahead for the LL(*), LL(2), and LL(1) rules is handled via backtracking. The amount of backtracking is expected to be small in reasonable grammars.") (xdoc::h3 "Termination") (xdoc::p "The termination of the singly recursive parsing functions (e.g. @(tsee parse-*bit)) is proved by showing that the size of the input decreases.") (xdoc::p "The termination of the mutually recursive parsing functions (i.e. @(tsee parse-alternation), @(tsee parse-concatenation), etc.) is proved via a lexicographic measure consisting of the size of the input and an ordering of the parsing functions. This is explained in the following paragraphs.") (xdoc::p "Since @(tsee parse-alternation) calls @(tsee parse-concatenation) on the same input, the size of the input alone is not sufficient to show that the mutually recursive parsing functions terminate. But @(tsee parse-concatenation) never (indirectly) calls @(tsee parse-alternation) on the same input: it has to go through @(tsee parse-group) or @(tsee parse-option), which consume a @('\"(\"') or a @('\"[\"') before calling @(tsee parse-alternation) on, therefore, a smaller input. So if we order the parsing functions, by assigning numbers to them, so that @(tsee parse-alternation) has a larger order number than @(tsee parse-concatenation), either the size of the input goes down, or it stays the same but the parsing function order number goes down. In other words, the lexicographic measure goes down.") (xdoc::p "To establish the relative ordering of the parsing functions, we look at which ones (may) call which other ones on the same input: the former must be (assigned) larger (order numbers) than the latter. Thus, we have the following ordering constraints:") (xdoc::ul (xdoc::li "@(tsee parse-alternation) must be larger than @(tsee parse-concatenation).") (xdoc::li "@(tsee parse-concatenation) must be larger than @(tsee parse-repetition).") (xdoc::li "@(tsee parse-repetition) must be larger than @(tsee parse-element). (The former calls the latter on the same input if @(tsee parse-?repeat) does not consume any input.)") (xdoc::li "@(tsee parse-element) must be larger than @(tsee parse-group).") (xdoc::li "@(tsee parse-element) must be larger than @(tsee parse-option).") (xdoc::li "@(tsee parse-alt-rest) must be larger than @(tsee parse-alt-rest-comp).") (xdoc::li "@(tsee parse-conc-rest) must be larger than @(tsee parse-conc-rest-comp).")) (xdoc::p "These constraints provide a partial order on the parsing function, which we can totalize as follows (from smallest to largest):") (xdoc::ol (xdoc::li "@(tsee parse-conc-rest-comp)") (xdoc::li "@(tsee parse-conc-rest)") (xdoc::li "@(tsee parse-alt-rest-comp)") (xdoc::li "@(tsee parse-alt-rest)") (xdoc::li "@(tsee parse-option)") (xdoc::li "@(tsee parse-group)") (xdoc::li "@(tsee parse-element)") (xdoc::li "@(tsee parse-repetition)") (xdoc::li "@(tsee parse-concatenation)") (xdoc::li "@(tsee parse-alternation)")) (xdoc::p "Note that when a smaller function calls a larger or equal function, it does so on a smaller input. In particular: @(tsee parse-group) and @(tsee parse-option) call @(tsee parse-alternation) @(tsee parse-alt-rest-comp) calls @(tsee parse-concatenation) @(tsee parse-conc-rest-comp) calls @(tsee parse-repetition) only after consuming at least one @('c-wsp'), which is never empty.") (xdoc::p "The theorems about input lengths that accompany the parsing function definitions are used in the termination proofs, both of the singly recursive functions and of the mutually recursive functions.") (xdoc::p "The termination of the mutually recursive parsing functions involves an additional complication. After @(tsee parse-alternation) calls @(tsee parse-concatenation), it may call @(tsee parse-alt-rest), which involves a proof obligation that the input to @(tsee parse-alt-rest), which is the remaining input after @(tsee parse-concatenation), has length less than or equal to the input to @(tsee parse-alternation). This is the case, because @(tsee parse-concatenation) always returns a remaining input of length less than or equal to its input. But this property can be only proved after @(tsee parse-concatenation) is admitted, that is after its (mutual) termination has been proved: for the termination proof, it is like an uninterpreted function. The same holds for the interaction between other mutually recursive parsing functions.") (xdoc::p "The known solution to the issue just discussed is to add tests saying that the remaining input of @(tsee parse-concatenation) is smaller than the initial input to @(tsee parse-alternation) (which is also the input to @(tsee parse-concatenation)). This way the termination proof can proceeed. However, since those tests are always true, they can be wrapped in @(tsee mbt), which engenders the obligation to prove that are always true, as part of guard verification (and additionally, their execution is avoided). The <i>@(see Seq)</i> macros provide operators @(':s=') and @(':w=') for this purpose (see their documentation): they generate @(tsee mbt) tests of inequalities on the lengths of inputs and remaining inputs. So we use those in our mutually recursive parsing functions.")) :order-subtopics t) (defval *grammar-parser-error-msg* :parents (grammar-parser-implementation) :short "Message for grammar parsing errors." :long (xdoc::topstring-p "This message does not carry a lot of information, but it keeps the grammar parser simpler for now.") (msg "ABNF Grammar Parser Error.~%") /// (defruled msgp-of-*grammar-parser-error-msg* (msgp *grammar-parser-error-msg*))) (define parse-in-either-range ((min1 natp) (max1 natp) (min2 natp) (max2 natp) (input nat-listp)) :guard (and (<= min1 max1) (< max1 min2) (<= min2 max2)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a natural number in one of two given ranges into a tree that matches a group consisting of an alternation of the corresponding range numeric value notations." (seq-backtrack input ((tree := (parse-in-range min1 max1 input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-in-range min2 max2 input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree)))))) :no-function t /// (fty::deffixequiv parse-in-either-range :args ((input nat-listp))) (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-in-either-range-linear :rule-classes :linear))) (define parse-*-in-either-range ((min1 natp) (max1 natp) (min2 natp) (max2 natp) (input nat-listp)) :guard (and (<= min1 max1) (< max1 min2) (<= min2 max2)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse zero or more natural numbers, each of which in one of two given ranges, into a list of trees that matches the repetition of zero or more alternations of the corresponding range numeric value notations." (seq-backtrack input ((tree := (parse-in-either-range min1 max1 min2 max2 input)) (trees := (parse-*-in-either-range min1 max1 min2 max2 input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t /// (fty::deffixequiv parse-*-in-either-range :args ((input nat-listp))) (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*-in-either-range-linear :rule-classes :linear))) (define parse-ichar ((char characterp) (input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a natural number that encodes, case-insensitively, a given character, into a tree that matches a case-insensitive character value notation that consists of that character." (b* (((mv error? nat input) (parse-any input)) ((when error?) (mv error? nil input)) ((unless (nat-match-insensitive-char-p nat char)) (mv *grammar-parser-error-msg* nil (cons nat input)))) (mv nil (tree-leafterm (list nat)) input)) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-ichar-linear :rule-classes :linear))) (define parse-ichar2 ((char1 characterp) (char2 characterp) (input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse two natural numbers that encode, case-insensitively, two given characters, into a tree that matches a case-insensitive character value notation that consists of those two characters." (b* (((mv error? nat1 input) (parse-any input)) ((when error?) (mv error? nil input)) ((unless (nat-match-insensitive-char-p nat1 char1)) (mv *grammar-parser-error-msg* nil (cons nat1 input))) ((mv error? nat2 input) (parse-any input)) ((when error?) (mv error? nil input)) ((unless (nat-match-insensitive-char-p nat2 char2)) (mv *grammar-parser-error-msg* nil (cons nat2 input)))) (mv nil (tree-leafterm (list nat1 nat2)) input)) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-ichar2-linear :rule-classes :linear))) (define parse-alpha ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a letter." (seq-backtrack input ((tree := (parse-in-range #x41 #x5a input)) (return (make-tree-nonleaf :rulename? *alpha* :branches (list (list tree))))) ((tree := (parse-in-range #x61 #x7a input)) (return (make-tree-nonleaf :rulename? *alpha* :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-alpha-linear :rule-classes :linear))) (define parse-bit ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a bit." (seq-backtrack input ((tree := (parse-ichar #\0 input)) (return (make-tree-nonleaf :rulename? *bit* :branches (list (list tree))))) ((tree := (parse-ichar #\1 input)) (return (make-tree-nonleaf :rulename? *bit* :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-bit-linear :rule-classes :linear))) (define parse-cr ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a carriage return." (seq input (tree := (parse-exact #x0d input)) (return (make-tree-nonleaf :rulename? *cr* :branches (list (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-cr-linear :rule-classes :linear))) (define parse-digit ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a decimal digit." (seq input (tree := (parse-in-range #x30 #x39 input)) (return (make-tree-nonleaf :rulename? *digit* :branches (list (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-digit-linear :rule-classes :linear))) (define parse-dquote ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a double quote." (seq input (tree := (parse-exact #x22 input)) (return (make-tree-nonleaf :rulename? *dquote* :branches (list (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dquote-linear :rule-classes :linear))) (define parse-htab ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a horizontal tab." (seq input (tree := (parse-exact #x09 input)) (return (make-tree-nonleaf :rulename? *htab* :branches (list (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-htab-linear :rule-classes :linear))) (define parse-lf ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a line feed." (seq input (tree := (parse-exact #x0a input)) (return (make-tree-nonleaf :rulename? *lf* :branches (list (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-lf-linear :rule-classes :linear))) (define parse-sp ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a space." (seq input (tree := (parse-exact #x20 input)) (return (make-tree-nonleaf :rulename? *sp* :branches (list (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-sp-linear :rule-classes :linear))) (define parse-vchar ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a visible character." (seq input (tree := (parse-in-range #x21 #x7e input)) (return (make-tree-nonleaf :rulename? *vchar* :branches (list (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-vchar-linear :rule-classes :linear))) (define parse-crlf ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a carriage return followed by a line feed." (seq input (tree-cr := (parse-cr input)) (tree-lf := (parse-lf input)) (return (make-tree-nonleaf :rulename? *crlf* :branches (list (list tree-cr) (list tree-lf))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-crlf-linear :rule-classes :linear))) (define parse-hexdig ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a hexadecimal digit." (seq-backtrack input ((tree := (parse-digit input)) (return (make-tree-nonleaf :rulename? *hexdig* :branches (list (list tree))))) ((tree := (parse-ichar #\A input)) (return (make-tree-nonleaf :rulename? *hexdig* :branches (list (list tree))))) ((tree := (parse-ichar #\B input)) (return (make-tree-nonleaf :rulename? *hexdig* :branches (list (list tree))))) ((tree := (parse-ichar #\C input)) (return (make-tree-nonleaf :rulename? *hexdig* :branches (list (list tree))))) ((tree := (parse-ichar #\D input)) (return (make-tree-nonleaf :rulename? *hexdig* :branches (list (list tree))))) ((tree := (parse-ichar #\E input)) (return (make-tree-nonleaf :rulename? *hexdig* :branches (list (list tree))))) ((tree := (parse-ichar #\F input)) (return (make-tree-nonleaf :rulename? *hexdig* :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-hexdig-linear :rule-classes :linear))) (define parse-wsp ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a space or horizontal tab." (seq-backtrack input ((tree := (parse-sp input)) (return (make-tree-nonleaf :rulename? *wsp* :branches (list (list tree))))) ((tree := (parse-htab input)) (return (make-tree-nonleaf :rulename? *wsp* :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-wsp-linear :rule-classes :linear))) (define parse-prose-val ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a prose value notation." (seq input (tree-open-angle := (parse-ichar #\< input)) (trees-text := (parse-*-in-either-range #x20 #x3d #x3f #x7e input)) (tree-close-angle := (parse-ichar #\> input)) (return (make-tree-nonleaf :rulename? *prose-val* :branches (list (list tree-open-angle) trees-text (list tree-close-angle))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-prose-val-linear :rule-classes :linear))) (define parse-*bit ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of zero or more bits." (seq-backtrack input ((tree := (parse-bit input)) (trees := (parse-*bit input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*bit-linear :rule-classes :linear))) (define parse-*digit ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of zero or more decimal digits." (seq-backtrack input ((tree := (parse-digit input)) (trees := (parse-*digit input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*digit-linear :rule-classes :linear))) (define parse-*hexdig ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of zero or more hexadecimal digits." (seq-backtrack input ((tree := (parse-hexdig input)) (trees := (parse-*hexdig input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*hexdig-linear :rule-classes :linear))) (define parse-1*bit ((input nat-listp)) :returns (mv (error? maybe-msgp) (trees (and (tree-listp trees) (implies error? (not trees)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of one or more bits." (seq input (tree := (parse-bit input)) (trees := (parse-*bit input)) (return (cons tree trees))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-1*bit-linear :rule-classes :linear))) (define parse-1*digit ((input nat-listp)) :returns (mv (error? maybe-msgp) (trees (and (tree-listp trees) (implies error? (not trees)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of one or more decimal digits." (seq input (tree := (parse-digit input)) (trees := (parse-*digit input)) (return (cons tree trees))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-1*digit-linear :rule-classes :linear))) (define parse-1*hexdig ((input nat-listp)) :returns (mv (error? maybe-msgp) (trees (and (tree-listp trees) (implies error? (not trees)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of one or more hexadecimal digits." (seq input (tree := (parse-hexdig input)) (trees := (parse-*hexdig input)) (return (cons tree trees))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-1*hexdig-linear :rule-classes :linear))) (define parse-dot-1*bit ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(\".\" 1*BIT)')." (seq input (tree := (parse-ichar #\. input)) (trees := (parse-1*bit input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dot-*1bit-linear :rule-classes :linear))) (define parse-dot-1*digit ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(\".\" 1*DIGIT)')." (seq input (tree := (parse-ichar #\. input)) (trees := (parse-1*digit input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dot-*1digit-linear :rule-classes :linear))) (define parse-dot-1*hexdig ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(\".\" 1*HEXDIG)')." (seq input (tree := (parse-ichar #\. input)) (trees := (parse-1*hexdig input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dot-*1hexdig-linear :rule-classes :linear))) (define parse-dash-1*bit ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(\"-\" 1*BIT)')." (seq input (tree := (parse-ichar #\- input)) (trees := (parse-1*bit input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dash-*1bit-linear :rule-classes :linear))) (define parse-dash-1*digit ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(\"-\" 1*DIGIT)')." (seq input (tree := (parse-ichar #\- input)) (trees := (parse-1*digit input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dash-*1digit-linear :rule-classes :linear))) (define parse-dash-1*hexdig ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(\"-\" 1*HEXDIG)')." (seq input (tree := (parse-ichar #\- input)) (trees := (parse-1*hexdig input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dash-*1hexdig-linear :rule-classes :linear))) (define parse-*-dot-1*bit ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*(\".\" 1*BIT)')." (seq-backtrack input ((tree := (parse-dot-1*bit input)) (trees := (parse-*-dot-1*bit input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*-dot-*1bit-linear :rule-classes :linear))) (define parse-*-dot-1*digit ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*(\".\" 1*DIGIT)')." (seq-backtrack input ((tree := (parse-dot-1*digit input)) (trees := (parse-*-dot-1*digit input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*-dot-*1digit-linear :rule-classes :linear))) (define parse-*-dot-1*hexdig ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*(\".\" 1*HEXDIG)')." (seq-backtrack input ((tree := (parse-dot-1*hexdig input)) (trees := (parse-*-dot-1*hexdig input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*-dot-*1hexdig-linear :rule-classes :linear))) (define parse-1*-dot-1*bit ((input nat-listp)) :returns (mv (error? maybe-msgp) (trees (and (tree-listp trees) (implies error? (not trees)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('1*(\".\" 1*BIT)')." (seq input (tree := (parse-dot-1*bit input)) (trees := (parse-*-dot-1*bit input)) (return (cons tree trees))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-1*-dot-1*bit-linear :rule-classes :linear))) (define parse-1*-dot-1*digit ((input nat-listp)) :returns (mv (error? maybe-msgp) (trees (and (tree-listp trees) (implies error? (not trees)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('1*(\".\" 1*DIGIT)')." (seq input (tree := (parse-dot-1*digit input)) (trees := (parse-*-dot-1*digit input)) (return (cons tree trees))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-1*-dot-1*digit-linear :rule-classes :linear))) (define parse-1*-dot-1*hexdig ((input nat-listp)) :returns (mv (error? maybe-msgp) (trees (and (tree-listp trees) (implies error? (not trees)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('1*(\".\" 1*HEXDIG)')." (seq input (tree := (parse-dot-1*hexdig input)) (trees := (parse-*-dot-1*hexdig input)) (return (cons tree trees))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-1*-dot-1*hexdig-linear :rule-classes :linear))) (define parse-bin-val-rest ((input nat-listp)) :returns (mv (error? not) (tree treep) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an option @('[ 1*(\".\" 1*BIT) / (\"-\" 1*BIT) ]'), which is the rest of the definiens of @('bin-val')." (seq-backtrack input ((trees := (parse-1*-dot-1*bit input)) (return (make-tree-nonleaf :rulename? nil :branches (list trees)))) ((tree := (parse-dash-1*bit input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((return-raw (mv nil (make-tree-nonleaf :rulename? nil :branches nil) (nat-list-fix input))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-bin-val-rest-linear :rule-classes :linear))) (define parse-dec-val-rest ((input nat-listp)) :returns (mv (error? not) (tree treep) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an option @('[ 1*(\".\" 1*DIGIT) / (\"-\" 1*DIGIT) ]'), which is the rest of the definiens of @('dec-val')." (seq-backtrack input ((trees := (parse-1*-dot-1*digit input)) (return (make-tree-nonleaf :rulename? nil :branches (list trees)))) ((tree := (parse-dash-1*digit input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((return-raw (mv nil (make-tree-nonleaf :rulename? nil :branches nil) (nat-list-fix input))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-dec-val-rest-linear :rule-classes :linear))) (define parse-hex-val-rest ((input nat-listp)) :returns (mv (error? not) (tree treep) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an option @('[ 1*(\".\" 1*HEXDIG) / (\"-\" 1*HEXDIG) ]'), which is the rest of the definiens of @('hex-val')." (seq-backtrack input ((trees := (parse-1*-dot-1*hexdig input)) (return (make-tree-nonleaf :rulename? nil :branches (list trees)))) ((tree := (parse-dash-1*hexdig input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((return-raw (mv nil (make-tree-nonleaf :rulename? nil :branches nil) (nat-list-fix input))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-hex-val-rest-linear :rule-classes :linear))) (define parse-bin-val ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a binary numeric value notation." (seq input (tree := (parse-ichar #\b input)) (trees := (parse-1*bit input)) (tree-rest := (parse-bin-val-rest input)) (return (make-tree-nonleaf :rulename? *bin-val* :branches (list (list tree) trees (list tree-rest))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name parse-bin-val-linear :rule-classes :linear))) (define parse-dec-val ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a decimal numeric value notation." (seq input (tree := (parse-ichar #\d input)) (trees := (parse-1*digit input)) (tree-rest := (parse-dec-val-rest input)) (return (make-tree-nonleaf :rulename? *dec-val* :branches (list (list tree) trees (list tree-rest))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-dec-val-linear :rule-classes :linear))) (define parse-hex-val ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a hexadecimal numeric value notation." (seq input (tree := (parse-ichar #\x input)) (trees := (parse-1*hexdig input)) (tree-rest := (parse-hex-val-rest input)) (return (make-tree-nonleaf :rulename? *hex-val* :branches (list (list tree) trees (list tree-rest))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-hex-val-linear :rule-classes :linear))) (define parse-bin/dec/hex-val ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(bin-val / dec-val / hex-val)')." (seq-backtrack input ((tree := (parse-bin-val input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-dec-val input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-hex-val input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-bin/dec/hex-val-linear :rule-classes :linear))) (define parse-num-val ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a numeric value notation." (seq input (tree-% := (parse-ichar #\% input)) (tree-val := (parse-bin/dec/hex-val input)) (return (make-tree-nonleaf :rulename? *num-val* :branches (list (list tree-%) (list tree-val))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-num-val-linear :rule-classes :linear))) (define parse-quoted-string ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a quoted string." (seq input (tree-open-quote := (parse-dquote input)) (trees := (parse-*-in-either-range #x20 #x21 #x23 #x7e input)) (tree-close-quote := (parse-dquote input)) (return (make-tree-nonleaf :rulename? *quoted-string* :branches (list (list tree-open-quote) trees (list tree-close-quote))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-quoted-string-linear :rule-classes :linear))) (define parse-?%i ((input nat-listp)) :returns (mv (error? not) (tree treep) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an option @('[ \"%i\" ]')." (seq-backtrack input ((tree := (parse-ichar2 #\% #\i input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((return-raw (mv nil (make-tree-nonleaf :rulename? nil :branches nil) (nat-list-fix input))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-?%i-rest-linear :rule-classes :linear))) (define parse-case-insensitive-string ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a case-insensitive character value notation." (seq input (tree-%i := (parse-?%i input)) (tree-qstring := (parse-quoted-string input)) (return (make-tree-nonleaf :rulename? *case-insensitive-string* :branches (list (list tree-%i) (list tree-qstring))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-case-insensitive-string-linear :rule-classes :linear))) (define parse-case-sensitive-string ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a case-sensitive character value notation." (seq input (tree-%s := (parse-ichar2 #\% #\s input)) (tree-qstring := (parse-quoted-string input)) (return (make-tree-nonleaf :rulename? *case-sensitive-string* :branches (list (list tree-%s) (list tree-qstring))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-case-sensitive-string-linear :rule-classes :linear))) (define parse-char-val ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a character value notation." (seq-backtrack input ((tree := (parse-case-insensitive-string input)) (return (make-tree-nonleaf :rulename? *char-val* :branches (list (list tree))))) ((tree := (parse-case-sensitive-string input)) (return (make-tree-nonleaf :rulename? *char-val* :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-char-val-linear :rule-classes :linear))) (define parse-wsp/vchar ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(WSP / VCHAR)')." (seq-backtrack input ((tree := (parse-wsp input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-vchar input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-wsp/vchar-linear :rule-classes :linear))) (define parse-*wsp/vchar ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*(WSP / VCHAR)')." (seq-backtrack input ((tree := (parse-wsp/vchar input)) (trees := (parse-*wsp/vchar input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*wsp/vchar-linear :rule-classes :linear))) (define parse-comment ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a comment." (seq input (trees-text := (parse-*wsp/vchar input)) (tree-crlf := (parse-crlf input)) (return (make-tree-nonleaf :rulename? *comment* :branches (list (list tree-semicolon) trees-text (list tree-crlf))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-comment-linear :rule-classes :linear))) (define parse-cnl ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a comment or new line." (seq-backtrack input ((tree := (parse-comment input)) (return (make-tree-nonleaf :rulename? *c-nl* :branches (list (list tree))))) ((tree := (parse-crlf input)) (return (make-tree-nonleaf :rulename? *c-nl* :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-cnl-linear :rule-classes :linear))) (define parse-cnl-wsp ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(c-nl WSP)')." (seq input (tree-cnl := (parse-cnl input)) (tree-wsp := (parse-wsp input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree-cnl) (list tree-wsp))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-cnl-wsp-linear :rule-classes :linear))) (define parse-cwsp ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse either white space, or a comment and new line followed by white space." (seq-backtrack input ((tree := (parse-wsp input)) (return (make-tree-nonleaf :rulename? *c-wsp* :branches (list (list tree))))) ((tree := (parse-cnl-wsp input)) (return (make-tree-nonleaf :rulename? *c-wsp* :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-cwsp-linear :rule-classes :linear))) (define parse-*cwsp ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of zero or more @('c-wsp')s." (seq-backtrack input ((tree := (parse-cwsp input)) (trees := (parse-*cwsp input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*cwsp-linear :rule-classes :linear))) (define parse-1*cwsp ((input nat-listp)) :returns (mv (error? maybe-msgp) (trees (and (tree-listp trees) (implies error? (not trees)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition of one or more @('c-wsp')s." (seq input (tree := (parse-cwsp input)) (trees := (parse-*cwsp input)) (return (cons tree trees))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-1*cwsp-linear :rule-classes :linear))) (define parse-*digit-star-*digit ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(*DIGIT \"*\" *DIGIT)')." (seq input (trees1 := (parse-*digit input)) (tree := (parse-ichar #\* input)) (trees2 := (parse-*digit input)) (return (make-tree-nonleaf :rulename? nil :branches (list trees1 (list tree) trees2)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-*digit-star-*digit-linear :rule-classes :linear))) (define parse-repeat ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition range." :long (xdoc::topstring-p "Since a non-empty sequence of digits matches both @('1*DIGIT') and the start of @('(*DIGIT \"*\" *DIGIT)'), the latter is tried before the former.") (seq-backtrack input ((tree := (parse-*digit-star-*digit input)) (return (make-tree-nonleaf :rulename? *repeat* :branches (list (list tree))))) ((trees := (parse-1*digit input)) (return (make-tree-nonleaf :rulename? *repeat* :branches (list trees))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-repeat-linear :rule-classes :linear))) (define parse-?repeat ((input nat-listp)) :returns (mv (error? not) (tree treep) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an optional repetition range." (seq-backtrack input ((tree := (parse-repeat input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((return-raw (mv nil (make-tree-nonleaf :rulename? nil :branches nil) (nat-list-fix input))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-?repeat-linear :rule-classes :linear))) (define parse-alpha/digit/dash ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(ALPHA / DIGIT / \"-\")')." (seq-backtrack input ((tree := (parse-alpha input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-digit input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-ichar #\- input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-alpha/digit/dash-linear :rule-classes :linear))) (define parse-*-alpha/digit/dash ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*(ALPHA / DIGIT / \"-\")')." (seq-backtrack input ((tree := (parse-alpha/digit/dash input)) (trees := (parse-*-alpha/digit/dash input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*-alpha/digit/dash-linear :rule-classes :linear))) (define parse-rulename ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a rule name." (seq input (tree := (parse-alpha input)) (trees := (parse-*-alpha/digit/dash input)) (return (make-tree-nonleaf :rulename? *rulename* :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-rulename-linear :rule-classes :linear))) (defines parse-alt/conc/rep/elem/group/option :flag-local nil (define parse-alternation ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an alternation." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-alternation") (xdoc::@def "len-of-parse-alternation-linear-1") (xdoc::@def "len-of-parse-alternation-linear-2")) (seq input (tree :s= (parse-concatenation input)) (trees := (parse-alt-rest input)) (return (make-tree-nonleaf :rulename? *alternation* :branches (list (list tree) trees)))) :measure (two-nats-measure (len input) 9) :no-function t) (define parse-concatenation ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a concatenation." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-concatenation") (xdoc::@def "len-of-parse-concatenation-linear-1") (xdoc::@def "len-of-parse-concatenation-linear-2")) (seq input (tree :s= (parse-repetition input)) (trees := (parse-conc-rest input)) (return (make-tree-nonleaf :rulename? *concatenation* :branches (list (list tree) trees)))) :measure (two-nats-measure (len input) 8) :no-function t) (define parse-repetition ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-repetition") (xdoc::@def "len-of-parse-repetition-linear-1") (xdoc::@def "len-of-parse-repetition-linear-2")) (seq input (tree-repeat := (parse-?repeat input)) (tree-element := (parse-element input)) (return (make-tree-nonleaf :rulename? *repetition* :branches (list (list tree-repeat) (list tree-element))))) :measure (two-nats-measure (len input) 7) :no-function t) (define parse-element ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an element." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-element") (xdoc::@def "len-of-parse-element-linear-1") (xdoc::@def "len-of-parse-element-linear-2")) (seq-backtrack input ((tree := (parse-rulename input)) (return (make-tree-nonleaf :rulename? *element* :branches (list (list tree))))) ((tree := (parse-group input)) (return (make-tree-nonleaf :rulename? *element* :branches (list (list tree))))) ((tree := (parse-option input)) (return (make-tree-nonleaf :rulename? *element* :branches (list (list tree))))) ((tree := (parse-char-val input)) (return (make-tree-nonleaf :rulename? *element* :branches (list (list tree))))) ((tree := (parse-num-val input)) (return (make-tree-nonleaf :rulename? *element* :branches (list (list tree))))) ((tree := (parse-prose-val input)) (return (make-tree-nonleaf :rulename? *element* :branches (list (list tree)))))) :measure (two-nats-measure (len input) 6) :no-function t) (define parse-group ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-group") (xdoc::@def "len-of-parse-group-linear-1") (xdoc::@def "len-of-parse-group-linear-2")) (seq input (tree-open-round := (parse-ichar #\( input)) (trees-open-pad := (parse-*cwsp input)) (tree-alt := (parse-alternation input)) (trees-close-pad := (parse-*cwsp input)) (tree-close-round := (parse-ichar #\) input)) (return (make-tree-nonleaf :rulename? *group* :branches (list (list tree-open-round) trees-open-pad (list tree-alt) trees-close-pad (list tree-close-round))))) :measure (two-nats-measure (len input) 5) :no-function t) (define parse-option ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse an option." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-option") (xdoc::@def "len-of-parse-option-linear-1") (xdoc::@def "len-of-parse-option-linear-2")) (seq input (tree-open-square := (parse-ichar #\[ input)) (trees-open-pad := (parse-*cwsp input)) (tree-alt := (parse-alternation input)) (trees-close-pad := (parse-*cwsp input)) (tree-close-square := (parse-ichar #\] input)) (return (make-tree-nonleaf :rulename? *option* :branches (list (list tree-open-square) trees-open-pad (list tree-alt) trees-close-pad (list tree-close-square))))) :measure (two-nats-measure (len input) 4) :no-function t) (define parse-alt-rest ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*(*c-wsp \"/\" *c-wsp concatenation)'), which is the rest of the definiens of @('alternation')." :long (xdoc::topstring (xdoc::p "The linear rule below is used in the guard verification proof.") (xdoc::@def "parse-alt-rest") (xdoc::@def "len-of-parse-alt-rest-linear-1")) (seq-backtrack input ((tree :s= (parse-alt-rest-comp input)) (trees := (parse-alt-rest input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (two-nats-measure (len input) 3) :no-function t) (define parse-alt-rest-comp ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(*c-wsp \"/\" *c-wsp concatenation)'), which is a component of the rest of the definiens of @('alternation')." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-alt-rest-comp") (xdoc::@def "len-of-parse-alt-rest-comp-linear-1") (xdoc::@def "len-of-parse-alt-rest-comp-linear-2")) (seq input (trees1 := (parse-*cwsp input)) (tree-slash := (parse-ichar #\/ input)) (trees2 := (parse-*cwsp input)) (tree-conc := (parse-concatenation input)) (return (make-tree-nonleaf :rulename? nil :branches (list trees1 (list tree-slash) trees2 (list tree-conc))))) :measure (two-nats-measure (len input) 2) :no-function t) (define parse-conc-rest ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*(1*c-wsp repetition)'), which is the rest of the definiens of @('concatenation')." :long (xdoc::topstring (xdoc::p "The linear rule below is used in the guard verification proof.") (xdoc::@def "parse-conc-rest") (xdoc::@def "len-of-parse-conc-rest-linear-1")) (seq-backtrack input ((tree :s= (parse-conc-rest-comp input)) (trees := (parse-conc-rest input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (two-nats-measure (len input) 1) :no-function t) (define parse-conc-rest-comp ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(1*c-wsp repetition)'), which is a component of the rest of the definiens of @('concatenation')." :long (xdoc::topstring (xdoc::p "The linear rules below are used in the guard verification proof.") (xdoc::@def "parse-conc-rest-comp") (xdoc::@def "len-of-parse-conc-rest-comp-linear-1") (xdoc::@def "len-of-parse-conc-rest-comp-linear-2")) (seq input (trees := (parse-1*cwsp input)) (tree := (parse-repetition input)) (return (make-tree-nonleaf :rulename? nil :branches (list trees (list tree))))) :measure (two-nats-measure (len input) 0) :no-function t) :ruler-extenders :all /// (defthm-parse-alt/conc/rep/elem/group/option-flag (defthm len-of-parse-alternation-linear-1 (<= (len (mv-nth 2 (parse-alternation input))) (len input)) :rule-classes :linear :flag parse-alternation) (defthm len-of-parse-concatenation-linear-1 (<= (len (mv-nth 2 (parse-concatenation input))) (len input)) :rule-classes :linear :flag parse-concatenation) (defthm len-of-parse-repetition-linear-1 (<= (len (mv-nth 2 (parse-repetition input))) (len input)) :rule-classes :linear :flag parse-repetition) (defthm len-of-parse-element-linear-1 (<= (len (mv-nth 2 (parse-element input))) (len input)) :rule-classes :linear :flag parse-element) (defthm len-of-parse-group-linear-1 (<= (len (mv-nth 2 (parse-group input))) (len input)) :rule-classes :linear :flag parse-group) (defthm len-of-parse-option-linear-1 (<= (len (mv-nth 2 (parse-option input))) (len input)) :rule-classes :linear :flag parse-option) (defthm len-of-parse-alt-rest-linear-1 (<= (len (mv-nth 2 (parse-alt-rest input))) (len input)) :rule-classes :linear :flag parse-alt-rest) (defthm len-of-parse-alt-rest-comp-linear-1 (<= (len (mv-nth 2 (parse-alt-rest-comp input))) (len input)) :rule-classes :linear :flag parse-alt-rest-comp) (defthm len-of-parse-conc-rest-linear-1 (<= (len (mv-nth 2 (parse-conc-rest input))) (len input)) :rule-classes :linear :flag parse-conc-rest) (defthm len-of-parse-conc-rest-comp-linear-1 (<= (len (mv-nth 2 (parse-conc-rest-comp input))) (len input)) :rule-classes :linear :flag parse-conc-rest-comp)) (defrule len-of-parse-conc-rest-comp-linear-2 (implies (not (mv-nth 0 (parse-conc-rest-comp input))) (< (len (mv-nth 2 (parse-conc-rest-comp input))) (len input))) :rule-classes :linear :expand ((parse-conc-rest-comp input))) (defrule len-of-parse-alt-rest-comp-linear-2 (implies (not (mv-nth 0 (parse-alt-rest-comp input))) (< (len (mv-nth 2 (parse-alt-rest-comp input))) (len input))) :rule-classes :linear :expand ((parse-alt-rest-comp input))) (defrule len-of-parse-option-linear-2 (implies (not (mv-nth 0 (parse-option input))) (< (len (mv-nth 2 (parse-option input))) (len input))) :rule-classes :linear :expand ((parse-option input))) (defrule len-of-parse-group-linear-2 (implies (not (mv-nth 0 (parse-group input))) (< (len (mv-nth 2 (parse-group input))) (len input))) :rule-classes :linear :expand ((parse-group input))) (defrule len-of-parse-element-linear-2 (implies (not (mv-nth 0 (parse-element input))) (< (len (mv-nth 2 (parse-element input))) (len input))) :rule-classes :linear :expand ((parse-element input))) (defrule len-of-parse-repetition-linear-2 (implies (not (mv-nth 0 (parse-repetition input))) (< (len (mv-nth 2 (parse-repetition input))) (len input))) :rule-classes :linear :expand ((parse-repetition input))) (defrule len-of-parse-concatenation-linear-2 (implies (not (mv-nth 0 (parse-concatenation input))) (< (len (mv-nth 2 (parse-concatenation input))) (len input))) :rule-classes :linear :expand ((parse-concatenation input))) (defrule len-of-parse-alternation-linear-2 (implies (not (mv-nth 0 (parse-alternation input))) (< (len (mv-nth 2 (parse-alternation input))) (len input))) :rule-classes :linear :expand ((parse-alternation input))) (verify-guards parse-alternation) (fty::deffixequiv-mutual parse-alt/conc/rep/elem/group/option :args (input))) (define parse-elements ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse the definiens of a rule." (seq input (tree := (parse-alternation input)) (trees := (parse-*cwsp input)) (return (make-tree-nonleaf :rulename? *elements* :branches (list (list tree) trees)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-elements-linear :rule-classes :linear))) (define parse-equal-/-equal-slash ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse the group @('(\"=\" / \"=/\")')." :long (xdoc::topstring-p "Since @('\"=\"') is a prefix of @('\"=/\"'), the latter is tried before the former.") (seq-backtrack input ((tree := (parse-ichar2 #\= #\/ input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-ichar #\= input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-equal-/-equal-slash-linear :rule-classes :linear))) (define parse-defined-as ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse the text between a rule name and its definiens." (seq input (trees1 := (parse-*cwsp input)) (tree := (parse-equal-/-equal-slash input)) (trees2 := (parse-*cwsp input)) (return (make-tree-nonleaf :rulename? *defined-as* :branches (list trees1 (list tree) trees2)))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-defined-as-linear :rule-classes :linear))) (define parse-rule ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a rule." (seq input (tree1 := (parse-rulename input)) (tree2 := (parse-defined-as input)) (tree3 := (parse-elements input)) (tree4 := (parse-cnl input)) (return (make-tree-nonleaf :rulename? *rule* :branches (list (list tree1) (list tree2) (list tree3) (list tree4))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-rule-linear :rule-classes :linear))) (define parse-*cwsp-cnl ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('(*c-wsp c-nl)')." (seq input (trees := (parse-*cwsp input)) (tree := (parse-cnl input)) (return (make-tree-nonleaf :rulename? nil :branches (list trees (list tree))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-*cwsp-cnl-linear :rule-classes :linear))) (define parse-rule-/-*cwsp-cnl ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a group @('( rule / (*c-wsp c-nl) )')." (seq-backtrack input ((tree := (parse-rule input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree))))) ((tree := (parse-*cwsp-cnl input)) (return (make-tree-nonleaf :rulename? nil :branches (list (list tree)))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-rule-/-*cwsp-cnl-linear :rule-classes :linear))) (define parse-*-rule-/-*cwsp-cnl ((input nat-listp)) :returns (mv (error? not) (trees tree-listp) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a repetition @('*( rule / (*c-wsp c-nl) )')." (seq-backtrack input ((tree := (parse-rule-/-*cwsp-cnl input)) (trees := (parse-*-rule-/-*cwsp-cnl input)) (return (cons tree trees))) ((return-raw (mv nil nil (nat-list-fix input))))) :measure (len input) :ruler-extenders :all :no-function t :hooks (:fix) /// (more-returns (rest-input (<= (len rest-input) (len input)) :name len-of-parse-*-rule-/-*cwsp-cnl-linear :rule-classes :linear))) (define parse-rulelist ((input nat-listp)) :returns (mv (error? maybe-msgp) (tree? (and (tree-optionp tree?) (implies (not error?) (treep tree?)) (implies error? (not tree?)))) (rest-input nat-listp)) :parents (grammar-parser-implementation) :short "Parse a rule list." (seq input (tree := (parse-rule-/-*cwsp-cnl input)) (trees := (parse-*-rule-/-*cwsp-cnl input)) (return (make-tree-nonleaf :rulename? *rulelist* :branches (list (cons tree trees))))) :no-function t :hooks (:fix) /// (more-returns (rest-input (and (<= (len rest-input) (len input)) (implies (not error?) (< (len rest-input) (len input)))) :name len-of-parse-rulelist-linear :rule-classes :linear))) (define parse-grammar ((nats nat-listp)) :returns (tree? tree-optionp) :parents (grammar-parser-implementation) :short "Parse a sequence of natural numbers into an ABNF grammar." :long (xdoc::topstring-p "This function parses the natural numbers into a list of rules, returning the corresponding parse tree, or @('nil') if parsing fails. This function also checks that there are no leftover natural numbers when parsing ends, returning @('nil') if this check fails.") (b* (((mv error? tree? rest) (parse-rulelist nats)) ((when error?) nil) ((when rest) nil)) tree?) :no-function t :hooks (:fix)) (define parse-grammar-from-file ((filename acl2::stringp) state) :returns (mv (tree? tree-optionp) state) :parents (grammar-parser-implementation) :short "Parse a file into an ABNF grammar." :long (xdoc::topstring (xdoc::p "The ABNF language consists of sequences of ASCII codes, as shown by theorem " (xdoc::seetopic "*grammar*" "@('ascii-only-*grammar*')") ". ASCII codes are octets (i.e. 8-bit bytes). Thus, instead of parsing sequences of natural numbers, we can parse sequences of characters (which are isomorphic to octets), by converting the characters to the corresponding octets. The characters can be read from a file.") (xdoc::p "This function parses the characters from a file into a grammar. If parsing fails, @('nil') is returned. If reading the characters from the file fails, @('nil') is returned.") (xdoc::p "Thus, a language definition in ABNF can be put into a file (e.g. copied and pasted from an RFC) and parsed with this function. Note that in ABNF lines are terminated by a carriage return and line feed, so the file must follow that convention. On Unix systems (e.g. Linux and macOS), this can be accomplished by writing the file in Emacs, setting the buffer's end-of-line to carriage return and line feed by calling @('set-buffer-file-coding-system') with @('dos'), and saving the file. If the file is put under a version control system, it should be forced to be treated as a text file with CRLF end-of-line (e.g. see the @('.gitattributes') file in this directory) to avoid turning carriage returns and line feeds into just line feeds across Windows and Unix platforms.") (xdoc::p "If parsing succeeds, it returns a correct parse tree for the contents of the file as a list of ABNF rules, according to the concrete syntax rules.")) (b* (((mv chars state) (read-file-characters filename state)) ((unless (character-listp chars)) (mv (hard-error 'abnf "ABNF Grammar File Reading Error." nil) state)) (nats (chars=>nats chars)) (tree? (parse-grammar nats)) ((unless tree?) (mv (hard-error 'abnf "ABNF Grammar File Parsing Error." nil) state))) (mv tree? state)) :no-function t)
32dc0b3e89591e3dca5344df8f85898b378c2eb5a8a7aa8aea167590671a1b27
unclebob/AdventOfCode2022
core.clj
(ns day7-no-space-left-on-device.core (:require [clojure.string :as string])) (defn add-directory [path directory dir-name] (let [new-path (conj path dir-name)] (assoc-in directory new-path {}))) (defn add-file [path directory size name] (let [new-path (conj path name)] (assoc-in directory new-path size))) (defn exec-command [path directories command] (cond (= command "$ cd /") [["/"] directories] (= command "$ cd ..") [(drop-last path) directories] (= command "$ ls") [path directories] (re-matches #"\$ cd (.+)$" command) (let [directory (second (re-matches #"\$ cd (.+)$" command))] [(conj (vec path) directory) directories]) (re-matches #"dir (.+)$" command) [path (add-directory path directories (second (re-matches #"dir (.+)$" command)))] (re-matches #"(\d+) (.+)$" command) (let [[_ size name] (re-matches #"(\d+) (.+)$" command) size (Integer/parseInt size)] [path (add-file path directories size name)]) :else "TILT" )) (defn exec-commands [path directories commands] (if (empty? commands) directories (let [command (first commands) [path directories] (exec-command path directories command)] (recur path directories (rest commands))))) (defn exec-command-file [file-name] (let [input (slurp file-name) commands (string/split-lines input)] (exec-commands ["/"] {"/" {}} commands))) (defn dir-size [directory] (loop [names (keys directory) size 0] (if (empty? names) size (let [name (first names) file (directory name)] (if (integer? file) (recur (rest names) (+ size file)) (recur (rest names) (+ size (dir-size file)))))))) (defn map-directories [path directories] (loop [names (keys directories) sizes {}] (if (empty? names) sizes (let [name (first names) file (directories name)] (if (integer? file) (recur (rest names) sizes) (recur (rest names) (merge (assoc sizes (conj path name) (dir-size file)) (map-directories (conj path name) file)))))))) (defn total-small-directories [file-name] (let [directories (exec-command-file file-name) directory-map (map-directories [] directories) sizes (vals directory-map) small-sizes (filter #(<= % 100000) sizes)] (reduce + small-sizes))) (defn find-best-to-delete [file-name] (let [directories (exec-command-file file-name) directory-map (map-directories [] directories) sizes (sort (vals directory-map)) total-used (directory-map ["/"]) free-space (- 70000000 total-used) needed-space (- 30000000 free-space) sufficient-sizes (filter #(>= % needed-space) sizes)] (first sufficient-sizes)))
null
https://raw.githubusercontent.com/unclebob/AdventOfCode2022/f1d7bd75822606317ba60813bb7956cba0fcc36c/day7-no-space-left-on-device/src/day7_no_space_left_on_device/core.clj
clojure
(ns day7-no-space-left-on-device.core (:require [clojure.string :as string])) (defn add-directory [path directory dir-name] (let [new-path (conj path dir-name)] (assoc-in directory new-path {}))) (defn add-file [path directory size name] (let [new-path (conj path name)] (assoc-in directory new-path size))) (defn exec-command [path directories command] (cond (= command "$ cd /") [["/"] directories] (= command "$ cd ..") [(drop-last path) directories] (= command "$ ls") [path directories] (re-matches #"\$ cd (.+)$" command) (let [directory (second (re-matches #"\$ cd (.+)$" command))] [(conj (vec path) directory) directories]) (re-matches #"dir (.+)$" command) [path (add-directory path directories (second (re-matches #"dir (.+)$" command)))] (re-matches #"(\d+) (.+)$" command) (let [[_ size name] (re-matches #"(\d+) (.+)$" command) size (Integer/parseInt size)] [path (add-file path directories size name)]) :else "TILT" )) (defn exec-commands [path directories commands] (if (empty? commands) directories (let [command (first commands) [path directories] (exec-command path directories command)] (recur path directories (rest commands))))) (defn exec-command-file [file-name] (let [input (slurp file-name) commands (string/split-lines input)] (exec-commands ["/"] {"/" {}} commands))) (defn dir-size [directory] (loop [names (keys directory) size 0] (if (empty? names) size (let [name (first names) file (directory name)] (if (integer? file) (recur (rest names) (+ size file)) (recur (rest names) (+ size (dir-size file)))))))) (defn map-directories [path directories] (loop [names (keys directories) sizes {}] (if (empty? names) sizes (let [name (first names) file (directories name)] (if (integer? file) (recur (rest names) sizes) (recur (rest names) (merge (assoc sizes (conj path name) (dir-size file)) (map-directories (conj path name) file)))))))) (defn total-small-directories [file-name] (let [directories (exec-command-file file-name) directory-map (map-directories [] directories) sizes (vals directory-map) small-sizes (filter #(<= % 100000) sizes)] (reduce + small-sizes))) (defn find-best-to-delete [file-name] (let [directories (exec-command-file file-name) directory-map (map-directories [] directories) sizes (sort (vals directory-map)) total-used (directory-map ["/"]) free-space (- 70000000 total-used) needed-space (- 30000000 free-space) sufficient-sizes (filter #(>= % needed-space) sizes)] (first sufficient-sizes)))
533d3fdf1b5ee553dade3a2f256d00cc25ebdeabeadca32fdd99f4f1ba9dfe5c
urs-of-the-backwoods/fresco
HaskellSpec.hs
-- Fresco Framework for Multi - Language Programming Copyright 2015 - 2017 -- Distributed under the Apache License , Version 2.0 -- (See attached file LICENSE or copy at -- http:--www.apache.org/licenses/LICENSE-2.0) -- -- file: test/HaskellSpec.hs -- {-# LANGUAGE OverloadedStrings #-} module HaskellSpec(main, spec) where import Test.Hspec import Sinopia.Data import Sinopia.Parser import Sinopia.Haskell import Data.Either.Unwrap import Numeric (showHex) import Data.ByteString.Lazy import Data.ByteString.Builder import Fresco import Data.Binary.Serialise.CBOR import Data.Binary.Serialise.CBOR.Decoding import Data.Binary.Serialise.CBOR.Encoding as E import Data.Monoid main :: IO () main = hspec spec data Shape = Sphere | Cube | Plane | Cylinder Int | Pyramid Float Float | Torus deriving (Eq, Read, Show) instance Serialise Shape where encode (Cube) = encode (0::Int) encode (Plane) = encode (1::Int) encode (Cylinder v1) = encode (2::Int) <> encode v1 encode (Pyramid v1 v2) = encode (3::Int) <> encode v1 <> encode v2 encode (Torus) = encode (4::Int) decode = do i <- decode :: Decoder s Int case i of 0 -> (pure Cube) 1 -> (pure Plane) 2 -> (Cylinder <$> decode) 3 -> (Pyramid <$> decode <*> decode) 4 -> (pure Torus) data TrueColour = TrueColour Bool Colour data Colour = Colour { colourRed::Float, colourGreen::Float, colourBlue::Float, colourAlpha::Float } deriving (Eq, Show) instance Serialise Colour where encode (Colour v1 v2 v3 v4) = encode v1 <> encode v2 <> encode v3 <> encode v4 decode = Colour <$> decode <*> decode <*> decode <*> decode instance Serialise TrueColour where encode (TrueColour isTrue c) = encode isTrue <> encode c decode = TrueColour <$> decode <*> decode spec :: Spec spec = describe "Sinopia.Haskell" $ do it "can output a simple datatype as CBOR data" $ do let c1 = Colour 1.0 2.0 3.0 4.0 in (toLazyByteString . lazyByteStringHex) (serialise c1) `shouldBe` "fa3f800000fa40000000fa40400000fa40800000" it "can output a complex datatype as CBOR data" $ do let tc1 = TrueColour False (Colour 1.0 2.0 3.0 4.0) in (toLazyByteString . lazyByteStringHex) (serialise tc1) `shouldBe` "f4fa3f800000fa40000000fa40400000fa40800000" it "can input colour from CBOR data" $ do (deserialise (serialise (Colour 2.0 3.0 4.0 5.0))) `shouldBe` (Colour 2.0 3.0 4.0 5.0) it "can output an enum as CBOR data" $ do let s1 = Plane in (toLazyByteString . lazyByteStringHex) (serialise s1) `shouldBe` "01" it "can output a more complex enum as CBOR data" $ do let s1 = Pyramid 1.0 2.0 in (toLazyByteString . lazyByteStringHex) (serialise s1) `shouldBe` "03fa3f800000fa40000000" it "can input enum from CBOR data" $ do (deserialise (serialise (Pyramid 1.0 2.0))) `shouldBe` (Pyramid 1.0 2.0) it "can input simple enum from CBOR data" $ do (deserialise (serialise (Plane))) `shouldBe` (Plane)
null
https://raw.githubusercontent.com/urs-of-the-backwoods/fresco/9914df6d534f591448ed1501965f1bd03f3724de/sinopia/test/HaskellSpec.hs
haskell
(See attached file LICENSE or copy at http:--www.apache.org/licenses/LICENSE-2.0) file: test/HaskellSpec.hs # LANGUAGE OverloadedStrings #
Fresco Framework for Multi - Language Programming Copyright 2015 - 2017 Distributed under the Apache License , Version 2.0 module HaskellSpec(main, spec) where import Test.Hspec import Sinopia.Data import Sinopia.Parser import Sinopia.Haskell import Data.Either.Unwrap import Numeric (showHex) import Data.ByteString.Lazy import Data.ByteString.Builder import Fresco import Data.Binary.Serialise.CBOR import Data.Binary.Serialise.CBOR.Decoding import Data.Binary.Serialise.CBOR.Encoding as E import Data.Monoid main :: IO () main = hspec spec data Shape = Sphere | Cube | Plane | Cylinder Int | Pyramid Float Float | Torus deriving (Eq, Read, Show) instance Serialise Shape where encode (Cube) = encode (0::Int) encode (Plane) = encode (1::Int) encode (Cylinder v1) = encode (2::Int) <> encode v1 encode (Pyramid v1 v2) = encode (3::Int) <> encode v1 <> encode v2 encode (Torus) = encode (4::Int) decode = do i <- decode :: Decoder s Int case i of 0 -> (pure Cube) 1 -> (pure Plane) 2 -> (Cylinder <$> decode) 3 -> (Pyramid <$> decode <*> decode) 4 -> (pure Torus) data TrueColour = TrueColour Bool Colour data Colour = Colour { colourRed::Float, colourGreen::Float, colourBlue::Float, colourAlpha::Float } deriving (Eq, Show) instance Serialise Colour where encode (Colour v1 v2 v3 v4) = encode v1 <> encode v2 <> encode v3 <> encode v4 decode = Colour <$> decode <*> decode <*> decode <*> decode instance Serialise TrueColour where encode (TrueColour isTrue c) = encode isTrue <> encode c decode = TrueColour <$> decode <*> decode spec :: Spec spec = describe "Sinopia.Haskell" $ do it "can output a simple datatype as CBOR data" $ do let c1 = Colour 1.0 2.0 3.0 4.0 in (toLazyByteString . lazyByteStringHex) (serialise c1) `shouldBe` "fa3f800000fa40000000fa40400000fa40800000" it "can output a complex datatype as CBOR data" $ do let tc1 = TrueColour False (Colour 1.0 2.0 3.0 4.0) in (toLazyByteString . lazyByteStringHex) (serialise tc1) `shouldBe` "f4fa3f800000fa40000000fa40400000fa40800000" it "can input colour from CBOR data" $ do (deserialise (serialise (Colour 2.0 3.0 4.0 5.0))) `shouldBe` (Colour 2.0 3.0 4.0 5.0) it "can output an enum as CBOR data" $ do let s1 = Plane in (toLazyByteString . lazyByteStringHex) (serialise s1) `shouldBe` "01" it "can output a more complex enum as CBOR data" $ do let s1 = Pyramid 1.0 2.0 in (toLazyByteString . lazyByteStringHex) (serialise s1) `shouldBe` "03fa3f800000fa40000000" it "can input enum from CBOR data" $ do (deserialise (serialise (Pyramid 1.0 2.0))) `shouldBe` (Pyramid 1.0 2.0) it "can input simple enum from CBOR data" $ do (deserialise (serialise (Plane))) `shouldBe` (Plane)
f13f666209f2fbf541bf756844572d54e5735bb4b63808c202fcc623315f1139
racket/math
gamma-normal.rkt
#lang typed/racket/base (require "../../../flonum.rkt" "../../distributions/impl/normal-cdf.rkt") (provide flgamma-normal) Temme 's normal approximation for regularized incomplete gamma functions This is much better than moment - matching or Wilson - Hilferty (: flgamma-normal (Float Float Any Any -> Float)) (define (flgamma-normal k x log? upper?) (define l (fl/ x k)) (define norm-x (cond [(or (l . fl< . epsilon.0) (l . fl> . (fl/ 1.0 epsilon.0))) ;; Avoid under-/overflow in calculating norm-x by doing it in log space (define log-l (fl- (fllog x) (fllog k))) (define l-1 (flexpm1 log-l)) (define l-1-sign (flsgn l-1)) (define log-n (fl* 0.5 (fl+ (fllog 2.0) (fllog (fl- l-1 log-l))))) (fl* l-1-sign (flexp (fl+ log-n (fl* 0.5 (fllog k)))))] [else (define n (fl* (flsgn (fl- l 1.0)) (flsqrt (fl* 2.0 (fl- (fl- l 1.0) (fllog l)))))) (fl* n (flsqrt k))])) (let ([norm-x (if upper? (- norm-x) norm-x)]) (cond [log? (standard-flnormal-log-cdf norm-x)] [else (standard-flnormal-cdf norm-x)])))
null
https://raw.githubusercontent.com/racket/math/dcd2ea1893dc5b45b26c8312997917a15fcd1c4a/math-lib/math/private/functions/incomplete-gamma/gamma-normal.rkt
racket
Avoid under-/overflow in calculating norm-x by doing it in log space
#lang typed/racket/base (require "../../../flonum.rkt" "../../distributions/impl/normal-cdf.rkt") (provide flgamma-normal) Temme 's normal approximation for regularized incomplete gamma functions This is much better than moment - matching or Wilson - Hilferty (: flgamma-normal (Float Float Any Any -> Float)) (define (flgamma-normal k x log? upper?) (define l (fl/ x k)) (define norm-x (cond [(or (l . fl< . epsilon.0) (l . fl> . (fl/ 1.0 epsilon.0))) (define log-l (fl- (fllog x) (fllog k))) (define l-1 (flexpm1 log-l)) (define l-1-sign (flsgn l-1)) (define log-n (fl* 0.5 (fl+ (fllog 2.0) (fllog (fl- l-1 log-l))))) (fl* l-1-sign (flexp (fl+ log-n (fl* 0.5 (fllog k)))))] [else (define n (fl* (flsgn (fl- l 1.0)) (flsqrt (fl* 2.0 (fl- (fl- l 1.0) (fllog l)))))) (fl* n (flsqrt k))])) (let ([norm-x (if upper? (- norm-x) norm-x)]) (cond [log? (standard-flnormal-log-cdf norm-x)] [else (standard-flnormal-cdf norm-x)])))
164e6e2423c1eaaeadda344f0b0c834117ef895ead32ffb6f573c0c6286af13a
janestreet/memtrace_viewer_with_deps
range_input.mli
open! Core_kernel open Bonsai_web open Memtrace_viewer_common module Size : sig type t = | Small | Large end type t val range : t -> Time_range.t val changing : t -> bool val lower_input : t -> Vdom.Node.t val upper_input : t -> Vdom.Node.t val reset_changing : t -> Vdom.Event.t val size : t -> Size.t val component : initial_value:Time_range.t -> max:Time_ns.Span.t Bonsai.Value.t -> start_time:Time_ns.t Bonsai.Value.t -> time_view:Graph_view.Time_view.t Bonsai.Value.t -> t Bonsai.Computation.t
null
https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/client/range_input.mli
ocaml
open! Core_kernel open Bonsai_web open Memtrace_viewer_common module Size : sig type t = | Small | Large end type t val range : t -> Time_range.t val changing : t -> bool val lower_input : t -> Vdom.Node.t val upper_input : t -> Vdom.Node.t val reset_changing : t -> Vdom.Event.t val size : t -> Size.t val component : initial_value:Time_range.t -> max:Time_ns.Span.t Bonsai.Value.t -> start_time:Time_ns.t Bonsai.Value.t -> time_view:Graph_view.Time_view.t Bonsai.Value.t -> t Bonsai.Computation.t
639fd5a15b290798d8573e382173f9b4d13a534d11e2d5dfab7a6e4674aebc7d
vikram/lisplibraries
employee.lisp
(in-package :weblocks-elephant-demo) Model (defpclass employee () ((first-name :initarg :first-name :accessor first-name :type string) (last-name :initarg :last-name :accessor last-name :type string) (age :initarg :age :accessor age :type integer) (address :accessor employee-address :initform (make-instance 'address) :type address) (company :accessor employee-company :type company))) ;;; Table View (defview employee-table-view (:type table :inherit-from '(:scaffold employee)) (address :type mixin :view 'address-table-view) (company :reader (compose #'company-name #'employee-company) :order-by '(company name))) ;;; Data view (defview employee-data-view (:type data :inherit-from '(:scaffold employee)) (address :type mixin :view 'address-data-view) (company :reader (compose #'company-name #'employee-company))) ;;; Form View (defview employee-form-view (:type form :inherit-from '(:scaffold employee)) (address :type mixin :view 'address-form-view :initform (make-instance 'address)) (company :present-as (dropdown :choices #'all-companies :label-key #'company-name) :parse-as (object-id :class-name 'company) :reader (compose #'object-id #'employee-company) :requiredp t))
null
https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/weblocks-stable/examples/weblocks-elephant-demo/src/model/employee.lisp
lisp
Table View Data view Form View
(in-package :weblocks-elephant-demo) Model (defpclass employee () ((first-name :initarg :first-name :accessor first-name :type string) (last-name :initarg :last-name :accessor last-name :type string) (age :initarg :age :accessor age :type integer) (address :accessor employee-address :initform (make-instance 'address) :type address) (company :accessor employee-company :type company))) (defview employee-table-view (:type table :inherit-from '(:scaffold employee)) (address :type mixin :view 'address-table-view) (company :reader (compose #'company-name #'employee-company) :order-by '(company name))) (defview employee-data-view (:type data :inherit-from '(:scaffold employee)) (address :type mixin :view 'address-data-view) (company :reader (compose #'company-name #'employee-company))) (defview employee-form-view (:type form :inherit-from '(:scaffold employee)) (address :type mixin :view 'address-form-view :initform (make-instance 'address)) (company :present-as (dropdown :choices #'all-companies :label-key #'company-name) :parse-as (object-id :class-name 'company) :reader (compose #'object-id #'employee-company) :requiredp t))
16ed478a00b1553ab46d9856e106e3863ada4edec89d12df93bfed80a551d622
janestreet/hardcaml
test_multiport_memory.ml
open! Import open Hardcaml_waveterm_kernel let write_port address_width data_width = { Signal.write_clock = Signal.gnd ; write_address = Signal.of_int ~width:address_width 0 ; write_data = Signal.of_int ~width:data_width 0 ; write_enable = Signal.gnd } ;; let%expect_test "exceptions" = require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[| write_port 3 8 |] ~read_addresses:[| Signal.of_int ~width:3 0 |]); [%expect {| ("[Signal.multiport_memory] size is greater than what can be addressed by write port" (size 16) (address_width 3)) |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[| write_port 4 8 |] ~read_addresses:[| Signal.of_int ~width:3 0 |]); [%expect {| ("[Signal.multiport_memory] size is greater than what can be addressed by read port" (size 16) (address_width 3)) |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[| write_port 4 8 |] ~read_addresses:[| Signal.of_int ~width:5 0 |]); [%expect {| ("[Signal.multiport_memory] width of read and write addresses differ" (write_address_width 4) (read_address_width 5)) |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports: [| { (write_port 4 8) with write_clock = Signal.of_int ~width:2 0 } |] ~read_addresses:[| Signal.of_int ~width:4 0 |]); [%expect {| ("[Signal.multiport_memory] width of clock must be 1" (port 0) (write_enable_width 1)) |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports: [| { (write_port 4 8) with write_enable = Signal.of_int ~width:2 0 } |] ~read_addresses:[| Signal.of_int ~width:4 0 |]); [%expect {| ("[Signal.multiport_memory] width of write enable must be 1" (port 0) (write_enable_width 2)) |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[||] ~read_addresses:[| Signal.of_int ~width:4 0 |]); [%expect {| "[Signal.multiport_memory] requires at least one write port" |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[| write_port 4 8 |] ~read_addresses:[||]); [%expect {| "[Signal.multiport_memory] requires at least one read port" |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[| write_port 4 8 |] ~read_addresses:[| Signal.of_int ~width:4 0; Signal.of_int ~width:5 0 |]); [%expect {| ("[Signal.multiport_memory] width of read address is inconsistent" (port 1) (read_address_width 5) (expected 4)) |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[| write_port 4 8; write_port 5 8 |] ~read_addresses:[| Signal.of_int ~width:4 0 |]); [%expect {| ("[Signal.multiport_memory] width of write address is inconsistent" (port 1) (write_address_width 5) (expected 4)) |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[| write_port 4 8; write_port 4 16 |] ~read_addresses:[| Signal.of_int ~width:4 0 |]); [%expect {| ("[Signal.multiport_memory] width of write data is inconsistent" (port 1) (write_data_width 16) (expected 8)) |}] ;; let%expect_test "sexp" = let sexp_of_signal = Signal.sexp_of_signal_recursive ~depth:2 in let memory = Signal.multiport_memory 32 ~write_ports:[| write_port 5 12; write_port 5 12 |] ~read_addresses:[| Signal.of_int ~width:5 0; Signal.of_int ~width:5 0 |] in print_s [%message (memory : signal array)]; [%expect {| (memory ( (memory_read_port (width 12) ((memory ( multiport_memory (width 12) ((size 32) (write_ports ( ((write_enable 0b0) (write_address 0b00000) (write_data 0x000)) ((write_enable 0b0) (write_address 0b00000) (write_data 0x000))))))) (read_addresses ( const (width 5) (value 0b00000))))) (memory_read_port (width 12) ((memory ( multiport_memory (width 12) ((size 32) (write_ports ( ((write_enable 0b0) (write_address 0b00000) (write_data 0x000)) ((write_enable 0b0) (write_address 0b00000) (write_data 0x000))))))) (read_addresses ( const (width 5) (value 0b00000))))))) |}] ;; let%expect_test "verilog, async memory, 1 port" = let read_data = Signal.multiport_memory 32 ~write_ports: [| { write_clock = clock ; write_enable = Signal.input "write_enable" 1 ; write_address = Signal.input "write_address" 5 ; write_data = Signal.input "write_data" 15 } |] ~read_addresses:[| Signal.input "read_address" 5 |] in let circuit = Circuit.create_exn ~name:"single_port_memory" (List.mapi (Array.to_list read_data) ~f:(fun i q -> Signal.output ("q" ^ Int.to_string i) q)) in Rtl.print Verilog circuit; [%expect {| module single_port_memory ( write_enable, write_data, write_address, clock, read_address, q0 ); input write_enable; input [14:0] write_data; input [4:0] write_address; input clock; input [4:0] read_address; output [14:0] q0; /* signal declarations */ reg [14:0] _7[0:31]; wire [14:0] _8; /* logic */ always @(posedge clock) begin if (write_enable) _7[write_address] <= write_data; end assign _8 = _7[read_address]; /* aliases */ /* output assignments */ assign q0 = _8; endmodule |}] ;; let%expect_test "verilog, async memory, 2 ports" = let read_data = Signal.multiport_memory 32 ~write_ports: [| { write_clock = clock ; write_enable = Signal.input "write_enable" 1 ; write_address = Signal.input "write_address" 5 ; write_data = Signal.input "write_data" 15 } ; { write_clock = Signal.input "clock2" 1 ; write_enable = Signal.input "write_enable2" 1 ; write_address = Signal.input "write_address2" 5 ; write_data = Signal.input "write_data2" 15 } |] ~read_addresses:[| Signal.input "read_address" 5; Signal.input "read_address2" 5 |] in let circuit = Circuit.create_exn ~name:"multi_port_memory" (List.mapi (Array.to_list read_data) ~f:(fun i q -> Signal.output ("q" ^ Int.to_string i) q)) in Rtl.print Verilog circuit; [%expect {| module multi_port_memory ( write_enable2, write_data2, write_address2, clock2, write_enable, write_data, write_address, clock, read_address2, read_address, q0, q1 ); input write_enable2; input [14:0] write_data2; input [4:0] write_address2; input clock2; input write_enable; input [14:0] write_data; input [4:0] write_address; input clock; input [4:0] read_address2; input [4:0] read_address; output [14:0] q0; output [14:0] q1; /* signal declarations */ wire [14:0] _14; reg [14:0] _13[0:31]; wire [14:0] _15; /* logic */ assign _14 = _13[read_address2]; always @(posedge clock) begin if (write_enable) _13[write_address] <= write_data; end always @(posedge clock2) begin if (write_enable2) _13[write_address2] <= write_data2; end assign _15 = _13[read_address]; /* aliases */ /* output assignments */ assign q0 = _15; assign q1 = _14; endmodule |}] ;; let dual_port ?(collision_mode = Ram.Collision_mode.Read_before_write) () = let read_data = Ram.create ~name:"foo" ~collision_mode ~size:32 ~write_ports: [| { write_clock = Signal.input "write_clock1" 1 ; write_enable = Signal.input "write_enable1" 1 ; write_address = Signal.input "write_address1" 5 ; write_data = Signal.input "write_data1" 15 } ; { write_clock = Signal.input "write_clock2" 1 ; write_enable = Signal.input "write_enable2" 1 ; write_address = Signal.input "write_address2" 5 ; write_data = Signal.input "write_data2" 15 } |] ~read_ports: [| { Ram.Read_port.read_clock = Signal.input "read_clock1" 1 ; read_address = Signal.input "read_address1" 5 ; read_enable = Signal.input "read_enable1" 1 } ; { read_clock = Signal.input "read_clock2" 1 ; read_address = Signal.input "read_address2" 5 ; read_enable = Signal.input "read_enable2" 1 } |] () in Circuit.create_exn ~name:"multi_port_memory" (List.mapi (Array.to_list read_data) ~f:(fun i q -> Signal.output ("q" ^ Int.to_string i) q)) ;; let%expect_test "dual port Verilog" = let circuit = dual_port () in Rtl.print Verilog circuit; [%expect {| module multi_port_memory ( read_enable2, read_clock2, read_enable1, read_clock1, write_enable2, write_data2, write_address2, write_clock2, write_enable1, write_data1, write_address1, write_clock1, read_address2, read_address1, q0, q1 ); input read_enable2; input read_clock2; input read_enable1; input read_clock1; input write_enable2; input [14:0] write_data2; input [4:0] write_address2; input write_clock2; input write_enable1; input [14:0] write_data1; input [4:0] write_address1; input write_clock1; input [4:0] read_address2; input [4:0] read_address1; output [14:0] q0; output [14:0] q1; /* signal declarations */ wire [14:0] _20 = 15'b000000000000000; wire [14:0] _19 = 15'b000000000000000; wire [14:0] _18; reg [14:0] _21; wire [14:0] _24 = 15'b000000000000000; wire [14:0] _23 = 15'b000000000000000; reg [14:0] foo[0:31]; wire [14:0] _22; reg [14:0] _25; /* logic */ assign _18 = foo[read_address2]; always @(posedge read_clock2) begin if (read_enable2) _21 <= _18; end always @(posedge write_clock1) begin if (write_enable1) foo[write_address1] <= write_data1; end always @(posedge write_clock2) begin if (write_enable2) foo[write_address2] <= write_data2; end assign _22 = foo[read_address1]; always @(posedge read_clock1) begin if (read_enable1) _25 <= _22; end /* aliases */ /* output assignments */ assign q0 = _25; assign q1 = _21; endmodule |}] ;; let%expect_test "dual port VHDL" = let circuit = dual_port () in Rtl.print Vhdl circuit; [%expect {| library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; entity multi_port_memory is port ( read_enable2 : in std_logic; read_clock2 : in std_logic; read_enable1 : in std_logic; read_clock1 : in std_logic; write_enable2 : in std_logic; write_data2 : in std_logic_vector (14 downto 0); write_address2 : in std_logic_vector (4 downto 0); write_clock2 : in std_logic; write_enable1 : in std_logic; write_data1 : in std_logic_vector (14 downto 0); write_address1 : in std_logic_vector (4 downto 0); write_clock1 : in std_logic; read_address2 : in std_logic_vector (4 downto 0); read_address1 : in std_logic_vector (4 downto 0); q0 : out std_logic_vector (14 downto 0); q1 : out std_logic_vector (14 downto 0) ); end entity; architecture rtl of multi_port_memory is -- conversion functions function hc_uns(a : std_logic) return unsigned is variable b : unsigned(0 downto 0); begin b(0) := a; return b; end; function hc_uns(a : std_logic_vector) return unsigned is begin return unsigned(a); end; function hc_sgn(a : std_logic) return signed is variable b : signed(0 downto 0); begin b(0) := a; return b; end; function hc_sgn(a : std_logic_vector) return signed is begin return signed(a); end; function hc_sl (a : std_logic_vector) return std_logic is begin return a(a'right); end; function hc_sl (a : unsigned) return std_logic is begin return a(a'right); end; function hc_sl (a : signed) return std_logic is begin return a(a'right); end; function hc_sl (a : boolean) return std_logic is begin if a then return '1'; else return '0'; end if; end; function hc_slv(a : std_logic_vector) return std_logic_vector is begin return a; end; function hc_slv(a : unsigned) return std_logic_vector is begin return std_logic_vector(a); end; function hc_slv(a : signed) return std_logic_vector is begin return std_logic_vector(a); end; -- signal declarations constant hc_20 : std_logic_vector (14 downto 0) := "000000000000000"; constant hc_19 : std_logic_vector (14 downto 0) := "000000000000000"; signal hc_18 : std_logic_vector (14 downto 0); signal hc_21 : std_logic_vector (14 downto 0); constant hc_24 : std_logic_vector (14 downto 0) := "000000000000000"; constant hc_23 : std_logic_vector (14 downto 0) := "000000000000000"; type foo_type is array (0 to 31) of std_logic_vector(14 downto 0); signal foo : foo_type; signal hc_22 : std_logic_vector (14 downto 0); signal hc_25 : std_logic_vector (14 downto 0); begin -- logic hc_18 <= foo(to_integer(hc_uns(read_address2))); process (read_clock2) begin if rising_edge(read_clock2) then if read_enable2 = '1' then hc_21 <= hc_18; end if; end if; end process; process (write_clock1) begin if rising_edge(write_clock1) then if write_enable1 = '1' then foo(to_integer(hc_uns(write_address1))) <= write_data1; end if; end if; end process; process (write_clock2) begin if rising_edge(write_clock2) then if write_enable2 = '1' then foo(to_integer(hc_uns(write_address2))) <= write_data2; end if; end if; end process; hc_22 <= foo(to_integer(hc_uns(read_address1))); process (read_clock1) begin if rising_edge(read_clock1) then if read_enable1 = '1' then hc_25 <= hc_22; end if; end if; end process; -- aliases -- output assignments q0 <= hc_25; q1 <= hc_21; end architecture; |}] ;; let%expect_test "simulation - write and read data on both ports" = let circuit = dual_port () in let simulator = Cyclesim.create circuit in let waves, simulator = Waveform.create simulator in let write_enable1 = Cyclesim.in_port simulator "write_enable1" in let write_address1 = Cyclesim.in_port simulator "write_address1" in let write_data1 = Cyclesim.in_port simulator "write_data1" in let _write_enable2 = Cyclesim.in_port simulator "write_enable2" in let _write_address2 = Cyclesim.in_port simulator "write_address2" in let _write_data2 = Cyclesim.in_port simulator "write_data2" in let read_address1 = Cyclesim.in_port simulator "read_address1" in let read_enable1 = Cyclesim.in_port simulator "read_enable1" in let read_address2 = Cyclesim.in_port simulator "read_address2" in let read_enable2 = Cyclesim.in_port simulator "read_enable2" in Cyclesim.reset simulator; write on port 1 and 2 write_enable1 := Bits.vdd; write_address1 := Bits.of_int ~width:5 3; write_data1 := Bits.of_int ~width:15 100; Cyclesim.cycle simulator; write_address1 := Bits.of_int ~width:5 4; write_data1 := Bits.of_int ~width:15 640; Cyclesim.cycle simulator; write_enable1 := Bits.gnd; read on port 1 Cyclesim.cycle simulator; read_address1 := Bits.of_int ~width:5 3; read_enable1 := Bits.vdd; Cyclesim.cycle simulator; read on port 2 read_enable1 := Bits.gnd; read_address2 := Bits.of_int ~width:5 3; read_enable2 := Bits.vdd; Cyclesim.cycle simulator; read_enable2 := Bits.gnd; Cyclesim.cycle simulator; read on ports 1 and 2 read_enable1 := Bits.vdd; read_enable2 := Bits.vdd; read_address1 := Bits.of_int ~width:5 4; read_address2 := Bits.of_int ~width:5 4; Cyclesim.cycle simulator; read_enable1 := Bits.gnd; read_enable2 := Bits.gnd; Cyclesim.cycle simulator; Waveform.print ~display_height:42 ~display_width:86 ~wave_width:2 waves; [%expect {| ┌Signals───────────┐┌Waves───────────────────────────────────────────────────────────┐ │ ││────────────────────────┬─────────────────┬─────────── │ │read_address1 ││ 00 │03 │04 │ │ ││────────────────────────┴─────────────────┴─────────── │ │ ││──────────────────────────────┬───────────┬─────────── │ │read_address2 ││ 00 │03 │04 │ │ ││──────────────────────────────┴───────────┴─────────── │ │read_clock1 ││ │ │ ││────────────────────────────────────────────────────── │ │read_clock2 ││ │ │ ││────────────────────────────────────────────────────── │ │read_enable1 ││ ┌─────┐ ┌─────┐ │ │ ││────────────────────────┘ └───────────┘ └───── │ │read_enable2 ││ ┌─────┐ ┌─────┐ │ │ ││──────────────────────────────┘ └─────┘ └───── │ │ ││──────┬─────┬───────────────────────────────────────── │ │write_address1 ││ 00 │03 │04 │ │ ││──────┴─────┴───────────────────────────────────────── │ │ ││────────────────────────────────────────────────────── │ │write_address2 ││ 00 │ │ ││────────────────────────────────────────────────────── │ │write_clock1 ││ │ │ ││────────────────────────────────────────────────────── │ │write_clock2 ││ │ │ ││────────────────────────────────────────────────────── │ │ ││──────┬─────┬───────────────────────────────────────── │ │write_data1 ││ 0000 │0064 │0280 │ │ ││──────┴─────┴───────────────────────────────────────── │ │ ││────────────────────────────────────────────────────── │ │write_data2 ││ 0000 │ │ ││────────────────────────────────────────────────────── │ │write_enable1 ││ ┌───────────┐ │ │ ││──────┘ └─────────────────────────────────── │ │write_enable2 ││ │ │ ││────────────────────────────────────────────────────── │ │ ││──────────────────────────────┬─────────────────┬───── │ │q0 ││ 0000 │0064 │0280 │ │ ││──────────────────────────────┴─────────────────┴───── │ │ ││────────────────────────────────────┬───────────┬───── │ │q1 ││ 0000 │0064 │0280 │ │ ││────────────────────────────────────┴───────────┴───── │ └──────────────────┘└────────────────────────────────────────────────────────────────┘ |}] ;; let%expect_test "simulation - write on both ports - highest indexed port wins" = let circuit = dual_port () in let simulator = Cyclesim.create circuit in let waves, simulator = Waveform.create simulator in let write_enable1 = Cyclesim.in_port simulator "write_enable1" in let write_address1 = Cyclesim.in_port simulator "write_address1" in let write_data1 = Cyclesim.in_port simulator "write_data1" in let write_enable2 = Cyclesim.in_port simulator "write_enable2" in let write_address2 = Cyclesim.in_port simulator "write_address2" in let write_data2 = Cyclesim.in_port simulator "write_data2" in let read_address1 = Cyclesim.in_port simulator "read_address1" in let read_enable1 = Cyclesim.in_port simulator "read_enable1" in let read_address2 = Cyclesim.in_port simulator "read_address2" in let read_enable2 = Cyclesim.in_port simulator "read_enable2" in Cyclesim.reset simulator; write_enable1 := Bits.vdd; write_address1 := Bits.of_int ~width:5 9; write_data1 := Bits.of_int ~width:15 100; write_enable2 := Bits.vdd; write_address2 := Bits.of_int ~width:5 9; write_data2 := Bits.of_int ~width:15 200; Cyclesim.cycle simulator; write_enable1 := Bits.gnd; write_enable2 := Bits.gnd; Cyclesim.cycle simulator; read_enable1 := Bits.vdd; read_address1 := Bits.of_int ~width:5 9; read_enable2 := Bits.vdd; read_address2 := Bits.of_int ~width:5 9; Cyclesim.cycle simulator; read_enable1 := Bits.gnd; read_enable2 := Bits.gnd; Cyclesim.cycle simulator; Waveform.print ~display_height:42 ~display_width:60 ~wave_width:2 waves; [%expect {| ┌Signals──────┐┌Waves──────────────────────────────────────┐ │ ││──────────────────┬─────────── │ │read_address1││ 00 │09 │ │ ││──────────────────┴─────────── │ │ ││──────────────────┬─────────── │ │read_address2││ 00 │09 │ │ ││──────────────────┴─────────── │ │read_clock1 ││ │ │ ││────────────────────────────── │ │read_clock2 ││ │ │ ││────────────────────────────── │ │read_enable1 ││ ┌─────┐ │ │ ││──────────────────┘ └───── │ │read_enable2 ││ ┌─────┐ │ │ ││──────────────────┘ └───── │ │ ││──────┬─────────────────────── │ │write_address││ 00 │09 │ │ ││──────┴─────────────────────── │ │ ││──────┬─────────────────────── │ │write_address││ 00 │09 │ │ ││──────┴─────────────────────── │ │write_clock1 ││ │ │ ││────────────────────────────── │ │write_clock2 ││ │ │ ││────────────────────────────── │ │ ││──────┬─────────────────────── │ │write_data1 ││ 0000 │0064 │ │ ││──────┴─────────────────────── │ │ ││──────┬─────────────────────── │ │write_data2 ││ 0000 │00C8 │ │ ││──────┴─────────────────────── │ │write_enable1││ ┌─────┐ │ │ ││──────┘ └───────────────── │ │write_enable2││ ┌─────┐ │ │ ││──────┘ └───────────────── │ │ ││────────────────────────┬───── │ │q0 ││ 0000 │00C8 │ │ ││────────────────────────┴───── │ │ ││────────────────────────┬───── │ │q1 ││ 0000 │00C8 │ │ ││────────────────────────┴───── │ └─────────────┘└───────────────────────────────────────────┘ |}] ;; let%expect_test "simulation - demonstrate collision modes" = let test collision_mode = let circuit = dual_port ~collision_mode () in let simulator = Cyclesim.create circuit in let waves, simulator = Waveform.create simulator in let write_enable1 = Cyclesim.in_port simulator "write_enable1" in let write_address1 = Cyclesim.in_port simulator "write_address1" in let write_data1 = Cyclesim.in_port simulator "write_data1" in let read_address1 = Cyclesim.in_port simulator "read_address1" in let read_enable1 = Cyclesim.in_port simulator "read_enable1" in Cyclesim.reset simulator; write_enable1 := Bits.vdd; write_address1 := Bits.of_int ~width:5 13; write_data1 := Bits.of_int ~width:15 10; Cyclesim.cycle simulator; write_enable1 := Bits.vdd; write_address1 := Bits.of_int ~width:5 13; write_data1 := Bits.of_int ~width:15 20; read_enable1 := Bits.vdd; read_address1 := Bits.of_int ~width:5 13; Cyclesim.cycle simulator; write_enable1 := Bits.gnd; read_enable1 := Bits.gnd; Cyclesim.cycle simulator; Waveform.print ~display_height:42 ~display_width:60 ~wave_width:2 waves in test Read_before_write; [%expect {| ┌Signals──────┐┌Waves──────────────────────────────────────┐ │ ││────────────┬─────────── │ │read_address1││ 00 │0D │ │ ││────────────┴─────────── │ │ ││──────────────────────── │ │read_address2││ 00 │ │ ││──────────────────────── │ │read_clock1 ││ │ │ ││──────────────────────── │ │read_clock2 ││ │ │ ││──────────────────────── │ │read_enable1 ││ ┌─────┐ │ │ ││────────────┘ └───── │ │read_enable2 ││ │ │ ││──────────────────────── │ │ ││──────┬───────────────── │ │write_address││ 00 │0D │ │ ││──────┴───────────────── │ │ ││──────────────────────── │ │write_address││ 00 │ │ ││──────────────────────── │ │write_clock1 ││ │ │ ││──────────────────────── │ │write_clock2 ││ │ │ ││──────────────────────── │ │ ││──────┬─────┬─────────── │ │write_data1 ││ 0000 │000A │0014 │ │ ││──────┴─────┴─────────── │ │ ││──────────────────────── │ │write_data2 ││ 0000 │ │ ││──────────────────────── │ │write_enable1││ ┌───────────┐ │ │ ││──────┘ └───── │ │write_enable2││ │ │ ││──────────────────────── │ │ ││──────────────────┬───── │ │q0 ││ 0000 │000A │ │ ││──────────────────┴───── │ │ ││──────────────────────── │ │q1 ││ 0000 │ │ ││──────────────────────── │ └─────────────┘└───────────────────────────────────────────┘ |}]; test Write_before_read; [%expect {| ┌Signals──────┐┌Waves──────────────────────────────────────┐ │ ││────────────┬─────────── │ │read_address1││ 00 │0D │ │ ││────────────┴─────────── │ │ ││──────────────────────── │ │read_address2││ 00 │ │ ││──────────────────────── │ │read_clock1 ││ │ │ ││──────────────────────── │ │read_clock2 ││ │ │ ││──────────────────────── │ │read_enable1 ││ ┌─────┐ │ │ ││────────────┘ └───── │ │read_enable2 ││ │ │ ││──────────────────────── │ │ ││──────┬───────────────── │ │write_address││ 00 │0D │ │ ││──────┴───────────────── │ │ ││──────────────────────── │ │write_address││ 00 │ │ ││──────────────────────── │ │write_clock1 ││ │ │ ││──────────────────────── │ │write_clock2 ││ │ │ ││──────────────────────── │ │ ││──────┬─────┬─────────── │ │write_data1 ││ 0000 │000A │0014 │ │ ││──────┴─────┴─────────── │ │ ││──────────────────────── │ │write_data2 ││ 0000 │ │ ││──────────────────────── │ │write_enable1││ ┌───────────┐ │ │ ││──────┘ └───── │ │write_enable2││ │ │ ││──────────────────────── │ │ ││──────────────────┬───── │ │q0 ││ 0000 │0014 │ │ ││──────────────────┴───── │ │ ││──────────────────────── │ │q1 ││ 0000 │ │ ││──────────────────────── │ └─────────────┘└───────────────────────────────────────────┘ |}] ;;
null
https://raw.githubusercontent.com/janestreet/hardcaml/15727795c2bf922dd852cc0cd895a4ed1d9527e5/test/lib/test_multiport_memory.ml
ocaml
open! Import open Hardcaml_waveterm_kernel let write_port address_width data_width = { Signal.write_clock = Signal.gnd ; write_address = Signal.of_int ~width:address_width 0 ; write_data = Signal.of_int ~width:data_width 0 ; write_enable = Signal.gnd } ;; let%expect_test "exceptions" = require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[| write_port 3 8 |] ~read_addresses:[| Signal.of_int ~width:3 0 |]); [%expect {| ("[Signal.multiport_memory] size is greater than what can be addressed by write port" (size 16) (address_width 3)) |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[| write_port 4 8 |] ~read_addresses:[| Signal.of_int ~width:3 0 |]); [%expect {| ("[Signal.multiport_memory] size is greater than what can be addressed by read port" (size 16) (address_width 3)) |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[| write_port 4 8 |] ~read_addresses:[| Signal.of_int ~width:5 0 |]); [%expect {| ("[Signal.multiport_memory] width of read and write addresses differ" (write_address_width 4) (read_address_width 5)) |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports: [| { (write_port 4 8) with write_clock = Signal.of_int ~width:2 0 } |] ~read_addresses:[| Signal.of_int ~width:4 0 |]); [%expect {| ("[Signal.multiport_memory] width of clock must be 1" (port 0) (write_enable_width 1)) |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports: [| { (write_port 4 8) with write_enable = Signal.of_int ~width:2 0 } |] ~read_addresses:[| Signal.of_int ~width:4 0 |]); [%expect {| ("[Signal.multiport_memory] width of write enable must be 1" (port 0) (write_enable_width 2)) |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[||] ~read_addresses:[| Signal.of_int ~width:4 0 |]); [%expect {| "[Signal.multiport_memory] requires at least one write port" |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[| write_port 4 8 |] ~read_addresses:[||]); [%expect {| "[Signal.multiport_memory] requires at least one read port" |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[| write_port 4 8 |] ~read_addresses:[| Signal.of_int ~width:4 0; Signal.of_int ~width:5 0 |]); [%expect {| ("[Signal.multiport_memory] width of read address is inconsistent" (port 1) (read_address_width 5) (expected 4)) |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[| write_port 4 8; write_port 5 8 |] ~read_addresses:[| Signal.of_int ~width:4 0 |]); [%expect {| ("[Signal.multiport_memory] width of write address is inconsistent" (port 1) (write_address_width 5) (expected 4)) |}]; require_does_raise [%here] (fun () -> Signal.multiport_memory 16 ~write_ports:[| write_port 4 8; write_port 4 16 |] ~read_addresses:[| Signal.of_int ~width:4 0 |]); [%expect {| ("[Signal.multiport_memory] width of write data is inconsistent" (port 1) (write_data_width 16) (expected 8)) |}] ;; let%expect_test "sexp" = let sexp_of_signal = Signal.sexp_of_signal_recursive ~depth:2 in let memory = Signal.multiport_memory 32 ~write_ports:[| write_port 5 12; write_port 5 12 |] ~read_addresses:[| Signal.of_int ~width:5 0; Signal.of_int ~width:5 0 |] in print_s [%message (memory : signal array)]; [%expect {| (memory ( (memory_read_port (width 12) ((memory ( multiport_memory (width 12) ((size 32) (write_ports ( ((write_enable 0b0) (write_address 0b00000) (write_data 0x000)) ((write_enable 0b0) (write_address 0b00000) (write_data 0x000))))))) (read_addresses ( const (width 5) (value 0b00000))))) (memory_read_port (width 12) ((memory ( multiport_memory (width 12) ((size 32) (write_ports ( ((write_enable 0b0) (write_address 0b00000) (write_data 0x000)) ((write_enable 0b0) (write_address 0b00000) (write_data 0x000))))))) (read_addresses ( const (width 5) (value 0b00000))))))) |}] ;; let%expect_test "verilog, async memory, 1 port" = let read_data = Signal.multiport_memory 32 ~write_ports: [| { write_clock = clock ; write_enable = Signal.input "write_enable" 1 ; write_address = Signal.input "write_address" 5 ; write_data = Signal.input "write_data" 15 } |] ~read_addresses:[| Signal.input "read_address" 5 |] in let circuit = Circuit.create_exn ~name:"single_port_memory" (List.mapi (Array.to_list read_data) ~f:(fun i q -> Signal.output ("q" ^ Int.to_string i) q)) in Rtl.print Verilog circuit; [%expect {| module single_port_memory ( write_enable, write_data, write_address, clock, read_address, q0 ); input write_enable; input [14:0] write_data; input [4:0] write_address; input clock; input [4:0] read_address; output [14:0] q0; /* signal declarations */ reg [14:0] _7[0:31]; wire [14:0] _8; /* logic */ always @(posedge clock) begin if (write_enable) _7[write_address] <= write_data; end assign _8 = _7[read_address]; /* aliases */ /* output assignments */ assign q0 = _8; endmodule |}] ;; let%expect_test "verilog, async memory, 2 ports" = let read_data = Signal.multiport_memory 32 ~write_ports: [| { write_clock = clock ; write_enable = Signal.input "write_enable" 1 ; write_address = Signal.input "write_address" 5 ; write_data = Signal.input "write_data" 15 } ; { write_clock = Signal.input "clock2" 1 ; write_enable = Signal.input "write_enable2" 1 ; write_address = Signal.input "write_address2" 5 ; write_data = Signal.input "write_data2" 15 } |] ~read_addresses:[| Signal.input "read_address" 5; Signal.input "read_address2" 5 |] in let circuit = Circuit.create_exn ~name:"multi_port_memory" (List.mapi (Array.to_list read_data) ~f:(fun i q -> Signal.output ("q" ^ Int.to_string i) q)) in Rtl.print Verilog circuit; [%expect {| module multi_port_memory ( write_enable2, write_data2, write_address2, clock2, write_enable, write_data, write_address, clock, read_address2, read_address, q0, q1 ); input write_enable2; input [14:0] write_data2; input [4:0] write_address2; input clock2; input write_enable; input [14:0] write_data; input [4:0] write_address; input clock; input [4:0] read_address2; input [4:0] read_address; output [14:0] q0; output [14:0] q1; /* signal declarations */ wire [14:0] _14; reg [14:0] _13[0:31]; wire [14:0] _15; /* logic */ assign _14 = _13[read_address2]; always @(posedge clock) begin if (write_enable) _13[write_address] <= write_data; end always @(posedge clock2) begin if (write_enable2) _13[write_address2] <= write_data2; end assign _15 = _13[read_address]; /* aliases */ /* output assignments */ assign q0 = _15; assign q1 = _14; endmodule |}] ;; let dual_port ?(collision_mode = Ram.Collision_mode.Read_before_write) () = let read_data = Ram.create ~name:"foo" ~collision_mode ~size:32 ~write_ports: [| { write_clock = Signal.input "write_clock1" 1 ; write_enable = Signal.input "write_enable1" 1 ; write_address = Signal.input "write_address1" 5 ; write_data = Signal.input "write_data1" 15 } ; { write_clock = Signal.input "write_clock2" 1 ; write_enable = Signal.input "write_enable2" 1 ; write_address = Signal.input "write_address2" 5 ; write_data = Signal.input "write_data2" 15 } |] ~read_ports: [| { Ram.Read_port.read_clock = Signal.input "read_clock1" 1 ; read_address = Signal.input "read_address1" 5 ; read_enable = Signal.input "read_enable1" 1 } ; { read_clock = Signal.input "read_clock2" 1 ; read_address = Signal.input "read_address2" 5 ; read_enable = Signal.input "read_enable2" 1 } |] () in Circuit.create_exn ~name:"multi_port_memory" (List.mapi (Array.to_list read_data) ~f:(fun i q -> Signal.output ("q" ^ Int.to_string i) q)) ;; let%expect_test "dual port Verilog" = let circuit = dual_port () in Rtl.print Verilog circuit; [%expect {| module multi_port_memory ( read_enable2, read_clock2, read_enable1, read_clock1, write_enable2, write_data2, write_address2, write_clock2, write_enable1, write_data1, write_address1, write_clock1, read_address2, read_address1, q0, q1 ); input read_enable2; input read_clock2; input read_enable1; input read_clock1; input write_enable2; input [14:0] write_data2; input [4:0] write_address2; input write_clock2; input write_enable1; input [14:0] write_data1; input [4:0] write_address1; input write_clock1; input [4:0] read_address2; input [4:0] read_address1; output [14:0] q0; output [14:0] q1; /* signal declarations */ wire [14:0] _20 = 15'b000000000000000; wire [14:0] _19 = 15'b000000000000000; wire [14:0] _18; reg [14:0] _21; wire [14:0] _24 = 15'b000000000000000; wire [14:0] _23 = 15'b000000000000000; reg [14:0] foo[0:31]; wire [14:0] _22; reg [14:0] _25; /* logic */ assign _18 = foo[read_address2]; always @(posedge read_clock2) begin if (read_enable2) _21 <= _18; end always @(posedge write_clock1) begin if (write_enable1) foo[write_address1] <= write_data1; end always @(posedge write_clock2) begin if (write_enable2) foo[write_address2] <= write_data2; end assign _22 = foo[read_address1]; always @(posedge read_clock1) begin if (read_enable1) _25 <= _22; end /* aliases */ /* output assignments */ assign q0 = _25; assign q1 = _21; endmodule |}] ;; let%expect_test "dual port VHDL" = let circuit = dual_port () in Rtl.print Vhdl circuit; [%expect {| library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; entity multi_port_memory is port ( read_enable2 : in std_logic; read_clock2 : in std_logic; read_enable1 : in std_logic; read_clock1 : in std_logic; write_enable2 : in std_logic; write_data2 : in std_logic_vector (14 downto 0); write_address2 : in std_logic_vector (4 downto 0); write_clock2 : in std_logic; write_enable1 : in std_logic; write_data1 : in std_logic_vector (14 downto 0); write_address1 : in std_logic_vector (4 downto 0); write_clock1 : in std_logic; read_address2 : in std_logic_vector (4 downto 0); read_address1 : in std_logic_vector (4 downto 0); q0 : out std_logic_vector (14 downto 0); q1 : out std_logic_vector (14 downto 0) ); end entity; architecture rtl of multi_port_memory is -- conversion functions function hc_uns(a : std_logic) return unsigned is variable b : unsigned(0 downto 0); begin b(0) := a; return b; end; function hc_uns(a : std_logic_vector) return unsigned is begin return unsigned(a); end; function hc_sgn(a : std_logic) return signed is variable b : signed(0 downto 0); begin b(0) := a; return b; end; function hc_sgn(a : std_logic_vector) return signed is begin return signed(a); end; function hc_sl (a : std_logic_vector) return std_logic is begin return a(a'right); end; function hc_sl (a : unsigned) return std_logic is begin return a(a'right); end; function hc_sl (a : signed) return std_logic is begin return a(a'right); end; function hc_sl (a : boolean) return std_logic is begin if a then return '1'; else return '0'; end if; end; function hc_slv(a : std_logic_vector) return std_logic_vector is begin return a; end; function hc_slv(a : unsigned) return std_logic_vector is begin return std_logic_vector(a); end; function hc_slv(a : signed) return std_logic_vector is begin return std_logic_vector(a); end; -- signal declarations constant hc_20 : std_logic_vector (14 downto 0) := "000000000000000"; constant hc_19 : std_logic_vector (14 downto 0) := "000000000000000"; signal hc_18 : std_logic_vector (14 downto 0); signal hc_21 : std_logic_vector (14 downto 0); constant hc_24 : std_logic_vector (14 downto 0) := "000000000000000"; constant hc_23 : std_logic_vector (14 downto 0) := "000000000000000"; type foo_type is array (0 to 31) of std_logic_vector(14 downto 0); signal foo : foo_type; signal hc_22 : std_logic_vector (14 downto 0); signal hc_25 : std_logic_vector (14 downto 0); begin -- logic hc_18 <= foo(to_integer(hc_uns(read_address2))); process (read_clock2) begin if rising_edge(read_clock2) then if read_enable2 = '1' then hc_21 <= hc_18; end if; end if; end process; process (write_clock1) begin if rising_edge(write_clock1) then if write_enable1 = '1' then foo(to_integer(hc_uns(write_address1))) <= write_data1; end if; end if; end process; process (write_clock2) begin if rising_edge(write_clock2) then if write_enable2 = '1' then foo(to_integer(hc_uns(write_address2))) <= write_data2; end if; end if; end process; hc_22 <= foo(to_integer(hc_uns(read_address1))); process (read_clock1) begin if rising_edge(read_clock1) then if read_enable1 = '1' then hc_25 <= hc_22; end if; end if; end process; -- aliases -- output assignments q0 <= hc_25; q1 <= hc_21; end architecture; |}] ;; let%expect_test "simulation - write and read data on both ports" = let circuit = dual_port () in let simulator = Cyclesim.create circuit in let waves, simulator = Waveform.create simulator in let write_enable1 = Cyclesim.in_port simulator "write_enable1" in let write_address1 = Cyclesim.in_port simulator "write_address1" in let write_data1 = Cyclesim.in_port simulator "write_data1" in let _write_enable2 = Cyclesim.in_port simulator "write_enable2" in let _write_address2 = Cyclesim.in_port simulator "write_address2" in let _write_data2 = Cyclesim.in_port simulator "write_data2" in let read_address1 = Cyclesim.in_port simulator "read_address1" in let read_enable1 = Cyclesim.in_port simulator "read_enable1" in let read_address2 = Cyclesim.in_port simulator "read_address2" in let read_enable2 = Cyclesim.in_port simulator "read_enable2" in Cyclesim.reset simulator; write on port 1 and 2 write_enable1 := Bits.vdd; write_address1 := Bits.of_int ~width:5 3; write_data1 := Bits.of_int ~width:15 100; Cyclesim.cycle simulator; write_address1 := Bits.of_int ~width:5 4; write_data1 := Bits.of_int ~width:15 640; Cyclesim.cycle simulator; write_enable1 := Bits.gnd; read on port 1 Cyclesim.cycle simulator; read_address1 := Bits.of_int ~width:5 3; read_enable1 := Bits.vdd; Cyclesim.cycle simulator; read on port 2 read_enable1 := Bits.gnd; read_address2 := Bits.of_int ~width:5 3; read_enable2 := Bits.vdd; Cyclesim.cycle simulator; read_enable2 := Bits.gnd; Cyclesim.cycle simulator; read on ports 1 and 2 read_enable1 := Bits.vdd; read_enable2 := Bits.vdd; read_address1 := Bits.of_int ~width:5 4; read_address2 := Bits.of_int ~width:5 4; Cyclesim.cycle simulator; read_enable1 := Bits.gnd; read_enable2 := Bits.gnd; Cyclesim.cycle simulator; Waveform.print ~display_height:42 ~display_width:86 ~wave_width:2 waves; [%expect {| ┌Signals───────────┐┌Waves───────────────────────────────────────────────────────────┐ │ ││────────────────────────┬─────────────────┬─────────── │ │read_address1 ││ 00 │03 │04 │ │ ││────────────────────────┴─────────────────┴─────────── │ │ ││──────────────────────────────┬───────────┬─────────── │ │read_address2 ││ 00 │03 │04 │ │ ││──────────────────────────────┴───────────┴─────────── │ │read_clock1 ││ │ │ ││────────────────────────────────────────────────────── │ │read_clock2 ││ │ │ ││────────────────────────────────────────────────────── │ │read_enable1 ││ ┌─────┐ ┌─────┐ │ │ ││────────────────────────┘ └───────────┘ └───── │ │read_enable2 ││ ┌─────┐ ┌─────┐ │ │ ││──────────────────────────────┘ └─────┘ └───── │ │ ││──────┬─────┬───────────────────────────────────────── │ │write_address1 ││ 00 │03 │04 │ │ ││──────┴─────┴───────────────────────────────────────── │ │ ││────────────────────────────────────────────────────── │ │write_address2 ││ 00 │ │ ││────────────────────────────────────────────────────── │ │write_clock1 ││ │ │ ││────────────────────────────────────────────────────── │ │write_clock2 ││ │ │ ││────────────────────────────────────────────────────── │ │ ││──────┬─────┬───────────────────────────────────────── │ │write_data1 ││ 0000 │0064 │0280 │ │ ││──────┴─────┴───────────────────────────────────────── │ │ ││────────────────────────────────────────────────────── │ │write_data2 ││ 0000 │ │ ││────────────────────────────────────────────────────── │ │write_enable1 ││ ┌───────────┐ │ │ ││──────┘ └─────────────────────────────────── │ │write_enable2 ││ │ │ ││────────────────────────────────────────────────────── │ │ ││──────────────────────────────┬─────────────────┬───── │ │q0 ││ 0000 │0064 │0280 │ │ ││──────────────────────────────┴─────────────────┴───── │ │ ││────────────────────────────────────┬───────────┬───── │ │q1 ││ 0000 │0064 │0280 │ │ ││────────────────────────────────────┴───────────┴───── │ └──────────────────┘└────────────────────────────────────────────────────────────────┘ |}] ;; let%expect_test "simulation - write on both ports - highest indexed port wins" = let circuit = dual_port () in let simulator = Cyclesim.create circuit in let waves, simulator = Waveform.create simulator in let write_enable1 = Cyclesim.in_port simulator "write_enable1" in let write_address1 = Cyclesim.in_port simulator "write_address1" in let write_data1 = Cyclesim.in_port simulator "write_data1" in let write_enable2 = Cyclesim.in_port simulator "write_enable2" in let write_address2 = Cyclesim.in_port simulator "write_address2" in let write_data2 = Cyclesim.in_port simulator "write_data2" in let read_address1 = Cyclesim.in_port simulator "read_address1" in let read_enable1 = Cyclesim.in_port simulator "read_enable1" in let read_address2 = Cyclesim.in_port simulator "read_address2" in let read_enable2 = Cyclesim.in_port simulator "read_enable2" in Cyclesim.reset simulator; write_enable1 := Bits.vdd; write_address1 := Bits.of_int ~width:5 9; write_data1 := Bits.of_int ~width:15 100; write_enable2 := Bits.vdd; write_address2 := Bits.of_int ~width:5 9; write_data2 := Bits.of_int ~width:15 200; Cyclesim.cycle simulator; write_enable1 := Bits.gnd; write_enable2 := Bits.gnd; Cyclesim.cycle simulator; read_enable1 := Bits.vdd; read_address1 := Bits.of_int ~width:5 9; read_enable2 := Bits.vdd; read_address2 := Bits.of_int ~width:5 9; Cyclesim.cycle simulator; read_enable1 := Bits.gnd; read_enable2 := Bits.gnd; Cyclesim.cycle simulator; Waveform.print ~display_height:42 ~display_width:60 ~wave_width:2 waves; [%expect {| ┌Signals──────┐┌Waves──────────────────────────────────────┐ │ ││──────────────────┬─────────── │ │read_address1││ 00 │09 │ │ ││──────────────────┴─────────── │ │ ││──────────────────┬─────────── │ │read_address2││ 00 │09 │ │ ││──────────────────┴─────────── │ │read_clock1 ││ │ │ ││────────────────────────────── │ │read_clock2 ││ │ │ ││────────────────────────────── │ │read_enable1 ││ ┌─────┐ │ │ ││──────────────────┘ └───── │ │read_enable2 ││ ┌─────┐ │ │ ││──────────────────┘ └───── │ │ ││──────┬─────────────────────── │ │write_address││ 00 │09 │ │ ││──────┴─────────────────────── │ │ ││──────┬─────────────────────── │ │write_address││ 00 │09 │ │ ││──────┴─────────────────────── │ │write_clock1 ││ │ │ ││────────────────────────────── │ │write_clock2 ││ │ │ ││────────────────────────────── │ │ ││──────┬─────────────────────── │ │write_data1 ││ 0000 │0064 │ │ ││──────┴─────────────────────── │ │ ││──────┬─────────────────────── │ │write_data2 ││ 0000 │00C8 │ │ ││──────┴─────────────────────── │ │write_enable1││ ┌─────┐ │ │ ││──────┘ └───────────────── │ │write_enable2││ ┌─────┐ │ │ ││──────┘ └───────────────── │ │ ││────────────────────────┬───── │ │q0 ││ 0000 │00C8 │ │ ││────────────────────────┴───── │ │ ││────────────────────────┬───── │ │q1 ││ 0000 │00C8 │ │ ││────────────────────────┴───── │ └─────────────┘└───────────────────────────────────────────┘ |}] ;; let%expect_test "simulation - demonstrate collision modes" = let test collision_mode = let circuit = dual_port ~collision_mode () in let simulator = Cyclesim.create circuit in let waves, simulator = Waveform.create simulator in let write_enable1 = Cyclesim.in_port simulator "write_enable1" in let write_address1 = Cyclesim.in_port simulator "write_address1" in let write_data1 = Cyclesim.in_port simulator "write_data1" in let read_address1 = Cyclesim.in_port simulator "read_address1" in let read_enable1 = Cyclesim.in_port simulator "read_enable1" in Cyclesim.reset simulator; write_enable1 := Bits.vdd; write_address1 := Bits.of_int ~width:5 13; write_data1 := Bits.of_int ~width:15 10; Cyclesim.cycle simulator; write_enable1 := Bits.vdd; write_address1 := Bits.of_int ~width:5 13; write_data1 := Bits.of_int ~width:15 20; read_enable1 := Bits.vdd; read_address1 := Bits.of_int ~width:5 13; Cyclesim.cycle simulator; write_enable1 := Bits.gnd; read_enable1 := Bits.gnd; Cyclesim.cycle simulator; Waveform.print ~display_height:42 ~display_width:60 ~wave_width:2 waves in test Read_before_write; [%expect {| ┌Signals──────┐┌Waves──────────────────────────────────────┐ │ ││────────────┬─────────── │ │read_address1││ 00 │0D │ │ ││────────────┴─────────── │ │ ││──────────────────────── │ │read_address2││ 00 │ │ ││──────────────────────── │ │read_clock1 ││ │ │ ││──────────────────────── │ │read_clock2 ││ │ │ ││──────────────────────── │ │read_enable1 ││ ┌─────┐ │ │ ││────────────┘ └───── │ │read_enable2 ││ │ │ ││──────────────────────── │ │ ││──────┬───────────────── │ │write_address││ 00 │0D │ │ ││──────┴───────────────── │ │ ││──────────────────────── │ │write_address││ 00 │ │ ││──────────────────────── │ │write_clock1 ││ │ │ ││──────────────────────── │ │write_clock2 ││ │ │ ││──────────────────────── │ │ ││──────┬─────┬─────────── │ │write_data1 ││ 0000 │000A │0014 │ │ ││──────┴─────┴─────────── │ │ ││──────────────────────── │ │write_data2 ││ 0000 │ │ ││──────────────────────── │ │write_enable1││ ┌───────────┐ │ │ ││──────┘ └───── │ │write_enable2││ │ │ ││──────────────────────── │ │ ││──────────────────┬───── │ │q0 ││ 0000 │000A │ │ ││──────────────────┴───── │ │ ││──────────────────────── │ │q1 ││ 0000 │ │ ││──────────────────────── │ └─────────────┘└───────────────────────────────────────────┘ |}]; test Write_before_read; [%expect {| ┌Signals──────┐┌Waves──────────────────────────────────────┐ │ ││────────────┬─────────── │ │read_address1││ 00 │0D │ │ ││────────────┴─────────── │ │ ││──────────────────────── │ │read_address2││ 00 │ │ ││──────────────────────── │ │read_clock1 ││ │ │ ││──────────────────────── │ │read_clock2 ││ │ │ ││──────────────────────── │ │read_enable1 ││ ┌─────┐ │ │ ││────────────┘ └───── │ │read_enable2 ││ │ │ ││──────────────────────── │ │ ││──────┬───────────────── │ │write_address││ 00 │0D │ │ ││──────┴───────────────── │ │ ││──────────────────────── │ │write_address││ 00 │ │ ││──────────────────────── │ │write_clock1 ││ │ │ ││──────────────────────── │ │write_clock2 ││ │ │ ││──────────────────────── │ │ ││──────┬─────┬─────────── │ │write_data1 ││ 0000 │000A │0014 │ │ ││──────┴─────┴─────────── │ │ ││──────────────────────── │ │write_data2 ││ 0000 │ │ ││──────────────────────── │ │write_enable1││ ┌───────────┐ │ │ ││──────┘ └───── │ │write_enable2││ │ │ ││──────────────────────── │ │ ││──────────────────┬───── │ │q0 ││ 0000 │0014 │ │ ││──────────────────┴───── │ │ ││──────────────────────── │ │q1 ││ 0000 │ │ ││──────────────────────── │ └─────────────┘└───────────────────────────────────────────┘ |}] ;;
a52467b9f95fad8a58642e78debfb50ae23e8232c13edf044f575fbe00fd2d61
naoto-ogawa/h-xproto-mysql
CapabilitiesGet.hs
# LANGUAGE BangPatterns , DeriveDataTypeable , DeriveGeneric , FlexibleInstances , MultiParamTypeClasses # # OPTIONS_GHC -fno - warn - unused - imports # module Com.Mysql.Cj.Mysqlx.Protobuf.CapabilitiesGet (CapabilitiesGet(..)) where import Prelude ((+), (/)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified GHC.Generics as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data CapabilitiesGet = CapabilitiesGet{} deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic) instance P'.Mergeable CapabilitiesGet where mergeAppend CapabilitiesGet CapabilitiesGet = CapabilitiesGet instance P'.Default CapabilitiesGet where defaultValue = CapabilitiesGet instance P'.Wire CapabilitiesGet where wireSize ft' self'@(CapabilitiesGet) = case ft' of 10 -> calc'Size 11 -> P'.prependMessageSize calc'Size _ -> P'.wireSizeErr ft' self' where calc'Size = 0 wirePut ft' self'@(CapabilitiesGet) = case ft' of 10 -> put'Fields 11 -> do P'.putSize (P'.wireSize 10 self') put'Fields _ -> P'.wirePutErr ft' self' where put'Fields = do Prelude'.return () wireGet ft' = case ft' of 10 -> P'.getBareMessageWith update'Self 11 -> P'.getMessageWith update'Self _ -> P'.wireGetErr ft' where update'Self wire'Tag old'Self = case wire'Tag of _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self instance P'.MessageAPI msg' (msg' -> CapabilitiesGet) CapabilitiesGet where getVal m' f' = f' m' instance P'.GPB CapabilitiesGet instance P'.ReflectDescriptor CapabilitiesGet where getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList []) reflectDescriptorInfo _ = Prelude'.read "DescriptorInfo {descName = ProtoName {protobufName = FIName \".Mysqlx.Connection.CapabilitiesGet\", haskellPrefix = [], parentModule = [MName \"Com\",MName \"Mysql\",MName \"Cj\",MName \"Mysqlx\",MName \"Protobuf\"], baseName = MName \"CapabilitiesGet\"}, descFilePath = [\"Com\",\"Mysql\",\"Cj\",\"Mysqlx\",\"Protobuf\",\"CapabilitiesGet.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}" instance P'.TextType CapabilitiesGet where tellT = P'.tellSubMessage getT = P'.getSubMessage instance P'.TextMsg CapabilitiesGet where textPut msg = Prelude'.return () textGet = Prelude'.return P'.defaultValue where
null
https://raw.githubusercontent.com/naoto-ogawa/h-xproto-mysql/1eacd6486c99b849016bf088788cb8d8b166f964/src/Com/Mysql/Cj/Mysqlx/Protobuf/CapabilitiesGet.hs
haskell
# LANGUAGE BangPatterns , DeriveDataTypeable , DeriveGeneric , FlexibleInstances , MultiParamTypeClasses # # OPTIONS_GHC -fno - warn - unused - imports # module Com.Mysql.Cj.Mysqlx.Protobuf.CapabilitiesGet (CapabilitiesGet(..)) where import Prelude ((+), (/)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified GHC.Generics as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data CapabilitiesGet = CapabilitiesGet{} deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic) instance P'.Mergeable CapabilitiesGet where mergeAppend CapabilitiesGet CapabilitiesGet = CapabilitiesGet instance P'.Default CapabilitiesGet where defaultValue = CapabilitiesGet instance P'.Wire CapabilitiesGet where wireSize ft' self'@(CapabilitiesGet) = case ft' of 10 -> calc'Size 11 -> P'.prependMessageSize calc'Size _ -> P'.wireSizeErr ft' self' where calc'Size = 0 wirePut ft' self'@(CapabilitiesGet) = case ft' of 10 -> put'Fields 11 -> do P'.putSize (P'.wireSize 10 self') put'Fields _ -> P'.wirePutErr ft' self' where put'Fields = do Prelude'.return () wireGet ft' = case ft' of 10 -> P'.getBareMessageWith update'Self 11 -> P'.getMessageWith update'Self _ -> P'.wireGetErr ft' where update'Self wire'Tag old'Self = case wire'Tag of _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self instance P'.MessageAPI msg' (msg' -> CapabilitiesGet) CapabilitiesGet where getVal m' f' = f' m' instance P'.GPB CapabilitiesGet instance P'.ReflectDescriptor CapabilitiesGet where getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList []) reflectDescriptorInfo _ = Prelude'.read "DescriptorInfo {descName = ProtoName {protobufName = FIName \".Mysqlx.Connection.CapabilitiesGet\", haskellPrefix = [], parentModule = [MName \"Com\",MName \"Mysql\",MName \"Cj\",MName \"Mysqlx\",MName \"Protobuf\"], baseName = MName \"CapabilitiesGet\"}, descFilePath = [\"Com\",\"Mysql\",\"Cj\",\"Mysqlx\",\"Protobuf\",\"CapabilitiesGet.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}" instance P'.TextType CapabilitiesGet where tellT = P'.tellSubMessage getT = P'.getSubMessage instance P'.TextMsg CapabilitiesGet where textPut msg = Prelude'.return () textGet = Prelude'.return P'.defaultValue where
72014c796cb15e4452fb34100e80f073505e3232f1ed9ceef55c26994c07cff0
sydow/ireal
Integrals.hs
module Integrals where import Data.Number.IReal import Taylor integral k d f i = try eps i where eps = 10 ^^ (-d) evens (x:_:xs) = x : evens xs try eps i | w < eps = approx + ((-w) -+- w) | otherwise = try eps2 (lower i -+- m) + try eps2 (m -+- upper i) where eps2 = scale eps (-1) m = mid i approx = 2 * sum (take (k `div` 2 + 1) (evens (zipWith (*) ts rs))) w = upper (abs (prec d $ (ts2!!k - ts!!k))) * rs!!k * 2 ts = taylorCoeffs f m ts2 = taylorCoeffs f i rs = zipWith (/) (iterate (*rad i) (rad i)) [1..] arcLength k eps f = integral where g x = sqrt ( 1 + deriv 1 f x ^ 2 ) arcLength k eps f = integral k eps g where g x = sqrt (1 + deriv 1 f x ^ 2) -}
null
https://raw.githubusercontent.com/sydow/ireal/c06438544c711169baac7960540202379f9294b1/applications/Integrals.hs
haskell
module Integrals where import Data.Number.IReal import Taylor integral k d f i = try eps i where eps = 10 ^^ (-d) evens (x:_:xs) = x : evens xs try eps i | w < eps = approx + ((-w) -+- w) | otherwise = try eps2 (lower i -+- m) + try eps2 (m -+- upper i) where eps2 = scale eps (-1) m = mid i approx = 2 * sum (take (k `div` 2 + 1) (evens (zipWith (*) ts rs))) w = upper (abs (prec d $ (ts2!!k - ts!!k))) * rs!!k * 2 ts = taylorCoeffs f m ts2 = taylorCoeffs f i rs = zipWith (/) (iterate (*rad i) (rad i)) [1..] arcLength k eps f = integral where g x = sqrt ( 1 + deriv 1 f x ^ 2 ) arcLength k eps f = integral k eps g where g x = sqrt (1 + deriv 1 f x ^ 2) -}
8d0835341d546d007ebc248bff1cb9055fc12a849920ccb638c453a68e57acca
esl/MongooseIM
mongoose_graphql_admin_query.erl
-module(mongoose_graphql_admin_query). -behaviour(mongoose_graphql). -export([execute/4]). -ignore_xref([execute/4]). -include("../mongoose_graphql_types.hrl"). execute(_Ctx, _Obj, <<"account">>, _Args) -> {ok, account}; execute(_Ctx, _Obj, <<"checkAuth">>, _Args) -> {ok, admin}; execute(_Ctx, _Obj, <<"domain">>, _Args) -> {ok, admin}; execute(_Ctx, _Obj, <<"gdpr">>, _Args) -> {ok, gdpr}; execute(_Ctx, _Obj, <<"last">>, _Args) -> {ok, last}; execute(_Ctx, _Obj, <<"metric">>, _Args) -> {ok, metric}; execute(_Ctx, _Obj, <<"mnesia">>, _Args) -> {ok, mnesia}; execute(_Ctx, _Obj, <<"muc">>, _Args) -> {ok, muc}; execute(_Ctx, _Obj, <<"muc_light">>, _Args) -> {ok, muc_light}; execute(_Ctx, _Obj, <<"private">>, _Args) -> {ok, private}; execute(_Ctx, _Obj, <<"roster">>, _Args) -> {ok, roster}; execute(_Ctx, _Obj, <<"server">>, _Args) -> {ok, server}; execute(_Ctx, _Obj, <<"session">>, _Args) -> {ok, session}; execute(_Ctx, _Obj, <<"stanza">>, _Args) -> {ok, #{}}; execute(_Ctx, _Obj, <<"stat">>, _Args) -> {ok, stats}; execute(_Ctx, _Obj, <<"vcard">>, _Args) -> {ok, vcard}.
null
https://raw.githubusercontent.com/esl/MongooseIM/584fb592d0b6af53767c90d614542925920bf906/src/graphql/admin/mongoose_graphql_admin_query.erl
erlang
-module(mongoose_graphql_admin_query). -behaviour(mongoose_graphql). -export([execute/4]). -ignore_xref([execute/4]). -include("../mongoose_graphql_types.hrl"). execute(_Ctx, _Obj, <<"account">>, _Args) -> {ok, account}; execute(_Ctx, _Obj, <<"checkAuth">>, _Args) -> {ok, admin}; execute(_Ctx, _Obj, <<"domain">>, _Args) -> {ok, admin}; execute(_Ctx, _Obj, <<"gdpr">>, _Args) -> {ok, gdpr}; execute(_Ctx, _Obj, <<"last">>, _Args) -> {ok, last}; execute(_Ctx, _Obj, <<"metric">>, _Args) -> {ok, metric}; execute(_Ctx, _Obj, <<"mnesia">>, _Args) -> {ok, mnesia}; execute(_Ctx, _Obj, <<"muc">>, _Args) -> {ok, muc}; execute(_Ctx, _Obj, <<"muc_light">>, _Args) -> {ok, muc_light}; execute(_Ctx, _Obj, <<"private">>, _Args) -> {ok, private}; execute(_Ctx, _Obj, <<"roster">>, _Args) -> {ok, roster}; execute(_Ctx, _Obj, <<"server">>, _Args) -> {ok, server}; execute(_Ctx, _Obj, <<"session">>, _Args) -> {ok, session}; execute(_Ctx, _Obj, <<"stanza">>, _Args) -> {ok, #{}}; execute(_Ctx, _Obj, <<"stat">>, _Args) -> {ok, stats}; execute(_Ctx, _Obj, <<"vcard">>, _Args) -> {ok, vcard}.
3ad15ad527841ec13e7034cb867fc3109f8c033024805c1d812cc304efe20012
AmpersandTarski/Ampersand
Input.hs
module Ampersand.Input ( module Ampersand.Input.ADL1.CtxError, module Ampersand.Input.Parsing, ) where import Ampersand.Input.ADL1.CtxError import Ampersand.Input.Parsing
null
https://raw.githubusercontent.com/AmpersandTarski/Ampersand/cb2306a09ce79d5609ccf8d3e28c0a1eb45feafe/src/Ampersand/Input.hs
haskell
module Ampersand.Input ( module Ampersand.Input.ADL1.CtxError, module Ampersand.Input.Parsing, ) where import Ampersand.Input.ADL1.CtxError import Ampersand.Input.Parsing
9819c5aafda7b17f469ffb7b8fd0eb6165ae78f441a028f4a76c4d9821fb5cb5
karlhof26/gimp-scheme
FU_sketch_pastel-image.scm
; FU_sketch_pastel-image.scm version 2.9 [ gimphelp.org ] last modified / tested by 02/15/2014 on GIMP-2.8.10 ; ; 02/15/2014 - accommodated indexed images ;============================================================== ; ; Installation: ; This script should be placed in the user or system-wide script folder. ; ; Windows Vista/7/8) C:\Program Files\GIMP 2\share\gimp\2.0\scripts ; or C:\Users\YOUR - NAME\.gimp-2.8\scripts ; Windows XP C:\Program Files\GIMP 2\share\gimp\2.0\scripts ; or ; C:\Documents and Settings\yourname\.gimp-2.8\scripts ; ; Linux /home / yourname/.gimp-2.8 / scripts ; or ; Linux system-wide ; /usr/share/gimp/2.0/scripts ; ;============================================================== ; ; LICENSE ; ; 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 </>. ; ;============================================================== ; Original information ; Pastel image script for GIMP 2.4 Copyright ( C ) 2001 Iccii < > Modified for GIMP 2.x by ; ; Author statement: ; This script is based on pastel-windows100.scm ; Reference Book Windows100 % Magazine October , 2001 Tamagorou 's Photograph touching up class No.29 ; theme 1 -- Create the Pastel image ;============================================================== (define (FU-pastel-image img drawable detail length amount angle canvas? ) (gimp-image-undo-group-start img) (define indexed (car (gimp-drawable-is-indexed drawable))) (if (= indexed TRUE)(gimp-image-convert-rgb img)) (let* ( (old-selection (car (gimp-selection-save img))) (layer-copy0 (car (gimp-layer-copy drawable TRUE))) (dummy (gimp-image-insert-layer img layer-copy0 0 -1)) (dummy (if (< 0 (car (gimp-layer-get-mask layer-copy0))) (gimp-layer-remove-mask layer-copy0 MASK-DISCARD))) (layer-copy1 (car (gimp-layer-copy layer-copy0 TRUE))) (length (if (= length 1) 0 length)) (dummy (begin (plug-in-mblur TRUE img layer-copy0 0 length angle 0 0 ) (plug-in-mblur TRUE img layer-copy0 0 length (+ angle 180) 0 0 ) ) ) (layer-copy2 (car (gimp-layer-copy layer-copy0 TRUE))) (marged-layer) (final-layer) ) (gimp-image-insert-layer img layer-copy2 0 -1) (gimp-image-insert-layer img layer-copy1 0 -1) (plug-in-gauss-iir TRUE img layer-copy1 (- 16 detail) TRUE TRUE) (plug-in-edge TRUE img layer-copy1 10.0 1 0) (gimp-layer-set-mode layer-copy1 LAYER-MODE-DIVIDE-LEGACY) (set! marged-layer (car (gimp-image-merge-down img layer-copy1 EXPAND-AS-NECESSARY))) (gimp-layer-set-mode marged-layer LAYER-MODE-HSV-VALUE-LEGACY) ; Value-mode ; Add the canvas if asked to (if (equal? canvas? TRUE) (plug-in-apply-canvas TRUE img marged-layer 0 5) ) (plug-in-unsharp-mask TRUE img layer-copy0 (+ 1 (/ length 5)) amount 0) (set! final-layer (car (gimp-image-merge-down img marged-layer EXPAND-AS-NECESSARY))) (gimp-image-select-item img CHANNEL-OP-REPLACE old-selection) (gimp-edit-copy final-layer) (gimp-image-remove-layer img final-layer) (gimp-floating-sel-anchor (car (gimp-edit-paste drawable 0))) (gimp-image-select-item img CHANNEL-OP-REPLACE old-selection) (gimp-image-remove-channel img old-selection) ; Clean up (gimp-image-undo-group-end img) (gimp-displays-flush) ) ) (script-fu-register "FU-pastel-image" "<Image>/Script-Fu/Artist/Pastel Sketch" "Create the Pastel image. \nfile:FU_sketch_pastel-image.scm" "Iccii <>" "Iccii" "2001, Oct" "*" SF-IMAGE "Image" 0 SF-DRAWABLE "Drawable" 0 SF-ADJUSTMENT "Detail Level" '(12.0 0 15.0 0.1 0.5 1 1) SF-ADJUSTMENT "Sketch Length" '(10 0 32 1 1 0 1) SF-ADJUSTMENT "Sketch Amount" '(1.0 0 5.0 0.1 0.5 1 1) SF-ADJUSTMENT "Angle" '(45 0 180 1 15 0 0) SF-TOGGLE "Add the canvas texture" FALSE ) ; end of script
null
https://raw.githubusercontent.com/karlhof26/gimp-scheme/ed9c875dc25ab1d9712e70b84d86151663e0a097/FU_sketch_pastel-image.scm
scheme
FU_sketch_pastel-image.scm 02/15/2014 - accommodated indexed images ============================================================== Installation: This script should be placed in the user or system-wide script folder. Windows Vista/7/8) or or C:\Documents and Settings\yourname\.gimp-2.8\scripts Linux or Linux system-wide /usr/share/gimp/2.0/scripts ============================================================== LICENSE 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 </>. ============================================================== Original information Author statement: This script is based on pastel-windows100.scm Reference Book theme 1 -- Create the Pastel image ============================================================== Value-mode Add the canvas if asked to Clean up end of script
version 2.9 [ gimphelp.org ] last modified / tested by 02/15/2014 on GIMP-2.8.10 C:\Program Files\GIMP 2\share\gimp\2.0\scripts C:\Users\YOUR - NAME\.gimp-2.8\scripts Windows XP C:\Program Files\GIMP 2\share\gimp\2.0\scripts /home / yourname/.gimp-2.8 / scripts 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 Pastel image script for GIMP 2.4 Copyright ( C ) 2001 Iccii < > Modified for GIMP 2.x by Windows100 % Magazine October , 2001 Tamagorou 's Photograph touching up class No.29 (define (FU-pastel-image img drawable detail length amount angle canvas? ) (gimp-image-undo-group-start img) (define indexed (car (gimp-drawable-is-indexed drawable))) (if (= indexed TRUE)(gimp-image-convert-rgb img)) (let* ( (old-selection (car (gimp-selection-save img))) (layer-copy0 (car (gimp-layer-copy drawable TRUE))) (dummy (gimp-image-insert-layer img layer-copy0 0 -1)) (dummy (if (< 0 (car (gimp-layer-get-mask layer-copy0))) (gimp-layer-remove-mask layer-copy0 MASK-DISCARD))) (layer-copy1 (car (gimp-layer-copy layer-copy0 TRUE))) (length (if (= length 1) 0 length)) (dummy (begin (plug-in-mblur TRUE img layer-copy0 0 length angle 0 0 ) (plug-in-mblur TRUE img layer-copy0 0 length (+ angle 180) 0 0 ) ) ) (layer-copy2 (car (gimp-layer-copy layer-copy0 TRUE))) (marged-layer) (final-layer) ) (gimp-image-insert-layer img layer-copy2 0 -1) (gimp-image-insert-layer img layer-copy1 0 -1) (plug-in-gauss-iir TRUE img layer-copy1 (- 16 detail) TRUE TRUE) (plug-in-edge TRUE img layer-copy1 10.0 1 0) (gimp-layer-set-mode layer-copy1 LAYER-MODE-DIVIDE-LEGACY) (set! marged-layer (car (gimp-image-merge-down img layer-copy1 EXPAND-AS-NECESSARY))) (if (equal? canvas? TRUE) (plug-in-apply-canvas TRUE img marged-layer 0 5) ) (plug-in-unsharp-mask TRUE img layer-copy0 (+ 1 (/ length 5)) amount 0) (set! final-layer (car (gimp-image-merge-down img marged-layer EXPAND-AS-NECESSARY))) (gimp-image-select-item img CHANNEL-OP-REPLACE old-selection) (gimp-edit-copy final-layer) (gimp-image-remove-layer img final-layer) (gimp-floating-sel-anchor (car (gimp-edit-paste drawable 0))) (gimp-image-select-item img CHANNEL-OP-REPLACE old-selection) (gimp-image-remove-channel img old-selection) (gimp-image-undo-group-end img) (gimp-displays-flush) ) ) (script-fu-register "FU-pastel-image" "<Image>/Script-Fu/Artist/Pastel Sketch" "Create the Pastel image. \nfile:FU_sketch_pastel-image.scm" "Iccii <>" "Iccii" "2001, Oct" "*" SF-IMAGE "Image" 0 SF-DRAWABLE "Drawable" 0 SF-ADJUSTMENT "Detail Level" '(12.0 0 15.0 0.1 0.5 1 1) SF-ADJUSTMENT "Sketch Length" '(10 0 32 1 1 0 1) SF-ADJUSTMENT "Sketch Amount" '(1.0 0 5.0 0.1 0.5 1 1) SF-ADJUSTMENT "Angle" '(45 0 180 1 15 0 0) SF-TOGGLE "Add the canvas texture" FALSE )
f9b95fcb062a000eb903a58990d2cdde2f36ef32b3e2a21ca540f17471eac70e
acl2/acl2
lg.lisp
Base-2 integer logarithm ; Copyright ( C ) 2008 - 2011 and Stanford University Copyright ( C ) 2013 - 2023 Kestrel Institute ; License : A 3 - clause BSD license . See the file books/3BSD - mod.txt . ; Author : ( ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") See also and ceiling-of-lg.lisp . TODO : Deprecate this book in favor of . ;TODO: Which do we prefer, lg or log2, or integer-length? Some rules about ;integer-length could be adapted to target lg or log2. (include-book "power-of-2p") (local (include-book "integer-length")) (local (include-book "expt2")) (local (include-book "plus")) (local (include-book "floor")) ;; Returns the floor of the base-2 logarithm of x, which must be a positive integer. ;; TODO: Rename lg to floor-of-lg ? ;; TODO: what should lg of 0 be? (defund lg (x) (declare (xargs :guard (posp x) :split-types t) (type integer x)) (+ -1 (integer-length x))) (defthm lg-of-expt (implies (natp x) (equal (lg (expt 2 x)) x)) :hints (("Goal" :in-theory (enable lg)))) ( defthmd lg - of - both - sides ;; (implies (equal x y) ;; (equal (lg x) (lg y)))) ;todo: lg of mask? (defthm equal-of-0-and-lg (implies (natp k) (equal (equal 0 (lg k)) (equal 1 k))) :hints (("Goal" :in-theory (enable lg integer-length)))) (defthm natp-of-lg (implies (natp x) (equal (natp (lg x)) (posp x))) :hints (("Goal" :in-theory (enable lg)))) todo : prove something about integer - length first ? (defthm posp-of-lg (implies (natp x) (equal (posp (lg x)) (< 1 x))) :hints (("Goal" :cases ((< 1 X)) :in-theory (enable lg integer-length)))) (defthm natp-of-lg-type (implies (posp x) (natp (lg x))) :rule-classes :type-prescription) (defthm expt-of-lg-when-power-of-2p (implies (power-of-2p x) (equal (expt 2 (lg x)) x)) :hints (("Goal" :in-theory (enable power-of-2p lg)))) These next two help show that LG is correct : (defthm <=-of-expt-2-of-lg-linear (implies (posp x) (<= (expt 2 (lg x)) x)) :rule-classes :linear :hints (("Goal" :in-theory (enable lg)))) (defthm <=-of-expt-2-of-+-of-1-and-lg-linear (implies (posp x) (< x (expt 2 (+ 1 (lg x))))) :rule-classes :linear :hints (("Goal" :in-theory (enable lg)))) (defthm <-of-expt-2-of-lg-same (implies (posp x) (equal (< (expt 2 (lg x)) x) (not (power-of-2p x)))) :hints (("Goal" :in-theory (enable lg)))) (defthm <-of-expt-2-of-lg-same-linear (implies (and (not (power-of-2p x)) (posp x)) (< (expt 2 (lg x)) x)) :rule-classes :linear :hints (("Goal" :in-theory (enable lg)))) (defthm <-of-lg-and-0 (implies (integerp x) (equal (< (lg x) 0) (or (equal x 0) (equal x -1)))) :hints (("Goal" :in-theory (enable lg)))) (defthm lg-of-*-of-1/2 (implies (and (evenp x) (rationalp x)) (equal (lg (* 1/2 x)) (if (equal 0 x) -1 (+ -1 (lg x))))) :hints (("Goal" :in-theory (enable lg)))) (defthmd <-of-lg-when-unsigned-byte-p (implies (unsigned-byte-p n x) (< (lg x) n)) :hints (("Goal" :cases ((equal x 0)) :in-theory (enable lg)))) (defthm <-of-lg-when-unsigned-byte-p-cheap (implies (unsigned-byte-p n x) (< (lg x) n)) :rule-classes ((:rewrite :backchain-limit-lst (0))) :hints (("Goal" :cases ((equal x 0)) :in-theory (enable lg))))
null
https://raw.githubusercontent.com/acl2/acl2/4a7cd3dee752dfbf8e390f67de6a1d2e6f604f7e/books/kestrel/arithmetic-light/lg.lisp
lisp
TODO: Which do we prefer, lg or log2, or integer-length? Some rules about integer-length could be adapted to target lg or log2. Returns the floor of the base-2 logarithm of x, which must be a positive integer. TODO: Rename lg to floor-of-lg ? TODO: what should lg of 0 be? (implies (equal x y) (equal (lg x) (lg y)))) todo: lg of mask?
Base-2 integer logarithm Copyright ( C ) 2008 - 2011 and Stanford University Copyright ( C ) 2013 - 2023 Kestrel Institute License : A 3 - clause BSD license . See the file books/3BSD - mod.txt . Author : ( ) (in-package "ACL2") See also and ceiling-of-lg.lisp . TODO : Deprecate this book in favor of . (include-book "power-of-2p") (local (include-book "integer-length")) (local (include-book "expt2")) (local (include-book "plus")) (local (include-book "floor")) (defund lg (x) (declare (xargs :guard (posp x) :split-types t) (type integer x)) (+ -1 (integer-length x))) (defthm lg-of-expt (implies (natp x) (equal (lg (expt 2 x)) x)) :hints (("Goal" :in-theory (enable lg)))) ( defthmd lg - of - both - sides (defthm equal-of-0-and-lg (implies (natp k) (equal (equal 0 (lg k)) (equal 1 k))) :hints (("Goal" :in-theory (enable lg integer-length)))) (defthm natp-of-lg (implies (natp x) (equal (natp (lg x)) (posp x))) :hints (("Goal" :in-theory (enable lg)))) todo : prove something about integer - length first ? (defthm posp-of-lg (implies (natp x) (equal (posp (lg x)) (< 1 x))) :hints (("Goal" :cases ((< 1 X)) :in-theory (enable lg integer-length)))) (defthm natp-of-lg-type (implies (posp x) (natp (lg x))) :rule-classes :type-prescription) (defthm expt-of-lg-when-power-of-2p (implies (power-of-2p x) (equal (expt 2 (lg x)) x)) :hints (("Goal" :in-theory (enable power-of-2p lg)))) These next two help show that LG is correct : (defthm <=-of-expt-2-of-lg-linear (implies (posp x) (<= (expt 2 (lg x)) x)) :rule-classes :linear :hints (("Goal" :in-theory (enable lg)))) (defthm <=-of-expt-2-of-+-of-1-and-lg-linear (implies (posp x) (< x (expt 2 (+ 1 (lg x))))) :rule-classes :linear :hints (("Goal" :in-theory (enable lg)))) (defthm <-of-expt-2-of-lg-same (implies (posp x) (equal (< (expt 2 (lg x)) x) (not (power-of-2p x)))) :hints (("Goal" :in-theory (enable lg)))) (defthm <-of-expt-2-of-lg-same-linear (implies (and (not (power-of-2p x)) (posp x)) (< (expt 2 (lg x)) x)) :rule-classes :linear :hints (("Goal" :in-theory (enable lg)))) (defthm <-of-lg-and-0 (implies (integerp x) (equal (< (lg x) 0) (or (equal x 0) (equal x -1)))) :hints (("Goal" :in-theory (enable lg)))) (defthm lg-of-*-of-1/2 (implies (and (evenp x) (rationalp x)) (equal (lg (* 1/2 x)) (if (equal 0 x) -1 (+ -1 (lg x))))) :hints (("Goal" :in-theory (enable lg)))) (defthmd <-of-lg-when-unsigned-byte-p (implies (unsigned-byte-p n x) (< (lg x) n)) :hints (("Goal" :cases ((equal x 0)) :in-theory (enable lg)))) (defthm <-of-lg-when-unsigned-byte-p-cheap (implies (unsigned-byte-p n x) (< (lg x) n)) :rule-classes ((:rewrite :backchain-limit-lst (0))) :hints (("Goal" :cases ((equal x 0)) :in-theory (enable lg))))
5faef94516da669adaf889e82c1227d63bb2d597f18c0cfcdc05c59917b18280
ocaml-sf/learn-ocaml-corpus
template.ml
module CharHashedType = struct (* replace this structure with your implementation *) end module CharHashtbl = struct (* replace this structure with your implementation *) end module Trie : GenericTrie with type 'a char_table = 'a CharHashtbl.t = struct type 'a char_table = 'a CharHashtbl.t type 'a trie = Trie of 'a option * 'a trie char_table let empty () = "Replace this string with your implementation." ;; let lookup trie w = "Replace this string with your implementation." ;; let insert trie w v = "Replace this string with your implementation." ;; end
null
https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/mooc/week6/seq3/ex1/template.ml
ocaml
replace this structure with your implementation replace this structure with your implementation
module CharHashedType = module CharHashtbl = module Trie : GenericTrie with type 'a char_table = 'a CharHashtbl.t = struct type 'a char_table = 'a CharHashtbl.t type 'a trie = Trie of 'a option * 'a trie char_table let empty () = "Replace this string with your implementation." ;; let lookup trie w = "Replace this string with your implementation." ;; let insert trie w v = "Replace this string with your implementation." ;; end
6896ce3befc7f7b1815433c99a2772455d43c1668abcf3b11254f4d977653900
mattmundell/nightshade
pick-new-file.lisp
;;; Tests of `lisp:pick-new-file'. (in-package "LISP") (import '(deftest:deftest deftest:with-test-dir deftest:with-test-search-list)) ;;;; Auto argument. (deftest pick-new-file (t pick-new-file-1) "Test `pick-new-file', picking a single name." (let ((file (pick-new-file))) (prog1 (if (probe-file file) t) (delete-file file)))) (deftest pick-new-file (t pick-new-file-2) "Test `pick-new-file', picking many names." (collect ((names)) (unwind-protect (progn (dotimes (num 40) (names (pick-new-file))) (fi (duplicatesp (names)) (and (eq (length (names)) 40) (dolist (file (names) t) (or (probe-file file) (return-from pick-new-file-2 ())))))) (dolist (name (names)) (delete-file name))))) (deftest pick-new-file (() pick-new-file-3) "Test `pick-new-file' where the first choice exists already." (let ((name (format () "/tmp/a~D-~D" (unix:unix-getpid) (1+ *last-new-code*)))) (touch-file name) (let ((new (pick-new-file "/tmp/a~D-~D"))) (prog1 (string= (namestring name) (namestring new)) (if (probe-file name) (delete-file name)) (if (probe-file new) (delete-file new)))))) ;;;; File argument. (deftest pick-new-file (t pick-new-file-20) "Test `pick-new-file', passing an absolute file name arg." (with-test-dir (dir) (let ((file (pick-new-file (namestring (merge-pathnames "pick-new-~D-~D" dir))))) (prog1 (if (probe-file file) t) (delete-file file))))) (deftest pick-new-file (t pick-new-file-21) "Test `pick-new-file', passing a relative file name arg." (with-test-dir (dir "eg") (in-directory dir (let ((file (pick-new-file "pick-new-file-test-~D-~D.c"))) (prog1 (if (probe-file file) t) (delete-file file)))))) (deftest pick-new-file (t pick-new-file-22) "Test `pick-new-file', picking many times, passing the same absolute file name arg each time." (with-test-dir (dir "zz/zz/" "zz/zz/zz") (collect ((names)) (dotimes (num 80) (names (pick-new-file (namestring (merge-pathnames "pick test ~D-~D" dir))))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ())))))))) (deftest pick-new-file (t pick-new-file-23) "Test `pick-new-file', picking many times, passing the same relative file name arg each time." (with-test-dir (dir) (in-directory dir (collect ((names)) (dotimes (num 80) (names (pick-new-file "~D~D"))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ()))))))))) ;;;; Hidden file argument. (deftest pick-new-file (t pick-new-file-30) "Test `pick-new-file', passing an absolute hidden file name arg." (with-test-dir (dir) (let ((file (pick-new-file (namestring (merge-pathnames ".pick-new-~D-~D" dir))))) (prog1 (if (probe-file file) t) (delete-file file))))) (deftest pick-new-file (t pick-new-file-31) "Test `pick-new-file', passing a relative hidden file name arg." (with-test-dir (dir "abc.Z") (in-directory dir (let ((file (pick-new-file ".pick-new-file-test-~D-~D"))) (prog1 (if (probe-file file) t) (delete-file file)))))) (deftest pick-new-file (t pick-new-file-32) "Test `pick-new-file', picking many times, passing the same absolute hidden file name arg each time." (with-test-dir (dir ".pick-test-1-1") (collect ((names)) (dotimes (num 80) (names (pick-new-file (namestring (merge-pathnames ".pick-test-~D-~D" dir))))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ())))))))) (deftest pick-new-file (t pick-new-file-33) "Test `pick-new-file', picking many times, passing the same relative hidden file name arg each time." (with-test-dir (dir) (in-directory dir (collect ((names)) (dotimes (num 80) (names (pick-new-file ".~D~D"))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ()))))))))) ;;;; Backup file argument. (deftest pick-new-file (t pick-new-file-40) "Test `pick-new-file', passing an absolute file backup name arg." (with-test-dir (dir) (let ((file (pick-new-file (namestring (merge-pathnames "pick-new-~D-~D~~" dir))))) (prog1 (if (probe-file file) t) (delete-file file))))) (deftest pick-new-file (t pick-new-file-41) "Test `pick-new-file', passing a relative backup file name arg." (with-test-dir (dir "pick-1000-1000.BAK" "a/b/") (in-directory dir (let ((file (pick-new-file "pick-~D-~D.BAK"))) (prog1 (if (probe-file file) t) (delete-file file)))))) (deftest pick-new-file (t pick-new-file-42) "Test `pick-new-file', picking many times, passing the same absolute file name arg each time." (with-test-dir (dir) (collect ((names)) (dotimes (num 80) (names (pick-new-file (namestring (merge-pathnames "pick-test-~D-~D.CKP" dir))))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ())))))))) (deftest pick-new-file (t pick-new-file-43) "Test `pick-new-file', picking many times, passing the same relative file name arg each time." (with-test-dir (dir) (in-directory dir (collect ((names)) (dotimes (num 80) (names (pick-new-file ",pick-test-~D-~D.BAK"))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ()))))))))) ;;;; Search list argument. (deftest pick-new-file (t pick-new-file-50) "Test `pick-new-file', passing a search list file name arg." (with-test-dir (dir "a" "b" "c/d/") (with-test-search-list ("a" dir) (let ((file (pick-new-file (namestring (merge-pathnames "a:pick-new-~D-~D" dir))))) (prog1 (if (probe-file file) t) (delete-file file)))))) (deftest pick-new-file (t pick-new-file-51) "Test `pick-new-file', picking many times, passing the same search list file name arg each time." (with-test-dir (dir) (with-test-search-list ("a" dir) (collect ((names)) (dotimes (num 80) (names (pick-new-file (namestring (merge-pathnames "a:pick-test-~D-~D" dir))))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ()))))))))) ;;;; Symlink argument. (deftest pick-new-file (t pick-new-file-60) "Test `pick-new-file', passing an absolute file name arg with a symlink in the path." (with-test-dir (dir "b/" ("l" "b/")) (let ((file (pick-new-file (namestring (merge-pathnames "l/pick-new-~D-~D" dir))))) (prog1 (if (probe-file file) t) (delete-file file))))) (deftest pick-new-file (t pick-new-file-61) "Test `pick-new-file', passing a relative file name arg with a symlink in the path." (with-test-dir (dir "b/" ("l" "b/")) (in-directory dir (let ((file (pick-new-file "l/pick-new-file-test-~D-~D"))) (prog1 (if (probe-file file) t) (delete-file file)))))) (deftest pick-new-file (t pick-new-file-62) "Test `pick-new-file', picking many times, passing the same absolute file name arg with a symlink in the path." (with-test-dir (dir "b/" ("l" "b/")) (collect ((names)) (dotimes (num 80) (names (pick-new-file (namestring (merge-pathnames "l/pick-test-~D-~D" dir))))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ())))))))) (deftest pick-new-file (t pick-new-file-63) "Test `pick-new-file', picking many times, passing the same relative search list file name arg with a symlink in the path." (with-test-dir (dir "b/" ("l" "b/")) (in-directory dir (collect ((names)) (dotimes (num 80) (names (pick-new-file "l/pick-test-~D-~D"))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ()))))))))) ;;;; Relative pathname argument. (deftest pick-new-file (t pick-new-file-71) "Test `pick-new-file', passing a relative file name arg with a relative pathname." (with-test-dir (dir "a/b/") (in-directory dir (in-directory "a/b/" (let ((file (pick-new-file "../../pick-new-file-test-~D-~D"))) (prog1 (if (probe-file file) (string= (namestring (truename (directory-namestring file))) (namestring dir))) (delete-file file))))))) (deftest pick-new-file (t pick-new-file-72) "Test `pick-new-file', picking many times, passing the same relative search list file name arg with a relative pathname." (with-test-dir (dir "a/b/") (in-directory (merge-pathnames "a/b/" dir) (collect ((names)) (dotimes (num 80) (names (pick-new-file "../pick-test-~D-~D"))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ())) (or (string= (namestring (truename (directory-namestring file))) (namestring (merge-pathnames "a/" dir))) (return ()))))))))) (deftest pick-new-file (t pick-new-file-73) "Test `pick-new-file', passing a relative file name arg with a relative pathname." (with-test-dir (dir "a/b/") (in-directory dir (let ((file (pick-new-file "./pick-new-file-test-~D-~D"))) (prog1 (if (probe-file file) (string= (namestring (truename (directory-namestring file))) (namestring dir))) (delete-file file)))))) (deftest pick-new-file (t pick-new-file-74) "Test `pick-new-file', picking many times, passing the same relative search list file name arg with a relative pathname." (with-test-dir (dir "a/b/") (in-directory (merge-pathnames "a/b/" dir) (collect ((names)) (dotimes (num 80) (names (pick-new-file ".././pick-test-~D-~D"))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ())) (or (string= (namestring (truename (directory-namestring file))) (namestring (merge-pathnames "a/" dir))) (return ()))))))))) ;;;; Errors. (deftest pick-new-file (t pick-new-file-100) "Test `pick-new-file', passing too few directives." (let (ret) (handler-case (pick-new-file "~D") (error () (setq ret t))) ret)) (deftest pick-new-file (t pick-new-file-101) "Test `pick-new-file', passing an empty string." (let (ret) (handler-case (pick-new-file "") (error () (setq ret t))) ret)) (deftest pick-new-file (t pick-new-file-102) "Test `pick-new-file', passing too many directives." (let (ret) (handler-case (pick-new-file "~D~D~D") (error () (setq ret t))) ret)) (deftest pick-new-file (t pick-new-file-103) "Test `pick-new-file', passing the wrong type of directive." (let (ret) (handler-case (pick-new-file "~A~D") (error () (setq ret t))) ret)) (deftest pick-new-file (t pick-new-file-104) "Test `pick-new-file', passing a pathname with wildcards." (let (ret) (handler-case (pick-new-file "~D~D*") (error () (setq ret t))) ret)) (deftest pick-new-file (t pick-new-file-105) "Test `pick-new-file', passing an empty pathname." (let (ret) (handler-case (pick-new-file ()) (error () (setq ret t))) ret)) (deftest pick-new-file (t pick-new-file-106) "Test `pick-new-file', passing a directory name arg." (let (ret) (deftest:with-test-dir (dir) (handler-case (pick-new-file (merge-pathnames "pick-test-~D-~D/" dir)) (error () (setq ret t)))) ret)) (deftest pick-new-file (t pick-new-file-107) "Test `pick-new-file' on a missing dir." (deftest:with-test-dir (dir) (let (ret) (handler-case (pick-new-file (merge-pathnames "pick-new/file-~D-~D" dir)) (error () (setq ret t))) ret))) (deftest pick-new-file (t pick-new-file-108) "Test `pick-new-file' on a read-blocked dir." (deftest:with-test-dir (dir) (setf (file-mode dir) "a-rwx") (let (ret) (unwind-protect (handler-case (pick-new-file (namestring (merge-pathnames "cde~D~D" dir))) (error () (setq ret t))) (setf (file-mode dir) "a+rwx")) ret))) (deftest pick-new-file (t pick-new-file-109) "Test `pick-new-file' on a symlink to a file." (deftest:with-test-dir (dir "a" ("l" "a")) (let (ret) (handler-case (pick-new-file (namestring (merge-pathnames "l/~D~D" dir))) (error () (setq ret t))) ret)))
null
https://raw.githubusercontent.com/mattmundell/nightshade/7a67f9eac96414355de1463ec251b98237cb4009/src/tests/code/filesys.lisp/pick-new-file.lisp
lisp
Tests of `lisp:pick-new-file'. Auto argument. File argument. Hidden file argument. Backup file argument. Search list argument. Symlink argument. Relative pathname argument. Errors.
(in-package "LISP") (import '(deftest:deftest deftest:with-test-dir deftest:with-test-search-list)) (deftest pick-new-file (t pick-new-file-1) "Test `pick-new-file', picking a single name." (let ((file (pick-new-file))) (prog1 (if (probe-file file) t) (delete-file file)))) (deftest pick-new-file (t pick-new-file-2) "Test `pick-new-file', picking many names." (collect ((names)) (unwind-protect (progn (dotimes (num 40) (names (pick-new-file))) (fi (duplicatesp (names)) (and (eq (length (names)) 40) (dolist (file (names) t) (or (probe-file file) (return-from pick-new-file-2 ())))))) (dolist (name (names)) (delete-file name))))) (deftest pick-new-file (() pick-new-file-3) "Test `pick-new-file' where the first choice exists already." (let ((name (format () "/tmp/a~D-~D" (unix:unix-getpid) (1+ *last-new-code*)))) (touch-file name) (let ((new (pick-new-file "/tmp/a~D-~D"))) (prog1 (string= (namestring name) (namestring new)) (if (probe-file name) (delete-file name)) (if (probe-file new) (delete-file new)))))) (deftest pick-new-file (t pick-new-file-20) "Test `pick-new-file', passing an absolute file name arg." (with-test-dir (dir) (let ((file (pick-new-file (namestring (merge-pathnames "pick-new-~D-~D" dir))))) (prog1 (if (probe-file file) t) (delete-file file))))) (deftest pick-new-file (t pick-new-file-21) "Test `pick-new-file', passing a relative file name arg." (with-test-dir (dir "eg") (in-directory dir (let ((file (pick-new-file "pick-new-file-test-~D-~D.c"))) (prog1 (if (probe-file file) t) (delete-file file)))))) (deftest pick-new-file (t pick-new-file-22) "Test `pick-new-file', picking many times, passing the same absolute file name arg each time." (with-test-dir (dir "zz/zz/" "zz/zz/zz") (collect ((names)) (dotimes (num 80) (names (pick-new-file (namestring (merge-pathnames "pick test ~D-~D" dir))))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ())))))))) (deftest pick-new-file (t pick-new-file-23) "Test `pick-new-file', picking many times, passing the same relative file name arg each time." (with-test-dir (dir) (in-directory dir (collect ((names)) (dotimes (num 80) (names (pick-new-file "~D~D"))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ()))))))))) (deftest pick-new-file (t pick-new-file-30) "Test `pick-new-file', passing an absolute hidden file name arg." (with-test-dir (dir) (let ((file (pick-new-file (namestring (merge-pathnames ".pick-new-~D-~D" dir))))) (prog1 (if (probe-file file) t) (delete-file file))))) (deftest pick-new-file (t pick-new-file-31) "Test `pick-new-file', passing a relative hidden file name arg." (with-test-dir (dir "abc.Z") (in-directory dir (let ((file (pick-new-file ".pick-new-file-test-~D-~D"))) (prog1 (if (probe-file file) t) (delete-file file)))))) (deftest pick-new-file (t pick-new-file-32) "Test `pick-new-file', picking many times, passing the same absolute hidden file name arg each time." (with-test-dir (dir ".pick-test-1-1") (collect ((names)) (dotimes (num 80) (names (pick-new-file (namestring (merge-pathnames ".pick-test-~D-~D" dir))))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ())))))))) (deftest pick-new-file (t pick-new-file-33) "Test `pick-new-file', picking many times, passing the same relative hidden file name arg each time." (with-test-dir (dir) (in-directory dir (collect ((names)) (dotimes (num 80) (names (pick-new-file ".~D~D"))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ()))))))))) (deftest pick-new-file (t pick-new-file-40) "Test `pick-new-file', passing an absolute file backup name arg." (with-test-dir (dir) (let ((file (pick-new-file (namestring (merge-pathnames "pick-new-~D-~D~~" dir))))) (prog1 (if (probe-file file) t) (delete-file file))))) (deftest pick-new-file (t pick-new-file-41) "Test `pick-new-file', passing a relative backup file name arg." (with-test-dir (dir "pick-1000-1000.BAK" "a/b/") (in-directory dir (let ((file (pick-new-file "pick-~D-~D.BAK"))) (prog1 (if (probe-file file) t) (delete-file file)))))) (deftest pick-new-file (t pick-new-file-42) "Test `pick-new-file', picking many times, passing the same absolute file name arg each time." (with-test-dir (dir) (collect ((names)) (dotimes (num 80) (names (pick-new-file (namestring (merge-pathnames "pick-test-~D-~D.CKP" dir))))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ())))))))) (deftest pick-new-file (t pick-new-file-43) "Test `pick-new-file', picking many times, passing the same relative file name arg each time." (with-test-dir (dir) (in-directory dir (collect ((names)) (dotimes (num 80) (names (pick-new-file ",pick-test-~D-~D.BAK"))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ()))))))))) (deftest pick-new-file (t pick-new-file-50) "Test `pick-new-file', passing a search list file name arg." (with-test-dir (dir "a" "b" "c/d/") (with-test-search-list ("a" dir) (let ((file (pick-new-file (namestring (merge-pathnames "a:pick-new-~D-~D" dir))))) (prog1 (if (probe-file file) t) (delete-file file)))))) (deftest pick-new-file (t pick-new-file-51) "Test `pick-new-file', picking many times, passing the same search list file name arg each time." (with-test-dir (dir) (with-test-search-list ("a" dir) (collect ((names)) (dotimes (num 80) (names (pick-new-file (namestring (merge-pathnames "a:pick-test-~D-~D" dir))))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ()))))))))) (deftest pick-new-file (t pick-new-file-60) "Test `pick-new-file', passing an absolute file name arg with a symlink in the path." (with-test-dir (dir "b/" ("l" "b/")) (let ((file (pick-new-file (namestring (merge-pathnames "l/pick-new-~D-~D" dir))))) (prog1 (if (probe-file file) t) (delete-file file))))) (deftest pick-new-file (t pick-new-file-61) "Test `pick-new-file', passing a relative file name arg with a symlink in the path." (with-test-dir (dir "b/" ("l" "b/")) (in-directory dir (let ((file (pick-new-file "l/pick-new-file-test-~D-~D"))) (prog1 (if (probe-file file) t) (delete-file file)))))) (deftest pick-new-file (t pick-new-file-62) "Test `pick-new-file', picking many times, passing the same absolute file name arg with a symlink in the path." (with-test-dir (dir "b/" ("l" "b/")) (collect ((names)) (dotimes (num 80) (names (pick-new-file (namestring (merge-pathnames "l/pick-test-~D-~D" dir))))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ())))))))) (deftest pick-new-file (t pick-new-file-63) "Test `pick-new-file', picking many times, passing the same relative search list file name arg with a symlink in the path." (with-test-dir (dir "b/" ("l" "b/")) (in-directory dir (collect ((names)) (dotimes (num 80) (names (pick-new-file "l/pick-test-~D-~D"))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ()))))))))) (deftest pick-new-file (t pick-new-file-71) "Test `pick-new-file', passing a relative file name arg with a relative pathname." (with-test-dir (dir "a/b/") (in-directory dir (in-directory "a/b/" (let ((file (pick-new-file "../../pick-new-file-test-~D-~D"))) (prog1 (if (probe-file file) (string= (namestring (truename (directory-namestring file))) (namestring dir))) (delete-file file))))))) (deftest pick-new-file (t pick-new-file-72) "Test `pick-new-file', picking many times, passing the same relative search list file name arg with a relative pathname." (with-test-dir (dir "a/b/") (in-directory (merge-pathnames "a/b/" dir) (collect ((names)) (dotimes (num 80) (names (pick-new-file "../pick-test-~D-~D"))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ())) (or (string= (namestring (truename (directory-namestring file))) (namestring (merge-pathnames "a/" dir))) (return ()))))))))) (deftest pick-new-file (t pick-new-file-73) "Test `pick-new-file', passing a relative file name arg with a relative pathname." (with-test-dir (dir "a/b/") (in-directory dir (let ((file (pick-new-file "./pick-new-file-test-~D-~D"))) (prog1 (if (probe-file file) (string= (namestring (truename (directory-namestring file))) (namestring dir))) (delete-file file)))))) (deftest pick-new-file (t pick-new-file-74) "Test `pick-new-file', picking many times, passing the same relative search list file name arg with a relative pathname." (with-test-dir (dir "a/b/") (in-directory (merge-pathnames "a/b/" dir) (collect ((names)) (dotimes (num 80) (names (pick-new-file ".././pick-test-~D-~D"))) (fi (duplicatesp (names)) (and (eq (length (names)) 80) (dolist (file (names) t) (or (probe-file file) (return ())) (or (string= (namestring (truename (directory-namestring file))) (namestring (merge-pathnames "a/" dir))) (return ()))))))))) (deftest pick-new-file (t pick-new-file-100) "Test `pick-new-file', passing too few directives." (let (ret) (handler-case (pick-new-file "~D") (error () (setq ret t))) ret)) (deftest pick-new-file (t pick-new-file-101) "Test `pick-new-file', passing an empty string." (let (ret) (handler-case (pick-new-file "") (error () (setq ret t))) ret)) (deftest pick-new-file (t pick-new-file-102) "Test `pick-new-file', passing too many directives." (let (ret) (handler-case (pick-new-file "~D~D~D") (error () (setq ret t))) ret)) (deftest pick-new-file (t pick-new-file-103) "Test `pick-new-file', passing the wrong type of directive." (let (ret) (handler-case (pick-new-file "~A~D") (error () (setq ret t))) ret)) (deftest pick-new-file (t pick-new-file-104) "Test `pick-new-file', passing a pathname with wildcards." (let (ret) (handler-case (pick-new-file "~D~D*") (error () (setq ret t))) ret)) (deftest pick-new-file (t pick-new-file-105) "Test `pick-new-file', passing an empty pathname." (let (ret) (handler-case (pick-new-file ()) (error () (setq ret t))) ret)) (deftest pick-new-file (t pick-new-file-106) "Test `pick-new-file', passing a directory name arg." (let (ret) (deftest:with-test-dir (dir) (handler-case (pick-new-file (merge-pathnames "pick-test-~D-~D/" dir)) (error () (setq ret t)))) ret)) (deftest pick-new-file (t pick-new-file-107) "Test `pick-new-file' on a missing dir." (deftest:with-test-dir (dir) (let (ret) (handler-case (pick-new-file (merge-pathnames "pick-new/file-~D-~D" dir)) (error () (setq ret t))) ret))) (deftest pick-new-file (t pick-new-file-108) "Test `pick-new-file' on a read-blocked dir." (deftest:with-test-dir (dir) (setf (file-mode dir) "a-rwx") (let (ret) (unwind-protect (handler-case (pick-new-file (namestring (merge-pathnames "cde~D~D" dir))) (error () (setq ret t))) (setf (file-mode dir) "a+rwx")) ret))) (deftest pick-new-file (t pick-new-file-109) "Test `pick-new-file' on a symlink to a file." (deftest:with-test-dir (dir "a" ("l" "a")) (let (ret) (handler-case (pick-new-file (namestring (merge-pathnames "l/~D~D" dir))) (error () (setq ret t))) ret)))
110990dbae7d80b4ce29fca5c8b806b29b41e1cc4a9e870993e78cc59e49e384
nd/bird
Section_5_3.hs
newtype ArbInt = Norm [Digit] type Digit = Int digits :: ArbInt -> [Digit] digits (Norm xs) = xs base, baseSize :: Int base = 10000 baseSize = 4 type Carry = Int carry :: Digit -> (Carry, [Digit]) -> (Carry, [Digit]) carry x (c, xs) = ((x + c) `div` base, (x + c) `mod` base : xs) norm :: [Int] -> ArbInt norm = Norm . dropWhile (== 0) . addCarry . foldr carry (0, []) addCarry :: (Carry, [Digit]) -> [Digit] addCarry (c, xs) = if (-1 <= c) && (c < base) then c:xs else addCarry(c `div` base, c `mod` base : xs) align :: ([Digit], [Digit]) -> ([Digit], [Digit]) align (xs, ys) | n > 0 = (replicate n 0 ++ xs, ys) | n <= 0 = (xs, replicate (-n) 0 ++ ys) where n = length ys - length xs instance Eq ArbInt where (==) = translate (==) instance Ord ArbInt where (<) = translate (<) translate :: ([Digit] -> [Digit] -> Bool) -> (ArbInt -> ArbInt -> Bool) translate op x y = op xs ys where (xs, ys) = align (digits x, digits y) isZero :: ArbInt -> Bool isZero = null . digits norm' xs = Norm (addCarry (c, ys)) where ys = map snd (init z) c = fst (head z) z = scanr (op) (0,0) xs x `op` (c, y) = ((x+c) `div` base, (x+c) `mod` base) instance Num ArbInt where x + y = norm (zippWith (+) (align (digits x, digits y))) x - y = norm (zippWith (-) (align (digits x, digits y))) x * y = ... negate x = norm . map neg . digits where neg x = -x zippWith = uncurry zipWith negative :: ArbInt -> Bool negative (Norm xs) = not (null xs) && (head xs < 0)
null
https://raw.githubusercontent.com/nd/bird/06dba97af7cfb11f558eaeb31a75bd04cacf7201/ch05/Section_5_3.hs
haskell
newtype ArbInt = Norm [Digit] type Digit = Int digits :: ArbInt -> [Digit] digits (Norm xs) = xs base, baseSize :: Int base = 10000 baseSize = 4 type Carry = Int carry :: Digit -> (Carry, [Digit]) -> (Carry, [Digit]) carry x (c, xs) = ((x + c) `div` base, (x + c) `mod` base : xs) norm :: [Int] -> ArbInt norm = Norm . dropWhile (== 0) . addCarry . foldr carry (0, []) addCarry :: (Carry, [Digit]) -> [Digit] addCarry (c, xs) = if (-1 <= c) && (c < base) then c:xs else addCarry(c `div` base, c `mod` base : xs) align :: ([Digit], [Digit]) -> ([Digit], [Digit]) align (xs, ys) | n > 0 = (replicate n 0 ++ xs, ys) | n <= 0 = (xs, replicate (-n) 0 ++ ys) where n = length ys - length xs instance Eq ArbInt where (==) = translate (==) instance Ord ArbInt where (<) = translate (<) translate :: ([Digit] -> [Digit] -> Bool) -> (ArbInt -> ArbInt -> Bool) translate op x y = op xs ys where (xs, ys) = align (digits x, digits y) isZero :: ArbInt -> Bool isZero = null . digits norm' xs = Norm (addCarry (c, ys)) where ys = map snd (init z) c = fst (head z) z = scanr (op) (0,0) xs x `op` (c, y) = ((x+c) `div` base, (x+c) `mod` base) instance Num ArbInt where x + y = norm (zippWith (+) (align (digits x, digits y))) x - y = norm (zippWith (-) (align (digits x, digits y))) x * y = ... negate x = norm . map neg . digits where neg x = -x zippWith = uncurry zipWith negative :: ArbInt -> Bool negative (Norm xs) = not (null xs) && (head xs < 0)
685bd1f2359a90401329b8bb9de8836d46d0fc75f2dcc45b5598bd0eeaf97716
BillHallahan/G2
Located.hs
module G2.Language.Located ( Located (..) , Spanning (..) , Locatable (..) , Spannable (..) , topLeft , bottomRight , combineSpans , spanLookup , locLookup , SpannedName(..) ) where import G2.Language.Naming import G2.Language.Syntax import G2.Language.ExprEnv (ExprEnv) import Data.Hashable import qualified Data.Map as M import Data.Maybe import Data.Foldable class Located l where loc :: l -> Maybe Loc class Spanning l where spanning :: l -> Maybe Span instance Located Span where loc = Just . start instance Located Name where loc (Name _ _ _ s) = maybe Nothing loc s instance Located Id where loc (Id n _) = loc n instance Spanning Name where spanning (Name _ _ _ s) = s instance Spanning Id where spanning (Id n _) = spanning n -- Allows equality checking and sorting by Location newtype Locatable a = Locatable a deriving (Show) instance Located a => Located (Locatable a) where loc (Locatable x) = loc x instance Spanning a => Spanning (Locatable a) where spanning (Locatable x) = spanning x instance Located a => Eq (Locatable a) where x == y = loc x == loc y instance Located a => Ord (Locatable a) where x `compare` y = loc x `compare` loc y -- Allows equality checking and sorting by Span newtype Spannable a = Spannable a deriving (Show) instance Located a => Located (Spannable a) where loc (Spannable x) = loc x instance Spanning a => Spanning (Spannable a) where spanning (Spannable x) = spanning x instance Spanning a => Eq (Spannable a) where x == y = spanning x == spanning y instance Spanning a => Ord (Spannable a) where x `compare` y = spanning x `compare` spanning y -- | Returns the span that begins the closest to the top, -- or, if both columns are the same, that is leftmost topLeft :: Span -> Span -> Span topLeft (s1@Span {start = st1}) (s2@Span {start = st2}) | col st1 < col st2 = s1 | col st1 > col st2 = s2 | line st1 < line st2 = s1 | otherwise = s2 -- | Returns the span that ends the closest to the bottom, -- or, if both columns are the same, that is rightmost bottomRight :: Span -> Span -> Span bottomRight (s1@Span {end = en1}) (s2@Span {end = en2}) | col en1 < col en2 = s2 | col en1 > col en2 = s1 | line en1 < line en2 = s2 | otherwise = s1 | combineSpans Combines two Spans into one , that covers all the characters from both spans . -- Assumes the files are the same. combineSpans :: Span -> Span -> Span combineSpans s1 s2 = let tl = topLeft s1 s2 br = bottomRight s1 s2 in s1 {start = start tl, end = end br} | Constructs a map of Spans to Names , based on all Names in the ExprEnv spanLookup :: ExprEnv -> M.Map Span Name spanLookup = M.fromList . mapMaybe (\n -> maybe Nothing (\s -> Just (s, n)) (spanning n)) . toList . names | Constructs a map of to Names , based on all Names in the ExprEnv locLookup :: ExprEnv -> M.Map Loc Name locLookup = M.mapKeys start . spanLookup newtype SpannedName = SpannedName Name deriving (Show) instance Eq SpannedName where (==) (SpannedName (Name occ1 mod1 unq1 sp1)) (SpannedName (Name occ2 mod2 unq2 sp2)) = occ1 == occ2 && mod1 == mod2 && unq1 == unq2 && sp1 == sp2 instance Hashable SpannedName where hashWithSalt s (SpannedName (Name n m i l)) = s `hashWithSalt` n `hashWithSalt` m `hashWithSalt` i `hashWithSalt` l
null
https://raw.githubusercontent.com/BillHallahan/G2/12efc2ff54fe34615bc782a426b9962fa4408832/src/G2/Language/Located.hs
haskell
Allows equality checking and sorting by Location Allows equality checking and sorting by Span | Returns the span that begins the closest to the top, or, if both columns are the same, that is leftmost | Returns the span that ends the closest to the bottom, or, if both columns are the same, that is rightmost Assumes the files are the same.
module G2.Language.Located ( Located (..) , Spanning (..) , Locatable (..) , Spannable (..) , topLeft , bottomRight , combineSpans , spanLookup , locLookup , SpannedName(..) ) where import G2.Language.Naming import G2.Language.Syntax import G2.Language.ExprEnv (ExprEnv) import Data.Hashable import qualified Data.Map as M import Data.Maybe import Data.Foldable class Located l where loc :: l -> Maybe Loc class Spanning l where spanning :: l -> Maybe Span instance Located Span where loc = Just . start instance Located Name where loc (Name _ _ _ s) = maybe Nothing loc s instance Located Id where loc (Id n _) = loc n instance Spanning Name where spanning (Name _ _ _ s) = s instance Spanning Id where spanning (Id n _) = spanning n newtype Locatable a = Locatable a deriving (Show) instance Located a => Located (Locatable a) where loc (Locatable x) = loc x instance Spanning a => Spanning (Locatable a) where spanning (Locatable x) = spanning x instance Located a => Eq (Locatable a) where x == y = loc x == loc y instance Located a => Ord (Locatable a) where x `compare` y = loc x `compare` loc y newtype Spannable a = Spannable a deriving (Show) instance Located a => Located (Spannable a) where loc (Spannable x) = loc x instance Spanning a => Spanning (Spannable a) where spanning (Spannable x) = spanning x instance Spanning a => Eq (Spannable a) where x == y = spanning x == spanning y instance Spanning a => Ord (Spannable a) where x `compare` y = spanning x `compare` spanning y topLeft :: Span -> Span -> Span topLeft (s1@Span {start = st1}) (s2@Span {start = st2}) | col st1 < col st2 = s1 | col st1 > col st2 = s2 | line st1 < line st2 = s1 | otherwise = s2 bottomRight :: Span -> Span -> Span bottomRight (s1@Span {end = en1}) (s2@Span {end = en2}) | col en1 < col en2 = s2 | col en1 > col en2 = s1 | line en1 < line en2 = s2 | otherwise = s1 | combineSpans Combines two Spans into one , that covers all the characters from both spans . combineSpans :: Span -> Span -> Span combineSpans s1 s2 = let tl = topLeft s1 s2 br = bottomRight s1 s2 in s1 {start = start tl, end = end br} | Constructs a map of Spans to Names , based on all Names in the ExprEnv spanLookup :: ExprEnv -> M.Map Span Name spanLookup = M.fromList . mapMaybe (\n -> maybe Nothing (\s -> Just (s, n)) (spanning n)) . toList . names | Constructs a map of to Names , based on all Names in the ExprEnv locLookup :: ExprEnv -> M.Map Loc Name locLookup = M.mapKeys start . spanLookup newtype SpannedName = SpannedName Name deriving (Show) instance Eq SpannedName where (==) (SpannedName (Name occ1 mod1 unq1 sp1)) (SpannedName (Name occ2 mod2 unq2 sp2)) = occ1 == occ2 && mod1 == mod2 && unq1 == unq2 && sp1 == sp2 instance Hashable SpannedName where hashWithSalt s (SpannedName (Name n m i l)) = s `hashWithSalt` n `hashWithSalt` m `hashWithSalt` i `hashWithSalt` l
eac0be5a5b49147edf935d6b6aa8303762a4bc76ba265f91773931225dce70ce
haskell-checkers/checkers
Eq.hs
module Test.QuickCheck.Instances.Eq (notEqualTo, notOneof) where import Test.QuickCheck import Test.QuickCheck.Checkers import Control.Monad.Extensions notEqualTo :: (Eq a) => a -> Gen a -> Gen a notEqualTo v = satisfiesM (/= v) notOneof :: (Eq a,Arbitrary a) => [a] -> Gen a notOneof es = arbitrarySatisfying (not . (`elem` es))
null
https://raw.githubusercontent.com/haskell-checkers/checkers/6cdc62e3fa50db3458f88f268682e5f1cfd9ab2c/src/Test/QuickCheck/Instances/Eq.hs
haskell
module Test.QuickCheck.Instances.Eq (notEqualTo, notOneof) where import Test.QuickCheck import Test.QuickCheck.Checkers import Control.Monad.Extensions notEqualTo :: (Eq a) => a -> Gen a -> Gen a notEqualTo v = satisfiesM (/= v) notOneof :: (Eq a,Arbitrary a) => [a] -> Gen a notOneof es = arbitrarySatisfying (not . (`elem` es))
171ba88b99ad193ad62042a885df536c634f9166563c1a1f35ce0a1f463b576d
atzedijkstra/chr
Parse.hs
# LANGUAGE RankNTypes , FlexibleContexts , CPP # module CHR.Parse ( module UU.Parsing -- * Specific parser types , PlainParser , LayoutParser, LayoutParser2 -- * Top level wrappers/invocations , parsePlain , parseOffsideToResMsgs , parseToResMsgs , parseToResWith , parseOffsideToResMsgsStopAtErr -- * Additional parser combinators , pAnyFromMap, pAnyKey , pMaybe, pMb , pDo -- * Re-exports , position -- * Dealing with Message , fromMessage ) where #if __GLASGOW_HASKELL__ >= 710 import Prelude hiding ( (<*>), (<*), (*>), (<$>), (<$) ) #else #endif import UU.Parsing import UU.Parsing.Machine import UU.Parsing.Offside import UU.Scanner.Position( Position(..) ) import UU.Scanner.GenToken import qualified Data.Map as Map import Data.Maybe ------------------------------------------------------------------------- -- Type(s) of parsers ------------------------------------------------------------------------- type LayoutParser tok ep = forall i o p . (IsParser (OffsideParser i o tok p) tok,InputState i tok p, OutputState o, Position p) => OffsideParser i o tok p ep type LayoutParser2 tok ep = forall i o p . (IsParser (OffsideParser i o tok p) tok,InputState i tok p, OutputState o, Position p) => OffsideParser i o tok p ep -> OffsideParser i o tok p ep type PlainParser tok gp = forall p . IsParser p tok => p gp ------------------------------------------------------------------------- -- Parsing utils ------------------------------------------------------------------------- valFromPair :: Steps (Pair a (Pair a1 r)) s p -> Steps (a, a1) s p valFromPair p = val fromPair p where fromPair (Pair x (Pair y _)) = (x,y) toResMsgs :: Steps (Pair a r) s pos -> (a, [Message s pos]) toResMsgs steps = (r,getMsgs steps) where (Pair r _) = evalSteps steps toOffsideResMsgs :: Steps (a,b) s pos -> (a, [Message s pos]) toOffsideResMsgs steps = r `seq` (r,getMsgs steps) where (r,_) = evalSteps steps parsePlain :: (Symbol s, InputState inp s pos) => AnaParser inp Pair s pos a -> inp -> Steps (a, inp) s pos parsePlain p inp = valFromPair (parse p inp) -- | Invoke parser, yielding result + errors parseToResMsgs :: (Symbol s, InputState inp s pos) => AnaParser inp Pair s pos a -> inp -> (a,[Message s pos]) parseToResMsgs p inp = toResMsgs (parse p inp) -- | Invoke parser, yielding result + errors processed with a function parseToResWith :: (Symbol s, Show s, Eq s, InputState inp s pos) => (pos -> String -> String -> e) -> AnaParser inp Pair s pos a -> inp -> (a,[e]) parseToResWith f p inp = (r, map (fromMessage f) e) where (r,e) = toResMsgs (parse p inp) parseOffsideToResMsgs :: (Symbol s, InputState i s p, Position p) => OffsideParser i Pair s p a -> OffsideInput i s p -> (a,[Message (OffsideSymbol s) p]) parseOffsideToResMsgs p inp = toOffsideResMsgs (parseOffside p inp) ------------------------------------------------------------------------- Parsing , stopping at first error ------------------------------------------------------------------------- handleEofStopAtErr input = case splitStateE input of Left' s ss -> NoMoreSteps (Pair ss ()) Right' ss -> NoMoreSteps (Pair ss ()) parseStopAtErr :: (Symbol s, InputState inp s pos) => AnaParser inp Pair s pos a -> inp -> Steps (Pair a (Pair inp ())) s pos parseStopAtErr = parsebasic handleEofStopAtErr parseOffsideStopAtErr :: (Symbol s, InputState i s p, Position p) => OffsideParser i Pair s p a -> OffsideInput i s p -> Steps (a, OffsideInput i s p) (OffsideSymbol s) p parseOffsideStopAtErr (OP p) inp = valFromPair (parseStopAtErr p inp) parseOffsideToResMsgsStopAtErr :: (Symbol s, InputState i s p, Position p) => OffsideParser i Pair s p a -> OffsideInput i s p -> (a, [Message (OffsideSymbol s) p]) parseOffsideToResMsgsStopAtErr p inp = toOffsideResMsgs (parseOffsideStopAtErr p inp) ------------------------------------------------------------------------- -- Offside for 'do' notation. -- Problem tackled here is that both do statements and the last expr may start with 'let x=e', -- and the presence of 'in e' following 'let x=e' indicates that it is the last statement. This is a variation of pBlock1 . ------------------------------------------------------------------------- pDo :: (InputState i s p, OutputState o, Position p, Symbol s, Ord s) => OffsideParser i o s p x -> OffsideParser i o s p y -> OffsideParser i o s p z -> OffsideParser i o s p a -> OffsideParser i o s p (Maybe last -> a) -> OffsideParser i o s p last -> OffsideParser i o s p [a] pDo open sep close pPlain pLastPrefix pLastRest = pOffside open close explicit implicit where sep' = () <$ sep elems s = sep0 *> es <* sep0 where es = (:) <$> pPlain <*> esTail <|> (pLastPrefix <**> ( (\r pre -> [pre (Just r)]) <$> pLastRest <|> (\tl pre -> pre Nothing : tl) <$> esTail ) ) esTail = pList1 s *> es <|> pSucceed [] sep0 = pList s explicit = elems sep' implicit = elems (sep' <|> pSeparator) pBlock1 : : ( InputState i s p , OutputState o , Position p , Symbol s , s ) = > OffsideParser i o s p x - > OffsideParser i o s p y - > OffsideParser i o s p z - > OffsideParser i o s p a - > OffsideParser i o s p [ a ] pBlock1 open sep close p = pOffside open close explicit implicit where sep ' = ( ) < $ sep elems s = pList s * > pList1Sep ( pList1 s ) p < * pList s explicit = elems sep ' implicit = elems ( sep ' < | > pSeparator ) pBlock1 :: (InputState i s p, OutputState o, Position p, Symbol s, Ord s) => OffsideParser i o s p x -> OffsideParser i o s p y -> OffsideParser i o s p z -> OffsideParser i o s p a -> OffsideParser i o s p [a] pBlock1 open sep close p = pOffside open close explicit implicit where sep' = () <$ sep elems s = pList s *> pList1Sep (pList1 s) p <* pList s explicit = elems sep' implicit = elems (sep' <|> pSeparator) -} ------------------------------------------------------------------------- -- Misc combinators ------------------------------------------------------------------------- parse possibly present p pMaybe :: (IsParser p s) => a1 -> (a -> a1) -> p a -> p a1 pMaybe n j p = j <$> p <|> pSucceed n pAnyKey :: (IsParser p s) => (a1 -> p a) -> [a1] -> p a pAnyKey pKey = foldr1 (<|>) . map pKey pMb :: (IsParser p s) => p a -> p (Maybe a) pMb = pMaybe Nothing Just -- given (non-empty) key->value map, return parser for all keys returning corresponding value pAnyFromMap :: (IsParser p s) => (k -> p a1) -> Map.Map k v -> p v pAnyFromMap pKey m = foldr1 (<|>) [ v <$ pKey k | (k,v) <- Map.toList m ] ------------------------------------------------------------------------- -- Dealing with error Message ------------------------------------------------------------------------- -- | Convert from Message to anything using a function taking as String position, expected symbol and action taken respectively fromMessage :: (Show s, Eq s) => (p -> String -> String -> x) -> Message s p -> x fromMessage f (Msg e p a) = f p (show e) (show a)
null
https://raw.githubusercontent.com/atzedijkstra/chr/ad465828b1560831e90c4056e12338231872e8db/chr-parse/src/CHR/Parse.hs
haskell
* Specific parser types * Top level wrappers/invocations * Additional parser combinators * Re-exports * Dealing with Message ----------------------------------------------------------------------- Type(s) of parsers ----------------------------------------------------------------------- ----------------------------------------------------------------------- Parsing utils ----------------------------------------------------------------------- | Invoke parser, yielding result + errors | Invoke parser, yielding result + errors processed with a function ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- Offside for 'do' notation. Problem tackled here is that both do statements and the last expr may start with 'let x=e', and the presence of 'in e' following 'let x=e' indicates that it is the last statement. ----------------------------------------------------------------------- ----------------------------------------------------------------------- Misc combinators ----------------------------------------------------------------------- given (non-empty) key->value map, return parser for all keys returning corresponding value ----------------------------------------------------------------------- Dealing with error Message ----------------------------------------------------------------------- | Convert from Message to anything using a function taking as String position, expected symbol and action taken respectively
# LANGUAGE RankNTypes , FlexibleContexts , CPP # module CHR.Parse ( module UU.Parsing , PlainParser , LayoutParser, LayoutParser2 , parsePlain , parseOffsideToResMsgs , parseToResMsgs , parseToResWith , parseOffsideToResMsgsStopAtErr , pAnyFromMap, pAnyKey , pMaybe, pMb , pDo , position , fromMessage ) where #if __GLASGOW_HASKELL__ >= 710 import Prelude hiding ( (<*>), (<*), (*>), (<$>), (<$) ) #else #endif import UU.Parsing import UU.Parsing.Machine import UU.Parsing.Offside import UU.Scanner.Position( Position(..) ) import UU.Scanner.GenToken import qualified Data.Map as Map import Data.Maybe type LayoutParser tok ep = forall i o p . (IsParser (OffsideParser i o tok p) tok,InputState i tok p, OutputState o, Position p) => OffsideParser i o tok p ep type LayoutParser2 tok ep = forall i o p . (IsParser (OffsideParser i o tok p) tok,InputState i tok p, OutputState o, Position p) => OffsideParser i o tok p ep -> OffsideParser i o tok p ep type PlainParser tok gp = forall p . IsParser p tok => p gp valFromPair :: Steps (Pair a (Pair a1 r)) s p -> Steps (a, a1) s p valFromPair p = val fromPair p where fromPair (Pair x (Pair y _)) = (x,y) toResMsgs :: Steps (Pair a r) s pos -> (a, [Message s pos]) toResMsgs steps = (r,getMsgs steps) where (Pair r _) = evalSteps steps toOffsideResMsgs :: Steps (a,b) s pos -> (a, [Message s pos]) toOffsideResMsgs steps = r `seq` (r,getMsgs steps) where (r,_) = evalSteps steps parsePlain :: (Symbol s, InputState inp s pos) => AnaParser inp Pair s pos a -> inp -> Steps (a, inp) s pos parsePlain p inp = valFromPair (parse p inp) parseToResMsgs :: (Symbol s, InputState inp s pos) => AnaParser inp Pair s pos a -> inp -> (a,[Message s pos]) parseToResMsgs p inp = toResMsgs (parse p inp) parseToResWith :: (Symbol s, Show s, Eq s, InputState inp s pos) => (pos -> String -> String -> e) -> AnaParser inp Pair s pos a -> inp -> (a,[e]) parseToResWith f p inp = (r, map (fromMessage f) e) where (r,e) = toResMsgs (parse p inp) parseOffsideToResMsgs :: (Symbol s, InputState i s p, Position p) => OffsideParser i Pair s p a -> OffsideInput i s p -> (a,[Message (OffsideSymbol s) p]) parseOffsideToResMsgs p inp = toOffsideResMsgs (parseOffside p inp) Parsing , stopping at first error handleEofStopAtErr input = case splitStateE input of Left' s ss -> NoMoreSteps (Pair ss ()) Right' ss -> NoMoreSteps (Pair ss ()) parseStopAtErr :: (Symbol s, InputState inp s pos) => AnaParser inp Pair s pos a -> inp -> Steps (Pair a (Pair inp ())) s pos parseStopAtErr = parsebasic handleEofStopAtErr parseOffsideStopAtErr :: (Symbol s, InputState i s p, Position p) => OffsideParser i Pair s p a -> OffsideInput i s p -> Steps (a, OffsideInput i s p) (OffsideSymbol s) p parseOffsideStopAtErr (OP p) inp = valFromPair (parseStopAtErr p inp) parseOffsideToResMsgsStopAtErr :: (Symbol s, InputState i s p, Position p) => OffsideParser i Pair s p a -> OffsideInput i s p -> (a, [Message (OffsideSymbol s) p]) parseOffsideToResMsgsStopAtErr p inp = toOffsideResMsgs (parseOffsideStopAtErr p inp) This is a variation of pBlock1 . pDo :: (InputState i s p, OutputState o, Position p, Symbol s, Ord s) => OffsideParser i o s p x -> OffsideParser i o s p y -> OffsideParser i o s p z -> OffsideParser i o s p a -> OffsideParser i o s p (Maybe last -> a) -> OffsideParser i o s p last -> OffsideParser i o s p [a] pDo open sep close pPlain pLastPrefix pLastRest = pOffside open close explicit implicit where sep' = () <$ sep elems s = sep0 *> es <* sep0 where es = (:) <$> pPlain <*> esTail <|> (pLastPrefix <**> ( (\r pre -> [pre (Just r)]) <$> pLastRest <|> (\tl pre -> pre Nothing : tl) <$> esTail ) ) esTail = pList1 s *> es <|> pSucceed [] sep0 = pList s explicit = elems sep' implicit = elems (sep' <|> pSeparator) pBlock1 : : ( InputState i s p , OutputState o , Position p , Symbol s , s ) = > OffsideParser i o s p x - > OffsideParser i o s p y - > OffsideParser i o s p z - > OffsideParser i o s p a - > OffsideParser i o s p [ a ] pBlock1 open sep close p = pOffside open close explicit implicit where sep ' = ( ) < $ sep elems s = pList s * > pList1Sep ( pList1 s ) p < * pList s explicit = elems sep ' implicit = elems ( sep ' < | > pSeparator ) pBlock1 :: (InputState i s p, OutputState o, Position p, Symbol s, Ord s) => OffsideParser i o s p x -> OffsideParser i o s p y -> OffsideParser i o s p z -> OffsideParser i o s p a -> OffsideParser i o s p [a] pBlock1 open sep close p = pOffside open close explicit implicit where sep' = () <$ sep elems s = pList s *> pList1Sep (pList1 s) p <* pList s explicit = elems sep' implicit = elems (sep' <|> pSeparator) -} parse possibly present p pMaybe :: (IsParser p s) => a1 -> (a -> a1) -> p a -> p a1 pMaybe n j p = j <$> p <|> pSucceed n pAnyKey :: (IsParser p s) => (a1 -> p a) -> [a1] -> p a pAnyKey pKey = foldr1 (<|>) . map pKey pMb :: (IsParser p s) => p a -> p (Maybe a) pMb = pMaybe Nothing Just pAnyFromMap :: (IsParser p s) => (k -> p a1) -> Map.Map k v -> p v pAnyFromMap pKey m = foldr1 (<|>) [ v <$ pKey k | (k,v) <- Map.toList m ] fromMessage :: (Show s, Eq s) => (p -> String -> String -> x) -> Message s p -> x fromMessage f (Msg e p a) = f p (show e) (show a)
579b471f225a5e38198d37d52a66ae048d3bd2af087df83f38c94a8e7056d1ab
nikita-volkov/rerebase
Rep.hs
module Data.Profunctor.Rep ( module Rebase.Data.Profunctor.Rep ) where import Rebase.Data.Profunctor.Rep
null
https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/Data/Profunctor/Rep.hs
haskell
module Data.Profunctor.Rep ( module Rebase.Data.Profunctor.Rep ) where import Rebase.Data.Profunctor.Rep
ae4f503bcda2ed51d77bf6e0b268463e5e30331832a051ade448a1bf7c7fda07
re-xyr/hina
Unify.hs
module Hina.Tyck.Unify where import Control.Monad (when) import Control.Monad.Freer (Eff, Member, Members) import Control.Monad.Freer.Error (Error, runError, throwError) import Control.Monad.Freer.State (State, evalState, get, modify) import qualified Data.IntMap.Strict as Map import Data.Maybe (fromMaybe) import Hina.Core (Arg (Arg), Param (Param), Term (TApp, TBind, TPi, TProj, TSigma, TUniv), TermApp (TermApp), TermBind (TermBind), TermPi (TermPi), TermProj (TermProj), TermSigma (TermSigma), TermUniv (TermUniv)) import Hina.Core.Normalize (normalizeToWhnf) import Hina.Core.Substitute (subst) import Hina.Ref (RefBind (rName, rUid), freshBind) import Hina.Tyck.Context (TyckEff, getLocal, withLocal) data UnifyFailure = UnifyFailure type UnifyEff m = (TyckEff m, Members '[State LocalCorrespond, Error UnifyFailure] m) newtype LocalCorrespond = LocalCorrespond { unLocalCorrespond :: Map.IntMap RefBind } withCorrespond :: Member (State LocalCorrespond) m => RefBind -> RefBind -> Eff m a -> Eff m a withCorrespond x y m = do modify (LocalCorrespond . Map.insert (rUid y) x . Map.insert (rUid x) y . unLocalCorrespond) res <- m modify (LocalCorrespond . Map.delete (rUid x) . Map.delete (rUid y) . unLocalCorrespond) pure res getCorrespond :: Member (State LocalCorrespond) m => RefBind -> Eff m RefBind getCorrespond r = fromMaybe r . Map.lookup (rUid r) . unLocalCorrespond <$> get unify :: TyckEff m => Term -> Term -> Term -> Eff m Bool unify ty x y = evalState (LocalCorrespond Map.empty) do res <- runError @UnifyFailure $ unify' ty x y pure case res of Left _ -> False Right _ -> True unify' :: UnifyEff m => Term -> Term -> Term -> Eff m () unify' ty x y = do ty' <- normalizeToWhnf ty x' <- normalizeToWhnf x y' <- normalizeToWhnf y unifyWhnf ty' x' y' unifyWhnf :: UnifyEff m => Term -> Term -> Term -> Eff m () unifyWhnf ty x y = case (ty, x, y) of (TPi (TermPi (Param tRef tTyp) tBody), _, _) -> do bnd <- freshBind (rName tRef) withLocal bnd tTyp do let dummy = TBind $ TermBind bnd unify' (subst tRef dummy tBody) (TApp $ TermApp x $ Arg dummy) (TApp $ TermApp x $ Arg dummy) (TSigma (TermSigma (Param tRef tTyp) tBody), _, _) -> do unify' tTyp (TProj $ TermProj x True) (TProj $ TermProj y True) unify' (subst tRef (TProj $ TermProj x True) tBody) (TProj $ TermProj x False) (TProj $ TermProj y False) (TUniv _, TPi (TermPi (Param xRef xTyp) xBody), TPi (TermPi (Param yRef yTyp) yBody)) -> do unify' (TUniv TermUniv) xTyp yTyp withLocal xRef xTyp $ withLocal yRef yTyp $ withCorrespond xRef yRef $ unify' (TUniv TermUniv) xBody yBody (TUniv _, TSigma (TermSigma (Param xRef xTyp) xBody), TSigma (TermSigma (Param yRef yTyp) yBody)) -> do unify' (TUniv TermUniv) xTyp yTyp withLocal xRef xTyp $ withLocal yRef yTyp $ withCorrespond xRef yRef $ unify' (TUniv TermUniv) xBody yBody (TUniv _, TUniv _, TUniv _) -> pure () (_, _, _) -> do ty' <- unifyNeutral x y unify' (TUniv TermUniv) ty' ty unifyNeutral :: UnifyEff m => Term -> Term -> Eff m Term unifyNeutral x y = case (x, y) of (TApp (TermApp xFn (Arg xArg)), TApp (TermApp yFn (Arg yArg))) -> do fnTy <- unifyNeutral xFn yFn >>= normalizeToWhnf case fnTy of TPi (TermPi (Param tRef tTyp) tBody) -> do unify' tTyp xArg yArg pure $ subst tRef xArg tBody _ -> error "Impossible" (TProj (TermProj xTup xIsLeft), TProj (TermProj yTup yIsLeft)) -> do when (xIsLeft /= yIsLeft) $ throwError UnifyFailure tupTy <- unifyNeutral xTup yTup >>= normalizeToWhnf pure case tupTy of TPi (TermPi (Param tRef tTyp) tBody) -> if xIsLeft then tTyp else subst tRef (TProj $ TermProj xTup True) tBody _ -> error "Impossible" (TBind (TermBind xRef), TBind (TermBind yRef)) -> do yRef' <- getCorrespond yRef when (xRef /= yRef') $ throwError UnifyFailure getLocal xRef _ -> throwError UnifyFailure
null
https://raw.githubusercontent.com/re-xyr/hina/5224b98fb4405d8aa54e1ee1668072844aa80dac/src/Hina/Tyck/Unify.hs
haskell
module Hina.Tyck.Unify where import Control.Monad (when) import Control.Monad.Freer (Eff, Member, Members) import Control.Monad.Freer.Error (Error, runError, throwError) import Control.Monad.Freer.State (State, evalState, get, modify) import qualified Data.IntMap.Strict as Map import Data.Maybe (fromMaybe) import Hina.Core (Arg (Arg), Param (Param), Term (TApp, TBind, TPi, TProj, TSigma, TUniv), TermApp (TermApp), TermBind (TermBind), TermPi (TermPi), TermProj (TermProj), TermSigma (TermSigma), TermUniv (TermUniv)) import Hina.Core.Normalize (normalizeToWhnf) import Hina.Core.Substitute (subst) import Hina.Ref (RefBind (rName, rUid), freshBind) import Hina.Tyck.Context (TyckEff, getLocal, withLocal) data UnifyFailure = UnifyFailure type UnifyEff m = (TyckEff m, Members '[State LocalCorrespond, Error UnifyFailure] m) newtype LocalCorrespond = LocalCorrespond { unLocalCorrespond :: Map.IntMap RefBind } withCorrespond :: Member (State LocalCorrespond) m => RefBind -> RefBind -> Eff m a -> Eff m a withCorrespond x y m = do modify (LocalCorrespond . Map.insert (rUid y) x . Map.insert (rUid x) y . unLocalCorrespond) res <- m modify (LocalCorrespond . Map.delete (rUid x) . Map.delete (rUid y) . unLocalCorrespond) pure res getCorrespond :: Member (State LocalCorrespond) m => RefBind -> Eff m RefBind getCorrespond r = fromMaybe r . Map.lookup (rUid r) . unLocalCorrespond <$> get unify :: TyckEff m => Term -> Term -> Term -> Eff m Bool unify ty x y = evalState (LocalCorrespond Map.empty) do res <- runError @UnifyFailure $ unify' ty x y pure case res of Left _ -> False Right _ -> True unify' :: UnifyEff m => Term -> Term -> Term -> Eff m () unify' ty x y = do ty' <- normalizeToWhnf ty x' <- normalizeToWhnf x y' <- normalizeToWhnf y unifyWhnf ty' x' y' unifyWhnf :: UnifyEff m => Term -> Term -> Term -> Eff m () unifyWhnf ty x y = case (ty, x, y) of (TPi (TermPi (Param tRef tTyp) tBody), _, _) -> do bnd <- freshBind (rName tRef) withLocal bnd tTyp do let dummy = TBind $ TermBind bnd unify' (subst tRef dummy tBody) (TApp $ TermApp x $ Arg dummy) (TApp $ TermApp x $ Arg dummy) (TSigma (TermSigma (Param tRef tTyp) tBody), _, _) -> do unify' tTyp (TProj $ TermProj x True) (TProj $ TermProj y True) unify' (subst tRef (TProj $ TermProj x True) tBody) (TProj $ TermProj x False) (TProj $ TermProj y False) (TUniv _, TPi (TermPi (Param xRef xTyp) xBody), TPi (TermPi (Param yRef yTyp) yBody)) -> do unify' (TUniv TermUniv) xTyp yTyp withLocal xRef xTyp $ withLocal yRef yTyp $ withCorrespond xRef yRef $ unify' (TUniv TermUniv) xBody yBody (TUniv _, TSigma (TermSigma (Param xRef xTyp) xBody), TSigma (TermSigma (Param yRef yTyp) yBody)) -> do unify' (TUniv TermUniv) xTyp yTyp withLocal xRef xTyp $ withLocal yRef yTyp $ withCorrespond xRef yRef $ unify' (TUniv TermUniv) xBody yBody (TUniv _, TUniv _, TUniv _) -> pure () (_, _, _) -> do ty' <- unifyNeutral x y unify' (TUniv TermUniv) ty' ty unifyNeutral :: UnifyEff m => Term -> Term -> Eff m Term unifyNeutral x y = case (x, y) of (TApp (TermApp xFn (Arg xArg)), TApp (TermApp yFn (Arg yArg))) -> do fnTy <- unifyNeutral xFn yFn >>= normalizeToWhnf case fnTy of TPi (TermPi (Param tRef tTyp) tBody) -> do unify' tTyp xArg yArg pure $ subst tRef xArg tBody _ -> error "Impossible" (TProj (TermProj xTup xIsLeft), TProj (TermProj yTup yIsLeft)) -> do when (xIsLeft /= yIsLeft) $ throwError UnifyFailure tupTy <- unifyNeutral xTup yTup >>= normalizeToWhnf pure case tupTy of TPi (TermPi (Param tRef tTyp) tBody) -> if xIsLeft then tTyp else subst tRef (TProj $ TermProj xTup True) tBody _ -> error "Impossible" (TBind (TermBind xRef), TBind (TermBind yRef)) -> do yRef' <- getCorrespond yRef when (xRef /= yRef') $ throwError UnifyFailure getLocal xRef _ -> throwError UnifyFailure
43779f366bfe78b0562af1073604027470fc4b75432d61bca52efeacd7882424
bmeurer/ocamljit2
set.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , 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 Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) $ Id$ (** Sets over ordered types. This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance. *) module type OrderedType = sig type t (** The type of the set elements. *) val compare : t -> t -> int * A total ordering function over the set elements . This is a two - argument function [ f ] such that [ f e1 e2 ] is zero if the elements [ e1 ] and [ e2 ] are equal , [ f e1 e2 ] is strictly negative if [ e1 ] is smaller than [ e2 ] , and [ f e1 e2 ] is strictly positive if [ e1 ] is greater than [ e2 ] . Example : a suitable ordering function is the generic structural comparison function { ! Pervasives.compare } . This is a two-argument function [f] such that [f e1 e2] is zero if the elements [e1] and [e2] are equal, [f e1 e2] is strictly negative if [e1] is smaller than [e2], and [f e1 e2] is strictly positive if [e1] is greater than [e2]. Example: a suitable ordering function is the generic structural comparison function {!Pervasives.compare}. *) end (** Input signature of the functor {!Set.Make}. *) module type S = sig type elt (** The type of the set elements. *) type t (** The type of sets. *) val empty: t (** The empty set. *) val is_empty: t -> bool (** Test whether a set is empty or not. *) val mem: elt -> t -> bool (** [mem x s] tests whether [x] belongs to the set [s]. *) val add: elt -> t -> t (** [add x s] returns a set containing all elements of [s], plus [x]. If [x] was already in [s], [s] is returned unchanged. *) val singleton: elt -> t * [ singleton x ] returns the one - element set containing only [ x ] . val remove: elt -> t -> t (** [remove x s] returns a set containing all elements of [s], except [x]. If [x] was not in [s], [s] is returned unchanged. *) val union: t -> t -> t (** Set union. *) val inter: t -> t -> t (** Set intersection. *) (** Set difference. *) val diff: t -> t -> t val compare: t -> t -> int (** Total ordering between sets. Can be used as the ordering function for doing sets of sets. *) val equal: t -> t -> bool (** [equal s1 s2] tests whether the sets [s1] and [s2] are equal, that is, contain equal elements. *) val subset: t -> t -> bool (** [subset s1 s2] tests whether the set [s1] is a subset of the set [s2]. *) val iter: (elt -> unit) -> t -> unit (** [iter f s] applies [f] in turn to all elements of [s]. The elements of [s] are presented to [f] in increasing order with respect to the ordering over the type of the elements. *) val fold: (elt -> 'a -> 'a) -> t -> 'a -> 'a (** [fold f s a] computes [(f xN ... (f x2 (f x1 a))...)], where [x1 ... xN] are the elements of [s], in increasing order. *) val for_all: (elt -> bool) -> t -> bool (** [for_all p s] checks if all elements of the set satisfy the predicate [p]. *) val exists: (elt -> bool) -> t -> bool * [ exists p s ] checks if at least one element of the set satisfies the predicate [ p ] . the set satisfies the predicate [p]. *) val filter: (elt -> bool) -> t -> t (** [filter p s] returns the set of all elements in [s] that satisfy predicate [p]. *) val partition: (elt -> bool) -> t -> t * t (** [partition p s] returns a pair of sets [(s1, s2)], where [s1] is the set of all the elements of [s] that satisfy the predicate [p], and [s2] is the set of all the elements of [s] that do not satisfy [p]. *) val cardinal: t -> int (** Return the number of elements of a set. *) val elements: t -> elt list * Return the list of all elements of the given set . The returned list is sorted in increasing order with respect to the ordering [ Ord.compare ] , where [ ] is the argument given to { ! Set . Make } . The returned list is sorted in increasing order with respect to the ordering [Ord.compare], where [Ord] is the argument given to {!Set.Make}. *) val min_elt: t -> elt (** Return the smallest element of the given set (with respect to the [Ord.compare] ordering), or raise [Not_found] if the set is empty. *) val max_elt: t -> elt (** Same as {!Set.S.min_elt}, but returns the largest element of the given set. *) val choose: t -> elt * Return one element of the given set , or raise [ Not_found ] if the set is empty . Which element is chosen is unspecified , but equal elements will be chosen for equal sets . the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. *) val split: elt -> t -> t * bool * t (** [split x s] returns a triple [(l, present, r)], where [l] is the set of elements of [s] that are strictly less than [x]; [r] is the set of elements of [s] that are strictly greater than [x]; [present] is [false] if [s] contains no element equal to [x], or [true] if [s] contains an element equal to [x]. *) end (** Output signature of the functor {!Set.Make}. *) module Make (Ord : OrderedType) : S with type elt = Ord.t (** Functor building an implementation of the set structure given a totally ordered type. *)
null
https://raw.githubusercontent.com/bmeurer/ocamljit2/ef06db5c688c1160acc1de1f63c29473bcd0055c/stdlib/set.mli
ocaml
********************************************************************* Objective Caml the special exception on linking described in file ../LICENSE. ********************************************************************* * Sets over ordered types. This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance. * The type of the set elements. * Input signature of the functor {!Set.Make}. * The type of the set elements. * The type of sets. * The empty set. * Test whether a set is empty or not. * [mem x s] tests whether [x] belongs to the set [s]. * [add x s] returns a set containing all elements of [s], plus [x]. If [x] was already in [s], [s] is returned unchanged. * [remove x s] returns a set containing all elements of [s], except [x]. If [x] was not in [s], [s] is returned unchanged. * Set union. * Set intersection. * Set difference. * Total ordering between sets. Can be used as the ordering function for doing sets of sets. * [equal s1 s2] tests whether the sets [s1] and [s2] are equal, that is, contain equal elements. * [subset s1 s2] tests whether the set [s1] is a subset of the set [s2]. * [iter f s] applies [f] in turn to all elements of [s]. The elements of [s] are presented to [f] in increasing order with respect to the ordering over the type of the elements. * [fold f s a] computes [(f xN ... (f x2 (f x1 a))...)], where [x1 ... xN] are the elements of [s], in increasing order. * [for_all p s] checks if all elements of the set satisfy the predicate [p]. * [filter p s] returns the set of all elements in [s] that satisfy predicate [p]. * [partition p s] returns a pair of sets [(s1, s2)], where [s1] is the set of all the elements of [s] that satisfy the predicate [p], and [s2] is the set of all the elements of [s] that do not satisfy [p]. * Return the number of elements of a set. * Return the smallest element of the given set (with respect to the [Ord.compare] ordering), or raise [Not_found] if the set is empty. * Same as {!Set.S.min_elt}, but returns the largest element of the given set. * [split x s] returns a triple [(l, present, r)], where [l] is the set of elements of [s] that are strictly less than [x]; [r] is the set of elements of [s] that are strictly greater than [x]; [present] is [false] if [s] contains no element equal to [x], or [true] if [s] contains an element equal to [x]. * Output signature of the functor {!Set.Make}. * Functor building an implementation of the set structure given a totally ordered type.
, 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 Library General Public License , with $ Id$ module type OrderedType = sig type t val compare : t -> t -> int * A total ordering function over the set elements . This is a two - argument function [ f ] such that [ f e1 e2 ] is zero if the elements [ e1 ] and [ e2 ] are equal , [ f e1 e2 ] is strictly negative if [ e1 ] is smaller than [ e2 ] , and [ f e1 e2 ] is strictly positive if [ e1 ] is greater than [ e2 ] . Example : a suitable ordering function is the generic structural comparison function { ! Pervasives.compare } . This is a two-argument function [f] such that [f e1 e2] is zero if the elements [e1] and [e2] are equal, [f e1 e2] is strictly negative if [e1] is smaller than [e2], and [f e1 e2] is strictly positive if [e1] is greater than [e2]. Example: a suitable ordering function is the generic structural comparison function {!Pervasives.compare}. *) end module type S = sig type elt type t val empty: t val is_empty: t -> bool val mem: elt -> t -> bool val add: elt -> t -> t val singleton: elt -> t * [ singleton x ] returns the one - element set containing only [ x ] . val remove: elt -> t -> t val union: t -> t -> t val inter: t -> t -> t val diff: t -> t -> t val compare: t -> t -> int val equal: t -> t -> bool val subset: t -> t -> bool val iter: (elt -> unit) -> t -> unit val fold: (elt -> 'a -> 'a) -> t -> 'a -> 'a val for_all: (elt -> bool) -> t -> bool val exists: (elt -> bool) -> t -> bool * [ exists p s ] checks if at least one element of the set satisfies the predicate [ p ] . the set satisfies the predicate [p]. *) val filter: (elt -> bool) -> t -> t val partition: (elt -> bool) -> t -> t * t val cardinal: t -> int val elements: t -> elt list * Return the list of all elements of the given set . The returned list is sorted in increasing order with respect to the ordering [ Ord.compare ] , where [ ] is the argument given to { ! Set . Make } . The returned list is sorted in increasing order with respect to the ordering [Ord.compare], where [Ord] is the argument given to {!Set.Make}. *) val min_elt: t -> elt val max_elt: t -> elt val choose: t -> elt * Return one element of the given set , or raise [ Not_found ] if the set is empty . Which element is chosen is unspecified , but equal elements will be chosen for equal sets . the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. *) val split: elt -> t -> t * bool * t end module Make (Ord : OrderedType) : S with type elt = Ord.t
177594fb5deedf488a820f376a7e1c2175aecb859512aa1a95a8979f2fc1e483
janestreet/incr_dom
app.mli
open! Core open! Incr_dom module Model : sig type t val cutoff : t -> t -> bool val create : int -> t end include App_intf.S with module Model := Model
null
https://raw.githubusercontent.com/janestreet/incr_dom/56c04e44d6a8f1cc9b2b841495ec448de4bf61a1/example/partial_rendering_table/app.mli
ocaml
open! Core open! Incr_dom module Model : sig type t val cutoff : t -> t -> bool val create : int -> t end include App_intf.S with module Model := Model
2e0a8c57bf06e7e32196b603a1ccdac428448707b794e090723bbafebadac92c
pistacchio/deviantchecker
core.clj
(ns org.github.pistacchio.deviantchecker.core (:use compojure.core ring.adapter.jetty org.github.pistacchio.deviantchecker.scraper [clojure.contrib.json :only (json-str)] net.cgrand.enlive-html) (:require [compojure.route :as route] [compojure.handler :as handler] [clojure.java.io :as io]) (:gen-class)) (def *data-file* "data/data.dat") ;; ** utilities ** ;; (defn emit** "given an enlive form, returns a string" [tpl] (apply str (emit* tpl))) (defn get-file "return the absolute path of relative-path" [relative-path] (.getPath (io/resource relative-path))) ;; ** data management ** ;; (defn load-galleries "returns a gallery database stored in *data-file*" [] (load-file (get-file *data-file*))) (defn save-data "serializes data to *data-file* like" [data] (with-open [f (java.io.FileWriter. (get-file *data-file*))] (print-dup (into [] data) f))) (defn get-gallery "retrieves gallery from a map data" [gallery-url data] (first (filter #(= (% :href) gallery-url) data))) (defn update-data "inserts of updates gallery into data" [gallery data] (let [gallery-url (gallery :href)](save-data (conj (remove #(= (% :href) gallery-url) data) gallery)))) ;; ** views ** ;; (defn get-home "GET / error-message may be a vector with a selector and an error message to display within it." [& error-message] (let [tpl (html-resource (java.io.File. (get-file "tpl/home.html"))) data (load-galleries) main-transform #(transform % [:li.gallery] (clone-for [g data] [:a.url] (set-attr :href (g :last_page)) [:a.url] (content (g :href)) [:a.delete] (set-attr :href (str "/delete?d=" (g :href))))) error-div (first error-message) error-text (second error-message) error-transform (fn [t s m] (if (empty? error-message) t (transform t [s] (content m))))] (emit** (-> tpl main-transform (error-transform error-div error-text))))) (defn add-gallery "adds a a new gallery with gallery url to the list of galleries if gallery-url is not empty and the url is not added already." [input] (if (string? input) (let [current-data (load-galleries) gallery-url (normalize-url input)] (if (empty? (get-gallery gallery-url current-data)) ;; gallery hasn't been added yet (if-let [gallery-data (gallery-info gallery-url)] ;; can retrieve data about gallery (do (save-data (conj current-data gallery-data)) (get-home)) (get-home :div#error-new-gallery "Gallery not found")) (get-home :div#error-new-gallery "Gallery already added."))))) (defn delete-gallery "adds a a new gallery with gallery url to the list of galleries if gallery-url is not empty and the url is not added already." [gallery-url] (let [current-data (load-galleries)] (if (not (empty? gallery-url)) (save-data (remove #(= (% :href) gallery-url) current-data))) (get-home))) (defn check-gallery "checks if a gallery has been updated since last check" [gallery] (let [ data (load-galleries) stored-gallery (get-gallery gallery data) updated (if (seq stored-gallery) ;; gallery found (let [current-gallery (gallery-info gallery) {cur-gal-last-page :last_page cur-gal-num-images :num_images} current-gallery {strd-gal-last-page :last_page strd-gal-num-images :num_images} stored-gallery] (if (and (= cur-gal-last-page strd-gal-last-page) ;; gallery unchanged (= cur-gal-num-images strd-gal-num-images)) "NO" (do (update-data current-gallery data) "YES"))) "NO")] {:headers {"Content-Type" "application/json"} :body (json-str {:updated updated})})) ;; ** route dispatcher ** ;; (defroutes main-routes (GET "/" [] (get-home)) (GET "/add" [d] (add-gallery d)) (GET "/delete" [d] (delete-gallery d)) (GET "/check" [d] (check-gallery d)) (route/resources "/") (route/not-found "Page not found")) (def app (handler/api main-routes)) ;; ** server starter ** ;; (defn -main [& args] (run-jetty app {:port 3000}))
null
https://raw.githubusercontent.com/pistacchio/deviantchecker/8b6c59e7f196b0051abba53b6a616fe4618fa080/src/org/github/pistacchio/deviantchecker/core.clj
clojure
** utilities ** ;; ** data management ** ;; ** views ** ;; gallery hasn't been added yet can retrieve data about gallery gallery found gallery unchanged ** route dispatcher ** ;; ** server starter ** ;;
(ns org.github.pistacchio.deviantchecker.core (:use compojure.core ring.adapter.jetty org.github.pistacchio.deviantchecker.scraper [clojure.contrib.json :only (json-str)] net.cgrand.enlive-html) (:require [compojure.route :as route] [compojure.handler :as handler] [clojure.java.io :as io]) (:gen-class)) (def *data-file* "data/data.dat") (defn emit** "given an enlive form, returns a string" [tpl] (apply str (emit* tpl))) (defn get-file "return the absolute path of relative-path" [relative-path] (.getPath (io/resource relative-path))) (defn load-galleries "returns a gallery database stored in *data-file*" [] (load-file (get-file *data-file*))) (defn save-data "serializes data to *data-file* like" [data] (with-open [f (java.io.FileWriter. (get-file *data-file*))] (print-dup (into [] data) f))) (defn get-gallery "retrieves gallery from a map data" [gallery-url data] (first (filter #(= (% :href) gallery-url) data))) (defn update-data "inserts of updates gallery into data" [gallery data] (let [gallery-url (gallery :href)](save-data (conj (remove #(= (% :href) gallery-url) data) gallery)))) (defn get-home "GET / error-message may be a vector with a selector and an error message to display within it." [& error-message] (let [tpl (html-resource (java.io.File. (get-file "tpl/home.html"))) data (load-galleries) main-transform #(transform % [:li.gallery] (clone-for [g data] [:a.url] (set-attr :href (g :last_page)) [:a.url] (content (g :href)) [:a.delete] (set-attr :href (str "/delete?d=" (g :href))))) error-div (first error-message) error-text (second error-message) error-transform (fn [t s m] (if (empty? error-message) t (transform t [s] (content m))))] (emit** (-> tpl main-transform (error-transform error-div error-text))))) (defn add-gallery "adds a a new gallery with gallery url to the list of galleries if gallery-url is not empty and the url is not added already." [input] (if (string? input) (let [current-data (load-galleries) gallery-url (normalize-url input)] (do (save-data (conj current-data gallery-data)) (get-home)) (get-home :div#error-new-gallery "Gallery not found")) (get-home :div#error-new-gallery "Gallery already added."))))) (defn delete-gallery "adds a a new gallery with gallery url to the list of galleries if gallery-url is not empty and the url is not added already." [gallery-url] (let [current-data (load-galleries)] (if (not (empty? gallery-url)) (save-data (remove #(= (% :href) gallery-url) current-data))) (get-home))) (defn check-gallery "checks if a gallery has been updated since last check" [gallery] (let [ data (load-galleries) stored-gallery (get-gallery gallery data) (let [current-gallery (gallery-info gallery) {cur-gal-last-page :last_page cur-gal-num-images :num_images} current-gallery {strd-gal-last-page :last_page strd-gal-num-images :num_images} stored-gallery] (= cur-gal-num-images strd-gal-num-images)) "NO" (do (update-data current-gallery data) "YES"))) "NO")] {:headers {"Content-Type" "application/json"} :body (json-str {:updated updated})})) (defroutes main-routes (GET "/" [] (get-home)) (GET "/add" [d] (add-gallery d)) (GET "/delete" [d] (delete-gallery d)) (GET "/check" [d] (check-gallery d)) (route/resources "/") (route/not-found "Page not found")) (def app (handler/api main-routes)) (defn -main [& args] (run-jetty app {:port 3000}))
7e32c296350a075a0f2a5270c36b76ae5d63a9bb32597b9bf89bcc3f412b22ae
squint-cljs/squint
http.cljs
(ns bun.http) (def default {:port 3000 :fetch (fn [_req] (js/Response. "Welcome to Bun!"))})
null
https://raw.githubusercontent.com/squint-cljs/squint/a77ace9d29ccb78ff6d0ab94d6502adc76db2134/examples/bun/http.cljs
clojure
(ns bun.http) (def default {:port 3000 :fetch (fn [_req] (js/Response. "Welcome to Bun!"))})
b1c24a2490563afcec99e2f788e7452a5259fd4d1300951afa171e3ff3db38b9
unnohideyuki/bunny
Desugar.hs
module Desugar where import Core import PreDefined import Symbol import TrCore import qualified Typing as Ty dsgModule :: Id -> Ty.Program -> Ty.Assumps -> ConstructorInfo -> Module dsgModule modident bgs as ci = let [(es, iss)] = bgs is = concat iss es' = map (\(n, _, alts) -> (n, alts)) es vdefs = dsgBs [] (es' ++ is) ci b = translateVdefs as vdefs ci in Core.Module modident [b]
null
https://raw.githubusercontent.com/unnohideyuki/bunny/501856ff48f14b252b674585f25a2bf3801cb185/compiler/src/Desugar.hs
haskell
module Desugar where import Core import PreDefined import Symbol import TrCore import qualified Typing as Ty dsgModule :: Id -> Ty.Program -> Ty.Assumps -> ConstructorInfo -> Module dsgModule modident bgs as ci = let [(es, iss)] = bgs is = concat iss es' = map (\(n, _, alts) -> (n, alts)) es vdefs = dsgBs [] (es' ++ is) ci b = translateVdefs as vdefs ci in Core.Module modident [b]
7caf090ca553f61c0ed8cf87437e3ac423b658f935e3e236bbe1f231fbf04321
dennismckinnon/Ethereum-Contracts
Database.lsp
{ [[0x0]] (Caller) ; Initial admin [[0x1]] 0 ;Permissions address (can be hardcoded of admin can set it) [[0x2]] 0x100 ;Database start location [[0x3]] 32 ;Block Size Set at database creation [[0x4]] 0; Number of entries } { (if (= @@0x0 (CALLER)) { [0x0]1 ;Admin } { [0x200] (CALLER) (when @@0x1 (call @@0x1 0 0 0x200 32 0 32)) ;When a permissions address has been given call it and return permission level of caller } ) (unless @0x0 (stop)) ;If not admin then don't allow them to do anything to the database (the dump if implemented would need to be before this) [0x0](calldataload 0) Add Permissions contract ( Format : " setperm " 0xPERMISSIONSADDR ) (when (= @0x0 "setperm") [[0x1]] (calldataload 32) ) (when (= @0x0 "kill") (suicide (CALLER)) ) Add / edit Database entry link ( Format : " moddbe " # locator 0xIndicator ( 6 hex digits ) 0xinfohash " filetype " " quality " " title " " description " ) - See top (when (= @0x0 "moddbe") { [0x60] (calldataload 32) ;#locator! very important (when (> @0x60 @@0x4) [[0x4]]@0x60) ;If the locator is greater then the current entry number [0x40] (calldataload 64) ;Data telling which parts are available. [0x20] (calldataload 96) ;This is the infohash. It is required! [0x110] 138 ;Calldata pointer [0x60] (+ (* @0x60 @@0x3) @@0x2) ;Find the starting location of this data entry INFOHASH ( 1 Seg ) ; I STORE THE INFOHASH TO MAKE THE USER MANAGER SIMPLER ( and this is the point where i realized i made this too difficult ) [0x140] 1;Data field size in data segments [0x100] (MOD @0x40 0x10) [0x40] (DIV @0x40 0x10) ;Copy out the new last digit (for [0xE0]0 (> @0xE0 @0x140) [0xE0](+ @0xE0 1) { (when @0x100 { [0x80] (calldataload @0x110) ;Get the next data segment [[@0x60]] @0x80 ;Copy data over } ) [0x60] (+ @0x60 1) ;Increment storage pointer } ) UPLOADER ( 1 Seg ) [0x140] 1;Data field size in data segments [0x100] (MOD @0x40 0x10) [0x40] (DIV @0x40 0x10) ;Copy out the new last digit (for [0xE0]0 (> @0xE0 @0x140) [0xE0](+ @0xE0 1) { (when @0x100 { [0x80] (calldataload @0x110) ;Get the next data segment [[@0x60]] @0x80 ;Copy data over } ) [0x60] (+ @0x60 1) ;Increment storage pointer } ) FILE TYPE ( 1 Seg ) [0x140] 1;Data field size in data segments [0x100] (MOD @0x40 0x10) [0x40] (DIV @0x40 0x10) ;Copy out the new last digit (for [0xE0]0 (> @0xE0 @0x140) [0xE0](+ @0xE0 1) { (when @0x100 { [0x80] (calldataload @0x110) ;Get the next data segment [[@0x60]] @0x80 ;Copy data over } ) [0x60] (+ @0x60 1) ;Increment storage pointer } ) FILE QUALITY ( 1 Seg ) [0x140] 1;Data field size in data segments [0x100] (MOD @0x40 0x10) [0x40] (DIV @0x40 0x10) ;Copy out the new last digit (for [0xE0]0 (> @0xE0 @0x140) [0xE0](+ @0xE0 1) { (when @0x100 { [0x80] (calldataload @0x110) ;Get the next data segment [[@0x60]] @0x80 ;Copy data over } ) [0x60] (+ @0x60 1) ;Increment storage pointer } ) TITLE ( 2 Seg ) [0x140] 2;Data field size in data segments [0x100] (MOD @0x40 0x10) [0x40] (DIV @0x40 0x10) ;Copy out the new last digit (for [0xE0]0 (> @0xE0 @0x140) [0xE0](+ @0xE0 1) { (when @0x100 { [0x80] (calldataload @0x110) ;Get the next data segment [[@0x60]] @0x80 ;Copy data over } ) [0x60] (+ @0x60 1) ;Increment storage pointer } ) DESCRIPTION ( 25 Seg ) [0x140] 25;Data field size in data segments [0x100] (MOD @0x40 0x10) [0x40] (DIV @0x40 0x10) ;Copy out the new last digit (for [0xE0]0 (> @0xE0 @0x140) [0xE0](+ @0xE0 1) { (when @0x100 { [0x80] (calldataload @0x110) ;Get the next data segment [[@0x60]] @0x80 ;Copy data over } ) [0x60] (+ @0x60 1) ;Increment storage pointer } ) (stop) } ) ;Delete magnet link and data (Format: "deldbe" #locator) (when (= @0x0 "deldbe") { [0x20] (calldataload 32) ;Get #locator [0x40] (+ (* @0x20 @@0x3) @@0x2) ;Initial storage location of this entry [0x200] @0x40 ;copy this location (for [0x60]0 (< @0x60 @@0x3) [0x60](+ @0x60 1) { [0x80](+ (* @0x20 @@0x3) @@0x2) ;Start point for the last entry (for copy over) [[@0x40]] @@ @0x80; perform copy [[@0x80]] 0 ;Delete [0x40](+ @0x40 1) [0x80](+ @0x80 1);increment to next slot [[0x4]](- @@0x4 1) ;reduce the entry count } ) [0x200] @@ @0x40 ;This is the new infohash (to send back) (return 0x200 32) ;Sends it back } ) ;Database Dump (Format: "dumpdb" 0xDUMPADDRESS) (no reason to protect this since the information is public anyways) ;This is likely extremely expensive it might be better to do this using external methods (hence commented out) ; (when (= @0x0 "dumpdb") ; { [ 0x20](calldataload 32 ) ; [0x40](* (+ @0x60 1) @@0x3) ;Length of database [ 0xE0 ] 0x100 ( for [ 0x60]@@0x2 ( > @0x60 ( + @0x40 @@0x2 ) ) [ 0x60](+ @0x60 1 ) ; { ; [@0xE0]@@ @0x60 ;Copy to memory ; [0xE0](+ @0xE0 0x20) ;Move mem pointer ; } ; ) ( call @0x20 0 0 0x100 ( * ) 0 0 ) ; Send all the data away ; (stop) ; } ; ) }
null
https://raw.githubusercontent.com/dennismckinnon/Ethereum-Contracts/25b5e7037da382dd95a1376fad81f936f6610b36/Magnet%20DB/Database.lsp
lisp
Initial admin Permissions address (can be hardcoded of admin can set it) Database start location Block Size Set at database creation Number of entries Admin When a permissions address has been given call it and return permission level of caller If not admin then don't allow them to do anything to the database (the dump if implemented would need to be before this) #locator! very important If the locator is greater then the current entry number Data telling which parts are available. This is the infohash. It is required! Calldata pointer Find the starting location of this data entry I STORE THE INFOHASH TO MAKE THE USER MANAGER SIMPLER ( and this is the point where i realized i made this too difficult ) Data field size in data segments Copy out the new last digit Get the next data segment Copy data over Increment storage pointer Data field size in data segments Copy out the new last digit Get the next data segment Copy data over Increment storage pointer Data field size in data segments Copy out the new last digit Get the next data segment Copy data over Increment storage pointer Data field size in data segments Copy out the new last digit Get the next data segment Copy data over Increment storage pointer Data field size in data segments Copy out the new last digit Get the next data segment Copy data over Increment storage pointer Data field size in data segments Copy out the new last digit Get the next data segment Copy data over Increment storage pointer Delete magnet link and data (Format: "deldbe" #locator) Get #locator Initial storage location of this entry copy this location Start point for the last entry (for copy over) perform copy Delete increment to next slot reduce the entry count This is the new infohash (to send back) Sends it back Database Dump (Format: "dumpdb" 0xDUMPADDRESS) (no reason to protect this since the information is public anyways) This is likely extremely expensive it might be better to do this using external methods (hence commented out) (when (= @0x0 "dumpdb") { [0x40](* (+ @0x60 1) @@0x3) ;Length of database { [@0xE0]@@ @0x60 ;Copy to memory [0xE0](+ @0xE0 0x20) ;Move mem pointer } ) Send all the data away (stop) } )
{ } { (if (= @@0x0 (CALLER)) { } { [0x200] (CALLER) } ) [0x0](calldataload 0) Add Permissions contract ( Format : " setperm " 0xPERMISSIONSADDR ) (when (= @0x0 "setperm") [[0x1]] (calldataload 32) ) (when (= @0x0 "kill") (suicide (CALLER)) ) Add / edit Database entry link ( Format : " moddbe " # locator 0xIndicator ( 6 hex digits ) 0xinfohash " filetype " " quality " " title " " description " ) - See top (when (= @0x0 "moddbe") { [0x100] (MOD @0x40 0x10) (for [0xE0]0 (> @0xE0 @0x140) [0xE0](+ @0xE0 1) { (when @0x100 { } ) } ) UPLOADER ( 1 Seg ) [0x100] (MOD @0x40 0x10) (for [0xE0]0 (> @0xE0 @0x140) [0xE0](+ @0xE0 1) { (when @0x100 { } ) } ) FILE TYPE ( 1 Seg ) [0x100] (MOD @0x40 0x10) (for [0xE0]0 (> @0xE0 @0x140) [0xE0](+ @0xE0 1) { (when @0x100 { } ) } ) FILE QUALITY ( 1 Seg ) [0x100] (MOD @0x40 0x10) (for [0xE0]0 (> @0xE0 @0x140) [0xE0](+ @0xE0 1) { (when @0x100 { } ) } ) TITLE ( 2 Seg ) [0x100] (MOD @0x40 0x10) (for [0xE0]0 (> @0xE0 @0x140) [0xE0](+ @0xE0 1) { (when @0x100 { } ) } ) DESCRIPTION ( 25 Seg ) [0x100] (MOD @0x40 0x10) (for [0xE0]0 (> @0xE0 @0x140) [0xE0](+ @0xE0 1) { (when @0x100 { } ) } ) (stop) } ) (when (= @0x0 "deldbe") { (for [0x60]0 (< @0x60 @@0x3) [0x60](+ @0x60 1) { [0x40](+ @0x40 1) } ) } ) [ 0x20](calldataload 32 ) [ 0xE0 ] 0x100 ( for [ 0x60]@@0x2 ( > @0x60 ( + @0x40 @@0x2 ) ) [ 0x60](+ @0x60 1 ) }
5a3d993e2c68b30debb38a2dd5cd408fbd616fa63a9f5255b1efc814f23a6be1
FPBench/FPBench
test-core2smtlib2.rkt
#lang racket (require generic-flonum) (require "test-common.rkt" "../src/core2smtlib2.rkt") (define (translate->smt prog ctx type test-file) (*prog* (core->smtlib2 prog "f")) test-file) (define (run<-smt exec-name ctx type number) (call-with-output-file exec-name #:exists 'replace (lambda (port) (define-values (w p) (match type ['binary32 (values 8 24)] ['binary64 (values 11 53)])) (fprintf port "~a\n\n" (*prog*)) (for ([arg ctx] [i (in-naturals)]) (match-define (cons var value) arg) (fprintf port "(define-const arg~a (_ FloatingPoint ~a ~a) ~a)\n" i w p (number->smt (value->real value) w p 'nearestEven))) (fprintf port "(check-sat)\n") (if (= (length ctx) 0) (fprintf port "(eval f)\n") (fprintf port "(eval (f ~a))\n" (string-join (for/list ([i (in-range (length ctx))]) (format "arg~a" i)) " "))))) (define out (with-output-to-string (lambda () (system (format "z3 ~a" exec-name))))) (define fp (last (string-split out "\n"))) (define stx (read-syntax exec-name (open-input-string fp))) (define out* (match (syntax-e stx) [(list (app syntax-e '_) (app syntax-e 'NaN) stxw stxp) +nan.0] [(list (app syntax-e '_) (app syntax-e '+oo) stxw stxp) +inf.0] [(list (app syntax-e '_) (app syntax-e '-oo) stxw stxp) -inf.0] [(list (app syntax-e '_) (app syntax-e '+zero) stxw stxp) 0] [(list (app syntax-e '_) (app syntax-e '-zero) stxw stxp) -0] [(list (app syntax-e 'fp) stxS stxE stxC) (let ([S (syntax->datum stxS)] [E (syntax->datum stxE)] [C (syntax->datum stxC)]) (match type ['binary32 (floating-point-bytes->real (integer->integer-bytes (bitwise-ior (arithmetic-shift S 31) (arithmetic-shift E 23) C) 4 #f))] ['binary64 (floating-point-bytes->real (integer->integer-bytes (bitwise-ior (arithmetic-shift S 63) (arithmetic-shift E 52) C) 8 #f))]))])) (cons (->value out* type) (format "~a" out*))) (define (smt-equality a b ulps type ignore?) (cond [(equal? a 'timeout) true] [(and (gflnan? a) (gflnan? b)) #t] [else (define a* (->value a type)) (define b* (->value b type)) (gfl= a* b*)])) (define (smt-format-args var val type) (define-values (w p) (match type ['binary32 (values 8 24)] ['binary64 (values 11 53)])) (format "~a = ~a\n\t~a = ~a" var val var (number->smt (value->real val) w p 'nearestEven))) (define (smt-format-output result) (format "~a" result)) (define smt-tester (tester "smt" translate->smt run<-smt smt-equality smt-format-args smt-format-output (const #t) smt-supported #f)) ; Command line (module+ main (parameterize ([*tester* smt-tester]) (let ([state (test-core (current-command-line-arguments) (current-input-port) "stdin" "/tmp/test.smt")]) (exit state))))
null
https://raw.githubusercontent.com/FPBench/FPBench/43a8f4854baebce88614059e4b48bcfc08d97f61/infra/test-core2smtlib2.rkt
racket
Command line
#lang racket (require generic-flonum) (require "test-common.rkt" "../src/core2smtlib2.rkt") (define (translate->smt prog ctx type test-file) (*prog* (core->smtlib2 prog "f")) test-file) (define (run<-smt exec-name ctx type number) (call-with-output-file exec-name #:exists 'replace (lambda (port) (define-values (w p) (match type ['binary32 (values 8 24)] ['binary64 (values 11 53)])) (fprintf port "~a\n\n" (*prog*)) (for ([arg ctx] [i (in-naturals)]) (match-define (cons var value) arg) (fprintf port "(define-const arg~a (_ FloatingPoint ~a ~a) ~a)\n" i w p (number->smt (value->real value) w p 'nearestEven))) (fprintf port "(check-sat)\n") (if (= (length ctx) 0) (fprintf port "(eval f)\n") (fprintf port "(eval (f ~a))\n" (string-join (for/list ([i (in-range (length ctx))]) (format "arg~a" i)) " "))))) (define out (with-output-to-string (lambda () (system (format "z3 ~a" exec-name))))) (define fp (last (string-split out "\n"))) (define stx (read-syntax exec-name (open-input-string fp))) (define out* (match (syntax-e stx) [(list (app syntax-e '_) (app syntax-e 'NaN) stxw stxp) +nan.0] [(list (app syntax-e '_) (app syntax-e '+oo) stxw stxp) +inf.0] [(list (app syntax-e '_) (app syntax-e '-oo) stxw stxp) -inf.0] [(list (app syntax-e '_) (app syntax-e '+zero) stxw stxp) 0] [(list (app syntax-e '_) (app syntax-e '-zero) stxw stxp) -0] [(list (app syntax-e 'fp) stxS stxE stxC) (let ([S (syntax->datum stxS)] [E (syntax->datum stxE)] [C (syntax->datum stxC)]) (match type ['binary32 (floating-point-bytes->real (integer->integer-bytes (bitwise-ior (arithmetic-shift S 31) (arithmetic-shift E 23) C) 4 #f))] ['binary64 (floating-point-bytes->real (integer->integer-bytes (bitwise-ior (arithmetic-shift S 63) (arithmetic-shift E 52) C) 8 #f))]))])) (cons (->value out* type) (format "~a" out*))) (define (smt-equality a b ulps type ignore?) (cond [(equal? a 'timeout) true] [(and (gflnan? a) (gflnan? b)) #t] [else (define a* (->value a type)) (define b* (->value b type)) (gfl= a* b*)])) (define (smt-format-args var val type) (define-values (w p) (match type ['binary32 (values 8 24)] ['binary64 (values 11 53)])) (format "~a = ~a\n\t~a = ~a" var val var (number->smt (value->real val) w p 'nearestEven))) (define (smt-format-output result) (format "~a" result)) (define smt-tester (tester "smt" translate->smt run<-smt smt-equality smt-format-args smt-format-output (const #t) smt-supported #f)) (module+ main (parameterize ([*tester* smt-tester]) (let ([state (test-core (current-command-line-arguments) (current-input-port) "stdin" "/tmp/test.smt")]) (exit state))))
c570d6c8112bf2b28c2bde8b8895e03b1188a9f1c61c6737bc14a3b69fcb0518
examachine/parallpairs
allPairsVertical.ml
* * * * Author : < > * * * * Copyright ( C ) 2011 - 2017 Gok Us Sibernetik Ar&Ge Ltd. * * * * This program is free software ; you can redistribute it and/or modify it under * * the terms of the Affero GNU General Public License as published by the Free * * Software Foundation ; either version 3 of the License , or ( at your option ) * * any later version . * * * * Please read the COPYING file . * * ** ** Author: Eray Ozkural <> ** ** Copyright (C) 2011-2017 Gok Us Sibernetik Ar&Ge Ltd. ** ** This program is free software; you can redistribute it and/or modify it under** the terms of the Affero GNU General Public License as published by the Free ** Software Foundation; either version 3 of the License, or (at your option) ** any later version. ** ** Please read the COPYING file. ** *) open Printf let index x dv i = Array.iter (fun dvelt-> i.(dvelt.term) <- SparseVector.append i.(dvelt.term) (x,dvelt.freq) ) dv.vector let all_pairs_vertical = let o = ref Docmatch_List.empty in let m = max_dim v in (* maximum dimension in data set *) (* inverted lists *) let v = Util.map Dv.normalize v in let i = Array.init (m+1) (fun ix->SparseVector.make ()) in let id = ref 0 in List.iter (fun dv -> o := Docmatch_List.union !o (find_matches_0 !id x i t); index !id dv i; id := !id + 1 ) v; !o (* return output set*)
null
https://raw.githubusercontent.com/examachine/parallpairs/6fafe8d6de3a55490cb8ed5ffd3493a28a914e0a/src/allPairsVertical.ml
ocaml
maximum dimension in data set inverted lists return output set
* * * * Author : < > * * * * Copyright ( C ) 2011 - 2017 Gok Us Sibernetik Ar&Ge Ltd. * * * * This program is free software ; you can redistribute it and/or modify it under * * the terms of the Affero GNU General Public License as published by the Free * * Software Foundation ; either version 3 of the License , or ( at your option ) * * any later version . * * * * Please read the COPYING file . * * ** ** Author: Eray Ozkural <> ** ** Copyright (C) 2011-2017 Gok Us Sibernetik Ar&Ge Ltd. ** ** This program is free software; you can redistribute it and/or modify it under** the terms of the Affero GNU General Public License as published by the Free ** Software Foundation; either version 3 of the License, or (at your option) ** any later version. ** ** Please read the COPYING file. ** *) open Printf let index x dv i = Array.iter (fun dvelt-> i.(dvelt.term) <- SparseVector.append i.(dvelt.term) (x,dvelt.freq) ) dv.vector let all_pairs_vertical = let o = ref Docmatch_List.empty in let v = Util.map Dv.normalize v in let i = Array.init (m+1) (fun ix->SparseVector.make ()) in let id = ref 0 in List.iter (fun dv -> o := Docmatch_List.union !o (find_matches_0 !id x i t); index !id dv i; id := !id + 1 ) v;
f9a39d4064da9eddbdfd3079954e157887d2dd4caa42210aa0b9d296dee03140
somnusand/Poker
hackney_url.erl
%% -*- erlang -*- %%% This file is part of released under the Apache 2 license . %%% See the NOTICE for more information. %%% Copyright ( c ) 2012 - 2015 < > Copyright ( c ) 2011 , < > %%% %% @doc module to manage urls. -module(hackney_url). -export([parse_url/1, transport_scheme/1, unparse_url/1, urldecode/1, urldecode/2, urlencode/1, urlencode/2, parse_qs/1, qs/1, make_url/3, fix_path/1, pathencode/1, normalize/1, normalize/2]). -include("hackney_lib.hrl"). -type qs_vals() :: [{binary(), binary() | true}]. @doc an url and return a # hackney_url record . -spec parse_url(URL::binary()|list()) -> hackney_url(). parse_url(URL) when is_list(URL) -> case unicode:characters_to_binary(URL) of URL1 when is_binary(URL1) -> parse_url(URL1); _ -> parse_url(unicode:characters_to_binary(list_to_binary(URL))) end; parse_url(<<"http://", Rest/binary>>) -> parse_url(Rest, #hackney_url{transport=hackney_tcp, scheme=http}); parse_url(<<"https://", Rest/binary>>) -> parse_url(Rest, #hackney_url{transport=hackney_ssl, scheme=https}); parse_url(<<"http+unix://", Rest/binary>>) -> parse_url(Rest, #hackney_url{transport=hackney_local_tcp, scheme=http_unix}); parse_url(URL) -> parse_url(URL, #hackney_url{transport=hackney_tcp, scheme=http}). parse_url(URL, S) -> case binary:split(URL, <<"/">>) of [Addr] -> Path = <<"/">>, parse_addr(Addr, S#hackney_url{raw_path = Path, path = Path }); [Addr, Path] -> RawPath = <<"/", Path/binary>>, {Path1, Query, Fragment} = parse_path(RawPath), parse_addr(Addr, S#hackney_url{raw_path = RawPath, path = Path1, qs = Query, fragment = Fragment}) end. @doc the encoding of a Url %% use the hackney_url:pathencode/1 to encode an url -spec normalize(URL) -> NormalizedUrl when URL :: binary() | list() | hackney_url(), NormalizedUrl :: hackney_url(). normalize(Url) -> normalize(Url, fun hackney_url:pathencode/1). @doc the encoding of a Url -spec normalize(URL, Fun) -> NormalizedUrl when URL :: binary() | list() | hackney_url(), Fun :: fun(), NormalizedUrl :: hackney_url(). normalize(Url, Fun) when is_list(Url) orelse is_binary(Url) -> normalize(parse_url(Url), Fun); normalize(#hackney_url{}=Url, Fun) when is_function(Fun, 1) -> #hackney_url{scheme=Scheme, host = Host0, port = Port, netloc = Netloc0, path = Path} = Url, {Host, Netloc} = case inet_parse:address(Host0) of {ok, {_, _, _, _}} -> {Host0, Netloc0}; {ok, {_, _, _, _, _, _, _, _}} -> {Host0, Netloc0}; _ -> Host1 = unicode:characters_to_list( urldecode(unicode:characters_to_binary(Host0))), %% encode domain if needed Host2 = idna:to_ascii(Host1), Netloc1 = case {Scheme, Port} of {http, 80} -> list_to_binary(Host2); {https, 443} -> list_to_binary(Host2); {http_unix, _} -> list_to_binary(Host2); _ -> iolist_to_binary([Host2, ":", integer_to_list(Port)]) end, {Host2, Netloc1} end, Path1 = Fun(Path), Url#hackney_url{host=Host, netloc=Netloc, path=Path1}. transport_scheme(hackney_tcp) -> http; transport_scheme(hackney_ssl) -> https; transport_scheme(hackney_local_tcp) -> http_unix. unparse_url(#hackney_url{}=Url) -> #hackney_url{scheme = Scheme, netloc = Netloc, path = Path, qs = Qs, fragment = Fragment, user = User, password = Password} = Url, Scheme1 = case Scheme of http -> <<"http://">>; https -> <<"https://">>; http_unix -> <<"http+unix://">> end, Netloc1 = case User of <<>> -> Netloc; _ when Password /= <<>>, Password /= <<"">> -> << User/binary, ":", Password/binary, "@", Netloc/binary >>; _ -> << User/binary, "@", Netloc/binary >> end, Qs1 = case Qs of <<>> -> <<>>; _ -> << "?", Qs/binary >> end, Fragment1 = case Fragment of <<>> -> <<>>; _ -> << "#", Fragment/binary >> end, Path1 = case Path of nil -> <<>>; undefined -> <<>>; <<>> -> <<"/">>; _ -> Path end, << Scheme1/binary, Netloc1/binary, Path1/binary, Qs1/binary, Fragment1/binary >>. @private parse_addr(Addr, S) -> case binary:split(Addr, <<"@">>) of [Addr] -> parse_netloc(Addr, S#hackney_url{netloc=Addr}); [Credentials, Addr1] -> case binary:split(Credentials, <<":">>) of [User, Password] -> parse_netloc(Addr1, S#hackney_url{netloc=Addr1, user = User, password = Password}); [User] -> parse_netloc(Addr1, S#hackney_url{netloc = Addr1, user = User, password = <<>> }) end end. parse_netloc(<<"[", Rest/binary>>, #hackney_url{transport=Transport}=S) -> case binary:split(Rest, <<"]">>) of [Host, <<>>] when Transport =:= hackney_tcp -> S#hackney_url{host=binary_to_list(Host), port=80}; [Host, <<>>] when Transport =:= hackney_ssl -> S#hackney_url{host=binary_to_list(Host), port=443}; [Host, <<":", Port/binary>>] -> S#hackney_url{host=binary_to_list(Host), port=list_to_integer(binary_to_list(Port))}; _ -> parse_netloc(Rest, S) end; parse_netloc(Netloc, #hackney_url{transport=Transport}=S) -> case binary:split(Netloc, <<":">>) of [Host] when Transport =:= hackney_tcp -> S#hackney_url{host=unicode:characters_to_list((Host)), port=80}; [Host] when Transport =:= hackney_ssl -> S#hackney_url{host=unicode:characters_to_list(Host), port=443}; [Host] when Transport =:= hackney_local_tcp -> S#hackney_url{host=unicode:characters_to_list(urldecode(Host)), port=0}; [Host, Port] -> S#hackney_url{host=unicode:characters_to_list(Host), port=list_to_integer(binary_to_list(Port))} end. parse_path(Path) -> case binary:split(Path, <<"?">>) of [_Path] -> {Path1, Fragment} = parse_fragment(Path), {Path1, <<>>, Fragment}; [Path1, Query] -> {Query1, Fragment} = parse_fragment(Query), {Path1, Query1, Fragment} end. parse_fragment(S) -> case binary:split(S, <<"#">>) of [_S] -> {S, <<>>}; [S1, F] -> {S1, F} end. %% @doc Decode a URL encoded binary. @equiv urldecode(Bin , crash ) -spec urldecode(binary()) -> binary(). urldecode(Bin) when is_binary(Bin) -> urldecode(Bin, <<>>, crash). %% @doc Decode a URL encoded binary. The second argument specifies how to handle percent characters that are not followed by two valid hex characters . Use ` skip ' to ignore such errors , %% if `crash' is used the function will fail with the reason `badarg'. -spec urldecode(binary(), crash | skip) -> binary(). urldecode(Bin, OnError) when is_binary(Bin) -> urldecode(Bin, <<>>, OnError). -spec urldecode(binary(), binary(), crash | skip) -> binary(). , H , L , Rest / binary > > , Acc , OnError ) - > G = unhex(H), M = unhex(L), if G =:= error; M =:= error -> case OnError of skip -> ok; crash -> erlang:error(badarg) end, > > , ) ; true -> urldecode(Rest, <<Acc/binary, (G bsl 4 bor M)>>, OnError) end; , Rest / binary > > , Acc , OnError ) - > case OnError of skip -> ok; crash -> erlang:error(badarg) end, > > , ) ; urldecode(<<$+, Rest/binary>>, Acc, OnError) -> urldecode(Rest, <<Acc/binary, $ >>, OnError); urldecode(<<C, Rest/binary>>, Acc, OnError) -> urldecode(Rest, <<Acc/binary, C>>, OnError); urldecode(<<>>, Acc, _OnError) -> Acc. -spec unhex(byte()) -> byte() | error. unhex(C) when C >= $0, C =< $9 -> C - $0; unhex(C) when C >= $A, C =< $F -> C - $A + 10; unhex(C) when C >= $a, C =< $f -> C - $a + 10; unhex(_) -> error. %% @doc URL encode a string binary. -spec urlencode(binary() | string()) -> binary(). urlencode(Bin) -> urlencode(Bin, []). %% @doc URL encode a string binary. %% The `noplus' option disables the default behaviour of quoting space characters , ` \s ' , as ` + ' . The ` upper ' option overrides the default behaviour %% of writing hex numbers using lowecase letters to using uppercase letters %% instead. -spec urlencode(binary() | string(), [noplus|upper]) -> binary(). urlencode(Bin, Opts) -> Plus = not proplists:get_value(noplus, Opts, false), Upper = proplists:get_value(upper, Opts, false), urlencode(hackney_bstr:to_binary(Bin), <<>>, Plus, Upper). -spec urlencode(binary(), binary(), boolean(), boolean()) -> binary(). urlencode(<<C, Rest/binary>>, Acc, P=Plus, U=Upper) -> if C >= $0, C =< $9 -> urlencode(Rest, <<Acc/binary, C>>, P, U); C >= $A, C =< $Z -> urlencode(Rest, <<Acc/binary, C>>, P, U); C >= $a, C =< $z -> urlencode(Rest, <<Acc/binary, C>>, P, U); C =:= $.; C =:= $-; C =:= $~; C =:= $_; C =:= $*; C =:= $@ -> urlencode(Rest, <<Acc/binary, C>>, P, U); C =:= $(; C =:= $); C =:= $!, C =:= $$ -> urlencode(Rest, <<Acc/binary, C>>, P, U); C =:= $ , Plus -> urlencode(Rest, <<Acc/binary, $+>>, P, U); true -> H = C band 16#F0 bsr 4, L = C band 16#0F, H1 = if Upper -> tohexu(H); true -> tohexl(H) end, L1 = if Upper -> tohexu(L); true -> tohexl(L) end, , H1 , L1 > > , P , U ) end; urlencode(<<>>, Acc, _Plus, _Upper) -> Acc. -spec tohexu(byte()) -> byte(). tohexu(C) when C < 10 -> $0 + C; tohexu(C) when C < 16 -> $A + C - 10. -spec tohexl(byte()) -> byte(). tohexl(C) when C < 10 -> $0 + C; tohexl(C) when C < 16 -> $a + C - 10. %% parse a query or a form from a binary and return a list of properties -spec parse_qs(binary()) -> qs_vals(). parse_qs(<<>>) -> []; parse_qs(Bin) -> Tokens = binary:split(Bin, <<"&">>, [trim, global]), [case binary:split(Token, <<"=">>, [trim]) of [T] -> {urldecode(T), true}; [Name, Value] -> {urldecode(Name), urldecode(Value)} end || Token <- Tokens]. %% @doc encode query properties to binary -spec qs(qs_vals()) -> binary(). qs(KVs) -> qs(KVs, []). qs([], Acc) -> hackney_bstr:join(lists:reverse(Acc), <<"&">>); qs([{K, V}|R], Acc) -> K1 = urlencode(K), V1 = urlencode(V), Line = << K1/binary, "=", V1/binary >>, qs(R, [Line | Acc]). %% @doc construct an url from a base url, a path and a list of %% properties to give to the url. -spec make_url(binary(), binary() | [binary()], binary() | qs_vals()) -> binary(). make_url(Url, Path, Query) when is_list(Query) -> %% a list of properties has been passed make_url(Url, Path, qs(Query)); make_url(Url, Path, Query) when is_binary(Path) -> make_url(Url, [Path], Query); make_url(Url, PathParts, Query) when is_binary(Query) -> %% create path PathParts1 = [fix_path(P) || P <- PathParts, P /= "", P /= "/" orelse P /= <<"/">>], Path = hackney_bstr:join([<<>> | PathParts1], <<"/">>), %% initialise the query Query1 = case Query of <<>> -> <<>>; _ -> << "?", Query/binary >> end, %% make the final uri iolist_to_binary([fix_path(Url), Path, Query1]). fix_path(Path) when is_list(Path) -> fix_path(list_to_binary(Path)); fix_path(<<>>) -> <<>>; fix_path(<<"/", Path/binary>>) -> fix_path(Path); fix_path(Path) -> case binary:part(Path, {size(Path), -1}) of <<"/">> -> binary:part(Path, {0, size(Path) - 1}); _ -> Path end. %% @doc encode a URL path %% @equiv pathencode(Bin, []) -spec pathencode(binary()) -> binary(). pathencode(Bin) -> Parts = binary:split(hackney_bstr:to_binary(Bin), <<"/">>, [global]), do_partial_pathencode(Parts, []). do_partial_pathencode([], Acc) -> hackney_bstr:join(lists:reverse(Acc), <<"/">>); do_partial_pathencode([Part | Rest], Acc) -> do_partial_pathencode(Rest, [partial_pathencode(Part, <<>>) | Acc]). partial_pathencode(<<C, Rest/binary>> = Bin, Acc) -> if C >= $0, C =< $9 -> partial_pathencode(Rest, <<Acc/binary, C>>); C >= $A, C =< $Z -> partial_pathencode(Rest, <<Acc/binary, C>>); C >= $a, C =< $z -> partial_pathencode(Rest, <<Acc/binary, C>>); C =:= $;; C =:= $=; C =:= $,; C =:= $:; C =:= $@ -> partial_pathencode(Rest, <<Acc/binary, C>>); C =:= $.; C =:= $-; C =:= $+; C =:= $~; C =:= $_ -> partial_pathencode(Rest, <<Acc/binary, C>>); C =:= $ -> partial_pathencode(Rest, <<Acc/binary, $+>>); C =:= $% -> %% special case, when a % is passed to the path, check if %% it's a valid escape sequence. If the sequence is valid we %% don't try to encode it and continue, else, we encode it. %% the behaviour is similar to the one you find in chrome: %% case Bin of , H , L , Rest1 / binary > > - > G = unhex(H), M = unhex(L), if G =:= error; M =:= error -> H1 = C band 16#F0 bsr 4, L1 = C band 16#0F, H2 = tohexl(H1), L2 = tohexl(L1), partial_pathencode(Rest, <<Acc/binary, $%, H2, L2>>); true -> partial_pathencode(Rest1, <<Acc/binary, $%, H, L>>) end; _ -> H1 = C band 16#F0 bsr 4, L1 = C band 16#0F, H2 = tohexl(H1), L2 = tohexl(L1), partial_pathencode(Rest, <<Acc/binary, $%, H2, L2>>) end; true -> H = C band 16#F0 bsr 4, L = C band 16#0F, H1 = tohexl(H), L1 = tohexl(L), , H1 , L1 > > ) end; partial_pathencode(<<>>, Acc) -> Acc.
null
https://raw.githubusercontent.com/somnusand/Poker/4934582a4a37f28c53108a6f6e09b55d21925ffa/server/deps/hackney/src/hackney_url.erl
erlang
-*- erlang -*- See the NOTICE for more information. @doc module to manage urls. use the hackney_url:pathencode/1 to encode an url encode domain if needed @doc Decode a URL encoded binary. @doc Decode a URL encoded binary. if `crash' is used the function will fail with the reason `badarg'. @doc URL encode a string binary. @doc URL encode a string binary. The `noplus' option disables the default behaviour of quoting space of writing hex numbers using lowecase letters to using uppercase letters instead. parse a query or a form from a binary and return a list of properties @doc encode query properties to binary @doc construct an url from a base url, a path and a list of properties to give to the url. a list of properties has been passed create path initialise the query make the final uri @doc encode a URL path @equiv pathencode(Bin, []) -> special case, when a % is passed to the path, check if it's a valid escape sequence. If the sequence is valid we don't try to encode it and continue, else, we encode it. the behaviour is similar to the one you find in chrome: , H2, L2>>); , H, L>>) , H2, L2>>)
This file is part of released under the Apache 2 license . Copyright ( c ) 2012 - 2015 < > Copyright ( c ) 2011 , < > -module(hackney_url). -export([parse_url/1, transport_scheme/1, unparse_url/1, urldecode/1, urldecode/2, urlencode/1, urlencode/2, parse_qs/1, qs/1, make_url/3, fix_path/1, pathencode/1, normalize/1, normalize/2]). -include("hackney_lib.hrl"). -type qs_vals() :: [{binary(), binary() | true}]. @doc an url and return a # hackney_url record . -spec parse_url(URL::binary()|list()) -> hackney_url(). parse_url(URL) when is_list(URL) -> case unicode:characters_to_binary(URL) of URL1 when is_binary(URL1) -> parse_url(URL1); _ -> parse_url(unicode:characters_to_binary(list_to_binary(URL))) end; parse_url(<<"http://", Rest/binary>>) -> parse_url(Rest, #hackney_url{transport=hackney_tcp, scheme=http}); parse_url(<<"https://", Rest/binary>>) -> parse_url(Rest, #hackney_url{transport=hackney_ssl, scheme=https}); parse_url(<<"http+unix://", Rest/binary>>) -> parse_url(Rest, #hackney_url{transport=hackney_local_tcp, scheme=http_unix}); parse_url(URL) -> parse_url(URL, #hackney_url{transport=hackney_tcp, scheme=http}). parse_url(URL, S) -> case binary:split(URL, <<"/">>) of [Addr] -> Path = <<"/">>, parse_addr(Addr, S#hackney_url{raw_path = Path, path = Path }); [Addr, Path] -> RawPath = <<"/", Path/binary>>, {Path1, Query, Fragment} = parse_path(RawPath), parse_addr(Addr, S#hackney_url{raw_path = RawPath, path = Path1, qs = Query, fragment = Fragment}) end. @doc the encoding of a Url -spec normalize(URL) -> NormalizedUrl when URL :: binary() | list() | hackney_url(), NormalizedUrl :: hackney_url(). normalize(Url) -> normalize(Url, fun hackney_url:pathencode/1). @doc the encoding of a Url -spec normalize(URL, Fun) -> NormalizedUrl when URL :: binary() | list() | hackney_url(), Fun :: fun(), NormalizedUrl :: hackney_url(). normalize(Url, Fun) when is_list(Url) orelse is_binary(Url) -> normalize(parse_url(Url), Fun); normalize(#hackney_url{}=Url, Fun) when is_function(Fun, 1) -> #hackney_url{scheme=Scheme, host = Host0, port = Port, netloc = Netloc0, path = Path} = Url, {Host, Netloc} = case inet_parse:address(Host0) of {ok, {_, _, _, _}} -> {Host0, Netloc0}; {ok, {_, _, _, _, _, _, _, _}} -> {Host0, Netloc0}; _ -> Host1 = unicode:characters_to_list( urldecode(unicode:characters_to_binary(Host0))), Host2 = idna:to_ascii(Host1), Netloc1 = case {Scheme, Port} of {http, 80} -> list_to_binary(Host2); {https, 443} -> list_to_binary(Host2); {http_unix, _} -> list_to_binary(Host2); _ -> iolist_to_binary([Host2, ":", integer_to_list(Port)]) end, {Host2, Netloc1} end, Path1 = Fun(Path), Url#hackney_url{host=Host, netloc=Netloc, path=Path1}. transport_scheme(hackney_tcp) -> http; transport_scheme(hackney_ssl) -> https; transport_scheme(hackney_local_tcp) -> http_unix. unparse_url(#hackney_url{}=Url) -> #hackney_url{scheme = Scheme, netloc = Netloc, path = Path, qs = Qs, fragment = Fragment, user = User, password = Password} = Url, Scheme1 = case Scheme of http -> <<"http://">>; https -> <<"https://">>; http_unix -> <<"http+unix://">> end, Netloc1 = case User of <<>> -> Netloc; _ when Password /= <<>>, Password /= <<"">> -> << User/binary, ":", Password/binary, "@", Netloc/binary >>; _ -> << User/binary, "@", Netloc/binary >> end, Qs1 = case Qs of <<>> -> <<>>; _ -> << "?", Qs/binary >> end, Fragment1 = case Fragment of <<>> -> <<>>; _ -> << "#", Fragment/binary >> end, Path1 = case Path of nil -> <<>>; undefined -> <<>>; <<>> -> <<"/">>; _ -> Path end, << Scheme1/binary, Netloc1/binary, Path1/binary, Qs1/binary, Fragment1/binary >>. @private parse_addr(Addr, S) -> case binary:split(Addr, <<"@">>) of [Addr] -> parse_netloc(Addr, S#hackney_url{netloc=Addr}); [Credentials, Addr1] -> case binary:split(Credentials, <<":">>) of [User, Password] -> parse_netloc(Addr1, S#hackney_url{netloc=Addr1, user = User, password = Password}); [User] -> parse_netloc(Addr1, S#hackney_url{netloc = Addr1, user = User, password = <<>> }) end end. parse_netloc(<<"[", Rest/binary>>, #hackney_url{transport=Transport}=S) -> case binary:split(Rest, <<"]">>) of [Host, <<>>] when Transport =:= hackney_tcp -> S#hackney_url{host=binary_to_list(Host), port=80}; [Host, <<>>] when Transport =:= hackney_ssl -> S#hackney_url{host=binary_to_list(Host), port=443}; [Host, <<":", Port/binary>>] -> S#hackney_url{host=binary_to_list(Host), port=list_to_integer(binary_to_list(Port))}; _ -> parse_netloc(Rest, S) end; parse_netloc(Netloc, #hackney_url{transport=Transport}=S) -> case binary:split(Netloc, <<":">>) of [Host] when Transport =:= hackney_tcp -> S#hackney_url{host=unicode:characters_to_list((Host)), port=80}; [Host] when Transport =:= hackney_ssl -> S#hackney_url{host=unicode:characters_to_list(Host), port=443}; [Host] when Transport =:= hackney_local_tcp -> S#hackney_url{host=unicode:characters_to_list(urldecode(Host)), port=0}; [Host, Port] -> S#hackney_url{host=unicode:characters_to_list(Host), port=list_to_integer(binary_to_list(Port))} end. parse_path(Path) -> case binary:split(Path, <<"?">>) of [_Path] -> {Path1, Fragment} = parse_fragment(Path), {Path1, <<>>, Fragment}; [Path1, Query] -> {Query1, Fragment} = parse_fragment(Query), {Path1, Query1, Fragment} end. parse_fragment(S) -> case binary:split(S, <<"#">>) of [_S] -> {S, <<>>}; [S1, F] -> {S1, F} end. @equiv urldecode(Bin , crash ) -spec urldecode(binary()) -> binary(). urldecode(Bin) when is_binary(Bin) -> urldecode(Bin, <<>>, crash). The second argument specifies how to handle percent characters that are not followed by two valid hex characters . Use ` skip ' to ignore such errors , -spec urldecode(binary(), crash | skip) -> binary(). urldecode(Bin, OnError) when is_binary(Bin) -> urldecode(Bin, <<>>, OnError). -spec urldecode(binary(), binary(), crash | skip) -> binary(). , H , L , Rest / binary > > , Acc , OnError ) - > G = unhex(H), M = unhex(L), if G =:= error; M =:= error -> case OnError of skip -> ok; crash -> erlang:error(badarg) end, > > , ) ; true -> urldecode(Rest, <<Acc/binary, (G bsl 4 bor M)>>, OnError) end; , Rest / binary > > , Acc , OnError ) - > case OnError of skip -> ok; crash -> erlang:error(badarg) end, > > , ) ; urldecode(<<$+, Rest/binary>>, Acc, OnError) -> urldecode(Rest, <<Acc/binary, $ >>, OnError); urldecode(<<C, Rest/binary>>, Acc, OnError) -> urldecode(Rest, <<Acc/binary, C>>, OnError); urldecode(<<>>, Acc, _OnError) -> Acc. -spec unhex(byte()) -> byte() | error. unhex(C) when C >= $0, C =< $9 -> C - $0; unhex(C) when C >= $A, C =< $F -> C - $A + 10; unhex(C) when C >= $a, C =< $f -> C - $a + 10; unhex(_) -> error. -spec urlencode(binary() | string()) -> binary(). urlencode(Bin) -> urlencode(Bin, []). characters , ` \s ' , as ` + ' . The ` upper ' option overrides the default behaviour -spec urlencode(binary() | string(), [noplus|upper]) -> binary(). urlencode(Bin, Opts) -> Plus = not proplists:get_value(noplus, Opts, false), Upper = proplists:get_value(upper, Opts, false), urlencode(hackney_bstr:to_binary(Bin), <<>>, Plus, Upper). -spec urlencode(binary(), binary(), boolean(), boolean()) -> binary(). urlencode(<<C, Rest/binary>>, Acc, P=Plus, U=Upper) -> if C >= $0, C =< $9 -> urlencode(Rest, <<Acc/binary, C>>, P, U); C >= $A, C =< $Z -> urlencode(Rest, <<Acc/binary, C>>, P, U); C >= $a, C =< $z -> urlencode(Rest, <<Acc/binary, C>>, P, U); C =:= $.; C =:= $-; C =:= $~; C =:= $_; C =:= $*; C =:= $@ -> urlencode(Rest, <<Acc/binary, C>>, P, U); C =:= $(; C =:= $); C =:= $!, C =:= $$ -> urlencode(Rest, <<Acc/binary, C>>, P, U); C =:= $ , Plus -> urlencode(Rest, <<Acc/binary, $+>>, P, U); true -> H = C band 16#F0 bsr 4, L = C band 16#0F, H1 = if Upper -> tohexu(H); true -> tohexl(H) end, L1 = if Upper -> tohexu(L); true -> tohexl(L) end, , H1 , L1 > > , P , U ) end; urlencode(<<>>, Acc, _Plus, _Upper) -> Acc. -spec tohexu(byte()) -> byte(). tohexu(C) when C < 10 -> $0 + C; tohexu(C) when C < 16 -> $A + C - 10. -spec tohexl(byte()) -> byte(). tohexl(C) when C < 10 -> $0 + C; tohexl(C) when C < 16 -> $a + C - 10. -spec parse_qs(binary()) -> qs_vals(). parse_qs(<<>>) -> []; parse_qs(Bin) -> Tokens = binary:split(Bin, <<"&">>, [trim, global]), [case binary:split(Token, <<"=">>, [trim]) of [T] -> {urldecode(T), true}; [Name, Value] -> {urldecode(Name), urldecode(Value)} end || Token <- Tokens]. -spec qs(qs_vals()) -> binary(). qs(KVs) -> qs(KVs, []). qs([], Acc) -> hackney_bstr:join(lists:reverse(Acc), <<"&">>); qs([{K, V}|R], Acc) -> K1 = urlencode(K), V1 = urlencode(V), Line = << K1/binary, "=", V1/binary >>, qs(R, [Line | Acc]). -spec make_url(binary(), binary() | [binary()], binary() | qs_vals()) -> binary(). make_url(Url, Path, Query) when is_list(Query) -> make_url(Url, Path, qs(Query)); make_url(Url, Path, Query) when is_binary(Path) -> make_url(Url, [Path], Query); make_url(Url, PathParts, Query) when is_binary(Query) -> PathParts1 = [fix_path(P) || P <- PathParts, P /= "", P /= "/" orelse P /= <<"/">>], Path = hackney_bstr:join([<<>> | PathParts1], <<"/">>), Query1 = case Query of <<>> -> <<>>; _ -> << "?", Query/binary >> end, iolist_to_binary([fix_path(Url), Path, Query1]). fix_path(Path) when is_list(Path) -> fix_path(list_to_binary(Path)); fix_path(<<>>) -> <<>>; fix_path(<<"/", Path/binary>>) -> fix_path(Path); fix_path(Path) -> case binary:part(Path, {size(Path), -1}) of <<"/">> -> binary:part(Path, {0, size(Path) - 1}); _ -> Path end. -spec pathencode(binary()) -> binary(). pathencode(Bin) -> Parts = binary:split(hackney_bstr:to_binary(Bin), <<"/">>, [global]), do_partial_pathencode(Parts, []). do_partial_pathencode([], Acc) -> hackney_bstr:join(lists:reverse(Acc), <<"/">>); do_partial_pathencode([Part | Rest], Acc) -> do_partial_pathencode(Rest, [partial_pathencode(Part, <<>>) | Acc]). partial_pathencode(<<C, Rest/binary>> = Bin, Acc) -> if C >= $0, C =< $9 -> partial_pathencode(Rest, <<Acc/binary, C>>); C >= $A, C =< $Z -> partial_pathencode(Rest, <<Acc/binary, C>>); C >= $a, C =< $z -> partial_pathencode(Rest, <<Acc/binary, C>>); C =:= $;; C =:= $=; C =:= $,; C =:= $:; C =:= $@ -> partial_pathencode(Rest, <<Acc/binary, C>>); C =:= $.; C =:= $-; C =:= $+; C =:= $~; C =:= $_ -> partial_pathencode(Rest, <<Acc/binary, C>>); C =:= $ -> partial_pathencode(Rest, <<Acc/binary, $+>>); case Bin of , H , L , Rest1 / binary > > - > G = unhex(H), M = unhex(L), if G =:= error; M =:= error -> H1 = C band 16#F0 bsr 4, L1 = C band 16#0F, H2 = tohexl(H1), L2 = tohexl(L1), true -> end; _ -> H1 = C band 16#F0 bsr 4, L1 = C band 16#0F, H2 = tohexl(H1), L2 = tohexl(L1), end; true -> H = C band 16#F0 bsr 4, L = C band 16#0F, H1 = tohexl(H), L1 = tohexl(L), , H1 , L1 > > ) end; partial_pathencode(<<>>, Acc) -> Acc.
572c162d37fd96266485fb0c5e05a7a26ba75972579cac6fa916044576b2157d
janestreet/ecaml
terminal.ml
open! Core open! Import0 module Q = struct let ns = "ns" |> Symbol.intern let pc = "pc" |> Symbol.intern let w32 = "w32" |> Symbol.intern let x = "x" |> Symbol.intern end let is_terminal = Funcall.Wrap.("terminal-live-p" <: value @-> return bool) include Value.Make_subtype (struct let name = "terminal" let here = [%here] let is_in_subtype = is_terminal end) module Type = struct module T = struct type t = | Text | X11 | Windows | Mac_os | Ms_dos [@@deriving enumerate, sexp_of] end include T let type_ = Value.Type.enum [%message "terminal-type"] (module T) (function | Text -> Value.t | X11 -> Q.x |> Symbol.to_value | Windows -> Q.w32 |> Symbol.to_value | Mac_os -> Q.ns |> Symbol.to_value | Ms_dos -> Q.pc |> Symbol.to_value) ;; let t = type_ end let all_live = Funcall.Wrap.("terminal-list" <: nullary @-> return (list t)) let terminal_type = Funcall.Wrap.("terminal-live-p" <: t @-> return Type.t) let name = Funcall.Wrap.("terminal-name" <: t @-> return string) let graphical t = match terminal_type t with | Text | Ms_dos -> false | X11 | Windows | Mac_os -> true ;;
null
https://raw.githubusercontent.com/janestreet/ecaml/7c16e5720ee1da04e0757cf185a074debf9088df/src/terminal.ml
ocaml
open! Core open! Import0 module Q = struct let ns = "ns" |> Symbol.intern let pc = "pc" |> Symbol.intern let w32 = "w32" |> Symbol.intern let x = "x" |> Symbol.intern end let is_terminal = Funcall.Wrap.("terminal-live-p" <: value @-> return bool) include Value.Make_subtype (struct let name = "terminal" let here = [%here] let is_in_subtype = is_terminal end) module Type = struct module T = struct type t = | Text | X11 | Windows | Mac_os | Ms_dos [@@deriving enumerate, sexp_of] end include T let type_ = Value.Type.enum [%message "terminal-type"] (module T) (function | Text -> Value.t | X11 -> Q.x |> Symbol.to_value | Windows -> Q.w32 |> Symbol.to_value | Mac_os -> Q.ns |> Symbol.to_value | Ms_dos -> Q.pc |> Symbol.to_value) ;; let t = type_ end let all_live = Funcall.Wrap.("terminal-list" <: nullary @-> return (list t)) let terminal_type = Funcall.Wrap.("terminal-live-p" <: t @-> return Type.t) let name = Funcall.Wrap.("terminal-name" <: t @-> return string) let graphical t = match terminal_type t with | Text | Ms_dos -> false | X11 | Windows | Mac_os -> true ;;
c37508d81f33a2c803d75665ef9d67f3f5a9bd44b9f6330f22e6a5b95df24498
8c6794b6/haskell-sc-scratch
Interpreter.hs
# LANGUAGE NoMonomorphismRestriction # # LANGUAGE ScopedTypeVariables # {-# LANGUAGE RankNTypes #-} # LANGUAGE FlexibleContexts # # LANGUAGE UndecidableInstances # {-# LANGUAGE GADTs #-} # LANGUAGE TemplateHaskell # | Module : $ Header$ CopyRight : ( c ) 8c6794b6 License : : Stability : unstable Portability : portable Module : $Header$ CopyRight : (c) 8c6794b6 License : BSD3 Maintainer : Stability : unstable Portability : portable -} module Test.Sound.SC3.Lepton.Pattern.Interpreter where import Control.Applicative import Control.DeepSeq import Data.Binary (decode, encode) import Data.Data import Data.Ratio ((%)) import Test.Tasty (TestTree) import Test.Tasty.TH (testGroupGenerator) import Test.Tasty.QuickCheck (testProperty) import Test.QuickCheck import Sound.SC3 hiding (label) import Sound.SC3.Lepton.Pattern import Sound.SC3.Lepton.QuickCheck import System . Random . Mersenne . Pure64 import qualified Data.ByteString.Lazy as BSL import qualified Data . Serialize as Srl -- tests :: TestTree -- tests = -- [ label "s_is_s" prop_s_is_s -- ] tests :: TestTree tests = $testGroupGenerator -- tests = [] -- tests = -- [ label "prop_prim_num" prop_prim_num , label " prop_listpat " prop_listpat -- , label "prop_fractional" prop_fractional -- , label "prop_floating" prop_floating -- , label "prop_unary" prop_unary -- , label "prop_fromnum" prop_fromnum -- , label "prop_outer_repeat" prop_outer_repeat -- ] prop_listpat = with_ppar_snew_nset list_patterns -- prop_unary = with_ppar_snew_nset unary_patterns -- prop_prim_num = with_ppar_snew_nset num_patterns -- prop_prim_double = with_ppar_snew_nset double_patterns -- prop_floating = with_ppar_snew_nset floating_patterns -- prop_fractional = with_ppar_snew_nset fractional_patterns -- prop_fromnum = -- forAll (arbitrary `suchThat` -- (\(_,n::Integer,d::Integer) -> d /= 0 && n /= 0)) $ \(i::Int , n::Integer , d::Integer ) - > -- let m = n % d -- in fromRational m == toExpr (pval m) && fromIntegral i = = toExpr ( pval i ) & & fromRational m = = toBz ( fromRational m ) & & -- fromIntegral i == toBz (fromIntegral i) && -- fromRational m == toS (fromRational m) && -- fromIntegral i == toS (fromIntegral i) -- prop_outer_repeat = forAll mixed_patterns $ \p -> let p1 = toExpr ( preplicate 2 ( pmerge ( snew_foo p ) ( nset_100 p ) ) ) p2 = toExpr ( pseq ( prange 1 4 ) [ snew_foo p , nset_100 p ] ) -- Right p1' = fromExpr p1 -- Right p2' = fromExpr p2 -- in p1' == p1 && p2' == p2 with_ppar_snew_nset ps = forAll ps $ \p - > let p ' = pconcat [ ppar [ snew_foo p , nset_100 p ] -- , pmerge (snew_foo p) (nset_100 p) ] -- -- Right (b :: Bz (ToOSC Double)) = fromExpr p' Right ( s : : S ( ToOSC Double ) ) = -- Right ( e : : ( ToOSC Double ) ) = fromExpr p ' -- in check_expr e && check_bz_s b s -- check_expr e = e `deepseq` -- let Right eb = fromTree (decode (encode $ toExpr e)) -- Right es = fromTree =<< Srl.decode (Srl.encode $ toExpr e) -- eString = fmap show e -- in eb == e && es == e && -- eString `deepseq` not (null (show $ prettyP eString)) && typeOf e = = ( undefined : : ( ToOSC Double ) ) -- check_bz_s bz s = -- show (toBz bz) == show (toS s) && -- bz == bz && lazyByteStringP bz == BSL.fromChunks [byteStringP bz] && typeOf bz = = ( undefined : : Bz ( ToOSC Double ) ) & & -- let Right bz ' = parseP ( lazyByteStringP bz ) in bz ' = = bz & & -- s == s -- ------------------------------------------------------------------------------ -- -- Pattern generators snew_foo o = psnew " foo " Nothing AddToTail 1 [ ( " bar " , o ) ] nset_100 o = pnset 100 [ ( " bar " , o ) ] prims = \(a , b , c ) - > [ pempty , pval a , plist b , prepeat c ] -- list_patterns = make_patterns $ \p1 p2 pi -> [ pconcat [ p1,p2 ] , pappend p1 p2 , pcycle [ p1,p2 ] , pseq pi [ p1,p2 ] , preplicate pi p1 , pforever p1 ] -- random_patterns = make_patterns $ \p1 p2 pi -> [ prandom , prange p1 p2 , pchoose pi [ p1,p2 ] , prand pi [ p1,p2 ] , pshuffle [ p1,p2 ] ] prop_s_is_s :: Property prop_s_is_s = forAll intP $ \x -> forAll doubleP $ \y -> let expr = ppar [ ptakeT y pat1, pdropT y pat2 , pmerge pat1 (pconcat [pat1,pat2]) ] pat1 = psnew "foo" Nothing AddToTail 1 [("bar",param1)] pat2 = pnset 1000 [("buzz",param2),("quux",param3)] pat3 = plam (ttoosc tdouble) (pmerge pz pz) `papp` psnew "blah" Nothing AddToTail 1 [("bloh", param4)] param1 = body1 `papp` x `papp` y' body1 = plam tint (plam tdouble ( let a = ps pz; b = pz in pcycle [preplicate (prand a [a, a+!pint 2, a*!pint 3]) b])) y' = pdrange y (y *@ pdouble 2) param2 = pforever (pseq x [pappend y y]) param3 = plam (ttup tdouble tdouble) body3 `papp` pzip y y body3 = pshuffle [pfst pz, pfsm [0] [(psnd pz, [0])]] param4 = y d = duplicate expr s = view (dupl d) et = let et' = etree (dupr d) in et' `seq` et' pet = ppTree et e1 = fromTree (decode $ encode $ et,()) e2 = t2s et e3 = e2s (dupr d) l1 = t2l et l2 = e2l (dupr d) isRight r = pet `seq` case r of Right _ -> True; _ -> False in collect (etSize et) $ case e1 of Left err -> False Right (Term _ e') -> view e' == s && e2 == s && e3 == s && isRight l1 && isRight l2 ap2 :: (a -> a -> c) -> a -> c ap2 f = \x -> f x x intP :: Pint p => Gen (p h Int) intP = elements [ ap2 (+!), ap2 (*!), ap2 (-!) , piabs, pinegate, pisignum, ap2 pirange ] <*> (pint <$> arbitrary) doubleP :: Pdouble p => Gen (p h Double) doubleP = elements [ ap2 (+@), ap2 (*@), ap2 (-@), ap2 pdrange , pdabs, pdnegate, pdsignum, ap2 (/@), precip, psqrt, plog , psin, ptan, pcos, pasin, patan, pacos, psinh, ptanh, pcosh , pasinh, patanh, pacosh, pampDb, pasFloat, pasInt , pcpsMIDI, pcpsOct, pcubed, pdbAmp, pdistort, pfrac, pisNil , plog10, plog2, pmidiCPS, pmidiRatio, pnotE, pnotNil, poctCPS , pramp_, pratioMIDI, psoftClip, psquared, const ppi , ap2 (**@), ap2 plogBase ] <*> (pdouble <$> arbitrary) -- num_patterns = elements [ \x - > x + x , \x - > x * x , \x - > x - x , abs , negate , signum ] < * > -- mixed_patterns -- unary_patterns = -- (elements [ ampDb , asFloat , asInt , bitNot , cpsMIDI , cpsOct , cubed , dbAmp , distort , frac , isNil , log10 , log2 , midiCPS , , notE , notNil , , ramp _ , ratioMIDI , softClip , squared ] ) < * > -- (elements =<< sequence [list_patterns, random_patterns]) -- fractional_patterns = -- elements [ \x -> x / x, recip ] <*> -- (elements =<< sequence [list_patterns, random_patterns]) -- floating_patterns = -- elements [ const pi , exp , sqrt , log , \x - > x * * x , \x - > logBase x x , sin , cos , tan , asin , atan , acos , sinh , tanh , cosh , asinh , atanh , acosh ] < * > -- (elements =<< sequence [list_patterns, random_patterns]) -- mixed_patterns = elements =<< sequence [ list_patterns , random_patterns , unary_patterns -- , fractional_patterns, floating_patterns ] -- make_patterns f = do -- (x,y,z) <- arbitrary -- elements =<< (f <$> (elements (prims x)) <*> -- (elements (prims y)) <*> -- (elements (prims z)))
null
https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/hsc3-lepton/src/test/Test/Sound/SC3/Lepton/Pattern/Interpreter.hs
haskell
# LANGUAGE RankNTypes # # LANGUAGE GADTs # tests :: TestTree tests = [ label "s_is_s" prop_s_is_s ] tests = [] tests = [ label "prop_prim_num" prop_prim_num , label "prop_fractional" prop_fractional , label "prop_floating" prop_floating , label "prop_unary" prop_unary , label "prop_fromnum" prop_fromnum , label "prop_outer_repeat" prop_outer_repeat ] prop_unary = with_ppar_snew_nset unary_patterns prop_prim_num = with_ppar_snew_nset num_patterns prop_prim_double = with_ppar_snew_nset double_patterns prop_floating = with_ppar_snew_nset floating_patterns prop_fractional = with_ppar_snew_nset fractional_patterns prop_fromnum = forAll (arbitrary `suchThat` (\(_,n::Integer,d::Integer) -> d /= 0 && n /= 0)) $ let m = n % d in fromRational m == toExpr (pval m) && fromIntegral i == toBz (fromIntegral i) && fromRational m == toS (fromRational m) && fromIntegral i == toS (fromIntegral i) prop_outer_repeat = forAll mixed_patterns $ \p -> Right p1' = fromExpr p1 Right p2' = fromExpr p2 in p1' == p1 && p2' == p2 , pmerge (snew_foo p) (nset_100 p) ] -- Right (b :: Bz (ToOSC Double)) = fromExpr p' Right ( e : : ( ToOSC Double ) ) = fromExpr p ' in check_expr e && check_bz_s b s check_expr e = e `deepseq` let Right eb = fromTree (decode (encode $ toExpr e)) Right es = fromTree =<< Srl.decode (Srl.encode $ toExpr e) eString = fmap show e in eb == e && es == e && eString `deepseq` not (null (show $ prettyP eString)) && check_bz_s bz s = show (toBz bz) == show (toS s) && bz == bz && lazyByteStringP bz == BSL.fromChunks [byteStringP bz] && let Right bz ' = parseP ( lazyByteStringP bz ) in bz ' = = bz & & s == s ------------------------------------------------------------------------------ -- Pattern generators list_patterns = make_patterns $ \p1 p2 pi -> random_patterns = make_patterns $ \p1 p2 pi -> num_patterns = mixed_patterns unary_patterns = (elements (elements =<< sequence [list_patterns, random_patterns]) fractional_patterns = elements [ \x -> x / x, recip ] <*> (elements =<< sequence [list_patterns, random_patterns]) floating_patterns = elements (elements =<< sequence [list_patterns, random_patterns]) mixed_patterns = elements =<< sequence , fractional_patterns, floating_patterns ] make_patterns f = do (x,y,z) <- arbitrary elements =<< (f <$> (elements (prims x)) <*> (elements (prims y)) <*> (elements (prims z)))
# LANGUAGE NoMonomorphismRestriction # # LANGUAGE ScopedTypeVariables # # LANGUAGE FlexibleContexts # # LANGUAGE UndecidableInstances # # LANGUAGE TemplateHaskell # | Module : $ Header$ CopyRight : ( c ) 8c6794b6 License : : Stability : unstable Portability : portable Module : $Header$ CopyRight : (c) 8c6794b6 License : BSD3 Maintainer : Stability : unstable Portability : portable -} module Test.Sound.SC3.Lepton.Pattern.Interpreter where import Control.Applicative import Control.DeepSeq import Data.Binary (decode, encode) import Data.Data import Data.Ratio ((%)) import Test.Tasty (TestTree) import Test.Tasty.TH (testGroupGenerator) import Test.Tasty.QuickCheck (testProperty) import Test.QuickCheck import Sound.SC3 hiding (label) import Sound.SC3.Lepton.Pattern import Sound.SC3.Lepton.QuickCheck import System . Random . Mersenne . Pure64 import qualified Data.ByteString.Lazy as BSL import qualified Data . Serialize as Srl tests :: TestTree tests = $testGroupGenerator , label " prop_listpat " prop_listpat prop_listpat = with_ppar_snew_nset list_patterns \(i::Int , n::Integer , d::Integer ) - > fromIntegral i = = toExpr ( pval i ) & & fromRational m = = toBz ( fromRational m ) & & let p1 = toExpr ( preplicate 2 ( pmerge ( snew_foo p ) ( nset_100 p ) ) ) p2 = toExpr ( pseq ( prange 1 4 ) [ snew_foo p , nset_100 p ] ) with_ppar_snew_nset ps = forAll ps $ \p - > let p ' = pconcat [ ppar [ snew_foo p , nset_100 p ] Right ( s : : S ( ToOSC Double ) ) = typeOf e = = ( undefined : : ( ToOSC Double ) ) typeOf bz = = ( undefined : : Bz ( ToOSC Double ) ) & & snew_foo o = psnew " foo " Nothing AddToTail 1 [ ( " bar " , o ) ] nset_100 o = pnset 100 [ ( " bar " , o ) ] prims = \(a , b , c ) - > [ pempty , pval a , plist b , prepeat c ] [ pconcat [ p1,p2 ] , pappend p1 p2 , pcycle [ p1,p2 ] , pseq pi [ p1,p2 ] , preplicate pi p1 , pforever p1 ] [ prandom , prange p1 p2 , pchoose pi [ p1,p2 ] , prand pi [ p1,p2 ] , pshuffle [ p1,p2 ] ] prop_s_is_s :: Property prop_s_is_s = forAll intP $ \x -> forAll doubleP $ \y -> let expr = ppar [ ptakeT y pat1, pdropT y pat2 , pmerge pat1 (pconcat [pat1,pat2]) ] pat1 = psnew "foo" Nothing AddToTail 1 [("bar",param1)] pat2 = pnset 1000 [("buzz",param2),("quux",param3)] pat3 = plam (ttoosc tdouble) (pmerge pz pz) `papp` psnew "blah" Nothing AddToTail 1 [("bloh", param4)] param1 = body1 `papp` x `papp` y' body1 = plam tint (plam tdouble ( let a = ps pz; b = pz in pcycle [preplicate (prand a [a, a+!pint 2, a*!pint 3]) b])) y' = pdrange y (y *@ pdouble 2) param2 = pforever (pseq x [pappend y y]) param3 = plam (ttup tdouble tdouble) body3 `papp` pzip y y body3 = pshuffle [pfst pz, pfsm [0] [(psnd pz, [0])]] param4 = y d = duplicate expr s = view (dupl d) et = let et' = etree (dupr d) in et' `seq` et' pet = ppTree et e1 = fromTree (decode $ encode $ et,()) e2 = t2s et e3 = e2s (dupr d) l1 = t2l et l2 = e2l (dupr d) isRight r = pet `seq` case r of Right _ -> True; _ -> False in collect (etSize et) $ case e1 of Left err -> False Right (Term _ e') -> view e' == s && e2 == s && e3 == s && isRight l1 && isRight l2 ap2 :: (a -> a -> c) -> a -> c ap2 f = \x -> f x x intP :: Pint p => Gen (p h Int) intP = elements [ ap2 (+!), ap2 (*!), ap2 (-!) , piabs, pinegate, pisignum, ap2 pirange ] <*> (pint <$> arbitrary) doubleP :: Pdouble p => Gen (p h Double) doubleP = elements [ ap2 (+@), ap2 (*@), ap2 (-@), ap2 pdrange , pdabs, pdnegate, pdsignum, ap2 (/@), precip, psqrt, plog , psin, ptan, pcos, pasin, patan, pacos, psinh, ptanh, pcosh , pasinh, patanh, pacosh, pampDb, pasFloat, pasInt , pcpsMIDI, pcpsOct, pcubed, pdbAmp, pdistort, pfrac, pisNil , plog10, plog2, pmidiCPS, pmidiRatio, pnotE, pnotNil, poctCPS , pramp_, pratioMIDI, psoftClip, psquared, const ppi , ap2 (**@), ap2 plogBase ] <*> (pdouble <$> arbitrary) elements [ \x - > x + x , \x - > x * x , \x - > x - x , abs , negate , signum ] < * > [ ampDb , asFloat , asInt , bitNot , cpsMIDI , cpsOct , cubed , dbAmp , distort , frac , isNil , log10 , log2 , midiCPS , , notE , notNil , , ramp _ , ratioMIDI , softClip , squared ] ) < * > [ const pi , exp , sqrt , log , \x - > x * * x , \x - > logBase x x , sin , cos , tan , asin , atan , acos , sinh , tanh , cosh , asinh , atanh , acosh ] < * > [ list_patterns , random_patterns , unary_patterns
7ac8231ad2f9b8f62751c74077c850d62cbed87cfd08063cc2906dd17f18673d
REPROSEC/dolev-yao-star
Spec_Frodo_KEM_Encaps.ml
open Prims let (frodo_mul_add_sa_plus_e : Spec_Frodo_Params.frodo_alg -> Spec_Frodo_Params.frodo_gen_a -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun a -> fun gen_a -> fun seed_a -> fun sp_matrix -> fun ep_matrix -> let a_matrix = (match gen_a with | Spec_Frodo_Params.SHAKE128 -> Spec_Frodo_Gen.frodo_gen_matrix_shake | Spec_Frodo_Params.AES128 -> Spec_Frodo_Gen.frodo_gen_matrix_aes) (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) seed_a in let b_matrix = Spec_Matrix.add Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) (Spec_Matrix.mul Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) sp_matrix a_matrix) ep_matrix in b_matrix let (crypto_kem_enc_ct_pack_c1 : Spec_Frodo_Params.frodo_alg -> Spec_Frodo_Params.frodo_gen_a -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq) = fun a -> fun gen_a -> fun seed_a -> fun sp_matrix -> fun ep_matrix -> let bp_matrix = frodo_mul_add_sa_plus_e a gen_a seed_a sp_matrix ep_matrix in let ct1 = Spec_Frodo_Pack.frodo_pack Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (16))) bp_matrix in ct1 let (frodo_mul_add_sb_plus_e : Spec_Frodo_Params.frodo_alg -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun a -> fun b -> fun sp_matrix -> fun epp_matrix -> let b_matrix = Spec_Frodo_Pack.frodo_unpack (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (16))) b in let v_matrix = Spec_Matrix.add Spec_Frodo_Params.params_nbar Spec_Frodo_Params.params_nbar (Spec_Matrix.mul Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) Spec_Frodo_Params.params_nbar sp_matrix b_matrix) epp_matrix in v_matrix let (frodo_mul_add_sb_plus_e_plus_mu : Spec_Frodo_Params.frodo_alg -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun a -> fun mu -> fun b -> fun sp_matrix -> fun epp_matrix -> let v_matrix = frodo_mul_add_sb_plus_e a b sp_matrix epp_matrix in let mu_encode = Spec_Frodo_Encode.frodo_key_encode (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (16))) (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (2)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (2)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (3)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (4))) Spec_Frodo_Params.params_nbar mu in let v_matrix1 = Spec_Matrix.add Spec_Frodo_Params.params_nbar Spec_Frodo_Params.params_nbar v_matrix mu_encode in v_matrix1 let (crypto_kem_enc_ct_pack_c2 : Spec_Frodo_Params.frodo_alg -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq) = fun a -> fun mu -> fun b -> fun sp_matrix -> fun epp_matrix -> let v_matrix = frodo_mul_add_sb_plus_e_plus_mu a mu b sp_matrix epp_matrix in let ct2 = Spec_Frodo_Pack.frodo_pack Spec_Frodo_Params.params_nbar Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (16))) v_matrix in ct2 let (get_sp_ep_epp_matrices : Spec_Frodo_Params.frodo_alg -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> ((FStar_UInt16.t, unit) Lib_Sequence.lseq * (FStar_UInt16.t, unit) Lib_Sequence.lseq * (FStar_UInt16.t, unit) Lib_Sequence.lseq)) = fun a -> fun seed_se -> let s_bytes_len = Spec_Frodo_Params.secretmatrixbytes_len a in let r = Spec_Frodo_KEM_KeyGen.frodo_shake_r a (FStar_UInt8.uint_to_t (Prims.of_int (0x96))) seed_se (((Prims.of_int (2)) * s_bytes_len) + (((Prims.of_int (2)) * Spec_Frodo_Params.params_nbar) * Spec_Frodo_Params.params_nbar)) in let sp_matrix = Spec_Frodo_Sample.frodo_sample_matrix a Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) (Lib_Sequence.sub (((Prims.of_int (2)) * s_bytes_len) + (((Prims.of_int (2)) * Spec_Frodo_Params.params_nbar) * Spec_Frodo_Params.params_nbar)) r Prims.int_zero s_bytes_len) in let ep_matrix = Spec_Frodo_Sample.frodo_sample_matrix a Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) (Lib_Sequence.sub (((Prims.of_int (2)) * s_bytes_len) + (((Prims.of_int (2)) * Spec_Frodo_Params.params_nbar) * Spec_Frodo_Params.params_nbar)) r s_bytes_len s_bytes_len) in let epp_matrix = Spec_Frodo_Sample.frodo_sample_matrix a Spec_Frodo_Params.params_nbar Spec_Frodo_Params.params_nbar (Lib_Sequence.sub (((Prims.of_int (2)) * s_bytes_len) + (((Prims.of_int (2)) * Spec_Frodo_Params.params_nbar) * Spec_Frodo_Params.params_nbar)) r ((Prims.of_int (2)) * s_bytes_len) (((Prims.of_int (2)) * Spec_Frodo_Params.params_nbar) * Spec_Frodo_Params.params_nbar)) in (sp_matrix, ep_matrix, epp_matrix) let (crypto_kem_enc_ct : Spec_Frodo_Params.frodo_alg -> Spec_Frodo_Params.frodo_gen_a -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq) = fun a -> fun gen_a -> fun mu -> fun pk -> fun seed_se -> let seed_a = Lib_Sequence.sub (Spec_Frodo_Params.crypto_publickeybytes a) pk Prims.int_zero Spec_Frodo_Params.bytes_seed_a in let b = Lib_Sequence.sub (Spec_Frodo_Params.crypto_publickeybytes a) pk Spec_Frodo_Params.bytes_seed_a (Spec_Frodo_Params.publicmatrixbytes_len a) in let uu___ = get_sp_ep_epp_matrices a seed_se in match uu___ with | (sp_matrix, ep_matrix, epp_matrix) -> let c1 = crypto_kem_enc_ct_pack_c1 a gen_a seed_a sp_matrix ep_matrix in let c2 = crypto_kem_enc_ct_pack_c2 a mu b sp_matrix epp_matrix in let ct = Lib_Sequence.concat (Spec_Frodo_Params.ct1bytes_len a) (Spec_Frodo_Params.ct2bytes_len a) c1 c2 in ct let (crypto_kem_enc_ss : Spec_Frodo_Params.frodo_alg -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq) = fun a -> fun k -> fun ct -> let shake_input_ss = Lib_Sequence.concat (Spec_Frodo_Params.crypto_ciphertextbytes a) (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32))) ct k in let ss = (match a with | Spec_Frodo_Params.Frodo64 -> Spec_SHA3.shake128 | Spec_Frodo_Params.Frodo640 -> Spec_SHA3.shake128 | Spec_Frodo_Params.Frodo976 -> Spec_SHA3.shake256 | Spec_Frodo_Params.Frodo1344 -> Spec_SHA3.shake256) ((Spec_Frodo_Params.crypto_ciphertextbytes a) + (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32)))) shake_input_ss (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32))) in ss let (crypto_kem_enc_seed_se_k : Spec_Frodo_Params.frodo_alg -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq) = fun a -> fun mu -> fun pk -> let pkh = (match a with | Spec_Frodo_Params.Frodo64 -> Spec_SHA3.shake128 | Spec_Frodo_Params.Frodo640 -> Spec_SHA3.shake128 | Spec_Frodo_Params.Frodo976 -> Spec_SHA3.shake256 | Spec_Frodo_Params.Frodo1344 -> Spec_SHA3.shake256) (Spec_Frodo_Params.crypto_publickeybytes a) pk (Spec_Frodo_Params.bytes_pkhash a) in let pkh_mu = Lib_Sequence.concat (Spec_Frodo_Params.bytes_pkhash a) (Spec_Frodo_Params.bytes_mu a) pkh mu in let seed_se_k = (match a with | Spec_Frodo_Params.Frodo64 -> Spec_SHA3.shake128 | Spec_Frodo_Params.Frodo640 -> Spec_SHA3.shake128 | Spec_Frodo_Params.Frodo976 -> Spec_SHA3.shake256 | Spec_Frodo_Params.Frodo1344 -> Spec_SHA3.shake256) ((Spec_Frodo_Params.bytes_pkhash a) + (Spec_Frodo_Params.bytes_mu a)) pkh_mu ((Prims.of_int (2)) * (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32)))) in seed_se_k let (crypto_kem_enc_ : Spec_Frodo_Params.frodo_alg -> Spec_Frodo_Params.frodo_gen_a -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> ((FStar_UInt8.t, unit) Lib_Sequence.lseq * (FStar_UInt8.t, unit) Lib_Sequence.lseq)) = fun a -> fun gen_a -> fun mu -> fun pk -> let seed_se_k = crypto_kem_enc_seed_se_k a mu pk in let seed_se = Lib_Sequence.sub ((Prims.of_int (2)) * (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32)))) seed_se_k Prims.int_zero (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32))) in let k = Lib_Sequence.sub ((Prims.of_int (2)) * (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32)))) seed_se_k (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32))) (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32))) in let ct = crypto_kem_enc_ct a gen_a mu pk seed_se in let ss = crypto_kem_enc_ss a k ct in (ct, ss) let (crypto_kem_enc : Spec_Frodo_Params.frodo_alg -> Spec_Frodo_Params.frodo_gen_a -> Spec_Frodo_Random.state_t -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> ((FStar_UInt8.t, unit) Lib_Sequence.lseq * (FStar_UInt8.t, unit) Lib_Sequence.lseq)) = fun a -> fun gen_a -> fun state -> fun pk -> let uu___ = Spec_Frodo_Random.randombytes_ state (Spec_Frodo_Params.bytes_mu a) in match uu___ with | (mu, uu___1) -> crypto_kem_enc_ a gen_a mu pk
null
https://raw.githubusercontent.com/REPROSEC/dolev-yao-star/d97a8dd4d07f2322437f186e4db6a1f4d5ee9230/concrete/hacl-star-snapshot/ml/Spec_Frodo_KEM_Encaps.ml
ocaml
open Prims let (frodo_mul_add_sa_plus_e : Spec_Frodo_Params.frodo_alg -> Spec_Frodo_Params.frodo_gen_a -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun a -> fun gen_a -> fun seed_a -> fun sp_matrix -> fun ep_matrix -> let a_matrix = (match gen_a with | Spec_Frodo_Params.SHAKE128 -> Spec_Frodo_Gen.frodo_gen_matrix_shake | Spec_Frodo_Params.AES128 -> Spec_Frodo_Gen.frodo_gen_matrix_aes) (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) seed_a in let b_matrix = Spec_Matrix.add Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) (Spec_Matrix.mul Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) sp_matrix a_matrix) ep_matrix in b_matrix let (crypto_kem_enc_ct_pack_c1 : Spec_Frodo_Params.frodo_alg -> Spec_Frodo_Params.frodo_gen_a -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq) = fun a -> fun gen_a -> fun seed_a -> fun sp_matrix -> fun ep_matrix -> let bp_matrix = frodo_mul_add_sa_plus_e a gen_a seed_a sp_matrix ep_matrix in let ct1 = Spec_Frodo_Pack.frodo_pack Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (16))) bp_matrix in ct1 let (frodo_mul_add_sb_plus_e : Spec_Frodo_Params.frodo_alg -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun a -> fun b -> fun sp_matrix -> fun epp_matrix -> let b_matrix = Spec_Frodo_Pack.frodo_unpack (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (16))) b in let v_matrix = Spec_Matrix.add Spec_Frodo_Params.params_nbar Spec_Frodo_Params.params_nbar (Spec_Matrix.mul Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) Spec_Frodo_Params.params_nbar sp_matrix b_matrix) epp_matrix in v_matrix let (frodo_mul_add_sb_plus_e_plus_mu : Spec_Frodo_Params.frodo_alg -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun a -> fun mu -> fun b -> fun sp_matrix -> fun epp_matrix -> let v_matrix = frodo_mul_add_sb_plus_e a b sp_matrix epp_matrix in let mu_encode = Spec_Frodo_Encode.frodo_key_encode (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (16))) (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (2)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (2)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (3)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (4))) Spec_Frodo_Params.params_nbar mu in let v_matrix1 = Spec_Matrix.add Spec_Frodo_Params.params_nbar Spec_Frodo_Params.params_nbar v_matrix mu_encode in v_matrix1 let (crypto_kem_enc_ct_pack_c2 : Spec_Frodo_Params.frodo_alg -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq) = fun a -> fun mu -> fun b -> fun sp_matrix -> fun epp_matrix -> let v_matrix = frodo_mul_add_sb_plus_e_plus_mu a mu b sp_matrix epp_matrix in let ct2 = Spec_Frodo_Pack.frodo_pack Spec_Frodo_Params.params_nbar Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (15)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (16))) v_matrix in ct2 let (get_sp_ep_epp_matrices : Spec_Frodo_Params.frodo_alg -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> ((FStar_UInt16.t, unit) Lib_Sequence.lseq * (FStar_UInt16.t, unit) Lib_Sequence.lseq * (FStar_UInt16.t, unit) Lib_Sequence.lseq)) = fun a -> fun seed_se -> let s_bytes_len = Spec_Frodo_Params.secretmatrixbytes_len a in let r = Spec_Frodo_KEM_KeyGen.frodo_shake_r a (FStar_UInt8.uint_to_t (Prims.of_int (0x96))) seed_se (((Prims.of_int (2)) * s_bytes_len) + (((Prims.of_int (2)) * Spec_Frodo_Params.params_nbar) * Spec_Frodo_Params.params_nbar)) in let sp_matrix = Spec_Frodo_Sample.frodo_sample_matrix a Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) (Lib_Sequence.sub (((Prims.of_int (2)) * s_bytes_len) + (((Prims.of_int (2)) * Spec_Frodo_Params.params_nbar) * Spec_Frodo_Params.params_nbar)) r Prims.int_zero s_bytes_len) in let ep_matrix = Spec_Frodo_Sample.frodo_sample_matrix a Spec_Frodo_Params.params_nbar (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (64)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (640)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (976)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (1344))) (Lib_Sequence.sub (((Prims.of_int (2)) * s_bytes_len) + (((Prims.of_int (2)) * Spec_Frodo_Params.params_nbar) * Spec_Frodo_Params.params_nbar)) r s_bytes_len s_bytes_len) in let epp_matrix = Spec_Frodo_Sample.frodo_sample_matrix a Spec_Frodo_Params.params_nbar Spec_Frodo_Params.params_nbar (Lib_Sequence.sub (((Prims.of_int (2)) * s_bytes_len) + (((Prims.of_int (2)) * Spec_Frodo_Params.params_nbar) * Spec_Frodo_Params.params_nbar)) r ((Prims.of_int (2)) * s_bytes_len) (((Prims.of_int (2)) * Spec_Frodo_Params.params_nbar) * Spec_Frodo_Params.params_nbar)) in (sp_matrix, ep_matrix, epp_matrix) let (crypto_kem_enc_ct : Spec_Frodo_Params.frodo_alg -> Spec_Frodo_Params.frodo_gen_a -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq) = fun a -> fun gen_a -> fun mu -> fun pk -> fun seed_se -> let seed_a = Lib_Sequence.sub (Spec_Frodo_Params.crypto_publickeybytes a) pk Prims.int_zero Spec_Frodo_Params.bytes_seed_a in let b = Lib_Sequence.sub (Spec_Frodo_Params.crypto_publickeybytes a) pk Spec_Frodo_Params.bytes_seed_a (Spec_Frodo_Params.publicmatrixbytes_len a) in let uu___ = get_sp_ep_epp_matrices a seed_se in match uu___ with | (sp_matrix, ep_matrix, epp_matrix) -> let c1 = crypto_kem_enc_ct_pack_c1 a gen_a seed_a sp_matrix ep_matrix in let c2 = crypto_kem_enc_ct_pack_c2 a mu b sp_matrix epp_matrix in let ct = Lib_Sequence.concat (Spec_Frodo_Params.ct1bytes_len a) (Spec_Frodo_Params.ct2bytes_len a) c1 c2 in ct let (crypto_kem_enc_ss : Spec_Frodo_Params.frodo_alg -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq) = fun a -> fun k -> fun ct -> let shake_input_ss = Lib_Sequence.concat (Spec_Frodo_Params.crypto_ciphertextbytes a) (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32))) ct k in let ss = (match a with | Spec_Frodo_Params.Frodo64 -> Spec_SHA3.shake128 | Spec_Frodo_Params.Frodo640 -> Spec_SHA3.shake128 | Spec_Frodo_Params.Frodo976 -> Spec_SHA3.shake256 | Spec_Frodo_Params.Frodo1344 -> Spec_SHA3.shake256) ((Spec_Frodo_Params.crypto_ciphertextbytes a) + (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32)))) shake_input_ss (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32))) in ss let (crypto_kem_enc_seed_se_k : Spec_Frodo_Params.frodo_alg -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq) = fun a -> fun mu -> fun pk -> let pkh = (match a with | Spec_Frodo_Params.Frodo64 -> Spec_SHA3.shake128 | Spec_Frodo_Params.Frodo640 -> Spec_SHA3.shake128 | Spec_Frodo_Params.Frodo976 -> Spec_SHA3.shake256 | Spec_Frodo_Params.Frodo1344 -> Spec_SHA3.shake256) (Spec_Frodo_Params.crypto_publickeybytes a) pk (Spec_Frodo_Params.bytes_pkhash a) in let pkh_mu = Lib_Sequence.concat (Spec_Frodo_Params.bytes_pkhash a) (Spec_Frodo_Params.bytes_mu a) pkh mu in let seed_se_k = (match a with | Spec_Frodo_Params.Frodo64 -> Spec_SHA3.shake128 | Spec_Frodo_Params.Frodo640 -> Spec_SHA3.shake128 | Spec_Frodo_Params.Frodo976 -> Spec_SHA3.shake256 | Spec_Frodo_Params.Frodo1344 -> Spec_SHA3.shake256) ((Spec_Frodo_Params.bytes_pkhash a) + (Spec_Frodo_Params.bytes_mu a)) pkh_mu ((Prims.of_int (2)) * (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32)))) in seed_se_k let (crypto_kem_enc_ : Spec_Frodo_Params.frodo_alg -> Spec_Frodo_Params.frodo_gen_a -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> ((FStar_UInt8.t, unit) Lib_Sequence.lseq * (FStar_UInt8.t, unit) Lib_Sequence.lseq)) = fun a -> fun gen_a -> fun mu -> fun pk -> let seed_se_k = crypto_kem_enc_seed_se_k a mu pk in let seed_se = Lib_Sequence.sub ((Prims.of_int (2)) * (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32)))) seed_se_k Prims.int_zero (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32))) in let k = Lib_Sequence.sub ((Prims.of_int (2)) * (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32)))) seed_se_k (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32))) (match a with | Spec_Frodo_Params.Frodo64 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo640 -> (Prims.of_int (16)) | Spec_Frodo_Params.Frodo976 -> (Prims.of_int (24)) | Spec_Frodo_Params.Frodo1344 -> (Prims.of_int (32))) in let ct = crypto_kem_enc_ct a gen_a mu pk seed_se in let ss = crypto_kem_enc_ss a k ct in (ct, ss) let (crypto_kem_enc : Spec_Frodo_Params.frodo_alg -> Spec_Frodo_Params.frodo_gen_a -> Spec_Frodo_Random.state_t -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> ((FStar_UInt8.t, unit) Lib_Sequence.lseq * (FStar_UInt8.t, unit) Lib_Sequence.lseq)) = fun a -> fun gen_a -> fun state -> fun pk -> let uu___ = Spec_Frodo_Random.randombytes_ state (Spec_Frodo_Params.bytes_mu a) in match uu___ with | (mu, uu___1) -> crypto_kem_enc_ a gen_a mu pk
865b6ce9f7d0ed38614b02bb44495c0a630169299294a009e1ca0ec8c1bba10c
ocaml-multicore/tezos
node_config_command.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2020 Nomadic Labs , < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) (** Commands *) let show (args : Node_shared_arg.t) = let open Lwt_result_syntax in let*! () = Tezos_base_unix.Internal_event_unix.init () in if not @@ Sys.file_exists args.config_file then Format.eprintf "@[<v>@[<v 9>Warning: no configuration file found at %s@,\ displaying the default configuration@]@]@." args.config_file ; let* config = Node_shared_arg.read_and_patch_config_file args in print_endline @@ Node_config_file.to_string config ; return_unit let reset (args : Node_shared_arg.t) = let open Lwt_result_syntax in let*! () = Tezos_base_unix.Internal_event_unix.init () in if Sys.file_exists args.config_file then Format.eprintf "Ignoring previous configuration file: %s.@." args.config_file ; let* config = Node_shared_arg.read_and_patch_config_file args in let* () = Node_config_validation.check config in Node_config_file.write args.config_file config let init (args : Node_shared_arg.t) = let open Lwt_result_syntax in let*! () = Tezos_base_unix.Internal_event_unix.init () in if Sys.file_exists args.config_file then failwith "Pre-existing configuration file at %s, use `reset`." args.config_file else let* config = Node_shared_arg.read_and_patch_config_file ~may_override_network:true args in let* () = Node_config_validation.check config in let* () = Node_config_file.write args.config_file config in let default = if args.network = None then " default" else "" in let alias = match config.blockchain_network.alias with | None -> (* Cannot happen, as --network cannot take custom networks as arguments. *) "" | Some alias -> ": " ^ alias in Format.eprintf "Created %s for%s network%s.@." args.config_file default alias ; return_unit let update (args : Node_shared_arg.t) = let open Lwt_result_syntax in let*! () = Tezos_base_unix.Internal_event_unix.init () in if not (Sys.file_exists args.config_file) then failwith "Missing configuration file at %s. Use `%s config init [options]` to \ generate a new file" args.config_file Sys.argv.(0) else let* config = Node_shared_arg.read_and_patch_config_file args in let* () = Node_config_validation.check config in Node_config_file.write args.config_file config let validate (args : Node_shared_arg.t) = let open Lwt_result_syntax in let*! () = Tezos_base_unix.Internal_event_unix.init () in if not (Sys.file_exists args.config_file) then Format.eprintf "@[<v>@[<v 9>Warning: no configuration file found at %s@,\ validating the default configuration@]@]@." args.config_file ; let* config = Node_shared_arg.read_and_patch_config_file args in let*! r = Node_config_validation.check config in match r with (* Here we do not consider the node configuration file being invalid as a failure. *) | Error (Node_config_validation.Invalid_node_configuration :: _) | Ok () -> return_unit | err -> Lwt.return err (** Main *) module Term = struct type subcommand = Show | Reset | Init | Update | Validate let process subcommand args = let res = match subcommand with | Show -> show args | Reset -> reset args | Init -> init args | Update -> update args | Validate -> validate args in match Lwt_main.run @@ Lwt_exit.wrap_and_exit res with | Ok () -> `Ok () | Error err -> `Error (false, Format.asprintf "%a" pp_print_trace err) let subcommand_arg = let parser = function | "show" -> `Ok Show | "reset" -> `Ok Reset | "init" -> `Ok Init | "update" -> `Ok Update | "validate" -> `Ok Validate | s -> `Error ("invalid argument: " ^ s) and printer ppf = function | Show -> Format.fprintf ppf "show" | Reset -> Format.fprintf ppf "reset" | Init -> Format.fprintf ppf "init" | Update -> Format.fprintf ppf "update" | Validate -> Format.fprintf ppf "validate" in let open Cmdliner.Arg in let doc = "Operation to perform. Possible values: $(b,show), $(b,reset), \ $(b,init), $(b,update), $(b,validate)." in value & pos 0 (parser, printer) Show & info [] ~docv:"OPERATION" ~doc let term = let open Cmdliner.Term in ret (const process $ subcommand_arg $ Node_shared_arg.Term.args) end module Manpage = struct let command_description = "The $(b,config) command is meant to inspect and amend the configuration \ of the Tezos node. This command is complementary to manually editing the \ tezos node configuration file. Its arguments are a subset of the $(i,run) \ command ones." let description = [ `S "DESCRIPTION"; `P (command_description ^ " Several operations are possible: "); `P "$(b,show) reads, parses and displays Tezos current config file. Use \ this command to see exactly what config file will be used by Tezos. \ If additional command-line arguments are provided, the displayed \ configuration will be amended accordingly. This is the default \ operation."; `P "$(b,reset) will overwrite the current configuration file with a \ factory default one. If additional command-line arguments are \ provided, they will amend the generated file. It assumes that a \ configuration file already exists and will abort otherwise."; `P "$(b,init) is like reset but assumes that no configuration file is \ present and will abort otherwise."; `P "$(b,update) is the main option to edit the configuration file of \ Tezos. It will parse command line arguments and add or replace \ corresponding entries in the Tezos configuration file."; `P "$(b,validate) verifies that the configuration file parses correctly \ and performs some sanity checks on its values."; ] let options = let schema = Data_encoding.Json.schema Node_config_file.encoding in let schema = Format.asprintf "@[%a@]" Json_schema.pp schema in let schema = String.concat "\\$" (String.split '$' schema) in [`S "OPTIONS"; `P "All options available in the config file"; `Pre schema] let man = description @ Node_shared_arg.Manpage.args @ options @ Node_shared_arg.Manpage.bugs let info = Cmdliner.Term.info ~doc:"Manage node configuration" ~man "config" end let cmd = (Term.term, Manpage.info)
null
https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/bin_node/node_config_command.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** * Commands Cannot happen, as --network cannot take custom networks as arguments. Here we do not consider the node configuration file being invalid as a failure. * Main
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2020 Nomadic Labs , < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING let show (args : Node_shared_arg.t) = let open Lwt_result_syntax in let*! () = Tezos_base_unix.Internal_event_unix.init () in if not @@ Sys.file_exists args.config_file then Format.eprintf "@[<v>@[<v 9>Warning: no configuration file found at %s@,\ displaying the default configuration@]@]@." args.config_file ; let* config = Node_shared_arg.read_and_patch_config_file args in print_endline @@ Node_config_file.to_string config ; return_unit let reset (args : Node_shared_arg.t) = let open Lwt_result_syntax in let*! () = Tezos_base_unix.Internal_event_unix.init () in if Sys.file_exists args.config_file then Format.eprintf "Ignoring previous configuration file: %s.@." args.config_file ; let* config = Node_shared_arg.read_and_patch_config_file args in let* () = Node_config_validation.check config in Node_config_file.write args.config_file config let init (args : Node_shared_arg.t) = let open Lwt_result_syntax in let*! () = Tezos_base_unix.Internal_event_unix.init () in if Sys.file_exists args.config_file then failwith "Pre-existing configuration file at %s, use `reset`." args.config_file else let* config = Node_shared_arg.read_and_patch_config_file ~may_override_network:true args in let* () = Node_config_validation.check config in let* () = Node_config_file.write args.config_file config in let default = if args.network = None then " default" else "" in let alias = match config.blockchain_network.alias with | None -> "" | Some alias -> ": " ^ alias in Format.eprintf "Created %s for%s network%s.@." args.config_file default alias ; return_unit let update (args : Node_shared_arg.t) = let open Lwt_result_syntax in let*! () = Tezos_base_unix.Internal_event_unix.init () in if not (Sys.file_exists args.config_file) then failwith "Missing configuration file at %s. Use `%s config init [options]` to \ generate a new file" args.config_file Sys.argv.(0) else let* config = Node_shared_arg.read_and_patch_config_file args in let* () = Node_config_validation.check config in Node_config_file.write args.config_file config let validate (args : Node_shared_arg.t) = let open Lwt_result_syntax in let*! () = Tezos_base_unix.Internal_event_unix.init () in if not (Sys.file_exists args.config_file) then Format.eprintf "@[<v>@[<v 9>Warning: no configuration file found at %s@,\ validating the default configuration@]@]@." args.config_file ; let* config = Node_shared_arg.read_and_patch_config_file args in let*! r = Node_config_validation.check config in match r with | Error (Node_config_validation.Invalid_node_configuration :: _) | Ok () -> return_unit | err -> Lwt.return err module Term = struct type subcommand = Show | Reset | Init | Update | Validate let process subcommand args = let res = match subcommand with | Show -> show args | Reset -> reset args | Init -> init args | Update -> update args | Validate -> validate args in match Lwt_main.run @@ Lwt_exit.wrap_and_exit res with | Ok () -> `Ok () | Error err -> `Error (false, Format.asprintf "%a" pp_print_trace err) let subcommand_arg = let parser = function | "show" -> `Ok Show | "reset" -> `Ok Reset | "init" -> `Ok Init | "update" -> `Ok Update | "validate" -> `Ok Validate | s -> `Error ("invalid argument: " ^ s) and printer ppf = function | Show -> Format.fprintf ppf "show" | Reset -> Format.fprintf ppf "reset" | Init -> Format.fprintf ppf "init" | Update -> Format.fprintf ppf "update" | Validate -> Format.fprintf ppf "validate" in let open Cmdliner.Arg in let doc = "Operation to perform. Possible values: $(b,show), $(b,reset), \ $(b,init), $(b,update), $(b,validate)." in value & pos 0 (parser, printer) Show & info [] ~docv:"OPERATION" ~doc let term = let open Cmdliner.Term in ret (const process $ subcommand_arg $ Node_shared_arg.Term.args) end module Manpage = struct let command_description = "The $(b,config) command is meant to inspect and amend the configuration \ of the Tezos node. This command is complementary to manually editing the \ tezos node configuration file. Its arguments are a subset of the $(i,run) \ command ones." let description = [ `S "DESCRIPTION"; `P (command_description ^ " Several operations are possible: "); `P "$(b,show) reads, parses and displays Tezos current config file. Use \ this command to see exactly what config file will be used by Tezos. \ If additional command-line arguments are provided, the displayed \ configuration will be amended accordingly. This is the default \ operation."; `P "$(b,reset) will overwrite the current configuration file with a \ factory default one. If additional command-line arguments are \ provided, they will amend the generated file. It assumes that a \ configuration file already exists and will abort otherwise."; `P "$(b,init) is like reset but assumes that no configuration file is \ present and will abort otherwise."; `P "$(b,update) is the main option to edit the configuration file of \ Tezos. It will parse command line arguments and add or replace \ corresponding entries in the Tezos configuration file."; `P "$(b,validate) verifies that the configuration file parses correctly \ and performs some sanity checks on its values."; ] let options = let schema = Data_encoding.Json.schema Node_config_file.encoding in let schema = Format.asprintf "@[%a@]" Json_schema.pp schema in let schema = String.concat "\\$" (String.split '$' schema) in [`S "OPTIONS"; `P "All options available in the config file"; `Pre schema] let man = description @ Node_shared_arg.Manpage.args @ options @ Node_shared_arg.Manpage.bugs let info = Cmdliner.Term.info ~doc:"Manage node configuration" ~man "config" end let cmd = (Term.term, Manpage.info)
35f610e90c4ba507e96a5622ed29547d9306f94ef2dbef84c427a3d99c20d346
xtdb/xtdb
jdbc.clj
(ns xtdb.fixtures.jdbc (:require [clojure.java.io :as io] [clojure.test :as t] [xtdb.fixtures :as fix] [xtdb.jdbc :as j] [juxt.clojars-mirrors.nextjdbc.v1v2v674.next.jdbc :as jdbc]) (:import com.opentable.db.postgres.embedded.EmbeddedPostgres)) (def ^:dynamic *jdbc-opts*) (def ^:dynamic *db-type*) (defn with-opts [opts f] (binding [*jdbc-opts* opts] (f))) (defn with-db-type [f] (binding [*db-type* (j/db-type (-> @(:!system fix/*api*) (get-in [::j/connection-pool :dialect])))] (f))) (defn with-h2-opts [f] (fix/with-tmp-dirs #{db-dir} (with-opts {:dialect 'xtdb.jdbc.h2/->dialect :db-spec {:dbname (str (io/file db-dir "xtdbtest"))}} f))) (defn with-sqlite-opts [f] (fix/with-tmp-dirs #{db-dir} (with-opts {:dialect 'xtdb.jdbc.sqlite/->dialect :db-spec {:dbname (str (io/file db-dir "xtdbtest"))}} f))) (defn with-mssql-opts [db-spec f] (with-opts {:dialect 'xtdb.jdbc.mssql/->dialect :db-spec db-spec} f)) (defn with-mysql-opts [db-spec f] (with-opts {:dialect 'xtdb.jdbc.mysql/->dialect :db-spec db-spec} f)) (defn with-embedded-postgres [f] (with-open [pg (.start (EmbeddedPostgres/builder))] (with-opts {:dialect 'xtdb.jdbc.psql/->dialect :db-spec {:port (.getPort pg) :dbname "postgres" :user "postgres"}} f))) (defn with-postgres-opts [db-spec f] (with-opts {:dialect 'xtdb.jdbc.psql/->dialect :db-spec db-spec} f)) (def jdbc-dialects (cond-> #{:h2 :sqlite #_:postgres #_:mysql #_:mssql} ;; current :embedded-postgres dep does not support m1 (amd64) ;; we can upgrade to get support via docker, but it changes the lib significantly (native tarball vs docker) ;; so skipping tests for now (not= "aarch64" (System/getProperty "os.arch")) (conj :embedded-postgres))) (defn set-test-dialects! "Use to override the dialects used for tests using the with-each-jdbc-dialect fixture. Usage: (set-test-dialects! :h2 :sqlite :mysql)" [& dialects] (alter-var-root #'jdbc-dialects (constantly (set dialects)))) ;; Optional: ;; in `xtdb-jdbc`: `docker-compose up` (`docker-compose up -d` for background) (defn with-each-jdbc-dialect [f] (when (:h2 jdbc-dialects) (t/testing "H2" (with-h2-opts f))) (when (:sqlite jdbc-dialects) (t/testing "SQLite" (with-sqlite-opts f))) (when (:embedded-postgres jdbc-dialects) (t/testing "embedded Postgres" (with-embedded-postgres f))) (when (:postgres jdbc-dialects) (t/testing "Postgres" (with-open [conn (jdbc/get-connection {:dbtype "postgresql", :user "postgres", :password "postgres"})] (jdbc/execute! conn ["DROP DATABASE IF EXISTS xtdbtest"]) (jdbc/execute! conn ["CREATE DATABASE xtdbtest"])) (with-postgres-opts {:dbname "xtdbtest", :user "postgres", :password "postgres"} f))) (when (:mysql jdbc-dialects) (t/testing "MySQL Database" (with-open [conn (jdbc/get-connection {:dbtype "mysql", :user "root", :password "my-secret-pw"})] (jdbc/execute! conn ["DROP DATABASE IF EXISTS xtdbtest"]) (jdbc/execute! conn ["CREATE DATABASE xtdbtest"])) (with-mysql-opts {:dbname "xtdbtest", :user "root", :password "my-secret-pw"} f))) (when (:mssql jdbc-dialects) (t/testing "MSSQL Database" (with-open [conn (jdbc/get-connection {:dbtype "mssql", :user "sa", :password "yourStrong(!)Password"})] (jdbc/execute! conn ["DROP DATABASE IF EXISTS xtdbtest"]) (jdbc/execute! conn ["CREATE DATABASE xtdbtest"])) (with-mssql-opts {:dbname "xtdbtest" :user "sa" :password "yourStrong(!)Password"} f))) (when (:oracle jdbc-dialects) Oh , Oracle . Right . Set up . We create a image for Oracle Express Edition ( XE ) ;; - `git clone -images.git /tmp/oracle-docker` - ` cd /tmp / oracle - docker / OracleDatabase / SingleInstance / dockerfiles ` - ` ./buildContainerImage.sh -x -v 18.4.0 ` ;; Go make a cup of coffee. Build completed in 530 seconds . Let 's continue . ;; - `docker-compose -f docker-compose.oracle.yml up -d` Time to go make another cup of coffee . ;; The below still fails with an auth error, I can't see why. Sorry :( (t/testing "Oracle Database" (with-opts {:dialect 'xtdb.jdbc.oracle/->dialect :db-spec {:jdbcUrl "jdbc:oracle:thin:@127.0.0.1:51521:XE" :username "sys as sysdba" :password "mysecurepassword"}} f)))) (defn with-jdbc-node [f] (fix/with-opts {::j/connection-pool *jdbc-opts* :xtdb/tx-log {:xtdb/module `j/->tx-log :connection-pool ::j/connection-pool} :xtdb/document-store {:xtdb/module `j/->document-store, :connection-pool ::j/connection-pool}} f)) FIXME # 1588 (t/deftest test-jdbc-url-string-key-1588 (when (:postgres jdbc-dialects) (let [jdbc-url "jdbc:postgresql:5432/postgres?user=postgres&password=postgres"] (with-postgres-opts {"jdbcUrl" jdbc-url} (fn [] (with-jdbc-node (fn [] (fix/with-node (fn [] (t/is true))))))))))
null
https://raw.githubusercontent.com/xtdb/xtdb/d29ff33d2433b5b72a75bffa2d3ac7ffad5bb6ea/test/src/xtdb/fixtures/jdbc.clj
clojure
current :embedded-postgres dep does not support m1 (amd64) we can upgrade to get support via docker, but it changes the lib significantly (native tarball vs docker) so skipping tests for now Optional: in `xtdb-jdbc`: `docker-compose up` (`docker-compose up -d` for background) - `git clone -images.git /tmp/oracle-docker` Go make a cup of coffee. - `docker-compose -f docker-compose.oracle.yml up -d` The below still fails with an auth error, I can't see why. Sorry :(
(ns xtdb.fixtures.jdbc (:require [clojure.java.io :as io] [clojure.test :as t] [xtdb.fixtures :as fix] [xtdb.jdbc :as j] [juxt.clojars-mirrors.nextjdbc.v1v2v674.next.jdbc :as jdbc]) (:import com.opentable.db.postgres.embedded.EmbeddedPostgres)) (def ^:dynamic *jdbc-opts*) (def ^:dynamic *db-type*) (defn with-opts [opts f] (binding [*jdbc-opts* opts] (f))) (defn with-db-type [f] (binding [*db-type* (j/db-type (-> @(:!system fix/*api*) (get-in [::j/connection-pool :dialect])))] (f))) (defn with-h2-opts [f] (fix/with-tmp-dirs #{db-dir} (with-opts {:dialect 'xtdb.jdbc.h2/->dialect :db-spec {:dbname (str (io/file db-dir "xtdbtest"))}} f))) (defn with-sqlite-opts [f] (fix/with-tmp-dirs #{db-dir} (with-opts {:dialect 'xtdb.jdbc.sqlite/->dialect :db-spec {:dbname (str (io/file db-dir "xtdbtest"))}} f))) (defn with-mssql-opts [db-spec f] (with-opts {:dialect 'xtdb.jdbc.mssql/->dialect :db-spec db-spec} f)) (defn with-mysql-opts [db-spec f] (with-opts {:dialect 'xtdb.jdbc.mysql/->dialect :db-spec db-spec} f)) (defn with-embedded-postgres [f] (with-open [pg (.start (EmbeddedPostgres/builder))] (with-opts {:dialect 'xtdb.jdbc.psql/->dialect :db-spec {:port (.getPort pg) :dbname "postgres" :user "postgres"}} f))) (defn with-postgres-opts [db-spec f] (with-opts {:dialect 'xtdb.jdbc.psql/->dialect :db-spec db-spec} f)) (def jdbc-dialects (cond-> #{:h2 :sqlite #_:postgres #_:mysql #_:mssql} (not= "aarch64" (System/getProperty "os.arch")) (conj :embedded-postgres))) (defn set-test-dialects! "Use to override the dialects used for tests using the with-each-jdbc-dialect fixture. Usage: (set-test-dialects! :h2 :sqlite :mysql)" [& dialects] (alter-var-root #'jdbc-dialects (constantly (set dialects)))) (defn with-each-jdbc-dialect [f] (when (:h2 jdbc-dialects) (t/testing "H2" (with-h2-opts f))) (when (:sqlite jdbc-dialects) (t/testing "SQLite" (with-sqlite-opts f))) (when (:embedded-postgres jdbc-dialects) (t/testing "embedded Postgres" (with-embedded-postgres f))) (when (:postgres jdbc-dialects) (t/testing "Postgres" (with-open [conn (jdbc/get-connection {:dbtype "postgresql", :user "postgres", :password "postgres"})] (jdbc/execute! conn ["DROP DATABASE IF EXISTS xtdbtest"]) (jdbc/execute! conn ["CREATE DATABASE xtdbtest"])) (with-postgres-opts {:dbname "xtdbtest", :user "postgres", :password "postgres"} f))) (when (:mysql jdbc-dialects) (t/testing "MySQL Database" (with-open [conn (jdbc/get-connection {:dbtype "mysql", :user "root", :password "my-secret-pw"})] (jdbc/execute! conn ["DROP DATABASE IF EXISTS xtdbtest"]) (jdbc/execute! conn ["CREATE DATABASE xtdbtest"])) (with-mysql-opts {:dbname "xtdbtest", :user "root", :password "my-secret-pw"} f))) (when (:mssql jdbc-dialects) (t/testing "MSSQL Database" (with-open [conn (jdbc/get-connection {:dbtype "mssql", :user "sa", :password "yourStrong(!)Password"})] (jdbc/execute! conn ["DROP DATABASE IF EXISTS xtdbtest"]) (jdbc/execute! conn ["CREATE DATABASE xtdbtest"])) (with-mssql-opts {:dbname "xtdbtest" :user "sa" :password "yourStrong(!)Password"} f))) (when (:oracle jdbc-dialects) Oh , Oracle . Right . Set up . We create a image for Oracle Express Edition ( XE ) - ` cd /tmp / oracle - docker / OracleDatabase / SingleInstance / dockerfiles ` - ` ./buildContainerImage.sh -x -v 18.4.0 ` Build completed in 530 seconds . Let 's continue . Time to go make another cup of coffee . (t/testing "Oracle Database" (with-opts {:dialect 'xtdb.jdbc.oracle/->dialect :db-spec {:jdbcUrl "jdbc:oracle:thin:@127.0.0.1:51521:XE" :username "sys as sysdba" :password "mysecurepassword"}} f)))) (defn with-jdbc-node [f] (fix/with-opts {::j/connection-pool *jdbc-opts* :xtdb/tx-log {:xtdb/module `j/->tx-log :connection-pool ::j/connection-pool} :xtdb/document-store {:xtdb/module `j/->document-store, :connection-pool ::j/connection-pool}} f)) FIXME # 1588 (t/deftest test-jdbc-url-string-key-1588 (when (:postgres jdbc-dialects) (let [jdbc-url "jdbc:postgresql:5432/postgres?user=postgres&password=postgres"] (with-postgres-opts {"jdbcUrl" jdbc-url} (fn [] (with-jdbc-node (fn [] (fix/with-node (fn [] (t/is true))))))))))
f40c000270036de0fc9958783881fb59e836bc3ca6ef3b29f32d8dd3d22431a9
kapilreddy/in-clojure-2018
core.clj
(ns in-clojure-2018.core (:require [in-clojure-2018.helper :as h] [clojure.core.async :refer [chan go <! >! <!! >!! alt! go-loop]])) ;; Problem - > ? ? ? - > ES ;; +1 (comment (let [e (h/init-es-bulk-updater (fn [success] ) ;; on error (fn [error] ))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (println "\t" m) (h/bulk-process-update e m)))) ;; +1 (comment (let [e (h/init-es-bulk-updater (fn [success] (case success :es-bulk-start (println "\t" "Bulk start") :es-bulk-success (println "\t" "Bulk success"))) ;; on error (fn [error] (case error :es-slow (println "\t" "ES response time is slow") :es-timeout (println "\t" "ES response timed out"))))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (println "\t" m) (h/bulk-process-update e m)))) ;; +1 ;; We introduce with-stubbed-events that emulates IO ;; Intro / Happy path (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:es :es-bulk-success]] (let [e (h/init-es-bulk-updater (fn [success] (println "\t" success)) ;; on error (fn [error] (println "\t" error)))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (println "\t" m) (h/bulk-process-update e m))))) ;; Condition #1 (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:kafka "kafka-msg-3*"] ;; !!! [:es :es-bulk-success] ] (let [e (h/init-es-bulk-updater (fn [success] (println "\t" success)) ;; on error (fn [error]))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (println "\t" m) (h/bulk-process-update e m))))) ;; +1 ;; Condition #1 / Solution (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:kafka "kafka-msg-3*"] ;;; !!! [:es :es-bulk-success]] (let [success-a (atom nil) e (h/init-es-bulk-updater (fn [success] (reset! success-a success) (println "\t" success)) ;; on error (fn [error] ))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (when (= @success-a :es-bulk-start) (loop [] (when-not (= @success-a :es-bulk-success) (recur)))) (println "\t" m) (h/bulk-process-update e m))))) ;; +2 Condition # 2 (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:kafka "kafka-msg-3*"] ;;!!! [:es :es-slow] [:kafka "kafka-msg-4"]] (let [success-a (atom nil) e (h/init-es-bulk-updater (fn [success] (println "\t" success) (reset! success-a success)) ;; on error (fn [error] (println "\t" error)))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (when (= @success-a :es-bulk-start) (loop [] (when-not (= @success-a :es-bulk-success) (recur)))) (println "\t" m) (h/bulk-process-update e m))))) ;; +2 ;; Condition #2 / Solution (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:kafka "kafka-msg-3*"] ;; !!! [:es :es-slow] [:kafka "kafka-msg-4"]] (let [success-a (atom nil) error-a (atom nil) e (h/init-es-bulk-updater (fn [success] (println "\t" success) (reset! success-a success)) ;; on error (fn [error] (println "\t" error) (reset! error-a error)))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (when (= @success-a :es-bulk-start) (loop [] (when-not (or (= @success-a :es-bulk-success) @error-a) (recur)))) (println "\t" m) (h/bulk-process-update e m))))) ;; +2 ;; Condition #3 (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:kafka "kafka-msg-3*"] ;;!!! [:es :es-slow] [:kafka "kafka-msg-4"] [:es :es-bulk-start] [:kafka "kafka-msg-5*"] ;;!!! [:es :es-bulk-success]] (let [success-a (atom nil) error-a (atom nil) e (h/init-es-bulk-updater (fn [success] (println "\t" success) (reset! success-a success)) ;; on error (fn [error] (println "\t" error) (reset! error-a error)))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (when (= @success-a :es-bulk-start) (loop [] (when (and (not= @success-a :es-bulk-success) (not @error-a)) (recur)))) (println "\t" m) (h/bulk-process-update e m))))) ;; +2 ;; Condition #3 / Solution (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:kafka "kafka-msg-3*"] ;;!!! [:es :es-slow] [:kafka "kafka-msg-4"] [:es :es-bulk-start] [:kafka "kafka-msg-5*"] ;;!!! [:es :es-bulk-success]] (let [success-a (atom nil) error-a (atom nil) e (h/init-es-bulk-updater (fn [success] (println "\t" success) (reset! success-a success)) ;; on error (fn [error] (println "\t" error) (reset! error-a error)))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (when (= @success-a :es-bulk-start) (loop [] (when (and (not= @success-a :es-bulk-success) (not @error-a)) (recur)))) (when @error-a (reset! error-a nil) (reset! success-a nil)) (println "\t" m) (h/bulk-process-update e m))))) ;; +2 ;; Intro to core.async (comment ;; core async intro (let [c (chan)] (go (>! c "message")) (go (println "\t" "Message from channel c "(<! c)))) (let [c-1 (chan)] (go (>! c-1 "message-1") (println "\t" "First put succeded")) (go (>! c-1 "message-2") (println "\t" "Second put succeded")) (go (<! c-1))) (let [c-2 (chan)] (go (>! c-2 "message-1")) (go (println "\t" "Message from channel " (<! c-2))) (go (println "\t" "Message from channel " (<! c-2)))) ;; alt! example (do (let [chan-1 (chan) chan-2 (chan)] (go (Thread/sleep (rand-int 1000)) (>! chan-1 "message 1")) (go (Thread/sleep (rand-int 1000)) (>! chan-2 "message 1")) (go (alt! chan-1 ([msg] (println "\t" "Message from channel 1 ")) chan-2 ([msg] (println "\t" "Message from channel 2 "))))))) ;; +2 ;; Place core.async (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:es :es-bulk-success]] (let [msg-chan (chan) e (h/init-es-bulk-updater (fn [success] (println "\t" success)) ;; on error (fn [error] (case error )))] (future (loop [] (let [m (<!! msg-chan)] (println "\t" m) (h/bulk-process-update e m)) (recur))) Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (>!! msg-chan m))))) ;; +3 (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:kafka "kafka-msg-3*"] ;;!!! [:es :es-slow] [:kafka "kafka-msg-4"] [:es :es-bulk-start] [:kafka "kafka-msg-5*"] ;;!!! [:es :es-bulk-success]] (let [control-chan (chan) msg-chan (chan) e (h/init-es-bulk-updater (fn [success] (>!! control-chan success) (println "\t" success)) ;; on error (fn [error] (>!! control-chan error) (println "\t" error)))] (go-loop [state :init] (case state :es-bulk-start (recur (<! control-chan)) (alt! control-chan ([msg] (case msg :es-bulk-start (recur :es-bulk-start) :es-bulk-success (do ;; (commit-kafka-offsets) (recur :es-bulk-success)) :es-slow (do (Thread/sleep 5000) (recur :es-slow)))) msg-chan ([msg] (println "\t" msg) (h/bulk-process-update e msg) (recur state))))) Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (>!! msg-chan m)))))
null
https://raw.githubusercontent.com/kapilreddy/in-clojure-2018/57e633bf40e3e55f233cf2d819ebb7a285f2b4d5/src/in_clojure_2018/core.clj
clojure
Problem +1 on error +1 on error +1 We introduce with-stubbed-events that emulates IO Intro / Happy path on error Condition #1 !!! on error +1 Condition #1 / Solution !!! on error +2 !!! on error +2 Condition #2 / Solution !!! on error +2 Condition #3 !!! !!! on error +2 Condition #3 / Solution !!! !!! on error +2 Intro to core.async core async intro alt! example +2 Place core.async on error +3 !!! !!! on error (commit-kafka-offsets)
(ns in-clojure-2018.core (:require [in-clojure-2018.helper :as h] [clojure.core.async :refer [chan go <! >! <!! >!! alt! go-loop]])) - > ? ? ? - > ES (comment (let [e (h/init-es-bulk-updater (fn [success] ) (fn [error] ))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (println "\t" m) (h/bulk-process-update e m)))) (comment (let [e (h/init-es-bulk-updater (fn [success] (case success :es-bulk-start (println "\t" "Bulk start") :es-bulk-success (println "\t" "Bulk success"))) (fn [error] (case error :es-slow (println "\t" "ES response time is slow") :es-timeout (println "\t" "ES response timed out"))))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (println "\t" m) (h/bulk-process-update e m)))) (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:es :es-bulk-success]] (let [e (h/init-es-bulk-updater (fn [success] (println "\t" success)) (fn [error] (println "\t" error)))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (println "\t" m) (h/bulk-process-update e m))))) (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:es :es-bulk-success] ] (let [e (h/init-es-bulk-updater (fn [success] (println "\t" success)) (fn [error]))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (println "\t" m) (h/bulk-process-update e m))))) (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:es :es-bulk-success]] (let [success-a (atom nil) e (h/init-es-bulk-updater (fn [success] (reset! success-a success) (println "\t" success)) (fn [error] ))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (when (= @success-a :es-bulk-start) (loop [] (when-not (= @success-a :es-bulk-success) (recur)))) (println "\t" m) (h/bulk-process-update e m))))) Condition # 2 (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:es :es-slow] [:kafka "kafka-msg-4"]] (let [success-a (atom nil) e (h/init-es-bulk-updater (fn [success] (println "\t" success) (reset! success-a success)) (fn [error] (println "\t" error)))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (when (= @success-a :es-bulk-start) (loop [] (when-not (= @success-a :es-bulk-success) (recur)))) (println "\t" m) (h/bulk-process-update e m))))) (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:es :es-slow] [:kafka "kafka-msg-4"]] (let [success-a (atom nil) error-a (atom nil) e (h/init-es-bulk-updater (fn [success] (println "\t" success) (reset! success-a success)) (fn [error] (println "\t" error) (reset! error-a error)))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (when (= @success-a :es-bulk-start) (loop [] (when-not (or (= @success-a :es-bulk-success) @error-a) (recur)))) (println "\t" m) (h/bulk-process-update e m))))) (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:es :es-slow] [:kafka "kafka-msg-4"] [:es :es-bulk-start] [:es :es-bulk-success]] (let [success-a (atom nil) error-a (atom nil) e (h/init-es-bulk-updater (fn [success] (println "\t" success) (reset! success-a success)) (fn [error] (println "\t" error) (reset! error-a error)))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (when (= @success-a :es-bulk-start) (loop [] (when (and (not= @success-a :es-bulk-success) (not @error-a)) (recur)))) (println "\t" m) (h/bulk-process-update e m))))) (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:es :es-slow] [:kafka "kafka-msg-4"] [:es :es-bulk-start] [:es :es-bulk-success]] (let [success-a (atom nil) error-a (atom nil) e (h/init-es-bulk-updater (fn [success] (println "\t" success) (reset! success-a success)) (fn [error] (println "\t" error) (reset! error-a error)))] Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (when (= @success-a :es-bulk-start) (loop [] (when (and (not= @success-a :es-bulk-success) (not @error-a)) (recur)))) (when @error-a (reset! error-a nil) (reset! success-a nil)) (println "\t" m) (h/bulk-process-update e m))))) (comment (let [c (chan)] (go (>! c "message")) (go (println "\t" "Message from channel c "(<! c)))) (let [c-1 (chan)] (go (>! c-1 "message-1") (println "\t" "First put succeded")) (go (>! c-1 "message-2") (println "\t" "Second put succeded")) (go (<! c-1))) (let [c-2 (chan)] (go (>! c-2 "message-1")) (go (println "\t" "Message from channel " (<! c-2))) (go (println "\t" "Message from channel " (<! c-2)))) (do (let [chan-1 (chan) chan-2 (chan)] (go (Thread/sleep (rand-int 1000)) (>! chan-1 "message 1")) (go (Thread/sleep (rand-int 1000)) (>! chan-2 "message 1")) (go (alt! chan-1 ([msg] (println "\t" "Message from channel 1 ")) chan-2 ([msg] (println "\t" "Message from channel 2 "))))))) (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:es :es-bulk-success]] (let [msg-chan (chan) e (h/init-es-bulk-updater (fn [success] (println "\t" success)) (fn [error] (case error )))] (future (loop [] (let [m (<!! msg-chan)] (println "\t" m) (h/bulk-process-update e m)) (recur))) Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (>!! msg-chan m))))) (comment (h/with-stubbed-events [[:kafka "kafka-msg-1"] [:kafka "kafka-msg-2"] [:es :es-bulk-start] [:es :es-slow] [:kafka "kafka-msg-4"] [:es :es-bulk-start] [:es :es-bulk-success]] (let [control-chan (chan) msg-chan (chan) e (h/init-es-bulk-updater (fn [success] (>!! control-chan success) (println "\t" success)) (fn [error] (>!! control-chan error) (println "\t" error)))] (go-loop [state :init] (case state :es-bulk-start (recur (<! control-chan)) (alt! control-chan ([msg] (case msg :es-bulk-start (recur :es-bulk-start) (recur :es-bulk-success)) :es-slow (do (Thread/sleep 5000) (recur :es-slow)))) msg-chan ([msg] (println "\t" msg) (h/bulk-process-update e msg) (recur state))))) Long running (doseq [m (h/kafka-messages "elastic_search_updates")] (>!! msg-chan m)))))
589960310432ecdb7d2822bd7f905518298fc8bbf084f01699b349b9cf4d95d3
fmi-lab/fp-elective-2017
sum-digits.scm
(require rackunit rackunit/text-ui) ; Единствената разлика с count-digits е в изчисляването на новия result. (define (sum-digits n) (define (helper counter result) (if (= counter 0) result (helper (quotient counter 10) (+ result (remainder counter 10))))) (helper n 0)) (define sum-digits-tests (test-suite "Tests for sum-digits" (check = (sum-digits 3) 3) (check = (sum-digits 12) 3) (check = (sum-digits 42) 6) (check = (sum-digits 666) 18) (check = (sum-digits 1337) 14) (check = (sum-digits 65510) 17) (check = (sum-digits 8833443388) 52) (check = (sum-digits 100000000000) 1))) (run-tests sum-digits-tests)
null
https://raw.githubusercontent.com/fmi-lab/fp-elective-2017/e88d5c0319b6d03c0ecd8a12a2856fb1bf5dcbf3/exercises/02/sum-digits.scm
scheme
Единствената разлика с count-digits е в изчисляването на новия result.
(require rackunit rackunit/text-ui) (define (sum-digits n) (define (helper counter result) (if (= counter 0) result (helper (quotient counter 10) (+ result (remainder counter 10))))) (helper n 0)) (define sum-digits-tests (test-suite "Tests for sum-digits" (check = (sum-digits 3) 3) (check = (sum-digits 12) 3) (check = (sum-digits 42) 6) (check = (sum-digits 666) 18) (check = (sum-digits 1337) 14) (check = (sum-digits 65510) 17) (check = (sum-digits 8833443388) 52) (check = (sum-digits 100000000000) 1))) (run-tests sum-digits-tests)
a5ddab4fa1679db197d0584ccd3c8ea3a034fb9aeed6a15cfaa4fbda3326cc94
CloudI/CloudI
b64.erl
-*- coding : utf-8 ; erlang - indent - level : 2 -*- %%% ------------------------------------------------------------------- Copyright 2010 - 2021 < > , < > , and < > %%% This file is part of PropEr . %%% %%% PropEr is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or %%% (at your option) any later version. %%% %%% PropEr is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %%% GNU General Public License for more details. %%% You should have received a copy of the GNU General Public License %%% along with PropEr. If not, see </>. 2010 - 2021 , , and %%% @version {@version} @author %%% @doc PropEr usage example: Some simple testcases for stdlib's base64 -module(b64). -export([prop_enc_dec/0]). -include_lib("proper/include/proper.hrl"). -include_lib("eunit/include/eunit.hrl"). prop_enc_dec() -> ?FORALL(Msg, union([binary(), list(range(1,255))]), begin EncDecMsg = base64:decode(base64:encode(Msg)), case is_binary(Msg) of true -> EncDecMsg =:= Msg; false -> EncDecMsg =:= list_to_binary(Msg) end end). b64_test_() -> {"Enc/dec", ?_assert(proper:quickcheck(prop_enc_dec(), [{numtests,10000}]))}.
null
https://raw.githubusercontent.com/CloudI/CloudI/3e45031c7ee3e974ead2612ea7dd06c9edf973c9/src/external/proper/examples/b64.erl
erlang
------------------------------------------------------------------- PropEr is free software: you can redistribute it and/or modify (at your option) any later version. PropEr is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with PropEr. If not, see </>. @version {@version} @doc PropEr usage example: Some simple testcases for stdlib's base64
-*- coding : utf-8 ; erlang - indent - level : 2 -*- Copyright 2010 - 2021 < > , < > , and < > This file is part of PropEr . it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License 2010 - 2021 , , and @author -module(b64). -export([prop_enc_dec/0]). -include_lib("proper/include/proper.hrl"). -include_lib("eunit/include/eunit.hrl"). prop_enc_dec() -> ?FORALL(Msg, union([binary(), list(range(1,255))]), begin EncDecMsg = base64:decode(base64:encode(Msg)), case is_binary(Msg) of true -> EncDecMsg =:= Msg; false -> EncDecMsg =:= list_to_binary(Msg) end end). b64_test_() -> {"Enc/dec", ?_assert(proper:quickcheck(prop_enc_dec(), [{numtests,10000}]))}.
f2a788fdddacc0cfbd478c470c5cc3a4e2e302fa39b3f214a1ba23ceb5fdd81d
qfpl/reflex-tutorial
Dynamic.hs
module Posts.Component.Dynamic ( ) where
null
https://raw.githubusercontent.com/qfpl/reflex-tutorial/07c1e6fab387cbeedd031630ba6a5cd946cc612e/code/basics/src/Posts/Component/Dynamic.hs
haskell
module Posts.Component.Dynamic ( ) where
34f7472e9d3bef337df6b7cd8998ee082b30aa0de52cfb85e5e46152ad23fde1
static-analysis-engineering/codehawk
tCHTestSuite.ml
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Unit Testing Framework Author : Adapted from : ( ) ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2019 Kestrel Technology LLC Copyright ( c ) 2020 - 2021 ) 2022 Aarno Labs LLC 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 , 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 . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Unit Testing Framework Author: Henny Sipma Adapted from: Kaputt () ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2019 Kestrel Technology LLC Copyright (c) 2020-2021 Henny Sipma Copyright (c) 2022 Aarno Labs LLC 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. ============================================================================= *) chlib open CHCommon open CHPretty (* chutil *) open CHFileIO open CHPrettyUtil open CHXmlDocument (* tchlib *) open TCHTestApi module H = Hashtbl let print_exception e = match e with | CHFailure p -> p | _ -> STR (Printexc.to_string e) let print_result (len:int) (index:int) (name:string) (result:testresult_t) = match result with | Passed t -> pr_debug [ fixed_length_pretty ~alignment:StrRight (INT index) 3; STR " "; fixed_length_pretty (STR name) len; STR " [ ... passed ("; STR (Printf.sprintf "%f" t); STR " secs) ]"; NL] | Failed { expected_value; actual_value; fmessage } -> if expected_value != actual_value then pr_debug [ fixed_length_pretty ~alignment:StrRight (INT index) 3; STR " "; fixed_length_pretty (STR name) len; STR " [ ... failed "; STR fmessage; NL; STR " expected "; STR expected_value; STR " but received "; STR actual_value; STR " ]"; NL] else pr_debug [ STR name; STR " ... failed "; STR fmessage; NL; STR " expected anything excluding "; STR expected_value; STR " but received "; STR actual_value; NL] | Uncaught (e, bt) -> pr_debug [ fixed_length_pretty ~alignment:StrRight (INT index) 3; STR " "; fixed_length_pretty (STR name) len; STR " [ ... raised an exception"; NL; STR " "; print_exception e; NL; STR bt; STR "]"; NL] | Report (valid, total, uncaught, counterexamples, categories, timeused) -> pr_debug [ fixed_length_pretty ~alignment:StrRight (INT index) 3; STR " "; fixed_length_pretty (STR name) len; STR " [ ... passed "; INT valid; STR "/"; INT total; STR " ("; STR (Printf.sprintf "%f" timeused); STR " secs) ]"; NL; (match counterexamples with | [] -> STR "" | l -> LBLOCK [ STR " counterexamples: "; pretty_print_list counterexamples (fun s -> STR s) "" ", " ""; NL]); (match categories with | [] -> STR "" | [("", _)] -> STR "" | _ -> LBLOCK [ STR " categories: "; pretty_print_list categories (fun (s, i) -> LBLOCK [STR s; STR ": "; INT i]) "" "; " ""; NL])] | Exit_code _ -> () let print_totals (name: string) (passed: int) (failed: int) (uncaught: int) (total: int) = pr_debug [ STR (string_repeat "-" 80); NL; STR "Summary for "; STR name; STR ":"; NL; STR "Passed : "; INT passed; STR "/"; INT total; NL; STR "Failed : "; INT failed; STR "/"; INT total; NL; STR "Uncaught : "; INT uncaught; STR "/"; INT total; NL; STR (string_repeat "=" 80); NL] let default_classifier _ = "" let default_reducer _ = [] let default_smaller _ _ = true let tests = H.create 3 let counter = ref 0 let testcounter = ref 0 let testsuitename = ref "testsuite" let testsuitedate = ref "2022-11-13" let fileresults = H.create 3 let testfilename = ref "testfile" let testfiledate = ref "2022-11-28" let get_title () = begin testcounter := !testcounter + 1; "test-" ^ (string_of_int !testcounter) end let get_seqnumber () = begin counter := !counter + 1; !counter end let add_simple_test ?(title=get_title ()) (f: unit -> unit) = let (name, test) = TCHTest.make_simple_test ~title f in H.add tests name (get_seqnumber (), test) let add_random_test ?(title=get_title ()) ?(nb_runs=100) ?(nb_tries=10*nb_runs) ?(classifier=default_classifier) ?(reducer=default_reducer) ?(reduce_depth=4) ?(reduce_smaller=default_smaller) ?(random_src=TCHGenerator.make_random ()) ((gen, prn): 'a generator_t) (f:'a -> 'b) (spec:(('a, 'b) specification_t) list) = let (name, test) = TCHTest.make_random_test ~title ~nb_runs ~nb_tries ~classifier ~reducer ~reduce_depth ~reduce_smaller ~random_src (gen, prn) f spec in H.add tests name (get_seqnumber (), test) let new_testfile (name: string) (date: string) = begin testfilename := name; testfiledate := date; H.clear fileresults end let add_results (tsname: string) (results: int * int * int * int) = H.add fileresults tsname results let report_results () = let (passed, failed, uncaught, total) = H.fold (fun _ (p, f, u, t) (tp, tf, tu, tt) -> (tp + p, tf + f, tu + u, tt + t)) fileresults (0, 0, 0, 0) in print_totals !testfilename passed failed uncaught total let exit_file () = let (passed, failed, uncaught, total) = H.fold (fun _ (p, f, u, t) (tp, tf, tu, tt) -> (tp + p, tf + f, tu + u, tt + t)) fileresults (0, 0, 0, 0) in begin print_totals !testfilename passed failed uncaught total; if failed + uncaught > 0 then begin pr_debug [ STR "Encountered "; INT (failed + uncaught); STR " failure(s)"; NL; NL]; exit 1 end else begin pr_debug [STR "All tests passed!"; NL; NL]; exit 0 end end let new_testsuite (name: string) (date: string) = begin testsuitename := name; testsuitedate := date; H.clear tests end let run_tests (names: string list) = let passed = ref 0 in let failed = ref 0 in let uncaught = ref 0 in let total = ref 0 in let lst = ref [] in let namelen = List.fold_left (fun m name -> let len = String.length name in if len > m then len else m) 0 names in let _ = List.iter (fun name -> if H.mem tests name then lst := (H.find tests name) :: !lst) (List.rev names) in begin pr_debug [ STR "Test suite "; STR !testsuitename; STR " (last updated: "; STR !testsuitedate; STR ")"; NL; STR (string_repeat "=" 80); NL]; List.iter (fun name -> let (index, testf) = H.find tests name in let result = testf () in begin (match result with | Passed _ -> begin incr passed; incr total end | Failed _ -> begin incr failed; incr total end | Uncaught _ -> begin incr uncaught; incr total end | Report (pass, tot, unc, _, _, _) -> begin passed := !passed + pass; failed := !failed + ((tot - pass) - unc); uncaught := !uncaught + unc; total := !total + tot end | Exit_code c -> begin incr (if c = 0 then passed else failed); incr total end); print_result namelen index name result end) names; print_totals !testsuitename !passed !failed !uncaught !total; add_results !testsuitename (!passed, !failed, !uncaught, !total) end let launch_tests () = let lst = ref [] in let _ = H.iter (fun name (index, _) -> lst := (index, name) :: !lst) tests in let lst = List.map snd (List.sort (fun (i1, _) (i2, _) -> Stdlib.compare i1 i2) !lst) in begin run_tests lst end
null
https://raw.githubusercontent.com/static-analysis-engineering/codehawk/c1b3158e0d73cda7cfc10d75f6173f4297991a82/CodeHawk/CHT/tchlib/tCHTestSuite.ml
ocaml
chutil tchlib
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Unit Testing Framework Author : Adapted from : ( ) ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2019 Kestrel Technology LLC Copyright ( c ) 2020 - 2021 ) 2022 Aarno Labs LLC 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 , 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 . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Unit Testing Framework Author: Henny Sipma Adapted from: Kaputt () ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2019 Kestrel Technology LLC Copyright (c) 2020-2021 Henny Sipma Copyright (c) 2022 Aarno Labs LLC 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. ============================================================================= *) chlib open CHCommon open CHPretty open CHFileIO open CHPrettyUtil open CHXmlDocument open TCHTestApi module H = Hashtbl let print_exception e = match e with | CHFailure p -> p | _ -> STR (Printexc.to_string e) let print_result (len:int) (index:int) (name:string) (result:testresult_t) = match result with | Passed t -> pr_debug [ fixed_length_pretty ~alignment:StrRight (INT index) 3; STR " "; fixed_length_pretty (STR name) len; STR " [ ... passed ("; STR (Printf.sprintf "%f" t); STR " secs) ]"; NL] | Failed { expected_value; actual_value; fmessage } -> if expected_value != actual_value then pr_debug [ fixed_length_pretty ~alignment:StrRight (INT index) 3; STR " "; fixed_length_pretty (STR name) len; STR " [ ... failed "; STR fmessage; NL; STR " expected "; STR expected_value; STR " but received "; STR actual_value; STR " ]"; NL] else pr_debug [ STR name; STR " ... failed "; STR fmessage; NL; STR " expected anything excluding "; STR expected_value; STR " but received "; STR actual_value; NL] | Uncaught (e, bt) -> pr_debug [ fixed_length_pretty ~alignment:StrRight (INT index) 3; STR " "; fixed_length_pretty (STR name) len; STR " [ ... raised an exception"; NL; STR " "; print_exception e; NL; STR bt; STR "]"; NL] | Report (valid, total, uncaught, counterexamples, categories, timeused) -> pr_debug [ fixed_length_pretty ~alignment:StrRight (INT index) 3; STR " "; fixed_length_pretty (STR name) len; STR " [ ... passed "; INT valid; STR "/"; INT total; STR " ("; STR (Printf.sprintf "%f" timeused); STR " secs) ]"; NL; (match counterexamples with | [] -> STR "" | l -> LBLOCK [ STR " counterexamples: "; pretty_print_list counterexamples (fun s -> STR s) "" ", " ""; NL]); (match categories with | [] -> STR "" | [("", _)] -> STR "" | _ -> LBLOCK [ STR " categories: "; pretty_print_list categories (fun (s, i) -> LBLOCK [STR s; STR ": "; INT i]) "" "; " ""; NL])] | Exit_code _ -> () let print_totals (name: string) (passed: int) (failed: int) (uncaught: int) (total: int) = pr_debug [ STR (string_repeat "-" 80); NL; STR "Summary for "; STR name; STR ":"; NL; STR "Passed : "; INT passed; STR "/"; INT total; NL; STR "Failed : "; INT failed; STR "/"; INT total; NL; STR "Uncaught : "; INT uncaught; STR "/"; INT total; NL; STR (string_repeat "=" 80); NL] let default_classifier _ = "" let default_reducer _ = [] let default_smaller _ _ = true let tests = H.create 3 let counter = ref 0 let testcounter = ref 0 let testsuitename = ref "testsuite" let testsuitedate = ref "2022-11-13" let fileresults = H.create 3 let testfilename = ref "testfile" let testfiledate = ref "2022-11-28" let get_title () = begin testcounter := !testcounter + 1; "test-" ^ (string_of_int !testcounter) end let get_seqnumber () = begin counter := !counter + 1; !counter end let add_simple_test ?(title=get_title ()) (f: unit -> unit) = let (name, test) = TCHTest.make_simple_test ~title f in H.add tests name (get_seqnumber (), test) let add_random_test ?(title=get_title ()) ?(nb_runs=100) ?(nb_tries=10*nb_runs) ?(classifier=default_classifier) ?(reducer=default_reducer) ?(reduce_depth=4) ?(reduce_smaller=default_smaller) ?(random_src=TCHGenerator.make_random ()) ((gen, prn): 'a generator_t) (f:'a -> 'b) (spec:(('a, 'b) specification_t) list) = let (name, test) = TCHTest.make_random_test ~title ~nb_runs ~nb_tries ~classifier ~reducer ~reduce_depth ~reduce_smaller ~random_src (gen, prn) f spec in H.add tests name (get_seqnumber (), test) let new_testfile (name: string) (date: string) = begin testfilename := name; testfiledate := date; H.clear fileresults end let add_results (tsname: string) (results: int * int * int * int) = H.add fileresults tsname results let report_results () = let (passed, failed, uncaught, total) = H.fold (fun _ (p, f, u, t) (tp, tf, tu, tt) -> (tp + p, tf + f, tu + u, tt + t)) fileresults (0, 0, 0, 0) in print_totals !testfilename passed failed uncaught total let exit_file () = let (passed, failed, uncaught, total) = H.fold (fun _ (p, f, u, t) (tp, tf, tu, tt) -> (tp + p, tf + f, tu + u, tt + t)) fileresults (0, 0, 0, 0) in begin print_totals !testfilename passed failed uncaught total; if failed + uncaught > 0 then begin pr_debug [ STR "Encountered "; INT (failed + uncaught); STR " failure(s)"; NL; NL]; exit 1 end else begin pr_debug [STR "All tests passed!"; NL; NL]; exit 0 end end let new_testsuite (name: string) (date: string) = begin testsuitename := name; testsuitedate := date; H.clear tests end let run_tests (names: string list) = let passed = ref 0 in let failed = ref 0 in let uncaught = ref 0 in let total = ref 0 in let lst = ref [] in let namelen = List.fold_left (fun m name -> let len = String.length name in if len > m then len else m) 0 names in let _ = List.iter (fun name -> if H.mem tests name then lst := (H.find tests name) :: !lst) (List.rev names) in begin pr_debug [ STR "Test suite "; STR !testsuitename; STR " (last updated: "; STR !testsuitedate; STR ")"; NL; STR (string_repeat "=" 80); NL]; List.iter (fun name -> let (index, testf) = H.find tests name in let result = testf () in begin (match result with | Passed _ -> begin incr passed; incr total end | Failed _ -> begin incr failed; incr total end | Uncaught _ -> begin incr uncaught; incr total end | Report (pass, tot, unc, _, _, _) -> begin passed := !passed + pass; failed := !failed + ((tot - pass) - unc); uncaught := !uncaught + unc; total := !total + tot end | Exit_code c -> begin incr (if c = 0 then passed else failed); incr total end); print_result namelen index name result end) names; print_totals !testsuitename !passed !failed !uncaught !total; add_results !testsuitename (!passed, !failed, !uncaught, !total) end let launch_tests () = let lst = ref [] in let _ = H.iter (fun name (index, _) -> lst := (index, name) :: !lst) tests in let lst = List.map snd (List.sort (fun (i1, _) (i2, _) -> Stdlib.compare i1 i2) !lst) in begin run_tests lst end
adf2a23be50c3267428a5ba705d205f7de42e5fe5df0d51e902ef6d2e2163c45
chicken-mobile/chicken-sdl2-android-builder
pixel-format.scm
;; chicken - sdl2 : CHICKEN Scheme bindings to Simple DirectMedia Layer 2 ;; Copyright © 2013 , 2015 - 2016 . ;; 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 COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS ;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 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. (export SDL_GetPixelFormatName SDL_PixelFormatEnumToMasks SDL_MasksToPixelFormatEnum SDL_AllocFormat SDL_FreeFormat SDL_AllocPalette SDL_FreePalette SDL_SetPixelFormatPalette SDL_SetPaletteColors SDL_MapRGB SDL_MapRGBA SDL_GetRGB SDL_GetRGBA SDL_CalculateGammaRamp) (define-function-binding SDL_GetPixelFormatName return: (c-string name) args: ((SDL_PixelFormatEnum format))) (define-function-binding SDL_PixelFormatEnumToMasks return: (bool success?) args: ((SDL_PixelFormatEnum format) (Sint32* bpp) (Uint32* rmask-out) (Uint32* gmask-out) (Uint32* bmask-out) (Uint32* amask-out))) (define-function-binding SDL_MasksToPixelFormatEnum return: (SDL_PixelFormatEnum format) args: ((Sint32 bpp) (Uint32 rmask) (Uint32 gmask) (Uint32 bmask) (Uint32 amask))) (define-function-binding SDL_AllocFormat return: (SDL_PixelFormat* format) args: ((SDL_PixelFormatEnum pixel_format))) (define-function-binding SDL_FreeFormat args: ((SDL_PixelFormat* format))) (define-function-binding SDL_AllocPalette return: (SDL_Palette* palette) args: ((Sint32 ncolors))) (define-function-binding SDL_FreePalette args: ((SDL_Palette* palette))) (define-function-binding SDL_SetPixelFormatPalette return: (Sint32 zero-if-success) args: ((SDL_PixelFormat* format) (SDL_Palette* palette))) (define-function-binding SDL_SetPaletteColors return: (Sint32 zero-if-success) args: ((SDL_Palette* palette) (SDL_Color* colors) (Sint32 firstcolor) (Sint32 ncolors))) (define-function-binding SDL_MapRGB return: (Uint32 color) args: ((SDL_PixelFormat* format) (Uint8 r) (Uint8 g) (Uint8 b))) (define-function-binding SDL_MapRGBA return: (Uint32 color) args: ((SDL_PixelFormat* format) (Uint8 r) (Uint8 g) (Uint8 b) (Uint8 a))) (define-function-binding SDL_GetRGB args: ((Uint32 pixel) (SDL_PixelFormat* format) (Uint8* r-out) (Uint8* g-out) (Uint8* b-out))) (define-function-binding SDL_GetRGBA args: ((Uint32 pixel) (SDL_PixelFormat* format) (Uint8* r-out) (Uint8* g-out) (Uint8* b-out) (Uint8* a-out))) (define-function-binding SDL_CalculateGammaRamp args: ((float gamma) (Uint16* ramp-out)))
null
https://raw.githubusercontent.com/chicken-mobile/chicken-sdl2-android-builder/90ef1f0ff667737736f1932e204d29ae615a00c4/eggs/sdl2/lib/sdl2-internals/functions/pixel-format.scm
scheme
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 COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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.
chicken - sdl2 : CHICKEN Scheme bindings to Simple DirectMedia Layer 2 Copyright © 2013 , 2015 - 2016 . " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , (export SDL_GetPixelFormatName SDL_PixelFormatEnumToMasks SDL_MasksToPixelFormatEnum SDL_AllocFormat SDL_FreeFormat SDL_AllocPalette SDL_FreePalette SDL_SetPixelFormatPalette SDL_SetPaletteColors SDL_MapRGB SDL_MapRGBA SDL_GetRGB SDL_GetRGBA SDL_CalculateGammaRamp) (define-function-binding SDL_GetPixelFormatName return: (c-string name) args: ((SDL_PixelFormatEnum format))) (define-function-binding SDL_PixelFormatEnumToMasks return: (bool success?) args: ((SDL_PixelFormatEnum format) (Sint32* bpp) (Uint32* rmask-out) (Uint32* gmask-out) (Uint32* bmask-out) (Uint32* amask-out))) (define-function-binding SDL_MasksToPixelFormatEnum return: (SDL_PixelFormatEnum format) args: ((Sint32 bpp) (Uint32 rmask) (Uint32 gmask) (Uint32 bmask) (Uint32 amask))) (define-function-binding SDL_AllocFormat return: (SDL_PixelFormat* format) args: ((SDL_PixelFormatEnum pixel_format))) (define-function-binding SDL_FreeFormat args: ((SDL_PixelFormat* format))) (define-function-binding SDL_AllocPalette return: (SDL_Palette* palette) args: ((Sint32 ncolors))) (define-function-binding SDL_FreePalette args: ((SDL_Palette* palette))) (define-function-binding SDL_SetPixelFormatPalette return: (Sint32 zero-if-success) args: ((SDL_PixelFormat* format) (SDL_Palette* palette))) (define-function-binding SDL_SetPaletteColors return: (Sint32 zero-if-success) args: ((SDL_Palette* palette) (SDL_Color* colors) (Sint32 firstcolor) (Sint32 ncolors))) (define-function-binding SDL_MapRGB return: (Uint32 color) args: ((SDL_PixelFormat* format) (Uint8 r) (Uint8 g) (Uint8 b))) (define-function-binding SDL_MapRGBA return: (Uint32 color) args: ((SDL_PixelFormat* format) (Uint8 r) (Uint8 g) (Uint8 b) (Uint8 a))) (define-function-binding SDL_GetRGB args: ((Uint32 pixel) (SDL_PixelFormat* format) (Uint8* r-out) (Uint8* g-out) (Uint8* b-out))) (define-function-binding SDL_GetRGBA args: ((Uint32 pixel) (SDL_PixelFormat* format) (Uint8* r-out) (Uint8* g-out) (Uint8* b-out) (Uint8* a-out))) (define-function-binding SDL_CalculateGammaRamp args: ((float gamma) (Uint16* ramp-out)))
ce217a170b90fb1244b9e7972d95d69b15165cb1ddc3087fa1267f7a9ff38f9f
fredrikt/yxa
autotest_util.erl
%%%------------------------------------------------------------------- %%% File : autotest_util.erl @author < > @doc Utility functions to use with YXA 's autotest unit %%% testing framework. %%% @since 30 Apr 2008 by < > %%% @end %%%------------------------------------------------------------------- -module(autotest_util). %%-compile(export_all). %%-------------------------------------------------------------------- %% External exports %%-------------------------------------------------------------------- -export([fail/1, is_unit_testing/2, store_unit_test_result/3, clear_unit_test_result/2, compare_records/3, compare_records/4, add_valid_credentials/3, add_valid_credentials/4, get_sippipe_result/0, get_created_response/0, test/0 ]). %%-------------------------------------------------------------------- %% Include files %%-------------------------------------------------------------------- -include("siprecords.hrl"). %%-------------------------------------------------------------------- Records %%-------------------------------------------------------------------- -record(test_rec_a, {key, value}). -record(test_rec_b, {name, age}). %%==================================================================== %% External functions %%==================================================================== %%-------------------------------------------------------------------- %% @spec (Fun) -> ok %% %% Fun = function() %% %% @throws {error, no_exception_thrown_by_test} %% %% @doc test case support function, used to check if call Fun() %% fails - as expected %% @end %%-------------------------------------------------------------------- fail(Fun) -> try Fun() of _ -> throw({error, no_exception_thrown_by_test}) catch _ -> ok %% catch user throw() end. %%-------------------------------------------------------------------- %% @spec (Module, Key) -> %% {true, Result} | %% false %% %% Module = atom() "calling module (currently unused)" %% Key = term() %% %% Result = term() %% %% @doc Check if we are currently unit testing and have a result stored for the user of this specific Key . %% @end %%-------------------------------------------------------------------- is_unit_testing(Module, Key) when is_atom(Module) -> case get({autotest, Key}) of undefined -> false; Res -> {true, Res} end. %%-------------------------------------------------------------------- %% @spec (Module, Key, Value) -> term() %% %% Module = atom() "calling module (currently unused)" %% Key = term() %% Value = term() %% %% @doc Store a value to be returned for this Key. %% @end %%-------------------------------------------------------------------- store_unit_test_result(Module, Key, Value) when is_atom(Module) -> put({autotest, Key}, Value). %%-------------------------------------------------------------------- %% @spec (Module, Key) -> term() %% %% Module = atom() "calling module (currently unused)" %% Key = term() %% %% @doc Clear any stored value for this Key. %% @end %%-------------------------------------------------------------------- clear_unit_test_result(Module, Key) when is_atom(Module) -> erase({autotest, Key}). %%-------------------------------------------------------------------- @spec ( T1 , T2 , ShouldChange ) - > ok | { error , Reason } %% T1 = tuple ( ) " Record # 1 " T2 = tuple ( ) " Record # 2 " ShouldChange = [ atom ( ) ] %% %% Reason = string() %% %% @see compare_records/4. %% %% @doc Same as compare_records/4 but will use numeric names of %% fields in error messages, if you don't care to use %% record_info in the calling module to get the real names. %% %% @end %%-------------------------------------------------------------------- compare_records(T1, T2, ShouldChange) when is_tuple(T1), is_tuple(T2), is_list(ShouldChange) -> Two records as input , see if they are standard ones ( from siprecords.hrl ) , and %% otherwise use numbers istead of field names Fields = case test_record_info(element(1, T1)) of undefined -> lists:seq(1, size(T1) - 1); T1_Fields -> T1_Fields end, compare_records(T1, T2, ShouldChange, Fields). %%-------------------------------------------------------------------- @spec ( T1 , T2 , ShouldChange , ) - > ok | { error , Reason } %% T1 = tuple ( ) " Record # 1 " T2 = tuple ( ) " Record # 2 " ShouldChange = [ atom ( ) ] %% Fields = [atom()] "Record fields, as given by record_info/2" %% %% Reason = string() %% @doc Compare two records , typically before- and after - versions %% of some kind of state in a test case. Fail if any field that is NOT listed in ShouldChange differs , or if a field that IS listed in ShouldChange has NOT changed . %% %% @end %%-------------------------------------------------------------------- compare_records(T1, T2, ShouldChange, Fields) when is_tuple(T1), is_tuple(T2), is_list(Fields), is_list(ShouldChange) -> compare_records(tuple_to_list(T1), tuple_to_list(T2), ShouldChange, Fields); compare_records(L1, L2, ShouldChange, Fields) when is_list(L1), is_list(L2), is_list(Fields), is_list(ShouldChange) -> if hd(L1) /= hd(L2) -> Msg = io_lib:format("Records are not of the same kind! : ~p /= ~p", [hd(L1), hd(L2)]), {error, lists:flatten(Msg)}; length(L1) /= length(L2) -> Msg = io_lib:format("These are not records, they have different length! ~p", [hd(L1)]), {error, lists:flatten(Msg)}; length(L1) /= length(Fields) + 1 -> Msg = io_lib:format("Length of record definition does not match first record (of type ~p)! ~p", [hd(L1), Fields]), {error, lists:flatten(Msg)}; length(L2) /= length(Fields) + 1 -> Msg = io_lib:format("Length of record definition does not match second record (of type ~p)! ~p", [hd(L2), Fields]), {error, lists:flatten(Msg)}; true -> RecName = hd(L1), case ShouldChange -- Fields of [] -> compare_records2(tl(L1), tl(L2), RecName, Fields, ShouldChange); Unknown -> Msg = io_lib:format("ShouldChange field(s) ~p not valid for record ~p (fields : ~w)", [Unknown, RecName, Fields]), {error, lists:flatten(Msg)} end end. compare_records2([Elem | L1], [Elem | L2], RecName, [ThisField | Fields], ShouldChange) -> element at first position matches io : format("Record matches ~ n " , [ RecName , ThisField ] ) , case lists:member(ThisField, ShouldChange) of true -> Msg = io_lib:format("Record ~p#~p NOT changed", [RecName, ThisField]), {error, lists:flatten(Msg), Elem}; false -> compare_records2(L1, L2, RecName, Fields, ShouldChange) end; compare_records2([Elem1 | L1], [Elem2 | L2], RecName, [ThisField | Fields], ShouldChange) -> case lists:member(ThisField, ShouldChange) of true -> io : format("Record does NOT match , but we ignore that : ~p /= ~p ~ n " , [ RecName , ThisField , Elem1 , ] ) , compare_records2(L1, L2, RecName, Fields, ShouldChange); false -> Msg = io_lib:format("Record ~p#~p does NOT match", [RecName, ThisField]), {error, lists:flatten(Msg), Elem1, Elem2} end; compare_records2([], [], _RecName, [], _ShouldChange) -> ok. %% add records found in siprecords.hrl here test_record_info(yxa_ctx) -> record_info(fields, yxa_ctx); test_record_info(yxa_app_init) -> record_info(fields, yxa_app_init); test_record_info(request) -> record_info(fields, request); test_record_info(response) -> record_info(fields, response); test_record_info(via) -> record_info(fields, via); test_record_info(contact) -> record_info(fields, contact); test_record_info(sipurl) -> record_info(fields, sipurl); test_record_info(keylist) -> record_info(fields, keylist); test_record_info(sipdns_srv) -> record_info(fields, sipdns_srv); test_record_info(sipdns_hostport) -> record_info(fields, sipdns_hostport); test_record_info(siplocationdb_e) -> record_info(fields, siplocationdb_e); test_record_info(dialog) -> record_info(fields, dialog); test_record_info(_) -> undefined. get_created_response() -> receive {'$gen_cast', {create_response, Status, Reason, EH, Body}} -> ok = assert_on_message(), {Status, Reason, EH, Body}; M -> Msg = io_lib:format("Test: Unknown signal found in process mailbox :~n~p~n~n", [M]), {error, lists:flatten(Msg)} after 0 -> {error, "no created response in my mailbox"} end. get_sippipe_result() -> receive {start_sippipe, Res} -> ok = assert_on_message(), Res; M -> Msg = io_lib:format("Test: Unknown signal found in process mailbox :~n~p~n~n", [M]), {error, lists:flatten(Msg)} after 0 -> {error, "no sippipe data in my mailbox"} end. add_valid_credentials(MethodName, Request, User) -> Password = sipuserdb:get_password_for_user(User), add_valid_credentials(MethodName, Request, User, Password). add_valid_credentials(MethodName, Request, User, Password) -> true = is_list(Password), NewHeader = sipauth:add_credentials(digest, MethodName, Request#request.method, Request#request.uri, Request#request.header, User, Password), Request#request{header = NewHeader}. assert_on_message() -> receive M -> Msg = io_lib:format("Test: Unknown signal found in process mailbox :~n~p~n~n", [M]), {error, lists:flatten(Msg)} after 0 -> ok end. %%==================================================================== %% Test functions %%==================================================================== %%-------------------------------------------------------------------- %% @spec () -> ok %% %% @doc autotest callback %% @hidden %% @end %%-------------------------------------------------------------------- -ifdef( YXA_NO_UNITTEST ). test() -> {error, "Unit test code disabled at compile time"}. -else. test() -> compare_records(T1 , T2 , ShouldChange , ) %%-------------------------------------------------------------------- autotest:mark(?LINE, "compare_records/4 - 0"), TestRec1 = #test_rec_a{key = b, value = c}, TestRec2 = #test_rec_a{key = b, value = other}, TestRec1Fields = test_test_record_info(test_rec_a), autotest:mark(?LINE, "compare_records/4 - 1"), ok = compare_records(TestRec1, TestRec1, [], TestRec1Fields), autotest:mark(?LINE, "compare_records/4 - 2"), {error,"Record test_rec_a#value does NOT match", c, other} = compare_records(TestRec1, TestRec2, [], TestRec1Fields), autotest:mark(?LINE, "compare_records/4 - 3"), different value , but value ShouldChange ok = compare_records(TestRec1, TestRec2, [value], TestRec1Fields), autotest:mark(?LINE, "compare_records/4 - 4"), same value , but value ShouldChange {error,"Record test_rec_a#value NOT changed",c} = compare_records(TestRec1, TestRec1, [value], TestRec1Fields), autotest:mark(?LINE, "compare_records/4 - 5"), same value , but value ShouldChange {error, "ShouldChange field(s) [bogus_field] not valid for record test_rec_a (fields : [key,value])"} = compare_records(TestRec1, TestRec1, [bogus_field], TestRec1Fields), autotest:mark(?LINE, "compare_records/4 - 6"), %% test detection of bad input values {error,"Records are not of the same kind! : test_rec_a /= test_rec_b"} = compare_records(TestRec1, #test_rec_b{}, [], []), autotest:mark(?LINE, "compare_records/4 - 7"), %% test detection of bad input values {error,"These are not records, they have different length! a"} = compare_records({a, b}, {a, b, c}, [], []), compare_records(T1 , T2 , ShouldChange ) %%-------------------------------------------------------------------- autotest:mark(?LINE, "compare_records/4 - 1"), ok = compare_records(sipurl:new([]), sipurl:new([]), []), autotest:mark(?LINE, "compare_records/4 - 2"), {error,"Record sipurl#host does NOT match", "test.example.org", "foo.example.org"} = compare_records(sipurl:parse("sip:test.example.org"), sipurl:parse("sip:foo.example.org"), []), autotest:mark(?LINE, "compare_records/4 - 3"), ok = compare_records(TestRec1, TestRec1, []), autotest:mark(?LINE, "compare_records/4 - 3"), {error, "Record test_rec_a#2 does NOT match", c, other} = compare_records(TestRec1, TestRec2, []), autotest:mark(?LINE, "compare_records/4 - 4"), {error, "Record test_rec_a#2 NOT changed", c} = compare_records(TestRec1, TestRec1, [2]), ok. test_test_record_info(test_rec_a) -> record_info(fields, test_rec_a). -endif.
null
https://raw.githubusercontent.com/fredrikt/yxa/85da46a999d083e6f00b5f156a634ca9be65645b/src/autotest_util.erl
erlang
------------------------------------------------------------------- File : autotest_util.erl testing framework. @end ------------------------------------------------------------------- -compile(export_all). -------------------------------------------------------------------- External exports -------------------------------------------------------------------- -------------------------------------------------------------------- Include files -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- ==================================================================== External functions ==================================================================== -------------------------------------------------------------------- @spec (Fun) -> ok Fun = function() @throws {error, no_exception_thrown_by_test} @doc test case support function, used to check if call Fun() fails - as expected @end -------------------------------------------------------------------- catch user throw() -------------------------------------------------------------------- @spec (Module, Key) -> {true, Result} | false Module = atom() "calling module (currently unused)" Key = term() Result = term() @doc Check if we are currently unit testing and have a result @end -------------------------------------------------------------------- -------------------------------------------------------------------- @spec (Module, Key, Value) -> term() Module = atom() "calling module (currently unused)" Key = term() Value = term() @doc Store a value to be returned for this Key. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @spec (Module, Key) -> term() Module = atom() "calling module (currently unused)" Key = term() @doc Clear any stored value for this Key. @end -------------------------------------------------------------------- -------------------------------------------------------------------- Reason = string() @see compare_records/4. @doc Same as compare_records/4 but will use numeric names of fields in error messages, if you don't care to use record_info in the calling module to get the real names. @end -------------------------------------------------------------------- otherwise use numbers istead of field names -------------------------------------------------------------------- Fields = [atom()] "Record fields, as given by record_info/2" Reason = string() of some kind of state in a test case. Fail if any field @end -------------------------------------------------------------------- add records found in siprecords.hrl here ==================================================================== Test functions ==================================================================== -------------------------------------------------------------------- @spec () -> ok @doc autotest callback @hidden @end -------------------------------------------------------------------- -------------------------------------------------------------------- test detection of bad input values test detection of bad input values --------------------------------------------------------------------
@author < > @doc Utility functions to use with YXA 's autotest unit @since 30 Apr 2008 by < > -module(autotest_util). -export([fail/1, is_unit_testing/2, store_unit_test_result/3, clear_unit_test_result/2, compare_records/3, compare_records/4, add_valid_credentials/3, add_valid_credentials/4, get_sippipe_result/0, get_created_response/0, test/0 ]). -include("siprecords.hrl"). Records -record(test_rec_a, {key, value}). -record(test_rec_b, {name, age}). fail(Fun) -> try Fun() of _ -> throw({error, no_exception_thrown_by_test}) catch end. stored for the user of this specific Key . is_unit_testing(Module, Key) when is_atom(Module) -> case get({autotest, Key}) of undefined -> false; Res -> {true, Res} end. store_unit_test_result(Module, Key, Value) when is_atom(Module) -> put({autotest, Key}, Value). clear_unit_test_result(Module, Key) when is_atom(Module) -> erase({autotest, Key}). @spec ( T1 , T2 , ShouldChange ) - > ok | { error , Reason } T1 = tuple ( ) " Record # 1 " T2 = tuple ( ) " Record # 2 " ShouldChange = [ atom ( ) ] compare_records(T1, T2, ShouldChange) when is_tuple(T1), is_tuple(T2), is_list(ShouldChange) -> Two records as input , see if they are standard ones ( from siprecords.hrl ) , and Fields = case test_record_info(element(1, T1)) of undefined -> lists:seq(1, size(T1) - 1); T1_Fields -> T1_Fields end, compare_records(T1, T2, ShouldChange, Fields). @spec ( T1 , T2 , ShouldChange , ) - > ok | { error , Reason } T1 = tuple ( ) " Record # 1 " T2 = tuple ( ) " Record # 2 " ShouldChange = [ atom ( ) ] @doc Compare two records , typically before- and after - versions that is NOT listed in ShouldChange differs , or if a field that IS listed in ShouldChange has NOT changed . compare_records(T1, T2, ShouldChange, Fields) when is_tuple(T1), is_tuple(T2), is_list(Fields), is_list(ShouldChange) -> compare_records(tuple_to_list(T1), tuple_to_list(T2), ShouldChange, Fields); compare_records(L1, L2, ShouldChange, Fields) when is_list(L1), is_list(L2), is_list(Fields), is_list(ShouldChange) -> if hd(L1) /= hd(L2) -> Msg = io_lib:format("Records are not of the same kind! : ~p /= ~p", [hd(L1), hd(L2)]), {error, lists:flatten(Msg)}; length(L1) /= length(L2) -> Msg = io_lib:format("These are not records, they have different length! ~p", [hd(L1)]), {error, lists:flatten(Msg)}; length(L1) /= length(Fields) + 1 -> Msg = io_lib:format("Length of record definition does not match first record (of type ~p)! ~p", [hd(L1), Fields]), {error, lists:flatten(Msg)}; length(L2) /= length(Fields) + 1 -> Msg = io_lib:format("Length of record definition does not match second record (of type ~p)! ~p", [hd(L2), Fields]), {error, lists:flatten(Msg)}; true -> RecName = hd(L1), case ShouldChange -- Fields of [] -> compare_records2(tl(L1), tl(L2), RecName, Fields, ShouldChange); Unknown -> Msg = io_lib:format("ShouldChange field(s) ~p not valid for record ~p (fields : ~w)", [Unknown, RecName, Fields]), {error, lists:flatten(Msg)} end end. compare_records2([Elem | L1], [Elem | L2], RecName, [ThisField | Fields], ShouldChange) -> element at first position matches io : format("Record matches ~ n " , [ RecName , ThisField ] ) , case lists:member(ThisField, ShouldChange) of true -> Msg = io_lib:format("Record ~p#~p NOT changed", [RecName, ThisField]), {error, lists:flatten(Msg), Elem}; false -> compare_records2(L1, L2, RecName, Fields, ShouldChange) end; compare_records2([Elem1 | L1], [Elem2 | L2], RecName, [ThisField | Fields], ShouldChange) -> case lists:member(ThisField, ShouldChange) of true -> io : format("Record does NOT match , but we ignore that : ~p /= ~p ~ n " , [ RecName , ThisField , Elem1 , ] ) , compare_records2(L1, L2, RecName, Fields, ShouldChange); false -> Msg = io_lib:format("Record ~p#~p does NOT match", [RecName, ThisField]), {error, lists:flatten(Msg), Elem1, Elem2} end; compare_records2([], [], _RecName, [], _ShouldChange) -> ok. test_record_info(yxa_ctx) -> record_info(fields, yxa_ctx); test_record_info(yxa_app_init) -> record_info(fields, yxa_app_init); test_record_info(request) -> record_info(fields, request); test_record_info(response) -> record_info(fields, response); test_record_info(via) -> record_info(fields, via); test_record_info(contact) -> record_info(fields, contact); test_record_info(sipurl) -> record_info(fields, sipurl); test_record_info(keylist) -> record_info(fields, keylist); test_record_info(sipdns_srv) -> record_info(fields, sipdns_srv); test_record_info(sipdns_hostport) -> record_info(fields, sipdns_hostport); test_record_info(siplocationdb_e) -> record_info(fields, siplocationdb_e); test_record_info(dialog) -> record_info(fields, dialog); test_record_info(_) -> undefined. get_created_response() -> receive {'$gen_cast', {create_response, Status, Reason, EH, Body}} -> ok = assert_on_message(), {Status, Reason, EH, Body}; M -> Msg = io_lib:format("Test: Unknown signal found in process mailbox :~n~p~n~n", [M]), {error, lists:flatten(Msg)} after 0 -> {error, "no created response in my mailbox"} end. get_sippipe_result() -> receive {start_sippipe, Res} -> ok = assert_on_message(), Res; M -> Msg = io_lib:format("Test: Unknown signal found in process mailbox :~n~p~n~n", [M]), {error, lists:flatten(Msg)} after 0 -> {error, "no sippipe data in my mailbox"} end. add_valid_credentials(MethodName, Request, User) -> Password = sipuserdb:get_password_for_user(User), add_valid_credentials(MethodName, Request, User, Password). add_valid_credentials(MethodName, Request, User, Password) -> true = is_list(Password), NewHeader = sipauth:add_credentials(digest, MethodName, Request#request.method, Request#request.uri, Request#request.header, User, Password), Request#request{header = NewHeader}. assert_on_message() -> receive M -> Msg = io_lib:format("Test: Unknown signal found in process mailbox :~n~p~n~n", [M]), {error, lists:flatten(Msg)} after 0 -> ok end. -ifdef( YXA_NO_UNITTEST ). test() -> {error, "Unit test code disabled at compile time"}. -else. test() -> compare_records(T1 , T2 , ShouldChange , ) autotest:mark(?LINE, "compare_records/4 - 0"), TestRec1 = #test_rec_a{key = b, value = c}, TestRec2 = #test_rec_a{key = b, value = other}, TestRec1Fields = test_test_record_info(test_rec_a), autotest:mark(?LINE, "compare_records/4 - 1"), ok = compare_records(TestRec1, TestRec1, [], TestRec1Fields), autotest:mark(?LINE, "compare_records/4 - 2"), {error,"Record test_rec_a#value does NOT match", c, other} = compare_records(TestRec1, TestRec2, [], TestRec1Fields), autotest:mark(?LINE, "compare_records/4 - 3"), different value , but value ShouldChange ok = compare_records(TestRec1, TestRec2, [value], TestRec1Fields), autotest:mark(?LINE, "compare_records/4 - 4"), same value , but value ShouldChange {error,"Record test_rec_a#value NOT changed",c} = compare_records(TestRec1, TestRec1, [value], TestRec1Fields), autotest:mark(?LINE, "compare_records/4 - 5"), same value , but value ShouldChange {error, "ShouldChange field(s) [bogus_field] not valid for record test_rec_a (fields : [key,value])"} = compare_records(TestRec1, TestRec1, [bogus_field], TestRec1Fields), autotest:mark(?LINE, "compare_records/4 - 6"), {error,"Records are not of the same kind! : test_rec_a /= test_rec_b"} = compare_records(TestRec1, #test_rec_b{}, [], []), autotest:mark(?LINE, "compare_records/4 - 7"), {error,"These are not records, they have different length! a"} = compare_records({a, b}, {a, b, c}, [], []), compare_records(T1 , T2 , ShouldChange ) autotest:mark(?LINE, "compare_records/4 - 1"), ok = compare_records(sipurl:new([]), sipurl:new([]), []), autotest:mark(?LINE, "compare_records/4 - 2"), {error,"Record sipurl#host does NOT match", "test.example.org", "foo.example.org"} = compare_records(sipurl:parse("sip:test.example.org"), sipurl:parse("sip:foo.example.org"), []), autotest:mark(?LINE, "compare_records/4 - 3"), ok = compare_records(TestRec1, TestRec1, []), autotest:mark(?LINE, "compare_records/4 - 3"), {error, "Record test_rec_a#2 does NOT match", c, other} = compare_records(TestRec1, TestRec2, []), autotest:mark(?LINE, "compare_records/4 - 4"), {error, "Record test_rec_a#2 NOT changed", c} = compare_records(TestRec1, TestRec1, [2]), ok. test_test_record_info(test_rec_a) -> record_info(fields, test_rec_a). -endif.
c9bdacc651addc876b476553c1a439b401994f6e2225b85c1a99e5278f6fe2f0
johnlawrenceaspden/hobby-code
k-armed-bandit.clj
Reinforcement Learning : Exploration vs Exploitation : Multi - Armed Bandits ( Part Two ) ;; I'm reading the excellent: ;; Reinforcement Learning: An Introduction by and ;; The book's website, on which is available a complete pdf, is here: ;; -book.html In Chapter 2 , they introduce multi - armed bandits as a simplified model problem ;; On the basis that you don't understand anything you can't explain to a computer, I thought I'd code it up: ;; From the previous post, we'll keep: A 2 armed bandit (defn bandit [action] (case action :arms? [:right :left] :right (if (< (rand) 0.5) 4 0) :left (if (< (rand) 0.2) 5 0) :oops!!)) ;; We can ask it how many arms it's got, and what they're called (bandit :arms?) ; [:right :left] ;; And we can pull those arms. Rewards are variable. 4 ; 4 ; 4 ; 0 ; 0 ; 0 ; 0 5 ; 0 ; 0 ; 0 ; 5 ; 0 ; 5 ; 0 ;; Once we pull an arm, we'll have an action/reward pair 4 ;; the pair would be: [:right 4] ;; Here's a function that yanks an arm at random, and gives us such a pair (defn random-yank [bandit] (let [a (rand-nth (bandit :arms?))] [a (bandit a)])) (random-yank bandit) ; [:left 0] [: right 4 ] ;; And a utility function to take the average of a sequence. We need to be able to provide a default value if the sequence is empty. (defn average ([seq default] (if (empty? seq) default (/ (reduce + seq) (count seq)))) ([seq] (average seq 0))) ;; with some examples 3 10 1 100 If we just pull arms at random we get an average reward of about 1.5 1.49 ;; Since we can see the code for this particular bandit, we know that the expected value of pulling the right arm is 2 ( a half - chance of a reward of 4 ) and the expected reward for the left arm is 0.2 * 5 = 1 ;; So if we were seeking to maximize reward, we'd probably be best to pull the right arm all the time. 1.9912 0.985 ;; The interesting question is, if we don't know how the bandit works, how should we design an algorithm that gets the most reward? ;; (Or at least do better than yanking arms at random!) One thing our algorithm is going to have to do is keep some state to record what happens . ;; Let's start by recording the results of all pulls to date: At first , we know nothing , so we can set up a table to represent that we know nothing (defn initial-state [bandit] (into {} (for [k (bandit :arms?)] [k (list)]))) ;; We haven't pulled either arm yet (initial-state bandit) ; {:right (), :left ()} ;; When we get a new action reward/pair, we'll add the result to our state (defn update-state [state [action reward]] (update-in state [action] #(conj % reward))) ;; here are some examples of using update-state { : right ( 2 ) , : left ( ) } { : right ( 5 4 2 ) , : left ( 3 ) } here 's how we can use it to record the result of ten random yanks (reduce update-state (initial-state bandit) { : right ( 4 4 0 0 0 ) , : left ( 0 0 0 0 5 ) } ;; Once we actually have some data, we can make estimates of the expected rewards ;; mapvals applies a function to every value in a map, returning a new map with the same keys (defn mapvals [m f] (into {} (for [[k v] m] [k (f v)]))) ;; examples (mapvals {} inc) ; {} { : a 2 } { : a 2 , : b 3 } { : a 1 , : b 4 , : c 9 } In the book , Q_t(a ) is the current estimate ( at time t ) We 'll use as our estimate of the value of an action the average value seen so far , or zero if we have no information (defn Q [state] (mapvals state #(average % 0))) ;; examples { : right 11/3 , : left 3 } { : right 11/3 , : left 0 } (Q (initial-state bandit)) ; {:right 0, :left 0} { : right 0 , : left 2 } ;; let's check that we get roughly what we expect in the long run (Q (reduce update-state (initial-state bandit) { : right 9832/5015 , : left 1027/997 } ;; If we have estimates of the value of each arm, then a good way to ;; use them is to pull the arm with the highest estimate. ;; This is called 'exploitation', as opposed to 'exploration', which ;; is when you try things you think may be suboptimal in order to get ;; information ;; The 'greedy' action is the one with the highest expected value. Of course there may be more than one greedy action especially at first . ;; To help with this, another utility function: ;; max-keys finds the keys with the highest value in a map, and returns a list with just these keys and values (defn max-keys [m] (let [slist (reverse (sort-by second m)) [_ max] (first slist)] (take-while #(= (second %) max) slist))) ;; examples (max-keys {}) ; () (max-keys {1 0}) ; ([1 0]) ( [ 2 0 ] [ 1 0 ] ) ( [ 2 1 ] ) ( [ 6 2 ] [ 5 2 ] ) ;; if there is a tie for the greedy action, we can choose at random between the candidates ;; And so we can go from estimates to greedy action like this: (defn greedy-action [estimates] (first (rand-nth (max-keys estimates)))) ;; examples (greedy-action '{:right 10, :left 3}) ; :right (greedy-action '{:right 10, :left 3 :centre 20}) ; :centre (greedy-action '{:right 10, :left 3 :centre 3}) ; :right (greedy-action '{:right 3, :left 3 :centre 3}) ; :right (greedy-action (Q '{:right (5 4 2), :left (3)})) ; :right (greedy-action (Q '{:right (), :left (3)})) ; :left (greedy-action (Q (initial-state bandit))) ; :left ;; after a lot of random pulls, the greedy action should reliably be the one with the highest expected payoff (greedy-action (Q (reduce update-state (initial-state bandit) (repeatedly 10000 #(random-yank bandit))))) ; :right ;; OK, so we have our stage set, a way of recording what's happened, and some helpful functions defined. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Our first try at a learning algorithm will be ' by hand ' , as it were . ;; We'll always make the 'greedy' choice. At first , we have no records to go on (initial-state bandit) ; {:right (), :left ()} expected values for both levers are therefore zero (Q (initial-state bandit)) ; {:right 0, :left 0} ;; so the greedy action will get chosen at random (greedy-action (Q (initial-state bandit))) ; :left ;; in this case, we've chosen :left, and the bandit's response is 0 ;; we record it (update-state (initial-state bandit) [:left 0]) ; {:right (), :left (0)} ;; and we have a new state '{:right (), :left (0)} ;; new estimates (Q '{:right (), :left (0)}) ; {:right 0, :left 0} ;; and again, we choose at random (greedy-action (Q '{:right (), :left (0)})) ; :left ;; the bandit is not feeling very generous 0 (update-state '{:right (), :left (0)} [:left 0]) ; {:right (), :left (0 0)} ;; new state: '{:right (), :left (0 0)} ;; new estimates (Q '{:right (), :left (0 0)}) ; {:right 0, :left 0} ;; this time we choose :right (greedy-action (Q '{:right (), :left (0 0)})) ; :right ;; and the bandit pays out! 4 { : right ( 4 ) , : left ( 0 0 ) } ;; the greedy action will be :right now, because we have evidence that right is better. (greedy-action (Q '{:right (4), :left (0 0)})) ; :right ;; You get the idea...... ;; Let's automate that.... ;; Given a state and a bandit, we decide an action and the bandit ;; responds, producing an action/reward pair, and a new state (defn greedy-algorithm [bandit state] (let [action (greedy-action (Q state)) reward (bandit action)] [[action reward] (update-state state [action reward])])) (greedy-algorithm bandit (initial-state bandit)) ; [[:left 0] {:right (), :left (0)}] ;; To get something we can iterate: (defn step [[[a r] state]] (greedy-algorithm bandit state)) (iterate step [ [:dummy :dummy] (initial-state bandit)]) ;; ([[:dummy :dummy] {:right (), :left ()}] [ [: left 5 ] { : right ( ) , : left ( 5 ) } ] ;; [[:left 0] {:right (), :left (0 5)}] ;; [[:left 0] {:right (), :left (0 0 5)}] ;; [[:left 0] {:right (), :left (0 0 0 5)}] ;; [[:left 0] {:right (), :left (0 0 0 0 5)}] ;; [[:left 0] {:right (), :left (0 0 0 0 0 5)}] ;; [[:left 0] {:right (), :left (0 0 0 0 0 0 5)}] ;; [[:left 0] {:right (), :left (0 0 0 0 0 0 0 5)}] ;; [[:left 0] {:right (), :left (0 0 0 0 0 0 0 0 5)}] ;; [[:left 0] {:right (), :left (0 0 0 0 0 0 0 0 0 5)}] ;; [[:left 0] {:right (), :left (0 0 0 0 0 0 0 0 0 0 5)}] [ [: left 5 ] { : right ( ) , : left ( 5 0 0 0 0 0 0 0 0 0 0 5 ) } ] ;; [[:left 0] {:right (), :left (0 5 0 0 0 0 0 0 0 0 0 0 5)}] ;; [[:left 0] {:right (), :left (0 0 5 0 0 0 0 0 0 0 0 0 0 5)}] ;; [[:left 0] {:right (), :left (0 0 0 5 0 0 0 0 0 0 0 0 0 0 5)}] [ [: left 0 ] { : right ( ) , : left ( 0 0 0 0 5 0 0 0 0 0 0 0 0 0 0 5 ) } ] ;; In this case, the greedy algorithm happens to get a payout on its first try , and decides that it will pull that arm for ever . It ;; never even tries the other arm. ;; Try again: (iterate step [ [:dummy :dummy] (initial-state bandit)]) ;;([[:dummy :dummy] {:right (), :left ()}] ;; [[:right 0] {:right (0), :left ()}] ;; [[:right 0] {:right (0 0), :left ()}] ;; [[:left 0] {:right (0 0), :left (0)}] [ [: right 4 ] { : right ( 4 0 0 ) , : left ( 0 ) } ] [ [: right 4 ] { : right ( 4 4 0 0 ) , : left ( 0 ) } ] [ [: right 4 ] { : right ( 4 4 4 0 0 ) , : left ( 0 ) } ] [ [: right 4 ] { : right ( 4 4 4 4 0 0 ) , : left ( 0 ) } ] [ [: right 4 ] { : right ( 4 4 4 4 4 0 0 ) , : left ( 0 ) } ] [ [: right 4 ] { : right ( 4 4 4 4 4 4 0 0 ) , : left ( 0 ) } ] ;; [[:right 0] {:right (0 4 4 4 4 4 4 0 0), :left (0)}] ;; [[:right 0] {:right (0 0 4 4 4 4 4 4 0 0), :left (0)}] [ [: right 4 ] { : right ( 4 0 0 4 4 4 4 4 4 0 0 ) , : left ( 0 ) } ] ;; [[:right 0] {:right (0 4 0 0 4 4 4 4 4 4 0 0), :left (0)}] [ [: right 4 ] { : right ( 4 0 4 0 0 4 4 4 4 4 4 0 0 ) , : left ( 0 ) } ] ;; [[:right 0] {:right (0 4 0 4 0 0 4 4 4 4 4 4 0 0), :left (0)}] ;; In this case, it tried the right arm a couple of times, then had a ;; go with the left arm, then went back to the right arm, won a ;; payout, and then got hung up on pulling the right arm repeatedly. ;; We've got a couple of problems here! First is that the algorithm has clearly got into a state where it always pulls the left arm ( in the first case ) , and the right arm ( in the second case ) . ;; It can't be doing the right thing in both cases. Secondly the state is growing linearly , as the algorithm remembers ;; all previous results. That's giving us algorithmic complexity ;; problems and the calculation will get slower and slower, and ;; eventually run out of memory.
null
https://raw.githubusercontent.com/johnlawrenceaspden/hobby-code/48e2a89d28557994c72299962cd8e3ace6a75b2d/reinforcement-learning/k-armed-bandit.clj
clojure
I'm reading the excellent: Reinforcement Learning: An Introduction The book's website, on which is available a complete pdf, is here: -book.html On the basis that you don't understand anything you can't explain to a computer, I thought I'd code it up: From the previous post, we'll keep: We can ask it how many arms it's got, and what they're called [:right :left] And we can pull those arms. Rewards are variable. 4 ; 4 ; 0 ; 0 ; 0 ; 0 0 ; 0 ; 0 ; 5 ; 0 ; 5 ; 0 Once we pull an arm, we'll have an action/reward pair the pair would be: Here's a function that yanks an arm at random, and gives us such a pair [:left 0] And a utility function to take the average of a sequence. We need to be able to provide a default value if the sequence is empty. with some examples Since we can see the code for this particular bandit, we know that So if we were seeking to maximize reward, we'd probably be best to pull the right arm all the time. The interesting question is, if we don't know how the bandit works, how should we design an algorithm that gets the most reward? (Or at least do better than yanking arms at random!) Let's start by recording the results of all pulls to date: We haven't pulled either arm yet {:right (), :left ()} When we get a new action reward/pair, we'll add the result to our state here are some examples of using update-state Once we actually have some data, we can make estimates of the expected rewards mapvals applies a function to every value in a map, returning a new map with the same keys examples {} examples {:right 0, :left 0} let's check that we get roughly what we expect in the long run If we have estimates of the value of each arm, then a good way to use them is to pull the arm with the highest estimate. This is called 'exploitation', as opposed to 'exploration', which is when you try things you think may be suboptimal in order to get information The 'greedy' action is the one with the highest expected value. Of To help with this, another utility function: max-keys finds the keys with the highest value in a map, and returns a list with just these keys and values examples () ([1 0]) if there is a tie for the greedy action, we can choose at random between the candidates And so we can go from estimates to greedy action like this: examples :right :centre :right :right :right :left :left after a lot of random pulls, the greedy action should reliably be the one with the highest expected payoff :right OK, so we have our stage set, a way of recording what's happened, and some helpful functions defined. We'll always make the 'greedy' choice. {:right (), :left ()} {:right 0, :left 0} so the greedy action will get chosen at random :left in this case, we've chosen :left, and the bandit's response is we record it {:right (), :left (0)} and we have a new state new estimates {:right 0, :left 0} and again, we choose at random :left the bandit is not feeling very generous {:right (), :left (0 0)} new state: new estimates {:right 0, :left 0} this time we choose :right :right and the bandit pays out! the greedy action will be :right now, because we have evidence that right is better. :right You get the idea...... Let's automate that.... Given a state and a bandit, we decide an action and the bandit responds, producing an action/reward pair, and a new state [[:left 0] {:right (), :left (0)}] To get something we can iterate: ([[:dummy :dummy] {:right (), :left ()}] [[:left 0] {:right (), :left (0 5)}] [[:left 0] {:right (), :left (0 0 5)}] [[:left 0] {:right (), :left (0 0 0 5)}] [[:left 0] {:right (), :left (0 0 0 0 5)}] [[:left 0] {:right (), :left (0 0 0 0 0 5)}] [[:left 0] {:right (), :left (0 0 0 0 0 0 5)}] [[:left 0] {:right (), :left (0 0 0 0 0 0 0 5)}] [[:left 0] {:right (), :left (0 0 0 0 0 0 0 0 5)}] [[:left 0] {:right (), :left (0 0 0 0 0 0 0 0 0 5)}] [[:left 0] {:right (), :left (0 0 0 0 0 0 0 0 0 0 5)}] [[:left 0] {:right (), :left (0 5 0 0 0 0 0 0 0 0 0 0 5)}] [[:left 0] {:right (), :left (0 0 5 0 0 0 0 0 0 0 0 0 0 5)}] [[:left 0] {:right (), :left (0 0 0 5 0 0 0 0 0 0 0 0 0 0 5)}] In this case, the greedy algorithm happens to get a payout on its never even tries the other arm. Try again: ([[:dummy :dummy] {:right (), :left ()}] [[:right 0] {:right (0), :left ()}] [[:right 0] {:right (0 0), :left ()}] [[:left 0] {:right (0 0), :left (0)}] [[:right 0] {:right (0 4 4 4 4 4 4 0 0), :left (0)}] [[:right 0] {:right (0 0 4 4 4 4 4 4 0 0), :left (0)}] [[:right 0] {:right (0 4 0 0 4 4 4 4 4 4 0 0), :left (0)}] [[:right 0] {:right (0 4 0 4 0 0 4 4 4 4 4 4 0 0), :left (0)}] In this case, it tried the right arm a couple of times, then had a go with the left arm, then went back to the right arm, won a payout, and then got hung up on pulling the right arm repeatedly. We've got a couple of problems here! It can't be doing the right thing in both cases. all previous results. That's giving us algorithmic complexity problems and the calculation will get slower and slower, and eventually run out of memory.
Reinforcement Learning : Exploration vs Exploitation : Multi - Armed Bandits ( Part Two ) by and In Chapter 2 , they introduce multi - armed bandits as a simplified model problem A 2 armed bandit (defn bandit [action] (case action :arms? [:right :left] :right (if (< (rand) 0.5) 4 0) :left (if (< (rand) 0.2) 5 0) :oops!!)) 4 [:right 4] (defn random-yank [bandit] (let [a (rand-nth (bandit :arms?))] [a (bandit a)])) [: right 4 ] (defn average ([seq default] (if (empty? seq) default (/ (reduce + seq) (count seq)))) ([seq] (average seq 0))) 3 10 1 100 If we just pull arms at random we get an average reward of about 1.5 1.49 the expected value of pulling the right arm is 2 ( a half - chance of a reward of 4 ) and the expected reward for the left arm is 0.2 * 5 = 1 1.9912 0.985 One thing our algorithm is going to have to do is keep some state to record what happens . At first , we know nothing , so we can set up a table to represent that we know nothing (defn initial-state [bandit] (into {} (for [k (bandit :arms?)] [k (list)]))) (defn update-state [state [action reward]] (update-in state [action] #(conj % reward))) { : right ( 2 ) , : left ( ) } { : right ( 5 4 2 ) , : left ( 3 ) } here 's how we can use it to record the result of ten random yanks (reduce update-state (initial-state bandit) { : right ( 4 4 0 0 0 ) , : left ( 0 0 0 0 5 ) } (defn mapvals [m f] (into {} (for [[k v] m] [k (f v)]))) { : a 2 } { : a 2 , : b 3 } { : a 1 , : b 4 , : c 9 } In the book , Q_t(a ) is the current estimate ( at time t ) We 'll use as our estimate of the value of an action the average value seen so far , or zero if we have no information (defn Q [state] (mapvals state #(average % 0))) { : right 11/3 , : left 3 } { : right 11/3 , : left 0 } { : right 0 , : left 2 } (Q (reduce update-state (initial-state bandit) { : right 9832/5015 , : left 1027/997 } course there may be more than one greedy action especially at first . (defn max-keys [m] (let [slist (reverse (sort-by second m)) [_ max] (first slist)] (take-while #(= (second %) max) slist))) ( [ 2 0 ] [ 1 0 ] ) ( [ 2 1 ] ) ( [ 6 2 ] [ 5 2 ] ) (defn greedy-action [estimates] (first (rand-nth (max-keys estimates)))) (greedy-action (Q (reduce update-state (initial-state bandit) Our first try at a learning algorithm will be ' by hand ' , as it were . At first , we have no records to go on expected values for both levers are therefore zero 0 '{:right (), :left (0)} 0 '{:right (), :left (0 0)} 4 { : right ( 4 ) , : left ( 0 0 ) } (defn greedy-algorithm [bandit state] (let [action (greedy-action (Q state)) reward (bandit action)] [[action reward] (update-state state [action reward])])) (defn step [[[a r] state]] (greedy-algorithm bandit state)) (iterate step [ [:dummy :dummy] (initial-state bandit)]) [ [: left 5 ] { : right ( ) , : left ( 5 ) } ] [ [: left 5 ] { : right ( ) , : left ( 5 0 0 0 0 0 0 0 0 0 0 5 ) } ] [ [: left 0 ] { : right ( ) , : left ( 0 0 0 0 5 0 0 0 0 0 0 0 0 0 0 5 ) } ] first try , and decides that it will pull that arm for ever . It (iterate step [ [:dummy :dummy] (initial-state bandit)]) [ [: right 4 ] { : right ( 4 0 0 ) , : left ( 0 ) } ] [ [: right 4 ] { : right ( 4 4 0 0 ) , : left ( 0 ) } ] [ [: right 4 ] { : right ( 4 4 4 0 0 ) , : left ( 0 ) } ] [ [: right 4 ] { : right ( 4 4 4 4 0 0 ) , : left ( 0 ) } ] [ [: right 4 ] { : right ( 4 4 4 4 4 0 0 ) , : left ( 0 ) } ] [ [: right 4 ] { : right ( 4 4 4 4 4 4 0 0 ) , : left ( 0 ) } ] [ [: right 4 ] { : right ( 4 0 0 4 4 4 4 4 4 0 0 ) , : left ( 0 ) } ] [ [: right 4 ] { : right ( 4 0 4 0 0 4 4 4 4 4 4 0 0 ) , : left ( 0 ) } ] First is that the algorithm has clearly got into a state where it always pulls the left arm ( in the first case ) , and the right arm ( in the second case ) . Secondly the state is growing linearly , as the algorithm remembers
c28eb2a0417e7297fbeedc9643c031d9e14549b47a496390c9dcd70292aeae9a
nervous-systems/sputter
rlp.clj
(ns sputter.util.rlp (:require [sputter.util :refer [byte-count long->bytes bytes->long]]) (:import [java.io ByteArrayOutputStream] [java.util Arrays]) (:refer-clojure :exclude [vector?])) (def ^:private cutoff 55) (def ^:private str-short 0x80) (def ^:private str-long (+ str-short cutoff)) (def ^:private seq-short 0xc0) (def ^:private seq-long (+ seq-short cutoff)) (def ^:private max-len 0xffffffffffffffff) (defprotocol RLP (stream-encode [this stream opts])) (defn- compact? [bs] (and (= (count bs) 1) (< (bit-and (first bs) 0xff) str-short))) (defn- write-long [stream l] (let [bs (long->bytes l)] (.write stream bs 0 (count bs)))) (defn- conform-count [n] (when (<= max-len n) (throw (ex-info "Length exceeded." {:length n}))) (unchecked-long n)) (defn- write-prefix [stream cnt magic] (if (<= cnt cutoff) (.write stream (+ cnt magic)) (do (write-long stream (+ (byte-count cnt) magic cutoff)) (write-long stream cnt)))) (extend-type nil RLP (stream-encode [_ stream opts] (write-prefix stream 0 str-short))) (extend-type (type (byte-array 0)) RLP (stream-encode [bs stream opts] (cond (:raw? opts) (.write stream bs 0 (conform-count (count bs))) (compact? bs) (.write stream bs 0 1) :else (let [cnt (conform-count (count bs))] (write-prefix stream cnt str-short) (.write stream bs 0 cnt))))) (extend-protocol RLP String (stream-encode [x stream opts] (stream-encode (.getBytes x) stream opts)) clojure.lang.IPersistentVector (stream-encode [xs stream opts] (let [stream' (ByteArrayOutputStream.)] (doseq [x xs] (stream-encode x stream' opts)) (write-prefix stream (.size stream') seq-short) (.writeTo stream' stream)))) (defn encode [x & [opts]] (let [stream (ByteArrayOutputStream.)] (stream-encode x stream opts) (.toByteArray stream))) (defn- read-wide-bounds [bs i width-width] (let [width (bytes->long bs (inc i) width-width)] [(+ i width-width 1) width])) (defn- read-bounds [bs i] (let [c (bit-and 0xff (aget bs i))] (cond (< c str-short) [i 1] (<= c str-long) [(inc i) (- c str-short)] (< c seq-short) (read-wide-bounds bs i (- c str-long)) (<= c seq-long) [(inc i) (- c seq-short)] :else (read-wide-bounds bs i (- c seq-long))))) (defn- split-vector [bs] (let [n (count bs)] (loop [i 0, acc []] (if (<= n i) acc (let [[start width] (read-bounds bs i) end (+ i width (- start i))] (recur end (conj acc (Arrays/copyOfRange bs i end)))))))) (defn vector? [bs] (<= seq-short (bit-and 0xff (aget bs 0)))) (defn decode [bs] (let [[start width] (read-bounds bs 0)] (when-not (= width 0) (let [out (Arrays/copyOfRange bs start (+ start width))] (cond-> out (vector? bs) split-vector)))))
null
https://raw.githubusercontent.com/nervous-systems/sputter/e96357cff7ea13384ed94c7b0d6028d125b92e00/src/sputter/util/rlp.clj
clojure
(ns sputter.util.rlp (:require [sputter.util :refer [byte-count long->bytes bytes->long]]) (:import [java.io ByteArrayOutputStream] [java.util Arrays]) (:refer-clojure :exclude [vector?])) (def ^:private cutoff 55) (def ^:private str-short 0x80) (def ^:private str-long (+ str-short cutoff)) (def ^:private seq-short 0xc0) (def ^:private seq-long (+ seq-short cutoff)) (def ^:private max-len 0xffffffffffffffff) (defprotocol RLP (stream-encode [this stream opts])) (defn- compact? [bs] (and (= (count bs) 1) (< (bit-and (first bs) 0xff) str-short))) (defn- write-long [stream l] (let [bs (long->bytes l)] (.write stream bs 0 (count bs)))) (defn- conform-count [n] (when (<= max-len n) (throw (ex-info "Length exceeded." {:length n}))) (unchecked-long n)) (defn- write-prefix [stream cnt magic] (if (<= cnt cutoff) (.write stream (+ cnt magic)) (do (write-long stream (+ (byte-count cnt) magic cutoff)) (write-long stream cnt)))) (extend-type nil RLP (stream-encode [_ stream opts] (write-prefix stream 0 str-short))) (extend-type (type (byte-array 0)) RLP (stream-encode [bs stream opts] (cond (:raw? opts) (.write stream bs 0 (conform-count (count bs))) (compact? bs) (.write stream bs 0 1) :else (let [cnt (conform-count (count bs))] (write-prefix stream cnt str-short) (.write stream bs 0 cnt))))) (extend-protocol RLP String (stream-encode [x stream opts] (stream-encode (.getBytes x) stream opts)) clojure.lang.IPersistentVector (stream-encode [xs stream opts] (let [stream' (ByteArrayOutputStream.)] (doseq [x xs] (stream-encode x stream' opts)) (write-prefix stream (.size stream') seq-short) (.writeTo stream' stream)))) (defn encode [x & [opts]] (let [stream (ByteArrayOutputStream.)] (stream-encode x stream opts) (.toByteArray stream))) (defn- read-wide-bounds [bs i width-width] (let [width (bytes->long bs (inc i) width-width)] [(+ i width-width 1) width])) (defn- read-bounds [bs i] (let [c (bit-and 0xff (aget bs i))] (cond (< c str-short) [i 1] (<= c str-long) [(inc i) (- c str-short)] (< c seq-short) (read-wide-bounds bs i (- c str-long)) (<= c seq-long) [(inc i) (- c seq-short)] :else (read-wide-bounds bs i (- c seq-long))))) (defn- split-vector [bs] (let [n (count bs)] (loop [i 0, acc []] (if (<= n i) acc (let [[start width] (read-bounds bs i) end (+ i width (- start i))] (recur end (conj acc (Arrays/copyOfRange bs i end)))))))) (defn vector? [bs] (<= seq-short (bit-and 0xff (aget bs 0)))) (defn decode [bs] (let [[start width] (read-bounds bs 0)] (when-not (= width 0) (let [out (Arrays/copyOfRange bs start (+ start width))] (cond-> out (vector? bs) split-vector)))))
598374bfa9feba47a7f81d812d371747b9b590f6dbc0cc631da58384e9b0908f
timbertson/opam2nix
hex.mli
val of_char : char -> char * char val to_char : char -> char -> char
null
https://raw.githubusercontent.com/timbertson/opam2nix/6f2fbdf3730d49bf8fadc22374a2e270bee9400d/src/hex.mli
ocaml
val of_char : char -> char * char val to_char : char -> char -> char
48a9aa9d2872849b4c56a0673a083c47203d2c3ffa869b7bc7152fe178469616
tsloughter/kuberl
kuberl_policy_v1beta1_allowed_host_path.erl
-module(kuberl_policy_v1beta1_allowed_host_path). -export([encode/1]). -export_type([kuberl_policy_v1beta1_allowed_host_path/0]). -type kuberl_policy_v1beta1_allowed_host_path() :: #{ 'pathPrefix' => binary(), 'readOnly' => boolean() }. encode(#{ 'pathPrefix' := PathPrefix, 'readOnly' := ReadOnly }) -> #{ 'pathPrefix' => PathPrefix, 'readOnly' => ReadOnly }.
null
https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_policy_v1beta1_allowed_host_path.erl
erlang
-module(kuberl_policy_v1beta1_allowed_host_path). -export([encode/1]). -export_type([kuberl_policy_v1beta1_allowed_host_path/0]). -type kuberl_policy_v1beta1_allowed_host_path() :: #{ 'pathPrefix' => binary(), 'readOnly' => boolean() }. encode(#{ 'pathPrefix' := PathPrefix, 'readOnly' := ReadOnly }) -> #{ 'pathPrefix' => PathPrefix, 'readOnly' => ReadOnly }.
6727ac8b389a89c441317a4bdee60ebc603e2e8c1be43d8dc5a0b6444617a0b6
ftovagliari/ocamleditor
comments.ml
OCamlEditor Copyright ( C ) 2010 - 2014 This file is part of OCamlEditor . OCamlEditor 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 . OCamlEditor 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 < / > . OCamlEditor Copyright (C) 2010-2014 Francesco Tovagliari This file is part of OCamlEditor. OCamlEditor 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. OCamlEditor 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 </>. *) open Str let pat = regexp "\\((\\*\\)\\|\\(\\*)\\)" let lineend = regexp "$" let search_f_pat = search_forward pat type t = Utf8 of (int * int * int * bool) list (* begin * end * extra bytes * ocamldoc *) | Locale of (int * int * bool) list (* begin * end * ocamldoc *) let scan_locale txt = (* Non vengono considerate le stringhe *) let rec f acc pos start = begin try let p = search_f_pat txt pos in begin try ignore (matched_group 1 txt); f acc (p + 2) (p :: start); with Not_found -> begin ignore (matched_group 2 txt); (match start with | [] -> f acc (p + 2) [] | [start] -> f ((start, (p + 2), (txt.[start + 2] = '*')) :: acc) (p + 2) [] | _::prev -> f acc (p + 2) prev) end end with Not_found -> acc end in List.rev (f [] 0 []) let scan txt = Locale (scan_locale txt) let scan_utf8 txt = match scan txt with | Locale comments -> Utf8 (List.map begin fun (x, y, ocamldoc) -> let c = String.sub txt x (y - x) in x, y, String.length c - String.length (Glib.Convert.convert_with_fallback ~fallback:"?" ~from_codeset:"UTF-8" ~to_codeset:Oe_config.ocaml_codeset c), ocamldoc end comments) | (Utf8 _) as res -> res let enclosing comments pos = let rec f = function | [] -> None | (start, stop, _) :: rest -> if start < pos && pos < stop then Some (start, stop) else f rest in f (match comments with Locale x -> x | Utf8 x -> List.map (fun (x, y, _, od) -> x, y, od) x) let nearest comments pos = let rec f = function | [] -> None | (b, e, _) :: [] -> Some (b, e) | (b1, e1, _) :: (((b2, e2, _) :: _) as next) -> if (pos <= b1) || (b1 <= pos && pos < e1) then Some (b1, e1) else if e1 <= pos && pos < b2 then if pos - e1 < b2 - pos then Some (b1, e1) else if pos - e1 >= b2 - pos then Some (b2, e2) else None else f next in f (match comments with Locale x -> x | Utf8 x -> List.map (fun (x, y, _, od) -> x, y, od) x) let partition comments pos = let pos = ref pos in match comments with | Utf8 comments -> let a, b = List.partition begin fun (_, y, e, _) -> if y <= !pos + e then (pos := !pos + e; true) else false end comments in Utf8 a, Utf8 b, !pos | Locale [] -> (Utf8 []), (Utf8 []), !pos | Locale comments -> let a, b = List.partition begin fun (_, y, _) -> if y <= !pos then true else false end comments in Locale a, Locale b, !pos let enclosing_comment2 text pos = begin try if String.length text < 2 then raise Not_found; let start = search_backward pat text (if pos = 0 then 0 else pos - 1) in begin try ignore (matched_group 1 text); begin try let stop = search_forward pat text pos in begin try ignore (matched_group 2 text); Some (start, stop + 2) (* start - stop *) with Not_found -> Some (start, (try search_forward lineend text pos with Not_found -> String.length text) ) (* start - start *) end; with Not_found -> Some (start, (try search_forward lineend text pos with Not_found -> String.length text) ) (* start - lineend | textend *) end with Not_found -> None (* stop - ? *) end; no_start , no_stop - ? end
null
https://raw.githubusercontent.com/ftovagliari/ocamleditor/53284253cf7603b96051e7425e85a731f09abcd1/src/comments.ml
ocaml
begin * end * extra bytes * ocamldoc begin * end * ocamldoc Non vengono considerate le stringhe start - stop start - start start - lineend | textend stop - ?
OCamlEditor Copyright ( C ) 2010 - 2014 This file is part of OCamlEditor . OCamlEditor 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 . OCamlEditor 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 < / > . OCamlEditor Copyright (C) 2010-2014 Francesco Tovagliari This file is part of OCamlEditor. OCamlEditor 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. OCamlEditor 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 </>. *) open Str let pat = regexp "\\((\\*\\)\\|\\(\\*)\\)" let lineend = regexp "$" let search_f_pat = search_forward pat type t = let scan_locale txt = let rec f acc pos start = begin try let p = search_f_pat txt pos in begin try ignore (matched_group 1 txt); f acc (p + 2) (p :: start); with Not_found -> begin ignore (matched_group 2 txt); (match start with | [] -> f acc (p + 2) [] | [start] -> f ((start, (p + 2), (txt.[start + 2] = '*')) :: acc) (p + 2) [] | _::prev -> f acc (p + 2) prev) end end with Not_found -> acc end in List.rev (f [] 0 []) let scan txt = Locale (scan_locale txt) let scan_utf8 txt = match scan txt with | Locale comments -> Utf8 (List.map begin fun (x, y, ocamldoc) -> let c = String.sub txt x (y - x) in x, y, String.length c - String.length (Glib.Convert.convert_with_fallback ~fallback:"?" ~from_codeset:"UTF-8" ~to_codeset:Oe_config.ocaml_codeset c), ocamldoc end comments) | (Utf8 _) as res -> res let enclosing comments pos = let rec f = function | [] -> None | (start, stop, _) :: rest -> if start < pos && pos < stop then Some (start, stop) else f rest in f (match comments with Locale x -> x | Utf8 x -> List.map (fun (x, y, _, od) -> x, y, od) x) let nearest comments pos = let rec f = function | [] -> None | (b, e, _) :: [] -> Some (b, e) | (b1, e1, _) :: (((b2, e2, _) :: _) as next) -> if (pos <= b1) || (b1 <= pos && pos < e1) then Some (b1, e1) else if e1 <= pos && pos < b2 then if pos - e1 < b2 - pos then Some (b1, e1) else if pos - e1 >= b2 - pos then Some (b2, e2) else None else f next in f (match comments with Locale x -> x | Utf8 x -> List.map (fun (x, y, _, od) -> x, y, od) x) let partition comments pos = let pos = ref pos in match comments with | Utf8 comments -> let a, b = List.partition begin fun (_, y, e, _) -> if y <= !pos + e then (pos := !pos + e; true) else false end comments in Utf8 a, Utf8 b, !pos | Locale [] -> (Utf8 []), (Utf8 []), !pos | Locale comments -> let a, b = List.partition begin fun (_, y, _) -> if y <= !pos then true else false end comments in Locale a, Locale b, !pos let enclosing_comment2 text pos = begin try if String.length text < 2 then raise Not_found; let start = search_backward pat text (if pos = 0 then 0 else pos - 1) in begin try ignore (matched_group 1 text); begin try let stop = search_forward pat text pos in begin try ignore (matched_group 2 text); with Not_found -> Some (start, (try search_forward lineend text pos with Not_found -> String.length text) end; with Not_found -> Some (start, (try search_forward lineend text pos with Not_found -> String.length text) end end; no_start , no_stop - ? end
bcde94ac7a1e0ed55a43ed3d21869c4425c0e381db85d97c373d649ce3e56864
yetanalytics/dl4clj
java_rdd.clj
(ns ^{:doc "name space for creating JavaRDDs, Not sure if this is the best way of doing it, need to do more research"} dl4clj.spark.data.java-rdd (:import [org.apache.spark.api.java JavaRDD JavaSparkContext] [org.apache.spark SparkConf]) (:require [dl4clj.helpers :refer [data-from-iter reset-iterator!]] [clojure.core.match :refer [match]] [dl4clj.utils :refer [obj-or-code? as-code eval-if-code]])) (defn new-java-spark-context "creates a java spark context from a spark conf if no spark conf is supplied, one will be create - master is will be set to local - app name will be set to :app-name or 'default app name'" [& {:keys [spark-conf app-name as-code?] :or {as-code? true} :as opts}] (let [code (if (contains? opts :spark-conf) `(JavaSparkContext. ~spark-conf) `(-> (SparkConf.) (.setMaster "local[*]") (.setAppName ~(if (string? app-name) app-name "default app name")) (JavaSparkContext.)))] (obj-or-code? as-code? code))) (defn text-file "Reads a text file from HDFS, a local file system (available on all nodes), or any Hadoop-supported file system URI, and returns it as an `JavaRDD` of Strings. :spark-context (spark context), your connection to spark :file-name (str) path to the file you want in the JavaRDD :min-partitions (int), the desired mininum number of partitions - optional" [& {:keys [spark-context file-name min-partitions as-code?] :or {as-code? true} :as opts}] (match [opts] [{:spark-context (_ :guard seq?) :file-name (:or (_ :guard string?) (_ :guard seq?)) :min-partitions (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.textFile ~spark-context ~file-name (int ~min-partitions))) [{:spark-context _ :file-name (:or (_ :guard string?) (_ :guard seq?)) :min-partitions (:or (_ :guard number?) (_ :guard seq?))}] (let [[sc f-n p] (eval-if-code [spark-context seq?] [file-name seq? string?] [min-partitions seq? number?])] (.textFile sc f-n (int p))) [{:spark-context (_ :guard seq?) :file-name (:or (_ :guard string?) (_ :guard seq?))}] (obj-or-code? as-code? `(.textFile ~spark-context ~file-name)) [{:spark-context _ :file-name (:or (_ :guard string?) (_ :guard seq?))}] (let [[sc f-n] (eval-if-code [spark-context seq?] [file-name seq? string?])] (.textFile sc f-n)))) (defn whole-text-files "Read a directory of text files from HDFS, a local file system (available on all nodes), or any Hadoop-supported file system URI, and returns it as a `JavaPairRDD` of (K, V) pairs, where, K is the path of each file, V is the content of each file. :spark-context (spark context), your connection to spark :path (str) path to the directory :min-partitions (int), the desired mininum number of partitions - optional" [& {:keys [spark-context path min-partitions as-code?] :or {as-code? true} :as opts}] (match [opts] [{:spark-context (_ :guard seq?) :path (:or (_ :guard string?) (_ :guard seq?)) :min-partitions (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.wholeTextFiles ~spark-context ~path (int ~min-partitions))) [{:spark-context _ :path (:or (_ :guard string?) (_ :guard seq?)) :min-partitions (:or (_ :guard number?) (_ :guard seq?))}] (let [[sc p n-p] (eval-if-code [spark-context seq?] [path seq? string?] [min-partitions seq? number?])] (.wholeTextFiles sc p (int n-p))) [{:spark-context (_ :guard seq?) :path (:or (_ :guard string?) (_ :guard seq?))}] (obj-or-code? as-code? `(.wholeTextFiles ~spark-context ~path)) [{:spark-context _ :path (:or (_ :guard string?) (_ :guard seq?))}] (let [[sc p] (eval-if-code [spark-context seq?] [path seq? string?])] (.wholeTextFiles sc p)))) (defn parallelize "Distributes a local collection to form/return an RDD :spark-context (spark context), your connection to spark :data (coll), a collection you want converted into a RDD :num-slices (int), need to get more familiar with spark lingo to give an accurate desc - optional" [& {:keys [spark-context data num-slices as-code?] :as opts}] (match [opts] [{:spark-context _ :data (:or (_ :guard coll?) (_ :guard seq?)) :num-slices (:or (_ :guard number?) (_ :guard seq?))}] (let [[sc d n-slices] (eval-if-code [spark-context seq?] [data seq? coll?] [num-slices seq? number?])] (.parallelize sc (if (vector? d) (reverse (into '() d)) d) (int n-slices))) [{:spark-context _ :data (:or (_ :guard coll?) (_ :guard seq?))}] (let [[sc d] (eval-if-code [spark-context seq?] [data seq? coll?])] (.parallelize sc (if (vector? d) (reverse (into '() d)) d))))) (defn parallelize-pairs "Distributes a local collection to form/return a Pair RDD :spark-context (spark context), your connection to spark :data (coll), a collection you want converted into a RDD :num-slices (int), need to get more familiar with spark lingo to give an accurate desc - optional" [& {:keys [spark-context data num-slices as-code?] :or {as-code? true} :as opts}] (match [opts] [{:spark-context _ :data (:or (_ :guard coll?) (_ :guard seq?)) :num-slices (:or (_ :guard number?) (_ :guard seq?))}] (let [[sc d n-slices] (eval-if-code [spark-context seq?] [data seq? coll?] [num-slices seq? number?])] (.parallelizePairs sc (if (vector? d) (reverse (into '() d)) d) n-slices)) [{:spark-context _ :data (:or (_ :guard coll?) (_ :guard seq?))}] (let [[sc d] (eval-if-code [spark-context seq?] [data seq? coll?])] (.parallelizePairs sc (if (vector? d) (reverse (into '() d)) d))))) (defn java-rdd-from-iter "given a spark context and an iterator, creates a javaRDD from the data in the iterator" [& {:keys [spark-context iter num-slices] :as opts}] (match [opts] [{:spark-context _ :iter (_ :guard seq?) :num-slices (:or (_ :guard number?) (_ :guard seq?))}] (parallelize :spark-context spark-context :data (data-from-iter iter :as-code? false) :num-slices num-slices) [{:spark-context _ :iter (_ :guard seq?)}] (parallelize :spark-context spark-context :data (data-from-iter iter :as-code? false)) [{:spark-context _ :iter _}] (let [[i] (eval-if-code [iter seq?])] (parallelize :spark-context spark-context :data (data-from-iter (reset-iterator! i))))))
null
https://raw.githubusercontent.com/yetanalytics/dl4clj/9ef055b2a460f1a6246733713136b981fd322510/src/dl4clj/spark/data/java_rdd.clj
clojure
(ns ^{:doc "name space for creating JavaRDDs, Not sure if this is the best way of doing it, need to do more research"} dl4clj.spark.data.java-rdd (:import [org.apache.spark.api.java JavaRDD JavaSparkContext] [org.apache.spark SparkConf]) (:require [dl4clj.helpers :refer [data-from-iter reset-iterator!]] [clojure.core.match :refer [match]] [dl4clj.utils :refer [obj-or-code? as-code eval-if-code]])) (defn new-java-spark-context "creates a java spark context from a spark conf if no spark conf is supplied, one will be create - master is will be set to local - app name will be set to :app-name or 'default app name'" [& {:keys [spark-conf app-name as-code?] :or {as-code? true} :as opts}] (let [code (if (contains? opts :spark-conf) `(JavaSparkContext. ~spark-conf) `(-> (SparkConf.) (.setMaster "local[*]") (.setAppName ~(if (string? app-name) app-name "default app name")) (JavaSparkContext.)))] (obj-or-code? as-code? code))) (defn text-file "Reads a text file from HDFS, a local file system (available on all nodes), or any Hadoop-supported file system URI, and returns it as an `JavaRDD` of Strings. :spark-context (spark context), your connection to spark :file-name (str) path to the file you want in the JavaRDD :min-partitions (int), the desired mininum number of partitions - optional" [& {:keys [spark-context file-name min-partitions as-code?] :or {as-code? true} :as opts}] (match [opts] [{:spark-context (_ :guard seq?) :file-name (:or (_ :guard string?) (_ :guard seq?)) :min-partitions (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.textFile ~spark-context ~file-name (int ~min-partitions))) [{:spark-context _ :file-name (:or (_ :guard string?) (_ :guard seq?)) :min-partitions (:or (_ :guard number?) (_ :guard seq?))}] (let [[sc f-n p] (eval-if-code [spark-context seq?] [file-name seq? string?] [min-partitions seq? number?])] (.textFile sc f-n (int p))) [{:spark-context (_ :guard seq?) :file-name (:or (_ :guard string?) (_ :guard seq?))}] (obj-or-code? as-code? `(.textFile ~spark-context ~file-name)) [{:spark-context _ :file-name (:or (_ :guard string?) (_ :guard seq?))}] (let [[sc f-n] (eval-if-code [spark-context seq?] [file-name seq? string?])] (.textFile sc f-n)))) (defn whole-text-files "Read a directory of text files from HDFS, a local file system (available on all nodes), or any Hadoop-supported file system URI, and returns it as a `JavaPairRDD` of (K, V) pairs, where, K is the path of each file, V is the content of each file. :spark-context (spark context), your connection to spark :path (str) path to the directory :min-partitions (int), the desired mininum number of partitions - optional" [& {:keys [spark-context path min-partitions as-code?] :or {as-code? true} :as opts}] (match [opts] [{:spark-context (_ :guard seq?) :path (:or (_ :guard string?) (_ :guard seq?)) :min-partitions (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.wholeTextFiles ~spark-context ~path (int ~min-partitions))) [{:spark-context _ :path (:or (_ :guard string?) (_ :guard seq?)) :min-partitions (:or (_ :guard number?) (_ :guard seq?))}] (let [[sc p n-p] (eval-if-code [spark-context seq?] [path seq? string?] [min-partitions seq? number?])] (.wholeTextFiles sc p (int n-p))) [{:spark-context (_ :guard seq?) :path (:or (_ :guard string?) (_ :guard seq?))}] (obj-or-code? as-code? `(.wholeTextFiles ~spark-context ~path)) [{:spark-context _ :path (:or (_ :guard string?) (_ :guard seq?))}] (let [[sc p] (eval-if-code [spark-context seq?] [path seq? string?])] (.wholeTextFiles sc p)))) (defn parallelize "Distributes a local collection to form/return an RDD :spark-context (spark context), your connection to spark :data (coll), a collection you want converted into a RDD :num-slices (int), need to get more familiar with spark lingo to give an accurate desc - optional" [& {:keys [spark-context data num-slices as-code?] :as opts}] (match [opts] [{:spark-context _ :data (:or (_ :guard coll?) (_ :guard seq?)) :num-slices (:or (_ :guard number?) (_ :guard seq?))}] (let [[sc d n-slices] (eval-if-code [spark-context seq?] [data seq? coll?] [num-slices seq? number?])] (.parallelize sc (if (vector? d) (reverse (into '() d)) d) (int n-slices))) [{:spark-context _ :data (:or (_ :guard coll?) (_ :guard seq?))}] (let [[sc d] (eval-if-code [spark-context seq?] [data seq? coll?])] (.parallelize sc (if (vector? d) (reverse (into '() d)) d))))) (defn parallelize-pairs "Distributes a local collection to form/return a Pair RDD :spark-context (spark context), your connection to spark :data (coll), a collection you want converted into a RDD :num-slices (int), need to get more familiar with spark lingo to give an accurate desc - optional" [& {:keys [spark-context data num-slices as-code?] :or {as-code? true} :as opts}] (match [opts] [{:spark-context _ :data (:or (_ :guard coll?) (_ :guard seq?)) :num-slices (:or (_ :guard number?) (_ :guard seq?))}] (let [[sc d n-slices] (eval-if-code [spark-context seq?] [data seq? coll?] [num-slices seq? number?])] (.parallelizePairs sc (if (vector? d) (reverse (into '() d)) d) n-slices)) [{:spark-context _ :data (:or (_ :guard coll?) (_ :guard seq?))}] (let [[sc d] (eval-if-code [spark-context seq?] [data seq? coll?])] (.parallelizePairs sc (if (vector? d) (reverse (into '() d)) d))))) (defn java-rdd-from-iter "given a spark context and an iterator, creates a javaRDD from the data in the iterator" [& {:keys [spark-context iter num-slices] :as opts}] (match [opts] [{:spark-context _ :iter (_ :guard seq?) :num-slices (:or (_ :guard number?) (_ :guard seq?))}] (parallelize :spark-context spark-context :data (data-from-iter iter :as-code? false) :num-slices num-slices) [{:spark-context _ :iter (_ :guard seq?)}] (parallelize :spark-context spark-context :data (data-from-iter iter :as-code? false)) [{:spark-context _ :iter _}] (let [[i] (eval-if-code [iter seq?])] (parallelize :spark-context spark-context :data (data-from-iter (reset-iterator! i))))))
439b7c1e1c920febfa4c68733f3a2d37fd5f0cb843fa626b88ed567c0c5547d3
soulomoon/SICP
Exercise 2.04.scm
Exercise 2.4 : Here is an alternative procedural representation of pairs . For this representation , verify that ( car ( cons x y ) ) yields x for any objects x and y. ; (define (cons x y) ; (lambda (m) (m x y))) ; (define (car z) ; (z (lambda (p q) p))) What is the corresponding definition of cdr ? ( Hint : To verify that this works , make use of the substitution model of 1.1.5 . ) #lang planet neil/sicp (define (cons x y) (lambda (m) (m x y))) (define (car z) (z (lambda (p q) p))) (define (cdr z) (z (lambda (p q) q))) (define a (cons 3 2)) (car a) (cdr a) ```````````````````````````````````````````` Welcome to DrRacket, version 6.6 [3m]. memory limit : 128 MB . 3 2 >
null
https://raw.githubusercontent.com/soulomoon/SICP/1c6cbf5ecf6397eaeb990738a938d48c193af1bb/Chapter2/Exercise%202.04.scm
scheme
(define (cons x y) (lambda (m) (m x y))) (define (car z) (z (lambda (p q) p)))
Exercise 2.4 : Here is an alternative procedural representation of pairs . For this representation , verify that ( car ( cons x y ) ) yields x for any objects x and y. What is the corresponding definition of cdr ? ( Hint : To verify that this works , make use of the substitution model of 1.1.5 . ) #lang planet neil/sicp (define (cons x y) (lambda (m) (m x y))) (define (car z) (z (lambda (p q) p))) (define (cdr z) (z (lambda (p q) q))) (define a (cons 3 2)) (car a) (cdr a) ```````````````````````````````````````````` Welcome to DrRacket, version 6.6 [3m]. memory limit : 128 MB . 3 2 >
5ef096ad5d4ccdf95d45ab5ebf96096a2b3ec30cc2574ede5d5df96fc28b93c1
bos/rwh
eqclasses.hs
{-- snippet color --} data Color = Red | Green | Blue colorEq :: Color -> Color -> Bool colorEq Red Red = True colorEq Green Green = True colorEq Blue Blue = True colorEq _ _ = False {-- /snippet color --} stringEq :: [Char] -> [Char] -> Bool -- Match if both are empty stringEq [] [] = True Evaluate when we have only one character in both stringEq [x] [y] = x == y -- If both start with the same char, check the rest stringEq (x:xs) (y:ys) = if x == y then stringEq xs ys else False -- Everything else doesn't match stringEq _ _ = False {-- snippet basiceq --} class BasicEq a where isEqual :: a -> a -> Bool {-- /snippet basiceq --} {-- snippet basicinstance --} instance BasicEq Bool where isEqual True True = True isEqual False False = True isEqual _ _ = False {-- /snippet basicinstance--} {-- snippet basiceq2 --} class BasicEq2 a where isEqual2 :: a -> a -> Bool isNotEqual2 :: a -> a -> Bool {-- /snippet basiceq2 --} - snippet - class BasicEq3 a where isEqual3 :: a -> a -> Bool isEqual3 x y = not (isNotEqual3 x y) isNotEqual3 :: a -> a -> Bool isNotEqual3 x y = not (isEqual3 x y) {-- /snippet basiceq3 --} {-- snippet basiceq3inst --} instance BasicEq3 Color where isEqual3 Red Red = True isEqual3 Green Green = True isEqual3 Blue Blue = True isEqual3 _ _ = False {-- /snippet basiceq3inst --} {-- snippet show --} instance Show Color where show Red = "Red" show Green = "Green" show Blue = "Blue" {-- /snippet show --} {-- snippet read --} instance Read Color where -- readsPrec is the main function for parsing input readsPrec _ value = We pass a list of pairs . Each pair has a string and the desired return value . will try to match the input to one of these strings . tryParse [("Red", Red), ("Green", Green), ("Blue", Blue)] where tryParse [] = [] -- If there is nothing left to try, fail tryParse ((attempt, result):xs) = -- Compare the start of the string to be parsed to the -- text we are looking for. if (take (length attempt) value) == attempt -- If we have a match, return the result and the -- remaining input then [(result, drop (length attempt) value)] -- If we don't have a match, try the next pair -- in the list of attempts. else tryParse xs {-- /snippet read --}
null
https://raw.githubusercontent.com/bos/rwh/7fd1e467d54aef832f5476ebf5f4f6a898a895d1/examples/ch07/eqclasses.hs
haskell
- snippet color - - /snippet color - Match if both are empty If both start with the same char, check the rest Everything else doesn't match - snippet basiceq - - /snippet basiceq - - snippet basicinstance - - /snippet basicinstance- - snippet basiceq2 - - /snippet basiceq2 - - /snippet basiceq3 - - snippet basiceq3inst - - /snippet basiceq3inst - - snippet show - - /snippet show - - snippet read - readsPrec is the main function for parsing input If there is nothing left to try, fail Compare the start of the string to be parsed to the text we are looking for. If we have a match, return the result and the remaining input If we don't have a match, try the next pair in the list of attempts. - /snippet read -
data Color = Red | Green | Blue colorEq :: Color -> Color -> Bool colorEq Red Red = True colorEq Green Green = True colorEq Blue Blue = True colorEq _ _ = False stringEq :: [Char] -> [Char] -> Bool stringEq [] [] = True Evaluate when we have only one character in both stringEq [x] [y] = x == y stringEq (x:xs) (y:ys) = if x == y then stringEq xs ys else False stringEq _ _ = False class BasicEq a where isEqual :: a -> a -> Bool instance BasicEq Bool where isEqual True True = True isEqual False False = True isEqual _ _ = False class BasicEq2 a where isEqual2 :: a -> a -> Bool isNotEqual2 :: a -> a -> Bool - snippet - class BasicEq3 a where isEqual3 :: a -> a -> Bool isEqual3 x y = not (isNotEqual3 x y) isNotEqual3 :: a -> a -> Bool isNotEqual3 x y = not (isEqual3 x y) instance BasicEq3 Color where isEqual3 Red Red = True isEqual3 Green Green = True isEqual3 Blue Blue = True isEqual3 _ _ = False instance Show Color where show Red = "Red" show Green = "Green" show Blue = "Blue" instance Read Color where readsPrec _ value = We pass a list of pairs . Each pair has a string and the desired return value . will try to match the input to one of these strings . tryParse [("Red", Red), ("Green", Green), ("Blue", Blue)] tryParse ((attempt, result):xs) = if (take (length attempt) value) == attempt then [(result, drop (length attempt) value)] else tryParse xs
7301118f14a390218502107d8b2ded76e4afc8852ea0938753d7bf750702a182
argp/bap
pack.ml
(**************************************************************************) (* *) : a generic graph library for OCaml Copyright ( C ) 2004 - 2010 , and (* *) (* This software is free software; you can redistribute it and/or *) modify it under the terms of the GNU Library General Public License version 2.1 , with the special exception on linking (* described in file LICENSE. *) (* *) (* This software 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. *) (* *) (**************************************************************************) $ I d : pack.ml , v 1.13 2006 - 05 - 12 14:07:16 filliatr Exp $ module Generic(G : Sig.IM with type V.label = int and type E.label = int) = struct include G exception Found of V.t let find_vertex g i = try iter_vertex (fun v -> if V.label v = i then raise (Found v)) g; raise Not_found with Found v -> v module Builder = Builder.I(G) module Dfs = Traverse.Dfs(G) module Bfs = Traverse.Bfs(G) module Marking = Traverse.Mark(G) module Classic = Classic.I(G) module Rand = Rand.I(G) module Components = Components.Make(G) module W = struct type label = int type t = int let weight x = x let zero = 0 let add = (+) let compare : t -> t -> int = Pervasives.compare end include Path.Dijkstra(G)(W) module BF = Path.BellmanFord(G)(W) let bellman_ford = BF.find_negative_cycle_from module F = struct type label = int type t = int let max_capacity x = x let min_capacity _ = 0 let flow _ = 0 let add = (+) let sub = (-) let compare : t -> t -> int = Pervasives.compare let max = max_int let min = 0 let zero = 0 end module FF = Flow.Ford_Fulkerson(G)(F) let ford_fulkerson g = if not G.is_directed then invalid_arg "ford_fulkerson: not a directed graph"; FF.maxflow g module Goldberg = Flow.Goldberg(G)(F) let goldberg g = if not G.is_directed then invalid_arg "goldberg: not a directed graph"; Goldberg.maxflow g include Oper.Make(Builder) module PathCheck = Path.Check(G) module Topological = struct include Topological.Make(G) module S = Topological.Make_stable(G) let fold_stable = S.fold let iter_stable = S.iter end module Int = struct type t = int let compare : t -> t -> int = Pervasives.compare end include Kruskal.Make(G)(Int) module Display = struct include G let vertex_name v = string_of_int (V.label v) let graph_attributes _ = [] let default_vertex_attributes _ = [] let vertex_attributes _ = [] let default_edge_attributes _ = [] let edge_attributes e = [ `Label (string_of_int (E.label e) ) ] let get_subgraph _ = None end module Dot_ = Graphviz.Dot(Display) module Neato = Graphviz.Neato(Display) let dot_output g f = let oc = open_out f in if is_directed then Dot_.output_graph oc g else Neato.output_graph oc g; close_out oc let display_with_gv g = let tmp = Filename.temp_file "graph" ".dot" in dot_output g tmp; ignore (Sys.command ("dot -Tps " ^ tmp ^ " | gv -")); Sys.remove tmp module GmlParser = Gml.Parse (Builder) (struct let node l = try match List.assoc "id" l with Gml.Int n -> n | _ -> -1 with Not_found -> -1 let edge _ = 0 end) let parse_gml_file = GmlParser.parse module DotParser = Dot.Parse (Builder) (struct let nodes = Hashtbl.create 97 let new_node = ref 0 let node (id,_) _ = try Hashtbl.find nodes id with Not_found -> incr new_node; Hashtbl.add nodes id !new_node; !new_node let edge _ = 0 end) let parse_dot_file = DotParser.parse open Format module GmlPrinter = Gml.Print (G) (struct let node n = ["label", Gml.Int n] let edge n = ["label", Gml.Int n] end) let print_gml = GmlPrinter.print let print_gml_file g f = let c = open_out f in let fmt = formatter_of_out_channel c in fprintf fmt "%a@." GmlPrinter.print g; close_out c let uid h find add = let n = ref 0 in fun x -> try find h x with Not_found -> incr n; add h x !n; !n module GraphmlPrinter = Graphml . Print ( G ) ( struct let node n = [ " label " , . Int n ] let edge n = [ " label " , . Int n ] module . Make(G.V ) let vertex_uid ( Vhash.create 17 ) Vhash.find Vhash.add module = . ) let edge_uid ( Ehash.create 17 ) Ehash.find Ehash.add end ) let print_gml = GmlPrinter.print let print_gml_file g f = let c = open_out f in let fmt = formatter_of_out_channel c in fprintf fmt " % a@. " GmlPrinter.print g ; close_out c module GraphmlPrinter = Graphml.Print (G) (struct let node n = ["label", Gml.Int n] let edge n = ["label", Gml.Int n] module Vhash = Hashtbl.Make(G.V) let vertex_uid = uid (Vhash.create 17) Vhash.find Vhash.add module Ehash = Hashtbl.Make(G.E) let edge_uid = uid (Ehash.create 17) Ehash.find Ehash.add end) let print_gml = GmlPrinter.print let print_gml_file g f = let c = open_out f in let fmt = formatter_of_out_channel c in fprintf fmt "%a@." GmlPrinter.print g; close_out c *) end module I = struct type t = int let compare : t -> t -> int = Pervasives.compare let hash = Hashtbl.hash let equal = (=) let default = 0 end module IW = struct type label = I.t type t = int module M = Map.Make(I) let map = M.empty let weight lbl = lbl let compare : t -> t -> int = Pervasives.compare let add = (+) let zero = 0 end module Digraph = Generic(Imperative.Digraph.AbstractLabeled(I)(I)) module Graph = Generic(Imperative.Graph.AbstractLabeled(I)(I))
null
https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/ocamlgraph/src/pack.ml
ocaml
************************************************************************ This software is free software; you can redistribute it and/or described in file LICENSE. This software 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. ************************************************************************
: a generic graph library for OCaml Copyright ( C ) 2004 - 2010 , and modify it under the terms of the GNU Library General Public License version 2.1 , with the special exception on linking $ I d : pack.ml , v 1.13 2006 - 05 - 12 14:07:16 filliatr Exp $ module Generic(G : Sig.IM with type V.label = int and type E.label = int) = struct include G exception Found of V.t let find_vertex g i = try iter_vertex (fun v -> if V.label v = i then raise (Found v)) g; raise Not_found with Found v -> v module Builder = Builder.I(G) module Dfs = Traverse.Dfs(G) module Bfs = Traverse.Bfs(G) module Marking = Traverse.Mark(G) module Classic = Classic.I(G) module Rand = Rand.I(G) module Components = Components.Make(G) module W = struct type label = int type t = int let weight x = x let zero = 0 let add = (+) let compare : t -> t -> int = Pervasives.compare end include Path.Dijkstra(G)(W) module BF = Path.BellmanFord(G)(W) let bellman_ford = BF.find_negative_cycle_from module F = struct type label = int type t = int let max_capacity x = x let min_capacity _ = 0 let flow _ = 0 let add = (+) let sub = (-) let compare : t -> t -> int = Pervasives.compare let max = max_int let min = 0 let zero = 0 end module FF = Flow.Ford_Fulkerson(G)(F) let ford_fulkerson g = if not G.is_directed then invalid_arg "ford_fulkerson: not a directed graph"; FF.maxflow g module Goldberg = Flow.Goldberg(G)(F) let goldberg g = if not G.is_directed then invalid_arg "goldberg: not a directed graph"; Goldberg.maxflow g include Oper.Make(Builder) module PathCheck = Path.Check(G) module Topological = struct include Topological.Make(G) module S = Topological.Make_stable(G) let fold_stable = S.fold let iter_stable = S.iter end module Int = struct type t = int let compare : t -> t -> int = Pervasives.compare end include Kruskal.Make(G)(Int) module Display = struct include G let vertex_name v = string_of_int (V.label v) let graph_attributes _ = [] let default_vertex_attributes _ = [] let vertex_attributes _ = [] let default_edge_attributes _ = [] let edge_attributes e = [ `Label (string_of_int (E.label e) ) ] let get_subgraph _ = None end module Dot_ = Graphviz.Dot(Display) module Neato = Graphviz.Neato(Display) let dot_output g f = let oc = open_out f in if is_directed then Dot_.output_graph oc g else Neato.output_graph oc g; close_out oc let display_with_gv g = let tmp = Filename.temp_file "graph" ".dot" in dot_output g tmp; ignore (Sys.command ("dot -Tps " ^ tmp ^ " | gv -")); Sys.remove tmp module GmlParser = Gml.Parse (Builder) (struct let node l = try match List.assoc "id" l with Gml.Int n -> n | _ -> -1 with Not_found -> -1 let edge _ = 0 end) let parse_gml_file = GmlParser.parse module DotParser = Dot.Parse (Builder) (struct let nodes = Hashtbl.create 97 let new_node = ref 0 let node (id,_) _ = try Hashtbl.find nodes id with Not_found -> incr new_node; Hashtbl.add nodes id !new_node; !new_node let edge _ = 0 end) let parse_dot_file = DotParser.parse open Format module GmlPrinter = Gml.Print (G) (struct let node n = ["label", Gml.Int n] let edge n = ["label", Gml.Int n] end) let print_gml = GmlPrinter.print let print_gml_file g f = let c = open_out f in let fmt = formatter_of_out_channel c in fprintf fmt "%a@." GmlPrinter.print g; close_out c let uid h find add = let n = ref 0 in fun x -> try find h x with Not_found -> incr n; add h x !n; !n module GraphmlPrinter = Graphml . Print ( G ) ( struct let node n = [ " label " , . Int n ] let edge n = [ " label " , . Int n ] module . Make(G.V ) let vertex_uid ( Vhash.create 17 ) Vhash.find Vhash.add module = . ) let edge_uid ( Ehash.create 17 ) Ehash.find Ehash.add end ) let print_gml = GmlPrinter.print let print_gml_file g f = let c = open_out f in let fmt = formatter_of_out_channel c in fprintf fmt " % a@. " GmlPrinter.print g ; close_out c module GraphmlPrinter = Graphml.Print (G) (struct let node n = ["label", Gml.Int n] let edge n = ["label", Gml.Int n] module Vhash = Hashtbl.Make(G.V) let vertex_uid = uid (Vhash.create 17) Vhash.find Vhash.add module Ehash = Hashtbl.Make(G.E) let edge_uid = uid (Ehash.create 17) Ehash.find Ehash.add end) let print_gml = GmlPrinter.print let print_gml_file g f = let c = open_out f in let fmt = formatter_of_out_channel c in fprintf fmt "%a@." GmlPrinter.print g; close_out c *) end module I = struct type t = int let compare : t -> t -> int = Pervasives.compare let hash = Hashtbl.hash let equal = (=) let default = 0 end module IW = struct type label = I.t type t = int module M = Map.Make(I) let map = M.empty let weight lbl = lbl let compare : t -> t -> int = Pervasives.compare let add = (+) let zero = 0 end module Digraph = Generic(Imperative.Digraph.AbstractLabeled(I)(I)) module Graph = Generic(Imperative.Graph.AbstractLabeled(I)(I))
db8ee0034fc456eb510d908eb409594f511c869021c9b9118f1d7b2dab1bd556
dwayne/eopl3
parser.rkt
#lang eopl ;; Program ::= Expression ;; ;; Expression ::= Number ;; ;; ::= Identifier ;; ;; ::= -(Expression, Expression) ;; ;; ::= *(Expression, Expression) ;; ;; ::= zero?(Expression) ;; ;; ::= if Expression then Expression else Expression ;; ;; ::= let Identifier = Expression in Expression ;; ;; ::= proc (Identifier) Expression ;; ;; ::= (Expression Expression) (provide AST program a-program expression expression? const-exp var-exp diff-exp mult-exp zero?-exp if-exp let-exp proc-exp call-exp Parser parse) (define scanner-spec '((number (digit (arbno digit)) number) (identifier (letter (arbno letter)) symbol) (ws ((arbno whitespace)) skip))) (define grammar '((program (expression) a-program) (expression (number) const-exp) (expression (identifier) var-exp) (expression ("-" "(" expression "," expression ")") diff-exp) (expression ("*" "(" expression "," expression ")") mult-exp) (expression ("zero?" "(" expression ")") zero?-exp) (expression ("if" expression "then" expression "else" expression) if-exp) (expression ("let" identifier "=" expression "in" expression) let-exp) (expression ("proc" "(" identifier ")" expression) proc-exp) (expression ("(" expression expression ")") call-exp))) (sllgen:make-define-datatypes scanner-spec grammar) (define parse (sllgen:make-string-parser scanner-spec grammar))
null
https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/03-ch3/interpreters/racket/PROC-3.28/parser.rkt
racket
Program ::= Expression Expression ::= Number ::= Identifier ::= -(Expression, Expression) ::= *(Expression, Expression) ::= zero?(Expression) ::= if Expression then Expression else Expression ::= let Identifier = Expression in Expression ::= proc (Identifier) Expression ::= (Expression Expression)
#lang eopl (provide AST program a-program expression expression? const-exp var-exp diff-exp mult-exp zero?-exp if-exp let-exp proc-exp call-exp Parser parse) (define scanner-spec '((number (digit (arbno digit)) number) (identifier (letter (arbno letter)) symbol) (ws ((arbno whitespace)) skip))) (define grammar '((program (expression) a-program) (expression (number) const-exp) (expression (identifier) var-exp) (expression ("-" "(" expression "," expression ")") diff-exp) (expression ("*" "(" expression "," expression ")") mult-exp) (expression ("zero?" "(" expression ")") zero?-exp) (expression ("if" expression "then" expression "else" expression) if-exp) (expression ("let" identifier "=" expression "in" expression) let-exp) (expression ("proc" "(" identifier ")" expression) proc-exp) (expression ("(" expression expression ")") call-exp))) (sllgen:make-define-datatypes scanner-spec grammar) (define parse (sllgen:make-string-parser scanner-spec grammar))
5d1d2643bd999d0fbbd18a0244462a4bd4e474a84033cbe73233156a8c80189a
threatgrid/asami
decoder.cljs
(ns ^{:doc "Encodes and decodes data for storage. Clojure implementation" :author "Joel Holdbrooks"} asami.durable.decoder (:require [clojure.string :as s] [asami.durable.common :refer [read-byte read-bytes read-short]]) (:import [goog.math Long Integer] [goog Uri])) (def ^{:private true} BYTE_BYTES 1) (def ^{:private true} SHORT_BYTES 1) (def ^{:private true} SHORT_SIZE 16) (def ^{:private true} INTEGER_BYTES 4) (def ^{:private true} LONG_BYTES 8) ;; temporary stub (defn type-info [data] 0) (defn decode-length "Reads the header to determine length. ext: if 0 then length is a byte, if 1 then length is in either a short or an int" [ext paged-rdr ^long pos] (if ext (let [raw (read-byte paged-rdr pos)] [BYTE_BYTES (bit-and 0xFF raw)]) (let [len (read-short paged-rdr pos)] (if (< len 0) (let [len2 (read-short paged-rdr pos)] [INTEGER_BYTES (bit-or (bit-shift-left (int (bit-and 0x7FFF len)) SHORT_SIZE) len2)]) [SHORT_BYTES len])))) ;; Readers are given the length and a position. They then read data into a type (defn bytes->str [bytes] (let [decoder (js/TextDecoder.)] (.decode decoder bytes))) (defn read-str [paged-rdr ^long pos ^long len] (bytes->str (read-bytes paged-rdr pos len))) (defn read-uri [paged-rdr ^long pos ^long len] (Uri/parse (read-str paged-rdr pos len))) (defn read-keyword [paged-rdr ^long pos ^long len] (keyword (read-str paged-rdr pos len))) ;; decoders operate on the bytes following the initial type byte information if the data type has variable length , then this is decoded first (defn bytes->int {:private true} [bytes] ;; `bytes` is assumed to be a `js/Array` like object. (let [bytes (to-array bytes)] (bit-or (bit-shift-left (bit-and (aget bytes 0) 0xFF) 24) (bit-shift-left (bit-and (aget bytes 1) 0xFF) 16) (bit-shift-left (bit-and (aget bytes 2) 0xFF) 8) (bit-shift-left (bit-and (aget bytes 3) 0xFF) 0)))) (defn bytes->long [bytes] ;; `bytes` is assumed to be an `js/Array` like object. (let [high-bits (bytes->int (.slice bytes 0 4)) low-bits (bytes->int (.slice bytes 4 8))] (.fromBits Long low-bits high-bits))) (defn long-decoder [ext paged-rdr ^long pos] (bytes->long (read-bytes paged-rdr pos LONG_BYTES))) #_ (defn double-decoder [ext paged-rdr ^long pos] (let [b (ByteBuffer/wrap (read-bytes paged-rdr pos Long/BYTES))] (.getDouble b 0))) (defn string-decoder [ext paged-rdr ^long pos] (let [[i len] (decode-length ext paged-rdr pos)] (read-str paged-rdr (+ pos i) len))) (defn uri-decoder [ext paged-rdr ^long pos] (let [[i len] (decode-length ext paged-rdr pos)] (read-uri paged-rdr (+ pos i) len))) #_ (defn bigint-decoder [ext paged-rdr ^long pos] (let [[i len] (decode-length ext paged-rdr pos) b (read-bytes paged-rdr (+ i pos) len)] (bigint (BigInteger. b)))) #_ (defn bigdec-decoder [ext paged-rdr ^long pos] (bigdec (string-decoder ext paged-rdr pos))) (defn date-decoder [ext paged-rdr ^long pos] Note : ` .toNumber ` may not be safe here . (js/Date. (.toNumber (long-decoder ext paged-rdr pos)))) (def ^:const instant-length (+ LONG_BYTES INTEGER_BYTES)) (defn instant-decoder [ext paged-rdr ^long pos] (let [b (read-bytes paged-rdr pos instant-length) epoch ( b 0 ) ; ; Ignored for now . sec (bytes->long b)] (js/Date. (* 1000 sec)))) (defn keyword-decoder [ext paged-rdr ^long pos] (let [[i len] (decode-length ext paged-rdr pos)] (read-keyword paged-rdr (+ pos i) len))) (def ^:const uuid-length (* 2 LONG_BYTES)) (defn uuid-decoder [ext paged-rdr ^long pos] (let [b (read-bytes paged-rdr pos uuid-length) hex (s/join (map (fn [b] (let [hex (.toString b 16)] (if (<= b 0xf) (str 0 hex) hex))) b))] (if-let [[_ a b c d e] (re-matches #"(.{8})(.{4})(.{4})(.{4})(.{12})" hex)] (uuid (str a "-" b "-" c "-" d "-" e)) ;; TODO: error handling ))) #_ (defn blob-decoder [ext paged-rdr ^long pos] (let [[i len] (decode-length ext paged-rdr pos)] (read-bytes paged-rdr (+ i pos) len))) #_ (defn xsd-decoder [ext paged-rdr ^long pos] (let [s (string-decoder ext paged-rdr pos) sp (s/index-of s \space)] [(URI/create (subs s 0 sp)) (subs (inc sp))])) (defn default-decoder "This is a decoder for unsupported data that has a string constructor" [ext paged-rdr ^long pos] (throw (ex-info "Not implemented" {})) #_ (let [s (string-decoder ext paged-rdr pos) sp (s/index-of s \space) class-name (subs s 0 sp)] (try (let [c (Class/forName class-name) cn (.getConstructor c (into-array Class [String]))] (.newInstance cn (object-array [(subs s (inc sp))]))) (catch Exception e (throw (ex-info (str "Unable to construct class: " class-name) {:class class-name})))))) (def typecode->decoder "Map of type codes to decoder functions" {0 long-decoder 1 double - decoder 2 string-decoder 3 uri-decoder 6 bigint - decoder 7 bigdec - decoder 8 date-decoder 9 instant-decoder 10 keyword-decoder 11 uuid-decoder 12 blob - decoder 13 xsd - decoder }) (defn long-bytes-compare "Compare data from 2 values that are the same type. If the data cannot give a result then return 0. Operates on an array, expected to be in an index node." [type-left left-header left-body left-object right-bytes] 0) (defn read-object "Reads an object from a paged-reader, at id=pos" [paged-rdr ^long pos] (let [b0 (read-byte paged-rdr pos) ipos (inc pos)] (cond (zero? (bit-and 0x80 b0)) (read-str paged-rdr ipos b0) (zero? (bit-and 0x40 b0)) (read-uri paged-rdr ipos (bit-and 0x3F b0)) (zero? (bit-and 0x20 b0)) (read-keyword paged-rdr ipos (bit-and 0x1F b0)) :default ((typecode->decoder (bit-and 0x0F b0) default-decoder) (zero? (bit-and 0x10 b0)) paged-rdr ipos)))) (defn unencapsulate-id [x]) (defn encapsulated-node? [id]) (defn decode-length-node [b])
null
https://raw.githubusercontent.com/threatgrid/asami/870b334c5ad28a56de483770329d0f75a2489932/src/asami/durable/decoder.cljs
clojure
temporary stub Readers are given the length and a position. They then read data into a type decoders operate on the bytes following the initial type byte information `bytes` is assumed to be a `js/Array` like object. `bytes` is assumed to be an `js/Array` like object. ; Ignored for now . TODO: error handling
(ns ^{:doc "Encodes and decodes data for storage. Clojure implementation" :author "Joel Holdbrooks"} asami.durable.decoder (:require [clojure.string :as s] [asami.durable.common :refer [read-byte read-bytes read-short]]) (:import [goog.math Long Integer] [goog Uri])) (def ^{:private true} BYTE_BYTES 1) (def ^{:private true} SHORT_BYTES 1) (def ^{:private true} SHORT_SIZE 16) (def ^{:private true} INTEGER_BYTES 4) (def ^{:private true} LONG_BYTES 8) (defn type-info [data] 0) (defn decode-length "Reads the header to determine length. ext: if 0 then length is a byte, if 1 then length is in either a short or an int" [ext paged-rdr ^long pos] (if ext (let [raw (read-byte paged-rdr pos)] [BYTE_BYTES (bit-and 0xFF raw)]) (let [len (read-short paged-rdr pos)] (if (< len 0) (let [len2 (read-short paged-rdr pos)] [INTEGER_BYTES (bit-or (bit-shift-left (int (bit-and 0x7FFF len)) SHORT_SIZE) len2)]) [SHORT_BYTES len])))) (defn bytes->str [bytes] (let [decoder (js/TextDecoder.)] (.decode decoder bytes))) (defn read-str [paged-rdr ^long pos ^long len] (bytes->str (read-bytes paged-rdr pos len))) (defn read-uri [paged-rdr ^long pos ^long len] (Uri/parse (read-str paged-rdr pos len))) (defn read-keyword [paged-rdr ^long pos ^long len] (keyword (read-str paged-rdr pos len))) if the data type has variable length , then this is decoded first (defn bytes->int {:private true} (let [bytes (to-array bytes)] (bit-or (bit-shift-left (bit-and (aget bytes 0) 0xFF) 24) (bit-shift-left (bit-and (aget bytes 1) 0xFF) 16) (bit-shift-left (bit-and (aget bytes 2) 0xFF) 8) (bit-shift-left (bit-and (aget bytes 3) 0xFF) 0)))) (defn bytes->long (let [high-bits (bytes->int (.slice bytes 0 4)) low-bits (bytes->int (.slice bytes 4 8))] (.fromBits Long low-bits high-bits))) (defn long-decoder [ext paged-rdr ^long pos] (bytes->long (read-bytes paged-rdr pos LONG_BYTES))) #_ (defn double-decoder [ext paged-rdr ^long pos] (let [b (ByteBuffer/wrap (read-bytes paged-rdr pos Long/BYTES))] (.getDouble b 0))) (defn string-decoder [ext paged-rdr ^long pos] (let [[i len] (decode-length ext paged-rdr pos)] (read-str paged-rdr (+ pos i) len))) (defn uri-decoder [ext paged-rdr ^long pos] (let [[i len] (decode-length ext paged-rdr pos)] (read-uri paged-rdr (+ pos i) len))) #_ (defn bigint-decoder [ext paged-rdr ^long pos] (let [[i len] (decode-length ext paged-rdr pos) b (read-bytes paged-rdr (+ i pos) len)] (bigint (BigInteger. b)))) #_ (defn bigdec-decoder [ext paged-rdr ^long pos] (bigdec (string-decoder ext paged-rdr pos))) (defn date-decoder [ext paged-rdr ^long pos] Note : ` .toNumber ` may not be safe here . (js/Date. (.toNumber (long-decoder ext paged-rdr pos)))) (def ^:const instant-length (+ LONG_BYTES INTEGER_BYTES)) (defn instant-decoder [ext paged-rdr ^long pos] (let [b (read-bytes paged-rdr pos instant-length) sec (bytes->long b)] (js/Date. (* 1000 sec)))) (defn keyword-decoder [ext paged-rdr ^long pos] (let [[i len] (decode-length ext paged-rdr pos)] (read-keyword paged-rdr (+ pos i) len))) (def ^:const uuid-length (* 2 LONG_BYTES)) (defn uuid-decoder [ext paged-rdr ^long pos] (let [b (read-bytes paged-rdr pos uuid-length) hex (s/join (map (fn [b] (let [hex (.toString b 16)] (if (<= b 0xf) (str 0 hex) hex))) b))] (if-let [[_ a b c d e] (re-matches #"(.{8})(.{4})(.{4})(.{4})(.{12})" hex)] (uuid (str a "-" b "-" c "-" d "-" e)) ))) #_ (defn blob-decoder [ext paged-rdr ^long pos] (let [[i len] (decode-length ext paged-rdr pos)] (read-bytes paged-rdr (+ i pos) len))) #_ (defn xsd-decoder [ext paged-rdr ^long pos] (let [s (string-decoder ext paged-rdr pos) sp (s/index-of s \space)] [(URI/create (subs s 0 sp)) (subs (inc sp))])) (defn default-decoder "This is a decoder for unsupported data that has a string constructor" [ext paged-rdr ^long pos] (throw (ex-info "Not implemented" {})) #_ (let [s (string-decoder ext paged-rdr pos) sp (s/index-of s \space) class-name (subs s 0 sp)] (try (let [c (Class/forName class-name) cn (.getConstructor c (into-array Class [String]))] (.newInstance cn (object-array [(subs s (inc sp))]))) (catch Exception e (throw (ex-info (str "Unable to construct class: " class-name) {:class class-name})))))) (def typecode->decoder "Map of type codes to decoder functions" {0 long-decoder 1 double - decoder 2 string-decoder 3 uri-decoder 6 bigint - decoder 7 bigdec - decoder 8 date-decoder 9 instant-decoder 10 keyword-decoder 11 uuid-decoder 12 blob - decoder 13 xsd - decoder }) (defn long-bytes-compare "Compare data from 2 values that are the same type. If the data cannot give a result then return 0. Operates on an array, expected to be in an index node." [type-left left-header left-body left-object right-bytes] 0) (defn read-object "Reads an object from a paged-reader, at id=pos" [paged-rdr ^long pos] (let [b0 (read-byte paged-rdr pos) ipos (inc pos)] (cond (zero? (bit-and 0x80 b0)) (read-str paged-rdr ipos b0) (zero? (bit-and 0x40 b0)) (read-uri paged-rdr ipos (bit-and 0x3F b0)) (zero? (bit-and 0x20 b0)) (read-keyword paged-rdr ipos (bit-and 0x1F b0)) :default ((typecode->decoder (bit-and 0x0F b0) default-decoder) (zero? (bit-and 0x10 b0)) paged-rdr ipos)))) (defn unencapsulate-id [x]) (defn encapsulated-node? [id]) (defn decode-length-node [b])
4e2f58cd5c686152455110f432452dd8549ac7c321e5b2cc34f283bc22360231
fakedata-haskell/fakedata
Drone.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE TemplateHaskell # module Faker.Provider.Drone where import Config import Control.Monad.Catch import Control.Monad.IO.Class import Data.Text (Text) import Data.Vector (Vector) import Data.Monoid ((<>)) import Data.Yaml import Faker import Faker.Internal import Faker.Provider.TH import Language.Haskell.TH parseDrone :: FromJSON a => FakerSettings -> Value -> Parser a parseDrone settings (Object obj) = do en <- obj .: (getLocaleKey settings) faker <- en .: "faker" drone <- faker .: "drone" pure drone parseDrone settings val = fail $ "expected Object, but got " <> (show val) parseDroneField :: (FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a parseDroneField settings txt val = do drone <- parseDrone settings val field <- drone .:? txt .!= mempty pure field parseDroneFields :: (FromJSON a, Monoid a) => FakerSettings -> [AesonKey] -> Value -> Parser a parseDroneFields settings txts val = do drone <- parseDrone settings val helper drone txts where helper :: (FromJSON a) => Value -> [AesonKey] -> Parser a helper a [] = parseJSON a helper (Object a) (x:xs) = do field <- a .: x helper field xs helper a (x:xs) = fail $ "expect Object, but got " <> (show a) parseUnresolvedDroneField :: (FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser (Unresolved a) parseUnresolvedDroneField settings txt val = do drone <- parseDrone settings val field <- drone .:? txt .!= mempty pure $ pure field parseUnresolvedDroneFields :: (FromJSON a, Monoid a) => FakerSettings -> [AesonKey] -> Value -> Parser (Unresolved a) parseUnresolvedDroneFields settings txts val = do drone <- parseDrone settings val helper drone txts where helper :: (FromJSON a) => Value -> [AesonKey] -> Parser (Unresolved a) helper a [] = do v <- parseJSON a pure $ pure v helper (Object a) (x:xs) = do field <- a .: x helper field xs helper a _ = fail $ "expect Object, but got " <> (show a) $(genParser "drone" "name") $(genProvider "drone" "name") $(genParser "drone" "battery_type") $(genProvider "drone" "battery_type") $(genParser "drone" "iso") $(genProvider "drone" "iso") $(genParser "drone" "photo_format") $(genProvider "drone" "photo_format") $(genParser "drone" "video_format") $(genProvider "drone" "video_format") $(genParser "drone" "max_shutter_speed") $(genProvider "drone" "max_shutter_speed") $(genParser "drone" "min_shutter_speed") $(genProvider "drone" "min_shutter_speed") $(genParser "drone" "shutter_speed_units") $(genProvider "drone" "shutter_speed_units") $(genParserSingleUnresolved "drone" "weight") $(genProvidersSingleUnresolved "drone" ["weight"]) $(genParserSingleUnresolved "drone" "max_ascent_speed") $(genProvidersSingleUnresolved "drone" ["max_ascent_speed"]) $(genParserSingleUnresolved "drone" "max_descent_speed") $(genProvidersSingleUnresolved "drone" ["max_descent_speed"]) $(genParserSingleUnresolved "drone" "flight_time") $(genProvidersSingleUnresolved "drone" ["flight_time"]) $(genParserSingleUnresolved "drone" "max_altitude") $(genProvidersSingleUnresolved "drone" ["max_altitude"]) $(genParserSingleUnresolved "drone" "max_flight_distance") $(genProvidersSingleUnresolved "drone" ["max_flight_distance"]) $(genParserSingleUnresolved "drone" "max_speed") $(genProvidersSingleUnresolved "drone" ["max_speed"]) $(genParserSingleUnresolved "drone" "max_wind_resistance") $(genProvidersSingleUnresolved "drone" ["max_wind_resistance"]) $(genParserSingleUnresolved "drone" "max_angular_velocity") $(genProvidersSingleUnresolved "drone" ["max_angular_velocity"]) $(genParserSingleUnresolved "drone" "max_tilt_angle") $(genProvidersSingleUnresolved "drone" ["max_tilt_angle"]) $(genParserSingleUnresolved "drone" "operating_temperature") $(genProvidersSingleUnresolved "drone" ["operating_temperature"]) $(genParserUnresolved "drone" "battery_capacity") $(genProviderUnresolveds "drone" ["battery_capacity"]) $(genParserSingleUnresolved "drone" "battery_voltage") $(genProvidersSingleUnresolved "drone" ["battery_voltage"]) $(genParserSingleUnresolved "drone" "battery_weight") $(genProvidersSingleUnresolved "drone" ["battery_weight"]) $(genParserSingleUnresolved "drone" "charging_temperature") $(genProvidersSingleUnresolved "drone" ["charging_temperature"]) $(genParserSingleUnresolved "drone" "max_charging_power") $(genProvidersSingleUnresolved "drone" ["max_charging_power"]) $(genParserSingleUnresolved "drone" "max_resolution") $(genProvidersSingleUnresolved "drone" ["max_resolution"]) resolveDroneText :: (MonadIO m, MonadThrow m) => FakerSettings -> AesonKey -> m Text resolveDroneText = genericResolver' resolveDroneField resolveDroneField :: (MonadThrow m, MonadIO m) => FakerSettings -> AesonKey -> m Text resolveDroneField settings str = throwM $ InvalidField "drone" str
null
https://raw.githubusercontent.com/fakedata-haskell/fakedata/7b0875067386e9bb844c8b985c901c91a58842ff/src/Faker/Provider/Drone.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE TemplateHaskell # module Faker.Provider.Drone where import Config import Control.Monad.Catch import Control.Monad.IO.Class import Data.Text (Text) import Data.Vector (Vector) import Data.Monoid ((<>)) import Data.Yaml import Faker import Faker.Internal import Faker.Provider.TH import Language.Haskell.TH parseDrone :: FromJSON a => FakerSettings -> Value -> Parser a parseDrone settings (Object obj) = do en <- obj .: (getLocaleKey settings) faker <- en .: "faker" drone <- faker .: "drone" pure drone parseDrone settings val = fail $ "expected Object, but got " <> (show val) parseDroneField :: (FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a parseDroneField settings txt val = do drone <- parseDrone settings val field <- drone .:? txt .!= mempty pure field parseDroneFields :: (FromJSON a, Monoid a) => FakerSettings -> [AesonKey] -> Value -> Parser a parseDroneFields settings txts val = do drone <- parseDrone settings val helper drone txts where helper :: (FromJSON a) => Value -> [AesonKey] -> Parser a helper a [] = parseJSON a helper (Object a) (x:xs) = do field <- a .: x helper field xs helper a (x:xs) = fail $ "expect Object, but got " <> (show a) parseUnresolvedDroneField :: (FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser (Unresolved a) parseUnresolvedDroneField settings txt val = do drone <- parseDrone settings val field <- drone .:? txt .!= mempty pure $ pure field parseUnresolvedDroneFields :: (FromJSON a, Monoid a) => FakerSettings -> [AesonKey] -> Value -> Parser (Unresolved a) parseUnresolvedDroneFields settings txts val = do drone <- parseDrone settings val helper drone txts where helper :: (FromJSON a) => Value -> [AesonKey] -> Parser (Unresolved a) helper a [] = do v <- parseJSON a pure $ pure v helper (Object a) (x:xs) = do field <- a .: x helper field xs helper a _ = fail $ "expect Object, but got " <> (show a) $(genParser "drone" "name") $(genProvider "drone" "name") $(genParser "drone" "battery_type") $(genProvider "drone" "battery_type") $(genParser "drone" "iso") $(genProvider "drone" "iso") $(genParser "drone" "photo_format") $(genProvider "drone" "photo_format") $(genParser "drone" "video_format") $(genProvider "drone" "video_format") $(genParser "drone" "max_shutter_speed") $(genProvider "drone" "max_shutter_speed") $(genParser "drone" "min_shutter_speed") $(genProvider "drone" "min_shutter_speed") $(genParser "drone" "shutter_speed_units") $(genProvider "drone" "shutter_speed_units") $(genParserSingleUnresolved "drone" "weight") $(genProvidersSingleUnresolved "drone" ["weight"]) $(genParserSingleUnresolved "drone" "max_ascent_speed") $(genProvidersSingleUnresolved "drone" ["max_ascent_speed"]) $(genParserSingleUnresolved "drone" "max_descent_speed") $(genProvidersSingleUnresolved "drone" ["max_descent_speed"]) $(genParserSingleUnresolved "drone" "flight_time") $(genProvidersSingleUnresolved "drone" ["flight_time"]) $(genParserSingleUnresolved "drone" "max_altitude") $(genProvidersSingleUnresolved "drone" ["max_altitude"]) $(genParserSingleUnresolved "drone" "max_flight_distance") $(genProvidersSingleUnresolved "drone" ["max_flight_distance"]) $(genParserSingleUnresolved "drone" "max_speed") $(genProvidersSingleUnresolved "drone" ["max_speed"]) $(genParserSingleUnresolved "drone" "max_wind_resistance") $(genProvidersSingleUnresolved "drone" ["max_wind_resistance"]) $(genParserSingleUnresolved "drone" "max_angular_velocity") $(genProvidersSingleUnresolved "drone" ["max_angular_velocity"]) $(genParserSingleUnresolved "drone" "max_tilt_angle") $(genProvidersSingleUnresolved "drone" ["max_tilt_angle"]) $(genParserSingleUnresolved "drone" "operating_temperature") $(genProvidersSingleUnresolved "drone" ["operating_temperature"]) $(genParserUnresolved "drone" "battery_capacity") $(genProviderUnresolveds "drone" ["battery_capacity"]) $(genParserSingleUnresolved "drone" "battery_voltage") $(genProvidersSingleUnresolved "drone" ["battery_voltage"]) $(genParserSingleUnresolved "drone" "battery_weight") $(genProvidersSingleUnresolved "drone" ["battery_weight"]) $(genParserSingleUnresolved "drone" "charging_temperature") $(genProvidersSingleUnresolved "drone" ["charging_temperature"]) $(genParserSingleUnresolved "drone" "max_charging_power") $(genProvidersSingleUnresolved "drone" ["max_charging_power"]) $(genParserSingleUnresolved "drone" "max_resolution") $(genProvidersSingleUnresolved "drone" ["max_resolution"]) resolveDroneText :: (MonadIO m, MonadThrow m) => FakerSettings -> AesonKey -> m Text resolveDroneText = genericResolver' resolveDroneField resolveDroneField :: (MonadThrow m, MonadIO m) => FakerSettings -> AesonKey -> m Text resolveDroneField settings str = throwM $ InvalidField "drone" str
294f15e14dc05b15a6fb6030d89943ee4576ab83fb31b3a01301283c154fb7d6
ta0kira/zeolite
Mergeable.hs
----------------------------------------------------------------------------- Copyright 2019 - 2020 under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . ----------------------------------------------------------------------------- Copyright 2019-2020 Kevin P. Barry Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ----------------------------------------------------------------------------- -} Author : [ ] # LANGUAGE FlexibleInstances # {-# LANGUAGE Safe #-} # LANGUAGE TypeFamilies # module Base.Mergeable ( Mergeable(..), PreserveMerge(..), (<||>), (<&&>), ) where import Data.Map as Map hiding (foldr) class Mergeable a where mergeAny :: Foldable f => f a -> a mergeAll :: Foldable f => f a -> a class (Bounded a, Mergeable a) => PreserveMerge a where type T a :: * convertMerge :: Mergeable b => (T a -> b) -> a -> b (<||>) :: Mergeable a => a -> a -> a (<||>) x y = mergeAny [x,y] infixl 2 <||> (<&&>) :: Mergeable a => a -> a -> a (<&&>) x y = mergeAll [x,y] infixl 2 <&&> instance Mergeable Bool where mergeAny = foldr (||) False mergeAll = foldr (&&) True instance (Ord k, Mergeable a) => Mergeable (Map k a) where mergeAny = Map.fromListWith (<||>) . foldr ((++) . Map.toList) [] mergeAll = Map.fromListWith (<&&>) . foldr ((++) . Map.toList) []
null
https://raw.githubusercontent.com/ta0kira/zeolite/6741e1fa38bdb7feaad10780290275cd5282fcbc/src/Base/Mergeable.hs
haskell
--------------------------------------------------------------------------- --------------------------------------------------------------------------- --------------------------------------------------------------------------- -} # LANGUAGE Safe #
Copyright 2019 - 2020 under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright 2019-2020 Kevin P. Barry Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Author : [ ] # LANGUAGE FlexibleInstances # # LANGUAGE TypeFamilies # module Base.Mergeable ( Mergeable(..), PreserveMerge(..), (<||>), (<&&>), ) where import Data.Map as Map hiding (foldr) class Mergeable a where mergeAny :: Foldable f => f a -> a mergeAll :: Foldable f => f a -> a class (Bounded a, Mergeable a) => PreserveMerge a where type T a :: * convertMerge :: Mergeable b => (T a -> b) -> a -> b (<||>) :: Mergeable a => a -> a -> a (<||>) x y = mergeAny [x,y] infixl 2 <||> (<&&>) :: Mergeable a => a -> a -> a (<&&>) x y = mergeAll [x,y] infixl 2 <&&> instance Mergeable Bool where mergeAny = foldr (||) False mergeAll = foldr (&&) True instance (Ord k, Mergeable a) => Mergeable (Map k a) where mergeAny = Map.fromListWith (<||>) . foldr ((++) . Map.toList) [] mergeAll = Map.fromListWith (<&&>) . foldr ((++) . Map.toList) []
d50c9d13315de3115ad1a1c864068c64739458de680a58551ab209dac6a82edf
shiguredo/swidden
swidden_client.erl
-module(swidden_client). -export([request/5, request/6]). -export([request_with_headers/6, request_with_headers/7]). Host は 127.0.0.1 固定にする request(Port, Target, Service, Version, Operation) -> request0(Port, [], Target, Service, Version, Operation, []). request(Port, Target, Service, Version, Operation, Json) -> RawJson = jsone:encode(Json), request0(Port, [], Target, Service, Version, Operation, RawJson). request_with_headers(Port, Headers, Target, Service, Version, Operation) -> request0(Port, Headers, Target, Service, Version, Operation, []). request_with_headers(Port, Headers, Target, Service, Version, Operation, Json) -> RawJson = jsone:encode(Json), request0(Port, Headers, Target, Service, Version, Operation, RawJson). request0(Port, Headers, Target, Service, Version, Operation, RawJson) when is_integer(Port) -> request0(integer_to_binary(Port), Headers, Target, Service, Version, Operation, RawJson); request0(RawPort, Headers0, Target, Service, Version, Operation, RawJson) -> URL = <<"", $:, RawPort/binary, $/>>, Headers = [{Target, list_to_binary([Service, $_, Version, $., Operation])}|Headers0], Options = [{pool, false}], case hackney:post(URL, Headers, RawJson, Options) of {ok, StatusCode, _RespHeaders, ClientRef} when StatusCode =:= 200 orelse StatusCode =:= 400 orelse StatusCode =:= 403 -> case hackney:body(ClientRef) of {ok, <<>>} -> hackney:close(ClientRef), {ok, StatusCode}; {ok, Body} -> hackney:close(ClientRef), {ok, StatusCode, jsone:decode(Body)} end; {ok, StatusCode, _RespHeaders, ClientRef} -> hackney:close(ClientRef), {error, {status_code, StatusCode}}; {error, Reason} -> {error, Reason} end.
null
https://raw.githubusercontent.com/shiguredo/swidden/faec93ae6b6c9e59840f0df22c5f72e381b54c02/src/swidden_client.erl
erlang
-module(swidden_client). -export([request/5, request/6]). -export([request_with_headers/6, request_with_headers/7]). Host は 127.0.0.1 固定にする request(Port, Target, Service, Version, Operation) -> request0(Port, [], Target, Service, Version, Operation, []). request(Port, Target, Service, Version, Operation, Json) -> RawJson = jsone:encode(Json), request0(Port, [], Target, Service, Version, Operation, RawJson). request_with_headers(Port, Headers, Target, Service, Version, Operation) -> request0(Port, Headers, Target, Service, Version, Operation, []). request_with_headers(Port, Headers, Target, Service, Version, Operation, Json) -> RawJson = jsone:encode(Json), request0(Port, Headers, Target, Service, Version, Operation, RawJson). request0(Port, Headers, Target, Service, Version, Operation, RawJson) when is_integer(Port) -> request0(integer_to_binary(Port), Headers, Target, Service, Version, Operation, RawJson); request0(RawPort, Headers0, Target, Service, Version, Operation, RawJson) -> URL = <<"", $:, RawPort/binary, $/>>, Headers = [{Target, list_to_binary([Service, $_, Version, $., Operation])}|Headers0], Options = [{pool, false}], case hackney:post(URL, Headers, RawJson, Options) of {ok, StatusCode, _RespHeaders, ClientRef} when StatusCode =:= 200 orelse StatusCode =:= 400 orelse StatusCode =:= 403 -> case hackney:body(ClientRef) of {ok, <<>>} -> hackney:close(ClientRef), {ok, StatusCode}; {ok, Body} -> hackney:close(ClientRef), {ok, StatusCode, jsone:decode(Body)} end; {ok, StatusCode, _RespHeaders, ClientRef} -> hackney:close(ClientRef), {error, {status_code, StatusCode}}; {error, Reason} -> {error, Reason} end.
88678d63cf17d02df82c9b1e440aaa88bbc39e3ee0f8d9c6e2d2962091af3305
orx/ocaml-orx
body.ml
include Orx_gen.Body let get_parts (body : t) : Body_part.t Seq.t = let rec iter prev_part () = match get_next_part body prev_part with | None -> Seq.Nil | Some next as part -> Seq.Cons (next, iter part) in iter None
null
https://raw.githubusercontent.com/orx/ocaml-orx/ce3be01870b04a1498dbb24bbe4ad0f13d36615c/src/lib/body.ml
ocaml
include Orx_gen.Body let get_parts (body : t) : Body_part.t Seq.t = let rec iter prev_part () = match get_next_part body prev_part with | None -> Seq.Nil | Some next as part -> Seq.Cons (next, iter part) in iter None
1c038b7f3ecd8c201e970cba3e767fe9071044611b884bbcf3746ff7f5d18fcd
input-output-hk/marlowe-cardano
revenue-based-loan.hs
{-# LANGUAGE OverloadedStrings #-} module RevenueBasedLoan where import Language.Marlowe.Extended.V1 main :: IO () main = printJSON $ contract djed :: Token djed = Token "f4cf384ddd1b1377b08302b17990e9618b62924f5705458c17ee4f7d" "DjedUSD" lender :: Party lender = Role "Lender" borrower :: Party borrower = Role "Borrower" oracle :: Party oracle = Role "Revenue Oracle" revenueChoice :: ChoiceId revenueChoice = ChoiceId "Revenue" oracle revenueValue :: Value revenueValue = ChoiceValue revenueChoice revenueBounds :: Bound revenueBounds = Bound 1 1000000 principal :: Value principal = ConstantParam "Principal" interest :: Value interest = ConstantParam "Interest" paymentPercent :: Value paymentPercent = ConstantParam "Payment as Percent of Revenue" remainingDue :: Value remainingDue = UseValue "Remaining Due" nextPayment :: Value nextPayment = UseValue "Next Payment" makePayment :: Int -> Contract -> Contract makePayment period continuation = When [ Case (Choice revenueChoice [revenueBounds]) $ Let "Next Payment" (DivValue (MulValue revenueValue paymentPercent) (Constant 100)) $ If (nextPayment `ValueGT` remainingDue) ( When [ Case (Deposit lender borrower djed remainingDue) $ Pay lender (Party lender) djed remainingDue Close ] (TimeParam $ "Deadline " <> show period <> " for Payment") continuation ) ( When [ Case (Deposit lender borrower djed nextPayment) $ Pay lender (Party lender) djed nextPayment $ Let "Remaining Due" (SubValue remainingDue nextPayment) continuation ] (TimeParam $ "Deadline " <> show period <> " for Payment") continuation ) ] (TimeParam $ "Deadline " <> show period <> " for Oracle") continuation collectRemainder :: Contract collectRemainder = When [ Case (Deposit lender borrower djed remainingDue) Close ] (TimeParam "End of Contract") Close contract :: Contract contract = When [ Case (Deposit lender lender djed principal) $ Pay lender (Party borrower) djed principal $ Let "Remaining Due" (AddValue principal interest) $ foldr makePayment collectRemainder [1..5] ] (TimeParam "Loan Deadline") Close
null
https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/78a3dbb1cd692146b7d1a32e1e66faed884f2432/marlowe-cli/cookbook/revenue-based-loan.hs
haskell
# LANGUAGE OverloadedStrings #
module RevenueBasedLoan where import Language.Marlowe.Extended.V1 main :: IO () main = printJSON $ contract djed :: Token djed = Token "f4cf384ddd1b1377b08302b17990e9618b62924f5705458c17ee4f7d" "DjedUSD" lender :: Party lender = Role "Lender" borrower :: Party borrower = Role "Borrower" oracle :: Party oracle = Role "Revenue Oracle" revenueChoice :: ChoiceId revenueChoice = ChoiceId "Revenue" oracle revenueValue :: Value revenueValue = ChoiceValue revenueChoice revenueBounds :: Bound revenueBounds = Bound 1 1000000 principal :: Value principal = ConstantParam "Principal" interest :: Value interest = ConstantParam "Interest" paymentPercent :: Value paymentPercent = ConstantParam "Payment as Percent of Revenue" remainingDue :: Value remainingDue = UseValue "Remaining Due" nextPayment :: Value nextPayment = UseValue "Next Payment" makePayment :: Int -> Contract -> Contract makePayment period continuation = When [ Case (Choice revenueChoice [revenueBounds]) $ Let "Next Payment" (DivValue (MulValue revenueValue paymentPercent) (Constant 100)) $ If (nextPayment `ValueGT` remainingDue) ( When [ Case (Deposit lender borrower djed remainingDue) $ Pay lender (Party lender) djed remainingDue Close ] (TimeParam $ "Deadline " <> show period <> " for Payment") continuation ) ( When [ Case (Deposit lender borrower djed nextPayment) $ Pay lender (Party lender) djed nextPayment $ Let "Remaining Due" (SubValue remainingDue nextPayment) continuation ] (TimeParam $ "Deadline " <> show period <> " for Payment") continuation ) ] (TimeParam $ "Deadline " <> show period <> " for Oracle") continuation collectRemainder :: Contract collectRemainder = When [ Case (Deposit lender borrower djed remainingDue) Close ] (TimeParam "End of Contract") Close contract :: Contract contract = When [ Case (Deposit lender lender djed principal) $ Pay lender (Party borrower) djed principal $ Let "Remaining Due" (AddValue principal interest) $ foldr makePayment collectRemainder [1..5] ] (TimeParam "Loan Deadline") Close
c4da2b7d51d8b1e40c75961d746a42d858bb36b4f51a4de476f958fc714d651d
czan/stateful-check
java_queue_test.clj
(ns stateful-check.java-queue-test (:refer-clojure :exclude [peek pop count]) (:require [clojure.test :refer :all] [clojure.test.check.generators :as gen] [stateful-check.core :refer :all]) (:import [java.util.concurrent ArrayBlockingQueue])) (defprotocol Queue (push [this val]) (peek [this]) (pop [this]) (count [this])) (deftype ArrayQueue [buffer ^:volatile-mutable read-i ^:volatile-mutable write-i] Queue (push [this val] (aset buffer write-i val) (set! write-i (mod (inc write-i) (alength buffer))) this) (peek [this] (aget buffer read-i)) (pop [this] (let [val (aget buffer read-i)] (set! read-i (mod (inc read-i) (alength buffer))) val)) (count [this] (mod (- write-i read-i) (alength buffer)))) (def array (atom clojure.lang.PersistentQueue/EMPTY)) (deftype SharedArrayQueue [length] Queue (push [this val] (let [add (fn [q v] (let [result (conj q v)] (if (> (clojure.core/count result) length) (clojure.core/pop result) result)))] (swap! array add val)) this) (peek [this] (clojure.core/peek @array)) (pop [this] (let [val (clojure.core/peek @array)] (swap! array clojure.core/pop) val)) (count [this] (clojure.core/count @array))) (defn new-shared-queue [n] (reset! array clojure.lang.PersistentQueue/EMPTY) (SharedArrayQueue. n)) (defn new-array-queue [n] (ArrayQueue. (int-array (inc n)) 0 0)) ;; ;; Generative testing commands ;; (def new-shared-queue-command {:args (fn [_] [gen/nat]) :precondition (fn [_ [size]] (pos? size)) :command #'new-shared-queue :next-state (fn [state [size] queue] (assoc state queue {:elements [] :size size}))}) (def new-array-queue-command {:args (fn [_] [gen/nat]) :precondition (fn [_ [size]] (pos? size)) :command #'new-array-queue :next-state (fn [state [size] queue] (assoc state queue {:elements [] :size size}))}) (def push-queue-command {:requires (complement nil?) :args (fn [state] [(gen/elements (keys state)) gen/nat]) :precondition (fn [state [queue _]] (let [{:keys [elements size]} (get state queue)] (< (clojure.core/count elements) size))) :command #'push :next-state (fn [state [queue val] _] (update-in state [queue :elements] conj val))}) (def peek-queue-command {:requires (complement nil?) :args (fn [state] [(gen/elements (keys state))]) :precondition (fn [state [queue]] (seq (get-in state [queue :elements]))) :command #'peek :postcondition (fn [state _ [queue] val] (= val (first (get-in state [queue :elements]))))}) (def pop-queue-command {:requires (complement nil?) :args (fn [state] [(gen/elements (keys state))]) :precondition (fn [state [queue]] (seq (get-in state [queue :elements]))) :command #'pop :next-state (fn [state [queue] _] (update-in state [queue :elements] (comp vec next))) :postcondition (fn [state _ [queue] val] (= val (first (get-in state [queue :elements]))))}) (def count-queue-command {:requires (complement nil?) :args (fn [state] [(gen/elements (keys state))]) :command #'count :postcondition (fn [state _ [queue] val] (= val (clojure.core/count (get-in state [queue :elements]))))}) ;; ;; Generative testing specification ;; (def shared-queue-specification {:commands {:new #'new-shared-queue-command :push #'push-queue-command :peek #'peek-queue-command :pop #'pop-queue-command :count #'count-queue-command} :setup #(reset! array clojure.lang.PersistentQueue/EMPTY) :generate-command (fn [state] (if (nil? state) (gen/return :new) (gen/frequency [[1 (gen/return :new)] [5 (gen/return :push)] [5 (gen/return :peek)] [5 (gen/return :pop)] [5 (gen/return :count)]])))}) (def array-queue-specification {:commands {:new #'new-array-queue-command :push #'push-queue-command :peek #'peek-queue-command :pop #'pop-queue-command :count #'count-queue-command} :generate-command (fn [state] (if (nil? state) (gen/return :new) (gen/frequency [[1 (gen/return :new)] [5 (gen/return :push)] [5 (gen/return :peek)] [5 (gen/return :pop)] [5 (gen/return :count)]])))}) (deftest shared-queue-test (is (not (specification-correct? shared-queue-specification)))) (deftest array-queue-test (is (specification-correct? array-queue-specification)))
null
https://raw.githubusercontent.com/czan/stateful-check/f7a369c9306d17849981283ac04f5a524db5745f/test/stateful_check/java_queue_test.clj
clojure
Generative testing commands Generative testing specification
(ns stateful-check.java-queue-test (:refer-clojure :exclude [peek pop count]) (:require [clojure.test :refer :all] [clojure.test.check.generators :as gen] [stateful-check.core :refer :all]) (:import [java.util.concurrent ArrayBlockingQueue])) (defprotocol Queue (push [this val]) (peek [this]) (pop [this]) (count [this])) (deftype ArrayQueue [buffer ^:volatile-mutable read-i ^:volatile-mutable write-i] Queue (push [this val] (aset buffer write-i val) (set! write-i (mod (inc write-i) (alength buffer))) this) (peek [this] (aget buffer read-i)) (pop [this] (let [val (aget buffer read-i)] (set! read-i (mod (inc read-i) (alength buffer))) val)) (count [this] (mod (- write-i read-i) (alength buffer)))) (def array (atom clojure.lang.PersistentQueue/EMPTY)) (deftype SharedArrayQueue [length] Queue (push [this val] (let [add (fn [q v] (let [result (conj q v)] (if (> (clojure.core/count result) length) (clojure.core/pop result) result)))] (swap! array add val)) this) (peek [this] (clojure.core/peek @array)) (pop [this] (let [val (clojure.core/peek @array)] (swap! array clojure.core/pop) val)) (count [this] (clojure.core/count @array))) (defn new-shared-queue [n] (reset! array clojure.lang.PersistentQueue/EMPTY) (SharedArrayQueue. n)) (defn new-array-queue [n] (ArrayQueue. (int-array (inc n)) 0 0)) (def new-shared-queue-command {:args (fn [_] [gen/nat]) :precondition (fn [_ [size]] (pos? size)) :command #'new-shared-queue :next-state (fn [state [size] queue] (assoc state queue {:elements [] :size size}))}) (def new-array-queue-command {:args (fn [_] [gen/nat]) :precondition (fn [_ [size]] (pos? size)) :command #'new-array-queue :next-state (fn [state [size] queue] (assoc state queue {:elements [] :size size}))}) (def push-queue-command {:requires (complement nil?) :args (fn [state] [(gen/elements (keys state)) gen/nat]) :precondition (fn [state [queue _]] (let [{:keys [elements size]} (get state queue)] (< (clojure.core/count elements) size))) :command #'push :next-state (fn [state [queue val] _] (update-in state [queue :elements] conj val))}) (def peek-queue-command {:requires (complement nil?) :args (fn [state] [(gen/elements (keys state))]) :precondition (fn [state [queue]] (seq (get-in state [queue :elements]))) :command #'peek :postcondition (fn [state _ [queue] val] (= val (first (get-in state [queue :elements]))))}) (def pop-queue-command {:requires (complement nil?) :args (fn [state] [(gen/elements (keys state))]) :precondition (fn [state [queue]] (seq (get-in state [queue :elements]))) :command #'pop :next-state (fn [state [queue] _] (update-in state [queue :elements] (comp vec next))) :postcondition (fn [state _ [queue] val] (= val (first (get-in state [queue :elements]))))}) (def count-queue-command {:requires (complement nil?) :args (fn [state] [(gen/elements (keys state))]) :command #'count :postcondition (fn [state _ [queue] val] (= val (clojure.core/count (get-in state [queue :elements]))))}) (def shared-queue-specification {:commands {:new #'new-shared-queue-command :push #'push-queue-command :peek #'peek-queue-command :pop #'pop-queue-command :count #'count-queue-command} :setup #(reset! array clojure.lang.PersistentQueue/EMPTY) :generate-command (fn [state] (if (nil? state) (gen/return :new) (gen/frequency [[1 (gen/return :new)] [5 (gen/return :push)] [5 (gen/return :peek)] [5 (gen/return :pop)] [5 (gen/return :count)]])))}) (def array-queue-specification {:commands {:new #'new-array-queue-command :push #'push-queue-command :peek #'peek-queue-command :pop #'pop-queue-command :count #'count-queue-command} :generate-command (fn [state] (if (nil? state) (gen/return :new) (gen/frequency [[1 (gen/return :new)] [5 (gen/return :push)] [5 (gen/return :peek)] [5 (gen/return :pop)] [5 (gen/return :count)]])))}) (deftest shared-queue-test (is (not (specification-correct? shared-queue-specification)))) (deftest array-queue-test (is (specification-correct? array-queue-specification)))
acbf73089cc4a23c716f813e508a82f97cece579a8f06a6074708907234a22e8
maximedenes/native-coq
obligations.ml
open Printf open Pp open Environ open Term open Names open Libnames open Summary open Libobject open Entries open Decl_kinds open Errors open Util open Evd open Declare open Proof_type open Compat * - Get types of existentials ; - Flatten dependency tree ( prefix order ) ; - Replace existentials by indices in term , applied to the right arguments ; - Apply term prefixed by quantification on " existentials " . - Get types of existentials ; - Flatten dependency tree (prefix order) ; - Replace existentials by De Bruijn indices in term, applied to the right arguments ; - Apply term prefixed by quantification on "existentials". *) open Term open Sign open Names open Evd open List open Pp open Errors open Util open Proof_type let declare_fix_ref = ref (fun _ _ _ _ _ -> assert false) let declare_definition_ref = ref (fun _ _ _ _ _ -> assert false) let trace s = if !Flags.debug then (msgnl s; msgerr s) else () let succfix (depth, fixrels) = (succ depth, List.map succ fixrels) let mkMetas n = list_tabulate (fun _ -> Evarutil.mk_new_meta ()) n let check_evars env evm = List.iter (fun (key, evi) -> let (loc,k) = evar_source key evm in match k with | QuestionMark _ | ImplicitArg (_,_,false) -> () | _ -> Pretype_errors.error_unsolvable_implicit loc env evm (Evarutil.nf_evar_info evm evi) k None) (Evd.undefined_list evm) type oblinfo = { ev_name: int * identifier; ev_hyps: named_context; ev_status: obligation_definition_status; ev_chop: int option; ev_src: hole_kind located; ev_typ: types; ev_tac: tactic option; ev_deps: Intset.t } (* spiwack: Store field for internalizing ev_tac in evar_infos' evar_extra. *) open Store.Field let evar_tactic = Store.field () * Substitute evar references in t using indices , where n binders were passed through . where n binders were passed through. *) let subst_evar_constr evs n idf t = let seen = ref Intset.empty in let transparent = ref Idset.empty in let evar_info id = List.assoc id evs in let rec substrec (depth, fixrels) c = match kind_of_term c with | Evar (k, args) -> let { ev_name = (id, idstr) ; ev_hyps = hyps ; ev_chop = chop } = try evar_info k with Not_found -> anomaly ("eterm: existential variable " ^ string_of_int k ^ " not found") in seen := Intset.add id !seen; Evar arguments are created in inverse order , and we must not apply to defined ones ( i.e. 's ) and we must not apply to defined ones (i.e. LetIn's) *) let args = let n = match chop with None -> 0 | Some c -> c in let (l, r) = list_chop n (List.rev (Array.to_list args)) in List.rev r in let args = let rec aux hyps args acc = match hyps, args with ((_, None, _) :: tlh), (c :: tla) -> aux tlh tla ((substrec (depth, fixrels) c) :: acc) | ((_, Some _, _) :: tlh), (_ :: tla) -> aux tlh tla acc | [], [] -> acc failwith " subst_evars : invalid argument " in aux hyps args [] in if List.exists (fun x -> match kind_of_term x with Rel n -> List.mem n fixrels | _ -> false) args then transparent := Idset.add idstr !transparent; mkApp (idf idstr, Array.of_list args) | Fix _ -> map_constr_with_binders succfix substrec (depth, 1 :: fixrels) c | _ -> map_constr_with_binders succfix substrec (depth, fixrels) c in let t' = substrec (0, []) t in t', !seen, !transparent * Substitute variable references in t using indices , where n binders were passed through . where n binders were passed through. *) let subst_vars acc n t = let var_index id = Util.list_index id acc in let rec substrec depth c = match kind_of_term c with | Var v -> (try mkRel (depth + (var_index v)) with Not_found -> c) | _ -> map_constr_with_binders succ substrec depth c in substrec 0 t * Rewrite type of an evar ( [ H1 : t1 , ... Hn : tn ] ) to a product : forall H1 : t1 , ... , forall Hn : tn , . Changes evars and hypothesis references to variable references . to a product : forall H1 : t1, ..., forall Hn : tn, concl. Changes evars and hypothesis references to variable references. *) let etype_of_evar evs hyps concl = let rec aux acc n = function (id, copt, t) :: tl -> let t', s, trans = subst_evar_constr evs n mkVar t in let t'' = subst_vars acc 0 t' in let rest, s', trans' = aux (id :: acc) (succ n) tl in let s' = Intset.union s s' in let trans' = Idset.union trans trans' in (match copt with Some c -> let c', s'', trans'' = subst_evar_constr evs n mkVar c in let c' = subst_vars acc 0 c' in mkNamedProd_or_LetIn (id, Some c', t'') rest, Intset.union s'' s', Idset.union trans'' trans' | None -> mkNamedProd_or_LetIn (id, None, t'') rest, s', trans') | [] -> let t', s, trans = subst_evar_constr evs n mkVar concl in subst_vars acc 0 t', s, trans in aux [] 0 (rev hyps) open Tacticals let trunc_named_context n ctx = let len = List.length ctx in list_firstn (len - n) ctx let rec chop_product n t = if n = 0 then Some t else match kind_of_term t with | Prod (_, _, b) -> if noccurn 1 b then chop_product (pred n) (Termops.pop b) else None | _ -> None let evars_of_evar_info evi = Intset.union (Evarutil.evars_of_term evi.evar_concl) (Intset.union (match evi.evar_body with | Evar_empty -> Intset.empty | Evar_defined b -> Evarutil.evars_of_term b) (Evarutil.evars_of_named_context (evar_filtered_context evi))) let evar_dependencies evm oev = let one_step deps = Intset.fold (fun ev s -> let evi = Evd.find evm ev in let deps' = evars_of_evar_info evi in if Intset.mem oev deps' then raise (Invalid_argument ("Ill-formed evar map: cycle detected for evar " ^ string_of_int oev)) else Intset.union deps' s) deps deps in let rec aux deps = let deps' = one_step deps in if Intset.equal deps deps' then deps else aux deps' in aux (Intset.singleton oev) let move_after (id, ev, deps as obl) l = let rec aux restdeps = function | (id', _, _) as obl' :: tl -> let restdeps' = Intset.remove id' restdeps in if Intset.is_empty restdeps' then obl' :: obl :: tl else obl' :: aux restdeps' tl | [] -> [obl] in aux (Intset.remove id deps) l let sort_dependencies evl = let rec aux l found list = match l with | (id, ev, deps) as obl :: tl -> let found' = Intset.union found (Intset.singleton id) in if Intset.subset deps found' then aux tl found' (obl :: list) else aux (move_after obl tl) found list | [] -> List.rev list in aux evl Intset.empty [] let map_evar_body f = function | Evar_empty -> Evar_empty | Evar_defined c -> Evar_defined (f c) open Environ let map_evar_info f evi = { evi with evar_hyps = val_of_named_context (map_named_context f (named_context_of_val evi.evar_hyps)); evar_concl = f evi.evar_concl; evar_body = map_evar_body f evi.evar_body } let eterm_obligations env name evm fs ?status t ty = ' Serialize ' the evars let nc = Environ.named_context env in let nc_len = Sign.named_context_length nc in let evm = Evarutil.nf_evar_map_undefined evm in let evl = List.rev (Evarutil.non_instantiated evm) in let evl = List.map (fun (id, ev) -> (id, ev, evar_dependencies evm id)) evl in let sevl = sort_dependencies evl in let evl = List.map (fun (id, ev, _) -> id, ev) sevl in let evn = let i = ref (-1) in List.rev_map (fun (id, ev) -> incr i; (id, (!i, id_of_string (string_of_id name ^ "_obligation_" ^ string_of_int (succ !i))), ev)) evl in let evts = (* Remove existential variables in types and build the corresponding products *) fold_right (fun (id, (n, nstr), ev) l -> let hyps = Evd.evar_filtered_context ev in let hyps = trunc_named_context nc_len hyps in let evtyp, deps, transp = etype_of_evar l hyps ev.evar_concl in let evtyp, hyps, chop = match chop_product fs evtyp with | Some t -> t, trunc_named_context fs hyps, fs | None -> evtyp, hyps, 0 in let loc, k = evar_source id evm in let status = match k with QuestionMark o -> Some o | _ -> status in let status, chop = match status with | Some (Define true as stat) -> if chop <> fs then Define false, None else stat, Some chop | Some s -> s, None | None -> Define true, None in let tac = match evar_tactic.get ev.evar_extra with | Some t -> if Dyn.tag t = "tactic" then Some (Tacinterp.interp (Tacinterp.globTacticIn (Tacinterp.tactic_out t))) else None | None -> None in let info = { ev_name = (n, nstr); ev_hyps = hyps; ev_status = status; ev_chop = chop; ev_src = loc, k; ev_typ = evtyp ; ev_deps = deps; ev_tac = tac } in (id, info) :: l) evn [] in let t', _, transparent = (* Substitute evar refs in the term by variables *) subst_evar_constr evts 0 mkVar t in let ty, _, _ = subst_evar_constr evts 0 mkVar ty in let evars = List.map (fun (ev, info) -> let { ev_name = (_, name); ev_status = status; ev_src = src; ev_typ = typ; ev_deps = deps; ev_tac = tac } = info in let status = match status with | Define true when Idset.mem name transparent -> Define false | _ -> status in name, typ, src, status, deps, tac) evts in let evnames = List.map (fun (ev, info) -> ev, snd info.ev_name) evts in let evmap f c = pi1 (subst_evar_constr evts 0 f c) in Array.of_list (List.rev evars), (evnames, evmap), t', ty let tactics_module = ["Program";"Tactics"] let safe_init_constant md name () = Coqlib.check_required_library ("Coq"::md); Coqlib.gen_constant "Obligations" md name let fix_proto = safe_init_constant tactics_module "fix_proto" let hide_obligation = safe_init_constant tactics_module "obligation" let ppwarn cmd = Pp.warn (str"Program:" ++ cmd) let pperror cmd = Errors.errorlabstrm "Program" cmd let error s = pperror (str s) let reduce c = Reductionops.clos_norm_flags Closure.betaiota (Global.env ()) Evd.empty c exception NoObligations of identifier option let explain_no_obligations = function Some ident -> str "No obligations for program " ++ str (string_of_id ident) | None -> str "No obligations remaining" type obligation_info = (Names.identifier * Term.types * hole_kind located * obligation_definition_status * Intset.t * tactic option) array type obligation = { obl_name : identifier; obl_type : types; obl_location : hole_kind located; obl_body : constr option; obl_status : obligation_definition_status; obl_deps : Intset.t; obl_tac : tactic option; } type obligations = (obligation array * int) type fixpoint_kind = | IsFixpoint of (identifier located option * Topconstr.recursion_order_expr) list | IsCoFixpoint type notations = (Vernacexpr.lstring * Topconstr.constr_expr * Topconstr.scope_name option) list type program_info = { prg_name: identifier; prg_body: constr; prg_type: constr; prg_obligations: obligations; prg_deps : identifier list; prg_fixkind : fixpoint_kind option ; prg_implicits : (Topconstr.explicitation * (bool * bool * bool)) list; prg_notations : notations ; prg_kind : definition_kind; prg_reduce : constr -> constr; prg_hook : unit Tacexpr.declaration_hook; } let assumption_message id = Flags.if_verbose message ((string_of_id id) ^ " is assumed") let (set_default_tactic, get_default_tactic, print_default_tactic) = Tactic_option.declare_tactic_option "Program tactic" (* true = All transparent, false = Opaque if possible *) let proofs_transparency = ref true let set_proofs_transparency = (:=) proofs_transparency let get_proofs_transparency () = !proofs_transparency open Goptions let _ = declare_bool_option { optsync = true; optdepr = false; optname = "transparency of Program obligations"; optkey = ["Transparent";"Obligations"]; optread = get_proofs_transparency; optwrite = set_proofs_transparency; } (* true = hide obligations *) let hide_obligations = ref false let set_hide_obligations = (:=) hide_obligations let get_hide_obligations () = !hide_obligations open Goptions let _ = declare_bool_option { optsync = true; optdepr = false; optname = "Hidding of Program obligations"; optkey = ["Hide";"Obligations"]; optread = get_hide_obligations; optwrite = set_hide_obligations; } let evar_of_obligation o = make_evar (Global.named_context_val ()) o.obl_type let get_obligation_body expand obl = let c = Option.get obl.obl_body in if expand && obl.obl_status = Expand then match kind_of_term c with | Const c -> constant_value (Global.env ()) c | _ -> c else c let obl_substitution expand obls deps = Intset.fold (fun x acc -> let xobl = obls.(x) in let oblb = try get_obligation_body expand xobl with _ -> assert(false) in (xobl.obl_name, (xobl.obl_type, oblb)) :: acc) deps [] let subst_deps expand obls deps t = let subst = obl_substitution expand obls deps in Term.replace_vars (List.map (fun (n, (_, b)) -> n, b) subst) t let rec prod_app t n = match kind_of_term (strip_outer_cast t) with | Prod (_,_,b) -> subst1 n b | LetIn (_, b, t, b') -> prod_app (subst1 b b') n | _ -> errorlabstrm "prod_app" (str"Needed a product, but didn't find one" ++ fnl ()) (* prod_appvect T [| a1 ; ... ; an |] -> (T a1 ... an) *) let prod_applist t nL = List.fold_left prod_app t nL let replace_appvars subst = let rec aux c = let f, l = decompose_app c in if isVar f then try let c' = List.map (map_constr aux) l in let (t, b) = List.assoc (destVar f) subst in mkApp (delayed_force hide_obligation, [| prod_applist t c'; applistc b c' |]) with Not_found -> map_constr aux c else map_constr aux c in map_constr aux let subst_prog expand obls ints prg = let subst = obl_substitution expand obls ints in if get_hide_obligations () then (replace_appvars subst prg.prg_body, replace_appvars subst (Termops.refresh_universes prg.prg_type)) else let subst' = List.map (fun (n, (_, b)) -> n, b) subst in (Term.replace_vars subst' prg.prg_body, Term.replace_vars subst' (Termops.refresh_universes prg.prg_type)) let subst_deps_obl obls obl = let t' = subst_deps true obls obl.obl_deps obl.obl_type in { obl with obl_type = t' } module ProgMap = Map.Make(struct type t = identifier let compare = compare end) let map_replace k v m = ProgMap.add k v (ProgMap.remove k m) let map_keys m = ProgMap.fold (fun k _ l -> k :: l) m [] let map_cardinal m = let i = ref 0 in ProgMap.iter (fun _ _ -> incr i) m; !i exception Found of program_info let map_first m = try ProgMap.iter (fun _ v -> raise (Found v)) m; assert(false) with Found x -> x let from_prg : program_info ProgMap.t ref = ref ProgMap.empty let freeze () = !from_prg let unfreeze v = from_prg := v let init () = from_prg := ProgMap.empty (** Beware: if this code is dynamically loaded via dynlink after the start of Coq, then this [init] function will not be run by [Lib.init ()]. Luckily, here we can launch [init] at load-time. *) let _ = init () let _ = Summary.declare_summary "program-tcc-table" { Summary.freeze_function = freeze; Summary.unfreeze_function = unfreeze; Summary.init_function = init } let progmap_union = ProgMap.fold ProgMap.add let close sec = if not (ProgMap.is_empty !from_prg) then let keys = map_keys !from_prg in errorlabstrm "Program" (str "Unsolved obligations when closing " ++ str sec ++ str":" ++ spc () ++ prlist_with_sep spc (fun x -> Nameops.pr_id x) keys ++ (str (if List.length keys = 1 then " has " else "have ") ++ str "unsolved obligations")) let input : program_info ProgMap.t -> obj = declare_object { (default_object "Program state") with cache_function = (fun (na, pi) -> from_prg := pi); load_function = (fun _ (_, pi) -> from_prg := pi); discharge_function = (fun _ -> close "section"; None); classify_function = (fun _ -> close "module"; Dispose) } open Evd let progmap_remove prg = Lib.add_anonymous_leaf (input (ProgMap.remove prg.prg_name !from_prg)) let progmap_add n prg = Lib.add_anonymous_leaf (input (ProgMap.add n prg !from_prg)) let progmap_replace prg' = Lib.add_anonymous_leaf (input (map_replace prg'.prg_name prg' !from_prg)) let rec intset_to = function -1 -> Intset.empty | n -> Intset.add n (intset_to (pred n)) let subst_body expand prg = let obls, _ = prg.prg_obligations in let ints = intset_to (pred (Array.length obls)) in subst_prog expand obls ints prg let declare_definition prg = let body, typ = subst_body true prg in let ce = { const_entry_body = body; const_entry_secctx = None; const_entry_type = Some typ; const_entry_opaque = false; const_entry_inline_code = false} in progmap_remove prg; !declare_definition_ref prg.prg_name prg.prg_kind ce prg.prg_implicits (fun local gr -> prg.prg_hook local gr; gr) open Pp open Ppconstr let rec lam_index n t acc = match kind_of_term t with | Lambda (na, _, b) -> if na = Name n then acc else lam_index n b (succ acc) | _ -> raise Not_found let compute_possible_guardness_evidences (n,_) fixbody fixtype = match n with | Some (loc, n) -> [lam_index n fixbody 0] | None -> (* If recursive argument was not given by user, we try all args. An earlier approach was to look only for inductive arguments, but doing it properly involves delta-reduction, and it finally doesn't seem to worth the effort (except for huge mutual fixpoints ?) *) let m = Term.nb_prod fixtype in let ctx = fst (decompose_prod_n_assum m fixtype) in list_map_i (fun i _ -> i) 0 ctx let declare_mutual_definition l = let len = List.length l in let first = List.hd l in let fixdefs, fixtypes, fiximps = list_split3 (List.map (fun x -> let subs, typ = (subst_body true x) in let term = snd (Reductionops.splay_lam_n (Global.env ()) Evd.empty len subs) in let typ = snd (Reductionops.splay_prod_n (Global.env ()) Evd.empty len typ) in x.prg_reduce term, x.prg_reduce typ, x.prg_implicits) l) in let fixdefs = List.map reduce_fix fixdefs in let fixkind = Option.get first.prg_fixkind in let arrrec, recvec = Array.of_list fixtypes, Array.of_list fixdefs in let fixdecls = (Array.of_list (List.map (fun x -> Name x.prg_name) l), arrrec, recvec) in let (local,kind) = first.prg_kind in let fixnames = first.prg_deps in let kind = if fixkind <> IsCoFixpoint then Fixpoint else CoFixpoint in let indexes, fixdecls = match fixkind with | IsFixpoint wfl -> let possible_indexes = list_map3 compute_possible_guardness_evidences wfl fixdefs fixtypes in let indexes = Pretyping.search_guard dummy_loc (Global.env ()) possible_indexes fixdecls in Some indexes, list_map_i (fun i _ -> mkFix ((indexes,i),fixdecls)) 0 l | IsCoFixpoint -> None, list_map_i (fun i _ -> mkCoFix (i,fixdecls)) 0 l in (* Declare the recursive definitions *) let kns = list_map4 (!declare_fix_ref kind) fixnames fixdecls fixtypes fiximps in (* Declare notations *) List.iter Metasyntax.add_notation_interpretation first.prg_notations; Declare.recursive_message (fixkind<>IsCoFixpoint) indexes fixnames; let gr = List.hd kns in let kn = match gr with ConstRef kn -> kn | _ -> assert false in first.prg_hook local gr; List.iter progmap_remove l; kn let declare_obligation prg obl body = let body = prg.prg_reduce body in let ty = prg.prg_reduce obl.obl_type in match obl.obl_status with | Expand -> { obl with obl_body = Some body } | Define opaque -> let opaque = if get_proofs_transparency () then false else opaque in let ce = { const_entry_body = body; const_entry_secctx = None; const_entry_type = Some ty; const_entry_opaque = opaque; const_entry_inline_code = false} in let constant = Declare.declare_constant obl.obl_name (DefinitionEntry ce,IsProof Property) in if not opaque then Auto.add_hints false [string_of_id prg.prg_name] (Auto.HintsUnfoldEntry [EvalConstRef constant]); definition_message obl.obl_name; { obl with obl_body = Some (mkConst constant) } let init_prog_info n b t deps fixkind notations obls impls kind reduce hook = let obls', b = match b with | None -> assert(obls = [||]); let n = Nameops.add_suffix n "_obligation" in [| { obl_name = n; obl_body = None; obl_location = dummy_loc, InternalHole; obl_type = t; obl_status = Expand; obl_deps = Intset.empty; obl_tac = None } |], mkVar n | Some b -> Array.mapi (fun i (n, t, l, o, d, tac) -> { obl_name = n ; obl_body = None; obl_location = l; obl_type = reduce t; obl_status = o; obl_deps = d; obl_tac = tac }) obls, b in { prg_name = n ; prg_body = b; prg_type = reduce t; prg_obligations = (obls', Array.length obls'); prg_deps = deps; prg_fixkind = fixkind ; prg_notations = notations ; prg_implicits = impls; prg_kind = kind; prg_reduce = reduce; prg_hook = hook; } let get_prog name = let prg_infos = !from_prg in match name with Some n -> (try ProgMap.find n prg_infos with Not_found -> raise (NoObligations (Some n))) | None -> (let n = map_cardinal prg_infos in match n with 0 -> raise (NoObligations None) | 1 -> map_first prg_infos | _ -> error "More than one program with unsolved obligations") let get_prog_err n = try get_prog n with NoObligations id -> pperror (explain_no_obligations id) let obligations_solved prg = (snd prg.prg_obligations) = 0 let all_programs () = ProgMap.fold (fun k p l -> p :: l) !from_prg [] type progress = | Remain of int | Dependent | Defined of global_reference let obligations_message rem = if rem > 0 then if rem = 1 then Flags.if_verbose msgnl (int rem ++ str " obligation remaining") else Flags.if_verbose msgnl (int rem ++ str " obligations remaining") else Flags.if_verbose msgnl (str "No more obligations remaining") let update_obls prg obls rem = let prg' = { prg with prg_obligations = (obls, rem) } in progmap_replace prg'; obligations_message rem; if rem > 0 then Remain rem else ( match prg'.prg_deps with | [] -> let kn = declare_definition prg' in progmap_remove prg'; Defined kn | l -> let progs = List.map (fun x -> ProgMap.find x !from_prg) prg'.prg_deps in if List.for_all (fun x -> obligations_solved x) progs then let kn = declare_mutual_definition progs in Defined (ConstRef kn) else Dependent) let is_defined obls x = obls.(x).obl_body <> None let deps_remaining obls deps = Intset.fold (fun x acc -> if is_defined obls x then acc else x :: acc) deps [] let dependencies obls n = let res = ref Intset.empty in Array.iteri (fun i obl -> if i <> n && Intset.mem n obl.obl_deps then res := Intset.add i !res) obls; !res let global_kind = Decl_kinds.IsDefinition Decl_kinds.Definition let goal_kind = Decl_kinds.Global, Decl_kinds.DefinitionBody Decl_kinds.Definition let global_proof_kind = Decl_kinds.IsProof Decl_kinds.Lemma let goal_proof_kind = Decl_kinds.Global, Decl_kinds.Proof Decl_kinds.Lemma let global_fix_kind = Decl_kinds.IsDefinition Decl_kinds.Fixpoint let goal_fix_kind = Decl_kinds.Global, Decl_kinds.DefinitionBody Decl_kinds.Fixpoint let kind_of_opacity o = match o with | Define false | Expand -> goal_kind | _ -> goal_proof_kind let not_transp_msg = str "Obligation should be transparent but was declared opaque." ++ spc () ++ str"Use 'Defined' instead." let warn_not_transp () = ppwarn not_transp_msg let error_not_transp () = pperror not_transp_msg let rec string_of_list sep f = function [] -> "" | x :: [] -> f x | x :: ((y :: _) as tl) -> f x ^ sep ^ string_of_list sep f tl (* Solve an obligation using tactics, return the corresponding proof term *) let solve_by_tac evi t = let id = id_of_string "H" in try Pfedit.start_proof id goal_kind evi.evar_hyps evi.evar_concl (fun _ _ -> ()); Pfedit.by (tclCOMPLETE t); let _,(const,_,_,_) = Pfedit.cook_proof ignore in Pfedit.delete_current_proof (); Inductiveops.control_only_guard (Global.env ()) const.Entries.const_entry_body; const.Entries.const_entry_body with e -> Pfedit.delete_current_proof(); raise e let rec solve_obligation prg num tac = let user_num = succ num in let obls, rem = prg.prg_obligations in let obl = obls.(num) in if obl.obl_body <> None then pperror (str "Obligation" ++ spc () ++ int user_num ++ str "already" ++ spc() ++ str "solved.") else match deps_remaining obls obl.obl_deps with | [] -> let obl = subst_deps_obl obls obl in Lemmas.start_proof obl.obl_name (kind_of_opacity obl.obl_status) obl.obl_type (fun strength gr -> let cst = match gr with ConstRef cst -> cst | _ -> assert false in let obl = let transparent = evaluable_constant1 cst (Global.env ()) in let body = match obl.obl_status with | Expand -> if not transparent then error_not_transp () else constant_value (Global.env ()) cst | Define opaque -> if not opaque && not transparent then error_not_transp () else Libnames.constr_of_global gr in if transparent then Auto.add_hints true [string_of_id prg.prg_name] (Auto.HintsUnfoldEntry [EvalConstRef cst]); { obl with obl_body = Some body } in let obls = Array.copy obls in let _ = obls.(num) <- obl in let res = try update_obls prg obls (pred rem) with e -> pperror (Errors.print (Cerrors.process_vernac_interp_error e)) in match res with | Remain n when n > 0 -> let deps = dependencies obls num in if deps <> Intset.empty then ignore(auto_solve_obligations (Some prg.prg_name) None ~oblset:deps) | _ -> ()); trace (str "Started obligation " ++ int user_num ++ str " proof: " ++ Printer.pr_constr_env (Global.env ()) obl.obl_type); Pfedit.by (snd (get_default_tactic ())); Option.iter (fun tac -> Pfedit.set_end_tac (Tacinterp.interp tac)) tac; Flags.if_verbose (fun () -> msg (Printer.pr_open_subgoals ())) () | l -> pperror (str "Obligation " ++ int user_num ++ str " depends on obligation(s) " ++ str (string_of_list ", " (fun x -> string_of_int (succ x)) l)) and obligation (user_num, name, typ) tac = let num = pred user_num in let prg = get_prog_err name in let obls, rem = prg.prg_obligations in if num < Array.length obls then let obl = obls.(num) in match obl.obl_body with None -> solve_obligation prg num tac | Some r -> error "Obligation already solved" else error (sprintf "Unknown obligation number %i" (succ num)) and solve_obligation_by_tac prg obls i tac = let obl = obls.(i) in match obl.obl_body with | Some _ -> false | None -> try if deps_remaining obls obl.obl_deps = [] then let obl = subst_deps_obl obls obl in let tac = match tac with | Some t -> t | None -> match obl.obl_tac with | Some t -> t | None -> snd (get_default_tactic ()) in let t = solve_by_tac (evar_of_obligation obl) tac in obls.(i) <- declare_obligation prg obl t; true else false with | Loc.Exc_located(_, Proof_type.LtacLocated (_, Refiner.FailError (_, s))) | Loc.Exc_located(_, Refiner.FailError (_, s)) | Refiner.FailError (_, s) -> user_err_loc (fst obl.obl_location, "solve_obligation", Lazy.force s) | Errors.Anomaly _ as e -> raise e | e -> false and solve_prg_obligations prg ?oblset tac = let obls, rem = prg.prg_obligations in let rem = ref rem in let obls' = Array.copy obls in let p = match oblset with | None -> (fun _ -> true) | Some s -> (fun i -> Intset.mem i s) in let _ = Array.iteri (fun i x -> if p i && solve_obligation_by_tac prg obls' i tac then decr rem) obls' in update_obls prg obls' !rem and solve_obligations n tac = let prg = get_prog_err n in solve_prg_obligations prg tac and solve_all_obligations tac = ProgMap.iter (fun k v -> ignore(solve_prg_obligations v tac)) !from_prg and try_solve_obligation n prg tac = let prg = get_prog prg in let obls, rem = prg.prg_obligations in let obls' = Array.copy obls in if solve_obligation_by_tac prg obls' n tac then ignore(update_obls prg obls' (pred rem)); and try_solve_obligations n tac = try ignore (solve_obligations n tac) with NoObligations _ -> () and auto_solve_obligations n ?oblset tac : progress = Flags.if_verbose msgnl (str "Solving obligations automatically..."); try solve_prg_obligations (get_prog_err n) ?oblset tac with NoObligations _ -> Dependent open Pp let show_obligations_of_prg ?(msg=true) prg = let n = prg.prg_name in let obls, rem = prg.prg_obligations in let showed = ref 5 in if msg then msgnl (int rem ++ str " obligation(s) remaining: "); Array.iteri (fun i x -> match x.obl_body with | None -> if !showed > 0 then ( decr showed; msgnl (str "Obligation" ++ spc() ++ int (succ i) ++ spc () ++ str "of" ++ spc() ++ str (string_of_id n) ++ str ":" ++ spc () ++ hov 1 (Printer.pr_constr_env (Global.env ()) x.obl_type ++ str "." ++ fnl ()))) | Some _ -> ()) obls let show_obligations ?(msg=true) n = let progs = match n with | None -> all_programs () | Some n -> try [ProgMap.find n !from_prg] with Not_found -> raise (NoObligations (Some n)) in List.iter (show_obligations_of_prg ~msg) progs let show_term n = let prg = get_prog_err n in let n = prg.prg_name in msgnl (str (string_of_id n) ++ spc () ++ str":" ++ spc () ++ Printer.pr_constr_env (Global.env ()) prg.prg_type ++ spc () ++ str ":=" ++ fnl () ++ Printer.pr_constr_env (Global.env ()) prg.prg_body) let add_definition n ?term t ?(implicits=[]) ?(kind=Global,Definition) ?tactic ?(reduce=reduce) ?(hook=fun _ _ -> ()) obls = Flags.if_verbose pp (str (string_of_id n) ++ str " has type-checked"); let prg = init_prog_info n term t [] None [] obls implicits kind reduce hook in let obls,_ = prg.prg_obligations in if Array.length obls = 0 then ( Flags.if_verbose ppnl (str "."); let cst = declare_definition prg in Defined cst) else ( let len = Array.length obls in let _ = Flags.if_verbose ppnl (str ", generating " ++ int len ++ str " obligation(s)") in progmap_add n prg; let res = auto_solve_obligations (Some n) tactic in match res with | Remain rem -> Flags.if_verbose (fun () -> show_obligations ~msg:false (Some n)) (); res | _ -> res) let add_mutual_definitions l ?tactic ?(kind=Global,Definition) ?(reduce=reduce) ?(hook=fun _ _ -> ()) notations fixkind = let deps = List.map (fun (n, b, t, imps, obls) -> n) l in List.iter (fun (n, b, t, imps, obls) -> let prg = init_prog_info n (Some b) t deps (Some fixkind) notations obls imps kind reduce hook in progmap_add n prg) l; let _defined = List.fold_left (fun finished x -> if finished then finished else let res = auto_solve_obligations (Some x) tactic in match res with | Defined _ -> If one definition is turned into a constant , the whole block is defined . the whole block is defined. *) true | _ -> false) false deps in () let admit_obligations n = let prg = get_prog_err n in let obls, rem = prg.prg_obligations in Array.iteri (fun i x -> match x.obl_body with | None -> let x = subst_deps_obl obls x in let kn = Declare.declare_constant x.obl_name (ParameterEntry (None, x.obl_type,None), IsAssumption Conjectural) in assumption_message x.obl_name; obls.(i) <- { x with obl_body = Some (mkConst kn) } | Some _ -> ()) obls; ignore(update_obls prg obls 0) exception FoundInt of int let array_find f arr = try Array.iteri (fun i x -> if f x then raise (FoundInt i)) arr; raise Not_found with FoundInt i -> i let next_obligation n tac = let prg = get_prog_err n in let obls, rem = prg.prg_obligations in let i = try array_find (fun x -> x.obl_body = None && deps_remaining obls x.obl_deps = []) obls with Not_found -> anomaly "Could not find a solvable obligation." in solve_obligation prg i tac let init_program () = Coqlib.check_required_library ["Coq";"Init";"Datatypes"]; Coqlib.check_required_library ["Coq";"Init";"Specif"]; Coqlib.check_required_library ["Coq";"Program";"Tactics"] let set_program_mode c = if c then if !Flags.program_mode then () else begin init_program (); Flags.program_mode := true; end
null
https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/toplevel/obligations.ml
ocaml
spiwack: Store field for internalizing ev_tac in evar_infos' evar_extra. Remove existential variables in types and build the corresponding products Substitute evar refs in the term by variables true = All transparent, false = Opaque if possible true = hide obligations prod_appvect T [| a1 ; ... ; an |] -> (T a1 ... an) * Beware: if this code is dynamically loaded via dynlink after the start of Coq, then this [init] function will not be run by [Lib.init ()]. Luckily, here we can launch [init] at load-time. If recursive argument was not given by user, we try all args. An earlier approach was to look only for inductive arguments, but doing it properly involves delta-reduction, and it finally doesn't seem to worth the effort (except for huge mutual fixpoints ?) Declare the recursive definitions Declare notations Solve an obligation using tactics, return the corresponding proof term
open Printf open Pp open Environ open Term open Names open Libnames open Summary open Libobject open Entries open Decl_kinds open Errors open Util open Evd open Declare open Proof_type open Compat * - Get types of existentials ; - Flatten dependency tree ( prefix order ) ; - Replace existentials by indices in term , applied to the right arguments ; - Apply term prefixed by quantification on " existentials " . - Get types of existentials ; - Flatten dependency tree (prefix order) ; - Replace existentials by De Bruijn indices in term, applied to the right arguments ; - Apply term prefixed by quantification on "existentials". *) open Term open Sign open Names open Evd open List open Pp open Errors open Util open Proof_type let declare_fix_ref = ref (fun _ _ _ _ _ -> assert false) let declare_definition_ref = ref (fun _ _ _ _ _ -> assert false) let trace s = if !Flags.debug then (msgnl s; msgerr s) else () let succfix (depth, fixrels) = (succ depth, List.map succ fixrels) let mkMetas n = list_tabulate (fun _ -> Evarutil.mk_new_meta ()) n let check_evars env evm = List.iter (fun (key, evi) -> let (loc,k) = evar_source key evm in match k with | QuestionMark _ | ImplicitArg (_,_,false) -> () | _ -> Pretype_errors.error_unsolvable_implicit loc env evm (Evarutil.nf_evar_info evm evi) k None) (Evd.undefined_list evm) type oblinfo = { ev_name: int * identifier; ev_hyps: named_context; ev_status: obligation_definition_status; ev_chop: int option; ev_src: hole_kind located; ev_typ: types; ev_tac: tactic option; ev_deps: Intset.t } open Store.Field let evar_tactic = Store.field () * Substitute evar references in t using indices , where n binders were passed through . where n binders were passed through. *) let subst_evar_constr evs n idf t = let seen = ref Intset.empty in let transparent = ref Idset.empty in let evar_info id = List.assoc id evs in let rec substrec (depth, fixrels) c = match kind_of_term c with | Evar (k, args) -> let { ev_name = (id, idstr) ; ev_hyps = hyps ; ev_chop = chop } = try evar_info k with Not_found -> anomaly ("eterm: existential variable " ^ string_of_int k ^ " not found") in seen := Intset.add id !seen; Evar arguments are created in inverse order , and we must not apply to defined ones ( i.e. 's ) and we must not apply to defined ones (i.e. LetIn's) *) let args = let n = match chop with None -> 0 | Some c -> c in let (l, r) = list_chop n (List.rev (Array.to_list args)) in List.rev r in let args = let rec aux hyps args acc = match hyps, args with ((_, None, _) :: tlh), (c :: tla) -> aux tlh tla ((substrec (depth, fixrels) c) :: acc) | ((_, Some _, _) :: tlh), (_ :: tla) -> aux tlh tla acc | [], [] -> acc failwith " subst_evars : invalid argument " in aux hyps args [] in if List.exists (fun x -> match kind_of_term x with Rel n -> List.mem n fixrels | _ -> false) args then transparent := Idset.add idstr !transparent; mkApp (idf idstr, Array.of_list args) | Fix _ -> map_constr_with_binders succfix substrec (depth, 1 :: fixrels) c | _ -> map_constr_with_binders succfix substrec (depth, fixrels) c in let t' = substrec (0, []) t in t', !seen, !transparent * Substitute variable references in t using indices , where n binders were passed through . where n binders were passed through. *) let subst_vars acc n t = let var_index id = Util.list_index id acc in let rec substrec depth c = match kind_of_term c with | Var v -> (try mkRel (depth + (var_index v)) with Not_found -> c) | _ -> map_constr_with_binders succ substrec depth c in substrec 0 t * Rewrite type of an evar ( [ H1 : t1 , ... Hn : tn ] ) to a product : forall H1 : t1 , ... , forall Hn : tn , . Changes evars and hypothesis references to variable references . to a product : forall H1 : t1, ..., forall Hn : tn, concl. Changes evars and hypothesis references to variable references. *) let etype_of_evar evs hyps concl = let rec aux acc n = function (id, copt, t) :: tl -> let t', s, trans = subst_evar_constr evs n mkVar t in let t'' = subst_vars acc 0 t' in let rest, s', trans' = aux (id :: acc) (succ n) tl in let s' = Intset.union s s' in let trans' = Idset.union trans trans' in (match copt with Some c -> let c', s'', trans'' = subst_evar_constr evs n mkVar c in let c' = subst_vars acc 0 c' in mkNamedProd_or_LetIn (id, Some c', t'') rest, Intset.union s'' s', Idset.union trans'' trans' | None -> mkNamedProd_or_LetIn (id, None, t'') rest, s', trans') | [] -> let t', s, trans = subst_evar_constr evs n mkVar concl in subst_vars acc 0 t', s, trans in aux [] 0 (rev hyps) open Tacticals let trunc_named_context n ctx = let len = List.length ctx in list_firstn (len - n) ctx let rec chop_product n t = if n = 0 then Some t else match kind_of_term t with | Prod (_, _, b) -> if noccurn 1 b then chop_product (pred n) (Termops.pop b) else None | _ -> None let evars_of_evar_info evi = Intset.union (Evarutil.evars_of_term evi.evar_concl) (Intset.union (match evi.evar_body with | Evar_empty -> Intset.empty | Evar_defined b -> Evarutil.evars_of_term b) (Evarutil.evars_of_named_context (evar_filtered_context evi))) let evar_dependencies evm oev = let one_step deps = Intset.fold (fun ev s -> let evi = Evd.find evm ev in let deps' = evars_of_evar_info evi in if Intset.mem oev deps' then raise (Invalid_argument ("Ill-formed evar map: cycle detected for evar " ^ string_of_int oev)) else Intset.union deps' s) deps deps in let rec aux deps = let deps' = one_step deps in if Intset.equal deps deps' then deps else aux deps' in aux (Intset.singleton oev) let move_after (id, ev, deps as obl) l = let rec aux restdeps = function | (id', _, _) as obl' :: tl -> let restdeps' = Intset.remove id' restdeps in if Intset.is_empty restdeps' then obl' :: obl :: tl else obl' :: aux restdeps' tl | [] -> [obl] in aux (Intset.remove id deps) l let sort_dependencies evl = let rec aux l found list = match l with | (id, ev, deps) as obl :: tl -> let found' = Intset.union found (Intset.singleton id) in if Intset.subset deps found' then aux tl found' (obl :: list) else aux (move_after obl tl) found list | [] -> List.rev list in aux evl Intset.empty [] let map_evar_body f = function | Evar_empty -> Evar_empty | Evar_defined c -> Evar_defined (f c) open Environ let map_evar_info f evi = { evi with evar_hyps = val_of_named_context (map_named_context f (named_context_of_val evi.evar_hyps)); evar_concl = f evi.evar_concl; evar_body = map_evar_body f evi.evar_body } let eterm_obligations env name evm fs ?status t ty = ' Serialize ' the evars let nc = Environ.named_context env in let nc_len = Sign.named_context_length nc in let evm = Evarutil.nf_evar_map_undefined evm in let evl = List.rev (Evarutil.non_instantiated evm) in let evl = List.map (fun (id, ev) -> (id, ev, evar_dependencies evm id)) evl in let sevl = sort_dependencies evl in let evl = List.map (fun (id, ev, _) -> id, ev) sevl in let evn = let i = ref (-1) in List.rev_map (fun (id, ev) -> incr i; (id, (!i, id_of_string (string_of_id name ^ "_obligation_" ^ string_of_int (succ !i))), ev)) evl in let evts = fold_right (fun (id, (n, nstr), ev) l -> let hyps = Evd.evar_filtered_context ev in let hyps = trunc_named_context nc_len hyps in let evtyp, deps, transp = etype_of_evar l hyps ev.evar_concl in let evtyp, hyps, chop = match chop_product fs evtyp with | Some t -> t, trunc_named_context fs hyps, fs | None -> evtyp, hyps, 0 in let loc, k = evar_source id evm in let status = match k with QuestionMark o -> Some o | _ -> status in let status, chop = match status with | Some (Define true as stat) -> if chop <> fs then Define false, None else stat, Some chop | Some s -> s, None | None -> Define true, None in let tac = match evar_tactic.get ev.evar_extra with | Some t -> if Dyn.tag t = "tactic" then Some (Tacinterp.interp (Tacinterp.globTacticIn (Tacinterp.tactic_out t))) else None | None -> None in let info = { ev_name = (n, nstr); ev_hyps = hyps; ev_status = status; ev_chop = chop; ev_src = loc, k; ev_typ = evtyp ; ev_deps = deps; ev_tac = tac } in (id, info) :: l) evn [] in subst_evar_constr evts 0 mkVar t in let ty, _, _ = subst_evar_constr evts 0 mkVar ty in let evars = List.map (fun (ev, info) -> let { ev_name = (_, name); ev_status = status; ev_src = src; ev_typ = typ; ev_deps = deps; ev_tac = tac } = info in let status = match status with | Define true when Idset.mem name transparent -> Define false | _ -> status in name, typ, src, status, deps, tac) evts in let evnames = List.map (fun (ev, info) -> ev, snd info.ev_name) evts in let evmap f c = pi1 (subst_evar_constr evts 0 f c) in Array.of_list (List.rev evars), (evnames, evmap), t', ty let tactics_module = ["Program";"Tactics"] let safe_init_constant md name () = Coqlib.check_required_library ("Coq"::md); Coqlib.gen_constant "Obligations" md name let fix_proto = safe_init_constant tactics_module "fix_proto" let hide_obligation = safe_init_constant tactics_module "obligation" let ppwarn cmd = Pp.warn (str"Program:" ++ cmd) let pperror cmd = Errors.errorlabstrm "Program" cmd let error s = pperror (str s) let reduce c = Reductionops.clos_norm_flags Closure.betaiota (Global.env ()) Evd.empty c exception NoObligations of identifier option let explain_no_obligations = function Some ident -> str "No obligations for program " ++ str (string_of_id ident) | None -> str "No obligations remaining" type obligation_info = (Names.identifier * Term.types * hole_kind located * obligation_definition_status * Intset.t * tactic option) array type obligation = { obl_name : identifier; obl_type : types; obl_location : hole_kind located; obl_body : constr option; obl_status : obligation_definition_status; obl_deps : Intset.t; obl_tac : tactic option; } type obligations = (obligation array * int) type fixpoint_kind = | IsFixpoint of (identifier located option * Topconstr.recursion_order_expr) list | IsCoFixpoint type notations = (Vernacexpr.lstring * Topconstr.constr_expr * Topconstr.scope_name option) list type program_info = { prg_name: identifier; prg_body: constr; prg_type: constr; prg_obligations: obligations; prg_deps : identifier list; prg_fixkind : fixpoint_kind option ; prg_implicits : (Topconstr.explicitation * (bool * bool * bool)) list; prg_notations : notations ; prg_kind : definition_kind; prg_reduce : constr -> constr; prg_hook : unit Tacexpr.declaration_hook; } let assumption_message id = Flags.if_verbose message ((string_of_id id) ^ " is assumed") let (set_default_tactic, get_default_tactic, print_default_tactic) = Tactic_option.declare_tactic_option "Program tactic" let proofs_transparency = ref true let set_proofs_transparency = (:=) proofs_transparency let get_proofs_transparency () = !proofs_transparency open Goptions let _ = declare_bool_option { optsync = true; optdepr = false; optname = "transparency of Program obligations"; optkey = ["Transparent";"Obligations"]; optread = get_proofs_transparency; optwrite = set_proofs_transparency; } let hide_obligations = ref false let set_hide_obligations = (:=) hide_obligations let get_hide_obligations () = !hide_obligations open Goptions let _ = declare_bool_option { optsync = true; optdepr = false; optname = "Hidding of Program obligations"; optkey = ["Hide";"Obligations"]; optread = get_hide_obligations; optwrite = set_hide_obligations; } let evar_of_obligation o = make_evar (Global.named_context_val ()) o.obl_type let get_obligation_body expand obl = let c = Option.get obl.obl_body in if expand && obl.obl_status = Expand then match kind_of_term c with | Const c -> constant_value (Global.env ()) c | _ -> c else c let obl_substitution expand obls deps = Intset.fold (fun x acc -> let xobl = obls.(x) in let oblb = try get_obligation_body expand xobl with _ -> assert(false) in (xobl.obl_name, (xobl.obl_type, oblb)) :: acc) deps [] let subst_deps expand obls deps t = let subst = obl_substitution expand obls deps in Term.replace_vars (List.map (fun (n, (_, b)) -> n, b) subst) t let rec prod_app t n = match kind_of_term (strip_outer_cast t) with | Prod (_,_,b) -> subst1 n b | LetIn (_, b, t, b') -> prod_app (subst1 b b') n | _ -> errorlabstrm "prod_app" (str"Needed a product, but didn't find one" ++ fnl ()) let prod_applist t nL = List.fold_left prod_app t nL let replace_appvars subst = let rec aux c = let f, l = decompose_app c in if isVar f then try let c' = List.map (map_constr aux) l in let (t, b) = List.assoc (destVar f) subst in mkApp (delayed_force hide_obligation, [| prod_applist t c'; applistc b c' |]) with Not_found -> map_constr aux c else map_constr aux c in map_constr aux let subst_prog expand obls ints prg = let subst = obl_substitution expand obls ints in if get_hide_obligations () then (replace_appvars subst prg.prg_body, replace_appvars subst (Termops.refresh_universes prg.prg_type)) else let subst' = List.map (fun (n, (_, b)) -> n, b) subst in (Term.replace_vars subst' prg.prg_body, Term.replace_vars subst' (Termops.refresh_universes prg.prg_type)) let subst_deps_obl obls obl = let t' = subst_deps true obls obl.obl_deps obl.obl_type in { obl with obl_type = t' } module ProgMap = Map.Make(struct type t = identifier let compare = compare end) let map_replace k v m = ProgMap.add k v (ProgMap.remove k m) let map_keys m = ProgMap.fold (fun k _ l -> k :: l) m [] let map_cardinal m = let i = ref 0 in ProgMap.iter (fun _ _ -> incr i) m; !i exception Found of program_info let map_first m = try ProgMap.iter (fun _ v -> raise (Found v)) m; assert(false) with Found x -> x let from_prg : program_info ProgMap.t ref = ref ProgMap.empty let freeze () = !from_prg let unfreeze v = from_prg := v let init () = from_prg := ProgMap.empty let _ = init () let _ = Summary.declare_summary "program-tcc-table" { Summary.freeze_function = freeze; Summary.unfreeze_function = unfreeze; Summary.init_function = init } let progmap_union = ProgMap.fold ProgMap.add let close sec = if not (ProgMap.is_empty !from_prg) then let keys = map_keys !from_prg in errorlabstrm "Program" (str "Unsolved obligations when closing " ++ str sec ++ str":" ++ spc () ++ prlist_with_sep spc (fun x -> Nameops.pr_id x) keys ++ (str (if List.length keys = 1 then " has " else "have ") ++ str "unsolved obligations")) let input : program_info ProgMap.t -> obj = declare_object { (default_object "Program state") with cache_function = (fun (na, pi) -> from_prg := pi); load_function = (fun _ (_, pi) -> from_prg := pi); discharge_function = (fun _ -> close "section"; None); classify_function = (fun _ -> close "module"; Dispose) } open Evd let progmap_remove prg = Lib.add_anonymous_leaf (input (ProgMap.remove prg.prg_name !from_prg)) let progmap_add n prg = Lib.add_anonymous_leaf (input (ProgMap.add n prg !from_prg)) let progmap_replace prg' = Lib.add_anonymous_leaf (input (map_replace prg'.prg_name prg' !from_prg)) let rec intset_to = function -1 -> Intset.empty | n -> Intset.add n (intset_to (pred n)) let subst_body expand prg = let obls, _ = prg.prg_obligations in let ints = intset_to (pred (Array.length obls)) in subst_prog expand obls ints prg let declare_definition prg = let body, typ = subst_body true prg in let ce = { const_entry_body = body; const_entry_secctx = None; const_entry_type = Some typ; const_entry_opaque = false; const_entry_inline_code = false} in progmap_remove prg; !declare_definition_ref prg.prg_name prg.prg_kind ce prg.prg_implicits (fun local gr -> prg.prg_hook local gr; gr) open Pp open Ppconstr let rec lam_index n t acc = match kind_of_term t with | Lambda (na, _, b) -> if na = Name n then acc else lam_index n b (succ acc) | _ -> raise Not_found let compute_possible_guardness_evidences (n,_) fixbody fixtype = match n with | Some (loc, n) -> [lam_index n fixbody 0] | None -> let m = Term.nb_prod fixtype in let ctx = fst (decompose_prod_n_assum m fixtype) in list_map_i (fun i _ -> i) 0 ctx let declare_mutual_definition l = let len = List.length l in let first = List.hd l in let fixdefs, fixtypes, fiximps = list_split3 (List.map (fun x -> let subs, typ = (subst_body true x) in let term = snd (Reductionops.splay_lam_n (Global.env ()) Evd.empty len subs) in let typ = snd (Reductionops.splay_prod_n (Global.env ()) Evd.empty len typ) in x.prg_reduce term, x.prg_reduce typ, x.prg_implicits) l) in let fixdefs = List.map reduce_fix fixdefs in let fixkind = Option.get first.prg_fixkind in let arrrec, recvec = Array.of_list fixtypes, Array.of_list fixdefs in let fixdecls = (Array.of_list (List.map (fun x -> Name x.prg_name) l), arrrec, recvec) in let (local,kind) = first.prg_kind in let fixnames = first.prg_deps in let kind = if fixkind <> IsCoFixpoint then Fixpoint else CoFixpoint in let indexes, fixdecls = match fixkind with | IsFixpoint wfl -> let possible_indexes = list_map3 compute_possible_guardness_evidences wfl fixdefs fixtypes in let indexes = Pretyping.search_guard dummy_loc (Global.env ()) possible_indexes fixdecls in Some indexes, list_map_i (fun i _ -> mkFix ((indexes,i),fixdecls)) 0 l | IsCoFixpoint -> None, list_map_i (fun i _ -> mkCoFix (i,fixdecls)) 0 l in let kns = list_map4 (!declare_fix_ref kind) fixnames fixdecls fixtypes fiximps in List.iter Metasyntax.add_notation_interpretation first.prg_notations; Declare.recursive_message (fixkind<>IsCoFixpoint) indexes fixnames; let gr = List.hd kns in let kn = match gr with ConstRef kn -> kn | _ -> assert false in first.prg_hook local gr; List.iter progmap_remove l; kn let declare_obligation prg obl body = let body = prg.prg_reduce body in let ty = prg.prg_reduce obl.obl_type in match obl.obl_status with | Expand -> { obl with obl_body = Some body } | Define opaque -> let opaque = if get_proofs_transparency () then false else opaque in let ce = { const_entry_body = body; const_entry_secctx = None; const_entry_type = Some ty; const_entry_opaque = opaque; const_entry_inline_code = false} in let constant = Declare.declare_constant obl.obl_name (DefinitionEntry ce,IsProof Property) in if not opaque then Auto.add_hints false [string_of_id prg.prg_name] (Auto.HintsUnfoldEntry [EvalConstRef constant]); definition_message obl.obl_name; { obl with obl_body = Some (mkConst constant) } let init_prog_info n b t deps fixkind notations obls impls kind reduce hook = let obls', b = match b with | None -> assert(obls = [||]); let n = Nameops.add_suffix n "_obligation" in [| { obl_name = n; obl_body = None; obl_location = dummy_loc, InternalHole; obl_type = t; obl_status = Expand; obl_deps = Intset.empty; obl_tac = None } |], mkVar n | Some b -> Array.mapi (fun i (n, t, l, o, d, tac) -> { obl_name = n ; obl_body = None; obl_location = l; obl_type = reduce t; obl_status = o; obl_deps = d; obl_tac = tac }) obls, b in { prg_name = n ; prg_body = b; prg_type = reduce t; prg_obligations = (obls', Array.length obls'); prg_deps = deps; prg_fixkind = fixkind ; prg_notations = notations ; prg_implicits = impls; prg_kind = kind; prg_reduce = reduce; prg_hook = hook; } let get_prog name = let prg_infos = !from_prg in match name with Some n -> (try ProgMap.find n prg_infos with Not_found -> raise (NoObligations (Some n))) | None -> (let n = map_cardinal prg_infos in match n with 0 -> raise (NoObligations None) | 1 -> map_first prg_infos | _ -> error "More than one program with unsolved obligations") let get_prog_err n = try get_prog n with NoObligations id -> pperror (explain_no_obligations id) let obligations_solved prg = (snd prg.prg_obligations) = 0 let all_programs () = ProgMap.fold (fun k p l -> p :: l) !from_prg [] type progress = | Remain of int | Dependent | Defined of global_reference let obligations_message rem = if rem > 0 then if rem = 1 then Flags.if_verbose msgnl (int rem ++ str " obligation remaining") else Flags.if_verbose msgnl (int rem ++ str " obligations remaining") else Flags.if_verbose msgnl (str "No more obligations remaining") let update_obls prg obls rem = let prg' = { prg with prg_obligations = (obls, rem) } in progmap_replace prg'; obligations_message rem; if rem > 0 then Remain rem else ( match prg'.prg_deps with | [] -> let kn = declare_definition prg' in progmap_remove prg'; Defined kn | l -> let progs = List.map (fun x -> ProgMap.find x !from_prg) prg'.prg_deps in if List.for_all (fun x -> obligations_solved x) progs then let kn = declare_mutual_definition progs in Defined (ConstRef kn) else Dependent) let is_defined obls x = obls.(x).obl_body <> None let deps_remaining obls deps = Intset.fold (fun x acc -> if is_defined obls x then acc else x :: acc) deps [] let dependencies obls n = let res = ref Intset.empty in Array.iteri (fun i obl -> if i <> n && Intset.mem n obl.obl_deps then res := Intset.add i !res) obls; !res let global_kind = Decl_kinds.IsDefinition Decl_kinds.Definition let goal_kind = Decl_kinds.Global, Decl_kinds.DefinitionBody Decl_kinds.Definition let global_proof_kind = Decl_kinds.IsProof Decl_kinds.Lemma let goal_proof_kind = Decl_kinds.Global, Decl_kinds.Proof Decl_kinds.Lemma let global_fix_kind = Decl_kinds.IsDefinition Decl_kinds.Fixpoint let goal_fix_kind = Decl_kinds.Global, Decl_kinds.DefinitionBody Decl_kinds.Fixpoint let kind_of_opacity o = match o with | Define false | Expand -> goal_kind | _ -> goal_proof_kind let not_transp_msg = str "Obligation should be transparent but was declared opaque." ++ spc () ++ str"Use 'Defined' instead." let warn_not_transp () = ppwarn not_transp_msg let error_not_transp () = pperror not_transp_msg let rec string_of_list sep f = function [] -> "" | x :: [] -> f x | x :: ((y :: _) as tl) -> f x ^ sep ^ string_of_list sep f tl let solve_by_tac evi t = let id = id_of_string "H" in try Pfedit.start_proof id goal_kind evi.evar_hyps evi.evar_concl (fun _ _ -> ()); Pfedit.by (tclCOMPLETE t); let _,(const,_,_,_) = Pfedit.cook_proof ignore in Pfedit.delete_current_proof (); Inductiveops.control_only_guard (Global.env ()) const.Entries.const_entry_body; const.Entries.const_entry_body with e -> Pfedit.delete_current_proof(); raise e let rec solve_obligation prg num tac = let user_num = succ num in let obls, rem = prg.prg_obligations in let obl = obls.(num) in if obl.obl_body <> None then pperror (str "Obligation" ++ spc () ++ int user_num ++ str "already" ++ spc() ++ str "solved.") else match deps_remaining obls obl.obl_deps with | [] -> let obl = subst_deps_obl obls obl in Lemmas.start_proof obl.obl_name (kind_of_opacity obl.obl_status) obl.obl_type (fun strength gr -> let cst = match gr with ConstRef cst -> cst | _ -> assert false in let obl = let transparent = evaluable_constant1 cst (Global.env ()) in let body = match obl.obl_status with | Expand -> if not transparent then error_not_transp () else constant_value (Global.env ()) cst | Define opaque -> if not opaque && not transparent then error_not_transp () else Libnames.constr_of_global gr in if transparent then Auto.add_hints true [string_of_id prg.prg_name] (Auto.HintsUnfoldEntry [EvalConstRef cst]); { obl with obl_body = Some body } in let obls = Array.copy obls in let _ = obls.(num) <- obl in let res = try update_obls prg obls (pred rem) with e -> pperror (Errors.print (Cerrors.process_vernac_interp_error e)) in match res with | Remain n when n > 0 -> let deps = dependencies obls num in if deps <> Intset.empty then ignore(auto_solve_obligations (Some prg.prg_name) None ~oblset:deps) | _ -> ()); trace (str "Started obligation " ++ int user_num ++ str " proof: " ++ Printer.pr_constr_env (Global.env ()) obl.obl_type); Pfedit.by (snd (get_default_tactic ())); Option.iter (fun tac -> Pfedit.set_end_tac (Tacinterp.interp tac)) tac; Flags.if_verbose (fun () -> msg (Printer.pr_open_subgoals ())) () | l -> pperror (str "Obligation " ++ int user_num ++ str " depends on obligation(s) " ++ str (string_of_list ", " (fun x -> string_of_int (succ x)) l)) and obligation (user_num, name, typ) tac = let num = pred user_num in let prg = get_prog_err name in let obls, rem = prg.prg_obligations in if num < Array.length obls then let obl = obls.(num) in match obl.obl_body with None -> solve_obligation prg num tac | Some r -> error "Obligation already solved" else error (sprintf "Unknown obligation number %i" (succ num)) and solve_obligation_by_tac prg obls i tac = let obl = obls.(i) in match obl.obl_body with | Some _ -> false | None -> try if deps_remaining obls obl.obl_deps = [] then let obl = subst_deps_obl obls obl in let tac = match tac with | Some t -> t | None -> match obl.obl_tac with | Some t -> t | None -> snd (get_default_tactic ()) in let t = solve_by_tac (evar_of_obligation obl) tac in obls.(i) <- declare_obligation prg obl t; true else false with | Loc.Exc_located(_, Proof_type.LtacLocated (_, Refiner.FailError (_, s))) | Loc.Exc_located(_, Refiner.FailError (_, s)) | Refiner.FailError (_, s) -> user_err_loc (fst obl.obl_location, "solve_obligation", Lazy.force s) | Errors.Anomaly _ as e -> raise e | e -> false and solve_prg_obligations prg ?oblset tac = let obls, rem = prg.prg_obligations in let rem = ref rem in let obls' = Array.copy obls in let p = match oblset with | None -> (fun _ -> true) | Some s -> (fun i -> Intset.mem i s) in let _ = Array.iteri (fun i x -> if p i && solve_obligation_by_tac prg obls' i tac then decr rem) obls' in update_obls prg obls' !rem and solve_obligations n tac = let prg = get_prog_err n in solve_prg_obligations prg tac and solve_all_obligations tac = ProgMap.iter (fun k v -> ignore(solve_prg_obligations v tac)) !from_prg and try_solve_obligation n prg tac = let prg = get_prog prg in let obls, rem = prg.prg_obligations in let obls' = Array.copy obls in if solve_obligation_by_tac prg obls' n tac then ignore(update_obls prg obls' (pred rem)); and try_solve_obligations n tac = try ignore (solve_obligations n tac) with NoObligations _ -> () and auto_solve_obligations n ?oblset tac : progress = Flags.if_verbose msgnl (str "Solving obligations automatically..."); try solve_prg_obligations (get_prog_err n) ?oblset tac with NoObligations _ -> Dependent open Pp let show_obligations_of_prg ?(msg=true) prg = let n = prg.prg_name in let obls, rem = prg.prg_obligations in let showed = ref 5 in if msg then msgnl (int rem ++ str " obligation(s) remaining: "); Array.iteri (fun i x -> match x.obl_body with | None -> if !showed > 0 then ( decr showed; msgnl (str "Obligation" ++ spc() ++ int (succ i) ++ spc () ++ str "of" ++ spc() ++ str (string_of_id n) ++ str ":" ++ spc () ++ hov 1 (Printer.pr_constr_env (Global.env ()) x.obl_type ++ str "." ++ fnl ()))) | Some _ -> ()) obls let show_obligations ?(msg=true) n = let progs = match n with | None -> all_programs () | Some n -> try [ProgMap.find n !from_prg] with Not_found -> raise (NoObligations (Some n)) in List.iter (show_obligations_of_prg ~msg) progs let show_term n = let prg = get_prog_err n in let n = prg.prg_name in msgnl (str (string_of_id n) ++ spc () ++ str":" ++ spc () ++ Printer.pr_constr_env (Global.env ()) prg.prg_type ++ spc () ++ str ":=" ++ fnl () ++ Printer.pr_constr_env (Global.env ()) prg.prg_body) let add_definition n ?term t ?(implicits=[]) ?(kind=Global,Definition) ?tactic ?(reduce=reduce) ?(hook=fun _ _ -> ()) obls = Flags.if_verbose pp (str (string_of_id n) ++ str " has type-checked"); let prg = init_prog_info n term t [] None [] obls implicits kind reduce hook in let obls,_ = prg.prg_obligations in if Array.length obls = 0 then ( Flags.if_verbose ppnl (str "."); let cst = declare_definition prg in Defined cst) else ( let len = Array.length obls in let _ = Flags.if_verbose ppnl (str ", generating " ++ int len ++ str " obligation(s)") in progmap_add n prg; let res = auto_solve_obligations (Some n) tactic in match res with | Remain rem -> Flags.if_verbose (fun () -> show_obligations ~msg:false (Some n)) (); res | _ -> res) let add_mutual_definitions l ?tactic ?(kind=Global,Definition) ?(reduce=reduce) ?(hook=fun _ _ -> ()) notations fixkind = let deps = List.map (fun (n, b, t, imps, obls) -> n) l in List.iter (fun (n, b, t, imps, obls) -> let prg = init_prog_info n (Some b) t deps (Some fixkind) notations obls imps kind reduce hook in progmap_add n prg) l; let _defined = List.fold_left (fun finished x -> if finished then finished else let res = auto_solve_obligations (Some x) tactic in match res with | Defined _ -> If one definition is turned into a constant , the whole block is defined . the whole block is defined. *) true | _ -> false) false deps in () let admit_obligations n = let prg = get_prog_err n in let obls, rem = prg.prg_obligations in Array.iteri (fun i x -> match x.obl_body with | None -> let x = subst_deps_obl obls x in let kn = Declare.declare_constant x.obl_name (ParameterEntry (None, x.obl_type,None), IsAssumption Conjectural) in assumption_message x.obl_name; obls.(i) <- { x with obl_body = Some (mkConst kn) } | Some _ -> ()) obls; ignore(update_obls prg obls 0) exception FoundInt of int let array_find f arr = try Array.iteri (fun i x -> if f x then raise (FoundInt i)) arr; raise Not_found with FoundInt i -> i let next_obligation n tac = let prg = get_prog_err n in let obls, rem = prg.prg_obligations in let i = try array_find (fun x -> x.obl_body = None && deps_remaining obls x.obl_deps = []) obls with Not_found -> anomaly "Could not find a solvable obligation." in solve_obligation prg i tac let init_program () = Coqlib.check_required_library ["Coq";"Init";"Datatypes"]; Coqlib.check_required_library ["Coq";"Init";"Specif"]; Coqlib.check_required_library ["Coq";"Program";"Tactics"] let set_program_mode c = if c then if !Flags.program_mode then () else begin init_program (); Flags.program_mode := true; end
cf0b098e8bc49f0ff119663b45f4e45c9466e6a8a110359b05806a3020766767
clojure-lsp/clojure-lsp
signature_help.clj
(ns clojure-lsp.feature.signature-help (:require [clojure-lsp.feature.file-management :as f.file-management] [clojure-lsp.parser :as parser] [clojure-lsp.queries :as q] [clojure-lsp.refactor.edit :as edit] [clojure-lsp.shared :as shared :refer [assoc-some]] [edamame.core :as edamame] [rewrite-clj.node :as n] [rewrite-clj.zip :as z]) (:import [clojure.lang PersistentVector])) (set! *warn-on-reflection* true) (defn ^:private function-loc->arglist-nodes [zloc] (->> zloc z/up z/node n/children (remove n/whitespace-or-comment?) (drop 1))) (defn ^:private get-active-parameter-index [signatures active-signature arglist-nodes cursor-row cursor-col] (let [params-count (-> (nth signatures active-signature) :parameters count) selected-arg (->> arglist-nodes reverse (filter (fn [node] (let [{:keys [row col]} (meta node)] (or (< row cursor-row) (and (= row cursor-row) (<= col cursor-col)))))) first)] (if selected-arg (let [index (.indexOf ^PersistentVector (vec arglist-nodes) selected-arg)] (if (> index (dec params-count)) (dec params-count) index)) 0))) (defn ^:private get-active-signature-index [{:keys [fixed-arities arglist-strs]} arglist-nodes] (let [arities (vec (sort-by max (if fixed-arities (if (= (count fixed-arities) (count arglist-strs)) fixed-arities (conj fixed-arities (inc (apply max fixed-arities)))) #{(count arglist-strs)}))) args-count (count arglist-nodes) current-arity (first (filter #(= % args-count) arities))] (if current-arity (.indexOf ^PersistentVector arities current-arity) (if (>= args-count (count arities)) (.indexOf ^PersistentVector arities (apply max arities)) (.indexOf ^PersistentVector arities (apply min arities)))))) (defn ^:private arglist-str->parameters [arglist-str] (let [parameters (edamame/parse-string arglist-str {:auto-resolve #(symbol (str ":" %))}) rest-args? (some #(= '& %) parameters) available-params (filter (complement #(= '& %)) parameters) params-count (dec (count available-params))] (->> available-params (map-indexed (fn [index arg] (let [last-arg? (= index params-count)] (if (and rest-args? last-arg?) {:label (format "& %s" arg)} {:label (str arg)}))))))) (defn ^:private definition->signature-informations [{:keys [arglist-strs] :as definition}] (map (fn [arglist-str] (-> {:label (format "(%s %s)" (-> definition :name str) arglist-str) :parameters (arglist-str->parameters arglist-str)} (assoc-some :documentation (:doc definition)))) arglist-strs)) (defn signature-help [uri row col {:keys [db*] :as components}] (when-let [function-loc (some-> (f.file-management/force-get-document-text uri components) parser/safe-zloc-of-string (parser/to-pos row col) edit/find-function-usage-name-loc)] (let [db @db* arglist-nodes (function-loc->arglist-nodes function-loc) function-meta (meta (z/node function-loc)) definition (q/find-definition-from-cursor db uri (:row function-meta) (:col function-meta)) signatures (definition->signature-informations definition) active-signature (get-active-signature-index definition arglist-nodes)] (when (seq signatures) {:signatures signatures :active-parameter (get-active-parameter-index signatures active-signature arglist-nodes row col) :active-signature active-signature}))))
null
https://raw.githubusercontent.com/clojure-lsp/clojure-lsp/d6ca21a6d2235d7438fd8901db93930b80ae257b/lib/src/clojure_lsp/feature/signature_help.clj
clojure
(ns clojure-lsp.feature.signature-help (:require [clojure-lsp.feature.file-management :as f.file-management] [clojure-lsp.parser :as parser] [clojure-lsp.queries :as q] [clojure-lsp.refactor.edit :as edit] [clojure-lsp.shared :as shared :refer [assoc-some]] [edamame.core :as edamame] [rewrite-clj.node :as n] [rewrite-clj.zip :as z]) (:import [clojure.lang PersistentVector])) (set! *warn-on-reflection* true) (defn ^:private function-loc->arglist-nodes [zloc] (->> zloc z/up z/node n/children (remove n/whitespace-or-comment?) (drop 1))) (defn ^:private get-active-parameter-index [signatures active-signature arglist-nodes cursor-row cursor-col] (let [params-count (-> (nth signatures active-signature) :parameters count) selected-arg (->> arglist-nodes reverse (filter (fn [node] (let [{:keys [row col]} (meta node)] (or (< row cursor-row) (and (= row cursor-row) (<= col cursor-col)))))) first)] (if selected-arg (let [index (.indexOf ^PersistentVector (vec arglist-nodes) selected-arg)] (if (> index (dec params-count)) (dec params-count) index)) 0))) (defn ^:private get-active-signature-index [{:keys [fixed-arities arglist-strs]} arglist-nodes] (let [arities (vec (sort-by max (if fixed-arities (if (= (count fixed-arities) (count arglist-strs)) fixed-arities (conj fixed-arities (inc (apply max fixed-arities)))) #{(count arglist-strs)}))) args-count (count arglist-nodes) current-arity (first (filter #(= % args-count) arities))] (if current-arity (.indexOf ^PersistentVector arities current-arity) (if (>= args-count (count arities)) (.indexOf ^PersistentVector arities (apply max arities)) (.indexOf ^PersistentVector arities (apply min arities)))))) (defn ^:private arglist-str->parameters [arglist-str] (let [parameters (edamame/parse-string arglist-str {:auto-resolve #(symbol (str ":" %))}) rest-args? (some #(= '& %) parameters) available-params (filter (complement #(= '& %)) parameters) params-count (dec (count available-params))] (->> available-params (map-indexed (fn [index arg] (let [last-arg? (= index params-count)] (if (and rest-args? last-arg?) {:label (format "& %s" arg)} {:label (str arg)}))))))) (defn ^:private definition->signature-informations [{:keys [arglist-strs] :as definition}] (map (fn [arglist-str] (-> {:label (format "(%s %s)" (-> definition :name str) arglist-str) :parameters (arglist-str->parameters arglist-str)} (assoc-some :documentation (:doc definition)))) arglist-strs)) (defn signature-help [uri row col {:keys [db*] :as components}] (when-let [function-loc (some-> (f.file-management/force-get-document-text uri components) parser/safe-zloc-of-string (parser/to-pos row col) edit/find-function-usage-name-loc)] (let [db @db* arglist-nodes (function-loc->arglist-nodes function-loc) function-meta (meta (z/node function-loc)) definition (q/find-definition-from-cursor db uri (:row function-meta) (:col function-meta)) signatures (definition->signature-informations definition) active-signature (get-active-signature-index definition arglist-nodes)] (when (seq signatures) {:signatures signatures :active-parameter (get-active-parameter-index signatures active-signature arglist-nodes row col) :active-signature active-signature}))))
2b323028d2d7474a146e10a3ec0ea05d394947b64b4f7a2bb39489397d47ad45
dalaing/little-languages
Check.hs
module Type.Check where
null
https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/old/prototypes/classy/src/Type/Check.hs
haskell
module Type.Check where
3cd9d4a418dac2d96895d3783a58b47ac5c09a55ea5b310808f052d9d7222d6b
zcaudate/hara
result_test.clj
(ns hara.core.base.result-test (:use hara.test) (:require [hara.core.base.result :refer :all])) ^{:refer hara.core.base.result/result :added "3.0"} (fact "creates a result used for printing" (result {:status :warn :data [1 2 3 4]}) # result{:status : warn , : data [ 1 2 3 4 ] } => hara.core.base.result.Result) ^{:refer hara.core.base.result/result? :added "3.0"} (fact "checks if an object is a result" (-> (result {:status :warn :data [1 2 3 4]}) result?) => true) ^{:refer hara.core.base.result/->result :added "3.0"} (fact "converts data into a result" (->result :hello [1 2 3]) # result.return{:data [ 1 2 3 ] , : key : hello } => hara.core.base.result.Result)
null
https://raw.githubusercontent.com/zcaudate/hara/481316c1f5c2aeba5be6e01ae673dffc46a63ec9/test/hara/core/base/result_test.clj
clojure
(ns hara.core.base.result-test (:use hara.test) (:require [hara.core.base.result :refer :all])) ^{:refer hara.core.base.result/result :added "3.0"} (fact "creates a result used for printing" (result {:status :warn :data [1 2 3 4]}) # result{:status : warn , : data [ 1 2 3 4 ] } => hara.core.base.result.Result) ^{:refer hara.core.base.result/result? :added "3.0"} (fact "checks if an object is a result" (-> (result {:status :warn :data [1 2 3 4]}) result?) => true) ^{:refer hara.core.base.result/->result :added "3.0"} (fact "converts data into a result" (->result :hello [1 2 3]) # result.return{:data [ 1 2 3 ] , : key : hello } => hara.core.base.result.Result)
16be560a18dc03adb7331197abb3eb4ed718856d56a8d74e36ad4535eea47f37
janestreet/bonsai
cleanup.ml
open! Core open! Bonsai_test.Arrow type packed = T : _ Driver.t -> packed let (most_recent_driver : packed option ref) = ref None let register_driver driver = most_recent_driver := Some (T driver) let invalidate_observers = Core_bench_js.Test.create_with_initialization ~name:"cleaning up observers..." (fun `init -> (match !most_recent_driver with | None -> () | Some (T driver) -> Driver.invalidate_observers driver); most_recent_driver := None; fun () -> ()) ;;
null
https://raw.githubusercontent.com/janestreet/bonsai/2619a3a5cafb94a57a80cdefc83da1b5c0e182c7/bench/src/cleanup.ml
ocaml
open! Core open! Bonsai_test.Arrow type packed = T : _ Driver.t -> packed let (most_recent_driver : packed option ref) = ref None let register_driver driver = most_recent_driver := Some (T driver) let invalidate_observers = Core_bench_js.Test.create_with_initialization ~name:"cleaning up observers..." (fun `init -> (match !most_recent_driver with | None -> () | Some (T driver) -> Driver.invalidate_observers driver); most_recent_driver := None; fun () -> ()) ;;
f7f1df386f5933408a3aa7dbe18edf669454f3004d3b1f2766b488c2d190eaa1
hexlet-codebattle/battle_asserts
maximum_triangle_edge.clj
(ns battle-asserts.issues.maximum-triangle-edge (:require [clojure.test.check.generators :as gen])) (def level :elementary) (def tags ["math"]) (def description {:en "Create a function that finds the maximum range of a triangle's third edge, where the side lengths are all integers." :ru "Создайте функцию, которая рассчитывает максимальную длину третьей стороны треугольника. Все длины сторон являются целыми числами."}) (def signature {:input [{:argument-name "first" :type {:name "integer"}} {:argument-name "second" :type {:name "integer"}}] :output {:type {:name "integer"}}}) (def test-data [{:expected 17 :arguments [8 10]} {:expected 11 :arguments [5 7]} {:expected 10 :arguments [9 2]}]) (defn arguments-generator [] (gen/tuple (gen/choose 1 20) (gen/choose 1 20))) (defn solution [side1 side2] (dec (+ side1 side2)))
null
https://raw.githubusercontent.com/hexlet-codebattle/battle_asserts/87bcd69bbacd12bdedfe56bad2ff9ba4d56f729a/src/battle_asserts/issues/maximum_triangle_edge.clj
clojure
(ns battle-asserts.issues.maximum-triangle-edge (:require [clojure.test.check.generators :as gen])) (def level :elementary) (def tags ["math"]) (def description {:en "Create a function that finds the maximum range of a triangle's third edge, where the side lengths are all integers." :ru "Создайте функцию, которая рассчитывает максимальную длину третьей стороны треугольника. Все длины сторон являются целыми числами."}) (def signature {:input [{:argument-name "first" :type {:name "integer"}} {:argument-name "second" :type {:name "integer"}}] :output {:type {:name "integer"}}}) (def test-data [{:expected 17 :arguments [8 10]} {:expected 11 :arguments [5 7]} {:expected 10 :arguments [9 2]}]) (defn arguments-generator [] (gen/tuple (gen/choose 1 20) (gen/choose 1 20))) (defn solution [side1 side2] (dec (+ side1 side2)))
4d8410f33e56c5ab588d8eb1c79a5ff0a84ae83bc020892ffa51c8e4c07d61b6
incoherentsoftware/defect-process
Types.hs
module World.Surface.Types ( WallSurfaceType(..) , SurfaceType(..) , Surface(..) ) where import Collision.Hitbox.Types import Util data WallSurfaceType = LeftWallSurface | RightWallSurface deriving Eq data SurfaceType = GeneralSurface | PlatformSurface | SpeedRailSurface Direction deriving Eq data Surface = Surface { _type :: SurfaceType , _hitbox :: Hitbox }
null
https://raw.githubusercontent.com/incoherentsoftware/defect-process/15f2569e7d0e481c2e28c0ca3a5e72d2c049b667/src/World/Surface/Types.hs
haskell
module World.Surface.Types ( WallSurfaceType(..) , SurfaceType(..) , Surface(..) ) where import Collision.Hitbox.Types import Util data WallSurfaceType = LeftWallSurface | RightWallSurface deriving Eq data SurfaceType = GeneralSurface | PlatformSurface | SpeedRailSurface Direction deriving Eq data Surface = Surface { _type :: SurfaceType , _hitbox :: Hitbox }
2561b8e78d7827afc69187c677bedb7fa87fe142d29ae2d709166c6d3cb905ad
Zoetermeer/latro
Display.hs
{-# LANGUAGE NamedFieldPuns, FlexibleInstances #-} module Latro.Semant.Display where import Data.List (intercalate, intersperse) import qualified Data.Map as Map import Latro.Ast import Latro.Output import Latro.Semant import Latro.Sexpable import Text.Printf (printf) instance Sexpable v => Sexpable (Maybe v) where sexp (Just v) = sexp v sexp Nothing = List [] -- To satisfy (Sexpable RawId) instance Sexpable RawId where sexp = Symbol instance Sexpable SourcePos where sexp (SourcePos filePath lineNum colNum) = List [ Symbol "SourcePos" , Atom filePath , Symbol $ show lineNum , Symbol $ show colNum ] instance Sexpable CheckedData where sexp (OfTy srcPos ty) = List [ Symbol "OfTy" , sexp srcPos , sexp ty ] instance (Sexpable a, Sexpable id) => Sexpable (QualifiedId a id) where sexp (Id _ raw) = sexp raw sexp (Path _ qid raw) = Symbol $ printf "%s.%s" (showSexp qid) (showSexp raw) instance (Sexpable a, CompilerOutput id) => CompilerOutput (QualifiedId a id) where render (Id _ raw) = render raw render (Path _ qid raw) = printf "%s.%s" (render qid) (render raw) instance (Sexpable a, Sexpable id) => Sexpable (SynTy a id) where sexp (SynTyInt d) = List [ Symbol "Int", sexp d ] sexp (SynTyBool d) = List [ Symbol "Bool", sexp d ] sexp (SynTyChar d) = List [ Symbol "Char", sexp d ] sexp (SynTyUnit d) = List [ Symbol "Unit", sexp d ] sexp (SynTyArrow d paramTys retTy) = List $ sexp d : (intersperse (Symbol "->" ) . map sexp) (paramTys ++ [retTy]) sexp (SynTyStruct d fields) = List [ Symbol "Struct" , sexp d , List $ map (\(id, ty) -> List [ Symbol "Field", sexp id, sexp ty ]) fields ] sexp (SynTyAdt d id alts) = List [ Symbol "ADT" , sexp d , sexp id , toSexpList alts ] sexp (SynTyTuple d synTys) = List [ Symbol "Tuple" , sexp d, toSexpList synTys ] sexp (SynTyList d synTy) = List [ Symbol "List", sexp d, sexp synTy ] sexp (SynTyRef d qid []) = List [ Symbol "Ref", sexp d, sexp qid ] sexp (SynTyRef d qid tyParamIds) = List [ Symbol "Ref", sexp d, sexp qid, toSexpList tyParamIds ] instance CompilerOutput RawId where render id = id instance Sexpable UniqId where sexp (UserId raw) = Symbol raw sexp (UniqId i raw) = List [ Symbol "Id", Symbol raw, Symbol $ show i ] instance CompilerOutput UniqId where render (UserId raw) = raw render (UniqId i raw) = printf "%s@%i" raw i instance (Sexpable a, Sexpable id) => Sexpable (CompUnit a id) where sexp (CompUnit d es) = List [ Symbol "CompUnit" , sexp d , toSexpList es ] instance (Sexpable a, Sexpable id) => CompilerOutput (CompUnit a id) where render = showSexp instance (Sexpable a, Sexpable id) => Sexpable (AdtAlternative a id) where sexp (AdtAlternative d id i sTys) = List [ Symbol "AdtAlternative" , sexp d , sexp id , Symbol $ show i , toSexpList sTys ] instance (Sexpable a, Sexpable id) => Sexpable (TypeDec a id) where sexp (TypeDecTy d id tyParamIds sTy) = List [ Symbol "TypeDecTy" , sexp d , sexp id , toSexpList tyParamIds , sexp sTy ] sexp (TypeDecAdt d id tyParamIds alts) = List [ Symbol "TypeDecAdt" , sexp d , sexp id , toSexpList tyParamIds , toSexpList alts ] sexp (TypeDecImplicit d tyDec) = List [ Symbol "TypeDecImplicit" , sexp d , sexp tyDec ] sexp (TypeDecEmpty d id tyParamIds) = List [ Symbol "TypeDecEmpty" , sexp d , sexp id , toSexpList tyParamIds ] instance (Sexpable a, Sexpable id) => Sexpable (PatExp a id) where sexp (PatExpNumLiteral d str) = List [ Symbol "PatExpNumLiteral", sexp d, Atom str ] sexp (PatExpBoolLiteral d b) = List [ Symbol "PatExpBoolLiteral", sexp d, Symbol $ show b ] sexp (PatExpStringLiteral d s) = List [ Symbol "PatExpStringLiteral", sexp d, Atom s ] sexp (PatExpCharLiteral d s) = List [ Symbol "PatExpCharLiteral", sexp d, Atom s ] sexp (PatExpTuple d patEs) = List [ Symbol "PatExpTuple", sexp d, toSexpList patEs ] sexp (PatExpAdt d qid patEs) = List [ Symbol "PatExpAdt", sexp d, sexp qid, toSexpList patEs ] sexp (PatExpList d patEs) = List [ Symbol "PatExpList", sexp d, toSexpList patEs ] sexp (PatExpListCons d a b) = List [ Symbol "PatExpListCons", sexp d, sexp a, sexp b ] sexp (PatExpId d id) = List [ Symbol "PatExpId", sexp d, sexp id ] sexp (PatExpWildcard d) = List [ Symbol "PatExpWildcard", sexp d ] instance (Sexpable a, Sexpable id) => Sexpable (CaseClause a id) where sexp (CaseClause d patE e) = List [ Symbol "CaseClause" , sexp d , sexp patE , sexp e ] instance (Sexpable a, Sexpable id) => Sexpable (FunDef a id) where sexp (FunDefFun d id argPatEs e) = List [ Symbol "FunDefFun" , sexp d , sexp id , toSexpList argPatEs , sexp e ] instance (Sexpable a, Sexpable id) => Sexpable (Constraint a id) where sexp (Constraint d tyId protoId) = List [ Symbol "Constraint" , sexp d , sexp tyId , sexp protoId ] instance (Sexpable a, Sexpable id) => Sexpable (FieldInit a id) where sexp (FieldInit id e) = List [ sexp id, sexp e ] instance (Sexpable a, Sexpable id) => Sexpable (AnnDef a id) where sexp (AnnDefModule d id e) = List [ Symbol "AnnDefModule", sexp d, sexp e ] sexp (AnnDefFun d funDef) = List [ Symbol "AnnDefFun", sexp d, sexp funDef ] instance (Sexpable a, Sexpable id) => Sexpable (CondCaseClause a id) where sexp (CondCaseClause d pExp bodyE) = List [ Symbol "CondCaseClause" , sexp d , sexp pExp , sexp bodyE ] sexp (CondCaseClauseWildcard d bodyE) = List [ Symbol "CondCaseClauseWildcard", sexp d, sexp bodyE ] instance (Sexpable a, Sexpable id) => Sexpable (Exp a id) where sexp (ExpCons d a b) = List [ Symbol "ExpCons", sexp d, sexp a, sexp b ] sexp (ExpInParens d e) = List [ Symbol "ExpInParens", sexp d, sexp e ] sexp (ExpCustomInfix d lhe id rhe) = List [ Symbol "ExpCustomInfix" , sexp d , sexp lhe , sexp id , sexp rhe ] sexp (ExpMemberAccess d e id) = List [ Symbol "ExpMemberAccess" , sexp d , sexp e , sexp id ] sexp (ExpApp d rator rands) = List [ Symbol "ExpApp" , sexp d , sexp rator , toSexpList rands ] sexp (ExpPrim d rator) = List [ Symbol "ExpPrim" , sexp d , sexp rator ] sexp (ExpImport d qid) = List [ Symbol "ExpImport", sexp d, sexp qid ] sexp (ExpAssign d patE e) = List [ Symbol "ExpAssign" , sexp d , sexp patE , sexp e ] sexp (ExpTypeDec d tyDec) = List [ Symbol "ExpTypeDec", sexp d, sexp tyDec ] sexp (ExpDataDec d tyDec) = List [ Symbol "ExpDataDec", sexp d, sexp tyDec ] sexp (ExpProtoDec d protoId tyId constraints tyAnns) = List [ Symbol "ExpProtoDec" , sexp d , sexp protoId , sexp tyId , toSexpList constraints , toSexpList tyAnns ] sexp (ExpProtoImp d sty protoId constraints es) = List [ Symbol "ExpProtoImp" , sexp d , sexp sty , sexp protoId , toSexpList constraints , toSexpList es ] sexp (ExpTyAnn (TyAnn d id tyParamIds synTy constrs)) = List [ Symbol "ExpTyAnn" , sexp d , sexp id , toSexpList tyParamIds , sexp synTy , toSexpList constrs ] sexp (ExpWithAnn tyAnn e) = List [ Symbol "ExpWithAnn" , sexp tyAnn , sexp e ] sexp (ExpFunDef (FunDefFun d id argPatEs bodyE)) = List [ Symbol "ExpFunDef" , sexp d , sexp id , toSexpList argPatEs , sexp bodyE ] sexp (ExpFunDefClauses d id funDefs) = List [ Symbol "ExpFunDefClauses" , sexp d , sexp id , toSexpList funDefs ] sexp (ExpInterfaceDec d id tyParamIds tyAnns) = List [ Symbol "ExpInterfaceDec" , sexp d , sexp id , toSexpList tyParamIds , toSexpList tyAnns ] sexp (ExpModule d id es) = List [ Symbol "ExpModule", sexp d, sexp id, toSexpList es ] sexp (ExpTypeModule d id tyDec es) = List [ Symbol "ExpTypeModule" , sexp d , sexp id , sexp tyDec , toSexpList es ] sexp (ExpStruct d tyE fieldInits) = List [ Symbol "ExpStruct" , sexp d , List $ map sexp fieldInits ] sexp (ExpIfElse d e thenE elseE) = List [ Symbol "ExpIfElse" , sexp d , sexp e , sexp thenE , sexp elseE ] sexp (ExpMakeAdt d sTy i es) = List [ Symbol "ExpMakeAdt" , sexp d , sexp sTy , Atom $ show i , toSexpList es ] sexp (ExpGetAdtField d e index) = List [ Symbol "ExpGetAdtField" , sexp d , sexp e , Atom $ show index ] sexp (ExpTuple d es) = List [ Symbol "ExpTuple", sexp d, toSexpList es ] sexp (ExpSwitch d e clauses) = List [ Symbol "ExpSwitch", sexp d, sexp e, toSexpList clauses ] sexp (ExpCond d clauses) = List [ Symbol "ExpCond" , sexp d , toSexpList clauses ] sexp (ExpList d es) = List [ Symbol "ExpList", sexp d, toSexpList es ] sexp (ExpFun d paramIds e) = List [ Symbol "ExpFun" , sexp d , toSexpList paramIds , sexp e ] sexp (ExpNum d str) = List [ Symbol "ExpNum", sexp d, Symbol str ] sexp (ExpBool d b) = List [ Symbol "ExpBool", sexp d, Symbol $ show b ] sexp (ExpString d s) = List [ Symbol "ExpString", sexp d, Atom s ] sexp (ExpChar d s) = List [ Symbol "ExpChar", sexp d, Atom s ] sexp (ExpRef d id) = List [ Symbol "ExpRef", sexp d, sexp id ] sexp (ExpQualifiedRef d qid) = List [ Symbol "ExpQualifiedRef", sexp d, sexp qid ] sexp (ExpUnit d) = List [ Symbol "ExpUnit", sexp d ] sexp (ExpBegin d es) = List [ Symbol "ExpBegin" , sexp d , toSexpList es ] sexp (ExpPrecAssign d id level) = List [ Symbol "ExpPrecAssign" , sexp d , sexp id , Atom (show level) ] sexp (ExpFail d msg) = List [ Symbol "ExpFail", sexp d, Atom msg ] instance (Sexpable a, Sexpable id) => Sexpable (TyAnn a id) where sexp (TyAnn d id tyParamIds synTy constrs) = List [ Symbol "TyAnn" , sexp d , sexp id , toSexpList tyParamIds , sexp synTy , toSexpList constrs ] instance (Sexpable a) => Sexpable (ILFieldInit a) where sexp (ILFieldInit fieldId e) = List [ Symbol "ILFieldInit", sexp fieldId, sexp e ] instance (Sexpable a) => Sexpable (ILCase a) where sexp (ILCase d patE bodyE) = List [ Symbol "ILCase", sexp d, sexp patE, sexp bodyE ] instance (Sexpable a) => Sexpable (ILPat a) where sexp ilPat = case ilPat of ILPatInt d i -> List [ Symbol "ILPatInt", sexp d, Atom $ show i ] ILPatBool d b -> List [ Symbol "ILPatBool", sexp d, Symbol $ show b ] ILPatStr d s -> List [ Symbol "ILPatStr", sexp d, Atom s ] ILPatChar d s -> List [ Symbol "ILPatChar", sexp d, Atom s ] ILPatTuple d argPatEs -> List [ Symbol "ILPatTuple", sexp d, toSexpList argPatEs ] ILPatAdt d ctorId argPatEs -> List [ Symbol "ILPatAdt", sexp d, sexp ctorId, toSexpList argPatEs ] ILPatList d argPatEs -> List [ Symbol "ILPatList", sexp d, toSexpList argPatEs ] ILPatCons d patHd patTl -> List [ Symbol "ILPatCons", sexp d, sexp patHd, sexp patTl ] ILPatId d id -> List [ Symbol "ILPatId", sexp d, sexp id ] ILPatWildcard d -> List [ Symbol "ILPatWildcard", sexp d ] instance Sexpable Prim where sexp prim = case prim of PrimPrintln -> Symbol "PrimPrintln" PrimReadln -> Symbol "PrimReadln" PrimCharEq -> Symbol "PrimCharEq" PrimCharToInt -> Symbol "PrimCharToInt" PrimIntAdd -> Symbol "PrimIntAdd" PrimIntSub -> Symbol "PrimIntSub" PrimIntDiv -> Symbol "PrimIntDiv" PrimIntMul -> Symbol "PrimIntMul" PrimIntMod -> Symbol "PrimIntMod" PrimIntEq -> Symbol "PrimIntEq" PrimIntLt -> Symbol "PrimIntLt" PrimIntLeq -> Symbol "PrimIntLeq" PrimIntGt -> Symbol "PrimIntGt" PrimIntGeq -> Symbol "PrimIntGeq" PrimUnknown id -> List [ Symbol "PrimUnknown", sexp id ] instance (Sexpable a) => Sexpable (IL a) where sexp il = case il of ILCons d a b -> List [ Symbol "ILCons", sexp d, sexp a, sexp b ] ILApp d rator rands -> List [ Symbol "ILApp" , sexp d , sexp rator , toSexpList rands ] ILPrim d prim -> List [ Symbol "ILPrim" , sexp d , sexp prim ] ILAssign d patE e -> List [ Symbol "ILAssign", sexp d, sexp patE, sexp e ] ILWithAnn d tyAnn e -> List [ Symbol "ILWithAnn", sexp d, sexp tyAnn, sexp e ] ILFunDef d id paramIds bodyE -> List [ Symbol "ILFunDef", sexp d, sexp id, toSexpList paramIds, sexp bodyE ] ILStruct d typeId fieldInits -> List [ Symbol "ILStruct", sexp d, toSexpList fieldInits ] ILMakeAdt d typeId ctorIndex argEs -> List [ Symbol "ILMakeAdt" , sexp d , sexp typeId , Atom $ show ctorIndex , toSexpList argEs ] ILGetAdtField d e fieldIndex -> List [ Symbol "ILGetAdtField", sexp d, sexp e, Atom $ show fieldIndex ] ILTuple d argEs -> List [ Symbol "ILTuple", sexp d, toSexpList argEs ] ILSwitch d e clauses -> List [ Symbol "ILSwitch", sexp d, sexp e, toSexpList clauses ] ILList d argEs -> List [ Symbol "ILList", sexp d, toSexpList argEs ] ILFun d paramIds bodyE -> List [ Symbol "ILFun" , sexp d , toSexpList paramIds , sexp bodyE ] ILInt d i -> List [ Symbol "ILInt", sexp d, Atom $ show i ] ILBool d b -> List [ Symbol "ILBool", sexp d, Symbol $ show b ] ILStr d s -> List [ Symbol "ILStr", sexp d, Atom $ printf "\"%s\"" s ] ILChar d s -> List [ Symbol "ILChar", sexp d, Atom $ printf "\'%s\'" s ] ILUnit d -> List [ Symbol "ILUnit", sexp d ] ILRef d id -> List [ Symbol "ILRef", sexp d, sexp id ] ILBegin d es -> List [ Symbol "ILBegin", sexp d, toSexpList es ] ILFail d msg -> List [ Symbol "ILFail", sexp d, Atom $ printf "\"%s\"" msg ] ILMain d paramIds bodyE -> List [ Symbol "ILMain" , sexp d , toSexpList paramIds , sexp bodyE ] ILPlaceholder d ph -> List [ Symbol "ILPlaceholder" , sexp d , sexp ph ] instance Sexpable OverloadPlaceholder where sexp (PlaceholderMethod methodId ty) = List [ Symbol "PlaceholderMethod" , sexp methodId , sexp ty ] sexp (PlaceholderDict protoId ty) = List [ Symbol "PlaceholderDict" , sexp protoId , sexp ty ] instance (Sexpable a) => Sexpable (ILCompUnit a) where sexp (ILCompUnit d tyDecs es) = List [ Symbol "ILCompUnit", sexp d, toSexpList tyDecs, toSexpList es ] instance (Sexpable a) => CompilerOutput (ILCompUnit a) where render = showSexp sexpOfMap :: (Sexpable k, Sexpable v) => Map.Map k v -> Sexp sexpOfMap m = List $ map ( \\(k , v ) - > List [ sexp k , sexp v ] ) $ Map.toList m sexpOfMap m = toSexpList $ Map.keys m instance Sexpable Exports where sexp Exports { exportTypes, exportVars } = List [ Symbol "Exports" , sexpOfMap exportVars ] instance Sexpable Module where sexp (Module cloEnv paramIds exports) = List [ Symbol "Module" , List [ Symbol "CloEnv", sexpOfMap cloEnv ] , List [ Symbol "Params", toSexpList paramIds ] , sexp exports ] instance Sexpable Closure where sexp (Closure id _ cloEnv _ _) = List [ Symbol "Fun" , sexp id , List [ Symbol "CloEnv", sexpOfMap cloEnv ] ] instance Sexpable Struct where sexp (Struct ty fields) = List [ Symbol "Struct" , sexp ty , List $ map (\(id, v) -> List [ sexp id, sexp v ]) fields ] instance Sexpable Adt where sexp (Adt id i vs) = List [ Symbol "Adt" , sexp id , Symbol (show i) , toSexpList vs ] instance Sexpable Value where sexp (ValueInt i) = Symbol $ show i sexp (ValueBool b) = Symbol $ show b sexp (ValueChar c) = Symbol $ printf "#\\%c" c sexp (ValueModule m) = sexp m sexp (ValueFun clo) = sexp clo sexp (ValueStruct struct) = sexp struct sexp (ValueAdt adt) = sexp adt sexp (ValueTuple vs) = List [ Symbol "Tuple", toSexpList vs ] sexp (ValueList vs) | null vs = List [ Symbol "List", toSexpList vs ] | all (\v -> case v of ValueChar _ -> True _ -> False ) vs = Atom $ map (\(ValueChar c) -> c) vs | otherwise = List [ Symbol "List", toSexpList vs ] sexp ValueUnit = Symbol "Unit" sexp (Err str) = List [ Symbol "Error", Atom str ] instance Sexpable Ty where sexp (TyApp TyConInt []) = Symbol "Int" sexp (TyApp TyConBool []) = Symbol "Bool" sexp (TyApp TyConChar []) = Symbol "Char" sexp (TyApp tyCon tys) = List [ Symbol "App" , sexp tyCon , toSexpList tys ] sexp (TyPoly tyVars [] ty) = List [ Symbol "Poly" , toSexpList tyVars , sexp ty ] sexp (TyPoly tyVars ctx ty) = List [ Symbol "Poly" , toSexpList tyVars , ctxSexp , sexp ty ] where ctxSexp = List $ map (\(ty, protoId) -> List [ sexp ty, sexp protoId ]) ctx sexp (TyOverloaded ctx ty) = List [ Symbol "Overloaded" , ctxSexp , sexp ty ] where ctxSexp = List $ map (\(ty, protoId) -> List [ sexp ty, sexp protoId ]) ctx sexp (TyVar [] tyVar) = List [ Symbol "Var", sexp tyVar ] sexp (TyVar straints tyVar) = List [ Symbol "Var" , toSexpList straints , sexp tyVar ] sexp (TyMeta [] id) = List [ Symbol "Meta", sexp id ] sexp (TyMeta straints id) = List [ Symbol "Meta" , toSexpList straints , sexp id ] sexp (TyRef qid) = List [ Symbol "Ref", sexp qid ] sexp (TyRigid ty) = List [ Symbol "Rigid", sexp ty ] instance Sexpable TyConstraint where sexp (TyConstraint protoId) = List [ Symbol "TyConstraint", sexp protoId ] instance CompilerOutput TyConstraint where render (TyConstraint protoId) = render protoId instance CompilerOutput Ty where render (TyApp TyConInt []) = "Int" render (TyApp TyConBool []) = "Bool" render (TyApp TyConChar []) = "Char" render (TyApp TyConArrow [retTy]) = printf "(-> %s)" $ render retTy render (TyApp TyConArrow tys) = let tyStrs = map render tys in intercalate " -> " tyStrs render (TyApp tyCon tys) = printf "%s<%s>" (render tyCon) (renderCommaSep tys) render (TyPoly _ [] ty) = render ty render (TyPoly _ ctx ty) = printf "(%s) => %s" contextStr (render ty) where contextStr = intercalate "," $ map (\(ty, protoId) -> printf "%s : %s" (render ty) (render protoId)) ctx render (TyVar [] tyVar) = render tyVar render (TyVar straints tyVar) = printf "%s(%s)" (intercalate ", " $ map render straints) (render tyVar) render (TyMeta [] id) = render id render (TyMeta straints id) = printf "%s(%s)" (intercalate ", " $ map render straints) (render id) render (TyRef qid) = render qid render (TyOverloaded context ty) = printf "(%s) => %s" contextStr (render ty) where contextStr = intercalate "," $ map (\(ty, protoId) -> printf "%s(%s)" (render protoId) (render ty)) context render (TyRigid ty) = printf "rigid type %s" $ render ty render ty = showSexp ty instance Sexpable TyCon where sexp TyConInt = Symbol "Int" sexp TyConBool = Symbol "Bool" sexp TyConChar = Symbol "Char" sexp TyConUnit = Symbol "Unit" sexp TyConList = Symbol "List" sexp TyConTuple = Symbol "Tuple" sexp TyConArrow = Symbol "Arrow" sexp (TyConStruct fieldNames) = List [ Symbol "Struct", toSexpList fieldNames ] sexp (TyConAdt ctorNames) = List [ Symbol "Adt", toSexpList ctorNames ] sexp (TyConTyFun tyVarIds ty) = List [ Symbol "TyFun", toSexpList tyVarIds, sexp ty ] sexp (TyConUnique id tyCon) = List [ Symbol "Unique", sexp id, sexp tyCon ] sexp (TyConTyVar varId) = List [ Symbol "TyVar", sexp varId ] instance CompilerOutput TyCon where render TyConInt = "Int" render TyConBool = "Bool" render TyConChar = "Char" render TyConUnit = "Unit" render TyConList = "List" render TyConTuple = "Tuple" render TyConArrow = "(->)" render (TyConStruct _) = "<<struct>>" render (TyConAdt _) = "<<adt>>" render (TyConUnique id TyConTyFun{}) = render id render (TyConTyFun tyVarIds ty) = printf "(tyfun<%s> -> %s)" (renderCommaSep tyVarIds) (render ty) render (TyConTyVar varId) = render varId instance CompilerOutput Value where render v = case v of ValueInt i -> show i ValueBool b -> show b ValueChar c -> printf "'%c'" c ValueFun (Closure fid fty _ paramIds _) -> printf "fun %s : %s" (show fid) (render fty) ValueStruct struct -> "struct" ValueAdt (Adt uid i []) -> printf "%s" (show uid) ValueAdt (Adt uid i vs) -> printf "%s(%s)" (show uid) (concat . intersperse ", " $ map render vs) ValueTuple vs -> printf "%%(%s)" $ concat . intersperse ", " $ map render vs ValueList vs@((ValueChar c) : _) -> let str = map (\(ValueChar c) -> c) vs in show str ValueList vs -> printf "[%s]" $ concat . intersperse ", " $ map render vs ValueUnit -> "Unit" ValuePrim prim -> "prim" Err str -> "Error = " ++ str
null
https://raw.githubusercontent.com/Zoetermeer/latro/afff03377e65e93a8a1faaa836b21f012758de0c/src/Latro/Semant/Display.hs
haskell
# LANGUAGE NamedFieldPuns, FlexibleInstances # To satisfy (Sexpable RawId)
module Latro.Semant.Display where import Data.List (intercalate, intersperse) import qualified Data.Map as Map import Latro.Ast import Latro.Output import Latro.Semant import Latro.Sexpable import Text.Printf (printf) instance Sexpable v => Sexpable (Maybe v) where sexp (Just v) = sexp v sexp Nothing = List [] instance Sexpable RawId where sexp = Symbol instance Sexpable SourcePos where sexp (SourcePos filePath lineNum colNum) = List [ Symbol "SourcePos" , Atom filePath , Symbol $ show lineNum , Symbol $ show colNum ] instance Sexpable CheckedData where sexp (OfTy srcPos ty) = List [ Symbol "OfTy" , sexp srcPos , sexp ty ] instance (Sexpable a, Sexpable id) => Sexpable (QualifiedId a id) where sexp (Id _ raw) = sexp raw sexp (Path _ qid raw) = Symbol $ printf "%s.%s" (showSexp qid) (showSexp raw) instance (Sexpable a, CompilerOutput id) => CompilerOutput (QualifiedId a id) where render (Id _ raw) = render raw render (Path _ qid raw) = printf "%s.%s" (render qid) (render raw) instance (Sexpable a, Sexpable id) => Sexpable (SynTy a id) where sexp (SynTyInt d) = List [ Symbol "Int", sexp d ] sexp (SynTyBool d) = List [ Symbol "Bool", sexp d ] sexp (SynTyChar d) = List [ Symbol "Char", sexp d ] sexp (SynTyUnit d) = List [ Symbol "Unit", sexp d ] sexp (SynTyArrow d paramTys retTy) = List $ sexp d : (intersperse (Symbol "->" ) . map sexp) (paramTys ++ [retTy]) sexp (SynTyStruct d fields) = List [ Symbol "Struct" , sexp d , List $ map (\(id, ty) -> List [ Symbol "Field", sexp id, sexp ty ]) fields ] sexp (SynTyAdt d id alts) = List [ Symbol "ADT" , sexp d , sexp id , toSexpList alts ] sexp (SynTyTuple d synTys) = List [ Symbol "Tuple" , sexp d, toSexpList synTys ] sexp (SynTyList d synTy) = List [ Symbol "List", sexp d, sexp synTy ] sexp (SynTyRef d qid []) = List [ Symbol "Ref", sexp d, sexp qid ] sexp (SynTyRef d qid tyParamIds) = List [ Symbol "Ref", sexp d, sexp qid, toSexpList tyParamIds ] instance CompilerOutput RawId where render id = id instance Sexpable UniqId where sexp (UserId raw) = Symbol raw sexp (UniqId i raw) = List [ Symbol "Id", Symbol raw, Symbol $ show i ] instance CompilerOutput UniqId where render (UserId raw) = raw render (UniqId i raw) = printf "%s@%i" raw i instance (Sexpable a, Sexpable id) => Sexpable (CompUnit a id) where sexp (CompUnit d es) = List [ Symbol "CompUnit" , sexp d , toSexpList es ] instance (Sexpable a, Sexpable id) => CompilerOutput (CompUnit a id) where render = showSexp instance (Sexpable a, Sexpable id) => Sexpable (AdtAlternative a id) where sexp (AdtAlternative d id i sTys) = List [ Symbol "AdtAlternative" , sexp d , sexp id , Symbol $ show i , toSexpList sTys ] instance (Sexpable a, Sexpable id) => Sexpable (TypeDec a id) where sexp (TypeDecTy d id tyParamIds sTy) = List [ Symbol "TypeDecTy" , sexp d , sexp id , toSexpList tyParamIds , sexp sTy ] sexp (TypeDecAdt d id tyParamIds alts) = List [ Symbol "TypeDecAdt" , sexp d , sexp id , toSexpList tyParamIds , toSexpList alts ] sexp (TypeDecImplicit d tyDec) = List [ Symbol "TypeDecImplicit" , sexp d , sexp tyDec ] sexp (TypeDecEmpty d id tyParamIds) = List [ Symbol "TypeDecEmpty" , sexp d , sexp id , toSexpList tyParamIds ] instance (Sexpable a, Sexpable id) => Sexpable (PatExp a id) where sexp (PatExpNumLiteral d str) = List [ Symbol "PatExpNumLiteral", sexp d, Atom str ] sexp (PatExpBoolLiteral d b) = List [ Symbol "PatExpBoolLiteral", sexp d, Symbol $ show b ] sexp (PatExpStringLiteral d s) = List [ Symbol "PatExpStringLiteral", sexp d, Atom s ] sexp (PatExpCharLiteral d s) = List [ Symbol "PatExpCharLiteral", sexp d, Atom s ] sexp (PatExpTuple d patEs) = List [ Symbol "PatExpTuple", sexp d, toSexpList patEs ] sexp (PatExpAdt d qid patEs) = List [ Symbol "PatExpAdt", sexp d, sexp qid, toSexpList patEs ] sexp (PatExpList d patEs) = List [ Symbol "PatExpList", sexp d, toSexpList patEs ] sexp (PatExpListCons d a b) = List [ Symbol "PatExpListCons", sexp d, sexp a, sexp b ] sexp (PatExpId d id) = List [ Symbol "PatExpId", sexp d, sexp id ] sexp (PatExpWildcard d) = List [ Symbol "PatExpWildcard", sexp d ] instance (Sexpable a, Sexpable id) => Sexpable (CaseClause a id) where sexp (CaseClause d patE e) = List [ Symbol "CaseClause" , sexp d , sexp patE , sexp e ] instance (Sexpable a, Sexpable id) => Sexpable (FunDef a id) where sexp (FunDefFun d id argPatEs e) = List [ Symbol "FunDefFun" , sexp d , sexp id , toSexpList argPatEs , sexp e ] instance (Sexpable a, Sexpable id) => Sexpable (Constraint a id) where sexp (Constraint d tyId protoId) = List [ Symbol "Constraint" , sexp d , sexp tyId , sexp protoId ] instance (Sexpable a, Sexpable id) => Sexpable (FieldInit a id) where sexp (FieldInit id e) = List [ sexp id, sexp e ] instance (Sexpable a, Sexpable id) => Sexpable (AnnDef a id) where sexp (AnnDefModule d id e) = List [ Symbol "AnnDefModule", sexp d, sexp e ] sexp (AnnDefFun d funDef) = List [ Symbol "AnnDefFun", sexp d, sexp funDef ] instance (Sexpable a, Sexpable id) => Sexpable (CondCaseClause a id) where sexp (CondCaseClause d pExp bodyE) = List [ Symbol "CondCaseClause" , sexp d , sexp pExp , sexp bodyE ] sexp (CondCaseClauseWildcard d bodyE) = List [ Symbol "CondCaseClauseWildcard", sexp d, sexp bodyE ] instance (Sexpable a, Sexpable id) => Sexpable (Exp a id) where sexp (ExpCons d a b) = List [ Symbol "ExpCons", sexp d, sexp a, sexp b ] sexp (ExpInParens d e) = List [ Symbol "ExpInParens", sexp d, sexp e ] sexp (ExpCustomInfix d lhe id rhe) = List [ Symbol "ExpCustomInfix" , sexp d , sexp lhe , sexp id , sexp rhe ] sexp (ExpMemberAccess d e id) = List [ Symbol "ExpMemberAccess" , sexp d , sexp e , sexp id ] sexp (ExpApp d rator rands) = List [ Symbol "ExpApp" , sexp d , sexp rator , toSexpList rands ] sexp (ExpPrim d rator) = List [ Symbol "ExpPrim" , sexp d , sexp rator ] sexp (ExpImport d qid) = List [ Symbol "ExpImport", sexp d, sexp qid ] sexp (ExpAssign d patE e) = List [ Symbol "ExpAssign" , sexp d , sexp patE , sexp e ] sexp (ExpTypeDec d tyDec) = List [ Symbol "ExpTypeDec", sexp d, sexp tyDec ] sexp (ExpDataDec d tyDec) = List [ Symbol "ExpDataDec", sexp d, sexp tyDec ] sexp (ExpProtoDec d protoId tyId constraints tyAnns) = List [ Symbol "ExpProtoDec" , sexp d , sexp protoId , sexp tyId , toSexpList constraints , toSexpList tyAnns ] sexp (ExpProtoImp d sty protoId constraints es) = List [ Symbol "ExpProtoImp" , sexp d , sexp sty , sexp protoId , toSexpList constraints , toSexpList es ] sexp (ExpTyAnn (TyAnn d id tyParamIds synTy constrs)) = List [ Symbol "ExpTyAnn" , sexp d , sexp id , toSexpList tyParamIds , sexp synTy , toSexpList constrs ] sexp (ExpWithAnn tyAnn e) = List [ Symbol "ExpWithAnn" , sexp tyAnn , sexp e ] sexp (ExpFunDef (FunDefFun d id argPatEs bodyE)) = List [ Symbol "ExpFunDef" , sexp d , sexp id , toSexpList argPatEs , sexp bodyE ] sexp (ExpFunDefClauses d id funDefs) = List [ Symbol "ExpFunDefClauses" , sexp d , sexp id , toSexpList funDefs ] sexp (ExpInterfaceDec d id tyParamIds tyAnns) = List [ Symbol "ExpInterfaceDec" , sexp d , sexp id , toSexpList tyParamIds , toSexpList tyAnns ] sexp (ExpModule d id es) = List [ Symbol "ExpModule", sexp d, sexp id, toSexpList es ] sexp (ExpTypeModule d id tyDec es) = List [ Symbol "ExpTypeModule" , sexp d , sexp id , sexp tyDec , toSexpList es ] sexp (ExpStruct d tyE fieldInits) = List [ Symbol "ExpStruct" , sexp d , List $ map sexp fieldInits ] sexp (ExpIfElse d e thenE elseE) = List [ Symbol "ExpIfElse" , sexp d , sexp e , sexp thenE , sexp elseE ] sexp (ExpMakeAdt d sTy i es) = List [ Symbol "ExpMakeAdt" , sexp d , sexp sTy , Atom $ show i , toSexpList es ] sexp (ExpGetAdtField d e index) = List [ Symbol "ExpGetAdtField" , sexp d , sexp e , Atom $ show index ] sexp (ExpTuple d es) = List [ Symbol "ExpTuple", sexp d, toSexpList es ] sexp (ExpSwitch d e clauses) = List [ Symbol "ExpSwitch", sexp d, sexp e, toSexpList clauses ] sexp (ExpCond d clauses) = List [ Symbol "ExpCond" , sexp d , toSexpList clauses ] sexp (ExpList d es) = List [ Symbol "ExpList", sexp d, toSexpList es ] sexp (ExpFun d paramIds e) = List [ Symbol "ExpFun" , sexp d , toSexpList paramIds , sexp e ] sexp (ExpNum d str) = List [ Symbol "ExpNum", sexp d, Symbol str ] sexp (ExpBool d b) = List [ Symbol "ExpBool", sexp d, Symbol $ show b ] sexp (ExpString d s) = List [ Symbol "ExpString", sexp d, Atom s ] sexp (ExpChar d s) = List [ Symbol "ExpChar", sexp d, Atom s ] sexp (ExpRef d id) = List [ Symbol "ExpRef", sexp d, sexp id ] sexp (ExpQualifiedRef d qid) = List [ Symbol "ExpQualifiedRef", sexp d, sexp qid ] sexp (ExpUnit d) = List [ Symbol "ExpUnit", sexp d ] sexp (ExpBegin d es) = List [ Symbol "ExpBegin" , sexp d , toSexpList es ] sexp (ExpPrecAssign d id level) = List [ Symbol "ExpPrecAssign" , sexp d , sexp id , Atom (show level) ] sexp (ExpFail d msg) = List [ Symbol "ExpFail", sexp d, Atom msg ] instance (Sexpable a, Sexpable id) => Sexpable (TyAnn a id) where sexp (TyAnn d id tyParamIds synTy constrs) = List [ Symbol "TyAnn" , sexp d , sexp id , toSexpList tyParamIds , sexp synTy , toSexpList constrs ] instance (Sexpable a) => Sexpable (ILFieldInit a) where sexp (ILFieldInit fieldId e) = List [ Symbol "ILFieldInit", sexp fieldId, sexp e ] instance (Sexpable a) => Sexpable (ILCase a) where sexp (ILCase d patE bodyE) = List [ Symbol "ILCase", sexp d, sexp patE, sexp bodyE ] instance (Sexpable a) => Sexpable (ILPat a) where sexp ilPat = case ilPat of ILPatInt d i -> List [ Symbol "ILPatInt", sexp d, Atom $ show i ] ILPatBool d b -> List [ Symbol "ILPatBool", sexp d, Symbol $ show b ] ILPatStr d s -> List [ Symbol "ILPatStr", sexp d, Atom s ] ILPatChar d s -> List [ Symbol "ILPatChar", sexp d, Atom s ] ILPatTuple d argPatEs -> List [ Symbol "ILPatTuple", sexp d, toSexpList argPatEs ] ILPatAdt d ctorId argPatEs -> List [ Symbol "ILPatAdt", sexp d, sexp ctorId, toSexpList argPatEs ] ILPatList d argPatEs -> List [ Symbol "ILPatList", sexp d, toSexpList argPatEs ] ILPatCons d patHd patTl -> List [ Symbol "ILPatCons", sexp d, sexp patHd, sexp patTl ] ILPatId d id -> List [ Symbol "ILPatId", sexp d, sexp id ] ILPatWildcard d -> List [ Symbol "ILPatWildcard", sexp d ] instance Sexpable Prim where sexp prim = case prim of PrimPrintln -> Symbol "PrimPrintln" PrimReadln -> Symbol "PrimReadln" PrimCharEq -> Symbol "PrimCharEq" PrimCharToInt -> Symbol "PrimCharToInt" PrimIntAdd -> Symbol "PrimIntAdd" PrimIntSub -> Symbol "PrimIntSub" PrimIntDiv -> Symbol "PrimIntDiv" PrimIntMul -> Symbol "PrimIntMul" PrimIntMod -> Symbol "PrimIntMod" PrimIntEq -> Symbol "PrimIntEq" PrimIntLt -> Symbol "PrimIntLt" PrimIntLeq -> Symbol "PrimIntLeq" PrimIntGt -> Symbol "PrimIntGt" PrimIntGeq -> Symbol "PrimIntGeq" PrimUnknown id -> List [ Symbol "PrimUnknown", sexp id ] instance (Sexpable a) => Sexpable (IL a) where sexp il = case il of ILCons d a b -> List [ Symbol "ILCons", sexp d, sexp a, sexp b ] ILApp d rator rands -> List [ Symbol "ILApp" , sexp d , sexp rator , toSexpList rands ] ILPrim d prim -> List [ Symbol "ILPrim" , sexp d , sexp prim ] ILAssign d patE e -> List [ Symbol "ILAssign", sexp d, sexp patE, sexp e ] ILWithAnn d tyAnn e -> List [ Symbol "ILWithAnn", sexp d, sexp tyAnn, sexp e ] ILFunDef d id paramIds bodyE -> List [ Symbol "ILFunDef", sexp d, sexp id, toSexpList paramIds, sexp bodyE ] ILStruct d typeId fieldInits -> List [ Symbol "ILStruct", sexp d, toSexpList fieldInits ] ILMakeAdt d typeId ctorIndex argEs -> List [ Symbol "ILMakeAdt" , sexp d , sexp typeId , Atom $ show ctorIndex , toSexpList argEs ] ILGetAdtField d e fieldIndex -> List [ Symbol "ILGetAdtField", sexp d, sexp e, Atom $ show fieldIndex ] ILTuple d argEs -> List [ Symbol "ILTuple", sexp d, toSexpList argEs ] ILSwitch d e clauses -> List [ Symbol "ILSwitch", sexp d, sexp e, toSexpList clauses ] ILList d argEs -> List [ Symbol "ILList", sexp d, toSexpList argEs ] ILFun d paramIds bodyE -> List [ Symbol "ILFun" , sexp d , toSexpList paramIds , sexp bodyE ] ILInt d i -> List [ Symbol "ILInt", sexp d, Atom $ show i ] ILBool d b -> List [ Symbol "ILBool", sexp d, Symbol $ show b ] ILStr d s -> List [ Symbol "ILStr", sexp d, Atom $ printf "\"%s\"" s ] ILChar d s -> List [ Symbol "ILChar", sexp d, Atom $ printf "\'%s\'" s ] ILUnit d -> List [ Symbol "ILUnit", sexp d ] ILRef d id -> List [ Symbol "ILRef", sexp d, sexp id ] ILBegin d es -> List [ Symbol "ILBegin", sexp d, toSexpList es ] ILFail d msg -> List [ Symbol "ILFail", sexp d, Atom $ printf "\"%s\"" msg ] ILMain d paramIds bodyE -> List [ Symbol "ILMain" , sexp d , toSexpList paramIds , sexp bodyE ] ILPlaceholder d ph -> List [ Symbol "ILPlaceholder" , sexp d , sexp ph ] instance Sexpable OverloadPlaceholder where sexp (PlaceholderMethod methodId ty) = List [ Symbol "PlaceholderMethod" , sexp methodId , sexp ty ] sexp (PlaceholderDict protoId ty) = List [ Symbol "PlaceholderDict" , sexp protoId , sexp ty ] instance (Sexpable a) => Sexpable (ILCompUnit a) where sexp (ILCompUnit d tyDecs es) = List [ Symbol "ILCompUnit", sexp d, toSexpList tyDecs, toSexpList es ] instance (Sexpable a) => CompilerOutput (ILCompUnit a) where render = showSexp sexpOfMap :: (Sexpable k, Sexpable v) => Map.Map k v -> Sexp sexpOfMap m = List $ map ( \\(k , v ) - > List [ sexp k , sexp v ] ) $ Map.toList m sexpOfMap m = toSexpList $ Map.keys m instance Sexpable Exports where sexp Exports { exportTypes, exportVars } = List [ Symbol "Exports" , sexpOfMap exportVars ] instance Sexpable Module where sexp (Module cloEnv paramIds exports) = List [ Symbol "Module" , List [ Symbol "CloEnv", sexpOfMap cloEnv ] , List [ Symbol "Params", toSexpList paramIds ] , sexp exports ] instance Sexpable Closure where sexp (Closure id _ cloEnv _ _) = List [ Symbol "Fun" , sexp id , List [ Symbol "CloEnv", sexpOfMap cloEnv ] ] instance Sexpable Struct where sexp (Struct ty fields) = List [ Symbol "Struct" , sexp ty , List $ map (\(id, v) -> List [ sexp id, sexp v ]) fields ] instance Sexpable Adt where sexp (Adt id i vs) = List [ Symbol "Adt" , sexp id , Symbol (show i) , toSexpList vs ] instance Sexpable Value where sexp (ValueInt i) = Symbol $ show i sexp (ValueBool b) = Symbol $ show b sexp (ValueChar c) = Symbol $ printf "#\\%c" c sexp (ValueModule m) = sexp m sexp (ValueFun clo) = sexp clo sexp (ValueStruct struct) = sexp struct sexp (ValueAdt adt) = sexp adt sexp (ValueTuple vs) = List [ Symbol "Tuple", toSexpList vs ] sexp (ValueList vs) | null vs = List [ Symbol "List", toSexpList vs ] | all (\v -> case v of ValueChar _ -> True _ -> False ) vs = Atom $ map (\(ValueChar c) -> c) vs | otherwise = List [ Symbol "List", toSexpList vs ] sexp ValueUnit = Symbol "Unit" sexp (Err str) = List [ Symbol "Error", Atom str ] instance Sexpable Ty where sexp (TyApp TyConInt []) = Symbol "Int" sexp (TyApp TyConBool []) = Symbol "Bool" sexp (TyApp TyConChar []) = Symbol "Char" sexp (TyApp tyCon tys) = List [ Symbol "App" , sexp tyCon , toSexpList tys ] sexp (TyPoly tyVars [] ty) = List [ Symbol "Poly" , toSexpList tyVars , sexp ty ] sexp (TyPoly tyVars ctx ty) = List [ Symbol "Poly" , toSexpList tyVars , ctxSexp , sexp ty ] where ctxSexp = List $ map (\(ty, protoId) -> List [ sexp ty, sexp protoId ]) ctx sexp (TyOverloaded ctx ty) = List [ Symbol "Overloaded" , ctxSexp , sexp ty ] where ctxSexp = List $ map (\(ty, protoId) -> List [ sexp ty, sexp protoId ]) ctx sexp (TyVar [] tyVar) = List [ Symbol "Var", sexp tyVar ] sexp (TyVar straints tyVar) = List [ Symbol "Var" , toSexpList straints , sexp tyVar ] sexp (TyMeta [] id) = List [ Symbol "Meta", sexp id ] sexp (TyMeta straints id) = List [ Symbol "Meta" , toSexpList straints , sexp id ] sexp (TyRef qid) = List [ Symbol "Ref", sexp qid ] sexp (TyRigid ty) = List [ Symbol "Rigid", sexp ty ] instance Sexpable TyConstraint where sexp (TyConstraint protoId) = List [ Symbol "TyConstraint", sexp protoId ] instance CompilerOutput TyConstraint where render (TyConstraint protoId) = render protoId instance CompilerOutput Ty where render (TyApp TyConInt []) = "Int" render (TyApp TyConBool []) = "Bool" render (TyApp TyConChar []) = "Char" render (TyApp TyConArrow [retTy]) = printf "(-> %s)" $ render retTy render (TyApp TyConArrow tys) = let tyStrs = map render tys in intercalate " -> " tyStrs render (TyApp tyCon tys) = printf "%s<%s>" (render tyCon) (renderCommaSep tys) render (TyPoly _ [] ty) = render ty render (TyPoly _ ctx ty) = printf "(%s) => %s" contextStr (render ty) where contextStr = intercalate "," $ map (\(ty, protoId) -> printf "%s : %s" (render ty) (render protoId)) ctx render (TyVar [] tyVar) = render tyVar render (TyVar straints tyVar) = printf "%s(%s)" (intercalate ", " $ map render straints) (render tyVar) render (TyMeta [] id) = render id render (TyMeta straints id) = printf "%s(%s)" (intercalate ", " $ map render straints) (render id) render (TyRef qid) = render qid render (TyOverloaded context ty) = printf "(%s) => %s" contextStr (render ty) where contextStr = intercalate "," $ map (\(ty, protoId) -> printf "%s(%s)" (render protoId) (render ty)) context render (TyRigid ty) = printf "rigid type %s" $ render ty render ty = showSexp ty instance Sexpable TyCon where sexp TyConInt = Symbol "Int" sexp TyConBool = Symbol "Bool" sexp TyConChar = Symbol "Char" sexp TyConUnit = Symbol "Unit" sexp TyConList = Symbol "List" sexp TyConTuple = Symbol "Tuple" sexp TyConArrow = Symbol "Arrow" sexp (TyConStruct fieldNames) = List [ Symbol "Struct", toSexpList fieldNames ] sexp (TyConAdt ctorNames) = List [ Symbol "Adt", toSexpList ctorNames ] sexp (TyConTyFun tyVarIds ty) = List [ Symbol "TyFun", toSexpList tyVarIds, sexp ty ] sexp (TyConUnique id tyCon) = List [ Symbol "Unique", sexp id, sexp tyCon ] sexp (TyConTyVar varId) = List [ Symbol "TyVar", sexp varId ] instance CompilerOutput TyCon where render TyConInt = "Int" render TyConBool = "Bool" render TyConChar = "Char" render TyConUnit = "Unit" render TyConList = "List" render TyConTuple = "Tuple" render TyConArrow = "(->)" render (TyConStruct _) = "<<struct>>" render (TyConAdt _) = "<<adt>>" render (TyConUnique id TyConTyFun{}) = render id render (TyConTyFun tyVarIds ty) = printf "(tyfun<%s> -> %s)" (renderCommaSep tyVarIds) (render ty) render (TyConTyVar varId) = render varId instance CompilerOutput Value where render v = case v of ValueInt i -> show i ValueBool b -> show b ValueChar c -> printf "'%c'" c ValueFun (Closure fid fty _ paramIds _) -> printf "fun %s : %s" (show fid) (render fty) ValueStruct struct -> "struct" ValueAdt (Adt uid i []) -> printf "%s" (show uid) ValueAdt (Adt uid i vs) -> printf "%s(%s)" (show uid) (concat . intersperse ", " $ map render vs) ValueTuple vs -> printf "%%(%s)" $ concat . intersperse ", " $ map render vs ValueList vs@((ValueChar c) : _) -> let str = map (\(ValueChar c) -> c) vs in show str ValueList vs -> printf "[%s]" $ concat . intersperse ", " $ map render vs ValueUnit -> "Unit" ValuePrim prim -> "prim" Err str -> "Error = " ++ str
f9b379d071003da887bbddaa6cbe9bc4f20d546c7ba61fe93c97d10d76d3ebd4
pomanu/waxeye
transform.rkt
#lang racket/base (require waxeye/ast "action.rkt" "expand.rkt" "gen.rkt" "util.rkt") (provide (all-defined-out)) ;; The hash table for the names of the non-terminals (define nt-names (make-hash)) ;; Transforms the grammar and performs sanity checks (define (transform-grammar g) (and (check-not-empty g) (collect-actions g) (collect-nt-names g) (check-refs g) (expand-grammar g))) (define (check-not-empty g) (when (null? (ast-c g)) (error 'check-not-empty "grammar is empty"))) (define (collect-nt-names g) (let ((ok #t)) (for-each (lambda (a) (let* ((name (get-non-term a)) (found (hash-ref nt-names name #f))) (if found (begin (set! ok #f) (error 'check-duplicate "duplicate definition of non-terminal: ~a" name)) (hash-set! nt-names name name)))) (ast-c g)) ok)) ;; Checks that referenced non-terminals have been defined (define (check-refs grammar) (define (visit-nt exp) (let ((name (list->string (ast-c exp)))) (unless (hash-ref nt-names name #f) (error 'waxeye "undefined reference to non-terminal: ~a" name)))) (define (visit-alternation exp) (for-each visit-sequence (ast-c exp))) (define (visit-sequence exp) (for-each visit-unit (ast-c exp))) (define (visit-unit exp) (let* ((el (ast-c exp)) (el-len (length el))) (visit-exp (list-ref el (- el-len 1))))) (define (visit-exp exp) (let ((type (ast-t exp))) (case type ((alternation) (visit-alternation exp)) ((identifier) (visit-nt exp)) ((sequence) (visit-sequence exp)) ((unit) (visit-unit exp))))) (define (check-nt-refs def) (visit-alternation (caddr (ast-c def)))) (for-each check-nt-refs (get-defs grammar)))
null
https://raw.githubusercontent.com/pomanu/waxeye/8c2fdc7d85d7c4f87adfc8f482a311b55bfda1e2/src/waxeye/transform.rkt
racket
The hash table for the names of the non-terminals Transforms the grammar and performs sanity checks Checks that referenced non-terminals have been defined
#lang racket/base (require waxeye/ast "action.rkt" "expand.rkt" "gen.rkt" "util.rkt") (provide (all-defined-out)) (define nt-names (make-hash)) (define (transform-grammar g) (and (check-not-empty g) (collect-actions g) (collect-nt-names g) (check-refs g) (expand-grammar g))) (define (check-not-empty g) (when (null? (ast-c g)) (error 'check-not-empty "grammar is empty"))) (define (collect-nt-names g) (let ((ok #t)) (for-each (lambda (a) (let* ((name (get-non-term a)) (found (hash-ref nt-names name #f))) (if found (begin (set! ok #f) (error 'check-duplicate "duplicate definition of non-terminal: ~a" name)) (hash-set! nt-names name name)))) (ast-c g)) ok)) (define (check-refs grammar) (define (visit-nt exp) (let ((name (list->string (ast-c exp)))) (unless (hash-ref nt-names name #f) (error 'waxeye "undefined reference to non-terminal: ~a" name)))) (define (visit-alternation exp) (for-each visit-sequence (ast-c exp))) (define (visit-sequence exp) (for-each visit-unit (ast-c exp))) (define (visit-unit exp) (let* ((el (ast-c exp)) (el-len (length el))) (visit-exp (list-ref el (- el-len 1))))) (define (visit-exp exp) (let ((type (ast-t exp))) (case type ((alternation) (visit-alternation exp)) ((identifier) (visit-nt exp)) ((sequence) (visit-sequence exp)) ((unit) (visit-unit exp))))) (define (check-nt-refs def) (visit-alternation (caddr (ast-c def)))) (for-each check-nt-refs (get-defs grammar)))
d3e98dca8cfd1b27de18cdc8197d94ba82609beedb99753ac5917f45c2aca08e
upenn-cis1xx/camelot
verbose.ml
(* Prepending with list construction and append, where cons should be used *) let f t = [1] @ t (* Likewise, but even more verbose *) let f t = 1 :: [] @ t (* Tuple projection bad! *) let f (t: int * int) = fst t + snd t (* Nested ifs :( - we skip local lets and sequencing to get the actual return type for now *) let x = true let y = false let dounit () = () No Flagging here - only two levels deep let f () = if x then (if x then x else y) else y let f () = if x then (if x then x else let z = 3 in dounit(); (if z = 2 then x else y) ) else y (* Nested matched bad as well *) let f () = let l = [] in begin match l with | [] -> begin match l with | [] -> let z = [] in begin match z with | _ -> true end | _ -> false end | _ -> true end If statement three layers deep let z = if x then 1 else if y then 2 else if x & y then 3 else 4 If statement four layers deep let z = if x then 1 else if y then 2 else if x & y then 3 else if z = 4 then 3 else 9 (* shouldn't trigger *) let z = (x = TConstr 3 || x = TConstr 4) let z = (x = [12] || x = [50]) let z = (x = 5 || x = 6) let z = (x = TConstr 3 && x = TConstr 4) let z = (x = [12] && x = [50]) let z = (x = 5 && x = 6) (* TODO: perhaps this one should trigger and say just change to true *) let z = (x = TConstr 3 || not (x = TConstr 3)) (* should trigger *) let z = (x = [] || x = []) let z = (x = None || x = None) let z = (x = 5 || x = 5) let z = (x = TConstr 3 || x = TConstr 3) let z = (x = TConstr 3 || x = TConstr 3 || x = TConstr 4) let z = (x = TConstr 3 || x = TConstr 4 || x = TConstr 3) let z = (x = [] && x = []) let z = (x = None && x = None) let z = (x = 5 && x = 5) let z = (x = TConstr 3 && x = TConstr 3) let z = (x = TConstr 3 && x = TConstr 3 && x = TConstr 4) let z = (x = TConstr 3 && x = TConstr 4 && x = TConstr 3)
null
https://raw.githubusercontent.com/upenn-cis1xx/camelot/87d9a0bcace974fe5fbe4dc3da2202ee01c17ad4/test/examples/verbose.ml
ocaml
Prepending with list construction and append, where cons should be used Likewise, but even more verbose Tuple projection bad! Nested ifs :( - we skip local lets and sequencing to get the actual return type for now Nested matched bad as well shouldn't trigger TODO: perhaps this one should trigger and say just change to true should trigger
let f t = [1] @ t let f t = 1 :: [] @ t let f (t: int * int) = fst t + snd t let x = true let y = false let dounit () = () No Flagging here - only two levels deep let f () = if x then (if x then x else y) else y let f () = if x then (if x then x else let z = 3 in dounit(); (if z = 2 then x else y) ) else y let f () = let l = [] in begin match l with | [] -> begin match l with | [] -> let z = [] in begin match z with | _ -> true end | _ -> false end | _ -> true end If statement three layers deep let z = if x then 1 else if y then 2 else if x & y then 3 else 4 If statement four layers deep let z = if x then 1 else if y then 2 else if x & y then 3 else if z = 4 then 3 else 9 let z = (x = TConstr 3 || x = TConstr 4) let z = (x = [12] || x = [50]) let z = (x = 5 || x = 6) let z = (x = TConstr 3 && x = TConstr 4) let z = (x = [12] && x = [50]) let z = (x = 5 && x = 6) let z = (x = TConstr 3 || not (x = TConstr 3)) let z = (x = [] || x = []) let z = (x = None || x = None) let z = (x = 5 || x = 5) let z = (x = TConstr 3 || x = TConstr 3) let z = (x = TConstr 3 || x = TConstr 3 || x = TConstr 4) let z = (x = TConstr 3 || x = TConstr 4 || x = TConstr 3) let z = (x = [] && x = []) let z = (x = None && x = None) let z = (x = 5 && x = 5) let z = (x = TConstr 3 && x = TConstr 3) let z = (x = TConstr 3 && x = TConstr 3 && x = TConstr 4) let z = (x = TConstr 3 && x = TConstr 4 && x = TConstr 3)
c6957460a7832b1d314e934bf9a2e8c733ea72c9762f462243e936905af1b37a
patrikja/autosar
NewABS.hs
Copyright ( c ) 2014 - 2015 , , , , and All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : * Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . * Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . * Neither the name of the Chalmers University of Technology nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . Copyright (c) 2014-2015, Johan Nordlander, Jonas Duregård, Michał Pałka, Patrik Jansson and Josef Svenningsson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Chalmers University of Technology nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Main where import NewARSim import System.Random import Graphics.EasyPlot import Debug.Trace instance (Valuable a, Valuable b) => Valuable (a,b) where toVal (a,b) = VArray [toVal a, toVal b] fromVal (VArray [a, b]) = (fromVal a, fromVal b) -------------------------------------------------------------- -- A generic skeleton for creating sequencer components; i.e., -- components that produce sequences of observable effects at -- programmable points in time. The skeleton is parametric in -- the actual step function (which takes takes a step index as -- a parameter, performs any observable effects, and returns a -- new sequencer state). A sequencer state is either Stopped or -- (Running ticks limit index), where limit is the step size in -- milliseconds, ticks is the time in milliseconds since the -- last step, and index is the new step index. A sequencer -- can be started and stopped by means of an exported boolean -- service operation. -------------------------------------------------------------- data SeqState = Stopped | Running Int Int Int instance Valuable SeqState where toVal Stopped = Void toVal (Running t l i) = VArray [VInt t, VInt l, VInt i] fromVal Void = Stopped fromVal (VArray [VInt t, VInt l, VInt i]) = Running t l i seq_init setup excl state = do rte_enter excl s <- setup rte_irvWrite state s rte_exit excl seq_tick step excl state = do rte_enter excl Ok s <- rte_irvRead state s' <- case s of Stopped -> return s Running ticks limit i | ticks < limit-1 -> return (Running (ticks+1) limit i) | otherwise -> step i rte_irvWrite state s' rte_exit excl seq_onoff onoff excl state on = do rte_enter excl s <- onoff on rte_irvWrite state s rte_exit excl return () sequencer setup step ctrl = do excl <- exclusiveArea state <- interRunnableVariable Stopped runnable Concurrent [Init] (seq_init setup excl state) runnable (MinInterval 0) [Timed 0.001] (seq_tick step excl state) onoff <- providedOperation serverRunnable (MinInterval 0) [onoff] (seq_onoff ctrl excl state) return (seal onoff) -------------------------------------------------------------- -- A relief component is a sequencer for toggling a brake relief -- valve in an ABS system. It requires a data element for reading -- wheel acceleration values (of type Double) and pulses the valve -- in lengths proportional to acceleration, as long as this value -- stays negative. It provides a boolean on/off control operation -- as well as a boolean data element producing valve settings. -------------------------------------------------------------- relief_setup valve = do rte_write valve False return Stopped relief_step valve accel 0 = do Ok a <- rte_read accel trace ("Relief " ++ show a) (return ()) if a < 0 then do rte_write valve True return (Running 0 (round (-a*10)) 1) else return (Running 0 5 0) relief_step valve accel n = do rte_write valve False return (Running 0 5 0) relief_ctrl valve accel True = relief_step valve accel 0 relief_ctrl valve accel False = do rte_write valve False return Stopped relief :: AR c (RE Double (), PO Bool () (), PE Bool ()) relief = component $ do valve <- providedDataElement accel <- requiredDataElement ctrl <- sequencer (relief_setup valve) (relief_step valve accel) (relief_ctrl valve accel) return (seal accel, ctrl, seal valve) -------------------------------------------------------------- -- A pressure component is a sequencer for toggling a brake -- pressure valve in an ABS system. It requires a data element -- for reading wheel acceleration values (of type Double) and pulses the valve 10 times in lengths proportional to positive -- acceleration. It provides a boolean on/off control operation -- as well as a boolean data element producing valve settings. -------------------------------------------------------------- pressure_setup valve = do rte_write valve True return Stopped pressure_step valve accel 0 = do rte_write valve True return (Running 0 100 1) pressure_step valve accel 20 = do rte_write valve True return Stopped pressure_step valve accel n | even n = do rte_write valve True Ok a <- rte_read accel trace ("Pressure " ++ show a) (return ()) return (Running 0 (round (a*50)) (n+1)) pressure_step valve accel n | odd n = do rte_write valve False return (Running 0 20 (n+1)) pressure_ctrl valve accel 2 = do rte_write valve True return Stopped pressure_ctrl valve accel 1 = pressure_step valve accel 0 pressure_ctrl valve accel 0 = do rte_write valve False return Stopped pressure :: AR c (RE Double (), PO Int () (), PE Bool ()) pressure = component $ do valve <- providedDataElement accel <- requiredDataElement ctrl <- sequencer (pressure_setup valve) (pressure_step valve accel) (pressure_ctrl valve accel) return (seal accel, ctrl, seal valve) -------------------------------------------------------------- -- A controller component reads a stream of slip values for a -- wheel (that is, ratios between wheel and vehicle speeds), and watches for points where slip drops below or rises above 80 % . If slip drops below 80 % , a relief sequence for the wheel is -- started (after any ongoing pressure sequence is aborted). If slip rises above 80 % , any ongoing relief sequence is aborted -- and a pressure sequence is started. -------------------------------------------------------------- control memo onoff_pressure onoff_relief slipstream = do Ok slip <- rte_receive slipstream Ok slip' <- rte_irvRead memo case (slip < 0.8, slip' < 0.8) of (True, False) -> do trace ("Slip " ++ show slip) (return ()) rte_call onoff_pressure 0 rte_call onoff_relief True return () (False, True) -> do trace ("Slip " ++ show slip) (return ()) rte_call onoff_relief False rte_call onoff_pressure (if slip >= 1.0 then 2 else 1) return () _ -> return () rte_irvWrite memo slip controller :: AR c (RQ Double (), RO Int () (), RO Bool () ()) controller = component $ do memo <- interRunnableVariable 1.0 onoff_pressure <- requiredOperation onoff_relief <- requiredOperation slipstream <- requiredQueueElement 10 runnable (MinInterval 0) [ReceiveQ slipstream] (control memo onoff_pressure onoff_relief slipstream) return (seal slipstream, seal onoff_pressure, seal onoff_relief) -------------------------------------------------------------- -- The "main loop" of the ABS algorithm is a component that -- periodically reads the current speeds of all wheels, -- approximates the vehicle speed as the maximum of the wheel -- speeds (should be refined for the case when all wheels are -- locked, must resort do dead reckoning based on latest -- deacceleration in these cases), and sends every wheel -- controller its updated slip ratio. -------------------------------------------------------------- loop velostreams slipstreams = do velos <- mapM (\re -> do Ok v <- rte_read re; return v) velostreams let v0 = maximum velos mapM (\(v,pe) -> rte_send pe (slip v0 v)) (velos `zip` slipstreams) slip 0.0 v = 1.0 slip v0 v = v/v0 main_loop :: AR c ([RE Double ()], [PQ Double ()]) main_loop = component $ do velostreams <- mapM (const requiredDataElement) [1..4] slipstreams <- mapM (const providedQueueElement) [1..4] runnable (MinInterval 0) [Timed 0.01] (loop velostreams slipstreams) return (map seal velostreams, map seal slipstreams) -------------------------------------------------------------- -- A full ABS system consists of a main loop component as well as one controller , one relief and one pressure component for -- each wheel. In addition, each wheel must be equipped with -- speed and acceleration sensors, but these parts are considered -- external to the current system. -------------------------------------------------------------- abs_system = do (velostreams_in, slipstreams_out) <- main_loop (slipstreams_in, onoffs_p_out, onoffs_r_out) <- fmap unzip3 $ mapM (const controller) [1..4] (accels_p_in, onoffs_p_in, valves_p_out) <- fmap unzip3 $ mapM (const pressure) [1..4] (accels_r_in, onoffs_r_in, valves_r_out) <- fmap unzip3 $ mapM (const relief) [1..4] connectAll slipstreams_out slipstreams_in connectAll onoffs_p_out onoffs_p_in connectAll onoffs_r_out onoffs_r_in return (velostreams_in, accels_r_in, accels_p_in, valves_r_out, valves_p_out) -------------------------------------------------------------- -- A test setup consists of the ABS system connected to simulated -- data sources in place of wheel sensors, and data sinks in place -- of pressure and relief valves. -------------------------------------------------------------- newtest = do (velos_in, accels_r_in, accels_p_in, valves_r_out, valves_p_out) <- abs_system env <- environment connectAll (repeat env) velos_in connectAll (repeat env) accels_r_in connectAll (repeat env) accels_p_in connectAll valves_r_out (repeat env) connectAll valves_p_out (repeat env) where a0 = [(1,-5)] v0 = (0,18) : minim 0 (integrate 0.01 a0) minim lim = map (\(t,v) -> (1,if v < lim then lim else v)) integrate dx {- _________ | | DElem --------> RE PE -----------> Env | | Env --------> RE PE -----------> Env | | --------- -} test vel_sim acc_sim = do (velos_in, accels_r_in, accels_p_in, valves_r_out, valves_p_out) <- abs_system v_sensors <- mapM source vel_sim a_sensors <- mapM source acc_sim connectAll v_sensors velos_in connectAll a_sensors accels_r_in connectAll a_sensors accels_p_in r_actuators <- mapM (const sink) [1..4] p_actuators <- mapM (const sink) [1..4] connectAll valves_r_out r_actuators connectAll valves_p_out p_actuators return (r_actuators, p_actuators) curve1 = slopes [(0,18),(1,18),(5,0)] curve2 = slopes [(0,18),(1,18),(1.8,10),(2.5,8),(3,8.5),(3.4,7),(4,4),(4.5,0)] v1 = curve1 Let wheel 2 speed deviate v3 = curve1 v4 = curve1 a1 = deriv v1 a2 = deriv v2 a3 = deriv v3 a4 = deriv v4 abs_sim = do s <- newStdGen let (trace,(r_acts,p_acts)) = chopTrace 400000 $ simulationRand s (test [v1,v2,v3,v4] [a1,a2,a3,a4]) [r1,r2,r3,r4] = map (discrete . bool2num 2.0 3.0 . collect trace) r_acts [p1,p2,p3,p4] = map (discrete . bool2num 4.0 5.0 . collect trace) p_acts plot (PS "plot.ps") $ [Data2D [Title "pressure 2", Style Lines, Color Red] [] p2, Data2D [Title "relief 2", Style Lines, Color Blue] [] r2, Data2D [Title "wheel speed 2", Style Lines, Color Green] [] v2, Data2D [Title "wheel acceleration 2", Style Lines, Color Violet] [] (discrete a2), Data2D [Title "vehicle speed", Style Lines, Color Black] [] v1] -- putTraceLabels trace main = abs_sim -- env t (Out a v) state = state { a_out = (t,a) : a_out state } -- env t (Time d) state = state { time = time state + d } test1 = do ( velos_in , accels_r_in , accels_p_in , valves_r_out , valves_p_out ) < - abs_system v_sensors < - mapM input [ " v1","v2","v3","v4 " ] a_sensors < - mapM input [ " " ] connectAll v_sensors velos_in a_sensors accels_r_in a_sensors accels_p_in r_actuators < - mapM output [ " r1","r2","r3","r4 " ] p_actuators < - mapM output [ " p1","p2","p3","p4 " ] connectAll valves_r_out r_actuators valves_p_out p_actuators environment say hear ( v1,v2,v3,v4,a1,a2,a3,a4 ) say ( v1,v2,v3,v4,a1,a2,a3,a4 ) | t = = 0 = ( Data a v , gen ) | t > 0 = ( Time t , ( t',a , ) hear ( Data a v ) ( t , gen ) = ( t , gen ) hear ( Time d ) ( t , gen ) = ( t+d , gen ) abs_sim1 = do s < - newStdGen test1 = do (velos_in, accels_r_in, accels_p_in, valves_r_out, valves_p_out) <- abs_system v_sensors <- mapM input ["v1","v2","v3","v4"] a_sensors <- mapM input ["a1","a2","a3","a4"] connectAll v_sensors velos_in connectAll a_sensors accels_r_in connectAll a_sensors accels_p_in r_actuators <- mapM output ["r1","r2","r3","r4"] p_actuators <- mapM output ["p1","p2","p3","p4"] connectAll valves_r_out r_actuators connectAll valves_p_out p_actuators environment say hear (v1,v2,v3,v4,a1,a2,a3,a4) say (v1,v2,v3,v4,a1,a2,a3,a4) | t == 0 = (Data a v, gen) | t > 0 = (Time t, (t',a,v):gen) hear (Data a v) (t,gen) = (t, gen) hear (Time d) (t,gen) = (t+d, gen) abs_sim1 = do s <- newStdGen -} -------------------------------------------------- -- Some helper functions for generating test data -------------------------------------------------- slopes ((x,y):pts@((x',y'):_)) | x >= x' = slopes pts | y == y' = (x,y) : slopes pts | otherwise = slope x y (dx*(y'-y)/(x'-x)) pts where dx = 0.01 slope x y dy pts@((x',y'):_) | x < x'-(dx/2) = (x,y) : slope (x+dx) (y+dy) dy pts slope x y dy pts = slopes pts slopes pts = pts discrete vs = disc 0.0 vs where disc v0 ((t,v):vs) = (t,v0) : (t+eps,v) : disc v vs disc _ _ = [] eps = 0.0001 deriv ((x,y):pts@((x',y'):_)) | x >= x' = deriv pts | otherwise = (x, (y'-y)/(x'-x)) : deriv pts deriv [(x,y)] = [] deriv [] = [] bool2num lo hi = map (\(t,b) -> (t,if b then hi else lo))
null
https://raw.githubusercontent.com/patrikja/autosar/2b8d3a22eb99812dca645a1c3c18ce18fbf6d539/oldARSim/NewABS.hs
haskell
------------------------------------------------------------ A generic skeleton for creating sequencer components; i.e., components that produce sequences of observable effects at programmable points in time. The skeleton is parametric in the actual step function (which takes takes a step index as a parameter, performs any observable effects, and returns a new sequencer state). A sequencer state is either Stopped or (Running ticks limit index), where limit is the step size in milliseconds, ticks is the time in milliseconds since the last step, and index is the new step index. A sequencer can be started and stopped by means of an exported boolean service operation. ------------------------------------------------------------ ------------------------------------------------------------ A relief component is a sequencer for toggling a brake relief valve in an ABS system. It requires a data element for reading wheel acceleration values (of type Double) and pulses the valve in lengths proportional to acceleration, as long as this value stays negative. It provides a boolean on/off control operation as well as a boolean data element producing valve settings. ------------------------------------------------------------ ------------------------------------------------------------ A pressure component is a sequencer for toggling a brake pressure valve in an ABS system. It requires a data element for reading wheel acceleration values (of type Double) and acceleration. It provides a boolean on/off control operation as well as a boolean data element producing valve settings. ------------------------------------------------------------ ------------------------------------------------------------ A controller component reads a stream of slip values for a wheel (that is, ratios between wheel and vehicle speeds), and started (after any ongoing pressure sequence is aborted). and a pressure sequence is started. ------------------------------------------------------------ ------------------------------------------------------------ The "main loop" of the ABS algorithm is a component that periodically reads the current speeds of all wheels, approximates the vehicle speed as the maximum of the wheel speeds (should be refined for the case when all wheels are locked, must resort do dead reckoning based on latest deacceleration in these cases), and sends every wheel controller its updated slip ratio. ------------------------------------------------------------ ------------------------------------------------------------ A full ABS system consists of a main loop component as well each wheel. In addition, each wheel must be equipped with speed and acceleration sensors, but these parts are considered external to the current system. ------------------------------------------------------------ ------------------------------------------------------------ A test setup consists of the ABS system connected to simulated data sources in place of wheel sensors, and data sinks in place of pressure and relief valves. ------------------------------------------------------------ _________ | | DElem --------> RE PE -----------> Env | | Env --------> RE PE -----------> Env | | --------- putTraceLabels trace env t (Out a v) state = state { a_out = (t,a) : a_out state } env t (Time d) state = state { time = time state + d } ------------------------------------------------ Some helper functions for generating test data ------------------------------------------------
Copyright ( c ) 2014 - 2015 , , , , and All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : * Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . * Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . * Neither the name of the Chalmers University of Technology nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . Copyright (c) 2014-2015, Johan Nordlander, Jonas Duregård, Michał Pałka, Patrik Jansson and Josef Svenningsson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Chalmers University of Technology nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Main where import NewARSim import System.Random import Graphics.EasyPlot import Debug.Trace instance (Valuable a, Valuable b) => Valuable (a,b) where toVal (a,b) = VArray [toVal a, toVal b] fromVal (VArray [a, b]) = (fromVal a, fromVal b) data SeqState = Stopped | Running Int Int Int instance Valuable SeqState where toVal Stopped = Void toVal (Running t l i) = VArray [VInt t, VInt l, VInt i] fromVal Void = Stopped fromVal (VArray [VInt t, VInt l, VInt i]) = Running t l i seq_init setup excl state = do rte_enter excl s <- setup rte_irvWrite state s rte_exit excl seq_tick step excl state = do rte_enter excl Ok s <- rte_irvRead state s' <- case s of Stopped -> return s Running ticks limit i | ticks < limit-1 -> return (Running (ticks+1) limit i) | otherwise -> step i rte_irvWrite state s' rte_exit excl seq_onoff onoff excl state on = do rte_enter excl s <- onoff on rte_irvWrite state s rte_exit excl return () sequencer setup step ctrl = do excl <- exclusiveArea state <- interRunnableVariable Stopped runnable Concurrent [Init] (seq_init setup excl state) runnable (MinInterval 0) [Timed 0.001] (seq_tick step excl state) onoff <- providedOperation serverRunnable (MinInterval 0) [onoff] (seq_onoff ctrl excl state) return (seal onoff) relief_setup valve = do rte_write valve False return Stopped relief_step valve accel 0 = do Ok a <- rte_read accel trace ("Relief " ++ show a) (return ()) if a < 0 then do rte_write valve True return (Running 0 (round (-a*10)) 1) else return (Running 0 5 0) relief_step valve accel n = do rte_write valve False return (Running 0 5 0) relief_ctrl valve accel True = relief_step valve accel 0 relief_ctrl valve accel False = do rte_write valve False return Stopped relief :: AR c (RE Double (), PO Bool () (), PE Bool ()) relief = component $ do valve <- providedDataElement accel <- requiredDataElement ctrl <- sequencer (relief_setup valve) (relief_step valve accel) (relief_ctrl valve accel) return (seal accel, ctrl, seal valve) pulses the valve 10 times in lengths proportional to positive pressure_setup valve = do rte_write valve True return Stopped pressure_step valve accel 0 = do rte_write valve True return (Running 0 100 1) pressure_step valve accel 20 = do rte_write valve True return Stopped pressure_step valve accel n | even n = do rte_write valve True Ok a <- rte_read accel trace ("Pressure " ++ show a) (return ()) return (Running 0 (round (a*50)) (n+1)) pressure_step valve accel n | odd n = do rte_write valve False return (Running 0 20 (n+1)) pressure_ctrl valve accel 2 = do rte_write valve True return Stopped pressure_ctrl valve accel 1 = pressure_step valve accel 0 pressure_ctrl valve accel 0 = do rte_write valve False return Stopped pressure :: AR c (RE Double (), PO Int () (), PE Bool ()) pressure = component $ do valve <- providedDataElement accel <- requiredDataElement ctrl <- sequencer (pressure_setup valve) (pressure_step valve accel) (pressure_ctrl valve accel) return (seal accel, ctrl, seal valve) watches for points where slip drops below or rises above 80 % . If slip drops below 80 % , a relief sequence for the wheel is If slip rises above 80 % , any ongoing relief sequence is aborted control memo onoff_pressure onoff_relief slipstream = do Ok slip <- rte_receive slipstream Ok slip' <- rte_irvRead memo case (slip < 0.8, slip' < 0.8) of (True, False) -> do trace ("Slip " ++ show slip) (return ()) rte_call onoff_pressure 0 rte_call onoff_relief True return () (False, True) -> do trace ("Slip " ++ show slip) (return ()) rte_call onoff_relief False rte_call onoff_pressure (if slip >= 1.0 then 2 else 1) return () _ -> return () rte_irvWrite memo slip controller :: AR c (RQ Double (), RO Int () (), RO Bool () ()) controller = component $ do memo <- interRunnableVariable 1.0 onoff_pressure <- requiredOperation onoff_relief <- requiredOperation slipstream <- requiredQueueElement 10 runnable (MinInterval 0) [ReceiveQ slipstream] (control memo onoff_pressure onoff_relief slipstream) return (seal slipstream, seal onoff_pressure, seal onoff_relief) loop velostreams slipstreams = do velos <- mapM (\re -> do Ok v <- rte_read re; return v) velostreams let v0 = maximum velos mapM (\(v,pe) -> rte_send pe (slip v0 v)) (velos `zip` slipstreams) slip 0.0 v = 1.0 slip v0 v = v/v0 main_loop :: AR c ([RE Double ()], [PQ Double ()]) main_loop = component $ do velostreams <- mapM (const requiredDataElement) [1..4] slipstreams <- mapM (const providedQueueElement) [1..4] runnable (MinInterval 0) [Timed 0.01] (loop velostreams slipstreams) return (map seal velostreams, map seal slipstreams) as one controller , one relief and one pressure component for abs_system = do (velostreams_in, slipstreams_out) <- main_loop (slipstreams_in, onoffs_p_out, onoffs_r_out) <- fmap unzip3 $ mapM (const controller) [1..4] (accels_p_in, onoffs_p_in, valves_p_out) <- fmap unzip3 $ mapM (const pressure) [1..4] (accels_r_in, onoffs_r_in, valves_r_out) <- fmap unzip3 $ mapM (const relief) [1..4] connectAll slipstreams_out slipstreams_in connectAll onoffs_p_out onoffs_p_in connectAll onoffs_r_out onoffs_r_in return (velostreams_in, accels_r_in, accels_p_in, valves_r_out, valves_p_out) newtest = do (velos_in, accels_r_in, accels_p_in, valves_r_out, valves_p_out) <- abs_system env <- environment connectAll (repeat env) velos_in connectAll (repeat env) accels_r_in connectAll (repeat env) accels_p_in connectAll valves_r_out (repeat env) connectAll valves_p_out (repeat env) where a0 = [(1,-5)] v0 = (0,18) : minim 0 (integrate 0.01 a0) minim lim = map (\(t,v) -> (1,if v < lim then lim else v)) integrate dx test vel_sim acc_sim = do (velos_in, accels_r_in, accels_p_in, valves_r_out, valves_p_out) <- abs_system v_sensors <- mapM source vel_sim a_sensors <- mapM source acc_sim connectAll v_sensors velos_in connectAll a_sensors accels_r_in connectAll a_sensors accels_p_in r_actuators <- mapM (const sink) [1..4] p_actuators <- mapM (const sink) [1..4] connectAll valves_r_out r_actuators connectAll valves_p_out p_actuators return (r_actuators, p_actuators) curve1 = slopes [(0,18),(1,18),(5,0)] curve2 = slopes [(0,18),(1,18),(1.8,10),(2.5,8),(3,8.5),(3.4,7),(4,4),(4.5,0)] v1 = curve1 Let wheel 2 speed deviate v3 = curve1 v4 = curve1 a1 = deriv v1 a2 = deriv v2 a3 = deriv v3 a4 = deriv v4 abs_sim = do s <- newStdGen let (trace,(r_acts,p_acts)) = chopTrace 400000 $ simulationRand s (test [v1,v2,v3,v4] [a1,a2,a3,a4]) [r1,r2,r3,r4] = map (discrete . bool2num 2.0 3.0 . collect trace) r_acts [p1,p2,p3,p4] = map (discrete . bool2num 4.0 5.0 . collect trace) p_acts plot (PS "plot.ps") $ [Data2D [Title "pressure 2", Style Lines, Color Red] [] p2, Data2D [Title "relief 2", Style Lines, Color Blue] [] r2, Data2D [Title "wheel speed 2", Style Lines, Color Green] [] v2, Data2D [Title "wheel acceleration 2", Style Lines, Color Violet] [] (discrete a2), Data2D [Title "vehicle speed", Style Lines, Color Black] [] v1] main = abs_sim test1 = do ( velos_in , accels_r_in , accels_p_in , valves_r_out , valves_p_out ) < - abs_system v_sensors < - mapM input [ " v1","v2","v3","v4 " ] a_sensors < - mapM input [ " " ] connectAll v_sensors velos_in a_sensors accels_r_in a_sensors accels_p_in r_actuators < - mapM output [ " r1","r2","r3","r4 " ] p_actuators < - mapM output [ " p1","p2","p3","p4 " ] connectAll valves_r_out r_actuators valves_p_out p_actuators environment say hear ( v1,v2,v3,v4,a1,a2,a3,a4 ) say ( v1,v2,v3,v4,a1,a2,a3,a4 ) | t = = 0 = ( Data a v , gen ) | t > 0 = ( Time t , ( t',a , ) hear ( Data a v ) ( t , gen ) = ( t , gen ) hear ( Time d ) ( t , gen ) = ( t+d , gen ) abs_sim1 = do s < - newStdGen test1 = do (velos_in, accels_r_in, accels_p_in, valves_r_out, valves_p_out) <- abs_system v_sensors <- mapM input ["v1","v2","v3","v4"] a_sensors <- mapM input ["a1","a2","a3","a4"] connectAll v_sensors velos_in connectAll a_sensors accels_r_in connectAll a_sensors accels_p_in r_actuators <- mapM output ["r1","r2","r3","r4"] p_actuators <- mapM output ["p1","p2","p3","p4"] connectAll valves_r_out r_actuators connectAll valves_p_out p_actuators environment say hear (v1,v2,v3,v4,a1,a2,a3,a4) say (v1,v2,v3,v4,a1,a2,a3,a4) | t == 0 = (Data a v, gen) | t > 0 = (Time t, (t',a,v):gen) hear (Data a v) (t,gen) = (t, gen) hear (Time d) (t,gen) = (t+d, gen) abs_sim1 = do s <- newStdGen -} slopes ((x,y):pts@((x',y'):_)) | x >= x' = slopes pts | y == y' = (x,y) : slopes pts | otherwise = slope x y (dx*(y'-y)/(x'-x)) pts where dx = 0.01 slope x y dy pts@((x',y'):_) | x < x'-(dx/2) = (x,y) : slope (x+dx) (y+dy) dy pts slope x y dy pts = slopes pts slopes pts = pts discrete vs = disc 0.0 vs where disc v0 ((t,v):vs) = (t,v0) : (t+eps,v) : disc v vs disc _ _ = [] eps = 0.0001 deriv ((x,y):pts@((x',y'):_)) | x >= x' = deriv pts | otherwise = (x, (y'-y)/(x'-x)) : deriv pts deriv [(x,y)] = [] deriv [] = [] bool2num lo hi = map (\(t,b) -> (t,if b then hi else lo))
5b861c8acbd696bab9914469c5459df5de136adfc231c3a67b82ae78d85a4736
csabahruska/jhc-components
Seq.hs
module Util.Seq( Seq() , singleton , cons , snoc , toList , appendToList , fromList , Util.Seq.concat ) where import Control.Applicative import Control.Monad import Data.Foldable(Foldable(..)) import Data.Monoid(Monoid(..)) import Data.Traversable(Traversable(..)) newtype Seq a = Seq ([a] -> [a]) singleton :: a -> Seq a singleton x = Seq (\ts -> x:ts) cons :: a -> Seq a -> Seq a cons x (Seq f) = Seq (\ts -> x:f ts) snoc :: Seq a -> a -> Seq a snoc (Seq f) x = Seq (\ts -> f (x:ts)) toList :: Seq a -> [a] toList (Seq f) = f [] appendToList :: Seq a -> [a] -> [a] appendToList (Seq f) xs = f xs fromList :: [a] -> Seq a fromList xs = Seq (\ts -> xs++ts) concat :: Seq (Seq a) -> Seq a concat (Seq f) = (Prelude.foldr mappend mempty (f [])) instance Functor Util.Seq.Seq where fmap f xs = Seq.fromList ( map f ( Seq.toList xs ) ) fmap f (Seq xs) = Seq (\ts -> map f (xs []) ++ ts ) instance Monad Util.Seq.Seq where --a >>= b = mconcat ( fmap b (Seq.toList a)) a >>= b = Util.Seq.concat (fmap b a) return = singleton fail _ = mempty instance Applicative Seq where pure = return (<*>) = ap instance Traversable Seq where traverse f (Seq g) = fmap fromList (traverse f (g [])) instance Foldable Util.Seq.Seq where foldMap f s = mconcat (map f (toList s)) instance MonadPlus Util.Seq.Seq where mplus = mappend mzero = mempty instance Monoid (Seq a) where mempty = Seq (\xs -> xs) Seq f `mappend` Seq g = Seq (\xs -> f (g xs))
null
https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/jhc-common/src/Util/Seq.hs
haskell
a >>= b = mconcat ( fmap b (Seq.toList a))
module Util.Seq( Seq() , singleton , cons , snoc , toList , appendToList , fromList , Util.Seq.concat ) where import Control.Applicative import Control.Monad import Data.Foldable(Foldable(..)) import Data.Monoid(Monoid(..)) import Data.Traversable(Traversable(..)) newtype Seq a = Seq ([a] -> [a]) singleton :: a -> Seq a singleton x = Seq (\ts -> x:ts) cons :: a -> Seq a -> Seq a cons x (Seq f) = Seq (\ts -> x:f ts) snoc :: Seq a -> a -> Seq a snoc (Seq f) x = Seq (\ts -> f (x:ts)) toList :: Seq a -> [a] toList (Seq f) = f [] appendToList :: Seq a -> [a] -> [a] appendToList (Seq f) xs = f xs fromList :: [a] -> Seq a fromList xs = Seq (\ts -> xs++ts) concat :: Seq (Seq a) -> Seq a concat (Seq f) = (Prelude.foldr mappend mempty (f [])) instance Functor Util.Seq.Seq where fmap f xs = Seq.fromList ( map f ( Seq.toList xs ) ) fmap f (Seq xs) = Seq (\ts -> map f (xs []) ++ ts ) instance Monad Util.Seq.Seq where a >>= b = Util.Seq.concat (fmap b a) return = singleton fail _ = mempty instance Applicative Seq where pure = return (<*>) = ap instance Traversable Seq where traverse f (Seq g) = fmap fromList (traverse f (g [])) instance Foldable Util.Seq.Seq where foldMap f s = mconcat (map f (toList s)) instance MonadPlus Util.Seq.Seq where mplus = mappend mzero = mempty instance Monoid (Seq a) where mempty = Seq (\xs -> xs) Seq f `mappend` Seq g = Seq (\xs -> f (g xs))
6da10a4fe784c78976187bc3774e5b432faf193f8530e113c487e37b6b7e3834
bhauman/rebel-readline
line_reader.clj
(ns rebel-readline.clojure.line-reader (:require [rebel-readline.commands :as commands] [rebel-readline.jline-api :as api :refer :all] [rebel-readline.jline-api.attributed-string :as astring] [rebel-readline.clojure.tokenizer :as tokenize] [rebel-readline.clojure.sexp :as sexp] [rebel-readline.tools :as tools :refer [color service-dispatch]] [rebel-readline.utils :as utils :refer [log]] ;; lazy-load #_[cljfmt.core :refer [reformat-string]] [clojure.string :as string] [clojure.java.io :as io] [clojure.main]) (:import [java.nio CharBuffer] [org.jline.keymap KeyMap] [org.jline.reader Highlighter Completer Candidate Parser Parser$ParseContext ParsedLine LineReader LineReader$Option LineReaderBuilder UserInterruptException EndOfFileException EOFError Widget] [org.jline.reader.impl LineReaderImpl DefaultParser BufferImpl] [org.jline.terminal TerminalBuilder] [org.jline.terminal.impl DumbTerminal] [org.jline.utils AttributedStringBuilder AttributedString AttributedStyle InfoCmp$Capability])) ;; ---------------------------------------------- ;; Default Configuration ;; ---------------------------------------------- (def default-config {:completion true :indent true :eldoc true :highlight true :redirect-output true :key-map :emacs :color-theme (if (= :light (utils/terminal-background-color?)) :light-screen-theme :dark-screen-theme)}) (def ^:dynamic *accept-fn* nil) (def highlight-clj-str (partial tools/highlight-str color tokenize/tag-font-lock)) ;; --------------------------------------------------------------------- ;; --------------------------------------------------------------------- ;; Service Abstraction ;; ;; This readline has pluggable service behavior to allow for fetching ;; docs, etc from the appropriate environment. ;; --------------------------------------------------------------------- ;; CurrentNS ;; ---------------------------------------------- (defmulti -current-ns "Returns a string representation of the current ns in the current execution environment. Returns nil if it hasn't been implemented for the current service" service-dispatch) ;; returning nil is a sensible signal of failure here (defmethod -current-ns :default [_]) (defn current-ns [] (-current-ns @*line-reader*)) ;; Prompt ;; ---------------------------------------------- (declare current-ns) (defn default-prompt-fn [] (format "%s=> " (or (current-ns) "clj"))) (defmethod tools/-prompt ::clojure [service] (default-prompt-fn)) ;; ---------------------------------------------- (defmulti -accept-line "Takes a string that is represents the current contents of a readline buffer and an integer position into that readline that represents the current position of the cursor. Returns a boolean indicating wether the line is complete and should be accepted as input. A service is not required to implement this fn, they would do this to override the default accept line behavior" service-dispatch) (defn default-accept-line [line-str cursor] (or (and *line-reader* (= "vicmd" (.getKeyMap *line-reader*))) (let [cursor (min (count line-str) cursor) x (subs line-str 0 cursor) tokens (tokenize/tag-sexp-traversal x)] (not (sexp/find-open-sexp-start tokens cursor))))) (defmethod -accept-line :default [_ line-str cursor] (default-accept-line line-str cursor)) (defn accept-line [line-str cursor] (-accept-line @*line-reader* line-str cursor)) ;; Completion ;; ---------------------------------------------- (defmulti -complete "Takes a word prefix and an options map} The options map can contain `:ns` - the current namespace the completion is occuring in `:context` - a sexp form that contains a marker '__prefix__ replacing the given prefix in teh expression where it is being completed. i.e. '(list __prefix__ 1 2) Returns a list of candidates of the form {:candidate \"alength\" :ns \"clojure.core\" :type :function}" service-dispatch) (defmethod -complete :default [service _ _]) (defn completions ([word] (completions word nil)) ([word options] (-complete @*line-reader* word options))) ResolveMeta ;; ---------------------------------------------- (defmulti -resolve-meta "Currently this finds and returns the meta data for the given string currently we are using the :ns, :name, :doc and :arglist meta data that is found on both vars, namespaces This function should return the standard or enhanced meta information that is afor a given \"word\" that and editor can focus on. `(resolve (symbol var-str))` This function shouldn't throw errors but catch them and return nil if the var doesn't exist." service-dispatch) (defmethod -resolve-meta :default [service _]) (defn resolve-meta [wrd] (-resolve-meta @*line-reader* wrd)) ;; ---------------------------------------------- ;; multi-methods that have to be defined or they ;; throw an exception ;; ---------------------------------------------- ;; Source ;; ---------------------------------------------- ;; TODO Maybe better to have a :file :line-start :line-end and a :url (defmulti -source "Given a string that represents a var Returns a map with source information for the var or nil if no source is found. A required :source key which will hold a string of the source code for the given var. An optional :url key which will hold a url to the source code in the context of the original file or potentially some other helpful url. DESIGN NOTE the :url isn't currently used Example result for `(-source service \"some?\")`: {:source \"(defn ^boolean some? [x] \\n(not (nil? x)))\" :url \"[...]main/cljs/cljs/core.cljs#L243-L245\" }" service-dispatch) (defmethod -source :default [service _]) (defn source [wrd] (-source @*line-reader* wrd)) ;; Apropos ;; ---------------------------------------------- (defmulti -apropos "Given a string returns a list of string repesentions of vars that match that string. This fn is already implemented on all the Clojure plaforms." service-dispatch) (defmethod -apropos :default [service _]) (defn apropos [wrd] (-apropos @*line-reader* wrd)) ;; Doc ;; ---------------------------------------------- (defmulti -doc "Given a string that represents a var, returns a map with documentation information for the named var or nil if no documentation is found. A required :doc key which will hold a string of the documentation for the given var. An optional :url key which will hold a url to the online documentation for the given var." service-dispatch) (defmethod -doc :default [service _]) (defn doc [wrd] (-doc @*line-reader* wrd)) ;; ReadString ;; ---------------------------------------------- (defmulti -read-string "Given a string with that contains clojure forms this will read and return a map containing the first form in the string under the key `:form` Example: (-read-string @api/*line-reader* \"1\") => {:form 1} If an exception is thrown this will return a throwable map under the key `:exception` Example: (-read-string @api/*line-reader* \"#asdfasdfas\") => {:exception {:cause ...}}" service-dispatch) (defmethod -read-string :default [service _] (tools/not-implemented! service "-read-string")) (defn read-form [form-str] (-read-string @*line-reader* form-str)) ;; Eval ;; ---------------------------------------------- (defmulti -eval "Given a clojure form this will evaluate that form and return a map of the outcome. The returned map will contain a `:result` key with a clj form that represents the result of it will contain a `:printed-result` key if the form can only be returned as a printed value. The returned map will also contain `:out` and `:err` keys containing any captured output that occured during the evaluation of the form. Example: (-eval @api/*line-reader* 1) => {:result 1 :out \"\" :err \"\"} If an exception is thrown this will return a throwable map under the key `:exception` Example: (-eval @api/*line-reader* '(defn)) => {:exception {:cause ...}} An important thing to remember abou this eval is that it is used internally by the line-reader to implement various capabilities (line inline eval)" service-dispatch) (defmethod -eval :default [service _] (tools/not-implemented! service "-eval")) (defn evaluate [form] (-eval @*line-reader* form)) EvalString ;; ---------------------------------------------- ;; only needed to prevent round trips for the most common ;; form of eval needed in an editor (defmulti -eval-str "Just like `-eval` but takes and string and reads it before sending it on to `-eval`" service-dispatch) (defmethod -eval-str :default [service form-str] (try (let [res (-read-string service form-str)] (if (contains? res :form) (-eval service (:form res)) res)) (catch Throwable e (set! *e e) {:exception (Throwable->map e)}))) (defn evaluate-str [form-str] (-eval-str @*line-reader* form-str)) ;; ---------------------------------------------------- ;; ---------------------------------------------------- ;; Widgets ;; ---------------------------------------------------- ;; ---------------------------------------------------- ;; Less Display ;; ---------------------------------------------------- (defn split-into-wrapped-lines [at-str columns] (mapcat (partial astring/partition-all columns) (astring/split-lines at-str))) (defn window-lines [at-str-lines pos rows] (astring/join "\n" (take rows (drop pos at-str-lines)))) (defn- lines-needed [hdr columns] (if-let [hdr (if (fn? hdr) (hdr) hdr)] (count (split-into-wrapped-lines hdr columns)) 0)) (defn display-less ([at-str] (display-less at-str {})) ([at-str options] (let [{:keys [header footer]} (merge {:header #(astring/astr [(apply str (repeat (:cols (terminal-size)) \-)) (.faint AttributedStyle/DEFAULT)]) :footer (astring/astr ["-- SCROLL WITH ARROW KEYS --" (color :widget/half-contrast-inverse)])} options) columns (:cols (terminal-size)) at-str-lines (split-into-wrapped-lines at-str columns) rows-needed (count at-str-lines) menu-keys (get (.getKeyMaps *line-reader*) LineReader/MENU)] (if (< (+ rows-needed (lines-needed (:header options) columns) (lines-needed (:footer options) columns)) (- (rows-available-for-post-display) 3)) (display-message (astring/join "\n" (keep identity [(when-let [header (:header options)] (if (fn? header) (header) header)) at-str (when-let [footer (:footer options)] (if (fn? footer) (footer) header))]))) (loop [pos 0] (let [columns (:cols (terminal-size)) at-str-lines (split-into-wrapped-lines at-str columns) rows-needed (count at-str-lines) header (if (fn? header) (header) header) footer (if (fn? footer) (footer) footer) header-lines-needed (lines-needed header columns) footer-lines-needed (lines-needed footer columns) window-rows (- (rows-available-for-post-display) header-lines-needed footer-lines-needed 3)] (if (< 2 window-rows) (do (display-message (astring/join "\n" (keep identity [header (window-lines at-str-lines pos window-rows) footer]))) (redisplay) (let [o (.readBinding *line-reader* (.getKeys ^LineReader *line-reader*) menu-keys) binding-name (.name ^org.jline.reader.Reference o)] (condp contains? binding-name #{LineReader/UP_LINE_OR_HISTORY LineReader/UP_LINE_OR_SEARCH LineReader/UP_LINE} (recur (max 0 (dec pos))) #{LineReader/DOWN_LINE_OR_HISTORY LineReader/DOWN_LINE_OR_SEARCH LineReader/DOWN_LINE LineReader/ACCEPT_LINE} (recur (min (- rows-needed window-rows) (inc pos))) ;; otherwise pushback the binding and (do ;; clear the post display (display-message " ") ;; pushback binding (when-let [s (.getLastBinding *line-reader*)] (when (not= "q" s) (.runMacro *line-reader* s))))))) ;; window is too small do nothing nil))))))) ;; ----------------------------------------- ;; force line accept ;; ----------------------------------------- (def always-accept-line (create-widget (binding [*accept-fn* (fn [l c] true)] (call-widget LineReader/ACCEPT_LINE) true))) ;; ----------------------------------------- ;; line indentation widget ;; ----------------------------------------- (defn indent-proxy-str [s cursor] (let [tagged-parses (tokenize/tag-sexp-traversal s)] ;; never indent in quotes ;; this is an optimization, the code should work fine without this (when-not (sexp/in-quote? tagged-parses cursor) (when-let [[delim sexp-start] (sexp/find-open-sexp-start tagged-parses cursor)] (let [line-start (sexp/search-for-line-start s sexp-start)] (str (apply str (repeat (- sexp-start line-start) \space)) (subs s sexp-start cursor) "\n1" (sexp/flip-delimiter-char (first delim)))))))) (defn indent-amount [s cursor] (if (zero? cursor) 0 (if-let [prx (indent-proxy-str s cursor)] ;; lazy-load for faster start up (let [reformat-string (utils/require-resolve-var 'cljfmt.core/reformat-string)] (try (->> (reformat-string prx {:remove-trailing-whitespace? false :insert-missing-whitespace? false :remove-surrounding-whitespace? false :remove-consecutive-blank-lines? false}) string/split-lines last sexp/count-leading-white-space) (catch clojure.lang.ExceptionInfo e (if (-> e ex-data :type (= :reader-exception)) (+ 2 (sexp/count-leading-white-space prx)) (throw e))))) 0))) (def indent-line-widget (create-widget (when (:indent @*line-reader*) (let [curs (cursor) s (buffer-as-string) ;; up-to-cursor better here? begin-of-line-pos (sexp/search-for-line-start s (dec curs)) leading-white-space (sexp/count-leading-white-space (subs s begin-of-line-pos)) indent-amount (indent-amount s begin-of-line-pos) cursor-in-leading-white-space? (< curs (+ leading-white-space begin-of-line-pos))] (cursor begin-of-line-pos) (delete leading-white-space) (write (apply str (repeat indent-amount \space))) ;; rectify cursor (when-not cursor-in-leading-white-space? (cursor (+ indent-amount (- curs leading-white-space)))))) ;; return true to re-render true)) (def indent-or-complete-widget (create-widget (let [curs (cursor) s (buffer-as-string) ;; up-to-cursor better here? begin-of-line-pos (sexp/search-for-line-start s (dec curs)) leading-white-space (sexp/count-leading-white-space (subs s begin-of-line-pos)) ;; indent-amount (#'ind/indent-amount s begin-of-line-pos) cursor-in-leading-white-space? (<= curs (+ leading-white-space begin-of-line-pos))] (if cursor-in-leading-white-space? (call-widget "clojure-indent-line") (call-widget LineReader/COMPLETE_WORD)) true))) ;; ------------------------------------------------ ;; Display argument docs on keypress functionality ;; ------------------------------------------------ (defn one-space-after-funcall-word? [] (let [s (buffer-as-string) curs (cursor) tagged-parses (tokenize/tag-sexp-traversal s) [_ start _ _] (sexp/find-open-sexp-start tagged-parses curs)] (when start (when-let [[word word-start word-end _] (and start (= (.charAt s start) \() (sexp/funcall-word s start))] (and (= (+ start word-end) curs) word))))) (defn name-arglist-display [meta-data] (let [{:keys [ns arglists name]} meta-data] (when (and ns name (not= ns name)) (astring/astr [(str ns) (color :widget/eldoc-namespace)] ["/" (color :widget/eldoc-separator)] [(str name) (color :widget/eldoc-varname)] (when arglists [": " (color :widget/eldoc-separator)]) (when arglists [(pr-str arglists) (color :widget/arglists)]))))) (defn display-argument-help-message [] (when-let [funcall-str (one-space-after-funcall-word?)] (when-let [fun-meta (resolve-meta funcall-str)] (when (:arglists fun-meta) (name-arglist-display fun-meta))))) TODO this ttd ( time to delete ) atom does n't work really ;; need a global state and countdown solution ;; and a callback on hook on any key presses (let [ttd-atom (atom -1)] (defn eldoc-self-insert-hook "This hooks SELF_INSERT to capture most keypresses that get echoed out to the terminal. We are using it here to display interactive behavior based on the state of the buffer at the time of a keypress." [] (when (zero? @ttd-atom) (display-message " ")) (when-not (neg? @ttd-atom) (swap! ttd-atom dec)) ;; hook here ;; if prev-char is a space and the char before that is part ;; of a word, and that word is a fn call (when (:eldoc @*line-reader*) (when-let [message (display-argument-help-message)] (reset! ttd-atom 1) (display-message message))))) (defn word-at-cursor [] (sexp/word-at-position (buffer-as-string) (cursor))) ;; ------------------------------------- ;; Documentation widget ;; ------------------------------------- (def document-at-point-widget (create-widget (when-let [[wrd] (word-at-cursor)] (when-let [doc-options (doc wrd)] (display-less (AttributedString. (string/trim (:doc doc-options)) (color :widget/doc)) (when-let [url (:url doc-options)] {:header (AttributedString. url (color :widget/light-anchor))})))) true)) ;; ------------------------------------- ;; Source widget ;; ------------------------------------- (defn source-at-point [] (when-let [[wrd] (word-at-cursor)] (when-let [var-meta-data (resolve-meta wrd)] (when-let [{:keys [source]} (source wrd)] (when-let [name-line (name-arglist-display var-meta-data)] (when-not (string/blank? source) {:arglist-line name-line :source (highlight-clj-str (string/trim source))})))))) (def source-at-point-widget (create-widget (when-let [{:keys [arglist-line source]} (source-at-point)] (display-less source {:header arglist-line})) true)) ;; ------------------------------------- ;; Apropos widget ;; ------------------------------------- ;; most of the code below is for formatting the results into a set of columns ;; that fit the terminal ;; I experimented with creating url anchors that are supported by iTerm but there seems to be a lack of support for arbitrary escape codes in Jline (defn osc-hyper-link [url show] (str (char 27) "]8;;" url (KeyMap/ctrl \G) show (char 27) "]8;;" (KeyMap/ctrl \G))) (defn format-pair-to-width [wrd width [ns' name']] (let [sep (apply str (repeat (- width (count ns') (count name')) \space)) idx (.indexOf name' wrd)] (astring/astr [(subs name' 0 idx) (color :widget/apropos-word)] [(subs name' idx (+ idx (count wrd))) (color :widget/apropos-highlight)] [(subs name' (+ idx (count wrd))) (color :widget/apropos-word)] sep [ns' (color :widget/apropos-namespace)]))) (defn format-column [wrd column] (let [max-width (apply max (map count column))] (map (partial format-pair-to-width wrd max-width) (map #(string/split % #"\/") (sort column))))) (defn row-width [columns] (+ (apply + (map #(apply max (map count %)) columns)) (* 3 (dec (count columns))))) ;; stats TODO move to lib (defn mean [coll] (if (pos? (count coll)) (/ (apply + coll) (count coll)) 0)) TODO move to lib ;; taken from clojure cookbook (defn standard-deviation [coll] (let [avg (mean coll) squares (for [x coll] (let [x-avg (- x avg)] (* x-avg x-avg))) total (count coll)] (-> (/ (apply + squares) (max (- total 1) 1)) (Math/sqrt)))) TODO move to lib (defn two-standards-plus-mean [coll] (+ (mean coll) (* 2 (standard-deviation coll)))) ;; sometimes there are exceptinoally long namespaces and function ;; names these screw up formatting and are normally very disntant from ;; the thing we are looking for (defn eliminate-long-outliers [coll] (let [max-len (two-standards-plus-mean (map count coll))] (filter #(<= (count %) max-len) coll))) (defn find-number-of-columns [coll total-width] (let [suggests coll] (first (filter #(let [columns (partition-all (Math/ceil (/ (count suggests) %)) suggests)] (< (row-width columns) total-width)) (range 10 0 -1))))) ;; the operation for finding the optimal layout is expensive ;; but this is OK as we are going to do it upon request from the ;; user and not as the user is typing (defn divide-into-displayable-columns [coll total-width] (let [max-length (apply max (map count coll)) coll (eliminate-long-outliers coll) cols (find-number-of-columns coll total-width)] (cond (and (= cols 1) (< (count coll) 15)) (list coll) (= cols 1) (recur (take (int (* 0.9 (count coll))) coll) total-width) (> (Math/ceil (/ (count coll) cols)) 20) (recur (take (int (* 0.9 (count coll))) coll) total-width) :else (map sort (partition-all (Math/ceil (/ (count coll) cols)) coll))))) (defn formatted-apropos [wrd] (let [suggests (sort-by (juxt count identity) (map str (apropos wrd)))] (when-let [suggests (not-empty (take 50 suggests))] (let [terminal-width (:cols (terminal-size))] (->> (divide-into-displayable-columns suggests terminal-width) (map (partial format-column wrd)) (apply map vector) (map #(interpose " " %)) (map #(apply astring/astr %)) (interpose (apply str "\n")) (apply astring/astr)))))) (def apropos-at-point-widget (create-widget (when-let [[wrd] (word-at-cursor)] (when-let [aprs (formatted-apropos wrd)] (display-less aprs {:header (AttributedString. (str "Apropos for: " wrd) (.faint AttributedStyle/DEFAULT))}))) true)) ;; ------------------------------------------ ;; In place eval widget ;; ------------------------------------------ (defn in-place-eval [] (let [s (buffer-as-string)] (when (not (string/blank? s)) (let [pos (cursor) fnw-pos (sexp/first-non-whitespace-char-backwards-from s (dec pos)) [form-str start end typ] (sexp/sexp-or-word-ending-at-position s fnw-pos)] (evaluate-str form-str))))) (defn inline-result-marker [^AttributedString at-str] (astring/astr ["#_=>" (color :widget/half-contrast-inverse)] " " at-str)) (defn limit-character-size [s] (let [{:keys [rows cols]} (terminal-size) max-char (int (* (- rows (count (string/split-lines (buffer-as-string)))) cols 0.5))] (if (< max-char (count s)) (str (subs s 0 max-char) "...") s))) (defn ensure-newline [s] (str (string/trim-newline s) "\n")) (defn no-greater-than [limit val] (min limit (or val Integer/MAX_VALUE))) (defn format-data-eval-result [{:keys [out err result printed-result exception] :as eval-result}] (let [[printed-result exception] (if (not printed-result) (try (binding [*print-length* (no-greater-than 100 *print-length*) *print-level* (no-greater-than 5 *print-level*)] [(pr-str result) exception]) (catch Throwable t [nil (Throwable->map t)])) [printed-result exception])] (cond-> (AttributedStringBuilder.) exception (.styled (color :widget/error) (str "=>!! " (or (:cause exception) (some-> exception :via first :type))) ) (not (string/blank? out)) (.append (ensure-newline out)) (not (string/blank? err)) (.styled (color :widget/error) (ensure-newline err)) (and (not exception) printed-result) (.append (inline-result-marker (.toAttributedString (highlight-clj-str printed-result))))))) (def eval-at-point-widget (create-widget (when-let [result (in-place-eval)] (display-less (format-data-eval-result result))) true)) ;; -------------------------------------------- ;; Buffer position ;; -------------------------------------------- (def end-of-buffer (create-widget (cursor (.length *buffer*)) true)) (def beginning-of-buffer (create-widget (cursor 0) true)) ;; -------------------------------------------- ;; Base Widget registration and binding helpers ;; -------------------------------------------- (defn add-all-widgets [line-reader] (binding [*line-reader* line-reader] (register-widget "clojure-indent-line" indent-line-widget) (register-widget "clojure-indent-or-complete" indent-or-complete-widget) (register-widget "clojure-doc-at-point" document-at-point-widget) (register-widget "clojure-source-at-point" source-at-point-widget) (register-widget "clojure-apropos-at-point" apropos-at-point-widget) (register-widget "clojure-eval-at-point" eval-at-point-widget) (register-widget "clojure-force-accept-line" always-accept-line) (register-widget "end-of-buffer" end-of-buffer) (register-widget "beginning-of-buffer" beginning-of-buffer))) (defn bind-indents [km-name] (doto km-name (key-binding (str (KeyMap/ctrl \X) (KeyMap/ctrl \I)) "clojure-indent-line") (key-binding (KeyMap/ctrl \I) "clojure-indent-or-complete"))) (defn bind-clojure-widgets [km-name] (doto km-name (key-binding (str (KeyMap/ctrl \X) (KeyMap/ctrl \D)) "clojure-doc-at-point") (key-binding (str (KeyMap/ctrl \X) (KeyMap/ctrl \S)) "clojure-source-at-point") (key-binding (str (KeyMap/ctrl \X) (KeyMap/ctrl \A)) "clojure-apropos-at-point") (key-binding (str (KeyMap/ctrl \X) (KeyMap/ctrl \E)) "clojure-eval-at-point") (key-binding (str (KeyMap/ctrl \X) (KeyMap/ctrl \M)) "clojure-force-accept-line"))) (defn bind-clojure-widgets-vi-cmd [km-name] (doto km-name (key-binding (str \\ \d) "clojure-doc-at-point") (key-binding (str \\ \s) "clojure-source-at-point") (key-binding (str \\ \a) "clojure-apropos-at-point") (key-binding (str \\ \e) "clojure-eval-at-point"))) (defn clojure-emacs-mode [km-name] (doto km-name bind-indents bind-clojure-widgets (key-binding (KeyMap/key (.getTerminal *line-reader*) InfoCmp$Capability/key_end) "end-of-buffer") (key-binding (KeyMap/key (.getTerminal *line-reader*) InfoCmp$Capability/key_home) "beginning-of-buffer"))) (defn clojure-vi-insert-mode [km-name] (doto km-name clojure-emacs-mode (key-binding (str (KeyMap/ctrl \E)) "clojure-force-accept-line"))) (defn clojure-vi-cmd-mode [km-name] (doto km-name bind-indents bind-clojure-widgets bind-clojure-widgets-vi-cmd)) (defn add-widgets-and-bindings [line-reader] (binding [*line-reader* line-reader] (clojure-emacs-mode :emacs) (clojure-vi-insert-mode :viins) (clojure-vi-cmd-mode :vicmd) (swap! line-reader #(update % :self-insert-hooks (fnil conj #{}) eldoc-self-insert-hook)) (doto line-reader (.setVariable LineReader/WORDCHARS "") add-all-widgets))) ;; ---------------------------------------------------- ;; ---------------------------------------------------- Building a Line Reader ;; ---------------------------------------------------- ;; ---------------------------------------------------- ;; --------------------------------------- Jline parser for Clojure ;; --------------------------------------- Jline uses a parser that pulls out the words from a read line ;; it mainly uses this for word completion and line acceptance ;; I.e. is this line complete or do we need to display a secondary ;; prompt? (defn parse-line [line cursor] (let [tokens (tokenize/tag-words line) words (filter (comp #{:string-literal-without-quotes :unterm-string-literal-without-quotes :word} last) tokens) word (first (filter (fn [[_ s e]] (<= s cursor e)) words)) word-index (.indexOf (vec words) word) word-cursor (if-not word 0 (- cursor (second word)))] TODO this can return a parsedline directly ;; but for now this is easier to debug {:word-index (or word-index -1) :word (or (first word) "") :word-cursor word-cursor :tokens words :word-token word :words (map first words) :line line :cursor cursor})) (defn parsed-line [{:keys [word-index word word-cursor words tokens line cursor] :as parse-data}] (proxy [ParsedLine clojure.lang.IMeta] [] (word [] word) (wordIndex [] word-index) (wordCursor [] word-cursor) (words [] (java.util.LinkedList. words)) (line [] line) (cursor [] cursor) (meta [] parse-data))) ;; this is an indent call that is specific to ACCEPT_LINE based actions ;; the functionality implemented here is indenting when you hit return on a line (defn indent [line-reader line cursor] ;; you could work on the buffer here instead TODO this key binding needs to be looked up from the macro if possible ;; changing the buffer here is the most stable but the logic is quite different ;; than the current indent action a two key macro here adds a slight delay to the indent action I think (.runMacro line-reader (str (KeyMap/ctrl \X) (KeyMap/ctrl \I)))) a parser for jline that respects (defn make-parser [] (doto (proxy [DefaultParser] [] (isDelimiterChar [^CharSequence buffer pos] (boolean (#{\space \tab \return \newline \, \{ \} \( \) \[ \] } (.charAt buffer pos)))) (parse [^String line cursor ^Parser$ParseContext context] (cond (= context Parser$ParseContext/ACCEPT_LINE) (when-not (or (and *accept-fn* (*accept-fn* line cursor)) (accept-line line cursor)) (indent *line-reader* line cursor) (throw (EOFError. -1 -1 "Unbalanced Expression" (str *ns*)))) (= context Parser$ParseContext/COMPLETE) (parsed-line (parse-line line cursor)) :else (proxy-super parse line cursor context)))) (.setQuoteChars (char-array [\"])))) ;; ---------------------------------------- Jline completer for Clojure candidates ;; ---------------------------------------- ;; Completion context (defn parsed-line-word-coords [^ParsedLine parsed-line] (let [pos (.cursor parsed-line) word-cursor (.wordCursor parsed-line) word (.word parsed-line) word-start (- pos word-cursor) word-end (+ pos (- (count word) word-cursor))] [word-start word-end])) TODO this has string hacks in it that would n't be needed ;; with better sexp parsing (defn replace-word-with-prefix [parsed-line] (let [[start end] (parsed-line-word-coords parsed-line) [_ _ _ typ] (:word-token (meta parsed-line)) line (.line parsed-line)] [(str (subs line 0 start) "__prefix__" (when (= typ :unterm-string-literal-without-quotes) \") (subs line end (count line))) (+ start (count "__prefix__") (if (#{:string-literal-without-quotes :unterm-string-literal-without-quotes} typ) 1 0))])) (defn complete-context [^ParsedLine parsed-line] (when-let [[form-str end-of-marker] (replace-word-with-prefix parsed-line)] (when-let [valid-sexp (sexp/valid-sexp-from-point form-str end-of-marker)] (binding [*default-data-reader-fn* identity] (try (read-string valid-sexp) (catch Throwable e (log :complete-context e) nil)))))) (defn candidate [{:keys [candidate type ns]}] (Candidate. candidate ;; value candidate ;; display nil ;; group (cond-> nil type (str (first (name type))) ns (str (when type " ") ns)) nil ;; suffix nil ;; key false)) (defn command-token? [{:keys [line tokens word]} starts-with] (and (= 1 (count tokens)) (.startsWith (string/triml line) starts-with) (.startsWith word starts-with))) (defn find-completions [candidates prefix] (->> candidates (map str) (filter #(.startsWith % prefix)) (sort-by (juxt count identity)) (map #(hash-map :candidate % :type :repl-command)) not-empty)) (defn repl-command-complete [{:keys [word] :as parsed-line}] (when (command-token? parsed-line ":r") (find-completions (commands/all-commands) word))) (defn cljs-quit-complete [{:keys [word] :as parsed-line}] (when (command-token? parsed-line ":c") (find-completions [:cljs/quit] word))) TODO abstract completion service here (defn clojure-completer [] (proxy [Completer] [] (complete [^LineReader reader ^ParsedLine line ^java.util.List candidates] (let [word (.word line)] (when (and (:completion @*line-reader*) (not (string/blank? word)) (pos? (count word))) (let [options (let [ns' (current-ns) context (complete-context line)] (cond-> {} ns' (assoc :ns ns') context (assoc :context context)))] (->> (or (repl-command-complete (meta line)) (cljs-quit-complete (meta line)) (completions (.word line) options)) (map #(candidate %)) (take 10) (.addAll candidates)))))))) ;; ---------------------------------------- Jline highlighter for Clojure code ;; ---------------------------------------- (defn clojure-highlighter [] (proxy [Highlighter] [] (highlight [^LineReader reader ^String buffer] ;; this gets called on a different thread ;; by the window resize interrupt handler ;; so add this binding here (binding [*line-reader* reader] (if (:highlight @reader) (.toAttributedString (highlight-clj-str buffer)) (AttributedString. buffer)))))) ;; ---------------------------------------- ;; Building the line reader ;; ---------------------------------------- (defn create* [terminal service & [{:keys [completer highlighter parser]}]] {:pre [(instance? org.jline.terminal.Terminal terminal) (map? service)]} (doto (create-line-reader terminal "Clojure Readline" service) (.setCompleter (or completer (clojure-completer))) (.setHighlighter (or highlighter (clojure-highlighter ))) (.setParser (or parser (make-parser))) ;; make sure that we don't have to double escape things (.setOpt LineReader$Option/DISABLE_EVENT_EXPANSION) ;; never insert tabs (.unsetOpt LineReader$Option/INSERT_TAB) (.setVariable LineReader/SECONDARY_PROMPT_PATTERN "%P #_=> ") ;; history (.setVariable LineReader/HISTORY_FILE (str (io/file ".rebel_readline_history"))) (.setOpt LineReader$Option/HISTORY_REDUCE_BLANKS) (.setOpt LineReader$Option/HISTORY_IGNORE_DUPS) (.setOpt LineReader$Option/HISTORY_INCREMENTAL) add-widgets-and-bindings (#(binding [*line-reader* %] (apply-key-bindings!) (set-main-key-map! (get service :key-map :emacs)))))) (defn create "Creates a line reader takes a service as an argument. A service implements the multimethods found in `rebel-readline.service` Example: (create (rebel-readline.clojure.service.local/create)) Or: (create (rebel-readline.clojure.service.simple/create)) This function also takes an optional options map. The available options are: :completer - to override the clojure based completer :highlighter - to override the clojure based systax highlighter :parser - to override the clojure base word parser" [service & [options]] (create* api/*terminal* service options))
null
https://raw.githubusercontent.com/bhauman/rebel-readline/6c314f8fe1cb44bde3a0511bf14d48157f89f6d7/rebel-readline/src/rebel_readline/clojure/line_reader.clj
clojure
lazy-load ---------------------------------------------- Default Configuration ---------------------------------------------- --------------------------------------------------------------------- --------------------------------------------------------------------- Service Abstraction This readline has pluggable service behavior to allow for fetching docs, etc from the appropriate environment. --------------------------------------------------------------------- CurrentNS ---------------------------------------------- returning nil is a sensible signal of failure here Prompt ---------------------------------------------- ---------------------------------------------- Completion ---------------------------------------------- ---------------------------------------------- ---------------------------------------------- multi-methods that have to be defined or they throw an exception ---------------------------------------------- Source ---------------------------------------------- TODO Maybe better to have a :file :line-start :line-end and a :url Apropos ---------------------------------------------- Doc ---------------------------------------------- ReadString ---------------------------------------------- Eval ---------------------------------------------- ---------------------------------------------- only needed to prevent round trips for the most common form of eval needed in an editor ---------------------------------------------------- ---------------------------------------------------- Widgets ---------------------------------------------------- ---------------------------------------------------- Less Display ---------------------------------------------------- otherwise pushback the binding and clear the post display pushback binding window is too small do nothing ----------------------------------------- force line accept ----------------------------------------- ----------------------------------------- line indentation widget ----------------------------------------- never indent in quotes this is an optimization, the code should work fine without this lazy-load for faster start up up-to-cursor better here? rectify cursor return true to re-render up-to-cursor better here? indent-amount (#'ind/indent-amount s begin-of-line-pos) ------------------------------------------------ Display argument docs on keypress functionality ------------------------------------------------ need a global state and countdown solution and a callback on hook on any key presses hook here if prev-char is a space and the char before that is part of a word, and that word is a fn call ------------------------------------- Documentation widget ------------------------------------- ------------------------------------- Source widget ------------------------------------- ------------------------------------- Apropos widget ------------------------------------- most of the code below is for formatting the results into a set of columns that fit the terminal I experimented with creating url anchors that are supported by iTerm but stats taken from clojure cookbook sometimes there are exceptinoally long namespaces and function names these screw up formatting and are normally very disntant from the thing we are looking for the operation for finding the optimal layout is expensive but this is OK as we are going to do it upon request from the user and not as the user is typing ------------------------------------------ In place eval widget ------------------------------------------ -------------------------------------------- Buffer position -------------------------------------------- -------------------------------------------- Base Widget registration and binding helpers -------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- --------------------------------------- --------------------------------------- it mainly uses this for word completion and line acceptance I.e. is this line complete or do we need to display a secondary prompt? but for now this is easier to debug this is an indent call that is specific to ACCEPT_LINE based actions the functionality implemented here is indenting when you hit return on a line you could work on the buffer here instead changing the buffer here is the most stable but the logic is quite different than the current indent action ---------------------------------------- ---------------------------------------- Completion context with better sexp parsing value display group suffix key ---------------------------------------- ---------------------------------------- this gets called on a different thread by the window resize interrupt handler so add this binding here ---------------------------------------- Building the line reader ---------------------------------------- make sure that we don't have to double escape things never insert tabs history
(ns rebel-readline.clojure.line-reader (:require [rebel-readline.commands :as commands] [rebel-readline.jline-api :as api :refer :all] [rebel-readline.jline-api.attributed-string :as astring] [rebel-readline.clojure.tokenizer :as tokenize] [rebel-readline.clojure.sexp :as sexp] [rebel-readline.tools :as tools :refer [color service-dispatch]] [rebel-readline.utils :as utils :refer [log]] #_[cljfmt.core :refer [reformat-string]] [clojure.string :as string] [clojure.java.io :as io] [clojure.main]) (:import [java.nio CharBuffer] [org.jline.keymap KeyMap] [org.jline.reader Highlighter Completer Candidate Parser Parser$ParseContext ParsedLine LineReader LineReader$Option LineReaderBuilder UserInterruptException EndOfFileException EOFError Widget] [org.jline.reader.impl LineReaderImpl DefaultParser BufferImpl] [org.jline.terminal TerminalBuilder] [org.jline.terminal.impl DumbTerminal] [org.jline.utils AttributedStringBuilder AttributedString AttributedStyle InfoCmp$Capability])) (def default-config {:completion true :indent true :eldoc true :highlight true :redirect-output true :key-map :emacs :color-theme (if (= :light (utils/terminal-background-color?)) :light-screen-theme :dark-screen-theme)}) (def ^:dynamic *accept-fn* nil) (def highlight-clj-str (partial tools/highlight-str color tokenize/tag-font-lock)) (defmulti -current-ns "Returns a string representation of the current ns in the current execution environment. Returns nil if it hasn't been implemented for the current service" service-dispatch) (defmethod -current-ns :default [_]) (defn current-ns [] (-current-ns @*line-reader*)) (declare current-ns) (defn default-prompt-fn [] (format "%s=> " (or (current-ns) "clj"))) (defmethod tools/-prompt ::clojure [service] (default-prompt-fn)) (defmulti -accept-line "Takes a string that is represents the current contents of a readline buffer and an integer position into that readline that represents the current position of the cursor. Returns a boolean indicating wether the line is complete and should be accepted as input. A service is not required to implement this fn, they would do this to override the default accept line behavior" service-dispatch) (defn default-accept-line [line-str cursor] (or (and *line-reader* (= "vicmd" (.getKeyMap *line-reader*))) (let [cursor (min (count line-str) cursor) x (subs line-str 0 cursor) tokens (tokenize/tag-sexp-traversal x)] (not (sexp/find-open-sexp-start tokens cursor))))) (defmethod -accept-line :default [_ line-str cursor] (default-accept-line line-str cursor)) (defn accept-line [line-str cursor] (-accept-line @*line-reader* line-str cursor)) (defmulti -complete "Takes a word prefix and an options map} The options map can contain `:ns` - the current namespace the completion is occuring in `:context` - a sexp form that contains a marker '__prefix__ replacing the given prefix in teh expression where it is being completed. i.e. '(list __prefix__ 1 2) Returns a list of candidates of the form {:candidate \"alength\" :ns \"clojure.core\" :type :function}" service-dispatch) (defmethod -complete :default [service _ _]) (defn completions ([word] (completions word nil)) ([word options] (-complete @*line-reader* word options))) ResolveMeta (defmulti -resolve-meta "Currently this finds and returns the meta data for the given string currently we are using the :ns, :name, :doc and :arglist meta data that is found on both vars, namespaces This function should return the standard or enhanced meta information that is afor a given \"word\" that and editor can focus on. `(resolve (symbol var-str))` This function shouldn't throw errors but catch them and return nil if the var doesn't exist." service-dispatch) (defmethod -resolve-meta :default [service _]) (defn resolve-meta [wrd] (-resolve-meta @*line-reader* wrd)) (defmulti -source "Given a string that represents a var Returns a map with source information for the var or nil if no source is found. A required :source key which will hold a string of the source code for the given var. An optional :url key which will hold a url to the source code in the context of the original file or potentially some other helpful url. DESIGN NOTE the :url isn't currently used Example result for `(-source service \"some?\")`: {:source \"(defn ^boolean some? [x] \\n(not (nil? x)))\" :url \"[...]main/cljs/cljs/core.cljs#L243-L245\" }" service-dispatch) (defmethod -source :default [service _]) (defn source [wrd] (-source @*line-reader* wrd)) (defmulti -apropos "Given a string returns a list of string repesentions of vars that match that string. This fn is already implemented on all the Clojure plaforms." service-dispatch) (defmethod -apropos :default [service _]) (defn apropos [wrd] (-apropos @*line-reader* wrd)) (defmulti -doc "Given a string that represents a var, returns a map with documentation information for the named var or nil if no documentation is found. A required :doc key which will hold a string of the documentation for the given var. An optional :url key which will hold a url to the online documentation for the given var." service-dispatch) (defmethod -doc :default [service _]) (defn doc [wrd] (-doc @*line-reader* wrd)) (defmulti -read-string "Given a string with that contains clojure forms this will read and return a map containing the first form in the string under the key `:form` Example: (-read-string @api/*line-reader* \"1\") => {:form 1} If an exception is thrown this will return a throwable map under the key `:exception` Example: (-read-string @api/*line-reader* \"#asdfasdfas\") => {:exception {:cause ...}}" service-dispatch) (defmethod -read-string :default [service _] (tools/not-implemented! service "-read-string")) (defn read-form [form-str] (-read-string @*line-reader* form-str)) (defmulti -eval "Given a clojure form this will evaluate that form and return a map of the outcome. The returned map will contain a `:result` key with a clj form that represents the result of it will contain a `:printed-result` key if the form can only be returned as a printed value. The returned map will also contain `:out` and `:err` keys containing any captured output that occured during the evaluation of the form. Example: (-eval @api/*line-reader* 1) => {:result 1 :out \"\" :err \"\"} If an exception is thrown this will return a throwable map under the key `:exception` Example: (-eval @api/*line-reader* '(defn)) => {:exception {:cause ...}} An important thing to remember abou this eval is that it is used internally by the line-reader to implement various capabilities (line inline eval)" service-dispatch) (defmethod -eval :default [service _] (tools/not-implemented! service "-eval")) (defn evaluate [form] (-eval @*line-reader* form)) EvalString (defmulti -eval-str "Just like `-eval` but takes and string and reads it before sending it on to `-eval`" service-dispatch) (defmethod -eval-str :default [service form-str] (try (let [res (-read-string service form-str)] (if (contains? res :form) (-eval service (:form res)) res)) (catch Throwable e (set! *e e) {:exception (Throwable->map e)}))) (defn evaluate-str [form-str] (-eval-str @*line-reader* form-str)) (defn split-into-wrapped-lines [at-str columns] (mapcat (partial astring/partition-all columns) (astring/split-lines at-str))) (defn window-lines [at-str-lines pos rows] (astring/join "\n" (take rows (drop pos at-str-lines)))) (defn- lines-needed [hdr columns] (if-let [hdr (if (fn? hdr) (hdr) hdr)] (count (split-into-wrapped-lines hdr columns)) 0)) (defn display-less ([at-str] (display-less at-str {})) ([at-str options] (let [{:keys [header footer]} (merge {:header #(astring/astr [(apply str (repeat (:cols (terminal-size)) \-)) (.faint AttributedStyle/DEFAULT)]) :footer (astring/astr ["-- SCROLL WITH ARROW KEYS --" (color :widget/half-contrast-inverse)])} options) columns (:cols (terminal-size)) at-str-lines (split-into-wrapped-lines at-str columns) rows-needed (count at-str-lines) menu-keys (get (.getKeyMaps *line-reader*) LineReader/MENU)] (if (< (+ rows-needed (lines-needed (:header options) columns) (lines-needed (:footer options) columns)) (- (rows-available-for-post-display) 3)) (display-message (astring/join "\n" (keep identity [(when-let [header (:header options)] (if (fn? header) (header) header)) at-str (when-let [footer (:footer options)] (if (fn? footer) (footer) header))]))) (loop [pos 0] (let [columns (:cols (terminal-size)) at-str-lines (split-into-wrapped-lines at-str columns) rows-needed (count at-str-lines) header (if (fn? header) (header) header) footer (if (fn? footer) (footer) footer) header-lines-needed (lines-needed header columns) footer-lines-needed (lines-needed footer columns) window-rows (- (rows-available-for-post-display) header-lines-needed footer-lines-needed 3)] (if (< 2 window-rows) (do (display-message (astring/join "\n" (keep identity [header (window-lines at-str-lines pos window-rows) footer]))) (redisplay) (let [o (.readBinding *line-reader* (.getKeys ^LineReader *line-reader*) menu-keys) binding-name (.name ^org.jline.reader.Reference o)] (condp contains? binding-name #{LineReader/UP_LINE_OR_HISTORY LineReader/UP_LINE_OR_SEARCH LineReader/UP_LINE} (recur (max 0 (dec pos))) #{LineReader/DOWN_LINE_OR_HISTORY LineReader/DOWN_LINE_OR_SEARCH LineReader/DOWN_LINE LineReader/ACCEPT_LINE} (recur (min (- rows-needed window-rows) (inc pos))) (do (display-message " ") (when-let [s (.getLastBinding *line-reader*)] (when (not= "q" s) (.runMacro *line-reader* s))))))) nil))))))) (def always-accept-line (create-widget (binding [*accept-fn* (fn [l c] true)] (call-widget LineReader/ACCEPT_LINE) true))) (defn indent-proxy-str [s cursor] (let [tagged-parses (tokenize/tag-sexp-traversal s)] (when-not (sexp/in-quote? tagged-parses cursor) (when-let [[delim sexp-start] (sexp/find-open-sexp-start tagged-parses cursor)] (let [line-start (sexp/search-for-line-start s sexp-start)] (str (apply str (repeat (- sexp-start line-start) \space)) (subs s sexp-start cursor) "\n1" (sexp/flip-delimiter-char (first delim)))))))) (defn indent-amount [s cursor] (if (zero? cursor) 0 (if-let [prx (indent-proxy-str s cursor)] (let [reformat-string (utils/require-resolve-var 'cljfmt.core/reformat-string)] (try (->> (reformat-string prx {:remove-trailing-whitespace? false :insert-missing-whitespace? false :remove-surrounding-whitespace? false :remove-consecutive-blank-lines? false}) string/split-lines last sexp/count-leading-white-space) (catch clojure.lang.ExceptionInfo e (if (-> e ex-data :type (= :reader-exception)) (+ 2 (sexp/count-leading-white-space prx)) (throw e))))) 0))) (def indent-line-widget (create-widget (when (:indent @*line-reader*) (let [curs (cursor) begin-of-line-pos (sexp/search-for-line-start s (dec curs)) leading-white-space (sexp/count-leading-white-space (subs s begin-of-line-pos)) indent-amount (indent-amount s begin-of-line-pos) cursor-in-leading-white-space? (< curs (+ leading-white-space begin-of-line-pos))] (cursor begin-of-line-pos) (delete leading-white-space) (write (apply str (repeat indent-amount \space))) (when-not cursor-in-leading-white-space? (cursor (+ indent-amount (- curs leading-white-space)))))) true)) (def indent-or-complete-widget (create-widget (let [curs (cursor) begin-of-line-pos (sexp/search-for-line-start s (dec curs)) leading-white-space (sexp/count-leading-white-space (subs s begin-of-line-pos)) cursor-in-leading-white-space? (<= curs (+ leading-white-space begin-of-line-pos))] (if cursor-in-leading-white-space? (call-widget "clojure-indent-line") (call-widget LineReader/COMPLETE_WORD)) true))) (defn one-space-after-funcall-word? [] (let [s (buffer-as-string) curs (cursor) tagged-parses (tokenize/tag-sexp-traversal s) [_ start _ _] (sexp/find-open-sexp-start tagged-parses curs)] (when start (when-let [[word word-start word-end _] (and start (= (.charAt s start) \() (sexp/funcall-word s start))] (and (= (+ start word-end) curs) word))))) (defn name-arglist-display [meta-data] (let [{:keys [ns arglists name]} meta-data] (when (and ns name (not= ns name)) (astring/astr [(str ns) (color :widget/eldoc-namespace)] ["/" (color :widget/eldoc-separator)] [(str name) (color :widget/eldoc-varname)] (when arglists [": " (color :widget/eldoc-separator)]) (when arglists [(pr-str arglists) (color :widget/arglists)]))))) (defn display-argument-help-message [] (when-let [funcall-str (one-space-after-funcall-word?)] (when-let [fun-meta (resolve-meta funcall-str)] (when (:arglists fun-meta) (name-arglist-display fun-meta))))) TODO this ttd ( time to delete ) atom does n't work really (let [ttd-atom (atom -1)] (defn eldoc-self-insert-hook "This hooks SELF_INSERT to capture most keypresses that get echoed out to the terminal. We are using it here to display interactive behavior based on the state of the buffer at the time of a keypress." [] (when (zero? @ttd-atom) (display-message " ")) (when-not (neg? @ttd-atom) (swap! ttd-atom dec)) (when (:eldoc @*line-reader*) (when-let [message (display-argument-help-message)] (reset! ttd-atom 1) (display-message message))))) (defn word-at-cursor [] (sexp/word-at-position (buffer-as-string) (cursor))) (def document-at-point-widget (create-widget (when-let [[wrd] (word-at-cursor)] (when-let [doc-options (doc wrd)] (display-less (AttributedString. (string/trim (:doc doc-options)) (color :widget/doc)) (when-let [url (:url doc-options)] {:header (AttributedString. url (color :widget/light-anchor))})))) true)) (defn source-at-point [] (when-let [[wrd] (word-at-cursor)] (when-let [var-meta-data (resolve-meta wrd)] (when-let [{:keys [source]} (source wrd)] (when-let [name-line (name-arglist-display var-meta-data)] (when-not (string/blank? source) {:arglist-line name-line :source (highlight-clj-str (string/trim source))})))))) (def source-at-point-widget (create-widget (when-let [{:keys [arglist-line source]} (source-at-point)] (display-less source {:header arglist-line})) true)) there seems to be a lack of support for arbitrary escape codes in Jline (defn osc-hyper-link [url show] (str (char 27) "]8;;" url (KeyMap/ctrl \G) show (char 27) "]8;;" (KeyMap/ctrl \G))) (defn format-pair-to-width [wrd width [ns' name']] (let [sep (apply str (repeat (- width (count ns') (count name')) \space)) idx (.indexOf name' wrd)] (astring/astr [(subs name' 0 idx) (color :widget/apropos-word)] [(subs name' idx (+ idx (count wrd))) (color :widget/apropos-highlight)] [(subs name' (+ idx (count wrd))) (color :widget/apropos-word)] sep [ns' (color :widget/apropos-namespace)]))) (defn format-column [wrd column] (let [max-width (apply max (map count column))] (map (partial format-pair-to-width wrd max-width) (map #(string/split % #"\/") (sort column))))) (defn row-width [columns] (+ (apply + (map #(apply max (map count %)) columns)) (* 3 (dec (count columns))))) TODO move to lib (defn mean [coll] (if (pos? (count coll)) (/ (apply + coll) (count coll)) 0)) TODO move to lib (defn standard-deviation [coll] (let [avg (mean coll) squares (for [x coll] (let [x-avg (- x avg)] (* x-avg x-avg))) total (count coll)] (-> (/ (apply + squares) (max (- total 1) 1)) (Math/sqrt)))) TODO move to lib (defn two-standards-plus-mean [coll] (+ (mean coll) (* 2 (standard-deviation coll)))) (defn eliminate-long-outliers [coll] (let [max-len (two-standards-plus-mean (map count coll))] (filter #(<= (count %) max-len) coll))) (defn find-number-of-columns [coll total-width] (let [suggests coll] (first (filter #(let [columns (partition-all (Math/ceil (/ (count suggests) %)) suggests)] (< (row-width columns) total-width)) (range 10 0 -1))))) (defn divide-into-displayable-columns [coll total-width] (let [max-length (apply max (map count coll)) coll (eliminate-long-outliers coll) cols (find-number-of-columns coll total-width)] (cond (and (= cols 1) (< (count coll) 15)) (list coll) (= cols 1) (recur (take (int (* 0.9 (count coll))) coll) total-width) (> (Math/ceil (/ (count coll) cols)) 20) (recur (take (int (* 0.9 (count coll))) coll) total-width) :else (map sort (partition-all (Math/ceil (/ (count coll) cols)) coll))))) (defn formatted-apropos [wrd] (let [suggests (sort-by (juxt count identity) (map str (apropos wrd)))] (when-let [suggests (not-empty (take 50 suggests))] (let [terminal-width (:cols (terminal-size))] (->> (divide-into-displayable-columns suggests terminal-width) (map (partial format-column wrd)) (apply map vector) (map #(interpose " " %)) (map #(apply astring/astr %)) (interpose (apply str "\n")) (apply astring/astr)))))) (def apropos-at-point-widget (create-widget (when-let [[wrd] (word-at-cursor)] (when-let [aprs (formatted-apropos wrd)] (display-less aprs {:header (AttributedString. (str "Apropos for: " wrd) (.faint AttributedStyle/DEFAULT))}))) true)) (defn in-place-eval [] (let [s (buffer-as-string)] (when (not (string/blank? s)) (let [pos (cursor) fnw-pos (sexp/first-non-whitespace-char-backwards-from s (dec pos)) [form-str start end typ] (sexp/sexp-or-word-ending-at-position s fnw-pos)] (evaluate-str form-str))))) (defn inline-result-marker [^AttributedString at-str] (astring/astr ["#_=>" (color :widget/half-contrast-inverse)] " " at-str)) (defn limit-character-size [s] (let [{:keys [rows cols]} (terminal-size) max-char (int (* (- rows (count (string/split-lines (buffer-as-string)))) cols 0.5))] (if (< max-char (count s)) (str (subs s 0 max-char) "...") s))) (defn ensure-newline [s] (str (string/trim-newline s) "\n")) (defn no-greater-than [limit val] (min limit (or val Integer/MAX_VALUE))) (defn format-data-eval-result [{:keys [out err result printed-result exception] :as eval-result}] (let [[printed-result exception] (if (not printed-result) (try (binding [*print-length* (no-greater-than 100 *print-length*) *print-level* (no-greater-than 5 *print-level*)] [(pr-str result) exception]) (catch Throwable t [nil (Throwable->map t)])) [printed-result exception])] (cond-> (AttributedStringBuilder.) exception (.styled (color :widget/error) (str "=>!! " (or (:cause exception) (some-> exception :via first :type))) ) (not (string/blank? out)) (.append (ensure-newline out)) (not (string/blank? err)) (.styled (color :widget/error) (ensure-newline err)) (and (not exception) printed-result) (.append (inline-result-marker (.toAttributedString (highlight-clj-str printed-result))))))) (def eval-at-point-widget (create-widget (when-let [result (in-place-eval)] (display-less (format-data-eval-result result))) true)) (def end-of-buffer (create-widget (cursor (.length *buffer*)) true)) (def beginning-of-buffer (create-widget (cursor 0) true)) (defn add-all-widgets [line-reader] (binding [*line-reader* line-reader] (register-widget "clojure-indent-line" indent-line-widget) (register-widget "clojure-indent-or-complete" indent-or-complete-widget) (register-widget "clojure-doc-at-point" document-at-point-widget) (register-widget "clojure-source-at-point" source-at-point-widget) (register-widget "clojure-apropos-at-point" apropos-at-point-widget) (register-widget "clojure-eval-at-point" eval-at-point-widget) (register-widget "clojure-force-accept-line" always-accept-line) (register-widget "end-of-buffer" end-of-buffer) (register-widget "beginning-of-buffer" beginning-of-buffer))) (defn bind-indents [km-name] (doto km-name (key-binding (str (KeyMap/ctrl \X) (KeyMap/ctrl \I)) "clojure-indent-line") (key-binding (KeyMap/ctrl \I) "clojure-indent-or-complete"))) (defn bind-clojure-widgets [km-name] (doto km-name (key-binding (str (KeyMap/ctrl \X) (KeyMap/ctrl \D)) "clojure-doc-at-point") (key-binding (str (KeyMap/ctrl \X) (KeyMap/ctrl \S)) "clojure-source-at-point") (key-binding (str (KeyMap/ctrl \X) (KeyMap/ctrl \A)) "clojure-apropos-at-point") (key-binding (str (KeyMap/ctrl \X) (KeyMap/ctrl \E)) "clojure-eval-at-point") (key-binding (str (KeyMap/ctrl \X) (KeyMap/ctrl \M)) "clojure-force-accept-line"))) (defn bind-clojure-widgets-vi-cmd [km-name] (doto km-name (key-binding (str \\ \d) "clojure-doc-at-point") (key-binding (str \\ \s) "clojure-source-at-point") (key-binding (str \\ \a) "clojure-apropos-at-point") (key-binding (str \\ \e) "clojure-eval-at-point"))) (defn clojure-emacs-mode [km-name] (doto km-name bind-indents bind-clojure-widgets (key-binding (KeyMap/key (.getTerminal *line-reader*) InfoCmp$Capability/key_end) "end-of-buffer") (key-binding (KeyMap/key (.getTerminal *line-reader*) InfoCmp$Capability/key_home) "beginning-of-buffer"))) (defn clojure-vi-insert-mode [km-name] (doto km-name clojure-emacs-mode (key-binding (str (KeyMap/ctrl \E)) "clojure-force-accept-line"))) (defn clojure-vi-cmd-mode [km-name] (doto km-name bind-indents bind-clojure-widgets bind-clojure-widgets-vi-cmd)) (defn add-widgets-and-bindings [line-reader] (binding [*line-reader* line-reader] (clojure-emacs-mode :emacs) (clojure-vi-insert-mode :viins) (clojure-vi-cmd-mode :vicmd) (swap! line-reader #(update % :self-insert-hooks (fnil conj #{}) eldoc-self-insert-hook)) (doto line-reader (.setVariable LineReader/WORDCHARS "") add-all-widgets))) Building a Line Reader Jline parser for Clojure Jline uses a parser that pulls out the words from a read line (defn parse-line [line cursor] (let [tokens (tokenize/tag-words line) words (filter (comp #{:string-literal-without-quotes :unterm-string-literal-without-quotes :word} last) tokens) word (first (filter (fn [[_ s e]] (<= s cursor e)) words)) word-index (.indexOf (vec words) word) word-cursor (if-not word 0 (- cursor (second word)))] TODO this can return a parsedline directly {:word-index (or word-index -1) :word (or (first word) "") :word-cursor word-cursor :tokens words :word-token word :words (map first words) :line line :cursor cursor})) (defn parsed-line [{:keys [word-index word word-cursor words tokens line cursor] :as parse-data}] (proxy [ParsedLine clojure.lang.IMeta] [] (word [] word) (wordIndex [] word-index) (wordCursor [] word-cursor) (words [] (java.util.LinkedList. words)) (line [] line) (cursor [] cursor) (meta [] parse-data))) (defn indent [line-reader line cursor] TODO this key binding needs to be looked up from the macro if possible a two key macro here adds a slight delay to the indent action I think (.runMacro line-reader (str (KeyMap/ctrl \X) (KeyMap/ctrl \I)))) a parser for jline that respects (defn make-parser [] (doto (proxy [DefaultParser] [] (isDelimiterChar [^CharSequence buffer pos] (boolean (#{\space \tab \return \newline \, \{ \} \( \) \[ \] } (.charAt buffer pos)))) (parse [^String line cursor ^Parser$ParseContext context] (cond (= context Parser$ParseContext/ACCEPT_LINE) (when-not (or (and *accept-fn* (*accept-fn* line cursor)) (accept-line line cursor)) (indent *line-reader* line cursor) (throw (EOFError. -1 -1 "Unbalanced Expression" (str *ns*)))) (= context Parser$ParseContext/COMPLETE) (parsed-line (parse-line line cursor)) :else (proxy-super parse line cursor context)))) (.setQuoteChars (char-array [\"])))) Jline completer for Clojure candidates (defn parsed-line-word-coords [^ParsedLine parsed-line] (let [pos (.cursor parsed-line) word-cursor (.wordCursor parsed-line) word (.word parsed-line) word-start (- pos word-cursor) word-end (+ pos (- (count word) word-cursor))] [word-start word-end])) TODO this has string hacks in it that would n't be needed (defn replace-word-with-prefix [parsed-line] (let [[start end] (parsed-line-word-coords parsed-line) [_ _ _ typ] (:word-token (meta parsed-line)) line (.line parsed-line)] [(str (subs line 0 start) "__prefix__" (when (= typ :unterm-string-literal-without-quotes) \") (subs line end (count line))) (+ start (count "__prefix__") (if (#{:string-literal-without-quotes :unterm-string-literal-without-quotes} typ) 1 0))])) (defn complete-context [^ParsedLine parsed-line] (when-let [[form-str end-of-marker] (replace-word-with-prefix parsed-line)] (when-let [valid-sexp (sexp/valid-sexp-from-point form-str end-of-marker)] (binding [*default-data-reader-fn* identity] (try (read-string valid-sexp) (catch Throwable e (log :complete-context e) nil)))))) (defn candidate [{:keys [candidate type ns]}] (Candidate. (cond-> nil type (str (first (name type))) ns (str (when type " ") ns)) false)) (defn command-token? [{:keys [line tokens word]} starts-with] (and (= 1 (count tokens)) (.startsWith (string/triml line) starts-with) (.startsWith word starts-with))) (defn find-completions [candidates prefix] (->> candidates (map str) (filter #(.startsWith % prefix)) (sort-by (juxt count identity)) (map #(hash-map :candidate % :type :repl-command)) not-empty)) (defn repl-command-complete [{:keys [word] :as parsed-line}] (when (command-token? parsed-line ":r") (find-completions (commands/all-commands) word))) (defn cljs-quit-complete [{:keys [word] :as parsed-line}] (when (command-token? parsed-line ":c") (find-completions [:cljs/quit] word))) TODO abstract completion service here (defn clojure-completer [] (proxy [Completer] [] (complete [^LineReader reader ^ParsedLine line ^java.util.List candidates] (let [word (.word line)] (when (and (:completion @*line-reader*) (not (string/blank? word)) (pos? (count word))) (let [options (let [ns' (current-ns) context (complete-context line)] (cond-> {} ns' (assoc :ns ns') context (assoc :context context)))] (->> (or (repl-command-complete (meta line)) (cljs-quit-complete (meta line)) (completions (.word line) options)) (map #(candidate %)) (take 10) (.addAll candidates)))))))) Jline highlighter for Clojure code (defn clojure-highlighter [] (proxy [Highlighter] [] (highlight [^LineReader reader ^String buffer] (binding [*line-reader* reader] (if (:highlight @reader) (.toAttributedString (highlight-clj-str buffer)) (AttributedString. buffer)))))) (defn create* [terminal service & [{:keys [completer highlighter parser]}]] {:pre [(instance? org.jline.terminal.Terminal terminal) (map? service)]} (doto (create-line-reader terminal "Clojure Readline" service) (.setCompleter (or completer (clojure-completer))) (.setHighlighter (or highlighter (clojure-highlighter ))) (.setParser (or parser (make-parser))) (.setOpt LineReader$Option/DISABLE_EVENT_EXPANSION) (.unsetOpt LineReader$Option/INSERT_TAB) (.setVariable LineReader/SECONDARY_PROMPT_PATTERN "%P #_=> ") (.setVariable LineReader/HISTORY_FILE (str (io/file ".rebel_readline_history"))) (.setOpt LineReader$Option/HISTORY_REDUCE_BLANKS) (.setOpt LineReader$Option/HISTORY_IGNORE_DUPS) (.setOpt LineReader$Option/HISTORY_INCREMENTAL) add-widgets-and-bindings (#(binding [*line-reader* %] (apply-key-bindings!) (set-main-key-map! (get service :key-map :emacs)))))) (defn create "Creates a line reader takes a service as an argument. A service implements the multimethods found in `rebel-readline.service` Example: (create (rebel-readline.clojure.service.local/create)) Or: (create (rebel-readline.clojure.service.simple/create)) This function also takes an optional options map. The available options are: :completer - to override the clojure based completer :highlighter - to override the clojure based systax highlighter :parser - to override the clojure base word parser" [service & [options]] (create* api/*terminal* service options))
9845ca4870691eb3ba8b63a79b0d308eec795924f3aca813809e6ae2538e8077
Gabriella439/Haskell-Morte-Library
Core.hs
# LANGUAGE CPP # {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE DeriveFoldable # {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} # OPTIONS_GHC -Wall # | This module contains the core calculus for the Morte language . This language is a minimalist implementation of the calculus of constructions , which is in turn a specific kind of pure type system . If you are new to pure type systems you may wish to read \"Henk : a typed intermediate language\ " . < -us/um/people/simonpj/papers/henk.ps.gz > is a strongly normalizing language , meaning that : * Every expression has a unique normal form computed by ` normalize ` * You test expressions for equality of their normal forms using ` = = ` * Equational reasoning preserves normal forms Strong normalization comes at a price : Morte forbids recursion . Instead , you must translate all recursion to F - algebras and translate all corecursion to F - coalgebras . If you are new to F-(co)algebras then you may wish to read " Morte . Tutorial " or read \"Recursive types for free!\ " : < -rectypes/free-rectypes.txt > Morte is designed to be a super - optimizing intermediate language with a simple optimization scheme . You optimize a Morte expression by just normalizing the expression . If you normalize a long - lived program encoded as an F - coalgebra you typically get a state machine , and if you normalize a long - lived program encoded as an F - algebra you typically get an unrolled loop . Strong normalization guarantees that all abstractions encodable in Morte are \"free\ " , meaning that they may increase your program 's compile times but they will never increase your program 's run time because they will normalize to the same code . language is a minimalist implementation of the calculus of constructions, which is in turn a specific kind of pure type system. If you are new to pure type systems you may wish to read \"Henk: a typed intermediate language\". <-us/um/people/simonpj/papers/henk.ps.gz> Morte is a strongly normalizing language, meaning that: * Every expression has a unique normal form computed by `normalize` * You test expressions for equality of their normal forms using `==` * Equational reasoning preserves normal forms Strong normalization comes at a price: Morte forbids recursion. Instead, you must translate all recursion to F-algebras and translate all corecursion to F-coalgebras. If you are new to F-(co)algebras then you may wish to read "Morte.Tutorial" or read \"Recursive types for free!\": <-rectypes/free-rectypes.txt> Morte is designed to be a super-optimizing intermediate language with a simple optimization scheme. You optimize a Morte expression by just normalizing the expression. If you normalize a long-lived program encoded as an F-coalgebra you typically get a state machine, and if you normalize a long-lived program encoded as an F-algebra you typically get an unrolled loop. Strong normalization guarantees that all abstractions encodable in Morte are \"free\", meaning that they may increase your program's compile times but they will never increase your program's run time because they will normalize to the same code. -} module Morte.Core ( -- * Syntax Var(..), Const(..), Path(..), Expr(..), Context, -- * Core functions typeWith, typeOf, normalize, -- * Utilities shift, subst, pretty, buildExpr, buildExprASCII, -- * Errors TypeError(..), TypeMessage(..), ) where #if MIN_VERSION_base(4,8,0) #else import Control.Applicative (Applicative(..), (<$>)) #endif import Control.DeepSeq (NFData(..)) import Control.Exception (Exception) import Data.Binary (Binary(..), Get, Put) import Data.Foldable import Data.Monoid ((<>)) import Data.String (IsString(..)) import Data.Text.Lazy (Text) import Data.Text.Lazy.Builder (Builder) import Data.Traversable import Data.Typeable (Typeable) import Data.Void (Void, absurd) import Data.Word (Word8) import Filesystem.Path.CurrentOS (FilePath) import Formatting.Buildable (Buildable(..)) import Morte.Context (Context) import Prelude hiding (FilePath) import qualified Control.Monad.Trans.State.Strict as State import qualified Data.Binary.Get as Get import qualified Data.Binary.Put as Put import qualified Data.Text.Encoding as Text import qualified Data.Text.Lazy as Text import qualified Data.Text.Lazy.Builder as Builder import qualified Filesystem.Path.CurrentOS as Filesystem import qualified Morte.Context as Context | Label for a bound variable The ` Text ` field is the variable 's name ( i.e. \"@x@\ " ) . The ` Int ` field disambiguates variables with the same name if there are multiple bound variables of the same name in scope . Zero refers to the nearest bound variable and the index increases by one for each bound variable of the same name going outward . The following diagram may help : > + -refers to-+ > | | > v | > \(x : * ) - > \(y : * ) - > \(x : * ) - > x@0 > > + -------------refers to-------------+ > | | > v | > \(x : * ) - > \(y : * ) - > \(x : * ) - > x@1 This ` Int ` behaves like a De Bruijn index in the special case where all variables have the same name . You can optionally omit the index if it is @0@ : > + refers to+ > | | > v | > \(x : * ) - > \(y : * ) - > \(x : * ) - > x Zero indices are omitted when pretty - printing ` Var`s and non - zero indices appear as a numeric suffix . The `Text` field is the variable's name (i.e. \"@x@\"). The `Int` field disambiguates variables with the same name if there are multiple bound variables of the same name in scope. Zero refers to the nearest bound variable and the index increases by one for each bound variable of the same name going outward. The following diagram may help: > +-refers to-+ > | | > v | > \(x : *) -> \(y : *) -> \(x : *) -> x@0 > > +-------------refers to-------------+ > | | > v | > \(x : *) -> \(y : *) -> \(x : *) -> x@1 This `Int` behaves like a De Bruijn index in the special case where all variables have the same name. You can optionally omit the index if it is @0@: > +refers to+ > | | > v | > \(x : *) -> \(y : *) -> \(x : *) -> x Zero indices are omitted when pretty-printing `Var`s and non-zero indices appear as a numeric suffix. -} data Var = V Text Int deriving (Eq, Show) putUtf8 :: Text -> Put putUtf8 txt = put (Text.encodeUtf8 (Text.toStrict txt)) getUtf8 :: Get Text getUtf8 = do bs <- get case Text.decodeUtf8' bs of Left e -> fail (show e) Right txt -> return (Text.fromStrict txt) instance Binary Var where put (V x n) = do putUtf8 x Put.putWord64le (fromIntegral n) get = V <$> getUtf8 <*> fmap fromIntegral Get.getWord64le instance IsString Var where fromString str = V (Text.pack str) 0 instance NFData Var where rnf (V n p) = rnf n `seq` rnf p instance Buildable Var where build (V txt n) = build txt <> if n == 0 then "" else ("@" <> build n) | Constants for the calculus of constructions The only axiom is : > ⊦ * : □ ... and all four rule pairs are valid : > ⊦ * ↝ * : * > ⊦ □ ↝ * : * > ⊦ * ↝ □ : □ > ⊦ □ ↝ □ : □ The only axiom is: > ⊦ * : □ ... and all four rule pairs are valid: > ⊦ * ↝ * : * > ⊦ □ ↝ * : * > ⊦ * ↝ □ : □ > ⊦ □ ↝ □ : □ -} data Const = Star | Box deriving (Eq, Show, Bounded, Enum) instance Binary Const where put c = case c of Star -> put (0 :: Word8) Box -> put (1 :: Word8) get = do n <- get :: Get Word8 case n of 0 -> return Star 1 -> return Box _ -> fail "get Const: Invalid tag byte" instance NFData Const where rnf c = seq c () instance Buildable Const where build c = case c of Star -> "*" Box -> "□" axiom :: Const -> Either TypeError Const axiom Star = return Box axiom Box = Left (TypeError Context.empty (Const Box) (Untyped Box)) rule :: Const -> Const -> Either TypeError Const rule Star Box = return Box rule Star Star = return Star rule Box Box = return Box rule Box Star = return Star -- | Path to an external resource data Path = File FilePath | URL Text deriving (Eq, Ord, Show) instance Buildable Path where build (File file) | Text.isPrefixOf "./" txt || Text.isPrefixOf "/" txt || Text.isPrefixOf "../" txt = build txt <> " " | otherwise = "./" <> build txt <> " " where txt = Text.fromStrict (either id id (Filesystem.toText file)) build (URL str ) = build str <> " " -- | Syntax tree for expressions data Expr a -- | > Const c ~ c = Const Const | > Var ( V x 0 ) -- > Var (V x n) ~ x@n | Var Var | > A b ~ λ(x : A ) → b | Lam Text (Expr a) (Expr a) -- | > Pi x A B ~ ∀(x : A) → B -- > Pi unused A B ~ A → B | Pi Text (Expr a) (Expr a) -- | > App f a ~ f a | App (Expr a) (Expr a) -- | > Embed path ~ #path | Embed a deriving (Functor, Foldable, Traversable, Show) instance Applicative Expr where pure = Embed mf <*> mx = case mf of Const c -> Const c Var v -> Var v Lam x _A b -> Lam x (_A <*> mx) ( b <*> mx) Pi x _A _B -> Pi x (_A <*> mx) (_B <*> mx) App f a -> App (f <*> mx) (a <*> mx) Embed f -> fmap f mx instance Monad Expr where return = Embed m >>= k = case m of Const c -> Const c Var v -> Var v Lam x _A b -> Lam x (_A >>= k) ( b >>= k) Pi x _A _B -> Pi x (_A >>= k) (_B >>= k) App f a -> App (f >>= k) (a >>= k) Embed r -> k r match :: Text -> Int -> Text -> Int -> [(Text, Text)] -> Bool match xL nL xR nR [] = xL == xR && nL == nR match xL 0 xR 0 ((xL', xR'):_ ) | xL == xL' && xR == xR' = True match xL nL xR nR ((xL', xR'):xs) = nL' `seq` nR' `seq` match xL nL' xR nR' xs where nL' = if xL == xL' then nL - 1 else nL nR' = if xR == xR' then nR - 1 else nR instance Eq a => Eq (Expr a) where eL0 == eR0 = State.evalState (go (normalize eL0) (normalize eR0)) [] where go : : a - > Expr a - > State [ ( Text , Text ) ] Bool go (Const cL) (Const cR) = return (cL == cR) go (Var (V xL nL)) (Var (V xR nR)) = do ctx <- State.get return (match xL nL xR nR ctx) go (Lam xL tL bL) (Lam xR tR bR) = do ctx <- State.get eq1 <- go tL tR if eq1 then do State.put ((xL, xR):ctx) eq2 <- go bL bR State.put ctx return eq2 else return False go (Pi xL tL bL) (Pi xR tR bR) = do ctx <- State.get eq1 <- go tL tR if eq1 then do State.put ((xL, xR):ctx) eq2 <- go bL bR State.put ctx return eq2 else return False go (App fL aL) (App fR aR) = do b1 <- go fL fR if b1 then go aL aR else return False go (Embed pL) (Embed pR) = return (pL == pR) go _ _ = return False instance Binary a => Binary (Expr a) where put e = case e of Const c -> do put (0 :: Word8) put c Var x -> do put (1 :: Word8) put x Lam x _A b -> do put (2 :: Word8) putUtf8 x put _A put b Pi x _A _B -> do put (3 :: Word8) putUtf8 x put _A put _B App f a -> do put (4 :: Word8) put f put a Embed p -> do put (5 :: Word8) put p get = do n <- get :: Get Word8 case n of 0 -> Const <$> get 1 -> Var <$> get 2 -> Lam <$> getUtf8 <*> get <*> get 3 -> Pi <$> getUtf8 <*> get <*> get 4 -> App <$> get <*> get 5 -> Embed <$> get _ -> fail "get Expr: Invalid tag byte" instance IsString (Expr a) where fromString str = Var (fromString str) instance NFData a => NFData (Expr a) where rnf e = case e of Const c -> rnf c Var v -> rnf v Lam x _A b -> rnf x `seq` rnf _A `seq` rnf b Pi x _A _B -> rnf x `seq` rnf _A `seq` rnf _B App f a -> rnf f `seq` rnf a Embed p -> rnf p buildLabel :: Text -> Builder buildLabel = build buildNumber :: Int -> Builder buildNumber = build buildConst :: Const -> Builder buildConst = build buildVExpr :: Var -> Builder buildVExpr (V a 0) = buildLabel a buildVExpr (V a b) = buildLabel a <> "@" <> buildNumber b | Pretty - print an expression as a ` Builder ` , using Unicode symbols buildExpr :: Buildable a => Expr a -> Builder buildExpr (Lam a b c) = "λ(" <> buildLabel a <> " : " <> buildExpr b <> ") → " <> buildExpr c buildExpr (Pi "_" b c) = buildBExpr b <> " → " <> buildExpr c buildExpr (Pi a b c) = "∀(" <> buildLabel a <> " : " <> buildExpr b <> ") → " <> buildExpr c buildExpr e = buildBExpr e buildBExpr :: Buildable a => Expr a -> Builder buildBExpr (App a b) = buildBExpr a <> " " <> buildAExpr b buildBExpr a = buildAExpr a buildAExpr :: Buildable a => Expr a -> Builder buildAExpr (Var a) = buildVExpr a buildAExpr (Const a) = buildConst a buildAExpr (Embed a) = build a buildAExpr a = "(" <> buildExpr a <> ")" -- | Pretty-print an expression as a `Builder`, using ASCII symbols buildExprASCII :: Buildable a => Expr a -> Builder buildExprASCII (Lam a b c) = "\\(" <> buildLabel a <> " : " <> buildExprASCII b <> ") -> " <> buildExprASCII c buildExprASCII (Pi "_" b c) = buildBExprASCII b <> " -> " <> buildExprASCII c buildExprASCII (Pi a b c) = "forall (" <> buildLabel a <> " : " <> buildExprASCII b <> ") -> " <> buildExprASCII c buildExprASCII e = buildBExprASCII e buildBExprASCII :: Buildable a => Expr a -> Builder buildBExprASCII (App a b) = buildBExprASCII a <> " " <> buildAExprASCII b buildBExprASCII a = buildAExprASCII a buildAExprASCII :: Buildable a => Expr a -> Builder buildAExprASCII (Var a) = buildVExpr a buildAExprASCII (Const a) = buildConst a buildAExprASCII (Embed a) = build a buildAExprASCII a = "(" <> buildExprASCII a <> ")" | Generates a syntactically valid Morte program instance Buildable a => Buildable (Expr a) where build = buildExpr -- | The specific type error data TypeMessage = UnboundVariable | InvalidInputType (Expr Void) | InvalidOutputType (Expr Void) | NotAFunction | TypeMismatch (Expr Void) (Expr Void) | Untyped Const deriving (Show) instance NFData TypeMessage where rnf tm = case tm of UnboundVariable -> () InvalidInputType e -> rnf e InvalidOutputType e -> rnf e NotAFunction -> () TypeMismatch e1 e2 -> rnf e1 `seq` rnf e2 Untyped c -> rnf c instance Buildable TypeMessage where build msg = case msg of UnboundVariable -> "Error: Unbound variable\n" InvalidInputType expr -> "Error: Invalid input type\n" <> "\n" <> "Type: " <> build expr <> "\n" InvalidOutputType expr -> "Error: Invalid output type\n" <> "\n" <> "Type: " <> build expr <> "\n" NotAFunction -> "Error: Only functions may be applied to values\n" TypeMismatch expr1 expr2 -> "Error: Function applied to argument of the wrong type\n" <> "\n" <> "Expected type: " <> build expr1 <> "\n" <> "Argument type: " <> build expr2 <> "\n" Untyped c -> "Error: " <> build c <> " has no type\n" -- | A structured type error that includes context data TypeError = TypeError { context :: Context (Expr Void) , current :: Expr Void , typeMessage :: TypeMessage } deriving (Typeable) instance Show TypeError where show = Text.unpack . pretty instance Exception TypeError instance NFData TypeError where rnf (TypeError ctx crr tym) = rnf ctx `seq` rnf crr `seq` rnf tym instance Buildable TypeError where build (TypeError ctx expr msg) = "\n" <> ( if Text.null (Builder.toLazyText (buildContext ctx)) then "" else "Context:\n" <> buildContext ctx <> "\n" ) <> "Expression: " <> build expr <> "\n" <> "\n" <> build msg where buildKV (key, val) = build key <> " : " <> build val buildContext = build . Text.unlines . map (Builder.toLazyText . buildKV) . reverse . Context.toList {-| Substitute all occurrences of a variable with an expression > subst x n C B ~ B[x@n := C] -} subst :: Text -> Int -> Expr a -> Expr a -> Expr a subst x n e' e = case e of Lam x' _A b -> Lam x' (subst x n e' _A) b' where n' = if x == x' then n + 1 else n b' = n' `seq` subst x n' (shift 1 x' e') b Pi x' _A _B -> Pi x' (subst x n e' _A) _B' where n' = if x == x' then n + 1 else n _B' = n' `seq` subst x n' (shift 1 x' e') _B App f a -> App (subst x n e' f) (subst x n e' a) Var (V x' n') -> if x == x' && n == n' then e' else e Const k -> Const k The Morte compiler enforces that all embedded values -- are closed expressions Embed p -> Embed p | @shift n adds @n@ to the index of all free variables named @x@ within an ` Expr ` `Expr` -} shift :: Int -> Text -> Expr a -> Expr a shift d x0 e0 = go e0 0 where go e c = case e of Lam x _A b -> Lam x (go _A c) (go b $! c') where c' = if x == x0 then c + 1 else c Pi x _A _B -> Pi x (go _A c) (go _B $! c') where c' = if x == x0 then c + 1 else c App f a -> App (go f c) (go a c) Var (V x n) -> n' `seq` Var (V x n') where n' = if x == x0 && n >= c then n + d else n Const k -> Const k The Morte compiler enforces that all embedded values -- are closed expressions Embed p -> Embed p {-| Type-check an expression and return the expression's type if type-checking suceeds or an error if type-checking fails `typeWith` does not necessarily normalize the type since full normalization is not necessary for just type-checking. If you actually care about the returned type then you may want to `normalize` it afterwards. -} typeWith :: Context (Expr Void) -> Expr Void -> Either TypeError (Expr Void) typeWith ctx e = case e of Const c -> fmap Const (axiom c) Var (V x n) -> case Context.lookup x n ctx of Nothing -> Left (TypeError ctx e UnboundVariable) Just a -> return a Lam x _A b -> do _ <- typeWith ctx _A let ctx' = fmap (shift 1 x) (Context.insert x _A ctx) _B <- typeWith ctx' b let p = Pi x _A _B _t <- typeWith ctx p return p Pi x _A _B -> do eS <- fmap whnf (typeWith ctx _A) s <- case eS of Const s -> return s _ -> Left (TypeError ctx e (InvalidInputType _A)) let ctx' = fmap (shift 1 x) (Context.insert x _A ctx) eT <- fmap whnf (typeWith ctx' _B) t <- case eT of Const t -> return t _ -> Left (TypeError ctx' e (InvalidOutputType _B)) fmap Const (rule s t) App f a -> do e' <- fmap whnf (typeWith ctx f) (x, _A, _B) <- case e' of Pi x _A _B -> return (x, _A, _B) _ -> Left (TypeError ctx e NotAFunction) _A' <- typeWith ctx a if _A == _A' then do let a' = shift 1 x a _B' = subst x 0 a' _B return (shift (-1) x _B') else do let nf_A = normalize _A nf_A' = normalize _A' Left (TypeError ctx e (TypeMismatch nf_A nf_A')) Embed p -> absurd p {-| `typeOf` is the same as `typeWith` with an empty context, meaning that the expression must be closed (i.e. no free variables), otherwise type-checking will fail. -} typeOf :: Expr Void -> Either TypeError (Expr Void) typeOf = typeWith Context.empty -- | Reduce an expression to weak-head normal form whnf :: Expr a -> Expr a whnf e = case e of App f a -> case whnf f of Lam x _A b -> whnf (shift (-1) x b') -- Beta reduce where a' = shift 1 x a b' = subst x 0 a' b f' -> App f' a _ -> e -- | Returns whether a variable is free in an expression freeIn :: Var -> Expr a -> Bool freeIn v@(V x n) = go where go e = case e of Lam x' _A b -> n' `seq` (go _A || if x == x' then freeIn (V x n') b else go b) where n' = n + 1 Pi x' _A _B -> n' `seq` (go _A || if x == x' then freeIn (V x n') _B else go _B) where n' = n + 1 Var v' -> v == v' App f a -> go f || go a Const _ -> False The Morte compiler enforces that all embedded values -- are closed expressions Embed _ -> False {-| Reduce an expression to its normal form, performing both beta reduction and eta reduction `normalize` does not type-check the expression. You may want to type-check expressions before normalizing them since normalization can convert an ill-typed expression into a well-typed expression. -} normalize :: Expr a -> Expr a normalize e = case e of Lam x _A b -> case b' of App f a -> case a' of Var v' | v == v' && not (v `freeIn` f) -> Eta reduce | otherwise -> e' where v = V x 0 _ -> e' where a' = whnf a _ -> e' where b' = normalize b e' = Lam x (normalize _A) b' Pi x _A _B -> Pi x (normalize _A) (normalize _B) App f a -> case normalize f of Lam x _A b -> normalize (shift (-1) x b') -- Beta reduce where a' = shift 1 x (normalize a) b' = subst x 0 a' b f' -> App f' (normalize a) Var _ -> e Const _ -> e Embed p -> Embed p -- | Pretty-print a value pretty :: Buildable a => a -> Text pretty = Builder.toLazyText . build
null
https://raw.githubusercontent.com/Gabriella439/Haskell-Morte-Library/f7a459c7ec1d69f71c389f5693a26a94c1854636/src/Morte/Core.hs
haskell
# LANGUAGE DeriveDataTypeable # # LANGUAGE DeriveFunctor # # LANGUAGE DeriveTraversable # # LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # * Syntax * Core functions * Utilities * Errors -----------refers to-------------+ -----------refers to-------------+ | Path to an external resource | Syntax tree for expressions | > Const c ~ c > Var (V x n) ~ x@n | > Pi x A B ~ ∀(x : A) → B > Pi unused A B ~ A → B | > App f a ~ f a | > Embed path ~ #path | Pretty-print an expression as a `Builder`, using ASCII symbols | The specific type error | A structured type error that includes context | Substitute all occurrences of a variable with an expression > subst x n C B ~ B[x@n := C] are closed expressions are closed expressions | Type-check an expression and return the expression's type if type-checking suceeds or an error if type-checking fails `typeWith` does not necessarily normalize the type since full normalization is not necessary for just type-checking. If you actually care about the returned type then you may want to `normalize` it afterwards. | `typeOf` is the same as `typeWith` with an empty context, meaning that the expression must be closed (i.e. no free variables), otherwise type-checking will fail. | Reduce an expression to weak-head normal form Beta reduce | Returns whether a variable is free in an expression are closed expressions | Reduce an expression to its normal form, performing both beta reduction and eta reduction `normalize` does not type-check the expression. You may want to type-check expressions before normalizing them since normalization can convert an ill-typed expression into a well-typed expression. Beta reduce | Pretty-print a value
# LANGUAGE CPP # # LANGUAGE DeriveFoldable # # LANGUAGE GeneralizedNewtypeDeriving # # OPTIONS_GHC -Wall # | This module contains the core calculus for the Morte language . This language is a minimalist implementation of the calculus of constructions , which is in turn a specific kind of pure type system . If you are new to pure type systems you may wish to read \"Henk : a typed intermediate language\ " . < -us/um/people/simonpj/papers/henk.ps.gz > is a strongly normalizing language , meaning that : * Every expression has a unique normal form computed by ` normalize ` * You test expressions for equality of their normal forms using ` = = ` * Equational reasoning preserves normal forms Strong normalization comes at a price : Morte forbids recursion . Instead , you must translate all recursion to F - algebras and translate all corecursion to F - coalgebras . If you are new to F-(co)algebras then you may wish to read " Morte . Tutorial " or read \"Recursive types for free!\ " : < -rectypes/free-rectypes.txt > Morte is designed to be a super - optimizing intermediate language with a simple optimization scheme . You optimize a Morte expression by just normalizing the expression . If you normalize a long - lived program encoded as an F - coalgebra you typically get a state machine , and if you normalize a long - lived program encoded as an F - algebra you typically get an unrolled loop . Strong normalization guarantees that all abstractions encodable in Morte are \"free\ " , meaning that they may increase your program 's compile times but they will never increase your program 's run time because they will normalize to the same code . language is a minimalist implementation of the calculus of constructions, which is in turn a specific kind of pure type system. If you are new to pure type systems you may wish to read \"Henk: a typed intermediate language\". <-us/um/people/simonpj/papers/henk.ps.gz> Morte is a strongly normalizing language, meaning that: * Every expression has a unique normal form computed by `normalize` * You test expressions for equality of their normal forms using `==` * Equational reasoning preserves normal forms Strong normalization comes at a price: Morte forbids recursion. Instead, you must translate all recursion to F-algebras and translate all corecursion to F-coalgebras. If you are new to F-(co)algebras then you may wish to read "Morte.Tutorial" or read \"Recursive types for free!\": <-rectypes/free-rectypes.txt> Morte is designed to be a super-optimizing intermediate language with a simple optimization scheme. You optimize a Morte expression by just normalizing the expression. If you normalize a long-lived program encoded as an F-coalgebra you typically get a state machine, and if you normalize a long-lived program encoded as an F-algebra you typically get an unrolled loop. Strong normalization guarantees that all abstractions encodable in Morte are \"free\", meaning that they may increase your program's compile times but they will never increase your program's run time because they will normalize to the same code. -} module Morte.Core ( Var(..), Const(..), Path(..), Expr(..), Context, typeWith, typeOf, normalize, shift, subst, pretty, buildExpr, buildExprASCII, TypeError(..), TypeMessage(..), ) where #if MIN_VERSION_base(4,8,0) #else import Control.Applicative (Applicative(..), (<$>)) #endif import Control.DeepSeq (NFData(..)) import Control.Exception (Exception) import Data.Binary (Binary(..), Get, Put) import Data.Foldable import Data.Monoid ((<>)) import Data.String (IsString(..)) import Data.Text.Lazy (Text) import Data.Text.Lazy.Builder (Builder) import Data.Traversable import Data.Typeable (Typeable) import Data.Void (Void, absurd) import Data.Word (Word8) import Filesystem.Path.CurrentOS (FilePath) import Formatting.Buildable (Buildable(..)) import Morte.Context (Context) import Prelude hiding (FilePath) import qualified Control.Monad.Trans.State.Strict as State import qualified Data.Binary.Get as Get import qualified Data.Binary.Put as Put import qualified Data.Text.Encoding as Text import qualified Data.Text.Lazy as Text import qualified Data.Text.Lazy.Builder as Builder import qualified Filesystem.Path.CurrentOS as Filesystem import qualified Morte.Context as Context | Label for a bound variable The ` Text ` field is the variable 's name ( i.e. \"@x@\ " ) . The ` Int ` field disambiguates variables with the same name if there are multiple bound variables of the same name in scope . Zero refers to the nearest bound variable and the index increases by one for each bound variable of the same name going outward . The following diagram may help : > + -refers to-+ > | | > v | > \(x : * ) - > \(y : * ) - > \(x : * ) - > x@0 > > | | > v | > \(x : * ) - > \(y : * ) - > \(x : * ) - > x@1 This ` Int ` behaves like a De Bruijn index in the special case where all variables have the same name . You can optionally omit the index if it is @0@ : > + refers to+ > | | > v | > \(x : * ) - > \(y : * ) - > \(x : * ) - > x Zero indices are omitted when pretty - printing ` Var`s and non - zero indices appear as a numeric suffix . The `Text` field is the variable's name (i.e. \"@x@\"). The `Int` field disambiguates variables with the same name if there are multiple bound variables of the same name in scope. Zero refers to the nearest bound variable and the index increases by one for each bound variable of the same name going outward. The following diagram may help: > +-refers to-+ > | | > v | > \(x : *) -> \(y : *) -> \(x : *) -> x@0 > > | | > v | > \(x : *) -> \(y : *) -> \(x : *) -> x@1 This `Int` behaves like a De Bruijn index in the special case where all variables have the same name. You can optionally omit the index if it is @0@: > +refers to+ > | | > v | > \(x : *) -> \(y : *) -> \(x : *) -> x Zero indices are omitted when pretty-printing `Var`s and non-zero indices appear as a numeric suffix. -} data Var = V Text Int deriving (Eq, Show) putUtf8 :: Text -> Put putUtf8 txt = put (Text.encodeUtf8 (Text.toStrict txt)) getUtf8 :: Get Text getUtf8 = do bs <- get case Text.decodeUtf8' bs of Left e -> fail (show e) Right txt -> return (Text.fromStrict txt) instance Binary Var where put (V x n) = do putUtf8 x Put.putWord64le (fromIntegral n) get = V <$> getUtf8 <*> fmap fromIntegral Get.getWord64le instance IsString Var where fromString str = V (Text.pack str) 0 instance NFData Var where rnf (V n p) = rnf n `seq` rnf p instance Buildable Var where build (V txt n) = build txt <> if n == 0 then "" else ("@" <> build n) | Constants for the calculus of constructions The only axiom is : > ⊦ * : □ ... and all four rule pairs are valid : > ⊦ * ↝ * : * > ⊦ □ ↝ * : * > ⊦ * ↝ □ : □ > ⊦ □ ↝ □ : □ The only axiom is: > ⊦ * : □ ... and all four rule pairs are valid: > ⊦ * ↝ * : * > ⊦ □ ↝ * : * > ⊦ * ↝ □ : □ > ⊦ □ ↝ □ : □ -} data Const = Star | Box deriving (Eq, Show, Bounded, Enum) instance Binary Const where put c = case c of Star -> put (0 :: Word8) Box -> put (1 :: Word8) get = do n <- get :: Get Word8 case n of 0 -> return Star 1 -> return Box _ -> fail "get Const: Invalid tag byte" instance NFData Const where rnf c = seq c () instance Buildable Const where build c = case c of Star -> "*" Box -> "□" axiom :: Const -> Either TypeError Const axiom Star = return Box axiom Box = Left (TypeError Context.empty (Const Box) (Untyped Box)) rule :: Const -> Const -> Either TypeError Const rule Star Box = return Box rule Star Star = return Star rule Box Box = return Box rule Box Star = return Star data Path = File FilePath | URL Text deriving (Eq, Ord, Show) instance Buildable Path where build (File file) | Text.isPrefixOf "./" txt || Text.isPrefixOf "/" txt || Text.isPrefixOf "../" txt = build txt <> " " | otherwise = "./" <> build txt <> " " where txt = Text.fromStrict (either id id (Filesystem.toText file)) build (URL str ) = build str <> " " data Expr a = Const Const | > Var ( V x 0 ) | Var Var | > A b ~ λ(x : A ) → b | Lam Text (Expr a) (Expr a) | Pi Text (Expr a) (Expr a) | App (Expr a) (Expr a) | Embed a deriving (Functor, Foldable, Traversable, Show) instance Applicative Expr where pure = Embed mf <*> mx = case mf of Const c -> Const c Var v -> Var v Lam x _A b -> Lam x (_A <*> mx) ( b <*> mx) Pi x _A _B -> Pi x (_A <*> mx) (_B <*> mx) App f a -> App (f <*> mx) (a <*> mx) Embed f -> fmap f mx instance Monad Expr where return = Embed m >>= k = case m of Const c -> Const c Var v -> Var v Lam x _A b -> Lam x (_A >>= k) ( b >>= k) Pi x _A _B -> Pi x (_A >>= k) (_B >>= k) App f a -> App (f >>= k) (a >>= k) Embed r -> k r match :: Text -> Int -> Text -> Int -> [(Text, Text)] -> Bool match xL nL xR nR [] = xL == xR && nL == nR match xL 0 xR 0 ((xL', xR'):_ ) | xL == xL' && xR == xR' = True match xL nL xR nR ((xL', xR'):xs) = nL' `seq` nR' `seq` match xL nL' xR nR' xs where nL' = if xL == xL' then nL - 1 else nL nR' = if xR == xR' then nR - 1 else nR instance Eq a => Eq (Expr a) where eL0 == eR0 = State.evalState (go (normalize eL0) (normalize eR0)) [] where go : : a - > Expr a - > State [ ( Text , Text ) ] Bool go (Const cL) (Const cR) = return (cL == cR) go (Var (V xL nL)) (Var (V xR nR)) = do ctx <- State.get return (match xL nL xR nR ctx) go (Lam xL tL bL) (Lam xR tR bR) = do ctx <- State.get eq1 <- go tL tR if eq1 then do State.put ((xL, xR):ctx) eq2 <- go bL bR State.put ctx return eq2 else return False go (Pi xL tL bL) (Pi xR tR bR) = do ctx <- State.get eq1 <- go tL tR if eq1 then do State.put ((xL, xR):ctx) eq2 <- go bL bR State.put ctx return eq2 else return False go (App fL aL) (App fR aR) = do b1 <- go fL fR if b1 then go aL aR else return False go (Embed pL) (Embed pR) = return (pL == pR) go _ _ = return False instance Binary a => Binary (Expr a) where put e = case e of Const c -> do put (0 :: Word8) put c Var x -> do put (1 :: Word8) put x Lam x _A b -> do put (2 :: Word8) putUtf8 x put _A put b Pi x _A _B -> do put (3 :: Word8) putUtf8 x put _A put _B App f a -> do put (4 :: Word8) put f put a Embed p -> do put (5 :: Word8) put p get = do n <- get :: Get Word8 case n of 0 -> Const <$> get 1 -> Var <$> get 2 -> Lam <$> getUtf8 <*> get <*> get 3 -> Pi <$> getUtf8 <*> get <*> get 4 -> App <$> get <*> get 5 -> Embed <$> get _ -> fail "get Expr: Invalid tag byte" instance IsString (Expr a) where fromString str = Var (fromString str) instance NFData a => NFData (Expr a) where rnf e = case e of Const c -> rnf c Var v -> rnf v Lam x _A b -> rnf x `seq` rnf _A `seq` rnf b Pi x _A _B -> rnf x `seq` rnf _A `seq` rnf _B App f a -> rnf f `seq` rnf a Embed p -> rnf p buildLabel :: Text -> Builder buildLabel = build buildNumber :: Int -> Builder buildNumber = build buildConst :: Const -> Builder buildConst = build buildVExpr :: Var -> Builder buildVExpr (V a 0) = buildLabel a buildVExpr (V a b) = buildLabel a <> "@" <> buildNumber b | Pretty - print an expression as a ` Builder ` , using Unicode symbols buildExpr :: Buildable a => Expr a -> Builder buildExpr (Lam a b c) = "λ(" <> buildLabel a <> " : " <> buildExpr b <> ") → " <> buildExpr c buildExpr (Pi "_" b c) = buildBExpr b <> " → " <> buildExpr c buildExpr (Pi a b c) = "∀(" <> buildLabel a <> " : " <> buildExpr b <> ") → " <> buildExpr c buildExpr e = buildBExpr e buildBExpr :: Buildable a => Expr a -> Builder buildBExpr (App a b) = buildBExpr a <> " " <> buildAExpr b buildBExpr a = buildAExpr a buildAExpr :: Buildable a => Expr a -> Builder buildAExpr (Var a) = buildVExpr a buildAExpr (Const a) = buildConst a buildAExpr (Embed a) = build a buildAExpr a = "(" <> buildExpr a <> ")" buildExprASCII :: Buildable a => Expr a -> Builder buildExprASCII (Lam a b c) = "\\(" <> buildLabel a <> " : " <> buildExprASCII b <> ") -> " <> buildExprASCII c buildExprASCII (Pi "_" b c) = buildBExprASCII b <> " -> " <> buildExprASCII c buildExprASCII (Pi a b c) = "forall (" <> buildLabel a <> " : " <> buildExprASCII b <> ") -> " <> buildExprASCII c buildExprASCII e = buildBExprASCII e buildBExprASCII :: Buildable a => Expr a -> Builder buildBExprASCII (App a b) = buildBExprASCII a <> " " <> buildAExprASCII b buildBExprASCII a = buildAExprASCII a buildAExprASCII :: Buildable a => Expr a -> Builder buildAExprASCII (Var a) = buildVExpr a buildAExprASCII (Const a) = buildConst a buildAExprASCII (Embed a) = build a buildAExprASCII a = "(" <> buildExprASCII a <> ")" | Generates a syntactically valid Morte program instance Buildable a => Buildable (Expr a) where build = buildExpr data TypeMessage = UnboundVariable | InvalidInputType (Expr Void) | InvalidOutputType (Expr Void) | NotAFunction | TypeMismatch (Expr Void) (Expr Void) | Untyped Const deriving (Show) instance NFData TypeMessage where rnf tm = case tm of UnboundVariable -> () InvalidInputType e -> rnf e InvalidOutputType e -> rnf e NotAFunction -> () TypeMismatch e1 e2 -> rnf e1 `seq` rnf e2 Untyped c -> rnf c instance Buildable TypeMessage where build msg = case msg of UnboundVariable -> "Error: Unbound variable\n" InvalidInputType expr -> "Error: Invalid input type\n" <> "\n" <> "Type: " <> build expr <> "\n" InvalidOutputType expr -> "Error: Invalid output type\n" <> "\n" <> "Type: " <> build expr <> "\n" NotAFunction -> "Error: Only functions may be applied to values\n" TypeMismatch expr1 expr2 -> "Error: Function applied to argument of the wrong type\n" <> "\n" <> "Expected type: " <> build expr1 <> "\n" <> "Argument type: " <> build expr2 <> "\n" Untyped c -> "Error: " <> build c <> " has no type\n" data TypeError = TypeError { context :: Context (Expr Void) , current :: Expr Void , typeMessage :: TypeMessage } deriving (Typeable) instance Show TypeError where show = Text.unpack . pretty instance Exception TypeError instance NFData TypeError where rnf (TypeError ctx crr tym) = rnf ctx `seq` rnf crr `seq` rnf tym instance Buildable TypeError where build (TypeError ctx expr msg) = "\n" <> ( if Text.null (Builder.toLazyText (buildContext ctx)) then "" else "Context:\n" <> buildContext ctx <> "\n" ) <> "Expression: " <> build expr <> "\n" <> "\n" <> build msg where buildKV (key, val) = build key <> " : " <> build val buildContext = build . Text.unlines . map (Builder.toLazyText . buildKV) . reverse . Context.toList subst :: Text -> Int -> Expr a -> Expr a -> Expr a subst x n e' e = case e of Lam x' _A b -> Lam x' (subst x n e' _A) b' where n' = if x == x' then n + 1 else n b' = n' `seq` subst x n' (shift 1 x' e') b Pi x' _A _B -> Pi x' (subst x n e' _A) _B' where n' = if x == x' then n + 1 else n _B' = n' `seq` subst x n' (shift 1 x' e') _B App f a -> App (subst x n e' f) (subst x n e' a) Var (V x' n') -> if x == x' && n == n' then e' else e Const k -> Const k The Morte compiler enforces that all embedded values Embed p -> Embed p | @shift n adds @n@ to the index of all free variables named @x@ within an ` Expr ` `Expr` -} shift :: Int -> Text -> Expr a -> Expr a shift d x0 e0 = go e0 0 where go e c = case e of Lam x _A b -> Lam x (go _A c) (go b $! c') where c' = if x == x0 then c + 1 else c Pi x _A _B -> Pi x (go _A c) (go _B $! c') where c' = if x == x0 then c + 1 else c App f a -> App (go f c) (go a c) Var (V x n) -> n' `seq` Var (V x n') where n' = if x == x0 && n >= c then n + d else n Const k -> Const k The Morte compiler enforces that all embedded values Embed p -> Embed p typeWith :: Context (Expr Void) -> Expr Void -> Either TypeError (Expr Void) typeWith ctx e = case e of Const c -> fmap Const (axiom c) Var (V x n) -> case Context.lookup x n ctx of Nothing -> Left (TypeError ctx e UnboundVariable) Just a -> return a Lam x _A b -> do _ <- typeWith ctx _A let ctx' = fmap (shift 1 x) (Context.insert x _A ctx) _B <- typeWith ctx' b let p = Pi x _A _B _t <- typeWith ctx p return p Pi x _A _B -> do eS <- fmap whnf (typeWith ctx _A) s <- case eS of Const s -> return s _ -> Left (TypeError ctx e (InvalidInputType _A)) let ctx' = fmap (shift 1 x) (Context.insert x _A ctx) eT <- fmap whnf (typeWith ctx' _B) t <- case eT of Const t -> return t _ -> Left (TypeError ctx' e (InvalidOutputType _B)) fmap Const (rule s t) App f a -> do e' <- fmap whnf (typeWith ctx f) (x, _A, _B) <- case e' of Pi x _A _B -> return (x, _A, _B) _ -> Left (TypeError ctx e NotAFunction) _A' <- typeWith ctx a if _A == _A' then do let a' = shift 1 x a _B' = subst x 0 a' _B return (shift (-1) x _B') else do let nf_A = normalize _A nf_A' = normalize _A' Left (TypeError ctx e (TypeMismatch nf_A nf_A')) Embed p -> absurd p typeOf :: Expr Void -> Either TypeError (Expr Void) typeOf = typeWith Context.empty whnf :: Expr a -> Expr a whnf e = case e of App f a -> case whnf f of where a' = shift 1 x a b' = subst x 0 a' b f' -> App f' a _ -> e freeIn :: Var -> Expr a -> Bool freeIn v@(V x n) = go where go e = case e of Lam x' _A b -> n' `seq` (go _A || if x == x' then freeIn (V x n') b else go b) where n' = n + 1 Pi x' _A _B -> n' `seq` (go _A || if x == x' then freeIn (V x n') _B else go _B) where n' = n + 1 Var v' -> v == v' App f a -> go f || go a Const _ -> False The Morte compiler enforces that all embedded values Embed _ -> False normalize :: Expr a -> Expr a normalize e = case e of Lam x _A b -> case b' of App f a -> case a' of Var v' | v == v' && not (v `freeIn` f) -> Eta reduce | otherwise -> e' where v = V x 0 _ -> e' where a' = whnf a _ -> e' where b' = normalize b e' = Lam x (normalize _A) b' Pi x _A _B -> Pi x (normalize _A) (normalize _B) App f a -> case normalize f of where a' = shift 1 x (normalize a) b' = subst x 0 a' b f' -> App f' (normalize a) Var _ -> e Const _ -> e Embed p -> Embed p pretty :: Buildable a => a -> Text pretty = Builder.toLazyText . build
307ccb1f55f55ef8c4dfa0551775384e6baad0b4c949f996643080e950477784
basho/riak_cs
riak_cs_bucket.erl
%% --------------------------------------------------------------------- %% Copyright ( c ) 2007 - 2014 Basho Technologies , Inc. All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% --------------------------------------------------------------------- %% @doc riak_cs bucket utility functions, but I dare not use a module %% name with '_utils'. -module(riak_cs_bucket). %% Public API -export([ fetch_bucket_object/2, create_bucket/6, delete_bucket/4, get_buckets/1, set_bucket_acl/5, set_bucket_policy/5, delete_bucket_policy/4, get_bucket_acl_policy/3, maybe_log_bucket_owner_error/2, resolve_buckets/3, update_bucket_record/1, delete_all_uploads/2, delete_old_uploads/3, fold_all_buckets/3, fetch_bucket_keys/1 ]). -include("riak_cs.hrl"). -include_lib("riak_pb/include/riak_pb_kv_codec.hrl"). -include_lib("riakc/include/riakc.hrl"). -ifdef(TEST). -compile(export_all). -include_lib("eunit/include/eunit.hrl"). -endif. %% =================================================================== %% Public API %% =================================================================== %% @doc Create a bucket in the global namespace or return %% an error if it already exists. -spec create_bucket(rcs_user(), term(), binary(), bag_id(), acl(), riak_client()) -> ok | {error, term()}. create_bucket(User, UserObj, Bucket, BagId, ACL, RcPid) -> CurrentBuckets = get_buckets(User), %% Do not attempt to create bucket if the user already owns it AttemptCreate = riak_cs_config:disable_local_bucket_check() orelse not bucket_exists(CurrentBuckets, binary_to_list(Bucket)), case AttemptCreate of true -> BucketLimit = riak_cs_config:max_buckets_per_user(), case valid_bucket_name(Bucket) of true when length(CurrentBuckets) >= BucketLimit -> {error, {toomanybuckets, length(CurrentBuckets), BucketLimit}}; true -> serialized_bucket_op(Bucket, BagId, ACL, User, UserObj, create, [velvet, create_bucket], RcPid); false -> {error, invalid_bucket_name} end; false -> ok end. -spec valid_bucket_name(binary()) -> boolean(). valid_bucket_name(Bucket) when byte_size(Bucket) < 3 orelse byte_size(Bucket) > 63 -> false; valid_bucket_name(Bucket) -> lists:all(fun(X) -> X end, [valid_bucket_label(Label) || Label <- binary:split(Bucket, <<".">>, [global])]) andalso not is_bucket_ip_addr(binary_to_list(Bucket)). -spec valid_bucket_label(binary()) -> boolean(). valid_bucket_label(<<>>) -> this clause gets called when we either have a ` . ' as the first or %% last byte. Or if it appears twice in a row. Examples are: %% `<<".myawsbucket">>' %% `<<"myawsbucket.">>' %% `<<"my..examplebucket">>' false; valid_bucket_label(Label) -> valid_bookend_char(binary:first(Label)) andalso valid_bookend_char(binary:last(Label)) andalso lists:all(fun(X) -> X end, [valid_bucket_char(C) || C <- middle_chars(Label)]). -spec middle_chars(binary()) -> list(). middle_chars(B) when byte_size(B) < 3 -> []; middle_chars(B) -> ` binary : at/2 ' is zero based ByteSize = byte_size(B), [binary:at(B, Position) || Position <- lists:seq(1, ByteSize - 2)]. -spec is_bucket_ip_addr(string()) -> boolean(). is_bucket_ip_addr(Bucket) -> case inet_parse:ipv4strict_address(Bucket) of {ok, _} -> true; {error, _} -> false end. -spec valid_bookend_char(integer()) -> boolean(). valid_bookend_char(Char) -> numeric_char(Char) orelse lower_case_char(Char). -spec valid_bucket_char(integer()) -> boolean(). valid_bucket_char(Char) -> numeric_char(Char) orelse lower_case_char(Char) orelse dash_char(Char). -spec numeric_char(integer()) -> boolean(). numeric_char(Char) -> Char >= $0 andalso Char =< $9. -spec lower_case_char(integer()) -> boolean(). lower_case_char(Char) -> Char >= $a andalso Char =< $z. -spec dash_char(integer()) -> boolean(). dash_char(Char) -> Char =:= $-. %% @doc Delete a bucket -spec delete_bucket(rcs_user(), riakc_obj:riakc_obj(), binary(), riak_client()) -> ok | {error, remaining_multipart_upload}. delete_bucket(User, UserObj, Bucket, RcPid) -> CurrentBuckets = get_buckets(User), %% Buckets can only be deleted if they exist {AttemptDelete, LocalError} = case bucket_exists(CurrentBuckets, binary_to_list(Bucket)) of true -> case bucket_empty(Bucket, RcPid) of {ok, true} -> {true, ok}; {ok, false} -> {false, {error, bucket_not_empty}} end; false -> {true, ok} end, case AttemptDelete of true -> %% TODO: output log if failed in cleaning up existing uploads. %% The number of retry is hardcoded. {ok, Count} = delete_all_uploads(Bucket, RcPid), _ = lager:debug("deleted ~p multiparts before bucket deletion.", [Count]), %% This call still may return {error, remaining_multipart_upload} %% even if all uploads cleaned up above, because concurrent multiple deletion may happen . Then returns 409 confliction %% which is not in S3 specification.... serialized_bucket_op(Bucket, ?ACL{}, User, UserObj, delete, [velvet, delete_bucket], RcPid); false -> LocalError end. %% @doc TODO: this function is to be moved to riak_cs_multipart_utils or else? -spec delete_all_uploads(binary(), riak_client()) -> {ok, non_neg_integer()} | {error, term()}. delete_all_uploads(Bucket, RcPid) -> delete_old_uploads(Bucket, RcPid, <<255>>). %% @doc deletes all multipart uploads older than Timestamp. %% input binary format of iso8068 -spec delete_old_uploads(binary(), riak_client(), binary()) -> {ok, non_neg_integer()} | {error, term()}. delete_old_uploads(Bucket, RcPid, Timestamp) when is_binary(Timestamp) -> Opts = [{delimiter, undefined}, {max_uploads, undefined}, {prefix, undefined}, {key_marker, <<>>}, {upload_id_marker, <<>>}], {ok, {Ds, _Commons}} = riak_cs_mp_utils:list_all_multipart_uploads(Bucket, Opts, RcPid), fold_delete_uploads(Bucket, RcPid, Ds, Timestamp, 0). fold_delete_uploads(_Bucket, _RcPid, [], _Timestamp, Count) -> {ok, Count}; fold_delete_uploads(Bucket, RcPid, [D|Ds], Timestamp, Count)-> Key = D?MULTIPART_DESCR.key, %% cannot fail here {ok, Obj, Manifests} = riak_cs_manifest:get_manifests(RcPid, Bucket, Key), UploadId = D?MULTIPART_DESCR.upload_id, %% find_manifest_with_uploadid case lists:keyfind(UploadId, 1, Manifests) of {UploadId, M} when M?MANIFEST.state == writing %% comparing timestamp here, like < < " 2012 - 02 - 17T18:22:50.000Z " > > < < < " 2014 - 05 - 11- .... " > > = > true andalso M?MANIFEST.created < Timestamp -> case riak_cs_gc:gc_specific_manifests( [M?MANIFEST.uuid], Obj, Bucket, Key, RcPid) of {ok, _NewObj} -> fold_delete_uploads(Bucket, RcPid, Ds, Timestamp, Count+1); E -> lager:debug("cannot delete multipart manifest: ~p ~p (~p)", [{Bucket, Key}, M?MANIFEST.uuid, E]), E end; _E -> lager:debug("skipping multipart manifest: ~p ~p (~p)", [{Bucket, Key}, UploadId, _E]), fold_delete_uploads(Bucket, RcPid, Ds, Timestamp, Count) end. -spec fold_all_buckets(fun(), term(), riak_client()) -> {ok, term()} | {error, any()}. fold_all_buckets(Fun, Acc0, RcPid) when is_function(Fun) -> iterate_csbuckets(RcPid, Acc0, Fun, undefined). -spec iterate_csbuckets(riak_client(), term(), fun(), binary()|undefined) -> {ok, term()} | {error, any()}. iterate_csbuckets(RcPid, Acc0, Fun, Cont0) -> Options = case Cont0 of undefined -> []; _ -> [{continuation, Cont0}] end ++ [{max_results, 1024}], {ok, MasterPbc} = riak_cs_riak_client:master_pbc(RcPid), case riak_cs_pbc:get_index_range(MasterPbc, ?BUCKETS_BUCKET, <<"$key">>, <<0>>, <<255>>, Options, [riakc, get_cs_buckets_by_index]) of {ok, ?INDEX_RESULTS{keys=BucketNames, continuation=Cont}} -> Foldfun = iterate_csbuckets_fold_fun(Fun), Acc2 = lists:foldl(Foldfun, Acc0, BucketNames), case Cont of undefined -> {ok, Acc2}; _ -> iterate_csbuckets(RcPid, Acc2, Fun, Cont) end; Error -> _ = lager:error("iterating CS buckets: ~p", [Error]), {error, {Error, Acc0}} end. iterate_csbuckets_fold_fun(FunForOneBucket) -> fun(BucketName, Acc) -> {ok, RcPidForOneBucket} = riak_cs_riak_client:start_link([]), try BucketRes = riak_cs_riak_client:get_bucket(RcPidForOneBucket, BucketName), FunForOneBucket(RcPidForOneBucket, BucketName, BucketRes, Acc) after riak_cs_riak_client:stop(RcPidForOneBucket) end end. %% @doc Return a user's buckets. -spec get_buckets(rcs_user()) -> [cs_bucket()]. get_buckets(?RCS_USER{buckets=Buckets}) -> [Bucket || Bucket <- Buckets, Bucket?RCS_BUCKET.last_action /= deleted]. @doc Set the ACL for a bucket . Existing ACLs are only %% replaced, they cannot be updated. -spec set_bucket_acl(rcs_user(), riakc_obj:riakc_obj(), binary(), acl(), riak_client()) -> ok | {error, term()}. set_bucket_acl(User, UserObj, Bucket, ACL, RcPid) -> serialized_bucket_op(Bucket, ACL, User, UserObj, update_acl, [velvet, set_bucket_acl], RcPid). %% @doc Set the policy for a bucket. Existing policy is only overwritten. -spec set_bucket_policy(rcs_user(), riakc_obj:riakc_obj(), binary(), []|policy()|acl(), riak_client()) -> ok | {error, term()}. set_bucket_policy(User, UserObj, Bucket, PolicyJson, RcPid) -> serialized_bucket_op(Bucket, PolicyJson, User, UserObj, update_policy, [velvet, set_bucket_policy], RcPid). %% @doc Set the policy for a bucket. Existing policy is only overwritten. -spec delete_bucket_policy(rcs_user(), riakc_obj:riakc_obj(), binary(), riak_client()) -> ok | {error, term()}. delete_bucket_policy(User, UserObj, Bucket, RcPid) -> serialized_bucket_op(Bucket, [], User, UserObj, delete_policy, [velvet, delete_bucket_policy], RcPid). %% @doc fetch moss.bucket and return acl and policy -spec get_bucket_acl_policy(binary(), atom(), riak_client()) -> {acl(), policy()} | {error, term()}. get_bucket_acl_policy(Bucket, PolicyMod, RcPid) -> case fetch_bucket_object(Bucket, RcPid) of {ok, Obj} -> %% For buckets there should not be siblings, but in rare %% cases it may happen so check for them and attempt to %% resolve if possible. Contents = riakc_obj:get_contents(Obj), Acl = riak_cs_acl:bucket_acl_from_contents(Bucket, Contents), Policy = PolicyMod:bucket_policy_from_contents(Bucket, Contents), format_acl_policy_response(Acl, Policy); {error, _}=Error -> Error end. -type policy_from_meta_result() :: {'ok', policy()} | {'error', 'policy_undefined'}. -type bucket_policy_result() :: policy_from_meta_result() | {'error', 'multiple_bucket_owners'}. -type acl_from_meta_result() :: {'ok', acl()} | {'error', 'acl_undefined'}. -type bucket_acl_result() :: acl_from_meta_result() | {'error', 'multiple_bucket_owners'}. -spec format_acl_policy_response(bucket_acl_result(), bucket_policy_result()) -> {error, atom()} | {acl(), 'undefined' | policy()}. format_acl_policy_response({error, _}=Error, _) -> Error; format_acl_policy_response(_, {error, multiple_bucket_owners}=Error) -> Error; format_acl_policy_response({ok, Acl}, {error, policy_undefined}) -> {Acl, undefined}; format_acl_policy_response({ok, Acl}, {ok, Policy}) -> {Acl, Policy}. %% =================================================================== Internal functions %% =================================================================== %% @doc Generate a JSON document to use for a bucket ACL request . -spec bucket_acl_json(acl(), string()) -> string(). bucket_acl_json(ACL, KeyId) -> binary_to_list( iolist_to_binary( mochijson2:encode({struct, [{<<"requester">>, list_to_binary(KeyId)}, riak_cs_acl_utils:acl_to_json_term(ACL)]}))). %% @doc Generate a JSON document to use for a bucket -spec bucket_policy_json(binary(), string()) -> string(). bucket_policy_json(PolicyJson, KeyId) -> binary_to_list( iolist_to_binary( mochijson2:encode({struct, [{<<"requester">>, list_to_binary(KeyId)}, {<<"policy">>, PolicyJson}] }))). %% @doc Check if a bucket is empty -spec bucket_empty(binary(), riak_client()) -> {ok, boolean()} | {error, term()}. bucket_empty(Bucket, RcPid) -> ManifestBucket = riak_cs_utils:to_bucket_name(objects, Bucket), @TODO Use ` stream_list_keys ' instead {ok, ManifestPbc} = riak_cs_riak_client:manifest_pbc(RcPid), Timeout = riak_cs_config:list_keys_list_objects_timeout(), ListKeysResult = riak_cs_pbc:list_keys(ManifestPbc, ManifestBucket, Timeout, [riakc, list_all_manifest_keys]), {ok, bucket_empty_handle_list_keys(RcPid, Bucket, ListKeysResult)}. -spec bucket_empty_handle_list_keys(riak_client(), binary(), {ok, list()} | {error, term()}) -> boolean(). bucket_empty_handle_list_keys(RcPid, Bucket, {ok, Keys}) -> AnyPred = bucket_empty_any_pred(RcPid, Bucket), %% `lists:any/2' will break out early as soon %% as something returns `true' not lists:any(AnyPred, Keys); bucket_empty_handle_list_keys(_RcPid, _Bucket, _Error) -> false. -spec bucket_empty_any_pred(riak_client(), Bucket :: binary()) -> fun((Key :: binary()) -> boolean()). bucket_empty_any_pred(RcPid, Bucket) -> fun (Key) -> riak_cs_utils:key_exists(RcPid, Bucket, Key) end. %% @doc Fetches the bucket object and verify its status. -spec fetch_bucket_object(binary(), riak_client()) -> {ok, riakc_obj:riakc_obj()} | {error, term()}. fetch_bucket_object(BucketName, RcPid) -> case fetch_bucket_object_raw(BucketName, RcPid) of {ok, Obj} -> [Value | _] = riakc_obj:get_values(Obj), case Value of ?FREE_BUCKET_MARKER -> {error, no_such_bucket}; _ -> {ok, Obj} end; {error, _}=Error -> Error end. %% @doc Fetches the bucket object, even it is marked as free -spec fetch_bucket_object_raw(binary(), riak_client()) -> {ok, riakc_obj:riakc_obj()} | {error, term()}. fetch_bucket_object_raw(BucketName, RcPid) -> case riak_cs_riak_client:get_bucket(RcPid, BucketName) of {ok, Obj} -> Values = riakc_obj:get_values(Obj), maybe_log_sibling_warning(BucketName, Values), {ok, Obj}; {error, _}=Error -> Error end. -spec maybe_log_sibling_warning(binary(), list(riakc_obj:value())) -> ok. maybe_log_sibling_warning(Bucket, Values) when length(Values) > 1 -> _ = lager:warning("The bucket ~s has ~b siblings that may need resolution.", [binary_to_list(Bucket), length(Values)]), ok; maybe_log_sibling_warning(_, _) -> ok. -spec maybe_log_bucket_owner_error(binary(), list(riakc_obj:value())) -> ok. maybe_log_bucket_owner_error(Bucket, Values) when length(Values) > 1 -> _ = lager:error("The bucket ~s has ~b owners." " This situation requires administrator intervention.", [binary_to_list(Bucket), length(Values)]), ok; maybe_log_bucket_owner_error(_, _) -> ok. %% @doc Check if a bucket exists in a list of the user's buckets. @TODO This will need to change once globally unique buckets %% are enforced. -spec bucket_exists([cs_bucket()], string()) -> boolean(). bucket_exists(Buckets, CheckBucket) -> SearchResults = [Bucket || Bucket <- Buckets, Bucket?RCS_BUCKET.name =:= CheckBucket andalso Bucket?RCS_BUCKET.last_action =:= created], case SearchResults of [] -> false; _ -> true end. %% @doc Return a closure over a specific function %% call to the stanchion client module for either %% bucket creation or deletion. -spec bucket_fun(bucket_operation(), binary(), bag_id(), [] | policy() | acl(), string(), {string(), string()}, {string(), pos_integer(), boolean()}) -> function(). bucket_fun(create, Bucket, BagId, ACL, KeyId, AdminCreds, StanchionData) -> {StanchionIp, StanchionPort, StanchionSSL} = StanchionData, %% Generate the bucket JSON document BucketDoc = bucket_json(Bucket, BagId, ACL, KeyId), fun() -> velvet:create_bucket(StanchionIp, StanchionPort, "application/json", BucketDoc, [{ssl, StanchionSSL}, {auth_creds, AdminCreds}]) end; bucket_fun(update_acl, Bucket, _BagId, ACL, KeyId, AdminCreds, StanchionData) -> {StanchionIp, StanchionPort, StanchionSSL} = StanchionData, Generate the bucket JSON document for the ACL request AclDoc = bucket_acl_json(ACL, KeyId), fun() -> velvet:set_bucket_acl(StanchionIp, StanchionPort, Bucket, "application/json", AclDoc, [{ssl, StanchionSSL}, {auth_creds, AdminCreds}]) end; bucket_fun(update_policy, Bucket, _BagId, PolicyJson, KeyId, AdminCreds, StanchionData) -> {StanchionIp, StanchionPort, StanchionSSL} = StanchionData, Generate the bucket JSON document for the ACL request PolicyDoc = bucket_policy_json(PolicyJson, KeyId), fun() -> velvet:set_bucket_policy(StanchionIp, StanchionPort, Bucket, "application/json", PolicyDoc, [{ssl, StanchionSSL}, {auth_creds, AdminCreds}]) end; bucket_fun(delete_policy, Bucket, _BagId, _, KeyId, AdminCreds, StanchionData) -> {StanchionIp, StanchionPort, StanchionSSL} = StanchionData, Generate the bucket JSON document for the ACL request fun() -> velvet:delete_bucket_policy(StanchionIp, StanchionPort, Bucket, KeyId, [{ssl, StanchionSSL}, {auth_creds, AdminCreds}]) end; bucket_fun(delete, Bucket, _BagId, _ACL, KeyId, AdminCreds, StanchionData) -> {StanchionIp, StanchionPort, StanchionSSL} = StanchionData, fun() -> velvet:delete_bucket(StanchionIp, StanchionPort, Bucket, KeyId, [{ssl, StanchionSSL}, {auth_creds, AdminCreds}]) end. %% @doc Generate a JSON document to use for a bucket %% creation request. -spec bucket_json(binary(), bag_id(), acl(), string()) -> string(). bucket_json(Bucket, BagId, ACL, KeyId) -> BagElement = case BagId of undefined -> []; _ -> [{<<"bag">>, BagId}] end, binary_to_list( iolist_to_binary( mochijson2:encode({struct, [{<<"bucket">>, Bucket}, {<<"requester">>, list_to_binary(KeyId)}, riak_cs_acl_utils:acl_to_json_term(ACL)] ++ BagElement}))). %% @doc Return a bucket record for the specified bucket name. -spec bucket_record(binary(), bucket_operation()) -> cs_bucket(). bucket_record(Name, Operation) -> Action = case Operation of create -> created; delete -> deleted; _ -> undefined end, ?RCS_BUCKET{name=binary_to_list(Name), last_action=Action, creation_date=riak_cs_wm_utils:iso_8601_datetime(), modification_time=os:timestamp()}. %% @doc Check for and resolve any conflict between %% a bucket record from a user record sibling and %% a list of resolved bucket records. -spec bucket_resolver(cs_bucket(), [cs_bucket()]) -> [cs_bucket()]. bucket_resolver(Bucket, ResolvedBuckets) -> case lists:member(Bucket, ResolvedBuckets) of true -> ResolvedBuckets; false -> case [RB || RB <- ResolvedBuckets, RB?RCS_BUCKET.name =:= Bucket?RCS_BUCKET.name] of [] -> [Bucket | ResolvedBuckets]; [ExistingBucket] -> case keep_existing_bucket(ExistingBucket, Bucket) of true -> ResolvedBuckets; false -> [Bucket | lists:delete(ExistingBucket, ResolvedBuckets)] end end end. %% @doc Ordering function for sorting a list of bucket records %% according to bucket name. -spec bucket_sorter(cs_bucket(), cs_bucket()) -> boolean(). bucket_sorter(?RCS_BUCKET{name=Bucket1}, ?RCS_BUCKET{name=Bucket2}) -> Bucket1 =< Bucket2. %% @doc Return true if the last action for the bucket %% is deleted and the action occurred over the configurable %% maximum prune-time. -spec cleanup_bucket(cs_bucket()) -> boolean(). cleanup_bucket(?RCS_BUCKET{last_action=created}) -> false; cleanup_bucket(?RCS_BUCKET{last_action=deleted, modification_time=ModTime}) -> the prune - time is specified in seconds , so we must convert Erlang timestamps to seconds first NowSeconds = riak_cs_utils:second_resolution_timestamp(os:timestamp()), ModTimeSeconds = riak_cs_utils:second_resolution_timestamp(ModTime), (NowSeconds - ModTimeSeconds) > riak_cs_config:user_buckets_prune_time(). %% @doc Determine if an existing bucket from the resolution list %% should be kept or replaced when a conflict occurs. -spec keep_existing_bucket(cs_bucket(), cs_bucket()) -> boolean(). keep_existing_bucket(?RCS_BUCKET{last_action=LastAction1, modification_time=ModTime1}, ?RCS_BUCKET{last_action=LastAction2, modification_time=ModTime2}) -> if LastAction1 == LastAction2 andalso ModTime1 =< ModTime2 -> true; LastAction1 == LastAction2 -> false; ModTime1 > ModTime2 -> true; true -> false end. %% @doc Resolve the set of buckets for a user when %% siblings are encountered on a read of a user record. -spec resolve_buckets([rcs_user()], [cs_bucket()], boolean()) -> [cs_bucket()]. resolve_buckets([], Buckets, true) -> lists:sort(fun bucket_sorter/2, Buckets); resolve_buckets([], Buckets, false) -> lists:sort(fun bucket_sorter/2, [Bucket || Bucket <- Buckets, not cleanup_bucket(Bucket)]); resolve_buckets([HeadUserRec | RestUserRecs], [], KeepDeletedBuckets) -> %% We can assume there are no bucket duplication under a single %% user record. It's already resolved. This function works %% without this head, but this head makes it very effecient in case of thousands of bucket records under single user . resolve_buckets(RestUserRecs, HeadUserRec?RCS_USER.buckets, KeepDeletedBuckets); resolve_buckets([HeadUserRec | RestUserRecs], Buckets, _KeepDeleted) -> HeadBuckets = HeadUserRec?RCS_USER.buckets, UpdBuckets = lists:foldl(fun bucket_resolver/2, Buckets, HeadBuckets), resolve_buckets(RestUserRecs, UpdBuckets, _KeepDeleted). %% @doc Shared code used when doing a bucket creation or deletion. -spec serialized_bucket_op(binary(), [] | acl() | policy(), rcs_user(), riakc_obj:riakc_obj(), bucket_operation(), riak_cs_stats:key(), riak_client()) -> ok | {error, term()}. serialized_bucket_op(Bucket, ACL, User, UserObj, BucketOp, StatKey, RcPid) -> serialized_bucket_op(Bucket, undefined, ACL, User, UserObj, BucketOp, StatKey, RcPid). %% @doc Shared code used when doing a bucket creation or deletion. -spec serialized_bucket_op(binary(), bag_id(), [] | acl() | policy(), rcs_user(), riakc_obj:riakc_obj(), bucket_operation(), riak_cs_stats:key(), riak_client()) -> ok | {error, term()}. serialized_bucket_op(Bucket, BagId, ACL, User, UserObj, BucketOp, StatsKey, RcPid) -> StartTime = os:timestamp(), _ = riak_cs_stats:inflow(StatsKey), {ok, AdminCreds} = riak_cs_config:admin_creds(), BucketFun = bucket_fun(BucketOp, Bucket, BagId, ACL, User?RCS_USER.key_id, AdminCreds, riak_cs_utils:stanchion_data()), %% Make a call to the request serialization service. OpResult = BucketFun(), _ = riak_cs_stats:update_with_start(StatsKey, StartTime, OpResult), case OpResult of ok -> BucketRecord = bucket_record(Bucket, BucketOp), case update_user_buckets(User, BucketRecord) of {ok, ignore} when BucketOp == update_acl -> OpResult; {ok, ignore} -> OpResult; {ok, UpdUser} -> riak_cs_user:save_user(UpdUser, UserObj, RcPid) end; {error, {error_status, Status, _, ErrorDoc}} -> handle_stanchion_response(Status, ErrorDoc, BucketOp, Bucket); {error, _} -> OpResult end. @doc needs retry for delete op . 409 assumes %% MultipartUploadRemaining for now if a new feature that needs retry %% could come up, add branch here. See tests in %% tests/riak_cs_bucket_test.erl -spec handle_stanchion_response(200..503, string(), delete|create, binary()) -> {error, remaining_multipart_upload} | {error, atom()}. handle_stanchion_response(409, ErrorDoc, Op, Bucket) when Op =:= delete orelse Op =:= create -> Value = riak_cs_s3_response:xml_error_code(ErrorDoc), case {lists:flatten(Value), Op} of {"MultipartUploadRemaining", delete} -> _ = lager:error("Concurrent multipart upload might have" " happened on deleting bucket '~s'.", [Bucket]), {error, remaining_multipart_upload}; {"MultipartUploadRemaining", create} -> %% might be security issue _ = lager:critical("Multipart upload remains in deleted bucket (~s)" " Clean up the deleted buckets now.", [Bucket]), Broken , returns 500 throw({remaining_multipart_upload_on_deleted_bucket, Bucket}); Other -> _ = lager:debug("errordoc: ~p => ~s", [Other, ErrorDoc]), riak_cs_s3_response:error_response(ErrorDoc) end; handle_stanchion_response(_C, ErrorDoc, _M, _) -> %% _ = lager:error("unexpected errordoc: (~p, ~p) ~s", [_C, _M, ErrorDoc]), riak_cs_s3_response:error_response(ErrorDoc). %% @doc Update a bucket record to convert the name from binary %% to string if necessary. -spec update_bucket_record(term()) -> cs_bucket(). update_bucket_record(Bucket=?RCS_BUCKET{name=Name}) when is_binary(Name) -> Bucket?RCS_BUCKET{name=binary_to_list(Name)}; update_bucket_record(Bucket) -> Bucket. %% @doc Check if a user already has an ownership of %% a bucket and update the bucket list if needed. -spec update_user_buckets(rcs_user(), cs_bucket()) -> {ok, ignore} | {ok, rcs_user()}. update_user_buckets(User, Bucket) -> Buckets = User?RCS_USER.buckets, %% At this point any siblings from the read of the %% user record have been resolved so the user bucket list should have 0 or 1 buckets that share a name %% with `Bucket'. case [B || B <- Buckets, B?RCS_BUCKET.name =:= Bucket?RCS_BUCKET.name] of [] -> {ok, User?RCS_USER{buckets=[Bucket | Buckets]}}; [ExistingBucket] -> case (Bucket?RCS_BUCKET.last_action == deleted andalso ExistingBucket?RCS_BUCKET.last_action == created) orelse (Bucket?RCS_BUCKET.last_action == created andalso ExistingBucket?RCS_BUCKET.last_action == deleted) of true -> UpdBuckets = [Bucket | lists:delete(ExistingBucket, Buckets)], {ok, User?RCS_USER{buckets=UpdBuckets}}; false -> {ok, ignore} end end. @doc Grab the whole list of Riak CS bucket keys . -spec fetch_bucket_keys(riak_client()) -> {ok, [binary()]} | {error, term()}. fetch_bucket_keys(RcPid) -> {ok, MasterPbc} = riak_cs_riak_client:master_pbc(RcPid), Timeout = riak_cs_config:list_keys_list_buckets_timeout(), riak_cs_pbc:list_keys(MasterPbc, ?BUCKETS_BUCKET, Timeout, [riakc, list_all_bucket_keys]).
null
https://raw.githubusercontent.com/basho/riak_cs/c0c1012d1c9c691c74c8c5d9f69d388f5047bcd2/src/riak_cs_bucket.erl
erlang
--------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------------------------------------------------------------------- @doc riak_cs bucket utility functions, but I dare not use a module name with '_utils'. Public API =================================================================== Public API =================================================================== @doc Create a bucket in the global namespace or return an error if it already exists. Do not attempt to create bucket if the user already owns it last byte. Or if it appears twice in a row. Examples are: `<<".myawsbucket">>' `<<"myawsbucket.">>' `<<"my..examplebucket">>' @doc Delete a bucket Buckets can only be deleted if they exist TODO: output log if failed in cleaning up existing uploads. The number of retry is hardcoded. This call still may return {error, remaining_multipart_upload} even if all uploads cleaned up above, because concurrent which is not in S3 specification.... @doc TODO: this function is to be moved to riak_cs_multipart_utils or else? @doc deletes all multipart uploads older than Timestamp. input binary format of iso8068 cannot fail here find_manifest_with_uploadid comparing timestamp here, like @doc Return a user's buckets. replaced, they cannot be updated. @doc Set the policy for a bucket. Existing policy is only overwritten. @doc Set the policy for a bucket. Existing policy is only overwritten. @doc fetch moss.bucket and return acl and policy For buckets there should not be siblings, but in rare cases it may happen so check for them and attempt to resolve if possible. =================================================================== =================================================================== @doc Generate a JSON document to use for a bucket @doc Generate a JSON document to use for a bucket @doc Check if a bucket is empty `lists:any/2' will break out early as soon as something returns `true' @doc Fetches the bucket object and verify its status. @doc Fetches the bucket object, even it is marked as free @doc Check if a bucket exists in a list of the user's buckets. are enforced. @doc Return a closure over a specific function call to the stanchion client module for either bucket creation or deletion. Generate the bucket JSON document @doc Generate a JSON document to use for a bucket creation request. @doc Return a bucket record for the specified bucket name. @doc Check for and resolve any conflict between a bucket record from a user record sibling and a list of resolved bucket records. @doc Ordering function for sorting a list of bucket records according to bucket name. @doc Return true if the last action for the bucket is deleted and the action occurred over the configurable maximum prune-time. @doc Determine if an existing bucket from the resolution list should be kept or replaced when a conflict occurs. @doc Resolve the set of buckets for a user when siblings are encountered on a read of a user record. We can assume there are no bucket duplication under a single user record. It's already resolved. This function works without this head, but this head makes it very effecient in @doc Shared code used when doing a bucket creation or deletion. @doc Shared code used when doing a bucket creation or deletion. Make a call to the request serialization service. MultipartUploadRemaining for now if a new feature that needs retry could come up, add branch here. See tests in tests/riak_cs_bucket_test.erl might be security issue _ = lager:error("unexpected errordoc: (~p, ~p) ~s", [_C, _M, ErrorDoc]), @doc Update a bucket record to convert the name from binary to string if necessary. @doc Check if a user already has an ownership of a bucket and update the bucket list if needed. At this point any siblings from the read of the user record have been resolved so the user bucket with `Bucket'.
Copyright ( c ) 2007 - 2014 Basho Technologies , Inc. All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(riak_cs_bucket). -export([ fetch_bucket_object/2, create_bucket/6, delete_bucket/4, get_buckets/1, set_bucket_acl/5, set_bucket_policy/5, delete_bucket_policy/4, get_bucket_acl_policy/3, maybe_log_bucket_owner_error/2, resolve_buckets/3, update_bucket_record/1, delete_all_uploads/2, delete_old_uploads/3, fold_all_buckets/3, fetch_bucket_keys/1 ]). -include("riak_cs.hrl"). -include_lib("riak_pb/include/riak_pb_kv_codec.hrl"). -include_lib("riakc/include/riakc.hrl"). -ifdef(TEST). -compile(export_all). -include_lib("eunit/include/eunit.hrl"). -endif. -spec create_bucket(rcs_user(), term(), binary(), bag_id(), acl(), riak_client()) -> ok | {error, term()}. create_bucket(User, UserObj, Bucket, BagId, ACL, RcPid) -> CurrentBuckets = get_buckets(User), AttemptCreate = riak_cs_config:disable_local_bucket_check() orelse not bucket_exists(CurrentBuckets, binary_to_list(Bucket)), case AttemptCreate of true -> BucketLimit = riak_cs_config:max_buckets_per_user(), case valid_bucket_name(Bucket) of true when length(CurrentBuckets) >= BucketLimit -> {error, {toomanybuckets, length(CurrentBuckets), BucketLimit}}; true -> serialized_bucket_op(Bucket, BagId, ACL, User, UserObj, create, [velvet, create_bucket], RcPid); false -> {error, invalid_bucket_name} end; false -> ok end. -spec valid_bucket_name(binary()) -> boolean(). valid_bucket_name(Bucket) when byte_size(Bucket) < 3 orelse byte_size(Bucket) > 63 -> false; valid_bucket_name(Bucket) -> lists:all(fun(X) -> X end, [valid_bucket_label(Label) || Label <- binary:split(Bucket, <<".">>, [global])]) andalso not is_bucket_ip_addr(binary_to_list(Bucket)). -spec valid_bucket_label(binary()) -> boolean(). valid_bucket_label(<<>>) -> this clause gets called when we either have a ` . ' as the first or false; valid_bucket_label(Label) -> valid_bookend_char(binary:first(Label)) andalso valid_bookend_char(binary:last(Label)) andalso lists:all(fun(X) -> X end, [valid_bucket_char(C) || C <- middle_chars(Label)]). -spec middle_chars(binary()) -> list(). middle_chars(B) when byte_size(B) < 3 -> []; middle_chars(B) -> ` binary : at/2 ' is zero based ByteSize = byte_size(B), [binary:at(B, Position) || Position <- lists:seq(1, ByteSize - 2)]. -spec is_bucket_ip_addr(string()) -> boolean(). is_bucket_ip_addr(Bucket) -> case inet_parse:ipv4strict_address(Bucket) of {ok, _} -> true; {error, _} -> false end. -spec valid_bookend_char(integer()) -> boolean(). valid_bookend_char(Char) -> numeric_char(Char) orelse lower_case_char(Char). -spec valid_bucket_char(integer()) -> boolean(). valid_bucket_char(Char) -> numeric_char(Char) orelse lower_case_char(Char) orelse dash_char(Char). -spec numeric_char(integer()) -> boolean(). numeric_char(Char) -> Char >= $0 andalso Char =< $9. -spec lower_case_char(integer()) -> boolean(). lower_case_char(Char) -> Char >= $a andalso Char =< $z. -spec dash_char(integer()) -> boolean(). dash_char(Char) -> Char =:= $-. -spec delete_bucket(rcs_user(), riakc_obj:riakc_obj(), binary(), riak_client()) -> ok | {error, remaining_multipart_upload}. delete_bucket(User, UserObj, Bucket, RcPid) -> CurrentBuckets = get_buckets(User), {AttemptDelete, LocalError} = case bucket_exists(CurrentBuckets, binary_to_list(Bucket)) of true -> case bucket_empty(Bucket, RcPid) of {ok, true} -> {true, ok}; {ok, false} -> {false, {error, bucket_not_empty}} end; false -> {true, ok} end, case AttemptDelete of true -> {ok, Count} = delete_all_uploads(Bucket, RcPid), _ = lager:debug("deleted ~p multiparts before bucket deletion.", [Count]), multiple deletion may happen . Then returns 409 confliction serialized_bucket_op(Bucket, ?ACL{}, User, UserObj, delete, [velvet, delete_bucket], RcPid); false -> LocalError end. -spec delete_all_uploads(binary(), riak_client()) -> {ok, non_neg_integer()} | {error, term()}. delete_all_uploads(Bucket, RcPid) -> delete_old_uploads(Bucket, RcPid, <<255>>). -spec delete_old_uploads(binary(), riak_client(), binary()) -> {ok, non_neg_integer()} | {error, term()}. delete_old_uploads(Bucket, RcPid, Timestamp) when is_binary(Timestamp) -> Opts = [{delimiter, undefined}, {max_uploads, undefined}, {prefix, undefined}, {key_marker, <<>>}, {upload_id_marker, <<>>}], {ok, {Ds, _Commons}} = riak_cs_mp_utils:list_all_multipart_uploads(Bucket, Opts, RcPid), fold_delete_uploads(Bucket, RcPid, Ds, Timestamp, 0). fold_delete_uploads(_Bucket, _RcPid, [], _Timestamp, Count) -> {ok, Count}; fold_delete_uploads(Bucket, RcPid, [D|Ds], Timestamp, Count)-> Key = D?MULTIPART_DESCR.key, {ok, Obj, Manifests} = riak_cs_manifest:get_manifests(RcPid, Bucket, Key), UploadId = D?MULTIPART_DESCR.upload_id, case lists:keyfind(UploadId, 1, Manifests) of {UploadId, M} when M?MANIFEST.state == writing < < " 2012 - 02 - 17T18:22:50.000Z " > > < < < " 2014 - 05 - 11- .... " > > = > true andalso M?MANIFEST.created < Timestamp -> case riak_cs_gc:gc_specific_manifests( [M?MANIFEST.uuid], Obj, Bucket, Key, RcPid) of {ok, _NewObj} -> fold_delete_uploads(Bucket, RcPid, Ds, Timestamp, Count+1); E -> lager:debug("cannot delete multipart manifest: ~p ~p (~p)", [{Bucket, Key}, M?MANIFEST.uuid, E]), E end; _E -> lager:debug("skipping multipart manifest: ~p ~p (~p)", [{Bucket, Key}, UploadId, _E]), fold_delete_uploads(Bucket, RcPid, Ds, Timestamp, Count) end. -spec fold_all_buckets(fun(), term(), riak_client()) -> {ok, term()} | {error, any()}. fold_all_buckets(Fun, Acc0, RcPid) when is_function(Fun) -> iterate_csbuckets(RcPid, Acc0, Fun, undefined). -spec iterate_csbuckets(riak_client(), term(), fun(), binary()|undefined) -> {ok, term()} | {error, any()}. iterate_csbuckets(RcPid, Acc0, Fun, Cont0) -> Options = case Cont0 of undefined -> []; _ -> [{continuation, Cont0}] end ++ [{max_results, 1024}], {ok, MasterPbc} = riak_cs_riak_client:master_pbc(RcPid), case riak_cs_pbc:get_index_range(MasterPbc, ?BUCKETS_BUCKET, <<"$key">>, <<0>>, <<255>>, Options, [riakc, get_cs_buckets_by_index]) of {ok, ?INDEX_RESULTS{keys=BucketNames, continuation=Cont}} -> Foldfun = iterate_csbuckets_fold_fun(Fun), Acc2 = lists:foldl(Foldfun, Acc0, BucketNames), case Cont of undefined -> {ok, Acc2}; _ -> iterate_csbuckets(RcPid, Acc2, Fun, Cont) end; Error -> _ = lager:error("iterating CS buckets: ~p", [Error]), {error, {Error, Acc0}} end. iterate_csbuckets_fold_fun(FunForOneBucket) -> fun(BucketName, Acc) -> {ok, RcPidForOneBucket} = riak_cs_riak_client:start_link([]), try BucketRes = riak_cs_riak_client:get_bucket(RcPidForOneBucket, BucketName), FunForOneBucket(RcPidForOneBucket, BucketName, BucketRes, Acc) after riak_cs_riak_client:stop(RcPidForOneBucket) end end. -spec get_buckets(rcs_user()) -> [cs_bucket()]. get_buckets(?RCS_USER{buckets=Buckets}) -> [Bucket || Bucket <- Buckets, Bucket?RCS_BUCKET.last_action /= deleted]. @doc Set the ACL for a bucket . Existing ACLs are only -spec set_bucket_acl(rcs_user(), riakc_obj:riakc_obj(), binary(), acl(), riak_client()) -> ok | {error, term()}. set_bucket_acl(User, UserObj, Bucket, ACL, RcPid) -> serialized_bucket_op(Bucket, ACL, User, UserObj, update_acl, [velvet, set_bucket_acl], RcPid). -spec set_bucket_policy(rcs_user(), riakc_obj:riakc_obj(), binary(), []|policy()|acl(), riak_client()) -> ok | {error, term()}. set_bucket_policy(User, UserObj, Bucket, PolicyJson, RcPid) -> serialized_bucket_op(Bucket, PolicyJson, User, UserObj, update_policy, [velvet, set_bucket_policy], RcPid). -spec delete_bucket_policy(rcs_user(), riakc_obj:riakc_obj(), binary(), riak_client()) -> ok | {error, term()}. delete_bucket_policy(User, UserObj, Bucket, RcPid) -> serialized_bucket_op(Bucket, [], User, UserObj, delete_policy, [velvet, delete_bucket_policy], RcPid). -spec get_bucket_acl_policy(binary(), atom(), riak_client()) -> {acl(), policy()} | {error, term()}. get_bucket_acl_policy(Bucket, PolicyMod, RcPid) -> case fetch_bucket_object(Bucket, RcPid) of {ok, Obj} -> Contents = riakc_obj:get_contents(Obj), Acl = riak_cs_acl:bucket_acl_from_contents(Bucket, Contents), Policy = PolicyMod:bucket_policy_from_contents(Bucket, Contents), format_acl_policy_response(Acl, Policy); {error, _}=Error -> Error end. -type policy_from_meta_result() :: {'ok', policy()} | {'error', 'policy_undefined'}. -type bucket_policy_result() :: policy_from_meta_result() | {'error', 'multiple_bucket_owners'}. -type acl_from_meta_result() :: {'ok', acl()} | {'error', 'acl_undefined'}. -type bucket_acl_result() :: acl_from_meta_result() | {'error', 'multiple_bucket_owners'}. -spec format_acl_policy_response(bucket_acl_result(), bucket_policy_result()) -> {error, atom()} | {acl(), 'undefined' | policy()}. format_acl_policy_response({error, _}=Error, _) -> Error; format_acl_policy_response(_, {error, multiple_bucket_owners}=Error) -> Error; format_acl_policy_response({ok, Acl}, {error, policy_undefined}) -> {Acl, undefined}; format_acl_policy_response({ok, Acl}, {ok, Policy}) -> {Acl, Policy}. Internal functions ACL request . -spec bucket_acl_json(acl(), string()) -> string(). bucket_acl_json(ACL, KeyId) -> binary_to_list( iolist_to_binary( mochijson2:encode({struct, [{<<"requester">>, list_to_binary(KeyId)}, riak_cs_acl_utils:acl_to_json_term(ACL)]}))). -spec bucket_policy_json(binary(), string()) -> string(). bucket_policy_json(PolicyJson, KeyId) -> binary_to_list( iolist_to_binary( mochijson2:encode({struct, [{<<"requester">>, list_to_binary(KeyId)}, {<<"policy">>, PolicyJson}] }))). -spec bucket_empty(binary(), riak_client()) -> {ok, boolean()} | {error, term()}. bucket_empty(Bucket, RcPid) -> ManifestBucket = riak_cs_utils:to_bucket_name(objects, Bucket), @TODO Use ` stream_list_keys ' instead {ok, ManifestPbc} = riak_cs_riak_client:manifest_pbc(RcPid), Timeout = riak_cs_config:list_keys_list_objects_timeout(), ListKeysResult = riak_cs_pbc:list_keys(ManifestPbc, ManifestBucket, Timeout, [riakc, list_all_manifest_keys]), {ok, bucket_empty_handle_list_keys(RcPid, Bucket, ListKeysResult)}. -spec bucket_empty_handle_list_keys(riak_client(), binary(), {ok, list()} | {error, term()}) -> boolean(). bucket_empty_handle_list_keys(RcPid, Bucket, {ok, Keys}) -> AnyPred = bucket_empty_any_pred(RcPid, Bucket), not lists:any(AnyPred, Keys); bucket_empty_handle_list_keys(_RcPid, _Bucket, _Error) -> false. -spec bucket_empty_any_pred(riak_client(), Bucket :: binary()) -> fun((Key :: binary()) -> boolean()). bucket_empty_any_pred(RcPid, Bucket) -> fun (Key) -> riak_cs_utils:key_exists(RcPid, Bucket, Key) end. -spec fetch_bucket_object(binary(), riak_client()) -> {ok, riakc_obj:riakc_obj()} | {error, term()}. fetch_bucket_object(BucketName, RcPid) -> case fetch_bucket_object_raw(BucketName, RcPid) of {ok, Obj} -> [Value | _] = riakc_obj:get_values(Obj), case Value of ?FREE_BUCKET_MARKER -> {error, no_such_bucket}; _ -> {ok, Obj} end; {error, _}=Error -> Error end. -spec fetch_bucket_object_raw(binary(), riak_client()) -> {ok, riakc_obj:riakc_obj()} | {error, term()}. fetch_bucket_object_raw(BucketName, RcPid) -> case riak_cs_riak_client:get_bucket(RcPid, BucketName) of {ok, Obj} -> Values = riakc_obj:get_values(Obj), maybe_log_sibling_warning(BucketName, Values), {ok, Obj}; {error, _}=Error -> Error end. -spec maybe_log_sibling_warning(binary(), list(riakc_obj:value())) -> ok. maybe_log_sibling_warning(Bucket, Values) when length(Values) > 1 -> _ = lager:warning("The bucket ~s has ~b siblings that may need resolution.", [binary_to_list(Bucket), length(Values)]), ok; maybe_log_sibling_warning(_, _) -> ok. -spec maybe_log_bucket_owner_error(binary(), list(riakc_obj:value())) -> ok. maybe_log_bucket_owner_error(Bucket, Values) when length(Values) > 1 -> _ = lager:error("The bucket ~s has ~b owners." " This situation requires administrator intervention.", [binary_to_list(Bucket), length(Values)]), ok; maybe_log_bucket_owner_error(_, _) -> ok. @TODO This will need to change once globally unique buckets -spec bucket_exists([cs_bucket()], string()) -> boolean(). bucket_exists(Buckets, CheckBucket) -> SearchResults = [Bucket || Bucket <- Buckets, Bucket?RCS_BUCKET.name =:= CheckBucket andalso Bucket?RCS_BUCKET.last_action =:= created], case SearchResults of [] -> false; _ -> true end. -spec bucket_fun(bucket_operation(), binary(), bag_id(), [] | policy() | acl(), string(), {string(), string()}, {string(), pos_integer(), boolean()}) -> function(). bucket_fun(create, Bucket, BagId, ACL, KeyId, AdminCreds, StanchionData) -> {StanchionIp, StanchionPort, StanchionSSL} = StanchionData, BucketDoc = bucket_json(Bucket, BagId, ACL, KeyId), fun() -> velvet:create_bucket(StanchionIp, StanchionPort, "application/json", BucketDoc, [{ssl, StanchionSSL}, {auth_creds, AdminCreds}]) end; bucket_fun(update_acl, Bucket, _BagId, ACL, KeyId, AdminCreds, StanchionData) -> {StanchionIp, StanchionPort, StanchionSSL} = StanchionData, Generate the bucket JSON document for the ACL request AclDoc = bucket_acl_json(ACL, KeyId), fun() -> velvet:set_bucket_acl(StanchionIp, StanchionPort, Bucket, "application/json", AclDoc, [{ssl, StanchionSSL}, {auth_creds, AdminCreds}]) end; bucket_fun(update_policy, Bucket, _BagId, PolicyJson, KeyId, AdminCreds, StanchionData) -> {StanchionIp, StanchionPort, StanchionSSL} = StanchionData, Generate the bucket JSON document for the ACL request PolicyDoc = bucket_policy_json(PolicyJson, KeyId), fun() -> velvet:set_bucket_policy(StanchionIp, StanchionPort, Bucket, "application/json", PolicyDoc, [{ssl, StanchionSSL}, {auth_creds, AdminCreds}]) end; bucket_fun(delete_policy, Bucket, _BagId, _, KeyId, AdminCreds, StanchionData) -> {StanchionIp, StanchionPort, StanchionSSL} = StanchionData, Generate the bucket JSON document for the ACL request fun() -> velvet:delete_bucket_policy(StanchionIp, StanchionPort, Bucket, KeyId, [{ssl, StanchionSSL}, {auth_creds, AdminCreds}]) end; bucket_fun(delete, Bucket, _BagId, _ACL, KeyId, AdminCreds, StanchionData) -> {StanchionIp, StanchionPort, StanchionSSL} = StanchionData, fun() -> velvet:delete_bucket(StanchionIp, StanchionPort, Bucket, KeyId, [{ssl, StanchionSSL}, {auth_creds, AdminCreds}]) end. -spec bucket_json(binary(), bag_id(), acl(), string()) -> string(). bucket_json(Bucket, BagId, ACL, KeyId) -> BagElement = case BagId of undefined -> []; _ -> [{<<"bag">>, BagId}] end, binary_to_list( iolist_to_binary( mochijson2:encode({struct, [{<<"bucket">>, Bucket}, {<<"requester">>, list_to_binary(KeyId)}, riak_cs_acl_utils:acl_to_json_term(ACL)] ++ BagElement}))). -spec bucket_record(binary(), bucket_operation()) -> cs_bucket(). bucket_record(Name, Operation) -> Action = case Operation of create -> created; delete -> deleted; _ -> undefined end, ?RCS_BUCKET{name=binary_to_list(Name), last_action=Action, creation_date=riak_cs_wm_utils:iso_8601_datetime(), modification_time=os:timestamp()}. -spec bucket_resolver(cs_bucket(), [cs_bucket()]) -> [cs_bucket()]. bucket_resolver(Bucket, ResolvedBuckets) -> case lists:member(Bucket, ResolvedBuckets) of true -> ResolvedBuckets; false -> case [RB || RB <- ResolvedBuckets, RB?RCS_BUCKET.name =:= Bucket?RCS_BUCKET.name] of [] -> [Bucket | ResolvedBuckets]; [ExistingBucket] -> case keep_existing_bucket(ExistingBucket, Bucket) of true -> ResolvedBuckets; false -> [Bucket | lists:delete(ExistingBucket, ResolvedBuckets)] end end end. -spec bucket_sorter(cs_bucket(), cs_bucket()) -> boolean(). bucket_sorter(?RCS_BUCKET{name=Bucket1}, ?RCS_BUCKET{name=Bucket2}) -> Bucket1 =< Bucket2. -spec cleanup_bucket(cs_bucket()) -> boolean(). cleanup_bucket(?RCS_BUCKET{last_action=created}) -> false; cleanup_bucket(?RCS_BUCKET{last_action=deleted, modification_time=ModTime}) -> the prune - time is specified in seconds , so we must convert Erlang timestamps to seconds first NowSeconds = riak_cs_utils:second_resolution_timestamp(os:timestamp()), ModTimeSeconds = riak_cs_utils:second_resolution_timestamp(ModTime), (NowSeconds - ModTimeSeconds) > riak_cs_config:user_buckets_prune_time(). -spec keep_existing_bucket(cs_bucket(), cs_bucket()) -> boolean(). keep_existing_bucket(?RCS_BUCKET{last_action=LastAction1, modification_time=ModTime1}, ?RCS_BUCKET{last_action=LastAction2, modification_time=ModTime2}) -> if LastAction1 == LastAction2 andalso ModTime1 =< ModTime2 -> true; LastAction1 == LastAction2 -> false; ModTime1 > ModTime2 -> true; true -> false end. -spec resolve_buckets([rcs_user()], [cs_bucket()], boolean()) -> [cs_bucket()]. resolve_buckets([], Buckets, true) -> lists:sort(fun bucket_sorter/2, Buckets); resolve_buckets([], Buckets, false) -> lists:sort(fun bucket_sorter/2, [Bucket || Bucket <- Buckets, not cleanup_bucket(Bucket)]); resolve_buckets([HeadUserRec | RestUserRecs], [], KeepDeletedBuckets) -> case of thousands of bucket records under single user . resolve_buckets(RestUserRecs, HeadUserRec?RCS_USER.buckets, KeepDeletedBuckets); resolve_buckets([HeadUserRec | RestUserRecs], Buckets, _KeepDeleted) -> HeadBuckets = HeadUserRec?RCS_USER.buckets, UpdBuckets = lists:foldl(fun bucket_resolver/2, Buckets, HeadBuckets), resolve_buckets(RestUserRecs, UpdBuckets, _KeepDeleted). -spec serialized_bucket_op(binary(), [] | acl() | policy(), rcs_user(), riakc_obj:riakc_obj(), bucket_operation(), riak_cs_stats:key(), riak_client()) -> ok | {error, term()}. serialized_bucket_op(Bucket, ACL, User, UserObj, BucketOp, StatKey, RcPid) -> serialized_bucket_op(Bucket, undefined, ACL, User, UserObj, BucketOp, StatKey, RcPid). -spec serialized_bucket_op(binary(), bag_id(), [] | acl() | policy(), rcs_user(), riakc_obj:riakc_obj(), bucket_operation(), riak_cs_stats:key(), riak_client()) -> ok | {error, term()}. serialized_bucket_op(Bucket, BagId, ACL, User, UserObj, BucketOp, StatsKey, RcPid) -> StartTime = os:timestamp(), _ = riak_cs_stats:inflow(StatsKey), {ok, AdminCreds} = riak_cs_config:admin_creds(), BucketFun = bucket_fun(BucketOp, Bucket, BagId, ACL, User?RCS_USER.key_id, AdminCreds, riak_cs_utils:stanchion_data()), OpResult = BucketFun(), _ = riak_cs_stats:update_with_start(StatsKey, StartTime, OpResult), case OpResult of ok -> BucketRecord = bucket_record(Bucket, BucketOp), case update_user_buckets(User, BucketRecord) of {ok, ignore} when BucketOp == update_acl -> OpResult; {ok, ignore} -> OpResult; {ok, UpdUser} -> riak_cs_user:save_user(UpdUser, UserObj, RcPid) end; {error, {error_status, Status, _, ErrorDoc}} -> handle_stanchion_response(Status, ErrorDoc, BucketOp, Bucket); {error, _} -> OpResult end. @doc needs retry for delete op . 409 assumes -spec handle_stanchion_response(200..503, string(), delete|create, binary()) -> {error, remaining_multipart_upload} | {error, atom()}. handle_stanchion_response(409, ErrorDoc, Op, Bucket) when Op =:= delete orelse Op =:= create -> Value = riak_cs_s3_response:xml_error_code(ErrorDoc), case {lists:flatten(Value), Op} of {"MultipartUploadRemaining", delete} -> _ = lager:error("Concurrent multipart upload might have" " happened on deleting bucket '~s'.", [Bucket]), {error, remaining_multipart_upload}; {"MultipartUploadRemaining", create} -> _ = lager:critical("Multipart upload remains in deleted bucket (~s)" " Clean up the deleted buckets now.", [Bucket]), Broken , returns 500 throw({remaining_multipart_upload_on_deleted_bucket, Bucket}); Other -> _ = lager:debug("errordoc: ~p => ~s", [Other, ErrorDoc]), riak_cs_s3_response:error_response(ErrorDoc) end; handle_stanchion_response(_C, ErrorDoc, _M, _) -> riak_cs_s3_response:error_response(ErrorDoc). -spec update_bucket_record(term()) -> cs_bucket(). update_bucket_record(Bucket=?RCS_BUCKET{name=Name}) when is_binary(Name) -> Bucket?RCS_BUCKET{name=binary_to_list(Name)}; update_bucket_record(Bucket) -> Bucket. -spec update_user_buckets(rcs_user(), cs_bucket()) -> {ok, ignore} | {ok, rcs_user()}. update_user_buckets(User, Bucket) -> Buckets = User?RCS_USER.buckets, list should have 0 or 1 buckets that share a name case [B || B <- Buckets, B?RCS_BUCKET.name =:= Bucket?RCS_BUCKET.name] of [] -> {ok, User?RCS_USER{buckets=[Bucket | Buckets]}}; [ExistingBucket] -> case (Bucket?RCS_BUCKET.last_action == deleted andalso ExistingBucket?RCS_BUCKET.last_action == created) orelse (Bucket?RCS_BUCKET.last_action == created andalso ExistingBucket?RCS_BUCKET.last_action == deleted) of true -> UpdBuckets = [Bucket | lists:delete(ExistingBucket, Buckets)], {ok, User?RCS_USER{buckets=UpdBuckets}}; false -> {ok, ignore} end end. @doc Grab the whole list of Riak CS bucket keys . -spec fetch_bucket_keys(riak_client()) -> {ok, [binary()]} | {error, term()}. fetch_bucket_keys(RcPid) -> {ok, MasterPbc} = riak_cs_riak_client:master_pbc(RcPid), Timeout = riak_cs_config:list_keys_list_buckets_timeout(), riak_cs_pbc:list_keys(MasterPbc, ?BUCKETS_BUCKET, Timeout, [riakc, list_all_bucket_keys]).
d830de79db76d515e1826764744fbf0c3e4d313d9406dbafa34800ba76e55812
chenyukang/eopl
02.scm
;; Prove by induction on n that for any g, (fib/k n g) = (g (fib n)). ;; initial step: ;; (fib/k 1 g) = (g 1) = (g (fib 1)) stands true ;; assume (fib/k n g) = (g fib(n)) ( fib / k n+1 g ) = > ( ) ) ;; => ( fib / k n ( lambda ( v1 ) ;; (fib/k (n-1) ;; (lambda (v2) ;; (g (v1 + v2)))))) ;; (lambda (v1) ;; (fib/k (n-1) ;; (lambda (v2) ;; (g (v1 + v2)))) ;; (fib/k n)) ;; (fib/k (n-1) (lambda (v2) ;; (g ((fib/k n) + v2)))) ;; (lambda (v2) ;; (g ((fib/k n) + v2)) ;; (fib/k (n-1))) ;; (g ((fib/k n) + (fib/k (n - 1)))) ( g ( / k ( n + 1 ) ) )
null
https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/ch6/02.scm
scheme
Prove by induction on n that for any g, (fib/k n g) = (g (fib n)). initial step: (fib/k 1 g) = (g 1) = (g (fib 1)) stands true assume (fib/k n g) = (g fib(n)) => (fib/k (n-1) (lambda (v2) (g (v1 + v2)))))) (lambda (v1) (fib/k (n-1) (lambda (v2) (g (v1 + v2)))) (fib/k n)) (fib/k (n-1) (lambda (v2) (g ((fib/k n) + v2)))) (lambda (v2) (g ((fib/k n) + v2)) (fib/k (n-1))) (g ((fib/k n) + (fib/k (n - 1))))
( fib / k n+1 g ) = > ( ) ) ( fib / k n ( lambda ( v1 ) ( g ( / k ( n + 1 ) ) )
d3f0f1787533b3e42b094114ddcac71526c89243f42caa73ff85e717158acd0c
AntidoteDB/antidote_aql
where.erl
%%%------------------------------------------------------------------- @author , %%% @doc A module to handle AQL where clauses. %%% @end %%%------------------------------------------------------------------- -module(where). -include("parser.hrl"). -include("aql.hrl"). -export([scan/3]). scan(Table, ?PARSER_WILDCARD, TxId) -> TName = table:name(Table), Index = index:p_keys(TName, TxId), lists:map(fun({_Key, BObj}) -> BObj end, Index); scan(Table, Conditions, TxId) -> evaluate(Table, Conditions, TxId, []). %% ==================================================================== Internal functions %% ==================================================================== evaluate(Table, [{_ClValue, Arop, Value} | T], TxId, Acc) -> case Arop of ?PARSER_EQUALITY -> NewAcc = lists:flatten(Acc, [element:create_key_from_table(Value, Table, TxId)]), evaluate(Table, T, TxId, NewAcc); _Else -> throw("Not supported yet") end; evaluate(_Table, [], _TxId, Acc) -> Acc.
null
https://raw.githubusercontent.com/AntidoteDB/antidote_aql/e7ef4913d233c2fee8ebff582d91fe3e2e95786c/src/where.erl
erlang
------------------------------------------------------------------- @doc A module to handle AQL where clauses. @end ------------------------------------------------------------------- ==================================================================== ====================================================================
@author , -module(where). -include("parser.hrl"). -include("aql.hrl"). -export([scan/3]). scan(Table, ?PARSER_WILDCARD, TxId) -> TName = table:name(Table), Index = index:p_keys(TName, TxId), lists:map(fun({_Key, BObj}) -> BObj end, Index); scan(Table, Conditions, TxId) -> evaluate(Table, Conditions, TxId, []). Internal functions evaluate(Table, [{_ClValue, Arop, Value} | T], TxId, Acc) -> case Arop of ?PARSER_EQUALITY -> NewAcc = lists:flatten(Acc, [element:create_key_from_table(Value, Table, TxId)]), evaluate(Table, T, TxId, NewAcc); _Else -> throw("Not supported yet") end; evaluate(_Table, [], _TxId, Acc) -> Acc.
c21bf4350e095aa12b03e8fd6926a9a360cbdd51237e74ddd8c772f794931f07
Viasat/halite
run.clj
Copyright ( c ) 2022 Viasat , Inc. Licensed under the MIT license (ns com.viasat.halite.doc.run (:require [com.viasat.halite :as halite] [com.viasat.halite.base :as base] [com.viasat.halite.lib.format-errors :as format-errors] [com.viasat.halite.lint :as lint] [com.viasat.halite.types :as types] [com.viasat.jadeite :as jadeite]) (:import [clojure.lang ExceptionInfo])) (set! *warn-on-reflection* true) (deftype HInfo [s t j-expr h-result jh-result j-result]) (def ^:dynamic *check-spec-map-for-cycles?* false) (defn- eval-h-expr [senv tenv env expr] (halite/eval-expr senv tenv env expr (assoc halite/default-eval-expr-options :check-for-spec-cycles? *check-spec-map-for-cycles?*))) (defmacro h-eval [expr] ;; helper for debugging `(let [spec-map# {} tenv# (halite/type-env {}) env# (halite/env {})] (eval-h-expr spec-map# tenv# env# '~expr))) (defmacro h-lint [expr] ;; helper for debugging `(let [spec-map# {} tenv# (halite/type-env {})] (lint/type-check-and-lint spec-map# tenv# '~expr))) (defn j-eval [expr-str] ;; helper for debugging (let [spec-map {} tenv (halite/type-env {}) env (halite/env {}) expr (jadeite/to-halite expr-str)] (eval-h-expr spec-map tenv env expr))) (defn is-harness-error? [x] (and (vector? x) (= :throws (first x)))) (defn check-result-type [spec-map tenv t result] (when-not (or (is-harness-error? result) (is-harness-error? t)) (if (= :Unset result) (assert (types/maybe-type? t)) (let [result-type (lint/type-check-and-lint spec-map tenv result)] (when-not (is-harness-error? t) (assert (types/subtype? result-type t))))))) (def halite-limits {:string-literal-length 1024 :string-runtime-length 1024 :vector-literal-count 1024 :vector-runtime-count 1024 :set-literal-count 1024 :set-runtime-count 1024 :list-literal-count 256 :expression-nesting-depth 10}) (defn ^HInfo h* ([expr] (h* expr false)) ([expr separate-err-id?] (binding [base/*limits* halite-limits format-errors/*squash-throw-site* true] (let [spec-map {} tenv (halite/type-env {}) env (halite/env {}) j-expr (try (jadeite/to-jadeite expr) (catch RuntimeException e [:throws (.getMessage e)])) s (try (halite/syntax-check expr) nil (catch RuntimeException e [:syntax-check-throws (.getMessage e)])) t (try (lint/type-check-and-lint spec-map tenv expr) (catch RuntimeException e [:throws (.getMessage e)])) h-result (try (eval-h-expr spec-map tenv env expr) (catch ExceptionInfo e (if separate-err-id? [:throws (.getMessage e) (:err-id (ex-data e))] [:throws (.getMessage e)])) (catch RuntimeException e [:throws (.getMessage e)])) h-result-type (check-result-type spec-map tenv t h-result) jh-expr (when (string? j-expr) (try (jadeite/to-halite j-expr) (catch RuntimeException e [:throws (.getMessage e)]))) jh-result (try (eval-h-expr spec-map tenv env jh-expr) (catch RuntimeException e [:throws (.getMessage e)])) jh-result-type (check-result-type spec-map tenv t jh-result) j-result (try (jadeite/to-jadeite (eval-h-expr spec-map tenv env jh-expr)) (catch RuntimeException e [:throws (.getMessage e)]))] (HInfo. s t j-expr h-result jh-result j-result))))) (deftype HCInfo [s t h-result j-expr jh-result j-result]) (defn ^HCInfo hc* [spec-map expr separate-err-id?] (binding [format-errors/*squash-throw-site* true] (let [tenv (halite/type-env {}) env (halite/env {}) j-expr (try (jadeite/to-jadeite expr) (catch RuntimeException e (vary-meta [:throws (.getMessage e)] :ex e))) s (try (halite/syntax-check expr) nil (catch RuntimeException e (vary-meta [:syntax-check-throws (.getMessage e)] assoc :ex e))) t (try (halite/type-check-and-lint spec-map tenv expr) (catch RuntimeException e (vary-meta [:throws (.getMessage e)] assoc :ex e))) h-result (try (eval-h-expr spec-map tenv env expr) (catch ExceptionInfo e (vary-meta (if separate-err-id? [:throws (.getMessage e) (:err-id (ex-data e))] [:throws (.getMessage e)]) assoc :ex e)) (catch RuntimeException e (vary-meta [:throws (.getMessage e)] assoc :ex e))) jh-expr (when (string? j-expr) (try (jadeite/to-halite j-expr) (catch RuntimeException e (vary-meta [:throws (.getMessage e)] assoc :ex e)))) jh-result (try (eval-h-expr spec-map tenv env jh-expr) (catch RuntimeException e (vary-meta [:throws (.getMessage e)] assoc :ex e))) j-result (try (jadeite/to-jadeite (eval-h-expr spec-map tenv env jh-expr)) (catch RuntimeException e (vary-meta [:throws (.getMessage e)] assoc :ex e)))] (HCInfo. s t h-result j-expr jh-result j-result)))) (defn hc-body ([spec-map expr] (hc* spec-map expr true)))
null
https://raw.githubusercontent.com/Viasat/halite/0960db0950835d6e699e4b871f326361eede29f9/src/com/viasat/halite/doc/run.clj
clojure
helper for debugging helper for debugging helper for debugging
Copyright ( c ) 2022 Viasat , Inc. Licensed under the MIT license (ns com.viasat.halite.doc.run (:require [com.viasat.halite :as halite] [com.viasat.halite.base :as base] [com.viasat.halite.lib.format-errors :as format-errors] [com.viasat.halite.lint :as lint] [com.viasat.halite.types :as types] [com.viasat.jadeite :as jadeite]) (:import [clojure.lang ExceptionInfo])) (set! *warn-on-reflection* true) (deftype HInfo [s t j-expr h-result jh-result j-result]) (def ^:dynamic *check-spec-map-for-cycles?* false) (defn- eval-h-expr [senv tenv env expr] (halite/eval-expr senv tenv env expr (assoc halite/default-eval-expr-options :check-for-spec-cycles? *check-spec-map-for-cycles?*))) (defmacro h-eval [expr] `(let [spec-map# {} tenv# (halite/type-env {}) env# (halite/env {})] (eval-h-expr spec-map# tenv# env# '~expr))) (defmacro h-lint [expr] `(let [spec-map# {} tenv# (halite/type-env {})] (lint/type-check-and-lint spec-map# tenv# '~expr))) (defn j-eval [expr-str] (let [spec-map {} tenv (halite/type-env {}) env (halite/env {}) expr (jadeite/to-halite expr-str)] (eval-h-expr spec-map tenv env expr))) (defn is-harness-error? [x] (and (vector? x) (= :throws (first x)))) (defn check-result-type [spec-map tenv t result] (when-not (or (is-harness-error? result) (is-harness-error? t)) (if (= :Unset result) (assert (types/maybe-type? t)) (let [result-type (lint/type-check-and-lint spec-map tenv result)] (when-not (is-harness-error? t) (assert (types/subtype? result-type t))))))) (def halite-limits {:string-literal-length 1024 :string-runtime-length 1024 :vector-literal-count 1024 :vector-runtime-count 1024 :set-literal-count 1024 :set-runtime-count 1024 :list-literal-count 256 :expression-nesting-depth 10}) (defn ^HInfo h* ([expr] (h* expr false)) ([expr separate-err-id?] (binding [base/*limits* halite-limits format-errors/*squash-throw-site* true] (let [spec-map {} tenv (halite/type-env {}) env (halite/env {}) j-expr (try (jadeite/to-jadeite expr) (catch RuntimeException e [:throws (.getMessage e)])) s (try (halite/syntax-check expr) nil (catch RuntimeException e [:syntax-check-throws (.getMessage e)])) t (try (lint/type-check-and-lint spec-map tenv expr) (catch RuntimeException e [:throws (.getMessage e)])) h-result (try (eval-h-expr spec-map tenv env expr) (catch ExceptionInfo e (if separate-err-id? [:throws (.getMessage e) (:err-id (ex-data e))] [:throws (.getMessage e)])) (catch RuntimeException e [:throws (.getMessage e)])) h-result-type (check-result-type spec-map tenv t h-result) jh-expr (when (string? j-expr) (try (jadeite/to-halite j-expr) (catch RuntimeException e [:throws (.getMessage e)]))) jh-result (try (eval-h-expr spec-map tenv env jh-expr) (catch RuntimeException e [:throws (.getMessage e)])) jh-result-type (check-result-type spec-map tenv t jh-result) j-result (try (jadeite/to-jadeite (eval-h-expr spec-map tenv env jh-expr)) (catch RuntimeException e [:throws (.getMessage e)]))] (HInfo. s t j-expr h-result jh-result j-result))))) (deftype HCInfo [s t h-result j-expr jh-result j-result]) (defn ^HCInfo hc* [spec-map expr separate-err-id?] (binding [format-errors/*squash-throw-site* true] (let [tenv (halite/type-env {}) env (halite/env {}) j-expr (try (jadeite/to-jadeite expr) (catch RuntimeException e (vary-meta [:throws (.getMessage e)] :ex e))) s (try (halite/syntax-check expr) nil (catch RuntimeException e (vary-meta [:syntax-check-throws (.getMessage e)] assoc :ex e))) t (try (halite/type-check-and-lint spec-map tenv expr) (catch RuntimeException e (vary-meta [:throws (.getMessage e)] assoc :ex e))) h-result (try (eval-h-expr spec-map tenv env expr) (catch ExceptionInfo e (vary-meta (if separate-err-id? [:throws (.getMessage e) (:err-id (ex-data e))] [:throws (.getMessage e)]) assoc :ex e)) (catch RuntimeException e (vary-meta [:throws (.getMessage e)] assoc :ex e))) jh-expr (when (string? j-expr) (try (jadeite/to-halite j-expr) (catch RuntimeException e (vary-meta [:throws (.getMessage e)] assoc :ex e)))) jh-result (try (eval-h-expr spec-map tenv env jh-expr) (catch RuntimeException e (vary-meta [:throws (.getMessage e)] assoc :ex e))) j-result (try (jadeite/to-jadeite (eval-h-expr spec-map tenv env jh-expr)) (catch RuntimeException e (vary-meta [:throws (.getMessage e)] assoc :ex e)))] (HCInfo. s t h-result j-expr jh-result j-result)))) (defn hc-body ([spec-map expr] (hc* spec-map expr true)))
bb3a33c06043a2af3ad6c322f4467d94c277884b1d05245941254deaccd0b073
ephemient/aoc2018
Day9Spec.hs
module Day9Spec (spec) where import Day9 (play) import Test.Hspec (Spec, it, shouldBe) spec :: Spec spec = it "examples" $ do play 9 25 `shouldBe` 32 play 10 1618 `shouldBe` 8317 play 13 7999 `shouldBe` 146373 play 17 1104 `shouldBe` 2764 play 21 6111 `shouldBe` 54718 play 30 5807 `shouldBe` 37305
null
https://raw.githubusercontent.com/ephemient/aoc2018/eb0d04193ccb6ad98ed8ad2253faeb3d503a5938/test/Day9Spec.hs
haskell
module Day9Spec (spec) where import Day9 (play) import Test.Hspec (Spec, it, shouldBe) spec :: Spec spec = it "examples" $ do play 9 25 `shouldBe` 32 play 10 1618 `shouldBe` 8317 play 13 7999 `shouldBe` 146373 play 17 1104 `shouldBe` 2764 play 21 6111 `shouldBe` 54718 play 30 5807 `shouldBe` 37305
61cfc502e1cf5c2716e16b3451075bb034659d58498a341882e957c8da54a5f5
bzg/covid19-faq
core.cljs
Copyright ( c ) 2020 DINUM , < > SPDX - License - Identifier : EPL-2.0 ;; License-Filename: LICENSES/EPL-2.0.txt (ns covid19faq.core (:require [cljs.core.async :as async] [clojure.string :as s] [ajax.core :refer [GET POST]] [re-frame.core :as re-frame] [reagent.core :as reagent] [reagent.dom] [clojure.walk :as walk] [reitit.frontend :as rf] [reitit.frontend.easy :as rfe] [cljsjs.clipboard])) (defonce dev? false) (defonce timeout 150) (defonce number-of-random-questions 12) (defonce number-of-sorted-questions 100) (defonce minimum-search-string-size 3) (defonce faq-covid-19-api-url (if dev? ":3000" "-faq.fr")) (defonce faq-covid-19-data-url "-faq-data/") (defonce faq-covid-19-questions "faq-questions.json") (defonce faq-covid-19-answers-dir "answers/") (def token (atom nil)) (def stats (atom nil)) (def noted (atom {})) (def init-filter {:query "" :source "" :sorting "" :faq ""}) (def global-filter (reagent/atom init-filter)) (defn set-focus-on-search [] (.focus (.getElementById js/document "search"))) (defn clean-state [m] (apply dissoc m (for [[k v] m :when (empty? v)] k))) (defn set-item! "Set `key` in browser's localStorage to `val`." [key val] (.setItem (.-localStorage js/window) key (.stringify js/JSON (clj->js val)))) (defn get-item "Return the value of `key` from browser's localStorage." [key] (js->clj (.parse js/JSON (.getItem (.-localStorage js/window) key)))) (defn remove-item! "Remove the browser's localStorage value for the given `key`." [key] (.removeItem (.-localStorage js/window) key)) (re-frame/reg-event-db :initialize-db! (fn [_ _] {:faqs nil :view :home :filter init-filter})) (re-frame/reg-event-db :view! (fn [db [_ view query-params]] (reset! global-filter (merge init-filter query-params)) (re-frame/dispatch [:filter! (merge init-filter query-params)]) (assoc db :view view))) (re-frame/reg-sub :view? (fn [db _] (:view db))) (re-frame/reg-event-db :filter! (fn [db [_ s]] (assoc db :filter (merge (:filter db) s)))) (re-frame/reg-sub :filter? (fn [db _] (:filter db))) (re-frame/reg-event-db :faqs! (fn [db [_ faqs]] (assoc db :faqs faqs))) (re-frame/reg-sub :faqs? (fn [db _] (:faqs db))) (defn add-match-index [{:keys [q] :as item} pattern] (when-let [matched (last (re-matches pattern q))] (let [idx (s/index-of q matched)] (assoc item :x idx :q (s/replace q matched (str "<b>" matched "</b>")))))) (defn apply-sorting [{:keys [sorting query source]} m] (condp = sorting "note" (take number-of-sorted-questions (reverse (sort-by :n m))) "hits" (take number-of-sorted-questions (reverse (sort-by :h m))) (if (and (empty? query) (empty? source)) (take number-of-random-questions (shuffle m)) m))) (defn apply-filter [m] (let [{:keys [sorting query source] :as f} @(re-frame/subscribe [:filter?]) q (-> query (s/replace #"(?i)e" "[éèëêe]") (s/replace #"(?i)a" "[æàâa]") (s/replace #"(?i)o" "[œöôo]") (s/replace #"(?i)c" "[çc]") (s/replace #"(?i)u" "[ûùu]")) p (re-pattern (str "(?i).*(" (s/join ".*" (s/split q #"\s+")) ").*"))] (->> (if (not-empty query) (sort-by :x (map #(add-match-index % p) m)) m) (filter #(if (not-empty source) (= source (:s %)) identity)) (apply-sorting f)))) (re-frame/reg-sub :filtered-faq? (fn [db _] (apply-filter @(re-frame/subscribe [:faqs?])))) (def filter-chan (async/chan)) (defn start-filter-loop [] (async/go (loop [f (async/<! filter-chan)] (re-frame/dispatch [:filter! f]) (rfe/push-state :home nil (merge (when-let [q (not-empty (:query @global-filter))] {:query q}) (when-let [s (not-empty (:source @global-filter))] {:source s}) (when-let [o (not-empty (:sorting @global-filter))] {:sorting o}))) (recur (async/<! filter-chan))))) (defn display-questions [] (let [questions (remove nil? @(re-frame/subscribe [:filtered-faq?]))] (if (seq questions) [:div.table-container [:table.table.is-hoverable.is-fullwidth [:tbody (for [question questions :let [id (:i question) text (:q question)]] ^{:key (random-uuid)} [:tr [:td [:a {:tabIndex 0 :on-click #(rfe/push-state :home nil (clean-state (merge @global-filter {:faq id})))} [:span {:dangerouslySetInnerHTML {:__html text}}]]]])]]] [:p "Aucune question n'a été trouvée : peut-être une faute de frappe ?"]))) ;; Create a copy-to-clipboard component (defn clipboard-button [label target] (let [clipboard-atom (reagent/atom nil)] (reagent/create-class {:display-name "clipboard-button" :component-did-mount #(let [clipboard (new js/ClipboardJS (reagent.dom/dom-node %))] (reset! clipboard-atom clipboard)) :component-will-unmount #(when-not (nil? @clipboard-atom) (reset! clipboard-atom nil)) :reagent-render (fn [] [:a.button.is-fullwidth.is-size-5 {:title "Copier dans le presse papier" :data-clipboard-target target} label])}))) (defn strip-html [s] (-> s (s/replace #"<br/?>" "\n") (s/replace #"</?[^>]+>" ""))) (defn shorten-source-name [s] (condp = s "Société Française de Pharmacologie et de Thérapeutique" "Société Française de Pharmacologie" s)) (defn bottom-links [{:keys [q r s u m]}] (let [url (.-href (.-location js/document)) short-s (shorten-source-name s) e-str (when (and q r u url) (str "mailto:" "?subject=[COVID-19] " q "&body=" (s/replace (str (strip-html r) "\nSource officielle : " u "\nEnvoyé depuis : " url) #"[\n\t]" "%0D%0A%0D%0A")))] [:div.tile.is-ancestor [:div.tile.is-parent [:a.button.is-success.is-fullwidth.is-light.is-size-5 {:target "new" :title (when m (str "Réponse en date du " (subs m 0 10) " - cliquez pour consulter la source")) :href u} short-s]] [:div.tile.is-parent.has-text-centered.is-1 [:a.button.is-fullwidth.is-size-5 {:title "Envoyer la question et la réponse par email" :href e-str} "📩"]] [:div.tile.is-parent.has-text-centered.is-1 [clipboard-button "📋" "#copy-this"]]])) (defn send-note [id note] (POST (str faq-covid-19-api-url "/note") {:params {:id id :token @token :note note} :handler (fn [r] (condp = (:response (walk/keywordize-keys r)) "OK" (do (swap! noted conj {id note}) (set-item! :noted @noted) (println "Note stored")) (println "Error while sending the note"))) :error-handler (fn [r] (prn (:response (walk/keywordize-keys r))))})) (defn display-call-to-note [id & [inactive?]] (let [ok [:span.icon [:i.far.fa-2x.fa-smile]] notok [:span.icon [:i.far.fa-2x.fa-angry]] space "   "] (if inactive? [:div.tile.is-parent [:a.tile {:title "Mon appréciation précédente"} (if (= "1" (get (get-item :noted) id)) ok notok)] [:a.tile {:title "Je veux revoter !" :on-click #(swap! noted dissoc id)} [:span.icon [:i.fas.fa-undo]]]] [:div.tile.is-parent [:a.tile.is-parent {:title "Ça m'a été utile !" :on-click #(send-note id "1")} ok] [:a.tile.is-parent {:title "Ça ne m'a pas été utile..." :on-click #(send-note id "-1")} notok]]))) (defn display-answer [id] (let [answer (reagent/atom {}) a-url (str faq-covid-19-data-url faq-covid-19-answers-dir id ".json")] (fn [] (GET a-url :handler #(reset! answer (walk/keywordize-keys %))) [:div [:article {:id "copy-this"} [:div.columns.is-vcentered [:div.column.is-1.has-text-centered [:a.delete.is-large {:title "Revenir aux autres questions" :on-click #(do (rfe/push-state :home nil (clean-state (dissoc @global-filter :faq))) (set-focus-on-search))}]] [:div.column.is-multiline.is-9 [:p [:strong.is-size-4 {:dangerouslySetInnerHTML {:__html (:q @answer)}}]]] [:div.column.is-2 (if (contains? @noted id) (display-call-to-note id "inactive") (display-call-to-note id))]] [:br] [:div.content {:dangerouslySetInnerHTML {:__html (:r @answer)}}] [:br]] (if-let [a @answer] [bottom-links a] [:br])]))) (defn faq-sources-select [] [:div.select [:select {:value (or (:source @(re-frame/subscribe [:filter?])) "") :tabIndex 0 :on-change (fn [e] (let [ev (.-value (.-target e))] (set-focus-on-search) (swap! global-filter merge {:query "" :source ev}) (async/go (async/>! filter-chan {:query "" :source ev}))))} [:option {:value ""} "Toutes les questions"] (for [s (distinct (map :s @(re-frame/subscribe [:faqs?])))] ^{:key (random-uuid)} [:option {:value s} (shorten-source-name s)])]]) (defn faq-sort-select [sort-type] [:div.select [:select {:value sort-type :tabIndex 0 :on-change (fn [e] (let [ev (.-value (.-target e))] (set-focus-on-search) (swap! global-filter merge {:query "" :sorting ev}) (async/go (async/>! filter-chan {:query "" :sorting ev}))))} [:option {:value ""} "Au hasard"] [:option {:value "note"} "Les mieux notées"] [:option {:value "hits"} "Les plus consultées"]]]) (defn main-page [] (let [filter @(re-frame/subscribe [:filter?]) answer-id (:faq filter) sort-type (:sorting filter)] [:div [:div.columns.is-vcentered [:input.input.column.is-6 {:id "search" :tabIndex 0 :size 20 :placeholder "Recherche" :value (or (:query @global-filter) (:query @(re-frame/subscribe [:filter?]))) :on-change (fn [e] (let [ev (.-value (.-target e)) ev-size (count ev)] (swap! global-filter merge {:query ev}) (when (or (= ev-size 0) (>= ev-size minimum-search-string-size)) (async/go (async/<! (async/timeout timeout)) (async/>! filter-chan {:query ev})))))}] [:div.column.is-3 (faq-sources-select)] [:div.column.is-2 (faq-sort-select sort-type)] [:div.column.is-1 [:a.delete.is-medium {:title "Effacer tous les filtres" :on-click #(do (rfe/push-state :home) (set-focus-on-search))}]]] [:br] (if (not-empty answer-id) (do (GET (str faq-covid-19-api-url "/hit") {:format :json :params {:token @token :id answer-id} :handler (fn [r] (prn r)) :error-handler (fn [r] (prn r))}) [display-answer answer-id]) [display-questions])])) (defn faq-with-stats [m] (map (fn [{:keys [i] :as faq}] (merge faq {:h (get-in @stats [(keyword i) :h]) ;; :hits :n (get-in @stats [(keyword i) :n :m])})) ;; :note :mean (walk/keywordize-keys m))) (defn main-class [] (reagent/create-class {:component-did-mount (fn [] (GET (str faq-covid-19-api-url "/stats") :handler #(reset! stats (walk/keywordize-keys %))) (GET (str faq-covid-19-api-url "/token") :handler #(reset! token (or (:token (walk/keywordize-keys %)) ""))) (GET (str faq-covid-19-data-url faq-covid-19-questions) :handler #(re-frame/dispatch [:faqs! (faq-with-stats %)]))) :reagent-render #(main-page)})) (def routes [["" :home]]) (defn on-navigate [match] (re-frame/dispatch [:view! :home (:query-params match)])) (defn ^:export init [] (re-frame/clear-subscription-cache!) (re-frame/dispatch-sync [:initialize-db!]) (start-filter-loop) (rfe/start! (rf/router routes {:conflicts nil}) on-navigate {:use-fragment true}) (reagent.dom/render [main-class] (. js/document (getElementById "app"))) (set-focus-on-search))
null
https://raw.githubusercontent.com/bzg/covid19-faq/89a3a74c000cbb14624d5e1bdc0569fccd0b9e67/src/cljs/covid19faq/core.cljs
clojure
License-Filename: LICENSES/EPL-2.0.txt Create a copy-to-clipboard component :hits :note :mean
Copyright ( c ) 2020 DINUM , < > SPDX - License - Identifier : EPL-2.0 (ns covid19faq.core (:require [cljs.core.async :as async] [clojure.string :as s] [ajax.core :refer [GET POST]] [re-frame.core :as re-frame] [reagent.core :as reagent] [reagent.dom] [clojure.walk :as walk] [reitit.frontend :as rf] [reitit.frontend.easy :as rfe] [cljsjs.clipboard])) (defonce dev? false) (defonce timeout 150) (defonce number-of-random-questions 12) (defonce number-of-sorted-questions 100) (defonce minimum-search-string-size 3) (defonce faq-covid-19-api-url (if dev? ":3000" "-faq.fr")) (defonce faq-covid-19-data-url "-faq-data/") (defonce faq-covid-19-questions "faq-questions.json") (defonce faq-covid-19-answers-dir "answers/") (def token (atom nil)) (def stats (atom nil)) (def noted (atom {})) (def init-filter {:query "" :source "" :sorting "" :faq ""}) (def global-filter (reagent/atom init-filter)) (defn set-focus-on-search [] (.focus (.getElementById js/document "search"))) (defn clean-state [m] (apply dissoc m (for [[k v] m :when (empty? v)] k))) (defn set-item! "Set `key` in browser's localStorage to `val`." [key val] (.setItem (.-localStorage js/window) key (.stringify js/JSON (clj->js val)))) (defn get-item "Return the value of `key` from browser's localStorage." [key] (js->clj (.parse js/JSON (.getItem (.-localStorage js/window) key)))) (defn remove-item! "Remove the browser's localStorage value for the given `key`." [key] (.removeItem (.-localStorage js/window) key)) (re-frame/reg-event-db :initialize-db! (fn [_ _] {:faqs nil :view :home :filter init-filter})) (re-frame/reg-event-db :view! (fn [db [_ view query-params]] (reset! global-filter (merge init-filter query-params)) (re-frame/dispatch [:filter! (merge init-filter query-params)]) (assoc db :view view))) (re-frame/reg-sub :view? (fn [db _] (:view db))) (re-frame/reg-event-db :filter! (fn [db [_ s]] (assoc db :filter (merge (:filter db) s)))) (re-frame/reg-sub :filter? (fn [db _] (:filter db))) (re-frame/reg-event-db :faqs! (fn [db [_ faqs]] (assoc db :faqs faqs))) (re-frame/reg-sub :faqs? (fn [db _] (:faqs db))) (defn add-match-index [{:keys [q] :as item} pattern] (when-let [matched (last (re-matches pattern q))] (let [idx (s/index-of q matched)] (assoc item :x idx :q (s/replace q matched (str "<b>" matched "</b>")))))) (defn apply-sorting [{:keys [sorting query source]} m] (condp = sorting "note" (take number-of-sorted-questions (reverse (sort-by :n m))) "hits" (take number-of-sorted-questions (reverse (sort-by :h m))) (if (and (empty? query) (empty? source)) (take number-of-random-questions (shuffle m)) m))) (defn apply-filter [m] (let [{:keys [sorting query source] :as f} @(re-frame/subscribe [:filter?]) q (-> query (s/replace #"(?i)e" "[éèëêe]") (s/replace #"(?i)a" "[æàâa]") (s/replace #"(?i)o" "[œöôo]") (s/replace #"(?i)c" "[çc]") (s/replace #"(?i)u" "[ûùu]")) p (re-pattern (str "(?i).*(" (s/join ".*" (s/split q #"\s+")) ").*"))] (->> (if (not-empty query) (sort-by :x (map #(add-match-index % p) m)) m) (filter #(if (not-empty source) (= source (:s %)) identity)) (apply-sorting f)))) (re-frame/reg-sub :filtered-faq? (fn [db _] (apply-filter @(re-frame/subscribe [:faqs?])))) (def filter-chan (async/chan)) (defn start-filter-loop [] (async/go (loop [f (async/<! filter-chan)] (re-frame/dispatch [:filter! f]) (rfe/push-state :home nil (merge (when-let [q (not-empty (:query @global-filter))] {:query q}) (when-let [s (not-empty (:source @global-filter))] {:source s}) (when-let [o (not-empty (:sorting @global-filter))] {:sorting o}))) (recur (async/<! filter-chan))))) (defn display-questions [] (let [questions (remove nil? @(re-frame/subscribe [:filtered-faq?]))] (if (seq questions) [:div.table-container [:table.table.is-hoverable.is-fullwidth [:tbody (for [question questions :let [id (:i question) text (:q question)]] ^{:key (random-uuid)} [:tr [:td [:a {:tabIndex 0 :on-click #(rfe/push-state :home nil (clean-state (merge @global-filter {:faq id})))} [:span {:dangerouslySetInnerHTML {:__html text}}]]]])]]] [:p "Aucune question n'a été trouvée : peut-être une faute de frappe ?"]))) (defn clipboard-button [label target] (let [clipboard-atom (reagent/atom nil)] (reagent/create-class {:display-name "clipboard-button" :component-did-mount #(let [clipboard (new js/ClipboardJS (reagent.dom/dom-node %))] (reset! clipboard-atom clipboard)) :component-will-unmount #(when-not (nil? @clipboard-atom) (reset! clipboard-atom nil)) :reagent-render (fn [] [:a.button.is-fullwidth.is-size-5 {:title "Copier dans le presse papier" :data-clipboard-target target} label])}))) (defn strip-html [s] (-> s (s/replace #"<br/?>" "\n") (s/replace #"</?[^>]+>" ""))) (defn shorten-source-name [s] (condp = s "Société Française de Pharmacologie et de Thérapeutique" "Société Française de Pharmacologie" s)) (defn bottom-links [{:keys [q r s u m]}] (let [url (.-href (.-location js/document)) short-s (shorten-source-name s) e-str (when (and q r u url) (str "mailto:" "?subject=[COVID-19] " q "&body=" (s/replace (str (strip-html r) "\nSource officielle : " u "\nEnvoyé depuis : " url) #"[\n\t]" "%0D%0A%0D%0A")))] [:div.tile.is-ancestor [:div.tile.is-parent [:a.button.is-success.is-fullwidth.is-light.is-size-5 {:target "new" :title (when m (str "Réponse en date du " (subs m 0 10) " - cliquez pour consulter la source")) :href u} short-s]] [:div.tile.is-parent.has-text-centered.is-1 [:a.button.is-fullwidth.is-size-5 {:title "Envoyer la question et la réponse par email" :href e-str} "📩"]] [:div.tile.is-parent.has-text-centered.is-1 [clipboard-button "📋" "#copy-this"]]])) (defn send-note [id note] (POST (str faq-covid-19-api-url "/note") {:params {:id id :token @token :note note} :handler (fn [r] (condp = (:response (walk/keywordize-keys r)) "OK" (do (swap! noted conj {id note}) (set-item! :noted @noted) (println "Note stored")) (println "Error while sending the note"))) :error-handler (fn [r] (prn (:response (walk/keywordize-keys r))))})) (defn display-call-to-note [id & [inactive?]] (let [ok [:span.icon [:i.far.fa-2x.fa-smile]] notok [:span.icon [:i.far.fa-2x.fa-angry]] space "   "] (if inactive? [:div.tile.is-parent [:a.tile {:title "Mon appréciation précédente"} (if (= "1" (get (get-item :noted) id)) ok notok)] [:a.tile {:title "Je veux revoter !" :on-click #(swap! noted dissoc id)} [:span.icon [:i.fas.fa-undo]]]] [:div.tile.is-parent [:a.tile.is-parent {:title "Ça m'a été utile !" :on-click #(send-note id "1")} ok] [:a.tile.is-parent {:title "Ça ne m'a pas été utile..." :on-click #(send-note id "-1")} notok]]))) (defn display-answer [id] (let [answer (reagent/atom {}) a-url (str faq-covid-19-data-url faq-covid-19-answers-dir id ".json")] (fn [] (GET a-url :handler #(reset! answer (walk/keywordize-keys %))) [:div [:article {:id "copy-this"} [:div.columns.is-vcentered [:div.column.is-1.has-text-centered [:a.delete.is-large {:title "Revenir aux autres questions" :on-click #(do (rfe/push-state :home nil (clean-state (dissoc @global-filter :faq))) (set-focus-on-search))}]] [:div.column.is-multiline.is-9 [:p [:strong.is-size-4 {:dangerouslySetInnerHTML {:__html (:q @answer)}}]]] [:div.column.is-2 (if (contains? @noted id) (display-call-to-note id "inactive") (display-call-to-note id))]] [:br] [:div.content {:dangerouslySetInnerHTML {:__html (:r @answer)}}] [:br]] (if-let [a @answer] [bottom-links a] [:br])]))) (defn faq-sources-select [] [:div.select [:select {:value (or (:source @(re-frame/subscribe [:filter?])) "") :tabIndex 0 :on-change (fn [e] (let [ev (.-value (.-target e))] (set-focus-on-search) (swap! global-filter merge {:query "" :source ev}) (async/go (async/>! filter-chan {:query "" :source ev}))))} [:option {:value ""} "Toutes les questions"] (for [s (distinct (map :s @(re-frame/subscribe [:faqs?])))] ^{:key (random-uuid)} [:option {:value s} (shorten-source-name s)])]]) (defn faq-sort-select [sort-type] [:div.select [:select {:value sort-type :tabIndex 0 :on-change (fn [e] (let [ev (.-value (.-target e))] (set-focus-on-search) (swap! global-filter merge {:query "" :sorting ev}) (async/go (async/>! filter-chan {:query "" :sorting ev}))))} [:option {:value ""} "Au hasard"] [:option {:value "note"} "Les mieux notées"] [:option {:value "hits"} "Les plus consultées"]]]) (defn main-page [] (let [filter @(re-frame/subscribe [:filter?]) answer-id (:faq filter) sort-type (:sorting filter)] [:div [:div.columns.is-vcentered [:input.input.column.is-6 {:id "search" :tabIndex 0 :size 20 :placeholder "Recherche" :value (or (:query @global-filter) (:query @(re-frame/subscribe [:filter?]))) :on-change (fn [e] (let [ev (.-value (.-target e)) ev-size (count ev)] (swap! global-filter merge {:query ev}) (when (or (= ev-size 0) (>= ev-size minimum-search-string-size)) (async/go (async/<! (async/timeout timeout)) (async/>! filter-chan {:query ev})))))}] [:div.column.is-3 (faq-sources-select)] [:div.column.is-2 (faq-sort-select sort-type)] [:div.column.is-1 [:a.delete.is-medium {:title "Effacer tous les filtres" :on-click #(do (rfe/push-state :home) (set-focus-on-search))}]]] [:br] (if (not-empty answer-id) (do (GET (str faq-covid-19-api-url "/hit") {:format :json :params {:token @token :id answer-id} :handler (fn [r] (prn r)) :error-handler (fn [r] (prn r))}) [display-answer answer-id]) [display-questions])])) (defn faq-with-stats [m] (map (fn [{:keys [i] :as faq}] (walk/keywordize-keys m))) (defn main-class [] (reagent/create-class {:component-did-mount (fn [] (GET (str faq-covid-19-api-url "/stats") :handler #(reset! stats (walk/keywordize-keys %))) (GET (str faq-covid-19-api-url "/token") :handler #(reset! token (or (:token (walk/keywordize-keys %)) ""))) (GET (str faq-covid-19-data-url faq-covid-19-questions) :handler #(re-frame/dispatch [:faqs! (faq-with-stats %)]))) :reagent-render #(main-page)})) (def routes [["" :home]]) (defn on-navigate [match] (re-frame/dispatch [:view! :home (:query-params match)])) (defn ^:export init [] (re-frame/clear-subscription-cache!) (re-frame/dispatch-sync [:initialize-db!]) (start-filter-loop) (rfe/start! (rf/router routes {:conflicts nil}) on-navigate {:use-fragment true}) (reagent.dom/render [main-class] (. js/document (getElementById "app"))) (set-focus-on-search))
21fbf4244415222b45cda052f2e6678dedc2442d5a7eacc18e70923a79303efc
iamaleksey/oserl
smpp_base.erl
Copyright ( C ) 2009 , %%% All rights reserved. %%% %%% Redistribution and use in source and binary forms, with or without %%% modification, are permitted provided that the following conditions are met: %%% %%% o Redistributions of source code must retain the above copyright notice, %%% this list of conditions and the following disclaimer. %%% %%% o 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. %%% %%% o Neither the name of ERLANG TRAINING AND CONSULTING nor the names of its %%% contributors may be used to endorse or promote products derived from this %%% software without specific prior written permission. %%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " %%% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR %%% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF %%% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , 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. -module(smpp_base). %%% INCLUDE FILES -include("smpp_base.hrl"). %%% STANDARD VALUES EXPORTS -export([dest_address_sme/4, dest_address_dl/2, unsuccess_sme/4]). %%% TLV VALUES EXPORTS -export([broadcast_area/2, broadcast_content_type/2, broadcast_frequency_interval/2, subaddress/2, callback_num/4, callback_num_atag/2, telematics_id/2, its_session_info/2, ms_validity_absolute/1, ms_validity_relative/3, network_error_code/2]). %%%----------------------------------------------------------------------------- %%% STANDARD VALUES EXPORTS %%%----------------------------------------------------------------------------- dest_address_sme(DestFlag, DestAddrTon, DestAddrNpi, DestAddr) -> ?DEST_ADDRESS_SME_VALUE(DestFlag, DestAddrTon, DestAddrNpi, DestAddr). dest_address_dl(DestFlag, DlName) -> ?DEST_ADDRESS_DL_VALUE(DestFlag, DlName). unsuccess_sme(DestAddrTon, DestAddrNpi, DestAddr, StatusCode) -> ?UNSUCCESS_SME_VALUE(DestAddrTon, DestAddrNpi, DestAddr, StatusCode). %%%----------------------------------------------------------------------------- %%% TLV VALUES EXPORTS %%%----------------------------------------------------------------------------- broadcast_area(Format, Details) -> ?BROADCAST_AREA_VALUE(Format, Details). broadcast_content_type(NetworkType, Service) -> ?BROADCAST_CONTENT_TYPE_VALUE(NetworkType, Service). broadcast_frequency_interval(TimeUnit, Number) -> ?BROADCAST_FREQUENCY_INTERVAL_VALUE(TimeUnit, Number). subaddress(Tag, Data) -> ?SUBADDRESS_VALUE(Tag, Data). callback_num(DigitModeIndicator, AddrTon, AddrNpi, NumberDigits) -> ?CALLBACK_NUM_VALUE(DigitModeIndicator, AddrTon, AddrNpi, NumberDigits). callback_num_atag(DataCoding, DisplayCharacters) -> ?CALLBACK_NUM_ATAG_VALUE(DataCoding, DisplayCharacters). telematics_id(ProtocolId, Reserved) -> ?TELEMATICS_ID_VALUE(ProtocolId, Reserved). its_session_info(SessionNumber, SequenceNumber) -> ?ITS_SESSION_INFO_VALUE(SessionNumber, SequenceNumber). ms_validity_absolute(Behaviour) -> ?MS_VALIDITY_ABSOLUTE_VALUE(Behaviour). ms_validity_relative(Behaviour, TimeUnit, Number) -> ?MS_VALIDITY_RELATIVE_VALUE(Behaviour, TimeUnit, Number). network_error_code(Type, Error) -> ?NETWORK_ERROR_CODE_VALUE(Type, Error).
null
https://raw.githubusercontent.com/iamaleksey/oserl/b254c68225b98384738c7a7ff9ddb53caa35c075/src/smpp_base.erl
erlang
All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: o Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. o 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. o Neither the name of ERLANG TRAINING AND CONSULTING nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 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. INCLUDE FILES STANDARD VALUES EXPORTS TLV VALUES EXPORTS ----------------------------------------------------------------------------- STANDARD VALUES EXPORTS ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- TLV VALUES EXPORTS -----------------------------------------------------------------------------
Copyright ( C ) 2009 , THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN -module(smpp_base). -include("smpp_base.hrl"). -export([dest_address_sme/4, dest_address_dl/2, unsuccess_sme/4]). -export([broadcast_area/2, broadcast_content_type/2, broadcast_frequency_interval/2, subaddress/2, callback_num/4, callback_num_atag/2, telematics_id/2, its_session_info/2, ms_validity_absolute/1, ms_validity_relative/3, network_error_code/2]). dest_address_sme(DestFlag, DestAddrTon, DestAddrNpi, DestAddr) -> ?DEST_ADDRESS_SME_VALUE(DestFlag, DestAddrTon, DestAddrNpi, DestAddr). dest_address_dl(DestFlag, DlName) -> ?DEST_ADDRESS_DL_VALUE(DestFlag, DlName). unsuccess_sme(DestAddrTon, DestAddrNpi, DestAddr, StatusCode) -> ?UNSUCCESS_SME_VALUE(DestAddrTon, DestAddrNpi, DestAddr, StatusCode). broadcast_area(Format, Details) -> ?BROADCAST_AREA_VALUE(Format, Details). broadcast_content_type(NetworkType, Service) -> ?BROADCAST_CONTENT_TYPE_VALUE(NetworkType, Service). broadcast_frequency_interval(TimeUnit, Number) -> ?BROADCAST_FREQUENCY_INTERVAL_VALUE(TimeUnit, Number). subaddress(Tag, Data) -> ?SUBADDRESS_VALUE(Tag, Data). callback_num(DigitModeIndicator, AddrTon, AddrNpi, NumberDigits) -> ?CALLBACK_NUM_VALUE(DigitModeIndicator, AddrTon, AddrNpi, NumberDigits). callback_num_atag(DataCoding, DisplayCharacters) -> ?CALLBACK_NUM_ATAG_VALUE(DataCoding, DisplayCharacters). telematics_id(ProtocolId, Reserved) -> ?TELEMATICS_ID_VALUE(ProtocolId, Reserved). its_session_info(SessionNumber, SequenceNumber) -> ?ITS_SESSION_INFO_VALUE(SessionNumber, SequenceNumber). ms_validity_absolute(Behaviour) -> ?MS_VALIDITY_ABSOLUTE_VALUE(Behaviour). ms_validity_relative(Behaviour, TimeUnit, Number) -> ?MS_VALIDITY_RELATIVE_VALUE(Behaviour, TimeUnit, Number). network_error_code(Type, Error) -> ?NETWORK_ERROR_CODE_VALUE(Type, Error).
c4860e5fe631f6f61c297d0cfc367ec5b4940f768126b2b0529cb58efdcd8e55
RyanGlScott/text-show-instances
Scientific.hs
{-# OPTIONS -Wno-orphans #-} module TextShow.Data.Scientific () where import Data.Scientific import Data.Text.Lazy.Builder.Scientific ( scientificBuilder ) import TextShow instance TextShow Scientific where showbPrec d s | coefficient s < 0 = showbParen (d > prefixMinusPrec) (scientificBuilder s) | otherwise = scientificBuilder s where prefixMinusPrec :: Int prefixMinusPrec = 6
null
https://raw.githubusercontent.com/RyanGlScott/text-show-instances/b08f4b46466cdc3c3f3c979b7a0abf5590fa2916/src/TextShow/Data/Scientific.hs
haskell
# OPTIONS -Wno-orphans #
module TextShow.Data.Scientific () where import Data.Scientific import Data.Text.Lazy.Builder.Scientific ( scientificBuilder ) import TextShow instance TextShow Scientific where showbPrec d s | coefficient s < 0 = showbParen (d > prefixMinusPrec) (scientificBuilder s) | otherwise = scientificBuilder s where prefixMinusPrec :: Int prefixMinusPrec = 6
b17121d4ea766f90d44544f5440c3ad364a6fbc1368ac38b31301af94f7fb53e
valerauko/gitegylet-electron
db.cljs
(ns gitegylet.commits.db) (defn commit->map [commit] (let [parents (js->clj (.-parents commit)) commit-id (.-id commit)] {:id commit-id :author (let [author (.-author commit)] {:name (.-name author) :email (.-email author) :md5 (.-md5 author)}) :time (.-timestamp commit) :parents parents :message (.-message commit) :summary (.-summary commit) :column (.-column commit)}))
null
https://raw.githubusercontent.com/valerauko/gitegylet-electron/bee01d4e70f3f1e8636bf82c0d1a78c3d640c1b7/src/cljs/gitegylet/commits/db.cljs
clojure
(ns gitegylet.commits.db) (defn commit->map [commit] (let [parents (js->clj (.-parents commit)) commit-id (.-id commit)] {:id commit-id :author (let [author (.-author commit)] {:name (.-name author) :email (.-email author) :md5 (.-md5 author)}) :time (.-timestamp commit) :parents parents :message (.-message commit) :summary (.-summary commit) :column (.-column commit)}))
d3401c8f8d30adb7ee2485697d3bff3ffc729415df7633b66a41744e59385c43
pyr/net
engine.clj
(ns webfile.engine (:require [com.stuartsierra.component :as component] [clojure.core.async :as a] [net.ty.buffer :as buf] [clojure.string :refer [join]] [clojure.tools.logging :refer [info]]) (:import java.nio.file.StandardOpenOption java.nio.file.OpenOption java.nio.file.FileSystem java.nio.ByteBuffer java.nio.channels.Channel io.netty.buffer.ByteBufHolder io.netty.buffer.ByteBuf java.nio.channels.FileChannel)) (def fs (delay (java.nio.file.FileSystems/getDefault))) (def open-options (into-array OpenOption [StandardOpenOption/WRITE StandardOpenOption/CREATE StandardOpenOption/TRUNCATE_EXISTING])) (def empty-response {:status 200 :headers {"Connection" "close" "Content-Length" "0"} :body ""}) (defn content-response [status content] {:status status :headers {"Connection" "close" "Content-Length" (str (count content))} :body content}) (defn path-for [root & elems] (.getPath ^FileSystem @fs root (into-array String [(join "-" elems)]))) (defn write-buf [root uri i http-content] (let [path (path-for root uri (format "%02d" i)) chan (FileChannel/open path open-options)] (.write chan (buf/nio-buffer (buf/as-buffer http-content))) (.close chan)) (inc i)) (defn body-for [uri] (cond (re-find #"(?i)stream" uri) {:status 200 :headers {:transfer-encoding "chunked" :connection "close"} :body (let [body (a/chan)] (a/go (dotimes [i 5] (a/<! (a/timeout 1000)) (a/>! body "foobar\n")) (a/close! body)) body)} (re-find #"(?i)delay" uri) (a/go (a/<! (a/timeout 3000)) {:status 200 :headers {:connection "close"} :body "sorry, running late!\n"}) :else {:status 200 :headers {:connection "close"} :body "A standard body\n"})) (defmulti handle-operation (fn [_ op _ _] op)) (defmethod handle-operation :get [_ _ uri _] (body-for uri)) (defmethod handle-operation :put [{:keys [root]} _ uri body] (a/go (loop [i 0] (if-let [http-content (a/<! body)] (recur (write-buf root uri i http-content)) empty-response)))) (defmethod handle-operation :default [& _] (content-response 400 "no such operation")) (defrecord StoreEngine [root] component/Lifecycle (start [this] this) (stop [this] this)) (defn make-engine [root] (map->StoreEngine {:root root}))
null
https://raw.githubusercontent.com/pyr/net/a2120bf61b6fd480707ea6b217545b3d640288d0/examples/webfile/engine.clj
clojure
(ns webfile.engine (:require [com.stuartsierra.component :as component] [clojure.core.async :as a] [net.ty.buffer :as buf] [clojure.string :refer [join]] [clojure.tools.logging :refer [info]]) (:import java.nio.file.StandardOpenOption java.nio.file.OpenOption java.nio.file.FileSystem java.nio.ByteBuffer java.nio.channels.Channel io.netty.buffer.ByteBufHolder io.netty.buffer.ByteBuf java.nio.channels.FileChannel)) (def fs (delay (java.nio.file.FileSystems/getDefault))) (def open-options (into-array OpenOption [StandardOpenOption/WRITE StandardOpenOption/CREATE StandardOpenOption/TRUNCATE_EXISTING])) (def empty-response {:status 200 :headers {"Connection" "close" "Content-Length" "0"} :body ""}) (defn content-response [status content] {:status status :headers {"Connection" "close" "Content-Length" (str (count content))} :body content}) (defn path-for [root & elems] (.getPath ^FileSystem @fs root (into-array String [(join "-" elems)]))) (defn write-buf [root uri i http-content] (let [path (path-for root uri (format "%02d" i)) chan (FileChannel/open path open-options)] (.write chan (buf/nio-buffer (buf/as-buffer http-content))) (.close chan)) (inc i)) (defn body-for [uri] (cond (re-find #"(?i)stream" uri) {:status 200 :headers {:transfer-encoding "chunked" :connection "close"} :body (let [body (a/chan)] (a/go (dotimes [i 5] (a/<! (a/timeout 1000)) (a/>! body "foobar\n")) (a/close! body)) body)} (re-find #"(?i)delay" uri) (a/go (a/<! (a/timeout 3000)) {:status 200 :headers {:connection "close"} :body "sorry, running late!\n"}) :else {:status 200 :headers {:connection "close"} :body "A standard body\n"})) (defmulti handle-operation (fn [_ op _ _] op)) (defmethod handle-operation :get [_ _ uri _] (body-for uri)) (defmethod handle-operation :put [{:keys [root]} _ uri body] (a/go (loop [i 0] (if-let [http-content (a/<! body)] (recur (write-buf root uri i http-content)) empty-response)))) (defmethod handle-operation :default [& _] (content-response 400 "no such operation")) (defrecord StoreEngine [root] component/Lifecycle (start [this] this) (stop [this] this)) (defn make-engine [root] (map->StoreEngine {:root root}))
f72287f667f495a6679ff4483616c0385f1e7ab6c45a5dd121c0f33f19bd1d16
spurious/chibi-scheme-mirror
server-util.scm
(define (get-host uri headers) (cond ((assq 'host headers) => (lambda (x) (let ((s (string-trim (cdr x)))) (substring-cursor s 0 (string-find s #\:))))) ((uri-host uri)) (else "localhost"))) (define (line-handler handler) (lambda (in out sock addr) (let ((line (read-line in))) (if (eof-object? line) #f (handler line in out sock addr))))) (define (parse-command line) (let ((ls (string-split line #\space))) (cons (string->symbol (car ls)) (cdr ls)))) (define (command-handler handler) (line-handler (cond ((hash-table? handler) (lambda (line in out sock addr) (let ((ls (parse-command line))) (cond ((hash-table-ref/default handler (car ls)) => (lambda (handler) (handler (car ls) (cdr ls) in out sock addr))))))) ((list? handler) (lambda (line in out sock addr) (let ((ls (parse-command line))) (cond ((assq (car ls) handler) => (lambda (cell) ((cdr cell) (car ls) (cdr ls) in out sock addr))))))) ((procedure? handler) (lambda (line in out sock addr) (let ((ls (parse-command line))) (handler (car ls) (cdr ls) in out sock addr)))) (else (error "invalid handler" handler))))) (define (load-mime-types ht file) (protect (exn (else (display "couldn't load mime types from " (current-error-port)) (write file (current-error-port)) (newline (current-error-port)) (print-exception exn))) (call-with-input-file file (lambda (in) (let lp () (let ((line (read-line in))) (cond ((not (eof-object? line)) (let ((ls (string-split (cond ((string-find line #\#) => (lambda (i) (substring line 0 i))) (else line))))) (if (and (pair? ls) (pair? (cdr ls))) (for-each (lambda (x) (hash-table-set! ht (string->symbol x) (car ls))) (cdr ls))) (lp)))))))))) (define file-mime-type (let ((ext-types #f)) (lambda (file . o) set mime types on first use (if (not ext-types) (let ((ht (make-hash-table eq?))) (cond ((any file-exists? '("/etc/mime.types" "/etc/httpd/mime.types" "/etc/apache2/mime.types")) => (lambda (file) (load-mime-types ht file)))) (set! ext-types ht))) (let* ((ext (path-extension file)) (mtype (or (and ext (hash-table-ref/default ext-types (string->symbol (string-downcase-ascii ext)) #f)) "application/octet-stream"))) ;; TODO: auto-detect charset (if (equal? mtype "text/html") (string-append mtype "; charset=UTF-8") mtype))))) (define (call-with-temp-file template proc) (let ((base (string-append "/tmp/" (path-strip-extension template) "-" (number->string (current-process-id)) "-" (number->string (round (current-seconds))) "-")) (ext (path-extension template))) (let lp ((i 0)) (let ((path (string-append base (number->string i) "." ext))) (cond ((> i 100) ;; give up after too many tries regardless (error "Repeatedly failed to generate temp file in /tmp")) ((file-exists? path) (lp (+ i 1))) (else (let ((fd (open path (bitwise-ior open/write open/create open/exclusive)))) (if (not fd) (if (file-exists? path) ;; created between test and open (lp (+ i 1)) (error "Couldn't generate temp file in /tmp " path)) (let* ((out (open-output-file-descriptor fd #o700)) (res (proc path out))) (close-output-port out) (delete-file path) res)))))))))
null
https://raw.githubusercontent.com/spurious/chibi-scheme-mirror/49168ab073f64a95c834b5f584a9aaea3469594d/lib/chibi/net/server-util.scm
scheme
TODO: auto-detect charset give up after too many tries regardless created between test and open
(define (get-host uri headers) (cond ((assq 'host headers) => (lambda (x) (let ((s (string-trim (cdr x)))) (substring-cursor s 0 (string-find s #\:))))) ((uri-host uri)) (else "localhost"))) (define (line-handler handler) (lambda (in out sock addr) (let ((line (read-line in))) (if (eof-object? line) #f (handler line in out sock addr))))) (define (parse-command line) (let ((ls (string-split line #\space))) (cons (string->symbol (car ls)) (cdr ls)))) (define (command-handler handler) (line-handler (cond ((hash-table? handler) (lambda (line in out sock addr) (let ((ls (parse-command line))) (cond ((hash-table-ref/default handler (car ls)) => (lambda (handler) (handler (car ls) (cdr ls) in out sock addr))))))) ((list? handler) (lambda (line in out sock addr) (let ((ls (parse-command line))) (cond ((assq (car ls) handler) => (lambda (cell) ((cdr cell) (car ls) (cdr ls) in out sock addr))))))) ((procedure? handler) (lambda (line in out sock addr) (let ((ls (parse-command line))) (handler (car ls) (cdr ls) in out sock addr)))) (else (error "invalid handler" handler))))) (define (load-mime-types ht file) (protect (exn (else (display "couldn't load mime types from " (current-error-port)) (write file (current-error-port)) (newline (current-error-port)) (print-exception exn))) (call-with-input-file file (lambda (in) (let lp () (let ((line (read-line in))) (cond ((not (eof-object? line)) (let ((ls (string-split (cond ((string-find line #\#) => (lambda (i) (substring line 0 i))) (else line))))) (if (and (pair? ls) (pair? (cdr ls))) (for-each (lambda (x) (hash-table-set! ht (string->symbol x) (car ls))) (cdr ls))) (lp)))))))))) (define file-mime-type (let ((ext-types #f)) (lambda (file . o) set mime types on first use (if (not ext-types) (let ((ht (make-hash-table eq?))) (cond ((any file-exists? '("/etc/mime.types" "/etc/httpd/mime.types" "/etc/apache2/mime.types")) => (lambda (file) (load-mime-types ht file)))) (set! ext-types ht))) (let* ((ext (path-extension file)) (mtype (or (and ext (hash-table-ref/default ext-types (string->symbol (string-downcase-ascii ext)) #f)) "application/octet-stream"))) (if (equal? mtype "text/html") (string-append mtype "; charset=UTF-8") mtype))))) (define (call-with-temp-file template proc) (let ((base (string-append "/tmp/" (path-strip-extension template) "-" (number->string (current-process-id)) "-" (number->string (round (current-seconds))) "-")) (ext (path-extension template))) (let lp ((i 0)) (let ((path (string-append base (number->string i) "." ext))) (cond (error "Repeatedly failed to generate temp file in /tmp")) ((file-exists? path) (lp (+ i 1))) (else (let ((fd (open path (bitwise-ior open/write open/create open/exclusive)))) (if (not fd) (lp (+ i 1)) (error "Couldn't generate temp file in /tmp " path)) (let* ((out (open-output-file-descriptor fd #o700)) (res (proc path out))) (close-output-port out) (delete-file path) res)))))))))
b8b4bee6d2df64925e2dad1f91ecd7554e5541dc97b393ae5dd3f2aa7de1c80d
AdaCore/why3
opt.mli
(********************************************************************) (* *) The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2022 -- Inria - CNRS - Paris - Saclay University (* *) (* This software is distributed under the terms of the GNU Lesser *) General Public License version 2.1 , with the special exception (* on linking described in file LICENSE. *) (* *) (********************************************************************) (** {1 Combinators on [option] type} *) val inhabited : 'a option -> bool val get : 'a option -> 'a val get_exn : exn -> 'a option -> 'a val get_def : 'a -> 'a option -> 'a val map : ('a -> 'b) -> 'a option -> 'b option val iter : ('a -> unit) -> 'a option -> unit val apply : 'b -> ('a -> 'b) option -> 'a -> 'b val apply2 : 'c -> ('a -> 'b -> 'c) option -> 'a -> 'b -> 'c val fold : ('b -> 'a -> 'b) -> 'b -> 'a option -> 'b (** [fold f d o] returns [d] if [o] is [None], and [f d x] if [o] is [Some x] *) val fold_right : ('a -> 'b -> 'b) -> 'a option -> 'b -> 'b val map2 : ('a -> 'b -> 'c) -> 'a option -> 'b option -> 'c option val equal : ('a -> 'b -> bool) -> 'a option -> 'b option -> bool val compare : ('a -> 'b -> int) -> 'a option -> 'b option -> int val map_fold : ('a -> 'b -> 'a * 'b) -> 'a -> 'b option -> 'a * 'b option val for_all : ('a -> bool) -> 'a option -> bool val bind : 'a option -> ('a -> 'b option) -> 'b option val exists : ('a -> bool) -> 'a option -> bool
null
https://raw.githubusercontent.com/AdaCore/why3/be1023970d48869285e68f12d32858c3383958e0/src/util/opt.mli
ocaml
****************************************************************** This software is distributed under the terms of the GNU Lesser on linking described in file LICENSE. ****************************************************************** * {1 Combinators on [option] type} * [fold f d o] returns [d] if [o] is [None], and [f d x] if [o] is [Some x]
The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2022 -- Inria - CNRS - Paris - Saclay University General Public License version 2.1 , with the special exception val inhabited : 'a option -> bool val get : 'a option -> 'a val get_exn : exn -> 'a option -> 'a val get_def : 'a -> 'a option -> 'a val map : ('a -> 'b) -> 'a option -> 'b option val iter : ('a -> unit) -> 'a option -> unit val apply : 'b -> ('a -> 'b) option -> 'a -> 'b val apply2 : 'c -> ('a -> 'b -> 'c) option -> 'a -> 'b -> 'c val fold : ('b -> 'a -> 'b) -> 'b -> 'a option -> 'b val fold_right : ('a -> 'b -> 'b) -> 'a option -> 'b -> 'b val map2 : ('a -> 'b -> 'c) -> 'a option -> 'b option -> 'c option val equal : ('a -> 'b -> bool) -> 'a option -> 'b option -> bool val compare : ('a -> 'b -> int) -> 'a option -> 'b option -> int val map_fold : ('a -> 'b -> 'a * 'b) -> 'a -> 'b option -> 'a * 'b option val for_all : ('a -> bool) -> 'a option -> bool val bind : 'a option -> ('a -> 'b option) -> 'b option val exists : ('a -> bool) -> 'a option -> bool
faa6af051e4ecdda577981691ff72ffd22a171c7dd6d51fc3e9e4ac7d1d095bb
reagent-project/reagent
project.clj
(defproject simple-reagent "0.6.0" :dependencies [[org.clojure/clojure "1.10.1"] [org.clojure/clojurescript "1.10.597"] [reagent "0.10.0"] [figwheel "0.5.19"]] :plugins [[lein-cljsbuild "1.1.7"] [lein-figwheel "0.5.19"]] :resource-paths ["resources" "target"] :clean-targets ^{:protect false} [:target-path] :profiles {:dev {:cljsbuild {:builds {:client {:figwheel {:on-jsload "simpleexample.core/run"} :compiler {:main "simpleexample.core" :optimizations :none}}}}} :prod {:cljsbuild {:builds {:client {:compiler {:optimizations :advanced :elide-asserts true :pretty-print false}}}}}} :figwheel {:repl false :http-server-root "public"} :cljsbuild {:builds {:client {:source-paths ["src"] :compiler {:output-dir "target/public/client" :asset-path "client" :output-to "target/public/client.js"}}}})
null
https://raw.githubusercontent.com/reagent-project/reagent/c214466bbcf099eafdfe28ff7cb91f99670a8433/examples/simple/project.clj
clojure
(defproject simple-reagent "0.6.0" :dependencies [[org.clojure/clojure "1.10.1"] [org.clojure/clojurescript "1.10.597"] [reagent "0.10.0"] [figwheel "0.5.19"]] :plugins [[lein-cljsbuild "1.1.7"] [lein-figwheel "0.5.19"]] :resource-paths ["resources" "target"] :clean-targets ^{:protect false} [:target-path] :profiles {:dev {:cljsbuild {:builds {:client {:figwheel {:on-jsload "simpleexample.core/run"} :compiler {:main "simpleexample.core" :optimizations :none}}}}} :prod {:cljsbuild {:builds {:client {:compiler {:optimizations :advanced :elide-asserts true :pretty-print false}}}}}} :figwheel {:repl false :http-server-root "public"} :cljsbuild {:builds {:client {:source-paths ["src"] :compiler {:output-dir "target/public/client" :asset-path "client" :output-to "target/public/client.js"}}}})
9c616952d1e8b121a4c698a9a9d397a9c6355f1c7062fc06f2d2acf9d53b88f5
justone/bb-scripts
ftime.clj
(ns ftime (:require [clojure.tools.cli :refer [parse-opts]] [lib.opts :as opts] [lib.time :as time]) (:gen-class)) (def progname "ftime") (def cli-options [["-f" "--format FORMAT" "Format to use to print the time" :default "datetime"] ["-z" "--timezone ZONE" "Timezone to use" :default "America/Los_Angeles"] ["-h" "--help"]]) (defn process [millis options] (let [{:keys [format timezone]} options] (-> (time/millis->datetime millis timezone) (time/format-datetime format)))) (defn -main [& args] (let [parsed (parse-opts args cli-options) {:keys [options arguments]} parsed] (or (some->> (opts/find-errors parsed) (opts/print-errors progname parsed) (System/exit)) (-> (process (or (some-> arguments first Long.) (time/now-millis)) options) (println)))))
null
https://raw.githubusercontent.com/justone/bb-scripts/9720711e0bc82874e534e49b98b5c16262528d45/src/ftime.clj
clojure
(ns ftime (:require [clojure.tools.cli :refer [parse-opts]] [lib.opts :as opts] [lib.time :as time]) (:gen-class)) (def progname "ftime") (def cli-options [["-f" "--format FORMAT" "Format to use to print the time" :default "datetime"] ["-z" "--timezone ZONE" "Timezone to use" :default "America/Los_Angeles"] ["-h" "--help"]]) (defn process [millis options] (let [{:keys [format timezone]} options] (-> (time/millis->datetime millis timezone) (time/format-datetime format)))) (defn -main [& args] (let [parsed (parse-opts args cli-options) {:keys [options arguments]} parsed] (or (some->> (opts/find-errors parsed) (opts/print-errors progname parsed) (System/exit)) (-> (process (or (some-> arguments first Long.) (time/now-millis)) options) (println)))))
8368f6bc6ab9d7c98cb8dec10be356f08213d08b19d75188c1fedc10750442df
tfausak/argo
Decoder.hs
module Argo.Internal.Type.Decoder where import qualified Argo.Internal.Literal as Literal import qualified Argo.Vendor.ByteString as ByteString import qualified Argo.Vendor.Transformers as Trans import qualified Control.Applicative as Applicative import qualified Control.Monad as Monad import qualified Data.Functor.Identity as Identity import qualified Data.Word as Word type Decoder = Trans.StateT ByteString.ByteString (Trans.ExceptT String Identity.Identity) unwrap :: Decoder a -> ByteString.ByteString -> Either String (a, ByteString.ByteString) unwrap d = Identity.runIdentity . Trans.runExceptT . Trans.runStateT d run :: Decoder a -> ByteString.ByteString -> Either String a run d = fmap fst . unwrap (d <* eof) list :: Decoder a -> Decoder [a] list f = listWith f [] listWith :: Decoder a -> [a] -> Decoder [a] listWith f xs = do m <- Applicative.optional $ do Monad.unless (null xs) $ do word8 Literal.comma spaces f case m of Nothing -> pure $ reverse xs Just x -> listWith f $ x : xs byteString :: ByteString.ByteString -> Decoder () byteString x = do b1 <- Trans.get case ByteString.stripPrefix x b1 of Nothing -> Trans.lift . Trans.throwE $ "byteString: " <> show x Just b2 -> Trans.put b2 dropWhile :: (Word.Word8 -> Bool) -> Decoder () dropWhile f = do b <- Trans.get Trans.put $ ByteString.dropWhile f b eof :: Decoder () eof = do b <- Trans.get Monad.unless (ByteString.null b) . Trans.lift $ Trans.throwE "eof" isDigit :: Word.Word8 -> Bool isDigit x = Literal.digitZero <= x && x <= Literal.digitNine isSpace :: Word.Word8 -> Bool isSpace x = (x == Literal.space) || (x == Literal.horizontalTabulation) || (x == Literal.newLine) || (x == Literal.carriageReturn) satisfy :: (Word.Word8 -> Bool) -> Decoder Word.Word8 satisfy f = do b1 <- Trans.get case ByteString.uncons b1 of Just (x, b2) | f x -> do Trans.put b2 pure x _ -> Trans.lift $ Trans.throwE "satisfy" spaces :: Decoder () spaces = Argo.Internal.Type.Decoder.dropWhile isSpace takeWhile :: (Word.Word8 -> Bool) -> Decoder ByteString.ByteString takeWhile f = do b1 <- Trans.get let (x, b2) = ByteString.span f b1 Trans.put b2 pure x takeWhile1 :: (Word.Word8 -> Bool) -> Decoder ByteString.ByteString takeWhile1 f = do x <- Argo.Internal.Type.Decoder.takeWhile f Monad.when (ByteString.null x) . Trans.lift $ Trans.throwE "takeWhile1" pure x word8 :: Word.Word8 -> Decoder () word8 = Monad.void . satisfy . (==)
null
https://raw.githubusercontent.com/tfausak/argo/2e225c671dec9d4991864de8faed48acf4789192/source/library/Argo/Internal/Type/Decoder.hs
haskell
module Argo.Internal.Type.Decoder where import qualified Argo.Internal.Literal as Literal import qualified Argo.Vendor.ByteString as ByteString import qualified Argo.Vendor.Transformers as Trans import qualified Control.Applicative as Applicative import qualified Control.Monad as Monad import qualified Data.Functor.Identity as Identity import qualified Data.Word as Word type Decoder = Trans.StateT ByteString.ByteString (Trans.ExceptT String Identity.Identity) unwrap :: Decoder a -> ByteString.ByteString -> Either String (a, ByteString.ByteString) unwrap d = Identity.runIdentity . Trans.runExceptT . Trans.runStateT d run :: Decoder a -> ByteString.ByteString -> Either String a run d = fmap fst . unwrap (d <* eof) list :: Decoder a -> Decoder [a] list f = listWith f [] listWith :: Decoder a -> [a] -> Decoder [a] listWith f xs = do m <- Applicative.optional $ do Monad.unless (null xs) $ do word8 Literal.comma spaces f case m of Nothing -> pure $ reverse xs Just x -> listWith f $ x : xs byteString :: ByteString.ByteString -> Decoder () byteString x = do b1 <- Trans.get case ByteString.stripPrefix x b1 of Nothing -> Trans.lift . Trans.throwE $ "byteString: " <> show x Just b2 -> Trans.put b2 dropWhile :: (Word.Word8 -> Bool) -> Decoder () dropWhile f = do b <- Trans.get Trans.put $ ByteString.dropWhile f b eof :: Decoder () eof = do b <- Trans.get Monad.unless (ByteString.null b) . Trans.lift $ Trans.throwE "eof" isDigit :: Word.Word8 -> Bool isDigit x = Literal.digitZero <= x && x <= Literal.digitNine isSpace :: Word.Word8 -> Bool isSpace x = (x == Literal.space) || (x == Literal.horizontalTabulation) || (x == Literal.newLine) || (x == Literal.carriageReturn) satisfy :: (Word.Word8 -> Bool) -> Decoder Word.Word8 satisfy f = do b1 <- Trans.get case ByteString.uncons b1 of Just (x, b2) | f x -> do Trans.put b2 pure x _ -> Trans.lift $ Trans.throwE "satisfy" spaces :: Decoder () spaces = Argo.Internal.Type.Decoder.dropWhile isSpace takeWhile :: (Word.Word8 -> Bool) -> Decoder ByteString.ByteString takeWhile f = do b1 <- Trans.get let (x, b2) = ByteString.span f b1 Trans.put b2 pure x takeWhile1 :: (Word.Word8 -> Bool) -> Decoder ByteString.ByteString takeWhile1 f = do x <- Argo.Internal.Type.Decoder.takeWhile f Monad.when (ByteString.null x) . Trans.lift $ Trans.throwE "takeWhile1" pure x word8 :: Word.Word8 -> Decoder () word8 = Monad.void . satisfy . (==)
2879ffef0a1cab6b7ef9c4a7dd99a36b64f62c83c8b480a02396aed174423205
mwunsch/overscan
clock.rkt
#lang racket/base (require ffi/unsafe/introspection racket/class racket/contract gstreamer/gst) (provide (contract-out [clock% (class/c [get-time (->m clock-time?)])] [clock-time? (-> any/c boolean?)] [clock-time-none clock-time?] [time-as-seconds (-> clock-time? exact-integer?)] [time-as-milliseconds (-> clock-time? exact-integer?)] [time-as-microseconds (-> clock-time? exact-integer?)] [clock-diff (-> clock-time? clock-time? clock-time?)])) (define clock-mixin (make-gobject-delegate get-time)) (define clock% (class (clock-mixin gst-object%) (super-new) (inherit-field pointer))) (define clock-time? exact-integer?) (define clock-time-none ((gst 'CLOCK_TIME_NONE))) (define second ((gst 'SECOND))) (define nanosecond ((gst 'NSECOND))) (define microsecond ((gst 'USECOND))) (define (time-as-seconds t) (quotient t second)) (define (time-as-milliseconds t) (quotient t 1000000)) (define (time-as-microseconds t) (quotient t microsecond)) (define (clock-diff s e) (- e s))
null
https://raw.githubusercontent.com/mwunsch/overscan/f198e6b4c1f64cf5720e66ab5ad27fdc4b9e67e9/gstreamer/clock.rkt
racket
#lang racket/base (require ffi/unsafe/introspection racket/class racket/contract gstreamer/gst) (provide (contract-out [clock% (class/c [get-time (->m clock-time?)])] [clock-time? (-> any/c boolean?)] [clock-time-none clock-time?] [time-as-seconds (-> clock-time? exact-integer?)] [time-as-milliseconds (-> clock-time? exact-integer?)] [time-as-microseconds (-> clock-time? exact-integer?)] [clock-diff (-> clock-time? clock-time? clock-time?)])) (define clock-mixin (make-gobject-delegate get-time)) (define clock% (class (clock-mixin gst-object%) (super-new) (inherit-field pointer))) (define clock-time? exact-integer?) (define clock-time-none ((gst 'CLOCK_TIME_NONE))) (define second ((gst 'SECOND))) (define nanosecond ((gst 'NSECOND))) (define microsecond ((gst 'USECOND))) (define (time-as-seconds t) (quotient t second)) (define (time-as-milliseconds t) (quotient t 1000000)) (define (time-as-microseconds t) (quotient t microsecond)) (define (clock-diff s e) (- e s))
f14a01aedae0307544e2c45455df92edf433290535695e5b87b4ece6c9aa4a6b
ocaml-sf/learn-ocaml-corpus
product_bizarre.ml
(* Basic constructor functions. *) let empty : 'a enum = fun _s -> Seq.empty let just (x : 'a) : 'a enum = fun s -> if s = 0 then Seq.singleton x else Seq.empty let pay (enum : 'a enum) : 'a enum = fun s -> (* Treating [s = 0] as a special case is required, because we have asked the student to guarantee that every size argument [s] ever passed to an enumeration is nonnegative. *) if s = 0 then Seq.empty else enum (s-1) let sum (enum1 : 'a enum) (enum2 : 'a enum) : 'a enum = fun s -> Seq.sum (enum1 s) (enum2 s) let ( ++ ) = sum let rec up i j = if i <= j then i :: up (i + 1) j else [] let product (enum1 : 'a enum) (enum2 : 'b enum) : ('a * 'b) enum = fun s -> Seq.bigsum ( List.map (fun s1 -> let s2 = s - s1 in Seq.product (enum1 s1) (enum2 s1) (* wrong *) ) (up 0 s) )
null
https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/fpottier/enumerating_trees/wrong/product_bizarre.ml
ocaml
Basic constructor functions. Treating [s = 0] as a special case is required, because we have asked the student to guarantee that every size argument [s] ever passed to an enumeration is nonnegative. wrong
let empty : 'a enum = fun _s -> Seq.empty let just (x : 'a) : 'a enum = fun s -> if s = 0 then Seq.singleton x else Seq.empty let pay (enum : 'a enum) : 'a enum = fun s -> if s = 0 then Seq.empty else enum (s-1) let sum (enum1 : 'a enum) (enum2 : 'a enum) : 'a enum = fun s -> Seq.sum (enum1 s) (enum2 s) let ( ++ ) = sum let rec up i j = if i <= j then i :: up (i + 1) j else [] let product (enum1 : 'a enum) (enum2 : 'b enum) : ('a * 'b) enum = fun s -> Seq.bigsum ( List.map (fun s1 -> let s2 = s - s1 in ) (up 0 s) )
6dcbc0d89126bef0aa22c7ad9f07e0518495a2ba58f8854fac95de8e7ab49812
cartazio/language-c
ConstEval.hs
# LANGUAGE RelaxedPolyRec # module Language.C.Analysis.ConstEval where import Control.Monad import Data.Bits import Data.Maybe import qualified Data.Map as Map import Language.C.Syntax.AST import Language.C.Syntax.Constants import {-# SOURCE #-} Language.C.Analysis.AstAnalysis (tExpr, ExprSide(..)) import Language.C.Analysis.Debug import Language.C.Analysis.DeclAnalysis import Language.C.Analysis.DefTable import Language.C.Data import Language.C.Pretty import Language.C.Analysis.SemRep import Language.C.Analysis.TravMonad import Language.C.Analysis.TypeUtils import Text.PrettyPrint.HughesPJ data MachineDesc = MachineDesc { iSize :: IntType -> Integer , fSize :: FloatType -> Integer , builtinSize :: BuiltinType -> Integer , ptrSize :: Integer , voidSize :: Integer , iAlign :: IntType -> Integer , fAlign :: FloatType -> Integer , builtinAlign :: BuiltinType -> Integer , ptrAlign :: Integer , voidAlign :: Integer } intExpr :: (Pos n, MonadName m) => n -> Integer -> m CExpr intExpr n i = genName >>= \name -> return $ CConst $ CIntConst (cInteger i) (mkNodeInfo (posOf n) name) sizeofType :: (MonadTrav m, CNode n) => MachineDesc -> n -> Type -> m Integer sizeofType md _ (DirectType TyVoid _ _) = return $ voidSize md sizeofType md _ (DirectType (TyIntegral it) _ _) = return $ iSize md it sizeofType md _ (DirectType (TyFloating ft) _ _) = return $ fSize md ft sizeofType md _ (DirectType (TyComplex ft) _ _) = return $ 2 * fSize md ft sizeofType md _ (DirectType (TyComp ctr) _ _) = compSize md ctr sizeofType md _ (DirectType (TyEnum _) _ _) = return $ iSize md TyInt sizeofType md _ (DirectType (TyBuiltin b) _ _) = return $ builtinSize md b sizeofType md _ (PtrType _ _ _) = return $ ptrSize md sizeofType md n (ArrayType bt (UnknownArraySize _) _ _) = return $ ptrSize md sizeofType md n (ArrayType bt (ArraySize _ sz) _ _) = do sz' <- constEval md Map.empty sz case sz' of CConst (CIntConst i _) -> do s <- sizeofType md n bt return $ getCInteger i * s _ -> return $ ptrSize md {- astError (nodeInfo sz) $ "array size is not a constant: " ++ (render . pretty) sz -} sizeofType md n (TypeDefType (TypeDefRef _ (Just t) _) _ _) = sizeofType md n t sizeofType md _ (FunctionType _ _) = return $ ptrSize md sizeofType _ n t = astError (nodeInfo n) $ "can't find size of type: " ++ (render . pretty) t alignofType :: (MonadTrav m, CNode n) => MachineDesc -> n -> Type -> m Integer alignofType md _ (DirectType TyVoid _ _) = return $ voidAlign md alignofType md _ (DirectType (TyIntegral it) _ _) = return $ iAlign md it alignofType md _ (DirectType (TyFloating ft) _ _) = return $ fAlign md ft alignofType md _ (DirectType (TyComplex ft) _ _) = return $ fAlign md ft alignofType md _ (DirectType (TyEnum _) _ _) = return $ iAlign md TyInt alignofType md _ (DirectType (TyBuiltin b) _ _) = return $ builtinAlign md b alignofType md _ (PtrType _ _ _) = return $ ptrAlign md alignofType md n (ArrayType bt (UnknownArraySize _) _ _) = return $ ptrAlign md alignofType md n (ArrayType bt (ArraySize _ sz) _ _) = alignofType md n bt alignofType md n (TypeDefType (TypeDefRef _ (Just t) _) _ _) = alignofType md n t alignofType _ n t = astError (nodeInfo n) $ "can't find alignment of type: " ++ (render . pretty) t compSize :: MonadTrav m => MachineDesc -> CompTypeRef -> m Integer compSize md ctr = do dt <- getDefTable case lookupTag (sueRef ctr) dt of Just (Left _) -> astError (nodeInfo ctr) "composite declared but not defined" Just (Right (CompDef (CompType _ tag ms _ ni))) -> do let ts = map declType ms sizes <- mapM (sizeofType md ni) ts -- XXX: handle padding case tag of StructTag -> return $ sum sizes UnionTag -> return $ maximum sizes Just (Right (EnumDef _)) -> return $ iSize md TyInt Nothing -> astError (nodeInfo ctr) "unknown composite" {- Expression evaluation -} -- Use the withWordBytes function to wrap the results around to the -- correct word size intOp :: CBinaryOp -> Integer -> Integer -> Integer intOp CAddOp i1 i2 = i1 + i2 intOp CSubOp i1 i2 = i1 - i2 intOp CMulOp i1 i2 = i1 * i2 intOp CDivOp i1 i2 = i1 `div` i2 intOp CRmdOp i1 i2 = i1 `mod` i2 intOp CShlOp i1 i2 = i1 `shiftL` fromInteger i2 intOp CShrOp i1 i2 = i1 `shiftR` fromInteger i2 intOp CLeOp i1 i2 = toInteger $ fromEnum $ i1 < i2 intOp CGrOp i1 i2 = toInteger $ fromEnum $ i1 > i2 intOp CLeqOp i1 i2 = toInteger $ fromEnum $ i1 <= i2 intOp CGeqOp i1 i2 = toInteger $ fromEnum $ i1 >= i2 intOp CEqOp i1 i2 = toInteger $ fromEnum $ i1 == i2 intOp CNeqOp i1 i2 = toInteger $ fromEnum $ i1 /= i2 intOp CAndOp i1 i2 = i1 .&. i2 intOp CXorOp i1 i2 = i1 `xor` i2 intOp COrOp i1 i2 = i1 .|. i2 intOp CLndOp i1 i2 = toInteger $ fromEnum $ (i1 /= 0) && (i2 /= 0) intOp CLorOp i1 i2 = toInteger $ fromEnum $ (i1 /= 0) || (i2 /= 0) -- Use the withWordBytes function to wrap the results around to the -- correct word size intUnOp :: CUnaryOp -> Integer -> Maybe Integer intUnOp CPlusOp i = Just i intUnOp CMinOp i = Just $ -i intUnOp CCompOp i = Just $ complement i intUnOp CNegOp i = Just $ toInteger $ fromEnum $ i == 0 intUnOp _ _ = Nothing withWordBytes :: Int -> Integer -> Integer withWordBytes bytes n = n `rem` (1 `shiftL` (bytes `shiftL` 3)) boolValue :: CExpr -> Maybe Bool boolValue (CConst (CIntConst i _)) = Just $ getCInteger i /= 0 boolValue (CConst (CCharConst c _)) = Just $ getCCharAsInt c /= 0 boolValue (CConst (CStrConst _ _)) = Just True boolValue _ = Nothing intValue :: CExpr -> Maybe Integer intValue (CConst (CIntConst i _)) = Just $ getCInteger i intValue (CConst (CCharConst c _)) = Just $ getCCharAsInt c intValue _ = Nothing constEval :: (MonadTrav m) => MachineDesc -> Map.Map Ident CExpr -> CExpr -> m CExpr constEval md env (CCond e1 me2 e3 ni) = do e1' <- constEval md env e1 me2' <- maybe (return Nothing) (\e -> Just `liftM` constEval md env e) me2 e3' <- constEval md env e3 case boolValue e1' of Just True -> return $ fromMaybe e1' me2' Just False -> return e3' Nothing -> return $ CCond e1' me2' e3' ni constEval md env e@(CBinary op e1 e2 ni) = do e1' <- constEval md env e1 e2' <- constEval md env e2 t <- tExpr [] RValue e bytes <- fromIntegral `liftM` sizeofType md e t case (intValue e1', intValue e2') of (Just i1, Just i2) -> intExpr ni (withWordBytes bytes (intOp op i1 i2)) (_, _) -> return $ CBinary op e1' e2' ni constEval md env (CUnary op e ni) = do e' <- constEval md env e t <- tExpr [] RValue e bytes <- fromIntegral `liftM` sizeofType md e t case intValue e' of Just i -> case intUnOp op i of Just i' -> intExpr ni (withWordBytes bytes i') Nothing -> astError ni "invalid unary operator applied to constant" Nothing -> return $ CUnary op e' ni constEval md env (CCast d e ni) = do e' <- constEval md env e t <- analyseTypeDecl d bytes <- fromIntegral `liftM` sizeofType md d t case intValue e' of Just i -> intExpr ni (withWordBytes bytes i) Nothing -> return $ CCast d e' ni constEval md _ (CSizeofExpr e ni) = do t <- tExpr [] RValue e sz <- sizeofType md e t intExpr ni sz constEval md _ (CSizeofType d ni) = do t <- analyseTypeDecl d sz <- sizeofType md d t intExpr ni sz constEval md _ (CAlignofExpr e ni) = do t <- tExpr [] RValue e sz <- alignofType md e t intExpr ni sz constEval md _ (CAlignofType d ni) = do t <- analyseTypeDecl d sz <- alignofType md d t intExpr ni sz constEval md env e@(CVar i _) | Map.member i env = return $ fromMaybe e $ Map.lookup i env constEval md env e@(CVar i _) = do t <- tExpr [] RValue e case derefTypeDef t of DirectType (TyEnum etr) _ _ -> do dt <- getDefTable case lookupTag (sueRef etr) dt of Just (Right (EnumDef (EnumType _ es _ _))) -> do env' <- foldM enumConst env es return $ fromMaybe e $ Map.lookup i env' _ -> return e _ -> return e where enumConst env' (Enumerator n e' _ _) = do c <- constEval md env' e' return $ Map.insert n c env' constEval _ _ e = return e
null
https://raw.githubusercontent.com/cartazio/language-c/d003206a45baec4e2a2a85026d88bd225162d951/src/Language/C/Analysis/ConstEval.hs
haskell
# SOURCE # astError (nodeInfo sz) $ "array size is not a constant: " ++ (render . pretty) sz XXX: handle padding Expression evaluation Use the withWordBytes function to wrap the results around to the correct word size Use the withWordBytes function to wrap the results around to the correct word size
# LANGUAGE RelaxedPolyRec # module Language.C.Analysis.ConstEval where import Control.Monad import Data.Bits import Data.Maybe import qualified Data.Map as Map import Language.C.Syntax.AST import Language.C.Syntax.Constants import Language.C.Analysis.Debug import Language.C.Analysis.DeclAnalysis import Language.C.Analysis.DefTable import Language.C.Data import Language.C.Pretty import Language.C.Analysis.SemRep import Language.C.Analysis.TravMonad import Language.C.Analysis.TypeUtils import Text.PrettyPrint.HughesPJ data MachineDesc = MachineDesc { iSize :: IntType -> Integer , fSize :: FloatType -> Integer , builtinSize :: BuiltinType -> Integer , ptrSize :: Integer , voidSize :: Integer , iAlign :: IntType -> Integer , fAlign :: FloatType -> Integer , builtinAlign :: BuiltinType -> Integer , ptrAlign :: Integer , voidAlign :: Integer } intExpr :: (Pos n, MonadName m) => n -> Integer -> m CExpr intExpr n i = genName >>= \name -> return $ CConst $ CIntConst (cInteger i) (mkNodeInfo (posOf n) name) sizeofType :: (MonadTrav m, CNode n) => MachineDesc -> n -> Type -> m Integer sizeofType md _ (DirectType TyVoid _ _) = return $ voidSize md sizeofType md _ (DirectType (TyIntegral it) _ _) = return $ iSize md it sizeofType md _ (DirectType (TyFloating ft) _ _) = return $ fSize md ft sizeofType md _ (DirectType (TyComplex ft) _ _) = return $ 2 * fSize md ft sizeofType md _ (DirectType (TyComp ctr) _ _) = compSize md ctr sizeofType md _ (DirectType (TyEnum _) _ _) = return $ iSize md TyInt sizeofType md _ (DirectType (TyBuiltin b) _ _) = return $ builtinSize md b sizeofType md _ (PtrType _ _ _) = return $ ptrSize md sizeofType md n (ArrayType bt (UnknownArraySize _) _ _) = return $ ptrSize md sizeofType md n (ArrayType bt (ArraySize _ sz) _ _) = do sz' <- constEval md Map.empty sz case sz' of CConst (CIntConst i _) -> do s <- sizeofType md n bt return $ getCInteger i * s _ -> return $ ptrSize md sizeofType md n (TypeDefType (TypeDefRef _ (Just t) _) _ _) = sizeofType md n t sizeofType md _ (FunctionType _ _) = return $ ptrSize md sizeofType _ n t = astError (nodeInfo n) $ "can't find size of type: " ++ (render . pretty) t alignofType :: (MonadTrav m, CNode n) => MachineDesc -> n -> Type -> m Integer alignofType md _ (DirectType TyVoid _ _) = return $ voidAlign md alignofType md _ (DirectType (TyIntegral it) _ _) = return $ iAlign md it alignofType md _ (DirectType (TyFloating ft) _ _) = return $ fAlign md ft alignofType md _ (DirectType (TyComplex ft) _ _) = return $ fAlign md ft alignofType md _ (DirectType (TyEnum _) _ _) = return $ iAlign md TyInt alignofType md _ (DirectType (TyBuiltin b) _ _) = return $ builtinAlign md b alignofType md _ (PtrType _ _ _) = return $ ptrAlign md alignofType md n (ArrayType bt (UnknownArraySize _) _ _) = return $ ptrAlign md alignofType md n (ArrayType bt (ArraySize _ sz) _ _) = alignofType md n bt alignofType md n (TypeDefType (TypeDefRef _ (Just t) _) _ _) = alignofType md n t alignofType _ n t = astError (nodeInfo n) $ "can't find alignment of type: " ++ (render . pretty) t compSize :: MonadTrav m => MachineDesc -> CompTypeRef -> m Integer compSize md ctr = do dt <- getDefTable case lookupTag (sueRef ctr) dt of Just (Left _) -> astError (nodeInfo ctr) "composite declared but not defined" Just (Right (CompDef (CompType _ tag ms _ ni))) -> do let ts = map declType ms sizes <- mapM (sizeofType md ni) ts case tag of StructTag -> return $ sum sizes UnionTag -> return $ maximum sizes Just (Right (EnumDef _)) -> return $ iSize md TyInt Nothing -> astError (nodeInfo ctr) "unknown composite" intOp :: CBinaryOp -> Integer -> Integer -> Integer intOp CAddOp i1 i2 = i1 + i2 intOp CSubOp i1 i2 = i1 - i2 intOp CMulOp i1 i2 = i1 * i2 intOp CDivOp i1 i2 = i1 `div` i2 intOp CRmdOp i1 i2 = i1 `mod` i2 intOp CShlOp i1 i2 = i1 `shiftL` fromInteger i2 intOp CShrOp i1 i2 = i1 `shiftR` fromInteger i2 intOp CLeOp i1 i2 = toInteger $ fromEnum $ i1 < i2 intOp CGrOp i1 i2 = toInteger $ fromEnum $ i1 > i2 intOp CLeqOp i1 i2 = toInteger $ fromEnum $ i1 <= i2 intOp CGeqOp i1 i2 = toInteger $ fromEnum $ i1 >= i2 intOp CEqOp i1 i2 = toInteger $ fromEnum $ i1 == i2 intOp CNeqOp i1 i2 = toInteger $ fromEnum $ i1 /= i2 intOp CAndOp i1 i2 = i1 .&. i2 intOp CXorOp i1 i2 = i1 `xor` i2 intOp COrOp i1 i2 = i1 .|. i2 intOp CLndOp i1 i2 = toInteger $ fromEnum $ (i1 /= 0) && (i2 /= 0) intOp CLorOp i1 i2 = toInteger $ fromEnum $ (i1 /= 0) || (i2 /= 0) intUnOp :: CUnaryOp -> Integer -> Maybe Integer intUnOp CPlusOp i = Just i intUnOp CMinOp i = Just $ -i intUnOp CCompOp i = Just $ complement i intUnOp CNegOp i = Just $ toInteger $ fromEnum $ i == 0 intUnOp _ _ = Nothing withWordBytes :: Int -> Integer -> Integer withWordBytes bytes n = n `rem` (1 `shiftL` (bytes `shiftL` 3)) boolValue :: CExpr -> Maybe Bool boolValue (CConst (CIntConst i _)) = Just $ getCInteger i /= 0 boolValue (CConst (CCharConst c _)) = Just $ getCCharAsInt c /= 0 boolValue (CConst (CStrConst _ _)) = Just True boolValue _ = Nothing intValue :: CExpr -> Maybe Integer intValue (CConst (CIntConst i _)) = Just $ getCInteger i intValue (CConst (CCharConst c _)) = Just $ getCCharAsInt c intValue _ = Nothing constEval :: (MonadTrav m) => MachineDesc -> Map.Map Ident CExpr -> CExpr -> m CExpr constEval md env (CCond e1 me2 e3 ni) = do e1' <- constEval md env e1 me2' <- maybe (return Nothing) (\e -> Just `liftM` constEval md env e) me2 e3' <- constEval md env e3 case boolValue e1' of Just True -> return $ fromMaybe e1' me2' Just False -> return e3' Nothing -> return $ CCond e1' me2' e3' ni constEval md env e@(CBinary op e1 e2 ni) = do e1' <- constEval md env e1 e2' <- constEval md env e2 t <- tExpr [] RValue e bytes <- fromIntegral `liftM` sizeofType md e t case (intValue e1', intValue e2') of (Just i1, Just i2) -> intExpr ni (withWordBytes bytes (intOp op i1 i2)) (_, _) -> return $ CBinary op e1' e2' ni constEval md env (CUnary op e ni) = do e' <- constEval md env e t <- tExpr [] RValue e bytes <- fromIntegral `liftM` sizeofType md e t case intValue e' of Just i -> case intUnOp op i of Just i' -> intExpr ni (withWordBytes bytes i') Nothing -> astError ni "invalid unary operator applied to constant" Nothing -> return $ CUnary op e' ni constEval md env (CCast d e ni) = do e' <- constEval md env e t <- analyseTypeDecl d bytes <- fromIntegral `liftM` sizeofType md d t case intValue e' of Just i -> intExpr ni (withWordBytes bytes i) Nothing -> return $ CCast d e' ni constEval md _ (CSizeofExpr e ni) = do t <- tExpr [] RValue e sz <- sizeofType md e t intExpr ni sz constEval md _ (CSizeofType d ni) = do t <- analyseTypeDecl d sz <- sizeofType md d t intExpr ni sz constEval md _ (CAlignofExpr e ni) = do t <- tExpr [] RValue e sz <- alignofType md e t intExpr ni sz constEval md _ (CAlignofType d ni) = do t <- analyseTypeDecl d sz <- alignofType md d t intExpr ni sz constEval md env e@(CVar i _) | Map.member i env = return $ fromMaybe e $ Map.lookup i env constEval md env e@(CVar i _) = do t <- tExpr [] RValue e case derefTypeDef t of DirectType (TyEnum etr) _ _ -> do dt <- getDefTable case lookupTag (sueRef etr) dt of Just (Right (EnumDef (EnumType _ es _ _))) -> do env' <- foldM enumConst env es return $ fromMaybe e $ Map.lookup i env' _ -> return e _ -> return e where enumConst env' (Enumerator n e' _ _) = do c <- constEval md env' e' return $ Map.insert n c env' constEval _ _ e = return e
3e093d19171d289efa3d38752e348c3aed0a9a8a3df80bb8c746c4df0454443b
dgtized/shimmers
voronoi_after_effect.cljs
(ns shimmers.sketches.voronoi-after-effect (:require [quil.core :as q :include-macros true] [quil.middleware :as m] [shimmers.algorithm.delaunay :as delvor] [shimmers.algorithm.random-points :as rp] [shimmers.common.framerate :as framerate] [shimmers.common.quil :as cq] [shimmers.math.deterministic-random :as dr] [shimmers.math.equations :as eq] [shimmers.math.vector :as v] [shimmers.sketch :as sketch :include-macros true] [thi.ng.geom.core :as g] [thi.ng.math.core :as tm])) ;; Experimenting with moving points but drawing the delayed voronoi diagram ;; around those points. ;; FIXME: it drifts to the right for some reason ;; TODO: experiment with particle physics for the underlying points? (defn setup [] (q/color-mode :hsl 1.0) (q/background 1.0 1.0) (let [bounds (cq/screen-rect 0.95)] {:bounds bounds :points (rp/poisson-disc-sampling bounds 128)})) (defn kick-point [t] (fn [p] (let [[vx vy] (tm/* p 0.01)] (v/wrap2d (v/+polar p (dr/gaussian 2.0 1) (* eq/TAU (q/noise vx vy t))) (q/width) (q/height))))) (defn perturb-points [points t] (dr/map-random-sample (constantly 0.025) (kick-point t) points)) (defn update-state [{:keys [t] :as state}] (-> state (update :points perturb-points t) (update :t + 0.01))) (defn draw [{:keys [points]}] (q/stroke-weight 0.33) (q/stroke 0.0 0.2) (let [polygons (delvor/voronoi-cells points (cq/screen-rect))] (doseq [shape (dr/random-sample 0.05 polygons)] (q/no-fill) (when (dr/chance 0.05) (q/fill 1.0 0.25)) (cq/draw-shape (g/vertices shape))))) (sketch/defquil voronoi-after-effect :created-at "2022-03-23" :size [800 600] :setup setup :update update-state :draw draw :middleware [m/fun-mode framerate/mode])
null
https://raw.githubusercontent.com/dgtized/shimmers/f096c20d7ebcb9796c7830efcd7e3f24767a46db/src/shimmers/sketches/voronoi_after_effect.cljs
clojure
Experimenting with moving points but drawing the delayed voronoi diagram around those points. FIXME: it drifts to the right for some reason TODO: experiment with particle physics for the underlying points?
(ns shimmers.sketches.voronoi-after-effect (:require [quil.core :as q :include-macros true] [quil.middleware :as m] [shimmers.algorithm.delaunay :as delvor] [shimmers.algorithm.random-points :as rp] [shimmers.common.framerate :as framerate] [shimmers.common.quil :as cq] [shimmers.math.deterministic-random :as dr] [shimmers.math.equations :as eq] [shimmers.math.vector :as v] [shimmers.sketch :as sketch :include-macros true] [thi.ng.geom.core :as g] [thi.ng.math.core :as tm])) (defn setup [] (q/color-mode :hsl 1.0) (q/background 1.0 1.0) (let [bounds (cq/screen-rect 0.95)] {:bounds bounds :points (rp/poisson-disc-sampling bounds 128)})) (defn kick-point [t] (fn [p] (let [[vx vy] (tm/* p 0.01)] (v/wrap2d (v/+polar p (dr/gaussian 2.0 1) (* eq/TAU (q/noise vx vy t))) (q/width) (q/height))))) (defn perturb-points [points t] (dr/map-random-sample (constantly 0.025) (kick-point t) points)) (defn update-state [{:keys [t] :as state}] (-> state (update :points perturb-points t) (update :t + 0.01))) (defn draw [{:keys [points]}] (q/stroke-weight 0.33) (q/stroke 0.0 0.2) (let [polygons (delvor/voronoi-cells points (cq/screen-rect))] (doseq [shape (dr/random-sample 0.05 polygons)] (q/no-fill) (when (dr/chance 0.05) (q/fill 1.0 0.25)) (cq/draw-shape (g/vertices shape))))) (sketch/defquil voronoi-after-effect :created-at "2022-03-23" :size [800 600] :setup setup :update update-state :draw draw :middleware [m/fun-mode framerate/mode])
a1ddf343678aa2d8f940cb5d4c68e0b4480c3334cee44e30ebd0e1d8cd4c2b60
flatironinstitute/flathub
Compression.hs
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeSynonymInstances #-} module Compression ( CompressionFormat(..) , encodingCompressions , compressionEncoding , compressionEncodingHeader , acceptCompressionEncoding , compressionExtension , compressionFilename , compressionMimeType , decompressExtension , decompressFile , compressStream ) where import Control.Arrow (first, Kleisli(..)) import Control.Exception (throwIO) import Control.Monad (unless) import qualified Codec.Compression.BZip as BZ import qualified Codec.Compression.GZip as GZ import qualified Data.ByteString as BS import qualified Data.ByteString.Builder as BSB import qualified Data.ByteString.Builder.Extra as BSB (flush) import qualified Data.ByteString.Lazy.Char8 as BSLC import Data.Function (fix) import qualified Data.Streaming.ByteString.Builder as SB import qualified Data.Streaming.Zlib as SZ import Data.String (IsString) import qualified Data.Text as T import Network.HTTP.Types.Header (Header, hAcceptEncoding, hContentEncoding) import qualified Network.Wai as Wai import System.FilePath (splitExtension, (<.>)) import Waimwork.HTTP (splitHTTP) import qualified Web.Route.Invertible as R data CompressionFormat = CompressionGZip | CompressionBZip2 deriving (Show, Eq, Enum, Bounded) encodingCompressions :: [CompressionFormat] encodingCompressions = [CompressionGZip] compressionEncoding :: CompressionFormat -> BS.ByteString compressionEncoding CompressionGZip = "gzip" compressionEncoding CompressionBZip2 = "bzip2" compressionEncodingHeader :: CompressionFormat -> Header compressionEncodingHeader = (,) hContentEncoding . compressionEncoding acceptCompressionEncoding :: Wai.Request -> [CompressionFormat] acceptCompressionEncoding req = filter (\c -> compressionEncoding c `elem` enc) encodingCompressions where enc = maybe [] splitHTTP $ lookup hAcceptEncoding $ Wai.requestHeaders req compressionExtension :: CompressionFormat -> String compressionExtension CompressionGZip = "gz" compressionExtension CompressionBZip2 = "bz2" compressionFilename :: Maybe CompressionFormat -> FilePath -> FilePath compressionFilename = maybe id (flip (<.>) . compressionExtension) compressionMimeType :: IsString s => CompressionFormat -> s compressionMimeType CompressionGZip = "application/gzip" compressionMimeType CompressionBZip2 = "application/x-bzip2" decompressExtension :: FilePath -> (FilePath, Maybe CompressionFormat) decompressExtension f = case splitExtension f of (b, ".gz") -> (b, Just CompressionGZip) (b, ".bz2") -> (b, Just CompressionBZip2) _ -> (f, Nothing) instance R.Parameter R.PathString a => R.Parameter R.PathString (a, Maybe CompressionFormat) where renderParameter (x, Nothing) = R.renderParameter x renderParameter (x, Just z) = R.renderParameter x <> T.pack ('.' : compressionExtension z) parseParameter s = runKleisli (first (Kleisli $ R.parseParameter . T.pack)) $ decompressExtension (T.unpack s) decompress :: CompressionFormat -> BSLC.ByteString -> BSLC.ByteString decompress CompressionGZip = GZ.decompress decompress CompressionBZip2 = BZ.decompress decompressMaybe :: Maybe CompressionFormat -> BSLC.ByteString -> BSLC.ByteString decompressMaybe = maybe id decompress decompressFile :: FilePath -> IO BSLC.ByteString decompressFile f = decompressMaybe (snd $ decompressExtension f) <$> BSLC.readFile f compressStream :: Maybe CompressionFormat -> Wai.StreamingBody -> Wai.StreamingBody compressStream Nothing body = body compressStream (Just CompressionGZip) body = \sendChunk flush -> do based on Network . Wai . Middleware . : (blazeRecv, _) <- SB.newByteStringBuilderRecv SB.defaultStrategy deflate <- SZ.initDeflate 3 (SZ.WindowBits 31) let sendBuilder builder = do popper <- blazeRecv builder fix $ \loop -> do bs <- popper unless (BS.null bs) $ do sendBS bs loop sendBS bs = SZ.feedDeflate deflate bs >>= deflatePopper flushBuilder = do sendBuilder BSB.flush deflatePopper $ SZ.flushDeflate deflate flush deflatePopper popper = fix $ \loop -> do result <- popper case result of SZ.PRDone -> return () SZ.PRNext bs' -> do sendChunk $ BSB.byteString bs' loop SZ.PRError e -> throwIO e body sendBuilder flushBuilder sendBuilder BSB.flush deflatePopper $ SZ.finishDeflate deflate compressStream (Just z) _ = \_ _ -> fail $ "Unsupported compression format: " ++ show z
null
https://raw.githubusercontent.com/flatironinstitute/flathub/f3f4dcb3d4808ee36632e48dd3911860fa25250a/src/Compression.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE TypeSynonymInstances #
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # module Compression ( CompressionFormat(..) , encodingCompressions , compressionEncoding , compressionEncodingHeader , acceptCompressionEncoding , compressionExtension , compressionFilename , compressionMimeType , decompressExtension , decompressFile , compressStream ) where import Control.Arrow (first, Kleisli(..)) import Control.Exception (throwIO) import Control.Monad (unless) import qualified Codec.Compression.BZip as BZ import qualified Codec.Compression.GZip as GZ import qualified Data.ByteString as BS import qualified Data.ByteString.Builder as BSB import qualified Data.ByteString.Builder.Extra as BSB (flush) import qualified Data.ByteString.Lazy.Char8 as BSLC import Data.Function (fix) import qualified Data.Streaming.ByteString.Builder as SB import qualified Data.Streaming.Zlib as SZ import Data.String (IsString) import qualified Data.Text as T import Network.HTTP.Types.Header (Header, hAcceptEncoding, hContentEncoding) import qualified Network.Wai as Wai import System.FilePath (splitExtension, (<.>)) import Waimwork.HTTP (splitHTTP) import qualified Web.Route.Invertible as R data CompressionFormat = CompressionGZip | CompressionBZip2 deriving (Show, Eq, Enum, Bounded) encodingCompressions :: [CompressionFormat] encodingCompressions = [CompressionGZip] compressionEncoding :: CompressionFormat -> BS.ByteString compressionEncoding CompressionGZip = "gzip" compressionEncoding CompressionBZip2 = "bzip2" compressionEncodingHeader :: CompressionFormat -> Header compressionEncodingHeader = (,) hContentEncoding . compressionEncoding acceptCompressionEncoding :: Wai.Request -> [CompressionFormat] acceptCompressionEncoding req = filter (\c -> compressionEncoding c `elem` enc) encodingCompressions where enc = maybe [] splitHTTP $ lookup hAcceptEncoding $ Wai.requestHeaders req compressionExtension :: CompressionFormat -> String compressionExtension CompressionGZip = "gz" compressionExtension CompressionBZip2 = "bz2" compressionFilename :: Maybe CompressionFormat -> FilePath -> FilePath compressionFilename = maybe id (flip (<.>) . compressionExtension) compressionMimeType :: IsString s => CompressionFormat -> s compressionMimeType CompressionGZip = "application/gzip" compressionMimeType CompressionBZip2 = "application/x-bzip2" decompressExtension :: FilePath -> (FilePath, Maybe CompressionFormat) decompressExtension f = case splitExtension f of (b, ".gz") -> (b, Just CompressionGZip) (b, ".bz2") -> (b, Just CompressionBZip2) _ -> (f, Nothing) instance R.Parameter R.PathString a => R.Parameter R.PathString (a, Maybe CompressionFormat) where renderParameter (x, Nothing) = R.renderParameter x renderParameter (x, Just z) = R.renderParameter x <> T.pack ('.' : compressionExtension z) parseParameter s = runKleisli (first (Kleisli $ R.parseParameter . T.pack)) $ decompressExtension (T.unpack s) decompress :: CompressionFormat -> BSLC.ByteString -> BSLC.ByteString decompress CompressionGZip = GZ.decompress decompress CompressionBZip2 = BZ.decompress decompressMaybe :: Maybe CompressionFormat -> BSLC.ByteString -> BSLC.ByteString decompressMaybe = maybe id decompress decompressFile :: FilePath -> IO BSLC.ByteString decompressFile f = decompressMaybe (snd $ decompressExtension f) <$> BSLC.readFile f compressStream :: Maybe CompressionFormat -> Wai.StreamingBody -> Wai.StreamingBody compressStream Nothing body = body compressStream (Just CompressionGZip) body = \sendChunk flush -> do based on Network . Wai . Middleware . : (blazeRecv, _) <- SB.newByteStringBuilderRecv SB.defaultStrategy deflate <- SZ.initDeflate 3 (SZ.WindowBits 31) let sendBuilder builder = do popper <- blazeRecv builder fix $ \loop -> do bs <- popper unless (BS.null bs) $ do sendBS bs loop sendBS bs = SZ.feedDeflate deflate bs >>= deflatePopper flushBuilder = do sendBuilder BSB.flush deflatePopper $ SZ.flushDeflate deflate flush deflatePopper popper = fix $ \loop -> do result <- popper case result of SZ.PRDone -> return () SZ.PRNext bs' -> do sendChunk $ BSB.byteString bs' loop SZ.PRError e -> throwIO e body sendBuilder flushBuilder sendBuilder BSB.flush deflatePopper $ SZ.finishDeflate deflate compressStream (Just z) _ = \_ _ -> fail $ "Unsupported compression format: " ++ show z
08847dd4d53deb88686e6a8bf29317c1ff1e322d9c2e723518b530f07dd3d0de
BranchTaken/Hemlock
test_neg_abs.ml
open! Basis.Rudiments open! Basis open Zint let test () = let rec test = function | [] -> () | u :: us' -> begin let fn u = begin File.Fmt.stdout |> Fmt.fmt "neg,abs " |> fmt ~alt:true ~radix:Radix.Hex u |> Fmt.fmt " -> " |> fmt ~alt:true ~radix:Radix.Hex (neg u) |> Fmt.fmt ", " |> fmt ~alt:true ~radix:Radix.Hex (abs u) |> Fmt.fmt "\n" |> ignore end in fn u; fn (neg u); test us' end in let us = [ of_string "0"; of_string "1"; of_string "2"; of_string "3"; of_string "0x8000_0000_0000_0000"; of_string "0xffff_ffff_ffff_ffff" ] in test us let _ = test ()
null
https://raw.githubusercontent.com/BranchTaken/Hemlock/a07e362d66319108c1478a4cbebab765c1808b1a/bootstrap/test/basis/zint/test_neg_abs.ml
ocaml
open! Basis.Rudiments open! Basis open Zint let test () = let rec test = function | [] -> () | u :: us' -> begin let fn u = begin File.Fmt.stdout |> Fmt.fmt "neg,abs " |> fmt ~alt:true ~radix:Radix.Hex u |> Fmt.fmt " -> " |> fmt ~alt:true ~radix:Radix.Hex (neg u) |> Fmt.fmt ", " |> fmt ~alt:true ~radix:Radix.Hex (abs u) |> Fmt.fmt "\n" |> ignore end in fn u; fn (neg u); test us' end in let us = [ of_string "0"; of_string "1"; of_string "2"; of_string "3"; of_string "0x8000_0000_0000_0000"; of_string "0xffff_ffff_ffff_ffff" ] in test us let _ = test ()
23e4eadb979f91654fef88a3bf29e3766e514ed9b1128933a8145d2d4e496771
S8A/htdp-exercises
ex503.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex503) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ; Matrix -> Matrix ; finds a row that doesn't start with 0 and uses it as the first one generative moves the first row to last place ; no termination if all rows start with 0 (define (rotate M) (cond [(not (= (first (first M)) 0)) M] [else (rotate (append (rest M) (list (first M))))])) (check-expect (rotate '((0 4 5) (1 2 3))) '((1 2 3) (0 4 5))) ; Matrix -> Matrix tries to find a row that does n't start with 0 and use it as the first one (define (rotate.v2 m0) (local (; Matrix [List-of Row] -> Matrix ; tries to find a row that doesn't start with 0 and use it as the first one , signaling an error if there are none ; generative if such a row is found, the previously checked rows ; are added to the end ; accumulator seen contains the rows that are in m0 but not in m, ; i.e. the ones that are known to start with 0 (define (rot m seen) (cond [(empty? m) (error 'rotate "can't find row that doesn't start with 0")] [(not (= (first (first m)) 0)) (append m seen)] [else (rot (rest m) (cons (first m) seen))]))) (rot m0 '()))) (check-expect (rotate.v2 '((0 4 5) (1 2 3))) '((1 2 3) (0 4 5))) (check-error (rotate.v2 '((0 4 5) (0 9 8) (0 0 7)))) ; N -> Matrix creates a matrix with n rows of three items , where each row starts with 0 except the last one (define (create-test-matrix n) (build-list n (lambda (row) (cons (if (= row (sub1 n)) (add1 (random 9)) 0) (build-list 2 (lambda (i) (random 10))))))) .. : : Perfomance comparison : Sep. 23 , 2019 : : .. (define matrix-list (build-list 5 (lambda (n) (create-test-matrix (* (add1 n) 1000))))) (define rv1-test (map (lambda (matrix) (time (rotate matrix))) matrix-list)) cpu time : 55 real time : 55 gc time : 40 cpu time : 100 real time : 101 gc time : 44 cpu time : 254 real time : 255 gc time : 127 cpu time : 417 real time : 419 gc time : 209 cpu time : 660 real time : 662 gc time : 327 (define rv2-test (map (lambda (matrix) (time (rotate.v2 matrix))) matrix-list)) cpu time : 1 real time : 1 gc time : 0 cpu time : 3 real time : 3 gc time : 0 cpu time : 4 real time : 4 gc time : 0 cpu time : 6 real time : 6 gc time : 0 cpu time : 7 real time : 7 gc time : 0
null
https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex503.rkt
racket
about the language level of this file in a form that our tools can easily process. Matrix -> Matrix finds a row that doesn't start with 0 and no termination if all rows start with 0 Matrix -> Matrix Matrix [List-of Row] -> Matrix tries to find a row that doesn't start with 0 and use it as generative if such a row is found, the previously checked rows are added to the end accumulator seen contains the rows that are in m0 but not in m, i.e. the ones that are known to start with 0 N -> Matrix
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex503) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) uses it as the first one generative moves the first row to last place (define (rotate M) (cond [(not (= (first (first M)) 0)) M] [else (rotate (append (rest M) (list (first M))))])) (check-expect (rotate '((0 4 5) (1 2 3))) '((1 2 3) (0 4 5))) tries to find a row that does n't start with 0 and use it as the first one (define (rotate.v2 m0) the first one , signaling an error if there are none (define (rot m seen) (cond [(empty? m) (error 'rotate "can't find row that doesn't start with 0")] [(not (= (first (first m)) 0)) (append m seen)] [else (rot (rest m) (cons (first m) seen))]))) (rot m0 '()))) (check-expect (rotate.v2 '((0 4 5) (1 2 3))) '((1 2 3) (0 4 5))) (check-error (rotate.v2 '((0 4 5) (0 9 8) (0 0 7)))) creates a matrix with n rows of three items , where each row starts with 0 except the last one (define (create-test-matrix n) (build-list n (lambda (row) (cons (if (= row (sub1 n)) (add1 (random 9)) 0) (build-list 2 (lambda (i) (random 10))))))) .. : : Perfomance comparison : Sep. 23 , 2019 : : .. (define matrix-list (build-list 5 (lambda (n) (create-test-matrix (* (add1 n) 1000))))) (define rv1-test (map (lambda (matrix) (time (rotate matrix))) matrix-list)) cpu time : 55 real time : 55 gc time : 40 cpu time : 100 real time : 101 gc time : 44 cpu time : 254 real time : 255 gc time : 127 cpu time : 417 real time : 419 gc time : 209 cpu time : 660 real time : 662 gc time : 327 (define rv2-test (map (lambda (matrix) (time (rotate.v2 matrix))) matrix-list)) cpu time : 1 real time : 1 gc time : 0 cpu time : 3 real time : 3 gc time : 0 cpu time : 4 real time : 4 gc time : 0 cpu time : 6 real time : 6 gc time : 0 cpu time : 7 real time : 7 gc time : 0