_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
367a1dd049e3a346648491bc40fd3a7ad096f7a60eb08184f3e5d6ea5377a3f8
lispbuilder/lispbuilder
procedural-primitives.lisp
(in-package #:rm) (defclass procedural-primitive (primitive)()) (defclass sphere-primitive (procedural-primitive)() (:default-initargs :fp (rm-cffi::rm-Primitive-New :rm-spheres))) (defclass cone-primitive (procedural-primitive)() (:default-initargs :fp (rm-cffi::rm-Primitive-New :rm-cones))) (defclass cylinder-primitive (procedural-primitive)() (:default-initargs :fp (rm-cffi::rm-Primitive-New :rm-cylinders))) (defmethod initialize-instance :around ((self procedural-primitive) &key (radius nil) (tesselate nil)) (call-next-method) (when radius (setf (radius self) radius)) (when tesselate (setf (tesselate self) tesselate))) (defmethod (setf radius) ((radius float) (self procedural-primitive)) (cffi:with-foreign-object (radii :float) (setf (cffi:mem-aref radii :float) radius) (rm-cffi::rm-Primitive-Set-Radii (fp self) 1 radii :RM-COPY-DATA (cffi:null-pointer))) self) (defmethod (setf radius) ((radius list) (self procedural-primitive)) (let ((size (length radius)) (radii (cffi:foreign-alloc :float :initial-contents radius))) (rm-cffi::rm-Primitive-Set-Radii (fp self) size radii :RM-COPY-DATA (cffi:null-pointer)) (cffi:foreign-free radii)) self) (defmethod (setf radius) ((radius vector) (self procedural-primitive)) (setf (radius self) (coerce radius 'list))) (defmethod (setf tesselate) (tesselate (self sphere-primitive)) (rm-cffi::rm-Primitive-Set-Model-Flag (fp self) (case tesselate (8 rm-cffi::+RM-SPHERES-8+) (32 rm-cffi::+RM-SPHERES-32+) (128 rm-cffi::+RM-SPHERES-128+) (512 rm-cffi::+RM-SPHERES-512+) (otherwise rm-cffi::+RM-SPHERES-32+))) self) (defmethod (setf tesselate) (tesselate (self cone-primitive)) (rm-cffi::rm-Primitive-Set-Model-Flag (fp self) (case tesselate (4 rm-cffi::+RM-CONES-4+) (8 rm-cffi::+RM-CONES-8+) (12 rm-cffi::+RM-CONES-12+) (16 rm-cffi::+RM-CONES-16+) (32 rm-cffi::+RM-CONES-32+) (64 rm-cffi::+RM-CONES-64+) (128 rm-cffi::+RM-CONES-128+) (otherwise rm-cffi::+RM-CONES-32+))) self) (defmethod (setf tesselate) (tesselate (self cylinder-primitive)) (rm-cffi::rm-Primitive-Set-Model-Flag (fp self) (case tesselate (4 rm-cffi::+RM-CYLINDERS-4+) (8 rm-cffi::+RM-CYLINDERS-8+) (12 rm-cffi::+RM-CYLINDERS-12+) (16 rm-cffi::+RM-CYLINDERS-16+) (32 rm-cffi::+RM-CYLINDERS-32+) (64 rm-cffi::+RM-CYLINDERS-64+) (128 rm-cffi::+RM-CYLINDERS-128+) (otherwise rm-cffi::+RM-CONES-16+))) self)
null
https://raw.githubusercontent.com/lispbuilder/lispbuilder/589b3c6d552bbec4b520f61388117d6c7b3de5ab/lispbuilder-openrm/openrm/procedural-primitives.lisp
lisp
(in-package #:rm) (defclass procedural-primitive (primitive)()) (defclass sphere-primitive (procedural-primitive)() (:default-initargs :fp (rm-cffi::rm-Primitive-New :rm-spheres))) (defclass cone-primitive (procedural-primitive)() (:default-initargs :fp (rm-cffi::rm-Primitive-New :rm-cones))) (defclass cylinder-primitive (procedural-primitive)() (:default-initargs :fp (rm-cffi::rm-Primitive-New :rm-cylinders))) (defmethod initialize-instance :around ((self procedural-primitive) &key (radius nil) (tesselate nil)) (call-next-method) (when radius (setf (radius self) radius)) (when tesselate (setf (tesselate self) tesselate))) (defmethod (setf radius) ((radius float) (self procedural-primitive)) (cffi:with-foreign-object (radii :float) (setf (cffi:mem-aref radii :float) radius) (rm-cffi::rm-Primitive-Set-Radii (fp self) 1 radii :RM-COPY-DATA (cffi:null-pointer))) self) (defmethod (setf radius) ((radius list) (self procedural-primitive)) (let ((size (length radius)) (radii (cffi:foreign-alloc :float :initial-contents radius))) (rm-cffi::rm-Primitive-Set-Radii (fp self) size radii :RM-COPY-DATA (cffi:null-pointer)) (cffi:foreign-free radii)) self) (defmethod (setf radius) ((radius vector) (self procedural-primitive)) (setf (radius self) (coerce radius 'list))) (defmethod (setf tesselate) (tesselate (self sphere-primitive)) (rm-cffi::rm-Primitive-Set-Model-Flag (fp self) (case tesselate (8 rm-cffi::+RM-SPHERES-8+) (32 rm-cffi::+RM-SPHERES-32+) (128 rm-cffi::+RM-SPHERES-128+) (512 rm-cffi::+RM-SPHERES-512+) (otherwise rm-cffi::+RM-SPHERES-32+))) self) (defmethod (setf tesselate) (tesselate (self cone-primitive)) (rm-cffi::rm-Primitive-Set-Model-Flag (fp self) (case tesselate (4 rm-cffi::+RM-CONES-4+) (8 rm-cffi::+RM-CONES-8+) (12 rm-cffi::+RM-CONES-12+) (16 rm-cffi::+RM-CONES-16+) (32 rm-cffi::+RM-CONES-32+) (64 rm-cffi::+RM-CONES-64+) (128 rm-cffi::+RM-CONES-128+) (otherwise rm-cffi::+RM-CONES-32+))) self) (defmethod (setf tesselate) (tesselate (self cylinder-primitive)) (rm-cffi::rm-Primitive-Set-Model-Flag (fp self) (case tesselate (4 rm-cffi::+RM-CYLINDERS-4+) (8 rm-cffi::+RM-CYLINDERS-8+) (12 rm-cffi::+RM-CYLINDERS-12+) (16 rm-cffi::+RM-CYLINDERS-16+) (32 rm-cffi::+RM-CYLINDERS-32+) (64 rm-cffi::+RM-CYLINDERS-64+) (128 rm-cffi::+RM-CYLINDERS-128+) (otherwise rm-cffi::+RM-CONES-16+))) self)
133180a5a6fdc786cf675dfed25f6050da43f8e9795f0785f9fe46d6c2e74685
kindista/kindista
conversations.lisp
Copyright 2012 - 2015 CommonGoods Network , Inc. ;;; This file is part of Kindista . ;;; Kindista is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ;;; (at your option) any later version. ;;; Kindista is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or ;;; FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public ;;; License for more details. ;;; You should have received a copy of the GNU Affero General Public License along with Kindista . If not , see < / > . (in-package :kindista) (defun create-conversation (&key people subject text (user *userid*) public) (let* ((time (get-universal-time)) (senders (mailbox-ids (list user))) (recipients (mailbox-ids people)) (mailboxes (append senders recipients)) (people-data (mapcar #'list mailboxes)) (people-ids (remove-duplicates (mapcar #'car mailboxes))) (message-folders (list :inbox people-ids)) (id (insert-db (list :type :conversation :participants (cons user people) :people people-data :message-folders message-folders :public public :subject subject :created time)))) (create-comment :on id :by (list user) :text text) id)) (defun get-conversations () (see-other "/messages")) (defun new-conversation (&key people subject text next single-recipient) (if people (standard-page "New conversation" (html (:div :class "item new-conversation" (:h2 "New Conversation") (:div :class "item" (:form :method "post" :action "/conversations/new" :class "recipients" (:fieldset :class "recipients" (:legend "With:") (:ul :id "recipients" :class "recipients" (unless people (htm (:li (:em "nobody yet")))) (dolist (person people) (htm (:li (:label :for person (str (getf (db person) :name))) (unless single-recipient (htm (:button :class "text large x-remove" :id person :type "submit" :name "remove" :value person " ⨯ ")))))) (unless single-recipient (htm (:li (:button :type "submit" :class "text" :name "add" :value "new" "+ Add someone")))))) (when people (htm (:input :type "hidden" :name "people" :value (format nil "~{~A~^,~}" people)))) (when next (htm (:input :type "hidden" :name "next" :value next))) (:p (:label :for "subject" "Subject: ") (:input :type "text" :id "subject" :name "subject" :value subject)) (:label :for "message" :class "message" "Message") (:textarea :rows "8" :id "message" :name "text" (str text)) (:p (:button :type "submit" :class "cancel" :name "cancel" "Cancel") (:button :class "yes" :type "submit" :name "send" "Send")))))) :selected "messages") (conversation-add-person :text text :next next))) (defun conversation-add-person (&key people subject text next (results 'none)) (standard-page "Add person to conversation" (html (:div :class "item" (:form :method "post" :class "conversation recipients" :action "/conversations/new" (:button :type "submit" :class "simple-link green" :name "cancel-add" "↩ go back") (:h2 "Who would you like to add to the conversation?") (:h3 "Search for a person") (:input :type "text" :name "name") (:button :type "submit" :class "yes input-height" :name "search" "Search") (if (eq results 'none) (progn (htm (:h3 "Or, select one of your contacts:") (:menu :type "toolbar" (dolist (contact (contacts-alphabetically *user*)) (htm (:li (:button :class "text" :type "submit" :value (car contact) :name "add" (str (cadr contact))))))))) (progn (htm (:h3 "Search results") (dolist (person results) (str (id-button (car person) "add" (cdr person))))))) (:input :type "submit" :class "cancel" :value "Back") (when people (htm (:input :type "hidden" :name "people" :value (format nil "~{~A~^,~}" people)))) (when next (htm (:input :type "hidden" :name "next" :value next))) (when subject (htm (:input :type "hidden" :name "subject" :value subject))) (when text (htm (:input :type "hidden" :name "text" :value (escape-for-html text)))) ))) :selected "messages")) (defun get-conversations-new () (require-user (:require-active-user t :require-email t) (if (getf *user* :pending) (progn (pending-flash "contact other Kindista members") (see-other (or (referer) "/home"))) (new-conversation :people (parse-subject-list (get-parameter "people")))))) (defun post-conversations-new () (require-user (:require-active-user t :require-email t) (cond ((getf *user* :pending) (pending-flash "contact other Kindista members") (see-other (or (post-parameter "next") "/home"))) ((or (post-parameter "cancel") (and (post-parameter "cancel-add") (not (post-parameter "people")))) (see-other (or (post-parameter "next") "/messages"))) ((post-parameter "send") (let ((people (parse-subject-list (post-parameter "people") :remove (write-to-string *userid*))) (text (post-parameter "text")) (subject (post-parameter "subject"))) (when (string= subject "") (setf subject nil)) (when (string= text "") (setf text nil)) (cond ((and people text subject) (flash "Your message has been sent.") (contact-opt-out-flash (append (list *userid*) people)) (see-other (format nil (or (post-parameter "next") "/conversations/~A") (create-conversation :people people :public nil :subject subject :text text)))) ((and people subject) "no text") ((and people text) "no subject") ((and subject text) "no recipients") (text "no people OR subject") (people "no text OR subject") (subject "no text OR recipients") (t "totally blank")))) ((post-parameter "add") (if (string= (post-parameter "add") "new") (conversation-add-person :people (parse-subject-list (post-parameter "people")) :text (post-parameter "text") :subject (post-parameter "subject") :next (post-parameter "next")) (new-conversation :text (post-parameter "text") :subject (post-parameter "subject") :next (post-parameter "next") :single-recipient (post-parameter "single-recipient") :people (parse-subject-list (format nil "~A,~A" (post-parameter "add") (post-parameter "people")))))) ((post-parameter "search") (conversation-add-person :people (parse-subject-list (post-parameter "people")) :text (post-parameter "text") :subject (post-parameter "subject") :next (post-parameter "next") :results (search-people (post-parameter "name")))) (t (new-conversation :text (post-parameter "text") :subject (post-parameter "subject") :people (parse-subject-list (post-parameter "people") :remove (post-parameter "remove"))))))) (defun go-conversation (id) (moved-permanently (strcat "/conversations/" id))) (defun conversation-comments (conversation-id latest-seen) (html (dolist (comment-id (gethash conversation-id *comment-index*)) (let* ((data (db comment-id)) (by (car (getf data :by))) (for (cdr (getf data :by))) (text (getf data :text))) (when data (str (conversation-comment-html data by (db by :name) for (db for :name) text (when (>= (or latest-seen 0) comment-id)) :id comment-id))))))) (defun conversation-comment-html (data by by-name for for-name text newp &key transaction-p id) (card id (html (str (h3-timestamp (getf data :created))) (:p :id id (if transaction-p (htm (:strong (str by-name))) (htm (:a :href (s+ "/people/" (username-or-id by)) (str by-name)))) (when for (htm (:strong (str (if transaction-p " (on behalf of " " (from ")) (str for-name) ") "))) (when transaction-p (htm (:strong " responded:")))) (:p :class (when newp "new") (str (regex-replace-all "\\n" text "<br>")))))) (defun conversation-html (id data with comments-html &key error) (standard-page (aif (getf data :subject) (ellipsis it :length 24) "Conversation") (html (str (menu-horiz (html (:a :href "/messages" "back to messages")) (html (:a :href "#reply" "reply"))) ;(when (eq type :conversation) ; (html (:a :href (strcat "/conversations/" id "/leave") "leave conversation"))) ; removed until we add the ability for ; individual members of a group to leave the ; conversation and for the group to leave ; when its members have ) (str (card id (html (when (getf data :subject) (htm (:h2 "Subject: " (str (getf data :subject))))) (if with (htm (:p "with " (str (name-list-all with)))) (htm (:p :class "error" "Everybody else has left this conversation.")))))) (:div :class "item" :id "reply" (:h4 "post a reply") (:form :method "post" :action (script-name*) (:textarea :cols "150" :rows "4" :name "text") (:div :class (when (eq error :no-reply-type) "error-border")) (:button :class "yes" :type "submit" :class "submit" "Send"))) (str comments-html)) :selected "messages")) (defun get-conversation (id) "when called, (modify-db conversation-id :people '((userid . this-comment-id) (other-user-id . whatever)))" (require-user () (setf id (parse-integer id)) (let* ((message (gethash id *db-messages*)) (people (message-people message)) (valid-mailboxes (loop for person in people when (eql *userid* (caar person)) collect person)) (type (message-type message))) (case type (:conversation (if valid-mailboxes (let* ((conversation (db id)) (person (assoc-assoc *userid* people)) (latest-comment (getf conversation :latest-comment)) (latest-seen (or (when (numberp (cdr person)) (cdr person)) latest-comment)) (with (remove *userid* (getf conversation :participants)))) (prog1 (conversation-html id conversation with (conversation-comments id latest-seen)) ; get most recent comment seen ; get comments for (when (or (not (eql (message-latest-comment message) (cdr (assoc-assoc *userid* (message-people message))))) (member *userid* (getf (message-folders message) :unread))) (update-folder-data message :read :last-read-comment (message-latest-comment message))))) (permission-denied))) (:transaction (see-other (strcat "/transactions/" id))) (t (not-found)))))) (defun get-conversation-leave (id) (require-user () (setf id (parse-integer id)) (let ((it (db id))) (if (and it (eql (getf it :type) :conversation)) (if (member *userid* (mapcar #'first (getf it :people))) (standard-page "Leave conversation" (html (:h2 "Are you sure you want to leave this conversation?") (:p "You won't be able to re-join the conversation after leaving.") (:p (:strong "Subject: ") (str (getf it :subject))) (:form :method "post" :action (strcat "/conversations/" id) (:a :href (strcat "/conversations/" id) "No, I didn't mean it!") (:button :class "yes" :type "submit" :class "submit" :name "leave" "Yes"))) :selected "messages") (permission-denied)) (not-found))))) (defun post-conversation (id) (require-active-user (setf id (parse-integer id)) (aif (db id) (let* ((people (getf it :people)) (mailbox (assoc-assoc *userid* people)) (party (car mailbox))) (if party (cond ((post-parameter "leave") (amodify-db id :people (remove *userid* it :key #'caar)) (see-other "/messages")) ((post-parameter "text") (flash "Your message has been sent.") (contact-opt-out-flash (mapcar #'caar people)) (create-comment :on id :text (post-parameter "text") :by party) (see-other (script-name*)))) (permission-denied))) (not-found))))
null
https://raw.githubusercontent.com/kindista/kindista/60da1325e628841721200aa00e4de5f9687c0adb/src/features/conversations.lisp
lisp
(at your option) any later version. without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. (when (eq type :conversation) (html (:a :href (strcat "/conversations/" id "/leave") "leave conversation"))) removed until we add the ability for individual members of a group to leave the conversation and for the group to leave when its members have get most recent comment seen get comments for
Copyright 2012 - 2015 CommonGoods Network , Inc. This file is part of Kindista . Kindista is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or Kindista is distributed in the hope that it will be useful , but WITHOUT You should have received a copy of the GNU Affero General Public License along with Kindista . If not , see < / > . (in-package :kindista) (defun create-conversation (&key people subject text (user *userid*) public) (let* ((time (get-universal-time)) (senders (mailbox-ids (list user))) (recipients (mailbox-ids people)) (mailboxes (append senders recipients)) (people-data (mapcar #'list mailboxes)) (people-ids (remove-duplicates (mapcar #'car mailboxes))) (message-folders (list :inbox people-ids)) (id (insert-db (list :type :conversation :participants (cons user people) :people people-data :message-folders message-folders :public public :subject subject :created time)))) (create-comment :on id :by (list user) :text text) id)) (defun get-conversations () (see-other "/messages")) (defun new-conversation (&key people subject text next single-recipient) (if people (standard-page "New conversation" (html (:div :class "item new-conversation" (:h2 "New Conversation") (:div :class "item" (:form :method "post" :action "/conversations/new" :class "recipients" (:fieldset :class "recipients" (:legend "With:") (:ul :id "recipients" :class "recipients" (unless people (htm (:li (:em "nobody yet")))) (dolist (person people) (htm (:li (:label :for person (str (getf (db person) :name))) (unless single-recipient (htm (:button :class "text large x-remove" :id person :type "submit" :name "remove" :value person " ⨯ ")))))) (unless single-recipient (htm (:li (:button :type "submit" :class "text" :name "add" :value "new" "+ Add someone")))))) (when people (htm (:input :type "hidden" :name "people" :value (format nil "~{~A~^,~}" people)))) (when next (htm (:input :type "hidden" :name "next" :value next))) (:p (:label :for "subject" "Subject: ") (:input :type "text" :id "subject" :name "subject" :value subject)) (:label :for "message" :class "message" "Message") (:textarea :rows "8" :id "message" :name "text" (str text)) (:p (:button :type "submit" :class "cancel" :name "cancel" "Cancel") (:button :class "yes" :type "submit" :name "send" "Send")))))) :selected "messages") (conversation-add-person :text text :next next))) (defun conversation-add-person (&key people subject text next (results 'none)) (standard-page "Add person to conversation" (html (:div :class "item" (:form :method "post" :class "conversation recipients" :action "/conversations/new" (:button :type "submit" :class "simple-link green" :name "cancel-add" "↩ go back") (:h2 "Who would you like to add to the conversation?") (:h3 "Search for a person") (:input :type "text" :name "name") (:button :type "submit" :class "yes input-height" :name "search" "Search") (if (eq results 'none) (progn (htm (:h3 "Or, select one of your contacts:") (:menu :type "toolbar" (dolist (contact (contacts-alphabetically *user*)) (htm (:li (:button :class "text" :type "submit" :value (car contact) :name "add" (str (cadr contact))))))))) (progn (htm (:h3 "Search results") (dolist (person results) (str (id-button (car person) "add" (cdr person))))))) (:input :type "submit" :class "cancel" :value "Back") (when people (htm (:input :type "hidden" :name "people" :value (format nil "~{~A~^,~}" people)))) (when next (htm (:input :type "hidden" :name "next" :value next))) (when subject (htm (:input :type "hidden" :name "subject" :value subject))) (when text (htm (:input :type "hidden" :name "text" :value (escape-for-html text)))) ))) :selected "messages")) (defun get-conversations-new () (require-user (:require-active-user t :require-email t) (if (getf *user* :pending) (progn (pending-flash "contact other Kindista members") (see-other (or (referer) "/home"))) (new-conversation :people (parse-subject-list (get-parameter "people")))))) (defun post-conversations-new () (require-user (:require-active-user t :require-email t) (cond ((getf *user* :pending) (pending-flash "contact other Kindista members") (see-other (or (post-parameter "next") "/home"))) ((or (post-parameter "cancel") (and (post-parameter "cancel-add") (not (post-parameter "people")))) (see-other (or (post-parameter "next") "/messages"))) ((post-parameter "send") (let ((people (parse-subject-list (post-parameter "people") :remove (write-to-string *userid*))) (text (post-parameter "text")) (subject (post-parameter "subject"))) (when (string= subject "") (setf subject nil)) (when (string= text "") (setf text nil)) (cond ((and people text subject) (flash "Your message has been sent.") (contact-opt-out-flash (append (list *userid*) people)) (see-other (format nil (or (post-parameter "next") "/conversations/~A") (create-conversation :people people :public nil :subject subject :text text)))) ((and people subject) "no text") ((and people text) "no subject") ((and subject text) "no recipients") (text "no people OR subject") (people "no text OR subject") (subject "no text OR recipients") (t "totally blank")))) ((post-parameter "add") (if (string= (post-parameter "add") "new") (conversation-add-person :people (parse-subject-list (post-parameter "people")) :text (post-parameter "text") :subject (post-parameter "subject") :next (post-parameter "next")) (new-conversation :text (post-parameter "text") :subject (post-parameter "subject") :next (post-parameter "next") :single-recipient (post-parameter "single-recipient") :people (parse-subject-list (format nil "~A,~A" (post-parameter "add") (post-parameter "people")))))) ((post-parameter "search") (conversation-add-person :people (parse-subject-list (post-parameter "people")) :text (post-parameter "text") :subject (post-parameter "subject") :next (post-parameter "next") :results (search-people (post-parameter "name")))) (t (new-conversation :text (post-parameter "text") :subject (post-parameter "subject") :people (parse-subject-list (post-parameter "people") :remove (post-parameter "remove"))))))) (defun go-conversation (id) (moved-permanently (strcat "/conversations/" id))) (defun conversation-comments (conversation-id latest-seen) (html (dolist (comment-id (gethash conversation-id *comment-index*)) (let* ((data (db comment-id)) (by (car (getf data :by))) (for (cdr (getf data :by))) (text (getf data :text))) (when data (str (conversation-comment-html data by (db by :name) for (db for :name) text (when (>= (or latest-seen 0) comment-id)) :id comment-id))))))) (defun conversation-comment-html (data by by-name for for-name text newp &key transaction-p id) (card id (html (str (h3-timestamp (getf data :created))) (:p :id id (if transaction-p (htm (:strong (str by-name))) (htm (:a :href (s+ "/people/" (username-or-id by)) (str by-name)))) (when for (htm (:strong (str (if transaction-p " (on behalf of " " (from ")) (str for-name) ") "))) (when transaction-p (htm (:strong " responded:")))) (:p :class (when newp "new") (str (regex-replace-all "\\n" text "<br>")))))) (defun conversation-html (id data with comments-html &key error) (standard-page (aif (getf data :subject) (ellipsis it :length 24) "Conversation") (html (str (menu-horiz (html (:a :href "/messages" "back to messages")) (html (:a :href "#reply" "reply"))) ) (str (card id (html (when (getf data :subject) (htm (:h2 "Subject: " (str (getf data :subject))))) (if with (htm (:p "with " (str (name-list-all with)))) (htm (:p :class "error" "Everybody else has left this conversation.")))))) (:div :class "item" :id "reply" (:h4 "post a reply") (:form :method "post" :action (script-name*) (:textarea :cols "150" :rows "4" :name "text") (:div :class (when (eq error :no-reply-type) "error-border")) (:button :class "yes" :type "submit" :class "submit" "Send"))) (str comments-html)) :selected "messages")) (defun get-conversation (id) "when called, (modify-db conversation-id :people '((userid . this-comment-id) (other-user-id . whatever)))" (require-user () (setf id (parse-integer id)) (let* ((message (gethash id *db-messages*)) (people (message-people message)) (valid-mailboxes (loop for person in people when (eql *userid* (caar person)) collect person)) (type (message-type message))) (case type (:conversation (if valid-mailboxes (let* ((conversation (db id)) (person (assoc-assoc *userid* people)) (latest-comment (getf conversation :latest-comment)) (latest-seen (or (when (numberp (cdr person)) (cdr person)) latest-comment)) (with (remove *userid* (getf conversation :participants)))) (prog1 (conversation-html id conversation with (conversation-comments id latest-seen)) (when (or (not (eql (message-latest-comment message) (cdr (assoc-assoc *userid* (message-people message))))) (member *userid* (getf (message-folders message) :unread))) (update-folder-data message :read :last-read-comment (message-latest-comment message))))) (permission-denied))) (:transaction (see-other (strcat "/transactions/" id))) (t (not-found)))))) (defun get-conversation-leave (id) (require-user () (setf id (parse-integer id)) (let ((it (db id))) (if (and it (eql (getf it :type) :conversation)) (if (member *userid* (mapcar #'first (getf it :people))) (standard-page "Leave conversation" (html (:h2 "Are you sure you want to leave this conversation?") (:p "You won't be able to re-join the conversation after leaving.") (:p (:strong "Subject: ") (str (getf it :subject))) (:form :method "post" :action (strcat "/conversations/" id) (:a :href (strcat "/conversations/" id) "No, I didn't mean it!") (:button :class "yes" :type "submit" :class "submit" :name "leave" "Yes"))) :selected "messages") (permission-denied)) (not-found))))) (defun post-conversation (id) (require-active-user (setf id (parse-integer id)) (aif (db id) (let* ((people (getf it :people)) (mailbox (assoc-assoc *userid* people)) (party (car mailbox))) (if party (cond ((post-parameter "leave") (amodify-db id :people (remove *userid* it :key #'caar)) (see-other "/messages")) ((post-parameter "text") (flash "Your message has been sent.") (contact-opt-out-flash (mapcar #'caar people)) (create-comment :on id :text (post-parameter "text") :by party) (see-other (script-name*)))) (permission-denied))) (not-found))))
d50084a93ccfc350afbfa8350ab1bc6345bb7e580f51bf2913adbb9429e167ec
Factual/skuld
bin.clj
(ns skuld.bin (:use [clj-helix.logging :only [mute]] [clojure.tools.cli :only [cli]] clojure.tools.logging) (:require [skuld.admin :as admin] [skuld.node :as node] [skuld.flake :as flake] [skuld.http]) (:import (sun.misc Signal SignalHandler)) (:gen-class)) (defn parse-int "Parse an integer." [^String s] (Integer. s)) (defmacro signal "Adds a signal handler." [signal & body] `(when-not (.contains (System/getProperty "os.name") "Windows") (Signal/handle (Signal. (name ~signal)) (reify SignalHandler (handle [this# sig#] ~@body))))) (def admin-spec [["-z" "--zookeeper" "Zookeeper connection string" :default "localhost:2181"] ["-c" "--cluster" "Cluster name" :default "skuld"] ["-partitions" "--partitions" "Number of partitions" :default 1 :parse-fn parse-int] ["-r" "--replicas" "Number of replicas" :default 3 :parse-fn parse-int]]) (def node-spec [["-z" "--zookeeper" "Zookeeper connection string" :default "localhost:2181"] ["-p" "--port" "Port" :default "13000" :parse-fn parse-int] ["-h" "--host" "Hostname" :default "127.0.0.1"]]) ; Cluster configuration (defn cluster-create [& args] (let [[opts _ _] (apply cli args admin-spec)] (admin/create-cluster! (admin/admin opts)))) (defn cluster-destroy [& args] (let [[opts _ _] (apply cli args admin-spec)] (admin/destroy-cluster! (admin/admin opts)))) (defn cluster-add [& args] (let [[opts _ _] (apply cli args (concat node-spec admin-spec))] (admin/add-node! (admin/admin opts) (select-keys opts [:host :port])))) (defn cluster [cmd & args] (apply (case cmd "create" cluster-create "add" cluster-add "destroy" cluster-destroy) args)) Node management (defn controller [& args] (let [[opts _ _] (apply cli args node-spec) controller (node/controller opts)] (.addShutdownHook (Runtime/getRuntime) (Thread. (bound-fn [] (node/shutdown! controller)))) (info "Controller started.") (debug controller) @(promise))) (defn start [& args] (flake/init!) (let [[opts _ _] (apply cli args node-spec) node (node/node opts)] (.addShutdownHook (Runtime/getRuntime) (Thread. (bound-fn [] (node/shutdown! node)))) (info :started node) @(promise))) (defn -main [cmd & args] (try (apply (case cmd "cluster" cluster "controller" controller "start" start) args) (catch Throwable t (.printStackTrace t) (System/exit 1))))
null
https://raw.githubusercontent.com/Factual/skuld/79599f9b13aee35c680183d6bf9e2fcbfde1d7c7/src/skuld/bin.clj
clojure
Cluster configuration
(ns skuld.bin (:use [clj-helix.logging :only [mute]] [clojure.tools.cli :only [cli]] clojure.tools.logging) (:require [skuld.admin :as admin] [skuld.node :as node] [skuld.flake :as flake] [skuld.http]) (:import (sun.misc Signal SignalHandler)) (:gen-class)) (defn parse-int "Parse an integer." [^String s] (Integer. s)) (defmacro signal "Adds a signal handler." [signal & body] `(when-not (.contains (System/getProperty "os.name") "Windows") (Signal/handle (Signal. (name ~signal)) (reify SignalHandler (handle [this# sig#] ~@body))))) (def admin-spec [["-z" "--zookeeper" "Zookeeper connection string" :default "localhost:2181"] ["-c" "--cluster" "Cluster name" :default "skuld"] ["-partitions" "--partitions" "Number of partitions" :default 1 :parse-fn parse-int] ["-r" "--replicas" "Number of replicas" :default 3 :parse-fn parse-int]]) (def node-spec [["-z" "--zookeeper" "Zookeeper connection string" :default "localhost:2181"] ["-p" "--port" "Port" :default "13000" :parse-fn parse-int] ["-h" "--host" "Hostname" :default "127.0.0.1"]]) (defn cluster-create [& args] (let [[opts _ _] (apply cli args admin-spec)] (admin/create-cluster! (admin/admin opts)))) (defn cluster-destroy [& args] (let [[opts _ _] (apply cli args admin-spec)] (admin/destroy-cluster! (admin/admin opts)))) (defn cluster-add [& args] (let [[opts _ _] (apply cli args (concat node-spec admin-spec))] (admin/add-node! (admin/admin opts) (select-keys opts [:host :port])))) (defn cluster [cmd & args] (apply (case cmd "create" cluster-create "add" cluster-add "destroy" cluster-destroy) args)) Node management (defn controller [& args] (let [[opts _ _] (apply cli args node-spec) controller (node/controller opts)] (.addShutdownHook (Runtime/getRuntime) (Thread. (bound-fn [] (node/shutdown! controller)))) (info "Controller started.") (debug controller) @(promise))) (defn start [& args] (flake/init!) (let [[opts _ _] (apply cli args node-spec) node (node/node opts)] (.addShutdownHook (Runtime/getRuntime) (Thread. (bound-fn [] (node/shutdown! node)))) (info :started node) @(promise))) (defn -main [cmd & args] (try (apply (case cmd "cluster" cluster "controller" controller "start" start) args) (catch Throwable t (.printStackTrace t) (System/exit 1))))
253b701898ab70c3f8efbf3b9b205c51fe72139a69248b9ccfdea59e1696da38
flodihn/NextGen
recv_loop.erl
-module(recv_loop). -export([ recv_loop/3 ]). -include("state.hrl"). -include("protocol.hrl"). -define(TIMEOUT, 200). recv_loop(Owner, Socket, #recv_state{id=Id, bytes_recv=BytesRecv, cmds_recv=CmdsRecv, resp_times=RespTimes, debug_output=DebugOutput} = State) -> Since we do n't need flow controler in recv loop whe call it before % data is received. inet:setopts(Socket, [{active, once}]), receive {get_state} -> Owner ! State; {tcp, Socket, <<?NOTIFY_PONG, BinTime/binary>> = Data} -> Diff = binary_time_to_diff(BinTime), %io:format("Got ping ms: ~p.~n", [Diff/1000]), NewBytesRecv = BytesRecv + byte_size(Data) + 2, recv_loop(Owner, Socket, State#recv_state{bytes_recv=NewBytesRecv, cmds_recv=CmdsRecv + 1, resp_times=[Diff] ++ RespTimes}); {tcp, Socket, <<?OBJ_DIR, IdLen/integer, Id:IdLen/binary, _X/little-float, _Y/little-float, Z/little-float, BinTime/binary>> = Data} -> Diff = time(), %Diff = binary_time_to_diff(BinTime), %io:format("OBJ_DIR ms: ~p.~n", [Diff/1000]), NewBytesRecv = BytesRecv + byte_size(Data) + 2, recv_loop(Owner, Socket, State#recv_state{bytes_recv=NewBytesRecv, cmds_recv=CmdsRecv + 1, resp_times=[Diff] ++ RespTimes}); {tcp, Socket, <<?OBJ_SPEED, IdLen/integer, Id:IdLen/binary, Speed/little-float, BinTime/binary>> = Data} -> Diff = binary_time_to_diff(BinTime), NewBytesRecv = BytesRecv + byte_size(Data) + 2, %io:format("OBJ_SPEED ms: ~p.~n", [Diff/1000]), recv_loop(Owner, Socket, State#recv_state{bytes_recv=NewBytesRecv, cmds_recv=CmdsRecv + 1, resp_times=[Diff] ++ RespTimes}); {tcp, Socket, Data} -> debug(Data, DebugOutput), NewBytesRecv = BytesRecv + byte_size(Data) + 2, recv_loop(Owner, Socket, State#recv_state{bytes_recv=NewBytesRecv, cmds_recv=CmdsRecv + 1}); Other -> error_logger:error_report([{unknown_data, Other}]) after ?TIMEOUT -> recv_loop(Owner, Socket, State) end. binary_time_to_diff(Binary) -> case Binary of <<>> -> -1; _ValidTime -> Time = binary_to_term(Binary), timer:now_diff(now(), Time) / 1000 end. debug(Msg, false) -> ok; debug(Msg, true) -> io:format("~p.~n", [Msg]).
null
https://raw.githubusercontent.com/flodihn/NextGen/3da1c3ee0d8f658383bdf5fccbdd49ace3cdb323/TestSuite/src/recv_loop.erl
erlang
data is received. io:format("Got ping ms: ~p.~n", [Diff/1000]), Diff = binary_time_to_diff(BinTime), io:format("OBJ_DIR ms: ~p.~n", [Diff/1000]), io:format("OBJ_SPEED ms: ~p.~n", [Diff/1000]),
-module(recv_loop). -export([ recv_loop/3 ]). -include("state.hrl"). -include("protocol.hrl"). -define(TIMEOUT, 200). recv_loop(Owner, Socket, #recv_state{id=Id, bytes_recv=BytesRecv, cmds_recv=CmdsRecv, resp_times=RespTimes, debug_output=DebugOutput} = State) -> Since we do n't need flow controler in recv loop whe call it before inet:setopts(Socket, [{active, once}]), receive {get_state} -> Owner ! State; {tcp, Socket, <<?NOTIFY_PONG, BinTime/binary>> = Data} -> Diff = binary_time_to_diff(BinTime), NewBytesRecv = BytesRecv + byte_size(Data) + 2, recv_loop(Owner, Socket, State#recv_state{bytes_recv=NewBytesRecv, cmds_recv=CmdsRecv + 1, resp_times=[Diff] ++ RespTimes}); {tcp, Socket, <<?OBJ_DIR, IdLen/integer, Id:IdLen/binary, _X/little-float, _Y/little-float, Z/little-float, BinTime/binary>> = Data} -> Diff = time(), NewBytesRecv = BytesRecv + byte_size(Data) + 2, recv_loop(Owner, Socket, State#recv_state{bytes_recv=NewBytesRecv, cmds_recv=CmdsRecv + 1, resp_times=[Diff] ++ RespTimes}); {tcp, Socket, <<?OBJ_SPEED, IdLen/integer, Id:IdLen/binary, Speed/little-float, BinTime/binary>> = Data} -> Diff = binary_time_to_diff(BinTime), NewBytesRecv = BytesRecv + byte_size(Data) + 2, recv_loop(Owner, Socket, State#recv_state{bytes_recv=NewBytesRecv, cmds_recv=CmdsRecv + 1, resp_times=[Diff] ++ RespTimes}); {tcp, Socket, Data} -> debug(Data, DebugOutput), NewBytesRecv = BytesRecv + byte_size(Data) + 2, recv_loop(Owner, Socket, State#recv_state{bytes_recv=NewBytesRecv, cmds_recv=CmdsRecv + 1}); Other -> error_logger:error_report([{unknown_data, Other}]) after ?TIMEOUT -> recv_loop(Owner, Socket, State) end. binary_time_to_diff(Binary) -> case Binary of <<>> -> -1; _ValidTime -> Time = binary_to_term(Binary), timer:now_diff(now(), Time) / 1000 end. debug(Msg, false) -> ok; debug(Msg, true) -> io:format("~p.~n", [Msg]).
54afcbd7eb5e056b79f3dfab7911751d4007f353a948e7396fbba4618b55326a
8c6794b6/haskell-sc-scratch
TTF.hs
# LANGUAGE NoMonomorphismRestriction # | Module : $ Header$ CopyRight : ( c ) 8c6794b6 License : : Stability : unstable Portability : non - portable Lecture : < -final/course/TTF.hs > Module : $Header$ CopyRight : (c) 8c6794b6 License : BSD3 Maintainer : Stability : unstable Portability : non-portable Lecture: <-final/course/TTF.hs> -} module TTF where class Symantics repr where int :: Int -> repr Int add :: repr Int -> repr Int -> repr Int lam :: (repr a -> repr b) -> repr (a->b) app :: repr (a->b) -> repr a -> repr b th1 = add (int 1) (int 2) th2 = lam (\x -> add x x) th3 = lam (\x -> add (app x (int 1)) (int 2)) newtype R a = R {unR :: a} instance Symantics R where int x = R x add e1 e2 = R $ unR e1 + unR e2 lam f = R $ (\x -> unR (f (R x))) app f a = R $ (unR f) (unR a) eval e = unR e th1_eval = eval th1 th2_eval = eval th2 th2_eval' = eval th2 21 -- th3_eval :: (Int -> Int) -> Int th3_eval = eval th3 type VarCounter = Int newtype S a = S {unS :: VarCounter -> String} instance Symantics S where int x = S $ const $ show x add e1 e2 = S $ \h -> "(" ++ unS e1 h ++ "+" ++ unS e2 h ++ ")" lam e = S $ \h -> let x = "x" ++ show h in "(\\" ++ x ++ " -> " ++ unS (e (S $ const x)) (succ h) ++ ")" app e1 e2 = S $ \h -> "(" ++ unS e1 h ++ " " ++ unS e2 h ++ ")" view e = unS e 0 view_th1 = view th1 view_th2 = view th2 view_th3 = view th3 class MulSYM repr where mul :: repr Int -> repr Int -> repr Int class BoolSYM repr where bool :: Bool -> repr Bool leq :: repr Int -> repr Int -> repr Bool if_ :: repr Bool -> repr a -> repr a -> repr a class FixSYM repr where fix :: (repr a -> repr a) -> repr a tpow = lam (\x -> fix (\self -> lam (\n -> if_ (leq n (int 0)) (int 1) (mul x (app self (add n (int (-1)))))))) tpow7 = lam (\x -> app (app tpow x) (int 7)) tpow72 = app tpow7 (int 2) instance MulSYM R where mul e1 e2 = R $ unR e1 * unR e2 instance BoolSYM R where bool b = R b leq e1 e2 = R $ unR e1 <= unR e2 if_ be et ef = R $ if unR be then unR et else unR ef instance FixSYM R where fix f = R $ fx (unR . f . R) where fx f = f (fx f) tpow_eval = eval tpow -- Int -> Int -> Int 128 instance MulSYM S where mul e1 e2 = S $ \h -> unS e1 h ++ "*" ++ unS e2 h instance BoolSYM S where bool x = S $ const $ show x leq e1 e2 = S $ \h -> "(" ++ unS e1 h ++ "<=" ++ unS e2 h ++ ")" if_ be et ee = S $ \h -> unwords ["(if", unS be h, "then", unS et h, "else", unS ee h, ")"] instance FixSYM S where fix e = S $ \h -> let self = "self" ++ show h in "(fix " ++ self ++ "." ++ unS (e (S $ const self)) (succ h) ++ ")"
null
https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/Oleg/TTF/Course/TTF.hs
haskell
th3_eval :: (Int -> Int) -> Int Int -> Int -> Int
# LANGUAGE NoMonomorphismRestriction # | Module : $ Header$ CopyRight : ( c ) 8c6794b6 License : : Stability : unstable Portability : non - portable Lecture : < -final/course/TTF.hs > Module : $Header$ CopyRight : (c) 8c6794b6 License : BSD3 Maintainer : Stability : unstable Portability : non-portable Lecture: <-final/course/TTF.hs> -} module TTF where class Symantics repr where int :: Int -> repr Int add :: repr Int -> repr Int -> repr Int lam :: (repr a -> repr b) -> repr (a->b) app :: repr (a->b) -> repr a -> repr b th1 = add (int 1) (int 2) th2 = lam (\x -> add x x) th3 = lam (\x -> add (app x (int 1)) (int 2)) newtype R a = R {unR :: a} instance Symantics R where int x = R x add e1 e2 = R $ unR e1 + unR e2 lam f = R $ (\x -> unR (f (R x))) app f a = R $ (unR f) (unR a) eval e = unR e th1_eval = eval th1 th2_eval = eval th2 th2_eval' = eval th2 21 th3_eval = eval th3 type VarCounter = Int newtype S a = S {unS :: VarCounter -> String} instance Symantics S where int x = S $ const $ show x add e1 e2 = S $ \h -> "(" ++ unS e1 h ++ "+" ++ unS e2 h ++ ")" lam e = S $ \h -> let x = "x" ++ show h in "(\\" ++ x ++ " -> " ++ unS (e (S $ const x)) (succ h) ++ ")" app e1 e2 = S $ \h -> "(" ++ unS e1 h ++ " " ++ unS e2 h ++ ")" view e = unS e 0 view_th1 = view th1 view_th2 = view th2 view_th3 = view th3 class MulSYM repr where mul :: repr Int -> repr Int -> repr Int class BoolSYM repr where bool :: Bool -> repr Bool leq :: repr Int -> repr Int -> repr Bool if_ :: repr Bool -> repr a -> repr a -> repr a class FixSYM repr where fix :: (repr a -> repr a) -> repr a tpow = lam (\x -> fix (\self -> lam (\n -> if_ (leq n (int 0)) (int 1) (mul x (app self (add n (int (-1)))))))) tpow7 = lam (\x -> app (app tpow x) (int 7)) tpow72 = app tpow7 (int 2) instance MulSYM R where mul e1 e2 = R $ unR e1 * unR e2 instance BoolSYM R where bool b = R b leq e1 e2 = R $ unR e1 <= unR e2 if_ be et ef = R $ if unR be then unR et else unR ef instance FixSYM R where fix f = R $ fx (unR . f . R) where fx f = f (fx f) 128 instance MulSYM S where mul e1 e2 = S $ \h -> unS e1 h ++ "*" ++ unS e2 h instance BoolSYM S where bool x = S $ const $ show x leq e1 e2 = S $ \h -> "(" ++ unS e1 h ++ "<=" ++ unS e2 h ++ ")" if_ be et ee = S $ \h -> unwords ["(if", unS be h, "then", unS et h, "else", unS ee h, ")"] instance FixSYM S where fix e = S $ \h -> let self = "self" ++ show h in "(fix " ++ self ++ "." ++ unS (e (S $ const self)) (succ h) ++ ")"
07f8b90f88b04fb8a6c391f527e23efee24f13e12c38d89941301a01cc341d9c
careercup/CtCI-6th-Edition-Clojure
chapter_2_q6.clj
(ns ^{:author "Leeor Engel"} chapter-2.chapter-2-q6) (defn palindrome? [l] (= l (reverse l)))
null
https://raw.githubusercontent.com/careercup/CtCI-6th-Edition-Clojure/ef151b94978af82fb3e0b1b0cd084d910870c52a/src/chapter_2/chapter_2_q6.clj
clojure
(ns ^{:author "Leeor Engel"} chapter-2.chapter-2-q6) (defn palindrome? [l] (= l (reverse l)))
056989c7d3357754a484109ab46ee7eb7888e6696282cdfa1adc587d1fa22498
nakagami/efirebirdsql
efirebirdsql_conv_tests.erl
The MIT License ( MIT ) Copyright ( c ) 2021 Hajime Nakagami< > -module(efirebirdsql_conv_tests). -include_lib("eunit/include/eunit.hrl"). params_to_blr_test() -> Firebird 2.5 {Blr, Value} = efirebirdsql_conv:params_to_blr(11, maps:new(), [nil]), ?assertEqual("0502040002000E00000700FF4C", efirebirdsql_srp:to_hex(Blr)), ?assertEqual("FFFFFFFF", efirebirdsql_srp:to_hex(Value)), Firebird 3 + {Blr1, Value1} = efirebirdsql_conv:params_to_blr(13, maps:new(), [nil]), ?assertEqual("0502040002000E00000700FF4C", efirebirdsql_srp:to_hex(Blr1)), ?assertEqual("01000000", efirebirdsql_srp:to_hex(Value1)), {Blr2, Value2} = efirebirdsql_conv:params_to_blr(13, maps:new(), ["foo", 1]), ?assertEqual("0502040004000E0300070008000700FF4C", efirebirdsql_srp:to_hex(Blr2)), ?assertEqual("00000000666F6F0000000001", efirebirdsql_srp:to_hex(Value2)), {Blr3, Value3} = efirebirdsql_conv:params_to_blr(13, maps:new(), [nil, nil, nil]), ?assertEqual("0502040006000E000007000E000007000E00000700FF4C", efirebirdsql_srp:to_hex(Blr3)), ?assertEqual("07000000", efirebirdsql_srp:to_hex(Value3)), {Blr4, Value4} = efirebirdsql_conv:params_to_blr(13, maps:new(), [nil, "foo", nil]), ?assertEqual("0502040006000E000007000E030007000E00000700FF4C", efirebirdsql_srp:to_hex(Blr4)), ?assertEqual("05000000666F6F00", efirebirdsql_srp:to_hex(Value4)), {Blr5, Value5} = efirebirdsql_conv:params_to_blr(13, maps:new(), ["foo", nil]), ?assertEqual("0502040004000E030007000E00000700FF4C", efirebirdsql_srp:to_hex(Blr5)), ?assertEqual("02000000666F6F00", efirebirdsql_srp:to_hex(Value5)).
null
https://raw.githubusercontent.com/nakagami/efirebirdsql/ab14ff8b8e4d856086d828a7f5b44f4b8436dce5/test/efirebirdsql_conv_tests.erl
erlang
The MIT License ( MIT ) Copyright ( c ) 2021 Hajime Nakagami< > -module(efirebirdsql_conv_tests). -include_lib("eunit/include/eunit.hrl"). params_to_blr_test() -> Firebird 2.5 {Blr, Value} = efirebirdsql_conv:params_to_blr(11, maps:new(), [nil]), ?assertEqual("0502040002000E00000700FF4C", efirebirdsql_srp:to_hex(Blr)), ?assertEqual("FFFFFFFF", efirebirdsql_srp:to_hex(Value)), Firebird 3 + {Blr1, Value1} = efirebirdsql_conv:params_to_blr(13, maps:new(), [nil]), ?assertEqual("0502040002000E00000700FF4C", efirebirdsql_srp:to_hex(Blr1)), ?assertEqual("01000000", efirebirdsql_srp:to_hex(Value1)), {Blr2, Value2} = efirebirdsql_conv:params_to_blr(13, maps:new(), ["foo", 1]), ?assertEqual("0502040004000E0300070008000700FF4C", efirebirdsql_srp:to_hex(Blr2)), ?assertEqual("00000000666F6F0000000001", efirebirdsql_srp:to_hex(Value2)), {Blr3, Value3} = efirebirdsql_conv:params_to_blr(13, maps:new(), [nil, nil, nil]), ?assertEqual("0502040006000E000007000E000007000E00000700FF4C", efirebirdsql_srp:to_hex(Blr3)), ?assertEqual("07000000", efirebirdsql_srp:to_hex(Value3)), {Blr4, Value4} = efirebirdsql_conv:params_to_blr(13, maps:new(), [nil, "foo", nil]), ?assertEqual("0502040006000E000007000E030007000E00000700FF4C", efirebirdsql_srp:to_hex(Blr4)), ?assertEqual("05000000666F6F00", efirebirdsql_srp:to_hex(Value4)), {Blr5, Value5} = efirebirdsql_conv:params_to_blr(13, maps:new(), ["foo", nil]), ?assertEqual("0502040004000E030007000E00000700FF4C", efirebirdsql_srp:to_hex(Blr5)), ?assertEqual("02000000666F6F00", efirebirdsql_srp:to_hex(Value5)).
1886945a63a6f27539df74291367b49b423a80c4dbce47cde1822dd782fd296d
cirodrig/triolet
Driver.hs
module SystemF.Datatypes.Driver (overriddenSerializerTypes, computeDataTypeInfo, addLayoutVariablesToTypeEnvironment ) where import Control.DeepSeq import Control.Monad import Control.Monad.Trans import qualified Data.IntMap as IntMap import Data.Maybe import Debug.Trace import Text.PrettyPrint.HughesPJ import Common.Error import Common.Identifier import Common.Label import Common.Supply import Common.MonadLogic import Type.Type import Type.Environment import Type.Compare import Type.Eval import qualified LowLevel.Syntax as LL import SystemF.Syntax import SystemF.MemoryIR import SystemF.Datatypes.Structure import SystemF.Datatypes.TypeObject -- | Type constructors that do not use auto-generated serializer and -- deserializer functions. The serializer and deserializer functions -- are explicitly defined. -- List of (tycon, (serializer, deserializer)) tuples. -- -- This information is used when generating serializer/deserializer code. overriddenSerializerTypes :: [(Var, (Var, Var))] overriddenSerializerTypes = [ (listSectionV, (putListSection_optimizedV, getListSection_optimizedV)) , (array2SectionV, (putArray2Section_optimizedV, getArray2Section_optimizedV)) ] -- | Primitive value types. These get special auto-generated definitions. primitiveValTypes :: [Var] primitiveValTypes = [intV, uintV, floatV, int64V] -- | Compute layout information for all algebraic data types in the -- given environment. The type environment is modified in-place -- by adding layout information to data types and by adding -- global serializer functions to the type environment. -- -- Returns a list of all data types for which info was created and a -- list of global variable definitions. computeDataTypeInfo :: IdentSupply LL.Var -> IdentSupply Var -> TypeEnv -> IO ([Var], [GDef Mem]) computeDataTypeInfo ll_var_supply var_supply type_env = runTypeEvalM compute var_supply type_env where compute = do -- Create layout information for each algebraic data type -- and update the type environment m_dtypes_needing_info <- mapM setLayoutInformation =<< get_algebraic_data_types let dtypes_needing_info = catMaybes m_dtypes_needing_info -- Create and return definitions of the info variables defss <- assume_info_vars dtypes_needing_info $ sequence [ -- Algebraic types liftM concat $ mapM define_info_var dtypes_needing_info -- Primitive types , liftM concat $ mapM define_primitive_info_var primitiveValTypes ] return (dtypes_needing_info, concat defss) define_primitive_info_var data_type_con = do Just dtype <- lookupDataType data_type_con definePrimitiveValInfo ll_var_supply dtype -- Create definitions for the info variables define_info_var :: Var -> UnboxedTypeEvalM [GDef Mem] define_info_var data_type_con = do Just dtype <- lookupDataType data_type_con case dataTypeKind dtype of ValK -> valInfoDefinition ll_var_supply dtype BareK -> bareInfoDefinition ll_var_supply dtype BoxK -> boxInfoDefinitions ll_var_supply dtype -- Given a list of data type constructors, add all their info variables -- to the environment assume_info_vars :: [Var] -> UnboxedTypeEvalM a -> UnboxedTypeEvalM a assume_info_vars data_type_cons m = do dtypes <- mapM lookupDataType data_type_cons -- For each data type, for each info variable, create a binding let bindings :: [Binder] bindings = [ v ::: infoConstructorType dtype | m_dtype <- dtypes , let Just dtype = m_dtype , v <- layoutInfoVars $ dataTypeLayout' dtype ] assumeBinders bindings m get_algebraic_data_types :: UnboxedTypeEvalM [DataType] get_algebraic_data_types = do i_type_env <- freezeTypeEnv return $ filter dataTypeIsAlgebraic $ IntMap.elems $ getAllDataTypeConstructors i_type_env -- | Compute size parameters for an algebraic data type constructor, and -- save them in the type environment. -- -- Save the types of any newly created serializer and deserializer -- functions in the type environment. -- The function definitions are not created until later. -- -- If a new info variable was created, return the data type constructor. setLayoutInformation :: DataType -> UnboxedTypeEvalM (Maybe Var) setLayoutInformation dtype | not $ dataTypeIsAlgebraic dtype = internalError "setLayoutInformation" | isJust $ dataTypeLayout dtype = -- Information is already set return Nothing | otherwise = do -- Compute the size parameters variance <- computeDataSizes dtype unless (map binderVar (dtsTyParams variance) == map binderVar (dataTypeParams dtype)) $ internalError "computeSizeParameters" layout <- createLayouts dtype (dtsSizeParamTypes variance) (dtsStaticTypes variance) -- Save layout information setLayout (dataTypeCon dtype) layout return $ Just (dataTypeCon dtype) createLayouts dtype size_param_types static_types = case dataTypeKind dtype of BoxK -> constructor_layouts BareK -> unboxed_layout ValK -> unboxed_layout where Create one layout for each data constructor constructor_layouts = do -- Create an info constructor and field size computation code xs <- createConstructorTable createInfoVariable dtype sers <- createConstructorTable createSerializerVariable dtype dess <- createConstructorTable createDeserializerVariable dtype fs <- createConstructorTable createSizeVariable dtype return $ boxedDataTypeLayout size_param_types static_types xs sers dess fs Create one layout for the data type unboxed_layout = do i <- createInfoVariable (dataTypeCon dtype) ser <- createSerializerVariable (dataTypeCon dtype) des <- createDeserializerVariable (dataTypeCon dtype) fs <- createConstructorTable createSizeVariable dtype return $ unboxedDataTypeLayout size_param_types static_types i ser des fs -- | Create a lookup table indexed by constructors. createConstructorTable :: (Var -> UnboxedTypeEvalM a) -> DataType -> UnboxedTypeEvalM [(Var, a)] createConstructorTable f dtype = forM (dataTypeDataConstructors dtype) $ \c -> do i <- f c return (c, i) -- | Create a new variable whose name consists of the given label -- extended with some extra string. createVariable :: String -> Maybe Label -> UnboxedTypeEvalM Var createVariable str data_label = do let info_name = case data_label of Nothing -> Nothing Just lab -> case labelLocalName lab of Left s -> let s' = s ++ str in Just (lab {labelLocalName = Left s'}) Right _ -> Nothing newVar info_name ObjectLevel createInfoVariable = newTaggedVar TypeInfoLabel createSizeVariable v = createVariable "_size" $ varName v createSerializerVariable = newTaggedVar SerializerLabel createDeserializerVariable = newTaggedVar DeserializerLabel ------------------------------------------------------------------------------- -- | Add the types of layout-related functions to the environment for the -- given list of data types. It should be the list that was returned by ' computeDataTypeInfo ' . -- The type environment is modified in-place. addLayoutVariablesToTypeEnvironment :: [Var] -> TypeEnv -> IO () addLayoutVariablesToTypeEnvironment vs tenv = do mapM_ add_generated_datatype vs mapM_ add_primitive_datatype primitiveValTypes where add_primitive_datatype v = do -- Look up the updated data type Just dtype <- runTypeEnvM tenv $ lookupDataType v -- Compute function types let info_type = infoConstructorType dtype insertGlobalType tenv (dataTypeUnboxedInfoVar dtype) info_type add_generated_datatype v = do -- Look up the updated data type Just dtype <- runTypeEnvM tenv $ lookupDataType v -- Compute function types let info_type = infoConstructorType dtype ser_type = serializerType dtype des_type = deserializerType dtype data_constructors = dataTypeDataConstructors dtype -- Process variables for each constructor of a boxed type let constructor_layouts = forM_ data_constructors $ \dcon -> do insertGlobalType tenv (dataTypeBoxedInfoVar dtype dcon) info_type insertGlobalType tenv (dataTypeBoxedSerializerVar dtype dcon) ser_type insertGlobalType tenv (dataTypeBoxedDeserializerVar dtype dcon) des_type Only one of each variable for a bare type let unboxed_layout = do insertGlobalType tenv (dataTypeUnboxedInfoVar dtype) info_type insertGlobalType tenv (dataTypeUnboxedSerializerVar dtype) ser_type insertGlobalType tenv (dataTypeUnboxedDeserializerVar dtype) des_type case dataTypeKind dtype of BoxK -> constructor_layouts BareK -> unboxed_layout ValK -> unboxed_layout
null
https://raw.githubusercontent.com/cirodrig/triolet/e515a1dc0d6b3e546320eac7b71fb36cea5b53d0/src/program/SystemF/Datatypes/Driver.hs
haskell
| Type constructors that do not use auto-generated serializer and deserializer functions. The serializer and deserializer functions are explicitly defined. List of (tycon, (serializer, deserializer)) tuples. This information is used when generating serializer/deserializer code. | Primitive value types. These get special auto-generated definitions. | Compute layout information for all algebraic data types in the given environment. The type environment is modified in-place by adding layout information to data types and by adding global serializer functions to the type environment. Returns a list of all data types for which info was created and a list of global variable definitions. Create layout information for each algebraic data type and update the type environment Create and return definitions of the info variables Algebraic types Primitive types Create definitions for the info variables Given a list of data type constructors, add all their info variables to the environment For each data type, for each info variable, create a binding | Compute size parameters for an algebraic data type constructor, and save them in the type environment. Save the types of any newly created serializer and deserializer functions in the type environment. The function definitions are not created until later. If a new info variable was created, return the data type constructor. Information is already set Compute the size parameters Save layout information Create an info constructor and field size computation code | Create a lookup table indexed by constructors. | Create a new variable whose name consists of the given label extended with some extra string. ----------------------------------------------------------------------------- | Add the types of layout-related functions to the environment for the given list of data types. It should be the list that was returned by The type environment is modified in-place. Look up the updated data type Compute function types Look up the updated data type Compute function types Process variables for each constructor of a boxed type
module SystemF.Datatypes.Driver (overriddenSerializerTypes, computeDataTypeInfo, addLayoutVariablesToTypeEnvironment ) where import Control.DeepSeq import Control.Monad import Control.Monad.Trans import qualified Data.IntMap as IntMap import Data.Maybe import Debug.Trace import Text.PrettyPrint.HughesPJ import Common.Error import Common.Identifier import Common.Label import Common.Supply import Common.MonadLogic import Type.Type import Type.Environment import Type.Compare import Type.Eval import qualified LowLevel.Syntax as LL import SystemF.Syntax import SystemF.MemoryIR import SystemF.Datatypes.Structure import SystemF.Datatypes.TypeObject overriddenSerializerTypes :: [(Var, (Var, Var))] overriddenSerializerTypes = [ (listSectionV, (putListSection_optimizedV, getListSection_optimizedV)) , (array2SectionV, (putArray2Section_optimizedV, getArray2Section_optimizedV)) ] primitiveValTypes :: [Var] primitiveValTypes = [intV, uintV, floatV, int64V] computeDataTypeInfo :: IdentSupply LL.Var -> IdentSupply Var -> TypeEnv -> IO ([Var], [GDef Mem]) computeDataTypeInfo ll_var_supply var_supply type_env = runTypeEvalM compute var_supply type_env where compute = do m_dtypes_needing_info <- mapM setLayoutInformation =<< get_algebraic_data_types let dtypes_needing_info = catMaybes m_dtypes_needing_info defss <- assume_info_vars dtypes_needing_info $ sequence liftM concat $ mapM define_info_var dtypes_needing_info , liftM concat $ mapM define_primitive_info_var primitiveValTypes ] return (dtypes_needing_info, concat defss) define_primitive_info_var data_type_con = do Just dtype <- lookupDataType data_type_con definePrimitiveValInfo ll_var_supply dtype define_info_var :: Var -> UnboxedTypeEvalM [GDef Mem] define_info_var data_type_con = do Just dtype <- lookupDataType data_type_con case dataTypeKind dtype of ValK -> valInfoDefinition ll_var_supply dtype BareK -> bareInfoDefinition ll_var_supply dtype BoxK -> boxInfoDefinitions ll_var_supply dtype assume_info_vars :: [Var] -> UnboxedTypeEvalM a -> UnboxedTypeEvalM a assume_info_vars data_type_cons m = do dtypes <- mapM lookupDataType data_type_cons let bindings :: [Binder] bindings = [ v ::: infoConstructorType dtype | m_dtype <- dtypes , let Just dtype = m_dtype , v <- layoutInfoVars $ dataTypeLayout' dtype ] assumeBinders bindings m get_algebraic_data_types :: UnboxedTypeEvalM [DataType] get_algebraic_data_types = do i_type_env <- freezeTypeEnv return $ filter dataTypeIsAlgebraic $ IntMap.elems $ getAllDataTypeConstructors i_type_env setLayoutInformation :: DataType -> UnboxedTypeEvalM (Maybe Var) setLayoutInformation dtype | not $ dataTypeIsAlgebraic dtype = internalError "setLayoutInformation" | isJust $ dataTypeLayout dtype = return Nothing | otherwise = do variance <- computeDataSizes dtype unless (map binderVar (dtsTyParams variance) == map binderVar (dataTypeParams dtype)) $ internalError "computeSizeParameters" layout <- createLayouts dtype (dtsSizeParamTypes variance) (dtsStaticTypes variance) setLayout (dataTypeCon dtype) layout return $ Just (dataTypeCon dtype) createLayouts dtype size_param_types static_types = case dataTypeKind dtype of BoxK -> constructor_layouts BareK -> unboxed_layout ValK -> unboxed_layout where Create one layout for each data constructor constructor_layouts = do xs <- createConstructorTable createInfoVariable dtype sers <- createConstructorTable createSerializerVariable dtype dess <- createConstructorTable createDeserializerVariable dtype fs <- createConstructorTable createSizeVariable dtype return $ boxedDataTypeLayout size_param_types static_types xs sers dess fs Create one layout for the data type unboxed_layout = do i <- createInfoVariable (dataTypeCon dtype) ser <- createSerializerVariable (dataTypeCon dtype) des <- createDeserializerVariable (dataTypeCon dtype) fs <- createConstructorTable createSizeVariable dtype return $ unboxedDataTypeLayout size_param_types static_types i ser des fs createConstructorTable :: (Var -> UnboxedTypeEvalM a) -> DataType -> UnboxedTypeEvalM [(Var, a)] createConstructorTable f dtype = forM (dataTypeDataConstructors dtype) $ \c -> do i <- f c return (c, i) createVariable :: String -> Maybe Label -> UnboxedTypeEvalM Var createVariable str data_label = do let info_name = case data_label of Nothing -> Nothing Just lab -> case labelLocalName lab of Left s -> let s' = s ++ str in Just (lab {labelLocalName = Left s'}) Right _ -> Nothing newVar info_name ObjectLevel createInfoVariable = newTaggedVar TypeInfoLabel createSizeVariable v = createVariable "_size" $ varName v createSerializerVariable = newTaggedVar SerializerLabel createDeserializerVariable = newTaggedVar DeserializerLabel ' computeDataTypeInfo ' . addLayoutVariablesToTypeEnvironment :: [Var] -> TypeEnv -> IO () addLayoutVariablesToTypeEnvironment vs tenv = do mapM_ add_generated_datatype vs mapM_ add_primitive_datatype primitiveValTypes where add_primitive_datatype v = do Just dtype <- runTypeEnvM tenv $ lookupDataType v let info_type = infoConstructorType dtype insertGlobalType tenv (dataTypeUnboxedInfoVar dtype) info_type add_generated_datatype v = do Just dtype <- runTypeEnvM tenv $ lookupDataType v let info_type = infoConstructorType dtype ser_type = serializerType dtype des_type = deserializerType dtype data_constructors = dataTypeDataConstructors dtype let constructor_layouts = forM_ data_constructors $ \dcon -> do insertGlobalType tenv (dataTypeBoxedInfoVar dtype dcon) info_type insertGlobalType tenv (dataTypeBoxedSerializerVar dtype dcon) ser_type insertGlobalType tenv (dataTypeBoxedDeserializerVar dtype dcon) des_type Only one of each variable for a bare type let unboxed_layout = do insertGlobalType tenv (dataTypeUnboxedInfoVar dtype) info_type insertGlobalType tenv (dataTypeUnboxedSerializerVar dtype) ser_type insertGlobalType tenv (dataTypeUnboxedDeserializerVar dtype) des_type case dataTypeKind dtype of BoxK -> constructor_layouts BareK -> unboxed_layout ValK -> unboxed_layout
026f6bed2a1fbbf6b2909ceeec8e9653cb84964e7f2e451c30e1f9ea46d0f3df
fccm/glMLite
wrap.ml
Copyright ( c ) 1993 - 1997 , Silicon Graphics , Inc. * ALL RIGHTS RESERVED * Permission to use , copy , modify , and distribute this software for * any purpose and without fee is hereby granted , provided that the above * copyright notice appear in all copies and that both the copyright notice * and this permission notice appear in supporting documentation , and that * the name of Silicon Graphics , Inc. not be used in advertising * or publicity pertaining to distribution of the software without specific , * written prior permission . * * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU " AS - IS " * AND WITHOUT WARRANTY OF ANY KIND , EXPRESS , IMPLIED OR OTHERWISE , * INCLUDING WITHOUT LIMITATION , ANY WARRANTY OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE . IN NO EVENT SHALL SILICON * GRAPHICS , INC . BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT , * SPECIAL , INCIDENTAL , INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY * KIND , OR ANY DAMAGES WHATSOEVER , INCLUDING WITHOUT LIMITATION , * LOSS OF PROFIT , LOSS OF USE , SAVINGS OR REVENUE , OR THE CLAIMS OF * THIRD PARTIES , WHETHER OR NOT SILICON GRAPHICS , INC . HAS * ADVISED OF THE POSSIBILITY OF SUCH LOSS , HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY , ARISING OUT OF OR IN CONNECTION WITH THE * POSSESSION , USE OR PERFORMANCE OF THIS SOFTWARE . * * US Government Users Restricted Rights * Use , duplication , or disclosure by the Government is subject to * restrictions set forth in FAR 52.227.19(c)(2 ) or subparagraph * ( c)(1)(ii ) of the Rights in Technical Data and Computer Software * clause at DFARS 252.227 - 7013 and/or in similar or successor * clauses in the FAR or the DOD or NASA FAR Supplement . * Unpublished-- rights reserved under the copyright laws of the * United States . Contractor / manufacturer is Silicon Graphics , * Inc. , 2011 N. Shoreline Blvd . , Mountain View , CA 94039 - 7311 . * * OpenGL(R ) is a registered trademark of Silicon Graphics , Inc. * ALL RIGHTS RESERVED * Permission to use, copy, modify, and distribute this software for * any purpose and without fee is hereby granted, provided that the above * copyright notice appear in all copies and that both the copyright notice * and this permission notice appear in supporting documentation, and that * the name of Silicon Graphics, Inc. not be used in advertising * or publicity pertaining to distribution of the software without specific, * written prior permission. * * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS" * AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON * GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, * SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY * KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION, * LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF * THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN * ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE * POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE. * * US Government Users Restricted Rights * Use, duplication, or disclosure by the Government is subject to * restrictions set forth in FAR 52.227.19(c)(2) or subparagraph * (c)(1)(ii) of the Rights in Technical Data and Computer Software * clause at DFARS 252.227-7013 and/or in similar or successor * clauses in the FAR or the DOD or NASA FAR Supplement. * Unpublished-- rights reserved under the copyright laws of the * United States. Contractor/manufacturer is Silicon Graphics, * Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311. * * OpenGL(R) is a registered trademark of Silicon Graphics, Inc. *) wrap.ml * This program texture maps a checkerboard image onto * two rectangles . This program demonstrates the wrapping * modes , if the texture coordinates fall outside 0.0 and 1.0 . * Interaction : Pressing the 's ' and 'S ' keys switch the * wrapping between clamping and repeating for the s parameter . * The ' t ' and ' T ' keys control the wrapping for the t parameter . * * If running this program on OpenGL 1.0 , texture objects are * not used . * This program texture maps a checkerboard image onto * two rectangles. This program demonstrates the wrapping * modes, if the texture coordinates fall outside 0.0 and 1.0. * Interaction: Pressing the 's' and 'S' keys switch the * wrapping between clamping and repeating for the s parameter. * The 't' and 'T' keys control the wrapping for the t parameter. * * If running this program on OpenGL 1.0, texture objects are * not used. *) open GL open Glu open Glut (* Create checkerboard texture *) let checkImageWidth = 64 let checkImageHeight = 64 let makeCheckImage() = let checkImage = Bigarray.Array3.create Bigarray.int8_unsigned Bigarray.c_layout checkImageHeight checkImageWidth 4 in for i = 0 to pred checkImageHeight do for j = 0 to pred checkImageWidth do let ( = ) a b = if a = b then 1 else 0 in let c = (((i land 0x8)=0) lxor ((j land 0x8)=0)) * 255 in checkImage.{i,j,0} <- c; checkImage.{i,j,1} <- c; checkImage.{i,j,2} <- c; checkImage.{i,j,3} <- 255; done; done; (Bigarray.genarray_of_array3 checkImage) ;; let init() = glClearColor 0.0 0.0 0.0 0.0; glShadeModel GL_FLAT; glEnable GL_DEPTH_TEST; let checkImage = makeCheckImage() in glPixelStorei GL_UNPACK_ALIGNMENT 1; let texName = glGenTexture() in glBindTexture BindTex.GL_TEXTURE_2D texName; glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_WRAP_S GL_REPEAT); glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_WRAP_T GL_REPEAT); glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_MAG_FILTER Mag.GL_NEAREST); glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_MIN_FILTER Min.GL_NEAREST); glTexImage2D TexTarget.GL_TEXTURE_2D 0 InternalFormat.GL_RGBA checkImageWidth checkImageHeight GL_RGBA GL_UNSIGNED_BYTE checkImage; (texName) ;; let display texName () = glClear [GL_COLOR_BUFFER_BIT; GL_DEPTH_BUFFER_BIT]; glEnable GL_TEXTURE_2D; glTexEnv TexEnv.GL_TEXTURE_ENV TexEnv.GL_TEXTURE_ENV_MODE TexEnv.GL_DECAL; glBindTexture BindTex.GL_TEXTURE_2D texName; glBegin GL_QUADS; glTexCoord2 0.0 0.0; glVertex3 (-2.0) (-1.0) (0.0); glTexCoord2 0.0 3.0; glVertex3 (-2.0) ( 1.0) (0.0); glTexCoord2 3.0 3.0; glVertex3 ( 0.0) ( 1.0) (0.0); glTexCoord2 3.0 0.0; glVertex3 ( 0.0) (-1.0) (0.0); glTexCoord2 0.0 0.0; glVertex3 (1.0) (-1.0) (0.0); glTexCoord2 0.0 3.0; glVertex3 (1.0) ( 1.0) (0.0); glTexCoord2 3.0 3.0; glVertex3 (2.41421) ( 1.0) (-1.41421); glTexCoord2 3.0 0.0; glVertex3 (2.41421) (-1.0) (-1.41421); glEnd(); glFlush(); glDisable GL_TEXTURE_2D; ;; let reshape ~width:w ~height:h = glViewport 0 0 w h; glMatrixMode GL_PROJECTION; glLoadIdentity(); gluPerspective 60.0 (float w /. float h) 1.0 30.0; glMatrixMode GL_MODELVIEW; glLoadIdentity(); glTranslate 0.0 0.0 (-3.6); ;; ARGSUSED1 let keyboard ~key ~x ~y = match key with | 's' -> glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_WRAP_S GL_CLAMP); glutPostRedisplay(); | 'S' -> glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_WRAP_S GL_REPEAT); glutPostRedisplay(); | 't' -> glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_WRAP_T GL_CLAMP); glutPostRedisplay(); | 'T' -> glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_WRAP_T GL_REPEAT); glutPostRedisplay(); | '\027' -> (* escape *) exit(0); | _ -> () ;; let () = let _ = glutInit Sys.argv in glutInitDisplayMode [GLUT_SINGLE; GLUT_RGB; GLUT_DEPTH]; glutInitWindowSize 250 250; glutInitWindowPosition 100 100; let _ = glutCreateWindow Sys.argv.(0) in let texName = init() in glutDisplayFunc ~display:(display texName); glutReshapeFunc ~reshape; glutKeyboardFunc ~keyboard; glutMainLoop(); ;;
null
https://raw.githubusercontent.com/fccm/glMLite/c52cd806909581e49d9b660195576c8a932f6d33/RedBook-Samples/wrap.ml
ocaml
Create checkerboard texture escape
Copyright ( c ) 1993 - 1997 , Silicon Graphics , Inc. * ALL RIGHTS RESERVED * Permission to use , copy , modify , and distribute this software for * any purpose and without fee is hereby granted , provided that the above * copyright notice appear in all copies and that both the copyright notice * and this permission notice appear in supporting documentation , and that * the name of Silicon Graphics , Inc. not be used in advertising * or publicity pertaining to distribution of the software without specific , * written prior permission . * * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU " AS - IS " * AND WITHOUT WARRANTY OF ANY KIND , EXPRESS , IMPLIED OR OTHERWISE , * INCLUDING WITHOUT LIMITATION , ANY WARRANTY OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE . IN NO EVENT SHALL SILICON * GRAPHICS , INC . BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT , * SPECIAL , INCIDENTAL , INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY * KIND , OR ANY DAMAGES WHATSOEVER , INCLUDING WITHOUT LIMITATION , * LOSS OF PROFIT , LOSS OF USE , SAVINGS OR REVENUE , OR THE CLAIMS OF * THIRD PARTIES , WHETHER OR NOT SILICON GRAPHICS , INC . HAS * ADVISED OF THE POSSIBILITY OF SUCH LOSS , HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY , ARISING OUT OF OR IN CONNECTION WITH THE * POSSESSION , USE OR PERFORMANCE OF THIS SOFTWARE . * * US Government Users Restricted Rights * Use , duplication , or disclosure by the Government is subject to * restrictions set forth in FAR 52.227.19(c)(2 ) or subparagraph * ( c)(1)(ii ) of the Rights in Technical Data and Computer Software * clause at DFARS 252.227 - 7013 and/or in similar or successor * clauses in the FAR or the DOD or NASA FAR Supplement . * Unpublished-- rights reserved under the copyright laws of the * United States . Contractor / manufacturer is Silicon Graphics , * Inc. , 2011 N. Shoreline Blvd . , Mountain View , CA 94039 - 7311 . * * OpenGL(R ) is a registered trademark of Silicon Graphics , Inc. * ALL RIGHTS RESERVED * Permission to use, copy, modify, and distribute this software for * any purpose and without fee is hereby granted, provided that the above * copyright notice appear in all copies and that both the copyright notice * and this permission notice appear in supporting documentation, and that * the name of Silicon Graphics, Inc. not be used in advertising * or publicity pertaining to distribution of the software without specific, * written prior permission. * * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS" * AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON * GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, * SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY * KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION, * LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF * THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN * ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE * POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE. * * US Government Users Restricted Rights * Use, duplication, or disclosure by the Government is subject to * restrictions set forth in FAR 52.227.19(c)(2) or subparagraph * (c)(1)(ii) of the Rights in Technical Data and Computer Software * clause at DFARS 252.227-7013 and/or in similar or successor * clauses in the FAR or the DOD or NASA FAR Supplement. * Unpublished-- rights reserved under the copyright laws of the * United States. Contractor/manufacturer is Silicon Graphics, * Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311. * * OpenGL(R) is a registered trademark of Silicon Graphics, Inc. *) wrap.ml * This program texture maps a checkerboard image onto * two rectangles . This program demonstrates the wrapping * modes , if the texture coordinates fall outside 0.0 and 1.0 . * Interaction : Pressing the 's ' and 'S ' keys switch the * wrapping between clamping and repeating for the s parameter . * The ' t ' and ' T ' keys control the wrapping for the t parameter . * * If running this program on OpenGL 1.0 , texture objects are * not used . * This program texture maps a checkerboard image onto * two rectangles. This program demonstrates the wrapping * modes, if the texture coordinates fall outside 0.0 and 1.0. * Interaction: Pressing the 's' and 'S' keys switch the * wrapping between clamping and repeating for the s parameter. * The 't' and 'T' keys control the wrapping for the t parameter. * * If running this program on OpenGL 1.0, texture objects are * not used. *) open GL open Glu open Glut let checkImageWidth = 64 let checkImageHeight = 64 let makeCheckImage() = let checkImage = Bigarray.Array3.create Bigarray.int8_unsigned Bigarray.c_layout checkImageHeight checkImageWidth 4 in for i = 0 to pred checkImageHeight do for j = 0 to pred checkImageWidth do let ( = ) a b = if a = b then 1 else 0 in let c = (((i land 0x8)=0) lxor ((j land 0x8)=0)) * 255 in checkImage.{i,j,0} <- c; checkImage.{i,j,1} <- c; checkImage.{i,j,2} <- c; checkImage.{i,j,3} <- 255; done; done; (Bigarray.genarray_of_array3 checkImage) ;; let init() = glClearColor 0.0 0.0 0.0 0.0; glShadeModel GL_FLAT; glEnable GL_DEPTH_TEST; let checkImage = makeCheckImage() in glPixelStorei GL_UNPACK_ALIGNMENT 1; let texName = glGenTexture() in glBindTexture BindTex.GL_TEXTURE_2D texName; glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_WRAP_S GL_REPEAT); glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_WRAP_T GL_REPEAT); glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_MAG_FILTER Mag.GL_NEAREST); glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_MIN_FILTER Min.GL_NEAREST); glTexImage2D TexTarget.GL_TEXTURE_2D 0 InternalFormat.GL_RGBA checkImageWidth checkImageHeight GL_RGBA GL_UNSIGNED_BYTE checkImage; (texName) ;; let display texName () = glClear [GL_COLOR_BUFFER_BIT; GL_DEPTH_BUFFER_BIT]; glEnable GL_TEXTURE_2D; glTexEnv TexEnv.GL_TEXTURE_ENV TexEnv.GL_TEXTURE_ENV_MODE TexEnv.GL_DECAL; glBindTexture BindTex.GL_TEXTURE_2D texName; glBegin GL_QUADS; glTexCoord2 0.0 0.0; glVertex3 (-2.0) (-1.0) (0.0); glTexCoord2 0.0 3.0; glVertex3 (-2.0) ( 1.0) (0.0); glTexCoord2 3.0 3.0; glVertex3 ( 0.0) ( 1.0) (0.0); glTexCoord2 3.0 0.0; glVertex3 ( 0.0) (-1.0) (0.0); glTexCoord2 0.0 0.0; glVertex3 (1.0) (-1.0) (0.0); glTexCoord2 0.0 3.0; glVertex3 (1.0) ( 1.0) (0.0); glTexCoord2 3.0 3.0; glVertex3 (2.41421) ( 1.0) (-1.41421); glTexCoord2 3.0 0.0; glVertex3 (2.41421) (-1.0) (-1.41421); glEnd(); glFlush(); glDisable GL_TEXTURE_2D; ;; let reshape ~width:w ~height:h = glViewport 0 0 w h; glMatrixMode GL_PROJECTION; glLoadIdentity(); gluPerspective 60.0 (float w /. float h) 1.0 30.0; glMatrixMode GL_MODELVIEW; glLoadIdentity(); glTranslate 0.0 0.0 (-3.6); ;; ARGSUSED1 let keyboard ~key ~x ~y = match key with | 's' -> glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_WRAP_S GL_CLAMP); glutPostRedisplay(); | 'S' -> glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_WRAP_S GL_REPEAT); glutPostRedisplay(); | 't' -> glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_WRAP_T GL_CLAMP); glutPostRedisplay(); | 'T' -> glTexParameter TexParam.GL_TEXTURE_2D (TexParam.GL_TEXTURE_WRAP_T GL_REPEAT); glutPostRedisplay(); exit(0); | _ -> () ;; let () = let _ = glutInit Sys.argv in glutInitDisplayMode [GLUT_SINGLE; GLUT_RGB; GLUT_DEPTH]; glutInitWindowSize 250 250; glutInitWindowPosition 100 100; let _ = glutCreateWindow Sys.argv.(0) in let texName = init() in glutDisplayFunc ~display:(display texName); glutReshapeFunc ~reshape; glutKeyboardFunc ~keyboard; glutMainLoop(); ;;
05258324799bd6e1d659609db6542c3f2763d5eaa03122271a5e52c5a37317b8
liquidz/clj-jwt
sign.clj
(ns clj-jwt.sign (:require [clj-jwt.base64 :refer [url-safe-encode-str url-safe-decode]] [crypto.equality :refer [eq?]])) HMAC (defn- hmac-sign "Function to sign data with HMAC algorithm." [alg key body & {:keys [charset] :or {charset "UTF-8"}}] (let [hmac-key (javax.crypto.spec.SecretKeySpec. (.getBytes key charset) alg) hmac (doto (javax.crypto.Mac/getInstance alg) (.init hmac-key))] (url-safe-encode-str (.doFinal hmac (.getBytes body charset))))) (defn- hmac-verify "Function to verify data and signature with HMAC algorithm." [alg key body signature & {:keys [charset] :or {charset "UTF-8"}}] (eq? signature (hmac-sign alg key body :charset charset))) RSA (defn- rsa-sign "Function to sign data with RSA algorithm." [alg key body & {:keys [charset] :or {charset "UTF-8"}}] (let [sig (doto (java.security.Signature/getInstance alg) (.initSign key (java.security.SecureRandom.)) (.update (.getBytes body charset)))] (url-safe-encode-str (.sign sig)))) (defn- rsa-verify "Function to verify data and signature with RSA algorithm." [alg key body signature & {:keys [charset] :or {charset "UTF-8"}}] (let [sig (doto (java.security.Signature/getInstance alg) (.initVerify key) (.update (.getBytes body charset)))] (.verify sig (url-safe-decode signature)))) (defn- ec-sign [alg key body & {:keys [charset] :or {charset "UTF-8"}}] (let [sig (doto (java.security.Signature/getInstance alg) (.initSign key) (.update (.getBytes body charset)))] (url-safe-encode-str (.sign sig)))) (defn ec-verify [alg key body signature & {:keys [charset] :or {charset "UTF-8"}}] (let [sig (doto (java.security.Signature/getInstance alg) (.initSign key) (.update (.getBytes body charset)))] (.verify sig (url-safe-decode signature)))) (def ^:private signature-fns {:HS256 (partial hmac-sign "HmacSHA256") :HS384 (partial hmac-sign "HmacSHA384") :HS512 (partial hmac-sign "HmacSHA512") :RS256 (partial rsa-sign "SHA256withRSA") :RS384 (partial rsa-sign "SHA384withRSA") :RS512 (partial rsa-sign "SHA512withRSA") :ES256 (partial ec-sign "SHA256withECDSA") :ES384 (partial ec-sign "SHA384withECDSA") :ES512 (partial ec-sign "SHA512withECDSA")}) (def ^:private verify-fns {:HS256 (partial hmac-verify "HmacSHA256") :HS384 (partial hmac-verify "HmacSHA384") :HS512 (partial hmac-verify "HmacSHA512") :RS256 (partial rsa-verify "SHA256withRSA") :RS384 (partial rsa-verify "SHA384withRSA") :RS512 (partial rsa-verify "SHA512withRSA") :ES256 (partial rsa-verify "SHA256withECDSA") :ES384 (partial rsa-verify "SHA384withECDSA") :ES512 (partial rsa-verify "SHA512withECDSA")}) (defn- get-fns [m alg] (if-let [f (get m alg)] f (throw (Exception. "Unkown signature")))) (def get-signature-fn (partial get-fns signature-fns)) (def get-verify-fn (partial get-fns verify-fns)) (def supported-algorithm? (set (keys verify-fns)))
null
https://raw.githubusercontent.com/liquidz/clj-jwt/8a339824504593c417eca508ca31539202108e32/src/clj_jwt/sign.clj
clojure
(ns clj-jwt.sign (:require [clj-jwt.base64 :refer [url-safe-encode-str url-safe-decode]] [crypto.equality :refer [eq?]])) HMAC (defn- hmac-sign "Function to sign data with HMAC algorithm." [alg key body & {:keys [charset] :or {charset "UTF-8"}}] (let [hmac-key (javax.crypto.spec.SecretKeySpec. (.getBytes key charset) alg) hmac (doto (javax.crypto.Mac/getInstance alg) (.init hmac-key))] (url-safe-encode-str (.doFinal hmac (.getBytes body charset))))) (defn- hmac-verify "Function to verify data and signature with HMAC algorithm." [alg key body signature & {:keys [charset] :or {charset "UTF-8"}}] (eq? signature (hmac-sign alg key body :charset charset))) RSA (defn- rsa-sign "Function to sign data with RSA algorithm." [alg key body & {:keys [charset] :or {charset "UTF-8"}}] (let [sig (doto (java.security.Signature/getInstance alg) (.initSign key (java.security.SecureRandom.)) (.update (.getBytes body charset)))] (url-safe-encode-str (.sign sig)))) (defn- rsa-verify "Function to verify data and signature with RSA algorithm." [alg key body signature & {:keys [charset] :or {charset "UTF-8"}}] (let [sig (doto (java.security.Signature/getInstance alg) (.initVerify key) (.update (.getBytes body charset)))] (.verify sig (url-safe-decode signature)))) (defn- ec-sign [alg key body & {:keys [charset] :or {charset "UTF-8"}}] (let [sig (doto (java.security.Signature/getInstance alg) (.initSign key) (.update (.getBytes body charset)))] (url-safe-encode-str (.sign sig)))) (defn ec-verify [alg key body signature & {:keys [charset] :or {charset "UTF-8"}}] (let [sig (doto (java.security.Signature/getInstance alg) (.initSign key) (.update (.getBytes body charset)))] (.verify sig (url-safe-decode signature)))) (def ^:private signature-fns {:HS256 (partial hmac-sign "HmacSHA256") :HS384 (partial hmac-sign "HmacSHA384") :HS512 (partial hmac-sign "HmacSHA512") :RS256 (partial rsa-sign "SHA256withRSA") :RS384 (partial rsa-sign "SHA384withRSA") :RS512 (partial rsa-sign "SHA512withRSA") :ES256 (partial ec-sign "SHA256withECDSA") :ES384 (partial ec-sign "SHA384withECDSA") :ES512 (partial ec-sign "SHA512withECDSA")}) (def ^:private verify-fns {:HS256 (partial hmac-verify "HmacSHA256") :HS384 (partial hmac-verify "HmacSHA384") :HS512 (partial hmac-verify "HmacSHA512") :RS256 (partial rsa-verify "SHA256withRSA") :RS384 (partial rsa-verify "SHA384withRSA") :RS512 (partial rsa-verify "SHA512withRSA") :ES256 (partial rsa-verify "SHA256withECDSA") :ES384 (partial rsa-verify "SHA384withECDSA") :ES512 (partial rsa-verify "SHA512withECDSA")}) (defn- get-fns [m alg] (if-let [f (get m alg)] f (throw (Exception. "Unkown signature")))) (def get-signature-fn (partial get-fns signature-fns)) (def get-verify-fn (partial get-fns verify-fns)) (def supported-algorithm? (set (keys verify-fns)))
58aca9b51adfd151cfaaaa7c52d678fedf813b72a2fff905a5a08c3b762d4fa8
brawnski/git-annex
Fix.hs
git - annex command - - Copyright 2010 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2010 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} module Command.Fix where import Control.Monad.State (liftIO) import System.Posix.Files import System.Directory import Command import qualified AnnexQueue import Utility import Content import Messages command :: [Command] command = [repoCommand "fix" paramPath seek "fix up symlinks to point to annexed content"] seek :: [CommandSeek] seek = [withFilesInGit start] {- Fixes the symlink to an annexed file. -} start :: CommandStartString start file = isAnnexed file $ \(key, _) -> do link <- calcGitLink file key l <- liftIO $ readSymbolicLink file if link == l then stop else do showStart "fix" file next $ perform file link perform :: FilePath -> FilePath -> CommandPerform perform file link = do liftIO $ createDirectoryIfMissing True (parentDir file) liftIO $ removeFile file liftIO $ createSymbolicLink link file next $ cleanup file cleanup :: FilePath -> CommandCleanup cleanup file = do AnnexQueue.add "add" [Param "--"] [file] return True
null
https://raw.githubusercontent.com/brawnski/git-annex/8b847517a810d384a79178124b9766141b89bc17/Command/Fix.hs
haskell
Fixes the symlink to an annexed file.
git - annex command - - Copyright 2010 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2010 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} module Command.Fix where import Control.Monad.State (liftIO) import System.Posix.Files import System.Directory import Command import qualified AnnexQueue import Utility import Content import Messages command :: [Command] command = [repoCommand "fix" paramPath seek "fix up symlinks to point to annexed content"] seek :: [CommandSeek] seek = [withFilesInGit start] start :: CommandStartString start file = isAnnexed file $ \(key, _) -> do link <- calcGitLink file key l <- liftIO $ readSymbolicLink file if link == l then stop else do showStart "fix" file next $ perform file link perform :: FilePath -> FilePath -> CommandPerform perform file link = do liftIO $ createDirectoryIfMissing True (parentDir file) liftIO $ removeFile file liftIO $ createSymbolicLink link file next $ cleanup file cleanup :: FilePath -> CommandCleanup cleanup file = do AnnexQueue.add "add" [Param "--"] [file] return True
bb81a3dd1276c20f5654efb9065c528f160c3d2eb9a63946d24d098907c5dcb7
malcolmreynolds/GSLL
bernoulli.lisp
distribution , Sat Nov 25 2006 - 16:59 Time - stamp : < 2009 - 05 - 26 22:56:49EDT bernoulli.lisp > $ Id$ (in-package :gsl) (defmfun sample ((generator random-number-generator) (type (eql 'bernoulli)) &key probability) "gsl_ran_bernoulli" (((mpointer generator) :pointer) (probability :double)) :definition :method :c-return :uint "Returns either 0 or 1, the result of a Bernoulli trial with probability p. The probability distribution for a Bernoulli trial is p(0) = 1 - p p(1) = p.") (defmfun bernoulli-pdf (k p) "gsl_ran_bernoulli_pdf" ((k :uint) (p :double)) :c-return :double "The probability p(k) of obtaining k from a Bernoulli distribution with probability parameter p, using the formula given in #'bernoulli.") ;;; Examples and unit test (save-test bernoulli (let ((rng (make-random-number-generator +mt19937+ 0))) (loop for i from 0 to 10 collect (sample rng 'bernoulli :probability 0.5d0))) (bernoulli-pdf 0 0.5d0))
null
https://raw.githubusercontent.com/malcolmreynolds/GSLL/2f722f12f1d08e1b9550a46e2a22adba8e1e52c4/random/bernoulli.lisp
lisp
Examples and unit test
distribution , Sat Nov 25 2006 - 16:59 Time - stamp : < 2009 - 05 - 26 22:56:49EDT bernoulli.lisp > $ Id$ (in-package :gsl) (defmfun sample ((generator random-number-generator) (type (eql 'bernoulli)) &key probability) "gsl_ran_bernoulli" (((mpointer generator) :pointer) (probability :double)) :definition :method :c-return :uint "Returns either 0 or 1, the result of a Bernoulli trial with probability p. The probability distribution for a Bernoulli trial is p(0) = 1 - p p(1) = p.") (defmfun bernoulli-pdf (k p) "gsl_ran_bernoulli_pdf" ((k :uint) (p :double)) :c-return :double "The probability p(k) of obtaining k from a Bernoulli distribution with probability parameter p, using the formula given in #'bernoulli.") (save-test bernoulli (let ((rng (make-random-number-generator +mt19937+ 0))) (loop for i from 0 to 10 collect (sample rng 'bernoulli :probability 0.5d0))) (bernoulli-pdf 0 0.5d0))
8fd87db257808ab1b57f3c691cc69a171d304cd068445b46d98f46d40607da70
robrix/sequoia
Biadjunction.hs
# LANGUAGE FunctionalDependencies # module Sequoia.Biadjunction ( -- * Biadjunctions Biadjunction(..) -- * Defaults , bileftAdjunctDisjConj , birightAdjunctDisjConj , leftAdjunctBiadjunction , rightAdjunctBiadjunction ) where import Data.Bifunctor import Sequoia.Bifunctor.Join import Sequoia.Birepresentable import Sequoia.Conjunction import Sequoia.Disjunction -- Biadjunctions class (Bifunctor f, Birepresentable u) => Biadjunction f u | f -> u, u -> f where bileftAdjunct :: (f a a -> b) -> (a -> u b b) birightAdjunct :: (a -> u b b) -> (f a a -> b) instance Biadjunction Either (,) where - < f . inr > exr . f -- Defaults bileftAdjunctDisjConj :: (Disj f, Conj u) => (f a a -> b) -> (a -> u b b) - < f . inr birightAdjunctDisjConj :: (Disj f, Conj u) => (a -> u b b) -> (f a a -> b) > exr . f leftAdjunctBiadjunction :: Biadjunction f u => (Join f a -> b) -> (a -> Join u b) leftAdjunctBiadjunction f = Join . bileftAdjunct (f . Join) rightAdjunctBiadjunction :: Biadjunction f u => (a -> Join u b) -> (Join f a -> b) rightAdjunctBiadjunction f = birightAdjunct (runJoin . f) . runJoin
null
https://raw.githubusercontent.com/robrix/sequoia/79bbcb79531cc110253f00ab4b2b529dae00b2eb/src/Sequoia/Biadjunction.hs
haskell
* Biadjunctions * Defaults Biadjunctions Defaults
# LANGUAGE FunctionalDependencies # module Sequoia.Biadjunction Biadjunction(..) , bileftAdjunctDisjConj , birightAdjunctDisjConj , leftAdjunctBiadjunction , rightAdjunctBiadjunction ) where import Data.Bifunctor import Sequoia.Bifunctor.Join import Sequoia.Birepresentable import Sequoia.Conjunction import Sequoia.Disjunction class (Bifunctor f, Birepresentable u) => Biadjunction f u | f -> u, u -> f where bileftAdjunct :: (f a a -> b) -> (a -> u b b) birightAdjunct :: (a -> u b b) -> (f a a -> b) instance Biadjunction Either (,) where - < f . inr > exr . f bileftAdjunctDisjConj :: (Disj f, Conj u) => (f a a -> b) -> (a -> u b b) - < f . inr birightAdjunctDisjConj :: (Disj f, Conj u) => (a -> u b b) -> (f a a -> b) > exr . f leftAdjunctBiadjunction :: Biadjunction f u => (Join f a -> b) -> (a -> Join u b) leftAdjunctBiadjunction f = Join . bileftAdjunct (f . Join) rightAdjunctBiadjunction :: Biadjunction f u => (a -> Join u b) -> (Join f a -> b) rightAdjunctBiadjunction f = birightAdjunct (runJoin . f) . runJoin
8c80815b4d8b8da2e11cc4421f0ad33b880843808fe387369dd238b6f22ea2a4
nervous-systems/iris-examples
common.clj
(ns iris-examples.common (:require [cognitect.transit :as transit] [clojure.tools.cli :as cli]) (:import [java.io ByteArrayOutputStream ByteArrayInputStream])) (def topic "iris-examples/pub-sub/events") (def bit-service "bit-service") (defn pack-message [m] (let [o (ByteArrayOutputStream.)] (transit/write (transit/writer o :msgpack) m) (let [result (.toByteArray o)] (.reset o) result))) (defn unpack-message [byte-array] (let [i (ByteArrayInputStream. byte-array)] (transit/read (transit/reader i :msgpack)))) (def port-cli-options [["-p" "--port N" "Port number" :default 55555 :parse-fn #(Integer/parseInt %)]]) (defn cli-args->int [cli-args default] (-> cli-args (cli/parse-opts [["-n" "--number N" nil :default default :parse-fn #(Integer/parseInt %)]]) :options :number)) (defn cli-args->port [cli-args] (-> cli-args (cli/parse-opts port-cli-options) :options :port)) (defn generate-event [i] {:event :integer :data {:value i} :time (System/currentTimeMillis)})
null
https://raw.githubusercontent.com/nervous-systems/iris-examples/37d8a3b13047ee0630f0ca975280406ed0533e58/src/iris_examples/common.clj
clojure
(ns iris-examples.common (:require [cognitect.transit :as transit] [clojure.tools.cli :as cli]) (:import [java.io ByteArrayOutputStream ByteArrayInputStream])) (def topic "iris-examples/pub-sub/events") (def bit-service "bit-service") (defn pack-message [m] (let [o (ByteArrayOutputStream.)] (transit/write (transit/writer o :msgpack) m) (let [result (.toByteArray o)] (.reset o) result))) (defn unpack-message [byte-array] (let [i (ByteArrayInputStream. byte-array)] (transit/read (transit/reader i :msgpack)))) (def port-cli-options [["-p" "--port N" "Port number" :default 55555 :parse-fn #(Integer/parseInt %)]]) (defn cli-args->int [cli-args default] (-> cli-args (cli/parse-opts [["-n" "--number N" nil :default default :parse-fn #(Integer/parseInt %)]]) :options :number)) (defn cli-args->port [cli-args] (-> cli-args (cli/parse-opts port-cli-options) :options :port)) (defn generate-event [i] {:event :integer :data {:value i} :time (System/currentTimeMillis)})
578ddca37b307c0b37c0549f09ce14cfbde46392e6856f349841c5d8ae1caf37
lley154/cardano-lottery
Main-scripts.hs
{-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleInstances # {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE StandaloneDeriving # {-# LANGUAGE TypeFamilies #-} module Main ( main , ExportTx(..) ) where import qualified Cardano.Api as C import Data.Default (Default (..)) import Data.Monoid (Sum (..)) import Ledger.Index (ValidatorMode (..)) import Options.Applicative import Plutus.Contract.Wallet (ExportTx (..)) import qualified TestLottery as TestLottery import Plutus.Trace (Command (..), ScriptsConfig (..), showStats, writeScriptsTo) writeWhat :: Command -> String writeWhat (Scripts FullyAppliedValidators) = "scripts (fully applied)" writeWhat (Scripts UnappliedValidators) = "scripts (unapplied)" writeWhat Transactions{} = "transactions" pathParser :: Parser FilePath pathParser = strArgument (metavar "SCRIPT_PATH" <> help "output path") protocolParamsParser :: Parser FilePath protocolParamsParser = strOption (long "protocol-parameters" <> short 'p' <> help "Path to protocol parameters JSON file" <> showDefault <> value "protocol-parameters.json") networkIdParser :: Parser C.NetworkId networkIdParser = let p = C.Testnet . C.NetworkMagic <$> option auto (long "network-magic" <> short 'n' <> help "Cardano network magic. If none is specified, mainnet addresses are generated.") in p <|> pure C.Mainnet commandParser :: Parser Command commandParser = hsubparser $ mconcat [scriptsParser, transactionsParser] scriptsParser :: Mod CommandFields Command scriptsParser = command "scripts" $ info (Scripts <$> flag FullyAppliedValidators UnappliedValidators (long "unapplied-validators" <> short 'u' <> help "Write the unapplied validator scripts" <> showDefault)) (fullDesc <> progDesc "Write fully applied validator scripts") transactionsParser :: Mod CommandFields Command transactionsParser = command "transactions" $ info (Transactions <$> networkIdParser <*> protocolParamsParser) (fullDesc <> progDesc "Write partial transactions") progParser :: ParserInfo ScriptsConfig progParser = let p = ScriptsConfig <$> pathParser <*> commandParser in info (p <**> helper) (fullDesc <> progDesc "Run a number of emulator traces and write all validator scripts and/or partial transactions to SCRIPT_PATH" <> header "cardano-lottery-scripts - extract validators and partial transactions from emulator traces" ) main :: IO () main = execParser progParser >>= writeScripts writeScripts :: ScriptsConfig -> IO () writeScripts config = do putStrLn $ "Writing " <> writeWhat (scCommand config) <> " to: " <> scPath config (Sum size, exBudget) <- foldMap (uncurry3 (writeScriptsTo config)) [ ("cardano-lottery-test", TestLottery.myTrace, def) ] if size > 0 then putStrLn $ "Total " <> showStats size exBudget else pure () -- | `uncurry3` converts a curried function to a function on triples. uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d uncurry3 f (a, b, c) = f a b c
null
https://raw.githubusercontent.com/lley154/cardano-lottery/e7f714472d869b336acf4c90303319498e493b4e/scripts/Main-scripts.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE NamedFieldPuns # # LANGUAGE OverloadedStrings # # LANGUAGE TypeFamilies # | `uncurry3` converts a curried function to a function on triples.
# LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleInstances # # LANGUAGE StandaloneDeriving # module Main ( main , ExportTx(..) ) where import qualified Cardano.Api as C import Data.Default (Default (..)) import Data.Monoid (Sum (..)) import Ledger.Index (ValidatorMode (..)) import Options.Applicative import Plutus.Contract.Wallet (ExportTx (..)) import qualified TestLottery as TestLottery import Plutus.Trace (Command (..), ScriptsConfig (..), showStats, writeScriptsTo) writeWhat :: Command -> String writeWhat (Scripts FullyAppliedValidators) = "scripts (fully applied)" writeWhat (Scripts UnappliedValidators) = "scripts (unapplied)" writeWhat Transactions{} = "transactions" pathParser :: Parser FilePath pathParser = strArgument (metavar "SCRIPT_PATH" <> help "output path") protocolParamsParser :: Parser FilePath protocolParamsParser = strOption (long "protocol-parameters" <> short 'p' <> help "Path to protocol parameters JSON file" <> showDefault <> value "protocol-parameters.json") networkIdParser :: Parser C.NetworkId networkIdParser = let p = C.Testnet . C.NetworkMagic <$> option auto (long "network-magic" <> short 'n' <> help "Cardano network magic. If none is specified, mainnet addresses are generated.") in p <|> pure C.Mainnet commandParser :: Parser Command commandParser = hsubparser $ mconcat [scriptsParser, transactionsParser] scriptsParser :: Mod CommandFields Command scriptsParser = command "scripts" $ info (Scripts <$> flag FullyAppliedValidators UnappliedValidators (long "unapplied-validators" <> short 'u' <> help "Write the unapplied validator scripts" <> showDefault)) (fullDesc <> progDesc "Write fully applied validator scripts") transactionsParser :: Mod CommandFields Command transactionsParser = command "transactions" $ info (Transactions <$> networkIdParser <*> protocolParamsParser) (fullDesc <> progDesc "Write partial transactions") progParser :: ParserInfo ScriptsConfig progParser = let p = ScriptsConfig <$> pathParser <*> commandParser in info (p <**> helper) (fullDesc <> progDesc "Run a number of emulator traces and write all validator scripts and/or partial transactions to SCRIPT_PATH" <> header "cardano-lottery-scripts - extract validators and partial transactions from emulator traces" ) main :: IO () main = execParser progParser >>= writeScripts writeScripts :: ScriptsConfig -> IO () writeScripts config = do putStrLn $ "Writing " <> writeWhat (scCommand config) <> " to: " <> scPath config (Sum size, exBudget) <- foldMap (uncurry3 (writeScriptsTo config)) [ ("cardano-lottery-test", TestLottery.myTrace, def) ] if size > 0 then putStrLn $ "Total " <> showStats size exBudget else pure () uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d uncurry3 f (a, b, c) = f a b c
008f0b35ac9cca0e3e0760774d7affc8b9d692ee5240f0165d5c1a23363215de
fugue/fregot
Comment.hs
| Copyright : ( c ) 2020 Fugue , Inc. License : Apache License , version 2.0 Maintainer : Stability : experimental Portability : POSIX Copyright : (c) 2020 Fugue, Inc. License : Apache License, version 2.0 Maintainer : Stability : experimental Portability : POSIX -} module Fregot.Lexer.Comment ( Comment (..) ) where import qualified Data.Text as T newtype Comment = Comment [T.Text] deriving (Eq, Show)
null
https://raw.githubusercontent.com/fugue/fregot/c3d87f37c43558761d5f6ac758d2f1a4117adb3e/lib/Fregot/Lexer/Comment.hs
haskell
| Copyright : ( c ) 2020 Fugue , Inc. License : Apache License , version 2.0 Maintainer : Stability : experimental Portability : POSIX Copyright : (c) 2020 Fugue, Inc. License : Apache License, version 2.0 Maintainer : Stability : experimental Portability : POSIX -} module Fregot.Lexer.Comment ( Comment (..) ) where import qualified Data.Text as T newtype Comment = Comment [T.Text] deriving (Eq, Show)
94f2f12f7fa77d23a8c580ce7117b608afdac47139bafcc7eb74c828d00a9c1a
danielholmes/wolf3d-haskell
Main.hs
module Wolf3D.Main ( createMain ) where import Wolf3D.Runner import Wolf3D.UI import Wolf3D.WorldData import Wolf3D.Display.Data import qualified SDL import Data.StateVar (($=)) type Scale = Int createMain :: Scale -> World -> (SDL.Renderer -> IO (SimRun -> IO ())) -> IO () createMain s initWorld createRender = do -- Original native size let width = (fromIntegral s) * screenWidth wolf3d was 320 x 200 on 4:3 displays , so it was scaled vertically let windowSize = (width, width `div` 4 * 3) On a machine with infinite resources , frame rate of Wolf3D was 70fps let frameTime = 14 createUI windowSize $ \r -> do render <- createRender r let fWindowWidth = fromIntegral (fst windowSize) let fWindowHeight = fromIntegral (snd windowSize) let fScreenWidth = fromIntegral screenWidth let fScreenHeight = fromIntegral screenHeight let scaleX = fWindowWidth / fScreenWidth let scaleY = fWindowHeight / fScreenHeight SDL.rendererScale r $= (SDL.V2 scaleX scaleY) runLoop initWorld frameTime 3 render
null
https://raw.githubusercontent.com/danielholmes/wolf3d-haskell/de934f657f1fb4351591448bb4e25aaa4923571f/src/Wolf3D/Main.hs
haskell
Original native size
module Wolf3D.Main ( createMain ) where import Wolf3D.Runner import Wolf3D.UI import Wolf3D.WorldData import Wolf3D.Display.Data import qualified SDL import Data.StateVar (($=)) type Scale = Int createMain :: Scale -> World -> (SDL.Renderer -> IO (SimRun -> IO ())) -> IO () createMain s initWorld createRender = do let width = (fromIntegral s) * screenWidth wolf3d was 320 x 200 on 4:3 displays , so it was scaled vertically let windowSize = (width, width `div` 4 * 3) On a machine with infinite resources , frame rate of Wolf3D was 70fps let frameTime = 14 createUI windowSize $ \r -> do render <- createRender r let fWindowWidth = fromIntegral (fst windowSize) let fWindowHeight = fromIntegral (snd windowSize) let fScreenWidth = fromIntegral screenWidth let fScreenHeight = fromIntegral screenHeight let scaleX = fWindowWidth / fScreenWidth let scaleY = fWindowHeight / fScreenHeight SDL.rendererScale r $= (SDL.V2 scaleX scaleY) runLoop initWorld frameTime 3 render
940852240ddfbea44be16b3650c20df3c4e9a35c111cbec6936d5b5f5cd670c4
klutometis/clrs
11.1-3.scm
(require-extension syntax-case check vector-lib) (require '../11.1/section) (require '../10.2/section) (import section-11.1) (import section-10.2) (let ((table (make-mda-table 2)) (e1 (make-da-element 0 (make-dlink 1 #f #f))) (e2 (make-da-element 0 (make-dlink 2 #f #f))) (e3 (make-da-element 1 (make-dlink 3 #f #f)))) (mda-insert! table e1) (mda-insert! table e2) (mda-insert! table e3) (check (mda->vector table) => '#((2 1) (3))) (mda-delete! table e2) (check (mda->vector table) => '#((1) (3))) (check (dlist-map dlink-key (mda-search table 1)) => '(3)))
null
https://raw.githubusercontent.com/klutometis/clrs/f85a8f0036f0946c9e64dde3259a19acc62b74a1/11.1/11.1-3.scm
scheme
(require-extension syntax-case check vector-lib) (require '../11.1/section) (require '../10.2/section) (import section-11.1) (import section-10.2) (let ((table (make-mda-table 2)) (e1 (make-da-element 0 (make-dlink 1 #f #f))) (e2 (make-da-element 0 (make-dlink 2 #f #f))) (e3 (make-da-element 1 (make-dlink 3 #f #f)))) (mda-insert! table e1) (mda-insert! table e2) (mda-insert! table e3) (check (mda->vector table) => '#((2 1) (3))) (mda-delete! table e2) (check (mda->vector table) => '#((1) (3))) (check (dlist-map dlink-key (mda-search table 1)) => '(3)))
69b37039968a975d43bcd00f3eac9db75b22faa16a8a334edab0036eb38b7c90
aliter/aliter
zone_master.erl
-module(zone_master). -behaviour(gen_server). -include("include/records.hrl"). -export([start_link/1]). -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([tick/0]). -record(state, {npc_id, servers}). start_link(Conf) -> log:debug("Starting master zone server."), gen_server:start_link({local, ?MODULE}, ?MODULE, Conf, []). init(Conf) -> process_flag(trap_exit, true), application:set_env(zone, started, now()), config:set_env(zone, Conf), ok = elixir:start_app(), nif:init(), zone_npc:load_all(), {zones, Zones} = config:find(server.zones, Conf), { ok, #state{ npc_id = 5000000, servers = [zone_srv:server_for(P) || {P, _} <- Zones] } }. handle_call({who_serves, Map}, _From, State) -> log:debug("Zone master server got who_serves call.", [{map, Map}]), { reply, who_serves(Map, State#state.servers), State }; handle_call({get_player, ActorID}, _From, State) -> log:debug("Zone master server got get_player call.", [{actor, ActorID}]), { reply, get_player( ActorID, State#state.servers ), State }; handle_call({get_player_by, Pred}, _From, State) -> log:debug("Zone master got get_player_by call."), { reply, get_player_by( Pred, State#state.servers ), State }; handle_call(player_count, _from, State) -> { reply, player_count(State#state.servers), State }; handle_call(Request, _From, State) -> log:debug("Zone master server got call.", [{call, Request}]), {reply, {illegal_request, Request}, State}. handle_cast({send_to_all, Msg}, State) -> lists:foreach( fun(Server) -> gen_server:cast(Server, Msg) end, State#state.servers ), {noreply, State}; handle_cast( {register_npc, Name, Sprite, Map, {X, Y}, Direction, Object}, State = #state{npc_id = Id}) -> lists:foreach( fun(Server) -> gen_server:cast( Server, { register_npc, #npc{ id = Id, name = Name, sprite = Sprite, map = Map, coordinates = {X, Y}, direction = Direction, main = Object } }) end, State#state.servers ), {noreply, State#state{npc_id = Id + 1}}; handle_cast(Cast, State) -> log:debug("Zone master server got cast.", [{cast, Cast}]), {noreply, State}. handle_info({'EXIT', From, Reason}, State) -> log:error("Zone master got EXIT signal.", [{from, From}, {reason, Reason}]), {stop, normal, State}; handle_info(Info, State) -> log:debug("Zone master server got info.", [{info, Info}]), {noreply, State}. terminate(_Reason, _State) -> log:info("Zone master server terminating."), ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. who_serves(_Map, []) -> none; who_serves(Map, [Server | Servers]) -> case gen_server:call(Server, {provides, Map}) of {yes, Port} -> {zone, Port, Server}; no -> who_serves(Map, Servers) end. player_count([]) -> 0; player_count([Server | Servers]) -> gen_server:call(Server, player_count) + player_count(Servers). get_player(_ActorID, []) -> none; get_player(ActorID, [Server | Servers]) -> case gen_server:call(Server, {get_player, ActorID}) of {ok, FSM} -> {ok, FSM}; none -> get_player(ActorID, Servers) end. get_player_by(_Pred, []) -> none; get_player_by(Pred, [Server | Servers]) -> log:debug( "Looking for player from zone_master.", [{server, Server}, {pred, Pred}] ), case gen_server:call(Server, {get_player_by, Pred}) of {ok, State} -> {ok, State}; none -> get_player_by(Pred, Servers) end. tick() -> {ok, Started} = application:get_env(zone, started), round(timer:now_diff(now(), Started) / 1000).
null
https://raw.githubusercontent.com/aliter/aliter/03c7d395d5812887aecdca20b16369f8a8abd278/src/zone/zone_master.erl
erlang
-module(zone_master). -behaviour(gen_server). -include("include/records.hrl"). -export([start_link/1]). -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([tick/0]). -record(state, {npc_id, servers}). start_link(Conf) -> log:debug("Starting master zone server."), gen_server:start_link({local, ?MODULE}, ?MODULE, Conf, []). init(Conf) -> process_flag(trap_exit, true), application:set_env(zone, started, now()), config:set_env(zone, Conf), ok = elixir:start_app(), nif:init(), zone_npc:load_all(), {zones, Zones} = config:find(server.zones, Conf), { ok, #state{ npc_id = 5000000, servers = [zone_srv:server_for(P) || {P, _} <- Zones] } }. handle_call({who_serves, Map}, _From, State) -> log:debug("Zone master server got who_serves call.", [{map, Map}]), { reply, who_serves(Map, State#state.servers), State }; handle_call({get_player, ActorID}, _From, State) -> log:debug("Zone master server got get_player call.", [{actor, ActorID}]), { reply, get_player( ActorID, State#state.servers ), State }; handle_call({get_player_by, Pred}, _From, State) -> log:debug("Zone master got get_player_by call."), { reply, get_player_by( Pred, State#state.servers ), State }; handle_call(player_count, _from, State) -> { reply, player_count(State#state.servers), State }; handle_call(Request, _From, State) -> log:debug("Zone master server got call.", [{call, Request}]), {reply, {illegal_request, Request}, State}. handle_cast({send_to_all, Msg}, State) -> lists:foreach( fun(Server) -> gen_server:cast(Server, Msg) end, State#state.servers ), {noreply, State}; handle_cast( {register_npc, Name, Sprite, Map, {X, Y}, Direction, Object}, State = #state{npc_id = Id}) -> lists:foreach( fun(Server) -> gen_server:cast( Server, { register_npc, #npc{ id = Id, name = Name, sprite = Sprite, map = Map, coordinates = {X, Y}, direction = Direction, main = Object } }) end, State#state.servers ), {noreply, State#state{npc_id = Id + 1}}; handle_cast(Cast, State) -> log:debug("Zone master server got cast.", [{cast, Cast}]), {noreply, State}. handle_info({'EXIT', From, Reason}, State) -> log:error("Zone master got EXIT signal.", [{from, From}, {reason, Reason}]), {stop, normal, State}; handle_info(Info, State) -> log:debug("Zone master server got info.", [{info, Info}]), {noreply, State}. terminate(_Reason, _State) -> log:info("Zone master server terminating."), ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. who_serves(_Map, []) -> none; who_serves(Map, [Server | Servers]) -> case gen_server:call(Server, {provides, Map}) of {yes, Port} -> {zone, Port, Server}; no -> who_serves(Map, Servers) end. player_count([]) -> 0; player_count([Server | Servers]) -> gen_server:call(Server, player_count) + player_count(Servers). get_player(_ActorID, []) -> none; get_player(ActorID, [Server | Servers]) -> case gen_server:call(Server, {get_player, ActorID}) of {ok, FSM} -> {ok, FSM}; none -> get_player(ActorID, Servers) end. get_player_by(_Pred, []) -> none; get_player_by(Pred, [Server | Servers]) -> log:debug( "Looking for player from zone_master.", [{server, Server}, {pred, Pred}] ), case gen_server:call(Server, {get_player_by, Pred}) of {ok, State} -> {ok, State}; none -> get_player_by(Pred, Servers) end. tick() -> {ok, Started} = application:get_env(zone, started), round(timer:now_diff(now(), Started) / 1000).
e787f389a7bcfa5aaa2186d5f205026425a4ff42c6ccc6f2b75b125d2d561228
mirage/ptt-deployer
logging.ml
module Metrics = struct open Prometheus let namespace = "baseimages" let subsystem = "logs" let inc_messages = let help = "Total number of messages logged" in let c = Counter.v_labels ~label_names:[ "level"; "src" ] ~help ~namespace ~subsystem "messages_total" in fun lvl src -> let lvl = Logs.level_to_string (Some lvl) in Counter.inc_one @@ Counter.labels c [ lvl; src ] end let pp_timestamp f x = let open Unix in let tm = localtime x in Fmt.pf f "%04d-%02d-%02d %02d:%02d.%02d" (tm.tm_year + 1900) (tm.tm_mon + 1) tm.tm_mday tm.tm_hour tm.tm_min tm.tm_sec let reporter = let report src level ~over k msgf = let k _ = over (); k () in let src = Logs.Src.name src in Metrics.inc_messages level src; msgf @@ fun ?header ?tags:_ fmt -> Fmt.kpf k Fmt.stdout ("%a %a %a @[" ^^ fmt ^^ "@]@.") pp_timestamp (Unix.gettimeofday ()) Fmt.(styled `Magenta string) (Printf.sprintf "%14s" src) Logs_fmt.pp_header (level, header) in { Logs.report } let init () = Fmt_tty.setup_std_outputs (); Logs.(set_level (Some Info)); Logs.set_reporter reporter let run x = match Lwt_main.run x with | Ok () -> Ok () | Error (`Msg m) as e -> Logs.err (fun f -> f "%a" Fmt.lines m); e
null
https://raw.githubusercontent.com/mirage/ptt-deployer/9a2bd4464c6dbc189ba1331adeaedc73defe01d2/src/logging.ml
ocaml
module Metrics = struct open Prometheus let namespace = "baseimages" let subsystem = "logs" let inc_messages = let help = "Total number of messages logged" in let c = Counter.v_labels ~label_names:[ "level"; "src" ] ~help ~namespace ~subsystem "messages_total" in fun lvl src -> let lvl = Logs.level_to_string (Some lvl) in Counter.inc_one @@ Counter.labels c [ lvl; src ] end let pp_timestamp f x = let open Unix in let tm = localtime x in Fmt.pf f "%04d-%02d-%02d %02d:%02d.%02d" (tm.tm_year + 1900) (tm.tm_mon + 1) tm.tm_mday tm.tm_hour tm.tm_min tm.tm_sec let reporter = let report src level ~over k msgf = let k _ = over (); k () in let src = Logs.Src.name src in Metrics.inc_messages level src; msgf @@ fun ?header ?tags:_ fmt -> Fmt.kpf k Fmt.stdout ("%a %a %a @[" ^^ fmt ^^ "@]@.") pp_timestamp (Unix.gettimeofday ()) Fmt.(styled `Magenta string) (Printf.sprintf "%14s" src) Logs_fmt.pp_header (level, header) in { Logs.report } let init () = Fmt_tty.setup_std_outputs (); Logs.(set_level (Some Info)); Logs.set_reporter reporter let run x = match Lwt_main.run x with | Ok () -> Ok () | Error (`Msg m) as e -> Logs.err (fun f -> f "%a" Fmt.lines m); e
44155c5723f0e9b7702a1fde79c717a27d1eeb673523ffd5f384324b5d922d67
Gandalf-/coreutils
LsSpec.hs
module LsSpec where import Coreutils.Ls import Data.Maybe import Data.Time import Test.Hspec spec :: Spec spec = parallel $ do describe "sorting" $ do it "defaults" $ do let rt = getRuntime defaultOptions sorter rt [entry "b", entry "a", entry "c"] `shouldBe` [entry "a", entry "b", entry "c"] it "reverse" $ do let rt = getRuntime defaultOptions { optSortReverse = True } sorter rt [entry "b", entry "a", entry "c"] `shouldBe` [entry "c", entry "b", entry "a"] it "nothing" $ do let rt = getRuntime defaultOptions { optSort = False } sorter rt [entry "b", entry "a", entry "c"] `shouldBe` [entry "b", entry "a", entry "c"] it "size" $ do let rt = getRuntime defaultOptions { optSortStrategy = SizeSorting } sorter rt [sEntry "a" 5, sEntry "c" 0, sEntry "b" 25] `shouldBe` [sEntry "b" 25, sEntry "a" 5, sEntry "c" 0] it "mtime" $ do let rt = getRuntime defaultOptions { optSortStrategy = StatSorting } sorter rt [mEntry "a" 5, mEntry "c" 0, mEntry "b" 25] `shouldBe` [mEntry "b" 25, mEntry "a" 5, mEntry "c" 0] it "reverse mtime" $ do let rt = getRuntime defaultOptions { optSortStrategy = StatSorting, optSortReverse = True } sorter rt [mEntry "a" 5, mEntry "c" 0, mEntry "b" 25] `shouldBe` [mEntry "c" 0, mEntry "a" 5, mEntry "b" 25] it "atime" $ do let rt = getRuntime defaultOptions { optSortStrategy = StatSorting, optSortStat = LastAccess } sorter rt [aEntry "a" 0 5, aEntry "c" 3 0, aEntry "b" 2 25] `shouldBe` [aEntry "b" 2 25, aEntry "a" 0 5, aEntry "c" 3 0] describe "getEntry" $ do it "defaults" $ do let os = defaultOptions getEntry os "LICENSE" `shouldReturn` entry "LICENSE" it "size file" $ do let os = defaultOptions { optSortStrategy = SizeSorting } getEntry os "LICENSE" `shouldReturn` sEntry "LICENSE" 1063 it "size dir" $ do let os = defaultOptions { optSortStrategy = SizeSorting } getEntry os "src" `shouldReturn` sEntry "src" 0 it "timestamps" $ do let os = defaultOptions { optSortStrategy = StatSorting } en <- getEntry os "LICENSE" mtime en `shouldSatisfy` isJust atime en `shouldSatisfy` isJust size en `shouldBe` Nothing perms en `shouldBe` Nothing describe "list" $ do it "defaults" $ do let rt = getRuntime defaultOptions es <- list rt "." "src" `elem` es `shouldBe` True "." `elem` es `shouldBe` False ".." `elem` es `shouldBe` False ".git" `elem` es `shouldBe` False it "all dots" $ do let rt = getRuntime defaultOptions { optAllDots = True } es <- list rt "." "src" `elem` es `shouldBe` True "." `elem` es `shouldBe` True ".." `elem` es `shouldBe` True ".git" `elem` es `shouldBe` True it "hidden" $ do let rt = getRuntime defaultOptions { optHidden = True } es <- list rt "." "src" `elem` es `shouldBe` True "." `elem` es `shouldBe` False ".." `elem` es `shouldBe` False ".git" `elem` es `shouldBe` True describe "ls" $ it "works" $ do let mList "." = pure ["b", "a", "c"] mList xs = fail xs mFill "a" = pure $ entry "a" mFill "b" = pure $ entry "b" mFill "c" = pure $ entry "c" mFill xs = fail xs rt = (getRuntime defaultOptions) { fill = mFill, list = mList } execute rt ["."] `shouldReturn` ["a", "b", "c"] where entry n = Entry n Nothing Nothing Nothing Nothing sEntry n size = Entry n (Just size) Nothing Nothing Nothing mEntry n mtime = Entry n Nothing (fromDay mtime) Nothing Nothing aEntry n mtime atime = Entry n Nothing (fromDay mtime) (fromDay atime) Nothing fromDay day = Just $ UTCTime (fromGregorian 2018 day 27) (secondsToDiffTime 0)
null
https://raw.githubusercontent.com/Gandalf-/coreutils/5b489febfbe6dfa56b1c894ede3d85c5001d2c0d/test/LsSpec.hs
haskell
module LsSpec where import Coreutils.Ls import Data.Maybe import Data.Time import Test.Hspec spec :: Spec spec = parallel $ do describe "sorting" $ do it "defaults" $ do let rt = getRuntime defaultOptions sorter rt [entry "b", entry "a", entry "c"] `shouldBe` [entry "a", entry "b", entry "c"] it "reverse" $ do let rt = getRuntime defaultOptions { optSortReverse = True } sorter rt [entry "b", entry "a", entry "c"] `shouldBe` [entry "c", entry "b", entry "a"] it "nothing" $ do let rt = getRuntime defaultOptions { optSort = False } sorter rt [entry "b", entry "a", entry "c"] `shouldBe` [entry "b", entry "a", entry "c"] it "size" $ do let rt = getRuntime defaultOptions { optSortStrategy = SizeSorting } sorter rt [sEntry "a" 5, sEntry "c" 0, sEntry "b" 25] `shouldBe` [sEntry "b" 25, sEntry "a" 5, sEntry "c" 0] it "mtime" $ do let rt = getRuntime defaultOptions { optSortStrategy = StatSorting } sorter rt [mEntry "a" 5, mEntry "c" 0, mEntry "b" 25] `shouldBe` [mEntry "b" 25, mEntry "a" 5, mEntry "c" 0] it "reverse mtime" $ do let rt = getRuntime defaultOptions { optSortStrategy = StatSorting, optSortReverse = True } sorter rt [mEntry "a" 5, mEntry "c" 0, mEntry "b" 25] `shouldBe` [mEntry "c" 0, mEntry "a" 5, mEntry "b" 25] it "atime" $ do let rt = getRuntime defaultOptions { optSortStrategy = StatSorting, optSortStat = LastAccess } sorter rt [aEntry "a" 0 5, aEntry "c" 3 0, aEntry "b" 2 25] `shouldBe` [aEntry "b" 2 25, aEntry "a" 0 5, aEntry "c" 3 0] describe "getEntry" $ do it "defaults" $ do let os = defaultOptions getEntry os "LICENSE" `shouldReturn` entry "LICENSE" it "size file" $ do let os = defaultOptions { optSortStrategy = SizeSorting } getEntry os "LICENSE" `shouldReturn` sEntry "LICENSE" 1063 it "size dir" $ do let os = defaultOptions { optSortStrategy = SizeSorting } getEntry os "src" `shouldReturn` sEntry "src" 0 it "timestamps" $ do let os = defaultOptions { optSortStrategy = StatSorting } en <- getEntry os "LICENSE" mtime en `shouldSatisfy` isJust atime en `shouldSatisfy` isJust size en `shouldBe` Nothing perms en `shouldBe` Nothing describe "list" $ do it "defaults" $ do let rt = getRuntime defaultOptions es <- list rt "." "src" `elem` es `shouldBe` True "." `elem` es `shouldBe` False ".." `elem` es `shouldBe` False ".git" `elem` es `shouldBe` False it "all dots" $ do let rt = getRuntime defaultOptions { optAllDots = True } es <- list rt "." "src" `elem` es `shouldBe` True "." `elem` es `shouldBe` True ".." `elem` es `shouldBe` True ".git" `elem` es `shouldBe` True it "hidden" $ do let rt = getRuntime defaultOptions { optHidden = True } es <- list rt "." "src" `elem` es `shouldBe` True "." `elem` es `shouldBe` False ".." `elem` es `shouldBe` False ".git" `elem` es `shouldBe` True describe "ls" $ it "works" $ do let mList "." = pure ["b", "a", "c"] mList xs = fail xs mFill "a" = pure $ entry "a" mFill "b" = pure $ entry "b" mFill "c" = pure $ entry "c" mFill xs = fail xs rt = (getRuntime defaultOptions) { fill = mFill, list = mList } execute rt ["."] `shouldReturn` ["a", "b", "c"] where entry n = Entry n Nothing Nothing Nothing Nothing sEntry n size = Entry n (Just size) Nothing Nothing Nothing mEntry n mtime = Entry n Nothing (fromDay mtime) Nothing Nothing aEntry n mtime atime = Entry n Nothing (fromDay mtime) (fromDay atime) Nothing fromDay day = Just $ UTCTime (fromGregorian 2018 day 27) (secondsToDiffTime 0)
1ce21a49527df1ba4359d317e5b69356bacb47d8d4625d4aea0ef76e0f2d43a0
hjcapple/reading-sicp
exercise_1_30.scm
#lang racket P40 - [ 练习 1.30 ] (define (sum term a next b) (define (iter a ret) (if (> a b) ret (iter (next a) (+ (term a) ret)))) (iter a 0)) ;;;;;;;;;;;;;;;;;;; (module* test #f (require rackunit) (define (inc n) (+ n 1)) (define (identity x) x) (check-equal? (sum identity 1 inc 100) 5050) )
null
https://raw.githubusercontent.com/hjcapple/reading-sicp/7051d55dde841c06cf9326dc865d33d656702ecc/chapter_1/exercise_1_30.scm
scheme
#lang racket P40 - [ 练习 1.30 ] (define (sum term a next b) (define (iter a ret) (if (> a b) ret (iter (next a) (+ (term a) ret)))) (iter a 0)) (module* test #f (require rackunit) (define (inc n) (+ n 1)) (define (identity x) x) (check-equal? (sum identity 1 inc 100) 5050) )
1e8d3b5e2478a19e7163b75ac7e1d7dc26a5741085dc97f2b8c39dfc8a2e4184
bravit/hid-examples
maybe.hs
import Text.Read (readMaybe) type Name = String type Phone = String type Location = String type PhoneNumbers = [(Name, Phone)] type Locations = [(Phone, Location)] doubleStrNumber1 :: (Num a, Read a) => String -> Maybe a doubleStrNumber1 str = case readMaybe str of Just x -> Just (2*x) Nothing -> Nothing doubleStrNumber2 :: (Num a, Read a) => String -> Maybe a doubleStrNumber2 s = (2*) `fmap` readMaybe s plusStrNumbers :: (Num a, Read a) => String -> String -> Maybe a plusStrNumbers s1 s2 = (+) <$> readMaybe s1 <*> readMaybe s2 locateByName :: PhoneNumbers -> Locations -> Name -> Maybe Location locateByName pnumbers locs name = lookup name pnumbers >>= flip lookup locs locateByName' :: PhoneNumbers -> Locations -> Name -> Maybe Location locateByName' pnumbers locs name = case lookup name pnumbers of Just number -> lookup number locs Nothing -> Nothing main :: IO () main = do print (doubleStrNumber1 "21" :: Maybe Int) print (doubleStrNumber2 "21" :: Maybe Int) print (plusStrNumbers "10" "xx" :: Maybe Int)
null
https://raw.githubusercontent.com/bravit/hid-examples/913e116b7ee9c7971bba10fe70ae0b61bfb9391b/ch05/maybe.hs
haskell
import Text.Read (readMaybe) type Name = String type Phone = String type Location = String type PhoneNumbers = [(Name, Phone)] type Locations = [(Phone, Location)] doubleStrNumber1 :: (Num a, Read a) => String -> Maybe a doubleStrNumber1 str = case readMaybe str of Just x -> Just (2*x) Nothing -> Nothing doubleStrNumber2 :: (Num a, Read a) => String -> Maybe a doubleStrNumber2 s = (2*) `fmap` readMaybe s plusStrNumbers :: (Num a, Read a) => String -> String -> Maybe a plusStrNumbers s1 s2 = (+) <$> readMaybe s1 <*> readMaybe s2 locateByName :: PhoneNumbers -> Locations -> Name -> Maybe Location locateByName pnumbers locs name = lookup name pnumbers >>= flip lookup locs locateByName' :: PhoneNumbers -> Locations -> Name -> Maybe Location locateByName' pnumbers locs name = case lookup name pnumbers of Just number -> lookup number locs Nothing -> Nothing main :: IO () main = do print (doubleStrNumber1 "21" :: Maybe Int) print (doubleStrNumber2 "21" :: Maybe Int) print (plusStrNumbers "10" "xx" :: Maybe Int)
c4adc0fbfc63e6d70fc2a1cda588ba9e0c9ae892c63e6eb7e861e46b4da4eb07
reagent-project/reagent-template
doo_runner.cljs
(ns {{project-ns}}.doo-runner (:require [doo.runner :refer-macros [doo-tests]] [{{project-ns}}.core-test])) (doo-tests '{{project-ns}}.core-test)
null
https://raw.githubusercontent.com/reagent-project/reagent-template/c769c6806540a9faafec36c27b07a1c86ae5eff7/resources/leiningen/new/reagent/runners/doo_runner.cljs
clojure
(ns {{project-ns}}.doo-runner (:require [doo.runner :refer-macros [doo-tests]] [{{project-ns}}.core-test])) (doo-tests '{{project-ns}}.core-test)
0448c91133ed2b9d5928d7de7f65f53bd857c0df96c57a99a1e2862aa513b886
mbutterick/beautiful-racket
main.rkt
#lang racket/base (module reader racket/base (require "reader.rkt") (provide (all-from-out "reader.rkt")))
null
https://raw.githubusercontent.com/mbutterick/beautiful-racket/f0e2cb5b325733b3f9cbd554cc7d2bb236af9ee9/beautiful-racket-demo/txtadv-demo/main.rkt
racket
#lang racket/base (module reader racket/base (require "reader.rkt") (provide (all-from-out "reader.rkt")))
a41f4f4dd803de1f4cb1d9ad9c1c35858dd9d54842b5153d37ebe593abf0cb2a
JHU-PL-Lab/jaylang
sum.ml
(* USED: PLDI2011 as sum USED: PEPM2013 as sum *) let rec sum n = if n <= 0 then 0 else n + sum (n-1) let main n = assert (n <= sum n)
null
https://raw.githubusercontent.com/JHU-PL-Lab/jaylang/484b3876986a515fb57b11768a1b3b50418cde0c/benchmark/cases/mochi_origin/mochi/sum.ml
ocaml
USED: PLDI2011 as sum USED: PEPM2013 as sum
let rec sum n = if n <= 0 then 0 else n + sum (n-1) let main n = assert (n <= sum n)
753ca94c8bd60f245af5f8ac0f7ca7faf40ee0de88c44bfee00a9f55a1148bf7
annapawlicka/om-data-vis
handler.clj
(ns om-data-vis.handler (:use compojure.core) (:require [compojure.handler :as handler] [compojure.route :as route] [liberator.core :refer [resource defresource]] [liberator.representation :refer (ring-response as-response)] [clojure.java.io :as io] [clojure.data.json :as json])) ;; Data - for quick demo only. Should be replaced with database, CSV, etc. ;; (def data {:devices [{:id "01" :type "electricityConsumption" :description "I'm a device with id 01" :unit "kWh"} {:id "02" :type "gasConsumption" :description "I'm a device with id 02" :unit "kWh"}] :measurements [{:id "01" :type "electricityConsumption" :timestamp "01/01/2011" :value 0.8} {:id "01" :type "electricityConsumption" :timestamp "01/02/2011" :value 0.9} {:id "01" :type "electricityConsumption" :timestamp "01/03/2011" :value 0.8} {:id "01" :type "electricityConsumption" :timestamp "01/04/2011" :value 0.75} {:id "01" :type "electricityConsumption" :timestamp "01/05/2011" :value 0.65} {:id "02" :type "gasConsumption" :timestamp "01/01/2011" :value 6} {:id "02" :type "gasConsumption" :timestamp "01/02/2011" :value 10} {:id "02" :type "gasConsumption" :timestamp "01/03/2011" :value 12} {:id "02" :type "gasConsumption" :timestmap "01/04/2011" :value 15} {:id "02" :type "gasConsumption" :timestamp "01/05/2011" :value 18}]}) (defn retrieve-api-key [ctx] (let [api-key (slurp (io/resource "lastfm.edn"))] (-> (as-response api-key ctx) (assoc-in [:headers "Access-Control-Allow-Origin"] "*") (assoc-in [:headers "Access-Control-Allow-Headers"] "X-Requested-With") (assoc-in [:headers "Access-Control-Allow-Methods"] "*") (ring-response)))) (defn retrieve-measurements [id type ctx] (let [measurements (filter #(and (= (:id %) id) (= (:type %) type)) (get-in data [:measurements]))] (when measurements (-> (as-response measurements ctx) (assoc-in [:headers "Access-Control-Allow-Origin"] "*") (assoc-in [:headers "Access-Control-Allow-Headers"] "X-Requested-With") (assoc-in [:headers "Access-Control-Allow-Methods"] "*") (ring-response))))) (defn retrieve-devices [ctx] (let [devices (get-in data [:devices])] (-> (as-response devices ctx) (assoc-in [:headers "Access-Control-Allow-Origin"] "*") (assoc-in [:headers "Access-Control-Allow-Headers"] "X-Requested-With") (assoc-in [:headers "Access-Control-Allow-Methods"] "*") (ring-response)))) (defresource measurements-resource [id type] :allowed-methods #{:get} :available-media-types ["application/json"] :handle-ok (partial retrieve-measurements id type)) (defresource devices-resource [_] :allowed-methods #{:get} :known-content-type? #{"application/edn"} :available-media-types #{"application/edn"} :handle-ok retrieve-devices) (defresource api-key [_] :allowed-methods #{:get} :known-content-type? #{"application/edn"} :available-media-types #{"application/edn"} :handle-ok retrieve-api-key) (defroutes app-routes (GET "/" [] "Hello World") (ANY "/device/:id/type/:type/measurements/" [id type] (measurements-resource id type)) (ANY "/devices/" [] devices-resource) (GET "/apikey/" [] api-key) (route/files "/examples" {:root "examples"}) (route/files "/css" {:root "css"}) (route/files "/js" {:root "js"}) (route/not-found "Not Found")) (def app (handler/site app-routes))
null
https://raw.githubusercontent.com/annapawlicka/om-data-vis/4e0323cf4a58bc90e12f9ce99ed3b7cc21c0a5b6/src/om_data_vis/handler.clj
clojure
Data - for quick demo only. Should be replaced with database, CSV, etc. ;;
(ns om-data-vis.handler (:use compojure.core) (:require [compojure.handler :as handler] [compojure.route :as route] [liberator.core :refer [resource defresource]] [liberator.representation :refer (ring-response as-response)] [clojure.java.io :as io] [clojure.data.json :as json])) (def data {:devices [{:id "01" :type "electricityConsumption" :description "I'm a device with id 01" :unit "kWh"} {:id "02" :type "gasConsumption" :description "I'm a device with id 02" :unit "kWh"}] :measurements [{:id "01" :type "electricityConsumption" :timestamp "01/01/2011" :value 0.8} {:id "01" :type "electricityConsumption" :timestamp "01/02/2011" :value 0.9} {:id "01" :type "electricityConsumption" :timestamp "01/03/2011" :value 0.8} {:id "01" :type "electricityConsumption" :timestamp "01/04/2011" :value 0.75} {:id "01" :type "electricityConsumption" :timestamp "01/05/2011" :value 0.65} {:id "02" :type "gasConsumption" :timestamp "01/01/2011" :value 6} {:id "02" :type "gasConsumption" :timestamp "01/02/2011" :value 10} {:id "02" :type "gasConsumption" :timestamp "01/03/2011" :value 12} {:id "02" :type "gasConsumption" :timestmap "01/04/2011" :value 15} {:id "02" :type "gasConsumption" :timestamp "01/05/2011" :value 18}]}) (defn retrieve-api-key [ctx] (let [api-key (slurp (io/resource "lastfm.edn"))] (-> (as-response api-key ctx) (assoc-in [:headers "Access-Control-Allow-Origin"] "*") (assoc-in [:headers "Access-Control-Allow-Headers"] "X-Requested-With") (assoc-in [:headers "Access-Control-Allow-Methods"] "*") (ring-response)))) (defn retrieve-measurements [id type ctx] (let [measurements (filter #(and (= (:id %) id) (= (:type %) type)) (get-in data [:measurements]))] (when measurements (-> (as-response measurements ctx) (assoc-in [:headers "Access-Control-Allow-Origin"] "*") (assoc-in [:headers "Access-Control-Allow-Headers"] "X-Requested-With") (assoc-in [:headers "Access-Control-Allow-Methods"] "*") (ring-response))))) (defn retrieve-devices [ctx] (let [devices (get-in data [:devices])] (-> (as-response devices ctx) (assoc-in [:headers "Access-Control-Allow-Origin"] "*") (assoc-in [:headers "Access-Control-Allow-Headers"] "X-Requested-With") (assoc-in [:headers "Access-Control-Allow-Methods"] "*") (ring-response)))) (defresource measurements-resource [id type] :allowed-methods #{:get} :available-media-types ["application/json"] :handle-ok (partial retrieve-measurements id type)) (defresource devices-resource [_] :allowed-methods #{:get} :known-content-type? #{"application/edn"} :available-media-types #{"application/edn"} :handle-ok retrieve-devices) (defresource api-key [_] :allowed-methods #{:get} :known-content-type? #{"application/edn"} :available-media-types #{"application/edn"} :handle-ok retrieve-api-key) (defroutes app-routes (GET "/" [] "Hello World") (ANY "/device/:id/type/:type/measurements/" [id type] (measurements-resource id type)) (ANY "/devices/" [] devices-resource) (GET "/apikey/" [] api-key) (route/files "/examples" {:root "examples"}) (route/files "/css" {:root "css"}) (route/files "/js" {:root "js"}) (route/not-found "Not Found")) (def app (handler/site app-routes))
f39b5300f5c2d3d690bbb8ae2ef5d925bea11318953fedb1ca72b4e3de8497ad
pjones/byline
menu.hs
-- | -- -- Copyright: -- This file is part of the package byline. It is subject to the -- license terms in the LICENSE file found in the top-level -- directory of this distribution and at: -- -- -- -- No part of this package, including this file, may be copied, -- modified, propagated, or distributed except according to the -- terms contained in the LICENSE file. -- -- License: BSD-2-Clause module Main ( main, ) where import Byline.Menu import qualified Data.List.NonEmpty as NonEmpty -- | Menu items that we'll ask the user to choose from. data Item = Fruit Text | Vegetable Text deriving (Show) -- | How to display a menu item. instance ToStylizedText Item where toStylizedText item = case item of Fruit name -> text name <> (" (fruit)" & fg red) Vegetable name -> text name <> (" (vegetable)" & fg green) -- | The list of menu items. items :: NonEmpty Item items = NonEmpty.fromList [ Fruit "Watermelon", Vegetable "Cucumber", Fruit "Kiwi", Vegetable "Asparagus" ] -- | It's main! main :: IO () main = do let menuConfig = menuBanner ("Pick a snack: " & bold) $ menu items prompt = "Which snack? " & bold & fg yellow onError = "Please pick a valid item!" & bg (vivid red) -- Display the menu and get back the item the user selected. The -- user will be able to select an item using it's index, name, or -- using tab completion. answer <- runBylineT $ askWithMenuRepeatedly menuConfig prompt onError putStrLn ("You picked: " ++ show answer)
null
https://raw.githubusercontent.com/pjones/byline/e975c1d6787acb7019d86cf9e29746796e4a5134/examples/menu.hs
haskell
| Copyright: This file is part of the package byline. It is subject to the license terms in the LICENSE file found in the top-level directory of this distribution and at: No part of this package, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the LICENSE file. License: BSD-2-Clause | Menu items that we'll ask the user to choose from. | How to display a menu item. | The list of menu items. | It's main! Display the menu and get back the item the user selected. The user will be able to select an item using it's index, name, or using tab completion.
module Main ( main, ) where import Byline.Menu import qualified Data.List.NonEmpty as NonEmpty data Item = Fruit Text | Vegetable Text deriving (Show) instance ToStylizedText Item where toStylizedText item = case item of Fruit name -> text name <> (" (fruit)" & fg red) Vegetable name -> text name <> (" (vegetable)" & fg green) items :: NonEmpty Item items = NonEmpty.fromList [ Fruit "Watermelon", Vegetable "Cucumber", Fruit "Kiwi", Vegetable "Asparagus" ] main :: IO () main = do let menuConfig = menuBanner ("Pick a snack: " & bold) $ menu items prompt = "Which snack? " & bold & fg yellow onError = "Please pick a valid item!" & bg (vivid red) answer <- runBylineT $ askWithMenuRepeatedly menuConfig prompt onError putStrLn ("You picked: " ++ show answer)
1b7b68c903ff7343f6f35dc7ce4fb01f4879896baf01a33902917967db495d18
ds-wizard/engine-backend
PackageBundleAudit.hs
module Wizard.Service.Package.Bundle.PackageBundleAudit where import Wizard.Model.Context.AppContext import Wizard.Service.Audit.AuditService auditPackageBundleExport :: String -> AppContextM () auditPackageBundleExport = logAudit "package_bundle" "export" auditPackageBundlePullFromRegistry :: String -> AppContextM () auditPackageBundlePullFromRegistry = logAudit "package_bundle" "pullFromRegistry" auditPackageBundleImportFromFile :: String -> AppContextM () auditPackageBundleImportFromFile = logAudit "package_bundle" "importFromFile"
null
https://raw.githubusercontent.com/ds-wizard/engine-backend/090f4f3460e8df128e88e2c3ce266b165e4a0a50/engine-wizard/src/Wizard/Service/Package/Bundle/PackageBundleAudit.hs
haskell
module Wizard.Service.Package.Bundle.PackageBundleAudit where import Wizard.Model.Context.AppContext import Wizard.Service.Audit.AuditService auditPackageBundleExport :: String -> AppContextM () auditPackageBundleExport = logAudit "package_bundle" "export" auditPackageBundlePullFromRegistry :: String -> AppContextM () auditPackageBundlePullFromRegistry = logAudit "package_bundle" "pullFromRegistry" auditPackageBundleImportFromFile :: String -> AppContextM () auditPackageBundleImportFromFile = logAudit "package_bundle" "importFromFile"
5a6e1abd061e33ff576dbe7cfc4080ad1ec0bf903ff4362554fdf4a50bb3c1cd
dfinity/motoko
hover_tests.ml
module Lsp = Lsp.Lsp_t let extract_cursor input = let cursor_pos = ref (0, 0) in String.split_on_char '\n' input |> List.mapi (fun line_num line -> match String.index_opt line '|' with | Some column_num -> cursor_pos := (line_num, column_num); line |> String.split_on_char '|' |> String.concat "" | None -> line) |> String.concat "\n" |> fun f -> (f, !cursor_pos) let hovered_identifier_test_case file expected = let file, (line, column) = extract_cursor file in let show = function | Some (Source_file.CIdent i) -> i | Some (Source_file.CQualified (qualifier, ident)) -> qualifier ^ "." ^ ident | None -> "None" in let actual = Source_file.cursor_target_at_pos Lsp.{ position_line = line; position_character = column } file in Option.equal ( = ) actual expected || (Printf.printf "\nExpected: %s\nActual: %s\n" (show expected) (show actual); false) let%test "it finds an identifier" = hovered_identifier_test_case "f|ilter" (Some (Source_file.CIdent "filter")) let%test "it ignores hovering over whitespace" = hovered_identifier_test_case "filter |" None let%test "it finds a qualified identifier" = hovered_identifier_test_case "List.f|ilter" (Some (Source_file.CQualified ("List", "filter")))
null
https://raw.githubusercontent.com/dfinity/motoko/399b8e8b0b47890388cd38ee0ace7638d9092b1a/src/languageServer/hover_tests.ml
ocaml
module Lsp = Lsp.Lsp_t let extract_cursor input = let cursor_pos = ref (0, 0) in String.split_on_char '\n' input |> List.mapi (fun line_num line -> match String.index_opt line '|' with | Some column_num -> cursor_pos := (line_num, column_num); line |> String.split_on_char '|' |> String.concat "" | None -> line) |> String.concat "\n" |> fun f -> (f, !cursor_pos) let hovered_identifier_test_case file expected = let file, (line, column) = extract_cursor file in let show = function | Some (Source_file.CIdent i) -> i | Some (Source_file.CQualified (qualifier, ident)) -> qualifier ^ "." ^ ident | None -> "None" in let actual = Source_file.cursor_target_at_pos Lsp.{ position_line = line; position_character = column } file in Option.equal ( = ) actual expected || (Printf.printf "\nExpected: %s\nActual: %s\n" (show expected) (show actual); false) let%test "it finds an identifier" = hovered_identifier_test_case "f|ilter" (Some (Source_file.CIdent "filter")) let%test "it ignores hovering over whitespace" = hovered_identifier_test_case "filter |" None let%test "it finds a qualified identifier" = hovered_identifier_test_case "List.f|ilter" (Some (Source_file.CQualified ("List", "filter")))
982ce1dd6f567634909f53c50d2b996ab584d80973baee1c587975b8c3d31bfc
racket/racket7
misc.rkt
;;---------------------------------------------------------------------- # % misc : file utilities , etc . - remaining functions (module misc '#%kernel (#%require "small-scheme.rkt" "define.rkt" "path.rkt" "old-path.rkt" "path-list.rkt" "executable-path.rkt" "reading-param.rkt" (for-syntax '#%kernel "qq-and-or.rkt" "stx.rkt" "stxcase-scheme.rkt" "stxcase.rkt")) ;; ------------------------------------------------------------------------- (define-for-syntax (pattern-failure user-stx pattern) (let*-values ([(sexpr) (syntax->datum user-stx)] [(msg) (if (pair? sexpr) (format "use does not match pattern: ~.s" (cons (car sexpr) pattern)) (if (symbol? sexpr) (format "use does not match pattern: ~.s" (cons sexpr pattern)) (error 'internal-error "something bad happened")))]) (raise-syntax-error #f msg user-stx))) (define-syntax define-syntax-rule (lambda (stx) (let-values ([(err) (lambda (what . xs) (apply raise-syntax-error 'define-syntax-rule what stx xs))]) (syntax-case stx () [(dr (name . pattern) template) (identifier? #'name) (syntax/loc stx (define-syntax name (lambda (user-stx) (syntax-case** dr #t user-stx () free-identifier=? #f [(_ . pattern) (syntax-protect (syntax/loc user-stx template))] [_ (pattern-failure user-stx 'pattern)]))))] [(_ (name . ptrn) tmpl) (err "expected an identifier" #'name)] [(_ (name . ptrn)) (err "missing template")] [(_ (name . ptrn) tmpl etc . _) (err "too many forms" #'etc)] [(_ head . _) (err "invalid pattern" #'head)])))) ;; ------------------------------------------------------------------------- (define rationalize (letrec ([check (lambda (x) (unless (real? x) (raise-argument-error 'rationalize "real?" x)))] [find-between (lambda (lo hi) (if (integer? lo) lo (let ([lo-int (floor lo)] [hi-int (floor hi)]) (if (< lo-int hi-int) (add1 lo-int) (+ lo-int (/ (find-between (/ (- hi lo-int)) (/ (- lo lo-int)))))))))] [do-find-between (lambda (lo hi) (cond [(negative? lo) (- (find-between (- hi) (- lo)))] [else (find-between lo hi)]))]) (lambda (x within) (check x) (check within) (let* ([delta (abs within)] [lo (- x delta)] [hi (+ x delta)]) (cond [(equal? x +nan.0) x] [(or (equal? x +inf.0) (equal? x -inf.0)) (if (equal? delta +inf.0) +nan.0 x)] [(equal? delta +inf.0) 0.0] [(not (= x x)) +nan.0] [(<= lo 0 hi) (if (exact? x) 0 0.0)] [(or (inexact? lo) (inexact? hi)) (exact->inexact (do-find-between (inexact->exact lo) (inexact->exact hi)))] [else (do-find-between lo hi)]))))) ;; ------------------------------------------------------------------------- (define (read-eval-print-loop) (let repl-loop () ;; This prompt catches all error escapes, including from read and print. (call-with-continuation-prompt (lambda () (let ([v ((current-prompt-read))]) (unless (eof-object? v) (call-with-values (lambda () ;; This prompt catches escapes during evaluation. ;; Unlike the outer prompt, the handler prints ;; the results. (call-with-continuation-prompt (lambda () (let ([w (cons '#%top-interaction v)]) ((current-eval) (if (syntax? v) (namespace-syntax-introduce (datum->syntax #f w v)) w)))))) (lambda results (for-each (current-print) results))) ;; Abort to loop. (Calling `repl-loop' directory would not be a tail call.) (abort-current-continuation (default-continuation-prompt-tag))))) (default-continuation-prompt-tag) (lambda args (repl-loop))))) (define load/cd (lambda (n) (unless (path-string? n) (raise-argument-error 'load/cd "path-string?" n)) (let-values ([(base name dir?) (split-path n)]) (if dir? (raise (exn:fail:filesystem (string->immutable-string (format "load/cd: cannot open a directory: ~s" n)) (current-continuation-marks))) (if (not (path? base)) (load n) (begin (if (not (directory-exists? base)) (raise (exn:fail:filesystem (string->immutable-string (format "load/cd: directory of ~s does not exist (current directory is ~s)" n (current-directory))) (current-continuation-marks))) (void)) (let ([orig (current-directory)]) (dynamic-wind (lambda () (current-directory base)) (lambda () (load name)) (lambda () (current-directory orig)))))))))) (define (-load load name path) (unless (path-string? path) (raise-argument-error name "path-string?" path)) (if (complete-path? path) (load path) (let ([dir (current-load-relative-directory)]) (load (if dir (path->complete-path path dir) path))))) (define (load-relative path) (-load load 'load-relative path)) (define (load-relative-extension path) (-load load-extension 'load-relative-extension path)) ;; ------------------------------------------------------------------------- (define-values (struct:guard make-guard guard? guard-ref guard-set!) (make-struct-type 'evt #f 1 0 #f (list (cons prop:evt 0)) (current-inspector) #f '(0))) (define (guard-evt proc) (unless (and (procedure? proc) (procedure-arity-includes? proc 0)) (raise-argument-error 'guard-evt "(any/c . -> . evt?)" proc)) (make-guard (lambda (self) (proc)))) (define (channel-get ch) (unless (channel? ch) (raise-argument-error 'channel-get "channel?" ch)) (sync ch)) (define (channel-try-get ch) (unless (channel? ch) (raise-argument-error 'channel-try-get "channel?" ch)) (sync/timeout 0 ch)) (define (channel-put ch val) (unless (channel? ch) (raise-argument-error 'channel-put "channel?" ch)) (and (sync (channel-put-evt ch val)) (void))) ;; ------------------------------------------------------------------------- (define (port? x) (or (input-port? x) (output-port? x))) (define writeln (case-lambda [(v) (writeln v (current-output-port))] [(v p) (unless (output-port? p) (raise-argument-error 'writeln "output-port?" 1 v p)) (write v p) (newline p)])) (define displayln (case-lambda [(v) (displayln v (current-output-port))] [(v p) (unless (output-port? p) (raise-argument-error 'displayln "output-port?" 1 v p)) (display v p) (newline p)])) (define println (case-lambda [(v) (println v (current-output-port) 0)] [(v p) (println v p 0)] [(v p d) (unless (output-port? p) (raise-argument-error 'println "output-port?" 1 v p d)) (unless (and (number? d) (or (= 0 d) (= d 1))) (raise-argument-error 'println "(or/c 0 1)" 2 v p d)) (print v p d) (newline p)])) ;; ------------------------------------------------------------------------- (define (string-no-nuls? s) (and (string? s) (not (regexp-match? #rx"\0" s)))) (define (bytes-environment-variable-name? s) (and (bytes? s) (if (eq? 'windows (system-type)) (regexp-match? #rx#"^[^\0=]+$" s) (regexp-match? #rx#"^[^\0=]*$" s)))) (define (string-environment-variable-name? s) (and (string? s) (bytes-environment-variable-name? (string->bytes/locale s (char->integer #\?))))) (define (getenv s) (unless (string-environment-variable-name? s) (raise-argument-error 'getenv "string-environment-variable-name?" s)) (let ([v (environment-variables-ref (current-environment-variables) (string->bytes/locale s (char->integer #\?)))]) (and v (bytes->string/locale v #\?)))) (define (putenv s t) (unless (string-no-nuls? s) (raise-argument-error 'putenv "string-environment-variable-name?" 0 s t)) (unless (string-no-nuls? t) (raise-argument-error 'putenv "string-no-nuls?" 1 s t)) (and (environment-variables-set! (current-environment-variables) (string->bytes/locale s (char->integer #\?)) (string->bytes/locale t (char->integer #\?)) (lambda () #f)) #t)) ;; ------------------------------------------------------------------------- (#%provide define-syntax-rule rationalize path-string? path-replace-suffix path-add-suffix path-replace-extension path-add-extension normal-case-path reroot-path read-eval-print-loop load/cd load-relative load-relative-extension path-list-string->path-list find-executable-path guard-evt channel-get channel-try-get channel-put port? writeln displayln println bytes-environment-variable-name? string-environment-variable-name? getenv putenv call-with-default-reading-parameterization From ' # % kernel , but re - exported for compatibility : collection-path collection-file-path))
null
https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/collects/racket/private/misc.rkt
racket
---------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- This prompt catches all error escapes, including from read and print. This prompt catches escapes during evaluation. Unlike the outer prompt, the handler prints the results. Abort to loop. (Calling `repl-loop' directory would not be a tail call.) ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- -------------------------------------------------------------------------
# % misc : file utilities , etc . - remaining functions (module misc '#%kernel (#%require "small-scheme.rkt" "define.rkt" "path.rkt" "old-path.rkt" "path-list.rkt" "executable-path.rkt" "reading-param.rkt" (for-syntax '#%kernel "qq-and-or.rkt" "stx.rkt" "stxcase-scheme.rkt" "stxcase.rkt")) (define-for-syntax (pattern-failure user-stx pattern) (let*-values ([(sexpr) (syntax->datum user-stx)] [(msg) (if (pair? sexpr) (format "use does not match pattern: ~.s" (cons (car sexpr) pattern)) (if (symbol? sexpr) (format "use does not match pattern: ~.s" (cons sexpr pattern)) (error 'internal-error "something bad happened")))]) (raise-syntax-error #f msg user-stx))) (define-syntax define-syntax-rule (lambda (stx) (let-values ([(err) (lambda (what . xs) (apply raise-syntax-error 'define-syntax-rule what stx xs))]) (syntax-case stx () [(dr (name . pattern) template) (identifier? #'name) (syntax/loc stx (define-syntax name (lambda (user-stx) (syntax-case** dr #t user-stx () free-identifier=? #f [(_ . pattern) (syntax-protect (syntax/loc user-stx template))] [_ (pattern-failure user-stx 'pattern)]))))] [(_ (name . ptrn) tmpl) (err "expected an identifier" #'name)] [(_ (name . ptrn)) (err "missing template")] [(_ (name . ptrn) tmpl etc . _) (err "too many forms" #'etc)] [(_ head . _) (err "invalid pattern" #'head)])))) (define rationalize (letrec ([check (lambda (x) (unless (real? x) (raise-argument-error 'rationalize "real?" x)))] [find-between (lambda (lo hi) (if (integer? lo) lo (let ([lo-int (floor lo)] [hi-int (floor hi)]) (if (< lo-int hi-int) (add1 lo-int) (+ lo-int (/ (find-between (/ (- hi lo-int)) (/ (- lo lo-int)))))))))] [do-find-between (lambda (lo hi) (cond [(negative? lo) (- (find-between (- hi) (- lo)))] [else (find-between lo hi)]))]) (lambda (x within) (check x) (check within) (let* ([delta (abs within)] [lo (- x delta)] [hi (+ x delta)]) (cond [(equal? x +nan.0) x] [(or (equal? x +inf.0) (equal? x -inf.0)) (if (equal? delta +inf.0) +nan.0 x)] [(equal? delta +inf.0) 0.0] [(not (= x x)) +nan.0] [(<= lo 0 hi) (if (exact? x) 0 0.0)] [(or (inexact? lo) (inexact? hi)) (exact->inexact (do-find-between (inexact->exact lo) (inexact->exact hi)))] [else (do-find-between lo hi)]))))) (define (read-eval-print-loop) (let repl-loop () (call-with-continuation-prompt (lambda () (let ([v ((current-prompt-read))]) (unless (eof-object? v) (call-with-values (lambda () (call-with-continuation-prompt (lambda () (let ([w (cons '#%top-interaction v)]) ((current-eval) (if (syntax? v) (namespace-syntax-introduce (datum->syntax #f w v)) w)))))) (lambda results (for-each (current-print) results))) (abort-current-continuation (default-continuation-prompt-tag))))) (default-continuation-prompt-tag) (lambda args (repl-loop))))) (define load/cd (lambda (n) (unless (path-string? n) (raise-argument-error 'load/cd "path-string?" n)) (let-values ([(base name dir?) (split-path n)]) (if dir? (raise (exn:fail:filesystem (string->immutable-string (format "load/cd: cannot open a directory: ~s" n)) (current-continuation-marks))) (if (not (path? base)) (load n) (begin (if (not (directory-exists? base)) (raise (exn:fail:filesystem (string->immutable-string (format "load/cd: directory of ~s does not exist (current directory is ~s)" n (current-directory))) (current-continuation-marks))) (void)) (let ([orig (current-directory)]) (dynamic-wind (lambda () (current-directory base)) (lambda () (load name)) (lambda () (current-directory orig)))))))))) (define (-load load name path) (unless (path-string? path) (raise-argument-error name "path-string?" path)) (if (complete-path? path) (load path) (let ([dir (current-load-relative-directory)]) (load (if dir (path->complete-path path dir) path))))) (define (load-relative path) (-load load 'load-relative path)) (define (load-relative-extension path) (-load load-extension 'load-relative-extension path)) (define-values (struct:guard make-guard guard? guard-ref guard-set!) (make-struct-type 'evt #f 1 0 #f (list (cons prop:evt 0)) (current-inspector) #f '(0))) (define (guard-evt proc) (unless (and (procedure? proc) (procedure-arity-includes? proc 0)) (raise-argument-error 'guard-evt "(any/c . -> . evt?)" proc)) (make-guard (lambda (self) (proc)))) (define (channel-get ch) (unless (channel? ch) (raise-argument-error 'channel-get "channel?" ch)) (sync ch)) (define (channel-try-get ch) (unless (channel? ch) (raise-argument-error 'channel-try-get "channel?" ch)) (sync/timeout 0 ch)) (define (channel-put ch val) (unless (channel? ch) (raise-argument-error 'channel-put "channel?" ch)) (and (sync (channel-put-evt ch val)) (void))) (define (port? x) (or (input-port? x) (output-port? x))) (define writeln (case-lambda [(v) (writeln v (current-output-port))] [(v p) (unless (output-port? p) (raise-argument-error 'writeln "output-port?" 1 v p)) (write v p) (newline p)])) (define displayln (case-lambda [(v) (displayln v (current-output-port))] [(v p) (unless (output-port? p) (raise-argument-error 'displayln "output-port?" 1 v p)) (display v p) (newline p)])) (define println (case-lambda [(v) (println v (current-output-port) 0)] [(v p) (println v p 0)] [(v p d) (unless (output-port? p) (raise-argument-error 'println "output-port?" 1 v p d)) (unless (and (number? d) (or (= 0 d) (= d 1))) (raise-argument-error 'println "(or/c 0 1)" 2 v p d)) (print v p d) (newline p)])) (define (string-no-nuls? s) (and (string? s) (not (regexp-match? #rx"\0" s)))) (define (bytes-environment-variable-name? s) (and (bytes? s) (if (eq? 'windows (system-type)) (regexp-match? #rx#"^[^\0=]+$" s) (regexp-match? #rx#"^[^\0=]*$" s)))) (define (string-environment-variable-name? s) (and (string? s) (bytes-environment-variable-name? (string->bytes/locale s (char->integer #\?))))) (define (getenv s) (unless (string-environment-variable-name? s) (raise-argument-error 'getenv "string-environment-variable-name?" s)) (let ([v (environment-variables-ref (current-environment-variables) (string->bytes/locale s (char->integer #\?)))]) (and v (bytes->string/locale v #\?)))) (define (putenv s t) (unless (string-no-nuls? s) (raise-argument-error 'putenv "string-environment-variable-name?" 0 s t)) (unless (string-no-nuls? t) (raise-argument-error 'putenv "string-no-nuls?" 1 s t)) (and (environment-variables-set! (current-environment-variables) (string->bytes/locale s (char->integer #\?)) (string->bytes/locale t (char->integer #\?)) (lambda () #f)) #t)) (#%provide define-syntax-rule rationalize path-string? path-replace-suffix path-add-suffix path-replace-extension path-add-extension normal-case-path reroot-path read-eval-print-loop load/cd load-relative load-relative-extension path-list-string->path-list find-executable-path guard-evt channel-get channel-try-get channel-put port? writeln displayln println bytes-environment-variable-name? string-environment-variable-name? getenv putenv call-with-default-reading-parameterization From ' # % kernel , but re - exported for compatibility : collection-path collection-file-path))
2f58c92d5c2f2f0c7a1b26d65ad055333338effb3f0efb8a16a0f6362a5d234e
antitypical/Surface
Surface.hs
# LANGUAGE FlexibleInstances , FlexibleContexts # module Surface ( module Surface', lambda, Surface.pi, (-->), apply, checkHasFunctionType, checkIsFunctionType, checkIsType, ) where import Prelude hiding (pi) import Data.Binding as Surface' import Data.Expression as Surface' import Data.Name as Surface' import Data.Name.Internal import Data.Term as Surface' import Data.Term.Types as Surface' import Data.Typing as Surface' import Data.Unification as Surface' import Control.Applicative import qualified Data.Set as Set infixr `lambda` -- | Construct a lambda from a type and a function from an argument variable to the resulting term. The variable will be picked automatically. The parameter type will be checked against `Type`, but there are no constraints on the type of the result. lambda :: Term Expression -> (Term Expression -> Term Expression) -> Term Expression lambda t f = checkedExpression checkType $ Lambda t body where body = abstract f checkType expected context = case out expected of Binding (Expression (Lambda from to)) -> checkTypeAgainst from to context Type _ -> checkTypeAgainst _type' _type' context _ -> checkTypeAgainst implicit implicit context >>= expectUnifiable expected checkTypeAgainst from to context = do _ <- checkIsType t context _ <- expectUnifiable from t bodyType <- inferTypeOf body (extendContext t context body) _ <- expectUnifiable to bodyType return $ case shadowing body bodyType of Just name -> t `pi` \ v -> substitute name v bodyType _ -> t --> bodyType infixr `pi` -- | Construct a pi type from a type and a function from an argument variable to the resulting type. The variable will be picked automatically. The parameter type will be checked against `Type`, as will the substitution of the parameter type into the body. pi :: Term Expression -> (Term Expression -> Term Expression) -> Term Expression pi t f = checkedExpression checkType $ Lambda t body where body = abstract f checkType expected context = case out expected of Binding (Expression (Lambda from to)) -> checkTypeAgainst from to context Type _ -> checkTypeAgainst _type' _type' context _ -> checkTypeAgainst implicit implicit context >>= expectUnifiable expected checkTypeAgainst from to context = do _ <- checkIsType t context _ <- expectUnifiable from t bodyType <- checkIsType body (extendContext t context body) _ <- expectUnifiable to bodyType return $ case shadowing body bodyType of Just name -> t `pi` \ v -> substitute name v bodyType _ -> t --> bodyType infixr --> | Construct a non - dependent function type between two types . Both operands will be checked against ` Type ` . (-->) :: Term Expression -> Term Expression -> Term Expression a --> b = checkedExpression (checkInferred inferType) $ Lambda a b where inferType context = do a' <- checkIsType a context b' <- checkIsType b context return $ a' --> b' | Construct the application of one term to another . The first argument will be checked as a function type , and the second will be checked against that type ’s domain . The resulting type will be the substitution of the domain type into the body . apply :: Term Expression -> Term Expression -> Term Expression apply a b = checkedExpression (checkInferred inferType) $ Application a b where inferType context = do (type', body) <- checkHasFunctionType a context _ <- typeOf b type' context return $ applySubstitution type' body checkHasFunctionType :: Term Expression -> Context (Term Expression) -> Result (Term Expression, Term Expression) checkHasFunctionType term context = inferTypeOf term context >>= checkIsFunctionType checkIsFunctionType :: Term Expression -> Result (Term Expression, Term Expression) checkIsFunctionType type' = case out type' of Binding (Expression (Lambda type' body)) -> return (type', body) _ -> Left "Expected function type." instance Monoid a => Alternative (Either a) where empty = Left mempty Left a <|> Left b = Left $ a `mappend` b Right a <|> _ = Right a _ <|> Right b = Right b checkIsType :: Term Expression -> Inferer (Term Expression) checkIsType term context = typeOf term _type' context <|> typeOf term (_type' --> _type') context instance Show (Term Expression) where show = fst . para (\ b -> case b of Binding (Variable n) -> (show n, maxBound) Binding (Abstraction _ (_, body)) -> body Type 0 -> ("Type", maxBound) Type n -> ("Type" ++ showNumeral "₀₁₂₃₄₅₆₇₈₉" n, maxBound) Binding (Expression (Application (_, a) (_, b))) -> (wrap 4 (<=) a ++ " " ++ wrap 4 (<) b, 4) Binding (Expression (Lambda (_, type') (Term _ _ (Binding (Abstraction name term)), body))) | Set.member name (freeVariables term) -> ("λ " ++ show name ++ " : " ++ wrap 3 (<) type' ++ " . " ++ wrap 3 (<=) body, 3) Binding (Expression (Lambda (_, type') (Term _ _ (Binding (Abstraction _ _)), body))) -> ("λ _ : " ++ wrap 3 (<) type' ++ " . " ++ wrap 3 (<=) body, 3) Binding (Expression (Lambda (_, type') (_, body))) -> (wrap 3 (<) type' ++ " → " ++ wrap 3 (<=) body, 3) Implicit -> ("_", maxBound) Annotation (_, term) (_, type') -> (wrap 3 (<=) term ++ " : " ++ wrap 3 (<) type', 3) :: (String, Int)) where wrap i op (s, j) | i `op` j = s wrap _ _ (s, _) = "(" ++ s ++ ")"
null
https://raw.githubusercontent.com/antitypical/Surface/9f36a39da8b93ff6f5bdf00af402bcc536f6e382/src/Surface.hs
haskell
>), | Construct a lambda from a type and a function from an argument variable to the resulting term. The variable will be picked automatically. The parameter type will be checked against `Type`, but there are no constraints on the type of the result. > bodyType | Construct a pi type from a type and a function from an argument variable to the resulting type. The variable will be picked automatically. The parameter type will be checked against `Type`, as will the substitution of the parameter type into the body. > bodyType > >) :: Term Expression -> Term Expression -> Term Expression > b = checkedExpression (checkInferred inferType) $ Lambda a b > b' > _type') context
# LANGUAGE FlexibleInstances , FlexibleContexts # module Surface ( module Surface', lambda, Surface.pi, apply, checkHasFunctionType, checkIsFunctionType, checkIsType, ) where import Prelude hiding (pi) import Data.Binding as Surface' import Data.Expression as Surface' import Data.Name as Surface' import Data.Name.Internal import Data.Term as Surface' import Data.Term.Types as Surface' import Data.Typing as Surface' import Data.Unification as Surface' import Control.Applicative import qualified Data.Set as Set infixr `lambda` lambda :: Term Expression -> (Term Expression -> Term Expression) -> Term Expression lambda t f = checkedExpression checkType $ Lambda t body where body = abstract f checkType expected context = case out expected of Binding (Expression (Lambda from to)) -> checkTypeAgainst from to context Type _ -> checkTypeAgainst _type' _type' context _ -> checkTypeAgainst implicit implicit context >>= expectUnifiable expected checkTypeAgainst from to context = do _ <- checkIsType t context _ <- expectUnifiable from t bodyType <- inferTypeOf body (extendContext t context body) _ <- expectUnifiable to bodyType return $ case shadowing body bodyType of Just name -> t `pi` \ v -> substitute name v bodyType infixr `pi` pi :: Term Expression -> (Term Expression -> Term Expression) -> Term Expression pi t f = checkedExpression checkType $ Lambda t body where body = abstract f checkType expected context = case out expected of Binding (Expression (Lambda from to)) -> checkTypeAgainst from to context Type _ -> checkTypeAgainst _type' _type' context _ -> checkTypeAgainst implicit implicit context >>= expectUnifiable expected checkTypeAgainst from to context = do _ <- checkIsType t context _ <- expectUnifiable from t bodyType <- checkIsType body (extendContext t context body) _ <- expectUnifiable to bodyType return $ case shadowing body bodyType of Just name -> t `pi` \ v -> substitute name v bodyType | Construct a non - dependent function type between two types . Both operands will be checked against ` Type ` . where inferType context = do a' <- checkIsType a context b' <- checkIsType b context | Construct the application of one term to another . The first argument will be checked as a function type , and the second will be checked against that type ’s domain . The resulting type will be the substitution of the domain type into the body . apply :: Term Expression -> Term Expression -> Term Expression apply a b = checkedExpression (checkInferred inferType) $ Application a b where inferType context = do (type', body) <- checkHasFunctionType a context _ <- typeOf b type' context return $ applySubstitution type' body checkHasFunctionType :: Term Expression -> Context (Term Expression) -> Result (Term Expression, Term Expression) checkHasFunctionType term context = inferTypeOf term context >>= checkIsFunctionType checkIsFunctionType :: Term Expression -> Result (Term Expression, Term Expression) checkIsFunctionType type' = case out type' of Binding (Expression (Lambda type' body)) -> return (type', body) _ -> Left "Expected function type." instance Monoid a => Alternative (Either a) where empty = Left mempty Left a <|> Left b = Left $ a `mappend` b Right a <|> _ = Right a _ <|> Right b = Right b checkIsType :: Term Expression -> Inferer (Term Expression) instance Show (Term Expression) where show = fst . para (\ b -> case b of Binding (Variable n) -> (show n, maxBound) Binding (Abstraction _ (_, body)) -> body Type 0 -> ("Type", maxBound) Type n -> ("Type" ++ showNumeral "₀₁₂₃₄₅₆₇₈₉" n, maxBound) Binding (Expression (Application (_, a) (_, b))) -> (wrap 4 (<=) a ++ " " ++ wrap 4 (<) b, 4) Binding (Expression (Lambda (_, type') (Term _ _ (Binding (Abstraction name term)), body))) | Set.member name (freeVariables term) -> ("λ " ++ show name ++ " : " ++ wrap 3 (<) type' ++ " . " ++ wrap 3 (<=) body, 3) Binding (Expression (Lambda (_, type') (Term _ _ (Binding (Abstraction _ _)), body))) -> ("λ _ : " ++ wrap 3 (<) type' ++ " . " ++ wrap 3 (<=) body, 3) Binding (Expression (Lambda (_, type') (_, body))) -> (wrap 3 (<) type' ++ " → " ++ wrap 3 (<=) body, 3) Implicit -> ("_", maxBound) Annotation (_, term) (_, type') -> (wrap 3 (<=) term ++ " : " ++ wrap 3 (<) type', 3) :: (String, Int)) where wrap i op (s, j) | i `op` j = s wrap _ _ (s, _) = "(" ++ s ++ ")"
8d71c0893afbbc4cdd55406ac32edfbe2dccea675b939a0dc494c0029bb82667
caiorss/Functional-Programming
BookStore2.hs
type CardHolder = String type CardNumber = String type Address = [String] type CustomerID = Int data BillingInfo = CreditCard CardNumber CardHolder Address | CashOnDelivery | Invoice CustomerID deriving (Show)
null
https://raw.githubusercontent.com/caiorss/Functional-Programming/ef3526898e3014e9c99bf495033ff36a4530503d/haskell/rwh/ch03/BookStore2.hs
haskell
type CardHolder = String type CardNumber = String type Address = [String] type CustomerID = Int data BillingInfo = CreditCard CardNumber CardHolder Address | CashOnDelivery | Invoice CustomerID deriving (Show)
fa99f5af1a4afbf1c4c0acff624795f07efb2fb2567006bed76ae7bdbdae587e
may-liu/qtalk
http_set_user_profile.erl
%% Feel free to use, reuse and abuse the code in this file. -module(http_set_user_profile). -export([init/3]). -export([handle/2]). -export([terminate/3]). -include("logger.hrl"). -include("ejb_http_server.hrl"). init(_Transport, Req, []) -> {ok, Req, undefined}. handle(Req, State) -> {Method, _} = cowboy_req:method(Req), catch ejb_monitor:monitor_count(<<"http_set_user_profile">>,1), case Method of <<"GET">> -> {Host,_ } = cowboy_req:host(Req), {ok, Req2 } = get_echo(Method,Host,Req), {ok, Req2, State}; <<"POST">> -> HasBody = cowboy_req:has_body(Req), {ok, Req2} = post_echo(Method, HasBody, Req), {ok, Req2, State}; _ -> {ok,Req2} = echo(undefined, Req), {ok, Req2, State} end. get_echo(<<"GET">>,_,Req) -> cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>} ], <<"No GET method">>, Req). post_echo(<<"POST">>, true, Req) -> {ok, Body, _} = cowboy_req:body(Req), {Host,_ } = cowboy_req:host(Req), {User,_} = cowboy_req:qs_val(<<"u">>, Req), case rfc4627:decode(Body) of {ok,{obj,Args},[]} -> Rslt = case http_utils:verify_user_key(Req) of true -> case proplists:get_value("user",Args) of User -> http_utils:gen_result(true, <<"0">>,<<"">>,set_user_profile(Args,User)); _ -> http_utils:gen_result(false, <<"2">>,<<"not allow to set other profile">>,<<"">>) end; false -> http_utils:gen_result(false, <<"1">>, <<"Not found Mac_Key">>,<<"">>) end, cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>}], Rslt, Req); _ -> cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>}], <<"Josn parse error">>, Req) end; post_echo(<<"POST">>, false, Req) -> cowboy_req:reply(400, [], <<"Missing Post body.">>, Req); post_echo(_, _, Req) -> cowboy_req:reply(405, Req). echo(undefined, Req) -> cowboy_req:reply(400, [], <<"Missing parameter.">>, Req); echo(Echo, Req) -> cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>} ], Echo, Req). terminate(_Reason, _Req, _State) -> ok. set_user_profile(Args,User)-> Mood = proplists:get_value("mood",Args), case catch ejb_odbc_query:update_user_profile(User,Mood) of {updated, 1} -> case ejb_odbc_query:get_profile_by_user(User) of {selected,[<<"profile_version">>],SRes} when is_list(SRes) -> [[V]] = SRes, ets:insert(user_profile,#user_profile{user = User,version = V,mood = Mood}), {obj,[{"user",User},{"version",V}]}; _ -> {obj,[{"user",User},{"version",<<"-1">>}]} end; _ -> case catch ejb_odbc_query:insert_user_profile(User,<<"2">>,Mood) of {updated, 1} -> ets:insert(user_profile,#user_profile{user = User,version = <<"2">>,mood = Mood}), {obj,[{"user",User},{"version",<<"2">>}]}; _ -> {obj,[{"user",User},{"version",<<"-1">>}]} end end.
null
https://raw.githubusercontent.com/may-liu/qtalk/f5431e5a7123975e9656e7ab239e674ce33713cd/qtalk_opensource/scripts/ejb_http_server/src/http_set_user_profile.erl
erlang
Feel free to use, reuse and abuse the code in this file.
-module(http_set_user_profile). -export([init/3]). -export([handle/2]). -export([terminate/3]). -include("logger.hrl"). -include("ejb_http_server.hrl"). init(_Transport, Req, []) -> {ok, Req, undefined}. handle(Req, State) -> {Method, _} = cowboy_req:method(Req), catch ejb_monitor:monitor_count(<<"http_set_user_profile">>,1), case Method of <<"GET">> -> {Host,_ } = cowboy_req:host(Req), {ok, Req2 } = get_echo(Method,Host,Req), {ok, Req2, State}; <<"POST">> -> HasBody = cowboy_req:has_body(Req), {ok, Req2} = post_echo(Method, HasBody, Req), {ok, Req2, State}; _ -> {ok,Req2} = echo(undefined, Req), {ok, Req2, State} end. get_echo(<<"GET">>,_,Req) -> cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>} ], <<"No GET method">>, Req). post_echo(<<"POST">>, true, Req) -> {ok, Body, _} = cowboy_req:body(Req), {Host,_ } = cowboy_req:host(Req), {User,_} = cowboy_req:qs_val(<<"u">>, Req), case rfc4627:decode(Body) of {ok,{obj,Args},[]} -> Rslt = case http_utils:verify_user_key(Req) of true -> case proplists:get_value("user",Args) of User -> http_utils:gen_result(true, <<"0">>,<<"">>,set_user_profile(Args,User)); _ -> http_utils:gen_result(false, <<"2">>,<<"not allow to set other profile">>,<<"">>) end; false -> http_utils:gen_result(false, <<"1">>, <<"Not found Mac_Key">>,<<"">>) end, cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>}], Rslt, Req); _ -> cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>}], <<"Josn parse error">>, Req) end; post_echo(<<"POST">>, false, Req) -> cowboy_req:reply(400, [], <<"Missing Post body.">>, Req); post_echo(_, _, Req) -> cowboy_req:reply(405, Req). echo(undefined, Req) -> cowboy_req:reply(400, [], <<"Missing parameter.">>, Req); echo(Echo, Req) -> cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>} ], Echo, Req). terminate(_Reason, _Req, _State) -> ok. set_user_profile(Args,User)-> Mood = proplists:get_value("mood",Args), case catch ejb_odbc_query:update_user_profile(User,Mood) of {updated, 1} -> case ejb_odbc_query:get_profile_by_user(User) of {selected,[<<"profile_version">>],SRes} when is_list(SRes) -> [[V]] = SRes, ets:insert(user_profile,#user_profile{user = User,version = V,mood = Mood}), {obj,[{"user",User},{"version",V}]}; _ -> {obj,[{"user",User},{"version",<<"-1">>}]} end; _ -> case catch ejb_odbc_query:insert_user_profile(User,<<"2">>,Mood) of {updated, 1} -> ets:insert(user_profile,#user_profile{user = User,version = <<"2">>,mood = Mood}), {obj,[{"user",User},{"version",<<"2">>}]}; _ -> {obj,[{"user",User},{"version",<<"-1">>}]} end end.
0b187a8d3f1560fab1b1ae698a6f6673fd3d250ae0c7623928db88fd1c4268af
haroldcarr/learn-haskell-coq-ml-etc
S5Logging.hs
#!/usr/bin/env stack -- stack --resolver lts-8.12 script # OPTIONS_GHC -fno - warn - missing - signatures # # OPTIONS_GHC -fno - warn - type - defaults # {-# LANGUAGE OverloadedStrings #-} module S5Logging where import Control.Exception.Safe (onException) import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger.CallStack (logDebug, logError, logInfo, runStdoutLoggingT) import qualified Data.Text as T (pack) s5 = main main :: IO () main = runStdoutLoggingT $ do let fp = "/tmp/JUNK/S5Logging" logInfo $ T.pack $ "Writing to file: " ++ fp liftIO (writeFile fp "Hey there!") `onException` logError "Writing to file failed" logInfo $ T.pack $ "Reading from file: " ++ fp content <- liftIO (readFile fp) `onException` logError "Reading from file failed" logDebug $ T.pack $ "Content read: " ++ content
null
https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/course/2017-05-snoyman-applied-haskell-at-lambdaconf/S5Logging.hs
haskell
stack --resolver lts-8.12 script # LANGUAGE OverloadedStrings #
#!/usr/bin/env stack # OPTIONS_GHC -fno - warn - missing - signatures # # OPTIONS_GHC -fno - warn - type - defaults # module S5Logging where import Control.Exception.Safe (onException) import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger.CallStack (logDebug, logError, logInfo, runStdoutLoggingT) import qualified Data.Text as T (pack) s5 = main main :: IO () main = runStdoutLoggingT $ do let fp = "/tmp/JUNK/S5Logging" logInfo $ T.pack $ "Writing to file: " ++ fp liftIO (writeFile fp "Hey there!") `onException` logError "Writing to file failed" logInfo $ T.pack $ "Reading from file: " ++ fp content <- liftIO (readFile fp) `onException` logError "Reading from file failed" logDebug $ T.pack $ "Content read: " ++ content
99dd4e686ebb06f366c373cf1901f859a17925fe8f674055b5f37bb4a554167b
davexunit/guile-allegro5
time.scm
(define-module (allegro time) #:use-module (system foreign) #:use-module (rnrs bytevectors) #:use-module (ice-9 format) #:use-module (allegro utils) #:export (al-get-time al-create-timeout al-rest al-rest)) (define-wrapped-pointer-type <allegro-timeout> allegro-timeout? wrap-allegro-timeout unwrap-allegro-timeout (lambda (t port) (format port "#<allegro-timeout ~x>" (pointer-address (unwrap-allegro-timeout t))))) (define types-timeout (list uint64 uint64)) (define-foreign al-get-time double "al_get_time" '()) (define-foreign %al-init-timeout void "al_init_timeout" (list '* double)) (define-foreign al-rest void "al_rest" (list double)) (define (al-create-timeout seconds) (let* ((bv (make-bytevector (sizeof types-timeout))) (timeout (bytevector->pointer bv))) (%al-init-timeout timeout seconds) (wrap-allegro-timeout timeout)))
null
https://raw.githubusercontent.com/davexunit/guile-allegro5/614ecc978e034f7b7ba5bd23e27111c8fef81b56/allegro/time.scm
scheme
(define-module (allegro time) #:use-module (system foreign) #:use-module (rnrs bytevectors) #:use-module (ice-9 format) #:use-module (allegro utils) #:export (al-get-time al-create-timeout al-rest al-rest)) (define-wrapped-pointer-type <allegro-timeout> allegro-timeout? wrap-allegro-timeout unwrap-allegro-timeout (lambda (t port) (format port "#<allegro-timeout ~x>" (pointer-address (unwrap-allegro-timeout t))))) (define types-timeout (list uint64 uint64)) (define-foreign al-get-time double "al_get_time" '()) (define-foreign %al-init-timeout void "al_init_timeout" (list '* double)) (define-foreign al-rest void "al_rest" (list double)) (define (al-create-timeout seconds) (let* ((bv (make-bytevector (sizeof types-timeout))) (timeout (bytevector->pointer bv))) (%al-init-timeout timeout seconds) (wrap-allegro-timeout timeout)))
e65e91175f4a61cb4c375308b08a3008d853943b5a9e3a2400a0cde6c1247f28
shirok/Gauche
r7rs-aux.scm
;; ;; Additional R7RS tests that hasn't covered by other tests NB : Most R7RS - large libraries are tested via its srfi counterparts . ;; ;; This is called after ext/* are tested. ;; (use gauche.test) (test-start "r7rs-aux") (test-section "scheme.bytevector") ;; scheme.bytevector exports a few conflicting symbols, so we isolate it. (define-module bytevector-test (use gauche.test) (use scheme.bytevector) (test-module 'scheme.bytevector) (let1 lis '(big big-endian little little-endian arm-little-endian) (test* "endianness" lis (map (^x (eval `(endianness ,x) (current-module))) lis)) (test* "endianness" (test-error) (eval '(endianness wha) (current-module))) (test* "native-endianness" #t (boolean (memq (native-endianness) lis)))) (test* "bytevector-[su8]-ref/set!" '#u8(5 255 0 3 4 5) (rlet1 v (u8-list->bytevector '(0 1 2 3 4 5)) (bytevector-u8-set! v 0 (bytevector-u8-ref v 5)) (bytevector-s8-set! v 1 -1) (bytevector-s8-set! v 2 (+ (bytevector-s8-ref v 1) 1)))) (test* "bytevector->u8-list" '(0 255 1 254 2 253) (bytevector->u8-list '#u8(0 255 1 254 2 253))) ) (test-end)
null
https://raw.githubusercontent.com/shirok/Gauche/ecaf82f72e2e946f62d99ed8febe0df8960d20c4/test/r7rs-aux.scm
scheme
Additional R7RS tests that hasn't covered by other tests This is called after ext/* are tested. scheme.bytevector exports a few conflicting symbols, so we isolate it.
NB : Most R7RS - large libraries are tested via its srfi counterparts . (use gauche.test) (test-start "r7rs-aux") (test-section "scheme.bytevector") (define-module bytevector-test (use gauche.test) (use scheme.bytevector) (test-module 'scheme.bytevector) (let1 lis '(big big-endian little little-endian arm-little-endian) (test* "endianness" lis (map (^x (eval `(endianness ,x) (current-module))) lis)) (test* "endianness" (test-error) (eval '(endianness wha) (current-module))) (test* "native-endianness" #t (boolean (memq (native-endianness) lis)))) (test* "bytevector-[su8]-ref/set!" '#u8(5 255 0 3 4 5) (rlet1 v (u8-list->bytevector '(0 1 2 3 4 5)) (bytevector-u8-set! v 0 (bytevector-u8-ref v 5)) (bytevector-s8-set! v 1 -1) (bytevector-s8-set! v 2 (+ (bytevector-s8-ref v 1) 1)))) (test* "bytevector->u8-list" '(0 255 1 254 2 253) (bytevector->u8-list '#u8(0 255 1 254 2 253))) ) (test-end)
7732fcc1f51a8b8069eb832dcc4de697054c9c7eb043e6462c3585caf4c6cd7c
edicl/cl-who
specials.lisp
-*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - WHO ; Base : 10 -*- $ Header : /usr / local / cvsrep / cl - who / specials.lisp , v 1.6 2009/01/26 11:10:49 edi Exp $ Copyright ( c ) 2003 - 2009 , Dr. . All rights reserved . ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :cl-who) #+(or :clasp :sbcl) (defmacro defconstant (name value &optional doc) "Make sure VALUE is evaluated only once \(to appease SBCL & clasp)." `(cl:defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value) ,@(when doc (list doc)))) (defvar *prologue* "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"-strict.dtd\">" "This is the first line that'll be printed if the :PROLOGUE keyword argument is T") (defvar *escape-char-p* (lambda (char) (or (find char "<>&'\"") (> (char-code char) 127))) "Used by ESCAPE-STRING to test whether a character should be escaped.") (defvar *indent* nil "Whether to insert line breaks and indent. Also controls amount of indentation dynamically.") (defvar *html-mode* :xml ":SGML for \(SGML-)HTML, :XML \(default) for XHTML, :HTML5 for HTML5.") (defvar *empty-attribute-syntax* nil "Set this to t to enable attribute minimization (also called 'boolean attributes', or 'empty attribute syntax' according to the w3 html standard). In XHTML attribute minimization is forbidden, and all attributes must have a value. Thus in XHTML boolean attributes must be defined as <input disabled='disabled' />. In HTML5 boolean attributes can be defined as <input disabled>") (defvar *downcase-tokens-p* t "If NIL, a keyword symbol representing a tag or attribute name will not be automatically converted to lowercase. If T, the tag and attribute name will be converted to lowercase only if it is in the same case. This is useful when one needs to output case sensitive XML.") (defvar *attribute-quote-char* #\' "Quote character for attributes.") (defvar *empty-tag-end* " />" "End of an empty tag. Default is XML style.") (defvar *html-no-indent-tags* '(:pre :textarea) "The list of HTML tags that should disable indentation inside them. The initial value is a list containing only :PRE and :TEXTAREA.") (defvar *html-empty-tags* '(:area :atop :audioscope :base :basefont :br :choose :col :command :embed :frame :hr :img :input :isindex :keygen :left :limittext :link :meta :nextid :of :over :param :range :right :source :spacer :spot :tab :track :wbr) "The list of HTML tags that should be output as empty tags. See *HTML-EMPTY-TAG-AWARE-P*.") (defvar *html-empty-tag-aware-p* t "Set this to NIL to if you want to use CL-WHO as a strict XML generator. Otherwise, CL-WHO will only write empty tags listed in *HTML-EMPTY-TAGS* as <tag/> \(XHTML mode) or <tag> \(SGML mode and HTML5 mode). For all other tags, it will always generate <tag></tag>.") (defconstant +newline+ (make-string 1 :initial-element #\Newline) "Used for indentation.") (defconstant +spaces+ (make-string 2000 :initial-element #\Space :element-type 'base-char) "Used for indentation.")
null
https://raw.githubusercontent.com/edicl/cl-who/0d3826475133271ee8c590937136c1bc41b8cbe0/specials.lisp
lisp
Syntax : COMMON - LISP ; Package : CL - WHO ; Base : 10 -*- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
$ Header : /usr / local / cvsrep / cl - who / specials.lisp , v 1.6 2009/01/26 11:10:49 edi Exp $ Copyright ( c ) 2003 - 2009 , Dr. . All rights reserved . DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , (in-package :cl-who) #+(or :clasp :sbcl) (defmacro defconstant (name value &optional doc) "Make sure VALUE is evaluated only once \(to appease SBCL & clasp)." `(cl:defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value) ,@(when doc (list doc)))) (defvar *prologue* "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"-strict.dtd\">" "This is the first line that'll be printed if the :PROLOGUE keyword argument is T") (defvar *escape-char-p* (lambda (char) (or (find char "<>&'\"") (> (char-code char) 127))) "Used by ESCAPE-STRING to test whether a character should be escaped.") (defvar *indent* nil "Whether to insert line breaks and indent. Also controls amount of indentation dynamically.") (defvar *html-mode* :xml ":SGML for \(SGML-)HTML, :XML \(default) for XHTML, :HTML5 for HTML5.") (defvar *empty-attribute-syntax* nil "Set this to t to enable attribute minimization (also called 'boolean attributes', or 'empty attribute syntax' according to the w3 html standard). In XHTML attribute minimization is forbidden, and all attributes must have a value. Thus in XHTML boolean attributes must be defined as <input disabled='disabled' />. In HTML5 boolean attributes can be defined as <input disabled>") (defvar *downcase-tokens-p* t "If NIL, a keyword symbol representing a tag or attribute name will not be automatically converted to lowercase. If T, the tag and attribute name will be converted to lowercase only if it is in the same case. This is useful when one needs to output case sensitive XML.") (defvar *attribute-quote-char* #\' "Quote character for attributes.") (defvar *empty-tag-end* " />" "End of an empty tag. Default is XML style.") (defvar *html-no-indent-tags* '(:pre :textarea) "The list of HTML tags that should disable indentation inside them. The initial value is a list containing only :PRE and :TEXTAREA.") (defvar *html-empty-tags* '(:area :atop :audioscope :base :basefont :br :choose :col :command :embed :frame :hr :img :input :isindex :keygen :left :limittext :link :meta :nextid :of :over :param :range :right :source :spacer :spot :tab :track :wbr) "The list of HTML tags that should be output as empty tags. See *HTML-EMPTY-TAG-AWARE-P*.") (defvar *html-empty-tag-aware-p* t "Set this to NIL to if you want to use CL-WHO as a strict XML generator. Otherwise, CL-WHO will only write empty tags listed in *HTML-EMPTY-TAGS* as <tag/> \(XHTML mode) or <tag> \(SGML mode and HTML5 mode). For all other tags, it will always generate <tag></tag>.") (defconstant +newline+ (make-string 1 :initial-element #\Newline) "Used for indentation.") (defconstant +spaces+ (make-string 2000 :initial-element #\Space :element-type 'base-char) "Used for indentation.")
e49d71ab3b4112db3139a095fab9b2457279d92e3dcd89c369d459a424f25a99
sg2002/lilypond-cheatsheets
cheatsheets-fns.scm
(use-modules (srfi srfi-1)) (define (is-sharp? note) (let ((note-list (string->list note))) (if (and (> (length note-list) 1) (char=? (cadr note-list) #\i)) #t #f))) (define (tone-name note) (let ((note-list (string->list note))) (if (is-sharp? note) (string (car note-list) #\i #\s) (string (car note-list))))) (define (higher-notes note) (member (tone-name note) (list "c" "cis" "d" "dis" "e" "f" "fis" "g" "gis" "a" "ais" "b" "c"))) (define (next-note note) (cadr (higher-notes note))) (define (octave note) (let ((note-list (string->list note))) (car (string-split (list->string (list-tail note-list (if (is-sharp? note) 3 1))) #\\)))) (define (add-octave octave) (let ((octave-list (string->list octave))) (if (not (null? octave-list)) (if (char=? (car octave-list) #\,) (list->string (list-tail octave-list 1)) (list->string (append octave-list (list #\')))) "'"))) (define (next-octave note) (let ((note-list (string->list note))) (let ((octave (octave note))) (if (char=? (car note-list) #\b) (add-octave octave) octave)))) (define (add-step note) (string-append (next-note note) (next-octave note))) (define (calculate-octave-value octave) (let ((octave-list (string->list octave))) (fold (lambda (v result) (cond ((char=? v #\')(+ result 12)) ((char=? v #\,)(- result 12)))) 0 octave-list))) (define (calculate-note-value note) (+ (- 14 (length (higher-notes note))) (calculate-octave-value (octave note)))) (define (note-position note string-root-note frets) (let ((pos (-(calculate-note-value note) (calculate-note-value string-root-note)))) (cond ((> pos frets) #f) ((>= pos 0) pos) (else #f)))) (define (note-position-to-staff note pos) (string-append note "\\" (number->string pos))) (define (last-note last-string frets) (if (= frets 0) last-string (last-note (add-step last-string) (- frets 1)))) (define (count-notes first-note last-note counter) (if (string=? last-note first-note) (+ 1 counter) (count-notes (add-step first-note) last-note (+ 1 counter)))) (define (fill-notes staff note note-index tuning frets) (do ((s 0 (+ 1 s))) ((>= s (length tuning))) (let ((pos (note-position note (list-ref tuning s) frets))) (if pos (array-set! staff (note-position-to-staff note (- (length tuning) s)) note-index s)))) (if (string=? note (last-note (last tuning) frets)) staff (fill-notes staff (add-step note) (+ 1 note-index) tuning frets))) (define (get-empty-staff tuning frets) (make-array "r" (count-notes (first tuning) (last-note (last tuning) frets) 0) (length tuning))) (define (get-notes tuning frets) (array->list (fill-notes (get-empty-staff tuning frets) (car tuning) 0 tuning frets))) (define (generate-octave-number note) (- (string-count note #\') (string-count note #\,) 1)) (define (generate-rest) (make-music 'RestEvent 'duration (ly:make-duration 2 0 1))) (define (generate-pitch note) (ly:make-pitch (generate-octave-number (octave note)) (- 8 (length (filter (lambda (e) (if (= (string-length e) 1) #t #f)) (higher-notes (string (car (string->list note))))))) (if (is-sharp? note) 1/2 0))) (define (generate-note note) (if (string=? note "r") (generate-rest) (make-music 'NoteEvent 'articulations (let ((strnum (string-split note #\\))) (if (= (length strnum) 2) (list (make-music 'StringNumberEvent 'string-number (string->number (cadr strnum)))))) 'duration (ly:make-duration 2 0 1) 'pitch (generate-pitch note)))) (define (generate-chord notes) (make-music 'EventChord 'elements (map generate-note notes))) (define (generate-single-note notes) (generate-note (car (string-split (find (lambda (x) (not (string=? x "r"))) notes) #\\)))) (define (generate-staff-music chords) (make-music 'SequentialMusic 'elements (map generate-single-note chords))) (define (generate-tab-staff chords tuning) (make-music 'ContextSpeccedMusic 'create-new #t 'property-operations '() 'context-type 'TabStaff 'element (make-music 'SequentialMusic 'elements (list (make-music 'ContextSpeccedMusic 'context-type 'TabStaff 'element (make-music 'PropertySet 'value (map generate-pitch (reverse tuning)) 'symbol 'stringTunings)) (make-music 'SequentialMusic 'elements (map generate-chord chords))))))
null
https://raw.githubusercontent.com/sg2002/lilypond-cheatsheets/6cb4d02f0248616241e628cd191c190b217d580f/cheatsheets-fns.scm
scheme
(use-modules (srfi srfi-1)) (define (is-sharp? note) (let ((note-list (string->list note))) (if (and (> (length note-list) 1) (char=? (cadr note-list) #\i)) #t #f))) (define (tone-name note) (let ((note-list (string->list note))) (if (is-sharp? note) (string (car note-list) #\i #\s) (string (car note-list))))) (define (higher-notes note) (member (tone-name note) (list "c" "cis" "d" "dis" "e" "f" "fis" "g" "gis" "a" "ais" "b" "c"))) (define (next-note note) (cadr (higher-notes note))) (define (octave note) (let ((note-list (string->list note))) (car (string-split (list->string (list-tail note-list (if (is-sharp? note) 3 1))) #\\)))) (define (add-octave octave) (let ((octave-list (string->list octave))) (if (not (null? octave-list)) (if (char=? (car octave-list) #\,) (list->string (list-tail octave-list 1)) (list->string (append octave-list (list #\')))) "'"))) (define (next-octave note) (let ((note-list (string->list note))) (let ((octave (octave note))) (if (char=? (car note-list) #\b) (add-octave octave) octave)))) (define (add-step note) (string-append (next-note note) (next-octave note))) (define (calculate-octave-value octave) (let ((octave-list (string->list octave))) (fold (lambda (v result) (cond ((char=? v #\')(+ result 12)) ((char=? v #\,)(- result 12)))) 0 octave-list))) (define (calculate-note-value note) (+ (- 14 (length (higher-notes note))) (calculate-octave-value (octave note)))) (define (note-position note string-root-note frets) (let ((pos (-(calculate-note-value note) (calculate-note-value string-root-note)))) (cond ((> pos frets) #f) ((>= pos 0) pos) (else #f)))) (define (note-position-to-staff note pos) (string-append note "\\" (number->string pos))) (define (last-note last-string frets) (if (= frets 0) last-string (last-note (add-step last-string) (- frets 1)))) (define (count-notes first-note last-note counter) (if (string=? last-note first-note) (+ 1 counter) (count-notes (add-step first-note) last-note (+ 1 counter)))) (define (fill-notes staff note note-index tuning frets) (do ((s 0 (+ 1 s))) ((>= s (length tuning))) (let ((pos (note-position note (list-ref tuning s) frets))) (if pos (array-set! staff (note-position-to-staff note (- (length tuning) s)) note-index s)))) (if (string=? note (last-note (last tuning) frets)) staff (fill-notes staff (add-step note) (+ 1 note-index) tuning frets))) (define (get-empty-staff tuning frets) (make-array "r" (count-notes (first tuning) (last-note (last tuning) frets) 0) (length tuning))) (define (get-notes tuning frets) (array->list (fill-notes (get-empty-staff tuning frets) (car tuning) 0 tuning frets))) (define (generate-octave-number note) (- (string-count note #\') (string-count note #\,) 1)) (define (generate-rest) (make-music 'RestEvent 'duration (ly:make-duration 2 0 1))) (define (generate-pitch note) (ly:make-pitch (generate-octave-number (octave note)) (- 8 (length (filter (lambda (e) (if (= (string-length e) 1) #t #f)) (higher-notes (string (car (string->list note))))))) (if (is-sharp? note) 1/2 0))) (define (generate-note note) (if (string=? note "r") (generate-rest) (make-music 'NoteEvent 'articulations (let ((strnum (string-split note #\\))) (if (= (length strnum) 2) (list (make-music 'StringNumberEvent 'string-number (string->number (cadr strnum)))))) 'duration (ly:make-duration 2 0 1) 'pitch (generate-pitch note)))) (define (generate-chord notes) (make-music 'EventChord 'elements (map generate-note notes))) (define (generate-single-note notes) (generate-note (car (string-split (find (lambda (x) (not (string=? x "r"))) notes) #\\)))) (define (generate-staff-music chords) (make-music 'SequentialMusic 'elements (map generate-single-note chords))) (define (generate-tab-staff chords tuning) (make-music 'ContextSpeccedMusic 'create-new #t 'property-operations '() 'context-type 'TabStaff 'element (make-music 'SequentialMusic 'elements (list (make-music 'ContextSpeccedMusic 'context-type 'TabStaff 'element (make-music 'PropertySet 'value (map generate-pitch (reverse tuning)) 'symbol 'stringTunings)) (make-music 'SequentialMusic 'elements (map generate-chord chords))))))
d3b365e07fdfef0c6133b15e73634e2e9b73f4f669c659e630b0b1be4085185f
tov/dssl2
test.rkt
#lang dssl2 test 'a test': assert 1 + 1 == 2 assert 2 + 2 == 4
null
https://raw.githubusercontent.com/tov/dssl2/105d18069465781bd9b87466f8336d5ce9e9a0f3/test/dssl2/test.rkt
racket
#lang dssl2 test 'a test': assert 1 + 1 == 2 assert 2 + 2 == 4
b44d05eb1160fb1855c9c16998a3a4d836f053e35f4f79b262dde6ca6e12b12d
nomnom-insights/nomnom.lockjaw
protocol.clj
(ns lockjaw.protocol) (defprotocol Lockjaw (acquire! [this] "Tries to get a lock for given component ID") (acquire-by-name! [this lock-name] "Converts passed name to ID and tries to aquire a lock for it") (acquired? [this] "Checks if lock was already acquired") (acquired-by-name? [this lock-name] "Converts passed name to ID and checks if lock was already acquired") (release! [this] "Rleases the component lock") (release-by-name! [this lock-name] "Converts passed name to ID and releases it") (release-all! [this] "Releases all acquired locks")) (defmacro with-lock "Run the code if a lock is obtained" [a-lock & body] `(if (acquire! ~a-lock) (do ~@body) :lockjaw.operation/no-lock)) (defmacro with-lock! "Like *with-lock* but release it after use" [a-lock & body] `(try (if (acquire! ~a-lock) (do ~@body) :lockjaw.operation/no-lock) (finally (release! ~a-lock)))) (defmacro with-named-lock "Run the code if a lock with the passed name is obtained" [a-lock lock-name & body] `(if (acquire-by-name! ~a-lock ~lock-name) (do ~@body) :lockjaw.operation/no-lock)) (defmacro with-named-lock! "Like *with-lock* but release it after use" [a-lock lock-name & body] `(try (if (acquire-by-name! ~a-lock ~lock-name) (do ~@body) :lockjaw.operation/no-lock) (finally (release-by-name! ~a-lock ~lock-name))))
null
https://raw.githubusercontent.com/nomnom-insights/nomnom.lockjaw/8d568d1ec36054ca25e798613ccd3e1d229c94cf/src/lockjaw/protocol.clj
clojure
(ns lockjaw.protocol) (defprotocol Lockjaw (acquire! [this] "Tries to get a lock for given component ID") (acquire-by-name! [this lock-name] "Converts passed name to ID and tries to aquire a lock for it") (acquired? [this] "Checks if lock was already acquired") (acquired-by-name? [this lock-name] "Converts passed name to ID and checks if lock was already acquired") (release! [this] "Rleases the component lock") (release-by-name! [this lock-name] "Converts passed name to ID and releases it") (release-all! [this] "Releases all acquired locks")) (defmacro with-lock "Run the code if a lock is obtained" [a-lock & body] `(if (acquire! ~a-lock) (do ~@body) :lockjaw.operation/no-lock)) (defmacro with-lock! "Like *with-lock* but release it after use" [a-lock & body] `(try (if (acquire! ~a-lock) (do ~@body) :lockjaw.operation/no-lock) (finally (release! ~a-lock)))) (defmacro with-named-lock "Run the code if a lock with the passed name is obtained" [a-lock lock-name & body] `(if (acquire-by-name! ~a-lock ~lock-name) (do ~@body) :lockjaw.operation/no-lock)) (defmacro with-named-lock! "Like *with-lock* but release it after use" [a-lock lock-name & body] `(try (if (acquire-by-name! ~a-lock ~lock-name) (do ~@body) :lockjaw.operation/no-lock) (finally (release-by-name! ~a-lock ~lock-name))))
2011983732b6249046211da717b63d2b2be2befd2e2bd2acde37484cc9a48ac4
xvw/planet
picture.ml
open Bedrock open Util open Paperwork type t = { name : string ; description : string ; date : Timetable.Day.t ; tools : string list ; tags : string list ; place : (string * string) option ; image : string ; thumbnail : string option } let new_picture name description date tools tags place image thumbnail = { name; description; date; tools; tags; place; image; thumbnail } ;; let qexp_place = function | None -> [] | Some (country, city) -> let open Qexp in [ node [ tag "place"; node [ string country; string city ] ] ] ;; let to_qexp picture = let open Qexp in node ([ kv "name" picture.name ; kv "description" picture.description ; kv "date" $ Timetable.Day.to_string picture.date ; node [ tag "tools"; node $ List.map string picture.tools ] ; node [ tag "tags"; node $ List.map string picture.tags ] ] @ qexp_place picture.place @ [ kv "image" picture.image ] @ Kv.option picture.thumbnail "thumbnail" id) ;; module Fetch = Table.Fetch module Mapper = Table.Mapper let from_qexp expr = match Table.configuration expr with | Ok config -> let open Validation.Infix in new_picture <$> Fetch.string config "name" <*> Fetch.string config "description" <*> Fetch.day config "date" <*> Fetch.list_refutable Mapper.string config "tools" <*> Fetch.list_refutable Mapper.string config "tags" <*> Fetch.(option $ map Mapper.(couple string string) $ config $ "place") <*> Fetch.string config "image" <*> Fetch.(option $ string $ config $ "thumbnail") | Error _ as e -> Validation.from_result e ;; let pp ppf picture = let qexp = to_qexp picture in Format.fprintf ppf "%a" Qexp.pp qexp ;; let eq left right = String.equal left.name right.name && String.equal left.description right.description && Timetable.Day.eq left.date right.date && List.eq String.equal left.tools right.tools && List.eq String.equal left.tags right.tags && Option.eq (fun (a, b) (x, y) -> String.equal a x && String.equal b y) left.place right.place && String.equal left.image right.image && Option.eq String.equal left.thumbnail right.thumbnail ;;
null
https://raw.githubusercontent.com/xvw/planet/c2a77ea66f61cc76df78b9c2ad06d114795f3053/src/shapes/picture.ml
ocaml
open Bedrock open Util open Paperwork type t = { name : string ; description : string ; date : Timetable.Day.t ; tools : string list ; tags : string list ; place : (string * string) option ; image : string ; thumbnail : string option } let new_picture name description date tools tags place image thumbnail = { name; description; date; tools; tags; place; image; thumbnail } ;; let qexp_place = function | None -> [] | Some (country, city) -> let open Qexp in [ node [ tag "place"; node [ string country; string city ] ] ] ;; let to_qexp picture = let open Qexp in node ([ kv "name" picture.name ; kv "description" picture.description ; kv "date" $ Timetable.Day.to_string picture.date ; node [ tag "tools"; node $ List.map string picture.tools ] ; node [ tag "tags"; node $ List.map string picture.tags ] ] @ qexp_place picture.place @ [ kv "image" picture.image ] @ Kv.option picture.thumbnail "thumbnail" id) ;; module Fetch = Table.Fetch module Mapper = Table.Mapper let from_qexp expr = match Table.configuration expr with | Ok config -> let open Validation.Infix in new_picture <$> Fetch.string config "name" <*> Fetch.string config "description" <*> Fetch.day config "date" <*> Fetch.list_refutable Mapper.string config "tools" <*> Fetch.list_refutable Mapper.string config "tags" <*> Fetch.(option $ map Mapper.(couple string string) $ config $ "place") <*> Fetch.string config "image" <*> Fetch.(option $ string $ config $ "thumbnail") | Error _ as e -> Validation.from_result e ;; let pp ppf picture = let qexp = to_qexp picture in Format.fprintf ppf "%a" Qexp.pp qexp ;; let eq left right = String.equal left.name right.name && String.equal left.description right.description && Timetable.Day.eq left.date right.date && List.eq String.equal left.tools right.tools && List.eq String.equal left.tags right.tags && Option.eq (fun (a, b) (x, y) -> String.equal a x && String.equal b y) left.place right.place && String.equal left.image right.image && Option.eq String.equal left.thumbnail right.thumbnail ;;
482d14acb8a43398a53e916ef947e1bb92ca6c69e99205723ad37adbea908bd4
theodormoroianu/SecondYearCourses
varList.hs
- Limbajul si Interpretorul type M = [] showM :: Show a => M a -> String showM = foldMap (\a -> show a ++ " ") type Name = String data Term = Var Name | Con Integer | Term :+: Term | Lam Name Term | App Term Term | Fail | Amb Term Term deriving (Show) pgm :: Term pgm = App (Lam "y" (App (App (Lam "f" (Lam "y" (App (Var "f") (Var "y")) ) ) (Lam "x" (Var "x" :+: Var "y") ) ) (Amb (Con 3) (Con 1)) ) ) (Con 4) data Value = Num Integer | Fun (Value -> M Value) instance Show Value where show (Num x) = show x show (Fun _) = "<function>" type Environment = [(Name, Value)] interp :: Term -> Environment -> M Value interp (Var name) env = case lookup name env of Just x -> return x Nothing -> [] interp (Con x) _ = return $ Num x interp (a :+: b) env = do v1 <- interp a env v2 <- interp b env case (v1, v2) of (Num x, Num y) -> return $ Num (x + y) _ -> [] interp (Lam name exp) env = return $ Fun (\x -> interp exp ((name, x) : env)) interp (App f v) env = do intf <- interp f env intv <- interp v env case intf of Fun a -> a intv _ -> [] interp Fail _ = [] interp (Amb a b) env = (interp a env) ++ (interp b env) test :: Term -> String test t = showM $ interp t [] pgm1:: Term pgm1 = App (Lam "x" ((Var "x") :+: (Var "x"))) ((Con 10) :+: (Con 11)) s1 = test pgm s2 = test pgm1
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/99185b0e97119135e7301c2c7be0f07ae7258006/FLP/laborator/lab4/varList.hs
haskell
- Limbajul si Interpretorul type M = [] showM :: Show a => M a -> String showM = foldMap (\a -> show a ++ " ") type Name = String data Term = Var Name | Con Integer | Term :+: Term | Lam Name Term | App Term Term | Fail | Amb Term Term deriving (Show) pgm :: Term pgm = App (Lam "y" (App (App (Lam "f" (Lam "y" (App (Var "f") (Var "y")) ) ) (Lam "x" (Var "x" :+: Var "y") ) ) (Amb (Con 3) (Con 1)) ) ) (Con 4) data Value = Num Integer | Fun (Value -> M Value) instance Show Value where show (Num x) = show x show (Fun _) = "<function>" type Environment = [(Name, Value)] interp :: Term -> Environment -> M Value interp (Var name) env = case lookup name env of Just x -> return x Nothing -> [] interp (Con x) _ = return $ Num x interp (a :+: b) env = do v1 <- interp a env v2 <- interp b env case (v1, v2) of (Num x, Num y) -> return $ Num (x + y) _ -> [] interp (Lam name exp) env = return $ Fun (\x -> interp exp ((name, x) : env)) interp (App f v) env = do intf <- interp f env intv <- interp v env case intf of Fun a -> a intv _ -> [] interp Fail _ = [] interp (Amb a b) env = (interp a env) ++ (interp b env) test :: Term -> String test t = showM $ interp t [] pgm1:: Term pgm1 = App (Lam "x" ((Var "x") :+: (Var "x"))) ((Con 10) :+: (Con 11)) s1 = test pgm s2 = test pgm1
38ecc595a71c071e422fb2a3ced0185f469abbb15772d2c43221db00490e0d99
ruricolist/serapeum
control-flow.lisp
(in-package :serapeum) (defmacro eval-always (&body body) "Shorthand for (eval-when (:compile-toplevel :load-toplevel :execute) ...)" `(eval-when (:compile-toplevel :load-toplevel :execute) ,@body)) (defmacro eval-and-compile (&body body) "Emacs's `eval-and-compile'. Alias for `eval-always'." `(eval-always ,@body)) (defun no (x) "Another alias for `not' and `null'. From Arc." (not x)) (define-compiler-macro no (x) `(not ,x)) (defmacro nor (&rest forms) "Equivalent to (not (or ...)). From Arc." (if (null forms) t (if (null (rest forms)) `(not ,(first forms)) `(if ,(first forms) nil (nor ,@(rest forms)))))) (defmacro nand (&rest forms) "Equivalent to (not (and ...))." (if (null forms) nil (if (null (rest forms)) `(not ,(first forms)) `(if ,(first forms) (nand ,@(rest forms)) t)))) (defun same-type? (type1 type2 &optional env) "Like `alexandria:type=', but takes an environment." (multiple-value-bind (sub sure) (subtypep type1 type2 env) (if (not sub) (values nil sure) (subtypep type2 type1 env)))) (defun explode-type (type env) "Extract the individual types from a type defined as a disjunction. TYPE could be the actual disjunction, or the name of the type. If TYPE is not a disjunction, just return TYPE as a list. Note that `member' types are disjunctions: (explode-type (member :x :y :z) nil) => ((eql :x) (:eql y) (eql :z))" (labels ((explode-type (type) (match type ((list* 'or subtypes) (mappend #'explode-type subtypes)) ((list* 'member subtypes) ;; Remember (member) is also the bottom type. (if (null subtypes) (list nil) (mappend #'explode-type (loop for subtype in subtypes collect `(eql ,subtype))))) (otherwise (list type))))) (explode-type (typexpand type env)))) (defun describe-non-exhaustive-match (stream partition type env) (assert (not (same-type? partition type))) (labels ((extra-types (partition) (loop for subtype in (explode-type partition env) unless (subtypep subtype type env) collect subtype)) (format-extra-types (stream partition) (when-let (et (extra-types partition)) (format stream "~&There are extra types: ~s" et))) (missing-types (partition) (remove-if (lambda (type) (subtypep type partition env)) (explode-type type env))) (format-missing-types (stream partition) (when-let (mt (missing-types partition)) (format stream "~&There are missing types: ~s" mt))) (format-subtype-problem (stream partition) (cond ((subtypep partition type env) (format stream "~s is a proper subtype of ~s." partition type)) ((subtypep type partition env) (format stream "~s contains types not in ~s." partition type)) (t (format stream "~s is not the same as ~s" partition type))))) (format stream "~&Non-exhaustive match: ") (format-subtype-problem stream partition) (format-extra-types stream partition) (format-missing-types stream partition))) (defun check-exhaustiveness (style type clauses env) ;; Should we do redundancy checking? Is there any Lisp that doesn't ;; already warn about that? (check-type style (member case typecase)) (multiple-value-bind (clause-types partition) (ecase style ((typecase) (loop for (type . nil) in clauses collect type into clause-types finally (return (values clause-types `(or ,@clause-types))))) ((case) (loop for (key-spec . nil) in clauses for keys = (ensure-list key-spec) for clause-type = `(member ,@keys) collect clause-type into clause-types append keys into all-keys finally (return (values clause-types `(member ,@all-keys)))))) ;; Check that every clause type is a subtype of TYPE. (dolist (clause-type clause-types) (multiple-value-bind (subtype? sure?) (subtypep clause-type type env) (cond ((not sure?) (warn "Can't tell if ~s is a subtype of ~s.~@[Is ~s defined?~]" clause-type type ;; Only warn about definition when the type could ;; be defined. (and (symbolp type) type))) ((not subtype?) (warn "~s is not a subtype of ~s" clause-type type))))) ;; Check that the clause types form an exhaustive partition of TYPE. (multiple-value-bind (same sure) (same-type? partition type env) (cond ((not sure) (warn "Can't check exhaustiveness: cannot determine if ~s is the same as ~s" partition type)) (same) (t (warn "~a" (with-output-to-string (s) (describe-non-exhaustive-match s partition type env))))))) (values)) (defmacro typecase-of (type x &body clauses &environment env) "Like `etypecase-of', but may, and must, have an `otherwise' clause in case X is not of TYPE." (let* ((otherwise (find 'otherwise clauses :key #'car)) (clauses (remove otherwise clauses))) (unless otherwise (error "No otherwise clause in typecase-of for type ~s" type)) (check-exhaustiveness 'typecase type clauses env) `(typecase ,x ,@clauses ,otherwise))) (defmacro etypecase-of (type x &body body) "Like `etypecase' but, at compile time, warn unless each clause in BODY is a subtype of TYPE, and the clauses in BODY form an exhaustive partition of TYPE." (once-only (x) `(typecase-of ,type ,x ,@body (otherwise (error 'type-error :datum ,x :expected-type ',type))))) (defmacro case-of (type x &body clauses &environment env) "Like `case' but may, and must, have an `otherwise' clause." (let* ((otherwise (find 'otherwise clauses :key #'car)) (clauses (remove otherwise clauses))) (unless otherwise (error "No otherwise clause in case-of for type ~s" type)) (check-exhaustiveness 'case type clauses env) `(case ,x ,@clauses ,otherwise))) (defmacro ecase-of (type x &body body) "Like `ecase' but, given a TYPE (which should be defined as `(member ...)'), warn, at compile time, unless the keys in BODY are all of TYPE and, taken together, they form an exhaustive partition of TYPE." (once-only (x) `(case-of ,type ,x ,@body (otherwise (error 'type-error :datum ,x :expected-type ',type))))) (defmacro ctypecase-of (type keyplace &body body &environment env) "Like `etypecase-of', but providing a `store-value' restart to correct KEYPLACE and try again." (check-exhaustiveness 'typecase type body env) `(ctypecase ,keyplace ,@body)) (defmacro ccase-of (type keyplace &body body &environment env) "Like `ecase-of', but providing a `store-value' restart to correct KEYPLACE and try again." (check-exhaustiveness 'case type body env) `(ccase ,keyplace ,@body)) Adapted from Alexandria . (defun expand-destructuring-case-of (type key clauses case-of) (once-only (key) `(if (typep ,key 'cons) (,case-of ,type (car ,key) ,@(mapcar (lambda (clause) (destructuring-bind ((keys . lambda-list) &body body) clause `(,keys (destructuring-bind ,lambda-list (cdr ,key) ,@body)))) clauses)) (error "Invalid key to DESTRUCTURING-~S: ~S" ',case-of ,key)))) (defmacro destructuring-ecase-of (type expr &body body) "Like `destructuring-ecase', from Alexandria, but with exhaustivness checking. TYPE is a designator for a type, which should be defined as `(member ...)'. At compile time, the macro checks that, taken together, the symbol at the head of each of the destructuring lists in BODY form an exhaustive partition of TYPE, and warns if it is not so." (expand-destructuring-case-of type expr body 'ecase-of)) (defmacro destructuring-case-of (type expr &body body) "Like `destructuring-ecase-of', but an `otherwise' clause must also be supplied. Note that the otherwise clauses must also be a list: ((otherwise &rest args) ...)" (expand-destructuring-case-of type expr body 'case-of)) (defmacro destructuring-ccase-of (type keyplace &body body) "Like `destructuring-case-of', but providing a `store-value' restart to collect KEYPLACE and try again." (expand-destructuring-case-of type keyplace body 'ccase-of)) (defmacro case-using (pred keyform &body clauses) "ISLISP's case-using. (case-using #'eql x ...) ≡ (case x ...). Note that, no matter the predicate, the keys are not evaluated. (But see `selector'.) The PRED form is evaluated. This version supports both single-item clauses (x ...) and multiple-item clauses ((x y) ...), as well as (t ...) or (otherwise ...) for the default clause." (case (extract-function-name pred) (eql `(case ,keyform ,@clauses)) ;; TODO Check that this isn't rebound in the environment. (Not a concern on SBCL as the package is locked there . ) (string= `(string-case ,keyform ,@clauses)) (t `(case-using-aux ,pred ,keyform ,@clauses)))) (define-case-macro case-using-aux (pred keyform &body clauses) (:default default) (once-only (keyform) (rebinding-functions (pred) `(cond ,@(loop for (key . body) in clauses collect `((funcall ,pred ,keyform ',key) ,@body)) (t ,@default))))) (defmacro ecase-using (pred keyform &body clauses) "Exhaustive variant of `case-using'." (once-only (keyform) `(case-using ,pred ,keyform ,@clauses (otherwise (error "~s fell through ~a with ~s" ,keyform 'ecase-using ',pred))))) (define-case-macro string-case (stringform &body clauses) (:default default) "Efficient `case'-like macro with string keys. Note that string matching is always case-sensitive. This uses Paul Khuong's `string-case' macro internally." (let ((keys (mapcar #'first clauses))) (if (every (lambda (key) (and (stringp key) (= (length key) 1))) keys) (with-unique-names (block) `(block ,block (and (= (length ,stringform) 1) (case (aref ,stringform 0) ,@(loop for (key . body) in clauses collect `(,(aref key 0) (return-from ,block (progn ,@body)))))) ,@default)) `(string-case:string-case (,stringform :default (progn ,@default)) ,@clauses)))) (defun string-case-failure (expr keys) (error "~s is not one of ~s" expr keys)) (define-case-macro string-ecase (stringform &body clauses) (:error string-case-failure) "Efficient `ecase'-like macro with string keys. Note that string matching is always case-sensitive. Cf. `string-case'." `(string-case ,stringform ,@clauses)) (defmacro if-let1 (var test &body (then else)) `(let1 ,var ,test (if ,var ,then ,else))) (defmacro eif (&whole whole test then &optional (else nil else?)) "Like `cl:if', but expects two branches. If there is only one branch a warning is signaled. This macro is useful when writing explicit decision trees; it will warn you if you forget a branch. Short for “exhaustive if”." (unless else? (warn "Missing else-branch in eif form:~%~a" whole)) `(if ,test ,then ,else)) (defmacro eif-let (&whole whole binds &body (then &optional (else nil else?))) "Like `alexandria:if-let', but expects two branches. Compare `eif'." (unless else? (warn "Missing else-branch in eif-let form:~%~a" whole)) `(if-let ,binds ,then ,else)) (define-condition econd-failure (error) ((test-count :type (integer 0 *) :initarg :test-count)) (:default-initargs :test-count 0) (:report (lambda (c s) (with-slots (test-count) c (format s "~s fell through after ~d failed test~:p." 'econd test-count)))) (:documentation "An ECOND failed.")) (defmacro econd (&rest clauses) "Like `cond', but signal an error of type `econd-failure' if no clause succeeds." (let ((test-count (length clauses))) `(cond ,@clauses SBCL will silently eliminate this branch if it is ;; unreachable. (t (error 'econd-failure :test-count ',test-count))))) (defmacro cond-let (var &body clauses) "Cross between COND and LET. (cond-let x ((test ...))) ≡ (let (x) (cond ((setf x test) ...))) Cf. `acond' in Anaphora." (match clauses (() nil) ((list* (list test) clauses) `(if-let1 ,var ,test ,var (cond-let ,var ,@clauses))) ((list* (list* t body) _) `(progn ,@body)) ((list* (list* test body) clauses) `(let ((,var ,test)) (if ,var Rebind the variables for declarations . (let1 ,var ,var ,@body) (cond-let ,var ,@clauses)))))) (defmacro econd-let (symbol &body clauses) "Like `cond-let' for `econd'." `(cond-let ,symbol ,@clauses (t (error 'econd-failure)))) ;;; cond-every has the same syntax as cond, but executes every clause whose condition is satisfied , not just the first . If a condition ;;; is the symbol otherwise, it is satisfied if and only if no ;;; preceding condition is satisfied. The value returned is the value ;;; of the last body form in the last clause whose condition is ;;; satisfied. Multiple values are not returned. (defmacro cond-every (&body clauses) "Like `cond', but instead of stopping after the first clause that succeeds, run all the clauses that succeed. Return the value of the last successful clause. If a clause begins with `cl:otherwise', it runs only if no preceding form has succeeded. Note that this does *not* do the same thing as a series of `when' forms: `cond-every' evaluates *all* the tests *before* it evaluates any of the forms. From Zetalisp." (let* ((otherwise-clause (find 'otherwise clauses :key #'car)) (test-clauses (remove otherwise-clause clauses)) (temps (make-gensym-list (length test-clauses)))) `(let* ,(loop for temp in temps for (test . nil) in test-clauses collect `(,temp ,test)) ;; Work around Iterate bug. See < -lisp.net/iterate/iterate/-/issues/11 > . (if (or ,@temps) ,(with-gensyms (ret) `(let (,ret) ,@(loop for temp in temps for (nil . body) in test-clauses collect `(when ,temp (setf ,ret ,(if (null body) temp `(progn ,@body))))) ,ret)) (progn ,@(rest otherwise-clause)))))) (defmacro bcond (&body clauses) "Scheme's extended COND. This is exactly like COND, except for clauses having the form (test :=> recipient) In that case, if TEST evaluates to a non-nil result, then RECIPIENT, a function, is called with that result, and the result of RECIPIENT is return as the value of the `cond`. As an extension, a clause like this: (test :=> var ...) Can be used as a shorthand for (test :=> (lambda (var) ...)) The name `bcond' for a “binding cond” goes back at least to the days of the Lisp Machines. I do not know who was first to use it, but the oldest examples I have found are by Michael Parker and Scott L. Burson." (flet ((send-clause? (clause) (let ((second (second clause))) (and (symbolp second) (string= second :=>)))) (parse-send-clause (clause) (destructuring-bind (test => . body) clause (declare (ignore =>)) (cond ((null body) (error "Missing clause")) ((null (rest body)) (values test (car body))) (t (destructuring-bind (var . body) body (let ((fn `(lambda (,var) ,@body))) (values test fn)))))))) ;; Note that we expand into `cond' rather than `if' so we don't ;; have to handle tests without bodies. (cond ((null clauses) nil) ((member-if #'send-clause? clauses) (let* ((tail (member-if #'send-clause? clauses)) (preceding (ldiff clauses tail)) (clause (car tail)) (clauses (cdr tail))) (multiple-value-bind (test fn) (parse-send-clause clause) (with-gensyms (tmp) `(cond ,@preceding (t (if-let1 ,tmp ,test (funcall ,fn ,tmp) (bcond ,@clauses)))))))) (t `(cond ,@clauses))))) (defmacro case-let ((var expr) &body cases) "Like (let ((VAR EXPR)) (case VAR ...)), with VAR read-only." `(let1 ,var ,expr (case ,var ,@cases))) (defmacro ecase-let ((var expr) &body cases) "Like (let ((VAR EXPR)) (ecase VAR ...)), with VAR read-only." `(let1 ,var ,expr (ecase ,var ,@cases))) (defmacro comment (&body body) "A macro that ignores its body and does nothing. Useful for comments-by-example. Also, as noted in EXTENSIONS.LISP of 1992, \"This may seem like a silly macro, but used inside of other macros or code generation facilities it is very useful - you can see comments in the (one-time) macro expansion!\"" (declare (ignore body))) (defmacro example (&body body) "Like `comment'." `(comment ,@body)) (defmacro nix-1 (place &environment env) (multiple-value-bind (vars vals new setter getter) (get-setf-expansion place env) `(let* (,@(mapcar #'list vars vals) (,(car new) ,getter)) (and ,(car new) (prog1 ,(car new) (setq ,(car new) nil) ,setter))))) (defmacro nix (&rest places) "Set PLACES to nil and return the old value(s) of PLACES. If there is more than one PLACE, return their old values as multiple values. This may be more efficient than (shiftf place nil), because it only sets PLACE when it is not already null." `(values ,@(loop for place in places collect `(nix-1 ,place)))) ;;; (defmacro ensure (place &body newval &environment env) "Essentially (or place (setf place newval)). PLACE is treated as unbound if it returns `nil', signals `unbound-slot', or signals `unbound-variable'. Note that ENSURE is `setf'-able, so you can do things like (incf (ensure x 0)) Cf. `ensure2'." (multiple-value-bind (vars vals stores setter getter) (get-setf-expansion place env) `(let* ,(mapcar #'list vars vals) (or (ignore-some-conditions (unbound-slot unbound-variable) ,getter) (multiple-value-bind ,stores (progn ,@newval) (when ,(first stores) ,setter)))))) (define-setf-expander ensure (place &rest newval &environment env) (multiple-value-bind (vars vals stores setter getter) (get-setf-expansion place env) (values vars vals stores setter `(or (ignore-some-conditions (unbound-slot unbound-variable) ,getter) (progn ,@newval))))) (defmacro ensure2 (place &body newval &environment env) "Like `ensure', but specifically for accessors that return a second value like `gethash'." (multiple-value-bind (vars vals stores setter getter) (get-setf-expansion place env) (with-gensyms (old presentp) `(let* ,(mapcar #'list vars vals) (multiple-value-bind (,old ,presentp) ,getter (if ,presentp ,old (multiple-value-bind ,stores (progn ,@newval) ,setter))))))) (define-setf-expander ensure2 (place &rest newval &environment env) (multiple-value-bind (vars vals stores setter getter) (get-setf-expansion place env) (values vars vals stores setter (with-gensyms (old presentp) `(multiple-value-bind (,old ,presentp) ,getter (if ,presentp ,old (progn ,@newval))))))) (defun thread-aux (threader needle holes thread-fn) ;; / (flet ((str= (x y) (and (symbolp x) (symbolp y) (string= x y)))) #+sbcl (labels ((find-_ (form env) (sb-walker:walk-form form env (lambda (f c e) (declare (ignore c e)) (cond ((str= f '_) (return-from find-_ f)) ((eql f form) f) (t (values f t))))) nil) (walker (form c env) (declare (ignore c)) (cond ((symbolp form) (list form)) ((atom form) form) (t (if-let (_ (find-_ form env)) (values `(let1 ,_ ,needle ,form) t) (values (funcall thread-fn needle form) t)))))) (if (not holes) needle `(,threader ,(sb-walker:walk-form (first holes) nil #'walker) ,@(rest holes)))) #-sbcl (if (not holes) needle `(,threader ,(let ((hole (first holes))) (if (listp hole) (if-let (_ (find '_ hole :test #'str=)) `(let1 ,_ ,needle ,hole) (funcall thread-fn needle hole)) `(,hole ,needle))) ,@(rest holes))))) (defun check-no-underscores (holes) (loop for hole in holes when (find '_ (ensure-list hole)) do (error "Arrow macros with underscores cannot be used as patterns: ~a" hole))) (defmacro ~> (needle &rest holes) "Threading macro from Clojure (by way of Racket). Thread NEEDLE through HOLES, where each hole is either a symbol (equivalent to `(hole needle)`) or a list (equivalent to `(hole needle args...)`). As an extension, an underscore in the argument list is replaced with the needle, so you can pass the needle as an argument other than the first." (thread-aux '~> needle holes (lambda (needle hole) (list* (car hole) needle (cdr hole))))) (defpattern ~> (needle &rest holes) (check-no-underscores holes) (macroexpand-1 `(~> ,needle ,@holes))) (defmacro ~>> (needle &rest holes) "Like `~>' but, by default, thread NEEDLE as the last argument instead of the first." (declare (notinline append1)) ;phasing (thread-aux '~>> needle holes (lambda (needle hole) (append1 hole needle)))) (defpattern ~>> (needle &rest holes) (check-no-underscores holes) (macroexpand-1 `(~>> ,needle ,@holes))) (defun expand-nest (things) "Helper function for `nest'." (reduce (lambda (outer inner) (let ((outer (ensure-list outer))) `(,@outer ,inner))) things :from-end t)) (defmacro nest (&rest things) "Like ~>>, but backward. This is useful when layering `with-x' macros where the order is not important, and extra indentation would be misleading. For example: (nest (with-open-file (in file1 :direction input)) (with-open-file (in file2 :direction output)) ...) Is equivalent to: (with-open-file (in file1 :direction input) (with-open-file (in file2 :direction output) ...)) \(But see `with-open-files'). If the outer macro has no arguments, you may omit the parentheses. (nest with-standard-io-syntax ...) ≡ (with-standard-io-syntax ...) From UIOP, based on a suggestion by Marco Baringer." (expand-nest things)) (defpattern nest (&rest things) (expand-nest things)) (defmacro select (keyform &body clauses) "Like `case', but with evaluated keys. Note that, like `case', `select' interprets a list as the first element of a clause as a list of keys. To use a form as a key, you must add an extra set of parentheses. (select 2 ((+ 2 2) t)) => T (select 4 (((+ 2 2)) t)) => T From Zetalisp." `(selector ,keyform eql ,@clauses)) (define-case-macro selector (keyform fn &body clauses) (:default default) "Like `select', but compare using FN. Note that (unlike `case-using'), FN is not evaluated. From Zetalisp." `(cond ,@(loop for (test . body) in clauses collect `((,fn ,keyform ,test) ,@body)) (t ,@default))) (def sorting-networks '((2 (0 1)) (3 (1 2) (0 2) (0 1)) (4 (0 1) (2 3) (0 2) (1 3) (1 2)) (5 (0 1) (3 4) (2 4) (2 3) (0 3) (0 2) (1 4) (1 3) (1 2)) (6 (1 2) (0 2) (0 1) (4 5) (3 5) (3 4) (0 3) (1 4) (2 5) (2 4) (1 3) (2 3)) (7 (1 2) (0 2) (0 1) (3 4) (5 6) (3 5) (4 6) (4 5) (0 4) (0 3) (1 5) (2 6) (2 5) (1 3) (2 4) (2 3)) (8 (0 1) (2 3) (0 2) (1 3) (1 2) (4 5) (6 7) (4 6) (5 7) (5 6) (0 4) (1 5) (1 4) (2 6) (3 7) (3 6) (2 4) (3 5) (3 4))) "Sorting networks for 2 to 8 elements.") (defun sorting-network (size) (check-type size (integer 2 *)) (or (cdr (assoc size sorting-networks)) (error "No sorting network of size ~d" size))) (defmacro sort-values/network (pred &rest values) (with-gensyms (swap) `(macrolet ((,swap (x y) `(unless (funcall ,',pred ,x ,y) (rotatef ,x ,y)))) ,(let ((network (sorting-network (length values)))) (assert network) (let ((temps (make-gensym-list (length values)))) `(let ,(mapcar #'list temps values) ,@(loop for (x y) in network collect `(,swap ,(nth x temps) ,(nth y temps))) (values ,@temps))))))) (defmacro sort-values/temp-vector (pred &rest values) (with-gensyms (temp) `(let ((,temp (make-array ,(length values)))) (declare (dynamic-extent ,temp)) ,@(loop for i from 0 for v in values collect `(setf (svref ,temp ,i) ,v)) ;; Keep compiler quiet. (setf ,temp (sort ,temp ,pred)) (values ,@(loop for i from 0 for nil in values collect `(svref ,temp ,i)))))) (defmacro sort-values (pred &rest values) "Sort VALUES with PRED and return as multiple values. Equivalent to (values-list (sort (list VALUES...) pred)) But with less consing, and potentially faster." ;; Remember to evaluate `pred' no matter what. (with-gensyms (gpred) `(let ((,gpred (ensure-function ,pred))) (declare (ignorable ,gpred) (function ,gpred) (optimize (safety 1) (debug 0) (compilation-speed 0))) ,(match values ((list) `(values)) ((list x) `(values ,x)) ;; The strategy here is to use a sorting network if the ;; inputs are few, and a stack-allocated vector if the ;; inputs are many. (otherwise (if (<= (length values) 8) `(sort-values/network ,gpred ,@values) `(sort-values/temp-vector ,gpred ,@values))))))) (defun expand-variadic-equality (binary variadic args) (match args (() t) ((list x) `(progn ,x t)) ((list x y) `(,binary ,x ,y)) It might be worth special - casing the three - argument case ; of ;; all the variadic cases it is likely to be the most common by ;; far. ((list x y z) (once-only (x y z) `(and (,binary ,x ,y) (,binary ,y ,z)))) (otherwise ;; Remember that we need to evaluate all of the arguments, ;; always, and in left-to-right order. (let ((temps (make-gensym-list (length args)))) (destructuring-bind (x y . zs) temps `(let ,(mapcar #'list temps args) (and (,binary ,x ,y) (,variadic ,y ,@zs)))))))) (defmacro define-variadic-equality (variadic binary) `(progn (defun ,variadic (&rest xs) ,(format nil "Variadic version of `~(~a~)'. With no arguments, return T. With one argument, return T. With two arguments, same as `~:*~(~a~)'. With three or more arguments, return T only if all of XS are equivalent under `~:*~(~a~)'. Has a compiler macro, so there is no loss of efficiency relative to writing out the tests by hand." binary) (match xs (() t) ((list _) t) ((list x y) (,binary x y)) (otherwise (every #',binary xs (rest xs))))) (define-compiler-macro ,variadic (&rest xs) (expand-variadic-equality ',binary ',variadic xs)))) (define-variadic-equality eq* eq) (define-variadic-equality eql* eql) (define-variadic-equality equal* equal) (define-variadic-equality equalp* equalp) (define-condition recursion-forbidden (error) ((form :initarg :form)) (:report (lambda (c s) (with-slots (form) c (format s "Forbidden recursion in form:~%~a" form))))) (defvar *recursions* nil) (defmacro without-recursion ((&key) &body body) "If BODY calls itself, at any depth, signal a (continuable) error of type `recursion-forbidden'." (with-unique-names (recursion-id) `(progn (when (member ',recursion-id *recursions*) (cerror "Recurse anyway." 'recursion-forbidden :form ',body)) (let ((*recursions* (cons ',recursion-id *recursions*))) (declare (dynamic-extent *recursions*)) ,@body))))
null
https://raw.githubusercontent.com/ruricolist/serapeum/712cc0fdf5cca9ae2bc82e086f3ee609f99e8d78/control-flow.lisp
lisp
Remember (member) is also the bottom type. Should we do redundancy checking? Is there any Lisp that doesn't already warn about that? Check that every clause type is a subtype of TYPE. Only warn about definition when the type could be defined. Check that the clause types form an exhaustive partition of TYPE. TODO Check that this isn't rebound in the environment. (Not a it will unreachable. cond-every has the same syntax as cond, but executes every clause is the symbol otherwise, it is satisfied if and only if no preceding condition is satisfied. The value returned is the value of the last body form in the last clause whose condition is satisfied. Multiple values are not returned. Work around Iterate bug. See Note that we expand into `cond' rather than `if' so we don't have to handle tests without bodies. / phasing Keep compiler quiet. Remember to evaluate `pred' no matter what. The strategy here is to use a sorting network if the inputs are few, and a stack-allocated vector if the inputs are many. of all the variadic cases it is likely to be the most common by far. Remember that we need to evaluate all of the arguments, always, and in left-to-right order.
(in-package :serapeum) (defmacro eval-always (&body body) "Shorthand for (eval-when (:compile-toplevel :load-toplevel :execute) ...)" `(eval-when (:compile-toplevel :load-toplevel :execute) ,@body)) (defmacro eval-and-compile (&body body) "Emacs's `eval-and-compile'. Alias for `eval-always'." `(eval-always ,@body)) (defun no (x) "Another alias for `not' and `null'. From Arc." (not x)) (define-compiler-macro no (x) `(not ,x)) (defmacro nor (&rest forms) "Equivalent to (not (or ...)). From Arc." (if (null forms) t (if (null (rest forms)) `(not ,(first forms)) `(if ,(first forms) nil (nor ,@(rest forms)))))) (defmacro nand (&rest forms) "Equivalent to (not (and ...))." (if (null forms) nil (if (null (rest forms)) `(not ,(first forms)) `(if ,(first forms) (nand ,@(rest forms)) t)))) (defun same-type? (type1 type2 &optional env) "Like `alexandria:type=', but takes an environment." (multiple-value-bind (sub sure) (subtypep type1 type2 env) (if (not sub) (values nil sure) (subtypep type2 type1 env)))) (defun explode-type (type env) "Extract the individual types from a type defined as a disjunction. TYPE could be the actual disjunction, or the name of the type. If TYPE is not a disjunction, just return TYPE as a list. Note that `member' types are disjunctions: (explode-type (member :x :y :z) nil) => ((eql :x) (:eql y) (eql :z))" (labels ((explode-type (type) (match type ((list* 'or subtypes) (mappend #'explode-type subtypes)) ((list* 'member subtypes) (if (null subtypes) (list nil) (mappend #'explode-type (loop for subtype in subtypes collect `(eql ,subtype))))) (otherwise (list type))))) (explode-type (typexpand type env)))) (defun describe-non-exhaustive-match (stream partition type env) (assert (not (same-type? partition type))) (labels ((extra-types (partition) (loop for subtype in (explode-type partition env) unless (subtypep subtype type env) collect subtype)) (format-extra-types (stream partition) (when-let (et (extra-types partition)) (format stream "~&There are extra types: ~s" et))) (missing-types (partition) (remove-if (lambda (type) (subtypep type partition env)) (explode-type type env))) (format-missing-types (stream partition) (when-let (mt (missing-types partition)) (format stream "~&There are missing types: ~s" mt))) (format-subtype-problem (stream partition) (cond ((subtypep partition type env) (format stream "~s is a proper subtype of ~s." partition type)) ((subtypep type partition env) (format stream "~s contains types not in ~s." partition type)) (t (format stream "~s is not the same as ~s" partition type))))) (format stream "~&Non-exhaustive match: ") (format-subtype-problem stream partition) (format-extra-types stream partition) (format-missing-types stream partition))) (defun check-exhaustiveness (style type clauses env) (check-type style (member case typecase)) (multiple-value-bind (clause-types partition) (ecase style ((typecase) (loop for (type . nil) in clauses collect type into clause-types finally (return (values clause-types `(or ,@clause-types))))) ((case) (loop for (key-spec . nil) in clauses for keys = (ensure-list key-spec) for clause-type = `(member ,@keys) collect clause-type into clause-types append keys into all-keys finally (return (values clause-types `(member ,@all-keys)))))) (dolist (clause-type clause-types) (multiple-value-bind (subtype? sure?) (subtypep clause-type type env) (cond ((not sure?) (warn "Can't tell if ~s is a subtype of ~s.~@[Is ~s defined?~]" clause-type type (and (symbolp type) type))) ((not subtype?) (warn "~s is not a subtype of ~s" clause-type type))))) (multiple-value-bind (same sure) (same-type? partition type env) (cond ((not sure) (warn "Can't check exhaustiveness: cannot determine if ~s is the same as ~s" partition type)) (same) (t (warn "~a" (with-output-to-string (s) (describe-non-exhaustive-match s partition type env))))))) (values)) (defmacro typecase-of (type x &body clauses &environment env) "Like `etypecase-of', but may, and must, have an `otherwise' clause in case X is not of TYPE." (let* ((otherwise (find 'otherwise clauses :key #'car)) (clauses (remove otherwise clauses))) (unless otherwise (error "No otherwise clause in typecase-of for type ~s" type)) (check-exhaustiveness 'typecase type clauses env) `(typecase ,x ,@clauses ,otherwise))) (defmacro etypecase-of (type x &body body) "Like `etypecase' but, at compile time, warn unless each clause in BODY is a subtype of TYPE, and the clauses in BODY form an exhaustive partition of TYPE." (once-only (x) `(typecase-of ,type ,x ,@body (otherwise (error 'type-error :datum ,x :expected-type ',type))))) (defmacro case-of (type x &body clauses &environment env) "Like `case' but may, and must, have an `otherwise' clause." (let* ((otherwise (find 'otherwise clauses :key #'car)) (clauses (remove otherwise clauses))) (unless otherwise (error "No otherwise clause in case-of for type ~s" type)) (check-exhaustiveness 'case type clauses env) `(case ,x ,@clauses ,otherwise))) (defmacro ecase-of (type x &body body) "Like `ecase' but, given a TYPE (which should be defined as `(member ...)'), warn, at compile time, unless the keys in BODY are all of TYPE and, taken together, they form an exhaustive partition of TYPE." (once-only (x) `(case-of ,type ,x ,@body (otherwise (error 'type-error :datum ,x :expected-type ',type))))) (defmacro ctypecase-of (type keyplace &body body &environment env) "Like `etypecase-of', but providing a `store-value' restart to correct KEYPLACE and try again." (check-exhaustiveness 'typecase type body env) `(ctypecase ,keyplace ,@body)) (defmacro ccase-of (type keyplace &body body &environment env) "Like `ecase-of', but providing a `store-value' restart to correct KEYPLACE and try again." (check-exhaustiveness 'case type body env) `(ccase ,keyplace ,@body)) Adapted from Alexandria . (defun expand-destructuring-case-of (type key clauses case-of) (once-only (key) `(if (typep ,key 'cons) (,case-of ,type (car ,key) ,@(mapcar (lambda (clause) (destructuring-bind ((keys . lambda-list) &body body) clause `(,keys (destructuring-bind ,lambda-list (cdr ,key) ,@body)))) clauses)) (error "Invalid key to DESTRUCTURING-~S: ~S" ',case-of ,key)))) (defmacro destructuring-ecase-of (type expr &body body) "Like `destructuring-ecase', from Alexandria, but with exhaustivness checking. TYPE is a designator for a type, which should be defined as `(member ...)'. At compile time, the macro checks that, taken together, the symbol at the head of each of the destructuring lists in BODY form an exhaustive partition of TYPE, and warns if it is not so." (expand-destructuring-case-of type expr body 'ecase-of)) (defmacro destructuring-case-of (type expr &body body) "Like `destructuring-ecase-of', but an `otherwise' clause must also be supplied. Note that the otherwise clauses must also be a list: ((otherwise &rest args) ...)" (expand-destructuring-case-of type expr body 'case-of)) (defmacro destructuring-ccase-of (type keyplace &body body) "Like `destructuring-case-of', but providing a `store-value' restart to collect KEYPLACE and try again." (expand-destructuring-case-of type keyplace body 'ccase-of)) (defmacro case-using (pred keyform &body clauses) "ISLISP's case-using. (case-using #'eql x ...) ≡ (case x ...). Note that, no matter the predicate, the keys are not evaluated. (But see `selector'.) The PRED form is evaluated. This version supports both single-item clauses (x ...) and multiple-item clauses ((x y) ...), as well as (t ...) or (otherwise ...) for the default clause." (case (extract-function-name pred) (eql `(case ,keyform ,@clauses)) concern on SBCL as the package is locked there . ) (string= `(string-case ,keyform ,@clauses)) (t `(case-using-aux ,pred ,keyform ,@clauses)))) (define-case-macro case-using-aux (pred keyform &body clauses) (:default default) (once-only (keyform) (rebinding-functions (pred) `(cond ,@(loop for (key . body) in clauses collect `((funcall ,pred ,keyform ',key) ,@body)) (t ,@default))))) (defmacro ecase-using (pred keyform &body clauses) "Exhaustive variant of `case-using'." (once-only (keyform) `(case-using ,pred ,keyform ,@clauses (otherwise (error "~s fell through ~a with ~s" ,keyform 'ecase-using ',pred))))) (define-case-macro string-case (stringform &body clauses) (:default default) "Efficient `case'-like macro with string keys. Note that string matching is always case-sensitive. This uses Paul Khuong's `string-case' macro internally." (let ((keys (mapcar #'first clauses))) (if (every (lambda (key) (and (stringp key) (= (length key) 1))) keys) (with-unique-names (block) `(block ,block (and (= (length ,stringform) 1) (case (aref ,stringform 0) ,@(loop for (key . body) in clauses collect `(,(aref key 0) (return-from ,block (progn ,@body)))))) ,@default)) `(string-case:string-case (,stringform :default (progn ,@default)) ,@clauses)))) (defun string-case-failure (expr keys) (error "~s is not one of ~s" expr keys)) (define-case-macro string-ecase (stringform &body clauses) (:error string-case-failure) "Efficient `ecase'-like macro with string keys. Note that string matching is always case-sensitive. Cf. `string-case'." `(string-case ,stringform ,@clauses)) (defmacro if-let1 (var test &body (then else)) `(let1 ,var ,test (if ,var ,then ,else))) (defmacro eif (&whole whole test then &optional (else nil else?)) "Like `cl:if', but expects two branches. If there is only one branch a warning is signaled. warn you if you forget a branch. Short for “exhaustive if”." (unless else? (warn "Missing else-branch in eif form:~%~a" whole)) `(if ,test ,then ,else)) (defmacro eif-let (&whole whole binds &body (then &optional (else nil else?))) "Like `alexandria:if-let', but expects two branches. Compare `eif'." (unless else? (warn "Missing else-branch in eif-let form:~%~a" whole)) `(if-let ,binds ,then ,else)) (define-condition econd-failure (error) ((test-count :type (integer 0 *) :initarg :test-count)) (:default-initargs :test-count 0) (:report (lambda (c s) (with-slots (test-count) c (format s "~s fell through after ~d failed test~:p." 'econd test-count)))) (:documentation "An ECOND failed.")) (defmacro econd (&rest clauses) "Like `cond', but signal an error of type `econd-failure' if no clause succeeds." (let ((test-count (length clauses))) `(cond ,@clauses SBCL will silently eliminate this branch if it is (t (error 'econd-failure :test-count ',test-count))))) (defmacro cond-let (var &body clauses) "Cross between COND and LET. (cond-let x ((test ...))) ≡ (let (x) (cond ((setf x test) ...))) Cf. `acond' in Anaphora." (match clauses (() nil) ((list* (list test) clauses) `(if-let1 ,var ,test ,var (cond-let ,var ,@clauses))) ((list* (list* t body) _) `(progn ,@body)) ((list* (list* test body) clauses) `(let ((,var ,test)) (if ,var Rebind the variables for declarations . (let1 ,var ,var ,@body) (cond-let ,var ,@clauses)))))) (defmacro econd-let (symbol &body clauses) "Like `cond-let' for `econd'." `(cond-let ,symbol ,@clauses (t (error 'econd-failure)))) whose condition is satisfied , not just the first . If a condition (defmacro cond-every (&body clauses) "Like `cond', but instead of stopping after the first clause that succeeds, run all the clauses that succeed. Return the value of the last successful clause. If a clause begins with `cl:otherwise', it runs only if no preceding form has succeeded. Note that this does *not* do the same thing as a series of `when' forms: `cond-every' evaluates *all* the tests *before* it evaluates any of the forms. From Zetalisp." (let* ((otherwise-clause (find 'otherwise clauses :key #'car)) (test-clauses (remove otherwise-clause clauses)) (temps (make-gensym-list (length test-clauses)))) `(let* ,(loop for temp in temps for (test . nil) in test-clauses collect `(,temp ,test)) < -lisp.net/iterate/iterate/-/issues/11 > . (if (or ,@temps) ,(with-gensyms (ret) `(let (,ret) ,@(loop for temp in temps for (nil . body) in test-clauses collect `(when ,temp (setf ,ret ,(if (null body) temp `(progn ,@body))))) ,ret)) (progn ,@(rest otherwise-clause)))))) (defmacro bcond (&body clauses) "Scheme's extended COND. This is exactly like COND, except for clauses having the form (test :=> recipient) In that case, if TEST evaluates to a non-nil result, then RECIPIENT, a function, is called with that result, and the result of RECIPIENT is return as the value of the `cond`. As an extension, a clause like this: (test :=> var ...) Can be used as a shorthand for (test :=> (lambda (var) ...)) The name `bcond' for a “binding cond” goes back at least to the days of the Lisp Machines. I do not know who was first to use it, but the oldest examples I have found are by Michael Parker and Scott L. Burson." (flet ((send-clause? (clause) (let ((second (second clause))) (and (symbolp second) (string= second :=>)))) (parse-send-clause (clause) (destructuring-bind (test => . body) clause (declare (ignore =>)) (cond ((null body) (error "Missing clause")) ((null (rest body)) (values test (car body))) (t (destructuring-bind (var . body) body (let ((fn `(lambda (,var) ,@body))) (values test fn)))))))) (cond ((null clauses) nil) ((member-if #'send-clause? clauses) (let* ((tail (member-if #'send-clause? clauses)) (preceding (ldiff clauses tail)) (clause (car tail)) (clauses (cdr tail))) (multiple-value-bind (test fn) (parse-send-clause clause) (with-gensyms (tmp) `(cond ,@preceding (t (if-let1 ,tmp ,test (funcall ,fn ,tmp) (bcond ,@clauses)))))))) (t `(cond ,@clauses))))) (defmacro case-let ((var expr) &body cases) "Like (let ((VAR EXPR)) (case VAR ...)), with VAR read-only." `(let1 ,var ,expr (case ,var ,@cases))) (defmacro ecase-let ((var expr) &body cases) "Like (let ((VAR EXPR)) (ecase VAR ...)), with VAR read-only." `(let1 ,var ,expr (ecase ,var ,@cases))) (defmacro comment (&body body) "A macro that ignores its body and does nothing. Useful for comments-by-example. Also, as noted in EXTENSIONS.LISP of 1992, \"This may seem like a silly macro, but used inside of other macros or code generation facilities it is very useful - you can see comments in the (one-time) macro expansion!\"" (declare (ignore body))) (defmacro example (&body body) "Like `comment'." `(comment ,@body)) (defmacro nix-1 (place &environment env) (multiple-value-bind (vars vals new setter getter) (get-setf-expansion place env) `(let* (,@(mapcar #'list vars vals) (,(car new) ,getter)) (and ,(car new) (prog1 ,(car new) (setq ,(car new) nil) ,setter))))) (defmacro nix (&rest places) "Set PLACES to nil and return the old value(s) of PLACES. If there is more than one PLACE, return their old values as multiple values. This may be more efficient than (shiftf place nil), because it only sets PLACE when it is not already null." `(values ,@(loop for place in places collect `(nix-1 ,place)))) (defmacro ensure (place &body newval &environment env) "Essentially (or place (setf place newval)). PLACE is treated as unbound if it returns `nil', signals `unbound-slot', or signals `unbound-variable'. Note that ENSURE is `setf'-able, so you can do things like (incf (ensure x 0)) Cf. `ensure2'." (multiple-value-bind (vars vals stores setter getter) (get-setf-expansion place env) `(let* ,(mapcar #'list vars vals) (or (ignore-some-conditions (unbound-slot unbound-variable) ,getter) (multiple-value-bind ,stores (progn ,@newval) (when ,(first stores) ,setter)))))) (define-setf-expander ensure (place &rest newval &environment env) (multiple-value-bind (vars vals stores setter getter) (get-setf-expansion place env) (values vars vals stores setter `(or (ignore-some-conditions (unbound-slot unbound-variable) ,getter) (progn ,@newval))))) (defmacro ensure2 (place &body newval &environment env) "Like `ensure', but specifically for accessors that return a second value like `gethash'." (multiple-value-bind (vars vals stores setter getter) (get-setf-expansion place env) (with-gensyms (old presentp) `(let* ,(mapcar #'list vars vals) (multiple-value-bind (,old ,presentp) ,getter (if ,presentp ,old (multiple-value-bind ,stores (progn ,@newval) ,setter))))))) (define-setf-expander ensure2 (place &rest newval &environment env) (multiple-value-bind (vars vals stores setter getter) (get-setf-expansion place env) (values vars vals stores setter (with-gensyms (old presentp) `(multiple-value-bind (,old ,presentp) ,getter (if ,presentp ,old (progn ,@newval))))))) (defun thread-aux (threader needle holes thread-fn) (flet ((str= (x y) (and (symbolp x) (symbolp y) (string= x y)))) #+sbcl (labels ((find-_ (form env) (sb-walker:walk-form form env (lambda (f c e) (declare (ignore c e)) (cond ((str= f '_) (return-from find-_ f)) ((eql f form) f) (t (values f t))))) nil) (walker (form c env) (declare (ignore c)) (cond ((symbolp form) (list form)) ((atom form) form) (t (if-let (_ (find-_ form env)) (values `(let1 ,_ ,needle ,form) t) (values (funcall thread-fn needle form) t)))))) (if (not holes) needle `(,threader ,(sb-walker:walk-form (first holes) nil #'walker) ,@(rest holes)))) #-sbcl (if (not holes) needle `(,threader ,(let ((hole (first holes))) (if (listp hole) (if-let (_ (find '_ hole :test #'str=)) `(let1 ,_ ,needle ,hole) (funcall thread-fn needle hole)) `(,hole ,needle))) ,@(rest holes))))) (defun check-no-underscores (holes) (loop for hole in holes when (find '_ (ensure-list hole)) do (error "Arrow macros with underscores cannot be used as patterns: ~a" hole))) (defmacro ~> (needle &rest holes) "Threading macro from Clojure (by way of Racket). Thread NEEDLE through HOLES, where each hole is either a symbol (equivalent to `(hole needle)`) or a list (equivalent to `(hole needle args...)`). As an extension, an underscore in the argument list is replaced with the needle, so you can pass the needle as an argument other than the first." (thread-aux '~> needle holes (lambda (needle hole) (list* (car hole) needle (cdr hole))))) (defpattern ~> (needle &rest holes) (check-no-underscores holes) (macroexpand-1 `(~> ,needle ,@holes))) (defmacro ~>> (needle &rest holes) "Like `~>' but, by default, thread NEEDLE as the last argument instead of the first." (thread-aux '~>> needle holes (lambda (needle hole) (append1 hole needle)))) (defpattern ~>> (needle &rest holes) (check-no-underscores holes) (macroexpand-1 `(~>> ,needle ,@holes))) (defun expand-nest (things) "Helper function for `nest'." (reduce (lambda (outer inner) (let ((outer (ensure-list outer))) `(,@outer ,inner))) things :from-end t)) (defmacro nest (&rest things) "Like ~>>, but backward. This is useful when layering `with-x' macros where the order is not important, and extra indentation would be misleading. For example: (nest (with-open-file (in file1 :direction input)) (with-open-file (in file2 :direction output)) ...) Is equivalent to: (with-open-file (in file1 :direction input) (with-open-file (in file2 :direction output) ...)) \(But see `with-open-files'). If the outer macro has no arguments, you may omit the parentheses. (nest with-standard-io-syntax ...) ≡ (with-standard-io-syntax ...) From UIOP, based on a suggestion by Marco Baringer." (expand-nest things)) (defpattern nest (&rest things) (expand-nest things)) (defmacro select (keyform &body clauses) "Like `case', but with evaluated keys. Note that, like `case', `select' interprets a list as the first element of a clause as a list of keys. To use a form as a key, you must add an extra set of parentheses. (select 2 ((+ 2 2) t)) => T (select 4 (((+ 2 2)) t)) => T From Zetalisp." `(selector ,keyform eql ,@clauses)) (define-case-macro selector (keyform fn &body clauses) (:default default) "Like `select', but compare using FN. Note that (unlike `case-using'), FN is not evaluated. From Zetalisp." `(cond ,@(loop for (test . body) in clauses collect `((,fn ,keyform ,test) ,@body)) (t ,@default))) (def sorting-networks '((2 (0 1)) (3 (1 2) (0 2) (0 1)) (4 (0 1) (2 3) (0 2) (1 3) (1 2)) (5 (0 1) (3 4) (2 4) (2 3) (0 3) (0 2) (1 4) (1 3) (1 2)) (6 (1 2) (0 2) (0 1) (4 5) (3 5) (3 4) (0 3) (1 4) (2 5) (2 4) (1 3) (2 3)) (7 (1 2) (0 2) (0 1) (3 4) (5 6) (3 5) (4 6) (4 5) (0 4) (0 3) (1 5) (2 6) (2 5) (1 3) (2 4) (2 3)) (8 (0 1) (2 3) (0 2) (1 3) (1 2) (4 5) (6 7) (4 6) (5 7) (5 6) (0 4) (1 5) (1 4) (2 6) (3 7) (3 6) (2 4) (3 5) (3 4))) "Sorting networks for 2 to 8 elements.") (defun sorting-network (size) (check-type size (integer 2 *)) (or (cdr (assoc size sorting-networks)) (error "No sorting network of size ~d" size))) (defmacro sort-values/network (pred &rest values) (with-gensyms (swap) `(macrolet ((,swap (x y) `(unless (funcall ,',pred ,x ,y) (rotatef ,x ,y)))) ,(let ((network (sorting-network (length values)))) (assert network) (let ((temps (make-gensym-list (length values)))) `(let ,(mapcar #'list temps values) ,@(loop for (x y) in network collect `(,swap ,(nth x temps) ,(nth y temps))) (values ,@temps))))))) (defmacro sort-values/temp-vector (pred &rest values) (with-gensyms (temp) `(let ((,temp (make-array ,(length values)))) (declare (dynamic-extent ,temp)) ,@(loop for i from 0 for v in values collect `(setf (svref ,temp ,i) ,v)) (setf ,temp (sort ,temp ,pred)) (values ,@(loop for i from 0 for nil in values collect `(svref ,temp ,i)))))) (defmacro sort-values (pred &rest values) "Sort VALUES with PRED and return as multiple values. Equivalent to (values-list (sort (list VALUES...) pred)) But with less consing, and potentially faster." (with-gensyms (gpred) `(let ((,gpred (ensure-function ,pred))) (declare (ignorable ,gpred) (function ,gpred) (optimize (safety 1) (debug 0) (compilation-speed 0))) ,(match values ((list) `(values)) ((list x) `(values ,x)) (otherwise (if (<= (length values) 8) `(sort-values/network ,gpred ,@values) `(sort-values/temp-vector ,gpred ,@values))))))) (defun expand-variadic-equality (binary variadic args) (match args (() t) ((list x) `(progn ,x t)) ((list x y) `(,binary ,x ,y)) ((list x y z) (once-only (x y z) `(and (,binary ,x ,y) (,binary ,y ,z)))) (otherwise (let ((temps (make-gensym-list (length args)))) (destructuring-bind (x y . zs) temps `(let ,(mapcar #'list temps args) (and (,binary ,x ,y) (,variadic ,y ,@zs)))))))) (defmacro define-variadic-equality (variadic binary) `(progn (defun ,variadic (&rest xs) ,(format nil "Variadic version of `~(~a~)'. With no arguments, return T. With one argument, return T. With two arguments, same as `~:*~(~a~)'. With three or more arguments, return T only if all of XS are equivalent under `~:*~(~a~)'. Has a compiler macro, so there is no loss of efficiency relative to writing out the tests by hand." binary) (match xs (() t) ((list _) t) ((list x y) (,binary x y)) (otherwise (every #',binary xs (rest xs))))) (define-compiler-macro ,variadic (&rest xs) (expand-variadic-equality ',binary ',variadic xs)))) (define-variadic-equality eq* eq) (define-variadic-equality eql* eql) (define-variadic-equality equal* equal) (define-variadic-equality equalp* equalp) (define-condition recursion-forbidden (error) ((form :initarg :form)) (:report (lambda (c s) (with-slots (form) c (format s "Forbidden recursion in form:~%~a" form))))) (defvar *recursions* nil) (defmacro without-recursion ((&key) &body body) "If BODY calls itself, at any depth, signal a (continuable) error of type `recursion-forbidden'." (with-unique-names (recursion-id) `(progn (when (member ',recursion-id *recursions*) (cerror "Recurse anyway." 'recursion-forbidden :form ',body)) (let ((*recursions* (cons ',recursion-id *recursions*))) (declare (dynamic-extent *recursions*)) ,@body))))
716dd7edc89401b395c3b5c0c782dbdb3ce09184a1fe593cbb99d4635b6173f7
Netflix/PigPen
functional_test.clj
;; ;; Copyright 2013 - 2015 Netflix , Inc. ;; Licensed under the Apache License , Version 2.0 ( the " License " ) ; ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; -2.0 ;; ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.functional-test (:refer-clojure :exclude [read])) (defprotocol TestHarness (data [this data] "Create mock input with specified data") (dump [this command] "Execute the command & return the results") (file [this] "Returns a new unique filename for writing results to") (read [this file] "Reads data from a file, returns a sequence of lines") (write [this lines] "Writes data to a file, returns the name of the file")) (defonce all-tests (atom [])) (defmacro deftest "Looks like defn, but defines a cross-platform test. Should take a single arg, which is a TestHarness. This should be used for all data creation and test execution." [name docstring params & body] {:pre [(symbol? name) (string? docstring) (vector? params) (nil? (next params)) body]} `(do (swap! all-tests conj '~(symbol (str (ns-name *ns*)) (str name))) (defn ~(symbol (clojure.core/name name)) ~docstring ~params ~@body)))
null
https://raw.githubusercontent.com/Netflix/PigPen/18d461d9b2ee6c1bb7eee7324889d32757fc7513/pigpen-core/src/test/clojure/pigpen/functional_test.clj
clojure
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright 2013 - 2015 Netflix , Inc. distributed under the License is distributed on an " AS IS " BASIS , (ns pigpen.functional-test (:refer-clojure :exclude [read])) (defprotocol TestHarness (data [this data] "Create mock input with specified data") (dump [this command] "Execute the command & return the results") (file [this] "Returns a new unique filename for writing results to") (read [this file] "Reads data from a file, returns a sequence of lines") (write [this lines] "Writes data to a file, returns the name of the file")) (defonce all-tests (atom [])) (defmacro deftest "Looks like defn, but defines a cross-platform test. Should take a single arg, which is a TestHarness. This should be used for all data creation and test execution." [name docstring params & body] {:pre [(symbol? name) (string? docstring) (vector? params) (nil? (next params)) body]} `(do (swap! all-tests conj '~(symbol (str (ns-name *ns*)) (str name))) (defn ~(symbol (clojure.core/name name)) ~docstring ~params ~@body)))
cb5c859743f2cddbee3a35f909622237da88cb2d9b80c4d9189fe4eaf3e347d3
rbkmoney/hellgate
hg_invoice_adjustment_tests_SUITE.erl
-module(hg_invoice_adjustment_tests_SUITE). -include("hg_ct_domain.hrl"). -include_lib("common_test/include/ct.hrl"). -include_lib("damsel/include/dmsl_payment_processing_thrift.hrl"). -include_lib("damsel/include/dmsl_payment_processing_errors_thrift.hrl"). -include_lib("stdlib/include/assert.hrl"). -export([all/0]). -export([groups/0]). -export([init_per_suite/1]). -export([end_per_suite/1]). -export([init_per_testcase/2]). -export([end_per_testcase/2]). -export([invoice_adjustment_capture/1]). -export([invoice_adjustment_capture_new/1]). -export([invoice_adjustment_cancel/1]). -export([invoice_adjustment_cancel_new/1]). -export([invoice_adjustment_existing_invoice_status/1]). -export([invoice_adjustment_existing_invoice_status_new/1]). -export([invoice_adjustment_invalid_invoice_status/1]). -export([invoice_adjustment_invalid_invoice_status_new/1]). -export([invoice_adjustment_invalid_adjustment_status/1]). -export([invoice_adjustment_invalid_adjustment_status_new/1]). -export([invoice_adjustment_payment_pending/1]). -export([invoice_adjustment_payment_pending_new/1]). -export([invoice_adjustment_pending_blocks_payment/1]). -export([invoice_adjustment_pending_blocks_payment_new/1]). -export([invoice_adjustment_pending_no_invoice_expiration/1]). -export([invoice_adjustment_invoice_expiration_after_capture/1]). -export([invoice_adjustment_invoice_expiration_after_capture_new/1]). -behaviour(supervisor). -export([init/1]). -spec init([]) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}. init([]) -> {ok, {#{strategy => one_for_all, intensity => 1, period => 1}, []}}. %% tests descriptions -type config() :: hg_ct_helper:config(). -type test_case_name() :: hg_ct_helper:test_case_name(). -type group_name() :: hg_ct_helper:group_name(). -type test_return() :: _ | no_return(). cfg(Key, C) -> hg_ct_helper:cfg(Key, C). -spec all() -> [test_case_name() | {group, group_name()}]. all() -> [ {group, all_tests} ]. -spec groups() -> [{group_name(), list(), [test_case_name()]}]. groups() -> [ {all_tests, [parallel], [ invoice_adjustment_capture, invoice_adjustment_capture_new, invoice_adjustment_cancel, invoice_adjustment_cancel_new, invoice_adjustment_existing_invoice_status, invoice_adjustment_existing_invoice_status_new, invoice_adjustment_invalid_invoice_status, invoice_adjustment_invalid_invoice_status_new, invoice_adjustment_invalid_adjustment_status, invoice_adjustment_invalid_adjustment_status_new, invoice_adjustment_payment_pending, invoice_adjustment_payment_pending_new, invoice_adjustment_pending_blocks_payment, invoice_adjustment_pending_blocks_payment_new, invoice_adjustment_pending_no_invoice_expiration, invoice_adjustment_invoice_expiration_after_capture_new, invoice_adjustment_invoice_expiration_after_capture ]} ]. %% starting/stopping -spec init_per_suite(config()) -> config(). init_per_suite(C) -> % _ = dbg:tracer(), % _ = dbg:p(all, c), % _ = dbg:tpl({'hg_invoice_payment', 'p', '_'}, x), CowboySpec = hg_dummy_provider:get_http_cowboy_spec(), {Apps, Ret} = hg_ct_helper:start_apps([woody, scoper, dmt_client, party_client, hellgate, {cowboy, CowboySpec}]), _ = hg_domain:insert(construct_domain_fixture()), RootUrl = maps:get(hellgate_root_url, Ret), PartyID = hg_utils:unique_id(), PartyClient = {party_client:create_client(), party_client:create_context(user_info())}, ShopID = hg_ct_helper:create_party_and_shop(PartyID, ?cat(1), <<"RUB">>, ?tmpl(1), ?pinst(1), PartyClient), {ok, SupPid} = supervisor:start_link(?MODULE, []), _ = unlink(SupPid), NewC = [ {party_id, PartyID}, {shop_id, ShopID}, {root_url, RootUrl}, {apps, Apps}, {test_sup, SupPid} | C ], ok = start_proxies([{hg_dummy_provider, 1, NewC}, {hg_dummy_inspector, 2, NewC}]), NewC. user_info() -> #{user_info => #{id => <<"test">>, realm => <<"service">>}}. -spec end_per_suite(config()) -> _. end_per_suite(C) -> _ = hg_domain:cleanup(), _ = [application:stop(App) || App <- cfg(apps, C)], exit(cfg(test_sup, C), shutdown). -spec init_per_testcase(test_case_name(), config()) -> config(). init_per_testcase(_Name, C) -> init_per_testcase(C). init_per_testcase(C) -> ApiClient = hg_ct_helper:create_client(cfg(root_url, C), cfg(party_id, C)), Client = hg_client_invoicing:start_link(ApiClient), ClientTpl = hg_client_invoice_templating:start_link(ApiClient), ok = hg_context:save(hg_context:create()), [{client, Client}, {client_tpl, ClientTpl} | C]. -spec end_per_testcase(test_case_name(), config()) -> _. end_per_testcase(_Name, _C) -> ok = hg_context:cleanup(). -include("invoice_events.hrl"). -include("payment_events.hrl"). -include("customer_events.hrl"). -define(invoice(ID), #domain_Invoice{id = ID}). -define(payment(ID), #domain_InvoicePayment{id = ID}). -define(invoice_state(Invoice), #payproc_Invoice{invoice = Invoice}). -define(payment_state(Payment), #payproc_InvoicePayment{payment = Payment}). -define(payment_w_status(Status), #domain_InvoicePayment{status = Status}). -define(trx_info(ID), #domain_TransactionInfo{id = ID}). -define(merchant_to_system_share_1, ?share(45, 1000, operation_amount)). -define(merchant_to_system_share_2, ?share(100, 1000, operation_amount)). %% ADJ -spec invoice_adjustment_capture(config()) -> test_return(). invoice_adjustment_capture(C) -> invoice_adjustment_capture(C, visa). -spec invoice_adjustment_capture_new(config()) -> test_return(). invoice_adjustment_capture_new(C) -> invoice_adjustment_capture(C, ?pmt_sys(<<"visa-ref">>)). invoice_adjustment_capture(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_due_date(10), make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_Invoice)] = next_event(InvoiceID, Client), PaymentID = process_payment(InvoiceID, make_payment_params(PmtSys), Client), PaymentID = await_payment_capture(InvoiceID, PaymentID, Client), Unpaid = {unpaid, #domain_InvoiceUnpaid{}}, AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = Unpaid }} }, Adjustment = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch({pending, #domain_InvoiceAdjustmentPending{}}, Adjustment#domain_InvoiceAdjustment.status), [?invoice_adjustment_ev(ID, ?invoice_adjustment_created(Adjustment))] = next_event(InvoiceID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Processed))] = next_event(InvoiceID, Client), ?assertMatch({processed, #domain_InvoiceAdjustmentProcessed{}}, Processed), ok = hg_client_invoicing:capture_invoice_adjustment(InvoiceID, ID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Captured))] = next_event(InvoiceID, Client), ?assertMatch({captured, #domain_InvoiceAdjustmentCaptured{}}, Captured), #payproc_Invoice{invoice = #domain_Invoice{status = FinalStatus}} = hg_client_invoicing:get(InvoiceID, Client), ?assertMatch(Unpaid, FinalStatus). -spec invoice_adjustment_cancel(config()) -> test_return(). invoice_adjustment_cancel(C) -> invoice_adjustment_cancel(C, visa). -spec invoice_adjustment_cancel_new(config()) -> test_return(). invoice_adjustment_cancel_new(C) -> invoice_adjustment_cancel(C, ?pmt_sys(<<"visa-ref">>)). invoice_adjustment_cancel(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_)] = next_event(InvoiceID, Client), PaymentID = process_payment(InvoiceID, make_payment_params(PmtSys), Client), PaymentID = await_payment_capture(InvoiceID, PaymentID, Client), #payproc_Invoice{invoice = #domain_Invoice{status = InvoiceStatus}} = hg_client_invoicing:get(InvoiceID, Client), TargetInvoiceStatus = {unpaid, #domain_InvoiceUnpaid{}}, AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = TargetInvoiceStatus }} }, Adjustment = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch({pending, #domain_InvoiceAdjustmentPending{}}, Adjustment#domain_InvoiceAdjustment.status), [?invoice_adjustment_ev(ID, ?invoice_adjustment_created(Adjustment))] = next_event(InvoiceID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Processed))] = next_event(InvoiceID, Client), ?assertMatch({processed, #domain_InvoiceAdjustmentProcessed{}}, Processed), ok = hg_client_invoicing:cancel_invoice_adjustment(InvoiceID, ID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Cancelled))] = next_event(InvoiceID, Client), ?assertMatch({cancelled, #domain_InvoiceAdjustmentCancelled{}}, Cancelled), #payproc_Invoice{invoice = #domain_Invoice{status = FinalStatus}} = hg_client_invoicing:get(InvoiceID, Client), ?assertMatch(InvoiceStatus, FinalStatus). -spec invoice_adjustment_invalid_invoice_status(config()) -> test_return(). invoice_adjustment_invalid_invoice_status(C) -> invoice_adjustment_invalid_invoice_status(C, visa). -spec invoice_adjustment_invalid_invoice_status_new(config()) -> test_return(). invoice_adjustment_invalid_invoice_status_new(C) -> invoice_adjustment_invalid_invoice_status(C, ?pmt_sys(<<"visa-ref">>)). invoice_adjustment_invalid_invoice_status(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_)] = next_event(InvoiceID, Client), PaymentID = process_payment(InvoiceID, make_payment_params(PmtSys), Client), PaymentID = await_payment_capture(InvoiceID, PaymentID, Client), AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = {unpaid, #domain_InvoiceUnpaid{}} }} }, ok = hg_client_invoicing:fulfill(InvoiceID, <<"ok">>, Client), {exception, E} = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch(#payproc_InvoiceAdjustmentStatusUnacceptable{}, E). -spec invoice_adjustment_existing_invoice_status(config()) -> test_return(). invoice_adjustment_existing_invoice_status(C) -> invoice_adjustment_existing_invoice_status(C, visa). -spec invoice_adjustment_existing_invoice_status_new(config()) -> test_return(). invoice_adjustment_existing_invoice_status_new(C) -> invoice_adjustment_existing_invoice_status(C, ?pmt_sys(<<"visa-ref">>)). invoice_adjustment_existing_invoice_status(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_)] = next_event(InvoiceID, Client), PaymentID = process_payment(InvoiceID, make_payment_params(PmtSys), Client), PaymentID = await_payment_capture(InvoiceID, PaymentID, Client), Paid = {paid, #domain_InvoicePaid{}}, AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = Paid }} }, {exception, E} = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch(#payproc_InvoiceAlreadyHasStatus{status = Paid}, E). -spec invoice_adjustment_invalid_adjustment_status(config()) -> test_return(). invoice_adjustment_invalid_adjustment_status(C) -> invoice_adjustment_invalid_adjustment_status(C, visa). -spec invoice_adjustment_invalid_adjustment_status_new(config()) -> test_return(). invoice_adjustment_invalid_adjustment_status_new(C) -> invoice_adjustment_invalid_adjustment_status(C, ?pmt_sys(<<"visa-ref">>)). invoice_adjustment_invalid_adjustment_status(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_)] = next_event(InvoiceID, Client), PaymentID = process_payment(InvoiceID, make_payment_params(PmtSys), Client), PaymentID = await_payment_capture(InvoiceID, PaymentID, Client), #payproc_Invoice{invoice = #domain_Invoice{status = InvoiceStatus}} = hg_client_invoicing:get(InvoiceID, Client), AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = {cancelled, #domain_InvoiceCancelled{details = <<"hulk smash">>}} }} }, Adjustment = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch({pending, #domain_InvoiceAdjustmentPending{}}, Adjustment#domain_InvoiceAdjustment.status), [?invoice_adjustment_ev(ID, ?invoice_adjustment_created(Adjustment))] = next_event(InvoiceID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Processed))] = next_event(InvoiceID, Client), ?assertMatch({processed, #domain_InvoiceAdjustmentProcessed{}}, Processed), ok = hg_client_invoicing:cancel_invoice_adjustment(InvoiceID, ID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Cancelled))] = next_event(InvoiceID, Client), ?assertMatch({cancelled, #domain_InvoiceAdjustmentCancelled{}}, Cancelled), #payproc_Invoice{invoice = #domain_Invoice{status = FinalStatus}} = hg_client_invoicing:get(InvoiceID, Client), ?assertMatch(InvoiceStatus, FinalStatus), {exception, E} = hg_client_invoicing:cancel_invoice_adjustment(InvoiceID, ID, Client), ?assertMatch(#payproc_InvalidInvoiceAdjustmentStatus{status = Cancelled}, E). -spec invoice_adjustment_payment_pending(config()) -> test_return(). invoice_adjustment_payment_pending(C) -> invoice_adjustment_payment_pending(C, visa). -spec invoice_adjustment_payment_pending_new(config()) -> test_return(). invoice_adjustment_payment_pending_new(C) -> invoice_adjustment_payment_pending(C, ?pmt_sys(<<"visa-ref">>)). invoice_adjustment_payment_pending(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_due_date(10), make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_)] = next_event(InvoiceID, Client), PaymentID = start_payment(InvoiceID, make_tds_payment_params(instant, PmtSys), Client), Paid = {paid, #domain_InvoicePaid{}}, AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = Paid }} }, {exception, E} = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch(#payproc_InvoicePaymentPending{id = PaymentID}, E), UserInteraction = await_payment_process_interaction(InvoiceID, PaymentID, Client), {URL, GoodForm} = get_post_request(UserInteraction), _ = assert_success_post_request({URL, GoodForm}), PaymentID = await_payment_process_finish(InvoiceID, PaymentID, Client), PaymentID = await_payment_capture(InvoiceID, PaymentID, Client). -spec invoice_adjustment_pending_blocks_payment(config()) -> test_return(). invoice_adjustment_pending_blocks_payment(C) -> invoice_adjustment_pending_blocks_payment(C, visa). -spec invoice_adjustment_pending_blocks_payment_new(config()) -> test_return(). invoice_adjustment_pending_blocks_payment_new(C) -> invoice_adjustment_pending_blocks_payment(C, visa). invoice_adjustment_pending_blocks_payment(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_Invoice)] = next_event(InvoiceID, Client), PaymentParams = make_payment_params({hold, capture}, PmtSys), PaymentID = process_payment(InvoiceID, PaymentParams, Client), Cash = ?cash(10, <<"RUB">>), Reason = <<"ok">>, TargetInvoiceStatus = {cancelled, #domain_InvoiceCancelled{details = <<"hulk smash">>}}, AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = TargetInvoiceStatus }} }, ok = hg_client_invoicing:capture_payment(InvoiceID, PaymentID, Reason, Cash, Client), PaymentID = await_payment_partial_capture(InvoiceID, PaymentID, Reason, Cash, Client), Adjustment = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch({pending, #domain_InvoiceAdjustmentPending{}}, Adjustment#domain_InvoiceAdjustment.status), [?invoice_adjustment_ev(ID, ?invoice_adjustment_created(Adjustment))] = next_event(InvoiceID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Processed))] = next_event(InvoiceID, Client), ?assertMatch({processed, #domain_InvoiceAdjustmentProcessed{}}, Processed), {exception, E} = hg_client_invoicing:start_payment(InvoiceID, PaymentParams, Client), ?assertMatch(#payproc_InvoiceAdjustmentPending{id = ID}, E). -spec invoice_adjustment_pending_no_invoice_expiration(config()) -> test_return(). invoice_adjustment_pending_no_invoice_expiration(C) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_due_date(5), make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_)] = next_event(InvoiceID, Client), Paid = {paid, #domain_InvoicePaid{}}, AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = Paid }} }, Adjustment = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_created(Adjustment))] = next_event(InvoiceID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(_Processed))] = next_event(InvoiceID, Client), timeout = next_event(InvoiceID, 6000, Client). -spec invoice_adjustment_invoice_expiration_after_capture(config()) -> test_return(). invoice_adjustment_invoice_expiration_after_capture(C) -> invoice_adjustment_invoice_expiration_after_capture(C, visa). -spec invoice_adjustment_invoice_expiration_after_capture_new(config()) -> test_return(). invoice_adjustment_invoice_expiration_after_capture_new(C) -> invoice_adjustment_invoice_expiration_after_capture(C, ?pmt_sys(<<"visa-ref">>)). invoice_adjustment_invoice_expiration_after_capture(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_due_date(10), make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_)] = next_event(InvoiceID, Client), Context = #'Content'{ type = <<"application/x-erlang-binary">>, data = erlang:term_to_binary({you, 643, "not", [<<"welcome">>, here]}) }, PaymentParams = set_payment_context(Context, make_payment_params(PmtSys)), PaymentID = process_payment(InvoiceID, PaymentParams, Client), PaymentID = await_payment_capture(InvoiceID, PaymentID, Client), Unpaid = {unpaid, #domain_InvoiceUnpaid{}}, AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = Unpaid }} }, Adjustment = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch({pending, #domain_InvoiceAdjustmentPending{}}, Adjustment#domain_InvoiceAdjustment.status), [?invoice_adjustment_ev(ID, ?invoice_adjustment_created(Adjustment))] = next_event(InvoiceID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Processed))] = next_event(InvoiceID, Client), ?assertMatch({processed, #domain_InvoiceAdjustmentProcessed{}}, Processed), ok = hg_client_invoicing:capture_invoice_adjustment(InvoiceID, ID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Captured))] = next_event(InvoiceID, Client), ?assertMatch({captured, #domain_InvoiceAdjustmentCaptured{}}, Captured), #payproc_Invoice{invoice = #domain_Invoice{status = Unpaid}} = hg_client_invoicing:get(InvoiceID, Client), [?invoice_status_changed(?invoice_cancelled(_))] = next_event(InvoiceID, Client). %% ADJ -spec construct_domain_fixture() -> [hg_domain:object()]. construct_domain_fixture() -> TestTermSet = #domain_TermSet{ payments = #domain_PaymentsServiceTerms{ currencies = {value, ?ordset([ ?cur(<<"RUB">>) ])}, categories = {value, ?ordset([ ?cat(1) ])}, payment_methods = {decisions, [ #domain_PaymentMethodDecision{ if_ = {constant, true}, then_ = {value, ?ordset([ ?pmt(bank_card, ?bank_card(<<"visa-ref">>)), ?pmt(bank_card_deprecated, visa) ])} } ]}, cash_limit = {decisions, [ #domain_CashLimitDecision{ if_ = {condition, {currency_is, ?cur(<<"RUB">>)}}, then_ = {value, ?cashrng( {inclusive, ?cash(10, <<"RUB">>)}, {exclusive, ?cash(420000000, <<"RUB">>)} )} } ]}, fees = {decisions, [ #domain_CashFlowDecision{ if_ = {condition, {payment_tool, {bank_card, #domain_BankCardCondition{ definition = {category_is, ?bc_cat(1)} }}}}, then_ = {value, [ ?cfpost( {merchant, settlement}, {system, settlement}, ?merchant_to_system_share_2 ) ]} }, #domain_CashFlowDecision{ if_ = {condition, {currency_is, ?cur(<<"RUB">>)}}, then_ = {value, [ ?cfpost( {merchant, settlement}, {system, settlement}, ?merchant_to_system_share_1 ) ]} } ]}, holds = #domain_PaymentHoldsServiceTerms{ payment_methods = {value, ?ordset([ ?pmt(bank_card, ?bank_card(<<"visa-ref">>)), ?pmt(bank_card_deprecated, visa) ])}, lifetime = {decisions, [ #domain_HoldLifetimeDecision{ if_ = {condition, {currency_is, ?cur(<<"RUB">>)}}, then_ = {value, #domain_HoldLifetime{seconds = 10}} } ]} }, refunds = #domain_PaymentRefundsServiceTerms{ payment_methods = {value, ?ordset([ ?pmt(bank_card, ?bank_card(<<"visa-ref">>)), ?pmt(bank_card_deprecated, visa) ])}, fees = {value, [ ?cfpost( {merchant, settlement}, {system, settlement}, ?fixed(100, <<"RUB">>) ) ]}, eligibility_time = {value, #'TimeSpan'{minutes = 1}}, partial_refunds = #domain_PartialRefundsServiceTerms{ cash_limit = {decisions, [ #domain_CashLimitDecision{ if_ = {condition, {currency_is, ?cur(<<"RUB">>)}}, then_ = {value, ?cashrng( {inclusive, ?cash(1000, <<"RUB">>)}, {exclusive, ?cash(1000000000, <<"RUB">>)} )} } ]} } } }, recurrent_paytools = #domain_RecurrentPaytoolsServiceTerms{ payment_methods = {value, ordsets:from_list([ ?pmt(bank_card, ?bank_card(<<"visa-ref">>)), ?pmt(bank_card_deprecated, visa) ])} } }, [ hg_ct_fixture:construct_bank_card_category( ?bc_cat(1), <<"Bank card category">>, <<"Corporative">>, [<<"*CORPORAT*">>] ), hg_ct_fixture:construct_currency(?cur(<<"RUB">>)), hg_ct_fixture:construct_category(?cat(1), <<"Test category">>, test), hg_ct_fixture:construct_payment_method(?pmt(bank_card_deprecated, visa)), hg_ct_fixture:construct_payment_method(?pmt(bank_card, ?bank_card(<<"visa-ref">>))), hg_ct_fixture:construct_proxy(?prx(1), <<"Dummy proxy">>), hg_ct_fixture:construct_proxy(?prx(2), <<"Inspector proxy">>), hg_ct_fixture:construct_inspector(?insp(1), <<"Rejector">>, ?prx(2), #{<<"risk_score">> => <<"low">>}), hg_ct_fixture:construct_contract_template(?tmpl(1), ?trms(1)), hg_ct_fixture:construct_system_account_set(?sas(1)), hg_ct_fixture:construct_external_account_set(?eas(1)), {payment_institution, #domain_PaymentInstitutionObject{ ref = ?pinst(1), data = #domain_PaymentInstitution{ name = <<"Test Inc.">>, system_account_set = {value, ?sas(1)}, default_contract_template = {value, ?tmpl(1)}, payment_routing_rules = #domain_RoutingRules{ policies = ?ruleset(2), prohibitions = ?ruleset(1) }, inspector = {decisions, [ #domain_InspectorDecision{ if_ = {condition, {currency_is, ?cur(<<"RUB">>)}}, then_ = {decisions, [ #domain_InspectorDecision{ if_ = {condition, {cost_in, ?cashrng( {inclusive, ?cash(0, <<"RUB">>)}, {exclusive, ?cash(500000, <<"RUB">>)} )}}, then_ = {value, ?insp(1)} } ]} } ]}, residences = [], realm = test } }}, {routing_rules, #domain_RoutingRulesObject{ ref = ?ruleset(1), data = #domain_RoutingRuleset{ name = <<"Prohibitions: all is allow">>, decisions = {candidates, []} } }}, {routing_rules, #domain_RoutingRulesObject{ ref = ?ruleset(2), data = #domain_RoutingRuleset{ name = <<"Prohibitions: all is allow">>, decisions = {candidates, [ ?candidate({constant, true}, ?trm(1)) ]} } }}, {globals, #domain_GlobalsObject{ ref = #domain_GlobalsRef{}, data = #domain_Globals{ external_account_set = {decisions, [ #domain_ExternalAccountSetDecision{ if_ = {constant, true}, then_ = {value, ?eas(1)} } ]}, payment_institutions = ?ordset([?pinst(1)]) } }}, {term_set_hierarchy, #domain_TermSetHierarchyObject{ ref = ?trms(1), data = #domain_TermSetHierarchy{ term_sets = [ #domain_TimedTermSet{ action_time = #'TimestampInterval'{}, terms = TestTermSet } ] } }}, {provider, #domain_ProviderObject{ ref = ?prv(1), data = #domain_Provider{ name = <<"Brovider">>, description = <<"A provider but bro">>, proxy = #domain_Proxy{ ref = ?prx(1), additional = #{ <<"override">> => <<"brovider">> } }, abs_account = <<"1234567890">>, accounts = hg_ct_fixture:construct_provider_account_set([?cur(<<"RUB">>)]), terms = #domain_ProvisionTermSet{ payments = #domain_PaymentsProvisionTerms{ currencies = {value, ?ordset([ ?cur(<<"RUB">>) ])}, categories = {value, ?ordset([ ?cat(1) ])}, payment_methods = {value, ?ordset([ ?pmt(bank_card, ?bank_card(<<"visa-ref">>)), ?pmt(bank_card_deprecated, visa) ])}, cash_limit = {value, ?cashrng( {inclusive, ?cash(1000, <<"RUB">>)}, {exclusive, ?cash(1000000000, <<"RUB">>)} )}, cash_flow = {decisions, [ #domain_CashFlowDecision{ if_ = {condition, {payment_tool, {bank_card, #domain_BankCardCondition{ definition = {payment_system, #domain_PaymentSystemCondition{ payment_system_is = ?pmt_sys(<<"visa-ref">>) }} }}}}, then_ = {value, [ ?cfpost( {provider, settlement}, {merchant, settlement}, ?share(1, 1, operation_amount) ), ?cfpost( {system, settlement}, {provider, settlement}, ?share(18, 1000, operation_amount) ) ]} }, #domain_CashFlowDecision{ if_ = {condition, {payment_tool, {bank_card, #domain_BankCardCondition{ definition = {payment_system_is, visa} }}}}, then_ = {value, [ ?cfpost( {provider, settlement}, {merchant, settlement}, ?share(1, 1, operation_amount) ), ?cfpost( {system, settlement}, {provider, settlement}, ?share(18, 1000, operation_amount) ) ]} } ]}, holds = #domain_PaymentHoldsProvisionTerms{ lifetime = {decisions, [ #domain_HoldLifetimeDecision{ if_ = {condition, {payment_tool, {bank_card, #domain_BankCardCondition{ definition = {payment_system, #domain_PaymentSystemCondition{ payment_system_is = ?pmt_sys(<<"visa-ref">>) }} }}}}, then_ = {value, ?hold_lifetime(12)} }, #domain_HoldLifetimeDecision{ if_ = {condition, {payment_tool, {bank_card, #domain_BankCardCondition{ definition = {payment_system_is, visa} }}}}, then_ = {value, ?hold_lifetime(12)} } ]} }, refunds = #domain_PaymentRefundsProvisionTerms{ cash_flow = {value, [ ?cfpost( {merchant, settlement}, {provider, settlement}, ?share(1, 1, operation_amount) ) ]}, partial_refunds = #domain_PartialRefundsProvisionTerms{ cash_limit = {value, ?cashrng( {inclusive, ?cash(10, <<"RUB">>)}, {exclusive, ?cash(1000000000, <<"RUB">>)} )} } }, chargebacks = #domain_PaymentChargebackProvisionTerms{ cash_flow = {value, [ ?cfpost( {merchant, settlement}, {provider, settlement}, ?share(1, 1, operation_amount) ) ]} } }, recurrent_paytools = #domain_RecurrentPaytoolsProvisionTerms{ categories = {value, ?ordset([?cat(1)])}, payment_methods = {value, ?ordset([ ?pmt(bank_card, ?bank_card(<<"visa-ref">>)), ?pmt(bank_card_deprecated, visa) ])}, cash_value = {value, ?cash(1000, <<"RUB">>)} } } } }}, {terminal, #domain_TerminalObject{ ref = ?trm(1), data = #domain_Terminal{ name = <<"Brominal 1">>, description = <<"Brominal 1">>, risk_coverage = high, provider_ref = ?prv(1) } }}, hg_ct_fixture:construct_payment_system(?pmt_sys(<<"visa-ref">>), <<"visa payment system">>) ]. start_service_handler(Module, C, HandlerOpts) -> start_service_handler(Module, Module, C, HandlerOpts). start_service_handler(Name, Module, C, HandlerOpts) -> IP = "127.0.0.1", Port = get_random_port(), Opts = maps:merge(HandlerOpts, #{hellgate_root_url => cfg(root_url, C)}), ChildSpec = hg_test_proxy:get_child_spec(Name, Module, IP, Port, Opts), {ok, _} = supervisor:start_child(cfg(test_sup, C), ChildSpec), hg_test_proxy:get_url(Module, IP, Port). start_proxies(Proxies) -> setup_proxies( lists:map( fun Mapper({Module, ProxyID, Context}) -> Mapper({Module, ProxyID, #{}, Context}); Mapper({Module, ProxyID, ProxyOpts, Context}) -> construct_proxy(ProxyID, start_service_handler(Module, Context, #{}), ProxyOpts) end, Proxies ) ). setup_proxies(Proxies) -> _ = hg_domain:upsert(Proxies), ok. get_random_port() -> rand:uniform(32768) + 32767. construct_proxy(ID, Url, Options) -> {proxy, #domain_ProxyObject{ ref = ?prx(ID), data = #domain_ProxyDefinition{ name = Url, description = Url, url = Url, options = Options } }}. make_cash(Amount) -> hg_ct_helper:make_cash(Amount, <<"RUB">>). make_invoice_params(PartyID, ShopID, Product, Cost) -> hg_ct_helper:make_invoice_params(PartyID, ShopID, Product, Cost). make_invoice_params(PartyID, ShopID, Product, Due, Cost) -> hg_ct_helper:make_invoice_params(PartyID, ShopID, Product, Due, Cost). make_due_date(LifetimeSeconds) -> genlib_time:unow() + LifetimeSeconds. create_invoice(InvoiceParams, Client) -> ?invoice_state(?invoice(InvoiceID)) = hg_client_invoicing:create(InvoiceParams, Client), InvoiceID. next_event(InvoiceID, Client) -> timeout should be at least as large as hold expiration in next_event(InvoiceID, 12000, Client). next_event(InvoiceID, Timeout, Client) -> case hg_client_invoicing:pull_event(InvoiceID, Timeout, Client) of {ok, ?invoice_ev(Changes)} -> case filter_changes(Changes) of L when length(L) > 0 -> L; [] -> next_event(InvoiceID, Timeout, Client) end; Result -> Result end. filter_changes(Changes) -> lists:filtermap(fun filter_change/1, Changes). filter_change(?payment_ev(_, C)) -> filter_change(C); filter_change(?chargeback_ev(_, C)) -> filter_change(C); filter_change(?refund_ev(_, C)) -> filter_change(C); filter_change(?session_ev(_, ?proxy_st_changed(_))) -> false; filter_change(?session_ev(_, ?session_suspended(_, _))) -> false; filter_change(?session_ev(_, ?session_activated())) -> false; filter_change(_) -> true. set_payment_context(Context, Params = #payproc_InvoicePaymentParams{}) -> Params#payproc_InvoicePaymentParams{context = Context}. make_payment_params(PmtSys) -> make_payment_params(instant, PmtSys). make_payment_params(FlowType, PmtSys) -> {PaymentTool, Session} = hg_dummy_provider:make_payment_tool(no_preauth, PmtSys), make_payment_params(PaymentTool, Session, FlowType). make_tds_payment_params(FlowType, PmtSys) -> {PaymentTool, Session} = hg_dummy_provider:make_payment_tool(preauth_3ds, PmtSys), make_payment_params(PaymentTool, Session, FlowType). make_payment_params(PaymentTool, Session, FlowType) -> Flow = case FlowType of instant -> {instant, #payproc_InvoicePaymentParamsFlowInstant{}}; {hold, OnHoldExpiration} -> {hold, #payproc_InvoicePaymentParamsFlowHold{on_hold_expiration = OnHoldExpiration}} end, #payproc_InvoicePaymentParams{ payer = {payment_resource, #payproc_PaymentResourcePayerParams{ resource = #domain_DisposablePaymentResource{ payment_tool = PaymentTool, payment_session_id = Session, client_info = #domain_ClientInfo{} }, contact_info = #domain_ContactInfo{} }}, flow = Flow }. get_post_request({'redirect', {'post_request', #'BrowserPostRequest'{uri = URL, form = Form}}}) -> {URL, Form}; get_post_request({payment_terminal_reciept, #'PaymentTerminalReceipt'{short_payment_id = SPID}}) -> URL = hg_dummy_provider:get_callback_url(), {URL, #{<<"tag">> => SPID}}. start_payment(InvoiceID, PaymentParams, Client) -> ?payment_state(?payment(PaymentID)) = hg_client_invoicing:start_payment(InvoiceID, PaymentParams, Client), [ ?payment_ev(PaymentID, ?payment_started(?payment_w_status(?pending()))) ] = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?risk_score_changed(_)) ] = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?route_changed(_)) ] = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?cash_flow_changed(_)) ] = next_event(InvoiceID, Client), PaymentID. process_payment(InvoiceID, PaymentParams, Client) -> process_payment(InvoiceID, PaymentParams, Client, 0). process_payment(InvoiceID, PaymentParams, Client, Restarts) -> PaymentID = start_payment(InvoiceID, PaymentParams, Client), PaymentID = await_payment_session_started(InvoiceID, PaymentID, Client, ?processed()), PaymentID = await_payment_process_finish(InvoiceID, PaymentID, Client, Restarts). await_payment_session_started(InvoiceID, PaymentID, Client, Target) -> [ ?payment_ev(PaymentID, ?session_ev(Target, ?session_started())) ] = next_event(InvoiceID, Client), PaymentID. await_payment_process_finish(InvoiceID, PaymentID, Client) -> await_payment_process_finish(InvoiceID, PaymentID, Client, 0). await_payment_process_finish(InvoiceID, PaymentID, Client, Restarts) -> PaymentID = await_sessions_restarts(PaymentID, ?processed(), InvoiceID, Client, Restarts), [ ?payment_ev(PaymentID, ?session_ev(?processed(), ?trx_bound(?trx_info(_)))), ?payment_ev(PaymentID, ?session_ev(?processed(), ?session_finished(?session_succeeded()))) ] = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?payment_status_changed(?processed())) ] = next_event(InvoiceID, Client), PaymentID. get_payment_cost(InvoiceID, PaymentID, Client) -> #payproc_InvoicePayment{ payment = #domain_InvoicePayment{cost = Cost} } = hg_client_invoicing:get_payment(InvoiceID, PaymentID, Client), Cost. await_payment_capture(InvoiceID, PaymentID, Client) -> await_payment_capture(InvoiceID, PaymentID, ?timeout_reason(), Client). await_payment_capture(InvoiceID, PaymentID, Reason, Client) -> await_payment_capture(InvoiceID, PaymentID, Reason, Client, 0). await_payment_capture(InvoiceID, PaymentID, Reason, Client, Restarts) -> Cost = get_payment_cost(InvoiceID, PaymentID, Client), [ ?payment_ev(PaymentID, ?payment_capture_started(Reason, Cost, _, _Allocation)), ?payment_ev(PaymentID, ?session_ev(?captured(Reason, Cost), ?session_started())) ] = next_event(InvoiceID, Client), await_payment_capture_finish(InvoiceID, PaymentID, Reason, Client, Restarts). await_payment_partial_capture(InvoiceID, PaymentID, Reason, Cash, Client) -> await_payment_partial_capture(InvoiceID, PaymentID, Reason, Cash, Client, 0). await_payment_partial_capture(InvoiceID, PaymentID, Reason, Cash, Client, Restarts) -> [ ?payment_ev(PaymentID, ?payment_capture_started(Reason, Cash, _, _Allocation)), ?payment_ev(PaymentID, ?cash_flow_changed(_)) ] = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?session_ev(?captured(Reason, Cash), ?session_started())) ] = next_event(InvoiceID, Client), await_payment_capture_finish(InvoiceID, PaymentID, Reason, Client, Restarts, Cash). await_payment_capture_finish(InvoiceID, PaymentID, Reason, Client, Restarts) -> Cost = get_payment_cost(InvoiceID, PaymentID, Client), await_payment_capture_finish(InvoiceID, PaymentID, Reason, Client, Restarts, Cost). await_payment_capture_finish(InvoiceID, PaymentID, Reason, Client, Restarts, Cost) -> await_payment_capture_finish(InvoiceID, PaymentID, Reason, Client, Restarts, Cost, undefined). await_payment_capture_finish(InvoiceID, PaymentID, Reason, Client, Restarts, Cost, Cart) -> Target = ?captured(Reason, Cost, Cart), PaymentID = await_sessions_restarts(PaymentID, Target, InvoiceID, Client, Restarts), [ ?payment_ev(PaymentID, ?session_ev(Target, ?session_finished(?session_succeeded()))) ] = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?payment_status_changed(Target)), ?invoice_status_changed(?invoice_paid()) ] = next_event(InvoiceID, Client), PaymentID. await_payment_process_interaction(InvoiceID, PaymentID, Client) -> Events0 = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?session_ev(?processed(), ?session_started())) ] = Events0, Events1 = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?session_ev(?processed(), ?interaction_requested(UserInteraction))) ] = Events1, UserInteraction. -dialyzer({no_match, await_sessions_restarts/5}). await_sessions_restarts(PaymentID, _Target, _InvoiceID, _Client, 0) -> PaymentID; await_sessions_restarts(PaymentID, ?refunded() = Target, InvoiceID, Client, Restarts) when Restarts > 0 -> [ ?payment_ev(PaymentID, ?refund_ev(_, ?session_ev(Target, ?session_finished(?session_failed(_))))), ?payment_ev(PaymentID, ?refund_ev(_, ?session_ev(Target, ?session_started()))) ] = next_event(InvoiceID, Client), await_sessions_restarts(PaymentID, Target, InvoiceID, Client, Restarts - 1); await_sessions_restarts(PaymentID, Target, InvoiceID, Client, Restarts) when Restarts > 0 -> [ ?payment_ev(PaymentID, ?session_ev(Target, ?session_finished(?session_failed(_)))), ?payment_ev(PaymentID, ?session_ev(Target, ?session_started())) ] = next_event(InvoiceID, Client), await_sessions_restarts(PaymentID, Target, InvoiceID, Client, Restarts - 1). assert_success_post_request(Req) -> {ok, 200, _RespHeaders, _ClientRef} = post_request(Req). post_request({URL, Form}) -> Method = post, Headers = [], Body = {form, maps:to_list(Form)}, hackney:request(Method, URL, Headers, Body).
null
https://raw.githubusercontent.com/rbkmoney/hellgate/e1932c161a7c1fd9830cfcd42de5154229b74686/apps/hellgate/test/hg_invoice_adjustment_tests_SUITE.erl
erlang
tests descriptions starting/stopping _ = dbg:tracer(), _ = dbg:p(all, c), _ = dbg:tpl({'hg_invoice_payment', 'p', '_'}, x), ADJ ADJ
-module(hg_invoice_adjustment_tests_SUITE). -include("hg_ct_domain.hrl"). -include_lib("common_test/include/ct.hrl"). -include_lib("damsel/include/dmsl_payment_processing_thrift.hrl"). -include_lib("damsel/include/dmsl_payment_processing_errors_thrift.hrl"). -include_lib("stdlib/include/assert.hrl"). -export([all/0]). -export([groups/0]). -export([init_per_suite/1]). -export([end_per_suite/1]). -export([init_per_testcase/2]). -export([end_per_testcase/2]). -export([invoice_adjustment_capture/1]). -export([invoice_adjustment_capture_new/1]). -export([invoice_adjustment_cancel/1]). -export([invoice_adjustment_cancel_new/1]). -export([invoice_adjustment_existing_invoice_status/1]). -export([invoice_adjustment_existing_invoice_status_new/1]). -export([invoice_adjustment_invalid_invoice_status/1]). -export([invoice_adjustment_invalid_invoice_status_new/1]). -export([invoice_adjustment_invalid_adjustment_status/1]). -export([invoice_adjustment_invalid_adjustment_status_new/1]). -export([invoice_adjustment_payment_pending/1]). -export([invoice_adjustment_payment_pending_new/1]). -export([invoice_adjustment_pending_blocks_payment/1]). -export([invoice_adjustment_pending_blocks_payment_new/1]). -export([invoice_adjustment_pending_no_invoice_expiration/1]). -export([invoice_adjustment_invoice_expiration_after_capture/1]). -export([invoice_adjustment_invoice_expiration_after_capture_new/1]). -behaviour(supervisor). -export([init/1]). -spec init([]) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}. init([]) -> {ok, {#{strategy => one_for_all, intensity => 1, period => 1}, []}}. -type config() :: hg_ct_helper:config(). -type test_case_name() :: hg_ct_helper:test_case_name(). -type group_name() :: hg_ct_helper:group_name(). -type test_return() :: _ | no_return(). cfg(Key, C) -> hg_ct_helper:cfg(Key, C). -spec all() -> [test_case_name() | {group, group_name()}]. all() -> [ {group, all_tests} ]. -spec groups() -> [{group_name(), list(), [test_case_name()]}]. groups() -> [ {all_tests, [parallel], [ invoice_adjustment_capture, invoice_adjustment_capture_new, invoice_adjustment_cancel, invoice_adjustment_cancel_new, invoice_adjustment_existing_invoice_status, invoice_adjustment_existing_invoice_status_new, invoice_adjustment_invalid_invoice_status, invoice_adjustment_invalid_invoice_status_new, invoice_adjustment_invalid_adjustment_status, invoice_adjustment_invalid_adjustment_status_new, invoice_adjustment_payment_pending, invoice_adjustment_payment_pending_new, invoice_adjustment_pending_blocks_payment, invoice_adjustment_pending_blocks_payment_new, invoice_adjustment_pending_no_invoice_expiration, invoice_adjustment_invoice_expiration_after_capture_new, invoice_adjustment_invoice_expiration_after_capture ]} ]. -spec init_per_suite(config()) -> config(). init_per_suite(C) -> CowboySpec = hg_dummy_provider:get_http_cowboy_spec(), {Apps, Ret} = hg_ct_helper:start_apps([woody, scoper, dmt_client, party_client, hellgate, {cowboy, CowboySpec}]), _ = hg_domain:insert(construct_domain_fixture()), RootUrl = maps:get(hellgate_root_url, Ret), PartyID = hg_utils:unique_id(), PartyClient = {party_client:create_client(), party_client:create_context(user_info())}, ShopID = hg_ct_helper:create_party_and_shop(PartyID, ?cat(1), <<"RUB">>, ?tmpl(1), ?pinst(1), PartyClient), {ok, SupPid} = supervisor:start_link(?MODULE, []), _ = unlink(SupPid), NewC = [ {party_id, PartyID}, {shop_id, ShopID}, {root_url, RootUrl}, {apps, Apps}, {test_sup, SupPid} | C ], ok = start_proxies([{hg_dummy_provider, 1, NewC}, {hg_dummy_inspector, 2, NewC}]), NewC. user_info() -> #{user_info => #{id => <<"test">>, realm => <<"service">>}}. -spec end_per_suite(config()) -> _. end_per_suite(C) -> _ = hg_domain:cleanup(), _ = [application:stop(App) || App <- cfg(apps, C)], exit(cfg(test_sup, C), shutdown). -spec init_per_testcase(test_case_name(), config()) -> config(). init_per_testcase(_Name, C) -> init_per_testcase(C). init_per_testcase(C) -> ApiClient = hg_ct_helper:create_client(cfg(root_url, C), cfg(party_id, C)), Client = hg_client_invoicing:start_link(ApiClient), ClientTpl = hg_client_invoice_templating:start_link(ApiClient), ok = hg_context:save(hg_context:create()), [{client, Client}, {client_tpl, ClientTpl} | C]. -spec end_per_testcase(test_case_name(), config()) -> _. end_per_testcase(_Name, _C) -> ok = hg_context:cleanup(). -include("invoice_events.hrl"). -include("payment_events.hrl"). -include("customer_events.hrl"). -define(invoice(ID), #domain_Invoice{id = ID}). -define(payment(ID), #domain_InvoicePayment{id = ID}). -define(invoice_state(Invoice), #payproc_Invoice{invoice = Invoice}). -define(payment_state(Payment), #payproc_InvoicePayment{payment = Payment}). -define(payment_w_status(Status), #domain_InvoicePayment{status = Status}). -define(trx_info(ID), #domain_TransactionInfo{id = ID}). -define(merchant_to_system_share_1, ?share(45, 1000, operation_amount)). -define(merchant_to_system_share_2, ?share(100, 1000, operation_amount)). -spec invoice_adjustment_capture(config()) -> test_return(). invoice_adjustment_capture(C) -> invoice_adjustment_capture(C, visa). -spec invoice_adjustment_capture_new(config()) -> test_return(). invoice_adjustment_capture_new(C) -> invoice_adjustment_capture(C, ?pmt_sys(<<"visa-ref">>)). invoice_adjustment_capture(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_due_date(10), make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_Invoice)] = next_event(InvoiceID, Client), PaymentID = process_payment(InvoiceID, make_payment_params(PmtSys), Client), PaymentID = await_payment_capture(InvoiceID, PaymentID, Client), Unpaid = {unpaid, #domain_InvoiceUnpaid{}}, AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = Unpaid }} }, Adjustment = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch({pending, #domain_InvoiceAdjustmentPending{}}, Adjustment#domain_InvoiceAdjustment.status), [?invoice_adjustment_ev(ID, ?invoice_adjustment_created(Adjustment))] = next_event(InvoiceID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Processed))] = next_event(InvoiceID, Client), ?assertMatch({processed, #domain_InvoiceAdjustmentProcessed{}}, Processed), ok = hg_client_invoicing:capture_invoice_adjustment(InvoiceID, ID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Captured))] = next_event(InvoiceID, Client), ?assertMatch({captured, #domain_InvoiceAdjustmentCaptured{}}, Captured), #payproc_Invoice{invoice = #domain_Invoice{status = FinalStatus}} = hg_client_invoicing:get(InvoiceID, Client), ?assertMatch(Unpaid, FinalStatus). -spec invoice_adjustment_cancel(config()) -> test_return(). invoice_adjustment_cancel(C) -> invoice_adjustment_cancel(C, visa). -spec invoice_adjustment_cancel_new(config()) -> test_return(). invoice_adjustment_cancel_new(C) -> invoice_adjustment_cancel(C, ?pmt_sys(<<"visa-ref">>)). invoice_adjustment_cancel(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_)] = next_event(InvoiceID, Client), PaymentID = process_payment(InvoiceID, make_payment_params(PmtSys), Client), PaymentID = await_payment_capture(InvoiceID, PaymentID, Client), #payproc_Invoice{invoice = #domain_Invoice{status = InvoiceStatus}} = hg_client_invoicing:get(InvoiceID, Client), TargetInvoiceStatus = {unpaid, #domain_InvoiceUnpaid{}}, AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = TargetInvoiceStatus }} }, Adjustment = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch({pending, #domain_InvoiceAdjustmentPending{}}, Adjustment#domain_InvoiceAdjustment.status), [?invoice_adjustment_ev(ID, ?invoice_adjustment_created(Adjustment))] = next_event(InvoiceID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Processed))] = next_event(InvoiceID, Client), ?assertMatch({processed, #domain_InvoiceAdjustmentProcessed{}}, Processed), ok = hg_client_invoicing:cancel_invoice_adjustment(InvoiceID, ID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Cancelled))] = next_event(InvoiceID, Client), ?assertMatch({cancelled, #domain_InvoiceAdjustmentCancelled{}}, Cancelled), #payproc_Invoice{invoice = #domain_Invoice{status = FinalStatus}} = hg_client_invoicing:get(InvoiceID, Client), ?assertMatch(InvoiceStatus, FinalStatus). -spec invoice_adjustment_invalid_invoice_status(config()) -> test_return(). invoice_adjustment_invalid_invoice_status(C) -> invoice_adjustment_invalid_invoice_status(C, visa). -spec invoice_adjustment_invalid_invoice_status_new(config()) -> test_return(). invoice_adjustment_invalid_invoice_status_new(C) -> invoice_adjustment_invalid_invoice_status(C, ?pmt_sys(<<"visa-ref">>)). invoice_adjustment_invalid_invoice_status(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_)] = next_event(InvoiceID, Client), PaymentID = process_payment(InvoiceID, make_payment_params(PmtSys), Client), PaymentID = await_payment_capture(InvoiceID, PaymentID, Client), AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = {unpaid, #domain_InvoiceUnpaid{}} }} }, ok = hg_client_invoicing:fulfill(InvoiceID, <<"ok">>, Client), {exception, E} = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch(#payproc_InvoiceAdjustmentStatusUnacceptable{}, E). -spec invoice_adjustment_existing_invoice_status(config()) -> test_return(). invoice_adjustment_existing_invoice_status(C) -> invoice_adjustment_existing_invoice_status(C, visa). -spec invoice_adjustment_existing_invoice_status_new(config()) -> test_return(). invoice_adjustment_existing_invoice_status_new(C) -> invoice_adjustment_existing_invoice_status(C, ?pmt_sys(<<"visa-ref">>)). invoice_adjustment_existing_invoice_status(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_)] = next_event(InvoiceID, Client), PaymentID = process_payment(InvoiceID, make_payment_params(PmtSys), Client), PaymentID = await_payment_capture(InvoiceID, PaymentID, Client), Paid = {paid, #domain_InvoicePaid{}}, AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = Paid }} }, {exception, E} = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch(#payproc_InvoiceAlreadyHasStatus{status = Paid}, E). -spec invoice_adjustment_invalid_adjustment_status(config()) -> test_return(). invoice_adjustment_invalid_adjustment_status(C) -> invoice_adjustment_invalid_adjustment_status(C, visa). -spec invoice_adjustment_invalid_adjustment_status_new(config()) -> test_return(). invoice_adjustment_invalid_adjustment_status_new(C) -> invoice_adjustment_invalid_adjustment_status(C, ?pmt_sys(<<"visa-ref">>)). invoice_adjustment_invalid_adjustment_status(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_)] = next_event(InvoiceID, Client), PaymentID = process_payment(InvoiceID, make_payment_params(PmtSys), Client), PaymentID = await_payment_capture(InvoiceID, PaymentID, Client), #payproc_Invoice{invoice = #domain_Invoice{status = InvoiceStatus}} = hg_client_invoicing:get(InvoiceID, Client), AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = {cancelled, #domain_InvoiceCancelled{details = <<"hulk smash">>}} }} }, Adjustment = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch({pending, #domain_InvoiceAdjustmentPending{}}, Adjustment#domain_InvoiceAdjustment.status), [?invoice_adjustment_ev(ID, ?invoice_adjustment_created(Adjustment))] = next_event(InvoiceID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Processed))] = next_event(InvoiceID, Client), ?assertMatch({processed, #domain_InvoiceAdjustmentProcessed{}}, Processed), ok = hg_client_invoicing:cancel_invoice_adjustment(InvoiceID, ID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Cancelled))] = next_event(InvoiceID, Client), ?assertMatch({cancelled, #domain_InvoiceAdjustmentCancelled{}}, Cancelled), #payproc_Invoice{invoice = #domain_Invoice{status = FinalStatus}} = hg_client_invoicing:get(InvoiceID, Client), ?assertMatch(InvoiceStatus, FinalStatus), {exception, E} = hg_client_invoicing:cancel_invoice_adjustment(InvoiceID, ID, Client), ?assertMatch(#payproc_InvalidInvoiceAdjustmentStatus{status = Cancelled}, E). -spec invoice_adjustment_payment_pending(config()) -> test_return(). invoice_adjustment_payment_pending(C) -> invoice_adjustment_payment_pending(C, visa). -spec invoice_adjustment_payment_pending_new(config()) -> test_return(). invoice_adjustment_payment_pending_new(C) -> invoice_adjustment_payment_pending(C, ?pmt_sys(<<"visa-ref">>)). invoice_adjustment_payment_pending(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_due_date(10), make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_)] = next_event(InvoiceID, Client), PaymentID = start_payment(InvoiceID, make_tds_payment_params(instant, PmtSys), Client), Paid = {paid, #domain_InvoicePaid{}}, AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = Paid }} }, {exception, E} = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch(#payproc_InvoicePaymentPending{id = PaymentID}, E), UserInteraction = await_payment_process_interaction(InvoiceID, PaymentID, Client), {URL, GoodForm} = get_post_request(UserInteraction), _ = assert_success_post_request({URL, GoodForm}), PaymentID = await_payment_process_finish(InvoiceID, PaymentID, Client), PaymentID = await_payment_capture(InvoiceID, PaymentID, Client). -spec invoice_adjustment_pending_blocks_payment(config()) -> test_return(). invoice_adjustment_pending_blocks_payment(C) -> invoice_adjustment_pending_blocks_payment(C, visa). -spec invoice_adjustment_pending_blocks_payment_new(config()) -> test_return(). invoice_adjustment_pending_blocks_payment_new(C) -> invoice_adjustment_pending_blocks_payment(C, visa). invoice_adjustment_pending_blocks_payment(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_Invoice)] = next_event(InvoiceID, Client), PaymentParams = make_payment_params({hold, capture}, PmtSys), PaymentID = process_payment(InvoiceID, PaymentParams, Client), Cash = ?cash(10, <<"RUB">>), Reason = <<"ok">>, TargetInvoiceStatus = {cancelled, #domain_InvoiceCancelled{details = <<"hulk smash">>}}, AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = TargetInvoiceStatus }} }, ok = hg_client_invoicing:capture_payment(InvoiceID, PaymentID, Reason, Cash, Client), PaymentID = await_payment_partial_capture(InvoiceID, PaymentID, Reason, Cash, Client), Adjustment = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch({pending, #domain_InvoiceAdjustmentPending{}}, Adjustment#domain_InvoiceAdjustment.status), [?invoice_adjustment_ev(ID, ?invoice_adjustment_created(Adjustment))] = next_event(InvoiceID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Processed))] = next_event(InvoiceID, Client), ?assertMatch({processed, #domain_InvoiceAdjustmentProcessed{}}, Processed), {exception, E} = hg_client_invoicing:start_payment(InvoiceID, PaymentParams, Client), ?assertMatch(#payproc_InvoiceAdjustmentPending{id = ID}, E). -spec invoice_adjustment_pending_no_invoice_expiration(config()) -> test_return(). invoice_adjustment_pending_no_invoice_expiration(C) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_due_date(5), make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_)] = next_event(InvoiceID, Client), Paid = {paid, #domain_InvoicePaid{}}, AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = Paid }} }, Adjustment = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_created(Adjustment))] = next_event(InvoiceID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(_Processed))] = next_event(InvoiceID, Client), timeout = next_event(InvoiceID, 6000, Client). -spec invoice_adjustment_invoice_expiration_after_capture(config()) -> test_return(). invoice_adjustment_invoice_expiration_after_capture(C) -> invoice_adjustment_invoice_expiration_after_capture(C, visa). -spec invoice_adjustment_invoice_expiration_after_capture_new(config()) -> test_return(). invoice_adjustment_invoice_expiration_after_capture_new(C) -> invoice_adjustment_invoice_expiration_after_capture(C, ?pmt_sys(<<"visa-ref">>)). invoice_adjustment_invoice_expiration_after_capture(C, PmtSys) -> Client = cfg(client, C), ShopID = cfg(shop_id, C), PartyID = cfg(party_id, C), InvoiceParams = make_invoice_params(PartyID, ShopID, <<"rubberduck">>, make_due_date(10), make_cash(10000)), InvoiceID = create_invoice(InvoiceParams, Client), [?invoice_created(_)] = next_event(InvoiceID, Client), Context = #'Content'{ type = <<"application/x-erlang-binary">>, data = erlang:term_to_binary({you, 643, "not", [<<"welcome">>, here]}) }, PaymentParams = set_payment_context(Context, make_payment_params(PmtSys)), PaymentID = process_payment(InvoiceID, PaymentParams, Client), PaymentID = await_payment_capture(InvoiceID, PaymentID, Client), Unpaid = {unpaid, #domain_InvoiceUnpaid{}}, AdjustmentParams = #payproc_InvoiceAdjustmentParams{ reason = <<"kek">>, scenario = {status_change, #domain_InvoiceAdjustmentStatusChange{ target_status = Unpaid }} }, Adjustment = hg_client_invoicing:create_invoice_adjustment(InvoiceID, AdjustmentParams, Client), ?assertMatch({pending, #domain_InvoiceAdjustmentPending{}}, Adjustment#domain_InvoiceAdjustment.status), [?invoice_adjustment_ev(ID, ?invoice_adjustment_created(Adjustment))] = next_event(InvoiceID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Processed))] = next_event(InvoiceID, Client), ?assertMatch({processed, #domain_InvoiceAdjustmentProcessed{}}, Processed), ok = hg_client_invoicing:capture_invoice_adjustment(InvoiceID, ID, Client), [?invoice_adjustment_ev(ID, ?invoice_adjustment_status_changed(Captured))] = next_event(InvoiceID, Client), ?assertMatch({captured, #domain_InvoiceAdjustmentCaptured{}}, Captured), #payproc_Invoice{invoice = #domain_Invoice{status = Unpaid}} = hg_client_invoicing:get(InvoiceID, Client), [?invoice_status_changed(?invoice_cancelled(_))] = next_event(InvoiceID, Client). -spec construct_domain_fixture() -> [hg_domain:object()]. construct_domain_fixture() -> TestTermSet = #domain_TermSet{ payments = #domain_PaymentsServiceTerms{ currencies = {value, ?ordset([ ?cur(<<"RUB">>) ])}, categories = {value, ?ordset([ ?cat(1) ])}, payment_methods = {decisions, [ #domain_PaymentMethodDecision{ if_ = {constant, true}, then_ = {value, ?ordset([ ?pmt(bank_card, ?bank_card(<<"visa-ref">>)), ?pmt(bank_card_deprecated, visa) ])} } ]}, cash_limit = {decisions, [ #domain_CashLimitDecision{ if_ = {condition, {currency_is, ?cur(<<"RUB">>)}}, then_ = {value, ?cashrng( {inclusive, ?cash(10, <<"RUB">>)}, {exclusive, ?cash(420000000, <<"RUB">>)} )} } ]}, fees = {decisions, [ #domain_CashFlowDecision{ if_ = {condition, {payment_tool, {bank_card, #domain_BankCardCondition{ definition = {category_is, ?bc_cat(1)} }}}}, then_ = {value, [ ?cfpost( {merchant, settlement}, {system, settlement}, ?merchant_to_system_share_2 ) ]} }, #domain_CashFlowDecision{ if_ = {condition, {currency_is, ?cur(<<"RUB">>)}}, then_ = {value, [ ?cfpost( {merchant, settlement}, {system, settlement}, ?merchant_to_system_share_1 ) ]} } ]}, holds = #domain_PaymentHoldsServiceTerms{ payment_methods = {value, ?ordset([ ?pmt(bank_card, ?bank_card(<<"visa-ref">>)), ?pmt(bank_card_deprecated, visa) ])}, lifetime = {decisions, [ #domain_HoldLifetimeDecision{ if_ = {condition, {currency_is, ?cur(<<"RUB">>)}}, then_ = {value, #domain_HoldLifetime{seconds = 10}} } ]} }, refunds = #domain_PaymentRefundsServiceTerms{ payment_methods = {value, ?ordset([ ?pmt(bank_card, ?bank_card(<<"visa-ref">>)), ?pmt(bank_card_deprecated, visa) ])}, fees = {value, [ ?cfpost( {merchant, settlement}, {system, settlement}, ?fixed(100, <<"RUB">>) ) ]}, eligibility_time = {value, #'TimeSpan'{minutes = 1}}, partial_refunds = #domain_PartialRefundsServiceTerms{ cash_limit = {decisions, [ #domain_CashLimitDecision{ if_ = {condition, {currency_is, ?cur(<<"RUB">>)}}, then_ = {value, ?cashrng( {inclusive, ?cash(1000, <<"RUB">>)}, {exclusive, ?cash(1000000000, <<"RUB">>)} )} } ]} } } }, recurrent_paytools = #domain_RecurrentPaytoolsServiceTerms{ payment_methods = {value, ordsets:from_list([ ?pmt(bank_card, ?bank_card(<<"visa-ref">>)), ?pmt(bank_card_deprecated, visa) ])} } }, [ hg_ct_fixture:construct_bank_card_category( ?bc_cat(1), <<"Bank card category">>, <<"Corporative">>, [<<"*CORPORAT*">>] ), hg_ct_fixture:construct_currency(?cur(<<"RUB">>)), hg_ct_fixture:construct_category(?cat(1), <<"Test category">>, test), hg_ct_fixture:construct_payment_method(?pmt(bank_card_deprecated, visa)), hg_ct_fixture:construct_payment_method(?pmt(bank_card, ?bank_card(<<"visa-ref">>))), hg_ct_fixture:construct_proxy(?prx(1), <<"Dummy proxy">>), hg_ct_fixture:construct_proxy(?prx(2), <<"Inspector proxy">>), hg_ct_fixture:construct_inspector(?insp(1), <<"Rejector">>, ?prx(2), #{<<"risk_score">> => <<"low">>}), hg_ct_fixture:construct_contract_template(?tmpl(1), ?trms(1)), hg_ct_fixture:construct_system_account_set(?sas(1)), hg_ct_fixture:construct_external_account_set(?eas(1)), {payment_institution, #domain_PaymentInstitutionObject{ ref = ?pinst(1), data = #domain_PaymentInstitution{ name = <<"Test Inc.">>, system_account_set = {value, ?sas(1)}, default_contract_template = {value, ?tmpl(1)}, payment_routing_rules = #domain_RoutingRules{ policies = ?ruleset(2), prohibitions = ?ruleset(1) }, inspector = {decisions, [ #domain_InspectorDecision{ if_ = {condition, {currency_is, ?cur(<<"RUB">>)}}, then_ = {decisions, [ #domain_InspectorDecision{ if_ = {condition, {cost_in, ?cashrng( {inclusive, ?cash(0, <<"RUB">>)}, {exclusive, ?cash(500000, <<"RUB">>)} )}}, then_ = {value, ?insp(1)} } ]} } ]}, residences = [], realm = test } }}, {routing_rules, #domain_RoutingRulesObject{ ref = ?ruleset(1), data = #domain_RoutingRuleset{ name = <<"Prohibitions: all is allow">>, decisions = {candidates, []} } }}, {routing_rules, #domain_RoutingRulesObject{ ref = ?ruleset(2), data = #domain_RoutingRuleset{ name = <<"Prohibitions: all is allow">>, decisions = {candidates, [ ?candidate({constant, true}, ?trm(1)) ]} } }}, {globals, #domain_GlobalsObject{ ref = #domain_GlobalsRef{}, data = #domain_Globals{ external_account_set = {decisions, [ #domain_ExternalAccountSetDecision{ if_ = {constant, true}, then_ = {value, ?eas(1)} } ]}, payment_institutions = ?ordset([?pinst(1)]) } }}, {term_set_hierarchy, #domain_TermSetHierarchyObject{ ref = ?trms(1), data = #domain_TermSetHierarchy{ term_sets = [ #domain_TimedTermSet{ action_time = #'TimestampInterval'{}, terms = TestTermSet } ] } }}, {provider, #domain_ProviderObject{ ref = ?prv(1), data = #domain_Provider{ name = <<"Brovider">>, description = <<"A provider but bro">>, proxy = #domain_Proxy{ ref = ?prx(1), additional = #{ <<"override">> => <<"brovider">> } }, abs_account = <<"1234567890">>, accounts = hg_ct_fixture:construct_provider_account_set([?cur(<<"RUB">>)]), terms = #domain_ProvisionTermSet{ payments = #domain_PaymentsProvisionTerms{ currencies = {value, ?ordset([ ?cur(<<"RUB">>) ])}, categories = {value, ?ordset([ ?cat(1) ])}, payment_methods = {value, ?ordset([ ?pmt(bank_card, ?bank_card(<<"visa-ref">>)), ?pmt(bank_card_deprecated, visa) ])}, cash_limit = {value, ?cashrng( {inclusive, ?cash(1000, <<"RUB">>)}, {exclusive, ?cash(1000000000, <<"RUB">>)} )}, cash_flow = {decisions, [ #domain_CashFlowDecision{ if_ = {condition, {payment_tool, {bank_card, #domain_BankCardCondition{ definition = {payment_system, #domain_PaymentSystemCondition{ payment_system_is = ?pmt_sys(<<"visa-ref">>) }} }}}}, then_ = {value, [ ?cfpost( {provider, settlement}, {merchant, settlement}, ?share(1, 1, operation_amount) ), ?cfpost( {system, settlement}, {provider, settlement}, ?share(18, 1000, operation_amount) ) ]} }, #domain_CashFlowDecision{ if_ = {condition, {payment_tool, {bank_card, #domain_BankCardCondition{ definition = {payment_system_is, visa} }}}}, then_ = {value, [ ?cfpost( {provider, settlement}, {merchant, settlement}, ?share(1, 1, operation_amount) ), ?cfpost( {system, settlement}, {provider, settlement}, ?share(18, 1000, operation_amount) ) ]} } ]}, holds = #domain_PaymentHoldsProvisionTerms{ lifetime = {decisions, [ #domain_HoldLifetimeDecision{ if_ = {condition, {payment_tool, {bank_card, #domain_BankCardCondition{ definition = {payment_system, #domain_PaymentSystemCondition{ payment_system_is = ?pmt_sys(<<"visa-ref">>) }} }}}}, then_ = {value, ?hold_lifetime(12)} }, #domain_HoldLifetimeDecision{ if_ = {condition, {payment_tool, {bank_card, #domain_BankCardCondition{ definition = {payment_system_is, visa} }}}}, then_ = {value, ?hold_lifetime(12)} } ]} }, refunds = #domain_PaymentRefundsProvisionTerms{ cash_flow = {value, [ ?cfpost( {merchant, settlement}, {provider, settlement}, ?share(1, 1, operation_amount) ) ]}, partial_refunds = #domain_PartialRefundsProvisionTerms{ cash_limit = {value, ?cashrng( {inclusive, ?cash(10, <<"RUB">>)}, {exclusive, ?cash(1000000000, <<"RUB">>)} )} } }, chargebacks = #domain_PaymentChargebackProvisionTerms{ cash_flow = {value, [ ?cfpost( {merchant, settlement}, {provider, settlement}, ?share(1, 1, operation_amount) ) ]} } }, recurrent_paytools = #domain_RecurrentPaytoolsProvisionTerms{ categories = {value, ?ordset([?cat(1)])}, payment_methods = {value, ?ordset([ ?pmt(bank_card, ?bank_card(<<"visa-ref">>)), ?pmt(bank_card_deprecated, visa) ])}, cash_value = {value, ?cash(1000, <<"RUB">>)} } } } }}, {terminal, #domain_TerminalObject{ ref = ?trm(1), data = #domain_Terminal{ name = <<"Brominal 1">>, description = <<"Brominal 1">>, risk_coverage = high, provider_ref = ?prv(1) } }}, hg_ct_fixture:construct_payment_system(?pmt_sys(<<"visa-ref">>), <<"visa payment system">>) ]. start_service_handler(Module, C, HandlerOpts) -> start_service_handler(Module, Module, C, HandlerOpts). start_service_handler(Name, Module, C, HandlerOpts) -> IP = "127.0.0.1", Port = get_random_port(), Opts = maps:merge(HandlerOpts, #{hellgate_root_url => cfg(root_url, C)}), ChildSpec = hg_test_proxy:get_child_spec(Name, Module, IP, Port, Opts), {ok, _} = supervisor:start_child(cfg(test_sup, C), ChildSpec), hg_test_proxy:get_url(Module, IP, Port). start_proxies(Proxies) -> setup_proxies( lists:map( fun Mapper({Module, ProxyID, Context}) -> Mapper({Module, ProxyID, #{}, Context}); Mapper({Module, ProxyID, ProxyOpts, Context}) -> construct_proxy(ProxyID, start_service_handler(Module, Context, #{}), ProxyOpts) end, Proxies ) ). setup_proxies(Proxies) -> _ = hg_domain:upsert(Proxies), ok. get_random_port() -> rand:uniform(32768) + 32767. construct_proxy(ID, Url, Options) -> {proxy, #domain_ProxyObject{ ref = ?prx(ID), data = #domain_ProxyDefinition{ name = Url, description = Url, url = Url, options = Options } }}. make_cash(Amount) -> hg_ct_helper:make_cash(Amount, <<"RUB">>). make_invoice_params(PartyID, ShopID, Product, Cost) -> hg_ct_helper:make_invoice_params(PartyID, ShopID, Product, Cost). make_invoice_params(PartyID, ShopID, Product, Due, Cost) -> hg_ct_helper:make_invoice_params(PartyID, ShopID, Product, Due, Cost). make_due_date(LifetimeSeconds) -> genlib_time:unow() + LifetimeSeconds. create_invoice(InvoiceParams, Client) -> ?invoice_state(?invoice(InvoiceID)) = hg_client_invoicing:create(InvoiceParams, Client), InvoiceID. next_event(InvoiceID, Client) -> timeout should be at least as large as hold expiration in next_event(InvoiceID, 12000, Client). next_event(InvoiceID, Timeout, Client) -> case hg_client_invoicing:pull_event(InvoiceID, Timeout, Client) of {ok, ?invoice_ev(Changes)} -> case filter_changes(Changes) of L when length(L) > 0 -> L; [] -> next_event(InvoiceID, Timeout, Client) end; Result -> Result end. filter_changes(Changes) -> lists:filtermap(fun filter_change/1, Changes). filter_change(?payment_ev(_, C)) -> filter_change(C); filter_change(?chargeback_ev(_, C)) -> filter_change(C); filter_change(?refund_ev(_, C)) -> filter_change(C); filter_change(?session_ev(_, ?proxy_st_changed(_))) -> false; filter_change(?session_ev(_, ?session_suspended(_, _))) -> false; filter_change(?session_ev(_, ?session_activated())) -> false; filter_change(_) -> true. set_payment_context(Context, Params = #payproc_InvoicePaymentParams{}) -> Params#payproc_InvoicePaymentParams{context = Context}. make_payment_params(PmtSys) -> make_payment_params(instant, PmtSys). make_payment_params(FlowType, PmtSys) -> {PaymentTool, Session} = hg_dummy_provider:make_payment_tool(no_preauth, PmtSys), make_payment_params(PaymentTool, Session, FlowType). make_tds_payment_params(FlowType, PmtSys) -> {PaymentTool, Session} = hg_dummy_provider:make_payment_tool(preauth_3ds, PmtSys), make_payment_params(PaymentTool, Session, FlowType). make_payment_params(PaymentTool, Session, FlowType) -> Flow = case FlowType of instant -> {instant, #payproc_InvoicePaymentParamsFlowInstant{}}; {hold, OnHoldExpiration} -> {hold, #payproc_InvoicePaymentParamsFlowHold{on_hold_expiration = OnHoldExpiration}} end, #payproc_InvoicePaymentParams{ payer = {payment_resource, #payproc_PaymentResourcePayerParams{ resource = #domain_DisposablePaymentResource{ payment_tool = PaymentTool, payment_session_id = Session, client_info = #domain_ClientInfo{} }, contact_info = #domain_ContactInfo{} }}, flow = Flow }. get_post_request({'redirect', {'post_request', #'BrowserPostRequest'{uri = URL, form = Form}}}) -> {URL, Form}; get_post_request({payment_terminal_reciept, #'PaymentTerminalReceipt'{short_payment_id = SPID}}) -> URL = hg_dummy_provider:get_callback_url(), {URL, #{<<"tag">> => SPID}}. start_payment(InvoiceID, PaymentParams, Client) -> ?payment_state(?payment(PaymentID)) = hg_client_invoicing:start_payment(InvoiceID, PaymentParams, Client), [ ?payment_ev(PaymentID, ?payment_started(?payment_w_status(?pending()))) ] = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?risk_score_changed(_)) ] = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?route_changed(_)) ] = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?cash_flow_changed(_)) ] = next_event(InvoiceID, Client), PaymentID. process_payment(InvoiceID, PaymentParams, Client) -> process_payment(InvoiceID, PaymentParams, Client, 0). process_payment(InvoiceID, PaymentParams, Client, Restarts) -> PaymentID = start_payment(InvoiceID, PaymentParams, Client), PaymentID = await_payment_session_started(InvoiceID, PaymentID, Client, ?processed()), PaymentID = await_payment_process_finish(InvoiceID, PaymentID, Client, Restarts). await_payment_session_started(InvoiceID, PaymentID, Client, Target) -> [ ?payment_ev(PaymentID, ?session_ev(Target, ?session_started())) ] = next_event(InvoiceID, Client), PaymentID. await_payment_process_finish(InvoiceID, PaymentID, Client) -> await_payment_process_finish(InvoiceID, PaymentID, Client, 0). await_payment_process_finish(InvoiceID, PaymentID, Client, Restarts) -> PaymentID = await_sessions_restarts(PaymentID, ?processed(), InvoiceID, Client, Restarts), [ ?payment_ev(PaymentID, ?session_ev(?processed(), ?trx_bound(?trx_info(_)))), ?payment_ev(PaymentID, ?session_ev(?processed(), ?session_finished(?session_succeeded()))) ] = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?payment_status_changed(?processed())) ] = next_event(InvoiceID, Client), PaymentID. get_payment_cost(InvoiceID, PaymentID, Client) -> #payproc_InvoicePayment{ payment = #domain_InvoicePayment{cost = Cost} } = hg_client_invoicing:get_payment(InvoiceID, PaymentID, Client), Cost. await_payment_capture(InvoiceID, PaymentID, Client) -> await_payment_capture(InvoiceID, PaymentID, ?timeout_reason(), Client). await_payment_capture(InvoiceID, PaymentID, Reason, Client) -> await_payment_capture(InvoiceID, PaymentID, Reason, Client, 0). await_payment_capture(InvoiceID, PaymentID, Reason, Client, Restarts) -> Cost = get_payment_cost(InvoiceID, PaymentID, Client), [ ?payment_ev(PaymentID, ?payment_capture_started(Reason, Cost, _, _Allocation)), ?payment_ev(PaymentID, ?session_ev(?captured(Reason, Cost), ?session_started())) ] = next_event(InvoiceID, Client), await_payment_capture_finish(InvoiceID, PaymentID, Reason, Client, Restarts). await_payment_partial_capture(InvoiceID, PaymentID, Reason, Cash, Client) -> await_payment_partial_capture(InvoiceID, PaymentID, Reason, Cash, Client, 0). await_payment_partial_capture(InvoiceID, PaymentID, Reason, Cash, Client, Restarts) -> [ ?payment_ev(PaymentID, ?payment_capture_started(Reason, Cash, _, _Allocation)), ?payment_ev(PaymentID, ?cash_flow_changed(_)) ] = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?session_ev(?captured(Reason, Cash), ?session_started())) ] = next_event(InvoiceID, Client), await_payment_capture_finish(InvoiceID, PaymentID, Reason, Client, Restarts, Cash). await_payment_capture_finish(InvoiceID, PaymentID, Reason, Client, Restarts) -> Cost = get_payment_cost(InvoiceID, PaymentID, Client), await_payment_capture_finish(InvoiceID, PaymentID, Reason, Client, Restarts, Cost). await_payment_capture_finish(InvoiceID, PaymentID, Reason, Client, Restarts, Cost) -> await_payment_capture_finish(InvoiceID, PaymentID, Reason, Client, Restarts, Cost, undefined). await_payment_capture_finish(InvoiceID, PaymentID, Reason, Client, Restarts, Cost, Cart) -> Target = ?captured(Reason, Cost, Cart), PaymentID = await_sessions_restarts(PaymentID, Target, InvoiceID, Client, Restarts), [ ?payment_ev(PaymentID, ?session_ev(Target, ?session_finished(?session_succeeded()))) ] = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?payment_status_changed(Target)), ?invoice_status_changed(?invoice_paid()) ] = next_event(InvoiceID, Client), PaymentID. await_payment_process_interaction(InvoiceID, PaymentID, Client) -> Events0 = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?session_ev(?processed(), ?session_started())) ] = Events0, Events1 = next_event(InvoiceID, Client), [ ?payment_ev(PaymentID, ?session_ev(?processed(), ?interaction_requested(UserInteraction))) ] = Events1, UserInteraction. -dialyzer({no_match, await_sessions_restarts/5}). await_sessions_restarts(PaymentID, _Target, _InvoiceID, _Client, 0) -> PaymentID; await_sessions_restarts(PaymentID, ?refunded() = Target, InvoiceID, Client, Restarts) when Restarts > 0 -> [ ?payment_ev(PaymentID, ?refund_ev(_, ?session_ev(Target, ?session_finished(?session_failed(_))))), ?payment_ev(PaymentID, ?refund_ev(_, ?session_ev(Target, ?session_started()))) ] = next_event(InvoiceID, Client), await_sessions_restarts(PaymentID, Target, InvoiceID, Client, Restarts - 1); await_sessions_restarts(PaymentID, Target, InvoiceID, Client, Restarts) when Restarts > 0 -> [ ?payment_ev(PaymentID, ?session_ev(Target, ?session_finished(?session_failed(_)))), ?payment_ev(PaymentID, ?session_ev(Target, ?session_started())) ] = next_event(InvoiceID, Client), await_sessions_restarts(PaymentID, Target, InvoiceID, Client, Restarts - 1). assert_success_post_request(Req) -> {ok, 200, _RespHeaders, _ClientRef} = post_request(Req). post_request({URL, Form}) -> Method = post, Headers = [], Body = {form, maps:to_list(Form)}, hackney:request(Method, URL, Headers, Body).
831c36ed445a39b4997fa0c1a655ebb999671b4b2af9b79e9e373adb45b6808d
mu-chaco/ReWire
test3.hs
import ReWire import ReWire.Bits tick :: ReT Bit W8 (StT W8 I) Bit tick = lift get >>= \ x -> signal x go :: ReT Bit W8 (StT W8 I) () go = do b <- tick case b of S -> go C -> go start :: ReT Bit W8 I () start = extrude go zeroW8 main = undefined
null
https://raw.githubusercontent.com/mu-chaco/ReWire/a8dcea6ab0989474988a758179a1d876e2c32370/tests/regression/test3.hs
haskell
import ReWire import ReWire.Bits tick :: ReT Bit W8 (StT W8 I) Bit tick = lift get >>= \ x -> signal x go :: ReT Bit W8 (StT W8 I) () go = do b <- tick case b of S -> go C -> go start :: ReT Bit W8 I () start = extrude go zeroW8 main = undefined
b8c88968fd1ba93d38662845da7d9b237e8655c7523414216afb9195823394bf
mstksg/nonempty-containers
Internal.hs
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_HADDOCK not-home #-} -- | Module : Data . IntSet . NonEmpty . Internal -- Copyright : (c) Justin Le 2018 -- License : BSD3 -- Maintainer : -- Stability : experimental -- Portability : non-portable -- Unsafe internal - use functions used in the implementation of " Data . IntSet . NonEmpty " . These functions can potentially be used to break -- the abstraction of 'NEIntSet' and produce unsound sets, so be wary! module Data.IntSet.NonEmpty.Internal ( NEIntSet(..) , Key , nonEmptySet , withNonEmpty , toSet , singleton , fromList , toList , union , unions , valid , insertMinSet , insertMaxSet , disjointSet ) where import Control.DeepSeq import Control.Monad import Data.Data import Data.Function import Data.IntSet.Internal (IntSet(..), Key) import Data.List.NonEmpty (NonEmpty(..)) import Data.Semigroup import Data.Semigroup.Foldable (Foldable1) import Text.Read import qualified Data.Aeson as A import qualified Data.Foldable as F import qualified Data.IntSet as S import qualified Data.Semigroup.Foldable as F1 | A non - empty ( by construction ) set of integers . At least one value -- exists in an @'NEIntSet' a@ at all times. -- -- Functions that /take/ an 'NEIntSet' can safely operate on it with the assumption that it has at least one item . -- -- Functions that /return/ an 'NEIntSet' provide an assurance that the result has at least one item . -- " Data . IntSet . NonEmpty " re - exports the API of " Data . IntSet " , faithfully reproducing asymptotics , constraints , and semantics . -- Functions that ensure that input and output sets are both non-empty -- (like 'Data.IntSet.NonEmpty.insert') return 'NEIntSet', but functions that -- might potentially return an empty map (like 'Data.IntSet.NonEmpty.delete') -- return a 'IntSet' instead. -- -- You can directly construct an 'NEIntSet' with the API from " Data . IntSet . NonEmpty " ; it 's more or less the same as constructing a normal ' ' , except you do n't have access to ' Data.IntSet.empty ' . There are also -- a few ways to construct an 'NEIntSet' from a 'IntSet': -- 1 . The ' nonEmptySet ' smart constructor will convert a @'IntSet ' a@ into a @'Maybe ' ( ' NEIntSet ' a)@ , returning ' Nothing ' if the original ' ' -- was empty. 2 . You can use the ' Data . IntSet . NonEmpty.insertIntSet ' family of functions to insert a value into a ' ' to create a guaranteed ' NEIntSet ' . 3 . You can use the ' Data . IntSet . NonEmpty . IsNonEmpty ' and ' Data . IntSet . NonEmpty . ' patterns to " pattern match " on a ' IntSet ' -- to reveal it as either containing a 'NEIntSet' or an empty map. 4 . ' withNonEmpty ' offers a continuation - based interface -- for deconstructing a 'IntSet' and treating it as if it were an 'NEIntSet'. -- -- You can convert an 'NEIntSet' into a 'IntSet' with 'toSet' or ' Data . IntSet . NonEmpty . IsNonEmpty ' , essentially " obscuring " the non - empty -- property from the type. data NEIntSet = NEIntSet { neisV0 :: !Key -- ^ invariant: must be smaller than smallest value in set , neisIntSet :: !IntSet } deriving (Typeable) instance Eq NEIntSet where t1 == t2 = S.size (neisIntSet t1) == S.size (neisIntSet t2) && toList t1 == toList t2 instance Ord NEIntSet where compare = compare `on` toList (<) = (<) `on` toList (>) = (>) `on` toList (<=) = (<=) `on` toList (>=) = (>=) `on` toList instance Show NEIntSet where showsPrec p xs = showParen (p > 10) $ showString "fromList (" . shows (toList xs) . showString ")" instance Read NEIntSet where readPrec = parens $ prec 10 $ do Ident "fromList" <- lexP xs <- parens . prec 10 $ readPrec return (fromList xs) readListPrec = readListPrecDefault instance NFData NEIntSet where rnf (NEIntSet x s) = rnf x `seq` rnf s Data instance code from Data . IntSet . Internal -- Copyright : ( c ) 2002 ( c ) 2011 instance Data NEIntSet where gfoldl f z is = z fromList `f` (toList is) toConstr _ = fromListConstr gunfold k z c = case constrIndex c of 1 -> k (z fromList) _ -> error "gunfold" dataTypeOf _ = intSetDataType fromListConstr :: Constr fromListConstr = mkConstr intSetDataType "fromList" [] Prefix intSetDataType :: DataType intSetDataType = mkDataType "Data.IntSet.NonEmpty.Internal.NEIntSet" [fromListConstr] instance A.ToJSON NEIntSet where toJSON = A.toJSON . toSet toEncoding = A.toEncoding . toSet instance A.FromJSON NEIntSet where parseJSON = withNonEmpty (fail err) pure <=< A.parseJSON where err = "NEIntSet: Non-empty set expected, but empty set found" | /O(log n)/. Smart constructor for an ' NEIntSet ' from a ' IntSet ' . Returns ' Nothing ' if the ' ' was originally actually empty , and @'Just ' n@ with an ' NEIntSet ' , if the ' ' was not empty . -- ' nonEmptySet ' and @'maybe ' ' Data.IntSet.empty ' ' toSet'@ form an -- isomorphism: they are perfect structure-preserving inverses of -- eachother. -- See ' Data . IntSet . NonEmpty . IsNonEmpty ' for a pattern synonym that lets you -- "match on" the possiblity of a 'IntSet' being an 'NEIntSet'. -- > nonEmptySet ( Data . IntSet.fromList [ 3,5 ] ) = = Just ( fromList ( 3:|[5 ] ) ) nonEmptySet :: IntSet -> Maybe NEIntSet nonEmptySet = (fmap . uncurry) NEIntSet . S.minView # INLINE nonEmptySet # -- | /O(log n)/. A general continuation-based way to consume a 'IntSet' as if -- it were an 'NEIntSet'. @'withNonEmpty' def f@ will take a 'IntSet'. If set is -- empty, it will evaluate to @def@. Otherwise, a non-empty set 'NEIntSet' will be fed to the function @f@ instead . -- @'nonEmptySet ' = = ' withNonEmpty ' ' Nothing ' ' withNonEmpty :: r -- ^ value to return if set is empty -> (NEIntSet -> r) -- ^ function to apply if set is not empty -> IntSet -> r withNonEmpty def f = maybe def f . nonEmptySet {-# INLINE withNonEmpty #-} | /O(log n)/. -- Convert a non-empty set back into a normal possibly-empty map, for usage with functions that expect ' ' . -- -- Can be thought of as "obscuring" the non-emptiness of the set in its type . See the ' Data . IntSet . NonEmpty . IsNotEmpty ' pattern . -- ' nonEmptySet ' and @'maybe ' ' Data.IntSet.empty ' ' toSet'@ form an -- isomorphism: they are perfect structure-preserving inverses of -- eachother. -- > toSet ( fromList ( ( 3,"a " ) :| [ ( 5,"b " ) ] ) ) = = Data . IntSet.fromList [ ( 3,"a " ) , ( 5,"b " ) ] toSet :: NEIntSet -> IntSet toSet (NEIntSet x s) = insertMinSet x s # INLINE toSet # -- | /O(1)/. Create a singleton set. singleton :: Key -> NEIntSet singleton x = NEIntSet x S.empty # INLINE singleton # | /O(n*log n)/. Create a set from a list of elements . TODO : write manually and optimize to be equivalent to -- 'fromDistinctAscList' if items are ordered, just like the actual -- 'S.fromList'. fromList :: NonEmpty Key -> NEIntSet fromList (x :| s) = withNonEmpty (singleton x) (<> singleton x) . S.fromList $ s # INLINE fromList # -- | /O(n)/. Convert the set to a non-empty list of elements. toList :: NEIntSet -> NonEmpty Key toList (NEIntSet x s) = x :| S.toList s # INLINE toList # | /O(m*log(n\/m + 1 ) ) , m < = n/. The union of two sets , preferring the first set when -- equal elements are encountered. union :: NEIntSet -> NEIntSet -> NEIntSet union n1@(NEIntSet x1 s1) n2@(NEIntSet x2 s2) = case compare x1 x2 of LT -> NEIntSet x1 . S.union s1 . toSet $ n2 EQ -> NEIntSet x1 . S.union s1 $ s2 GT -> NEIntSet x2 . S.union (toSet n1) $ s2 # INLINE union # -- | The union of a non-empty list of sets unions :: Foldable1 f => f NEIntSet -> NEIntSet unions (F1.toNonEmpty->(s :| ss)) = F.foldl' union s ss # INLINE unions # -- | Left-biased union instance Semigroup NEIntSet where (<>) = union {-# INLINE (<>) #-} sconcat = unions # INLINE sconcat # -- | /O(n)/. Test if the internal set structure is valid. valid :: NEIntSet -> Bool valid (NEIntSet x s) = all ((x <) . fst) (S.minView s) -- | /O(log n)/. Insert new value into a set where values are -- /strictly greater than/ the new values That is, the new value must be -- /strictly less than/ all values present in the 'IntSet'. /The precondition is not checked./ -- -- At the moment this is simply an alias for @Data.IntSet.insert@, but it's -- left here as a placeholder in case this eventually gets implemented in -- a more efficient way. -- TODO: implementation insertMinSet :: Key -> IntSet -> IntSet insertMinSet = S.insert # INLINABLE insertMinSet # -- | /O(log n)/. Insert new value into a set where values are /strictly -- less than/ the new value. That is, the new value must be /strictly -- greater than/ all values present in the 'IntSet'. /The precondition is not -- checked./ -- -- At the moment this is simply an alias for @Data.IntSet.insert@, but it's -- left here as a placeholder in case this eventually gets implemented in -- a more efficient way. -- TODO: implementation insertMaxSet :: Key -> IntSet -> IntSet insertMaxSet = S.insert # INLINABLE insertMaxSet # -- --------------------------------------------- | CPP for new functions not in old containers -- --------------------------------------------- -- | Comptability layer for 'Data.IntSet.disjoint'. disjointSet :: IntSet -> IntSet -> Bool #if MIN_VERSION_containers(0,5,11) disjointSet = S.disjoint #else disjointSet xs = S.null . S.intersection xs #endif # INLINE disjointSet #
null
https://raw.githubusercontent.com/mstksg/nonempty-containers/d875a3b4a21137f21896ca529860c193d6a38f21/src/Data/IntSet/NonEmpty/Internal.hs
haskell
# LANGUAGE CPP # # LANGUAGE DeriveDataTypeable # # LANGUAGE ViewPatterns # # OPTIONS_HADDOCK not-home # | Copyright : (c) Justin Le 2018 License : BSD3 Stability : experimental Portability : non-portable the abstraction of 'NEIntSet' and produce unsound sets, so be wary! exists in an @'NEIntSet' a@ at all times. Functions that /take/ an 'NEIntSet' can safely operate on it with the Functions that /return/ an 'NEIntSet' provide an assurance that the Functions that ensure that input and output sets are both non-empty (like 'Data.IntSet.NonEmpty.insert') return 'NEIntSet', but functions that might potentially return an empty map (like 'Data.IntSet.NonEmpty.delete') return a 'IntSet' instead. You can directly construct an 'NEIntSet' with the API from a few ways to construct an 'NEIntSet' from a 'IntSet': was empty. to reveal it as either containing a 'NEIntSet' or an empty map. for deconstructing a 'IntSet' and treating it as if it were an 'NEIntSet'. You can convert an 'NEIntSet' into a 'IntSet' with 'toSet' or property from the type. ^ invariant: must be smaller than smallest value in set isomorphism: they are perfect structure-preserving inverses of eachother. "match on" the possiblity of a 'IntSet' being an 'NEIntSet'. | /O(log n)/. A general continuation-based way to consume a 'IntSet' as if it were an 'NEIntSet'. @'withNonEmpty' def f@ will take a 'IntSet'. If set is empty, it will evaluate to @def@. Otherwise, a non-empty set 'NEIntSet' ^ value to return if set is empty ^ function to apply if set is not empty # INLINE withNonEmpty # Convert a non-empty set back into a normal possibly-empty map, for usage Can be thought of as "obscuring" the non-emptiness of the set in its isomorphism: they are perfect structure-preserving inverses of eachother. | /O(1)/. Create a singleton set. 'fromDistinctAscList' if items are ordered, just like the actual 'S.fromList'. | /O(n)/. Convert the set to a non-empty list of elements. equal elements are encountered. | The union of a non-empty list of sets | Left-biased union # INLINE (<>) # | /O(n)/. Test if the internal set structure is valid. | /O(log n)/. Insert new value into a set where values are /strictly greater than/ the new values That is, the new value must be /strictly less than/ all values present in the 'IntSet'. /The precondition At the moment this is simply an alias for @Data.IntSet.insert@, but it's left here as a placeholder in case this eventually gets implemented in a more efficient way. TODO: implementation | /O(log n)/. Insert new value into a set where values are /strictly less than/ the new value. That is, the new value must be /strictly greater than/ all values present in the 'IntSet'. /The precondition is not checked./ At the moment this is simply an alias for @Data.IntSet.insert@, but it's left here as a placeholder in case this eventually gets implemented in a more efficient way. TODO: implementation --------------------------------------------- --------------------------------------------- | Comptability layer for 'Data.IntSet.disjoint'.
Module : Data . IntSet . NonEmpty . Internal Maintainer : Unsafe internal - use functions used in the implementation of " Data . IntSet . NonEmpty " . These functions can potentially be used to break module Data.IntSet.NonEmpty.Internal ( NEIntSet(..) , Key , nonEmptySet , withNonEmpty , toSet , singleton , fromList , toList , union , unions , valid , insertMinSet , insertMaxSet , disjointSet ) where import Control.DeepSeq import Control.Monad import Data.Data import Data.Function import Data.IntSet.Internal (IntSet(..), Key) import Data.List.NonEmpty (NonEmpty(..)) import Data.Semigroup import Data.Semigroup.Foldable (Foldable1) import Text.Read import qualified Data.Aeson as A import qualified Data.Foldable as F import qualified Data.IntSet as S import qualified Data.Semigroup.Foldable as F1 | A non - empty ( by construction ) set of integers . At least one value assumption that it has at least one item . result has at least one item . " Data . IntSet . NonEmpty " re - exports the API of " Data . IntSet " , faithfully reproducing asymptotics , constraints , and semantics . " Data . IntSet . NonEmpty " ; it 's more or less the same as constructing a normal ' ' , except you do n't have access to ' Data.IntSet.empty ' . There are also 1 . The ' nonEmptySet ' smart constructor will convert a @'IntSet ' a@ into a @'Maybe ' ( ' NEIntSet ' a)@ , returning ' Nothing ' if the original ' ' 2 . You can use the ' Data . IntSet . NonEmpty.insertIntSet ' family of functions to insert a value into a ' ' to create a guaranteed ' NEIntSet ' . 3 . You can use the ' Data . IntSet . NonEmpty . IsNonEmpty ' and ' Data . IntSet . NonEmpty . ' patterns to " pattern match " on a ' IntSet ' 4 . ' withNonEmpty ' offers a continuation - based interface ' Data . IntSet . NonEmpty . IsNonEmpty ' , essentially " obscuring " the non - empty data NEIntSet = , neisIntSet :: !IntSet } deriving (Typeable) instance Eq NEIntSet where t1 == t2 = S.size (neisIntSet t1) == S.size (neisIntSet t2) && toList t1 == toList t2 instance Ord NEIntSet where compare = compare `on` toList (<) = (<) `on` toList (>) = (>) `on` toList (<=) = (<=) `on` toList (>=) = (>=) `on` toList instance Show NEIntSet where showsPrec p xs = showParen (p > 10) $ showString "fromList (" . shows (toList xs) . showString ")" instance Read NEIntSet where readPrec = parens $ prec 10 $ do Ident "fromList" <- lexP xs <- parens . prec 10 $ readPrec return (fromList xs) readListPrec = readListPrecDefault instance NFData NEIntSet where rnf (NEIntSet x s) = rnf x `seq` rnf s Data instance code from Data . IntSet . Internal Copyright : ( c ) 2002 ( c ) 2011 instance Data NEIntSet where gfoldl f z is = z fromList `f` (toList is) toConstr _ = fromListConstr gunfold k z c = case constrIndex c of 1 -> k (z fromList) _ -> error "gunfold" dataTypeOf _ = intSetDataType fromListConstr :: Constr fromListConstr = mkConstr intSetDataType "fromList" [] Prefix intSetDataType :: DataType intSetDataType = mkDataType "Data.IntSet.NonEmpty.Internal.NEIntSet" [fromListConstr] instance A.ToJSON NEIntSet where toJSON = A.toJSON . toSet toEncoding = A.toEncoding . toSet instance A.FromJSON NEIntSet where parseJSON = withNonEmpty (fail err) pure <=< A.parseJSON where err = "NEIntSet: Non-empty set expected, but empty set found" | /O(log n)/. Smart constructor for an ' NEIntSet ' from a ' IntSet ' . Returns ' Nothing ' if the ' ' was originally actually empty , and @'Just ' n@ with an ' NEIntSet ' , if the ' ' was not empty . ' nonEmptySet ' and @'maybe ' ' Data.IntSet.empty ' ' toSet'@ form an See ' Data . IntSet . NonEmpty . IsNonEmpty ' for a pattern synonym that lets you > nonEmptySet ( Data . IntSet.fromList [ 3,5 ] ) = = Just ( fromList ( 3:|[5 ] ) ) nonEmptySet :: IntSet -> Maybe NEIntSet nonEmptySet = (fmap . uncurry) NEIntSet . S.minView # INLINE nonEmptySet # will be fed to the function @f@ instead . @'nonEmptySet ' = = ' withNonEmpty ' ' Nothing ' ' withNonEmpty -> IntSet -> r withNonEmpty def f = maybe def f . nonEmptySet | /O(log n)/. with functions that expect ' ' . type . See the ' Data . IntSet . NonEmpty . IsNotEmpty ' pattern . ' nonEmptySet ' and @'maybe ' ' Data.IntSet.empty ' ' toSet'@ form an > toSet ( fromList ( ( 3,"a " ) :| [ ( 5,"b " ) ] ) ) = = Data . IntSet.fromList [ ( 3,"a " ) , ( 5,"b " ) ] toSet :: NEIntSet -> IntSet toSet (NEIntSet x s) = insertMinSet x s # INLINE toSet # singleton :: Key -> NEIntSet singleton x = NEIntSet x S.empty # INLINE singleton # | /O(n*log n)/. Create a set from a list of elements . TODO : write manually and optimize to be equivalent to fromList :: NonEmpty Key -> NEIntSet fromList (x :| s) = withNonEmpty (singleton x) (<> singleton x) . S.fromList $ s # INLINE fromList # toList :: NEIntSet -> NonEmpty Key toList (NEIntSet x s) = x :| S.toList s # INLINE toList # | /O(m*log(n\/m + 1 ) ) , m < = n/. The union of two sets , preferring the first set when union :: NEIntSet -> NEIntSet -> NEIntSet union n1@(NEIntSet x1 s1) n2@(NEIntSet x2 s2) = case compare x1 x2 of LT -> NEIntSet x1 . S.union s1 . toSet $ n2 EQ -> NEIntSet x1 . S.union s1 $ s2 GT -> NEIntSet x2 . S.union (toSet n1) $ s2 # INLINE union # unions :: Foldable1 f => f NEIntSet -> NEIntSet unions (F1.toNonEmpty->(s :| ss)) = F.foldl' union s ss # INLINE unions # instance Semigroup NEIntSet where (<>) = union sconcat = unions # INLINE sconcat # valid :: NEIntSet -> Bool valid (NEIntSet x s) = all ((x <) . fst) (S.minView s) is not checked./ insertMinSet :: Key -> IntSet -> IntSet insertMinSet = S.insert # INLINABLE insertMinSet # insertMaxSet :: Key -> IntSet -> IntSet insertMaxSet = S.insert # INLINABLE insertMaxSet # | CPP for new functions not in old containers disjointSet :: IntSet -> IntSet -> Bool #if MIN_VERSION_containers(0,5,11) disjointSet = S.disjoint #else disjointSet xs = S.null . S.intersection xs #endif # INLINE disjointSet #
41e06dcf937f305d85b9ddb3c6adc7213b9a181134b66d94b98746068003354a
UU-ComputerScience/uhc
FloatingFloat1.hs
{- ---------------------------------------------------------------------------------------- what : Floating functions, on Float expected: all ok ---------------------------------------------------------------------------------------- -} module FloatingFloat1 where main = do p sin (pi / 2) p sin (pi / 4) p cos (pi / 2) p cos (pi / 4) p tan (pi / 2) p tan (pi / 4) p asin 1 p acos 1 p atan 1 p exp 1 p log (exp 2) p sqrt 2 p sqrt 4 p sinh 1 p cosh 1 p tanh 1 where p :: (Float -> Float) -> Float -> IO () p f x = putStrLn (show (f x))
null
https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/test/regress/99/FloatingFloat1.hs
haskell
---------------------------------------------------------------------------------------- what : Floating functions, on Float expected: all ok ----------------------------------------------------------------------------------------
module FloatingFloat1 where main = do p sin (pi / 2) p sin (pi / 4) p cos (pi / 2) p cos (pi / 4) p tan (pi / 2) p tan (pi / 4) p asin 1 p acos 1 p atan 1 p exp 1 p log (exp 2) p sqrt 2 p sqrt 4 p sinh 1 p cosh 1 p tanh 1 where p :: (Float -> Float) -> Float -> IO () p f x = putStrLn (show (f x))
2d4213ded03d46608bc4268a4b5c24db87f16416360e117c0155cc2ff97754e5
cdepillabout/servant-static-th
Server.hs
# LANGUAGE QuasiQuotes # {-# LANGUAGE RankNTypes #-} # LANGUAGE TemplateHaskell # module Servant.Static.TH.Internal.Server where import Data.Foldable (foldl1) import Data.List.NonEmpty (NonEmpty((:|))) import Language.Haskell.TH (Dec, Exp, Q, appE, clause, conT, funD, mkName, normalB, runIO, sigD) import Language.Haskell.TH.Syntax (addDependentFile) import Servant.API ((:<|>)((:<|>))) import Servant.Server (ServerT) import System.FilePath (takeFileName) import Servant.Static.TH.Internal.FileTree import Servant.Static.TH.Internal.Mime combineWithExp :: Q Exp -> Q Exp -> Q Exp -> Q Exp combineWithExp combiningExp = appE . appE combiningExp combineWithServantOr :: Q Exp -> Q Exp -> Q Exp combineWithServantOr = combineWithExp [e|(:<|>)|] combineMultiWithServantOr :: NonEmpty (Q Exp) -> Q Exp combineMultiWithServantOr = foldl1 combineWithServantOr fileTreeToServer :: FileTree -> Q Exp fileTreeToServer (FileTreeFile filePath fileContents) = do addDependentFile filePath MimeTypeInfo _ _ contentToExp <- extensionToMimeTypeInfoEx filePath let fileName = takeFileName filePath case fileName of "index.html" -> combineWithServantOr -- content to serve on the root (contentToExp fileContents) -- content to serve on the path "index.html" (contentToExp fileContents) _ -> contentToExp fileContents fileTreeToServer (FileTreeDir _ fileTrees) = combineMultiWithServantOr $ fmap fileTreeToServer fileTrees -- | Take a template directory argument as a 'FilePath' and create a 'ServerT' -- function that serves the files under the directory. Empty directories will -- be ignored. 'index.html' files will also be served at the root. -- -- Note that the file contents will be embedded in the function. They will -- not be served dynamically at runtime. This makes it easy to create a Haskell binary for a website with all static files completely baked - in . -- -- For example, assume the following directory structure and file contents: -- -- @ -- $ tree dir\/ -- dir\/ -- ├── js │    ─ test.js ─ ─ index.html -- @ -- -- @ -- $ cat dir\/index.html \<p\>Hello World\<\/p\ > -- $ cat dir\/js\/test.js -- console.log(\"hello world\"); -- @ -- ' createServerExp ' is used like the following : -- -- @ \{\-\ # LANGUAGE DataKinds \#\-\ } \{\-\ # LANGUAGE TemplateHaskell \#\-\ } -- type FrontEndAPI = $ ( ' Servant . Static . TH.Internal . API.createApiType ' \"dir\ " ) -- -- frontEndServer :: 'Applicative' m => 'ServerT' FrontEndAPI m -- frontEndServer = $('createServerExp' \"dir\") -- @ -- -- At compile time, this expands to something like the following. This has -- been slightly simplified to make it easier to understand: -- -- @ type FrontEndAPI = " ' Servant . API . :> ' " ' Servant . API . :> ' ' Servant . API.Get ' \'['JS ' ] ' Data . ByteString . ByteString ' ' : < | > ' ' Servant . API.Get ' \'['Servant . HTML.Blaze . HTML ' ] ' Text . Blaze . Html . Html ' ' : < | > ' " ' Servant . API . :> ' ' Servant . API.Get ' \'['Servant . HTML.Blaze . HTML ' ] ' Text . Blaze . Html . Html ' -- -- frontEndServer :: 'Applicative' m => 'ServerT' FrontEndAPI m -- frontEndServer = -- 'pure' "console.log(\\"hello world\\");" ' : < | > ' ' pure ' " \<p\>Hello World\<\/p\ > " -- @ createServerExp :: FilePath -> Q Exp createServerExp templateDir = do fileTree <- runIO $ getFileTreeIgnoreEmpty templateDir combineMultiWithServantOr $ fmap fileTreeToServer fileTree | This is similar to ' createServerExp ' , but it creates the whole function -- declaration. -- -- Given the following code: -- -- @ \{\-\ # LANGUAGE DataKinds \#\-\ } \{\-\ # LANGUAGE TemplateHaskell \#\-\ } -- -- $('createServerDec' \"FrontAPI\" \"frontServer\" \"dir\") -- @ -- -- You can think of it as expanding to the following: -- -- @ frontServer : : ' Applicative ' m = > ' ServerT ' m -- frontServer = $('createServerExp' \"dir\") -- @ createServerDec :: String -- ^ name of the api type synonym -> String -- ^ name of the server function -> FilePath -- ^ directory name to read files from -> Q [Dec] createServerDec apiName serverName templateDir = let funcName = mkName serverName sigTypeQ = [t|forall m. Applicative m => ServerT $(conT (mkName apiName)) m|] signatureQ = sigD funcName sigTypeQ clauses = [clause [] (normalB (createServerExp templateDir)) []] funcQ = funD funcName clauses in sequence [signatureQ, funcQ]
null
https://raw.githubusercontent.com/cdepillabout/servant-static-th/5ec0027ed2faa6f8c42a2259a963f52e6b30edad/src/Servant/Static/TH/Internal/Server.hs
haskell
# LANGUAGE RankNTypes # content to serve on the root content to serve on the path "index.html" | Take a template directory argument as a 'FilePath' and create a 'ServerT' function that serves the files under the directory. Empty directories will be ignored. 'index.html' files will also be served at the root. Note that the file contents will be embedded in the function. They will not be served dynamically at runtime. This makes it easy to create a For example, assume the following directory structure and file contents: @ $ tree dir\/ dir\/ ├── js @ @ $ cat dir\/index.html $ cat dir\/js\/test.js console.log(\"hello world\"); @ @ frontEndServer :: 'Applicative' m => 'ServerT' FrontEndAPI m frontEndServer = $('createServerExp' \"dir\") @ At compile time, this expands to something like the following. This has been slightly simplified to make it easier to understand: @ frontEndServer :: 'Applicative' m => 'ServerT' FrontEndAPI m frontEndServer = 'pure' "console.log(\\"hello world\\");" @ declaration. Given the following code: @ $('createServerDec' \"FrontAPI\" \"frontServer\" \"dir\") @ You can think of it as expanding to the following: @ frontServer = $('createServerExp' \"dir\") @ ^ name of the api type synonym ^ name of the server function ^ directory name to read files from
# LANGUAGE QuasiQuotes # # LANGUAGE TemplateHaskell # module Servant.Static.TH.Internal.Server where import Data.Foldable (foldl1) import Data.List.NonEmpty (NonEmpty((:|))) import Language.Haskell.TH (Dec, Exp, Q, appE, clause, conT, funD, mkName, normalB, runIO, sigD) import Language.Haskell.TH.Syntax (addDependentFile) import Servant.API ((:<|>)((:<|>))) import Servant.Server (ServerT) import System.FilePath (takeFileName) import Servant.Static.TH.Internal.FileTree import Servant.Static.TH.Internal.Mime combineWithExp :: Q Exp -> Q Exp -> Q Exp -> Q Exp combineWithExp combiningExp = appE . appE combiningExp combineWithServantOr :: Q Exp -> Q Exp -> Q Exp combineWithServantOr = combineWithExp [e|(:<|>)|] combineMultiWithServantOr :: NonEmpty (Q Exp) -> Q Exp combineMultiWithServantOr = foldl1 combineWithServantOr fileTreeToServer :: FileTree -> Q Exp fileTreeToServer (FileTreeFile filePath fileContents) = do addDependentFile filePath MimeTypeInfo _ _ contentToExp <- extensionToMimeTypeInfoEx filePath let fileName = takeFileName filePath case fileName of "index.html" -> combineWithServantOr (contentToExp fileContents) (contentToExp fileContents) _ -> contentToExp fileContents fileTreeToServer (FileTreeDir _ fileTrees) = combineMultiWithServantOr $ fmap fileTreeToServer fileTrees Haskell binary for a website with all static files completely baked - in . │    ─ test.js ─ ─ index.html \<p\>Hello World\<\/p\ > ' createServerExp ' is used like the following : \{\-\ # LANGUAGE DataKinds \#\-\ } \{\-\ # LANGUAGE TemplateHaskell \#\-\ } type FrontEndAPI = $ ( ' Servant . Static . TH.Internal . API.createApiType ' \"dir\ " ) type FrontEndAPI = " ' Servant . API . :> ' " ' Servant . API . :> ' ' Servant . API.Get ' \'['JS ' ] ' Data . ByteString . ByteString ' ' : < | > ' ' Servant . API.Get ' \'['Servant . HTML.Blaze . HTML ' ] ' Text . Blaze . Html . Html ' ' : < | > ' " ' Servant . API . :> ' ' Servant . API.Get ' \'['Servant . HTML.Blaze . HTML ' ] ' Text . Blaze . Html . Html ' ' : < | > ' ' pure ' " \<p\>Hello World\<\/p\ > " createServerExp :: FilePath -> Q Exp createServerExp templateDir = do fileTree <- runIO $ getFileTreeIgnoreEmpty templateDir combineMultiWithServantOr $ fmap fileTreeToServer fileTree | This is similar to ' createServerExp ' , but it creates the whole function \{\-\ # LANGUAGE DataKinds \#\-\ } \{\-\ # LANGUAGE TemplateHaskell \#\-\ } frontServer : : ' Applicative ' m = > ' ServerT ' m createServerDec -> Q [Dec] createServerDec apiName serverName templateDir = let funcName = mkName serverName sigTypeQ = [t|forall m. Applicative m => ServerT $(conT (mkName apiName)) m|] signatureQ = sigD funcName sigTypeQ clauses = [clause [] (normalB (createServerExp templateDir)) []] funcQ = funD funcName clauses in sequence [signatureQ, funcQ]
56ca29933f91edd2e02cacc3206d37a6dfcec3002690d7c47271d58899048f2a
anoma/juvix
Negative.hs
module Core.Eval.Negative where import Base import Core.Eval.Base data NegTest = NegTest { _name :: String, _relDir :: Path Rel Dir, _file :: Path Rel File } root :: Path Abs Dir root = relToProject $(mkRelDir "tests/Core/negative") testDescr :: NegTest -> TestDescr testDescr NegTest {..} = let tRoot = root <//> _relDir file' = tRoot <//> _file in TestDescr { _testName = _name, _testRoot = tRoot, _testAssertion = Steps $ coreEvalErrorAssertion file' } allTests :: TestTree allTests = testGroup "JuvixCore negative tests" (map (mkTest . testDescr) tests) tests :: [NegTest] tests = [ NegTest "Division by zero" $(mkRelDir ".") $(mkRelFile "test001.jvc"), NegTest "Arithmetic operations on non-numbers" $(mkRelDir ".") $(mkRelFile "test002.jvc"), NegTest "Matching on non-data" $(mkRelDir ".") $(mkRelFile "test003.jvc"), NegTest "If on non-boolean" $(mkRelDir ".") $(mkRelFile "test004.jvc"), NegTest "No matching case branch" $(mkRelDir ".") $(mkRelFile "test005.jvc"), NegTest "Invalid application" $(mkRelDir ".") $(mkRelFile "test006.jvc"), NegTest "Invalid builtin application" $(mkRelDir ".") $(mkRelFile "test007.jvc"), NegTest "Undefined symbol" $(mkRelDir ".") $(mkRelFile "test008.jvc"), NegTest "Erroneous Church numerals" $(mkRelDir ".") $(mkRelFile "test009.jvc"), NegTest "Empty letrec" $(mkRelDir ".") $(mkRelFile "test010.jvc") ]
null
https://raw.githubusercontent.com/anoma/juvix/af63c36574da981e62d72b3c985fff2ba6266e8b/test/Core/Eval/Negative.hs
haskell
module Core.Eval.Negative where import Base import Core.Eval.Base data NegTest = NegTest { _name :: String, _relDir :: Path Rel Dir, _file :: Path Rel File } root :: Path Abs Dir root = relToProject $(mkRelDir "tests/Core/negative") testDescr :: NegTest -> TestDescr testDescr NegTest {..} = let tRoot = root <//> _relDir file' = tRoot <//> _file in TestDescr { _testName = _name, _testRoot = tRoot, _testAssertion = Steps $ coreEvalErrorAssertion file' } allTests :: TestTree allTests = testGroup "JuvixCore negative tests" (map (mkTest . testDescr) tests) tests :: [NegTest] tests = [ NegTest "Division by zero" $(mkRelDir ".") $(mkRelFile "test001.jvc"), NegTest "Arithmetic operations on non-numbers" $(mkRelDir ".") $(mkRelFile "test002.jvc"), NegTest "Matching on non-data" $(mkRelDir ".") $(mkRelFile "test003.jvc"), NegTest "If on non-boolean" $(mkRelDir ".") $(mkRelFile "test004.jvc"), NegTest "No matching case branch" $(mkRelDir ".") $(mkRelFile "test005.jvc"), NegTest "Invalid application" $(mkRelDir ".") $(mkRelFile "test006.jvc"), NegTest "Invalid builtin application" $(mkRelDir ".") $(mkRelFile "test007.jvc"), NegTest "Undefined symbol" $(mkRelDir ".") $(mkRelFile "test008.jvc"), NegTest "Erroneous Church numerals" $(mkRelDir ".") $(mkRelFile "test009.jvc"), NegTest "Empty letrec" $(mkRelDir ".") $(mkRelFile "test010.jvc") ]
6023824907e7b148f68a308448f98f39fb113991160c98fb352403402d9659b2
graninas/Pragmatic-Type-Level-Design
DataActions.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} # LANGUAGE FunctionalDependencies # {-# LANGUAGE TypeFamilies #-} # LANGUAGE PolyKinds # {-# LANGUAGE KindSignatures #-} # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE ScopedTypeVariables #-} module Auction.Language.DataActions where import TypeLevelDSL.Language.Action import GHC.TypeLits (Symbol, Nat) data LotName data LotDescr -- Should valName be a Symbol? data GetPayloadValue' (valTag :: *) (valType :: *) (lam :: LambdaTag lamBody) data GetLotName' (lam :: LambdaTag lamBody) -- custom methods data GetLotDescr' (lam :: LambdaTag lamBody) -- custom methods -- Helpers type GetPayloadValue tag typ lam = MkAction (GetPayloadValue' tag typ lam) type GetLotName lam = MkAction (GetLotName' lam) -- Custom methods type GetLotDescr lam = MkAction (GetLotDescr' lam) -- Custom methods type GetLotName2 lam = MkAction (GetPayloadValue' LotName String lam) type GetLotDescr2 lam = MkAction (GetPayloadValue' LotDescr String lam)
null
https://raw.githubusercontent.com/graninas/Pragmatic-Type-Level-Design/a7e051ed9d664c6986323336a0ad2132a3fa3f1c/demo-apps/auction/src/Auction/Language/DataActions.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE TypeOperators # # LANGUAGE TypeFamilies # # LANGUAGE KindSignatures # # LANGUAGE ScopedTypeVariables # Should valName be a Symbol? custom methods custom methods Helpers Custom methods Custom methods
# LANGUAGE FunctionalDependencies # # LANGUAGE PolyKinds # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # module Auction.Language.DataActions where import TypeLevelDSL.Language.Action import GHC.TypeLits (Symbol, Nat) data LotName data LotDescr data GetPayloadValue' (valTag :: *) (valType :: *) (lam :: LambdaTag lamBody) type GetPayloadValue tag typ lam = MkAction (GetPayloadValue' tag typ lam) type GetLotName2 lam = MkAction (GetPayloadValue' LotName String lam) type GetLotDescr2 lam = MkAction (GetPayloadValue' LotDescr String lam)
9ca9fffc4629f3cb7f5c95c5520a92dc74f5e158f4e9da68fdc9bdb972da41d6
awslabs/s2n-bignum
bignum_montmul_p256k1_alt.ml
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved . * SPDX - License - Identifier : Apache-2.0 OR ISC * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 OR ISC *) (* ========================================================================= *) (* Montgomery multiply mod p_256k1, the field characteristic for secp256k1. *) (* ========================================================================= *) (**** print_literal_from_elf "x86/secp256k1/bignum_montmul_p256k1_alt.o";; ****) let bignum_montmul_p256k1_alt_mc = define_assert_from_elf "bignum_montmul_p256k1_alt_mc" "x86/secp256k1/bignum_montmul_p256k1_alt.o" [ 0x53; (* PUSH (% rbx) *) 0x41; 0x54; (* PUSH (% r12) *) 0x41; 0x55; (* PUSH (% r13) *) 0x41; 0x56; (* PUSH (% r14) *) 0x41; 0x57; (* PUSH (% r15) *) MOV ( % rcx ) ( % rdx ) MOV ( % rax ) ( ( % % ( rsi,0 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,0 ) ) ) MOV ( % r8 ) ( % rax ) MOV ( % r9 ) ( % rdx ) 0x4d; 0x31; 0xd2; (* XOR (% r10) (% r10) *) 0x4d; 0x31; 0xdb; (* XOR (% r11) (% r11) *) MOV ( % rax ) ( ( % % ( rsi,0 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,8 ) ) ) 0x49; 0x01; 0xc1; (* ADD (% r9) (% rax) *) 0x49; 0x11; 0xd2; (* ADC (% r10) (% rdx) *) MOV ( % rax ) ( ( % % ( rsi,8 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,0 ) ) ) 0x49; 0x01; 0xc1; (* ADD (% r9) (% rax) *) 0x49; 0x11; 0xd2; (* ADC (% r10) (% rdx) *) 0x4d; 0x11; 0xdb; (* ADC (% r11) (% r11) *) 0x4d; 0x31; 0xe4; (* XOR (% r12) (% r12) *) MOV ( % rax ) ( ( % % ( rsi,0 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,16 ) ) ) 0x49; 0x01; 0xc2; (* ADD (% r10) (% rax) *) 0x49; 0x11; 0xd3; (* ADC (% r11) (% rdx) *) 0x4d; 0x11; 0xe4; (* ADC (% r12) (% r12) *) MOV ( % rax ) ( ( % % ( rsi,8 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,8 ) ) ) 0x49; 0x01; 0xc2; (* ADD (% r10) (% rax) *) 0x49; 0x11; 0xd3; (* ADC (% r11) (% rdx) *) 0x49; 0x83; 0xd4; 0x00; (* ADC (% r12) (Imm8 (word 0)) *) MOV ( % rax ) ( ( % % ( rsi,16 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,0 ) ) ) 0x49; 0x01; 0xc2; (* ADD (% r10) (% rax) *) 0x49; 0x11; 0xd3; (* ADC (% r11) (% rdx) *) 0x49; 0x83; 0xd4; 0x00; (* ADC (% r12) (Imm8 (word 0)) *) 0x4d; 0x31; 0xed; (* XOR (% r13) (% r13) *) MOV ( % rax ) ( ( % % ( rsi,0 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,24 ) ) ) 0x49; 0x01; 0xc3; (* ADD (% r11) (% rax) *) 0x49; 0x11; 0xd4; (* ADC (% r12) (% rdx) *) 0x4d; 0x11; 0xed; (* ADC (% r13) (% r13) *) MOV ( % rax ) ( ( % % ( rsi,8 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,16 ) ) ) 0x49; 0x01; 0xc3; (* ADD (% r11) (% rax) *) 0x49; 0x11; 0xd4; (* ADC (% r12) (% rdx) *) 0x49; 0x83; 0xd5; 0x00; (* ADC (% r13) (Imm8 (word 0)) *) MOV ( % rax ) ( ( % % ( rsi,16 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,8 ) ) ) 0x49; 0x01; 0xc3; (* ADD (% r11) (% rax) *) 0x49; 0x11; 0xd4; (* ADC (% r12) (% rdx) *) 0x49; 0x83; 0xd5; 0x00; (* ADC (% r13) (Imm8 (word 0)) *) MOV ( % rax ) ( ( % % ( rsi,24 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,0 ) ) ) 0x49; 0x01; 0xc3; (* ADD (% r11) (% rax) *) 0x49; 0x11; 0xd4; (* ADC (% r12) (% rdx) *) 0x49; 0x83; 0xd5; 0x00; (* ADC (% r13) (Imm8 (word 0)) *) 0x4d; 0x31; 0xf6; (* XOR (% r14) (% r14) *) MOV ( % rax ) ( ( % % ( rsi,8 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,24 ) ) ) 0x49; 0x01; 0xc4; (* ADD (% r12) (% rax) *) 0x49; 0x11; 0xd5; (* ADC (% r13) (% rdx) *) 0x4d; 0x11; 0xf6; (* ADC (% r14) (% r14) *) MOV ( % rax ) ( ( % % ( rsi,16 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,16 ) ) ) 0x49; 0x01; 0xc4; (* ADD (% r12) (% rax) *) 0x49; 0x11; 0xd5; (* ADC (% r13) (% rdx) *) 0x49; 0x83; 0xd6; 0x00; (* ADC (% r14) (Imm8 (word 0)) *) MOV ( % rax ) ( ( % % ( rsi,24 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,8 ) ) ) 0x49; 0x01; 0xc4; (* ADD (% r12) (% rax) *) 0x49; 0x11; 0xd5; (* ADC (% r13) (% rdx) *) 0x49; 0x83; 0xd6; 0x00; (* ADC (% r14) (Imm8 (word 0)) *) 0x4d; 0x31; 0xff; (* XOR (% r15) (% r15) *) MOV ( % rax ) ( ( % % ( rsi,16 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,24 ) ) ) 0x49; 0x01; 0xc5; (* ADD (% r13) (% rax) *) 0x49; 0x11; 0xd6; (* ADC (% r14) (% rdx) *) 0x4d; 0x11; 0xff; (* ADC (% r15) (% r15) *) MOV ( % rax ) ( ( % % ( rsi,24 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,16 ) ) ) 0x49; 0x01; 0xc5; (* ADD (% r13) (% rax) *) 0x49; 0x11; 0xd6; (* ADC (% r14) (% rdx) *) 0x49; 0x83; 0xd7; 0x00; (* ADC (% r15) (Imm8 (word 0)) *) MOV ( % rax ) ( ( % % ( rsi,24 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,24 ) ) ) 0x49; 0x01; 0xc6; (* ADD (% r14) (% rax) *) 0x49; 0x11; 0xd7; (* ADC (% r15) (% rdx) *) 0x48; 0xbe; 0x31; 0x35; 0x25; 0xd2; 0x1d; 0x09; 0x38; 0xd8; MOV ( % rsi ) ( Imm64 ( word 15580212934572586289 ) ) 0x48; 0xbb; 0xd1; 0x03; 0x00; 0x00; 0x01; 0x00; 0x00; 0x00; MOV ( % rbx ) ( Imm64 ( word 4294968273 ) ) MOV ( % rax ) ( % rbx ) IMUL ( % r8 ) ( % rsi ) MUL2 ( % rdx,% rax ) ( % r8 ) 0x49; 0x29; 0xd1; (* SUB (% r9) (% rdx) *) SBB ( % rcx ) ( % rcx ) MOV ( % rax ) ( % rbx ) IMUL ( % r9 ) ( % rsi ) MUL2 ( % rdx,% rax ) ( % r9 ) 0x48; 0xf7; 0xd9; (* NEG (% rcx) *) SBB ( % r10 ) ( % rdx ) SBB ( % rcx ) ( % rcx ) MOV ( % rax ) ( % rbx ) IMUL ( % r10 ) ( % rsi ) MUL2 ( % rdx,% rax ) ( % r10 ) 0x48; 0xf7; 0xd9; (* NEG (% rcx) *) SBB ( % r11 ) ( % rdx ) SBB ( % rcx ) ( % rcx ) MOV ( % rax ) ( % rbx ) IMUL ( % r11 ) ( % rsi ) MUL2 ( % rdx,% rax ) ( % r11 ) 0x48; 0xf7; 0xd9; (* NEG (% rcx) *) SBB ( % r8 ) ( % rdx ) SBB ( % r9 ) ( Imm8 ( word 0 ) ) SBB ( % r10 ) ( Imm8 ( word 0 ) ) SBB ( % r11 ) ( Imm8 ( word 0 ) ) 0x4d; 0x01; 0xc4; (* ADD (% r12) (% r8) *) 0x4d; 0x11; 0xcd; (* ADC (% r13) (% r9) *) 0x4d; 0x11; 0xd6; (* ADC (% r14) (% r10) *) 0x4d; 0x11; 0xdf; (* ADC (% r15) (% r11) *) SBB ( % rsi ) ( % rsi ) MOV ( % r8 ) ( % r12 ) 0x49; 0x01; 0xd8; (* ADD (% r8) (% rbx) *) MOV ( % r9 ) ( % r13 ) 0x49; 0x83; 0xd1; 0x00; (* ADC (% r9) (Imm8 (word 0)) *) MOV ( % r10 ) ( % r14 ) 0x49; 0x83; 0xd2; 0x00; (* ADC (% r10) (Imm8 (word 0)) *) MOV ( % r11 ) ( % r15 ) 0x49; 0x83; 0xd3; 0x00; (* ADC (% r11) (Imm8 (word 0)) *) ADC ( % rsi ) ( Imm8 ( word 255 ) ) CMOVB ( % r12 ) ( % r8 ) MOV ( ( % % ( rdi,0 ) ) ) ( % r12 ) CMOVB ( % r13 ) ( % r9 ) MOV ( ( % % ( rdi,8 ) ) ) ( % r13 ) CMOVB ( % r14 ) ( % r10 ) MOV ( ( % % ( rdi,16 ) ) ) ( % r14 ) CMOVB ( % r15 ) ( % r11 ) MOV ( ( % % ( ) ) ) ( % r15 ) 0x41; 0x5f; (* POP (% r15) *) 0x41; 0x5e; (* POP (% r14) *) 0x41; 0x5d; (* POP (% r13) *) 0x41; 0x5c; (* POP (% r12) *) 0x5b; (* POP (% rbx) *) RET ];; let BIGNUM_MONTMUL_P256K1_ALT_EXEC = X86_MK_CORE_EXEC_RULE bignum_montmul_p256k1_alt_mc;; (* ------------------------------------------------------------------------- *) (* Proof. *) (* ------------------------------------------------------------------------- *) let p_256k1 = new_definition `p_256k1 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F`;; let mmlemma = prove (`!h (l:int64) (x:int64). &2 pow 64 * &h + &(val(l:int64)):real = &4294968273 * &(val(word_mul x (word 15580212934572586289):int64)) ==> &2 pow 64 * &h + &(val(x:int64)):real = &4294968273 * &(val(word_mul x (word 15580212934572586289):int64))`, REPEAT GEN_TAC THEN REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN REPEAT STRIP_TAC THEN FIRST_ASSUM(SUBST1_TAC o SYM) THEN AP_TERM_TAC THEN AP_TERM_TAC THEN REWRITE_TAC[GSYM VAL_CONG; DIMINDEX_64] THEN FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (NUMBER_RULE `p * h + l:num = y ==> (y == x) (mod p) ==> (x == l) (mod p)`)) THEN REWRITE_TAC[CONG; VAL_WORD; VAL_WORD_MUL; DIMINDEX_64] THEN CONV_TAC MOD_DOWN_CONV THEN REWRITE_TAC[GSYM CONG] THEN MATCH_MP_TAC(NUMBER_RULE `(a * b == 1) (mod p) ==> (a * x * b == x) (mod p)`) THEN REWRITE_TAC[CONG] THEN CONV_TAC NUM_REDUCE_CONV);; let BIGNUM_MONTMUL_P256K1_ALT_CORRECT = time prove (`!z x y a b pc. nonoverlapping (word pc,0x1e2) (z,8 * 4) ==> ensures x86 (\s. bytes_loaded s (word pc) (BUTLAST bignum_montmul_p256k1_alt_mc) /\ read RIP s = word(pc + 0x9) /\ C_ARGUMENTS [z; x; y] s /\ bignum_from_memory (x,4) s = a /\ bignum_from_memory (y,4) s = b) (\s. read RIP s = word (pc + 0x1d8) /\ (a * b <= 2 EXP 256 * p_256k1 ==> bignum_from_memory (z,4) s = (inverse_mod p_256k1 (2 EXP 256) * a * b) MOD p_256k1)) (MAYCHANGE [RIP; RSI; RAX; RBX; RCX; RDX; R8; R9; R10; R11; R12; R13; R14; R15] ,, MAYCHANGE [memory :> bytes(z,8 * 4)] ,, MAYCHANGE SOME_FLAGS)`, MAP_EVERY X_GEN_TAC [`z:int64`; `x:int64`; `y:int64`; `a:num`; `b:num`; `pc:num`] THEN REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN * * Globalize the a * b < = 2 EXP 256 * p_256k1 assumption * * ASM_CASES_TAC `a * b <= 2 EXP 256 * p_256k1` THENL [ASM_REWRITE_TAC[]; X86_SIM_TAC BIGNUM_MONTMUL_P256K1_ALT_EXEC (1--133)] THEN ENSURES_INIT_TAC "s0" THEN BIGNUM_DIGITIZE_TAC "x_" `bignum_from_memory (x,4) s0` THEN BIGNUM_DIGITIZE_TAC "y_" `bignum_from_memory (y,4) s0` THEN * * The initial multiplication , separate from Montgomery reduction * * X86_ACCSTEPS_TAC BIGNUM_MONTMUL_P256K1_ALT_EXEC (1--84) (1--84) THEN ABBREV_TAC `l = bignum_of_wordlist [mullo_s3; sum_s14; sum_s30; sum_s51; sum_s67; sum_s78; sum_s83; sum_s84]` THEN SUBGOAL_THEN `a * b = l` SUBST_ALL_TAC THENL [MAP_EVERY EXPAND_TAC ["l"; "a"; "b"] THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist] THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_ARITH_TAC; ACCUMULATOR_POP_ASSUM_LIST(K ALL_TAC)] THEN * * The main Montgomery reduction to 4 words plus 1 bit * * X86_ACCSTEPS_TAC BIGNUM_MONTMUL_P256K1_ALT_EXEC [89;90;91;94;96;100;102;106;108;109;110;111;112;113;114;115] (85--116) THEN RULE_ASSUM_TAC(REWRITE_RULE[WORD_NEG_EQ_0; WORD_BITVAL_EQ_0]) THEN RULE_ASSUM_TAC(fun th -> try MATCH_MP mmlemma th with Failure _ -> th) THEN ABBREV_TAC `t = bignum_of_wordlist[sum_s112; sum_s113; sum_s114; sum_s115; word(bitval(carry_s115))]` THEN SUBGOAL_THEN `t < 2 * p_256k1 /\ (2 EXP 256 * t == l) (mod p_256k1)` STRIP_ASSUME_TAC THENL [ACCUMULATOR_POP_ASSUM_LIST (STRIP_ASSUME_TAC o end_itlist CONJ o DECARRY_RULE) THEN CONJ_TAC THENL [FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (ARITH_RULE `ab <= 2 EXP 256 * p ==> 2 EXP 256 * t < ab + 2 EXP 256 * p ==> t < 2 * p`)) THEN MAP_EVERY EXPAND_TAC ["l"; "t"] THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist] THEN REWRITE_TAC[p_256k1; REAL_ARITH `a:real < b + c <=> a - b < c`] THEN ASM_REWRITE_TAC[VAL_WORD_BITVAL] THEN BOUNDER_TAC[]; REWRITE_TAC[REAL_CONGRUENCE; p_256k1] THEN CONV_TAC NUM_REDUCE_CONV THEN MAP_EVERY EXPAND_TAC ["l"; "t"] THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist] THEN ASM_REWRITE_TAC[VAL_WORD_BITVAL] THEN REAL_INTEGER_TAC]; ACCUMULATOR_POP_ASSUM_LIST(K ALL_TAC)] THEN (*** Final correction stage ***) X86_ACCSTEPS_TAC BIGNUM_MONTMUL_P256K1_ALT_EXEC [118;120;122;124] (117--133) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN TRANS_TAC EQ_TRANS `t MOD p_256k1` THEN CONJ_TAC THENL [ALL_TAC; REWRITE_TAC[GSYM CONG] THEN FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (NUMBER_RULE `(e * t == l) (mod p) ==> (e * i == 1) (mod p) ==> (t == i * l) (mod p)`)) THEN REWRITE_TAC[INVERSE_MOD_RMUL_EQ; COPRIME_REXP; COPRIME_2] THEN REWRITE_TAC[p_256k1] THEN CONV_TAC NUM_REDUCE_CONV] THEN CONV_TAC SYM_CONV THEN MATCH_MP_TAC EQUAL_FROM_CONGRUENT_MOD_MOD THEN MAP_EVERY EXISTS_TAC [`256`; `if t < p_256k1 then &t:real else &t - &p_256k1`] THEN REPEAT CONJ_TAC THENL [REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN BOUNDER_TAC[]; REWRITE_TAC[p_256k1] THEN ARITH_TAC; REWRITE_TAC[p_256k1] THEN ARITH_TAC; ALL_TAC; ASM_SIMP_TAC[MOD_CASES] THEN GEN_REWRITE_TAC LAND_CONV [COND_RAND] THEN SIMP_TAC[REAL_OF_NUM_SUB; GSYM NOT_LT]] THEN (*** The slightly wacky comparison and hence the final result ***) SUBGOAL_THEN `2 EXP 64 <= val(word_neg(word(bitval carry_s115):int64)) + 18446744073709551615 + bitval carry_s124 <=> p_256k1 <= t` SUBST_ALL_TAC THENL [EXPAND_TAC "t" THEN BOOL_CASES_TAC `carry_s115:bool` THEN ASM_REWRITE_TAC[BITVAL_CLAUSES; p_256k1; bignum_of_wordlist] THEN CONV_TAC(DEPTH_CONV WORD_NUM_RED_CONV) THENL [ARITH_TAC; ALL_TAC] THEN TRANS_TAC EQ_TRANS `carry_s124:bool` THEN CONJ_TAC THENL [REWRITE_TAC[bitval] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN ARITH_TAC; ALL_TAC] THEN MATCH_MP_TAC FLAG_FROM_CARRY_LE THEN EXISTS_TAC `256` THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[]; REWRITE_TAC[GSYM NOT_LT; COND_SWAP]] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN EXPAND_TAC "t" THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist; p_256k1] THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN ASM_REWRITE_TAC[BITVAL_CLAUSES; VAL_WORD_BITVAL] THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_INTEGER_TAC);; let BIGNUM_MONTMUL_P256K1_ALT_SUBROUTINE_CORRECT = time prove (`!z x y a b pc stackpointer returnaddress. nonoverlapping (z,8 * 4) (word_sub stackpointer (word 40),48) /\ ALL (nonoverlapping (word_sub stackpointer (word 40),40)) [(word pc,0x1e2); (x,8 * 4); (y,8 * 4)] /\ nonoverlapping (word pc,0x1e2) (z,8 * 4) ==> ensures x86 (\s. bytes_loaded s (word pc) bignum_montmul_p256k1_alt_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ C_ARGUMENTS [z; x; y] s /\ bignum_from_memory (x,4) s = a /\ bignum_from_memory (y,4) s = b) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ (a * b <= 2 EXP 256 * p_256k1 ==> bignum_from_memory (z,4) s = (inverse_mod p_256k1 (2 EXP 256) * a * b) MOD p_256k1)) (MAYCHANGE [RIP; RSP; RSI; RAX; RCX; RDX; R8; R9; R10; R11] ,, MAYCHANGE [memory :> bytes(z,8 * 4); memory :> bytes(word_sub stackpointer (word 40),40)] ,, MAYCHANGE SOME_FLAGS)`, X86_PROMOTE_RETURN_STACK_TAC bignum_montmul_p256k1_alt_mc BIGNUM_MONTMUL_P256K1_ALT_CORRECT `[RBX; R12; R13; R14; R15]` 40);; (* ------------------------------------------------------------------------- *) (* Correctness of Windows ABI version. *) (* ------------------------------------------------------------------------- *) let windows_bignum_montmul_p256k1_alt_mc = define_from_elf "windows_bignum_montmul_p256k1_alt_mc" "x86/secp256k1/bignum_montmul_p256k1_alt.obj";; let WINDOWS_BIGNUM_MONTMUL_P256K1_ALT_SUBROUTINE_CORRECT = time prove (`!z x y a b pc stackpointer returnaddress. nonoverlapping (z,8 * 4) (word_sub stackpointer (word 56),64) /\ ALL (nonoverlapping (word_sub stackpointer (word 56),56)) [(word pc,0x1ef); (x,8 * 4); (y,8 * 4)] /\ nonoverlapping (word pc,0x1ef) (z,8 * 4) ==> ensures x86 (\s. bytes_loaded s (word pc) windows_bignum_montmul_p256k1_alt_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ WINDOWS_C_ARGUMENTS [z; x; y] s /\ bignum_from_memory (x,4) s = a /\ bignum_from_memory (y,4) s = b) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ (a * b <= 2 EXP 256 * p_256k1 ==> bignum_from_memory (z,4) s = (inverse_mod p_256k1 (2 EXP 256) * a * b) MOD p_256k1)) (MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,, MAYCHANGE [memory :> bytes(z,8 * 4); memory :> bytes(word_sub stackpointer (word 56),56)] ,, MAYCHANGE SOME_FLAGS)`, WINDOWS_X86_WRAP_STACK_TAC windows_bignum_montmul_p256k1_alt_mc bignum_montmul_p256k1_alt_mc BIGNUM_MONTMUL_P256K1_ALT_CORRECT `[RBX; R12; R13; R14; R15]` 40);;
null
https://raw.githubusercontent.com/awslabs/s2n-bignum/824c15f908d7a343af1b2f378cfedd36e880bdde/x86/proofs/bignum_montmul_p256k1_alt.ml
ocaml
========================================================================= Montgomery multiply mod p_256k1, the field characteristic for secp256k1. ========================================================================= *** print_literal_from_elf "x86/secp256k1/bignum_montmul_p256k1_alt.o";; *** PUSH (% rbx) PUSH (% r12) PUSH (% r13) PUSH (% r14) PUSH (% r15) XOR (% r10) (% r10) XOR (% r11) (% r11) ADD (% r9) (% rax) ADC (% r10) (% rdx) ADD (% r9) (% rax) ADC (% r10) (% rdx) ADC (% r11) (% r11) XOR (% r12) (% r12) ADD (% r10) (% rax) ADC (% r11) (% rdx) ADC (% r12) (% r12) ADD (% r10) (% rax) ADC (% r11) (% rdx) ADC (% r12) (Imm8 (word 0)) ADD (% r10) (% rax) ADC (% r11) (% rdx) ADC (% r12) (Imm8 (word 0)) XOR (% r13) (% r13) ADD (% r11) (% rax) ADC (% r12) (% rdx) ADC (% r13) (% r13) ADD (% r11) (% rax) ADC (% r12) (% rdx) ADC (% r13) (Imm8 (word 0)) ADD (% r11) (% rax) ADC (% r12) (% rdx) ADC (% r13) (Imm8 (word 0)) ADD (% r11) (% rax) ADC (% r12) (% rdx) ADC (% r13) (Imm8 (word 0)) XOR (% r14) (% r14) ADD (% r12) (% rax) ADC (% r13) (% rdx) ADC (% r14) (% r14) ADD (% r12) (% rax) ADC (% r13) (% rdx) ADC (% r14) (Imm8 (word 0)) ADD (% r12) (% rax) ADC (% r13) (% rdx) ADC (% r14) (Imm8 (word 0)) XOR (% r15) (% r15) ADD (% r13) (% rax) ADC (% r14) (% rdx) ADC (% r15) (% r15) ADD (% r13) (% rax) ADC (% r14) (% rdx) ADC (% r15) (Imm8 (word 0)) ADD (% r14) (% rax) ADC (% r15) (% rdx) SUB (% r9) (% rdx) NEG (% rcx) NEG (% rcx) NEG (% rcx) ADD (% r12) (% r8) ADC (% r13) (% r9) ADC (% r14) (% r10) ADC (% r15) (% r11) ADD (% r8) (% rbx) ADC (% r9) (Imm8 (word 0)) ADC (% r10) (Imm8 (word 0)) ADC (% r11) (Imm8 (word 0)) POP (% r15) POP (% r14) POP (% r13) POP (% r12) POP (% rbx) ------------------------------------------------------------------------- Proof. ------------------------------------------------------------------------- ** Final correction stage ** ** The slightly wacky comparison and hence the final result ** ------------------------------------------------------------------------- Correctness of Windows ABI version. -------------------------------------------------------------------------
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved . * SPDX - License - Identifier : Apache-2.0 OR ISC * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 OR ISC *) let bignum_montmul_p256k1_alt_mc = define_assert_from_elf "bignum_montmul_p256k1_alt_mc" "x86/secp256k1/bignum_montmul_p256k1_alt.o" [ MOV ( % rcx ) ( % rdx ) MOV ( % rax ) ( ( % % ( rsi,0 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,0 ) ) ) MOV ( % r8 ) ( % rax ) MOV ( % r9 ) ( % rdx ) MOV ( % rax ) ( ( % % ( rsi,0 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,8 ) ) ) MOV ( % rax ) ( ( % % ( rsi,8 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,0 ) ) ) MOV ( % rax ) ( ( % % ( rsi,0 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,16 ) ) ) MOV ( % rax ) ( ( % % ( rsi,8 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,8 ) ) ) MOV ( % rax ) ( ( % % ( rsi,16 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,0 ) ) ) MOV ( % rax ) ( ( % % ( rsi,0 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,24 ) ) ) MOV ( % rax ) ( ( % % ( rsi,8 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,16 ) ) ) MOV ( % rax ) ( ( % % ( rsi,16 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,8 ) ) ) MOV ( % rax ) ( ( % % ( rsi,24 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,0 ) ) ) MOV ( % rax ) ( ( % % ( rsi,8 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,24 ) ) ) MOV ( % rax ) ( ( % % ( rsi,16 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,16 ) ) ) MOV ( % rax ) ( ( % % ( rsi,24 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,8 ) ) ) MOV ( % rax ) ( ( % % ( rsi,16 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,24 ) ) ) MOV ( % rax ) ( ( % % ( rsi,24 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,16 ) ) ) MOV ( % rax ) ( ( % % ( rsi,24 ) ) ) MUL2 ( % rdx,% rax ) ( ( % % ( rcx,24 ) ) ) 0x48; 0xbe; 0x31; 0x35; 0x25; 0xd2; 0x1d; 0x09; 0x38; 0xd8; MOV ( % rsi ) ( Imm64 ( word 15580212934572586289 ) ) 0x48; 0xbb; 0xd1; 0x03; 0x00; 0x00; 0x01; 0x00; 0x00; 0x00; MOV ( % rbx ) ( Imm64 ( word 4294968273 ) ) MOV ( % rax ) ( % rbx ) IMUL ( % r8 ) ( % rsi ) MUL2 ( % rdx,% rax ) ( % r8 ) SBB ( % rcx ) ( % rcx ) MOV ( % rax ) ( % rbx ) IMUL ( % r9 ) ( % rsi ) MUL2 ( % rdx,% rax ) ( % r9 ) SBB ( % r10 ) ( % rdx ) SBB ( % rcx ) ( % rcx ) MOV ( % rax ) ( % rbx ) IMUL ( % r10 ) ( % rsi ) MUL2 ( % rdx,% rax ) ( % r10 ) SBB ( % r11 ) ( % rdx ) SBB ( % rcx ) ( % rcx ) MOV ( % rax ) ( % rbx ) IMUL ( % r11 ) ( % rsi ) MUL2 ( % rdx,% rax ) ( % r11 ) SBB ( % r8 ) ( % rdx ) SBB ( % r9 ) ( Imm8 ( word 0 ) ) SBB ( % r10 ) ( Imm8 ( word 0 ) ) SBB ( % r11 ) ( Imm8 ( word 0 ) ) SBB ( % rsi ) ( % rsi ) MOV ( % r8 ) ( % r12 ) MOV ( % r9 ) ( % r13 ) MOV ( % r10 ) ( % r14 ) MOV ( % r11 ) ( % r15 ) ADC ( % rsi ) ( Imm8 ( word 255 ) ) CMOVB ( % r12 ) ( % r8 ) MOV ( ( % % ( rdi,0 ) ) ) ( % r12 ) CMOVB ( % r13 ) ( % r9 ) MOV ( ( % % ( rdi,8 ) ) ) ( % r13 ) CMOVB ( % r14 ) ( % r10 ) MOV ( ( % % ( rdi,16 ) ) ) ( % r14 ) CMOVB ( % r15 ) ( % r11 ) MOV ( ( % % ( ) ) ) ( % r15 ) RET ];; let BIGNUM_MONTMUL_P256K1_ALT_EXEC = X86_MK_CORE_EXEC_RULE bignum_montmul_p256k1_alt_mc;; let p_256k1 = new_definition `p_256k1 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F`;; let mmlemma = prove (`!h (l:int64) (x:int64). &2 pow 64 * &h + &(val(l:int64)):real = &4294968273 * &(val(word_mul x (word 15580212934572586289):int64)) ==> &2 pow 64 * &h + &(val(x:int64)):real = &4294968273 * &(val(word_mul x (word 15580212934572586289):int64))`, REPEAT GEN_TAC THEN REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN REPEAT STRIP_TAC THEN FIRST_ASSUM(SUBST1_TAC o SYM) THEN AP_TERM_TAC THEN AP_TERM_TAC THEN REWRITE_TAC[GSYM VAL_CONG; DIMINDEX_64] THEN FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (NUMBER_RULE `p * h + l:num = y ==> (y == x) (mod p) ==> (x == l) (mod p)`)) THEN REWRITE_TAC[CONG; VAL_WORD; VAL_WORD_MUL; DIMINDEX_64] THEN CONV_TAC MOD_DOWN_CONV THEN REWRITE_TAC[GSYM CONG] THEN MATCH_MP_TAC(NUMBER_RULE `(a * b == 1) (mod p) ==> (a * x * b == x) (mod p)`) THEN REWRITE_TAC[CONG] THEN CONV_TAC NUM_REDUCE_CONV);; let BIGNUM_MONTMUL_P256K1_ALT_CORRECT = time prove (`!z x y a b pc. nonoverlapping (word pc,0x1e2) (z,8 * 4) ==> ensures x86 (\s. bytes_loaded s (word pc) (BUTLAST bignum_montmul_p256k1_alt_mc) /\ read RIP s = word(pc + 0x9) /\ C_ARGUMENTS [z; x; y] s /\ bignum_from_memory (x,4) s = a /\ bignum_from_memory (y,4) s = b) (\s. read RIP s = word (pc + 0x1d8) /\ (a * b <= 2 EXP 256 * p_256k1 ==> bignum_from_memory (z,4) s = (inverse_mod p_256k1 (2 EXP 256) * a * b) MOD p_256k1)) (MAYCHANGE [RIP; RSI; RAX; RBX; RCX; RDX; R8; R9; R10; R11; R12; R13; R14; R15] ,, MAYCHANGE [memory :> bytes(z,8 * 4)] ,, MAYCHANGE SOME_FLAGS)`, MAP_EVERY X_GEN_TAC [`z:int64`; `x:int64`; `y:int64`; `a:num`; `b:num`; `pc:num`] THEN REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN * * Globalize the a * b < = 2 EXP 256 * p_256k1 assumption * * ASM_CASES_TAC `a * b <= 2 EXP 256 * p_256k1` THENL [ASM_REWRITE_TAC[]; X86_SIM_TAC BIGNUM_MONTMUL_P256K1_ALT_EXEC (1--133)] THEN ENSURES_INIT_TAC "s0" THEN BIGNUM_DIGITIZE_TAC "x_" `bignum_from_memory (x,4) s0` THEN BIGNUM_DIGITIZE_TAC "y_" `bignum_from_memory (y,4) s0` THEN * * The initial multiplication , separate from Montgomery reduction * * X86_ACCSTEPS_TAC BIGNUM_MONTMUL_P256K1_ALT_EXEC (1--84) (1--84) THEN ABBREV_TAC `l = bignum_of_wordlist [mullo_s3; sum_s14; sum_s30; sum_s51; sum_s67; sum_s78; sum_s83; sum_s84]` THEN SUBGOAL_THEN `a * b = l` SUBST_ALL_TAC THENL [MAP_EVERY EXPAND_TAC ["l"; "a"; "b"] THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist] THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_ARITH_TAC; ACCUMULATOR_POP_ASSUM_LIST(K ALL_TAC)] THEN * * The main Montgomery reduction to 4 words plus 1 bit * * X86_ACCSTEPS_TAC BIGNUM_MONTMUL_P256K1_ALT_EXEC [89;90;91;94;96;100;102;106;108;109;110;111;112;113;114;115] (85--116) THEN RULE_ASSUM_TAC(REWRITE_RULE[WORD_NEG_EQ_0; WORD_BITVAL_EQ_0]) THEN RULE_ASSUM_TAC(fun th -> try MATCH_MP mmlemma th with Failure _ -> th) THEN ABBREV_TAC `t = bignum_of_wordlist[sum_s112; sum_s113; sum_s114; sum_s115; word(bitval(carry_s115))]` THEN SUBGOAL_THEN `t < 2 * p_256k1 /\ (2 EXP 256 * t == l) (mod p_256k1)` STRIP_ASSUME_TAC THENL [ACCUMULATOR_POP_ASSUM_LIST (STRIP_ASSUME_TAC o end_itlist CONJ o DECARRY_RULE) THEN CONJ_TAC THENL [FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (ARITH_RULE `ab <= 2 EXP 256 * p ==> 2 EXP 256 * t < ab + 2 EXP 256 * p ==> t < 2 * p`)) THEN MAP_EVERY EXPAND_TAC ["l"; "t"] THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist] THEN REWRITE_TAC[p_256k1; REAL_ARITH `a:real < b + c <=> a - b < c`] THEN ASM_REWRITE_TAC[VAL_WORD_BITVAL] THEN BOUNDER_TAC[]; REWRITE_TAC[REAL_CONGRUENCE; p_256k1] THEN CONV_TAC NUM_REDUCE_CONV THEN MAP_EVERY EXPAND_TAC ["l"; "t"] THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist] THEN ASM_REWRITE_TAC[VAL_WORD_BITVAL] THEN REAL_INTEGER_TAC]; ACCUMULATOR_POP_ASSUM_LIST(K ALL_TAC)] THEN X86_ACCSTEPS_TAC BIGNUM_MONTMUL_P256K1_ALT_EXEC [118;120;122;124] (117--133) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN TRANS_TAC EQ_TRANS `t MOD p_256k1` THEN CONJ_TAC THENL [ALL_TAC; REWRITE_TAC[GSYM CONG] THEN FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (NUMBER_RULE `(e * t == l) (mod p) ==> (e * i == 1) (mod p) ==> (t == i * l) (mod p)`)) THEN REWRITE_TAC[INVERSE_MOD_RMUL_EQ; COPRIME_REXP; COPRIME_2] THEN REWRITE_TAC[p_256k1] THEN CONV_TAC NUM_REDUCE_CONV] THEN CONV_TAC SYM_CONV THEN MATCH_MP_TAC EQUAL_FROM_CONGRUENT_MOD_MOD THEN MAP_EVERY EXISTS_TAC [`256`; `if t < p_256k1 then &t:real else &t - &p_256k1`] THEN REPEAT CONJ_TAC THENL [REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN BOUNDER_TAC[]; REWRITE_TAC[p_256k1] THEN ARITH_TAC; REWRITE_TAC[p_256k1] THEN ARITH_TAC; ALL_TAC; ASM_SIMP_TAC[MOD_CASES] THEN GEN_REWRITE_TAC LAND_CONV [COND_RAND] THEN SIMP_TAC[REAL_OF_NUM_SUB; GSYM NOT_LT]] THEN SUBGOAL_THEN `2 EXP 64 <= val(word_neg(word(bitval carry_s115):int64)) + 18446744073709551615 + bitval carry_s124 <=> p_256k1 <= t` SUBST_ALL_TAC THENL [EXPAND_TAC "t" THEN BOOL_CASES_TAC `carry_s115:bool` THEN ASM_REWRITE_TAC[BITVAL_CLAUSES; p_256k1; bignum_of_wordlist] THEN CONV_TAC(DEPTH_CONV WORD_NUM_RED_CONV) THENL [ARITH_TAC; ALL_TAC] THEN TRANS_TAC EQ_TRANS `carry_s124:bool` THEN CONJ_TAC THENL [REWRITE_TAC[bitval] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN ARITH_TAC; ALL_TAC] THEN MATCH_MP_TAC FLAG_FROM_CARRY_LE THEN EXISTS_TAC `256` THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[]; REWRITE_TAC[GSYM NOT_LT; COND_SWAP]] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN EXPAND_TAC "t" THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist; p_256k1] THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN ASM_REWRITE_TAC[BITVAL_CLAUSES; VAL_WORD_BITVAL] THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_INTEGER_TAC);; let BIGNUM_MONTMUL_P256K1_ALT_SUBROUTINE_CORRECT = time prove (`!z x y a b pc stackpointer returnaddress. nonoverlapping (z,8 * 4) (word_sub stackpointer (word 40),48) /\ ALL (nonoverlapping (word_sub stackpointer (word 40),40)) [(word pc,0x1e2); (x,8 * 4); (y,8 * 4)] /\ nonoverlapping (word pc,0x1e2) (z,8 * 4) ==> ensures x86 (\s. bytes_loaded s (word pc) bignum_montmul_p256k1_alt_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ C_ARGUMENTS [z; x; y] s /\ bignum_from_memory (x,4) s = a /\ bignum_from_memory (y,4) s = b) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ (a * b <= 2 EXP 256 * p_256k1 ==> bignum_from_memory (z,4) s = (inverse_mod p_256k1 (2 EXP 256) * a * b) MOD p_256k1)) (MAYCHANGE [RIP; RSP; RSI; RAX; RCX; RDX; R8; R9; R10; R11] ,, MAYCHANGE [memory :> bytes(z,8 * 4); memory :> bytes(word_sub stackpointer (word 40),40)] ,, MAYCHANGE SOME_FLAGS)`, X86_PROMOTE_RETURN_STACK_TAC bignum_montmul_p256k1_alt_mc BIGNUM_MONTMUL_P256K1_ALT_CORRECT `[RBX; R12; R13; R14; R15]` 40);; let windows_bignum_montmul_p256k1_alt_mc = define_from_elf "windows_bignum_montmul_p256k1_alt_mc" "x86/secp256k1/bignum_montmul_p256k1_alt.obj";; let WINDOWS_BIGNUM_MONTMUL_P256K1_ALT_SUBROUTINE_CORRECT = time prove (`!z x y a b pc stackpointer returnaddress. nonoverlapping (z,8 * 4) (word_sub stackpointer (word 56),64) /\ ALL (nonoverlapping (word_sub stackpointer (word 56),56)) [(word pc,0x1ef); (x,8 * 4); (y,8 * 4)] /\ nonoverlapping (word pc,0x1ef) (z,8 * 4) ==> ensures x86 (\s. bytes_loaded s (word pc) windows_bignum_montmul_p256k1_alt_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ WINDOWS_C_ARGUMENTS [z; x; y] s /\ bignum_from_memory (x,4) s = a /\ bignum_from_memory (y,4) s = b) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ (a * b <= 2 EXP 256 * p_256k1 ==> bignum_from_memory (z,4) s = (inverse_mod p_256k1 (2 EXP 256) * a * b) MOD p_256k1)) (MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,, MAYCHANGE [memory :> bytes(z,8 * 4); memory :> bytes(word_sub stackpointer (word 56),56)] ,, MAYCHANGE SOME_FLAGS)`, WINDOWS_X86_WRAP_STACK_TAC windows_bignum_montmul_p256k1_alt_mc bignum_montmul_p256k1_alt_mc BIGNUM_MONTMUL_P256K1_ALT_CORRECT `[RBX; R12; R13; R14; R15]` 40);;
8149e56f3a30eaf888385dddc20e40fe05d58f071cc6f22f2d7d41d13b93273b
yesodweb/wai
CleanPath.hs
# LANGUAGE CPP # module Network.Wai.Middleware.CleanPath ( cleanPath ) where import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy as L #if __GLASGOW_HASKELL__ < 710 import Data.Monoid (mconcat) #endif import Data.Text (Text) import Network.HTTP.Types (hLocation, status301) import Network.Wai (Application, pathInfo, rawQueryString, responseLBS) cleanPath :: ([Text] -> Either B.ByteString [Text]) -> B.ByteString -> ([Text] -> Application) -> Application cleanPath splitter prefix app env sendResponse = case splitter $ pathInfo env of Right pieces -> app pieces env sendResponse Left p -> sendResponse $ responseLBS status301 [(hLocation, mconcat [prefix, p, suffix])] L.empty where -- include the query string if present suffix = case B.uncons $ rawQueryString env of Nothing -> B.empty Just ('?', _) -> rawQueryString env _ -> B.cons '?' $ rawQueryString env
null
https://raw.githubusercontent.com/yesodweb/wai/5d1fd4926d0f210eb77c2bc0e546cb3cca6bc197/wai-extra/Network/Wai/Middleware/CleanPath.hs
haskell
include the query string if present
# LANGUAGE CPP # module Network.Wai.Middleware.CleanPath ( cleanPath ) where import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy as L #if __GLASGOW_HASKELL__ < 710 import Data.Monoid (mconcat) #endif import Data.Text (Text) import Network.HTTP.Types (hLocation, status301) import Network.Wai (Application, pathInfo, rawQueryString, responseLBS) cleanPath :: ([Text] -> Either B.ByteString [Text]) -> B.ByteString -> ([Text] -> Application) -> Application cleanPath splitter prefix app env sendResponse = case splitter $ pathInfo env of Right pieces -> app pieces env sendResponse Left p -> sendResponse $ responseLBS status301 [(hLocation, mconcat [prefix, p, suffix])] L.empty where suffix = case B.uncons $ rawQueryString env of Nothing -> B.empty Just ('?', _) -> rawQueryString env _ -> B.cons '?' $ rawQueryString env
6b5995c5f3a3ae901c46790841bfea83038a4a29192b80fdd57387194d549be4
spurious/snd-mirror
tread.scm
(load "write.scm") (load "s7test-block.so" (sublet (curlet) (cons 'init_func 'block_init))) (set! (*s7* 'print-length) 8) ; :readable should ignore this (set! (*s7* 'default-hash-table-length) 4) ( set ! ( * s7 * ' heap - size ) ( * 10 1024000 ) ) (define (tester) (do ((baddies 0) (size 3 (+ size 1))) ((= size 4)) (format *stderr* "~%-------- ~D --------~%" size) (do ((tries (* 2000 (expt 3 size))) (k 0 (+ k 1))) ((or (= k tries) (> baddies 1))) (let ((cp-lst (make-list 3 #f)) (it-lst (make-list 3 #f))) (let ((bases (vector (make-list 3 #f) (make-vector 3 #f) (make-cycle #f) (hash-table 'a 1 'b 2 'c 3) (inlet 'a 1 'b 2 'c 3) (make-iterator it-lst) (c-pointer 1 cp-lst))) (sets ()) (b1 0) (b2 0)) (do ((i 0 (+ i 1)) (r1 (random 7) (random 7)) (r2 (random 7) (random 7)) (loc (random 3) (random 3))) ((= i size)) (set! b1 (bases r1)) (set! b2 (bases r2)) (case (type-of b1) ((pair?) (if (> (random 10) 3) (begin (set! (b1 loc) b2) (set! sets (cons (list r1 loc r2) sets))) (begin (set-cdr! (cddr b1) (case loc ((0) b1) ((1) (cdr b1)) (else (cddr b1)))) (set! sets (cons (list r1 (+ loc 3) r2) sets))))) ((vector?) (set! (b1 loc) b2) (set! sets (cons (list r1 loc r2) sets))) ((c-object?) (set! (b1 0) b2) (set! sets (cons (list r1 0 r2) sets))) ((hash-table? let?) (let ((key (#(a b c) loc))) (set! (b1 key) b2) (set! sets (cons (list r1 key r2) sets)))) ((c-pointer?) (set! (cp-lst loc) b2) (set! sets (cons (list r1 loc r2) sets))) ((iterator?) (set! (it-lst loc) b2) (set! sets (cons (list r1 loc r2) sets))))) (let ((bi 0)) (for-each (lambda (x) (let ((str (object->string x :readable))) (unless (equal? x (eval-string str)) (set! baddies (+ baddies 1)) (format *stderr* "x: ~S~%" x) (format *stderr* "ex: ~S~%" (eval-string str)) (format *stderr* "sets: ~S~%" (reverse sets)) (format *stderr* "str: ~S~%" str) (pretty-print (with-input-from-string str read) *stderr* 0) (format *stderr* "~%~%") (format *stderr* " (let ((p (make-list 3 #f)) (v (make-vector 3 #f)) (cy (make-cycle #f)) (h (hash-table 'a 1 'b 2 'c 3)) (e (inlet 'a 1 'b 2 'c 3)) (it (make-iterator (make-list 3 #f))) (cp (c-pointer 1 (make-list 3 #f)))) ") (for-each (lambda (set) (cond ((and (zero? (car set)) (> (cadr set) 2)) (format *stderr* " (set-cdr! (list-tail p 2) ~A)~%" (#("p" "(cdr p)" "(cddr p)") (- (cadr set) 3)))) ((< (car set) 5) (format *stderr* " (set! (~A ~A) ~A)~%" (#(p v cy h e) (car set)) (case (car set) ((0 1) (cadr set)) ((2) 0) ((3) (format #f "~W" (cadr set))) ((4) (symbol->keyword (cadr set)))) (#(p v cy h e it cp) (caddr set)))) ((= (car set) 5) (format *stderr* " (set! ((iterator-sequence it) ~A) ~A)~%" (cadr set) (#(p v cy h e it cp) (caddr set)))) (else (format *stderr* " (set! (((object->let cp) 'c-type) ~A) ~A)~%" (cadr set) (#(p v cy h e it cp) (caddr set)))))) sets) (format *stderr* " ~A)~%" (#(p v cy h e it cp) bi))) (set! bi (+ bi 1)))) bases))))))) (tester) (when (> (*s7* 'profile) 0) (show-profile 200)) (exit)
null
https://raw.githubusercontent.com/spurious/snd-mirror/8e7a643c840592797c29384ffe07c87ba5c0a3eb/tools/tread.scm
scheme
:readable should ignore this
(load "write.scm") (load "s7test-block.so" (sublet (curlet) (cons 'init_func 'block_init))) (set! (*s7* 'default-hash-table-length) 4) ( set ! ( * s7 * ' heap - size ) ( * 10 1024000 ) ) (define (tester) (do ((baddies 0) (size 3 (+ size 1))) ((= size 4)) (format *stderr* "~%-------- ~D --------~%" size) (do ((tries (* 2000 (expt 3 size))) (k 0 (+ k 1))) ((or (= k tries) (> baddies 1))) (let ((cp-lst (make-list 3 #f)) (it-lst (make-list 3 #f))) (let ((bases (vector (make-list 3 #f) (make-vector 3 #f) (make-cycle #f) (hash-table 'a 1 'b 2 'c 3) (inlet 'a 1 'b 2 'c 3) (make-iterator it-lst) (c-pointer 1 cp-lst))) (sets ()) (b1 0) (b2 0)) (do ((i 0 (+ i 1)) (r1 (random 7) (random 7)) (r2 (random 7) (random 7)) (loc (random 3) (random 3))) ((= i size)) (set! b1 (bases r1)) (set! b2 (bases r2)) (case (type-of b1) ((pair?) (if (> (random 10) 3) (begin (set! (b1 loc) b2) (set! sets (cons (list r1 loc r2) sets))) (begin (set-cdr! (cddr b1) (case loc ((0) b1) ((1) (cdr b1)) (else (cddr b1)))) (set! sets (cons (list r1 (+ loc 3) r2) sets))))) ((vector?) (set! (b1 loc) b2) (set! sets (cons (list r1 loc r2) sets))) ((c-object?) (set! (b1 0) b2) (set! sets (cons (list r1 0 r2) sets))) ((hash-table? let?) (let ((key (#(a b c) loc))) (set! (b1 key) b2) (set! sets (cons (list r1 key r2) sets)))) ((c-pointer?) (set! (cp-lst loc) b2) (set! sets (cons (list r1 loc r2) sets))) ((iterator?) (set! (it-lst loc) b2) (set! sets (cons (list r1 loc r2) sets))))) (let ((bi 0)) (for-each (lambda (x) (let ((str (object->string x :readable))) (unless (equal? x (eval-string str)) (set! baddies (+ baddies 1)) (format *stderr* "x: ~S~%" x) (format *stderr* "ex: ~S~%" (eval-string str)) (format *stderr* "sets: ~S~%" (reverse sets)) (format *stderr* "str: ~S~%" str) (pretty-print (with-input-from-string str read) *stderr* 0) (format *stderr* "~%~%") (format *stderr* " (let ((p (make-list 3 #f)) (v (make-vector 3 #f)) (cy (make-cycle #f)) (h (hash-table 'a 1 'b 2 'c 3)) (e (inlet 'a 1 'b 2 'c 3)) (it (make-iterator (make-list 3 #f))) (cp (c-pointer 1 (make-list 3 #f)))) ") (for-each (lambda (set) (cond ((and (zero? (car set)) (> (cadr set) 2)) (format *stderr* " (set-cdr! (list-tail p 2) ~A)~%" (#("p" "(cdr p)" "(cddr p)") (- (cadr set) 3)))) ((< (car set) 5) (format *stderr* " (set! (~A ~A) ~A)~%" (#(p v cy h e) (car set)) (case (car set) ((0 1) (cadr set)) ((2) 0) ((3) (format #f "~W" (cadr set))) ((4) (symbol->keyword (cadr set)))) (#(p v cy h e it cp) (caddr set)))) ((= (car set) 5) (format *stderr* " (set! ((iterator-sequence it) ~A) ~A)~%" (cadr set) (#(p v cy h e it cp) (caddr set)))) (else (format *stderr* " (set! (((object->let cp) 'c-type) ~A) ~A)~%" (cadr set) (#(p v cy h e it cp) (caddr set)))))) sets) (format *stderr* " ~A)~%" (#(p v cy h e it cp) bi))) (set! bi (+ bi 1)))) bases))))))) (tester) (when (> (*s7* 'profile) 0) (show-profile 200)) (exit)
473648c97f1dcf96baae59100e2b2e35e15fd53bb3966b1c5459cbd5796a9781
TristeFigure/shuriken
pprint_meta_test.clj
(ns shuriken.monkey-patches.pprint-meta-test (:require [clojure.test :refer :all] [clojure.pprint :refer [pprint]] [shuriken.monkey-patches.pprint-meta])) (deftest test-pprint-meta (binding [clojure.pprint/*print-meta* true] (testing "works globally" (let [coll ^{:meta 1} [' ^{:meta 2} a (with-meta (list ^{:meta 4} [:list]) {:meta 3}) ^{:meta 5} [^{:meta 6} [:vector]] ^{:meta 7} #{^{:meta 8} [:set]} ^{:meta 9} {^{:meta 10} [' ^{:meta 11} key] ^{:meta 12} [' ^{:meta 13} value]} (doto (make-array Object 1) (aset 0 ^{:meta 14} [:array])) '(ns ^{:meta 15} some.namespace (:gen-class :methods [^{:meta 16} [m [] int]])) '(binding [^{:meta 17} truc 123] truc) '(var some-var) (with-meta (into clojure.lang.PersistentQueue/EMPTY [1 2 3]) {:meta 18})]] (is (= (str "^{:meta 1}\n" " [^{:meta 2} a\n" " ^{:meta 3} (^{:meta 4} [:list])\n" " ^{:meta 5} [^{:meta 6} [:vector]]\n" " ^{:meta 7} #{^{:meta 8} [:set]}\n" " ^{:meta 9}\n" " {^{:meta 10} [^{:meta 11} key] ^{:meta 12} [^{:meta 13} value]}\n" " [^{:meta 14} [:array]]\n" " ^{:line 18, :column 31}\n" " (ns\n" " ^{:meta 15} some.namespace\n" " ^{:line 19, :column 32}\n" " (:gen-class :methods [^{:meta 16} [m [] int]]))\n" " ^{:line 21, :column 31} (binding [^{:meta 17} truc 123] truc)\n" " ^{:line 22, :column 31} #'some-var\n" " ^{:meta 18} <-(1 2 3)-<]\n") (with-out-str (pprint coll)))))) (testing "doesn't print metas in metas by default" (is (= "^{:meta [2]} [1]\n" (with-out-str (pprint ^{:meta ^{:meta [3]} [2]} [1]))))) (testing "prints metas in metas on command" (is (= "^{:meta ^{:meta [3]} [2]} [1]\n" (binding [clojure.pprint/*print-metas-in-metas* true] (with-out-str (pprint ^{:meta ^{:meta [3]} [2]} [1])))))) (testing "shorthands" (is (= "^Object [123]\n" (with-out-str (pprint ^Object [123])))) (is (= "^Object ^:static ^:dynamic ^{:meta :yes} [123]\n" (with-out-str (pprint ^Object ^:dynamic ^:static ^{:meta :yes} [123]))))) (testing "vars (IMeta but not IObj)" (is (= "^{:ns nil, :name nil} #<Var: --unnamed-->\n" (with-local-vars [x 1] (with-out-str (pprint x))))))))
null
https://raw.githubusercontent.com/TristeFigure/shuriken/cd36dd2a4005c85260125d89d5a3f475d248e6e4/test/shuriken/monkey_patches/pprint_meta_test.clj
clojure
(ns shuriken.monkey-patches.pprint-meta-test (:require [clojure.test :refer :all] [clojure.pprint :refer [pprint]] [shuriken.monkey-patches.pprint-meta])) (deftest test-pprint-meta (binding [clojure.pprint/*print-meta* true] (testing "works globally" (let [coll ^{:meta 1} [' ^{:meta 2} a (with-meta (list ^{:meta 4} [:list]) {:meta 3}) ^{:meta 5} [^{:meta 6} [:vector]] ^{:meta 7} #{^{:meta 8} [:set]} ^{:meta 9} {^{:meta 10} [' ^{:meta 11} key] ^{:meta 12} [' ^{:meta 13} value]} (doto (make-array Object 1) (aset 0 ^{:meta 14} [:array])) '(ns ^{:meta 15} some.namespace (:gen-class :methods [^{:meta 16} [m [] int]])) '(binding [^{:meta 17} truc 123] truc) '(var some-var) (with-meta (into clojure.lang.PersistentQueue/EMPTY [1 2 3]) {:meta 18})]] (is (= (str "^{:meta 1}\n" " [^{:meta 2} a\n" " ^{:meta 3} (^{:meta 4} [:list])\n" " ^{:meta 5} [^{:meta 6} [:vector]]\n" " ^{:meta 7} #{^{:meta 8} [:set]}\n" " ^{:meta 9}\n" " {^{:meta 10} [^{:meta 11} key] ^{:meta 12} [^{:meta 13} value]}\n" " [^{:meta 14} [:array]]\n" " ^{:line 18, :column 31}\n" " (ns\n" " ^{:meta 15} some.namespace\n" " ^{:line 19, :column 32}\n" " (:gen-class :methods [^{:meta 16} [m [] int]]))\n" " ^{:line 21, :column 31} (binding [^{:meta 17} truc 123] truc)\n" " ^{:line 22, :column 31} #'some-var\n" " ^{:meta 18} <-(1 2 3)-<]\n") (with-out-str (pprint coll)))))) (testing "doesn't print metas in metas by default" (is (= "^{:meta [2]} [1]\n" (with-out-str (pprint ^{:meta ^{:meta [3]} [2]} [1]))))) (testing "prints metas in metas on command" (is (= "^{:meta ^{:meta [3]} [2]} [1]\n" (binding [clojure.pprint/*print-metas-in-metas* true] (with-out-str (pprint ^{:meta ^{:meta [3]} [2]} [1])))))) (testing "shorthands" (is (= "^Object [123]\n" (with-out-str (pprint ^Object [123])))) (is (= "^Object ^:static ^:dynamic ^{:meta :yes} [123]\n" (with-out-str (pprint ^Object ^:dynamic ^:static ^{:meta :yes} [123]))))) (testing "vars (IMeta but not IObj)" (is (= "^{:ns nil, :name nil} #<Var: --unnamed-->\n" (with-local-vars [x 1] (with-out-str (pprint x))))))))
b32b0da923a93fcf9bc3c45c1575753b4db3220d440051540628f6efd9aed037
bufferswap/ViralityEngine
camera-following.lisp
(in-package #:virality.component) (v:define-component following-camera () ((%slave :reader slave) (%target-actor :accessor target-actor :initarg :target-actor) (%target-transform :reader target-transform) (%offset :reader offset :initarg :offset :initform (v3:zero)))) (defmethod camera-target-actor ((camera following-camera) actor) (with-slots (%target-transform) camera (setf (target-actor camera) actor) (when actor (setf %target-transform (v:component-by-type actor 'transform))))) (defmethod v:on-component-initialize ((self following-camera)) (with-slots (%slave) self (setf %slave (v:component-by-type (v:actor self) 'camera)) (camera-target-actor self (target-actor self)))) (defmethod v:on-component-update ((self following-camera)) (with-slots (%transform) (slave self) (let* ((target-position (m4:get-translation (v:get-model-matrix (target-transform self)))) (new-camera-position (v3:+! target-position target-position (offset self))) (model (v:get-model-matrix self))) (m4:set-translation! model model new-camera-position) (compute-camera-view (slave self)))))
null
https://raw.githubusercontent.com/bufferswap/ViralityEngine/df7bb4dffaecdcb6fdcbfa618031a5e1f85f4002/src/components/camera-following.lisp
lisp
(in-package #:virality.component) (v:define-component following-camera () ((%slave :reader slave) (%target-actor :accessor target-actor :initarg :target-actor) (%target-transform :reader target-transform) (%offset :reader offset :initarg :offset :initform (v3:zero)))) (defmethod camera-target-actor ((camera following-camera) actor) (with-slots (%target-transform) camera (setf (target-actor camera) actor) (when actor (setf %target-transform (v:component-by-type actor 'transform))))) (defmethod v:on-component-initialize ((self following-camera)) (with-slots (%slave) self (setf %slave (v:component-by-type (v:actor self) 'camera)) (camera-target-actor self (target-actor self)))) (defmethod v:on-component-update ((self following-camera)) (with-slots (%transform) (slave self) (let* ((target-position (m4:get-translation (v:get-model-matrix (target-transform self)))) (new-camera-position (v3:+! target-position target-position (offset self))) (model (v:get-model-matrix self))) (m4:set-translation! model model new-camera-position) (compute-camera-view (slave self)))))
2e3d35d3000f6c271f738220041a1a79cf860237a20d01e176c5e5ed248af922
ocaml/odoc
test.mli
module CanonicalTest : sig module Base__List : sig type 'a t val id : 'a t -> 'a t end module Base__ : sig module List = Base__List (** @canonical Test.CanonicalTest.Base.List *) end module Base : sig module List = Base__.List end module Base_Tests : sig module C : module type of Base__.List open Base__ module L = List val baz : 'a Base__.List.t -> unit (** We can't reference [Base__] because it's hidden. {!List.t} ([List.t]) should resolve. *) end end val test : 'a CanonicalTest.Base__.List.t -> unit
null
https://raw.githubusercontent.com/ocaml/odoc/45c73070c9f45d305d84fa6a9cbd73025b321944/test/xref2/hidden_modules.t/test.mli
ocaml
* @canonical Test.CanonicalTest.Base.List * We can't reference [Base__] because it's hidden. {!List.t} ([List.t]) should resolve.
module CanonicalTest : sig module Base__List : sig type 'a t val id : 'a t -> 'a t end module Base__ : sig module List = Base__List end module Base : sig module List = Base__.List end module Base_Tests : sig module C : module type of Base__.List open Base__ module L = List val baz : 'a Base__.List.t -> unit end end val test : 'a CanonicalTest.Base__.List.t -> unit
32bf5c8160c675f8cfa720c34275116800ec4d080c72d47169c9291ee23ddcdd
flyspeck/flyspeck
glpk_link.ml
(* ========================================================================== *) FLYSPECK - BOOK FORMALIZATION (* *) Linear Programming Link Author : Date : 2010 - 05 - 19 (* ========================================================================== *) (* This file contains material that does not depend on the details of the LP. list processing functions, IO operations, glpk function calls. *) module Glpk_link = struct needs new mktop on platforms that do not support dynamic loading of Str . ocamlmktop unix.cma nums.cma str.cma -o ocampl ./ocampl glpk needs to be installed , and glpsol needs to be found in the path . needs lib.ml from HOL Light and flyspeck_lib.hl from Flyspeck . needs new mktop on platforms that do not support dynamic loading of Str. ocamlmktop unix.cma nums.cma str.cma -o ocampl ./ocampl glpk needs to be installed, and glpsol needs to be found in the path. needs lib.ml from HOL Light and flyspeck_lib.hl from Flyspeck. *) open Str;; open List;; let sprintf = Printf.sprintf;; let (nextc,resetc) = let counter = ref 0 in ((fun () -> counter:= !counter + 1; !counter),(fun () -> (counter :=0)));; (* list operations *) NB : value is always at least 0 let get_values key xs = map snd (find_all (function k,_ -> (k=key)) xs);; let rec sort cmp lis = ( * from HOL Light lib.ml let rec sort cmp lis = (* from HOL Light lib.ml *) match lis with [] -> [] | piv::rest -> let r,l = partition (cmp piv) rest in (sort cmp l) @ (piv::(sort cmp r));; *) let sort = Lib.sort;; let (--) = Lib.(--);; let rec ( -- ) = fun m n - > if m > n then [ ] else m::((m + 1 ) -- n ) ; ; ( * from HOL Light lib.ml let rec (--) = fun m n -> if m > n then [] else m::((m + 1) -- n);; (* from HOL Light lib.ml *) *) let up i = 0 -- (i-1);; let rec rotateL i xs = if i=0 then xs else match xs with | x::xss -> rotateL ((i-1) mod length xs) (xss @ [x]) | [] -> [];; let rotateR i = rotateL (-i);; let rotation xs = let maxsz = maxlist0 (map length xs) in flatten (map (fun i -> map (rotateL i) xs) (up maxsz));; zip from 's lib.ml . List.combine causes a stack overflow : let tt = up 30000 in combine tt tt ; ; Stack overflow during evaluation ( looping recursion ? ) . let rec zip l1 l2 = match ( l1,l2 ) with ( [ ] , [ ] ) - > [ ] | ( h1::t1,h2::t2 ) - > ( h1,h2)::(zip t1 t2 ) | _ - > failwith " zip " ; ; zip from Harrison's lib.ml. List.combine causes a stack overflow : let tt = up 30000 in combine tt tt;; Stack overflow during evaluation (looping recursion?). let rec zip l1 l2 = match (l1,l2) with ([],[]) -> [] | (h1::t1,h2::t2) -> (h1,h2)::(zip t1 t2) | _ -> failwith "zip";; *) let zip = Lib.zip;; let enumerate xs = zip (up (length xs)) xs;; let whereis i xs = let (p,_) = find (function _,j -> j=i) (enumerate xs) in p;; let wheremod xs x = let ys = rotation xs in (whereis x ys) mod (length xs);; (* example *) 2 let unsplit = Flyspeck_lib.unsplit;; let nub = Flyspeck_lib.nub;; let join_lines = Flyspeck_lib.join_lines;; let rec nub = function | [ ] - > [ ] | x::xs - > x::filter ( ( ! ) ( nub xs ) ; ; let unsplit d f = function | ( x::xs ) - > fold_left ( fun s t - > s^d^(f t ) ) ( f x ) xs | [ ] - > " " ; ; let = unsplit " \n " ( fun x- > x ) ; ; let rec nub = function | [] -> [] | x::xs -> x::filter ((!=) x) (nub xs);; let unsplit d f = function | (x::xs) -> fold_left (fun s t -> s^d^(f t)) (f x) xs | [] -> "";; let join_lines = unsplit "\n" (fun x-> x);; *) (* read and write *) let load_and_close_channel do_close ic = let rec lf ichan a = try lf ic ( Pervasives.input_line ) with End_of_file - > a in let rs = lf ic [ ] in if do_close then Pervasives.close_in ic else ( ) ; rev rs ; ; let load_file filename = let ic = Pervasives.open_in filename in load_and_close_channel true ic ; ; let load_and_close_channel do_close ic = let rec lf ichan a = try lf ic (Pervasives.input_line ic::a) with End_of_file -> a in let rs = lf ic [] in if do_close then Pervasives.close_in ic else (); rev rs;; let load_file filename = let ic = Pervasives.open_in filename in load_and_close_channel true ic;; *) let load_and_close_channel = Flyspeck_lib.load_and_close_channel;; let load_file = Flyspeck_lib.load_file;; let save_stringarray filename xs = let oc = open_out filename in for i=0 to length xs -1 do Pervasives.output_string oc (nth xs i ^ "\n"); done; close_out oc;; let strip_archive filename = (* strip // comments, blank lines, quotation marks etc. *) let (ic,oc) = Unix.open_process(sprintf "cat %s | grep -v '=' | grep -v 'list' | grep -v '^//' | grep -v '^$' | grep '^[^a-z/-]' | sed 's/\"[,;]*//g' | sed 's/_//g' " filename) in let s = load_and_close_channel false ic in let _ = Unix.close_process (ic,oc) in s;; (* example of java style string from hypermap generator. *) let pentstring = "13_150834109178 18 3 0 1 2 3 3 2 7 3 3 0 2 4 5 4 0 3 4 6 1 0 4 3 7 2 8 3 8 2 1 4 8 1 6 9 3 9 6 10 3 10 6 4 3 10 4 5 4 5 3 7 11 3 10 5 11 3 11 7 12 3 12 7 8 3 12 8 9 3 9 10 11 3 11 12 9 ";; (* conversion to list. e.g. convert_to_list pentstring *) let convert_to_list3 = let split_sp= Str.split (Str.regexp " +") in let strip_ = Str.global_replace (Str.regexp "_") "" in let rec movelist n (x,a) = if n=0 then (x,a) else match x with y::ys -> movelist (n-1) (ys, y::a) in let getone (x,a) = match x with | [] -> ([],a) | y::ys -> let (u,v) = movelist y (ys,[]) in (u,v::a) in let rec getall (x,a) = if (x=[]) then (x,a) else getall (getone (x,a)) in fun s -> let h::ss = (split_sp (strip_ s)) in let _::ns = map int_of_string ss in let (_,a) = getall (ns,[]) in (h,s,rev (map rev a));; let convert_to_list = (fun (h,_,ls) -> (h,ls)) o convert_to_list3;; let convert_to_list = let split_sp= Str.split ( regexp " + " ) in let strip _ = global_replace ( regexp " _ " ) " " in let rec movelist n ( x , a ) = if then ( x , a ) else match x with y::ys - > ( n-1 ) ( ys , y::a ) in let getone ( x , a ) = match x with | [ ] - > ( [ ] , a ) | y::ys - > let ( u , v ) = movelist y ( ys , [ ] ) in ( u , v::a ) in let rec getall ( x , a ) = if ( x= [ ] ) then ( x , a ) else ( getone ( x , a ) ) in fun s - > let ( split_sp ( strip _ s ) ) in let _ : : ns = map ss in let ( _ , a ) = getall ( ns , [ ] ) in ( h , rev ( map rev a ) ) ; ; let convert_to_list = let split_sp= Str.split (regexp " +") in let strip_ = global_replace (regexp "_") "" in let rec movelist n (x,a) = if n=0 then (x,a) else match x with y::ys -> movelist (n-1) (ys, y::a) in let getone (x,a) = match x with | [] -> ([],a) | y::ys -> let (u,v) = movelist y (ys,[]) in (u,v::a) in let rec getall (x,a) = if (x=[]) then (x,a) else getall (getone (x,a)) in fun s -> let h::ss = (split_sp (strip_ s)) in let _::ns = map int_of_string ss in let (_,a) = getall (ns,[]) in (h,rev (map rev a));; *) Linear programming let display_ampl ampl_datafile ampl_of_bb bb = (* for debugging *) let outs = open_out ampl_datafile in let _ = ampl_of_bb outs bb in let _ = close_out outs in Sys.command(sprintf "cat %s" ampl_datafile);; (* model should name the optimal value "optival" *) let solve_counter=ref 0;; let solve com model glpk_outfile varname ampl_of_bb bb = let (ic,oc) = Unix.open_process(com) in let _ = ampl_of_bb oc bb in let _ = close_out oc in let _ = (solve_counter := !solve_counter + 1) in let inp = load_and_close_channel false ic in let _ = Unix.close_process (ic,oc) in test for no feasible solution . There are two different messages . let _ = Sys.command("cat " ^ glpk_outfile ) in ( * debug let com2 = sprintf "grep \"PROBLEM HAS NO.*FEASIBLE SOLUTION\" %s" glpk_outfile in let (ic,oc) =Unix.open_process(com2) in let inp2 = load_and_close_channel false ic in let _ = Unix.close_process(ic,oc) in (inp2,inp);; let solve_branch_f model glpk_outfile varname ampl_of_bb bb = let com = sprintf "glpsol -m %s -d /dev/stdin | tee %s | grep '^%s' | sed 's/.val//' | sed 's/%s = //' " model glpk_outfile varname varname in solve com model glpk_outfile varname ampl_of_bb bb;; let solve_dual_f model glpk_outfile varname ampl_of_bb bb = let com = sprintf "glpsol -m %s -d /dev/stdin --simplex --exact --dual -w /tmp/dual.out --output /tmp/output.out | tee %s | grep '^%s' | sed 's/.val//' | sed 's/%s = //' " model glpk_outfile varname varname in solve com model glpk_outfile varname ampl_of_bb bb;; let display_lp model ampl_datafile glpk_outfile ampl_of_bb bb = let oc = open_out ampl_datafile in let _ = ampl_of_bb oc bb in let _ = close_out oc in let com = sprintf "glpsol -m %s -d %s | tee %s" model ampl_datafile glpk_outfile in let _ = Sys.command(com) in ();; let cpx_branch model cpxfile ampl_of_bb bb = (* debug *) let com = sprintf "glpsol -m %s --wcpxlp %s -d /dev/stdin | grep '^opti' | sed 's/optival = //' " model cpxfile in let (ic,oc) = Unix.open_process(com) in let _ = ampl_of_bb oc bb in let _ = close_out oc in let _ = load_and_close_channel false ic in let _ = Unix.close_process (ic,oc) in sprintf "cplex file created of lp: %s" cpxfile;; (* for debugging: reading optimal variables values from the glpk_outfile *) let get_dumpvar glpk_outfile s = (* read variables from glpk_outfile *) let com = sprintf "grep '%s' %s | sed 's/^.*= //' " s glpk_outfile in let (ic,oc) = Unix.open_process(com) in let _ = close_out oc in let inp = load_and_close_channel false ic in let _ = Unix.close_process(ic,oc) in inp;; (* get_dumpvar "yn.0.*=";; *) end;;
null
https://raw.githubusercontent.com/flyspeck/flyspeck/05bd66666b4b641f49e5131a37830f4881f39db9/formal_lp/glpk/glpk_link.ml
ocaml
========================================================================== ========================================================================== This file contains material that does not depend on the details of the LP. list processing functions, IO operations, glpk function calls. list operations from HOL Light lib.ml from HOL Light lib.ml example read and write strip // comments, blank lines, quotation marks etc. example of java style string from hypermap generator. conversion to list. e.g. convert_to_list pentstring for debugging model should name the optimal value "optival" debug for debugging: reading optimal variables values from the glpk_outfile read variables from glpk_outfile get_dumpvar "yn.0.*=";;
FLYSPECK - BOOK FORMALIZATION Linear Programming Link Author : Date : 2010 - 05 - 19 module Glpk_link = struct needs new mktop on platforms that do not support dynamic loading of Str . ocamlmktop unix.cma nums.cma str.cma -o ocampl ./ocampl glpk needs to be installed , and glpsol needs to be found in the path . needs lib.ml from HOL Light and flyspeck_lib.hl from Flyspeck . needs new mktop on platforms that do not support dynamic loading of Str. ocamlmktop unix.cma nums.cma str.cma -o ocampl ./ocampl glpk needs to be installed, and glpsol needs to be found in the path. needs lib.ml from HOL Light and flyspeck_lib.hl from Flyspeck. *) open Str;; open List;; let sprintf = Printf.sprintf;; let (nextc,resetc) = let counter = ref 0 in ((fun () -> counter:= !counter + 1; !counter),(fun () -> (counter :=0)));; NB : value is always at least 0 let get_values key xs = map snd (find_all (function k,_ -> (k=key)) xs);; let rec sort cmp lis = ( * from HOL Light lib.ml match lis with [] -> [] | piv::rest -> let r,l = partition (cmp piv) rest in (sort cmp l) @ (piv::(sort cmp r));; *) let sort = Lib.sort;; let (--) = Lib.(--);; let rec ( -- ) = fun m n - > if m > n then [ ] else m::((m + 1 ) -- n ) ; ; ( * from HOL Light lib.ml *) let up i = 0 -- (i-1);; let rec rotateL i xs = if i=0 then xs else match xs with | x::xss -> rotateL ((i-1) mod length xs) (xss @ [x]) | [] -> [];; let rotateR i = rotateL (-i);; let rotation xs = let maxsz = maxlist0 (map length xs) in flatten (map (fun i -> map (rotateL i) xs) (up maxsz));; zip from 's lib.ml . List.combine causes a stack overflow : let tt = up 30000 in combine tt tt ; ; Stack overflow during evaluation ( looping recursion ? ) . let rec zip l1 l2 = match ( l1,l2 ) with ( [ ] , [ ] ) - > [ ] | ( h1::t1,h2::t2 ) - > ( h1,h2)::(zip t1 t2 ) | _ - > failwith " zip " ; ; zip from Harrison's lib.ml. List.combine causes a stack overflow : let tt = up 30000 in combine tt tt;; Stack overflow during evaluation (looping recursion?). let rec zip l1 l2 = match (l1,l2) with ([],[]) -> [] | (h1::t1,h2::t2) -> (h1,h2)::(zip t1 t2) | _ -> failwith "zip";; *) let zip = Lib.zip;; let enumerate xs = zip (up (length xs)) xs;; let whereis i xs = let (p,_) = find (function _,j -> j=i) (enumerate xs) in p;; let wheremod xs x = let ys = rotation xs in (whereis x ys) mod (length xs);; 2 let unsplit = Flyspeck_lib.unsplit;; let nub = Flyspeck_lib.nub;; let join_lines = Flyspeck_lib.join_lines;; let rec nub = function | [ ] - > [ ] | x::xs - > x::filter ( ( ! ) ( nub xs ) ; ; let unsplit d f = function | ( x::xs ) - > fold_left ( fun s t - > s^d^(f t ) ) ( f x ) xs | [ ] - > " " ; ; let = unsplit " \n " ( fun x- > x ) ; ; let rec nub = function | [] -> [] | x::xs -> x::filter ((!=) x) (nub xs);; let unsplit d f = function | (x::xs) -> fold_left (fun s t -> s^d^(f t)) (f x) xs | [] -> "";; let join_lines = unsplit "\n" (fun x-> x);; *) let load_and_close_channel do_close ic = let rec lf ichan a = try lf ic ( Pervasives.input_line ) with End_of_file - > a in let rs = lf ic [ ] in if do_close then Pervasives.close_in ic else ( ) ; rev rs ; ; let load_file filename = let ic = Pervasives.open_in filename in load_and_close_channel true ic ; ; let load_and_close_channel do_close ic = let rec lf ichan a = try lf ic (Pervasives.input_line ic::a) with End_of_file -> a in let rs = lf ic [] in if do_close then Pervasives.close_in ic else (); rev rs;; let load_file filename = let ic = Pervasives.open_in filename in load_and_close_channel true ic;; *) let load_and_close_channel = Flyspeck_lib.load_and_close_channel;; let load_file = Flyspeck_lib.load_file;; let save_stringarray filename xs = let oc = open_out filename in for i=0 to length xs -1 do Pervasives.output_string oc (nth xs i ^ "\n"); done; close_out oc;; let (ic,oc) = Unix.open_process(sprintf "cat %s | grep -v '=' | grep -v 'list' | grep -v '^//' | grep -v '^$' | grep '^[^a-z/-]' | sed 's/\"[,;]*//g' | sed 's/_//g' " filename) in let s = load_and_close_channel false ic in let _ = Unix.close_process (ic,oc) in s;; let pentstring = "13_150834109178 18 3 0 1 2 3 3 2 7 3 3 0 2 4 5 4 0 3 4 6 1 0 4 3 7 2 8 3 8 2 1 4 8 1 6 9 3 9 6 10 3 10 6 4 3 10 4 5 4 5 3 7 11 3 10 5 11 3 11 7 12 3 12 7 8 3 12 8 9 3 9 10 11 3 11 12 9 ";; let convert_to_list3 = let split_sp= Str.split (Str.regexp " +") in let strip_ = Str.global_replace (Str.regexp "_") "" in let rec movelist n (x,a) = if n=0 then (x,a) else match x with y::ys -> movelist (n-1) (ys, y::a) in let getone (x,a) = match x with | [] -> ([],a) | y::ys -> let (u,v) = movelist y (ys,[]) in (u,v::a) in let rec getall (x,a) = if (x=[]) then (x,a) else getall (getone (x,a)) in fun s -> let h::ss = (split_sp (strip_ s)) in let _::ns = map int_of_string ss in let (_,a) = getall (ns,[]) in (h,s,rev (map rev a));; let convert_to_list = (fun (h,_,ls) -> (h,ls)) o convert_to_list3;; let convert_to_list = let split_sp= Str.split ( regexp " + " ) in let strip _ = global_replace ( regexp " _ " ) " " in let rec movelist n ( x , a ) = if then ( x , a ) else match x with y::ys - > ( n-1 ) ( ys , y::a ) in let getone ( x , a ) = match x with | [ ] - > ( [ ] , a ) | y::ys - > let ( u , v ) = movelist y ( ys , [ ] ) in ( u , v::a ) in let rec getall ( x , a ) = if ( x= [ ] ) then ( x , a ) else ( getone ( x , a ) ) in fun s - > let ( split_sp ( strip _ s ) ) in let _ : : ns = map ss in let ( _ , a ) = getall ( ns , [ ] ) in ( h , rev ( map rev a ) ) ; ; let convert_to_list = let split_sp= Str.split (regexp " +") in let strip_ = global_replace (regexp "_") "" in let rec movelist n (x,a) = if n=0 then (x,a) else match x with y::ys -> movelist (n-1) (ys, y::a) in let getone (x,a) = match x with | [] -> ([],a) | y::ys -> let (u,v) = movelist y (ys,[]) in (u,v::a) in let rec getall (x,a) = if (x=[]) then (x,a) else getall (getone (x,a)) in fun s -> let h::ss = (split_sp (strip_ s)) in let _::ns = map int_of_string ss in let (_,a) = getall (ns,[]) in (h,rev (map rev a));; *) Linear programming let outs = open_out ampl_datafile in let _ = ampl_of_bb outs bb in let _ = close_out outs in Sys.command(sprintf "cat %s" ampl_datafile);; let solve_counter=ref 0;; let solve com model glpk_outfile varname ampl_of_bb bb = let (ic,oc) = Unix.open_process(com) in let _ = ampl_of_bb oc bb in let _ = close_out oc in let _ = (solve_counter := !solve_counter + 1) in let inp = load_and_close_channel false ic in let _ = Unix.close_process (ic,oc) in test for no feasible solution . There are two different messages . let _ = Sys.command("cat " ^ glpk_outfile ) in ( * debug let com2 = sprintf "grep \"PROBLEM HAS NO.*FEASIBLE SOLUTION\" %s" glpk_outfile in let (ic,oc) =Unix.open_process(com2) in let inp2 = load_and_close_channel false ic in let _ = Unix.close_process(ic,oc) in (inp2,inp);; let solve_branch_f model glpk_outfile varname ampl_of_bb bb = let com = sprintf "glpsol -m %s -d /dev/stdin | tee %s | grep '^%s' | sed 's/.val//' | sed 's/%s = //' " model glpk_outfile varname varname in solve com model glpk_outfile varname ampl_of_bb bb;; let solve_dual_f model glpk_outfile varname ampl_of_bb bb = let com = sprintf "glpsol -m %s -d /dev/stdin --simplex --exact --dual -w /tmp/dual.out --output /tmp/output.out | tee %s | grep '^%s' | sed 's/.val//' | sed 's/%s = //' " model glpk_outfile varname varname in solve com model glpk_outfile varname ampl_of_bb bb;; let display_lp model ampl_datafile glpk_outfile ampl_of_bb bb = let oc = open_out ampl_datafile in let _ = ampl_of_bb oc bb in let _ = close_out oc in let com = sprintf "glpsol -m %s -d %s | tee %s" model ampl_datafile glpk_outfile in let _ = Sys.command(com) in ();; let com = sprintf "glpsol -m %s --wcpxlp %s -d /dev/stdin | grep '^opti' | sed 's/optival = //' " model cpxfile in let (ic,oc) = Unix.open_process(com) in let _ = ampl_of_bb oc bb in let _ = close_out oc in let _ = load_and_close_channel false ic in let _ = Unix.close_process (ic,oc) in sprintf "cplex file created of lp: %s" cpxfile;; let com = sprintf "grep '%s' %s | sed 's/^.*= //' " s glpk_outfile in let (ic,oc) = Unix.open_process(com) in let _ = close_out oc in let inp = load_and_close_channel false ic in let _ = Unix.close_process(ic,oc) in inp;; end;;
48578504074d921774fd9931b7e38df0c991a2915cf7cc66ae9dc5ebe0f06d5e
Rotaerk/vulkanTest
GLFW.hs
module Graphics.VulkanAux.GLFW where import Data.Acquire.Local import Data.Function import Foreign.Marshal.Alloc import Foreign.Ptr import Foreign.Storable import qualified Graphics.UI.GLFW as GLFW import Graphics.Vulkan.Core_1_0 import Graphics.Vulkan.Ext.VK_KHR_surface import Graphics.VulkanAux.Exception newVulkanGLFWWindowSurface :: VkInstance -> GLFW.Window -> Acquire VkSurfaceKHR newVulkanGLFWWindowSurface vulkanInstance window = ( alloca $ \surfacePtr -> do GLFW.createWindowSurface vulkanInstance window nullPtr surfacePtr & onVkFailureThrow_ "GLFW.createWindowSurface" peek surfacePtr ) `mkAcquire` \surface -> vkDestroySurfaceKHR vulkanInstance surface VK_NULL
null
https://raw.githubusercontent.com/Rotaerk/vulkanTest/228007f3f56ce4200f9fe841ac85292cae044c97/sandbox/sandbox/src/Graphics/VulkanAux/GLFW.hs
haskell
module Graphics.VulkanAux.GLFW where import Data.Acquire.Local import Data.Function import Foreign.Marshal.Alloc import Foreign.Ptr import Foreign.Storable import qualified Graphics.UI.GLFW as GLFW import Graphics.Vulkan.Core_1_0 import Graphics.Vulkan.Ext.VK_KHR_surface import Graphics.VulkanAux.Exception newVulkanGLFWWindowSurface :: VkInstance -> GLFW.Window -> Acquire VkSurfaceKHR newVulkanGLFWWindowSurface vulkanInstance window = ( alloca $ \surfacePtr -> do GLFW.createWindowSurface vulkanInstance window nullPtr surfacePtr & onVkFailureThrow_ "GLFW.createWindowSurface" peek surfacePtr ) `mkAcquire` \surface -> vkDestroySurfaceKHR vulkanInstance surface VK_NULL
288aeca7d04b51bae3330fd93369e2053834b4f2cda54c518be70908026c2db3
lamdu/lamdu
Expr.hs
module Lamdu.GUI.Expr ( make ) where import GUI.Momentu (Responsive) import qualified GUI.Momentu as M import qualified GUI.Momentu.Element as Element import qualified GUI.Momentu.State as GuiState import qualified Lamdu.GUI.Expr.ApplyEdit as ApplyEdit import qualified Lamdu.GUI.Expr.FragmentEdit as FragmentEdit import qualified Lamdu.GUI.Expr.GetVarEdit as GetVarEdit import qualified Lamdu.GUI.Expr.HoleEdit as HoleEdit import qualified Lamdu.GUI.Expr.IfElseEdit as IfElseEdit import qualified Lamdu.GUI.Expr.InjectEdit as InjectEdit import qualified Lamdu.GUI.Expr.LambdaEdit as LambdaEdit import qualified Lamdu.GUI.Expr.LiteralEdit as LiteralEdit import qualified Lamdu.GUI.Expr.NominalEdit as NominalEdit import qualified Lamdu.GUI.Expr.RecordEdit as RecordEdit import Lamdu.GUI.Monad (GuiM) import qualified Lamdu.GUI.Types as ExprGui import qualified Lamdu.GUI.WidgetIds as WidgetIds import qualified Lamdu.Sugar.Types as Sugar import Lamdu.Prelude make :: _ => ExprGui.Expr Sugar.Term i o -> GuiM env i o (Responsive o) make e = makeEditor e & assignCursor where exprHiddenEntityIds = e ^. annotation . Sugar.plHiddenEntityIds myId = e ^. annotation & WidgetIds.fromExprPayload assignCursor x = exprHiddenEntityIds <&> WidgetIds.fromEntityId & foldr (`GuiState.assignCursorPrefix` const myId) x makeEditor :: _ => ExprGui.Expr Sugar.Term i o -> GuiM env i o (Responsive o) makeEditor (Ann (Const pl) body) = case body of Sugar.BodyLabeledApply x -> editor pl x ApplyEdit.makeLabeled Sugar.BodySimpleApply x -> editor pl x ApplyEdit.makeSimple Sugar.BodyPostfixApply x -> editor pl x ApplyEdit.makePostfix Sugar.BodyPostfixFunc x -> editor pl x ApplyEdit.makePostfixFunc Sugar.BodyLam x -> editor pl x LambdaEdit.make Sugar.BodyRecord x -> editor pl x RecordEdit.make Sugar.BodyIfElse x -> editor pl x IfElseEdit.make Sugar.BodyToNom x -> editor pl x NominalEdit.makeToNom Sugar.BodyFragment x -> editor pl x FragmentEdit.make Sugar.BodyNullaryInject x -> editor pl x InjectEdit.makeNullary Sugar.BodyLeaf l -> case l of Sugar.LeafHole x -> editor pl (Const x) HoleEdit.make Sugar.LeafLiteral x -> editor pl (Const x) LiteralEdit.make Sugar.LeafInject x -> editor pl (Const x) InjectEdit.make Sugar.LeafGetVar x -> editor pl (Const x) (GetVarEdit.make GetVarEdit.Normal) & local (Element.elemIdPrefix .~ M.asElemId (WidgetIds.fromExprPayload pl)) editor :: a -> h # Annotated a -> (Annotated a # h -> r) -> r editor pl x f = Ann (Const pl) x & f
null
https://raw.githubusercontent.com/lamdu/lamdu/5b15688e53ccbf7448ff11134b3e51ed082c6b6c/src/Lamdu/GUI/Expr.hs
haskell
module Lamdu.GUI.Expr ( make ) where import GUI.Momentu (Responsive) import qualified GUI.Momentu as M import qualified GUI.Momentu.Element as Element import qualified GUI.Momentu.State as GuiState import qualified Lamdu.GUI.Expr.ApplyEdit as ApplyEdit import qualified Lamdu.GUI.Expr.FragmentEdit as FragmentEdit import qualified Lamdu.GUI.Expr.GetVarEdit as GetVarEdit import qualified Lamdu.GUI.Expr.HoleEdit as HoleEdit import qualified Lamdu.GUI.Expr.IfElseEdit as IfElseEdit import qualified Lamdu.GUI.Expr.InjectEdit as InjectEdit import qualified Lamdu.GUI.Expr.LambdaEdit as LambdaEdit import qualified Lamdu.GUI.Expr.LiteralEdit as LiteralEdit import qualified Lamdu.GUI.Expr.NominalEdit as NominalEdit import qualified Lamdu.GUI.Expr.RecordEdit as RecordEdit import Lamdu.GUI.Monad (GuiM) import qualified Lamdu.GUI.Types as ExprGui import qualified Lamdu.GUI.WidgetIds as WidgetIds import qualified Lamdu.Sugar.Types as Sugar import Lamdu.Prelude make :: _ => ExprGui.Expr Sugar.Term i o -> GuiM env i o (Responsive o) make e = makeEditor e & assignCursor where exprHiddenEntityIds = e ^. annotation . Sugar.plHiddenEntityIds myId = e ^. annotation & WidgetIds.fromExprPayload assignCursor x = exprHiddenEntityIds <&> WidgetIds.fromEntityId & foldr (`GuiState.assignCursorPrefix` const myId) x makeEditor :: _ => ExprGui.Expr Sugar.Term i o -> GuiM env i o (Responsive o) makeEditor (Ann (Const pl) body) = case body of Sugar.BodyLabeledApply x -> editor pl x ApplyEdit.makeLabeled Sugar.BodySimpleApply x -> editor pl x ApplyEdit.makeSimple Sugar.BodyPostfixApply x -> editor pl x ApplyEdit.makePostfix Sugar.BodyPostfixFunc x -> editor pl x ApplyEdit.makePostfixFunc Sugar.BodyLam x -> editor pl x LambdaEdit.make Sugar.BodyRecord x -> editor pl x RecordEdit.make Sugar.BodyIfElse x -> editor pl x IfElseEdit.make Sugar.BodyToNom x -> editor pl x NominalEdit.makeToNom Sugar.BodyFragment x -> editor pl x FragmentEdit.make Sugar.BodyNullaryInject x -> editor pl x InjectEdit.makeNullary Sugar.BodyLeaf l -> case l of Sugar.LeafHole x -> editor pl (Const x) HoleEdit.make Sugar.LeafLiteral x -> editor pl (Const x) LiteralEdit.make Sugar.LeafInject x -> editor pl (Const x) InjectEdit.make Sugar.LeafGetVar x -> editor pl (Const x) (GetVarEdit.make GetVarEdit.Normal) & local (Element.elemIdPrefix .~ M.asElemId (WidgetIds.fromExprPayload pl)) editor :: a -> h # Annotated a -> (Annotated a # h -> r) -> r editor pl x f = Ann (Const pl) x & f
659652caf08f71a0f5a5926e2410f3fce0647849fce2a894f15a56c13f7f2e4b
hyperfiddle/rcf
rcf_test.cljc
(ns hyperfiddle.rcf-test (:require [clojure.test :as t :refer [deftest is testing]] [hyperfiddle.rcf :as rcf :refer [tests]] [matcher-combinators.test] #_[hyperfiddle.rcf.analyzer :as ana]) #?(:clj (:import [clojure.lang ExceptionInfo])) #?(:cljs (:require-macros [hyperfiddle.rcf-test]))) (deftest tap-outside-tests (is (= (with-out-str (rcf/tap 1)) "1\n")) (is (= (rcf/tap 1) 1))) (defmacro my-def [x] `(def ~(vary-meta x assoc :form3 (inc 1) ; evaluated now :form4 (quote (inc 1)) ; interpreted as if evaluated after code emission :form5 (quote (quote (inc 1))) ; escaping interpretation ))) #?(:clj (tests "Custom var meta on def symbol are interpreted as if they were evaluated after emission." CLJ only , no vars in cljs . (my-def ^{:form1 (quote (inc 1)) :form2 (inc 1)} ; read and evaluated as usual x) (:form1 (meta #'x)) := '(inc 1) (:form2 (meta #'x)) := 2 (:form3 (meta #'x)) := 2 (:form4 (meta #'x)) := 2 (:form5 (meta #'x)) := '(inc 1))) (tests issue # 65 (let [f (fn ([a] [a]) ; also check multi arity ([a b] [a b]) ([a b & cs] [a b cs])) g (fn [& args] args) h #(vector %&)] (f 1) := [1] (f 1 2) := [1 2] (f 1 2 3 4) := [1 2 '(3 4)] (g 1 2) := [1 2] (h 1 2) := ['(1 2)] )) (tests "Inline letfn support" (letfn [(descent [x] (cond (pos? x) (dec x) (neg? x) (inc x) :else x)) (is-even? [x] (if (zero? x) true (is-odd? (descent x)))) (is-odd? [x] (if (zero? x) false (is-even? (descent x))))] [(is-even? 0) (is-even? 1) (is-even? 2) (is-even? -2)] := [true false true true] [(is-odd? 0) (is-odd? 2) (is-odd? 3) (is-odd? -3)] := [false false true true])) (tests "! still works" (rcf/! 5) rcf/% := 5) (tests ":throws works in clj(s)" ;; inlining `thrower` leads to "unreachable code" warning (let [thrower #(throw (ex-info "boom" {}))] (thrower) :throws ExceptionInfo)) (tests "matcher-combinators match? works infix" {:a {:b 1}} match? {:a {:b int?}}) (tests "`with` discards in presence of exceptions, too" (try (rcf/with #(rcf/tap :ran) (throw (ex-info "" {}))) (catch ExceptionInfo _)) rcf/% := :ran ) ;; For an unknown reason, `macroexpand-1` acts as identity when runnning ;; tests without a repl. ( defn disable - ci [ f ] ;; (let [gen rcf/*generate-tests* ;; enabled rcf/*enabled*] ;; (alter-var-root #'rcf/*generate-tests* (constantly (not gen))) ;; (alter-var-root #'rcf/*enabled* (constantly (not enabled))) ;; (f) ;; (alter-var-root #'rcf/*generate-tests* (constantly gen)) ;; (alter-var-root #'rcf/*enabled* (constantly enabled)))) ;; ;; (t/use-fixtures :once disable-ci) ;; ( defn tests ' [ & [ body ] ] ;; (apply #'tests nil nil body)) ;; ;; (deftest block-behavior ;; (testing "`tests` behaves like" ( testing " ` cc / comment ` when RCF is disabled . " ;; (binding [rcf/*enabled* false] ( is ( nil ? ( tests ' ' ( 1 : = 1 ) ) ) ) ) ) ( testing " ` cc / do ` when RCF is enabled . " ;; (is (= '(do) (tests'))) ( is (= ' 1 ( tests ' ' ( 1 ) ) ) ) ( is (= ' ( do 1 2 ) ( tests ' ' ( 1 2 ) ) ) ) ) ) ) ;; ;; (deftest nesting ;; (testing "Nested `tests` flattens" ;; (is (= '(do) (tests' '((tests))))) ( is (= ' ( do 1 2 ) ( tests ' ' ( 1 ( tests 2 ) ) ) ) ) ) ) ;; ;; #_(deftest documentation-behavior ;; (testing "`tests` behaves like `t/testing` when a string litteral is followed by an expression." ( is (= ` ( t / testing " a " 1 ) ;; (macroexpand-1 '(tests "a" 1)))))) ;; ;; #_(deftest basic-assertion ;; (testing "Assertion sigils are listed by `t/assert-expr`." ;; (is (contains? (methods t/assert-expr) :default))) ;; (testing "Infix sigils desugares to `is`" ( is (= ` ( t / is (: default 1 1 ) ) ( macroexpand-1 ' ( tests 1 : default 1 ) ) ) ) ) ( testing " rewrites some sigils to avoid conflicts " ; ; extensible by a multimethod ;; (is (= '(clojure.test/is (:hyperfiddle.rcf/= '_ '_)) ;; (macroexpand-1 '(tests _ := _)))))) ;; ;; (comment ;; (alter-var-root #'rcf/*generate-tests* (constantly false)) ;; (rcf/enable! true)) ;; (deftest repl-behavior ;; (testing "`tests` behaves like a REPL" ( testing " where * 1 , * 2 , * 3 referers to previous results . " ( is (= ' ( i / repl 1 * 1 * 2 * 3 ) ( tests * 1 * 1 * 2 * 3 ) ) ) ) ;; (testing "where a `def` form is immediately available after being evaluated." ( is (= ' ( i / repl ( def a 1 ) a ) ( tests * ( def a 1 ) a ) ) ) ( is (= ' ( i / repl ( ( def a identity ) 1 ) ) ( tests * ( ( def a identity ) 1 ) ) ) ) ) ) ) ;; ;; (deftest async-behavior ;; (testing "`tests` can probe for values using `!`" ;; (is (= '(let [[! %] (i/queue)] ( ! 1 ) ) ( tests * ( ! 1 ) ) ) ) ) ;; (testing "`tests` can inspect probed values using `%`" ;; (is (= '(let [[! %] (i/queue)] ( ! 1 ) ;; (%)) ( tests * ( ! 1 ) % ) ) ) ;; (is (= '(let [[! %] (i/queue)] ( ! 1 ) ( % ( fn [ result ] ( i / is (: = result 1 ) ) ) ) ) ( tests * ( ! 1 ) % : = 1 ) ) ) ) ) ;; ;; (deftest repl-macro ( testing " repl behavior " ( testing " supports * 1 * 2 * 3 " ;; (is (= '(let [[push! peek] (i/binding-queue)] ( push ! 1 ) ;; (push! (peek 0)) ( push ! ( peek 1 ) ) ( peek 2 ) ) ' ( i / repl 1 * 1 * 2 * 3 ) ) ) ) ( testing " handles the scenario " ( is (= ' ( do ( def a 1 ) a ) ( tests * ( def a 1 ) a ) ) ) ( is (= ' ( do ( def a identity ) ( a 1 ) ) ( tests * ( ( def a identity ) 1 ) ) ) ) ) ) ) ;; ( macroexpand-1 ` ( tests * 1 : = 1 ) ) ( macroexpand-1 ` ( tests * ( do ( rcf/ ! 1 ) rcf/% : = 1 ) ) )
null
https://raw.githubusercontent.com/hyperfiddle/rcf/6d859fee548d5a2c80cf60ba5b0b4ff803e69f18/test/hyperfiddle/rcf_test.cljc
clojure
evaluated now interpreted as if evaluated after code emission escaping interpretation read and evaluated as usual also check multi arity inlining `thrower` leads to "unreachable code" warning For an unknown reason, `macroexpand-1` acts as identity when runnning tests without a repl. (let [gen rcf/*generate-tests* enabled rcf/*enabled*] (alter-var-root #'rcf/*generate-tests* (constantly (not gen))) (alter-var-root #'rcf/*enabled* (constantly (not enabled))) (f) (alter-var-root #'rcf/*generate-tests* (constantly gen)) (alter-var-root #'rcf/*enabled* (constantly enabled)))) (t/use-fixtures :once disable-ci) (apply #'tests nil nil body)) (deftest block-behavior (testing "`tests` behaves like" (binding [rcf/*enabled* false] (is (= '(do) (tests'))) (deftest nesting (testing "Nested `tests` flattens" (is (= '(do) (tests' '((tests))))) #_(deftest documentation-behavior (testing "`tests` behaves like `t/testing` when a string litteral is followed by an expression." (macroexpand-1 '(tests "a" 1)))))) #_(deftest basic-assertion (testing "Assertion sigils are listed by `t/assert-expr`." (is (contains? (methods t/assert-expr) :default))) (testing "Infix sigils desugares to `is`" ; extensible by a multimethod (is (= '(clojure.test/is (:hyperfiddle.rcf/= '_ '_)) (macroexpand-1 '(tests _ := _)))))) (comment (alter-var-root #'rcf/*generate-tests* (constantly false)) (rcf/enable! true)) (deftest repl-behavior (testing "`tests` behaves like a REPL" (testing "where a `def` form is immediately available after being evaluated." (deftest async-behavior (testing "`tests` can probe for values using `!`" (is (= '(let [[! %] (i/queue)] (testing "`tests` can inspect probed values using `%`" (is (= '(let [[! %] (i/queue)] (%)) (is (= '(let [[! %] (i/queue)] (deftest repl-macro (is (= '(let [[push! peek] (i/binding-queue)] (push! (peek 0))
(ns hyperfiddle.rcf-test (:require [clojure.test :as t :refer [deftest is testing]] [hyperfiddle.rcf :as rcf :refer [tests]] [matcher-combinators.test] #_[hyperfiddle.rcf.analyzer :as ana]) #?(:clj (:import [clojure.lang ExceptionInfo])) #?(:cljs (:require-macros [hyperfiddle.rcf-test]))) (deftest tap-outside-tests (is (= (with-out-str (rcf/tap 1)) "1\n")) (is (= (rcf/tap 1) 1))) (defmacro my-def [x] `(def ~(vary-meta x assoc ))) #?(:clj (tests "Custom var meta on def symbol are interpreted as if they were evaluated after emission." CLJ only , no vars in cljs . (my-def ^{:form1 (quote (inc 1)) x) (:form1 (meta #'x)) := '(inc 1) (:form2 (meta #'x)) := 2 (:form3 (meta #'x)) := 2 (:form4 (meta #'x)) := 2 (:form5 (meta #'x)) := '(inc 1))) (tests issue # 65 ([a b] [a b]) ([a b & cs] [a b cs])) g (fn [& args] args) h #(vector %&)] (f 1) := [1] (f 1 2) := [1 2] (f 1 2 3 4) := [1 2 '(3 4)] (g 1 2) := [1 2] (h 1 2) := ['(1 2)] )) (tests "Inline letfn support" (letfn [(descent [x] (cond (pos? x) (dec x) (neg? x) (inc x) :else x)) (is-even? [x] (if (zero? x) true (is-odd? (descent x)))) (is-odd? [x] (if (zero? x) false (is-even? (descent x))))] [(is-even? 0) (is-even? 1) (is-even? 2) (is-even? -2)] := [true false true true] [(is-odd? 0) (is-odd? 2) (is-odd? 3) (is-odd? -3)] := [false false true true])) (tests "! still works" (rcf/! 5) rcf/% := 5) (tests ":throws works in clj(s)" (let [thrower #(throw (ex-info "boom" {}))] (thrower) :throws ExceptionInfo)) (tests "matcher-combinators match? works infix" {:a {:b 1}} match? {:a {:b int?}}) (tests "`with` discards in presence of exceptions, too" (try (rcf/with #(rcf/tap :ran) (throw (ex-info "" {}))) (catch ExceptionInfo _)) rcf/% := :ran ) ( defn disable - ci [ f ] ( defn tests ' [ & [ body ] ] ( testing " ` cc / comment ` when RCF is disabled . " ( is ( nil ? ( tests ' ' ( 1 : = 1 ) ) ) ) ) ) ( testing " ` cc / do ` when RCF is enabled . " ( is (= ' 1 ( tests ' ' ( 1 ) ) ) ) ( is (= ' ( do 1 2 ) ( tests ' ' ( 1 2 ) ) ) ) ) ) ) ( is (= ' ( do 1 2 ) ( tests ' ' ( 1 ( tests 2 ) ) ) ) ) ) ) ( is (= ` ( t / testing " a " 1 ) ( is (= ` ( t / is (: default 1 1 ) ) ( macroexpand-1 ' ( tests 1 : default 1 ) ) ) ) ) ( testing " where * 1 , * 2 , * 3 referers to previous results . " ( is (= ' ( i / repl 1 * 1 * 2 * 3 ) ( tests * 1 * 1 * 2 * 3 ) ) ) ) ( is (= ' ( i / repl ( def a 1 ) a ) ( tests * ( def a 1 ) a ) ) ) ( is (= ' ( i / repl ( ( def a identity ) 1 ) ) ( tests * ( ( def a identity ) 1 ) ) ) ) ) ) ) ( ! 1 ) ) ( tests * ( ! 1 ) ) ) ) ) ( ! 1 ) ( tests * ( ! 1 ) % ) ) ) ( ! 1 ) ( % ( fn [ result ] ( i / is (: = result 1 ) ) ) ) ) ( tests * ( ! 1 ) % : = 1 ) ) ) ) ) ( testing " repl behavior " ( testing " supports * 1 * 2 * 3 " ( push ! 1 ) ( push ! ( peek 1 ) ) ( peek 2 ) ) ' ( i / repl 1 * 1 * 2 * 3 ) ) ) ) ( testing " handles the scenario " ( is (= ' ( do ( def a 1 ) a ) ( tests * ( def a 1 ) a ) ) ) ( is (= ' ( do ( def a identity ) ( a 1 ) ) ( tests * ( ( def a identity ) 1 ) ) ) ) ) ) ) ( macroexpand-1 ` ( tests * 1 : = 1 ) ) ( macroexpand-1 ` ( tests * ( do ( rcf/ ! 1 ) rcf/% : = 1 ) ) )
9b6de5600d203a4205a14368a6e16409d775a93c4705aa11f25db3ce62381675
ygrek/mldonkey
mp3_ui.mli
(**************************************************************************) Copyright 2003 , 2002 b8_bavard , , , b52_simon INRIA (* *) (* This file is part of mldonkey. *) (* *) is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , (* or (at your option) any later version. *) (* *) 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 mldonkey ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA (* *) (**************************************************************************) (** Graphical user interface functions. *) (** A type to indicate which tag we want to read and write.*) type id3 = * Id3 version 1 * Id3 version 2 * Both id3 versions 1 and 2 (** Make the user edit the tag of the given file. *) val edit_file : id3 -> string -> unit (** Make the user edit the given v1 tag in a window with the given title. *) val edit_tag_v1 : string -> Mp3tag.Id3v1.tag -> unit (** Make the user edit the given v2 tag in a window with the given title. *) val edit_tag_v2 : string -> Mp3tag.Id3v2.tag -> Mp3tag.Id3v2.tag
null
https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/src/utils/mp3tagui/mp3_ui.mli
ocaml
************************************************************************ This file is part of mldonkey. or (at your option) any later version. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ************************************************************************ * Graphical user interface functions. * A type to indicate which tag we want to read and write. * Make the user edit the tag of the given file. * Make the user edit the given v1 tag in a window with the given title. * Make the user edit the given v2 tag in a window with the given title.
Copyright 2003 , 2002 b8_bavard , , , b52_simon INRIA is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , is distributed in the hope that it will be useful , You should have received a copy of the GNU General Public License along with mldonkey ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA type id3 = * Id3 version 1 * Id3 version 2 * Both id3 versions 1 and 2 val edit_file : id3 -> string -> unit val edit_tag_v1 : string -> Mp3tag.Id3v1.tag -> unit val edit_tag_v2 : string -> Mp3tag.Id3v2.tag -> Mp3tag.Id3v2.tag
187a19dffe11549bc5168310a22c339d23d36a224a67e7b1136343216af1395f
haskell-suite/haskell-src-exts
NegativePatterns.hs
f 1 = -1 f (-1) = 1 f ( - 2) = 2 f ( - 3) = 3 data Z a = Higher a a | Same a a | Lower a a infixr 7 `Higher` infixr 6 `Same` infixr 5 `Lower` g :: Z Int -> () g ( -1 `Higher` x) = () g ( - 2 `Same` x) = () g ( - 3 `Lower` x) = ()
null
https://raw.githubusercontent.com/haskell-suite/haskell-src-exts/84a4930e0e5c051b7d9efd20ef7c822d5fc1c33b/tests/examples/NegativePatterns.hs
haskell
f 1 = -1 f (-1) = 1 f ( - 2) = 2 f ( - 3) = 3 data Z a = Higher a a | Same a a | Lower a a infixr 7 `Higher` infixr 6 `Same` infixr 5 `Lower` g :: Z Int -> () g ( -1 `Higher` x) = () g ( - 2 `Same` x) = () g ( - 3 `Lower` x) = ()
a93e5ab0090ab1ab527cf184c99b43ac5b66e27fb9ee2c71dc5cc324ed2f756e
funcool/promesa
exec_test.clj
(ns promesa.tests.exec-test (:require [promesa.core :as p] [promesa.exec.bulkhead :as pbh] [promesa.exec :as px] [clojure.test :as t])) (t/use-fixtures :each (fn [next] (binding [px/*default-executor* (px/forkjoin-executor)] (next) (.shutdown px/*default-executor*)))) (def ^:dynamic *my-dyn-var* nil) (t/deftest check-dynamic-vars-with-dispatch (let [executor (px/single-executor) result (binding [*my-dyn-var* 10] (px/with-dispatch executor (+ *my-dyn-var* 1)))] (t/is (= 11 @result)))) (t/deftest check-dynamic-vars-future (let [result (binding [*my-dyn-var* 10] (p/future (+ *my-dyn-var* 1)))] (t/is (= 11 @result)))) (t/deftest check-dynamic-vars-thread (let [result (binding [*my-dyn-var* 10] (p/thread (+ *my-dyn-var* 1)))] (t/is (= 11 @result)))) (when px/virtual-threads-available? (t/deftest check-dynamic-vars-vthread (let [result (binding [*my-dyn-var* 10] (p/vthread (+ *my-dyn-var* 1)))] (t/is (= 11 @result))))) (t/deftest with-executor-closes-pool-1 (let [executor (px/single-executor)] (px/with-executor ^:interrupt executor (px/with-dispatch executor (Thread/sleep 1000))) (t/is (thrown? java.util.concurrent.RejectedExecutionException (px/submit! executor (constantly nil)))))) (t/deftest with-executor-closes-pool-2 (let [executor (px/single-executor)] (px/with-executor ^:interrupt executor (px/with-dispatch executor (Thread/sleep 1000))) (t/is (thrown? java.util.concurrent.RejectedExecutionException (px/submit! executor (constantly nil)))))) (t/deftest pmap-sample-1 (let [result (->> (range 5) (pmap inc) vec)] (t/is (= result [1 2 3 4 5])))) (t/deftest pmap-sample-2 (let [result (pmap + (range 5) (range 5))] (t/is (= result [0 2 4 6 8]))))
null
https://raw.githubusercontent.com/funcool/promesa/84d727721506af5656f334ba43672445e675e7fe/test/promesa/tests/exec_test.clj
clojure
(ns promesa.tests.exec-test (:require [promesa.core :as p] [promesa.exec.bulkhead :as pbh] [promesa.exec :as px] [clojure.test :as t])) (t/use-fixtures :each (fn [next] (binding [px/*default-executor* (px/forkjoin-executor)] (next) (.shutdown px/*default-executor*)))) (def ^:dynamic *my-dyn-var* nil) (t/deftest check-dynamic-vars-with-dispatch (let [executor (px/single-executor) result (binding [*my-dyn-var* 10] (px/with-dispatch executor (+ *my-dyn-var* 1)))] (t/is (= 11 @result)))) (t/deftest check-dynamic-vars-future (let [result (binding [*my-dyn-var* 10] (p/future (+ *my-dyn-var* 1)))] (t/is (= 11 @result)))) (t/deftest check-dynamic-vars-thread (let [result (binding [*my-dyn-var* 10] (p/thread (+ *my-dyn-var* 1)))] (t/is (= 11 @result)))) (when px/virtual-threads-available? (t/deftest check-dynamic-vars-vthread (let [result (binding [*my-dyn-var* 10] (p/vthread (+ *my-dyn-var* 1)))] (t/is (= 11 @result))))) (t/deftest with-executor-closes-pool-1 (let [executor (px/single-executor)] (px/with-executor ^:interrupt executor (px/with-dispatch executor (Thread/sleep 1000))) (t/is (thrown? java.util.concurrent.RejectedExecutionException (px/submit! executor (constantly nil)))))) (t/deftest with-executor-closes-pool-2 (let [executor (px/single-executor)] (px/with-executor ^:interrupt executor (px/with-dispatch executor (Thread/sleep 1000))) (t/is (thrown? java.util.concurrent.RejectedExecutionException (px/submit! executor (constantly nil)))))) (t/deftest pmap-sample-1 (let [result (->> (range 5) (pmap inc) vec)] (t/is (= result [1 2 3 4 5])))) (t/deftest pmap-sample-2 (let [result (pmap + (range 5) (range 5))] (t/is (= result [0 2 4 6 8]))))
576ba447a8e5b798f419687f3f9efb1cfde38e7876c241939c74c83a6c25dfea
simplegeo/erlang
sofs_SUITE.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2001 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% -module(sofs_SUITE). %-define(debug, true). -ifdef(debug). -define(format(S, A), io:format(S, A)). -define(line, put(line, ?LINE), ). -define(config(X,Y), foo). -define(t, test_server). -else. -include("test_server.hrl"). -define(format(S, A), ok). -endif. -export([all/1]). -export([sofs/1, from_term_1/1, set_1/1, from_sets_1/1, relation_1/1, a_function_1/1, family_1/1, projection/1, relation_to_family_1/1, domain_1/1, range_1/1, image/1, inverse_image/1, inverse_1/1, converse_1/1, no_elements_1/1, substitution/1, restriction/1, drestriction/1, strict_relation_1/1, extension/1, weak_relation_1/1, to_sets_1/1, specification/1, union_1/1, intersection_1/1, difference/1, symdiff/1, symmetric_partition/1, is_sofs_set_1/1, is_set_1/1, is_equal/1, is_subset/1, is_a_function_1/1, is_disjoint/1, join/1, canonical/1, composite_1/1, relative_product_1/1, relative_product_2/1, product_1/1, partition_1/1, partition_3/1, multiple_relative_product/1, digraph/1, constant_function/1, misc/1]). -export([sofs_family/1, family_specification/1, family_domain_1/1, family_range_1/1, family_to_relation_1/1, union_of_family_1/1, intersection_of_family_1/1, family_projection/1, family_difference/1, family_intersection_1/1, family_union_1/1, family_intersection_2/1, family_union_2/1, partition_family/1]). -import(sofs, [a_function/1, a_function/2, constant_function/2, canonical_relation/1, composite/2, converse/1, extension/3, from_term/1, from_term/2, difference/2, domain/1, empty_set/0, family_difference/2, family_intersection/1, family_intersection/2, family_union/1, family_union/2, family/1, family/2, family_specification/2, family_domain/1, family_range/1, family_field/1, family_projection/2, family_to_relation/1, union_of_family/1, field/1, from_external/2, image/2, intersection/1, intersection/2, intersection_of_family/1, inverse/1, inverse_image/2, is_disjoint/2, is_empty_set/1, is_equal/2, is_a_function/1, is_set/1, is_sofs_set/1, is_subset/2, join/4, from_sets/1, multiple_relative_product/2, no_elements/1, partition/1, partition/2, partition/3, partition_family/2, product/1, product/2, projection/2, range/1, relation/1, relation/2, relation_to_family/1, relative_product/1, relative_product/2, relative_product1/2, strict_relation/1, weak_relation/1, restriction/2, restriction/3, drestriction/2, drestriction/3, to_sets/1, is_type/1, set/1, set/2, specification/2, substitution/2, symdiff/2, symmetric_partition/2, to_external/1, type/1, union/1, union/2, family_to_digraph/1, family_to_digraph/2, digraph_to_family/1, digraph_to_family/2]). -export([init_per_testcase/2, fin_per_testcase/2]). -compile({inline,[{eval,2}]}). all(suite) -> [sofs, sofs_family]. init_per_testcase(_Case, Config) -> Dog=?t:timetrap(?t:minutes(2)), [{watchdog, Dog}|Config]. fin_per_testcase(_Case, Config) -> Dog=?config(watchdog, Config), test_server:timetrap_cancel(Dog), ok. [ { 2,b},{1,a , b } ] = = lists : sort([{2,b},{1,a , b } ] ) %% [{1,a,b},{2,b}] == lists:keysort(1,[{2,b},{1,a,b}]) sofs(suite) -> [from_term_1, set_1, from_sets_1, relation_1, a_function_1, family_1, relation_to_family_1, domain_1, range_1, image, inverse_image, inverse_1, converse_1, no_elements_1, substitution, restriction, drestriction, projection, strict_relation_1, extension, weak_relation_1, to_sets_1, specification, union_1, intersection_1, difference, symdiff, symmetric_partition, is_sofs_set_1, is_set_1, is_equal, is_subset, is_a_function_1, is_disjoint, join, canonical, composite_1, relative_product_1, relative_product_2, product_1, partition_1, partition_3, multiple_relative_product, digraph, constant_function, misc]. from_term_1(suite) -> []; from_term_1(doc) -> [""]; from_term_1(Conf) when list(Conf) -> %% would go wrong: projection(1,from_term([{2,b},{1,a,b}])), ?line {'EXIT', {badarg, _}} = (catch from_term([], {atom,'_',atom})), ?line {'EXIT', {badarg, _}} = (catch from_term([], [])), ?line {'EXIT', {badarg, _}} = (catch from_term([], [atom,atom])), ?line [] = to_external(from_term([])), ?line eval(from_term([]), empty_set()), ?line [] = to_external(from_term([], ['_'])), ?line eval(from_term([], ['_']), empty_set()), ?line [[]] = to_external(from_term([[]])), ?line [[['_']]] = type(from_term([[],[[]]])), ?line [[],[[]]] = to_external(from_term([[],[[]]])), ?line [[['_']]] = type(from_term([[],[[]]])), ?line eval(from_term([a],['_']), set([a])), ?line [[],[a]] = to_external(from_term([[],[a]])), ?line [[],[{a}]] = to_external(from_term([[{a}],[]])), ?line [{[],[{a,b,[d]}]},{[{a,b}],[]}] = to_external(from_term([{[],[{a,b,[d]}]},{[{a,b}],[]}])), ?line [{[a,b],[c,d]}] = to_external(from_term([{[a,b],[c,d]}])), ?line [{{a,b},[a,b],{{a},{b}}}] = to_external(from_term([{{a,b},[a,b],{{a},{b}}}])), ?line [{{a,{[a,b]},a}},{{z,{[y,z]},z}}] = to_external(from_term([{{a,{[a,b,a]},a}},{{z,{[y,y,z]},z}}])), ?line {'EXIT', {badarg, _}} = (catch from_term([{m1,[{m1,f1,1},{m1,f2,2}]},{m2,[]},{m3,[a]}])), ?line MS1 = [{m1,[{m1,f1,1},{m1,f2,2}]},{m2,[]},{m3,[{m3,f3,3}]}], ?line eval(to_external(from_term(MS1)), MS1), ?line eval(to_external(from_term(a)), a), ?line eval(to_external(from_term({a})), {a}), ?line eval(to_external(from_term([[a],[{b,c}]],[[atomic]])), [[a],[{b,c}]]), ?line eval(type(from_term([[a],[{b,c}]],[[atomic]])), [[atomic]]), ?line {'EXIT', {badarg, _}} = (catch from_term([[],[],a])), ?line {'EXIT', {badarg, _}} = (catch from_term([{[a,b],[c,{d}]}])), ?line {'EXIT', {badarg, _}} = (catch from_term([[],[a],[{a}]])), ?line {'EXIT', {badarg, _}} = (catch from_term([a,{a,b}])), ?line {'EXIT', {badarg, _}} = (catch from_term([[a],[{b,c}]],[['_']])), ?line {'EXIT', {badarg, _}} = (catch from_term([a | {a,b}])), ?line {'EXIT', {badarg, _}} = (catch from_term([{{a},b,c},{d,e,f}],[{{atom},atom,atom}])), ?line {'EXIT', {badarg, _}} = (catch from_term([{a,{b,c}} | tail], [{atom,{atom,atom}}])), ?line {'EXIT', {badarg, _}} = (catch from_term({})), ?line {'EXIT', {badarg, _}} = (catch from_term([{}])), ?line [{foo,bar},[b,a]] = to_external(from_term([[b,a],{foo,bar},[b,a]], [atom])), ?line [{[atom],{atom,atom}}] = type(from_term([{[], {a,b}},{[a,b],{e,f}}])), ?line [{[atom],{atom,atom}}] = type(from_term([{[], {a,b}},{[a,b],{e,f}}], [{[atom],{atom,atom}}])), ?line [[atom]] = type(from_term([[a],[{b,c}]],[[atom]])), ?line {atom, atom} = type(from_term({a,b}, {atom, atom})), ?line atom = type(from_term(a, atom)), ?line {'EXIT', {badarg, _}} = (catch from_term({a,b},{atom})), ?line [{{a},b,c},{{d},e,f}] = to_external(from_term([{{a},b,c},{{a},b,c},{{d},e,f}], [{{atom},atom,atom}])), %% from_external too... ?line e = to_external(from_external(e, atom)), ?line {e} = to_external(from_external({e}, {atom})), ?line [e] = to_external(from_external([e], [atom])), %% and is_type... ?line true = is_type(['_']), ?line false = is_type('_'), ?line true = is_type([['_']]), ?line false = is_type({atom,[],atom}), ?line false = is_type({atom,'_',atom}), ?line true = is_type({atom,atomic,atom}), ?line true = is_type({atom,atom}), ?line true = is_type(atom), ?line true = is_type([atom]), ?line true = is_type(type), ok. set_1(suite) -> []; set_1(doc) -> [""]; set_1(Conf) when list(Conf) -> %% set/1 ?line {'EXIT', {badarg, _}} = (catch set(a)), ?line {'EXIT', {badarg, _}} = (catch set({a})), ?line eval(set([]), from_term([],[atom])), ?line eval(set([a,b,c]), from_term([a,b,c])), ?line eval(set([a,b,a,a,b]), from_term([a,b])), ?line eval(set([a,b,c,a,d,d,c,1]), from_term([1,a,b,c,d])), ?line eval(set([a,b,d,a,c]), from_term([a,b,c,d])), ?line eval(set([f,e,d,c,d]), from_term([c,d,e,f])), ?line eval(set([h,f,d,g,g,d,c]), from_term([c,d,f,g,h])), ?line eval(set([h,e,d,k,l]), from_term([d,e,h,k,l])), ?line eval(set([h,e,c,k,d]), from_term([c,d,e,h,k])), %% set/2 ?line {'EXIT', {badarg, _}} = (catch set(a, [a])), ?line {'EXIT', {badarg, _}} = (catch set({a}, [a])), ?line {'EXIT', {badarg, _}} = (catch set([a], {a})), ?line {'EXIT', {badarg, _}} = (catch set([a], a)), ?line {'EXIT', {badarg, _}} = (catch set([a], [a,b])), ?line {'EXIT', {badarg, _}} = (catch set([a | b],[foo])), ?line {'EXIT', {badarg, _}} = (catch set([a | b],['_'])), ?line {'EXIT', {badarg, _}} = (catch set([a | b],[[atom]])), ?line {'EXIT', {badarg, _}} = (catch set([{}],[{}])), ?line eval(set([a],['_']), from_term([a],['_'])), ?line eval(set([], ['_']), empty_set()), ?line eval(set([a,b,a,b],[foo]), from_term([a,b],[foo])), ok. from_sets_1(suite) -> []; from_sets_1(doc) -> [""]; from_sets_1(Conf) when list(Conf) -> ?line E = empty_set(), %% unordered ?line eval(from_sets([]), E), ?line {'EXIT', {type_mismatch, _}} = (catch from_sets([from_term([{a,b}]), E, from_term([{a,b,c}])])), ?line eval(from_sets([from_term([{a,b}]), E]), from_term([[],[{a,b}]])), ?line eval(from_sets([from_term({a,b},{atom,atom}), from_term({b,c},{atom,atom})]), relation([{a,b}, {b,c}])), ?line {'EXIT', {type_mismatch, _}} = (catch from_sets([from_term({a,b},{atom,atom}), from_term({a,b,c},{atom,atom,atom})])), ?line {'EXIT', {badarg, _}} = (catch from_sets(foo)), ?line eval(from_sets([E]), from_term([[]])), ?line eval(from_sets([E,E]), from_term([[]])), ?line eval(from_sets([E,set([a])]), from_term([[],[a]])), ?line {'EXIT', {badarg, _}} = (catch from_sets([E,{a}])), ?line {'EXIT', {type_mismatch, _}} = (catch from_sets([E,from_term({a}),E])), ?line {'EXIT', {type_mismatch, _}} = (catch from_sets([from_term({a}),E])), %% ordered ?line O = {from_term(a,atom), from_term({b}, {atom}), set([c,d])}, ?line eval(from_sets(O), from_term({a,{b},[c,d]}, {atom,{atom},[atom]})), ?line {'EXIT', {badarg, _}} = (catch from_sets([a,b])), ?line {'EXIT', {badarg, _}} = (catch from_sets({a,b})), ?line eval(from_sets({from_term({a}),E}), from_term({{a},[]})), ok. relation_1(suite) -> []; relation_1(doc) -> [""]; relation_1(Conf) when list(Conf) -> %% relation/1 ?line eval(relation([]), from_term([], [{atom,atom}])), ?line eval(from_term([{a}]), relation([{a}])), ?line {'EXIT', {badarg, _}} = (catch relation(a)), ?line {'EXIT', {badarg, _}} = (catch relation([{a} | a])), ?line {'EXIT', {badarg, _}} = (catch relation([{}])), ?line {'EXIT', {badarg, _}} = (catch relation([],0)), ?line {'EXIT', {badarg, _}} = (catch relation([{a}],a)), %% relation/2 ?line eval(relation([{a},{b}], 1), from_term([{a},{b}])), ?line eval(relation([{1,a},{2,b},{1,a}], [{x,y}]), from_term([{1,a},{2,b}], [{x,y}])), ?line eval(relation([{[1,2],a},{[2,1],b},{[2,1],a}], [{[x],y}]), from_term([{[1,2],a},{[1,2],b}], [{[x],y}])), ?line {'EXIT', {badarg, _}} = (catch relation([{1,a},{2,b}], [{[x],y}])), ?line {'EXIT', {badarg, _}} = (catch relation([{1,a},{1,a,b}], [{x,y}])), ?line {'EXIT', {badarg, _}} = (catch relation([{a}], 2)), ?line {'EXIT', {badarg, _}} = (catch relation([{a},{b},{c,d}], 1)), ?line eval(relation([{{a},[{foo,bar}]}], ['_']), from_term([{{a},[{foo,bar}]}], ['_'])), ?line eval(relation([], ['_']), from_term([], ['_'])), ?line {'EXIT', {badarg, _}} = (catch relation([[a]],['_'])), ?line eval(relation([{[a,b,a]}], [{[atom]}]), from_term([{[a,b,a]}])), ?line eval(relation([{[a,b,a],[[d,e,d]]}], [{[atom],[[atom]]}]), from_term([{[a,b,a],[[d,e,d]]}])), ?line eval(relation([{[a,b,a],[[d,e,d]]}], [{atom,[[atom]]}]), from_term([{[a,b,a],[[d,e,d]]}], [{atom,[[atom]]}])), ok. a_function_1(suite) -> []; a_function_1(doc) -> [""]; a_function_1(Conf) when list(Conf) -> %% a_function/1 ?line eval(a_function([]), from_term([], [{atom,atom}])), ?line eval(a_function([{a,b},{a,b},{b,c}]), from_term([{a,b},{b,c}])), ?line {'EXIT', {badarg, _}} = (catch a_function([{a}])), ?line {'EXIT', {badarg, _}} = (catch a_function([{a},{b},{c,d}])), ?line {'EXIT', {badarg, _}} = (catch a_function(a)), ?line {'EXIT', {badarg, _}} = (catch a_function([{a,b} | a])), ?line {'EXIT', {bad_function, _}} = (catch a_function([{a,b},{b,c},{a,c}])), F = 0.0, I = round(F), if F == I -> % term ordering ?line {'EXIT', {bad_function, _}} = (catch a_function([{I,a},{F,b}])), ?line {'EXIT', {bad_function, _}} = (catch a_function([{[I],a},{[F],b}],[{[a],b}])); true -> ?line 2 = no_elements(a_function([{I,a},{F,b}])), ?line 2 = no_elements(a_function([{[I],a},{[F],b}],[{[a],b}])) end, %% a_function/2 FT = [{atom,atom}], ?line eval(a_function([], FT), from_term([], FT)), ?line eval(a_function([{a,b},{b,c},{b,c}], FT), from_term([{a,b},{b,c}], FT)), ?line {'EXIT', {badarg, _}} = (catch a_function([{a,b}], [{a}])), ?line {'EXIT', {badarg, _}} = (catch a_function([{a,b}], [{a,[b,c]}])), ?line {'EXIT', {badarg, _}} = (catch a_function([{a}], FT)), ?line {'EXIT', {badarg, _}} = (catch a_function([{a},{b},{c,d}], FT)), ?line {'EXIT', {badarg, _}} = (catch a_function(a, FT)), ?line {'EXIT', {badarg, _}} = (catch a_function([{a,b} | a], FT)), ?line eval(a_function([{{a},[{foo,bar}]}], ['_']), from_term([{{a},[{foo,bar}]}], ['_'])), ?line eval(a_function([], ['_']), from_term([], ['_'])), ?line {'EXIT', {badarg, _}} = (catch a_function([[a]],['_'])), ?line {'EXIT', {bad_function, _}} = (catch a_function([{a,b},{b,c},{a,c}], FT)), ?line eval(a_function([{a,[a]},{a,[a,a]}], [{atom,[atom]}]), from_term([{a,[a]}])), ?line eval(a_function([{[b,a],c},{[a,b],c}], [{[atom],atom}]), from_term([{[a,b],c}])), ok. family_1(suite) -> []; family_1(doc) -> [""]; family_1(Conf) when list(Conf) -> %% family/1 ?line eval(family([]), from_term([],[{atom,[atom]}])), ?line {'EXIT', {badarg, _}} = (catch family(a)), ?line {'EXIT', {badarg, _}} = (catch family([a])), ?line {'EXIT', {badarg, _}} = (catch family([{a,b}])), ?line {'EXIT', {badarg, _}} = (catch family([{a,[]} | a])), ?line {'EXIT', {badarg, _}} = (catch family([{a,[a|b]}])), ?line {'EXIT', {bad_function, _}} = (catch family([{a,[a]},{a,[]}])), ?line {'EXIT', {bad_function, _}} = (catch family([{a,[]},{b,[]},{a,[a]}])), F = 0.0, I = round(F), if F == I -> % term ordering ?line {'EXIT', {bad_function, _}} = (catch family([{I,[a]},{F,[b]}])), ?line true = (1 =:= no_elements(family([{a,[I]},{a,[F]}]))); true -> ?line {'EXIT', {bad_function, _}} = (catch family([{a,[I]},{a,[F]}])) end, ?line eval(family([{a,[]},{b,[b]},{a,[]}]), from_term([{a,[]},{b,[b]}])), ?line eval(to_external(family([{b,[{hej,san},tjo]},{a,[]}])), [{a,[]},{b,[tjo,{hej,san}]}]), ?line eval(family([{a,[a]},{a,[a,a]}]), family([{a,[a]}])), %% family/2 FT = [{a,[a]}], ?line eval(family([], FT), from_term([],FT)), ?line {'EXIT', {badarg, _}} = (catch family(a,FT)), ?line {'EXIT', {badarg, _}} = (catch family([a],FT)), ?line {'EXIT', {badarg, _}} = (catch family([{a,b}],FT)), ?line {'EXIT', {badarg, _}} = (catch family([{a,[]} | a],FT)), ?line {'EXIT', {badarg, _}} = (catch family([{a,[a|b]}], FT)), ?line {'EXIT', {bad_function, _}} = (catch family([{a,[a]},{a,[]}], FT)), ?line {'EXIT', {bad_function, _}} = (catch family([{a,[]},{b,[]},{a,[a]}], FT)), ?line eval(family([{a,[]},{b,[b,b]},{a,[]}], FT), from_term([{a,[]},{b,[b]}], FT)), ?line eval(to_external(family([{b,[{hej,san},tjo]},{a,[]}], FT)), [{a,[]},{b,[tjo,{hej,san}]}]), ?line eval(family([{{a},[{foo,bar}]}], ['_']), from_term([{{a},[{foo,bar}]}], ['_'])), ?line eval(family([], ['_']), from_term([], ['_'])), ?line {'EXIT', {badarg, _}} = (catch family([[a]],['_'])), ?line {'EXIT', {badarg, _}} = (catch family([{a,b}],['_'])), ?line {'EXIT', {badarg, _}} = (catch family([{a,[foo]}], [{atom,atom}])), ?line eval(family([{{a},[{foo,bar}]}], [{{dt},[{r1,t2}]}]), from_term([{{a},[{foo,bar}]}], [{{dt},[{r1,t2}]}])), ?line eval(family([{a,[a]},{a,[a,a]}],[{atom,[atom]}]), family([{a,[a]}])), ?line eval(family([{[a,b],[a]},{[b,a],[a,a]}],[{[atom],[atom]}]), from_term([{[a,b],[a]},{[b,a],[a,a]}])), ok. projection(suite) -> []; projection(doc) -> [""]; projection(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), %% set of ordered sets ?line S1 = relation([{a,1},{b,2},{b,22},{c,0}]), ?line S2 = relation([{a,1},{a,2},{a,3},{b,4},{b,5},{b,6}]), ?line eval(projection(1, E), E), ?line eval(projection(1, ER), set([])), ?line eval(projection(1, relation([{a,1}])), set([a])), ?line eval(projection(1, S1), set([a,b,c])), ?line eval(projection(1, S2), set([a,b])), ?line eval(projection(2, S1), set([0,1,2,22])), ?line eval(projection(2, relation([{1,a},{2,a},{3,b}])), set([a,b])), ?line eval(projection(1, relation([{a},{b},{c}])), set([a,b,c])), Fun1 = {external, fun({A,B,C}) -> {A,{B,C}} end}, ?line eval(projection(Fun1, E), E), %% No check here: ?line eval(projection(3, projection(Fun1, empty_set())), E), ?line E2 = relation([], 3), ?line eval(projection(Fun1, E2), from_term([], [{atom,{atom,atom}}])), Fun2 = {external, fun({A,_B}) -> {A} end}, ?line eval(projection(Fun2, ER), from_term([], [{atom}])), ?line eval(projection(Fun2, relation([{a,1}])), relation([{a}])), ?line eval(projection(Fun2, relation([{a,1},{b,3},{a,2}])), relation([{a},{b}])), Fun3 = {external, fun({A,_B,C}) -> {C,{A},C} end}, ?line eval(projection(Fun3, relation([{a,1,x},{b,3,y},{a,2,z}])), from_term([{x,{a},x},{y,{b},y},{z,{a},z}])), Fun4 = {external, fun(A={B,_C,_D}) -> {B, A} end}, ?line eval(projection(Fun4, relation([{a,1,x},{b,3,y},{a,2,z}])), from_term([{a,{a,1,x}},{b,{b,3,y}},{a,{a,2,z}}])), ?line eval(projection({external, fun({A,B,_C,D}) -> {A,B,A,D} end}, relation([{1,1,1,2}, {1,1,3,1}])), relation([{1,1,1,1}, {1,1,1,2}])), ?line {'EXIT', {badarg, _}} = (catch projection(1, set([]))), ?line {'EXIT', {function_clause, _}} = (catch projection({external, fun({A}) -> A end}, S1)), ?line {'EXIT', {badarg, _}} = (catch projection({external, fun({A,_}) -> {A,0} end}, from_term([{1,a}]))), %% {} is not an ordered set ?line {'EXIT', {badarg, _}} = (catch projection({external, fun(_) -> {} end}, ER)), ?line {'EXIT', {badarg, _}} = (catch projection({external, fun(_) -> {{}} end}, ER)), ?line eval(projection({external, fun({T,_}) -> T end}, relation([{{},a},{{},b}])), set([{}])), ?line eval(projection({external, fun({T}) -> T end}, relation([{{}}])), set([{}])), ?line eval(projection({external, fun(A) -> {A} end}, relation([{1,a},{2,b}])), from_term([{{1,a}},{{2,b}}])), ?line eval(projection({external, fun({A,B}) -> {B,A} end}, relation([{1,a},{2,b}])), relation([{a,1},{b,2}])), ?line eval(projection({external, fun(X=Y=A) -> {X,Y,A} end}, set([a,b,c])), relation([{a,a,a},{b,b,b},{c,c,c}])), ?line eval(projection({external, fun({A,{_},B}) -> {A,B} end}, from_term([{a,{a},b},{a,{b},c}])), relation([{a,b},{a,c}])), ?line eval(projection({external, fun({A,_,B}) -> {A,B} end}, relation([{a,{},b},{a,{},c}])), relation([{a,b},{a,c}])), Fun5 = fun(S) -> from_term({to_external(S),0}, {type(S),atom}) end, ?line eval(projection(Fun5, E), E), ?line eval(projection(Fun5, set([a,b])), from_term([{a,0},{b,0}])), ?line eval(projection(Fun5, relation([{a,1},{b,2}])), from_term([{{a,1},0},{{b,2},0}])), ?line eval(projection(Fun5, from_term([[a],[b]])), from_term([{[a],0},{[b],0}])), F = 0.0, I = round(F), ?line FR = relation([{I},{F}]), if F == I -> % term ordering true = (no_elements(projection(1, FR)) =:= 1); true -> eval(projection(1, FR), set([I,F])) end, %% set of sets ?line {'EXIT', {badarg, _}} = (catch projection({external, fun(X) -> X end}, from_term([], [[atom]]))), ?line {'EXIT', {badarg, _}} = (catch projection({external, fun(X) -> X end}, from_term([[a]]))), ?line eval(projection({sofs,union}, from_term([[[1,2],[2,3]], [[a,b],[b,c]]])), from_term([[1,2,3], [a,b,c]])), ?line eval(projection(fun(_) -> from_term([a]) end, from_term([[b]], [[a]])), from_term([[a]])), ?line eval(projection(fun(_) -> from_term([a]) end, from_term([[1,2],[3,4]])), from_term([[a]])), Fun10 = fun(S) -> %% Cheating a lot... case to_external(S) of [1] -> from_term({1,1}); _ -> S end end, ?line eval(projection(Fun10, from_term([[1]])), from_term([{1,1}])), ?line eval(projection(fun(_) -> from_term({a}) end, from_term([[a]])), from_term([{a}])), ?line {'EXIT', {badarg, _}} = (catch projection(fun(_) -> {a} end, from_term([[a]]))), ok. substitution(suite) -> []; substitution(doc) -> [""]; substitution(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), %% set of ordered sets ?line S1 = relation([{a,1},{b,2},{b,22},{c,0}]), ?line S2 = relation([{a,1},{a,2},{a,3},{b,4},{b,5},{b,6}]), ?line eval(substitution(1, E), E), %% No check here: Fun0 = {external, fun({A,B,C}) -> {A,{B,C}} end}, ?line eval(substitution(3, substitution(Fun0, empty_set())), E), ?line eval(substitution(1, ER), from_term([],[{{atom,atom},atom}])), ?line eval(substitution(1, relation([{a,1}])), from_term([{{a,1},a}])), ?line eval(substitution(1, S1), from_term([{{a,1},a},{{b,2},b},{{b,22},b},{{c,0},c}])), ?line eval(substitution(1, S2), from_term([{{a,1},a},{{a,2},a},{{a,3},a},{{b,4},b}, {{b,5},b},{{b,6},b}])), ?line eval(substitution(2, S1), from_term([{{a,1},1},{{b,2},2},{{b,22},22},{{c,0},0}])), Fun1 = fun({A,_B}) -> {A} end, XFun1 = {external, Fun1}, ?line eval(substitution(XFun1, E), E), ?line eval(substitution(Fun1, E), E), ?line eval(substitution(XFun1, ER), from_term([], [{{atom,atom},{atom}}])), ?line eval(substitution(XFun1, relation([{a,1}])), from_term([{{a,1},{a}}])), ?line eval(substitution(XFun1, relation([{a,1},{b,3},{a,2}])), from_term([{{a,1},{a}},{{a,2},{a}},{{b,3},{b}}])), ?line eval(substitution({external, fun({A,_B,C}) -> {C,A,C} end}, relation([{a,1,x},{b,3,y},{a,2,z}])), from_term([{{a,1,x},{x,a,x}},{{a,2,z},{z,a,z}}, {{b,3,y},{y,b,y}}])), Fun2 = fun(S) -> {A,_B} = to_external(S), from_term({A}) end, ?line eval(substitution(Fun2, ER), E), ?line eval(substitution(Fun2, relation([{a,1}])), from_term([{{a,1},{a}}])), Fun3 = fun(S) -> from_term({to_external(S),0}, {type(S),atom}) end, ?line eval(substitution(Fun3, E), E), ?line eval(substitution(Fun3, set([a,b])), from_term([{a,{a,0}},{b,{b,0}}])), ?line eval(substitution(Fun3, relation([{a,1},{b,2}])), from_term([{{a,1},{{a,1},0}},{{b,2},{{b,2},0}}])), ?line eval(substitution(Fun3, from_term([[a],[b]])), from_term([{[a],{[a],0}},{[b],{[b],0}}])), ?line eval(substitution(fun(_) -> E end, from_term([[a],[b]])), from_term([{[a],[]},{[b],[]}])), ?line {'EXIT', {badarg, _}} = (catch substitution(1, set([]))), ?line eval(substitution(1, ER), from_term([], [{{atom,atom},atom}])), ?line {'EXIT', {function_clause, _}} = (catch substitution({external, fun({A,_}) -> A end}, set([]))), ?line {'EXIT', {badarg, _}} = (catch substitution({external, fun({A,_}) -> {A,0} end}, from_term([{1,a}]))), %% set of sets ?line {'EXIT', {badarg, _}} = (catch substitution({external, fun(X) -> X end}, from_term([], [[atom]]))), ?line {'EXIT', {badarg, _}} = (catch substitution({external, fun(X) -> X end}, from_term([[a]]))), ?line eval(substitution(fun(X) -> X end, from_term([], [[atom]])), E), ?line eval(substitution({sofs,union}, from_term([[[1,2],[2,3]], [[a,b],[b,c]]])), from_term([{[[1,2],[2,3]],[1,2,3]}, {[[a,b],[b,c]],[a,b,c]}])), ?line eval(substitution(fun(_) -> from_term([a]) end, from_term([[b]], [[a]])), from_term([{[b],[a]}], [{[a],[atom]}])), ?line eval(substitution(fun(_) -> from_term([a]) end, from_term([[1,2],[3,4]])), from_term([{[1,2],[a]},{[3,4],[a]}])), Fun10 = fun(S) -> %% Cheating a lot... case to_external(S) of [1] -> from_term({1,1}); _ -> S end end, ?line eval(substitution(Fun10, from_term([[1]])), from_term([{[1],{1,1}}])), ?line {'EXIT', {type_mismatch, _}} = (catch substitution(Fun10, from_term([[1],[2]]))), ?line {'EXIT', {type_mismatch, _}} = (catch substitution(Fun10, from_term([[1],[0]]))), ?line eval(substitution(fun(_) -> from_term({a}) end, from_term([[a]])), from_term([{[a],{a}}])), ?line {'EXIT', {badarg, _}} = (catch substitution(fun(_) -> {a} end, from_term([[a]]))), ok. restriction(suite) -> []; restriction(doc) -> [""]; restriction(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([], 2), %% set of ordered sets ?line S1 = relation([{a,1},{b,2},{b,22},{c,0}]), ?line eval(restriction(S1, set([a,b])), relation([{a,1},{b,2},{b,22}])), ?line eval(restriction(2, S1, set([1,2])), relation([{a,1},{b,2}])), ?line eval(restriction(S1, set([a,b,c])), S1), ?line eval(restriction(1, S1, set([0,1,d,e])), ER), ?line eval(restriction(1, S1, E), ER), ?line eval(restriction({external, fun({_A,B,C}) -> {B,C} end}, relation([{a,aa,1},{b,bb,2},{c,cc,3}]), relation([{bb,2},{cc,3}])), relation([{b,bb,2},{c,cc,3}])), R1 = relation([],[{a,b}]), ?line eval(restriction(2, R1,sofs:set([],[b])), R1), Id = fun(X) -> X end, XId = {external, Id}, ?line eval(restriction(XId, relation([{a,b}]), E), ER), ?line eval(restriction(XId, E, relation([{b,d}])), E), Fun1 = fun(S) -> {_A,B,C} = to_external(S), from_term({B,C}) end, ?line eval(restriction(Fun1, relation([{a,aa,1},{b,bb,2},{c,cc,3}]), relation([{bb,2},{cc,3}])), relation([{b,bb,2},{c,cc,3}])), ?line eval(restriction({external, fun({_,{A},B}) -> {A,B} end}, from_term([{a,{aa},1},{b,{bb},2},{c,{cc},3}]), from_term([{bb,2},{cc,3}])), from_term([{b,{bb},2},{c,{cc},3}])), S5 = relation([{1,a},{2,b},{3,c}]), ?line eval(restriction(2, S5, set([b,c])), relation([{2,b},{3,c}])), S4 = relation([{a,1},{b,2},{b,27},{c,0}]), ?line eval(restriction(2, S4, E), ER), S6 = relation([{1,a},{2,c},{3,b}]), ?line eval(restriction(2, S6, set([d,e])), ER), ?line eval(restriction(2, relation([{1,d},{2,c},{3,b},{4,a},{5,e}]), set([c])), relation([{2,c}])), ?line eval(restriction(XId, relation([{1,a},{3,b},{4,c},{4,d}]), relation([{2,a},{2,c},{4,c}])), relation([{4,c}])), ?line eval(restriction(2, relation([{a,b}]), E), ER), ?line eval(restriction(2, E, relation([{b,d}])), E), ?line eval(restriction(2, relation([{b,d}]), E), ER), ?line eval(restriction(XId, E, set([a])), E), ?line eval(restriction(1, S1, E), ER), ?line {'EXIT', {badarg, _}} = (catch restriction(3, relation([{a,b}]), E)), ?line {'EXIT', {badarg, _}} = (catch restriction(3, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {badarg, _}} = (catch restriction(3, relation([{a,b}]), set([{b,d}]))), ?line {'EXIT', {type_mismatch, _}} = (catch restriction(2, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {type_mismatch, _}} = (catch restriction({external, fun({A,_B}) -> A end}, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {badarg, _}} = (catch restriction({external, fun({A,_}) -> {A,0} end}, from_term([{1,a}]), from_term([{1,0}]))), ?line eval(restriction(2, relation([{a,d},{b,e},{c,b},{d,c}]), set([b,d])), relation([{a,d},{c,b}])), ?line {'EXIT', {function_clause, _}} = (catch restriction({external, fun({A,_B}) -> A end}, set([]), E)), Fun3 = fun(S) -> from_term({to_external(S),0}, {type(S),atom}) end, ?line eval(restriction(Fun3, set([1,2]), from_term([{1,0}])), from_term([1])), %% set of sets ?line {'EXIT', {badarg, _}} = (catch restriction({external, fun(X) -> X end}, from_term([], [[atom]]), set([a]))), S2 = from_term([], [[atom]]), ?line eval(restriction(Id, S2, E), E), S3 = from_term([[a],[b]], [[atom]]), ?line eval(restriction(Id, S3, E), E), ?line eval(restriction(Id, from_term([], [[atom]]), set([a])), from_term([], [[atom]])), ?line eval(restriction({sofs,union}, from_term([[[a],[b]], [[b],[c]], [[], [a,b]], [[1],[2]]]), from_term([[a,b],[1,2,3],[b,c]])), from_term([[[],[a,b]], [[a],[b]],[[b],[c]]])), ?line eval(restriction(fun(_) -> from_term([a]) end, from_term([], [[atom]]), from_term([], [[a]])), from_term([], [[atom]])), ?line {'EXIT', {type_mismatch, _}} = (catch restriction(fun(_) -> from_term([a]) end, from_term([[1,2],[3,4]]), from_term([], [atom]))), Fun10 = fun(S) -> %% Cheating a lot... case to_external(S) of [1] -> from_term({1,1}); _ -> S end end, ?line {'EXIT', {type_mismatch, _}} = (catch restriction(Fun10, from_term([[1]]), from_term([], [[atom]]))), ?line {'EXIT', {type_mismatch, _}} = (catch restriction(fun(_) -> from_term({a}) end, from_term([[a]]), from_term([], [atom]))), ?line {'EXIT', {badarg, _}} = (catch restriction(fun(_) -> {a} end, from_term([[a]]), from_term([], [atom]))), ok. drestriction(suite) -> []; drestriction(doc) -> [""]; drestriction(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([], 2), %% set of ordered sets ?line S1 = relation([{a,1},{b,2},{b,22},{c,0}]), ?line eval(drestriction(S1, set([a,b])), relation([{c,0}])), ?line eval(drestriction(2, S1, set([1,2])), relation([{b,22},{c,0}])), ?line eval(drestriction(S1, set([a,b,c])), ER), ?line eval(drestriction(2, ER, set([a,b])), ER), ?line eval(drestriction(1, S1, set([0,1,d,e])), S1), ?line eval(drestriction(1, S1, E), S1), ?line eval(drestriction({external, fun({_A,B,C}) -> {B,C} end}, relation([{a,aa,1},{b,bb,2},{c,cc,3}]), relation([{bb,2},{cc,3}])), relation([{a,aa,1}])), Id = fun(X) -> X end, XId = {external, Id}, ?line eval(drestriction(XId, relation([{a,b}]), E), relation([{a,b}])), ?line eval(drestriction(XId, E, relation([{b,d}])), E), Fun1 = fun(S) -> {_A,B,C} = to_external(S), from_term({B,C}) end, ?line eval(drestriction(Fun1, relation([{a,aa,1},{b,bb,2},{c,cc,3}]), relation([{bb,2},{cc,3}])), relation([{a,aa,1}])), ?line eval(drestriction({external, fun({_,{A},B}) -> {A,B} end}, from_term([{a,{aa},1},{b,{bb},2},{c,{cc},3}]), from_term([{bb,2},{cc,3}])), from_term([{a,{aa},1}])), S5 = relation([{1,a},{2,b},{3,c}]), ?line eval(drestriction(2, S5, set([b,c])), relation([{1,a}])), S4 = relation([{a,1},{b,2},{b,27},{c,0}]), ?line eval(drestriction(2, S4, set([])), S4), S6 = relation([{1,a},{2,c},{3,b}]), ?line eval(drestriction(2, S6, set([d,e])), S6), ?line eval(drestriction(2, relation([{1,d},{2,c},{3,b},{4,a},{5,e}]), set([c])), relation([{1,d},{3,b},{4,a},{5,e}])), ?line eval(drestriction(XId, relation([{1,a},{3,b},{4,c},{4,d}]), relation([{2,a},{2,c},{4,c}])), relation([{1,a},{3,b},{4,d}])), ?line eval(drestriction(2, relation([{a,b}]), E), relation([{a,b}])), ?line eval(drestriction(2, E, relation([{b,d}])), E), ?line eval(drestriction(2, relation([{b,d}]), E), relation([{b,d}])), ?line eval(drestriction(XId, E, set([a])), E), ?line eval(drestriction(1, S1, E), S1), ?line {'EXIT', {badarg, _}} = (catch drestriction(3, relation([{a,b}]), E)), ?line {'EXIT', {badarg, _}} = (catch drestriction(3, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {badarg, _}} = (catch drestriction(3, relation([{a,b}]), set([{b,d}]))), ?line {'EXIT', {type_mismatch, _}} = (catch drestriction(2, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {type_mismatch, _}} = (catch drestriction({external, fun({A,_B}) -> A end}, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {badarg, _}} = (catch drestriction({external, fun({A,_}) -> {A,0} end}, from_term([{1,a}]), from_term([{1,0}]))), ?line eval(drestriction(2, relation([{a,d},{b,e},{c,b},{d,c}]), set([b,d])), relation([{b,e},{d,c}])), ?line {'EXIT', {function_clause, _}} = (catch drestriction({external, fun({A,_B}) -> A end}, set([]), E)), Fun3 = fun(S) -> from_term({to_external(S),0}, {type(S),atom}) end, ?line eval(drestriction(Fun3, set([1,2]), from_term([{1,0}])), from_term([2])), %% set of sets ?line {'EXIT', {badarg, _}} = (catch drestriction({external, fun(X) -> X end}, from_term([], [[atom]]), set([a]))), S2 = from_term([], [[atom]]), ?line eval(drestriction(Id, S2, E), S2), S3 = from_term([[a],[b]], [[atom]]), ?line eval(drestriction(Id, S3, E), S3), ?line eval(drestriction(Id, from_term([], [[atom]]), set([a])), from_term([], [[atom]])), ?line eval(drestriction({sofs,union}, from_term([[[a],[b]], [[b],[c]], [[], [a,b]], [[1],[2]]]), from_term([[a,b],[1,2,3],[b,c]])), from_term([[[1],[2]]])), ?line eval(drestriction(fun(_) -> from_term([a]) end, from_term([], [[atom]]), from_term([], [[a]])), from_term([], [[atom]])), ?line {'EXIT', {type_mismatch, _}} = (catch drestriction(fun(_) -> from_term([a]) end, from_term([[1,2],[3,4]]), from_term([], [atom]))), Fun10 = fun(S) -> %% Cheating a lot... case to_external(S) of [1] -> from_term({1,1}); _ -> S end end, ?line {'EXIT', {type_mismatch, _}} = (catch drestriction(Fun10, from_term([[1]]), from_term([], [[atom]]))), ?line {'EXIT', {type_mismatch, _}} = (catch drestriction(fun(_) -> from_term({a}) end, from_term([[a]]), from_term([], [atom]))), ?line {'EXIT', {badarg, _}} = (catch drestriction(fun(_) -> {a} end, from_term([[a]]), from_term([], [atom]))), ok. strict_relation_1(suite) -> []; strict_relation_1(doc) -> [""]; strict_relation_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([], 2), ?line eval(strict_relation(E), E), ?line eval(strict_relation(ER), ER), ?line eval(strict_relation(relation([{1,a},{a,a},{2,b}])), relation([{1,a},{2,b}])), ?line {'EXIT', {badarg, _}} = (catch strict_relation(relation([{1,2,3}]))), F = 0.0, I = round(F), ?line FR = relation([{F,I}]), if F == I -> % term ordering eval(strict_relation(FR), ER); true -> eval(strict_relation(FR), FR) end, ok. extension(suite) -> []; extension(doc) -> [""]; extension(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([], 2), ?line EF = family([]), ?line C1 = from_term(3), ?line C2 = from_term([3]), ?line {'EXIT', {function_clause, _}} = (catch extension(foo, E, C1)), ?line {'EXIT', {function_clause, _}} = (catch extension(ER, foo, C1)), ?line {'EXIT', {{case_clause, _},_}} = (catch extension(ER, E, foo)), ?line {'EXIT', {type_mismatch, _}} = (catch extension(ER, E, E)), ?line {'EXIT', {badarg, _}} = (catch extension(C2, E, E)), ?line eval(E, extension(E, E, E)), ?line eval(EF, extension(EF, E, E)), ?line eval(family([{3,[]}]), extension(EF, set([3]), E)), ?line eval(ER, extension(ER, E, C1)), ?line eval(E, extension(E, ER, E)), ?line eval(from_term([],[{{atom,atom},type(ER)}]), extension(E, ER, ER)), ?line R1 = relation([{c,7},{c,9},{c,11},{d,17},{f,20}]), ?line S1 = set([a,c,d,e]), ?line eval(extension(R1, S1, C1), lextension(R1, S1, C1)), ?line S2 = set([1,2,3]), ?line eval(extension(ER, S2, C1), lextension(ER, S2, C1)), ?line R3 = relation([{4,a},{8,b}]), ?line S3 = set([1,2,3,4,5,6,7,8,9,10,11]), ?line eval(extension(R3, S3, C1), lextension(R3, S3, C1)), ?line R4 = relation([{2,b},{4,d},{6,f}]), ?line S4 = set([1,3,5,7]), ?line eval(extension(R4, S4, C1), lextension(R4, S4, C1)), ?line F1 = family([{a,[1]},{c,[2]}]), ?line S5 = set([a,b,c,d]), ?line eval(extension(F1, S5, C2), lextension(F1, S5, C2)), ok. lextension(R, S, C) -> union(R, drestriction(1, constant_function(S, C), domain(R))). weak_relation_1(suite) -> []; weak_relation_1(doc) -> [""]; weak_relation_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([], 2), ?line eval(weak_relation(E), E), ?line eval(weak_relation(ER), ER), ?line eval(weak_relation(relation([{a,1},{a,2},{b,2},{c,c}])), relation([{1,1},{2,2},{a,1},{a,2},{a,a},{b,2},{b,b},{c,c}])), ?line eval(weak_relation(relation([{a,1},{a,a},{a,b}])), relation([{1,1},{a,1},{a,a},{a,b},{b,b}])), ?line eval(weak_relation(relation([{a,1},{a,b},{7,w}])), relation([{1,1},{7,7},{7,w},{a,1},{a,a},{a,b},{b,b},{w,w}])), ?line {'EXIT', {badarg, _}} = (catch weak_relation(from_term([{{a},a}]))), ?line {'EXIT', {badarg, _}} = (catch weak_relation(from_term([{a,a}],[{d,r}]))), ?line {'EXIT', {badarg, _}} = (catch weak_relation(relation([{1,2,3}]))), F = 0.0, I = round(F), if F == I -> % term ordering ?line FR1 = relation([{F,I}]), eval(weak_relation(FR1), FR1), ?line FR2 = relation([{F,2},{I,1}]), true = no_elements(weak_relation(FR2)) =:= 5, ?line FR3 = relation([{1,0},{1.0,1}]), true = no_elements(weak_relation(FR3)) =:= 3; true -> ok end, ok. to_sets_1(suite) -> []; to_sets_1(doc) -> [""]; to_sets_1(Conf) when list(Conf) -> ?line {'EXIT', {badarg, _}} = (catch to_sets(from_term(a))), ?line {'EXIT', {function_clause, _}} = (catch to_sets(a)), %% unordered ?line [] = to_sets(empty_set()), ?line eval(to_sets(from_term([a])), [from_term(a)]), ?line eval(to_sets(from_term([[]],[[atom]])), [set([])]), ?line L = [from_term([a,b]),from_term([c,d])], ?line eval(to_sets(from_sets(L)), L), ?line eval(to_sets(relation([{a,1},{b,2}])), [from_term({a,1},{atom,atom}), from_term({b,2},{atom,atom})]), %% ordered ?line O = {from_term(a,atom), from_term({b}, {atom}), set([c,d])}, ?line eval(to_sets(from_sets(O)), O), ok. specification(suite) -> []; specification(doc) -> [""]; specification(Conf) when list(Conf) -> Fun = {external, fun(I) when integer(I) -> true; (_) -> false end}, ?line [1,2,3] = to_external(specification(Fun, set([a,1,b,2,c,3]))), Fun2 = fun(S) -> is_subset(S, set([1,3,5,7,9])) end, S2 = from_term([[1],[2],[3],[4],[5],[6],[7]]), ?line eval(specification(Fun2, S2), from_term([[1],[3],[5],[7]])), Fun2x = fun([1]) -> true; ([3]) -> true; (_) -> false end, ?line eval(specification({external,Fun2x}, S2), from_term([[1],[3]])), Fun3 = fun(_) -> neither_true_or_false end, ?line {'EXIT', {badarg, _}} = (catch specification(Fun3, set([a]))), ?line {'EXIT', {badarg, _}} = (catch specification({external, Fun3}, set([a]))), ?line {'EXIT', {badarg, _}} = (catch specification(Fun3, from_term([[a]]))), ?line {'EXIT', {function_clause, _}} = (catch specification(Fun, a)), ok. union_1(suite) -> []; union_1(doc) -> [""]; union_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([], 2), ?line {'EXIT', {badarg, _}} = (catch union(ER)), ?line {'EXIT', {type_mismatch, _}} = (catch union(relation([{a,b}]), relation([{a,b,c}]))), ?line {'EXIT', {type_mismatch, _}} = (catch union(from_term([{a,b}]), from_term([{c,[x]}]))), ?line {'EXIT', {type_mismatch, _}} = (catch union(from_term([{a,b}]), from_term([{c,d}], [{d,r}]))), ?line {'EXIT', {badarg, _}} = (catch union(set([a,b,c]))), ?line eval(union(E), E), ?line eval(union(from_term([[]],[[atom]])), set([])), ?line eval(union(from_term([[{a,b},{b,c}],[{b,c}]])), relation([{a,b},{b,c}])), ?line eval(union(from_term([[1,2,3],[2,3,4],[3,4,5]])), set([1,2,3,4,5])), ?line eval(union(from_term([{[a],[],c}]), from_term([{[],[],q}])), from_term([{[a],[],c},{[],[],q}])), ?line eval(union(E, E), E), ?line eval(union(set([a,b]), E), set([a,b])), ?line eval(union(E, set([a,b])), set([a,b])), ?line eval(union(from_term([[a,b]])), from_term([a,b])), ok. intersection_1(suite) -> []; intersection_1(doc) -> [""]; intersection_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line {'EXIT', {badarg, _}} = (catch intersection(from_term([a,b]))), ?line {'EXIT', {badarg, _}} = (catch intersection(E)), ?line {'EXIT', {type_mismatch, _}} = (catch intersection(relation([{a,b}]), relation([{a,b,c}]))), ?line {'EXIT', {type_mismatch, _}} = (catch intersection(relation([{a,b}]), from_term([{a,b}],[{d,r}]))), ?line eval(intersection(from_term([[a,b,c],[d,e,f],[g,h,i]])), set([])), ?line eval(intersection(E, E), E), ?line eval(intersection(set([a,b,c]),set([0,b,q])), set([b])), ?line eval(intersection(set([0,b,q]),set([a,b,c])), set([b])), ?line eval(intersection(set([a,b,c]),set([a,b,c])), set([a,b,c])), ?line eval(intersection(set([a,b,d]),set([c,d])), set([d])), ok. difference(suite) -> []; difference(doc) -> [""]; difference(Conf) when list(Conf) -> ?line E = empty_set(), ?line {'EXIT', {type_mismatch, _}} = (catch difference(relation([{a,b}]), relation([{a,b,c}]))), ?line eval(difference(E, E), E), ?line {'EXIT', {type_mismatch, _}} = (catch difference(relation([{a,b}]), from_term([{a,c}],[{d,r}]))), ?line eval(difference(set([a,b,c,d,f]), set([a,d,e,g])), set([b,c,f])), ?line eval(difference(set([a,b,c]), set([d,e,f])), set([a,b,c])), ?line eval(difference(set([a,b,c]), set([a,b,c,d,e,f])), set([])), ?line eval(difference(set([e,f,g]), set([a,b,c,e])), set([f,g])), ?line eval(difference(set([a,b,d,e,f]), set([c])), set([a,b,d,e,f])), ok. symdiff(suite) -> []; symdiff(doc) -> [""]; symdiff(Conf) when list(Conf) -> ?line E = empty_set(), ?line {'EXIT', {type_mismatch, _}} = (catch symdiff(relation([{a,b}]), relation([{a,b,c}]))), ?line {'EXIT', {type_mismatch, _}} = (catch symdiff(relation([{a,b}]), from_term([{a,b}], [{d,r}]))), ?line eval(symdiff(E, E), E), ?line eval(symdiff(set([a,b,c,d,e,f]), set([0,1,a,c])), union(set([b,d,e,f]), set([0,1]))), ?line eval(symdiff(set([a,b,c]), set([q,v,w,x,y])), union(set([a,b,c]), set([q,v,w,x,y]))), ?line eval(symdiff(set([a,b,c,d,e,f]), set([a,b,c])), set([d,e,f])), ?line eval(symdiff(set([c,e,g,h,i]), set([b,d,f])), union(set([c,e,g,h,i]), set([b,d,f]))), ?line eval(symdiff(set([c,d,g,h,k,l]), set([a,b,e,f,i,j,m,n])), union(set([c,d,g,h,k,l]), set([a,b,e,f,i,j,m,n]))), ?line eval(symdiff(set([c,d,g,h,k,l]), set([d,e,h,i,l,m,n,o,p])), union(set([c,g,k]), set([e,i,m,n,o,p]))), ok. symmetric_partition(suite) -> []; symmetric_partition(doc) -> [""]; symmetric_partition(Conf) when list(Conf) -> ?line E = set([]), ?line S1 = set([1,2,3,4]), ?line S2 = set([3,4,5,6]), ?line S3 = set([3,4]), ?line S4 = set([1,2,3,4,5,6]), ?line T1 = set([1,2]), ?line T2 = set([3,4]), ?line T3 = set([5,6]), ?line T4 = set([1,2,5,6]), ?line {'EXIT', {type_mismatch, _}} = (catch symmetric_partition(relation([{a,b}]), relation([{a,b,c}]))), ?line {E, E, E} = symmetric_partition(E, E), ?line {'EXIT', {type_mismatch, _}} = (catch symmetric_partition(relation([{a,b}]), from_term([{a,c}],[{d,r}]))), ?line {E, E, S1} = symmetric_partition(E, S1), ?line {S1, E, E} = symmetric_partition(S1, E), ?line {T1, T2, T3} = symmetric_partition(S1, S2), ?line {T3, T2, T1} = symmetric_partition(S2, S1), ?line {E, T2, T4} = symmetric_partition(S3, S4), ?line {T4, T2, E} = symmetric_partition(S4, S3), ?line S5 = set([1,3,5]), ?line S6 = set([2,4,6,7,8]), ?line {S5, E, S6} = symmetric_partition(S5, S6), ?line {S6, E, S5} = symmetric_partition(S6, S5), ?line EE = empty_set(), ?line {EE, EE, EE} = symmetric_partition(EE, EE), ok. is_sofs_set_1(suite) -> []; is_sofs_set_1(doc) -> [""]; is_sofs_set_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line true = is_sofs_set(E), ?line true = is_sofs_set(from_term([a])), ?line true = is_sofs_set(from_term({a})), ?line true = is_sofs_set(from_term(a)), ?line false = is_sofs_set(a), ok. is_set_1(suite) -> []; is_set_1(doc) -> [""]; is_set_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line true = is_set(E), ?line true = is_set(from_term([a])), ?line false = is_set(from_term({a})), ?line false = is_set(from_term(a)), ?line {'EXIT', _} = (catch is_set(a)), ?line true = is_empty_set(E), ?line false = is_empty_set(from_term([a])), ?line false = is_empty_set(from_term({a})), ?line false = is_empty_set(from_term(a)), ?line {'EXIT', _} = (catch is_empty_set(a)), ok. is_equal(suite) -> []; is_equal(doc) -> [""]; is_equal(Conf) when list(Conf) -> ?line E = empty_set(), ?line true = is_equal(E, E), ?line false = is_equal(from_term([a]), E), ?line {'EXIT', {type_mismatch, _}} = (catch is_equal(intersection(set([a]), set([b])), intersection(from_term([{a}]), from_term([{b}])))), ?line {'EXIT', {type_mismatch, _}} = (catch is_equal(from_term([],[{[atom],atom,[atom]}]), from_term([],[{[atom],{atom},[atom]}]))), ?line {'EXIT', {type_mismatch, _}} = (catch is_equal(set([a]), from_term([a],[type]))), ?line E2 = from_sets({from_term(a,atom)}), ?line true = is_equal(E2, E2), ?line true = is_equal(from_term({a}, {atom}), E2), ?line false = is_equal(from_term([{[a],[],c}]), from_term([{[],[],q}])), ?line {'EXIT', {type_mismatch, _}} = (catch is_equal(E, E2)), ?line {'EXIT', {type_mismatch, _}} = (catch is_equal(E2, E)), ?line true = is_equal(from_term({[],a,[]},{[atom],atom,[atom]}), from_term({[],a,[]},{[atom],atom,[atom]})), ?line {'EXIT', {type_mismatch, _}} = (catch is_equal(from_term({[],a,[]},{[atom],atom,[atom]}), from_term({[],{a},[]},{[atom],{atom},[atom]}))), ?line {'EXIT', {type_mismatch, _}} = (catch is_equal(from_term({a}), from_term({a},{type}))), ok. is_subset(suite) -> []; is_subset(doc) -> [""]; is_subset(Conf) when list(Conf) -> ?line E = empty_set(), ?line true = is_subset(E, E), ?line true = is_subset(set([a,c,e]), set([a,b,c,d,e])), ?line false = is_subset(set([a,b]), E), ?line false = is_subset(set([d,e,f]), set([b,c,d,e])), ?line false = is_subset(set([a,b,c]), set([b,c])), ?line false = is_subset(set([b,c]), set([a,c])), ?line false = is_subset(set([d,e]), set([a,b])), ?line {'EXIT', {type_mismatch, _}} = (catch is_subset(intersection(set([a]), set([b])), intersection(from_term([{a}]), from_term([{b}])))), ?line {'EXIT', {type_mismatch, _}} = (catch is_subset(set([a]), from_term([a,b], [at]))), ok. is_a_function_1(suite) -> []; is_a_function_1(doc) -> [""]; is_a_function_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([], 2), ?line {'EXIT', {badarg, _}} = (catch is_a_function(set([a,b]))), ?line true = is_a_function(E), ?line true = is_a_function(ER), ?line true = is_a_function(relation([])), ?line true = is_a_function(relation([],2)), ?line true = is_a_function(relation([{a,b},{b,c}])), ?line false = is_a_function(relation([{a,b},{b,c},{b,d},{e,f}])), ?line IS = relation([{{a,b},c},{{a,b},d}]), ?line false = is_a_function(IS), F = 0.0, I = round(F), ?line FR = relation([{I,F},{F,1}]), if F == I -> % term ordering false = is_a_function(FR); true -> true = is_a_function(FR) end, ok. is_disjoint(suite) -> []; is_disjoint(doc) -> [""]; is_disjoint(Conf) when list(Conf) -> ?line E = empty_set(), ?line {'EXIT', {type_mismatch, _}} = (catch is_disjoint(relation([{a,1}]), set([a,b]))), ?line {'EXIT', {type_mismatch, _}} = (catch is_disjoint(set([a]), from_term([a],[mota]))), ?line true = is_disjoint(E, E), ?line false = is_disjoint(set([a,b,c]),set([b,c,d])), ?line false = is_disjoint(set([b,c,d]),set([a,b,c])), ?line true = is_disjoint(set([a,c,e]),set([b,d,f])), ok. join(suite) -> []; join(doc) -> [""]; join(Conf) when list(Conf) -> ?line E = empty_set(), ?line {'EXIT', {badarg, _}} = (catch join(relation([{a,1}]), 3, E, 5)), ?line {'EXIT', {badarg, _}} = (catch join(E, 1, relation([{a,1}]), 3)), ?line {'EXIT', {badarg, _}} = (catch join(E, 1, from_term([a]), 1)), ?line eval(join(E, 1, E, 2), E), ?line eval(join(E, 1, from_term([{{a},b}]), 2), E), ?line eval(join(from_term([{{a},b}]), 2, E, 1), E), ?line eval(join(from_term([{{a},b,e}]), 2, from_term([{c,{d}}]), 1), from_term([], [{{atom},atom,atom,{atom}}])), ?line eval(join(relation([{a}]), 1, relation([{1,a},{2,a}]), 2), relation([{a,1},{a,2}])), ?line eval(join(relation([{a,b,c},{b,c,d}]), 2, relation([{1,b},{2,a},{3,c}]), 2), relation([{a,b,c,1},{b,c,d,3}])), ?line eval(join(relation([{1,a,aa},{1,b,bb},{1,c,cc},{2,a,aa},{2,b,bb}]), 1, relation([{1,c,cc},{1,d,dd},{1,e,ee},{2,c,cc},{2,d,dd}]), 1), relation([{1,a,aa,c,cc},{1,a,aa,d,dd},{1,a,aa,e,ee},{1,b,bb,c,cc}, {1,b,bb,d,dd},{1,b,bb,e,ee},{1,c,cc,c,cc},{1,c,cc,d,dd}, {1,c,cc,e,ee},{2,a,aa,c,cc},{2,a,aa,d,dd},{2,b,bb,c,cc}, {2,b,bb,d,dd}])), R1 = relation([{a,b},{b,c}]), R2 = relation([{b,1},{a,2},{c,3},{c,4}]), ?line eval(join(R1, 1, R2, 1), from_term([{a,b,2},{b,c,1}])), ?line eval(join(R1, 2, R2, 1), from_term([{a,b,1},{b,c,3},{b,c,4}])), ?line eval(join(R1, 1, converse(R2), 2), from_term([{a,b,2},{b,c,1}])), ?line eval(join(R1, 2, converse(R2), 2), from_term([{a,b,1},{b,c,3},{b,c,4}])), ok. canonical(suite) -> []; canonical(doc) -> [""]; canonical(Conf) when list(Conf) -> ?line E = empty_set(), ?line {'EXIT', {badarg, _}} = (catch canonical_relation(set([a,b]))), ?line eval(canonical_relation(E), E), ?line eval(canonical_relation(from_term([[]])), E), ?line eval(canonical_relation(from_term([[a,b,c]])), from_term([{a,[a,b,c]},{b,[a,b,c]},{c,[a,b,c]}])), ok. relation_to_family_1(suite) -> []; relation_to_family_1(doc) -> [""]; relation_to_family_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = family([]), ?line eval(relation_to_family(E), E), ?line eval(relation_to_family(relation([])), EF), ?line eval(relation_to_family(relation([], 2)), EF), ?line R = relation([{b,1},{c,7},{c,9},{c,11}]), ?line F = family([{b,[1]},{c,[7,9,11]}]), ?line eval(relation_to_family(R), F), ?line eval(sofs:rel2fam(R), F), ?line {'EXIT', {badarg, _}} = (catch relation_to_family(set([a]))), ok. domain_1(suite) -> []; domain_1(doc) -> [""]; domain_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line {'EXIT', {badarg, _}} = (catch domain(relation([],3))), ?line eval(domain(E), E), ?line eval(domain(ER), set([])), ?line eval(domain(relation([{1,a},{1,b},{2,a},{2,b}])), set([1,2])), ?line eval(domain(relation([{a,1},{b,2},{c,3}])), set([a,b,c])), ?line eval(field(relation([{a,1},{b,2},{c,3}])), set([a,b,c,1,2,3])), F = 0.0, I = round(F), ?line FR = relation([{I,a},{F,b}]), if F == I -> % term ordering ?line true = (1 =:= no_elements(domain(FR))); true -> ?line true = (2 =:= no_elements(domain(FR))) end, ok. range_1(suite) -> []; range_1(doc) -> [""]; range_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line {'EXIT', {badarg, _}} = (catch range(relation([],3))), ?line eval(range(E), E), ?line eval(range(ER), set([])), ?line eval(range(relation([{1,a},{1,b},{2,a},{2,b}])), set([a,b])), ?line eval(range(relation([{a,1},{b,2},{c,3}])), set([1,2,3])), ok. inverse_1(suite) -> []; inverse_1(doc) -> [""]; inverse_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line {'EXIT', {badarg, _}} = (catch inverse(relation([],3))), ?line {'EXIT', {bad_function, _}} = (catch inverse(relation([{1,a},{1,b}]))), ?line {'EXIT', {bad_function, _}} = (catch inverse(relation([{1,a},{2,a}]))), ?line eval(inverse(E), E), ?line eval(inverse(ER), ER), ?line eval(inverse(relation([{a,1},{b,2},{c,3}])), relation([{1,a},{2,b},{3,c}])), F = 0.0, I = round(F), ?line FR = relation([{I,a},{F,b}]), if F == I -> % term ordering ?line {'EXIT', {bad_function, _}} = (catch inverse(FR)); true -> ?line eval(inverse(FR), relation([{a,I},{b,F}])) end, ok. converse_1(suite) -> []; converse_1(doc) -> [""]; converse_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line {'EXIT', {badarg, _}} = (catch converse(relation([],3))), ?line eval(converse(ER), ER), ?line eval(converse(E), E), ?line eval(converse(relation([{a,1},{b,2},{c,3}])), relation([{1,a},{2,b},{3,c}])), ?line eval(converse(relation([{1,a},{1,b}])), relation([{a,1},{b,1}])), ?line eval(converse(relation([{1,a},{2,a}])), relation([{a,1},{a,2}])), ok. no_elements_1(suite) -> []; no_elements_1(doc) -> [""]; no_elements_1(Conf) when list(Conf) -> ?line 0 = no_elements(empty_set()), ?line 0 = no_elements(set([])), ?line 1 = no_elements(from_term([a])), ?line 10 = no_elements(from_term(lists:seq(1,10))), ?line 3 = no_elements(from_term({a,b,c},{atom,atom,atom})), ?line {'EXIT', {badarg, _}} = (catch no_elements(from_term(a))), ?line {'EXIT', {function_clause, _}} = (catch no_elements(a)), ok. image(suite) -> []; image(doc) -> [""]; image(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line eval(image(E, E), E), ?line eval(image(ER, E), set([])), ?line eval(image(relation([{a,1},{b,2},{c,3},{f,6}]), set([a,b,c,d,f])), set([1,2,3,6])), ?line eval(image(relation([{a,1},{b,2},{c,3},{d,4},{r,17}]), set([b,c,q,r])), set([2,3,17])), ?line eval(image(from_term([{[a],{1}},{[b],{2}}]), from_term([[a]])), from_term([{1}])), ?line eval(image(relation([{1,a},{2,a},{3,a},{4,b},{2,b}]), set([1,2,4])), set([a,b])), ?line {'EXIT', {badarg, _}} = (catch image(from_term([a,b]), E)), ?line {'EXIT', {type_mismatch, _}} = (catch image(from_term([{[a],1}]), set([[a]]))), ok. inverse_image(suite) -> []; inverse_image(doc) -> [""]; inverse_image(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line eval(inverse_image(E, E), E), ?line eval(inverse_image(ER, E), set([])), ?line eval(inverse_image(converse(relation([{a,1},{b,2},{c,3},{f,6}])), set([a,b,c,d,f])), set([1,2,3,6])), ?line eval(inverse_image(converse(relation([{a,1},{b,2},{c,3}, {d,4},{r,17}])), set([b,c,q,r])), set([2,3,17])), ?line eval(inverse_image(converse(from_term([{[a],{1}},{[b],{2}}])), from_term([[a]])), from_term([{1}])), ?line eval(inverse_image(converse(relation([{1,a},{2,a}, {3,a},{4,b},{2,b}])), set([1,2,4])), set([a,b])), ?line {'EXIT', {badarg, _}} = (catch inverse_image(from_term([a,b]), E)), ?line {'EXIT', {type_mismatch, _}} = (catch inverse_image(converse(from_term([{[a],1}])), set([[a]]))), ok. composite_1(suite) -> []; composite_1(doc) -> [""]; composite_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = a_function([]), ?line eval(composite(E, E), E), ?line eval(composite(E, a_function([{a,b}])), E), ?line eval(composite(relation([{a,b}]), E), E), ?line {'EXIT', {bad_function, _}} = (catch composite(EF, relation([{a,b},{a,c}]))), ?line {'EXIT', {bad_function, _}} = (catch composite(a_function([{b,a}]), EF)), ?line {'EXIT', {bad_function, _}} = (catch composite(relation([{1,a},{2,b},{2,a}]), a_function([{a,1},{b,3}]))), ?line {'EXIT', {bad_function, _}} = (catch composite(a_function([{1,a},{2,b}]), a_function([{b,3}]))), ?line eval(composite(EF, EF), EF), ?line eval(composite(a_function([{b,a}]), from_term([{a,{b,c}}])), from_term([{b,{b,c}}])), ?line eval(composite(a_function([{q,1},{z,2}]), a_function([{1,a},{2,a}])), a_function([{q,a},{z,a}])), ?line eval(composite(a_function([{a,0},{b,0},{c,1},{d,1},{e,2},{f,3}]), a_function([{0,p},{1,q},{2,r},{3,w},{4,aa}])), a_function([{c,q},{d,q},{f,w},{e,r},{a,p},{b,p}])), ?line eval(composite(a_function([{1,c}]), a_function([{a,1},{b,3},{c,4}])), a_function([{1,4}])), ?line {'EXIT', {bad_function, _}} = (catch composite(a_function([{1,a},{2,b}]), a_function([{a,1},{c,3}]))), ?line {'EXIT', {badarg, _}} = (catch composite(from_term([a,b]), E)), ?line {'EXIT', {badarg, _}} = (catch composite(E, from_term([a,b]))), ?line {'EXIT', {type_mismatch, _}} = (catch composite(from_term([{a,b}]), from_term([{{a},b}]))), ?line {'EXIT', {type_mismatch, _}} = (catch composite(from_term([{a,b}]), from_term([{b,c}], [{d,r}]))), F = 0.0, I = round(F), ?line FR1 = relation([{1,c}]), ?line FR2 = relation([{I,1},{F,3},{c,4}]), if F == I -> % term ordering ?line {'EXIT', {bad_function, _}} = (catch composite(FR1, FR2)); true -> ?line eval(composite(FR1, FR2), a_function([{1,4}])) end, ok. relative_product_1(suite) -> []; relative_product_1(doc) -> [""]; relative_product_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line eval(relative_product1(E, E), E), ?line eval(relative_product1(E, relation([{a,b}])), E), ?line eval(relative_product1(relation([{a,b}]), E), E), ?line eval(relative_product1(relation([{a,b}]), from_term([{a,{b,c}}])), from_term([{b,{b,c}}])), ?line eval(relative_product1(relation([{1,z},{1,q},{2,z}]), relation([{1,a},{1,b},{2,a}])), relation([{q,a},{q,b},{z,a},{z,b}])), ?line eval(relative_product1(relation([{0,a},{0,b},{1,c}, {1,d},{2,e},{3,f}]), relation([{1,q},{3,w}])), relation([{c,q},{d,q},{f,w}])), ?line {'EXIT', {badarg, _}} = (catch relative_product1(from_term([a,b]), ER)), ?line {'EXIT', {badarg, _}} = (catch relative_product1(ER, from_term([a,b]))), ?line {'EXIT', {type_mismatch, _}} = (catch relative_product1(from_term([{a,b}]), from_term([{{a},b}]))), ?line {'EXIT', {type_mismatch, _}} = (catch relative_product1(from_term([{a,b}]), from_term([{b,c}], [{d,r}]))), ok. relative_product_2(suite) -> []; relative_product_2(doc) -> [""]; relative_product_2(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line {'EXIT', {badarg, _}} = (catch relative_product({from_term([a,b])})), ?line {'EXIT', {type_mismatch, _}} = (catch relative_product({from_term([{a,b}]), from_term([{{a},b}])})), ?line {'EXIT', {badarg, _}} = (catch relative_product({})), ?line true = is_equal(relative_product({ER}), from_term([], [{atom,{atom}}])), ?line eval(relative_product({relation([{a,b},{c,a}]), relation([{a,1},{a,2}]), relation([{a,aa},{c,1}])}), from_term([{a,{b,1,aa}},{a,{b,2,aa}}])), ?line eval(relative_product({relation([{a,b}])}, E), E), ?line eval(relative_product({E}, relation([{a,b}])), E), ?line eval(relative_product({E,from_term([], [{{atom,atom,atom},atom}])}), E), ?line {'EXIT', {badarg, _}} = (catch relative_product({from_term([a,b])}, E)), ?line {'EXIT', {badarg, _}} = (catch relative_product({relation([])}, set([]))), ?line {'EXIT', {type_mismatch, _}} = (catch relative_product({from_term([{a,b}]), from_term([{{a},b}])}, ER)), ?line {'EXIT', {badarg, _}} = (catch relative_product({}, ER)), ?line eval(relative_product({relation([{a,b}])}, from_term([],[{{atom},atom}])), ER), ?line eval(relative_product({relation([{a,b}]),relation([{a,1}])}, from_term([{{b,1},{tjo,hej,sa}}])), from_term([{a,{tjo,hej,sa}}])), ?line eval(relative_product({relation([{a,b}]), ER}, from_term([{{a,b},b}])), ER), ?line eval(relative_product({relation([{a,b},{c,a}]), relation([{a,1},{a,2}])}, from_term([{{b,1},b1},{{b,2},b2}])), relation([{a,b1},{a,b2}])), ?line eval(relative_product({relation([{a,b}]), ER}), from_term([],[{atom,{atom,atom}}])), ?line eval(relative_product({from_term([{{a,[a,b]},[a]}]), from_term([{{a,[a,b]},[[a,b]]}])}), from_term([{{a,[a,b]},{[a],[[a,b]]}}])), ok. product_1(suite) -> []; product_1(doc) -> [""]; product_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line eval(product(E, E), E), ?line eval(product(relation([]), E), E), ?line eval(product(E, relation([])), E), ?line eval(product(relation([{a,b}]),relation([{c,d}])), from_term([{{a,b},{c,d}}],[{{atom,atom},{atom,atom}}])), ?line eval(product({E, set([a,b,c])}), E), ?line eval(product({set([a,b,c]), E}), E), ?line eval(product({set([a,b,c]), E, E}), E), ?line eval(product({E,E}), E), ?line eval(product({set([a,b]),set([1,2])}), relation([{a,1},{a,2},{b,1},{b,2}])), ?line eval(product({from_term([a,b]), from_term([{a,b},{c,d}]), from_term([1])}), from_term([{a,{a,b},1},{a,{c,d},1},{b,{a,b},1},{b,{c,d},1}])), ?line {'EXIT', {badarg, _}} = (catch product({})), ?line {'EXIT', {badarg, _}} = (catch product({foo})), ?line eval(product({E}), E), ?line eval(product({E, E}), E), ?line eval(product(set([a,b]), set([1,2])), relation([{a,1},{a,2},{b,1},{b,2}])), ?line eval(product({relation([]), E}), E), ok. partition_1(suite) -> []; partition_1(doc) -> [""]; partition_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line Id = fun(A) -> A end, ?line S1 = relation([{a,1},{b,2},{b,22},{c,0}]), ?line eval(partition(1, E), E), ?line eval(partition(2, E), E), ?line eval(partition(1, ER), from_term([], [type(ER)])), ?line eval(partition(2, ER), from_term([], [type(ER)])), ?line eval(partition(1, relation([{1,a},{1,b},{2,c},{2,d}])), from_term([[{1,a},{1,b}],[{2,c},{2,d}]])), ?line eval(partition(2, relation([{1,a},{1,b},{2,a},{2,b},{3,c}])), from_term([[{1,a},{2,a}],[{1,b},{2,b}],[{3,c}]])), ?line eval(partition(2, relation([{1,a}])), from_term([[{1,a}]])), ?line eval(partition(2, relation([{1,a},{2,b}])), from_term([[{1,a}],[{2,b}]])), ?line eval(partition(2, relation([{1,a},{2,a},{3,a}])), from_term([[{1,a},{2,a},{3,a}]])), ?line eval(partition(2, relation([{1,b},{2,a}])), % OTP-4516 from_term([[{1,b}],[{2,a}]])), ?line eval(union(partition(Id, S1)), S1), ?line eval(partition({external, fun({A,{B,_}}) -> {A,B} end}, from_term([{a,{b,c}},{b,{c,d}},{a,{b,f}}])), from_term([[{a,{b,c}},{a,{b,f}}],[{b,{c,d}}]])), F = 0.0, I = round(F), ?line FR = relation([{I,a},{F,b}]), if F == I -> % term ordering ?line eval(partition(1, FR), from_term([[{I,a},{F,b}]])); true -> ?line eval(partition(1, FR), from_term([[{I,a}],[{F,b}]])) end, ?line {'EXIT', {badarg, _}} = (catch partition(2, set([a]))), ?line {'EXIT', {badarg, _}} = (catch partition(1, set([a]))), ?line eval(partition(Id, set([a])), from_term([[a]])), ?line eval(partition(E), E), ?line P1 = from_term([[a,b,c],[d,e,f],[g,h]]), ?line P2 = from_term([[a,d],[b,c,e,f,q,v]]), ?line eval(partition(union(P1, P2)), from_term([[a],[b,c],[d],[e,f],[g,h],[q,v]])), ?line {'EXIT', {badarg, _}} = (catch partition(from_term([a]))), ok. partition_3(suite) -> []; partition_3(doc) -> [""]; partition_3(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), %% set of ordered sets ?line S1 = relation([{a,1},{b,2},{b,22},{c,0}]), ?line eval(partition(1, S1, set([0,1,d,e])), lpartition(1, S1, set([0,1,d,e]))), ?line eval(partition(1, S1, E), lpartition(1, S1, E)), ?line eval(partition(2, ER, set([a,b])), lpartition(2, ER, set([a,b]))), XFun1 = {external, fun({_A,B,C}) -> {B,C} end}, R1a = relation([{a,aa,1},{b,bb,2},{c,cc,3}]), R1b = relation([{bb,2},{cc,3}]), ?line eval(partition(XFun1, R1a, R1b), lpartition(XFun1, R1a, R1b)), Id = fun(X) -> X end, XId = {external, Id}, R2 = relation([{a,b}]), ?line eval(partition(XId, R2, E), lpartition(XId, R2, E)), R3 = relation([{b,d}]), ?line eval(partition(XId, E, R3), lpartition(XId, E, R3)), Fun1 = fun(S) -> {_A,B,C} = to_external(S), from_term({B,C}) end, R4a = relation([{a,aa,1},{b,bb,2},{c,cc,3}]), R4b = relation([{bb,2},{cc,3}]), ?line eval(partition(Fun1,R4a,R4b), lpartition(Fun1,R4a,R4b)), XFun2 = {external, fun({_,{A},B}) -> {A,B} end}, R5a = from_term([{a,{aa},1},{b,{bb},2},{c,{cc},3}]), R5b = from_term([{bb,2},{cc,3}]), ?line eval(partition(XFun2,R5a, R5b), lpartition(XFun2,R5a, R5b)), R6 = relation([{a,b}]), ?line eval(partition(2, R6, E), lpartition(2, R6, E)), R7 = relation([{b,d}]), ?line eval(partition(2, E, R7), lpartition(2, E, R7)), S2 = set([a]), ?line eval(partition(XId, E, S2), lpartition(XId, E, S2)), ?line eval(partition(XId, S1, E), lpartition(XId, S1, E)), ?line {'EXIT', {badarg, _}} = (catch partition(3, relation([{a,b}]), E)), ?line {'EXIT', {badarg, _}} = (catch partition(3, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {badarg, _}} = (catch partition(3, relation([{a,b}]), set([{b,d}]))), ?line {'EXIT', {type_mismatch, _}} = (catch partition(2, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {type_mismatch, _}} = (catch partition({external, fun({A,_B}) -> A end}, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {badarg, _}} = (catch partition({external, fun({A,_}) -> {A,0} end}, from_term([{1,a}]), from_term([{1,0}]))), S18a = relation([{1,e},{2,b},{3,c},{4,b},{5,a},{6,0}]), S18b = set([b,d,f]), ?line eval(partition({external,fun({_,X}) -> X end}, S18a, S18b), lpartition({external,fun({_,X}) -> X end}, S18a, S18b)), S19a = sofs:relation([{3,a},{8,b}]), S19b = set([2,6,7]), ?line eval(partition({external,fun({X,_}) -> X end}, S19a, S19b), lpartition({external,fun({X,_}) -> X end}, S19a, S19b)), R8a = relation([{a,d},{b,e},{c,b},{d,c}]), S8 = set([b,d]), ?line eval(partition(2, R8a, S8), lpartition(2, R8a, S8)), S16a = relation([{1,e},{2,b},{3,c},{4,b},{5,a},{6,0}]), S16b = set([b,c,d]), ?line eval(partition(2, S16a, S16b), lpartition(2, S16a, S16b)), S17a = relation([{e,1},{b,2},{c,3},{b,4},{a,5},{0,6}]), S17b = set([b,c,d]), ?line eval(partition(1, S17a, S17b), lpartition(1, S17a, S17b)), ?line {'EXIT', {function_clause, _}} = (catch partition({external, fun({A,_B}) -> A end}, set([]), E)), Fun3 = fun(S) -> from_term({to_external(S),0}, {type(S),atom}) end, S9a = set([1,2]), S9b = from_term([{1,0}]), ?line eval(partition(Fun3, S9a, S9b), lpartition(Fun3, S9a, S9b)), S14a = relation([{1,a},{2,b},{3,c},{0,0}]), S14b = set([b,c]), ?line eval(partition(2, S14a, S14b), lpartition(2, S14a, S14b)), S15a = relation([{a,1},{b,2},{c,3},{0,0}]), S15b = set([b,c]), ?line eval(partition(1, S15a, S15b), lpartition(1, S15a, S15b)), %% set of sets ?line {'EXIT', {badarg, _}} = (catch partition({external, fun(X) -> X end}, from_term([], [[atom]]), set([a]))), S10 = from_term([], [[atom]]), ?line eval(partition(Id, S10, E), lpartition(Id, S10, E)), S10e = from_term([[a],[b]], [[atom]]), ?line eval(partition(Id, S10e, E), lpartition(Id, S10e, E)), S11a = from_term([], [[atom]]), S11b = set([a]), ?line eval(partition(Id, S11a, S11b), lpartition(Id, S11a, S11b)), S12a = from_term([[[a],[b]], [[b],[c]], [[], [a,b]], [[1],[2]]]), S12b = from_term([[a,b],[1,2,3],[b,c]]), ?line eval(partition({sofs,union}, S12a, S12b), lpartition({sofs,union}, S12a, S12b)), Fun13 = fun(_) -> from_term([a]) end, S13a = from_term([], [[atom]]), S13b = from_term([], [[a]]), ?line eval(partition(Fun13, S13a, S13b), lpartition(Fun13, S13a, S13b)), ?line {'EXIT', {type_mismatch, _}} = (catch partition(fun(_) -> from_term([a]) end, from_term([[1,2],[3,4]]), from_term([], [atom]))), Fun10 = fun(S) -> %% Cheating a lot... case to_external(S) of [1] -> from_term({1,1}); _ -> S end end, ?line {'EXIT', {type_mismatch, _}} = (catch partition(Fun10, from_term([[1]]), from_term([], [[atom]]))), ?line {'EXIT', {type_mismatch, _}} = (catch partition(fun(_) -> from_term({a}) end, from_term([[a]]), from_term([], [atom]))), ?line {'EXIT', {badarg, _}} = (catch partition(fun(_) -> {a} end, from_term([[a]]), from_term([], [atom]))), ok. lpartition(F, S1, S2) -> {restriction(F, S1, S2), drestriction(F, S1, S2)}. multiple_relative_product(suite) -> []; multiple_relative_product(doc) -> [""]; multiple_relative_product(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line T = relation([{a,1},{a,11},{b,2},{c,3},{c,33},{d,4}]), ?line {'EXIT', {badarg, _}} = (catch multiple_relative_product({}, ER)), ?line {'EXIT', {badarg, _}} = (catch multiple_relative_product({}, relation([{a,b}]))), ?line eval(multiple_relative_product({E,T,T}, relation([], 3)), E), ?line eval(multiple_relative_product({T,T,T}, E), E), ?line eval(multiple_relative_product({T,T,T}, relation([],3)), from_term([],[{{atom,atom,atom},{atom,atom,atom}}])), ?line eval(multiple_relative_product({T,T,T}, relation([{a,b,c},{c,d,a}])), from_term([{{a,b,c},{1,2,3}}, {{a,b,c},{1,2,33}}, {{a,b,c},{11,2,3}}, {{a,b,c},{11,2,33}}, {{c,d,a},{3,4,1}}, {{c,d,a},{3,4,11}}, {{c,d,a},{33,4,1}}, {{c,d,a},{33,4,11}}])), ?line {'EXIT', {type_mismatch, _}} = (catch multiple_relative_product({T}, from_term([{{a}}]))), ok. digraph(suite) -> []; digraph(doc) -> [""]; digraph(Conf) when list(Conf) -> ?line T0 = ets:all(), ?line E = empty_set(), ?line R = relation([{a,b},{b,c},{c,d},{d,a}]), ?line F = relation_to_family(R), Type = type(F), ?line {'EXIT', {badarg, _}} = (catch family_to_digraph(set([a]))), ?line {'EXIT', {badarg, [{sofs,family_to_digraph,[_,_]}|_]}} = (catch family_to_digraph(set([a]), [foo])), ?line {'EXIT', {badarg, [{sofs,family_to_digraph,[_,_]}|_]}} = (catch family_to_digraph(F, [foo])), ?line {'EXIT', {cyclic, [{sofs,family_to_digraph,[_,_]}|_]}} = (catch family_to_digraph(family([{a,[a]}]),[acyclic])), ?line G1 = family_to_digraph(E), ?line {'EXIT', {badarg, _}} = (catch digraph_to_family(G1, foo)), ?line {'EXIT', {badarg, _}} = (catch digraph_to_family(G1, atom)), ?line true = [] == to_external(digraph_to_family(G1)), ?line true = [] == to_external(digraph_to_family(G1, Type)), ?line true = digraph:delete(G1), ?line G1a = family_to_digraph(E, [protected]), ?line true = [] == to_external(digraph_to_family(G1a)), ?line true = [] == to_external(digraph_to_family(G1a, Type)), ?line true = digraph:delete(G1a), ?line G2 = family_to_digraph(F), ?line true = F == digraph_to_family(G2), ?line true = F == digraph_to_family(G2, type(F)), ?line true = digraph:delete(G2), ?line R2 = from_term([{{a},b},{{c},d}]), ?line F2 = relation_to_family(R2), ?line Type2 = type(F2), ?line G3 = family_to_digraph(F2, [protected]), ?line true = is_subset(F2, digraph_to_family(G3, Type2)), ?line true = digraph:delete(G3), Fl = 0.0, I = round(Fl), if Fl == I -> % term ordering ?line G4 = digraph:new(), digraph:add_vertex(G4, Fl), digraph:add_vertex(G4, I), ?line {'EXIT', {badarg, _}} = (catch digraph_to_family(G4, Type)), ?line {'EXIT', {badarg, _}} = (catch digraph_to_family(G4)), ?line true = digraph:delete(G4); true -> ok end, ?line true = T0 == ets:all(), ok. constant_function(suite) -> []; constant_function(doc) -> [""]; constant_function(Conf) when list(Conf) -> ?line E = empty_set(), ?line C = from_term(3), ?line eval(constant_function(E, C), E), ?line eval(constant_function(set([a,b]), E), from_term([{a,[]},{b,[]}])), ?line eval(constant_function(set([a,b]), C), from_term([{a,3},{b,3}])), ?line {'EXIT', {badarg, _}} = (catch constant_function(C, C)), ?line {'EXIT', {badarg, _}} = (catch constant_function(set([]), foo)), ok. misc(suite) -> []; misc(doc) -> [""]; misc(Conf) when list(Conf) -> % find "relational" part of relation: ?line S = relation([{a,b},{b,c},{b,d},{c,d}]), Id = fun(A) -> A end, ?line RR = relational_restriction(S), ?line eval(union(difference(partition(Id,S), partition(1,S))), RR), ?line eval(union(difference(partition(1,S), partition(Id,S))), RR), % the "functional" part: ?line eval(union(intersection(partition(1,S), partition(Id,S))), difference(S, RR)), %% The function external:foo/1 is undefined. ?line {'EXIT', {undef, _}} = (catch projection({external,foo}, set([a,b,c]))), ok. relational_restriction(R) -> Fun = fun(S) -> no_elements(S) > 1 end, family_to_relation(family_specification(Fun, relation_to_family(R))). sofs_family(suite) -> [family_specification, family_domain_1, family_range_1, family_to_relation_1, union_of_family_1, intersection_of_family_1, family_projection, family_difference, family_intersection_1, family_intersection_2, family_union_1, family_union_2, partition_family]. family_specification(suite) -> []; family_specification(doc) -> [""]; family_specification(Conf) when list(Conf) -> E = empty_set(), %% internal ?line eval(family_specification({sofs, is_set}, E), E), ?line {'EXIT', {badarg, _}} = (catch family_specification({sofs,is_set}, set([]))), ?line F1 = from_term([{1,[1]}]), ?line eval(family_specification({sofs,is_set}, F1), F1), Fun = fun(S) -> is_subset(S, set([0,1,2,3,4])) end, ?line F2 = family([{a,[1,2]},{b,[3,4,5]}]), ?line eval(family_specification(Fun, F2), family([{a,[1,2]}])), ?line F3 = from_term([{a,[]},{b,[]}]), ?line eval(family_specification({sofs,is_set}, F3), F3), Fun2 = fun(_) -> throw(fippla) end, ?line fippla = (catch family_specification(Fun2, family([{a,[1]}]))), Fun3 = fun(_) -> neither_true_or_false end, ?line {'EXIT', {badarg, _}} = (catch family_specification(Fun3, F3)), %% external IsList = {external, fun(L) when list(L) -> true; (_) -> false end}, ?line eval(family_specification(IsList, E), E), ?line eval(family_specification(IsList, F1), F1), MF = {external, fun(L) -> lists:member(3, L) end}, ?line eval(family_specification(MF, F2), family([{b,[3,4,5]}])), ?line fippla = (catch family_specification(Fun2, family([{a,[1]}]))), ?line {'EXIT', {badarg, _}} = (catch family_specification({external, Fun3}, F3)), ok. family_domain_1(suite) -> []; family_domain_1(doc) -> [""]; family_domain_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = from_term([{a,[]},{b,[]}],[{atom,[{atom,atom}]}]), ?line EF = from_term([{a,[]},{b,[]}],[{atom,[atom]}]), ?line eval(family_domain(E), E), ?line eval(family_domain(ER), EF), ?line FR = from_term([{a,[{1,a},{2,b},{3,c}]},{b,[]},{c,[{4,d},{5,e}]}]), ?line eval(family_domain(FR), from_term([{a,[1,2,3]},{b,[]},{c,[4,5]}])), ?line eval(family_field(E), E), ?line eval(family_field(FR), from_term([{a,[a,b,c,1,2,3]},{b,[]},{c,[d,e,4,5]}])), ?line eval(family_domain(from_term([{{a},[{{1,[]},c}]}])), from_term([{{a},[{1,[]}]}])), ?line eval(family_domain(from_term([{{a},[{{1,[a]},c}]}])), from_term([{{a},[{1,[a]}]}])), ?line eval(family_domain(from_term([{{a},[]}])), from_term([{{a},[]}])), ?line eval(family_domain(from_term([], type(FR))), from_term([], [{atom,[atom]}])), ?line {'EXIT', {badarg, _}} = (catch family_domain(set([a]))), ?line {'EXIT', {badarg, _}} = (catch family_field(set([a]))), ?line {'EXIT', {badarg, _}} = (catch family_domain(set([{a,[b]}]))), ok. family_range_1(suite) -> []; family_range_1(doc) -> [""]; family_range_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = from_term([{a,[]},{b,[]}],[{atom,[{atom,atom}]}]), ?line EF = from_term([{a,[]},{b,[]}],[{atom,[atom]}]), ?line eval(family_range(E), E), ?line eval(family_range(ER), EF), ?line FR = from_term([{a,[{1,a},{2,b},{3,c}]},{b,[]},{c,[{4,d},{5,e}]}]), ?line eval(family_range(FR), from_term([{a,[a,b,c]},{b,[]},{c,[d,e]}])), ?line eval(family_range(from_term([{{a},[{c,{1,[a]}}]}])), from_term([{{a},[{1,[a]}]}])), ?line eval(family_range(from_term([{{a},[{c,{1,[]}}]}])), from_term([{{a},[{1,[]}]}])), ?line eval(family_range(from_term([{{a},[]}])), from_term([{{a},[]}])), ?line eval(family_range(from_term([], type(FR))), from_term([], [{atom,[atom]}])), ?line {'EXIT', {badarg, _}} = (catch family_range(set([a]))), ?line {'EXIT', {badarg, _}} = (catch family_range(set([{a,[b]}]))), ok. family_to_relation_1(suite) -> []; family_to_relation_1(doc) -> [""]; family_to_relation_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line EF = family([]), ?line eval(family_to_relation(E), E), ?line eval(family_to_relation(EF), ER), ?line eval(sofs:fam2rel(EF), ER), ?line F = family([{a,[]},{b,[1]},{c,[7,9,11]}]), ?line eval(family_to_relation(F), relation([{b,1},{c,7},{c,9},{c,11}])), ?line {'EXIT', {badarg, _}} = (catch family_to_relation(set([a]))), ok. union_of_family_1(suite) -> []; union_of_family_1(doc) -> [""]; union_of_family_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = from_term([{a,[]},{b,[]}],[{atom,[atom]}]), ?line eval(union_of_family(E), E), ?line eval(union_of_family(EF), set([])), ?line eval(union_of_family(family([])), set([])), ?line FR = from_term([{a,[1,2,3]},{b,[]},{c,[4,5]}]), ?line eval(union_of_family(FR), set([1,2,3,4,5])), ?line eval(union_of_family(sofs:family([{a,[1,2]},{b,[1,2]}])), set([1,2])), ?line {'EXIT', {badarg, _}} = (catch union_of_family(set([a]))), ok. intersection_of_family_1(suite) -> []; intersection_of_family_1(doc) -> [""]; intersection_of_family_1(Conf) when list(Conf) -> ?line EF = from_term([{a,[]},{b,[]}],[{atom,[atom]}]), ?line eval(intersection_of_family(EF), set([])), ?line FR = from_term([{a,[1,2,3]},{b,[2,3]},{c,[3,4,5]}]), ?line eval(intersection_of_family(FR), set([3])), ?line {'EXIT', {badarg, _}} = (catch intersection_of_family(family([]))), ?line EE = from_term([], [[atom]]), ?line {'EXIT', {badarg, _}} = (catch intersection_of_family(EE)), ?line {'EXIT', {badarg, _}} = (catch intersection_of_family(set([a]))), ok. family_projection(suite) -> []; family_projection(doc) -> [""]; family_projection(Conf) when list(Conf) -> SSType = [{atom,[[atom]]}], SRType = [{atom,[{atom,atom}]}], ?line E = empty_set(), ?line eval(family_projection(fun(X) -> X end, family([])), E), ?line L1 = [{a,[]}], ?line eval(family_projection({sofs,union}, E), E), ?line eval(family_projection({sofs,union}, from_term(L1, SSType)), family(L1)), ?line {'EXIT', {badarg, _}} = (catch family_projection({sofs,union}, set([]))), ?line {'EXIT', {badarg, _}} = (catch family_projection({sofs,union}, from_term([{1,[1]}]))), ?line F2 = from_term([{a,[[1],[2]]},{b,[[3,4],[5]]}], SSType), ?line eval(family_projection({sofs,union}, F2), family_union(F2)), ?line F3 = from_term([{1,[{a,b},{b,c},{c,d}]},{3,[]},{5,[{3,5}]}], SRType), ?line eval(family_projection({sofs,domain}, F3), family_domain(F3)), ?line eval(family_projection({sofs,range}, F3), family_range(F3)), ?line eval(family_projection(fun(_) -> E end, family([{a,[b,c]}])), from_term([{a,[]}])), Fun1 = fun(S) -> case to_external(S) of [1] -> from_term({1,1}); _ -> S end end, ?line eval(family_projection(Fun1, family([{a,[1]}])), from_term([{a,{1,1}}])), Fun2 = fun(_) -> throw(fippla) end, ?line fippla = (catch family_projection(Fun2, family([{a,[1]}]))), ?line {'EXIT', {type_mismatch, _}} = (catch family_projection(Fun1, from_term([{1,[1]},{2,[2]}]))), ?line {'EXIT', {type_mismatch, _}} = (catch family_projection(Fun1, from_term([{1,[1]},{0,[0]}]))), ?line eval(family_projection(fun(_) -> E end, from_term([{a,[]}])), from_term([{a,[]}])), F4 = from_term([{a,[{1,2,3}]},{b,[{4,5,6}]},{c,[]},{m3,[]}]), Z = from_term(0), ?line eval(family_projection(fun(S) -> local_adjoin(S, Z) end, F4), from_term([{a,[{{1,2,3},0}]},{b,[{{4,5,6},0}]},{c,[]},{m3,[]}])), ?line {'EXIT', {badarg, _}} = (catch family_projection({external, fun(X) -> X end}, from_term([{1,[1]}]))), %% ordered set element ?line eval(family_projection(fun(_) -> from_term(a, atom) end, from_term([{1,[a]}])), from_term([{1,a}])), ok. family_difference(suite) -> []; family_difference(doc) -> [""]; family_difference(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = family([]), ?line F9 = from_term([{b,[b,c]}]), ?line F10 = from_term([{a,[b,c]}]), ?line eval(family_difference(E, E), E), ?line eval(family_difference(E, F10), from_term([], type(F10))), ?line eval(family_difference(F10, E), F10), ?line eval(family_difference(F9, F10), F9), ?line eval(family_difference(F10, F10), family([{a,[]}])), ?line F20 = from_term([{a,[1,2,3]},{b,[1,2,3]},{c,[1,2,3]}]), ?line F21 = from_term([{b,[1,2,3]},{c,[1,2,3]}]), ?line eval(family_difference(F20, from_term([{a,[2]}])), from_term([{a,[1,3]},{b,[1,2,3]},{c,[1,2,3]}])), ?line eval(family_difference(F20, from_term([{0,[2]},{q,[1,2]}])), F20), ?line eval(family_difference(F20, F21), from_term([{a,[1,2,3]},{b,[]},{c,[]}])), ?line eval(family_difference(from_term([{e,[f,g]}]), family([])), from_term([{e,[f,g]}])), ?line eval(family_difference(from_term([{e,[f,g]}]), EF), from_term([{e,[f,g]}])), ?line eval(family_difference(from_term([{a,[a,b,c,d]},{c,[b,c]}]), from_term([{a,[b,c]},{b,[d]},{d,[e,f]}])), from_term([{a,[a,d]},{c,[b,c]}])), ?line {'EXIT', {badarg, _}} = (catch family_difference(set([]), set([]))), ?line {'EXIT', {type_mismatch, _}} = (catch family_difference(from_term([{a,[b,c]}]), from_term([{e,[{f}]}]))), ?line {'EXIT', {type_mismatch, _}} = (catch family_difference(from_term([{a,[b]}]), from_term([{c,[d]}], [{i,[s]}]))), ok. family_intersection_1(suite) -> []; family_intersection_1(doc) -> [""]; family_intersection_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = family([]), ?line ES = from_term([], [{atom,[[atom]]}]), ?line eval(family_intersection(E), E), ?line {'EXIT', {badarg, _}} = (catch family_intersection(EF)), ?line eval(family_intersection(ES), EF), ?line {'EXIT', {badarg, _}} = (catch family_intersection(set([]))), ?line {'EXIT', {badarg, _}} = (catch family_intersection(from_term([{a,[1,2]}]))), ?line F1 = from_term([{a,[[1],[2],[2,3]]},{b,[]},{c,[[4]]}]), ?line {'EXIT', {badarg, _}} = (catch family_intersection(F1)), ?line F2 = from_term([{b,[[1],[2],[2,3]]},{a,[]},{c,[[4]]}]), ?line {'EXIT', {badarg, _}} = (catch family_intersection(F2)), ?line F3 = from_term([{a,[[1,2,3],[2],[2,3]]},{c,[[4,5,6],[5,6,7]]}]), ?line eval(family_intersection(F3), family([{a,[2]},{c,[5,6]}])), ok. family_intersection_2(suite) -> []; family_intersection_2(doc) -> [""]; family_intersection_2(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = family([]), ?line F1 = from_term([{a,[1,2]},{b,[4,5]},{c,[7,8]},{d,[10,11]}]), ?line F2 = from_term([{c,[6,7]},{d,[9,10,11]},{q,[1]}]), ?line F3 = from_term([{a,[1,2]},{b,[4,5]},{c,[6,7,8]},{d,[9,10,11]}, {q,[1]}]), ?line eval(family_intersection(E, E), E), ?line eval(family_intersection(EF, EF), EF), ?line eval(family_intersection(F1, F2), from_term([{c,[7]},{d,[10,11]}])), ?line eval(family_intersection(F1, F3), F1), ?line eval(family_intersection(F2, F3), F2), ?line eval(family_intersection(EF, from_term([{e,[f,g]}])), EF), ?line eval(family_intersection(E, from_term([{e,[f,g]}])), EF), ?line eval(family_intersection(from_term([{e,[f,g]}]), EF), EF), ?line eval(family_intersection(from_term([{e,[f,g]}]), E), EF), ?line {'EXIT', {type_mismatch, _}} = (catch family_intersection(from_term([{a,[b,c]}]), from_term([{e,[{f}]}]))), ?line F11 = family([{a,[1,2,3]},{b,[0,2,4]},{c,[0,3,6,9]}]), ?line eval(union_of_family(F11), set([0,1,2,3,4,6,9])), ?line F12 = from_term([{a,[1,2,3,4]},{b,[0,2,4]},{c,[2,3,4,5]}]), ?line eval(intersection_of_family(F12), set([2,4])), ok. family_union_1(suite) -> []; family_union_1(doc) -> [""]; family_union_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = family([]), ?line ES = from_term([], [{atom,[[atom]]}]), ?line eval(family_union(E), E), ?line eval(family_union(ES), EF), ?line {'EXIT', {badarg, _}} = (catch family_union(set([]))), ?line {'EXIT', {badarg, _}} = (catch family_union(from_term([{a,[1,2]}]))), ?line eval(family_union(from_term([{a,[[1],[2],[2,3]]},{b,[]},{c,[[4]]}])), family([{a,[1,2,3]},{b,[]},{c,[4]}])), ok. family_union_2(suite) -> []; family_union_2(doc) -> [""]; family_union_2(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = family([]), ?line F1 = from_term([{a,[1,2]},{b,[4,5]},{c,[7,8]},{d,[10,11]}]), ?line F2 = from_term([{c,[6,7]},{d,[9,10,11]},{q,[1]}]), ?line F3 = from_term([{a,[1,2]},{b,[4,5]},{c,[6,7,8]},{d,[9,10,11]}, {q,[1]}]), ?line eval(family_union(E, E), E), ?line eval(family_union(F1, E), F1), ?line eval(family_union(E, F2), F2), ?line eval(family_union(F1, F2), F3), ?line eval(family_union(F2, F1), F3), ?line eval(family_union(E, from_term([{e,[f,g]}])), from_term([{e,[f,g]}])), ?line eval(family_union(EF, from_term([{e,[f,g]}])), from_term([{e,[f,g]}])), ?line eval(family_union(from_term([{e,[f,g]}]), E), from_term([{e,[f,g]}])), ?line {'EXIT', {badarg, _}} = (catch family_union(set([]),set([]))), ?line {'EXIT', {type_mismatch, _}} = (catch family_union(from_term([{a,[b,c]}]), from_term([{e,[{f}]}]))), ok. partition_family(suite) -> []; partition_family(doc) -> [""]; partition_family(Conf) when list(Conf) -> ?line E = empty_set(), %% set of ordered sets ?line ER = relation([]), ?line EF = from_term([], [{atom,[{atom,atom}]}]), ?line eval(partition_family(1, E), E), ?line eval(partition_family(2, E), E), ?line eval(partition_family({sofs,union}, E), E), ?line eval(partition_family(1, ER), EF), ?line eval(partition_family(2, ER), EF), ?line {'EXIT', {badarg, _}} = (catch partition_family(1, set([]))), ?line {'EXIT', {badarg, _}} = (catch partition_family(2, set([]))), ?line {'EXIT', {function_clause, _}} = (catch partition_family(fun({_A,B}) -> {B} end, from_term([{1}]))), ?line eval(partition_family(1, relation([{1,a},{1,b},{2,c},{2,d}])), from_term([{1,[{1,a},{1,b}]},{2,[{2,c},{2,d}]}])), ?line eval(partition_family(1, relation([{1,a},{2,b}])), from_term([{1,[{1,a}]},{2,[{2,b}]}])), ?line eval(partition_family(2, relation([{1,a},{1,b},{2,a},{2,b},{3,c}])), from_term([{a,[{1,a},{2,a}]},{b,[{1,b},{2,b}]},{c,[{3,c}]}])), ?line eval(partition_family(2, relation([{1,a}])), from_term([{a,[{1,a}]}])), ?line eval(partition_family(2, relation([{1,a},{2,a},{3,a}])), from_term([{a,[{1,a},{2,a},{3,a}]}])), ?line eval(partition_family(2, relation([{1,a},{2,b}])), from_term([{a,[{1,a}]},{b,[{2,b}]}])), ?line F13 = from_term([{a,b,c},{a,b,d},{b,b,c},{a,c,c},{a,c,d},{b,c,c}]), ?line eval(partition_family(2, F13), from_term([{b,[{a,b,c},{a,b,d},{b,b,c}]}, {c,[{a,c,c},{a,c,d},{b,c,c}]}])), Fun1 = {external, fun({A,_B}) -> {A} end}, ?line eval(partition_family(Fun1, relation([{a,1},{a,2},{b,3}])), from_term([{{a},[{a,1},{a,2}]},{{b},[{b,3}]}])), Fun2 = fun(S) -> {A,_B} = to_external(S), from_term({A}) end, ?line eval(partition_family(Fun2, relation([{a,1},{a,2},{b,3}])), from_term([{{a},[{a,1},{a,2}]},{{b},[{b,3}]}])), ?line {'EXIT', {badarg, _}} = (catch partition_family({external, fun({A,_}) -> {A,0} end}, from_term([{1,a}]))), ?line [{{atom,atom},[{atom,atom,atom,atom}]}] = type(partition_family({external, fun({A,_B,C,_D}) -> {C,A} end}, relation([],4))), Fun3 = fun(S) -> from_term({to_external(S),0}, {type(S),atom}) end, ?line eval(partition_family(Fun3, E), E), ?line eval(partition_family(Fun3, set([a,b])), from_term([{{a,0},[a]}, {{b,0},[b]}])), ?line eval(partition_family(Fun3, relation([{a,1},{b,2}])), from_term([{{{a,1},0},[{a,1}]},{{{b,2},0},[{b,2}]}])), ?line eval(partition_family(Fun3, from_term([[a],[b]])), from_term([{{[a],0},[[a]]}, {{[b],0},[[b]]}])), ?line partition_family({external, fun(X) -> X end}, E), F = 0.0, I = round(F), ?line FR = relation([{I,a},{F,b}]), if F == I -> % term ordering ?line true = (1 =:= no_elements(partition_family(1, FR))); true -> ?line eval(partition_family(1, FR), from_term([{I,[{I,a}]},{F,[{F,b}]}])) end, %% set of sets ?line {'EXIT', {badarg, _}} = (catch partition_family({external, fun(X) -> X end}, from_term([], [[atom]]))), ?line {'EXIT', {badarg, _}} = (catch partition_family({external, fun(X) -> X end}, from_term([[a]]))), ?line eval(partition_family({sofs,union}, from_term([[[1],[1,2]], [[1,2]]])), from_term([{[1,2], [[[1],[1,2]],[[1,2]]]}])), ?line eval(partition_family(fun(X) -> X end, from_term([[1],[1,2],[1,2,3]])), from_term([{[1],[[1]]},{[1,2],[[1,2]]},{[1,2,3],[[1,2,3]]}])), ?line eval(partition_family(fun(_) -> from_term([a]) end, from_term([], [[atom]])), E), Fun10 = fun(S) -> %% Cheating a lot... case to_external(S) of [1] -> from_term({1,1}); _ -> S end end, ?line eval(partition_family(Fun10, from_term([[1]])), from_term([{{1,1},[[1]]}])), ?line eval(partition_family(fun(_) -> from_term({a}) end, from_term([[a]])), from_term([{{a},[[a]]}])), ?line {'EXIT', {badarg, _}} = (catch partition_family(fun(_) -> {a} end, from_term([[a]]))), ok. %% Not meant to be efficient... local_adjoin(S, C) -> X = to_external(C), T = type(C), F = fun(Y) -> from_term({to_external(Y),X}, {type(Y),T}) end, projection(F, S). eval(R, E) when R == E -> R; eval(R, E) -> io:format("expected ~p~n got ~p~n", [E, R]), exit({R,E}).
null
https://raw.githubusercontent.com/simplegeo/erlang/15eda8de27ba73d176c7eeb3a70a64167f50e2c4/lib/stdlib/test/sofs_SUITE.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% -define(debug, true). [{1,a,b},{2,b}] == lists:keysort(1,[{2,b},{1,a,b}]) would go wrong: projection(1,from_term([{2,b},{1,a,b}])), from_external too... and is_type... set/1 set/2 unordered ordered relation/1 relation/2 a_function/1 term ordering a_function/2 family/1 term ordering family/2 set of ordered sets No check here: {} is not an ordered set term ordering set of sets Cheating a lot... set of ordered sets No check here: set of sets Cheating a lot... set of ordered sets set of sets Cheating a lot... set of ordered sets set of sets Cheating a lot... term ordering term ordering unordered ordered term ordering term ordering term ordering term ordering OTP-4516 term ordering set of ordered sets set of sets Cheating a lot... term ordering find "relational" part of relation: the "functional" part: The function external:foo/1 is undefined. internal external ordered set element set of ordered sets term ordering set of sets Cheating a lot... Not meant to be efficient...
Copyright Ericsson AB 2001 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(sofs_SUITE). -ifdef(debug). -define(format(S, A), io:format(S, A)). -define(line, put(line, ?LINE), ). -define(config(X,Y), foo). -define(t, test_server). -else. -include("test_server.hrl"). -define(format(S, A), ok). -endif. -export([all/1]). -export([sofs/1, from_term_1/1, set_1/1, from_sets_1/1, relation_1/1, a_function_1/1, family_1/1, projection/1, relation_to_family_1/1, domain_1/1, range_1/1, image/1, inverse_image/1, inverse_1/1, converse_1/1, no_elements_1/1, substitution/1, restriction/1, drestriction/1, strict_relation_1/1, extension/1, weak_relation_1/1, to_sets_1/1, specification/1, union_1/1, intersection_1/1, difference/1, symdiff/1, symmetric_partition/1, is_sofs_set_1/1, is_set_1/1, is_equal/1, is_subset/1, is_a_function_1/1, is_disjoint/1, join/1, canonical/1, composite_1/1, relative_product_1/1, relative_product_2/1, product_1/1, partition_1/1, partition_3/1, multiple_relative_product/1, digraph/1, constant_function/1, misc/1]). -export([sofs_family/1, family_specification/1, family_domain_1/1, family_range_1/1, family_to_relation_1/1, union_of_family_1/1, intersection_of_family_1/1, family_projection/1, family_difference/1, family_intersection_1/1, family_union_1/1, family_intersection_2/1, family_union_2/1, partition_family/1]). -import(sofs, [a_function/1, a_function/2, constant_function/2, canonical_relation/1, composite/2, converse/1, extension/3, from_term/1, from_term/2, difference/2, domain/1, empty_set/0, family_difference/2, family_intersection/1, family_intersection/2, family_union/1, family_union/2, family/1, family/2, family_specification/2, family_domain/1, family_range/1, family_field/1, family_projection/2, family_to_relation/1, union_of_family/1, field/1, from_external/2, image/2, intersection/1, intersection/2, intersection_of_family/1, inverse/1, inverse_image/2, is_disjoint/2, is_empty_set/1, is_equal/2, is_a_function/1, is_set/1, is_sofs_set/1, is_subset/2, join/4, from_sets/1, multiple_relative_product/2, no_elements/1, partition/1, partition/2, partition/3, partition_family/2, product/1, product/2, projection/2, range/1, relation/1, relation/2, relation_to_family/1, relative_product/1, relative_product/2, relative_product1/2, strict_relation/1, weak_relation/1, restriction/2, restriction/3, drestriction/2, drestriction/3, to_sets/1, is_type/1, set/1, set/2, specification/2, substitution/2, symdiff/2, symmetric_partition/2, to_external/1, type/1, union/1, union/2, family_to_digraph/1, family_to_digraph/2, digraph_to_family/1, digraph_to_family/2]). -export([init_per_testcase/2, fin_per_testcase/2]). -compile({inline,[{eval,2}]}). all(suite) -> [sofs, sofs_family]. init_per_testcase(_Case, Config) -> Dog=?t:timetrap(?t:minutes(2)), [{watchdog, Dog}|Config]. fin_per_testcase(_Case, Config) -> Dog=?config(watchdog, Config), test_server:timetrap_cancel(Dog), ok. [ { 2,b},{1,a , b } ] = = lists : sort([{2,b},{1,a , b } ] ) sofs(suite) -> [from_term_1, set_1, from_sets_1, relation_1, a_function_1, family_1, relation_to_family_1, domain_1, range_1, image, inverse_image, inverse_1, converse_1, no_elements_1, substitution, restriction, drestriction, projection, strict_relation_1, extension, weak_relation_1, to_sets_1, specification, union_1, intersection_1, difference, symdiff, symmetric_partition, is_sofs_set_1, is_set_1, is_equal, is_subset, is_a_function_1, is_disjoint, join, canonical, composite_1, relative_product_1, relative_product_2, product_1, partition_1, partition_3, multiple_relative_product, digraph, constant_function, misc]. from_term_1(suite) -> []; from_term_1(doc) -> [""]; from_term_1(Conf) when list(Conf) -> ?line {'EXIT', {badarg, _}} = (catch from_term([], {atom,'_',atom})), ?line {'EXIT', {badarg, _}} = (catch from_term([], [])), ?line {'EXIT', {badarg, _}} = (catch from_term([], [atom,atom])), ?line [] = to_external(from_term([])), ?line eval(from_term([]), empty_set()), ?line [] = to_external(from_term([], ['_'])), ?line eval(from_term([], ['_']), empty_set()), ?line [[]] = to_external(from_term([[]])), ?line [[['_']]] = type(from_term([[],[[]]])), ?line [[],[[]]] = to_external(from_term([[],[[]]])), ?line [[['_']]] = type(from_term([[],[[]]])), ?line eval(from_term([a],['_']), set([a])), ?line [[],[a]] = to_external(from_term([[],[a]])), ?line [[],[{a}]] = to_external(from_term([[{a}],[]])), ?line [{[],[{a,b,[d]}]},{[{a,b}],[]}] = to_external(from_term([{[],[{a,b,[d]}]},{[{a,b}],[]}])), ?line [{[a,b],[c,d]}] = to_external(from_term([{[a,b],[c,d]}])), ?line [{{a,b},[a,b],{{a},{b}}}] = to_external(from_term([{{a,b},[a,b],{{a},{b}}}])), ?line [{{a,{[a,b]},a}},{{z,{[y,z]},z}}] = to_external(from_term([{{a,{[a,b,a]},a}},{{z,{[y,y,z]},z}}])), ?line {'EXIT', {badarg, _}} = (catch from_term([{m1,[{m1,f1,1},{m1,f2,2}]},{m2,[]},{m3,[a]}])), ?line MS1 = [{m1,[{m1,f1,1},{m1,f2,2}]},{m2,[]},{m3,[{m3,f3,3}]}], ?line eval(to_external(from_term(MS1)), MS1), ?line eval(to_external(from_term(a)), a), ?line eval(to_external(from_term({a})), {a}), ?line eval(to_external(from_term([[a],[{b,c}]],[[atomic]])), [[a],[{b,c}]]), ?line eval(type(from_term([[a],[{b,c}]],[[atomic]])), [[atomic]]), ?line {'EXIT', {badarg, _}} = (catch from_term([[],[],a])), ?line {'EXIT', {badarg, _}} = (catch from_term([{[a,b],[c,{d}]}])), ?line {'EXIT', {badarg, _}} = (catch from_term([[],[a],[{a}]])), ?line {'EXIT', {badarg, _}} = (catch from_term([a,{a,b}])), ?line {'EXIT', {badarg, _}} = (catch from_term([[a],[{b,c}]],[['_']])), ?line {'EXIT', {badarg, _}} = (catch from_term([a | {a,b}])), ?line {'EXIT', {badarg, _}} = (catch from_term([{{a},b,c},{d,e,f}],[{{atom},atom,atom}])), ?line {'EXIT', {badarg, _}} = (catch from_term([{a,{b,c}} | tail], [{atom,{atom,atom}}])), ?line {'EXIT', {badarg, _}} = (catch from_term({})), ?line {'EXIT', {badarg, _}} = (catch from_term([{}])), ?line [{foo,bar},[b,a]] = to_external(from_term([[b,a],{foo,bar},[b,a]], [atom])), ?line [{[atom],{atom,atom}}] = type(from_term([{[], {a,b}},{[a,b],{e,f}}])), ?line [{[atom],{atom,atom}}] = type(from_term([{[], {a,b}},{[a,b],{e,f}}], [{[atom],{atom,atom}}])), ?line [[atom]] = type(from_term([[a],[{b,c}]],[[atom]])), ?line {atom, atom} = type(from_term({a,b}, {atom, atom})), ?line atom = type(from_term(a, atom)), ?line {'EXIT', {badarg, _}} = (catch from_term({a,b},{atom})), ?line [{{a},b,c},{{d},e,f}] = to_external(from_term([{{a},b,c},{{a},b,c},{{d},e,f}], [{{atom},atom,atom}])), ?line e = to_external(from_external(e, atom)), ?line {e} = to_external(from_external({e}, {atom})), ?line [e] = to_external(from_external([e], [atom])), ?line true = is_type(['_']), ?line false = is_type('_'), ?line true = is_type([['_']]), ?line false = is_type({atom,[],atom}), ?line false = is_type({atom,'_',atom}), ?line true = is_type({atom,atomic,atom}), ?line true = is_type({atom,atom}), ?line true = is_type(atom), ?line true = is_type([atom]), ?line true = is_type(type), ok. set_1(suite) -> []; set_1(doc) -> [""]; set_1(Conf) when list(Conf) -> ?line {'EXIT', {badarg, _}} = (catch set(a)), ?line {'EXIT', {badarg, _}} = (catch set({a})), ?line eval(set([]), from_term([],[atom])), ?line eval(set([a,b,c]), from_term([a,b,c])), ?line eval(set([a,b,a,a,b]), from_term([a,b])), ?line eval(set([a,b,c,a,d,d,c,1]), from_term([1,a,b,c,d])), ?line eval(set([a,b,d,a,c]), from_term([a,b,c,d])), ?line eval(set([f,e,d,c,d]), from_term([c,d,e,f])), ?line eval(set([h,f,d,g,g,d,c]), from_term([c,d,f,g,h])), ?line eval(set([h,e,d,k,l]), from_term([d,e,h,k,l])), ?line eval(set([h,e,c,k,d]), from_term([c,d,e,h,k])), ?line {'EXIT', {badarg, _}} = (catch set(a, [a])), ?line {'EXIT', {badarg, _}} = (catch set({a}, [a])), ?line {'EXIT', {badarg, _}} = (catch set([a], {a})), ?line {'EXIT', {badarg, _}} = (catch set([a], a)), ?line {'EXIT', {badarg, _}} = (catch set([a], [a,b])), ?line {'EXIT', {badarg, _}} = (catch set([a | b],[foo])), ?line {'EXIT', {badarg, _}} = (catch set([a | b],['_'])), ?line {'EXIT', {badarg, _}} = (catch set([a | b],[[atom]])), ?line {'EXIT', {badarg, _}} = (catch set([{}],[{}])), ?line eval(set([a],['_']), from_term([a],['_'])), ?line eval(set([], ['_']), empty_set()), ?line eval(set([a,b,a,b],[foo]), from_term([a,b],[foo])), ok. from_sets_1(suite) -> []; from_sets_1(doc) -> [""]; from_sets_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line eval(from_sets([]), E), ?line {'EXIT', {type_mismatch, _}} = (catch from_sets([from_term([{a,b}]), E, from_term([{a,b,c}])])), ?line eval(from_sets([from_term([{a,b}]), E]), from_term([[],[{a,b}]])), ?line eval(from_sets([from_term({a,b},{atom,atom}), from_term({b,c},{atom,atom})]), relation([{a,b}, {b,c}])), ?line {'EXIT', {type_mismatch, _}} = (catch from_sets([from_term({a,b},{atom,atom}), from_term({a,b,c},{atom,atom,atom})])), ?line {'EXIT', {badarg, _}} = (catch from_sets(foo)), ?line eval(from_sets([E]), from_term([[]])), ?line eval(from_sets([E,E]), from_term([[]])), ?line eval(from_sets([E,set([a])]), from_term([[],[a]])), ?line {'EXIT', {badarg, _}} = (catch from_sets([E,{a}])), ?line {'EXIT', {type_mismatch, _}} = (catch from_sets([E,from_term({a}),E])), ?line {'EXIT', {type_mismatch, _}} = (catch from_sets([from_term({a}),E])), ?line O = {from_term(a,atom), from_term({b}, {atom}), set([c,d])}, ?line eval(from_sets(O), from_term({a,{b},[c,d]}, {atom,{atom},[atom]})), ?line {'EXIT', {badarg, _}} = (catch from_sets([a,b])), ?line {'EXIT', {badarg, _}} = (catch from_sets({a,b})), ?line eval(from_sets({from_term({a}),E}), from_term({{a},[]})), ok. relation_1(suite) -> []; relation_1(doc) -> [""]; relation_1(Conf) when list(Conf) -> ?line eval(relation([]), from_term([], [{atom,atom}])), ?line eval(from_term([{a}]), relation([{a}])), ?line {'EXIT', {badarg, _}} = (catch relation(a)), ?line {'EXIT', {badarg, _}} = (catch relation([{a} | a])), ?line {'EXIT', {badarg, _}} = (catch relation([{}])), ?line {'EXIT', {badarg, _}} = (catch relation([],0)), ?line {'EXIT', {badarg, _}} = (catch relation([{a}],a)), ?line eval(relation([{a},{b}], 1), from_term([{a},{b}])), ?line eval(relation([{1,a},{2,b},{1,a}], [{x,y}]), from_term([{1,a},{2,b}], [{x,y}])), ?line eval(relation([{[1,2],a},{[2,1],b},{[2,1],a}], [{[x],y}]), from_term([{[1,2],a},{[1,2],b}], [{[x],y}])), ?line {'EXIT', {badarg, _}} = (catch relation([{1,a},{2,b}], [{[x],y}])), ?line {'EXIT', {badarg, _}} = (catch relation([{1,a},{1,a,b}], [{x,y}])), ?line {'EXIT', {badarg, _}} = (catch relation([{a}], 2)), ?line {'EXIT', {badarg, _}} = (catch relation([{a},{b},{c,d}], 1)), ?line eval(relation([{{a},[{foo,bar}]}], ['_']), from_term([{{a},[{foo,bar}]}], ['_'])), ?line eval(relation([], ['_']), from_term([], ['_'])), ?line {'EXIT', {badarg, _}} = (catch relation([[a]],['_'])), ?line eval(relation([{[a,b,a]}], [{[atom]}]), from_term([{[a,b,a]}])), ?line eval(relation([{[a,b,a],[[d,e,d]]}], [{[atom],[[atom]]}]), from_term([{[a,b,a],[[d,e,d]]}])), ?line eval(relation([{[a,b,a],[[d,e,d]]}], [{atom,[[atom]]}]), from_term([{[a,b,a],[[d,e,d]]}], [{atom,[[atom]]}])), ok. a_function_1(suite) -> []; a_function_1(doc) -> [""]; a_function_1(Conf) when list(Conf) -> ?line eval(a_function([]), from_term([], [{atom,atom}])), ?line eval(a_function([{a,b},{a,b},{b,c}]), from_term([{a,b},{b,c}])), ?line {'EXIT', {badarg, _}} = (catch a_function([{a}])), ?line {'EXIT', {badarg, _}} = (catch a_function([{a},{b},{c,d}])), ?line {'EXIT', {badarg, _}} = (catch a_function(a)), ?line {'EXIT', {badarg, _}} = (catch a_function([{a,b} | a])), ?line {'EXIT', {bad_function, _}} = (catch a_function([{a,b},{b,c},{a,c}])), F = 0.0, I = round(F), if ?line {'EXIT', {bad_function, _}} = (catch a_function([{I,a},{F,b}])), ?line {'EXIT', {bad_function, _}} = (catch a_function([{[I],a},{[F],b}],[{[a],b}])); true -> ?line 2 = no_elements(a_function([{I,a},{F,b}])), ?line 2 = no_elements(a_function([{[I],a},{[F],b}],[{[a],b}])) end, FT = [{atom,atom}], ?line eval(a_function([], FT), from_term([], FT)), ?line eval(a_function([{a,b},{b,c},{b,c}], FT), from_term([{a,b},{b,c}], FT)), ?line {'EXIT', {badarg, _}} = (catch a_function([{a,b}], [{a}])), ?line {'EXIT', {badarg, _}} = (catch a_function([{a,b}], [{a,[b,c]}])), ?line {'EXIT', {badarg, _}} = (catch a_function([{a}], FT)), ?line {'EXIT', {badarg, _}} = (catch a_function([{a},{b},{c,d}], FT)), ?line {'EXIT', {badarg, _}} = (catch a_function(a, FT)), ?line {'EXIT', {badarg, _}} = (catch a_function([{a,b} | a], FT)), ?line eval(a_function([{{a},[{foo,bar}]}], ['_']), from_term([{{a},[{foo,bar}]}], ['_'])), ?line eval(a_function([], ['_']), from_term([], ['_'])), ?line {'EXIT', {badarg, _}} = (catch a_function([[a]],['_'])), ?line {'EXIT', {bad_function, _}} = (catch a_function([{a,b},{b,c},{a,c}], FT)), ?line eval(a_function([{a,[a]},{a,[a,a]}], [{atom,[atom]}]), from_term([{a,[a]}])), ?line eval(a_function([{[b,a],c},{[a,b],c}], [{[atom],atom}]), from_term([{[a,b],c}])), ok. family_1(suite) -> []; family_1(doc) -> [""]; family_1(Conf) when list(Conf) -> ?line eval(family([]), from_term([],[{atom,[atom]}])), ?line {'EXIT', {badarg, _}} = (catch family(a)), ?line {'EXIT', {badarg, _}} = (catch family([a])), ?line {'EXIT', {badarg, _}} = (catch family([{a,b}])), ?line {'EXIT', {badarg, _}} = (catch family([{a,[]} | a])), ?line {'EXIT', {badarg, _}} = (catch family([{a,[a|b]}])), ?line {'EXIT', {bad_function, _}} = (catch family([{a,[a]},{a,[]}])), ?line {'EXIT', {bad_function, _}} = (catch family([{a,[]},{b,[]},{a,[a]}])), F = 0.0, I = round(F), if ?line {'EXIT', {bad_function, _}} = (catch family([{I,[a]},{F,[b]}])), ?line true = (1 =:= no_elements(family([{a,[I]},{a,[F]}]))); true -> ?line {'EXIT', {bad_function, _}} = (catch family([{a,[I]},{a,[F]}])) end, ?line eval(family([{a,[]},{b,[b]},{a,[]}]), from_term([{a,[]},{b,[b]}])), ?line eval(to_external(family([{b,[{hej,san},tjo]},{a,[]}])), [{a,[]},{b,[tjo,{hej,san}]}]), ?line eval(family([{a,[a]},{a,[a,a]}]), family([{a,[a]}])), FT = [{a,[a]}], ?line eval(family([], FT), from_term([],FT)), ?line {'EXIT', {badarg, _}} = (catch family(a,FT)), ?line {'EXIT', {badarg, _}} = (catch family([a],FT)), ?line {'EXIT', {badarg, _}} = (catch family([{a,b}],FT)), ?line {'EXIT', {badarg, _}} = (catch family([{a,[]} | a],FT)), ?line {'EXIT', {badarg, _}} = (catch family([{a,[a|b]}], FT)), ?line {'EXIT', {bad_function, _}} = (catch family([{a,[a]},{a,[]}], FT)), ?line {'EXIT', {bad_function, _}} = (catch family([{a,[]},{b,[]},{a,[a]}], FT)), ?line eval(family([{a,[]},{b,[b,b]},{a,[]}], FT), from_term([{a,[]},{b,[b]}], FT)), ?line eval(to_external(family([{b,[{hej,san},tjo]},{a,[]}], FT)), [{a,[]},{b,[tjo,{hej,san}]}]), ?line eval(family([{{a},[{foo,bar}]}], ['_']), from_term([{{a},[{foo,bar}]}], ['_'])), ?line eval(family([], ['_']), from_term([], ['_'])), ?line {'EXIT', {badarg, _}} = (catch family([[a]],['_'])), ?line {'EXIT', {badarg, _}} = (catch family([{a,b}],['_'])), ?line {'EXIT', {badarg, _}} = (catch family([{a,[foo]}], [{atom,atom}])), ?line eval(family([{{a},[{foo,bar}]}], [{{dt},[{r1,t2}]}]), from_term([{{a},[{foo,bar}]}], [{{dt},[{r1,t2}]}])), ?line eval(family([{a,[a]},{a,[a,a]}],[{atom,[atom]}]), family([{a,[a]}])), ?line eval(family([{[a,b],[a]},{[b,a],[a,a]}],[{[atom],[atom]}]), from_term([{[a,b],[a]},{[b,a],[a,a]}])), ok. projection(suite) -> []; projection(doc) -> [""]; projection(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line S1 = relation([{a,1},{b,2},{b,22},{c,0}]), ?line S2 = relation([{a,1},{a,2},{a,3},{b,4},{b,5},{b,6}]), ?line eval(projection(1, E), E), ?line eval(projection(1, ER), set([])), ?line eval(projection(1, relation([{a,1}])), set([a])), ?line eval(projection(1, S1), set([a,b,c])), ?line eval(projection(1, S2), set([a,b])), ?line eval(projection(2, S1), set([0,1,2,22])), ?line eval(projection(2, relation([{1,a},{2,a},{3,b}])), set([a,b])), ?line eval(projection(1, relation([{a},{b},{c}])), set([a,b,c])), Fun1 = {external, fun({A,B,C}) -> {A,{B,C}} end}, ?line eval(projection(Fun1, E), E), ?line eval(projection(3, projection(Fun1, empty_set())), E), ?line E2 = relation([], 3), ?line eval(projection(Fun1, E2), from_term([], [{atom,{atom,atom}}])), Fun2 = {external, fun({A,_B}) -> {A} end}, ?line eval(projection(Fun2, ER), from_term([], [{atom}])), ?line eval(projection(Fun2, relation([{a,1}])), relation([{a}])), ?line eval(projection(Fun2, relation([{a,1},{b,3},{a,2}])), relation([{a},{b}])), Fun3 = {external, fun({A,_B,C}) -> {C,{A},C} end}, ?line eval(projection(Fun3, relation([{a,1,x},{b,3,y},{a,2,z}])), from_term([{x,{a},x},{y,{b},y},{z,{a},z}])), Fun4 = {external, fun(A={B,_C,_D}) -> {B, A} end}, ?line eval(projection(Fun4, relation([{a,1,x},{b,3,y},{a,2,z}])), from_term([{a,{a,1,x}},{b,{b,3,y}},{a,{a,2,z}}])), ?line eval(projection({external, fun({A,B,_C,D}) -> {A,B,A,D} end}, relation([{1,1,1,2}, {1,1,3,1}])), relation([{1,1,1,1}, {1,1,1,2}])), ?line {'EXIT', {badarg, _}} = (catch projection(1, set([]))), ?line {'EXIT', {function_clause, _}} = (catch projection({external, fun({A}) -> A end}, S1)), ?line {'EXIT', {badarg, _}} = (catch projection({external, fun({A,_}) -> {A,0} end}, from_term([{1,a}]))), ?line {'EXIT', {badarg, _}} = (catch projection({external, fun(_) -> {} end}, ER)), ?line {'EXIT', {badarg, _}} = (catch projection({external, fun(_) -> {{}} end}, ER)), ?line eval(projection({external, fun({T,_}) -> T end}, relation([{{},a},{{},b}])), set([{}])), ?line eval(projection({external, fun({T}) -> T end}, relation([{{}}])), set([{}])), ?line eval(projection({external, fun(A) -> {A} end}, relation([{1,a},{2,b}])), from_term([{{1,a}},{{2,b}}])), ?line eval(projection({external, fun({A,B}) -> {B,A} end}, relation([{1,a},{2,b}])), relation([{a,1},{b,2}])), ?line eval(projection({external, fun(X=Y=A) -> {X,Y,A} end}, set([a,b,c])), relation([{a,a,a},{b,b,b},{c,c,c}])), ?line eval(projection({external, fun({A,{_},B}) -> {A,B} end}, from_term([{a,{a},b},{a,{b},c}])), relation([{a,b},{a,c}])), ?line eval(projection({external, fun({A,_,B}) -> {A,B} end}, relation([{a,{},b},{a,{},c}])), relation([{a,b},{a,c}])), Fun5 = fun(S) -> from_term({to_external(S),0}, {type(S),atom}) end, ?line eval(projection(Fun5, E), E), ?line eval(projection(Fun5, set([a,b])), from_term([{a,0},{b,0}])), ?line eval(projection(Fun5, relation([{a,1},{b,2}])), from_term([{{a,1},0},{{b,2},0}])), ?line eval(projection(Fun5, from_term([[a],[b]])), from_term([{[a],0},{[b],0}])), F = 0.0, I = round(F), ?line FR = relation([{I},{F}]), if true = (no_elements(projection(1, FR)) =:= 1); true -> eval(projection(1, FR), set([I,F])) end, ?line {'EXIT', {badarg, _}} = (catch projection({external, fun(X) -> X end}, from_term([], [[atom]]))), ?line {'EXIT', {badarg, _}} = (catch projection({external, fun(X) -> X end}, from_term([[a]]))), ?line eval(projection({sofs,union}, from_term([[[1,2],[2,3]], [[a,b],[b,c]]])), from_term([[1,2,3], [a,b,c]])), ?line eval(projection(fun(_) -> from_term([a]) end, from_term([[b]], [[a]])), from_term([[a]])), ?line eval(projection(fun(_) -> from_term([a]) end, from_term([[1,2],[3,4]])), from_term([[a]])), Fun10 = fun(S) -> case to_external(S) of [1] -> from_term({1,1}); _ -> S end end, ?line eval(projection(Fun10, from_term([[1]])), from_term([{1,1}])), ?line eval(projection(fun(_) -> from_term({a}) end, from_term([[a]])), from_term([{a}])), ?line {'EXIT', {badarg, _}} = (catch projection(fun(_) -> {a} end, from_term([[a]]))), ok. substitution(suite) -> []; substitution(doc) -> [""]; substitution(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line S1 = relation([{a,1},{b,2},{b,22},{c,0}]), ?line S2 = relation([{a,1},{a,2},{a,3},{b,4},{b,5},{b,6}]), ?line eval(substitution(1, E), E), Fun0 = {external, fun({A,B,C}) -> {A,{B,C}} end}, ?line eval(substitution(3, substitution(Fun0, empty_set())), E), ?line eval(substitution(1, ER), from_term([],[{{atom,atom},atom}])), ?line eval(substitution(1, relation([{a,1}])), from_term([{{a,1},a}])), ?line eval(substitution(1, S1), from_term([{{a,1},a},{{b,2},b},{{b,22},b},{{c,0},c}])), ?line eval(substitution(1, S2), from_term([{{a,1},a},{{a,2},a},{{a,3},a},{{b,4},b}, {{b,5},b},{{b,6},b}])), ?line eval(substitution(2, S1), from_term([{{a,1},1},{{b,2},2},{{b,22},22},{{c,0},0}])), Fun1 = fun({A,_B}) -> {A} end, XFun1 = {external, Fun1}, ?line eval(substitution(XFun1, E), E), ?line eval(substitution(Fun1, E), E), ?line eval(substitution(XFun1, ER), from_term([], [{{atom,atom},{atom}}])), ?line eval(substitution(XFun1, relation([{a,1}])), from_term([{{a,1},{a}}])), ?line eval(substitution(XFun1, relation([{a,1},{b,3},{a,2}])), from_term([{{a,1},{a}},{{a,2},{a}},{{b,3},{b}}])), ?line eval(substitution({external, fun({A,_B,C}) -> {C,A,C} end}, relation([{a,1,x},{b,3,y},{a,2,z}])), from_term([{{a,1,x},{x,a,x}},{{a,2,z},{z,a,z}}, {{b,3,y},{y,b,y}}])), Fun2 = fun(S) -> {A,_B} = to_external(S), from_term({A}) end, ?line eval(substitution(Fun2, ER), E), ?line eval(substitution(Fun2, relation([{a,1}])), from_term([{{a,1},{a}}])), Fun3 = fun(S) -> from_term({to_external(S),0}, {type(S),atom}) end, ?line eval(substitution(Fun3, E), E), ?line eval(substitution(Fun3, set([a,b])), from_term([{a,{a,0}},{b,{b,0}}])), ?line eval(substitution(Fun3, relation([{a,1},{b,2}])), from_term([{{a,1},{{a,1},0}},{{b,2},{{b,2},0}}])), ?line eval(substitution(Fun3, from_term([[a],[b]])), from_term([{[a],{[a],0}},{[b],{[b],0}}])), ?line eval(substitution(fun(_) -> E end, from_term([[a],[b]])), from_term([{[a],[]},{[b],[]}])), ?line {'EXIT', {badarg, _}} = (catch substitution(1, set([]))), ?line eval(substitution(1, ER), from_term([], [{{atom,atom},atom}])), ?line {'EXIT', {function_clause, _}} = (catch substitution({external, fun({A,_}) -> A end}, set([]))), ?line {'EXIT', {badarg, _}} = (catch substitution({external, fun({A,_}) -> {A,0} end}, from_term([{1,a}]))), ?line {'EXIT', {badarg, _}} = (catch substitution({external, fun(X) -> X end}, from_term([], [[atom]]))), ?line {'EXIT', {badarg, _}} = (catch substitution({external, fun(X) -> X end}, from_term([[a]]))), ?line eval(substitution(fun(X) -> X end, from_term([], [[atom]])), E), ?line eval(substitution({sofs,union}, from_term([[[1,2],[2,3]], [[a,b],[b,c]]])), from_term([{[[1,2],[2,3]],[1,2,3]}, {[[a,b],[b,c]],[a,b,c]}])), ?line eval(substitution(fun(_) -> from_term([a]) end, from_term([[b]], [[a]])), from_term([{[b],[a]}], [{[a],[atom]}])), ?line eval(substitution(fun(_) -> from_term([a]) end, from_term([[1,2],[3,4]])), from_term([{[1,2],[a]},{[3,4],[a]}])), Fun10 = fun(S) -> case to_external(S) of [1] -> from_term({1,1}); _ -> S end end, ?line eval(substitution(Fun10, from_term([[1]])), from_term([{[1],{1,1}}])), ?line {'EXIT', {type_mismatch, _}} = (catch substitution(Fun10, from_term([[1],[2]]))), ?line {'EXIT', {type_mismatch, _}} = (catch substitution(Fun10, from_term([[1],[0]]))), ?line eval(substitution(fun(_) -> from_term({a}) end, from_term([[a]])), from_term([{[a],{a}}])), ?line {'EXIT', {badarg, _}} = (catch substitution(fun(_) -> {a} end, from_term([[a]]))), ok. restriction(suite) -> []; restriction(doc) -> [""]; restriction(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([], 2), ?line S1 = relation([{a,1},{b,2},{b,22},{c,0}]), ?line eval(restriction(S1, set([a,b])), relation([{a,1},{b,2},{b,22}])), ?line eval(restriction(2, S1, set([1,2])), relation([{a,1},{b,2}])), ?line eval(restriction(S1, set([a,b,c])), S1), ?line eval(restriction(1, S1, set([0,1,d,e])), ER), ?line eval(restriction(1, S1, E), ER), ?line eval(restriction({external, fun({_A,B,C}) -> {B,C} end}, relation([{a,aa,1},{b,bb,2},{c,cc,3}]), relation([{bb,2},{cc,3}])), relation([{b,bb,2},{c,cc,3}])), R1 = relation([],[{a,b}]), ?line eval(restriction(2, R1,sofs:set([],[b])), R1), Id = fun(X) -> X end, XId = {external, Id}, ?line eval(restriction(XId, relation([{a,b}]), E), ER), ?line eval(restriction(XId, E, relation([{b,d}])), E), Fun1 = fun(S) -> {_A,B,C} = to_external(S), from_term({B,C}) end, ?line eval(restriction(Fun1, relation([{a,aa,1},{b,bb,2},{c,cc,3}]), relation([{bb,2},{cc,3}])), relation([{b,bb,2},{c,cc,3}])), ?line eval(restriction({external, fun({_,{A},B}) -> {A,B} end}, from_term([{a,{aa},1},{b,{bb},2},{c,{cc},3}]), from_term([{bb,2},{cc,3}])), from_term([{b,{bb},2},{c,{cc},3}])), S5 = relation([{1,a},{2,b},{3,c}]), ?line eval(restriction(2, S5, set([b,c])), relation([{2,b},{3,c}])), S4 = relation([{a,1},{b,2},{b,27},{c,0}]), ?line eval(restriction(2, S4, E), ER), S6 = relation([{1,a},{2,c},{3,b}]), ?line eval(restriction(2, S6, set([d,e])), ER), ?line eval(restriction(2, relation([{1,d},{2,c},{3,b},{4,a},{5,e}]), set([c])), relation([{2,c}])), ?line eval(restriction(XId, relation([{1,a},{3,b},{4,c},{4,d}]), relation([{2,a},{2,c},{4,c}])), relation([{4,c}])), ?line eval(restriction(2, relation([{a,b}]), E), ER), ?line eval(restriction(2, E, relation([{b,d}])), E), ?line eval(restriction(2, relation([{b,d}]), E), ER), ?line eval(restriction(XId, E, set([a])), E), ?line eval(restriction(1, S1, E), ER), ?line {'EXIT', {badarg, _}} = (catch restriction(3, relation([{a,b}]), E)), ?line {'EXIT', {badarg, _}} = (catch restriction(3, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {badarg, _}} = (catch restriction(3, relation([{a,b}]), set([{b,d}]))), ?line {'EXIT', {type_mismatch, _}} = (catch restriction(2, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {type_mismatch, _}} = (catch restriction({external, fun({A,_B}) -> A end}, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {badarg, _}} = (catch restriction({external, fun({A,_}) -> {A,0} end}, from_term([{1,a}]), from_term([{1,0}]))), ?line eval(restriction(2, relation([{a,d},{b,e},{c,b},{d,c}]), set([b,d])), relation([{a,d},{c,b}])), ?line {'EXIT', {function_clause, _}} = (catch restriction({external, fun({A,_B}) -> A end}, set([]), E)), Fun3 = fun(S) -> from_term({to_external(S),0}, {type(S),atom}) end, ?line eval(restriction(Fun3, set([1,2]), from_term([{1,0}])), from_term([1])), ?line {'EXIT', {badarg, _}} = (catch restriction({external, fun(X) -> X end}, from_term([], [[atom]]), set([a]))), S2 = from_term([], [[atom]]), ?line eval(restriction(Id, S2, E), E), S3 = from_term([[a],[b]], [[atom]]), ?line eval(restriction(Id, S3, E), E), ?line eval(restriction(Id, from_term([], [[atom]]), set([a])), from_term([], [[atom]])), ?line eval(restriction({sofs,union}, from_term([[[a],[b]], [[b],[c]], [[], [a,b]], [[1],[2]]]), from_term([[a,b],[1,2,3],[b,c]])), from_term([[[],[a,b]], [[a],[b]],[[b],[c]]])), ?line eval(restriction(fun(_) -> from_term([a]) end, from_term([], [[atom]]), from_term([], [[a]])), from_term([], [[atom]])), ?line {'EXIT', {type_mismatch, _}} = (catch restriction(fun(_) -> from_term([a]) end, from_term([[1,2],[3,4]]), from_term([], [atom]))), Fun10 = fun(S) -> case to_external(S) of [1] -> from_term({1,1}); _ -> S end end, ?line {'EXIT', {type_mismatch, _}} = (catch restriction(Fun10, from_term([[1]]), from_term([], [[atom]]))), ?line {'EXIT', {type_mismatch, _}} = (catch restriction(fun(_) -> from_term({a}) end, from_term([[a]]), from_term([], [atom]))), ?line {'EXIT', {badarg, _}} = (catch restriction(fun(_) -> {a} end, from_term([[a]]), from_term([], [atom]))), ok. drestriction(suite) -> []; drestriction(doc) -> [""]; drestriction(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([], 2), ?line S1 = relation([{a,1},{b,2},{b,22},{c,0}]), ?line eval(drestriction(S1, set([a,b])), relation([{c,0}])), ?line eval(drestriction(2, S1, set([1,2])), relation([{b,22},{c,0}])), ?line eval(drestriction(S1, set([a,b,c])), ER), ?line eval(drestriction(2, ER, set([a,b])), ER), ?line eval(drestriction(1, S1, set([0,1,d,e])), S1), ?line eval(drestriction(1, S1, E), S1), ?line eval(drestriction({external, fun({_A,B,C}) -> {B,C} end}, relation([{a,aa,1},{b,bb,2},{c,cc,3}]), relation([{bb,2},{cc,3}])), relation([{a,aa,1}])), Id = fun(X) -> X end, XId = {external, Id}, ?line eval(drestriction(XId, relation([{a,b}]), E), relation([{a,b}])), ?line eval(drestriction(XId, E, relation([{b,d}])), E), Fun1 = fun(S) -> {_A,B,C} = to_external(S), from_term({B,C}) end, ?line eval(drestriction(Fun1, relation([{a,aa,1},{b,bb,2},{c,cc,3}]), relation([{bb,2},{cc,3}])), relation([{a,aa,1}])), ?line eval(drestriction({external, fun({_,{A},B}) -> {A,B} end}, from_term([{a,{aa},1},{b,{bb},2},{c,{cc},3}]), from_term([{bb,2},{cc,3}])), from_term([{a,{aa},1}])), S5 = relation([{1,a},{2,b},{3,c}]), ?line eval(drestriction(2, S5, set([b,c])), relation([{1,a}])), S4 = relation([{a,1},{b,2},{b,27},{c,0}]), ?line eval(drestriction(2, S4, set([])), S4), S6 = relation([{1,a},{2,c},{3,b}]), ?line eval(drestriction(2, S6, set([d,e])), S6), ?line eval(drestriction(2, relation([{1,d},{2,c},{3,b},{4,a},{5,e}]), set([c])), relation([{1,d},{3,b},{4,a},{5,e}])), ?line eval(drestriction(XId, relation([{1,a},{3,b},{4,c},{4,d}]), relation([{2,a},{2,c},{4,c}])), relation([{1,a},{3,b},{4,d}])), ?line eval(drestriction(2, relation([{a,b}]), E), relation([{a,b}])), ?line eval(drestriction(2, E, relation([{b,d}])), E), ?line eval(drestriction(2, relation([{b,d}]), E), relation([{b,d}])), ?line eval(drestriction(XId, E, set([a])), E), ?line eval(drestriction(1, S1, E), S1), ?line {'EXIT', {badarg, _}} = (catch drestriction(3, relation([{a,b}]), E)), ?line {'EXIT', {badarg, _}} = (catch drestriction(3, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {badarg, _}} = (catch drestriction(3, relation([{a,b}]), set([{b,d}]))), ?line {'EXIT', {type_mismatch, _}} = (catch drestriction(2, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {type_mismatch, _}} = (catch drestriction({external, fun({A,_B}) -> A end}, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {badarg, _}} = (catch drestriction({external, fun({A,_}) -> {A,0} end}, from_term([{1,a}]), from_term([{1,0}]))), ?line eval(drestriction(2, relation([{a,d},{b,e},{c,b},{d,c}]), set([b,d])), relation([{b,e},{d,c}])), ?line {'EXIT', {function_clause, _}} = (catch drestriction({external, fun({A,_B}) -> A end}, set([]), E)), Fun3 = fun(S) -> from_term({to_external(S),0}, {type(S),atom}) end, ?line eval(drestriction(Fun3, set([1,2]), from_term([{1,0}])), from_term([2])), ?line {'EXIT', {badarg, _}} = (catch drestriction({external, fun(X) -> X end}, from_term([], [[atom]]), set([a]))), S2 = from_term([], [[atom]]), ?line eval(drestriction(Id, S2, E), S2), S3 = from_term([[a],[b]], [[atom]]), ?line eval(drestriction(Id, S3, E), S3), ?line eval(drestriction(Id, from_term([], [[atom]]), set([a])), from_term([], [[atom]])), ?line eval(drestriction({sofs,union}, from_term([[[a],[b]], [[b],[c]], [[], [a,b]], [[1],[2]]]), from_term([[a,b],[1,2,3],[b,c]])), from_term([[[1],[2]]])), ?line eval(drestriction(fun(_) -> from_term([a]) end, from_term([], [[atom]]), from_term([], [[a]])), from_term([], [[atom]])), ?line {'EXIT', {type_mismatch, _}} = (catch drestriction(fun(_) -> from_term([a]) end, from_term([[1,2],[3,4]]), from_term([], [atom]))), Fun10 = fun(S) -> case to_external(S) of [1] -> from_term({1,1}); _ -> S end end, ?line {'EXIT', {type_mismatch, _}} = (catch drestriction(Fun10, from_term([[1]]), from_term([], [[atom]]))), ?line {'EXIT', {type_mismatch, _}} = (catch drestriction(fun(_) -> from_term({a}) end, from_term([[a]]), from_term([], [atom]))), ?line {'EXIT', {badarg, _}} = (catch drestriction(fun(_) -> {a} end, from_term([[a]]), from_term([], [atom]))), ok. strict_relation_1(suite) -> []; strict_relation_1(doc) -> [""]; strict_relation_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([], 2), ?line eval(strict_relation(E), E), ?line eval(strict_relation(ER), ER), ?line eval(strict_relation(relation([{1,a},{a,a},{2,b}])), relation([{1,a},{2,b}])), ?line {'EXIT', {badarg, _}} = (catch strict_relation(relation([{1,2,3}]))), F = 0.0, I = round(F), ?line FR = relation([{F,I}]), if eval(strict_relation(FR), ER); true -> eval(strict_relation(FR), FR) end, ok. extension(suite) -> []; extension(doc) -> [""]; extension(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([], 2), ?line EF = family([]), ?line C1 = from_term(3), ?line C2 = from_term([3]), ?line {'EXIT', {function_clause, _}} = (catch extension(foo, E, C1)), ?line {'EXIT', {function_clause, _}} = (catch extension(ER, foo, C1)), ?line {'EXIT', {{case_clause, _},_}} = (catch extension(ER, E, foo)), ?line {'EXIT', {type_mismatch, _}} = (catch extension(ER, E, E)), ?line {'EXIT', {badarg, _}} = (catch extension(C2, E, E)), ?line eval(E, extension(E, E, E)), ?line eval(EF, extension(EF, E, E)), ?line eval(family([{3,[]}]), extension(EF, set([3]), E)), ?line eval(ER, extension(ER, E, C1)), ?line eval(E, extension(E, ER, E)), ?line eval(from_term([],[{{atom,atom},type(ER)}]), extension(E, ER, ER)), ?line R1 = relation([{c,7},{c,9},{c,11},{d,17},{f,20}]), ?line S1 = set([a,c,d,e]), ?line eval(extension(R1, S1, C1), lextension(R1, S1, C1)), ?line S2 = set([1,2,3]), ?line eval(extension(ER, S2, C1), lextension(ER, S2, C1)), ?line R3 = relation([{4,a},{8,b}]), ?line S3 = set([1,2,3,4,5,6,7,8,9,10,11]), ?line eval(extension(R3, S3, C1), lextension(R3, S3, C1)), ?line R4 = relation([{2,b},{4,d},{6,f}]), ?line S4 = set([1,3,5,7]), ?line eval(extension(R4, S4, C1), lextension(R4, S4, C1)), ?line F1 = family([{a,[1]},{c,[2]}]), ?line S5 = set([a,b,c,d]), ?line eval(extension(F1, S5, C2), lextension(F1, S5, C2)), ok. lextension(R, S, C) -> union(R, drestriction(1, constant_function(S, C), domain(R))). weak_relation_1(suite) -> []; weak_relation_1(doc) -> [""]; weak_relation_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([], 2), ?line eval(weak_relation(E), E), ?line eval(weak_relation(ER), ER), ?line eval(weak_relation(relation([{a,1},{a,2},{b,2},{c,c}])), relation([{1,1},{2,2},{a,1},{a,2},{a,a},{b,2},{b,b},{c,c}])), ?line eval(weak_relation(relation([{a,1},{a,a},{a,b}])), relation([{1,1},{a,1},{a,a},{a,b},{b,b}])), ?line eval(weak_relation(relation([{a,1},{a,b},{7,w}])), relation([{1,1},{7,7},{7,w},{a,1},{a,a},{a,b},{b,b},{w,w}])), ?line {'EXIT', {badarg, _}} = (catch weak_relation(from_term([{{a},a}]))), ?line {'EXIT', {badarg, _}} = (catch weak_relation(from_term([{a,a}],[{d,r}]))), ?line {'EXIT', {badarg, _}} = (catch weak_relation(relation([{1,2,3}]))), F = 0.0, I = round(F), if ?line FR1 = relation([{F,I}]), eval(weak_relation(FR1), FR1), ?line FR2 = relation([{F,2},{I,1}]), true = no_elements(weak_relation(FR2)) =:= 5, ?line FR3 = relation([{1,0},{1.0,1}]), true = no_elements(weak_relation(FR3)) =:= 3; true -> ok end, ok. to_sets_1(suite) -> []; to_sets_1(doc) -> [""]; to_sets_1(Conf) when list(Conf) -> ?line {'EXIT', {badarg, _}} = (catch to_sets(from_term(a))), ?line {'EXIT', {function_clause, _}} = (catch to_sets(a)), ?line [] = to_sets(empty_set()), ?line eval(to_sets(from_term([a])), [from_term(a)]), ?line eval(to_sets(from_term([[]],[[atom]])), [set([])]), ?line L = [from_term([a,b]),from_term([c,d])], ?line eval(to_sets(from_sets(L)), L), ?line eval(to_sets(relation([{a,1},{b,2}])), [from_term({a,1},{atom,atom}), from_term({b,2},{atom,atom})]), ?line O = {from_term(a,atom), from_term({b}, {atom}), set([c,d])}, ?line eval(to_sets(from_sets(O)), O), ok. specification(suite) -> []; specification(doc) -> [""]; specification(Conf) when list(Conf) -> Fun = {external, fun(I) when integer(I) -> true; (_) -> false end}, ?line [1,2,3] = to_external(specification(Fun, set([a,1,b,2,c,3]))), Fun2 = fun(S) -> is_subset(S, set([1,3,5,7,9])) end, S2 = from_term([[1],[2],[3],[4],[5],[6],[7]]), ?line eval(specification(Fun2, S2), from_term([[1],[3],[5],[7]])), Fun2x = fun([1]) -> true; ([3]) -> true; (_) -> false end, ?line eval(specification({external,Fun2x}, S2), from_term([[1],[3]])), Fun3 = fun(_) -> neither_true_or_false end, ?line {'EXIT', {badarg, _}} = (catch specification(Fun3, set([a]))), ?line {'EXIT', {badarg, _}} = (catch specification({external, Fun3}, set([a]))), ?line {'EXIT', {badarg, _}} = (catch specification(Fun3, from_term([[a]]))), ?line {'EXIT', {function_clause, _}} = (catch specification(Fun, a)), ok. union_1(suite) -> []; union_1(doc) -> [""]; union_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([], 2), ?line {'EXIT', {badarg, _}} = (catch union(ER)), ?line {'EXIT', {type_mismatch, _}} = (catch union(relation([{a,b}]), relation([{a,b,c}]))), ?line {'EXIT', {type_mismatch, _}} = (catch union(from_term([{a,b}]), from_term([{c,[x]}]))), ?line {'EXIT', {type_mismatch, _}} = (catch union(from_term([{a,b}]), from_term([{c,d}], [{d,r}]))), ?line {'EXIT', {badarg, _}} = (catch union(set([a,b,c]))), ?line eval(union(E), E), ?line eval(union(from_term([[]],[[atom]])), set([])), ?line eval(union(from_term([[{a,b},{b,c}],[{b,c}]])), relation([{a,b},{b,c}])), ?line eval(union(from_term([[1,2,3],[2,3,4],[3,4,5]])), set([1,2,3,4,5])), ?line eval(union(from_term([{[a],[],c}]), from_term([{[],[],q}])), from_term([{[a],[],c},{[],[],q}])), ?line eval(union(E, E), E), ?line eval(union(set([a,b]), E), set([a,b])), ?line eval(union(E, set([a,b])), set([a,b])), ?line eval(union(from_term([[a,b]])), from_term([a,b])), ok. intersection_1(suite) -> []; intersection_1(doc) -> [""]; intersection_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line {'EXIT', {badarg, _}} = (catch intersection(from_term([a,b]))), ?line {'EXIT', {badarg, _}} = (catch intersection(E)), ?line {'EXIT', {type_mismatch, _}} = (catch intersection(relation([{a,b}]), relation([{a,b,c}]))), ?line {'EXIT', {type_mismatch, _}} = (catch intersection(relation([{a,b}]), from_term([{a,b}],[{d,r}]))), ?line eval(intersection(from_term([[a,b,c],[d,e,f],[g,h,i]])), set([])), ?line eval(intersection(E, E), E), ?line eval(intersection(set([a,b,c]),set([0,b,q])), set([b])), ?line eval(intersection(set([0,b,q]),set([a,b,c])), set([b])), ?line eval(intersection(set([a,b,c]),set([a,b,c])), set([a,b,c])), ?line eval(intersection(set([a,b,d]),set([c,d])), set([d])), ok. difference(suite) -> []; difference(doc) -> [""]; difference(Conf) when list(Conf) -> ?line E = empty_set(), ?line {'EXIT', {type_mismatch, _}} = (catch difference(relation([{a,b}]), relation([{a,b,c}]))), ?line eval(difference(E, E), E), ?line {'EXIT', {type_mismatch, _}} = (catch difference(relation([{a,b}]), from_term([{a,c}],[{d,r}]))), ?line eval(difference(set([a,b,c,d,f]), set([a,d,e,g])), set([b,c,f])), ?line eval(difference(set([a,b,c]), set([d,e,f])), set([a,b,c])), ?line eval(difference(set([a,b,c]), set([a,b,c,d,e,f])), set([])), ?line eval(difference(set([e,f,g]), set([a,b,c,e])), set([f,g])), ?line eval(difference(set([a,b,d,e,f]), set([c])), set([a,b,d,e,f])), ok. symdiff(suite) -> []; symdiff(doc) -> [""]; symdiff(Conf) when list(Conf) -> ?line E = empty_set(), ?line {'EXIT', {type_mismatch, _}} = (catch symdiff(relation([{a,b}]), relation([{a,b,c}]))), ?line {'EXIT', {type_mismatch, _}} = (catch symdiff(relation([{a,b}]), from_term([{a,b}], [{d,r}]))), ?line eval(symdiff(E, E), E), ?line eval(symdiff(set([a,b,c,d,e,f]), set([0,1,a,c])), union(set([b,d,e,f]), set([0,1]))), ?line eval(symdiff(set([a,b,c]), set([q,v,w,x,y])), union(set([a,b,c]), set([q,v,w,x,y]))), ?line eval(symdiff(set([a,b,c,d,e,f]), set([a,b,c])), set([d,e,f])), ?line eval(symdiff(set([c,e,g,h,i]), set([b,d,f])), union(set([c,e,g,h,i]), set([b,d,f]))), ?line eval(symdiff(set([c,d,g,h,k,l]), set([a,b,e,f,i,j,m,n])), union(set([c,d,g,h,k,l]), set([a,b,e,f,i,j,m,n]))), ?line eval(symdiff(set([c,d,g,h,k,l]), set([d,e,h,i,l,m,n,o,p])), union(set([c,g,k]), set([e,i,m,n,o,p]))), ok. symmetric_partition(suite) -> []; symmetric_partition(doc) -> [""]; symmetric_partition(Conf) when list(Conf) -> ?line E = set([]), ?line S1 = set([1,2,3,4]), ?line S2 = set([3,4,5,6]), ?line S3 = set([3,4]), ?line S4 = set([1,2,3,4,5,6]), ?line T1 = set([1,2]), ?line T2 = set([3,4]), ?line T3 = set([5,6]), ?line T4 = set([1,2,5,6]), ?line {'EXIT', {type_mismatch, _}} = (catch symmetric_partition(relation([{a,b}]), relation([{a,b,c}]))), ?line {E, E, E} = symmetric_partition(E, E), ?line {'EXIT', {type_mismatch, _}} = (catch symmetric_partition(relation([{a,b}]), from_term([{a,c}],[{d,r}]))), ?line {E, E, S1} = symmetric_partition(E, S1), ?line {S1, E, E} = symmetric_partition(S1, E), ?line {T1, T2, T3} = symmetric_partition(S1, S2), ?line {T3, T2, T1} = symmetric_partition(S2, S1), ?line {E, T2, T4} = symmetric_partition(S3, S4), ?line {T4, T2, E} = symmetric_partition(S4, S3), ?line S5 = set([1,3,5]), ?line S6 = set([2,4,6,7,8]), ?line {S5, E, S6} = symmetric_partition(S5, S6), ?line {S6, E, S5} = symmetric_partition(S6, S5), ?line EE = empty_set(), ?line {EE, EE, EE} = symmetric_partition(EE, EE), ok. is_sofs_set_1(suite) -> []; is_sofs_set_1(doc) -> [""]; is_sofs_set_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line true = is_sofs_set(E), ?line true = is_sofs_set(from_term([a])), ?line true = is_sofs_set(from_term({a})), ?line true = is_sofs_set(from_term(a)), ?line false = is_sofs_set(a), ok. is_set_1(suite) -> []; is_set_1(doc) -> [""]; is_set_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line true = is_set(E), ?line true = is_set(from_term([a])), ?line false = is_set(from_term({a})), ?line false = is_set(from_term(a)), ?line {'EXIT', _} = (catch is_set(a)), ?line true = is_empty_set(E), ?line false = is_empty_set(from_term([a])), ?line false = is_empty_set(from_term({a})), ?line false = is_empty_set(from_term(a)), ?line {'EXIT', _} = (catch is_empty_set(a)), ok. is_equal(suite) -> []; is_equal(doc) -> [""]; is_equal(Conf) when list(Conf) -> ?line E = empty_set(), ?line true = is_equal(E, E), ?line false = is_equal(from_term([a]), E), ?line {'EXIT', {type_mismatch, _}} = (catch is_equal(intersection(set([a]), set([b])), intersection(from_term([{a}]), from_term([{b}])))), ?line {'EXIT', {type_mismatch, _}} = (catch is_equal(from_term([],[{[atom],atom,[atom]}]), from_term([],[{[atom],{atom},[atom]}]))), ?line {'EXIT', {type_mismatch, _}} = (catch is_equal(set([a]), from_term([a],[type]))), ?line E2 = from_sets({from_term(a,atom)}), ?line true = is_equal(E2, E2), ?line true = is_equal(from_term({a}, {atom}), E2), ?line false = is_equal(from_term([{[a],[],c}]), from_term([{[],[],q}])), ?line {'EXIT', {type_mismatch, _}} = (catch is_equal(E, E2)), ?line {'EXIT', {type_mismatch, _}} = (catch is_equal(E2, E)), ?line true = is_equal(from_term({[],a,[]},{[atom],atom,[atom]}), from_term({[],a,[]},{[atom],atom,[atom]})), ?line {'EXIT', {type_mismatch, _}} = (catch is_equal(from_term({[],a,[]},{[atom],atom,[atom]}), from_term({[],{a},[]},{[atom],{atom},[atom]}))), ?line {'EXIT', {type_mismatch, _}} = (catch is_equal(from_term({a}), from_term({a},{type}))), ok. is_subset(suite) -> []; is_subset(doc) -> [""]; is_subset(Conf) when list(Conf) -> ?line E = empty_set(), ?line true = is_subset(E, E), ?line true = is_subset(set([a,c,e]), set([a,b,c,d,e])), ?line false = is_subset(set([a,b]), E), ?line false = is_subset(set([d,e,f]), set([b,c,d,e])), ?line false = is_subset(set([a,b,c]), set([b,c])), ?line false = is_subset(set([b,c]), set([a,c])), ?line false = is_subset(set([d,e]), set([a,b])), ?line {'EXIT', {type_mismatch, _}} = (catch is_subset(intersection(set([a]), set([b])), intersection(from_term([{a}]), from_term([{b}])))), ?line {'EXIT', {type_mismatch, _}} = (catch is_subset(set([a]), from_term([a,b], [at]))), ok. is_a_function_1(suite) -> []; is_a_function_1(doc) -> [""]; is_a_function_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([], 2), ?line {'EXIT', {badarg, _}} = (catch is_a_function(set([a,b]))), ?line true = is_a_function(E), ?line true = is_a_function(ER), ?line true = is_a_function(relation([])), ?line true = is_a_function(relation([],2)), ?line true = is_a_function(relation([{a,b},{b,c}])), ?line false = is_a_function(relation([{a,b},{b,c},{b,d},{e,f}])), ?line IS = relation([{{a,b},c},{{a,b},d}]), ?line false = is_a_function(IS), F = 0.0, I = round(F), ?line FR = relation([{I,F},{F,1}]), if false = is_a_function(FR); true -> true = is_a_function(FR) end, ok. is_disjoint(suite) -> []; is_disjoint(doc) -> [""]; is_disjoint(Conf) when list(Conf) -> ?line E = empty_set(), ?line {'EXIT', {type_mismatch, _}} = (catch is_disjoint(relation([{a,1}]), set([a,b]))), ?line {'EXIT', {type_mismatch, _}} = (catch is_disjoint(set([a]), from_term([a],[mota]))), ?line true = is_disjoint(E, E), ?line false = is_disjoint(set([a,b,c]),set([b,c,d])), ?line false = is_disjoint(set([b,c,d]),set([a,b,c])), ?line true = is_disjoint(set([a,c,e]),set([b,d,f])), ok. join(suite) -> []; join(doc) -> [""]; join(Conf) when list(Conf) -> ?line E = empty_set(), ?line {'EXIT', {badarg, _}} = (catch join(relation([{a,1}]), 3, E, 5)), ?line {'EXIT', {badarg, _}} = (catch join(E, 1, relation([{a,1}]), 3)), ?line {'EXIT', {badarg, _}} = (catch join(E, 1, from_term([a]), 1)), ?line eval(join(E, 1, E, 2), E), ?line eval(join(E, 1, from_term([{{a},b}]), 2), E), ?line eval(join(from_term([{{a},b}]), 2, E, 1), E), ?line eval(join(from_term([{{a},b,e}]), 2, from_term([{c,{d}}]), 1), from_term([], [{{atom},atom,atom,{atom}}])), ?line eval(join(relation([{a}]), 1, relation([{1,a},{2,a}]), 2), relation([{a,1},{a,2}])), ?line eval(join(relation([{a,b,c},{b,c,d}]), 2, relation([{1,b},{2,a},{3,c}]), 2), relation([{a,b,c,1},{b,c,d,3}])), ?line eval(join(relation([{1,a,aa},{1,b,bb},{1,c,cc},{2,a,aa},{2,b,bb}]), 1, relation([{1,c,cc},{1,d,dd},{1,e,ee},{2,c,cc},{2,d,dd}]), 1), relation([{1,a,aa,c,cc},{1,a,aa,d,dd},{1,a,aa,e,ee},{1,b,bb,c,cc}, {1,b,bb,d,dd},{1,b,bb,e,ee},{1,c,cc,c,cc},{1,c,cc,d,dd}, {1,c,cc,e,ee},{2,a,aa,c,cc},{2,a,aa,d,dd},{2,b,bb,c,cc}, {2,b,bb,d,dd}])), R1 = relation([{a,b},{b,c}]), R2 = relation([{b,1},{a,2},{c,3},{c,4}]), ?line eval(join(R1, 1, R2, 1), from_term([{a,b,2},{b,c,1}])), ?line eval(join(R1, 2, R2, 1), from_term([{a,b,1},{b,c,3},{b,c,4}])), ?line eval(join(R1, 1, converse(R2), 2), from_term([{a,b,2},{b,c,1}])), ?line eval(join(R1, 2, converse(R2), 2), from_term([{a,b,1},{b,c,3},{b,c,4}])), ok. canonical(suite) -> []; canonical(doc) -> [""]; canonical(Conf) when list(Conf) -> ?line E = empty_set(), ?line {'EXIT', {badarg, _}} = (catch canonical_relation(set([a,b]))), ?line eval(canonical_relation(E), E), ?line eval(canonical_relation(from_term([[]])), E), ?line eval(canonical_relation(from_term([[a,b,c]])), from_term([{a,[a,b,c]},{b,[a,b,c]},{c,[a,b,c]}])), ok. relation_to_family_1(suite) -> []; relation_to_family_1(doc) -> [""]; relation_to_family_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = family([]), ?line eval(relation_to_family(E), E), ?line eval(relation_to_family(relation([])), EF), ?line eval(relation_to_family(relation([], 2)), EF), ?line R = relation([{b,1},{c,7},{c,9},{c,11}]), ?line F = family([{b,[1]},{c,[7,9,11]}]), ?line eval(relation_to_family(R), F), ?line eval(sofs:rel2fam(R), F), ?line {'EXIT', {badarg, _}} = (catch relation_to_family(set([a]))), ok. domain_1(suite) -> []; domain_1(doc) -> [""]; domain_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line {'EXIT', {badarg, _}} = (catch domain(relation([],3))), ?line eval(domain(E), E), ?line eval(domain(ER), set([])), ?line eval(domain(relation([{1,a},{1,b},{2,a},{2,b}])), set([1,2])), ?line eval(domain(relation([{a,1},{b,2},{c,3}])), set([a,b,c])), ?line eval(field(relation([{a,1},{b,2},{c,3}])), set([a,b,c,1,2,3])), F = 0.0, I = round(F), ?line FR = relation([{I,a},{F,b}]), if ?line true = (1 =:= no_elements(domain(FR))); true -> ?line true = (2 =:= no_elements(domain(FR))) end, ok. range_1(suite) -> []; range_1(doc) -> [""]; range_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line {'EXIT', {badarg, _}} = (catch range(relation([],3))), ?line eval(range(E), E), ?line eval(range(ER), set([])), ?line eval(range(relation([{1,a},{1,b},{2,a},{2,b}])), set([a,b])), ?line eval(range(relation([{a,1},{b,2},{c,3}])), set([1,2,3])), ok. inverse_1(suite) -> []; inverse_1(doc) -> [""]; inverse_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line {'EXIT', {badarg, _}} = (catch inverse(relation([],3))), ?line {'EXIT', {bad_function, _}} = (catch inverse(relation([{1,a},{1,b}]))), ?line {'EXIT', {bad_function, _}} = (catch inverse(relation([{1,a},{2,a}]))), ?line eval(inverse(E), E), ?line eval(inverse(ER), ER), ?line eval(inverse(relation([{a,1},{b,2},{c,3}])), relation([{1,a},{2,b},{3,c}])), F = 0.0, I = round(F), ?line FR = relation([{I,a},{F,b}]), if ?line {'EXIT', {bad_function, _}} = (catch inverse(FR)); true -> ?line eval(inverse(FR), relation([{a,I},{b,F}])) end, ok. converse_1(suite) -> []; converse_1(doc) -> [""]; converse_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line {'EXIT', {badarg, _}} = (catch converse(relation([],3))), ?line eval(converse(ER), ER), ?line eval(converse(E), E), ?line eval(converse(relation([{a,1},{b,2},{c,3}])), relation([{1,a},{2,b},{3,c}])), ?line eval(converse(relation([{1,a},{1,b}])), relation([{a,1},{b,1}])), ?line eval(converse(relation([{1,a},{2,a}])), relation([{a,1},{a,2}])), ok. no_elements_1(suite) -> []; no_elements_1(doc) -> [""]; no_elements_1(Conf) when list(Conf) -> ?line 0 = no_elements(empty_set()), ?line 0 = no_elements(set([])), ?line 1 = no_elements(from_term([a])), ?line 10 = no_elements(from_term(lists:seq(1,10))), ?line 3 = no_elements(from_term({a,b,c},{atom,atom,atom})), ?line {'EXIT', {badarg, _}} = (catch no_elements(from_term(a))), ?line {'EXIT', {function_clause, _}} = (catch no_elements(a)), ok. image(suite) -> []; image(doc) -> [""]; image(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line eval(image(E, E), E), ?line eval(image(ER, E), set([])), ?line eval(image(relation([{a,1},{b,2},{c,3},{f,6}]), set([a,b,c,d,f])), set([1,2,3,6])), ?line eval(image(relation([{a,1},{b,2},{c,3},{d,4},{r,17}]), set([b,c,q,r])), set([2,3,17])), ?line eval(image(from_term([{[a],{1}},{[b],{2}}]), from_term([[a]])), from_term([{1}])), ?line eval(image(relation([{1,a},{2,a},{3,a},{4,b},{2,b}]), set([1,2,4])), set([a,b])), ?line {'EXIT', {badarg, _}} = (catch image(from_term([a,b]), E)), ?line {'EXIT', {type_mismatch, _}} = (catch image(from_term([{[a],1}]), set([[a]]))), ok. inverse_image(suite) -> []; inverse_image(doc) -> [""]; inverse_image(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line eval(inverse_image(E, E), E), ?line eval(inverse_image(ER, E), set([])), ?line eval(inverse_image(converse(relation([{a,1},{b,2},{c,3},{f,6}])), set([a,b,c,d,f])), set([1,2,3,6])), ?line eval(inverse_image(converse(relation([{a,1},{b,2},{c,3}, {d,4},{r,17}])), set([b,c,q,r])), set([2,3,17])), ?line eval(inverse_image(converse(from_term([{[a],{1}},{[b],{2}}])), from_term([[a]])), from_term([{1}])), ?line eval(inverse_image(converse(relation([{1,a},{2,a}, {3,a},{4,b},{2,b}])), set([1,2,4])), set([a,b])), ?line {'EXIT', {badarg, _}} = (catch inverse_image(from_term([a,b]), E)), ?line {'EXIT', {type_mismatch, _}} = (catch inverse_image(converse(from_term([{[a],1}])), set([[a]]))), ok. composite_1(suite) -> []; composite_1(doc) -> [""]; composite_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = a_function([]), ?line eval(composite(E, E), E), ?line eval(composite(E, a_function([{a,b}])), E), ?line eval(composite(relation([{a,b}]), E), E), ?line {'EXIT', {bad_function, _}} = (catch composite(EF, relation([{a,b},{a,c}]))), ?line {'EXIT', {bad_function, _}} = (catch composite(a_function([{b,a}]), EF)), ?line {'EXIT', {bad_function, _}} = (catch composite(relation([{1,a},{2,b},{2,a}]), a_function([{a,1},{b,3}]))), ?line {'EXIT', {bad_function, _}} = (catch composite(a_function([{1,a},{2,b}]), a_function([{b,3}]))), ?line eval(composite(EF, EF), EF), ?line eval(composite(a_function([{b,a}]), from_term([{a,{b,c}}])), from_term([{b,{b,c}}])), ?line eval(composite(a_function([{q,1},{z,2}]), a_function([{1,a},{2,a}])), a_function([{q,a},{z,a}])), ?line eval(composite(a_function([{a,0},{b,0},{c,1},{d,1},{e,2},{f,3}]), a_function([{0,p},{1,q},{2,r},{3,w},{4,aa}])), a_function([{c,q},{d,q},{f,w},{e,r},{a,p},{b,p}])), ?line eval(composite(a_function([{1,c}]), a_function([{a,1},{b,3},{c,4}])), a_function([{1,4}])), ?line {'EXIT', {bad_function, _}} = (catch composite(a_function([{1,a},{2,b}]), a_function([{a,1},{c,3}]))), ?line {'EXIT', {badarg, _}} = (catch composite(from_term([a,b]), E)), ?line {'EXIT', {badarg, _}} = (catch composite(E, from_term([a,b]))), ?line {'EXIT', {type_mismatch, _}} = (catch composite(from_term([{a,b}]), from_term([{{a},b}]))), ?line {'EXIT', {type_mismatch, _}} = (catch composite(from_term([{a,b}]), from_term([{b,c}], [{d,r}]))), F = 0.0, I = round(F), ?line FR1 = relation([{1,c}]), ?line FR2 = relation([{I,1},{F,3},{c,4}]), if ?line {'EXIT', {bad_function, _}} = (catch composite(FR1, FR2)); true -> ?line eval(composite(FR1, FR2), a_function([{1,4}])) end, ok. relative_product_1(suite) -> []; relative_product_1(doc) -> [""]; relative_product_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line eval(relative_product1(E, E), E), ?line eval(relative_product1(E, relation([{a,b}])), E), ?line eval(relative_product1(relation([{a,b}]), E), E), ?line eval(relative_product1(relation([{a,b}]), from_term([{a,{b,c}}])), from_term([{b,{b,c}}])), ?line eval(relative_product1(relation([{1,z},{1,q},{2,z}]), relation([{1,a},{1,b},{2,a}])), relation([{q,a},{q,b},{z,a},{z,b}])), ?line eval(relative_product1(relation([{0,a},{0,b},{1,c}, {1,d},{2,e},{3,f}]), relation([{1,q},{3,w}])), relation([{c,q},{d,q},{f,w}])), ?line {'EXIT', {badarg, _}} = (catch relative_product1(from_term([a,b]), ER)), ?line {'EXIT', {badarg, _}} = (catch relative_product1(ER, from_term([a,b]))), ?line {'EXIT', {type_mismatch, _}} = (catch relative_product1(from_term([{a,b}]), from_term([{{a},b}]))), ?line {'EXIT', {type_mismatch, _}} = (catch relative_product1(from_term([{a,b}]), from_term([{b,c}], [{d,r}]))), ok. relative_product_2(suite) -> []; relative_product_2(doc) -> [""]; relative_product_2(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line {'EXIT', {badarg, _}} = (catch relative_product({from_term([a,b])})), ?line {'EXIT', {type_mismatch, _}} = (catch relative_product({from_term([{a,b}]), from_term([{{a},b}])})), ?line {'EXIT', {badarg, _}} = (catch relative_product({})), ?line true = is_equal(relative_product({ER}), from_term([], [{atom,{atom}}])), ?line eval(relative_product({relation([{a,b},{c,a}]), relation([{a,1},{a,2}]), relation([{a,aa},{c,1}])}), from_term([{a,{b,1,aa}},{a,{b,2,aa}}])), ?line eval(relative_product({relation([{a,b}])}, E), E), ?line eval(relative_product({E}, relation([{a,b}])), E), ?line eval(relative_product({E,from_term([], [{{atom,atom,atom},atom}])}), E), ?line {'EXIT', {badarg, _}} = (catch relative_product({from_term([a,b])}, E)), ?line {'EXIT', {badarg, _}} = (catch relative_product({relation([])}, set([]))), ?line {'EXIT', {type_mismatch, _}} = (catch relative_product({from_term([{a,b}]), from_term([{{a},b}])}, ER)), ?line {'EXIT', {badarg, _}} = (catch relative_product({}, ER)), ?line eval(relative_product({relation([{a,b}])}, from_term([],[{{atom},atom}])), ER), ?line eval(relative_product({relation([{a,b}]),relation([{a,1}])}, from_term([{{b,1},{tjo,hej,sa}}])), from_term([{a,{tjo,hej,sa}}])), ?line eval(relative_product({relation([{a,b}]), ER}, from_term([{{a,b},b}])), ER), ?line eval(relative_product({relation([{a,b},{c,a}]), relation([{a,1},{a,2}])}, from_term([{{b,1},b1},{{b,2},b2}])), relation([{a,b1},{a,b2}])), ?line eval(relative_product({relation([{a,b}]), ER}), from_term([],[{atom,{atom,atom}}])), ?line eval(relative_product({from_term([{{a,[a,b]},[a]}]), from_term([{{a,[a,b]},[[a,b]]}])}), from_term([{{a,[a,b]},{[a],[[a,b]]}}])), ok. product_1(suite) -> []; product_1(doc) -> [""]; product_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line eval(product(E, E), E), ?line eval(product(relation([]), E), E), ?line eval(product(E, relation([])), E), ?line eval(product(relation([{a,b}]),relation([{c,d}])), from_term([{{a,b},{c,d}}],[{{atom,atom},{atom,atom}}])), ?line eval(product({E, set([a,b,c])}), E), ?line eval(product({set([a,b,c]), E}), E), ?line eval(product({set([a,b,c]), E, E}), E), ?line eval(product({E,E}), E), ?line eval(product({set([a,b]),set([1,2])}), relation([{a,1},{a,2},{b,1},{b,2}])), ?line eval(product({from_term([a,b]), from_term([{a,b},{c,d}]), from_term([1])}), from_term([{a,{a,b},1},{a,{c,d},1},{b,{a,b},1},{b,{c,d},1}])), ?line {'EXIT', {badarg, _}} = (catch product({})), ?line {'EXIT', {badarg, _}} = (catch product({foo})), ?line eval(product({E}), E), ?line eval(product({E, E}), E), ?line eval(product(set([a,b]), set([1,2])), relation([{a,1},{a,2},{b,1},{b,2}])), ?line eval(product({relation([]), E}), E), ok. partition_1(suite) -> []; partition_1(doc) -> [""]; partition_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line Id = fun(A) -> A end, ?line S1 = relation([{a,1},{b,2},{b,22},{c,0}]), ?line eval(partition(1, E), E), ?line eval(partition(2, E), E), ?line eval(partition(1, ER), from_term([], [type(ER)])), ?line eval(partition(2, ER), from_term([], [type(ER)])), ?line eval(partition(1, relation([{1,a},{1,b},{2,c},{2,d}])), from_term([[{1,a},{1,b}],[{2,c},{2,d}]])), ?line eval(partition(2, relation([{1,a},{1,b},{2,a},{2,b},{3,c}])), from_term([[{1,a},{2,a}],[{1,b},{2,b}],[{3,c}]])), ?line eval(partition(2, relation([{1,a}])), from_term([[{1,a}]])), ?line eval(partition(2, relation([{1,a},{2,b}])), from_term([[{1,a}],[{2,b}]])), ?line eval(partition(2, relation([{1,a},{2,a},{3,a}])), from_term([[{1,a},{2,a},{3,a}]])), from_term([[{1,b}],[{2,a}]])), ?line eval(union(partition(Id, S1)), S1), ?line eval(partition({external, fun({A,{B,_}}) -> {A,B} end}, from_term([{a,{b,c}},{b,{c,d}},{a,{b,f}}])), from_term([[{a,{b,c}},{a,{b,f}}],[{b,{c,d}}]])), F = 0.0, I = round(F), ?line FR = relation([{I,a},{F,b}]), if ?line eval(partition(1, FR), from_term([[{I,a},{F,b}]])); true -> ?line eval(partition(1, FR), from_term([[{I,a}],[{F,b}]])) end, ?line {'EXIT', {badarg, _}} = (catch partition(2, set([a]))), ?line {'EXIT', {badarg, _}} = (catch partition(1, set([a]))), ?line eval(partition(Id, set([a])), from_term([[a]])), ?line eval(partition(E), E), ?line P1 = from_term([[a,b,c],[d,e,f],[g,h]]), ?line P2 = from_term([[a,d],[b,c,e,f,q,v]]), ?line eval(partition(union(P1, P2)), from_term([[a],[b,c],[d],[e,f],[g,h],[q,v]])), ?line {'EXIT', {badarg, _}} = (catch partition(from_term([a]))), ok. partition_3(suite) -> []; partition_3(doc) -> [""]; partition_3(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line S1 = relation([{a,1},{b,2},{b,22},{c,0}]), ?line eval(partition(1, S1, set([0,1,d,e])), lpartition(1, S1, set([0,1,d,e]))), ?line eval(partition(1, S1, E), lpartition(1, S1, E)), ?line eval(partition(2, ER, set([a,b])), lpartition(2, ER, set([a,b]))), XFun1 = {external, fun({_A,B,C}) -> {B,C} end}, R1a = relation([{a,aa,1},{b,bb,2},{c,cc,3}]), R1b = relation([{bb,2},{cc,3}]), ?line eval(partition(XFun1, R1a, R1b), lpartition(XFun1, R1a, R1b)), Id = fun(X) -> X end, XId = {external, Id}, R2 = relation([{a,b}]), ?line eval(partition(XId, R2, E), lpartition(XId, R2, E)), R3 = relation([{b,d}]), ?line eval(partition(XId, E, R3), lpartition(XId, E, R3)), Fun1 = fun(S) -> {_A,B,C} = to_external(S), from_term({B,C}) end, R4a = relation([{a,aa,1},{b,bb,2},{c,cc,3}]), R4b = relation([{bb,2},{cc,3}]), ?line eval(partition(Fun1,R4a,R4b), lpartition(Fun1,R4a,R4b)), XFun2 = {external, fun({_,{A},B}) -> {A,B} end}, R5a = from_term([{a,{aa},1},{b,{bb},2},{c,{cc},3}]), R5b = from_term([{bb,2},{cc,3}]), ?line eval(partition(XFun2,R5a, R5b), lpartition(XFun2,R5a, R5b)), R6 = relation([{a,b}]), ?line eval(partition(2, R6, E), lpartition(2, R6, E)), R7 = relation([{b,d}]), ?line eval(partition(2, E, R7), lpartition(2, E, R7)), S2 = set([a]), ?line eval(partition(XId, E, S2), lpartition(XId, E, S2)), ?line eval(partition(XId, S1, E), lpartition(XId, S1, E)), ?line {'EXIT', {badarg, _}} = (catch partition(3, relation([{a,b}]), E)), ?line {'EXIT', {badarg, _}} = (catch partition(3, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {badarg, _}} = (catch partition(3, relation([{a,b}]), set([{b,d}]))), ?line {'EXIT', {type_mismatch, _}} = (catch partition(2, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {type_mismatch, _}} = (catch partition({external, fun({A,_B}) -> A end}, relation([{a,b}]), relation([{b,d}]))), ?line {'EXIT', {badarg, _}} = (catch partition({external, fun({A,_}) -> {A,0} end}, from_term([{1,a}]), from_term([{1,0}]))), S18a = relation([{1,e},{2,b},{3,c},{4,b},{5,a},{6,0}]), S18b = set([b,d,f]), ?line eval(partition({external,fun({_,X}) -> X end}, S18a, S18b), lpartition({external,fun({_,X}) -> X end}, S18a, S18b)), S19a = sofs:relation([{3,a},{8,b}]), S19b = set([2,6,7]), ?line eval(partition({external,fun({X,_}) -> X end}, S19a, S19b), lpartition({external,fun({X,_}) -> X end}, S19a, S19b)), R8a = relation([{a,d},{b,e},{c,b},{d,c}]), S8 = set([b,d]), ?line eval(partition(2, R8a, S8), lpartition(2, R8a, S8)), S16a = relation([{1,e},{2,b},{3,c},{4,b},{5,a},{6,0}]), S16b = set([b,c,d]), ?line eval(partition(2, S16a, S16b), lpartition(2, S16a, S16b)), S17a = relation([{e,1},{b,2},{c,3},{b,4},{a,5},{0,6}]), S17b = set([b,c,d]), ?line eval(partition(1, S17a, S17b), lpartition(1, S17a, S17b)), ?line {'EXIT', {function_clause, _}} = (catch partition({external, fun({A,_B}) -> A end}, set([]), E)), Fun3 = fun(S) -> from_term({to_external(S),0}, {type(S),atom}) end, S9a = set([1,2]), S9b = from_term([{1,0}]), ?line eval(partition(Fun3, S9a, S9b), lpartition(Fun3, S9a, S9b)), S14a = relation([{1,a},{2,b},{3,c},{0,0}]), S14b = set([b,c]), ?line eval(partition(2, S14a, S14b), lpartition(2, S14a, S14b)), S15a = relation([{a,1},{b,2},{c,3},{0,0}]), S15b = set([b,c]), ?line eval(partition(1, S15a, S15b), lpartition(1, S15a, S15b)), ?line {'EXIT', {badarg, _}} = (catch partition({external, fun(X) -> X end}, from_term([], [[atom]]), set([a]))), S10 = from_term([], [[atom]]), ?line eval(partition(Id, S10, E), lpartition(Id, S10, E)), S10e = from_term([[a],[b]], [[atom]]), ?line eval(partition(Id, S10e, E), lpartition(Id, S10e, E)), S11a = from_term([], [[atom]]), S11b = set([a]), ?line eval(partition(Id, S11a, S11b), lpartition(Id, S11a, S11b)), S12a = from_term([[[a],[b]], [[b],[c]], [[], [a,b]], [[1],[2]]]), S12b = from_term([[a,b],[1,2,3],[b,c]]), ?line eval(partition({sofs,union}, S12a, S12b), lpartition({sofs,union}, S12a, S12b)), Fun13 = fun(_) -> from_term([a]) end, S13a = from_term([], [[atom]]), S13b = from_term([], [[a]]), ?line eval(partition(Fun13, S13a, S13b), lpartition(Fun13, S13a, S13b)), ?line {'EXIT', {type_mismatch, _}} = (catch partition(fun(_) -> from_term([a]) end, from_term([[1,2],[3,4]]), from_term([], [atom]))), Fun10 = fun(S) -> case to_external(S) of [1] -> from_term({1,1}); _ -> S end end, ?line {'EXIT', {type_mismatch, _}} = (catch partition(Fun10, from_term([[1]]), from_term([], [[atom]]))), ?line {'EXIT', {type_mismatch, _}} = (catch partition(fun(_) -> from_term({a}) end, from_term([[a]]), from_term([], [atom]))), ?line {'EXIT', {badarg, _}} = (catch partition(fun(_) -> {a} end, from_term([[a]]), from_term([], [atom]))), ok. lpartition(F, S1, S2) -> {restriction(F, S1, S2), drestriction(F, S1, S2)}. multiple_relative_product(suite) -> []; multiple_relative_product(doc) -> [""]; multiple_relative_product(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line T = relation([{a,1},{a,11},{b,2},{c,3},{c,33},{d,4}]), ?line {'EXIT', {badarg, _}} = (catch multiple_relative_product({}, ER)), ?line {'EXIT', {badarg, _}} = (catch multiple_relative_product({}, relation([{a,b}]))), ?line eval(multiple_relative_product({E,T,T}, relation([], 3)), E), ?line eval(multiple_relative_product({T,T,T}, E), E), ?line eval(multiple_relative_product({T,T,T}, relation([],3)), from_term([],[{{atom,atom,atom},{atom,atom,atom}}])), ?line eval(multiple_relative_product({T,T,T}, relation([{a,b,c},{c,d,a}])), from_term([{{a,b,c},{1,2,3}}, {{a,b,c},{1,2,33}}, {{a,b,c},{11,2,3}}, {{a,b,c},{11,2,33}}, {{c,d,a},{3,4,1}}, {{c,d,a},{3,4,11}}, {{c,d,a},{33,4,1}}, {{c,d,a},{33,4,11}}])), ?line {'EXIT', {type_mismatch, _}} = (catch multiple_relative_product({T}, from_term([{{a}}]))), ok. digraph(suite) -> []; digraph(doc) -> [""]; digraph(Conf) when list(Conf) -> ?line T0 = ets:all(), ?line E = empty_set(), ?line R = relation([{a,b},{b,c},{c,d},{d,a}]), ?line F = relation_to_family(R), Type = type(F), ?line {'EXIT', {badarg, _}} = (catch family_to_digraph(set([a]))), ?line {'EXIT', {badarg, [{sofs,family_to_digraph,[_,_]}|_]}} = (catch family_to_digraph(set([a]), [foo])), ?line {'EXIT', {badarg, [{sofs,family_to_digraph,[_,_]}|_]}} = (catch family_to_digraph(F, [foo])), ?line {'EXIT', {cyclic, [{sofs,family_to_digraph,[_,_]}|_]}} = (catch family_to_digraph(family([{a,[a]}]),[acyclic])), ?line G1 = family_to_digraph(E), ?line {'EXIT', {badarg, _}} = (catch digraph_to_family(G1, foo)), ?line {'EXIT', {badarg, _}} = (catch digraph_to_family(G1, atom)), ?line true = [] == to_external(digraph_to_family(G1)), ?line true = [] == to_external(digraph_to_family(G1, Type)), ?line true = digraph:delete(G1), ?line G1a = family_to_digraph(E, [protected]), ?line true = [] == to_external(digraph_to_family(G1a)), ?line true = [] == to_external(digraph_to_family(G1a, Type)), ?line true = digraph:delete(G1a), ?line G2 = family_to_digraph(F), ?line true = F == digraph_to_family(G2), ?line true = F == digraph_to_family(G2, type(F)), ?line true = digraph:delete(G2), ?line R2 = from_term([{{a},b},{{c},d}]), ?line F2 = relation_to_family(R2), ?line Type2 = type(F2), ?line G3 = family_to_digraph(F2, [protected]), ?line true = is_subset(F2, digraph_to_family(G3, Type2)), ?line true = digraph:delete(G3), Fl = 0.0, I = round(Fl), if ?line G4 = digraph:new(), digraph:add_vertex(G4, Fl), digraph:add_vertex(G4, I), ?line {'EXIT', {badarg, _}} = (catch digraph_to_family(G4, Type)), ?line {'EXIT', {badarg, _}} = (catch digraph_to_family(G4)), ?line true = digraph:delete(G4); true -> ok end, ?line true = T0 == ets:all(), ok. constant_function(suite) -> []; constant_function(doc) -> [""]; constant_function(Conf) when list(Conf) -> ?line E = empty_set(), ?line C = from_term(3), ?line eval(constant_function(E, C), E), ?line eval(constant_function(set([a,b]), E), from_term([{a,[]},{b,[]}])), ?line eval(constant_function(set([a,b]), C), from_term([{a,3},{b,3}])), ?line {'EXIT', {badarg, _}} = (catch constant_function(C, C)), ?line {'EXIT', {badarg, _}} = (catch constant_function(set([]), foo)), ok. misc(suite) -> []; misc(doc) -> [""]; misc(Conf) when list(Conf) -> ?line S = relation([{a,b},{b,c},{b,d},{c,d}]), Id = fun(A) -> A end, ?line RR = relational_restriction(S), ?line eval(union(difference(partition(Id,S), partition(1,S))), RR), ?line eval(union(difference(partition(1,S), partition(Id,S))), RR), ?line eval(union(intersection(partition(1,S), partition(Id,S))), difference(S, RR)), ?line {'EXIT', {undef, _}} = (catch projection({external,foo}, set([a,b,c]))), ok. relational_restriction(R) -> Fun = fun(S) -> no_elements(S) > 1 end, family_to_relation(family_specification(Fun, relation_to_family(R))). sofs_family(suite) -> [family_specification, family_domain_1, family_range_1, family_to_relation_1, union_of_family_1, intersection_of_family_1, family_projection, family_difference, family_intersection_1, family_intersection_2, family_union_1, family_union_2, partition_family]. family_specification(suite) -> []; family_specification(doc) -> [""]; family_specification(Conf) when list(Conf) -> E = empty_set(), ?line eval(family_specification({sofs, is_set}, E), E), ?line {'EXIT', {badarg, _}} = (catch family_specification({sofs,is_set}, set([]))), ?line F1 = from_term([{1,[1]}]), ?line eval(family_specification({sofs,is_set}, F1), F1), Fun = fun(S) -> is_subset(S, set([0,1,2,3,4])) end, ?line F2 = family([{a,[1,2]},{b,[3,4,5]}]), ?line eval(family_specification(Fun, F2), family([{a,[1,2]}])), ?line F3 = from_term([{a,[]},{b,[]}]), ?line eval(family_specification({sofs,is_set}, F3), F3), Fun2 = fun(_) -> throw(fippla) end, ?line fippla = (catch family_specification(Fun2, family([{a,[1]}]))), Fun3 = fun(_) -> neither_true_or_false end, ?line {'EXIT', {badarg, _}} = (catch family_specification(Fun3, F3)), IsList = {external, fun(L) when list(L) -> true; (_) -> false end}, ?line eval(family_specification(IsList, E), E), ?line eval(family_specification(IsList, F1), F1), MF = {external, fun(L) -> lists:member(3, L) end}, ?line eval(family_specification(MF, F2), family([{b,[3,4,5]}])), ?line fippla = (catch family_specification(Fun2, family([{a,[1]}]))), ?line {'EXIT', {badarg, _}} = (catch family_specification({external, Fun3}, F3)), ok. family_domain_1(suite) -> []; family_domain_1(doc) -> [""]; family_domain_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = from_term([{a,[]},{b,[]}],[{atom,[{atom,atom}]}]), ?line EF = from_term([{a,[]},{b,[]}],[{atom,[atom]}]), ?line eval(family_domain(E), E), ?line eval(family_domain(ER), EF), ?line FR = from_term([{a,[{1,a},{2,b},{3,c}]},{b,[]},{c,[{4,d},{5,e}]}]), ?line eval(family_domain(FR), from_term([{a,[1,2,3]},{b,[]},{c,[4,5]}])), ?line eval(family_field(E), E), ?line eval(family_field(FR), from_term([{a,[a,b,c,1,2,3]},{b,[]},{c,[d,e,4,5]}])), ?line eval(family_domain(from_term([{{a},[{{1,[]},c}]}])), from_term([{{a},[{1,[]}]}])), ?line eval(family_domain(from_term([{{a},[{{1,[a]},c}]}])), from_term([{{a},[{1,[a]}]}])), ?line eval(family_domain(from_term([{{a},[]}])), from_term([{{a},[]}])), ?line eval(family_domain(from_term([], type(FR))), from_term([], [{atom,[atom]}])), ?line {'EXIT', {badarg, _}} = (catch family_domain(set([a]))), ?line {'EXIT', {badarg, _}} = (catch family_field(set([a]))), ?line {'EXIT', {badarg, _}} = (catch family_domain(set([{a,[b]}]))), ok. family_range_1(suite) -> []; family_range_1(doc) -> [""]; family_range_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = from_term([{a,[]},{b,[]}],[{atom,[{atom,atom}]}]), ?line EF = from_term([{a,[]},{b,[]}],[{atom,[atom]}]), ?line eval(family_range(E), E), ?line eval(family_range(ER), EF), ?line FR = from_term([{a,[{1,a},{2,b},{3,c}]},{b,[]},{c,[{4,d},{5,e}]}]), ?line eval(family_range(FR), from_term([{a,[a,b,c]},{b,[]},{c,[d,e]}])), ?line eval(family_range(from_term([{{a},[{c,{1,[a]}}]}])), from_term([{{a},[{1,[a]}]}])), ?line eval(family_range(from_term([{{a},[{c,{1,[]}}]}])), from_term([{{a},[{1,[]}]}])), ?line eval(family_range(from_term([{{a},[]}])), from_term([{{a},[]}])), ?line eval(family_range(from_term([], type(FR))), from_term([], [{atom,[atom]}])), ?line {'EXIT', {badarg, _}} = (catch family_range(set([a]))), ?line {'EXIT', {badarg, _}} = (catch family_range(set([{a,[b]}]))), ok. family_to_relation_1(suite) -> []; family_to_relation_1(doc) -> [""]; family_to_relation_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line EF = family([]), ?line eval(family_to_relation(E), E), ?line eval(family_to_relation(EF), ER), ?line eval(sofs:fam2rel(EF), ER), ?line F = family([{a,[]},{b,[1]},{c,[7,9,11]}]), ?line eval(family_to_relation(F), relation([{b,1},{c,7},{c,9},{c,11}])), ?line {'EXIT', {badarg, _}} = (catch family_to_relation(set([a]))), ok. union_of_family_1(suite) -> []; union_of_family_1(doc) -> [""]; union_of_family_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = from_term([{a,[]},{b,[]}],[{atom,[atom]}]), ?line eval(union_of_family(E), E), ?line eval(union_of_family(EF), set([])), ?line eval(union_of_family(family([])), set([])), ?line FR = from_term([{a,[1,2,3]},{b,[]},{c,[4,5]}]), ?line eval(union_of_family(FR), set([1,2,3,4,5])), ?line eval(union_of_family(sofs:family([{a,[1,2]},{b,[1,2]}])), set([1,2])), ?line {'EXIT', {badarg, _}} = (catch union_of_family(set([a]))), ok. intersection_of_family_1(suite) -> []; intersection_of_family_1(doc) -> [""]; intersection_of_family_1(Conf) when list(Conf) -> ?line EF = from_term([{a,[]},{b,[]}],[{atom,[atom]}]), ?line eval(intersection_of_family(EF), set([])), ?line FR = from_term([{a,[1,2,3]},{b,[2,3]},{c,[3,4,5]}]), ?line eval(intersection_of_family(FR), set([3])), ?line {'EXIT', {badarg, _}} = (catch intersection_of_family(family([]))), ?line EE = from_term([], [[atom]]), ?line {'EXIT', {badarg, _}} = (catch intersection_of_family(EE)), ?line {'EXIT', {badarg, _}} = (catch intersection_of_family(set([a]))), ok. family_projection(suite) -> []; family_projection(doc) -> [""]; family_projection(Conf) when list(Conf) -> SSType = [{atom,[[atom]]}], SRType = [{atom,[{atom,atom}]}], ?line E = empty_set(), ?line eval(family_projection(fun(X) -> X end, family([])), E), ?line L1 = [{a,[]}], ?line eval(family_projection({sofs,union}, E), E), ?line eval(family_projection({sofs,union}, from_term(L1, SSType)), family(L1)), ?line {'EXIT', {badarg, _}} = (catch family_projection({sofs,union}, set([]))), ?line {'EXIT', {badarg, _}} = (catch family_projection({sofs,union}, from_term([{1,[1]}]))), ?line F2 = from_term([{a,[[1],[2]]},{b,[[3,4],[5]]}], SSType), ?line eval(family_projection({sofs,union}, F2), family_union(F2)), ?line F3 = from_term([{1,[{a,b},{b,c},{c,d}]},{3,[]},{5,[{3,5}]}], SRType), ?line eval(family_projection({sofs,domain}, F3), family_domain(F3)), ?line eval(family_projection({sofs,range}, F3), family_range(F3)), ?line eval(family_projection(fun(_) -> E end, family([{a,[b,c]}])), from_term([{a,[]}])), Fun1 = fun(S) -> case to_external(S) of [1] -> from_term({1,1}); _ -> S end end, ?line eval(family_projection(Fun1, family([{a,[1]}])), from_term([{a,{1,1}}])), Fun2 = fun(_) -> throw(fippla) end, ?line fippla = (catch family_projection(Fun2, family([{a,[1]}]))), ?line {'EXIT', {type_mismatch, _}} = (catch family_projection(Fun1, from_term([{1,[1]},{2,[2]}]))), ?line {'EXIT', {type_mismatch, _}} = (catch family_projection(Fun1, from_term([{1,[1]},{0,[0]}]))), ?line eval(family_projection(fun(_) -> E end, from_term([{a,[]}])), from_term([{a,[]}])), F4 = from_term([{a,[{1,2,3}]},{b,[{4,5,6}]},{c,[]},{m3,[]}]), Z = from_term(0), ?line eval(family_projection(fun(S) -> local_adjoin(S, Z) end, F4), from_term([{a,[{{1,2,3},0}]},{b,[{{4,5,6},0}]},{c,[]},{m3,[]}])), ?line {'EXIT', {badarg, _}} = (catch family_projection({external, fun(X) -> X end}, from_term([{1,[1]}]))), ?line eval(family_projection(fun(_) -> from_term(a, atom) end, from_term([{1,[a]}])), from_term([{1,a}])), ok. family_difference(suite) -> []; family_difference(doc) -> [""]; family_difference(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = family([]), ?line F9 = from_term([{b,[b,c]}]), ?line F10 = from_term([{a,[b,c]}]), ?line eval(family_difference(E, E), E), ?line eval(family_difference(E, F10), from_term([], type(F10))), ?line eval(family_difference(F10, E), F10), ?line eval(family_difference(F9, F10), F9), ?line eval(family_difference(F10, F10), family([{a,[]}])), ?line F20 = from_term([{a,[1,2,3]},{b,[1,2,3]},{c,[1,2,3]}]), ?line F21 = from_term([{b,[1,2,3]},{c,[1,2,3]}]), ?line eval(family_difference(F20, from_term([{a,[2]}])), from_term([{a,[1,3]},{b,[1,2,3]},{c,[1,2,3]}])), ?line eval(family_difference(F20, from_term([{0,[2]},{q,[1,2]}])), F20), ?line eval(family_difference(F20, F21), from_term([{a,[1,2,3]},{b,[]},{c,[]}])), ?line eval(family_difference(from_term([{e,[f,g]}]), family([])), from_term([{e,[f,g]}])), ?line eval(family_difference(from_term([{e,[f,g]}]), EF), from_term([{e,[f,g]}])), ?line eval(family_difference(from_term([{a,[a,b,c,d]},{c,[b,c]}]), from_term([{a,[b,c]},{b,[d]},{d,[e,f]}])), from_term([{a,[a,d]},{c,[b,c]}])), ?line {'EXIT', {badarg, _}} = (catch family_difference(set([]), set([]))), ?line {'EXIT', {type_mismatch, _}} = (catch family_difference(from_term([{a,[b,c]}]), from_term([{e,[{f}]}]))), ?line {'EXIT', {type_mismatch, _}} = (catch family_difference(from_term([{a,[b]}]), from_term([{c,[d]}], [{i,[s]}]))), ok. family_intersection_1(suite) -> []; family_intersection_1(doc) -> [""]; family_intersection_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = family([]), ?line ES = from_term([], [{atom,[[atom]]}]), ?line eval(family_intersection(E), E), ?line {'EXIT', {badarg, _}} = (catch family_intersection(EF)), ?line eval(family_intersection(ES), EF), ?line {'EXIT', {badarg, _}} = (catch family_intersection(set([]))), ?line {'EXIT', {badarg, _}} = (catch family_intersection(from_term([{a,[1,2]}]))), ?line F1 = from_term([{a,[[1],[2],[2,3]]},{b,[]},{c,[[4]]}]), ?line {'EXIT', {badarg, _}} = (catch family_intersection(F1)), ?line F2 = from_term([{b,[[1],[2],[2,3]]},{a,[]},{c,[[4]]}]), ?line {'EXIT', {badarg, _}} = (catch family_intersection(F2)), ?line F3 = from_term([{a,[[1,2,3],[2],[2,3]]},{c,[[4,5,6],[5,6,7]]}]), ?line eval(family_intersection(F3), family([{a,[2]},{c,[5,6]}])), ok. family_intersection_2(suite) -> []; family_intersection_2(doc) -> [""]; family_intersection_2(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = family([]), ?line F1 = from_term([{a,[1,2]},{b,[4,5]},{c,[7,8]},{d,[10,11]}]), ?line F2 = from_term([{c,[6,7]},{d,[9,10,11]},{q,[1]}]), ?line F3 = from_term([{a,[1,2]},{b,[4,5]},{c,[6,7,8]},{d,[9,10,11]}, {q,[1]}]), ?line eval(family_intersection(E, E), E), ?line eval(family_intersection(EF, EF), EF), ?line eval(family_intersection(F1, F2), from_term([{c,[7]},{d,[10,11]}])), ?line eval(family_intersection(F1, F3), F1), ?line eval(family_intersection(F2, F3), F2), ?line eval(family_intersection(EF, from_term([{e,[f,g]}])), EF), ?line eval(family_intersection(E, from_term([{e,[f,g]}])), EF), ?line eval(family_intersection(from_term([{e,[f,g]}]), EF), EF), ?line eval(family_intersection(from_term([{e,[f,g]}]), E), EF), ?line {'EXIT', {type_mismatch, _}} = (catch family_intersection(from_term([{a,[b,c]}]), from_term([{e,[{f}]}]))), ?line F11 = family([{a,[1,2,3]},{b,[0,2,4]},{c,[0,3,6,9]}]), ?line eval(union_of_family(F11), set([0,1,2,3,4,6,9])), ?line F12 = from_term([{a,[1,2,3,4]},{b,[0,2,4]},{c,[2,3,4,5]}]), ?line eval(intersection_of_family(F12), set([2,4])), ok. family_union_1(suite) -> []; family_union_1(doc) -> [""]; family_union_1(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = family([]), ?line ES = from_term([], [{atom,[[atom]]}]), ?line eval(family_union(E), E), ?line eval(family_union(ES), EF), ?line {'EXIT', {badarg, _}} = (catch family_union(set([]))), ?line {'EXIT', {badarg, _}} = (catch family_union(from_term([{a,[1,2]}]))), ?line eval(family_union(from_term([{a,[[1],[2],[2,3]]},{b,[]},{c,[[4]]}])), family([{a,[1,2,3]},{b,[]},{c,[4]}])), ok. family_union_2(suite) -> []; family_union_2(doc) -> [""]; family_union_2(Conf) when list(Conf) -> ?line E = empty_set(), ?line EF = family([]), ?line F1 = from_term([{a,[1,2]},{b,[4,5]},{c,[7,8]},{d,[10,11]}]), ?line F2 = from_term([{c,[6,7]},{d,[9,10,11]},{q,[1]}]), ?line F3 = from_term([{a,[1,2]},{b,[4,5]},{c,[6,7,8]},{d,[9,10,11]}, {q,[1]}]), ?line eval(family_union(E, E), E), ?line eval(family_union(F1, E), F1), ?line eval(family_union(E, F2), F2), ?line eval(family_union(F1, F2), F3), ?line eval(family_union(F2, F1), F3), ?line eval(family_union(E, from_term([{e,[f,g]}])), from_term([{e,[f,g]}])), ?line eval(family_union(EF, from_term([{e,[f,g]}])), from_term([{e,[f,g]}])), ?line eval(family_union(from_term([{e,[f,g]}]), E), from_term([{e,[f,g]}])), ?line {'EXIT', {badarg, _}} = (catch family_union(set([]),set([]))), ?line {'EXIT', {type_mismatch, _}} = (catch family_union(from_term([{a,[b,c]}]), from_term([{e,[{f}]}]))), ok. partition_family(suite) -> []; partition_family(doc) -> [""]; partition_family(Conf) when list(Conf) -> ?line E = empty_set(), ?line ER = relation([]), ?line EF = from_term([], [{atom,[{atom,atom}]}]), ?line eval(partition_family(1, E), E), ?line eval(partition_family(2, E), E), ?line eval(partition_family({sofs,union}, E), E), ?line eval(partition_family(1, ER), EF), ?line eval(partition_family(2, ER), EF), ?line {'EXIT', {badarg, _}} = (catch partition_family(1, set([]))), ?line {'EXIT', {badarg, _}} = (catch partition_family(2, set([]))), ?line {'EXIT', {function_clause, _}} = (catch partition_family(fun({_A,B}) -> {B} end, from_term([{1}]))), ?line eval(partition_family(1, relation([{1,a},{1,b},{2,c},{2,d}])), from_term([{1,[{1,a},{1,b}]},{2,[{2,c},{2,d}]}])), ?line eval(partition_family(1, relation([{1,a},{2,b}])), from_term([{1,[{1,a}]},{2,[{2,b}]}])), ?line eval(partition_family(2, relation([{1,a},{1,b},{2,a},{2,b},{3,c}])), from_term([{a,[{1,a},{2,a}]},{b,[{1,b},{2,b}]},{c,[{3,c}]}])), ?line eval(partition_family(2, relation([{1,a}])), from_term([{a,[{1,a}]}])), ?line eval(partition_family(2, relation([{1,a},{2,a},{3,a}])), from_term([{a,[{1,a},{2,a},{3,a}]}])), ?line eval(partition_family(2, relation([{1,a},{2,b}])), from_term([{a,[{1,a}]},{b,[{2,b}]}])), ?line F13 = from_term([{a,b,c},{a,b,d},{b,b,c},{a,c,c},{a,c,d},{b,c,c}]), ?line eval(partition_family(2, F13), from_term([{b,[{a,b,c},{a,b,d},{b,b,c}]}, {c,[{a,c,c},{a,c,d},{b,c,c}]}])), Fun1 = {external, fun({A,_B}) -> {A} end}, ?line eval(partition_family(Fun1, relation([{a,1},{a,2},{b,3}])), from_term([{{a},[{a,1},{a,2}]},{{b},[{b,3}]}])), Fun2 = fun(S) -> {A,_B} = to_external(S), from_term({A}) end, ?line eval(partition_family(Fun2, relation([{a,1},{a,2},{b,3}])), from_term([{{a},[{a,1},{a,2}]},{{b},[{b,3}]}])), ?line {'EXIT', {badarg, _}} = (catch partition_family({external, fun({A,_}) -> {A,0} end}, from_term([{1,a}]))), ?line [{{atom,atom},[{atom,atom,atom,atom}]}] = type(partition_family({external, fun({A,_B,C,_D}) -> {C,A} end}, relation([],4))), Fun3 = fun(S) -> from_term({to_external(S),0}, {type(S),atom}) end, ?line eval(partition_family(Fun3, E), E), ?line eval(partition_family(Fun3, set([a,b])), from_term([{{a,0},[a]}, {{b,0},[b]}])), ?line eval(partition_family(Fun3, relation([{a,1},{b,2}])), from_term([{{{a,1},0},[{a,1}]},{{{b,2},0},[{b,2}]}])), ?line eval(partition_family(Fun3, from_term([[a],[b]])), from_term([{{[a],0},[[a]]}, {{[b],0},[[b]]}])), ?line partition_family({external, fun(X) -> X end}, E), F = 0.0, I = round(F), ?line FR = relation([{I,a},{F,b}]), if ?line true = (1 =:= no_elements(partition_family(1, FR))); true -> ?line eval(partition_family(1, FR), from_term([{I,[{I,a}]},{F,[{F,b}]}])) end, ?line {'EXIT', {badarg, _}} = (catch partition_family({external, fun(X) -> X end}, from_term([], [[atom]]))), ?line {'EXIT', {badarg, _}} = (catch partition_family({external, fun(X) -> X end}, from_term([[a]]))), ?line eval(partition_family({sofs,union}, from_term([[[1],[1,2]], [[1,2]]])), from_term([{[1,2], [[[1],[1,2]],[[1,2]]]}])), ?line eval(partition_family(fun(X) -> X end, from_term([[1],[1,2],[1,2,3]])), from_term([{[1],[[1]]},{[1,2],[[1,2]]},{[1,2,3],[[1,2,3]]}])), ?line eval(partition_family(fun(_) -> from_term([a]) end, from_term([], [[atom]])), E), Fun10 = fun(S) -> case to_external(S) of [1] -> from_term({1,1}); _ -> S end end, ?line eval(partition_family(Fun10, from_term([[1]])), from_term([{{1,1},[[1]]}])), ?line eval(partition_family(fun(_) -> from_term({a}) end, from_term([[a]])), from_term([{{a},[[a]]}])), ?line {'EXIT', {badarg, _}} = (catch partition_family(fun(_) -> {a} end, from_term([[a]]))), ok. local_adjoin(S, C) -> X = to_external(C), T = type(C), F = fun(Y) -> from_term({to_external(Y),X}, {type(Y),T}) end, projection(F, S). eval(R, E) when R == E -> R; eval(R, E) -> io:format("expected ~p~n got ~p~n", [E, R]), exit({R,E}).
481c124efee79c03ba9de924dcfde8fd7781311653cf958983670ff090b5d481
unnohideyuki/bunny
sample163.hs
main = print [1, 2, 3]
null
https://raw.githubusercontent.com/unnohideyuki/bunny/501856ff48f14b252b674585f25a2bf3801cb185/compiler/test/samples/sample163.hs
haskell
main = print [1, 2, 3]
2593380a004d5fccf53d5e51dc9ba0e971a6c26d016cd1473922011015fc62a7
project-oak/hafnium-verification
Mleak_buckets.ml
* Copyright ( c ) 2009 - 2013 , Monoidics ltd . * Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) 2009-2013, Monoidics ltd. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd open PolyVariantEqual (** This module handles buckets of memory leaks in Objective-C/C++ *) let bucket_to_message bucket = match bucket with `MLeak_cpp -> "[CPP]" | `MLeak_unknown -> "[UNKNOWN ORIGIN]" let contains_cpp = List.mem ~equal:( = ) Config.ml_buckets `MLeak_cpp let contains_unknown_origin = List.mem ~equal:( = ) Config.ml_buckets `MLeak_unknown let should_raise_leak_unknown_origin = contains_unknown_origin let ml_bucket_unknown_origin = bucket_to_message `MLeak_unknown (* Returns whether a memory leak should be raised for a C++ object.*) (* If ml_buckets contains cpp, then check leaks from C++ objects. *) let should_raise_cpp_leak = if contains_cpp then Some (bucket_to_message `MLeak_cpp) else None
null
https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/IR/Mleak_buckets.ml
ocaml
* This module handles buckets of memory leaks in Objective-C/C++ Returns whether a memory leak should be raised for a C++ object. If ml_buckets contains cpp, then check leaks from C++ objects.
* Copyright ( c ) 2009 - 2013 , Monoidics ltd . * Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) 2009-2013, Monoidics ltd. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd open PolyVariantEqual let bucket_to_message bucket = match bucket with `MLeak_cpp -> "[CPP]" | `MLeak_unknown -> "[UNKNOWN ORIGIN]" let contains_cpp = List.mem ~equal:( = ) Config.ml_buckets `MLeak_cpp let contains_unknown_origin = List.mem ~equal:( = ) Config.ml_buckets `MLeak_unknown let should_raise_leak_unknown_origin = contains_unknown_origin let ml_bucket_unknown_origin = bucket_to_message `MLeak_unknown let should_raise_cpp_leak = if contains_cpp then Some (bucket_to_message `MLeak_cpp) else None
c94a627a8b864e6c049d50fc422cb2669e7a6707b24ce46906a59974c57d3aae
faylang/fay
SkipLetTypes.hs
module SkipLetType where main = let t :: Bool t = True in print t
null
https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/tests/SkipLetTypes.hs
haskell
module SkipLetType where main = let t :: Bool t = True in print t
c8f209f6585bf4bfe7beeddec68031c978fda94f860a300e2c6129d90ea421a2
scicloj/notespace
config.clj
(ns scicloj.notespace.v4.config) (def *config (atom {:debug? false :last-eval? true :summary? true :header? true :notebook? true :note-layout :vertical})) (defn set! [new-config] (reset! *config new-config)) (defn merge! [new-config] (swap! *config merge new-config))
null
https://raw.githubusercontent.com/scicloj/notespace/534b3ba08200a9227d6c362c8ce42cb2805595ca/src/scicloj/notespace/v4/config.clj
clojure
(ns scicloj.notespace.v4.config) (def *config (atom {:debug? false :last-eval? true :summary? true :header? true :notebook? true :note-layout :vertical})) (defn set! [new-config] (reset! *config new-config)) (defn merge! [new-config] (swap! *config merge new-config))
392f90f1404bce18e9cdcfb47052ccc9b30e7766609c7f62586acf07e1be264b
marcoonroad/twostep
api_interface.ml
open Alcotest module String = Base.String module TOTP = Twostep.TOTP module HOTP = Twostep.HOTP let _drop_spaces text = String.filter ~f:(( != ) ' ') text let _char_is_base32 char = char == 'A' || char == 'B' || char == 'C' || char == 'D' || char == 'E' || char == 'F' || char == 'G' || char == 'H' || char == 'I' || char == 'J' || char == 'K' || char == 'L' || char == 'M' || char == 'N' || char == 'O' || char == 'P' || char == 'Q' || char == 'R' || char == 'S' || char == 'T' || char == 'U' || char == 'V' || char == 'W' || char == 'X' || char == 'Y' || char == 'Z' || char == '2' || char == '3' || char == '4' || char == '5' || char == '6' || char == '7' let _is_base32 data = String.for_all ~f:_char_is_base32 @@ _drop_spaces data let _char_is_integer char = char == '0' || char == '1' || char == '2' || char == '3' || char == '4' || char == '5' || char == '6' || char == '7' || char == '8' || char == '9' let _is_integer data = String.for_all ~f:_char_is_integer data let __length_case () = let secret = TOTP.secret () in let no_spaces = _drop_spaces secret in let codeA = TOTP.code ~secret () in let codeB = TOTP.code ~secret ~digits:6 () in let codeC = TOTP.code ~secret ~digits:8 () in check int "secret w/ spaces must have 19 chars" (String.length secret) 19 ; check int "secret must contain 16 characters" (String.length no_spaces) 16 ; check int "code length must be 6 w/ default params" (String.length codeA) 6 ; check int "code length must be 6 w/ param digits=6" (String.length codeB) 6 ; check int "code length must be 8 w/ param digits=8" (String.length codeC) 8 let __format_case () = let secret = TOTP.secret () in let code6 = TOTP.code ~secret ~digits:6 () in let code8 = TOTP.code ~secret ~digits:8 () in check bool "secret must be under base-32" true @@ _is_base32 secret ; check bool "otp code w/ digits=6 must be int" true @@ _is_integer code6 ; check bool "otp code w/ digits=8 must be int" true @@ _is_integer code8 ; let procedure () = ignore @@ TOTP.code ~hash:"SHA-0" ~secret () in let failure = Failure "Invalid hash algorithm: SHA-0" in check_raises "otp code fails if hash is invalid" failure procedure ; let procedure () = ignore @@ TOTP.code ~secret:"ABCD E9FG H123 4567" () in let failure = Failure "Invalid base32 character: 9" in check_raises "otp code fails if secret is invalid" failure procedure ; ignore @@ TOTP.code ~secret:"ABCD EFGH IJKL MNOP" () ; ignore @@ TOTP.code ~secret:"QRST UVWX YZ23 4567" () let __secret_case () = let secret16 = _drop_spaces @@ TOTP.secret () in let secret24 = _drop_spaces @@ TOTP.secret ~bytes:15 () in let secret32 = _drop_spaces @@ TOTP.secret ~bytes:20 () in check int "10-bytes secret must contain 16 characters" (String.length secret16) 16 ; check int "15-bytes secret must contain 24 characters" (String.length secret24) 24 ; check int "20-bytes secret must contain 32 characters" (String.length secret32) 32 ; let procedure bytes () = ignore @@ TOTP.secret ~bytes () in let failureA = Failure "Invalid amount of bytes (8) for secret, it must be at least 10 and \ divisible by 5!" in let failureB = Failure "Invalid amount of bytes (12) for secret, it must be at least 10 and \ divisible by 5!" in let failureC = Failure "Invalid amount of bytes (19) for secret, it must be at least 10 and \ divisible by 5!" in check_raises "secret generation should fail when bytes = 8" failureA @@ procedure 8 ; check_raises "secret generation should fail when bytes = 12" failureB @@ procedure 12 ; check_raises "secret generation should fail when bytes = 19" failureC @@ procedure 19 let __verification_failure_case () = let secretA = TOTP.secret () in let secretB = TOTP.secret () in (****************************************************************************) let codeA0 = TOTP.code ~secret:secretA ~drift:(-3) () in let codeB0 = TOTP.code ~secret:secretB ~drift:(-3) () in let resultA0 = TOTP.verify ~secret:secretA ~code:codeA0 () in let resultB0 = TOTP.verify ~secret:secretB ~code:codeB0 () in let result0 = resultA0 || resultB0 in check bool "should not authenticate with codes too old" false result0 ; (****************************************************************************) let codeA1 = TOTP.code ~secret:secretA ~drift:3 () in let codeB1 = TOTP.code ~secret:secretB ~drift:3 () in let resultA1 = TOTP.verify ~secret:secretA ~code:codeA1 () in let resultB1 = TOTP.verify ~secret:secretB ~code:codeB1 () in let result1 = resultA1 || resultB1 in check bool "shouldn't pass codes on future" false result1 ; (****************************************************************************) let codeA = TOTP.code ~secret:secretA () in let codeB = TOTP.code ~secret:secretB () in let resultA = TOTP.verify ~secret:secretA ~code:codeB () in let resultB = TOTP.verify ~secret:secretB ~code:codeA () in let result = resultA || resultB in check bool "shouldn't pass codes from different secrets" false result let __verification_success_case () = let secret = TOTP.secret () in let code1 = TOTP.code ~secret ~drift:(-1) () in let code2 = TOTP.code ~secret ~drift:0 () in let code3 = TOTP.code ~secret ~drift:1 () in let result1 = TOTP.verify ~secret ~code:code1 () in let result2 = TOTP.verify ~secret ~code:code2 () in let result3 = TOTP.verify ~secret ~code:code3 () in let result = result1 && result2 && result3 in check bool "should authenticate with valid otp codes" true result let __hotp_resynch_case () = let secret = HOTP.secret () in let codes = HOTP.codes ~counter:0 ~secret () in let codes' = HOTP.codes ~counter:0 ~secret () in check (list string) "hotp code generation is deterministic" codes codes' ; let result = HOTP.verify ~counter:0 ~secret ~codes () in check bool "should pass verification flag with true" true @@ fst result ; check int "should increment counter as next one" 1 @@ snd result ; let secret = HOTP.secret ~bytes:15 () in let result = HOTP.verify ~counter:0 ~secret ~codes () in check bool "should fail verification flag with false" false @@ fst result ; check int "should not increment counter on failure" 0 @@ snd result ; let codes = HOTP.codes ~counter:7 ~amount:3 ~secret () in let result = HOTP.verify ~counter:4 ~ahead:6 ~secret ~codes () in check bool "should pass verification flag with true" true @@ fst result ; check int "should increment counter as next one" 10 @@ snd result ; let result = HOTP.verify ~counter:2 ~ahead:4 ~secret ~codes () in check bool "should fail verification flag with false" false @@ fst result ; check int "should not increment counter on failure" 2 @@ snd result let suite = [ ("secret and otp code length", `Quick, __length_case) ; ("secret-only length for custom bytes", `Quick, __secret_case) ; ("secret and otp code format", `Quick, __format_case) ; ("otp code verification failure", `Quick, __verification_failure_case) ; ("otp code verification success", `Quick, __verification_success_case) ; ("hotp counter resynchronization", `Quick, __hotp_resynch_case) ] let () = Mirage_crypto_rng_unix.initialize () ; run "Twostep tests" [ ("test suite", suite) ]
null
https://raw.githubusercontent.com/marcoonroad/twostep/090ce0dddbd2016b28bb145e3f8bcbea08ef60fc/test/api_interface.ml
ocaml
************************************************************************** ************************************************************************** **************************************************************************
open Alcotest module String = Base.String module TOTP = Twostep.TOTP module HOTP = Twostep.HOTP let _drop_spaces text = String.filter ~f:(( != ) ' ') text let _char_is_base32 char = char == 'A' || char == 'B' || char == 'C' || char == 'D' || char == 'E' || char == 'F' || char == 'G' || char == 'H' || char == 'I' || char == 'J' || char == 'K' || char == 'L' || char == 'M' || char == 'N' || char == 'O' || char == 'P' || char == 'Q' || char == 'R' || char == 'S' || char == 'T' || char == 'U' || char == 'V' || char == 'W' || char == 'X' || char == 'Y' || char == 'Z' || char == '2' || char == '3' || char == '4' || char == '5' || char == '6' || char == '7' let _is_base32 data = String.for_all ~f:_char_is_base32 @@ _drop_spaces data let _char_is_integer char = char == '0' || char == '1' || char == '2' || char == '3' || char == '4' || char == '5' || char == '6' || char == '7' || char == '8' || char == '9' let _is_integer data = String.for_all ~f:_char_is_integer data let __length_case () = let secret = TOTP.secret () in let no_spaces = _drop_spaces secret in let codeA = TOTP.code ~secret () in let codeB = TOTP.code ~secret ~digits:6 () in let codeC = TOTP.code ~secret ~digits:8 () in check int "secret w/ spaces must have 19 chars" (String.length secret) 19 ; check int "secret must contain 16 characters" (String.length no_spaces) 16 ; check int "code length must be 6 w/ default params" (String.length codeA) 6 ; check int "code length must be 6 w/ param digits=6" (String.length codeB) 6 ; check int "code length must be 8 w/ param digits=8" (String.length codeC) 8 let __format_case () = let secret = TOTP.secret () in let code6 = TOTP.code ~secret ~digits:6 () in let code8 = TOTP.code ~secret ~digits:8 () in check bool "secret must be under base-32" true @@ _is_base32 secret ; check bool "otp code w/ digits=6 must be int" true @@ _is_integer code6 ; check bool "otp code w/ digits=8 must be int" true @@ _is_integer code8 ; let procedure () = ignore @@ TOTP.code ~hash:"SHA-0" ~secret () in let failure = Failure "Invalid hash algorithm: SHA-0" in check_raises "otp code fails if hash is invalid" failure procedure ; let procedure () = ignore @@ TOTP.code ~secret:"ABCD E9FG H123 4567" () in let failure = Failure "Invalid base32 character: 9" in check_raises "otp code fails if secret is invalid" failure procedure ; ignore @@ TOTP.code ~secret:"ABCD EFGH IJKL MNOP" () ; ignore @@ TOTP.code ~secret:"QRST UVWX YZ23 4567" () let __secret_case () = let secret16 = _drop_spaces @@ TOTP.secret () in let secret24 = _drop_spaces @@ TOTP.secret ~bytes:15 () in let secret32 = _drop_spaces @@ TOTP.secret ~bytes:20 () in check int "10-bytes secret must contain 16 characters" (String.length secret16) 16 ; check int "15-bytes secret must contain 24 characters" (String.length secret24) 24 ; check int "20-bytes secret must contain 32 characters" (String.length secret32) 32 ; let procedure bytes () = ignore @@ TOTP.secret ~bytes () in let failureA = Failure "Invalid amount of bytes (8) for secret, it must be at least 10 and \ divisible by 5!" in let failureB = Failure "Invalid amount of bytes (12) for secret, it must be at least 10 and \ divisible by 5!" in let failureC = Failure "Invalid amount of bytes (19) for secret, it must be at least 10 and \ divisible by 5!" in check_raises "secret generation should fail when bytes = 8" failureA @@ procedure 8 ; check_raises "secret generation should fail when bytes = 12" failureB @@ procedure 12 ; check_raises "secret generation should fail when bytes = 19" failureC @@ procedure 19 let __verification_failure_case () = let secretA = TOTP.secret () in let secretB = TOTP.secret () in let codeA0 = TOTP.code ~secret:secretA ~drift:(-3) () in let codeB0 = TOTP.code ~secret:secretB ~drift:(-3) () in let resultA0 = TOTP.verify ~secret:secretA ~code:codeA0 () in let resultB0 = TOTP.verify ~secret:secretB ~code:codeB0 () in let result0 = resultA0 || resultB0 in check bool "should not authenticate with codes too old" false result0 ; let codeA1 = TOTP.code ~secret:secretA ~drift:3 () in let codeB1 = TOTP.code ~secret:secretB ~drift:3 () in let resultA1 = TOTP.verify ~secret:secretA ~code:codeA1 () in let resultB1 = TOTP.verify ~secret:secretB ~code:codeB1 () in let result1 = resultA1 || resultB1 in check bool "shouldn't pass codes on future" false result1 ; let codeA = TOTP.code ~secret:secretA () in let codeB = TOTP.code ~secret:secretB () in let resultA = TOTP.verify ~secret:secretA ~code:codeB () in let resultB = TOTP.verify ~secret:secretB ~code:codeA () in let result = resultA || resultB in check bool "shouldn't pass codes from different secrets" false result let __verification_success_case () = let secret = TOTP.secret () in let code1 = TOTP.code ~secret ~drift:(-1) () in let code2 = TOTP.code ~secret ~drift:0 () in let code3 = TOTP.code ~secret ~drift:1 () in let result1 = TOTP.verify ~secret ~code:code1 () in let result2 = TOTP.verify ~secret ~code:code2 () in let result3 = TOTP.verify ~secret ~code:code3 () in let result = result1 && result2 && result3 in check bool "should authenticate with valid otp codes" true result let __hotp_resynch_case () = let secret = HOTP.secret () in let codes = HOTP.codes ~counter:0 ~secret () in let codes' = HOTP.codes ~counter:0 ~secret () in check (list string) "hotp code generation is deterministic" codes codes' ; let result = HOTP.verify ~counter:0 ~secret ~codes () in check bool "should pass verification flag with true" true @@ fst result ; check int "should increment counter as next one" 1 @@ snd result ; let secret = HOTP.secret ~bytes:15 () in let result = HOTP.verify ~counter:0 ~secret ~codes () in check bool "should fail verification flag with false" false @@ fst result ; check int "should not increment counter on failure" 0 @@ snd result ; let codes = HOTP.codes ~counter:7 ~amount:3 ~secret () in let result = HOTP.verify ~counter:4 ~ahead:6 ~secret ~codes () in check bool "should pass verification flag with true" true @@ fst result ; check int "should increment counter as next one" 10 @@ snd result ; let result = HOTP.verify ~counter:2 ~ahead:4 ~secret ~codes () in check bool "should fail verification flag with false" false @@ fst result ; check int "should not increment counter on failure" 2 @@ snd result let suite = [ ("secret and otp code length", `Quick, __length_case) ; ("secret-only length for custom bytes", `Quick, __secret_case) ; ("secret and otp code format", `Quick, __format_case) ; ("otp code verification failure", `Quick, __verification_failure_case) ; ("otp code verification success", `Quick, __verification_success_case) ; ("hotp counter resynchronization", `Quick, __hotp_resynch_case) ] let () = Mirage_crypto_rng_unix.initialize () ; run "Twostep tests" [ ("test suite", suite) ]
790b90d1df1e4e4ffe91b470bf3b82d6ed7310a0ea0e77b4037fd49b6839e4e6
spectrum-finance/cardano-dex-sdk-haskell
Main.hs
module Main where import qualified Data.Text.Encoding as E import Test.Tasty import Test.Tasty.HUnit import Spec.Pool as PS main :: IO () main = do defaultMain tests tests = testGroup "DexCore" [ PS.toFromLedgerPoolTests , PS.checkDeposit , PS.checkRedeem , PS.checkSwap , PS.initialLiquidityTests , PS.initPoolTests ]
null
https://raw.githubusercontent.com/spectrum-finance/cardano-dex-sdk-haskell/c769f92aeb348b5fb7d6fb74a447fe18e9fadb38/dex-core/test/Main.hs
haskell
module Main where import qualified Data.Text.Encoding as E import Test.Tasty import Test.Tasty.HUnit import Spec.Pool as PS main :: IO () main = do defaultMain tests tests = testGroup "DexCore" [ PS.toFromLedgerPoolTests , PS.checkDeposit , PS.checkRedeem , PS.checkSwap , PS.initialLiquidityTests , PS.initPoolTests ]
f3be193d713eeeccaf408b54643cd025418a4f47a4416562ee10629a1f9c9a92
input-output-hk/cardano-sl
Block.hs
# LANGUAGE RecordWildCards # module Statistics.Block ( BlockHeader (..) , blockHeadersF , blockChain , blockChainF , txBlocksF , inBlockChainF , txCntInChainF , TxFate (..) , txFateF ) where import Control.Foldl (Fold (..), fold) import qualified Data.Map.Lazy as ML import qualified Data.Map.Strict as MS import Data.Maybe (fromJust, isJust) import qualified Data.Set as S import qualified Data.Text as T import Data.Time.Units (Microsecond) import JSONLog (IndexedJLTimedEvent (..)) import Pos.Infra.Util.JsonLog.Events (JLBlock (..), JLEvent (..)) import Prelude (id) import Statistics.Tx (txFirstReceivedF) import Types import Universum hiding (fold) data BlockHeader = BlockHeader { bhNode :: !NodeId , bhTimestamp :: !Timestamp , bhHash :: !BlockHash , bhPrevBlock :: !BlockHash , bhSlot :: !Slot , bhTxCnt :: !Int } deriving Show type SMap k a = MS.Map k a type LMap k a = ML.Map k a blockHeadersF :: Fold IndexedJLTimedEvent (SMap BlockHash BlockHeader) blockHeadersF = Fold step MS.empty id where step :: SMap Text BlockHeader -> IndexedJLTimedEvent -> SMap Text BlockHeader step m IndexedJLTimedEvent{..} = case ijlEvent of JLCreatedBlock JLBlock{..} -> let bh = BlockHeader { bhNode = ijlNode , bhTimestamp = ijlTimestamp , bhHash = jlHash , bhPrevBlock = jlPrevBlock , bhSlot = jlSlot , bhTxCnt = length jlTxs } in MS.insert jlHash bh m _ -> m blockChain :: SMap BlockHash BlockHeader -> Set BlockHash blockChain m = S.fromList $ maybe [] id $ (fmap fst . uncons) $ sortByLengthDesc [getLongestChain h | h <- allHashes] where allHashes :: [BlockHash] allHashes = MS.keys m sortByLengthDesc :: [[a]] -> [[a]] sortByLengthDesc = sortBy (compare `on` (negate . length)) successors :: SMap BlockHash [BlockHash] successors = foldl' f MS.empty allHashes getSuccessors :: BlockHash -> [BlockHash] getSuccessors h = MS.findWithDefault [] h successors f :: SMap BlockHash [BlockHash] -> BlockHash -> SMap BlockHash [BlockHash] f s h = let BlockHeader{..} = m MS.! h in MS.alter (Just . maybe [bhHash] (bhHash :)) bhPrevBlock s longestChains :: LMap Text [Text] longestChains = ML.fromList [(h, getLongestChain h) | h <- allHashes] getLongestChain :: Text -> [Text] getLongestChain h = case sortByLengthDesc $ map (longestChains ML.!) $ getSuccessors h of [] -> [h] (c : _) -> h : c blockChainF :: Fold IndexedJLTimedEvent (Set BlockHash) blockChainF = blockChain <$> blockHeadersF txBlocksF :: Fold IndexedJLTimedEvent (SMap TxHash [(Timestamp, BlockHash)]) txBlocksF = Fold step MS.empty id where step :: SMap Text [(Microsecond, Text)] -> IndexedJLTimedEvent -> SMap Text [(Microsecond, Text)] step m IndexedJLTimedEvent{..} = case ijlEvent of JLCreatedBlock JLBlock{..} -> foldl' (f ijlTimestamp jlHash) m [T.take 16 x | x <- jlTxs] _ -> m f :: Timestamp -> Text -> SMap Text [(Timestamp, Text)] -> Text -> SMap Text [(Timestamp, Text)] f ts h m tx = let y = (ts, h) in MS.alter (Just . maybe [y] (y :)) tx m inBlockChainF :: Fold IndexedJLTimedEvent (SMap TxHash Timestamp) inBlockChainF = f <$> txFateF where f :: SMap TxHash TxFate -> SMap TxHash Timestamp f = MS.map fromJust . MS.filter isJust . MS.map txInBlockChain txCntInChainF :: Fold IndexedJLTimedEvent [(NodeId, Timestamp, Int)] txCntInChainF = f <$> blockHeadersF <*> blockChainF where f :: Map BlockHash BlockHeader -> Set BlockHash -> [(NodeId, Timestamp, Int)] f m cs = [(bhNode, bhTimestamp, bhTxCnt) | (_, BlockHeader{..}) <- MS.toList m, bhHash `S.member` cs] data TxFate = InNoBlock | InBlockChain !Timestamp !BlockHash !(Set (Timestamp, BlockHash)) | InFork !(Set (Timestamp, BlockHash)) deriving Show txInBlockChain :: TxFate -> Maybe Timestamp txInBlockChain InNoBlock = Nothing txInBlockChain (InBlockChain ts _ _) = Just ts txInBlockChain (InFork _) = Nothing txFateF :: Fold IndexedJLTimedEvent (SMap TxHash TxFate) txFateF = f <$> txFirstReceivedF <*> txBlocksF <*> blockChainF where f :: SMap TxHash Timestamp -> SMap TxHash [(Timestamp, BlockHash)] -> Set BlockHash -> SMap TxHash TxFate f received blocks chain = MS.fromList [(tx, fate tx) | tx <- MS.keys received] where fate :: TxHash -> TxFate fate tx = case MS.lookup tx blocks of Nothing -> InNoBlock Just xs -> fold (Fold step (Nothing, S.empty) extract) xs step :: (Maybe (Timestamp, BlockHash), Set (Timestamp, BlockHash)) -> (Timestamp, BlockHash) -> (Maybe (Timestamp, BlockHash), Set (Timestamp, BlockHash)) step (Nothing, s) (ts, h) | S.member h chain = (Just (ts, h), s) | otherwise = (Nothing , S.insert (ts, h) s) step (p , s) q = (p , S.insert q s) extract :: (Maybe (Timestamp, BlockHash), Set (Timestamp, BlockHash)) -> TxFate extract (Nothing , s) = InFork s extract (Just (ts, h), s) = InBlockChain ts h s
null
https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/tools/post-mortem/src/Statistics/Block.hs
haskell
# LANGUAGE RecordWildCards # module Statistics.Block ( BlockHeader (..) , blockHeadersF , blockChain , blockChainF , txBlocksF , inBlockChainF , txCntInChainF , TxFate (..) , txFateF ) where import Control.Foldl (Fold (..), fold) import qualified Data.Map.Lazy as ML import qualified Data.Map.Strict as MS import Data.Maybe (fromJust, isJust) import qualified Data.Set as S import qualified Data.Text as T import Data.Time.Units (Microsecond) import JSONLog (IndexedJLTimedEvent (..)) import Pos.Infra.Util.JsonLog.Events (JLBlock (..), JLEvent (..)) import Prelude (id) import Statistics.Tx (txFirstReceivedF) import Types import Universum hiding (fold) data BlockHeader = BlockHeader { bhNode :: !NodeId , bhTimestamp :: !Timestamp , bhHash :: !BlockHash , bhPrevBlock :: !BlockHash , bhSlot :: !Slot , bhTxCnt :: !Int } deriving Show type SMap k a = MS.Map k a type LMap k a = ML.Map k a blockHeadersF :: Fold IndexedJLTimedEvent (SMap BlockHash BlockHeader) blockHeadersF = Fold step MS.empty id where step :: SMap Text BlockHeader -> IndexedJLTimedEvent -> SMap Text BlockHeader step m IndexedJLTimedEvent{..} = case ijlEvent of JLCreatedBlock JLBlock{..} -> let bh = BlockHeader { bhNode = ijlNode , bhTimestamp = ijlTimestamp , bhHash = jlHash , bhPrevBlock = jlPrevBlock , bhSlot = jlSlot , bhTxCnt = length jlTxs } in MS.insert jlHash bh m _ -> m blockChain :: SMap BlockHash BlockHeader -> Set BlockHash blockChain m = S.fromList $ maybe [] id $ (fmap fst . uncons) $ sortByLengthDesc [getLongestChain h | h <- allHashes] where allHashes :: [BlockHash] allHashes = MS.keys m sortByLengthDesc :: [[a]] -> [[a]] sortByLengthDesc = sortBy (compare `on` (negate . length)) successors :: SMap BlockHash [BlockHash] successors = foldl' f MS.empty allHashes getSuccessors :: BlockHash -> [BlockHash] getSuccessors h = MS.findWithDefault [] h successors f :: SMap BlockHash [BlockHash] -> BlockHash -> SMap BlockHash [BlockHash] f s h = let BlockHeader{..} = m MS.! h in MS.alter (Just . maybe [bhHash] (bhHash :)) bhPrevBlock s longestChains :: LMap Text [Text] longestChains = ML.fromList [(h, getLongestChain h) | h <- allHashes] getLongestChain :: Text -> [Text] getLongestChain h = case sortByLengthDesc $ map (longestChains ML.!) $ getSuccessors h of [] -> [h] (c : _) -> h : c blockChainF :: Fold IndexedJLTimedEvent (Set BlockHash) blockChainF = blockChain <$> blockHeadersF txBlocksF :: Fold IndexedJLTimedEvent (SMap TxHash [(Timestamp, BlockHash)]) txBlocksF = Fold step MS.empty id where step :: SMap Text [(Microsecond, Text)] -> IndexedJLTimedEvent -> SMap Text [(Microsecond, Text)] step m IndexedJLTimedEvent{..} = case ijlEvent of JLCreatedBlock JLBlock{..} -> foldl' (f ijlTimestamp jlHash) m [T.take 16 x | x <- jlTxs] _ -> m f :: Timestamp -> Text -> SMap Text [(Timestamp, Text)] -> Text -> SMap Text [(Timestamp, Text)] f ts h m tx = let y = (ts, h) in MS.alter (Just . maybe [y] (y :)) tx m inBlockChainF :: Fold IndexedJLTimedEvent (SMap TxHash Timestamp) inBlockChainF = f <$> txFateF where f :: SMap TxHash TxFate -> SMap TxHash Timestamp f = MS.map fromJust . MS.filter isJust . MS.map txInBlockChain txCntInChainF :: Fold IndexedJLTimedEvent [(NodeId, Timestamp, Int)] txCntInChainF = f <$> blockHeadersF <*> blockChainF where f :: Map BlockHash BlockHeader -> Set BlockHash -> [(NodeId, Timestamp, Int)] f m cs = [(bhNode, bhTimestamp, bhTxCnt) | (_, BlockHeader{..}) <- MS.toList m, bhHash `S.member` cs] data TxFate = InNoBlock | InBlockChain !Timestamp !BlockHash !(Set (Timestamp, BlockHash)) | InFork !(Set (Timestamp, BlockHash)) deriving Show txInBlockChain :: TxFate -> Maybe Timestamp txInBlockChain InNoBlock = Nothing txInBlockChain (InBlockChain ts _ _) = Just ts txInBlockChain (InFork _) = Nothing txFateF :: Fold IndexedJLTimedEvent (SMap TxHash TxFate) txFateF = f <$> txFirstReceivedF <*> txBlocksF <*> blockChainF where f :: SMap TxHash Timestamp -> SMap TxHash [(Timestamp, BlockHash)] -> Set BlockHash -> SMap TxHash TxFate f received blocks chain = MS.fromList [(tx, fate tx) | tx <- MS.keys received] where fate :: TxHash -> TxFate fate tx = case MS.lookup tx blocks of Nothing -> InNoBlock Just xs -> fold (Fold step (Nothing, S.empty) extract) xs step :: (Maybe (Timestamp, BlockHash), Set (Timestamp, BlockHash)) -> (Timestamp, BlockHash) -> (Maybe (Timestamp, BlockHash), Set (Timestamp, BlockHash)) step (Nothing, s) (ts, h) | S.member h chain = (Just (ts, h), s) | otherwise = (Nothing , S.insert (ts, h) s) step (p , s) q = (p , S.insert q s) extract :: (Maybe (Timestamp, BlockHash), Set (Timestamp, BlockHash)) -> TxFate extract (Nothing , s) = InFork s extract (Just (ts, h), s) = InBlockChain ts h s
f1482d928fb15220e0e3ea4fc3ac906fcfb160336829a8a54666811470cbf903
mstksg/backprop-learn
Combinator.hs
# LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE InstanceSigs # # LANGUAGE KindSignatures # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PatternSynonyms # {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} # LANGUAGE TupleSections # # LANGUAGE TypeApplications # {-# LANGUAGE TypeFamilies #-} # LANGUAGE TypeFamilyDependencies # {-# LANGUAGE TypeInType #-} {-# LANGUAGE TypeOperators #-} # LANGUAGE UndecidableInstances # {-# LANGUAGE ViewPatterns #-} module Backprop.Learn.Model.Combinator ( Chain(..) , (~++) , chainParamLength , chainStateLength , LearnFunc(..), learnFunc , LMap(..), RMap(..) , Dimap, pattern DM, _dmPre, _dmPost, _dmLearn , (.~) , nilLF, onlyLF , (:.~)(..) , (:&&&)(..) , KAutoencoder, kAutoencoder, kaeEncoder, kaeDecoder , Feedback(..), feedbackId , FeedbackTrace(..), feedbackTraceId ) where import Backprop.Learn.Model.Class import Backprop.Learn.Model.Function import Control.Applicative import Control.Category import Control.Monad import Control.Monad.Primitive import Control.Monad.Trans.State import Data.Bifunctor import Data.Kind import Data.Type.Equality import Data.Type.Length import Data.Type.Mayb as Mayb import Data.Type.NonEmpty import Data.Type.Tuple hiding (T2(..), T3(..)) import Data.Typeable import GHC.TypeNats import Numeric.Backprop import Numeric.LinearAlgebra.Static.Backprop import Prelude hiding ((.), id) import Type.Class.Known import Type.Class.Witness import Type.Family.List as List import qualified Data.Type.Tuple as T import qualified Data.Vector.Sized as SV import qualified System.Random.MWC as MWC -- | Chain components linearly, retaining the ability to deconstruct at -- a later time. data Chain :: [Type] -> Type -> Type -> Type where CNil :: Chain '[] a a (:~>) :: (Learn a b l, KnownMayb (LParamMaybe l), KnownMayb (LStateMaybe l)) => l -> Chain ls b c -> Chain (l ': ls) a c deriving (Typeable) infixr 5 :~> instance ( ListC (Backprop List.<$> LParams ls) , ListC (Backprop List.<$> LStates ls) ) => Learn a b (Chain ls a b) where type LParamMaybe (Chain ls a b) = NETup Mayb.<$> ToNonEmpty (LParams ls) type LStateMaybe (Chain ls a b) = NETup Mayb.<$> ToNonEmpty (LStates ls) runLearn = runChainLearn runLearnStoch = runChainLearnStoch runChainLearn :: (Reifies s W, ListC (Backprop List.<$> LParams ls), ListC (Backprop List.<$> LStates ls)) => Chain ls a b -> Mayb (BVar s) (NETup Mayb.<$> ToNonEmpty (LParams ls)) -> BVar s a -> Mayb (BVar s) (NETup Mayb.<$> ToNonEmpty (LStates ls)) -> (BVar s b, Mayb (BVar s) (NETup Mayb.<$> ToNonEmpty (LStates ls))) runChainLearn = \case CNil -> \_ x _ -> (x, N_) (l :: l) :~> ls -> let lenPs = chainParamLength ls lenSs = chainStateLength ls in case knownMayb @(LParamMaybe l) of N_ -> \ps x -> case knownMayb @(LStateMaybe l) of N_ -> \ss -> flip (runChainLearn ls ps) ss . runLearnStateless l N_ $ x J_ _ -> case lenSs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->s) -> let (y, J_ s') = runLearn l N_ x (J_ s) (z, _ ) = runChainLearn ls ps y N_ in (z, J_ $ isoVar (NETT . onlyT) (tOnly . netT) s') LS _ -> \case J_ ss -> lenSs // let (y, J_ s' ) = runLearn l N_ x (J_ (ss ^^. netHead)) ssTail = isoVar NETT netT $ ss ^^. netTail (z, J_ ss') = runChainLearn ls ps y (J_ ssTail) in (z, J_ $ isoVar2 NET unNet s' $ isoVar netT NETT ss') J_ _ -> case lenPs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->p) -> \x -> case knownMayb @(LStateMaybe l) of N_ -> \ss -> flip (runChainLearn ls N_) ss . runLearnStateless l (J_ p) $ x J_ _ -> case lenSs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->s) -> let (y, J_ s') = runLearn l (J_ p) x (J_ s) (z, _ ) = runChainLearn ls N_ y N_ in (z, J_ $ isoVar (NETT . onlyT) (tOnly . netT) s') LS _ -> \case J_ ss -> lenSs // let (y, J_ s' ) = runLearn l (J_ p) x (J_ (ss ^^. netHead)) ssTail = isoVar NETT netT $ ss ^^. netTail (z, J_ ss') = runChainLearn ls N_ y (J_ ssTail) in (z, J_ $ isoVar2 NET unNet s' $ isoVar netT NETT ss') LS _ -> \case J_ ps -> \x -> lenPs // let psHead = ps ^^. netHead psTail = isoVar NETT netT $ ps ^^. netTail in case knownMayb @(LStateMaybe l) of N_ -> \ss -> flip (runChainLearn ls (J_ psTail)) ss . runLearnStateless l (J_ psHead) $ x J_ _ -> case lenSs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->s) -> let (y, J_ s') = runLearn l (J_ psHead) x (J_ s) (z, _ ) = runChainLearn ls (J_ psTail) y N_ in (z, J_ $ isoVar (NETT . onlyT) (tOnly . netT) s') LS _ -> \case J_ ss -> lenSs // let (y, J_ s' ) = runLearn l (J_ psHead) x (J_ (ss ^^. netHead)) ssTail = isoVar NETT netT $ ss ^^. netTail (z, J_ ss') = runChainLearn ls (J_ psTail) y (J_ ssTail) in (z, J_ $ isoVar2 NET unNet s' $ isoVar netT NETT ss') runChainLearnStoch :: ( Reifies s W , ListC (Backprop List.<$> LParams ls) , ListC (Backprop List.<$> LStates ls) , PrimMonad m ) => Chain ls a b -> MWC.Gen (PrimState m) -> Mayb (BVar s) (NETup Mayb.<$> ToNonEmpty (LParams ls)) -> BVar s a -> Mayb (BVar s) (NETup Mayb.<$> ToNonEmpty (LStates ls)) -> m (BVar s b, Mayb (BVar s) (NETup Mayb.<$> ToNonEmpty (LStates ls))) runChainLearnStoch = \case CNil -> \_ _ x _ -> pure (x, N_) (l :: l) :~> ls -> \g -> let lenPs = chainParamLength ls lenSs = chainStateLength ls in case knownMayb @(LParamMaybe l) of N_ -> \ps x -> case knownMayb @(LStateMaybe l) of N_ -> \ss -> flip (runChainLearnStoch ls g ps) ss <=< runLearnStochStateless l g N_ $ x J_ _ -> case lenSs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->s) -> do (y, s') <- second fromJ_ <$> runLearnStoch l g N_ x (J_ s) (z, _ ) <- runChainLearnStoch ls g ps y N_ pure (z, J_ $ isoVar (NETT . onlyT) (tOnly . netT) s') LS _ -> \case J_ ss -> lenSs // do (y, s' ) <- second fromJ_ <$> runLearnStoch l g N_ x (J_ (ss ^^. netHead)) let ssTail = isoVar NETT netT $ ss ^^. netTail (z, ss') <- second fromJ_ <$> runChainLearnStoch ls g ps y (J_ ssTail) pure (z, J_ $ isoVar2 NET unNet s' $ isoVar netT NETT ss') J_ _ -> case lenPs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->p) -> \x -> case knownMayb @(LStateMaybe l) of N_ -> \ss -> flip (runChainLearnStoch ls g N_) ss <=< runLearnStochStateless l g (J_ p) $ x J_ _ -> case lenSs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->s) -> do (y, s') <- second fromJ_ <$> runLearnStoch l g (J_ p) x (J_ s) (z, _ ) <- runChainLearnStoch ls g N_ y N_ pure (z, J_ $ isoVar (NETT . onlyT) (tOnly . netT) s') LS _ -> \case J_ ss -> lenSs // do (y, s' ) <- second fromJ_ <$> runLearnStoch l g (J_ p) x (J_ (ss ^^. netHead)) let ssTail = isoVar NETT netT $ ss ^^. netTail (z, ss') <- second fromJ_ <$> runChainLearnStoch ls g N_ y (J_ ssTail) pure (z, J_ $ isoVar2 NET unNet s' $ isoVar netT NETT ss') LS _ -> \case J_ ps -> \x -> lenPs // let psHead = ps ^^. netHead psTail = isoVar NETT netT $ ps ^^. netTail in case knownMayb @(LStateMaybe l) of N_ -> \ss -> flip (runChainLearnStoch ls g (J_ psTail)) ss <=< runLearnStochStateless l g (J_ psHead) $ x J_ _ -> case lenSs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->s) -> do (y, s') <- second fromJ_ <$> runLearnStoch l g (J_ psHead) x (J_ s) (z, _ ) <- runChainLearnStoch ls g (J_ psTail) y N_ pure (z, J_ $ isoVar (NETT . onlyT) (tOnly . netT) s') LS _ -> \case J_ ss -> lenSs // do (y, s' ) <- second fromJ_ <$> runLearnStoch l g (J_ psHead) x (J_ (ss ^^. netHead)) let ssTail = isoVar NETT netT $ ss ^^. netTail (z, ss') <- second fromJ_ <$> runChainLearnStoch ls g (J_ psTail) y (J_ ssTail) pure (z, J_ $ isoVar2 NET unNet s' $ isoVar netT NETT ss') -- | Appending 'Chain' (~++) :: forall ls ms a b c. () => Chain ls a b -> Chain ms b c -> Chain (ls ++ ms) a c (~++) = \case CNil -> id (l :: l) :~> (ls :: Chain ls' a' b) -> case assocMaybAppend @(LParamMaybe l) @(LParams ls') @(LParams ms) known of Refl -> case assocMaybAppend @(LStateMaybe l) @(LStates ls') @(LStates ls) known of Refl -> \ms -> (l :~> (ls ~++ ms)) \\ appendLength (chainParamLength ls) (chainParamLength ms) \\ appendLength (chainStateLength ls) (chainStateLength ms) chainParamLength :: Chain ls a b -> Length (LParams ls) chainParamLength = \case CNil -> LZ (_ :: l) :~> ls -> case knownMayb @(LParamMaybe l) of N_ -> chainParamLength ls J_ _ -> LS $ chainParamLength ls chainStateLength :: Chain ls a b -> Length (LStates ls) chainStateLength = \case CNil -> LZ (_ :: l) :~> ls -> case knownMayb @(LStateMaybe l) of N_ -> chainStateLength ls J_ _ -> LS $ chainStateLength ls appendLength :: forall as bs. () => Length as -> Length bs -> Length (as ++ bs) appendLength LZ = id appendLength (LS l) = LS . appendLength l assocMaybAppend :: forall a bs cs. () => Mayb P a -> (MaybeToList a ++ (bs ++ cs)) :~: ((MaybeToList a ++ bs) ++ cs) assocMaybAppend = \case N_ -> Refl J_ _ -> Refl -- | Data type representing trainable models. -- -- Useful for performant composition, but you lose the ability to decompose -- parts. data LearnFunc :: Maybe Type -> Maybe Type -> Type -> Type -> Type where LF :: { _lfRunLearn :: forall q. Reifies q W => Mayb (BVar q) p -> BVar q a -> Mayb (BVar q) s -> (BVar q b, Mayb (BVar q) s) , _lfRunLearnStoch :: forall m q. (PrimMonad m, Reifies q W) => MWC.Gen (PrimState m) -> Mayb (BVar q) p -> BVar q a -> Mayb (BVar q) s -> m (BVar q b, Mayb (BVar q) s) } -> LearnFunc p s a b deriving (Typeable) learnFunc :: Learn a b l => l -> LearnFunc (LParamMaybe l) (LStateMaybe l) a b learnFunc l = LF { _lfRunLearn = runLearn l , _lfRunLearnStoch = runLearnStoch l } instance Learn a b (LearnFunc p s a b) where type LParamMaybe (LearnFunc p s a b) = p type LStateMaybe (LearnFunc p s a b) = s runLearn = _lfRunLearn runLearnStoch = _lfRunLearnStoch instance Category (LearnFunc p s) where id = LF { _lfRunLearn = \_ -> (,) , _lfRunLearnStoch = \_ _ x -> pure . (x,) } f . g = LF { _lfRunLearn = \p x s0 -> let (y, s1) = _lfRunLearn g p x s0 in _lfRunLearn f p y s1 , _lfRunLearnStoch = \gen p x s0 -> do (y, s1) <- _lfRunLearnStoch g gen p x s0 _lfRunLearnStoch f gen p y s1 } | Compose two ' LearnFunc ' on lists . (.~) :: forall ps qs ss ts a b c. ( ListC (Backprop List.<$> ps) , ListC (Backprop List.<$> qs) , ListC (Backprop List.<$> ss) , ListC (Backprop List.<$> ts) , ListC (Backprop List.<$> (ss ++ ts)) , Known Length ps , Known Length ss , Known Length ts ) => LearnFunc ('Just (T ps )) ('Just (T ss )) b c -> LearnFunc ('Just (T qs )) ('Just (T ts )) a b -> LearnFunc ('Just (T (ps ++ qs))) ('Just (T (ss ++ ts ))) a c f .~ g = LF { _lfRunLearn = \(J_ psqs) x (J_ ssts) -> appendLength @ss @ts known known // let (y, J_ ts) = _lfRunLearn g (J_ (psqs ^^. tDrop @ps @qs known)) x (J_ (ssts ^^. tDrop @ss @ts known)) (z, J_ ss) = _lfRunLearn f (J_ (psqs ^^. tTake @ps @qs known)) y (J_ (ssts ^^. tTake @ss @ts known)) in (z, J_ $ isoVar2 (tAppend @ss @ts) (tSplit @ss @ts known) ss ts ) , _lfRunLearnStoch = \gen (J_ psqs) x (J_ ssts) -> appendLength @ss @ts known known // do (y, ts) <- second fromJ_ <$> _lfRunLearnStoch g gen (J_ (psqs ^^. tDrop @ps @qs known)) x (J_ (ssts ^^. tDrop @ss @ts known)) (z, ss) <- second fromJ_ <$> _lfRunLearnStoch f gen (J_ (psqs ^^. tTake @ps @qs known)) y (J_ (ssts ^^. tTake @ss @ts known)) pure (z, J_ $ isoVar2 (tAppend @ss @ts) (tSplit @ss @ts known) ss ts ) } | Identity of ' .~ ' nilLF :: LearnFunc ('Just (T '[])) ('Just (T '[])) a a nilLF = id | ' LearnFunc ' with singleton lists ; meant to be used with ' .~ ' onlyLF :: forall p s a b. (KnownMayb p, MaybeC Backprop p, KnownMayb s, MaybeC Backprop s) => LearnFunc p s a b -> LearnFunc ('Just (T (MaybeToList p))) ('Just (T (MaybeToList s))) a b onlyLF f = LF { _lfRunLearn = \(J_ ps) x ssM@(J_ ss) -> case knownMayb @p of N_ -> case knownMayb @s of N_ -> (second . const) ssM $ _lfRunLearn f N_ x N_ J_ _ -> second (J_ . isoVar onlyT tOnly . fromJ_) $ _lfRunLearn f N_ x (J_ (isoVar tOnly onlyT ss)) J_ _ -> let p = isoVar tOnly onlyT ps in case knownMayb @s of N_ -> (second . const) ssM $ _lfRunLearn f (J_ p) x N_ J_ _ -> second (J_ . isoVar onlyT tOnly . fromJ_) $ _lfRunLearn f (J_ p) x (J_ (isoVar tOnly onlyT ss)) , _lfRunLearnStoch = \g (J_ ps) x ssM@(J_ ss) -> case knownMayb @p of N_ -> case knownMayb @s of N_ -> (fmap . second . const) ssM $ _lfRunLearnStoch f g N_ x N_ J_ _ -> (fmap . second) (J_ . isoVar onlyT tOnly . fromJ_) $ _lfRunLearnStoch f g N_ x (J_ (isoVar tOnly onlyT ss)) J_ _ -> let p = isoVar tOnly onlyT ps in case knownMayb @s of N_ -> (fmap . second . const) ssM $ _lfRunLearnStoch f g (J_ p) x N_ J_ _ -> (fmap . second) (J_ . isoVar onlyT tOnly . fromJ_) $ _lfRunLearnStoch f g (J_ p) x (J_ (isoVar tOnly onlyT ss)) } | Compose two layers sequentially -- -- Note that this composes in the opposite order of '.' and ':.:', for -- consistency with the rest of the library. -- The basic autoencoder is simply @l ' : .~ ' m@ , where @'Learn ' a b l@ and @'Learn ' b a m@. However , for sparse autoencoder , look at -- 'Autoencoder'. data (:.~) :: Type -> Type -> Type where (:.~) :: l -> m -> l :.~ m infixr 5 :.~ instance ( Learn a b l , Learn b c m , KnownMayb (LParamMaybe l) , KnownMayb (LParamMaybe m) , KnownMayb (LStateMaybe l) , KnownMayb (LStateMaybe m) , MaybeC Backprop (LParamMaybe l) , MaybeC Backprop (LParamMaybe m) , MaybeC Backprop (LStateMaybe l) , MaybeC Backprop (LStateMaybe m) ) => Learn a c (l :.~ m) where type LParamMaybe (l :.~ m) = TupMaybe (LParamMaybe l) (LParamMaybe m) type LStateMaybe (l :.~ m) = TupMaybe (LStateMaybe l) (LStateMaybe m) runLearn (l :.~ m) pq x st = (z, tupMaybe T2B s' t') where (p, q) = splitTupMaybe @_ @(LParamMaybe l) @(LParamMaybe m) (\(T2B v u) -> (v, u)) pq (s, t) = splitTupMaybe @_ @(LStateMaybe l) @(LStateMaybe m) (\(T2B v u) -> (v, u)) st (y, s') = runLearn l p x s (z, t') = runLearn m q y t runLearnStoch (l :.~ m) g pq x st = do (y, s') <- runLearnStoch l g p x s (z, t') <- runLearnStoch m g q y t pure (z, tupMaybe T2B s' t') where (p, q) = splitTupMaybe @_ @(LParamMaybe l) @(LParamMaybe m) (\(T2B v u) -> (v, u)) pq (s, t) = splitTupMaybe @_ @(LStateMaybe l) @(LStateMaybe m) (\(T2B v u) -> (v, u)) st -- | Pre-compose a pure parameterless function to a model. -- An @'LMap ' b a@ takes a model from @b@ and turns it into a model from data LMap :: Type -> Type -> Type -> Type where LM :: { _lmPre :: forall s. Reifies s W => BVar s a -> BVar s b , _lmLearn :: l } -> LMap b a l -- | Post-compose a pure parameterless function to a model. -- An @'Rmap ' b c@ takes a model returning @b@ and turns it into a model returning data RMap :: Type -> Type -> Type -> Type where RM :: { _rmPost :: forall s. Reifies s W => BVar s b -> BVar s c , _rmLearn :: l } -> RMap b c l -- | Pre- and post-compose pure parameterless functions to a model. -- A @'Dimap ' b c a d@ takes a model from @b@ to @c@ and turns it into a model from @a@ to -- -- @ instance ' Learn ' b c = > Learn a d ( ' Dimap ' b c a d l ) where -- type 'LParamMaybe' (Dimap b c a d l) = LParamMaybe l -- type 'LStateMaybe' (Dimap b c a d l) = LStateMaybe l -- @ type Dimap b c a d l = RMap c d (LMap b a l) | Constructor for ' Dimap ' pattern DM :: (forall s. Reifies s W => BVar s a -> BVar s b) -> (forall s. Reifies s W => BVar s c -> BVar s d) -> l -> Dimap b c a d l pattern DM { _dmPre, _dmPost, _dmLearn } = RM _dmPost (LM _dmPre _dmLearn) instance Learn b c l => Learn a c (LMap b a l) where type LParamMaybe (LMap b a l) = LParamMaybe l type LStateMaybe (LMap b a l) = LStateMaybe l runLearn (LM f l) p x = runLearn l p (f x) runLearnStoch (LM f l) g p x = runLearnStoch l g p (f x) instance Learn a b l => Learn a c (RMap b c l) where type LParamMaybe (RMap b c l) = LParamMaybe l type LStateMaybe (RMap b c l) = LStateMaybe l runLearn (RM f l) p x = first f . runLearn l p x runLearnStoch (RM f l) g p x = (fmap . first) f . runLearnStoch l g p x -- | Take a model and turn it into a model that runs its output into itself -- several times, returning the final result. Parameterized by the number -- of repeats, and the function to process the output to become the next -- input. -- -- I don't know why anyone would ever want this. -- -- See 'FeedbackTrace' if you want to observe all of the intermediate -- outputs. data Feedback :: Type -> Type -> Type -> Type where FB :: { _fbTimes :: Int , _fbFeed :: forall s. Reifies s W => BVar s b -> BVar s a , _fbLearn :: l } -> Feedback a b l deriving (Typeable) -- | Construct a 'Feedback' from an endofunction (a function that returns -- a value fo the same type as its input) by simply providing the output -- directly as the next intput. feedbackId :: Int -> l -> Feedback a a l feedbackId n = FB n id instance Learn a b l => Learn a b (Feedback a b l) where type LParamMaybe (Feedback a b l) = LParamMaybe l type LStateMaybe (Feedback a b l) = LStateMaybe l runLearn (FB n f l) p = runState . foldr (>=>) go (replicate (n - 1) (fmap f . go)) where go = state . runLearn l p runLearnStoch (FB n f l) g p = runStateT . foldr (>=>) go (replicate (n - 1) (fmap f . go)) where go = StateT . runLearnStoch l g p -- | Take a model and turn it into a model that runs its output into itself -- several times, and returns all of the intermediate outputs. -- Parameterized by the function to process the output to become the next -- input. -- -- See 'Feedback' if you only need the final result. -- Compare also to ' Unroll ' . data FeedbackTrace :: Nat -> Type -> Type -> Type -> Type where FBT :: { _fbtFeed :: forall s. Reifies s W => BVar s b -> BVar s a , _fbtLearn :: l } -> FeedbackTrace n a b l deriving (Typeable) -- | Construct a 'FeedbackTrace' from an endofunction (a function that -- returns a value fo the same type as its input) by simply providing the -- output directly as the next intput. feedbackTraceId :: l -> FeedbackTrace n a a l feedbackTraceId = FBT id instance (Learn a b l, KnownNat n, Backprop b) => Learn a (ABP (SV.Vector n) b) (FeedbackTrace n a b l) where type LParamMaybe (FeedbackTrace n a b l) = LParamMaybe l type LStateMaybe (FeedbackTrace n a b l) = LStateMaybe l runLearn (FBT f l) p x0 = second snd . runState (collectVar . ABP <$> SV.replicateM (state go)) . (x0,) where go (x, s) = (y, (f y, s')) where (y, s') = runLearn l p x s runLearnStoch (FBT f l) g p x0 = (fmap . second) snd . runStateT (collectVar . ABP <$> SV.replicateM (StateT go)) . (x0,) where go (x, s) = do (y, s') <- runLearnStoch l g p x s pure (y, (f y, s')) | " Fork"/"Fan out " two models from the same input . Useful for data (:&&&) :: Type -> Type -> Type where (:&&&) :: l -> m -> l :&&& m infixr 3 :&&& instance ( Learn a b l , Learn a c m , KnownMayb (LParamMaybe l) , KnownMayb (LParamMaybe m) , KnownMayb (LStateMaybe l) , KnownMayb (LStateMaybe m) , MaybeC Backprop (LParamMaybe l) , MaybeC Backprop (LParamMaybe m) , MaybeC Backprop (LStateMaybe l) , MaybeC Backprop (LStateMaybe m) , Backprop b , Backprop c ) => Learn a (T.T2 b c) (l :&&& m) where type LParamMaybe (l :&&& m) = TupMaybe (LParamMaybe l) (LParamMaybe m) type LStateMaybe (l :&&& m) = TupMaybe (LStateMaybe l) (LStateMaybe m) runLearn (l :&&& m) pq x st = ( T2B y z , tupMaybe T2B s' t' ) where (p, q) = splitTupMaybe @_ @(LParamMaybe l) @(LParamMaybe m) (\(T2B v u) -> (v, u)) pq (s, t) = splitTupMaybe @_ @(LStateMaybe l) @(LStateMaybe m) (\(T2B v u) -> (v, u)) st (y, s') = runLearn l p x s (z, t') = runLearn m q x t runLearnStoch (l :&&& m) g pq x st = do (y, s') <- runLearnStoch l g p x s (z, t') <- runLearnStoch m g q x t pure ( T2B y z , tupMaybe T2B s' t' ) where (p, q) = splitTupMaybe @_ @(LParamMaybe l) @(LParamMaybe m) (\(T2B v u) -> (v, u)) pq (s, t) = splitTupMaybe @_ @(LStateMaybe l) @(LStateMaybe m) (\(T2B v u) -> (v, u)) st | K - sparse autoencoder . A normal autoencoder is simply @l ' : .~ ' m@ ; -- however a k-sparse autoencoder attempts to ensure that the encoding has about @k@ active components for every input . -- -- <-learning-sparse-autoencoders> -- -- @ -- instance ('Learn' a ('R' n) l, Learn (R n) a m) => Learn a a ('KAutoencoder' n l m) where type ' LParamMaybe ' ( ' KAutoencoder ' n l m ) = ' TupMaybe ' ( LParamMaybe l ) ( ) type ' LStateMaybe ' ( ' KAutoencoder ' n l m ) = ' TupMaybe ' ( LStateMaybe l ) ( ) -- @ -- -- To "encode" after training this, get the encoder with 'kaeEncoder'. type KAutoencoder n l m = RMap (R n) (R n) l :.~ m -- | Construct a 'KAutoencoder'. -- Note that this only has a ' Learn ' instance of @l@ outputs @'R ' n@ and -- @m@ takes @'R' n@. Also, for this to be an actual autoencoder, the input of @l@ has to be the same as the output of @m@. kAutoencoder :: KnownNat n => l -> m -> Int -> KAutoencoder n l m kAutoencoder l m k = RM (kSparse k) l :.~ m kaeEncoder :: KAutoencoder n l m -> l kaeEncoder (RM _ l :.~ _) = l kaeDecoder :: KAutoencoder n l m -> m kaeDecoder (_ :.~ m) = m -- TODO: KL-divergence autoencoders, a la -- </>. -- -- | Simple /sparse/ autoencoder that outputs the average activation of -- -- a vector encoding as well as the result. -- -- -- The traditional autoencoder is simply @l ' : .~ ' m@. However , the enforce -- -- sparsity, you have to also be able to observe the average activation of -- -- your encoding for your loss function (typically 'klDivergence' for -- -- Kullback-Leibler divergence) -- -- -- -- See </>. -- -- -- -- @ -- -- instance ('Learn' a ('R' n) l, Learn (R n) a l, 1 '<=' n) => Learn a ('T2' 'Double' a) where -- type ' LParamMaybe ' ( ' Autoencoder ' n l m ) = ' TupMaybe ' ( LParamMaybe l ) ( ) -- type ' LStateMaybe ' ( ' Autoencoder ' n l m ) = ' TupMaybe ' ( LStateMaybe l ) ( ) -- -- @ -- -- -- To /use/ the autoencoder after training it , just pattern match on ' AE ' -- -- or use '_aeEncode' (or '_aeDecode') type Autoencoder n l m = l : .~ ( FixedFunc ( R n ) Double : & & & m ) -- -- -- | Construct an 'Autoencoder' by giving the encoder and decoder. pattern AE : : ( Learn a ( R n ) l , Learn ( R n ) a m , 1 < = n , KnownNat n ) -- => l -- ^ '_aeEncode' -- -> m -- ^ '_aeDecode' -- -> Autoencoder n l m -- pattern AE { _aeEncode, _aeDecode } <- _aeEncode :.~ (_ :&&& _aeDecode) -- where AE e d = e : .~ ( FF mean : & & & d )
null
https://raw.githubusercontent.com/mstksg/backprop-learn/59aea530a0fad45de6d18b9a723914d1d66dc222/old2/src/Backprop/Learn/Model/Combinator.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DataKinds # # LANGUAGE DeriveDataTypeable # # LANGUAGE FlexibleContexts # # LANGUAGE GADTs # # LANGUAGE RankNTypes # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeInType # # LANGUAGE TypeOperators # # LANGUAGE ViewPatterns # | Chain components linearly, retaining the ability to deconstruct at a later time. | Appending 'Chain' | Data type representing trainable models. Useful for performant composition, but you lose the ability to decompose parts. Note that this composes in the opposite order of '.' and ':.:', for consistency with the rest of the library. 'Autoencoder'. | Pre-compose a pure parameterless function to a model. | Post-compose a pure parameterless function to a model. | Pre- and post-compose pure parameterless functions to a model. @ type 'LParamMaybe' (Dimap b c a d l) = LParamMaybe l type 'LStateMaybe' (Dimap b c a d l) = LStateMaybe l @ | Take a model and turn it into a model that runs its output into itself several times, returning the final result. Parameterized by the number of repeats, and the function to process the output to become the next input. I don't know why anyone would ever want this. See 'FeedbackTrace' if you want to observe all of the intermediate outputs. | Construct a 'Feedback' from an endofunction (a function that returns a value fo the same type as its input) by simply providing the output directly as the next intput. | Take a model and turn it into a model that runs its output into itself several times, and returns all of the intermediate outputs. Parameterized by the function to process the output to become the next input. See 'Feedback' if you only need the final result. | Construct a 'FeedbackTrace' from an endofunction (a function that returns a value fo the same type as its input) by simply providing the output directly as the next intput. however a k-sparse autoencoder attempts to ensure that the encoding has <-learning-sparse-autoencoders> @ instance ('Learn' a ('R' n) l, Learn (R n) a m) => Learn a a ('KAutoencoder' n l m) where @ To "encode" after training this, get the encoder with 'kaeEncoder'. | Construct a 'KAutoencoder'. @m@ takes @'R' n@. Also, for this to be an actual autoencoder, the TODO: KL-divergence autoencoders, a la </>. -- | Simple /sparse/ autoencoder that outputs the average activation of -- a vector encoding as well as the result. -- The traditional autoencoder is simply @l ' : .~ ' m@. However , the enforce -- sparsity, you have to also be able to observe the average activation of -- your encoding for your loss function (typically 'klDivergence' for -- Kullback-Leibler divergence) -- -- See </>. -- -- @ -- instance ('Learn' a ('R' n) l, Learn (R n) a l, 1 '<=' n) => Learn a ('T2' 'Double' a) where type ' LParamMaybe ' ( ' Autoencoder ' n l m ) = ' TupMaybe ' ( LParamMaybe l ) ( ) type ' LStateMaybe ' ( ' Autoencoder ' n l m ) = ' TupMaybe ' ( LStateMaybe l ) ( ) -- @ -- To /use/ the autoencoder after training it , just pattern match on ' AE ' -- or use '_aeEncode' (or '_aeDecode') -- | Construct an 'Autoencoder' by giving the encoder and decoder. => l -- ^ '_aeEncode' -> m -- ^ '_aeDecode' -> Autoencoder n l m pattern AE { _aeEncode, _aeDecode } <- _aeEncode :.~ (_ :&&& _aeDecode) where
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE FlexibleInstances # # LANGUAGE InstanceSigs # # LANGUAGE KindSignatures # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PatternSynonyms # # LANGUAGE TupleSections # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilyDependencies # # LANGUAGE UndecidableInstances # module Backprop.Learn.Model.Combinator ( Chain(..) , (~++) , chainParamLength , chainStateLength , LearnFunc(..), learnFunc , LMap(..), RMap(..) , Dimap, pattern DM, _dmPre, _dmPost, _dmLearn , (.~) , nilLF, onlyLF , (:.~)(..) , (:&&&)(..) , KAutoencoder, kAutoencoder, kaeEncoder, kaeDecoder , Feedback(..), feedbackId , FeedbackTrace(..), feedbackTraceId ) where import Backprop.Learn.Model.Class import Backprop.Learn.Model.Function import Control.Applicative import Control.Category import Control.Monad import Control.Monad.Primitive import Control.Monad.Trans.State import Data.Bifunctor import Data.Kind import Data.Type.Equality import Data.Type.Length import Data.Type.Mayb as Mayb import Data.Type.NonEmpty import Data.Type.Tuple hiding (T2(..), T3(..)) import Data.Typeable import GHC.TypeNats import Numeric.Backprop import Numeric.LinearAlgebra.Static.Backprop import Prelude hiding ((.), id) import Type.Class.Known import Type.Class.Witness import Type.Family.List as List import qualified Data.Type.Tuple as T import qualified Data.Vector.Sized as SV import qualified System.Random.MWC as MWC data Chain :: [Type] -> Type -> Type -> Type where CNil :: Chain '[] a a (:~>) :: (Learn a b l, KnownMayb (LParamMaybe l), KnownMayb (LStateMaybe l)) => l -> Chain ls b c -> Chain (l ': ls) a c deriving (Typeable) infixr 5 :~> instance ( ListC (Backprop List.<$> LParams ls) , ListC (Backprop List.<$> LStates ls) ) => Learn a b (Chain ls a b) where type LParamMaybe (Chain ls a b) = NETup Mayb.<$> ToNonEmpty (LParams ls) type LStateMaybe (Chain ls a b) = NETup Mayb.<$> ToNonEmpty (LStates ls) runLearn = runChainLearn runLearnStoch = runChainLearnStoch runChainLearn :: (Reifies s W, ListC (Backprop List.<$> LParams ls), ListC (Backprop List.<$> LStates ls)) => Chain ls a b -> Mayb (BVar s) (NETup Mayb.<$> ToNonEmpty (LParams ls)) -> BVar s a -> Mayb (BVar s) (NETup Mayb.<$> ToNonEmpty (LStates ls)) -> (BVar s b, Mayb (BVar s) (NETup Mayb.<$> ToNonEmpty (LStates ls))) runChainLearn = \case CNil -> \_ x _ -> (x, N_) (l :: l) :~> ls -> let lenPs = chainParamLength ls lenSs = chainStateLength ls in case knownMayb @(LParamMaybe l) of N_ -> \ps x -> case knownMayb @(LStateMaybe l) of N_ -> \ss -> flip (runChainLearn ls ps) ss . runLearnStateless l N_ $ x J_ _ -> case lenSs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->s) -> let (y, J_ s') = runLearn l N_ x (J_ s) (z, _ ) = runChainLearn ls ps y N_ in (z, J_ $ isoVar (NETT . onlyT) (tOnly . netT) s') LS _ -> \case J_ ss -> lenSs // let (y, J_ s' ) = runLearn l N_ x (J_ (ss ^^. netHead)) ssTail = isoVar NETT netT $ ss ^^. netTail (z, J_ ss') = runChainLearn ls ps y (J_ ssTail) in (z, J_ $ isoVar2 NET unNet s' $ isoVar netT NETT ss') J_ _ -> case lenPs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->p) -> \x -> case knownMayb @(LStateMaybe l) of N_ -> \ss -> flip (runChainLearn ls N_) ss . runLearnStateless l (J_ p) $ x J_ _ -> case lenSs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->s) -> let (y, J_ s') = runLearn l (J_ p) x (J_ s) (z, _ ) = runChainLearn ls N_ y N_ in (z, J_ $ isoVar (NETT . onlyT) (tOnly . netT) s') LS _ -> \case J_ ss -> lenSs // let (y, J_ s' ) = runLearn l (J_ p) x (J_ (ss ^^. netHead)) ssTail = isoVar NETT netT $ ss ^^. netTail (z, J_ ss') = runChainLearn ls N_ y (J_ ssTail) in (z, J_ $ isoVar2 NET unNet s' $ isoVar netT NETT ss') LS _ -> \case J_ ps -> \x -> lenPs // let psHead = ps ^^. netHead psTail = isoVar NETT netT $ ps ^^. netTail in case knownMayb @(LStateMaybe l) of N_ -> \ss -> flip (runChainLearn ls (J_ psTail)) ss . runLearnStateless l (J_ psHead) $ x J_ _ -> case lenSs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->s) -> let (y, J_ s') = runLearn l (J_ psHead) x (J_ s) (z, _ ) = runChainLearn ls (J_ psTail) y N_ in (z, J_ $ isoVar (NETT . onlyT) (tOnly . netT) s') LS _ -> \case J_ ss -> lenSs // let (y, J_ s' ) = runLearn l (J_ psHead) x (J_ (ss ^^. netHead)) ssTail = isoVar NETT netT $ ss ^^. netTail (z, J_ ss') = runChainLearn ls (J_ psTail) y (J_ ssTail) in (z, J_ $ isoVar2 NET unNet s' $ isoVar netT NETT ss') runChainLearnStoch :: ( Reifies s W , ListC (Backprop List.<$> LParams ls) , ListC (Backprop List.<$> LStates ls) , PrimMonad m ) => Chain ls a b -> MWC.Gen (PrimState m) -> Mayb (BVar s) (NETup Mayb.<$> ToNonEmpty (LParams ls)) -> BVar s a -> Mayb (BVar s) (NETup Mayb.<$> ToNonEmpty (LStates ls)) -> m (BVar s b, Mayb (BVar s) (NETup Mayb.<$> ToNonEmpty (LStates ls))) runChainLearnStoch = \case CNil -> \_ _ x _ -> pure (x, N_) (l :: l) :~> ls -> \g -> let lenPs = chainParamLength ls lenSs = chainStateLength ls in case knownMayb @(LParamMaybe l) of N_ -> \ps x -> case knownMayb @(LStateMaybe l) of N_ -> \ss -> flip (runChainLearnStoch ls g ps) ss <=< runLearnStochStateless l g N_ $ x J_ _ -> case lenSs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->s) -> do (y, s') <- second fromJ_ <$> runLearnStoch l g N_ x (J_ s) (z, _ ) <- runChainLearnStoch ls g ps y N_ pure (z, J_ $ isoVar (NETT . onlyT) (tOnly . netT) s') LS _ -> \case J_ ss -> lenSs // do (y, s' ) <- second fromJ_ <$> runLearnStoch l g N_ x (J_ (ss ^^. netHead)) let ssTail = isoVar NETT netT $ ss ^^. netTail (z, ss') <- second fromJ_ <$> runChainLearnStoch ls g ps y (J_ ssTail) pure (z, J_ $ isoVar2 NET unNet s' $ isoVar netT NETT ss') J_ _ -> case lenPs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->p) -> \x -> case knownMayb @(LStateMaybe l) of N_ -> \ss -> flip (runChainLearnStoch ls g N_) ss <=< runLearnStochStateless l g (J_ p) $ x J_ _ -> case lenSs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->s) -> do (y, s') <- second fromJ_ <$> runLearnStoch l g (J_ p) x (J_ s) (z, _ ) <- runChainLearnStoch ls g N_ y N_ pure (z, J_ $ isoVar (NETT . onlyT) (tOnly . netT) s') LS _ -> \case J_ ss -> lenSs // do (y, s' ) <- second fromJ_ <$> runLearnStoch l g (J_ p) x (J_ (ss ^^. netHead)) let ssTail = isoVar NETT netT $ ss ^^. netTail (z, ss') <- second fromJ_ <$> runChainLearnStoch ls g N_ y (J_ ssTail) pure (z, J_ $ isoVar2 NET unNet s' $ isoVar netT NETT ss') LS _ -> \case J_ ps -> \x -> lenPs // let psHead = ps ^^. netHead psTail = isoVar NETT netT $ ps ^^. netTail in case knownMayb @(LStateMaybe l) of N_ -> \ss -> flip (runChainLearnStoch ls g (J_ psTail)) ss <=< runLearnStochStateless l g (J_ psHead) $ x J_ _ -> case lenSs of LZ -> \case J_ (isoVar (tOnly . netT) (NETT . onlyT)->s) -> do (y, s') <- second fromJ_ <$> runLearnStoch l g (J_ psHead) x (J_ s) (z, _ ) <- runChainLearnStoch ls g (J_ psTail) y N_ pure (z, J_ $ isoVar (NETT . onlyT) (tOnly . netT) s') LS _ -> \case J_ ss -> lenSs // do (y, s' ) <- second fromJ_ <$> runLearnStoch l g (J_ psHead) x (J_ (ss ^^. netHead)) let ssTail = isoVar NETT netT $ ss ^^. netTail (z, ss') <- second fromJ_ <$> runChainLearnStoch ls g (J_ psTail) y (J_ ssTail) pure (z, J_ $ isoVar2 NET unNet s' $ isoVar netT NETT ss') (~++) :: forall ls ms a b c. () => Chain ls a b -> Chain ms b c -> Chain (ls ++ ms) a c (~++) = \case CNil -> id (l :: l) :~> (ls :: Chain ls' a' b) -> case assocMaybAppend @(LParamMaybe l) @(LParams ls') @(LParams ms) known of Refl -> case assocMaybAppend @(LStateMaybe l) @(LStates ls') @(LStates ls) known of Refl -> \ms -> (l :~> (ls ~++ ms)) \\ appendLength (chainParamLength ls) (chainParamLength ms) \\ appendLength (chainStateLength ls) (chainStateLength ms) chainParamLength :: Chain ls a b -> Length (LParams ls) chainParamLength = \case CNil -> LZ (_ :: l) :~> ls -> case knownMayb @(LParamMaybe l) of N_ -> chainParamLength ls J_ _ -> LS $ chainParamLength ls chainStateLength :: Chain ls a b -> Length (LStates ls) chainStateLength = \case CNil -> LZ (_ :: l) :~> ls -> case knownMayb @(LStateMaybe l) of N_ -> chainStateLength ls J_ _ -> LS $ chainStateLength ls appendLength :: forall as bs. () => Length as -> Length bs -> Length (as ++ bs) appendLength LZ = id appendLength (LS l) = LS . appendLength l assocMaybAppend :: forall a bs cs. () => Mayb P a -> (MaybeToList a ++ (bs ++ cs)) :~: ((MaybeToList a ++ bs) ++ cs) assocMaybAppend = \case N_ -> Refl J_ _ -> Refl data LearnFunc :: Maybe Type -> Maybe Type -> Type -> Type -> Type where LF :: { _lfRunLearn :: forall q. Reifies q W => Mayb (BVar q) p -> BVar q a -> Mayb (BVar q) s -> (BVar q b, Mayb (BVar q) s) , _lfRunLearnStoch :: forall m q. (PrimMonad m, Reifies q W) => MWC.Gen (PrimState m) -> Mayb (BVar q) p -> BVar q a -> Mayb (BVar q) s -> m (BVar q b, Mayb (BVar q) s) } -> LearnFunc p s a b deriving (Typeable) learnFunc :: Learn a b l => l -> LearnFunc (LParamMaybe l) (LStateMaybe l) a b learnFunc l = LF { _lfRunLearn = runLearn l , _lfRunLearnStoch = runLearnStoch l } instance Learn a b (LearnFunc p s a b) where type LParamMaybe (LearnFunc p s a b) = p type LStateMaybe (LearnFunc p s a b) = s runLearn = _lfRunLearn runLearnStoch = _lfRunLearnStoch instance Category (LearnFunc p s) where id = LF { _lfRunLearn = \_ -> (,) , _lfRunLearnStoch = \_ _ x -> pure . (x,) } f . g = LF { _lfRunLearn = \p x s0 -> let (y, s1) = _lfRunLearn g p x s0 in _lfRunLearn f p y s1 , _lfRunLearnStoch = \gen p x s0 -> do (y, s1) <- _lfRunLearnStoch g gen p x s0 _lfRunLearnStoch f gen p y s1 } | Compose two ' LearnFunc ' on lists . (.~) :: forall ps qs ss ts a b c. ( ListC (Backprop List.<$> ps) , ListC (Backprop List.<$> qs) , ListC (Backprop List.<$> ss) , ListC (Backprop List.<$> ts) , ListC (Backprop List.<$> (ss ++ ts)) , Known Length ps , Known Length ss , Known Length ts ) => LearnFunc ('Just (T ps )) ('Just (T ss )) b c -> LearnFunc ('Just (T qs )) ('Just (T ts )) a b -> LearnFunc ('Just (T (ps ++ qs))) ('Just (T (ss ++ ts ))) a c f .~ g = LF { _lfRunLearn = \(J_ psqs) x (J_ ssts) -> appendLength @ss @ts known known // let (y, J_ ts) = _lfRunLearn g (J_ (psqs ^^. tDrop @ps @qs known)) x (J_ (ssts ^^. tDrop @ss @ts known)) (z, J_ ss) = _lfRunLearn f (J_ (psqs ^^. tTake @ps @qs known)) y (J_ (ssts ^^. tTake @ss @ts known)) in (z, J_ $ isoVar2 (tAppend @ss @ts) (tSplit @ss @ts known) ss ts ) , _lfRunLearnStoch = \gen (J_ psqs) x (J_ ssts) -> appendLength @ss @ts known known // do (y, ts) <- second fromJ_ <$> _lfRunLearnStoch g gen (J_ (psqs ^^. tDrop @ps @qs known)) x (J_ (ssts ^^. tDrop @ss @ts known)) (z, ss) <- second fromJ_ <$> _lfRunLearnStoch f gen (J_ (psqs ^^. tTake @ps @qs known)) y (J_ (ssts ^^. tTake @ss @ts known)) pure (z, J_ $ isoVar2 (tAppend @ss @ts) (tSplit @ss @ts known) ss ts ) } | Identity of ' .~ ' nilLF :: LearnFunc ('Just (T '[])) ('Just (T '[])) a a nilLF = id | ' LearnFunc ' with singleton lists ; meant to be used with ' .~ ' onlyLF :: forall p s a b. (KnownMayb p, MaybeC Backprop p, KnownMayb s, MaybeC Backprop s) => LearnFunc p s a b -> LearnFunc ('Just (T (MaybeToList p))) ('Just (T (MaybeToList s))) a b onlyLF f = LF { _lfRunLearn = \(J_ ps) x ssM@(J_ ss) -> case knownMayb @p of N_ -> case knownMayb @s of N_ -> (second . const) ssM $ _lfRunLearn f N_ x N_ J_ _ -> second (J_ . isoVar onlyT tOnly . fromJ_) $ _lfRunLearn f N_ x (J_ (isoVar tOnly onlyT ss)) J_ _ -> let p = isoVar tOnly onlyT ps in case knownMayb @s of N_ -> (second . const) ssM $ _lfRunLearn f (J_ p) x N_ J_ _ -> second (J_ . isoVar onlyT tOnly . fromJ_) $ _lfRunLearn f (J_ p) x (J_ (isoVar tOnly onlyT ss)) , _lfRunLearnStoch = \g (J_ ps) x ssM@(J_ ss) -> case knownMayb @p of N_ -> case knownMayb @s of N_ -> (fmap . second . const) ssM $ _lfRunLearnStoch f g N_ x N_ J_ _ -> (fmap . second) (J_ . isoVar onlyT tOnly . fromJ_) $ _lfRunLearnStoch f g N_ x (J_ (isoVar tOnly onlyT ss)) J_ _ -> let p = isoVar tOnly onlyT ps in case knownMayb @s of N_ -> (fmap . second . const) ssM $ _lfRunLearnStoch f g (J_ p) x N_ J_ _ -> (fmap . second) (J_ . isoVar onlyT tOnly . fromJ_) $ _lfRunLearnStoch f g (J_ p) x (J_ (isoVar tOnly onlyT ss)) } | Compose two layers sequentially The basic autoencoder is simply @l ' : .~ ' m@ , where @'Learn ' a b l@ and @'Learn ' b a m@. However , for sparse autoencoder , look at data (:.~) :: Type -> Type -> Type where (:.~) :: l -> m -> l :.~ m infixr 5 :.~ instance ( Learn a b l , Learn b c m , KnownMayb (LParamMaybe l) , KnownMayb (LParamMaybe m) , KnownMayb (LStateMaybe l) , KnownMayb (LStateMaybe m) , MaybeC Backprop (LParamMaybe l) , MaybeC Backprop (LParamMaybe m) , MaybeC Backprop (LStateMaybe l) , MaybeC Backprop (LStateMaybe m) ) => Learn a c (l :.~ m) where type LParamMaybe (l :.~ m) = TupMaybe (LParamMaybe l) (LParamMaybe m) type LStateMaybe (l :.~ m) = TupMaybe (LStateMaybe l) (LStateMaybe m) runLearn (l :.~ m) pq x st = (z, tupMaybe T2B s' t') where (p, q) = splitTupMaybe @_ @(LParamMaybe l) @(LParamMaybe m) (\(T2B v u) -> (v, u)) pq (s, t) = splitTupMaybe @_ @(LStateMaybe l) @(LStateMaybe m) (\(T2B v u) -> (v, u)) st (y, s') = runLearn l p x s (z, t') = runLearn m q y t runLearnStoch (l :.~ m) g pq x st = do (y, s') <- runLearnStoch l g p x s (z, t') <- runLearnStoch m g q y t pure (z, tupMaybe T2B s' t') where (p, q) = splitTupMaybe @_ @(LParamMaybe l) @(LParamMaybe m) (\(T2B v u) -> (v, u)) pq (s, t) = splitTupMaybe @_ @(LStateMaybe l) @(LStateMaybe m) (\(T2B v u) -> (v, u)) st An @'LMap ' b a@ takes a model from @b@ and turns it into a model from data LMap :: Type -> Type -> Type -> Type where LM :: { _lmPre :: forall s. Reifies s W => BVar s a -> BVar s b , _lmLearn :: l } -> LMap b a l An @'Rmap ' b c@ takes a model returning @b@ and turns it into a model returning data RMap :: Type -> Type -> Type -> Type where RM :: { _rmPost :: forall s. Reifies s W => BVar s b -> BVar s c , _rmLearn :: l } -> RMap b c l A @'Dimap ' b c a d@ takes a model from @b@ to @c@ and turns it into a model from @a@ to instance ' Learn ' b c = > Learn a d ( ' Dimap ' b c a d l ) where type Dimap b c a d l = RMap c d (LMap b a l) | Constructor for ' Dimap ' pattern DM :: (forall s. Reifies s W => BVar s a -> BVar s b) -> (forall s. Reifies s W => BVar s c -> BVar s d) -> l -> Dimap b c a d l pattern DM { _dmPre, _dmPost, _dmLearn } = RM _dmPost (LM _dmPre _dmLearn) instance Learn b c l => Learn a c (LMap b a l) where type LParamMaybe (LMap b a l) = LParamMaybe l type LStateMaybe (LMap b a l) = LStateMaybe l runLearn (LM f l) p x = runLearn l p (f x) runLearnStoch (LM f l) g p x = runLearnStoch l g p (f x) instance Learn a b l => Learn a c (RMap b c l) where type LParamMaybe (RMap b c l) = LParamMaybe l type LStateMaybe (RMap b c l) = LStateMaybe l runLearn (RM f l) p x = first f . runLearn l p x runLearnStoch (RM f l) g p x = (fmap . first) f . runLearnStoch l g p x data Feedback :: Type -> Type -> Type -> Type where FB :: { _fbTimes :: Int , _fbFeed :: forall s. Reifies s W => BVar s b -> BVar s a , _fbLearn :: l } -> Feedback a b l deriving (Typeable) feedbackId :: Int -> l -> Feedback a a l feedbackId n = FB n id instance Learn a b l => Learn a b (Feedback a b l) where type LParamMaybe (Feedback a b l) = LParamMaybe l type LStateMaybe (Feedback a b l) = LStateMaybe l runLearn (FB n f l) p = runState . foldr (>=>) go (replicate (n - 1) (fmap f . go)) where go = state . runLearn l p runLearnStoch (FB n f l) g p = runStateT . foldr (>=>) go (replicate (n - 1) (fmap f . go)) where go = StateT . runLearnStoch l g p Compare also to ' Unroll ' . data FeedbackTrace :: Nat -> Type -> Type -> Type -> Type where FBT :: { _fbtFeed :: forall s. Reifies s W => BVar s b -> BVar s a , _fbtLearn :: l } -> FeedbackTrace n a b l deriving (Typeable) feedbackTraceId :: l -> FeedbackTrace n a a l feedbackTraceId = FBT id instance (Learn a b l, KnownNat n, Backprop b) => Learn a (ABP (SV.Vector n) b) (FeedbackTrace n a b l) where type LParamMaybe (FeedbackTrace n a b l) = LParamMaybe l type LStateMaybe (FeedbackTrace n a b l) = LStateMaybe l runLearn (FBT f l) p x0 = second snd . runState (collectVar . ABP <$> SV.replicateM (state go)) . (x0,) where go (x, s) = (y, (f y, s')) where (y, s') = runLearn l p x s runLearnStoch (FBT f l) g p x0 = (fmap . second) snd . runStateT (collectVar . ABP <$> SV.replicateM (StateT go)) . (x0,) where go (x, s) = do (y, s') <- runLearnStoch l g p x s pure (y, (f y, s')) | " Fork"/"Fan out " two models from the same input . Useful for data (:&&&) :: Type -> Type -> Type where (:&&&) :: l -> m -> l :&&& m infixr 3 :&&& instance ( Learn a b l , Learn a c m , KnownMayb (LParamMaybe l) , KnownMayb (LParamMaybe m) , KnownMayb (LStateMaybe l) , KnownMayb (LStateMaybe m) , MaybeC Backprop (LParamMaybe l) , MaybeC Backprop (LParamMaybe m) , MaybeC Backprop (LStateMaybe l) , MaybeC Backprop (LStateMaybe m) , Backprop b , Backprop c ) => Learn a (T.T2 b c) (l :&&& m) where type LParamMaybe (l :&&& m) = TupMaybe (LParamMaybe l) (LParamMaybe m) type LStateMaybe (l :&&& m) = TupMaybe (LStateMaybe l) (LStateMaybe m) runLearn (l :&&& m) pq x st = ( T2B y z , tupMaybe T2B s' t' ) where (p, q) = splitTupMaybe @_ @(LParamMaybe l) @(LParamMaybe m) (\(T2B v u) -> (v, u)) pq (s, t) = splitTupMaybe @_ @(LStateMaybe l) @(LStateMaybe m) (\(T2B v u) -> (v, u)) st (y, s') = runLearn l p x s (z, t') = runLearn m q x t runLearnStoch (l :&&& m) g pq x st = do (y, s') <- runLearnStoch l g p x s (z, t') <- runLearnStoch m g q x t pure ( T2B y z , tupMaybe T2B s' t' ) where (p, q) = splitTupMaybe @_ @(LParamMaybe l) @(LParamMaybe m) (\(T2B v u) -> (v, u)) pq (s, t) = splitTupMaybe @_ @(LStateMaybe l) @(LStateMaybe m) (\(T2B v u) -> (v, u)) st | K - sparse autoencoder . A normal autoencoder is simply @l ' : .~ ' m@ ; about @k@ active components for every input . type ' LParamMaybe ' ( ' KAutoencoder ' n l m ) = ' TupMaybe ' ( LParamMaybe l ) ( ) type ' LStateMaybe ' ( ' KAutoencoder ' n l m ) = ' TupMaybe ' ( LStateMaybe l ) ( ) type KAutoencoder n l m = RMap (R n) (R n) l :.~ m Note that this only has a ' Learn ' instance of @l@ outputs @'R ' n@ and input of @l@ has to be the same as the output of @m@. kAutoencoder :: KnownNat n => l -> m -> Int -> KAutoencoder n l m kAutoencoder l m k = RM (kSparse k) l :.~ m kaeEncoder :: KAutoencoder n l m -> l kaeEncoder (RM _ l :.~ _) = l kaeDecoder :: KAutoencoder n l m -> m kaeDecoder (_ :.~ m) = m type Autoencoder n l m = l : .~ ( FixedFunc ( R n ) Double : & & & m ) pattern AE : : ( Learn a ( R n ) l , Learn ( R n ) a m , 1 < = n , KnownNat n ) AE e d = e : .~ ( FF mean : & & & d )
93b91b11c7470beff80e5504358946ba5e20927eef8ae1d9edd2bc71dd09cce4
avsm/platform
opamEnv.ml
(**************************************************************************) (* *) Copyright 2012 - 2015 OCamlPro Copyright 2012 INRIA (* *) (* All rights reserved. This file is distributed under the terms of the *) GNU Lesser General Public License version 2.1 , with the special (* exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) open OpamTypes open OpamStateTypes open OpamTypesBase open OpamStd.Op open OpamFilename.Op let log fmt = OpamConsole.log "ENV" fmt let slog = OpamConsole.slog (* - Environment and updates handling - *) let split_var v = OpamStd.Sys.split_path_variable ~clean:false v let join_var l = String.concat (String.make 1 OpamStd.Sys.path_sep) l To allow in - place updates , we store intermediate values of path - like as a pair of list [ ( rl1 , l2 ) ] such that the value is [ rl1 l2 ] and the place where the new value should be inserted is in front of [ l2 ] pair of list [(rl1, l2)] such that the value is [List.rev_append rl1 l2] and the place where the new value should be inserted is in front of [l2] *) let unzip_to elt = let rec aux acc = function | [] -> None | x::r -> if x = elt then Some (acc, r) else aux (x::acc) r in aux [] let rezip ?insert (l1, l2) = List.rev_append l1 (match insert with None -> l2 | Some i -> i::l2) let rezip_to_string ?insert z = join_var (rezip ?insert z) let apply_op_zip op arg (rl1,l2 as zip) = let colon_eq ?(eqcol=false) = function (* prepend a, but keep ":"s *) | [] | [""] -> [], [arg; ""] | "" :: l -> (* keep surrounding colons *) if eqcol then l@[""], [arg] else l, [""; arg] | l -> l, [arg] in match op with | Eq -> [],[arg] | PlusEq -> [], arg :: rezip zip | EqPlus -> List.rev_append l2 rl1, [arg] | EqPlusEq -> rl1, arg::l2 | ColonEq -> let l, add = colon_eq (rezip zip) in [], add @ l | EqColon -> let l, add = colon_eq ~eqcol:true (List.rev_append l2 rl1) in l, List.rev add (** Undoes previous updates done by opam, useful for not duplicating already done updates; this is obviously not perfect, as all operators are not reversible. [cur_value] is provided as a list split at path_sep. None is returned if the revert doesn't match. Otherwise, a zip (pair of lists [(preceding_elements_reverted, following_elements)]) is returned, to keep the position of the matching element and allow [=+=] to be applied later. A pair or empty lists is returned if the variable should be unset or has an unknown previous value. *) let reverse_env_update op arg cur_value = match op with | Eq -> if arg = join_var cur_value then Some ([],[]) else None | PlusEq | EqPlusEq -> unzip_to arg cur_value | EqPlus -> (match unzip_to arg (List.rev cur_value) with | None -> None | Some (rl1, l2) -> Some (List.rev l2, List.rev rl1)) | ColonEq -> (match unzip_to arg cur_value with | Some ([], [""]) -> Some ([], []) | r -> r) | EqColon -> (match unzip_to arg (List.rev cur_value) with | Some ([], [""]) -> Some ([], []) | Some (rl1, l2) -> Some (List.rev l2, List.rev rl1) | None -> None) let updates_from_previous_instance = lazy ( match OpamStd.Env.getopt "OPAM_SWITCH_PREFIX" with | None -> None | Some pfx -> let env_file = OpamPath.Switch.env_relative_to_prefix (OpamFilename.Dir.of_string pfx) in try OpamFile.Environment.read_opt env_file with e -> OpamStd.Exn.fatal e; None ) let expand (updates: env_update list) : env = (* Reverse all previous updates, in reverse order, on current environment *) let reverts = match Lazy.force updates_from_previous_instance with | None -> [] | Some updates -> List.fold_right (fun (var, op, arg, _) defs0 -> let v_opt, defs = OpamStd.List.pick_assoc var defs0 in let v = OpamStd.Option.Op.((v_opt >>| rezip >>+ fun () -> OpamStd.Env.getopt var >>| split_var) +! []) in match reverse_env_update op arg v with | Some v -> (var, v)::defs | None -> defs0) updates [] in (* And apply the new ones *) let rec apply_updates reverts acc = function | (var, op, arg, doc) :: updates -> let zip, reverts = let f, var = if Sys.win32 then String.uppercase_ascii, String.uppercase_ascii var else (fun x -> x), var in match OpamStd.List.find_opt (fun (v, _, _) -> f v = var) acc with | Some (_, z, _doc) -> z, reverts | None -> match OpamStd.List.pick_assoc var reverts with | Some z, reverts -> z, reverts | None, _ -> match OpamStd.Env.getopt var with | Some s -> ([], split_var s), reverts | None -> ([], []), reverts in apply_updates reverts ((var, apply_op_zip op arg zip, doc) :: acc) updates | [] -> List.rev @@ List.rev_append (List.rev_map (fun (var, z, doc) -> var, rezip_to_string z, doc) acc) @@ List.rev_map (fun (var, z) -> var, rezip_to_string z, Some "Reverting previous opam update") reverts in apply_updates reverts [] updates let add (env: env) (updates: env_update list) = let env = if Sys.win32 then * Environment variable names are case insensitive on Windows * Environment variable names are case insensitive on Windows *) let updates = List.rev_map (fun (u,_,_,_) -> (String.uppercase_ascii u, "", "", None)) updates in List.filter (fun (k,_,_) -> let k = String.uppercase_ascii k in List.for_all (fun (u,_,_,_) -> u <> k) updates) env else List.filter (fun (k,_,_) -> List.for_all (fun (u,_,_,_) -> u <> k) updates) env in env @ expand updates let compute_updates ?(force_path=false) st = Todo : put these back into their packages ! let . Name.of_string " perl5 " in let add_to_perl5lib = OpamPath.Switch.lib t.root t.switch t.switch_config perl5 in let new_perl5lib = " PERL5LIB " , " + = " , OpamFilename . in let perl5 = OpamPackage.Name.of_string "perl5" in let add_to_perl5lib = OpamPath.Switch.lib t.root t.switch t.switch_config perl5 in let new_perl5lib = "PERL5LIB", "+=", OpamFilename.Dir.to_string add_to_perl5lib in *) let fenv ?opam v = try OpamPackageVar.resolve st ?opam v with Not_found -> log "Undefined variable: %s" (OpamVariable.Full.to_string v); None in let bindir = OpamPath.Switch.bin st.switch_global.root st.switch st.switch_config in let path = "PATH", (if force_path then PlusEq else EqPlusEq), OpamFilename.Dir.to_string bindir, Some ("Binary dir for opam switch "^OpamSwitch.to_string st.switch) in let man_path = let open OpamStd.Sys in match os () with | OpenBSD | NetBSD | FreeBSD | Darwin | DragonFly -> [] (* MANPATH is a global override on those, so disabled for now *) | _ -> ["MANPATH", EqColon, OpamFilename.Dir.to_string (OpamPath.Switch.man_dir st.switch_global.root st.switch st.switch_config), Some "Current opam switch man dir"] in let env_expansion ?opam (name,op,str,cmt) = let s = OpamFilter.expand_string ~default:(fun _ -> "") (fenv ?opam) str in name, op, s, cmt in let switch_env = ("OPAM_SWITCH_PREFIX", Eq, OpamFilename.Dir.to_string (OpamPath.Switch.root st.switch_global.root st.switch), Some "Prefix of the current opam switch") :: List.map env_expansion st.switch_config.OpamFile.Switch_config.env in let pkg_env = (* XXX: Does this need a (costly) topological sort? *) OpamPackage.Set.fold (fun nv acc -> match OpamPackage.Map.find_opt nv st.opams with | Some opam -> List.map (env_expansion ~opam) (OpamFile.OPAM.env opam) @ acc | None -> acc) st.installed [] in switch_env @ pkg_env @ man_path @ [path] let updates_common ~set_opamroot ~set_opamswitch root switch = let root = if set_opamroot then [ "OPAMROOT", Eq, OpamFilename.Dir.to_string root, Some "Opam root in use" ] else [] in let switch = if set_opamswitch then [ "OPAMSWITCH", Eq, OpamSwitch.to_string switch, None ] else [] in root @ switch let updates ?(set_opamroot=false) ?(set_opamswitch=false) ?force_path st = updates_common ~set_opamroot ~set_opamswitch st.switch_global.root st.switch @ compute_updates ?force_path st let get_pure ?(updates=[]) () = let env = List.map (fun (v,va) -> v,va,None) (OpamStd.Env.list ()) in add env updates let get_opam ?(set_opamroot=false) ?(set_opamswitch=false) ~force_path st = add [] (updates ~set_opamroot ~set_opamswitch ~force_path st) let get_opam_raw ?(set_opamroot=false) ?(set_opamswitch=false) ~force_path root switch = let env_file = OpamPath.Switch.environment root switch in let upd = OpamFile.Environment.safe_read env_file in let upd = ("OPAM_SWITCH_PREFIX", Eq, OpamFilename.Dir.to_string (OpamPath.Switch.root root switch), Some "Prefix of the current opam switch") :: List.filter (function ("OPAM_SWITCH_PREFIX", Eq, _, _) -> false | _ -> true) upd in let upd = if force_path then List.map (function | "PATH", EqPlusEq, v, doc -> "PATH", PlusEq, v, doc | e -> e) upd else List.map (function | "PATH", PlusEq, v, doc -> "PATH", EqPlusEq, v, doc | e -> e) upd in add [] (updates_common ~set_opamroot ~set_opamswitch root switch @ upd) let get_full ?(set_opamroot=false) ?(set_opamswitch=false) ~force_path ?updates:(u=[]) st = let env0 = List.map (fun (v,va) -> v,va,None) (OpamStd.Env.list ()) in let updates = u @ updates ~set_opamroot ~set_opamswitch ~force_path st in add env0 updates let is_up_to_date_raw updates = OpamStateConfig.(!r.no_env_notice) || let not_utd = List.fold_left (fun notutd (var, op, arg, _doc as upd) -> match OpamStd.Env.getopt var with | None -> upd::notutd | Some v -> if reverse_env_update op arg (split_var v) = None then upd::notutd else List.filter (fun (v, _, _, _) -> v <> var) notutd) [] updates in let r = not_utd = [] in if not r then log "Not up-to-date env variables: [%a]" (slog @@ String.concat " " @* List.map (fun (v, _, _, _) -> v)) not_utd else log "Environment is up-to-date"; r let is_up_to_date_switch root switch = let env_file = OpamPath.Switch.environment root switch in try match OpamFile.Environment.read_opt env_file with | Some upd -> is_up_to_date_raw upd | None -> true with e -> OpamStd.Exn.fatal e; true let switch_path_update ~force_path root switch = let bindir = OpamPath.Switch.bin root switch (OpamFile.Switch_config.safe_read (OpamPath.Switch.switch_config root switch)) in [ "PATH", (if force_path then PlusEq else EqPlusEq), OpamFilename.Dir.to_string bindir, Some "Current opam switch binary dir" ] let path ~force_path root switch = let env = expand (switch_path_update ~force_path root switch) in let (_, path_value, _) = List.find (fun (v, _, _) -> v = "PATH") env in path_value let full_with_path ~force_path ?(updates=[]) root switch = let env0 = List.map (fun (v,va) -> v,va,None) (OpamStd.Env.list ()) in add env0 (switch_path_update ~force_path root switch @ updates) let is_up_to_date st = is_up_to_date_raw (updates ~set_opamroot:false ~set_opamswitch:false ~force_path:false st) let eval_string gt ?(set_opamswitch=false) switch = let root = let opamroot_cur = OpamFilename.Dir.to_string gt.root in let opamroot_env = OpamStd.Option.Op.( OpamStd.Env.getopt "OPAMROOT" +! OpamFilename.Dir.to_string OpamStateConfig.(default.root_dir) ) in if opamroot_cur <> opamroot_env then Printf.sprintf " --root=%s" opamroot_cur else "" in let switch = match switch with | None -> "" | Some sw -> let sw_cur = OpamSwitch.to_string sw in let sw_env = OpamStd.Option.Op.( OpamStd.Env.getopt "OPAMSWITCH" ++ (OpamStateConfig.get_current_switch_from_cwd gt.root >>| OpamSwitch.to_string) ++ (OpamFile.Config.switch gt.config >>| OpamSwitch.to_string) ) in if Some sw_cur <> sw_env then Printf.sprintf " --switch=%s" sw_cur else "" in let setswitch = if set_opamswitch then " --set-switch" else "" in match OpamStd.Sys.guess_shell_compat () with | SH_fish -> Printf.sprintf "eval (opam env%s%s%s)" root switch setswitch | SH_csh -> Printf.sprintf "eval `opam env%s%s%s`" root switch setswitch | _ -> Printf.sprintf "eval $(opam env%s%s%s)" root switch setswitch -- Shell and init scripts handling -- (** The shells for which we generate init scripts (bash and sh are the same entry) *) let shells_list = [ SH_sh; SH_zsh; SH_csh; SH_fish ] let complete_file = function | SH_sh | SH_bash -> Some "complete.sh" | SH_zsh -> Some "complete.zsh" | SH_csh | SH_fish -> None let env_hook_file = function | SH_sh | SH_bash -> Some "env_hook.sh" | SH_zsh -> Some "env_hook.zsh" | SH_csh -> Some "env_hook.csh" | SH_fish -> Some "env_hook.fish" let variables_file = function | SH_sh | SH_bash | SH_zsh -> "variables.sh" | SH_csh -> "variables.csh" | SH_fish -> "variables.fish" let init_file = function | SH_sh | SH_bash -> "init.sh" | SH_zsh -> "init.zsh" | SH_csh -> "init.csh" | SH_fish -> "init.fish" let complete_script = function | SH_sh | SH_bash -> Some OpamScript.complete | SH_zsh -> Some OpamScript.complete_zsh | SH_csh | SH_fish -> None let env_hook_script_base = function | SH_sh | SH_bash -> Some OpamScript.env_hook | SH_zsh -> Some OpamScript.env_hook_zsh | SH_csh -> Some OpamScript.env_hook_csh | SH_fish -> Some OpamScript.env_hook_fish let export_in_shell shell = let make_comment comment_opt = OpamStd.Option.to_string (Printf.sprintf "# %s\n") comment_opt in let sh (k,v,comment) = Printf.sprintf "%s%s=%s; export %s;\n" (make_comment comment) k v k in let csh (k,v,comment) = Printf.sprintf "%sif ( ! ${?%s} ) setenv %s \"\"\nsetenv %s %s\n" (make_comment comment) k k k v in let fish (k,v,comment) = (* Fish converts some colon-separated vars to arrays, which have to be treated differently. MANPATH is handled automatically, so better not to set it at all when not already defined *) let to_arr_string v = OpamStd.List.concat_map " " (fun v -> if v = Printf.sprintf "\"$%s\"" k then "$"^k (* remove quotes *) else v) (OpamStd.String.split v ':') in match k with | "PATH" -> Printf.sprintf "%sset -gx %s %s;\n" (make_comment comment) k (to_arr_string v) | "MANPATH" -> Printf.sprintf "%sif [ (count $%s) -gt 0 ]; set -gx %s %s; end;\n" (make_comment comment) k k (to_arr_string v) | _ -> (* Regular string variables *) Printf.sprintf "%sset -gx %s %s;\n" (make_comment comment) k v in match shell with | SH_zsh | SH_bash | SH_sh -> sh | SH_fish -> fish | SH_csh -> csh let env_hook_script shell = OpamStd.Option.map (fun script -> export_in_shell shell ("OPAMNOENVNOTICE", "true", None) ^ script) (env_hook_script_base shell) let source root shell f = let file f = OpamFilename.to_string (OpamPath.init root // f) in match shell with | SH_csh -> Printf.sprintf "source %s >& /dev/null || true\n" (file f) | SH_fish -> Printf.sprintf "source %s > /dev/null 2> /dev/null; or true\n" (file f) | SH_sh | SH_bash | SH_zsh -> Printf.sprintf "test -r %s && . %s > /dev/null 2> /dev/null || true\n" (file f) (file f) let if_interactive_script shell t e = let ielse else_opt = match else_opt with | None -> "" | Some e -> Printf.sprintf "else\n %s" e in match shell with | SH_sh | SH_zsh | SH_bash -> Printf.sprintf "if [ -t 0 ]; then\n %s%sfi\n" t @@ ielse e | SH_csh -> Printf.sprintf "if ( $?prompt ) then\n %s%sendif\n" t @@ ielse e | SH_fish -> Printf.sprintf "if isatty\n %s%send\n" t @@ ielse e let init_script root shell = let interactive = List.map (source root shell) @@ OpamStd.List.filter_some [complete_file shell; env_hook_file shell] in String.concat "\n" @@ (if interactive <> [] then [if_interactive_script shell (String.concat "\n " interactive) None] else []) @ [source root shell (variables_file shell)] let string_of_update st shell updates = let fenv = OpamPackageVar.resolve st in let aux (ident, symbol, string, comment) = let string = OpamFilter.expand_string ~default:(fun _ -> "") fenv string |> OpamStd.Env.escape_single_quotes ~using_backslashes:(shell = SH_fish) in let key, value = ident, match symbol with | Eq -> Printf.sprintf "'%s'" string | PlusEq | ColonEq | EqPlusEq -> Printf.sprintf "'%s':\"$%s\"" string ident | EqColon | EqPlus -> Printf.sprintf "\"$%s\":'%s'" ident string in export_in_shell shell (key, value, comment) in OpamStd.List.concat_map "" aux updates let write_script dir (name, body) = let file = dir // name in try OpamFilename.write file body with e -> OpamStd.Exn.fatal e; OpamConsole.error "Could not write %s" (OpamFilename.to_string file) let write_init_shell_scripts root = let scripts = List.map (fun shell -> init_file shell, init_script root shell) shells_list in List.iter (write_script (OpamPath.init root)) scripts let write_static_init_scripts root ?completion ?env_hook () = write_init_shell_scripts root; let update_scripts filef scriptf enable = let scripts = OpamStd.List.filter_map (fun shell -> match filef shell, scriptf shell with | Some f, Some s -> Some (f, s) | _ -> None) shells_list in match enable with | Some true -> List.iter (write_script (OpamPath.init root)) scripts | Some false -> List.iter (fun (f,_) -> OpamFilename.remove (OpamPath.init root // f)) scripts | None -> () in update_scripts complete_file complete_script completion; update_scripts env_hook_file env_hook_script env_hook let write_custom_init_scripts root custom = List.iter (fun (name, script) -> write_script (OpamPath.hooks_dir root) (name, script); OpamFilename.chmod (OpamPath.hooks_dir root // name) 0o777 ) custom let write_dynamic_init_scripts st = let updates = updates ~set_opamroot:false ~set_opamswitch:false st in try OpamFilename.with_flock_upgrade `Lock_write ~dontblock:true st.switch_global.global_lock @@ fun _ -> List.iter (fun shell -> write_script (OpamPath.init st.switch_global.root) (variables_file shell, string_of_update st shell updates)) [SH_sh; SH_csh; SH_fish] with OpamSystem.Locked -> OpamConsole.warning "Global shell init scripts not installed (could not acquire lock)" let clear_dynamic_init_scripts gt = List.iter (fun shell -> OpamFilename.remove (OpamPath.init gt.root // variables_file shell)) [SH_sh; SH_csh; SH_fish] let dot_profile_needs_update root dot_profile = if not (OpamFilename.exists dot_profile) then `yes else let body = OpamFilename.read dot_profile in let pattern1 = "opam config env" in let pattern1b = "opam env" in let pattern2 = OpamFilename.to_string (OpamPath.init root // "init") in let pattern3 = OpamStd.String.remove_prefix ~prefix:(OpamFilename.Dir.to_string root) pattern2 in let uncommented_re patts = Re.(compile (seq [bol; rep (diff any (set "#:")); alt (List.map str patts)])) in if Re.execp (uncommented_re [pattern1; pattern1b; pattern2]) body then `no else if Re.execp (uncommented_re [pattern3]) body then `otherroot else `yes let update_dot_profile root dot_profile shell = let pretty_dot_profile = OpamFilename.prettify dot_profile in let bash_src () = if shell = SH_bash || shell = SH_sh then OpamConsole.note "Make sure that %s is well %s in your ~/.bashrc.\n" pretty_dot_profile (OpamConsole.colorise `underline "sourced") in match dot_profile_needs_update root dot_profile with | `no -> OpamConsole.msg " %s is already up-to-date.\n" pretty_dot_profile; bash_src() | `otherroot -> OpamConsole.msg " %s is already configured for another opam root.\n" pretty_dot_profile | `yes -> let init_file = init_file shell in let body = if OpamFilename.exists dot_profile then OpamFilename.read dot_profile else "" in OpamConsole.msg " Updating %s.\n" pretty_dot_profile; bash_src(); let body = Printf.sprintf "%s\n\n\ # opam configuration\n\ %s" (OpamStd.String.strip body) (source root shell init_file) in OpamFilename.write dot_profile body let update_user_setup root ?dot_profile shell = if dot_profile <> None then ( OpamConsole.msg "\nUser configuration:\n"; OpamStd.Option.iter (fun f -> update_dot_profile root f shell) dot_profile ) let check_and_print_env_warning st = if not (is_up_to_date st) && (OpamFile.Config.switch st.switch_global.config = Some st.switch || OpamStateConfig.(!r.switch_from <> `Command_line)) then OpamConsole.formatted_msg "# Run %s to update the current shell environment\n" (OpamConsole.colorise `bold (eval_string st.switch_global (Some st.switch))) let setup root ~interactive ?dot_profile ?update_config ?env_hook ?completion shell = let update_dot_profile = match update_config, dot_profile, interactive with | Some false, _, _ -> None | _, None, _ -> invalid_arg "OpamEnv.setup" | Some true, Some dot_profile, _ -> Some dot_profile | None, _, false -> None | None, Some dot_profile, true -> OpamConsole.header_msg "Required setup - please read"; OpamConsole.msg "\n\ \ In normal operation, opam only alters files within ~/.opam.\n\ \n\ \ However, to best integrate with your system, some environment variables\n\ \ should be set. If you allow it to, this initialisation step will update\n\ \ your %s configuration by adding the following line to %s:\n\ \n\ \ %s\ \n\ \ Otherwise, every time you want to access your opam installation, you will\n\ \ need to run:\n\ \n\ \ %s\n\ \n\ \ You can always re-run this setup with 'opam init' later.\n\n" (OpamConsole.colorise `bold @@ string_of_shell shell) (OpamConsole.colorise `cyan @@ OpamFilename.prettify dot_profile) (OpamConsole.colorise `bold @@ source root shell (init_file shell)) (OpamConsole.colorise `bold @@ "eval $(opam env)"); match OpamConsole.read "Do you want opam to modify %s? [N/y/f]\n\ (default is 'no', use 'f' to choose a different file)" (OpamFilename.prettify dot_profile) with | Some ("y" | "Y" | "yes" | "YES" ) -> Some dot_profile | Some ("f" | "F" | "file" | "FILE") -> begin match OpamConsole.read " Enter the name of the file to update:" with | None -> OpamConsole.msg "Alright, assuming you changed your mind, not \ performing any changes.\n"; None | Some f -> Some (OpamFilename.of_string f) end | _ -> None in let env_hook = match env_hook, interactive with | Some b, _ -> Some b | None, false -> None | None, true -> Some (OpamConsole.confirm ~default:false "A hook can be added to opam's init scripts to ensure that the \ shell remains in sync with the opam environment when they are \ loaded. Set that up?") in update_user_setup root ?dot_profile:update_dot_profile shell; write_static_init_scripts root ?completion ?env_hook ()
null
https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/opam-client.2.0.5%2Bdune/src/state/opamEnv.ml
ocaml
************************************************************************ All rights reserved. This file is distributed under the terms of the exception on linking described in the file LICENSE. ************************************************************************ - Environment and updates handling - prepend a, but keep ":"s keep surrounding colons * Undoes previous updates done by opam, useful for not duplicating already done updates; this is obviously not perfect, as all operators are not reversible. [cur_value] is provided as a list split at path_sep. None is returned if the revert doesn't match. Otherwise, a zip (pair of lists [(preceding_elements_reverted, following_elements)]) is returned, to keep the position of the matching element and allow [=+=] to be applied later. A pair or empty lists is returned if the variable should be unset or has an unknown previous value. Reverse all previous updates, in reverse order, on current environment And apply the new ones MANPATH is a global override on those, so disabled for now XXX: Does this need a (costly) topological sort? * The shells for which we generate init scripts (bash and sh are the same entry) Fish converts some colon-separated vars to arrays, which have to be treated differently. MANPATH is handled automatically, so better not to set it at all when not already defined remove quotes Regular string variables
Copyright 2012 - 2015 OCamlPro Copyright 2012 INRIA GNU Lesser General Public License version 2.1 , with the special open OpamTypes open OpamStateTypes open OpamTypesBase open OpamStd.Op open OpamFilename.Op let log fmt = OpamConsole.log "ENV" fmt let slog = OpamConsole.slog let split_var v = OpamStd.Sys.split_path_variable ~clean:false v let join_var l = String.concat (String.make 1 OpamStd.Sys.path_sep) l To allow in - place updates , we store intermediate values of path - like as a pair of list [ ( rl1 , l2 ) ] such that the value is [ rl1 l2 ] and the place where the new value should be inserted is in front of [ l2 ] pair of list [(rl1, l2)] such that the value is [List.rev_append rl1 l2] and the place where the new value should be inserted is in front of [l2] *) let unzip_to elt = let rec aux acc = function | [] -> None | x::r -> if x = elt then Some (acc, r) else aux (x::acc) r in aux [] let rezip ?insert (l1, l2) = List.rev_append l1 (match insert with None -> l2 | Some i -> i::l2) let rezip_to_string ?insert z = join_var (rezip ?insert z) let apply_op_zip op arg (rl1,l2 as zip) = | [] | [""] -> [], [arg; ""] | "" :: l -> if eqcol then l@[""], [arg] else l, [""; arg] | l -> l, [arg] in match op with | Eq -> [],[arg] | PlusEq -> [], arg :: rezip zip | EqPlus -> List.rev_append l2 rl1, [arg] | EqPlusEq -> rl1, arg::l2 | ColonEq -> let l, add = colon_eq (rezip zip) in [], add @ l | EqColon -> let l, add = colon_eq ~eqcol:true (List.rev_append l2 rl1) in l, List.rev add let reverse_env_update op arg cur_value = match op with | Eq -> if arg = join_var cur_value then Some ([],[]) else None | PlusEq | EqPlusEq -> unzip_to arg cur_value | EqPlus -> (match unzip_to arg (List.rev cur_value) with | None -> None | Some (rl1, l2) -> Some (List.rev l2, List.rev rl1)) | ColonEq -> (match unzip_to arg cur_value with | Some ([], [""]) -> Some ([], []) | r -> r) | EqColon -> (match unzip_to arg (List.rev cur_value) with | Some ([], [""]) -> Some ([], []) | Some (rl1, l2) -> Some (List.rev l2, List.rev rl1) | None -> None) let updates_from_previous_instance = lazy ( match OpamStd.Env.getopt "OPAM_SWITCH_PREFIX" with | None -> None | Some pfx -> let env_file = OpamPath.Switch.env_relative_to_prefix (OpamFilename.Dir.of_string pfx) in try OpamFile.Environment.read_opt env_file with e -> OpamStd.Exn.fatal e; None ) let expand (updates: env_update list) : env = let reverts = match Lazy.force updates_from_previous_instance with | None -> [] | Some updates -> List.fold_right (fun (var, op, arg, _) defs0 -> let v_opt, defs = OpamStd.List.pick_assoc var defs0 in let v = OpamStd.Option.Op.((v_opt >>| rezip >>+ fun () -> OpamStd.Env.getopt var >>| split_var) +! []) in match reverse_env_update op arg v with | Some v -> (var, v)::defs | None -> defs0) updates [] in let rec apply_updates reverts acc = function | (var, op, arg, doc) :: updates -> let zip, reverts = let f, var = if Sys.win32 then String.uppercase_ascii, String.uppercase_ascii var else (fun x -> x), var in match OpamStd.List.find_opt (fun (v, _, _) -> f v = var) acc with | Some (_, z, _doc) -> z, reverts | None -> match OpamStd.List.pick_assoc var reverts with | Some z, reverts -> z, reverts | None, _ -> match OpamStd.Env.getopt var with | Some s -> ([], split_var s), reverts | None -> ([], []), reverts in apply_updates reverts ((var, apply_op_zip op arg zip, doc) :: acc) updates | [] -> List.rev @@ List.rev_append (List.rev_map (fun (var, z, doc) -> var, rezip_to_string z, doc) acc) @@ List.rev_map (fun (var, z) -> var, rezip_to_string z, Some "Reverting previous opam update") reverts in apply_updates reverts [] updates let add (env: env) (updates: env_update list) = let env = if Sys.win32 then * Environment variable names are case insensitive on Windows * Environment variable names are case insensitive on Windows *) let updates = List.rev_map (fun (u,_,_,_) -> (String.uppercase_ascii u, "", "", None)) updates in List.filter (fun (k,_,_) -> let k = String.uppercase_ascii k in List.for_all (fun (u,_,_,_) -> u <> k) updates) env else List.filter (fun (k,_,_) -> List.for_all (fun (u,_,_,_) -> u <> k) updates) env in env @ expand updates let compute_updates ?(force_path=false) st = Todo : put these back into their packages ! let . Name.of_string " perl5 " in let add_to_perl5lib = OpamPath.Switch.lib t.root t.switch t.switch_config perl5 in let new_perl5lib = " PERL5LIB " , " + = " , OpamFilename . in let perl5 = OpamPackage.Name.of_string "perl5" in let add_to_perl5lib = OpamPath.Switch.lib t.root t.switch t.switch_config perl5 in let new_perl5lib = "PERL5LIB", "+=", OpamFilename.Dir.to_string add_to_perl5lib in *) let fenv ?opam v = try OpamPackageVar.resolve st ?opam v with Not_found -> log "Undefined variable: %s" (OpamVariable.Full.to_string v); None in let bindir = OpamPath.Switch.bin st.switch_global.root st.switch st.switch_config in let path = "PATH", (if force_path then PlusEq else EqPlusEq), OpamFilename.Dir.to_string bindir, Some ("Binary dir for opam switch "^OpamSwitch.to_string st.switch) in let man_path = let open OpamStd.Sys in match os () with | OpenBSD | NetBSD | FreeBSD | Darwin | DragonFly -> | _ -> ["MANPATH", EqColon, OpamFilename.Dir.to_string (OpamPath.Switch.man_dir st.switch_global.root st.switch st.switch_config), Some "Current opam switch man dir"] in let env_expansion ?opam (name,op,str,cmt) = let s = OpamFilter.expand_string ~default:(fun _ -> "") (fenv ?opam) str in name, op, s, cmt in let switch_env = ("OPAM_SWITCH_PREFIX", Eq, OpamFilename.Dir.to_string (OpamPath.Switch.root st.switch_global.root st.switch), Some "Prefix of the current opam switch") :: List.map env_expansion st.switch_config.OpamFile.Switch_config.env in OpamPackage.Set.fold (fun nv acc -> match OpamPackage.Map.find_opt nv st.opams with | Some opam -> List.map (env_expansion ~opam) (OpamFile.OPAM.env opam) @ acc | None -> acc) st.installed [] in switch_env @ pkg_env @ man_path @ [path] let updates_common ~set_opamroot ~set_opamswitch root switch = let root = if set_opamroot then [ "OPAMROOT", Eq, OpamFilename.Dir.to_string root, Some "Opam root in use" ] else [] in let switch = if set_opamswitch then [ "OPAMSWITCH", Eq, OpamSwitch.to_string switch, None ] else [] in root @ switch let updates ?(set_opamroot=false) ?(set_opamswitch=false) ?force_path st = updates_common ~set_opamroot ~set_opamswitch st.switch_global.root st.switch @ compute_updates ?force_path st let get_pure ?(updates=[]) () = let env = List.map (fun (v,va) -> v,va,None) (OpamStd.Env.list ()) in add env updates let get_opam ?(set_opamroot=false) ?(set_opamswitch=false) ~force_path st = add [] (updates ~set_opamroot ~set_opamswitch ~force_path st) let get_opam_raw ?(set_opamroot=false) ?(set_opamswitch=false) ~force_path root switch = let env_file = OpamPath.Switch.environment root switch in let upd = OpamFile.Environment.safe_read env_file in let upd = ("OPAM_SWITCH_PREFIX", Eq, OpamFilename.Dir.to_string (OpamPath.Switch.root root switch), Some "Prefix of the current opam switch") :: List.filter (function ("OPAM_SWITCH_PREFIX", Eq, _, _) -> false | _ -> true) upd in let upd = if force_path then List.map (function | "PATH", EqPlusEq, v, doc -> "PATH", PlusEq, v, doc | e -> e) upd else List.map (function | "PATH", PlusEq, v, doc -> "PATH", EqPlusEq, v, doc | e -> e) upd in add [] (updates_common ~set_opamroot ~set_opamswitch root switch @ upd) let get_full ?(set_opamroot=false) ?(set_opamswitch=false) ~force_path ?updates:(u=[]) st = let env0 = List.map (fun (v,va) -> v,va,None) (OpamStd.Env.list ()) in let updates = u @ updates ~set_opamroot ~set_opamswitch ~force_path st in add env0 updates let is_up_to_date_raw updates = OpamStateConfig.(!r.no_env_notice) || let not_utd = List.fold_left (fun notutd (var, op, arg, _doc as upd) -> match OpamStd.Env.getopt var with | None -> upd::notutd | Some v -> if reverse_env_update op arg (split_var v) = None then upd::notutd else List.filter (fun (v, _, _, _) -> v <> var) notutd) [] updates in let r = not_utd = [] in if not r then log "Not up-to-date env variables: [%a]" (slog @@ String.concat " " @* List.map (fun (v, _, _, _) -> v)) not_utd else log "Environment is up-to-date"; r let is_up_to_date_switch root switch = let env_file = OpamPath.Switch.environment root switch in try match OpamFile.Environment.read_opt env_file with | Some upd -> is_up_to_date_raw upd | None -> true with e -> OpamStd.Exn.fatal e; true let switch_path_update ~force_path root switch = let bindir = OpamPath.Switch.bin root switch (OpamFile.Switch_config.safe_read (OpamPath.Switch.switch_config root switch)) in [ "PATH", (if force_path then PlusEq else EqPlusEq), OpamFilename.Dir.to_string bindir, Some "Current opam switch binary dir" ] let path ~force_path root switch = let env = expand (switch_path_update ~force_path root switch) in let (_, path_value, _) = List.find (fun (v, _, _) -> v = "PATH") env in path_value let full_with_path ~force_path ?(updates=[]) root switch = let env0 = List.map (fun (v,va) -> v,va,None) (OpamStd.Env.list ()) in add env0 (switch_path_update ~force_path root switch @ updates) let is_up_to_date st = is_up_to_date_raw (updates ~set_opamroot:false ~set_opamswitch:false ~force_path:false st) let eval_string gt ?(set_opamswitch=false) switch = let root = let opamroot_cur = OpamFilename.Dir.to_string gt.root in let opamroot_env = OpamStd.Option.Op.( OpamStd.Env.getopt "OPAMROOT" +! OpamFilename.Dir.to_string OpamStateConfig.(default.root_dir) ) in if opamroot_cur <> opamroot_env then Printf.sprintf " --root=%s" opamroot_cur else "" in let switch = match switch with | None -> "" | Some sw -> let sw_cur = OpamSwitch.to_string sw in let sw_env = OpamStd.Option.Op.( OpamStd.Env.getopt "OPAMSWITCH" ++ (OpamStateConfig.get_current_switch_from_cwd gt.root >>| OpamSwitch.to_string) ++ (OpamFile.Config.switch gt.config >>| OpamSwitch.to_string) ) in if Some sw_cur <> sw_env then Printf.sprintf " --switch=%s" sw_cur else "" in let setswitch = if set_opamswitch then " --set-switch" else "" in match OpamStd.Sys.guess_shell_compat () with | SH_fish -> Printf.sprintf "eval (opam env%s%s%s)" root switch setswitch | SH_csh -> Printf.sprintf "eval `opam env%s%s%s`" root switch setswitch | _ -> Printf.sprintf "eval $(opam env%s%s%s)" root switch setswitch -- Shell and init scripts handling -- let shells_list = [ SH_sh; SH_zsh; SH_csh; SH_fish ] let complete_file = function | SH_sh | SH_bash -> Some "complete.sh" | SH_zsh -> Some "complete.zsh" | SH_csh | SH_fish -> None let env_hook_file = function | SH_sh | SH_bash -> Some "env_hook.sh" | SH_zsh -> Some "env_hook.zsh" | SH_csh -> Some "env_hook.csh" | SH_fish -> Some "env_hook.fish" let variables_file = function | SH_sh | SH_bash | SH_zsh -> "variables.sh" | SH_csh -> "variables.csh" | SH_fish -> "variables.fish" let init_file = function | SH_sh | SH_bash -> "init.sh" | SH_zsh -> "init.zsh" | SH_csh -> "init.csh" | SH_fish -> "init.fish" let complete_script = function | SH_sh | SH_bash -> Some OpamScript.complete | SH_zsh -> Some OpamScript.complete_zsh | SH_csh | SH_fish -> None let env_hook_script_base = function | SH_sh | SH_bash -> Some OpamScript.env_hook | SH_zsh -> Some OpamScript.env_hook_zsh | SH_csh -> Some OpamScript.env_hook_csh | SH_fish -> Some OpamScript.env_hook_fish let export_in_shell shell = let make_comment comment_opt = OpamStd.Option.to_string (Printf.sprintf "# %s\n") comment_opt in let sh (k,v,comment) = Printf.sprintf "%s%s=%s; export %s;\n" (make_comment comment) k v k in let csh (k,v,comment) = Printf.sprintf "%sif ( ! ${?%s} ) setenv %s \"\"\nsetenv %s %s\n" (make_comment comment) k k k v in let fish (k,v,comment) = let to_arr_string v = OpamStd.List.concat_map " " (fun v -> if v = Printf.sprintf "\"$%s\"" k then else v) (OpamStd.String.split v ':') in match k with | "PATH" -> Printf.sprintf "%sset -gx %s %s;\n" (make_comment comment) k (to_arr_string v) | "MANPATH" -> Printf.sprintf "%sif [ (count $%s) -gt 0 ]; set -gx %s %s; end;\n" (make_comment comment) k k (to_arr_string v) | _ -> Printf.sprintf "%sset -gx %s %s;\n" (make_comment comment) k v in match shell with | SH_zsh | SH_bash | SH_sh -> sh | SH_fish -> fish | SH_csh -> csh let env_hook_script shell = OpamStd.Option.map (fun script -> export_in_shell shell ("OPAMNOENVNOTICE", "true", None) ^ script) (env_hook_script_base shell) let source root shell f = let file f = OpamFilename.to_string (OpamPath.init root // f) in match shell with | SH_csh -> Printf.sprintf "source %s >& /dev/null || true\n" (file f) | SH_fish -> Printf.sprintf "source %s > /dev/null 2> /dev/null; or true\n" (file f) | SH_sh | SH_bash | SH_zsh -> Printf.sprintf "test -r %s && . %s > /dev/null 2> /dev/null || true\n" (file f) (file f) let if_interactive_script shell t e = let ielse else_opt = match else_opt with | None -> "" | Some e -> Printf.sprintf "else\n %s" e in match shell with | SH_sh | SH_zsh | SH_bash -> Printf.sprintf "if [ -t 0 ]; then\n %s%sfi\n" t @@ ielse e | SH_csh -> Printf.sprintf "if ( $?prompt ) then\n %s%sendif\n" t @@ ielse e | SH_fish -> Printf.sprintf "if isatty\n %s%send\n" t @@ ielse e let init_script root shell = let interactive = List.map (source root shell) @@ OpamStd.List.filter_some [complete_file shell; env_hook_file shell] in String.concat "\n" @@ (if interactive <> [] then [if_interactive_script shell (String.concat "\n " interactive) None] else []) @ [source root shell (variables_file shell)] let string_of_update st shell updates = let fenv = OpamPackageVar.resolve st in let aux (ident, symbol, string, comment) = let string = OpamFilter.expand_string ~default:(fun _ -> "") fenv string |> OpamStd.Env.escape_single_quotes ~using_backslashes:(shell = SH_fish) in let key, value = ident, match symbol with | Eq -> Printf.sprintf "'%s'" string | PlusEq | ColonEq | EqPlusEq -> Printf.sprintf "'%s':\"$%s\"" string ident | EqColon | EqPlus -> Printf.sprintf "\"$%s\":'%s'" ident string in export_in_shell shell (key, value, comment) in OpamStd.List.concat_map "" aux updates let write_script dir (name, body) = let file = dir // name in try OpamFilename.write file body with e -> OpamStd.Exn.fatal e; OpamConsole.error "Could not write %s" (OpamFilename.to_string file) let write_init_shell_scripts root = let scripts = List.map (fun shell -> init_file shell, init_script root shell) shells_list in List.iter (write_script (OpamPath.init root)) scripts let write_static_init_scripts root ?completion ?env_hook () = write_init_shell_scripts root; let update_scripts filef scriptf enable = let scripts = OpamStd.List.filter_map (fun shell -> match filef shell, scriptf shell with | Some f, Some s -> Some (f, s) | _ -> None) shells_list in match enable with | Some true -> List.iter (write_script (OpamPath.init root)) scripts | Some false -> List.iter (fun (f,_) -> OpamFilename.remove (OpamPath.init root // f)) scripts | None -> () in update_scripts complete_file complete_script completion; update_scripts env_hook_file env_hook_script env_hook let write_custom_init_scripts root custom = List.iter (fun (name, script) -> write_script (OpamPath.hooks_dir root) (name, script); OpamFilename.chmod (OpamPath.hooks_dir root // name) 0o777 ) custom let write_dynamic_init_scripts st = let updates = updates ~set_opamroot:false ~set_opamswitch:false st in try OpamFilename.with_flock_upgrade `Lock_write ~dontblock:true st.switch_global.global_lock @@ fun _ -> List.iter (fun shell -> write_script (OpamPath.init st.switch_global.root) (variables_file shell, string_of_update st shell updates)) [SH_sh; SH_csh; SH_fish] with OpamSystem.Locked -> OpamConsole.warning "Global shell init scripts not installed (could not acquire lock)" let clear_dynamic_init_scripts gt = List.iter (fun shell -> OpamFilename.remove (OpamPath.init gt.root // variables_file shell)) [SH_sh; SH_csh; SH_fish] let dot_profile_needs_update root dot_profile = if not (OpamFilename.exists dot_profile) then `yes else let body = OpamFilename.read dot_profile in let pattern1 = "opam config env" in let pattern1b = "opam env" in let pattern2 = OpamFilename.to_string (OpamPath.init root // "init") in let pattern3 = OpamStd.String.remove_prefix ~prefix:(OpamFilename.Dir.to_string root) pattern2 in let uncommented_re patts = Re.(compile (seq [bol; rep (diff any (set "#:")); alt (List.map str patts)])) in if Re.execp (uncommented_re [pattern1; pattern1b; pattern2]) body then `no else if Re.execp (uncommented_re [pattern3]) body then `otherroot else `yes let update_dot_profile root dot_profile shell = let pretty_dot_profile = OpamFilename.prettify dot_profile in let bash_src () = if shell = SH_bash || shell = SH_sh then OpamConsole.note "Make sure that %s is well %s in your ~/.bashrc.\n" pretty_dot_profile (OpamConsole.colorise `underline "sourced") in match dot_profile_needs_update root dot_profile with | `no -> OpamConsole.msg " %s is already up-to-date.\n" pretty_dot_profile; bash_src() | `otherroot -> OpamConsole.msg " %s is already configured for another opam root.\n" pretty_dot_profile | `yes -> let init_file = init_file shell in let body = if OpamFilename.exists dot_profile then OpamFilename.read dot_profile else "" in OpamConsole.msg " Updating %s.\n" pretty_dot_profile; bash_src(); let body = Printf.sprintf "%s\n\n\ # opam configuration\n\ %s" (OpamStd.String.strip body) (source root shell init_file) in OpamFilename.write dot_profile body let update_user_setup root ?dot_profile shell = if dot_profile <> None then ( OpamConsole.msg "\nUser configuration:\n"; OpamStd.Option.iter (fun f -> update_dot_profile root f shell) dot_profile ) let check_and_print_env_warning st = if not (is_up_to_date st) && (OpamFile.Config.switch st.switch_global.config = Some st.switch || OpamStateConfig.(!r.switch_from <> `Command_line)) then OpamConsole.formatted_msg "# Run %s to update the current shell environment\n" (OpamConsole.colorise `bold (eval_string st.switch_global (Some st.switch))) let setup root ~interactive ?dot_profile ?update_config ?env_hook ?completion shell = let update_dot_profile = match update_config, dot_profile, interactive with | Some false, _, _ -> None | _, None, _ -> invalid_arg "OpamEnv.setup" | Some true, Some dot_profile, _ -> Some dot_profile | None, _, false -> None | None, Some dot_profile, true -> OpamConsole.header_msg "Required setup - please read"; OpamConsole.msg "\n\ \ In normal operation, opam only alters files within ~/.opam.\n\ \n\ \ However, to best integrate with your system, some environment variables\n\ \ should be set. If you allow it to, this initialisation step will update\n\ \ your %s configuration by adding the following line to %s:\n\ \n\ \ %s\ \n\ \ Otherwise, every time you want to access your opam installation, you will\n\ \ need to run:\n\ \n\ \ %s\n\ \n\ \ You can always re-run this setup with 'opam init' later.\n\n" (OpamConsole.colorise `bold @@ string_of_shell shell) (OpamConsole.colorise `cyan @@ OpamFilename.prettify dot_profile) (OpamConsole.colorise `bold @@ source root shell (init_file shell)) (OpamConsole.colorise `bold @@ "eval $(opam env)"); match OpamConsole.read "Do you want opam to modify %s? [N/y/f]\n\ (default is 'no', use 'f' to choose a different file)" (OpamFilename.prettify dot_profile) with | Some ("y" | "Y" | "yes" | "YES" ) -> Some dot_profile | Some ("f" | "F" | "file" | "FILE") -> begin match OpamConsole.read " Enter the name of the file to update:" with | None -> OpamConsole.msg "Alright, assuming you changed your mind, not \ performing any changes.\n"; None | Some f -> Some (OpamFilename.of_string f) end | _ -> None in let env_hook = match env_hook, interactive with | Some b, _ -> Some b | None, false -> None | None, true -> Some (OpamConsole.confirm ~default:false "A hook can be added to opam's init scripts to ensure that the \ shell remains in sync with the opam environment when they are \ loaded. Set that up?") in update_user_setup root ?dot_profile:update_dot_profile shell; write_static_init_scripts root ?completion ?env_hook ()
992587c7b134b1c01bd5e381b93ed647978e5fc49ad1d9b86999ac020a8d9563
haroldcarr/learn-haskell-coq-ml-etc
ch_07_8.hs
Created : 2015 Apr 20 ( Mon ) 12:59:55 by . Last Modified : 2015 Apr 22 ( We d ) 17:52:44 by . Created : 2015 Apr 20 (Mon) 12:59:55 by Harold Carr. Last Modified : 2015 Apr 22 (Wed) 17:52:44 by Harold Carr. -} module Ch_07_8 where import Data.Char (chr, ord) import Test.HUnit as T import Test.HUnit.Util as U 7.8 Exercises ------------------------------------------------------------------------------ 1 mf1 :: (a -> b) -> (a -> Bool) -> [a] -> [b] mf1 f p xs = [ f x | x <- xs, p x ] mf2 :: (a -> b) -> (a -> Bool) -> [a] -> [b] mf2 f p = (map f) . (filter p) e1 :: [Test] e1 = U.tt "e1" [ mf1 (*2) (even) [1,2,3,4,5] , mf2 (*2) (even) [1,2,3,4,5] ] [4,8] ------------------------------------------------------------------------------ 2 all1 :: (a -> Bool) -> [a] -> Bool all1 _ [] = True all1 p (x:xs) = p x && all1 p xs e2allt :: [Test] e2allt = U.t "e2allt" (all1 (even) [2,4,6,8]) True e2allf :: [Test] e2allf = U.t "e2allf" (all1 (even) [2,4,5,8]) False any1 :: (a -> Bool) -> [a] -> Bool any1 _ [] = False any1 p (x:xs) = p x || all1 p xs e2anyt :: [Test] e2anyt = U.t "e2anyt" (any1 (even) [2,4,6,8]) True e2anyf :: [Test] e2anyf = U.t "e2anyf" (all1 (even) [2,4,5,8]) False takeWhile1 :: (a -> Bool) -> [a] -> [a] takeWhile1 p xs | null xs || not (p (head xs)) = [] | otherwise = head xs : takeWhile1 p (tail xs) e2tw :: [Test] e2tw = U.t "e2tw" (takeWhile1 (even) [2,4,6,7,8,10]) [2,4,6] dropWhile1 :: (a -> Bool) -> [a] -> [a] dropWhile1 _ [] = [] dropWhile1 p ax@(x:xs) | p x = dropWhile p xs | otherwise = ax e2dw :: [Test] e2dw = U.t "e2dw" (dropWhile1 (odd) [1,3,5,8,9,10]) [8,9,10] ------------------------------------------------------------------------------ 3 {- f x : (foldr f [] xs) -} map1 :: (a -> b) -> [a] -> [b] map1 f = foldr (\a b -> f a : b) [] e3map :: [Test] e3map = U.t "e3map" (map1 (*2) [1,2,3,4]) [2,4,6,8] -- TODO bad definition filter1 :: (a -> Bool) -> [a] -> [a] filter1 p = foldr (\a b -> if p a then a : b else []) [] e3filter :: [Test] e3filter = U.t "e3filter" (filter1 (\x -> x `mod` 17 /= 0) [1,5 .. ]) [1,5,9,13] e3filterbad :: [Test] e3filterbad = U.t "e3filterbad" True True ( filter1 (= = 1 ) [ 0,0,1,1,0,0,1,0 ] ) [ 1,1,1 ] (filter1 (==1) [0,0,1,1,0,0,1,0]) [1,1,1] -} ----------------------------------------------------------------------------- 4 {- foldl f a x:xs = foldl f (f a x) xs -} dec2int :: [Int] -> Int dec2int = foldl (\a x -> (a * 10) + x) 0 e4 :: [Test] e4 = U.t "e4" (dec2int [2,3,4,5]) 2345 ------------------------------------------------------------------------------ 5 compose :: [a -> a] -> (a -> a) compose = foldr (.) id This does n't type check because non of the functions have the necessary a - > a type . sumsqreven = compose [ sum -- : : a = > [ a ] - > a , map ( ^2 ) -- : : a = > [ a ] - > [ a ] , filter even -- : : Integral a = > [ a ] - > [ a ] ] This doesn't type check because non of the functions have the necessary a -> a type. sumsqreven = compose [ sum -- :: Num a => [a] -> a , map (^2) -- :: Num a => [a] -> [a] , filter even -- :: Integral a => [a] -> [a] ] -} e5 :: [Test] e5 = U.t "e5" (compose [(+1), (*2), (^2)] 2) 9 ------------------------------------------------------------------------------ 6 curry1 :: ((x,y) -> z) -> x -> y -> z curry1 f x y = f (x, y) fc :: Num a => (a, a) -> a fc (x, y) = x + y fc1 :: Num a => a -> a fc1 = curry1 fc 1 e6curry = U.t "e6curry" (fc1 2) 3 uncurry1 :: (x -> y -> z) -> (x,y) -> z uncurry1 f (x,y) = f x y fu :: Num a => a -> a -> a fu x y = x + y e6uncurry = U.t "e6uncurry" (uncurry1 fu (1,2)) 3 ------------------------------------------------------------------------------ 7 unfold :: (b -> Bool) -> (b -> a) -> (b -> b) -> b -> [a] unfold p h t x | p x = [] | otherwise = h x : unfold p h t (t x) -- least significant bit on left int2bin1 :: Int -> [Int] int2bin1 0 = [] int2bin1 n = n `mod` 2 : int2bin1 (n `div` 2) int2bin2 :: Int -> [Int] int2bin2 = unfold (== 0) (`mod` 2) (`div` 2) type Bit = Int chop81 :: [Bit] -> [[Bit]] chop81 [] = [] chop81 bits = take 8 bits : chop81 (drop 8 bits) chop82 :: [Bit] -> [[Bit]] chop82 = unfold null (take 8) (drop 8) e7chop = U.tt "e7chop" [ chop81 (int2bin2 62345) , chop82 (int2bin2 62345) ] [[1,0,0,1,0,0,0,1],[1,1,0,0,1,1,1,1]] mapu :: (a -> b) -> [a] -> [b] mapu f = unfold null (f . head) tail e7map = U.t "e7map" (mapu (^2) [2,3,4]) [4,9,16] iterate1 :: (a -> a) -> a -> [a] iterate1 f a = a : unfold (const False) f f a e7iterate = U.tt "e7iterate" [ take 5 $ iterate (+2) 1 , take 5 $ iterate1 (+2) 1 ] [1,3,5,7,9] ------------------------------------------------------------------------------ 8 bin2int1 :: [Bit] -> Int bin2int1 bits = sum [ w * b | (w,b) <- zip weights bits ] where weights = iterate1 (*2) 1 bin2int2 :: [Bit] -> Int bin2int2 = foldr (\x y -> x + 2 * y) 0 make8 :: [Bit] -> [Bit] make8 bits = take 8 (bits ++ repeat 0) oddOnes :: [Bit] -> Bool oddOnes = odd . sum . filter (==1) addParity :: [Bit] -> [Bit] addParity bits = (if oddOnes bits then 1 else 0) : bits encode :: String -> [Bit] encode = concat . map (addParity . make8 . int2bin2 . ord) checkParity :: [Bit] -> [Bit] checkParity (x:xs) | x == 1 && oddOnes xs = xs | x == 0 && not (oddOnes xs) = xs | otherwise = error "parity error" chop9 :: [Bit] -> [[Bit]] chop9 = unfold null (take 9) (drop 9) decode :: [Bit] -> String decode = map (chr . bin2int2) . (map checkParity) . chop9 transmit :: String -> String transmit = decode . channel . encode channel :: [Bit] -> [Bit] channel = id e8 :: [Test] e8 = U.t "e8" (transmit "Harold" == "Harold") True ------------------------------------------------------------------------------ 9 badtransmit :: String -> String badtransmit = decode . badchannel . encode badchannel :: [Bit] -> [Bit] badchannel (x:xs) = (if x == 1 then 0 else 1) : xs e9 :: [Test] e9 = U.e "e9" (badtransmit "Harold" == "Harold") "parity error" ------------------------------------------------------------------------------ main :: IO Counts main = T.runTestTT $ T.TestList $ e1 ++ e2allt ++ e2allf ++ e2anyt ++ e2anyf ++ e2tw ++ e2dw ++ e3map ++ e3filter ++ e3filterbad ++ e4 ++ e5 ++ e6curry ++ e6uncurry ++ e7chop ++ e7map ++ e7iterate ++ e8 ++ e9 -- End of file.
null
https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/book/2007-Programming_in_Haskell-1st_Edition-Graham_Hutton/ch_07_8.hs
haskell
---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- f x : (foldr f [] xs) TODO bad definition --------------------------------------------------------------------------- foldl f a x:xs = foldl f (f a x) xs ---------------------------------------------------------------------------- : : a = > [ a ] - > a : : a = > [ a ] - > [ a ] : : Integral a = > [ a ] - > [ a ] :: Num a => [a] -> a :: Num a => [a] -> [a] :: Integral a => [a] -> [a] ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- least significant bit on left ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- End of file.
Created : 2015 Apr 20 ( Mon ) 12:59:55 by . Last Modified : 2015 Apr 22 ( We d ) 17:52:44 by . Created : 2015 Apr 20 (Mon) 12:59:55 by Harold Carr. Last Modified : 2015 Apr 22 (Wed) 17:52:44 by Harold Carr. -} module Ch_07_8 where import Data.Char (chr, ord) import Test.HUnit as T import Test.HUnit.Util as U 7.8 Exercises 1 mf1 :: (a -> b) -> (a -> Bool) -> [a] -> [b] mf1 f p xs = [ f x | x <- xs, p x ] mf2 :: (a -> b) -> (a -> Bool) -> [a] -> [b] mf2 f p = (map f) . (filter p) e1 :: [Test] e1 = U.tt "e1" [ mf1 (*2) (even) [1,2,3,4,5] , mf2 (*2) (even) [1,2,3,4,5] ] [4,8] 2 all1 :: (a -> Bool) -> [a] -> Bool all1 _ [] = True all1 p (x:xs) = p x && all1 p xs e2allt :: [Test] e2allt = U.t "e2allt" (all1 (even) [2,4,6,8]) True e2allf :: [Test] e2allf = U.t "e2allf" (all1 (even) [2,4,5,8]) False any1 :: (a -> Bool) -> [a] -> Bool any1 _ [] = False any1 p (x:xs) = p x || all1 p xs e2anyt :: [Test] e2anyt = U.t "e2anyt" (any1 (even) [2,4,6,8]) True e2anyf :: [Test] e2anyf = U.t "e2anyf" (all1 (even) [2,4,5,8]) False takeWhile1 :: (a -> Bool) -> [a] -> [a] takeWhile1 p xs | null xs || not (p (head xs)) = [] | otherwise = head xs : takeWhile1 p (tail xs) e2tw :: [Test] e2tw = U.t "e2tw" (takeWhile1 (even) [2,4,6,7,8,10]) [2,4,6] dropWhile1 :: (a -> Bool) -> [a] -> [a] dropWhile1 _ [] = [] dropWhile1 p ax@(x:xs) | p x = dropWhile p xs | otherwise = ax e2dw :: [Test] e2dw = U.t "e2dw" (dropWhile1 (odd) [1,3,5,8,9,10]) [8,9,10] 3 map1 :: (a -> b) -> [a] -> [b] map1 f = foldr (\a b -> f a : b) [] e3map :: [Test] e3map = U.t "e3map" (map1 (*2) [1,2,3,4]) [2,4,6,8] filter1 :: (a -> Bool) -> [a] -> [a] filter1 p = foldr (\a b -> if p a then a : b else []) [] e3filter :: [Test] e3filter = U.t "e3filter" (filter1 (\x -> x `mod` 17 /= 0) [1,5 .. ]) [1,5,9,13] e3filterbad :: [Test] e3filterbad = U.t "e3filterbad" True True ( filter1 (= = 1 ) [ 0,0,1,1,0,0,1,0 ] ) [ 1,1,1 ] (filter1 (==1) [0,0,1,1,0,0,1,0]) [1,1,1] -} 4 dec2int :: [Int] -> Int dec2int = foldl (\a x -> (a * 10) + x) 0 e4 :: [Test] e4 = U.t "e4" (dec2int [2,3,4,5]) 2345 5 compose :: [a -> a] -> (a -> a) compose = foldr (.) id This does n't type check because non of the functions have the necessary a - > a type . sumsqreven = compose [ ] This doesn't type check because non of the functions have the necessary a -> a type. sumsqreven = compose [ ] -} e5 :: [Test] e5 = U.t "e5" (compose [(+1), (*2), (^2)] 2) 9 6 curry1 :: ((x,y) -> z) -> x -> y -> z curry1 f x y = f (x, y) fc :: Num a => (a, a) -> a fc (x, y) = x + y fc1 :: Num a => a -> a fc1 = curry1 fc 1 e6curry = U.t "e6curry" (fc1 2) 3 uncurry1 :: (x -> y -> z) -> (x,y) -> z uncurry1 f (x,y) = f x y fu :: Num a => a -> a -> a fu x y = x + y e6uncurry = U.t "e6uncurry" (uncurry1 fu (1,2)) 3 7 unfold :: (b -> Bool) -> (b -> a) -> (b -> b) -> b -> [a] unfold p h t x | p x = [] | otherwise = h x : unfold p h t (t x) int2bin1 :: Int -> [Int] int2bin1 0 = [] int2bin1 n = n `mod` 2 : int2bin1 (n `div` 2) int2bin2 :: Int -> [Int] int2bin2 = unfold (== 0) (`mod` 2) (`div` 2) type Bit = Int chop81 :: [Bit] -> [[Bit]] chop81 [] = [] chop81 bits = take 8 bits : chop81 (drop 8 bits) chop82 :: [Bit] -> [[Bit]] chop82 = unfold null (take 8) (drop 8) e7chop = U.tt "e7chop" [ chop81 (int2bin2 62345) , chop82 (int2bin2 62345) ] [[1,0,0,1,0,0,0,1],[1,1,0,0,1,1,1,1]] mapu :: (a -> b) -> [a] -> [b] mapu f = unfold null (f . head) tail e7map = U.t "e7map" (mapu (^2) [2,3,4]) [4,9,16] iterate1 :: (a -> a) -> a -> [a] iterate1 f a = a : unfold (const False) f f a e7iterate = U.tt "e7iterate" [ take 5 $ iterate (+2) 1 , take 5 $ iterate1 (+2) 1 ] [1,3,5,7,9] 8 bin2int1 :: [Bit] -> Int bin2int1 bits = sum [ w * b | (w,b) <- zip weights bits ] where weights = iterate1 (*2) 1 bin2int2 :: [Bit] -> Int bin2int2 = foldr (\x y -> x + 2 * y) 0 make8 :: [Bit] -> [Bit] make8 bits = take 8 (bits ++ repeat 0) oddOnes :: [Bit] -> Bool oddOnes = odd . sum . filter (==1) addParity :: [Bit] -> [Bit] addParity bits = (if oddOnes bits then 1 else 0) : bits encode :: String -> [Bit] encode = concat . map (addParity . make8 . int2bin2 . ord) checkParity :: [Bit] -> [Bit] checkParity (x:xs) | x == 1 && oddOnes xs = xs | x == 0 && not (oddOnes xs) = xs | otherwise = error "parity error" chop9 :: [Bit] -> [[Bit]] chop9 = unfold null (take 9) (drop 9) decode :: [Bit] -> String decode = map (chr . bin2int2) . (map checkParity) . chop9 transmit :: String -> String transmit = decode . channel . encode channel :: [Bit] -> [Bit] channel = id e8 :: [Test] e8 = U.t "e8" (transmit "Harold" == "Harold") True 9 badtransmit :: String -> String badtransmit = decode . badchannel . encode badchannel :: [Bit] -> [Bit] badchannel (x:xs) = (if x == 1 then 0 else 1) : xs e9 :: [Test] e9 = U.e "e9" (badtransmit "Harold" == "Harold") "parity error" main :: IO Counts main = T.runTestTT $ T.TestList $ e1 ++ e2allt ++ e2allf ++ e2anyt ++ e2anyf ++ e2tw ++ e2dw ++ e3map ++ e3filter ++ e3filterbad ++ e4 ++ e5 ++ e6curry ++ e6uncurry ++ e7chop ++ e7map ++ e7iterate ++ e8 ++ e9
fe29985a6b9b5d3287202db9466cc73d246f16d8f2be20ea2b95b5b4e0780f7c
acfoltzer/minecraft-data
Region.hs
module Game.Minecraft.Region where import Codec.Compression.Zlib import Control.Applicative import Control.Monad import Data.Bits import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import Data.Serialize import qualified Data.Serialize.Builder as Builder import Data.Vector (Vector) import qualified Data.Vector as V import Data.Word import System.FilePath import Data.NBT import Game.Minecraft.Block -- | The (X,Z) coordinates specifying a 'Chunk' type ChunkCoords = (Int, Int) -- | The (X,Z) coordinates specifying a 'Region' type RegionCoords = (Int, Int) -- | A region contains a collection of 'Chunk's -- TODO: Replace bytestring with actual chunk data data Region = Region (Vector (Maybe Chunk)) deriving Show data Chunk = Chunk L.ByteString instance Show Chunk where show _ = "<chunk>" data Location = Loc Int Word8 getWord24be :: Get Word32 getWord24be = do s <- getBytes 3 return $! (fromIntegral (s `S.index` 0) `shift` 16) .|. (fromIntegral (s `S.index` 1) `shift` 8) .|. (fromIntegral (s `S.index` 2) ) putWord24be :: Putter Word32 putWord24be w | w `shift` (-24) /= 0 = error "tried to put word larger than 24 bits" | otherwise = putBuilder $ Builder.fromByteString bytes where bytes = S.pack [ (fromIntegral (w `shift` (-16)) :: Word8) , (fromIntegral (w `shift` (-8)) :: Word8) , (fromIntegral (w) :: Word8) ] instance Serialize Location where get = Loc . fromIntegral <$> getWord24be <*> getWord8 put (Loc offset sectorCount) = putWord24be (fromIntegral offset) >> put sectorCount getLocations :: Get (Vector Location) getLocations = V.replicateM 1024 (get :: Get Location) -- | Don't care about timestamps yet getTimestamps :: Get () getTimestamps = replicateM_ 1024 (get :: Get Word32) getChunks :: (Vector Location, L.ByteString) -> Vector (Maybe Chunk) getChunks (locV, chunkData) = V.map getChunk locV where getChunk (Loc 0 0) = mzero getChunk (Loc offset sectorCount) = return . Chunk . either error id . runGetLazy extractChunk $ L.take (4096 * (fromIntegral sectorCount)) (L.drop (4096 * (fromIntegral (offset - 2))) chunkData) extractChunk = do len <- fromIntegral <$> getWord32be compScheme <- getWord8 case compScheme of 1 -> fail "GZip-compressed chunks not supported" 2 -> decompress . L.fromChunks . (:[]) <$> ensure (len-1) getRawRegion :: Get (Vector Location, L.ByteString) getRawRegion = do locV <- getLocations getTimestamps chunkData <- getLazyByteString . fromIntegral =<< remaining return (locV, chunkData) instance Serialize Region where get = do raw <- getRawRegion return $ Region (getChunks raw) put = undefined | Given ' ChunkCoords ' , gives back the ' RegionCoords ' containing -- that chunk chunkToRegionCoords :: ChunkCoords -> RegionCoords chunkToRegionCoords (x, z) = (x `shift` (-5), z `shift` (-5)) | Given ' RegionCoords ' , gives back the filename of the region file -- containing that region regionFileName :: RegionCoords -> FilePath regionFileName (x, z) = "r" <.> show x <.> show z <.> "mcr" testRegion = decode <$> S.readFile ("testWorld/region" </> regionFileName (-1,-1)) :: IO (Either String Region) testChunk = do (Right (Region v)) <- testRegion let (Just (Chunk c)) = (V.!) v 1023 (Right nbt) = decodeLazy c return (nbt :: NBT) testBlocks = do (CompoundTag _ [(CompoundTag (Just "Level") ts)]) <- testChunk return $ filter (\t -> case t of (ByteArrayTag (Just "Blocks") _ _) -> True; _ -> False) ts testBlockIds :: IO [BlockId] testBlockIds = do [(ByteArrayTag _ _ bs)] <- testBlocks return (map (toEnum . fromIntegral) (S.unpack bs))
null
https://raw.githubusercontent.com/acfoltzer/minecraft-data/bd08d2eee862de0443d8ac409b4eb8cf4a373ff1/Game/Minecraft/Region.hs
haskell
| The (X,Z) coordinates specifying a 'Chunk' | The (X,Z) coordinates specifying a 'Region' | A region contains a collection of 'Chunk's TODO: Replace bytestring with actual chunk data | Don't care about timestamps yet that chunk containing that region
module Game.Minecraft.Region where import Codec.Compression.Zlib import Control.Applicative import Control.Monad import Data.Bits import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import Data.Serialize import qualified Data.Serialize.Builder as Builder import Data.Vector (Vector) import qualified Data.Vector as V import Data.Word import System.FilePath import Data.NBT import Game.Minecraft.Block type ChunkCoords = (Int, Int) type RegionCoords = (Int, Int) data Region = Region (Vector (Maybe Chunk)) deriving Show data Chunk = Chunk L.ByteString instance Show Chunk where show _ = "<chunk>" data Location = Loc Int Word8 getWord24be :: Get Word32 getWord24be = do s <- getBytes 3 return $! (fromIntegral (s `S.index` 0) `shift` 16) .|. (fromIntegral (s `S.index` 1) `shift` 8) .|. (fromIntegral (s `S.index` 2) ) putWord24be :: Putter Word32 putWord24be w | w `shift` (-24) /= 0 = error "tried to put word larger than 24 bits" | otherwise = putBuilder $ Builder.fromByteString bytes where bytes = S.pack [ (fromIntegral (w `shift` (-16)) :: Word8) , (fromIntegral (w `shift` (-8)) :: Word8) , (fromIntegral (w) :: Word8) ] instance Serialize Location where get = Loc . fromIntegral <$> getWord24be <*> getWord8 put (Loc offset sectorCount) = putWord24be (fromIntegral offset) >> put sectorCount getLocations :: Get (Vector Location) getLocations = V.replicateM 1024 (get :: Get Location) getTimestamps :: Get () getTimestamps = replicateM_ 1024 (get :: Get Word32) getChunks :: (Vector Location, L.ByteString) -> Vector (Maybe Chunk) getChunks (locV, chunkData) = V.map getChunk locV where getChunk (Loc 0 0) = mzero getChunk (Loc offset sectorCount) = return . Chunk . either error id . runGetLazy extractChunk $ L.take (4096 * (fromIntegral sectorCount)) (L.drop (4096 * (fromIntegral (offset - 2))) chunkData) extractChunk = do len <- fromIntegral <$> getWord32be compScheme <- getWord8 case compScheme of 1 -> fail "GZip-compressed chunks not supported" 2 -> decompress . L.fromChunks . (:[]) <$> ensure (len-1) getRawRegion :: Get (Vector Location, L.ByteString) getRawRegion = do locV <- getLocations getTimestamps chunkData <- getLazyByteString . fromIntegral =<< remaining return (locV, chunkData) instance Serialize Region where get = do raw <- getRawRegion return $ Region (getChunks raw) put = undefined | Given ' ChunkCoords ' , gives back the ' RegionCoords ' containing chunkToRegionCoords :: ChunkCoords -> RegionCoords chunkToRegionCoords (x, z) = (x `shift` (-5), z `shift` (-5)) | Given ' RegionCoords ' , gives back the filename of the region file regionFileName :: RegionCoords -> FilePath regionFileName (x, z) = "r" <.> show x <.> show z <.> "mcr" testRegion = decode <$> S.readFile ("testWorld/region" </> regionFileName (-1,-1)) :: IO (Either String Region) testChunk = do (Right (Region v)) <- testRegion let (Just (Chunk c)) = (V.!) v 1023 (Right nbt) = decodeLazy c return (nbt :: NBT) testBlocks = do (CompoundTag _ [(CompoundTag (Just "Level") ts)]) <- testChunk return $ filter (\t -> case t of (ByteArrayTag (Just "Blocks") _ _) -> True; _ -> False) ts testBlockIds :: IO [BlockId] testBlockIds = do [(ByteArrayTag _ _ bs)] <- testBlocks return (map (toEnum . fromIntegral) (S.unpack bs))
e1637646e0c68a87649c3ace3d3fa6d69f7c0c0987b1e5eb59cbbd7c95f4ca6e
anoma/juvix
Options.hs
module Commands.Dev.Internal.Arity.Options where import CommonOptions newtype InternalArityOptions = InternalArityOptions { _internalArityInputFile :: AppPath File } deriving stock (Data) makeLenses ''InternalArityOptions parseInternalArity :: Parser InternalArityOptions parseInternalArity = do _internalArityInputFile <- parseInputJuvixFile pure InternalArityOptions {..}
null
https://raw.githubusercontent.com/anoma/juvix/af63c36574da981e62d72b3c985fff2ba6266e8b/app/Commands/Dev/Internal/Arity/Options.hs
haskell
module Commands.Dev.Internal.Arity.Options where import CommonOptions newtype InternalArityOptions = InternalArityOptions { _internalArityInputFile :: AppPath File } deriving stock (Data) makeLenses ''InternalArityOptions parseInternalArity :: Parser InternalArityOptions parseInternalArity = do _internalArityInputFile <- parseInputJuvixFile pure InternalArityOptions {..}
62145296a344135bc1e680eea28a942ff5049507c1fcc9d2d609c603ad5883dd
abdulapopoola/SICPBook
Ex2.21.scm
#lang planet neil/sicp (define (map proc items) (if (null? items) nil (cons (proc (car items)) (map proc (cdr items))))) (define (square x) (* x x)) (define (square-list items) (if (null? items) nil (cons (square (car items)) (square-list (cdr items))))) (define (square-list2 items) (map square items)) (square-list (list 1 2 3 4)) (square-list2 (list 1 2 3 4)) ;;Using inbuilt map - (map square items)
null
https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%202/2.2/Ex2.21.scm
scheme
Using inbuilt map - (map square items)
#lang planet neil/sicp (define (map proc items) (if (null? items) nil (cons (proc (car items)) (map proc (cdr items))))) (define (square x) (* x x)) (define (square-list items) (if (null? items) nil (cons (square (car items)) (square-list (cdr items))))) (define (square-list2 items) (map square items)) (square-list (list 1 2 3 4)) (square-list2 (list 1 2 3 4))
dd0dca2047c6d04c8b145075378b0e5a5a6f191b065b0162d83985a225728b3d
gldubc/cast-machine
abstract.ml
(* open Types *) open Syntax open Primitives open Types.Print module Abstract = struct include Eager module Env = struct include Hashtbl.Make(struct type t = var let equal = (=) let hash = Hashtbl.hash end) end type c = tau * tau (* a bit hacky, done in order to define u, v and env properly *) type 'a au = [ `Cst of b | `Cls of var * e * 'a ] type 'a av = [ 'a au | `Cast of ('a au) * c ] type env = (env av) Env.t and u = (env au) and v = (env av) let env_empty () = Env.create 20 type ctxt = Nothing | LeftSquare of e * ctxt | RightSquare of v * ctxt | Cast of c * ctxt type sigma = SNothing | Frame of ctxt * env * kappa and kappa = Sigma of sigma | Bound of c * sigma (* type 'b id = 'b *) type ' a akap = [ ` Cast of c * ( ' a asig ) ] type kappa = kappa and sigma = kappa asig type kappa = kappa akap and sigma = kappa asig *) let comp : c -> c -> c = fun (t1,t2) (t1',t2') -> (cap t1 t1', cap t2 t2') let applycast : c -> v -> v = fun _ u -> u let cast : c -> kappa -> kappa = fun c -> function | Sigma s -> Bound (c, s) | Bound (d, s) -> Bound (comp c d, s) type state = e * env * ctxt * kappa type val_state = v * env * ctxt * kappa let rec term_step : state -> v = fun (e, rho, ctx, ka) -> match e with | Cst k -> val_step (`Cst k, rho, ctx, ka) | Var x -> val_step (Env.find rho x, rho, ctx, ka) | ( _ , x , m ) - > val_step ( ` Cls ( x , m , rho ) , rho , ctx , ka ) | App (l, m) -> term_step (l, rho, LeftSquare (m, ctx), ka) | Cast (m, c) when ctx = Nothing -> term_step (m, rho, Nothing, cast c ka) | Cast (m, c) -> term_step (m, rho, Cast (c, ctx), ka) | _ -> failwith "not implemented" and val_step : val_state -> v = fun (v, rho, ctx, ka) -> begin match ctx with | Nothing -> begin match ka with | Sigma SNothing -> v | Sigma (Frame (ctx, rho', ka)) -> val_step (v, rho', ctx, ka) | Bound (c, s) -> val_step (v, rho, Cast (c, Nothing), Sigma s) end | LeftSquare (m, ctx) -> term_step (m, rho, RightSquare (v, ctx), ka) | RightSquare (`Cls (x, m, rho'), Nothing) -> let () = Env.replace rho' x v in term_step (m, rho', Nothing, ka) | RightSquare (`Cls (x, m, rho'), ctx) -> let () = Env.replace rho' x v in term_step (m, rho', ctx, Sigma (Frame (ctx, rho, ka))) | Cast (c, ctx) -> let v' = applycast c v in val_step (v', rho, ctx, ka) | _ -> failwith "not implem" end let show_cast (c1, c2) = Printf.sprintf "(%s, %s)" (show_tau c1) (show_tau c2) let rec show_v = function | `Cst c -> pp_b c | `Cls _ -> "closure" | `Cast (u, c) -> Printf.sprintf "%s<%s>" (show_v u) (show_cast c) let wrap_abstract : e -> unit = fun e -> let _ = term_step (e, env_empty (), Nothing, Sigma SNothing) in print_string "" (* in print_endline (show_v v) *) end
null
https://raw.githubusercontent.com/gldubc/cast-machine/34d79c324cd0a9aff52865ead19e74126b96daaa/src/abstract.ml
ocaml
open Types a bit hacky, done in order to define u, v and env properly type 'b id = 'b in print_endline (show_v v)
open Syntax open Primitives open Types.Print module Abstract = struct include Eager module Env = struct include Hashtbl.Make(struct type t = var let equal = (=) let hash = Hashtbl.hash end) end type c = tau * tau type 'a au = [ `Cst of b | `Cls of var * e * 'a ] type 'a av = [ 'a au | `Cast of ('a au) * c ] type env = (env av) Env.t and u = (env au) and v = (env av) let env_empty () = Env.create 20 type ctxt = Nothing | LeftSquare of e * ctxt | RightSquare of v * ctxt | Cast of c * ctxt type sigma = SNothing | Frame of ctxt * env * kappa and kappa = Sigma of sigma | Bound of c * sigma type ' a akap = [ ` Cast of c * ( ' a asig ) ] type kappa = kappa and sigma = kappa asig type kappa = kappa akap and sigma = kappa asig *) let comp : c -> c -> c = fun (t1,t2) (t1',t2') -> (cap t1 t1', cap t2 t2') let applycast : c -> v -> v = fun _ u -> u let cast : c -> kappa -> kappa = fun c -> function | Sigma s -> Bound (c, s) | Bound (d, s) -> Bound (comp c d, s) type state = e * env * ctxt * kappa type val_state = v * env * ctxt * kappa let rec term_step : state -> v = fun (e, rho, ctx, ka) -> match e with | Cst k -> val_step (`Cst k, rho, ctx, ka) | Var x -> val_step (Env.find rho x, rho, ctx, ka) | ( _ , x , m ) - > val_step ( ` Cls ( x , m , rho ) , rho , ctx , ka ) | App (l, m) -> term_step (l, rho, LeftSquare (m, ctx), ka) | Cast (m, c) when ctx = Nothing -> term_step (m, rho, Nothing, cast c ka) | Cast (m, c) -> term_step (m, rho, Cast (c, ctx), ka) | _ -> failwith "not implemented" and val_step : val_state -> v = fun (v, rho, ctx, ka) -> begin match ctx with | Nothing -> begin match ka with | Sigma SNothing -> v | Sigma (Frame (ctx, rho', ka)) -> val_step (v, rho', ctx, ka) | Bound (c, s) -> val_step (v, rho, Cast (c, Nothing), Sigma s) end | LeftSquare (m, ctx) -> term_step (m, rho, RightSquare (v, ctx), ka) | RightSquare (`Cls (x, m, rho'), Nothing) -> let () = Env.replace rho' x v in term_step (m, rho', Nothing, ka) | RightSquare (`Cls (x, m, rho'), ctx) -> let () = Env.replace rho' x v in term_step (m, rho', ctx, Sigma (Frame (ctx, rho, ka))) | Cast (c, ctx) -> let v' = applycast c v in val_step (v', rho, ctx, ka) | _ -> failwith "not implem" end let show_cast (c1, c2) = Printf.sprintf "(%s, %s)" (show_tau c1) (show_tau c2) let rec show_v = function | `Cst c -> pp_b c | `Cls _ -> "closure" | `Cast (u, c) -> Printf.sprintf "%s<%s>" (show_v u) (show_cast c) let wrap_abstract : e -> unit = fun e -> let _ = term_step (e, env_empty (), Nothing, Sigma SNothing) in print_string "" end
b0ee3b23fe3da0ba65e3c4c3c6a133797ca087f2c0219c675967255ae46af71e
pariyatti/kosa
header.clj
(ns kosa.layouts.shared.header (:require [hiccup2.core :as h] [buddy.auth :as auth])) (def logout-js "This is a rather weird hack to drop Basic HTTP Auth credentials from the client. Adapted from the bookmarklet suggested here: -to-log-out-user-from-web-site-using-basic-authentication" "javascript:(function (c) { var a, b = 'You will be logged out now.'; try { a = document.execCommand('ClearAuthenticationCache') } catch (d) { } a || ((a = window.XMLHttpRequest ? new window.XMLHttpRequest : window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : void 0) ? (a.open('HEAD', c || location.href, !0, 'logout', (new Date).getTime().toString()), a.send(''), a = 1) : a = void 0); a || (b = 'Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser.'); if (alert(b)) { window.open('/login','_self'); } else { window.open('/login','_self'); } })(/*pass safeLocation here if you need*/);") (defn session-btn [req] (if (auth/authenticated? req) [:li [:a {:href "#" :onclick logout-js} "Logout"]] [:li [:a {:href "/login"} "Login"]])) (defn render [req title home-url other-title other-home-url] (h/html [:header {:class "header"} [:div {:class "header-logo"} [:a {:href home-url} [:img {:src "/images/pariyatti-logo-256-solid.png" :width "40" :height "40"}]] [:a {:href home-url} [:span title]]] [:div {:class "header-user"} [:p {:class "user-email"} (when other-title [:a {:href other-home-url} (str "Switch to " other-title)]) [:span "&nbsp; | &nbsp;"] [:div.menu-wrapper [:input {:id "menu-check" :class "menu" :type "checkbox" :name "menu"}] [:label {:class "menu btn btn-secondary" :for "menu-check"} "Account"] [:ul {:class "submenu"} #_[:li [:a {:href "#"} "TODO: Settings"]] (session-btn req)]]]]]))
null
https://raw.githubusercontent.com/pariyatti/kosa/68099ccb830b99a9d0ead81ccfd878ba72020e78/src/kosa/layouts/shared/header.clj
clojure
")
(ns kosa.layouts.shared.header (:require [hiccup2.core :as h] [buddy.auth :as auth])) (def logout-js "This is a rather weird hack to drop Basic HTTP Auth credentials from the client. Adapted from the bookmarklet suggested here: -to-log-out-user-from-web-site-using-basic-authentication" "javascript:(function (c) { try { a = document.execCommand('ClearAuthenticationCache') } catch (d) { } if (alert(b)) { } else { } (defn session-btn [req] (if (auth/authenticated? req) [:li [:a {:href "#" :onclick logout-js} "Logout"]] [:li [:a {:href "/login"} "Login"]])) (defn render [req title home-url other-title other-home-url] (h/html [:header {:class "header"} [:div {:class "header-logo"} [:a {:href home-url} [:img {:src "/images/pariyatti-logo-256-solid.png" :width "40" :height "40"}]] [:a {:href home-url} [:span title]]] [:div {:class "header-user"} [:p {:class "user-email"} (when other-title [:a {:href other-home-url} (str "Switch to " other-title)]) [:span "&nbsp; | &nbsp;"] [:div.menu-wrapper [:input {:id "menu-check" :class "menu" :type "checkbox" :name "menu"}] [:label {:class "menu btn btn-secondary" :for "menu-check"} "Account"] [:ul {:class "submenu"} #_[:li [:a {:href "#"} "TODO: Settings"]] (session-btn req)]]]]]))
d7ab49f21537d8f9736b04633949d980b2d9ed4c8889c66f52f931927d1d6bba
helium/blockchain-core
icdf_eqc.erl
%%%----------------------------------------------------------------------------- %% Evaluate probabilistic accuracy of calculating inverse cumulative distritbution %% function. %% %% - Generate a random list: [{Weight: float, Node: binary}, ...] %% %% - Check that the number of times a node gets picked is roughly equal to it's %% weight of getting picked in the list. Statistically, those count and weights %% should line up, probably. Maybe. %% %% Inverse Cumulative Distribution Function gives the value associated with a %% _cumulative_ proabability. It ONLY works with cumulative probabilities and that's %% what makes it magical. %%%----------------------------------------------------------------------------- -module(icdf_eqc). -include_lib("eqc/include/eqc.hrl"). -include_lib("eunit/include/eunit.hrl"). -export([prop_icdf_check/0]). prop_icdf_check() -> ?FORALL({Population, Iterations, Hash}, {gen_population(), gen_iterations(), binary(32)}, begin %% Use entropy to generate randval for running iterations Entropy = blockchain_utils:rand_state(Hash), %% Need this to match counters against assumptions CumulativePopulationList = cdf(Population), CumulativePopulationMap = maps:from_list(CumulativePopulationList), Intiial acc for the counter , each node starts with a 0 count InitAcc = maps:map(fun(_, _) -> 0 end, CumulativePopulationMap), %% Track all counts a node gets picked {Counter, _} = lists:foldl(fun(_I, {Acc, AccEntropy}) -> {RandVal, NewEntropy} = rand:uniform_s(AccEntropy), {ok, Node} = blockchain_utils:icdf_select(Population, RandVal), {maps:update_with(Node, fun(X) -> X + 1 end, 1, Acc), NewEntropy} end, {InitAcc, Entropy}, lists:seq(1, Iterations)), Check that it 's roughly equal or more appropriately within some threshold ( 0.1 is good enough , probably ) . %% Fucking probabilities. CheckCounterLinesUp = lists:all(fun({Node, Count}) -> abs(Count/Iterations - maps:get(Node, CumulativePopulationMap)) < 0.1 end, maps:to_list(Counter)), ?WHENFAIL(begin io:format("Population: ~p~n", [Population]), io:format("CDF: ~p~n", [CumulativePopulationList]), io:format("Counter: ~p~n", [Counter]) end, noshrink(conjunction( [{verify_population_exists, length(Population) > 0}, {verify_unique_nodes, length(Population) == length(lists:usort(Population))}, it 's pretty much 1.0 but damn floats {verify_counts_line_up, CheckCounterLinesUp}] ) ) ) end). gen_iterations() -> %% Count these many times, lower counts don't quite "work" in the sense that the %% error threshold maybe too high for eqc to work with. But given enough iterations %% counts _should_ line up with the weights. elements([1000, 10000, 100000]). gen_population() -> %% We need unique node names to mimic unique hotspot addresses %% Also keeps things simple. ?SUCHTHAT(L, list({gen_node(), gen_weight()}), length(L) >= 3). gen_node() -> %% Some random node name. binary(32). gen_weight() -> A viable weight between ( 0 , 1 ) , open intervals . gen_prob(). gen_prob() -> %% Some probability ?SUCHTHAT(W, real(), W > 0 andalso W < 1). cdf(PopulationList) -> %% This takes the population and coverts it to a cumulative distribution. Sum = lists:sum([Weight || {_Node, Weight} <- PopulationList]), [{Node, blockchain_utils:normalize_float(Weight/Sum)} || {Node, Weight} <- PopulationList].
null
https://raw.githubusercontent.com/helium/blockchain-core/9011de7537ecfd737074b85b7b16e7d8e1ceef00/eqc/icdf_eqc.erl
erlang
----------------------------------------------------------------------------- Evaluate probabilistic accuracy of calculating inverse cumulative distritbution function. - Generate a random list: [{Weight: float, Node: binary}, ...] - Check that the number of times a node gets picked is roughly equal to it's weight of getting picked in the list. Statistically, those count and weights should line up, probably. Maybe. Inverse Cumulative Distribution Function gives the value associated with a _cumulative_ proabability. It ONLY works with cumulative probabilities and that's what makes it magical. ----------------------------------------------------------------------------- Use entropy to generate randval for running iterations Need this to match counters against assumptions Track all counts a node gets picked Fucking probabilities. Count these many times, lower counts don't quite "work" in the sense that the error threshold maybe too high for eqc to work with. But given enough iterations counts _should_ line up with the weights. We need unique node names to mimic unique hotspot addresses Also keeps things simple. Some random node name. Some probability This takes the population and coverts it to a cumulative distribution.
-module(icdf_eqc). -include_lib("eqc/include/eqc.hrl"). -include_lib("eunit/include/eunit.hrl"). -export([prop_icdf_check/0]). prop_icdf_check() -> ?FORALL({Population, Iterations, Hash}, {gen_population(), gen_iterations(), binary(32)}, begin Entropy = blockchain_utils:rand_state(Hash), CumulativePopulationList = cdf(Population), CumulativePopulationMap = maps:from_list(CumulativePopulationList), Intiial acc for the counter , each node starts with a 0 count InitAcc = maps:map(fun(_, _) -> 0 end, CumulativePopulationMap), {Counter, _} = lists:foldl(fun(_I, {Acc, AccEntropy}) -> {RandVal, NewEntropy} = rand:uniform_s(AccEntropy), {ok, Node} = blockchain_utils:icdf_select(Population, RandVal), {maps:update_with(Node, fun(X) -> X + 1 end, 1, Acc), NewEntropy} end, {InitAcc, Entropy}, lists:seq(1, Iterations)), Check that it 's roughly equal or more appropriately within some threshold ( 0.1 is good enough , probably ) . CheckCounterLinesUp = lists:all(fun({Node, Count}) -> abs(Count/Iterations - maps:get(Node, CumulativePopulationMap)) < 0.1 end, maps:to_list(Counter)), ?WHENFAIL(begin io:format("Population: ~p~n", [Population]), io:format("CDF: ~p~n", [CumulativePopulationList]), io:format("Counter: ~p~n", [Counter]) end, noshrink(conjunction( [{verify_population_exists, length(Population) > 0}, {verify_unique_nodes, length(Population) == length(lists:usort(Population))}, it 's pretty much 1.0 but damn floats {verify_counts_line_up, CheckCounterLinesUp}] ) ) ) end). gen_iterations() -> elements([1000, 10000, 100000]). gen_population() -> ?SUCHTHAT(L, list({gen_node(), gen_weight()}), length(L) >= 3). gen_node() -> binary(32). gen_weight() -> A viable weight between ( 0 , 1 ) , open intervals . gen_prob(). gen_prob() -> ?SUCHTHAT(W, real(), W > 0 andalso W < 1). cdf(PopulationList) -> Sum = lists:sum([Weight || {_Node, Weight} <- PopulationList]), [{Node, blockchain_utils:normalize_float(Weight/Sum)} || {Node, Weight} <- PopulationList].
f7eb6791773c6549c1eee1407e3c2ed036c0fddb6b62b7f2925cf88973c23890
dmitryvk/sbcl-win32-threads
primtype.lisp
;;;; machine-independent aspects of the object representation and ;;;; primitive types This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB!VM") ;;;; primitive type definitions (/show0 "primtype.lisp 17") (!def-primitive-type t (descriptor-reg)) (/show0 "primtype.lisp 20") (setf *backend-t-primitive-type* (primitive-type-or-lose t)) ;;; primitive integer types that fit in registers (/show0 "primtype.lisp 24") (!def-primitive-type positive-fixnum (any-reg signed-reg unsigned-reg) :type (unsigned-byte #.sb!vm:n-positive-fixnum-bits)) (/show0 "primtype.lisp 27") #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 32) '(and) '(or)) (!def-primitive-type unsigned-byte-31 (signed-reg unsigned-reg descriptor-reg) :type (unsigned-byte 31)) (/show0 "primtype.lisp 31") #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 32) '(and) '(or)) (!def-primitive-type unsigned-byte-32 (unsigned-reg descriptor-reg) :type (unsigned-byte 32)) (/show0 "primtype.lisp 35") #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or)) (!def-primitive-type unsigned-byte-63 (signed-reg unsigned-reg descriptor-reg) :type (unsigned-byte 63)) #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or)) (!def-primitive-type unsigned-byte-64 (unsigned-reg descriptor-reg) :type (unsigned-byte 64)) (!def-primitive-type fixnum (any-reg signed-reg) :type (signed-byte #.(1+ sb!vm:n-positive-fixnum-bits))) #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 32) '(and) '(or)) (!def-primitive-type signed-byte-32 (signed-reg descriptor-reg) :type (signed-byte 32)) #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or)) (!def-primitive-type signed-byte-64 (signed-reg descriptor-reg) :type (signed-byte 64)) (defvar *fixnum-primitive-type* (primitive-type-or-lose 'fixnum)) (/show0 "primtype.lisp 53") (!def-primitive-type-alias tagged-num (:or positive-fixnum fixnum)) (progn (!def-primitive-type-alias unsigned-num #1= #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or)) (:or unsigned-byte-64 unsigned-byte-63 positive-fixnum) #!-#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or)) (:or unsigned-byte-32 unsigned-byte-31 positive-fixnum)) (!def-primitive-type-alias signed-num #2= #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or)) (:or signed-byte-64 fixnum unsigned-byte-63 positive-fixnum) #!-#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or)) (:or signed-byte-32 fixnum unsigned-byte-31 positive-fixnum)) (!def-primitive-type-alias untagged-num (:or . #.(sort (copy-list (union (cdr '#1#) (cdr '#2#))) #'string<)))) ;;; other primitive immediate types (/show0 "primtype.lisp 68") (!def-primitive-type character (character-reg any-reg)) ;;; primitive pointer types (/show0 "primtype.lisp 73") (!def-primitive-type function (descriptor-reg)) (!def-primitive-type list (descriptor-reg)) (!def-primitive-type instance (descriptor-reg)) (/show0 "primtype.lisp 77") (!def-primitive-type funcallable-instance (descriptor-reg)) ;;; primitive other-pointer number types (/show0 "primtype.lisp 81") (!def-primitive-type bignum (descriptor-reg)) (!def-primitive-type ratio (descriptor-reg)) (!def-primitive-type complex (descriptor-reg)) (/show0 "about to !DEF-PRIMITIVE-TYPE SINGLE-FLOAT") (!def-primitive-type single-float (single-reg descriptor-reg)) (/show0 "about to !DEF-PRIMITIVE-TYPE DOUBLE-FLOAT") (!def-primitive-type double-float (double-reg descriptor-reg)) (/show0 "about to !DEF-PRIMITIVE-TYPE COMPLEX-SINGLE-FLOAT") (!def-primitive-type complex-single-float (complex-single-reg descriptor-reg) :type (complex single-float)) (/show0 "about to !DEF-PRIMITIVE-TYPE COMPLEX-DOUBLE-FLOAT") (!def-primitive-type complex-double-float (complex-double-reg descriptor-reg) :type (complex double-float)) ;;; primitive other-pointer array types (/show0 "primtype.lisp 96") (macrolet ((define-simple-array-primitive-types () `(progn ,@(map 'list (lambda (saetp) `(!def-primitive-type ,(saetp-primitive-type-name saetp) (descriptor-reg) :type (simple-array ,(saetp-specifier saetp) (*)))) *specialized-array-element-type-properties*)))) (define-simple-array-primitive-types)) ;;; Note: The complex array types are not included, 'cause it is ;;; pointless to restrict VOPs to them. ;;; other primitive other-pointer types (!def-primitive-type system-area-pointer (sap-reg descriptor-reg)) (!def-primitive-type weak-pointer (descriptor-reg)) ;;; miscellaneous primitive types that don't exist at the LISP level (!def-primitive-type catch-block (catch-block) :type nil) ;;;; PRIMITIVE-TYPE-OF and friends ;;; Return the most restrictive primitive type that contains OBJECT. (/show0 "primtype.lisp 147") (!def-vm-support-routine primitive-type-of (object) (let ((type (ctype-of object))) (cond ((not (member-type-p type)) (primitive-type type)) ((and (eql 1 (member-type-size type)) (equal (member-type-members type) '(nil))) (primitive-type-or-lose 'list)) (t *backend-t-primitive-type*)))) ;;; Return the primitive type corresponding to a type descriptor structure . The second value is true when the primitive type is ;;; exactly equivalent to the argument Lisp type. ;;; ;;; In a bootstrapping situation, we should be careful to use the ;;; correct values for the system parameters. ;;; ;;; We need an aux function because we need to use both ! DEF - VM - SUPPORT - ROUTINE and DEFUN - CACHED . (/show0 "primtype.lisp 188") (!def-vm-support-routine primitive-type (type) (sb!kernel::maybe-reparse-specifier! type) (primitive-type-aux type)) (/show0 "primtype.lisp 191") (defun-cached (primitive-type-aux :hash-function (lambda (x) (logand (type-hash-value x) #x1FF)) :hash-bits 9 :values 2 :default (values nil :empty)) ((type eq)) (declare (type ctype type)) (macrolet ((any () '(values *backend-t-primitive-type* nil)) (exactly (type) `(values (primitive-type-or-lose ',type) t)) (part-of (type) `(values (primitive-type-or-lose ',type) nil))) (flet ((maybe-numeric-type-union (t1 t2) (let ((t1-name (primitive-type-name t1)) (t2-name (primitive-type-name t2))) (case t1-name (positive-fixnum (if (or (eq t2-name 'fixnum) (eq t2-name (ecase sb!vm::n-machine-word-bits (32 'signed-byte-32) (64 'signed-byte-64))) (eq t2-name (ecase sb!vm::n-machine-word-bits (32 'unsigned-byte-31) (64 'unsigned-byte-63))) (eq t2-name (ecase sb!vm::n-machine-word-bits (32 'unsigned-byte-32) (64 'unsigned-byte-64)))) t2)) (fixnum (case t2-name (#.(ecase sb!vm::n-machine-word-bits (32 'signed-byte-32) (64 'signed-byte-64)) t2) (#.(ecase sb!vm::n-machine-word-bits (32 'unsigned-byte-31) (64 'unsigned-byte-63)) (primitive-type-or-lose (ecase sb!vm::n-machine-word-bits (32 'signed-byte-32) (64 'signed-byte-64)))))) (#.(ecase sb!vm::n-machine-word-bits (32 'signed-byte-32) (64 'signed-byte-64)) (if (eq t2-name (ecase sb!vm::n-machine-word-bits (32 'unsigned-byte-31) (64 'unsigned-byte-63))) t1)) (#.(ecase sb!vm::n-machine-word-bits (32 'unsigned-byte-31) (64 'unsigned-byte-63)) (if (eq t2-name (ecase sb!vm::n-machine-word-bits (32 'unsigned-byte-32) (64 'unsigned-byte-64))) t2)))))) (etypecase type (numeric-type (let ((lo (numeric-type-low type)) (hi (numeric-type-high type))) (case (numeric-type-complexp type) (:real (case (numeric-type-class type) (integer (cond ((and hi lo) (dolist (spec `((positive-fixnum 0 ,sb!xc:most-positive-fixnum) ,@(ecase sb!vm::n-machine-word-bits (32 `((unsigned-byte-31 0 ,(1- (ash 1 31))) (unsigned-byte-32 0 ,(1- (ash 1 32))))) (64 `((unsigned-byte-63 0 ,(1- (ash 1 63))) (unsigned-byte-64 0 ,(1- (ash 1 64)))))) (fixnum ,sb!xc:most-negative-fixnum ,sb!xc:most-positive-fixnum) ,(ecase sb!vm::n-machine-word-bits (32 `(signed-byte-32 ,(ash -1 31) ,(1- (ash 1 31)))) (64 `(signed-byte-64 ,(ash -1 63) ,(1- (ash 1 63)))))) (if (or (< hi sb!xc:most-negative-fixnum) (> lo sb!xc:most-positive-fixnum)) (part-of bignum) (any))) (let ((type (car spec)) (min (cadr spec)) (max (caddr spec))) (when (<= min lo hi max) (return (values (primitive-type-or-lose type) (and (= lo min) (= hi max)))))))) ((or (and hi (< hi sb!xc:most-negative-fixnum)) (and lo (> lo sb!xc:most-positive-fixnum))) (part-of bignum)) (t (any)))) (float (let ((exact (and (null lo) (null hi)))) (case (numeric-type-format type) ((short-float single-float) (values (primitive-type-or-lose 'single-float) exact)) ((double-float) (values (primitive-type-or-lose 'double-float) exact)) (t (any))))) (t (any)))) (:complex (if (eq (numeric-type-class type) 'float) (let ((exact (and (null lo) (null hi)))) (case (numeric-type-format type) ((short-float single-float) (values (primitive-type-or-lose 'complex-single-float) exact)) ((double-float long-float) (values (primitive-type-or-lose 'complex-double-float) exact)) (t (part-of complex)))) (part-of complex))) (t (any))))) (array-type (if (array-type-complexp type) (any) (let* ((dims (array-type-dimensions type)) (etype (array-type-specialized-element-type type)) (type-spec (type-specifier etype)) ;; FIXME: We're _WHAT_? Testing for type equality ;; with a specifier and #'EQUAL? *BOGGLE*. -- CSR , 2003 - 06 - 24 (ptype (cdr (assoc type-spec *simple-array-primitive-types* :test #'equal)))) (if (and (consp dims) (null (rest dims)) ptype) (values (primitive-type-or-lose ptype) (eq (first dims) '*)) (any))))) (union-type (if (type= type (specifier-type 'list)) (exactly list) (let ((types (union-type-types type))) (multiple-value-bind (res exact) (primitive-type (first types)) (dolist (type (rest types) (values res exact)) (multiple-value-bind (ptype ptype-exact) (primitive-type type) (unless ptype-exact (setq exact nil)) (unless (eq ptype res) (let ((new-ptype (or (maybe-numeric-type-union res ptype) (maybe-numeric-type-union ptype res)))) (if new-ptype (setq res new-ptype) (return (any))))))))))) (intersection-type (let ((types (intersection-type-types type)) (res (any))) ;; why NIL for the exact? Well, we assume that the ;; intersection type is in fact doing something for us: ;; that is, that each of the types in the intersection is ;; in fact cutting off some of the type lattice. Since no ;; intersection type is represented by a primitive type and ;; primitive types are mutually exclusive, it follows that ;; no intersection type can represent the entirety of the primitive type . ( And NIL is the conservative answer , anyway ) . -- CSR , 2006 - 09 - 14 (dolist (type types (values res nil)) (multiple-value-bind (ptype) (primitive-type type) (cond ;; if the result so far is (any), any improvement on ;; the specificity of the primitive type is valid. ((eq res (any)) (setq res ptype)) ;; if the primitive type returned is (any), the ;; result so far is valid. Likewise, if the ;; primitive type is the same as the result so far, ;; everything is fine. ((or (eq ptype (any)) (eq ptype res))) ;; otherwise, we have something hairy and confusing, ;; such as (and condition funcallable-instance). Punt . (t (return (any)))))))) (member-type (let (res) (block nil (mapc-member-type-members (lambda (member) (let ((ptype (primitive-type-of member))) (if res (unless (eq ptype res) (let ((new-ptype (or (maybe-numeric-type-union res ptype) (maybe-numeric-type-union ptype res)))) (if new-ptype (setq res new-ptype) (return (any))))) (setf res ptype)))) type)) res)) (named-type (ecase (named-type-name type) ((t *) (values *backend-t-primitive-type* t)) ((instance) (exactly instance)) ((funcallable-instance) (part-of function)) ((extended-sequence) (any)) ((nil) (any)))) (character-set-type (let ((pairs (character-set-type-pairs type))) (if (and (= (length pairs) 1) (= (caar pairs) 0) (= (cdar pairs) (1- sb!xc:char-code-limit))) (exactly character) (part-of character)))) (built-in-classoid (case (classoid-name type) ((complex function system-area-pointer weak-pointer) (values (primitive-type-or-lose (classoid-name type)) t)) (cons-type (part-of list)) (t (any)))) (fun-type (exactly function)) (classoid (if (csubtypep type (specifier-type 'function)) (part-of function) (part-of instance))) (ctype (if (csubtypep type (specifier-type 'function)) (part-of function) (any))))))) (/show0 "primtype.lisp end of file")
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/compiler/generic/primtype.lisp
lisp
machine-independent aspects of the object representation and primitive types more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. primitive type definitions primitive integer types that fit in registers other primitive immediate types primitive pointer types primitive other-pointer number types primitive other-pointer array types Note: The complex array types are not included, 'cause it is pointless to restrict VOPs to them. other primitive other-pointer types miscellaneous primitive types that don't exist at the LISP level PRIMITIVE-TYPE-OF and friends Return the most restrictive primitive type that contains OBJECT. Return the primitive type corresponding to a type descriptor exactly equivalent to the argument Lisp type. In a bootstrapping situation, we should be careful to use the correct values for the system parameters. We need an aux function because we need to use both FIXME: We're _WHAT_? Testing for type equality with a specifier and #'EQUAL? *BOGGLE*. -- why NIL for the exact? Well, we assume that the intersection type is in fact doing something for us: that is, that each of the types in the intersection is in fact cutting off some of the type lattice. Since no intersection type is represented by a primitive type and primitive types are mutually exclusive, it follows that no intersection type can represent the entirety of the if the result so far is (any), any improvement on the specificity of the primitive type is valid. if the primitive type returned is (any), the result so far is valid. Likewise, if the primitive type is the same as the result so far, everything is fine. otherwise, we have something hairy and confusing, such as (and condition funcallable-instance).
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB!VM") (/show0 "primtype.lisp 17") (!def-primitive-type t (descriptor-reg)) (/show0 "primtype.lisp 20") (setf *backend-t-primitive-type* (primitive-type-or-lose t)) (/show0 "primtype.lisp 24") (!def-primitive-type positive-fixnum (any-reg signed-reg unsigned-reg) :type (unsigned-byte #.sb!vm:n-positive-fixnum-bits)) (/show0 "primtype.lisp 27") #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 32) '(and) '(or)) (!def-primitive-type unsigned-byte-31 (signed-reg unsigned-reg descriptor-reg) :type (unsigned-byte 31)) (/show0 "primtype.lisp 31") #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 32) '(and) '(or)) (!def-primitive-type unsigned-byte-32 (unsigned-reg descriptor-reg) :type (unsigned-byte 32)) (/show0 "primtype.lisp 35") #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or)) (!def-primitive-type unsigned-byte-63 (signed-reg unsigned-reg descriptor-reg) :type (unsigned-byte 63)) #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or)) (!def-primitive-type unsigned-byte-64 (unsigned-reg descriptor-reg) :type (unsigned-byte 64)) (!def-primitive-type fixnum (any-reg signed-reg) :type (signed-byte #.(1+ sb!vm:n-positive-fixnum-bits))) #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 32) '(and) '(or)) (!def-primitive-type signed-byte-32 (signed-reg descriptor-reg) :type (signed-byte 32)) #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or)) (!def-primitive-type signed-byte-64 (signed-reg descriptor-reg) :type (signed-byte 64)) (defvar *fixnum-primitive-type* (primitive-type-or-lose 'fixnum)) (/show0 "primtype.lisp 53") (!def-primitive-type-alias tagged-num (:or positive-fixnum fixnum)) (progn (!def-primitive-type-alias unsigned-num #1= #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or)) (:or unsigned-byte-64 unsigned-byte-63 positive-fixnum) #!-#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or)) (:or unsigned-byte-32 unsigned-byte-31 positive-fixnum)) (!def-primitive-type-alias signed-num #2= #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or)) (:or signed-byte-64 fixnum unsigned-byte-63 positive-fixnum) #!-#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or)) (:or signed-byte-32 fixnum unsigned-byte-31 positive-fixnum)) (!def-primitive-type-alias untagged-num (:or . #.(sort (copy-list (union (cdr '#1#) (cdr '#2#))) #'string<)))) (/show0 "primtype.lisp 68") (!def-primitive-type character (character-reg any-reg)) (/show0 "primtype.lisp 73") (!def-primitive-type function (descriptor-reg)) (!def-primitive-type list (descriptor-reg)) (!def-primitive-type instance (descriptor-reg)) (/show0 "primtype.lisp 77") (!def-primitive-type funcallable-instance (descriptor-reg)) (/show0 "primtype.lisp 81") (!def-primitive-type bignum (descriptor-reg)) (!def-primitive-type ratio (descriptor-reg)) (!def-primitive-type complex (descriptor-reg)) (/show0 "about to !DEF-PRIMITIVE-TYPE SINGLE-FLOAT") (!def-primitive-type single-float (single-reg descriptor-reg)) (/show0 "about to !DEF-PRIMITIVE-TYPE DOUBLE-FLOAT") (!def-primitive-type double-float (double-reg descriptor-reg)) (/show0 "about to !DEF-PRIMITIVE-TYPE COMPLEX-SINGLE-FLOAT") (!def-primitive-type complex-single-float (complex-single-reg descriptor-reg) :type (complex single-float)) (/show0 "about to !DEF-PRIMITIVE-TYPE COMPLEX-DOUBLE-FLOAT") (!def-primitive-type complex-double-float (complex-double-reg descriptor-reg) :type (complex double-float)) (/show0 "primtype.lisp 96") (macrolet ((define-simple-array-primitive-types () `(progn ,@(map 'list (lambda (saetp) `(!def-primitive-type ,(saetp-primitive-type-name saetp) (descriptor-reg) :type (simple-array ,(saetp-specifier saetp) (*)))) *specialized-array-element-type-properties*)))) (define-simple-array-primitive-types)) (!def-primitive-type system-area-pointer (sap-reg descriptor-reg)) (!def-primitive-type weak-pointer (descriptor-reg)) (!def-primitive-type catch-block (catch-block) :type nil) (/show0 "primtype.lisp 147") (!def-vm-support-routine primitive-type-of (object) (let ((type (ctype-of object))) (cond ((not (member-type-p type)) (primitive-type type)) ((and (eql 1 (member-type-size type)) (equal (member-type-members type) '(nil))) (primitive-type-or-lose 'list)) (t *backend-t-primitive-type*)))) structure . The second value is true when the primitive type is ! DEF - VM - SUPPORT - ROUTINE and DEFUN - CACHED . (/show0 "primtype.lisp 188") (!def-vm-support-routine primitive-type (type) (sb!kernel::maybe-reparse-specifier! type) (primitive-type-aux type)) (/show0 "primtype.lisp 191") (defun-cached (primitive-type-aux :hash-function (lambda (x) (logand (type-hash-value x) #x1FF)) :hash-bits 9 :values 2 :default (values nil :empty)) ((type eq)) (declare (type ctype type)) (macrolet ((any () '(values *backend-t-primitive-type* nil)) (exactly (type) `(values (primitive-type-or-lose ',type) t)) (part-of (type) `(values (primitive-type-or-lose ',type) nil))) (flet ((maybe-numeric-type-union (t1 t2) (let ((t1-name (primitive-type-name t1)) (t2-name (primitive-type-name t2))) (case t1-name (positive-fixnum (if (or (eq t2-name 'fixnum) (eq t2-name (ecase sb!vm::n-machine-word-bits (32 'signed-byte-32) (64 'signed-byte-64))) (eq t2-name (ecase sb!vm::n-machine-word-bits (32 'unsigned-byte-31) (64 'unsigned-byte-63))) (eq t2-name (ecase sb!vm::n-machine-word-bits (32 'unsigned-byte-32) (64 'unsigned-byte-64)))) t2)) (fixnum (case t2-name (#.(ecase sb!vm::n-machine-word-bits (32 'signed-byte-32) (64 'signed-byte-64)) t2) (#.(ecase sb!vm::n-machine-word-bits (32 'unsigned-byte-31) (64 'unsigned-byte-63)) (primitive-type-or-lose (ecase sb!vm::n-machine-word-bits (32 'signed-byte-32) (64 'signed-byte-64)))))) (#.(ecase sb!vm::n-machine-word-bits (32 'signed-byte-32) (64 'signed-byte-64)) (if (eq t2-name (ecase sb!vm::n-machine-word-bits (32 'unsigned-byte-31) (64 'unsigned-byte-63))) t1)) (#.(ecase sb!vm::n-machine-word-bits (32 'unsigned-byte-31) (64 'unsigned-byte-63)) (if (eq t2-name (ecase sb!vm::n-machine-word-bits (32 'unsigned-byte-32) (64 'unsigned-byte-64))) t2)))))) (etypecase type (numeric-type (let ((lo (numeric-type-low type)) (hi (numeric-type-high type))) (case (numeric-type-complexp type) (:real (case (numeric-type-class type) (integer (cond ((and hi lo) (dolist (spec `((positive-fixnum 0 ,sb!xc:most-positive-fixnum) ,@(ecase sb!vm::n-machine-word-bits (32 `((unsigned-byte-31 0 ,(1- (ash 1 31))) (unsigned-byte-32 0 ,(1- (ash 1 32))))) (64 `((unsigned-byte-63 0 ,(1- (ash 1 63))) (unsigned-byte-64 0 ,(1- (ash 1 64)))))) (fixnum ,sb!xc:most-negative-fixnum ,sb!xc:most-positive-fixnum) ,(ecase sb!vm::n-machine-word-bits (32 `(signed-byte-32 ,(ash -1 31) ,(1- (ash 1 31)))) (64 `(signed-byte-64 ,(ash -1 63) ,(1- (ash 1 63)))))) (if (or (< hi sb!xc:most-negative-fixnum) (> lo sb!xc:most-positive-fixnum)) (part-of bignum) (any))) (let ((type (car spec)) (min (cadr spec)) (max (caddr spec))) (when (<= min lo hi max) (return (values (primitive-type-or-lose type) (and (= lo min) (= hi max)))))))) ((or (and hi (< hi sb!xc:most-negative-fixnum)) (and lo (> lo sb!xc:most-positive-fixnum))) (part-of bignum)) (t (any)))) (float (let ((exact (and (null lo) (null hi)))) (case (numeric-type-format type) ((short-float single-float) (values (primitive-type-or-lose 'single-float) exact)) ((double-float) (values (primitive-type-or-lose 'double-float) exact)) (t (any))))) (t (any)))) (:complex (if (eq (numeric-type-class type) 'float) (let ((exact (and (null lo) (null hi)))) (case (numeric-type-format type) ((short-float single-float) (values (primitive-type-or-lose 'complex-single-float) exact)) ((double-float long-float) (values (primitive-type-or-lose 'complex-double-float) exact)) (t (part-of complex)))) (part-of complex))) (t (any))))) (array-type (if (array-type-complexp type) (any) (let* ((dims (array-type-dimensions type)) (etype (array-type-specialized-element-type type)) (type-spec (type-specifier etype)) CSR , 2003 - 06 - 24 (ptype (cdr (assoc type-spec *simple-array-primitive-types* :test #'equal)))) (if (and (consp dims) (null (rest dims)) ptype) (values (primitive-type-or-lose ptype) (eq (first dims) '*)) (any))))) (union-type (if (type= type (specifier-type 'list)) (exactly list) (let ((types (union-type-types type))) (multiple-value-bind (res exact) (primitive-type (first types)) (dolist (type (rest types) (values res exact)) (multiple-value-bind (ptype ptype-exact) (primitive-type type) (unless ptype-exact (setq exact nil)) (unless (eq ptype res) (let ((new-ptype (or (maybe-numeric-type-union res ptype) (maybe-numeric-type-union ptype res)))) (if new-ptype (setq res new-ptype) (return (any))))))))))) (intersection-type (let ((types (intersection-type-types type)) (res (any))) primitive type . ( And NIL is the conservative answer , anyway ) . -- CSR , 2006 - 09 - 14 (dolist (type types (values res nil)) (multiple-value-bind (ptype) (primitive-type type) (cond ((eq res (any)) (setq res ptype)) ((or (eq ptype (any)) (eq ptype res))) Punt . (t (return (any)))))))) (member-type (let (res) (block nil (mapc-member-type-members (lambda (member) (let ((ptype (primitive-type-of member))) (if res (unless (eq ptype res) (let ((new-ptype (or (maybe-numeric-type-union res ptype) (maybe-numeric-type-union ptype res)))) (if new-ptype (setq res new-ptype) (return (any))))) (setf res ptype)))) type)) res)) (named-type (ecase (named-type-name type) ((t *) (values *backend-t-primitive-type* t)) ((instance) (exactly instance)) ((funcallable-instance) (part-of function)) ((extended-sequence) (any)) ((nil) (any)))) (character-set-type (let ((pairs (character-set-type-pairs type))) (if (and (= (length pairs) 1) (= (caar pairs) 0) (= (cdar pairs) (1- sb!xc:char-code-limit))) (exactly character) (part-of character)))) (built-in-classoid (case (classoid-name type) ((complex function system-area-pointer weak-pointer) (values (primitive-type-or-lose (classoid-name type)) t)) (cons-type (part-of list)) (t (any)))) (fun-type (exactly function)) (classoid (if (csubtypep type (specifier-type 'function)) (part-of function) (part-of instance))) (ctype (if (csubtypep type (specifier-type 'function)) (part-of function) (any))))))) (/show0 "primtype.lisp end of file")
80440defd2fc25c0ff87d199c68adbeda51a3860dd3a46190e9b74e3bc4b1cb6
dsheets/ocaml-unix-time
unix_time_types.ml
* Copyright ( c ) 2016 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * * Copyright (c) 2016 David Sheets <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *) open Ctypes module C(F: Cstubs.Types.TYPE) = struct module Timespec = struct type t let t : t structure F.typ = F.structure "timespec" let ( -:* ) s x = F.field t s x let tv_sec = "tv_sec" -:* F.lift_typ PosixTypes.time_t let tv_nsec = "tv_nsec" -:* F.long let () = F.seal t end end
null
https://raw.githubusercontent.com/dsheets/ocaml-unix-time/b3f1db3185b04dce1f8704ec0d82687f95307802/lib_gen/unix_time_types.ml
ocaml
* Copyright ( c ) 2016 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * * Copyright (c) 2016 David Sheets <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *) open Ctypes module C(F: Cstubs.Types.TYPE) = struct module Timespec = struct type t let t : t structure F.typ = F.structure "timespec" let ( -:* ) s x = F.field t s x let tv_sec = "tv_sec" -:* F.lift_typ PosixTypes.time_t let tv_nsec = "tv_nsec" -:* F.long let () = F.seal t end end
5c99ceb9339493598dc35675f90604f7a14678d85340be7013c7317317632af5
xmonad/xmonad-contrib
DynamicWorkspaceGroups.hs
----------------------------------------------------------------------------- -- | Module : XMonad . Actions . DynamicWorkspaceGroups -- Description : Dynamically manage workspace groups in multi-head setups. Copyright : ( c ) 2009 -- License : BSD-style (see LICENSE) -- -- Maintainer : <> -- Stability : experimental -- Portability : unportable -- -- Dynamically manage \"workspace groups\", sets of workspaces being -- used together for some common task or purpose, to allow switching -- between workspace groups in a single action. Note that this only -- makes sense for multi-head setups. -- ----------------------------------------------------------------------------- module XMonad.Actions.DynamicWorkspaceGroups ( -- * Usage -- $usage WSGroupId , addRawWSGroup , addWSGroup , addCurrentWSGroup , forgetWSGroup , viewWSGroup , promptWSGroupView , promptWSGroupAdd , promptWSGroupForget , WSGPrompt -- * TopicSpace Integration -- $topics , viewTopicGroup , promptTopicGroupView ) where import Control.Arrow ((&&&)) import qualified Data.Map as M import XMonad import XMonad.Prelude (find, for_) import qualified XMonad.StackSet as W import XMonad.Prompt import qualified XMonad.Util.ExtensibleState as XS import XMonad.Actions.TopicSpace -- $usage You can use this module by importing it into your file : -- > import XMonad . Actions . DynamicWorkspaceGroups -- -- Then add keybindings like the following (this example uses " XMonad . Util . EZConfig"-style keybindings , but this is not necessary ): -- > , ( " M - y n " , " Name this group : " ) -- > , ("M-y g", promptWSGroupView myXPConfig "Go to group: ") -- > , ("M-y d", promptWSGroupForget myXPConfig "Forget group: ") -- type WSGroup = [(ScreenId,WorkspaceId)] type WSGroupId = String newtype WSGroupStorage = WSG { unWSG :: M.Map WSGroupId WSGroup } deriving (Read, Show) withWSG :: (M.Map WSGroupId WSGroup -> M.Map WSGroupId WSGroup) -> WSGroupStorage -> WSGroupStorage withWSG f = WSG . f . unWSG instance ExtensionClass WSGroupStorage where initialValue = WSG M.empty extensionType = PersistentExtension -- | Add a new workspace group of the given name, mapping to an -- explicitly specified association between screen IDs and workspace -- names. This function could be useful for, say, creating some -- standard workspace groups in your startup hook. addRawWSGroup :: WSGroupId -> [(ScreenId, WorkspaceId)] -> X () addRawWSGroup name = XS.modify . withWSG . M.insert name -- | Add a new workspace group with the given name. addWSGroup :: WSGroupId -> [WorkspaceId] -> X () addWSGroup name wids = withWindowSet $ \w -> do let wss = map ((W.tag . W.workspace) &&& W.screen) $ W.screens w wmap = mapM (strength . (flip lookup wss &&& id)) wids for_ wmap (addRawWSGroup name) where strength (ma, b) = ma >>= \a -> return (a,b) -- | Give a name to the current workspace group. addCurrentWSGroup :: WSGroupId -> X () addCurrentWSGroup name = withWindowSet $ \w -> addWSGroup name $ map (W.tag . W.workspace) (reverse $ W.current w : W.visible w) -- | Delete the named workspace group from the list of workspace -- groups. Note that this has no effect on the workspaces involved; -- it simply forgets the given name. forgetWSGroup :: WSGroupId -> X () forgetWSGroup = XS.modify . withWSG . M.delete -- | View the workspace group with the given name. viewWSGroup :: WSGroupId -> X () viewWSGroup = viewGroup (windows . W.greedyView) -- | Internal function for viewing a group. viewGroup :: (WorkspaceId -> X ()) -> WSGroupId -> X () viewGroup fview name = do WSG m <- XS.get for_ (M.lookup name m) $ mapM_ (uncurry (viewWS fview)) -- | View the given workspace on the given screen, using the provided function. viewWS :: (WorkspaceId -> X ()) -> ScreenId -> WorkspaceId -> X () viewWS fview sid wid = do mw <- findScreenWS sid case mw of Just w -> do windows $ W.view w fview wid Nothing -> return () -- | Find the workspace which is currently on the given screen. findScreenWS :: ScreenId -> X (Maybe WorkspaceId) findScreenWS sid = withWindowSet $ return . fmap (W.tag . W.workspace) . find ((==sid) . W.screen) . W.screens newtype WSGPrompt = WSGPrompt String instance XPrompt WSGPrompt where showXPrompt (WSGPrompt s) = s -- | Prompt for a workspace group to view. promptWSGroupView :: XPConfig -> String -> X () promptWSGroupView = promptGroupView viewWSGroup -- | Internal function for making a prompt to view a workspace group promptGroupView :: (WSGroupId -> X ()) -> XPConfig -> String -> X () promptGroupView fview xp s = do gs <- fmap (M.keys . unWSG) XS.get mkXPrompt (WSGPrompt s) xp (mkComplFunFromList' xp gs) fview -- | Prompt for a name for the current workspace group. promptWSGroupAdd :: XPConfig -> String -> X () promptWSGroupAdd xp s = mkXPrompt (WSGPrompt s) xp (const $ return []) addCurrentWSGroup -- | Prompt for a workspace group to forget. promptWSGroupForget :: XPConfig -> String -> X () promptWSGroupForget xp s = do gs <- fmap (M.keys . unWSG) XS.get mkXPrompt (WSGPrompt s) xp (mkComplFunFromList' xp gs) forgetWSGroup -- $topics -- You can use this module with "XMonad.Actions.TopicSpace" — just replace -- 'promptWSGroupView' with 'promptTopicGroupView': -- > , ( " M - y n " , " Name this group : " ) > , ( " M - y g " , promptTopicGroupView myTopicConfig myXPConfig " Go to group : " ) -- > , ("M-y d", promptWSGroupForget myXPConfig "Forget group: ") -- -- It's also a good idea to replace 'spawn' with ' XMonad . Actions . SpawnOn.spawnOn ' or ' XMonad . Actions . SpawnOn.spawnHere ' in -- your topic actions, so everything is spawned where it should be. -- | Prompt for a workspace group to view, treating the workspaces as topics. promptTopicGroupView :: TopicConfig -> XPConfig -> String -> X () promptTopicGroupView = promptGroupView . viewTopicGroup -- | View the workspace group with the given name, treating the workspaces as -- topics. viewTopicGroup :: TopicConfig -> WSGroupId -> X () viewTopicGroup = viewGroup . switchTopic
null
https://raw.githubusercontent.com/xmonad/xmonad-contrib/3058d1ca22d565b2fa93227fdde44d8626d6f75d/XMonad/Actions/DynamicWorkspaceGroups.hs
haskell
--------------------------------------------------------------------------- | Description : Dynamically manage workspace groups in multi-head setups. License : BSD-style (see LICENSE) Maintainer : <> Stability : experimental Portability : unportable Dynamically manage \"workspace groups\", sets of workspaces being used together for some common task or purpose, to allow switching between workspace groups in a single action. Note that this only makes sense for multi-head setups. --------------------------------------------------------------------------- * Usage $usage * TopicSpace Integration $topics $usage Then add keybindings like the following (this example uses > , ("M-y g", promptWSGroupView myXPConfig "Go to group: ") > , ("M-y d", promptWSGroupForget myXPConfig "Forget group: ") | Add a new workspace group of the given name, mapping to an explicitly specified association between screen IDs and workspace names. This function could be useful for, say, creating some standard workspace groups in your startup hook. | Add a new workspace group with the given name. | Give a name to the current workspace group. | Delete the named workspace group from the list of workspace groups. Note that this has no effect on the workspaces involved; it simply forgets the given name. | View the workspace group with the given name. | Internal function for viewing a group. | View the given workspace on the given screen, using the provided function. | Find the workspace which is currently on the given screen. | Prompt for a workspace group to view. | Internal function for making a prompt to view a workspace group | Prompt for a name for the current workspace group. | Prompt for a workspace group to forget. $topics You can use this module with "XMonad.Actions.TopicSpace" — just replace 'promptWSGroupView' with 'promptTopicGroupView': > , ("M-y d", promptWSGroupForget myXPConfig "Forget group: ") It's also a good idea to replace 'spawn' with your topic actions, so everything is spawned where it should be. | Prompt for a workspace group to view, treating the workspaces as topics. | View the workspace group with the given name, treating the workspaces as topics.
Module : XMonad . Actions . DynamicWorkspaceGroups Copyright : ( c ) 2009 module XMonad.Actions.DynamicWorkspaceGroups WSGroupId , addRawWSGroup , addWSGroup , addCurrentWSGroup , forgetWSGroup , viewWSGroup , promptWSGroupView , promptWSGroupAdd , promptWSGroupForget , WSGPrompt , viewTopicGroup , promptTopicGroupView ) where import Control.Arrow ((&&&)) import qualified Data.Map as M import XMonad import XMonad.Prelude (find, for_) import qualified XMonad.StackSet as W import XMonad.Prompt import qualified XMonad.Util.ExtensibleState as XS import XMonad.Actions.TopicSpace You can use this module by importing it into your file : > import XMonad . Actions . DynamicWorkspaceGroups " XMonad . Util . EZConfig"-style keybindings , but this is not necessary ): > , ( " M - y n " , " Name this group : " ) type WSGroup = [(ScreenId,WorkspaceId)] type WSGroupId = String newtype WSGroupStorage = WSG { unWSG :: M.Map WSGroupId WSGroup } deriving (Read, Show) withWSG :: (M.Map WSGroupId WSGroup -> M.Map WSGroupId WSGroup) -> WSGroupStorage -> WSGroupStorage withWSG f = WSG . f . unWSG instance ExtensionClass WSGroupStorage where initialValue = WSG M.empty extensionType = PersistentExtension addRawWSGroup :: WSGroupId -> [(ScreenId, WorkspaceId)] -> X () addRawWSGroup name = XS.modify . withWSG . M.insert name addWSGroup :: WSGroupId -> [WorkspaceId] -> X () addWSGroup name wids = withWindowSet $ \w -> do let wss = map ((W.tag . W.workspace) &&& W.screen) $ W.screens w wmap = mapM (strength . (flip lookup wss &&& id)) wids for_ wmap (addRawWSGroup name) where strength (ma, b) = ma >>= \a -> return (a,b) addCurrentWSGroup :: WSGroupId -> X () addCurrentWSGroup name = withWindowSet $ \w -> addWSGroup name $ map (W.tag . W.workspace) (reverse $ W.current w : W.visible w) forgetWSGroup :: WSGroupId -> X () forgetWSGroup = XS.modify . withWSG . M.delete viewWSGroup :: WSGroupId -> X () viewWSGroup = viewGroup (windows . W.greedyView) viewGroup :: (WorkspaceId -> X ()) -> WSGroupId -> X () viewGroup fview name = do WSG m <- XS.get for_ (M.lookup name m) $ mapM_ (uncurry (viewWS fview)) viewWS :: (WorkspaceId -> X ()) -> ScreenId -> WorkspaceId -> X () viewWS fview sid wid = do mw <- findScreenWS sid case mw of Just w -> do windows $ W.view w fview wid Nothing -> return () findScreenWS :: ScreenId -> X (Maybe WorkspaceId) findScreenWS sid = withWindowSet $ return . fmap (W.tag . W.workspace) . find ((==sid) . W.screen) . W.screens newtype WSGPrompt = WSGPrompt String instance XPrompt WSGPrompt where showXPrompt (WSGPrompt s) = s promptWSGroupView :: XPConfig -> String -> X () promptWSGroupView = promptGroupView viewWSGroup promptGroupView :: (WSGroupId -> X ()) -> XPConfig -> String -> X () promptGroupView fview xp s = do gs <- fmap (M.keys . unWSG) XS.get mkXPrompt (WSGPrompt s) xp (mkComplFunFromList' xp gs) fview promptWSGroupAdd :: XPConfig -> String -> X () promptWSGroupAdd xp s = mkXPrompt (WSGPrompt s) xp (const $ return []) addCurrentWSGroup promptWSGroupForget :: XPConfig -> String -> X () promptWSGroupForget xp s = do gs <- fmap (M.keys . unWSG) XS.get mkXPrompt (WSGPrompt s) xp (mkComplFunFromList' xp gs) forgetWSGroup > , ( " M - y n " , " Name this group : " ) > , ( " M - y g " , promptTopicGroupView myTopicConfig myXPConfig " Go to group : " ) ' XMonad . Actions . SpawnOn.spawnOn ' or ' XMonad . Actions . SpawnOn.spawnHere ' in promptTopicGroupView :: TopicConfig -> XPConfig -> String -> X () promptTopicGroupView = promptGroupView . viewTopicGroup viewTopicGroup :: TopicConfig -> WSGroupId -> X () viewTopicGroup = viewGroup . switchTopic
53c141d440ba2519a5a9434c01e077390a4e1ba0115622694f5ae3c1fe027204
jakemcc/sicp-study
ex2_54.clj
Exercise 2.54 ; Two lists are said to be equal ? if they contain ; equal elements arranged in the same order. Implement equal? for ; lists of symbols (use 'clojure.test) (def equal? =) (deftest equal?-works (is (= true (equal? '(a b c) '(a b c)))) (is (= false (equal? '(a b) '(a b z)))) (is (= false (equal? '(b a c) '(b a d))))) (run-tests) (defn equal? [x y] "equal? defined using recursion instead of cheating and using =" (cond (and (not (seq? x)) (not (seq? y))) (= x y) (empty? x) (empty? y) (empty? y) (empty? x) :else (and (equal? (first x) (first y)) (equal? (rest x) (rest y))))) (run-tests)
null
https://raw.githubusercontent.com/jakemcc/sicp-study/3b9e3d6c8cc30ad92b0d9bbcbbbfe36a8413f89d/clojure/section2.3/ex2_54.clj
clojure
equal elements arranged in the same order. Implement equal? for lists of symbols
Exercise 2.54 Two lists are said to be equal ? if they contain (use 'clojure.test) (def equal? =) (deftest equal?-works (is (= true (equal? '(a b c) '(a b c)))) (is (= false (equal? '(a b) '(a b z)))) (is (= false (equal? '(b a c) '(b a d))))) (run-tests) (defn equal? [x y] "equal? defined using recursion instead of cheating and using =" (cond (and (not (seq? x)) (not (seq? y))) (= x y) (empty? x) (empty? y) (empty? y) (empty? x) :else (and (equal? (first x) (first y)) (equal? (rest x) (rest y))))) (run-tests)
b0bdea5af916a67b7039ad98a663463ef9b01ba50fb1bf627ef1aa7c55344135
marhop/pandoc-unicode-math
UnicodeToLatex.hs
{-# LANGUAGE OverloadedStrings #-} module UnicodeToLatex where import Data.Char (isAlphaNum) import Data.Map.Strict (findWithDefault, (!?)) import Data.Text (Text, cons, singleton, snoc, uncons) import qualified Data.Text as T import Text.Pandoc.JSON (toJSONFilter) import MathFilter import Symbols main :: IO () main = toJSONFilter (mathFilter unicodeToLatex) -- | Replace Unicode math symbols in a string by equivalent Latex commands. -- Examples: -- -- * α → \alpha -- * ℕ → \mathbb{N} * Α → A ( greek Alpha to latin A ) , ugly but that 's how Latex handles it -- -- Sensible whitespace is added where necessary: -- -- * λx → \lambda x -- * αβ → \alpha\beta unicodeToLatex :: Text -> Text unicodeToLatex = T.foldr f "" where f :: Char -> Text -> Text f x acc | Just (y, ys) <- uncons acc = maybe (x `cons` acc) (<> isolate y <> ys) (unicodeToLatexMap !? x) | otherwise = findWithDefault (singleton x) x unicodeToLatexMap isolate :: Char -> Text isolate x | isAlphaNum x = " " `snoc` x | otherwise = singleton x
null
https://raw.githubusercontent.com/marhop/pandoc-unicode-math/51e374d83d77a26946c3528b1295dd848fe5d7c9/src/UnicodeToLatex.hs
haskell
# LANGUAGE OverloadedStrings # | Replace Unicode math symbols in a string by equivalent Latex commands. Examples: * α → \alpha * ℕ → \mathbb{N} Sensible whitespace is added where necessary: * λx → \lambda x * αβ → \alpha\beta
module UnicodeToLatex where import Data.Char (isAlphaNum) import Data.Map.Strict (findWithDefault, (!?)) import Data.Text (Text, cons, singleton, snoc, uncons) import qualified Data.Text as T import Text.Pandoc.JSON (toJSONFilter) import MathFilter import Symbols main :: IO () main = toJSONFilter (mathFilter unicodeToLatex) * Α → A ( greek Alpha to latin A ) , ugly but that 's how Latex handles it unicodeToLatex :: Text -> Text unicodeToLatex = T.foldr f "" where f :: Char -> Text -> Text f x acc | Just (y, ys) <- uncons acc = maybe (x `cons` acc) (<> isolate y <> ys) (unicodeToLatexMap !? x) | otherwise = findWithDefault (singleton x) x unicodeToLatexMap isolate :: Char -> Text isolate x | isAlphaNum x = " " `snoc` x | otherwise = singleton x
b72f1d821300845b5c554d1a48f588a926c2fc7e7e6032952e6cb05312889aa7
bmeurer/ocaml-arm
debugger_config.ml
(***********************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt OCaml port by and (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) $ Id$ (**************************** Configuration file ***********************) open Int64ops exception Toplevel (*** Miscellaneous parameters. ***) ISO 6429 color sequences 00 to restore default color 01 for brighter colors 04 for underlined text 05 for flashing text 30 for black foreground 31 for red foreground 32 for green foreground 33 for yellow ( or brown ) foreground 34 for blue foreground 35 for purple foreground 36 for cyan foreground 37 for white ( or gray ) foreground 40 for black background 41 for red background 42 for green background 43 for yellow ( or brown ) background 44 for blue background 45 for purple background 46 for cyan background 47 for white ( or gray ) background let debugger_prompt = " \027[1;04m(ocd)\027[0 m " and event_mark_before = " \027[1;31m$\027[0 m " and event_mark_after = " \027[1;34m$\027[0 m " 00 to restore default color 01 for brighter colors 04 for underlined text 05 for flashing text 30 for black foreground 31 for red foreground 32 for green foreground 33 for yellow (or brown) foreground 34 for blue foreground 35 for purple foreground 36 for cyan foreground 37 for white (or gray) foreground 40 for black background 41 for red background 42 for green background 43 for yellow (or brown) background 44 for blue background 45 for purple background 46 for cyan background 47 for white (or gray) background let debugger_prompt = "\027[1;04m(ocd)\027[0m " and event_mark_before = "\027[1;31m$\027[0m" and event_mark_after = "\027[1;34m$\027[0m" *) let debugger_prompt = "(ocd) " let event_mark_before = "<|b|>" let event_mark_after = "<|a|>" (* Name of shell used to launch the debuggee *) let shell = match Sys.os_type with "Win32" -> "cmd" | _ -> "/bin/sh" (* Name of the OCaml runtime. *) let runtime_program = "ocamlrun" Time history size ( for ` last ' ) let history_size = ref 30 let load_path_for = Hashtbl.create 7 (*** Time travel parameters. ***) (* Step between checkpoints for long displacements.*) let checkpoint_big_step = ref (~~ "10000") Idem for small ones . let checkpoint_small_step = ref (~~ "1000") (* Maximum number of checkpoints. *) let checkpoint_max_count = ref 15 (* Whether to keep checkpoints or not. *) let make_checkpoints = ref (match Sys.os_type with "Win32" -> false | _ -> true) * * Environment variables for debugee . * * let environment = ref []
null
https://raw.githubusercontent.com/bmeurer/ocaml-arm/43f7689c76a349febe3d06ae7a4fc1d52984fd8b/debugger/debugger_config.ml
ocaml
********************************************************************* OCaml ********************************************************************* *************************** Configuration file ********************** ** Miscellaneous parameters. ** Name of shell used to launch the debuggee Name of the OCaml runtime. ** Time travel parameters. ** Step between checkpoints for long displacements. Maximum number of checkpoints. Whether to keep checkpoints or not.
, projet Cristal , INRIA Rocquencourt OCaml port by and Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . $ Id$ open Int64ops exception Toplevel ISO 6429 color sequences 00 to restore default color 01 for brighter colors 04 for underlined text 05 for flashing text 30 for black foreground 31 for red foreground 32 for green foreground 33 for yellow ( or brown ) foreground 34 for blue foreground 35 for purple foreground 36 for cyan foreground 37 for white ( or gray ) foreground 40 for black background 41 for red background 42 for green background 43 for yellow ( or brown ) background 44 for blue background 45 for purple background 46 for cyan background 47 for white ( or gray ) background let debugger_prompt = " \027[1;04m(ocd)\027[0 m " and event_mark_before = " \027[1;31m$\027[0 m " and event_mark_after = " \027[1;34m$\027[0 m " 00 to restore default color 01 for brighter colors 04 for underlined text 05 for flashing text 30 for black foreground 31 for red foreground 32 for green foreground 33 for yellow (or brown) foreground 34 for blue foreground 35 for purple foreground 36 for cyan foreground 37 for white (or gray) foreground 40 for black background 41 for red background 42 for green background 43 for yellow (or brown) background 44 for blue background 45 for purple background 46 for cyan background 47 for white (or gray) background let debugger_prompt = "\027[1;04m(ocd)\027[0m " and event_mark_before = "\027[1;31m$\027[0m" and event_mark_after = "\027[1;34m$\027[0m" *) let debugger_prompt = "(ocd) " let event_mark_before = "<|b|>" let event_mark_after = "<|a|>" let shell = match Sys.os_type with "Win32" -> "cmd" | _ -> "/bin/sh" let runtime_program = "ocamlrun" Time history size ( for ` last ' ) let history_size = ref 30 let load_path_for = Hashtbl.create 7 let checkpoint_big_step = ref (~~ "10000") Idem for small ones . let checkpoint_small_step = ref (~~ "1000") let checkpoint_max_count = ref 15 let make_checkpoints = ref (match Sys.os_type with "Win32" -> false | _ -> true) * * Environment variables for debugee . * * let environment = ref []
e5610cf018638392596db77e205ddb080edeb489618b33bb3b48b7575f1786ce
Elzair/nazghul
basic-night-time.scm
(define hour 00) (define minutes 45) (define time-in-minutes (+ (* hour 60) minutes)) (kern-set-clock 0 ; year 0 ; month 0 ; week 0 ; day hour ; hour minutes ; minutes( ) (kern-mk-astral-body 'sun ; tag "Fyer (the sun)" ; name 1 ; relative astronomical distance 1 ; minutes per phase (n/a for sun) (/ (* 24 60) 360) ; minutes per degree 0 ; initial arc 0 ; initial phase '() ; script interface ;; phases: (list (list s_sun 255 "full") ) )
null
https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/haxima-1.001/tests/basic-night-time.scm
scheme
year month week day hour minutes( tag name relative astronomical distance minutes per phase (n/a for sun) minutes per degree initial arc initial phase script interface phases:
(define hour 00) (define minutes 45) (define time-in-minutes (+ (* hour 60) minutes)) (kern-set-clock ) (kern-mk-astral-body (list (list s_sun 255 "full") ) )
627e5cbc659e9fe06c422057bcadf29029c9dea4751b46d3bc2d1214b31d9948
sph-mn/sph-lib
other.scm
(define-module (sph list other)) (use-modules (srfi srfi-1) (rnrs sorting) (sph) (sph alist) (sph hashtable) (sph list)) (export group group-recursively list-ref-random list-ref-randomise-cycle list-replace-from-hashtable randomise sph-list-other-description) (define sph-list-other-description "additional list processing bindings that depend on libraries that depend on (sph list). to avoid circular dependencies") (define (list-replace-from-hashtable a ht) "list rnrs-hashtable -> list replaces elements in list that exist as key in a hashtable with the associated value. if the value is a list, the element is either removed (empty list) or replaced with multiple elements" (fold (l (e r) (let (value (ht-ref ht e)) (if value ((if (list? value) append pair) value r) (pair e r)))) (list) a)) (define* (group a #:optional (accessor identity)) "list [procedure:{any -> any}] -> ((any:group-key any:group-value ...):group ...) groups entries by unique result values of accessor. by default accessor is identity and groups equal elements. returns an association list with one entry for each group with the value as key and related values as value" (let loop ((rest a) (groups (alist))) (if (null? rest) (map (l (a) (pair (first a) (reverse (tail a)))) groups) (let* ((a (first rest)) (key (accessor a)) (group (alist-ref groups key))) (loop (tail rest) (alist-set groups key (if group (pair a group) (list a)))))))) (define* (group-recursively a #:optional (accessor first)) "((any ...) ...) [procedure] -> list group lists and the elements of groups until no further sub-groups are possible. the default accessor is \"first\". # example (group-recursively (list (list 1 2 3) (list 1 2 6) (list 1 4 7) (list 8 9)) first) -> ((1 (2 3 6) (4 7)) (8 9)) note in the example input how the entries after 1 2 have been grouped into (2 3 6) # example use case converting a list of filesystem paths split at slashes to a nested list where prefixes are directories" (map (l (a) "(group-name element ...)" (let (rest (map tail (remove (compose null? tail) (tail a)))) (if (null? rest) (first a) (pair (first a) (group-recursively rest))))) (group a accessor))) (define* (list-ref-random a #:optional (random-state *random-state*)) "list -> any retrieve a random element of a list" (list-ref a (random (length a) random-state))) (define* (list-ref-randomise-cycle a #:optional (random-state *random-state*)) "list -> procedure:{-> any} gives a procedure that when called gives the next element from a randomised version of \"a\" when the end of the list has been reached, the list is reset to a newly randomised version of \"a\"" (let ((a-length (length a)) (new (randomise a random-state)) (old (list))) (letrec ( (loop (l () (if (null? new) (begin (set! new (randomise old random-state)) (set! old (list)) (loop)) (let (r (first new)) (set! new (tail new)) (set! old (pair r old)) r))))) loop))) (define* (randomise a #:optional (random-state *random-state*)) "list -> list return a new list with the elements of list in random order. algorithm: connect a random number to each element, re-sort list corresponding to the random numbers." (let (length-a (length a)) (map tail (list-sort (l (a b) (< (first a) (first b))) (map (l (c) (pair (random length-a random-state) c)) a)))))
null
https://raw.githubusercontent.com/sph-mn/sph-lib/c7daf74f42d6bd1304f49c2fef89dcd6dd94fdc9/modules/sph/list/other.scm
scheme
(define-module (sph list other)) (use-modules (srfi srfi-1) (rnrs sorting) (sph) (sph alist) (sph hashtable) (sph list)) (export group group-recursively list-ref-random list-ref-randomise-cycle list-replace-from-hashtable randomise sph-list-other-description) (define sph-list-other-description "additional list processing bindings that depend on libraries that depend on (sph list). to avoid circular dependencies") (define (list-replace-from-hashtable a ht) "list rnrs-hashtable -> list replaces elements in list that exist as key in a hashtable with the associated value. if the value is a list, the element is either removed (empty list) or replaced with multiple elements" (fold (l (e r) (let (value (ht-ref ht e)) (if value ((if (list? value) append pair) value r) (pair e r)))) (list) a)) (define* (group a #:optional (accessor identity)) "list [procedure:{any -> any}] -> ((any:group-key any:group-value ...):group ...) groups entries by unique result values of accessor. by default accessor is identity and groups equal elements. returns an association list with one entry for each group with the value as key and related values as value" (let loop ((rest a) (groups (alist))) (if (null? rest) (map (l (a) (pair (first a) (reverse (tail a)))) groups) (let* ((a (first rest)) (key (accessor a)) (group (alist-ref groups key))) (loop (tail rest) (alist-set groups key (if group (pair a group) (list a)))))))) (define* (group-recursively a #:optional (accessor first)) "((any ...) ...) [procedure] -> list group lists and the elements of groups until no further sub-groups are possible. the default accessor is \"first\". # example (group-recursively (list (list 1 2 3) (list 1 2 6) (list 1 4 7) (list 8 9)) first) -> ((1 (2 3 6) (4 7)) (8 9)) note in the example input how the entries after 1 2 have been grouped into (2 3 6) # example use case converting a list of filesystem paths split at slashes to a nested list where prefixes are directories" (map (l (a) "(group-name element ...)" (let (rest (map tail (remove (compose null? tail) (tail a)))) (if (null? rest) (first a) (pair (first a) (group-recursively rest))))) (group a accessor))) (define* (list-ref-random a #:optional (random-state *random-state*)) "list -> any retrieve a random element of a list" (list-ref a (random (length a) random-state))) (define* (list-ref-randomise-cycle a #:optional (random-state *random-state*)) "list -> procedure:{-> any} gives a procedure that when called gives the next element from a randomised version of \"a\" when the end of the list has been reached, the list is reset to a newly randomised version of \"a\"" (let ((a-length (length a)) (new (randomise a random-state)) (old (list))) (letrec ( (loop (l () (if (null? new) (begin (set! new (randomise old random-state)) (set! old (list)) (loop)) (let (r (first new)) (set! new (tail new)) (set! old (pair r old)) r))))) loop))) (define* (randomise a #:optional (random-state *random-state*)) "list -> list return a new list with the elements of list in random order. algorithm: connect a random number to each element, re-sort list corresponding to the random numbers." (let (length-a (length a)) (map tail (list-sort (l (a b) (< (first a) (first b))) (map (l (c) (pair (random length-a random-state) c)) a)))))
74c6a4e39c889d3dbd8bafb3aba8c0dbb70de6d90b354883bfbd9a65f377f62e
eatonphil/owebl
handler.ml
open Response open Rule type t = < getResponse: Request.t -> Response.r > class handler (rule: RouteRule.t) (response: Response.t) = object(self) method getResponse (request: Request.t) : Response.r = match rule#matches request with | RouteRule.Match -> response#getResponse request | RouteRule.NoMatch -> Response.Empty end let create (rule: RouteRule.t) (response: Response.t) = new handler rule response
null
https://raw.githubusercontent.com/eatonphil/owebl/deb9794606a36ea831a260bfe3812e23c0a70fce/src/handler.ml
ocaml
open Response open Rule type t = < getResponse: Request.t -> Response.r > class handler (rule: RouteRule.t) (response: Response.t) = object(self) method getResponse (request: Request.t) : Response.r = match rule#matches request with | RouteRule.Match -> response#getResponse request | RouteRule.NoMatch -> Response.Empty end let create (rule: RouteRule.t) (response: Response.t) = new handler rule response
100fcc2d011d30b2f1028cb332bea9aa5052d1794b1cb2d51dc14d96ca4ae4b5
b0-system/brzo
tool.ml
let () = ignore (Cap.sayno) let () = Printf.printf "The answer is: %d\n" (Q.answer ())
null
https://raw.githubusercontent.com/b0-system/brzo/79d316a5024025a0112a8569a6335241b4620da8/examples/ocaml-deps/tool.ml
ocaml
let () = ignore (Cap.sayno) let () = Printf.printf "The answer is: %d\n" (Q.answer ())
8a47727f1ea6534f3be1c9c5b6110d22bc6c6ac21e6f6b309e4632968db19099
videolang/interactive-syntax
context-text.rkt
#lang racket/base (provide (rename-out [editor-reader reader])) (require racket/class wxme) (define editor-reader% (class* object% (snip-reader<%>) (super-new) (define/public (read-header version stream) (void)) (define/public (read-snip text-only? version stream) (define text (send stream read-bytes 'editor)) (cond [text-only? text] [else text])))) ; <- fix? (define editor-reader (new editor-reader%))
null
https://raw.githubusercontent.com/videolang/interactive-syntax/8c13d83ac0f5dbd624d59083b32f765952d1d440/editor/private/context-text.rkt
racket
<- fix?
#lang racket/base (provide (rename-out [editor-reader reader])) (require racket/class wxme) (define editor-reader% (class* object% (snip-reader<%>) (super-new) (define/public (read-header version stream) (void)) (define/public (read-snip text-only? version stream) (define text (send stream read-bytes 'editor)) (cond [text-only? text] (define editor-reader (new editor-reader%))
fd6ebaa786cabaf7ee001935492f98fa78cdb0adf6200522eda1fc549fd7ea88
jrm-code-project/LISP-Machine
editst.lisp
;; -*- Mode: Lisp; Package: System-Internals -*- ;; Lisp Machine Editor Stream ;; The rubout handler implemented here is a crock since it duplicates ;; the functions of ZWEI. However, this editor is implemented in terms of stream ;; operations, and thus can be used from consoles other than the local Lisp Machine console . This file makes use of the definitions in LMMAX;UTILS . ;; There are a couple ideas here: ;; The editor stream itself is separated from the underlying console ;; stream. This is nice since the console stream need know nothing about ;; the rubout handler, and thus rubout handlers can be changed easily ;; without having to duplicate the code for the entire console stream. In addition , it makes it easy to have one editor stream work for ;; different console streams. ;; Another thought would be to split the bare console stream into ;; an input stream from a keyboard and an output stream to a window on a given monitor . The editor stream would then bind these two ;; streams together into a single interactive i/o stream. I can't see ;; much use for this, unless somebody wanted a keyboard stream without ;; having a window, or there were multiple keyboard types in use. ;; Terminology: ;; CONSOLE-STREAM -- a bi-directional stream to some console. This stream ;; knows nothing about rubout handling. ;; EDITOR-STREAM -- a bi-directional stream connected to some console stream. ;; It handles both the :RUBOUT-HANDLER and :UNTYI stream operations. TV - STREAM -- a bi - directional stream to the Lisp Machine console . Special ;; case of a console stream. ;; SUPDUP-STREAM -- a bi-directional stream to a console connected via the ;; Chaos net. Special case of a console stream. ;; MAKE-TV-STREAM takes a piece of paper, and returns a stream which talks to the TV terminal of the Lisp Machine . For input , ;; it uses the keyboard. For output, it types on the piece of paper. (DECLARE (SPECIAL TV-STREAM-PC-PPR)) (DEFUN MAKE-TV-STREAM (TV-STREAM-PC-PPR) (CLOSURE '(TV-STREAM-PC-PPR) #'TV-STREAM)) (DEFSELECT (TV-STREAM TV-STREAM-DEFAULT-HANDLER) ;; Input operations (:TYI () (KBD-TYI)) (:TYI-NO-HANG () (KBD-TYI-NO-HANG)) (:LISTEN () (KBD-CHAR-AVAILABLE)) (:CLEAR-INPUT () (DO () ((NOT (KBD-CHAR-AVAILABLE))) ;Clear hardware/firmware buffers (KBD-TYI))) ;; Output operations ;; TV-TYO doesn't print "control" characters. (:TYO (CHAR) (TV-TYO TV-STREAM-PC-PPR CHAR)) (:STRING-OUT (STRING &OPTIONAL (BEGIN 0) END) (TV-STRING-OUT TV-STREAM-PC-PPR STRING BEGIN END)) (:LINE-OUT (STRING &OPTIONAL (BEGIN 0) END) (TV-STRING-OUT TV-STREAM-PC-PPR STRING BEGIN END) (TV-CRLF TV-STREAM-PC-PPR)) ;; If at the beginning of a line, clear it. Otherwise, go to the beginning of the next line and clear it . (:FRESH-LINE () (COND ((= (PC-PPR-CURRENT-X TV-STREAM-PC-PPR) (PC-PPR-LEFT-MARGIN TV-STREAM-PC-PPR)) (TV-CLEAR-EOL TV-STREAM-PC-PPR)) (T (TV-CRLF TV-STREAM-PC-PPR)))) (:TRIGGER-MORE () (OR (ZEROP (PC-PPR-EXCEPTIONS TV-STREAM-PC-PPR)) (TV-EXCEPTION TV-STREAM-PC-PPR))) (:BEEP (&OPTIONAL (WAVELENGTH TV-BEEP-WAVELENGTH) (DURATION TV-BEEP-DURATION)) (%BEEP WAVELENGTH DURATION)) ;; If no unit is specified, then the "preferred" unit is used. This is the ;; unit that :SET-CURSORPOS defaults to and that :COMPUTE-MOTION uses. ;; The :CHARACTER unit of these operations is useless with variable width fonts. (:READ-CURSORPOS (&OPTIONAL (UNIT ':PIXEL)) (MULTIPLE-VALUE-BIND (X Y) (TV-READ-CURSORPOS TV-STREAM-PC-PPR) (SELECTQ UNIT (:PIXEL) (:CHARACTER (SETQ X (// X (PC-PPR-CHAR-WIDTH TV-STREAM-PC-PPR))) (SETQ Y (// Y (PC-PPR-LINE-HEIGHT TV-STREAM-PC-PPR)))) (:OTHERWISE (FERROR NIL "~S is not a known unit." UNIT))) (MVRETURN X Y))) (:SET-CURSORPOS (X Y &OPTIONAL (UNIT ':PIXEL)) ;; For compatibility (IF (FIXP UNIT) (PSETQ UNIT X X Y Y UNIT)) (SELECTQ UNIT (:PIXEL) (:CHARACTER (SETQ X (* X (PC-PPR-CHAR-WIDTH TV-STREAM-PC-PPR))) (SETQ Y (* Y (PC-PPR-LINE-HEIGHT TV-STREAM-PC-PPR)))) (:OTHERWISE (FERROR NIL "~S is not a known unit." UNIT))) (TV-SET-CURSORPOS TV-STREAM-PC-PPR X Y)) (:SET-CURSORPOS-RELATIVE (X Y &OPTIONAL (UNIT ':PIXEL)) (SELECTQ UNIT (:PIXEL) (:CHARACTER (SETQ X (* X (PC-PPR-CHAR-WIDTH TV-STREAM-PC-PPR))) (SETQ Y (* Y (PC-PPR-LINE-HEIGHT TV-STREAM-PC-PPR)))) (:OTHERWISE (FERROR NIL "~S is not a known unit." UNIT))) (TV-SET-CURSORPOS-RELATIVE TV-STREAM-PC-PPR X Y)) (:SIZE-IN-CHARACTERS () (MVRETURN (// (- (PC-PPR-RIGHT-MARGIN TV-STREAM-PC-PPR) (PC-PPR-LEFT-MARGIN TV-STREAM-PC-PPR)) (PC-PPR-CHAR-WIDTH TV-STREAM-PC-PPR)) (// (- (PC-PPR-BOTTOM-MARGIN TV-STREAM-PC-PPR) (PC-PPR-TOP-MARGIN TV-STREAM-PC-PPR)) (PC-PPR-LINE-HEIGHT TV-STREAM-PC-PPR)))) ;; Compute the new cursor position if STRING were output at the specified point . NIL for X - POS and Y - POS mean use the current cursor position . ;; X-POS and Y-POS are in pixels. (:COMPUTE-MOTION (X-POS Y-POS STRING &OPTIONAL (BEGIN 0) (END (STRING-LENGTH STRING))) (TV-COMPUTE-MOTION TV-STREAM-PC-PPR X-POS Y-POS STRING BEGIN END)) ;; Compute the motion for printing a string and then move the cursor there. ;; This eliminates the problem of knowing whether to use the :PIXEL or :CHARACTER ;; unit when calling :SET-CURSORPOS. Since the string is passed in here as an argument , this stream need know nothing about the buffer maintained by the ;; editor stream. This might be better named :MOVE-OVER-STRING. (:CURSOR-MOTION (X-POS Y-POS STRING &OPTIONAL (BEGIN 0) (END (STRING-LENGTH STRING))) (MULTIPLE-VALUE-BIND (X Y HOW-FAR) (TV-COMPUTE-MOTION TV-STREAM-PC-PPR X-POS Y-POS STRING BEGIN END) ;; Check for page wrap-around. (IF HOW-FAR (MULTIPLE-VALUE (X Y) (TV-COMPUTE-MOTION TV-STREAM-PC-PPR 0 0 STRING HOW-FAR END))) (TV-SET-CURSORPOS TV-STREAM-PC-PPR X Y))) ;; This assumes that the cursor is positioned before the string to be underlined. ;; The operation should be defined to xor, so that underlining twice erases. (:UNDERLINE (STRING &OPTIONAL (BEGIN 0) (END (STRING-LENGTH STRING)) &AUX (X1 (PC-PPR-CURRENT-X TV-STREAM-PC-PPR)) (Y1 (+ (PC-PPR-CURRENT-Y TV-STREAM-PC-PPR) (PC-PPR-LINE-HEIGHT TV-STREAM-PC-PPR)))) (MULTIPLE-VALUE-BIND (X2 Y2) (TV-COMPUTE-MOTION TV-STREAM-PC-PPR X1 Y1 STRING BEGIN END) (TV-DRAW-LINE X1 Y1 X2 Y2 TV-ALU-XOR (PC-PPR-SCREEN TV-STREAM-PC-PPR)))) ;; Font hackery. FONT-LIST is a list of strings describing fonts, since ;; internal font representations are per-stream. Try to avoid calling TV - REDEFINE - PC - PPR whenever a font change is made since this reallocates a new font map rather than reusing the old one . If the buffer is to contain font changes , then it should contain 16 - bit characters . (:SET-FONTS (&REST FONT-LIST) (TV-REDEFINE-PC-PPR TV-STREAM-PC-PPR ':FONTS (MAPCAR #'(LAMBDA (FONT) (SETQ FONT (INTERN FONT "FONTS")) (IF (BOUNDP FONT) (SYMEVAL FONT) FONTS:CPTFONT)) FONT-LIST))) (:SET-CURRENT-FONT (N) (TV-TYO TV-STREAM-PC-PPR (+ 240 N))) (:CHAR-WIDTH (&OPTIONAL CHAR FONT) (COND ((NOT CHAR) (PC-PPR-CHAR-WIDTH TV-STREAM-PC-PPR)) (T (SETQ FONT (IF (FIXP FONT) (AREF (PC-PPR-FONT-MAP TV-STREAM-PC-PPR)) (PC-PPR-CURRENT-FONT TV-STREAM-PC-PPR))) (TV-CHAR-WIDTH TV-STREAM-PC-PPR CHAR FONT)))) (:LINE-HEIGHT () (PC-PPR-LINE-HEIGHT TV-STREAM-PC-PPR)) (:STRING-WIDTH (STRING &OPTIONAL (BEGIN 0) (END (STRING-LENGTH STRING))) (TV-STRING-LENGTH TV-STREAM-PC-PPR STRING BEGIN END)) (:DRAW-LINE (X0 Y0 X1 Y1 &OPTIONAL (TV-ALU TV-ALU-IOR)) (LET ((TOP (PC-PPR-TOP TV-STREAM-PC-PPR)) (LEFT (PC-PPR-LEFT TV-STREAM-PC-PPR))) (TV-DRAW-LINE (+ LEFT X0) (+ TOP Y0) (+ LEFT X1) (+ TOP Y1) TV-ALU TV-DEFAULT-SCREEN))) ;; The character or string to be inserted is passed along so that variable ;; width fonts can work correctly. Fixed width font console ;; streams can ignore this argument. By default, the characters are printed ;; in the newly created whitespace since this is what happens most of the time. ;; :INSERT-STRING and :DELETE-STRING both assume that the strings contain no newlines. (:INSERT-CHAR (&OPTIONAL (CHAR #\SPACE) (COUNT 1)) (TV-INSERT-WIDTH TV-STREAM-PC-PPR (* COUNT (TV-CHAR-WIDTH TV-STREAM-PC-PPR CHAR (PC-PPR-CURRENT-FONT TV-STREAM-PC-PPR)))) (DOTIMES (I COUNT) (TV-TYO TV-STREAM-PC-PPR CHAR))) (:INSERT-STRING (STRING &OPTIONAL (BEGIN 0) (END (STRING-LENGTH STRING))) (TV-INSERT-WIDTH TV-STREAM-PC-PPR (TV-STRING-LENGTH TV-STREAM-PC-PPR STRING BEGIN END)) (TV-STRING-OUT TV-STREAM-PC-PPR STRING BEGIN END)) (:DELETE-CHAR (&OPTIONAL (CHAR #\SPACE) (COUNT 1)) (TV-DELETE-WIDTH TV-STREAM-PC-PPR (* COUNT (TV-CHAR-WIDTH TV-STREAM-PC-PPR CHAR (PC-PPR-CURRENT-FONT TV-STREAM-PC-PPR))))) (:DELETE-STRING (STRING &OPTIONAL (BEGIN 0) (END (STRING-LENGTH STRING))) (TV-DELETE-WIDTH TV-STREAM-PC-PPR (TV-STRING-LENGTH TV-STREAM-PC-PPR STRING BEGIN END))) (:CLEAR-SCREEN () (TV-CLEAR-PC-PPR TV-STREAM-PC-PPR)) (:CLEAR-EOL () (TV-CLEAR-EOL TV-STREAM-PC-PPR)) ;; Operations particular to this type of stream (:PC-PPR () TV-STREAM-PC-PPR) (:SET-PC-PPR (PC-PPR) (SETQ TV-STREAM-PC-PPR PC-PPR)) ) (DEFUN TV-STREAM-DEFAULT-HANDLER (OP &OPTIONAL ARG1 &REST REST) (STREAM-DEFAULT-HANDLER #'TV-STREAM OP ARG1 REST)) The stream in AI : also follows this protocol . ;; Below is the definition of the editor stream. The particular ;; "editor" or rubout handler used is a parameter of the stream. This stream handles the : and : RUBOUT - HANDLER operations ;; so that console streams don't have to worry about this. ;; Set up the :WHICH-OPERATIONS list ahead of time so as to avoid ;; excessive consing. This operation gets invoked every time READ or READLINE is called , for instance . (DECLARE (SPECIAL ES-CONSOLE-STREAM ES-EDITOR ES-UNTYI-CHAR ES-KILL-RING ES-BUFFER ES-WHICH-OPERATIONS ES-X-ORIGIN ES-Y-ORIGIN)) (DEFUN MAKE-EDITOR-STREAM (ES-CONSOLE-STREAM ES-EDITOR &OPTIONAL (KILL-RING-SIZE 20.)) (LET ((ES-UNTYI-CHAR NIL) (ES-KILL-RING NIL) (ES-BUFFER) (ES-X-ORIGIN) (ES-Y-ORIGIN) ;; Be sure to include :CLEAR-INPUT for BREAK. Don't include :TYI and ;; :TYI-NO-HANG since we can't really do them unless the underlying ;; stream can. (ES-WHICH-OPERATIONS (UNION '(:UNTYI :RUBOUT-HANDLER :CLEAR-INPUT :LISTEN) (FUNCALL ES-CONSOLE-STREAM ':WHICH-OPERATIONS)))) (DOTIMES (I KILL-RING-SIZE) (PUSH (MAKE-ARRAY NIL 'ART-8B 400 NIL '(0 0 0)) ES-KILL-RING)) ;; Make the kill ring into a real ring. (RPLACD (LAST ES-KILL-RING) ES-KILL-RING) (SETQ ES-BUFFER (CAR ES-KILL-RING)) (CLOSURE '(ES-CONSOLE-STREAM ES-EDITOR ES-UNTYI-CHAR ES-KILL-RING ES-BUFFER ES-WHICH-OPERATIONS) #'EDITOR-STREAM))) ;; FILL-POINTER points to what has been typed so far. SCAN-POINTER points ;; to what has been read so far. TYPEIN-POINTER points to where in the ;; middle of the line we are typing. (DEFMACRO FILL-POINTER () '(ARRAY-LEADER ES-BUFFER 0)) (DEFMACRO SCAN-POINTER () '(ARRAY-LEADER ES-BUFFER 1)) (DEFMACRO TYPEIN-POINTER () '(ARRAY-LEADER ES-BUFFER 2)) The third argument in the DEFSELECT function specification means ;; that we're handling :WHICH-OPERATIONS ourselves. May want to flush - CHAR infavor of using the buffer . (DEFSELECT (EDITOR-STREAM EDITOR-STREAM-DEFAULT-HANDLER T) (:WHICH-OPERATIONS () ES-WHICH-OPERATIONS) ;; Input Operations ;; Don't need EOF-OPTION for :TYI since this will always be an interactive stream. ;; Accept the option anyway since some functions may work for both interactive and ;; batch streams. (:TYI (&OPTIONAL IGNORE &AUX SCAN-POINTER) (COND ;; Give buffered-back character, if any. Don't bother echoing or putting ;; it in the editor buffer since this has already happened. We are guaranteed ;; that the untyi'ed char is the one just tyi'ed. (ES-UNTYI-CHAR (PROG1 ES-UNTYI-CHAR (SETQ ES-UNTYI-CHAR NIL))) ;; If not using a rubout processor, go directly to the underlying stream. ((NOT RUBOUT-HANDLER) (FUNCALL ES-CONSOLE-STREAM ':TYI)) ;; If using a rubout processor and unread input exists, then return it. ((> (FILL-POINTER) (SETQ SCAN-POINTER (SCAN-POINTER))) (SETF (SCAN-POINTER) (1+ SCAN-POINTER)) (AREF ES-BUFFER SCAN-POINTER)) ;; Else get more input via the rubout processor. ;; This is kind of a kludge. We really want a handle of SELF. ;; The stream state will be passed along since the specials are still bound. (T (FUNCALL ES-EDITOR #'EDITOR-STREAM)))) (:TYI-NO-HANG (&AUX SCAN-POINTER) (COND ;; Give buffered-back character, if any. (ES-UNTYI-CHAR (PROG1 ES-UNTYI-CHAR (SETQ ES-UNTYI-CHAR NIL))) ;; If not using a rubout processor, go directly to the underlying stream. ((NOT RUBOUT-HANDLER) (FUNCALL ES-CONSOLE-STREAM ':TYI-NO-HANG)) ;; Give buffered input from the rubout processor, if unread input exists. ((> (FILL-POINTER) (SETQ SCAN-POINTER (SCAN-POINTER))) (SETF (SCAN-POINTER) (1+ SCAN-POINTER)) (AREF ES-BUFFER SCAN-POINTER)) ;; In the case where the rubout handler is on, but no unread input exists, ;; just go to the underlying stream and try to get a character. Don't ;; bother with echoing it or putting it in the character buffer, although ;; this is probably what we should do. (T (FUNCALL ES-CONSOLE-STREAM ':TYI-NO-HANG)))) (:UNTYI (CHAR) (SETQ ES-UNTYI-CHAR CHAR)) ;; Should we check here to see of the console stream really supports :LISTEN? (:LISTEN () (COND (ES-UNTYI-CHAR) ((> (FILL-POINTER) (SCAN-POINTER)) (AREF ES-BUFFER (SCAN-POINTER))) (T (FUNCALL ES-CONSOLE-STREAM ':LISTEN)))) ;; If the rubout handler is on, empty the buffer. Perhaps we should clear the ;; input from the screen in this case as well since the user is still typing. ;; I don't see how this could ever happen. If the handler is off, don't clear ;; the buffer since we want to save the input to be yanked back. (:CLEAR-INPUT () (COND (RUBOUT-HANDLER (SETF (FILL-POINTER) 0) (SETF (SCAN-POINTER) 0) (SETF (TYPEIN-POINTER) 0))) (SETQ ES-UNTYI-CHAR NIL) (FUNCALL ES-CONSOLE-STREAM ':CLEAR-INPUT)) The first argument for this operation is an alist of options or NIL . The options currently supported are : FULL - RUBOUT , : PROMPT , : REPROMPT and : PASS - THROUGH . (:RUBOUT-HANDLER (OPTIONS READ-FUNCTION &REST ARGS TEMP) ;; Save whatever the previous input was by cycling through the kill ring. ;; If the previous input was the empty string, as in exiting via the :FULL-RUBOUT ;; option, don't bother. (COND ((NOT (ZEROP (FILL-POINTER))) (SETQ ES-KILL-RING (CIRCULAR-LIST-LAST ES-KILL-RING)) (SETQ ES-BUFFER (CAR ES-KILL-RING)))) ;; Empty the rubout handler buffer of the new buffer. (SETF (FILL-POINTER) 0) (SETF (TYPEIN-POINTER) 0) ;; Prompt if desired. (SETQ TEMP (ASSQ ':PROMPT OPTIONS)) (IF TEMP (FUNCALL (CADR TEMP) #'EDITOR-STREAM NIL)) ;; Record the position on the screen at which the handler was entered. (IF (MEMQ ':READ-CURSORPOS ES-WHICH-OPERATIONS) (MULTIPLE-VALUE (ES-X-ORIGIN ES-Y-ORIGIN) (FUNCALL ES-CONSOLE-STREAM ':READ-CURSORPOS))) ;; Absorb and echo the untyi'ed char. We don't need to do this while inside ;; the rubout handler since characters get echoed there. This code runs when ;; READ is called from inside the error handler, for instance. ;; This is kind of a crock since the rubout handler should decide what to do ;; with the character. (COND (ES-UNTYI-CHAR (ARRAY-PUSH ES-BUFFER ES-UNTYI-CHAR) (FUNCALL ES-CONSOLE-STREAM ':TYO (LDB %%KBD-CHAR ES-UNTYI-CHAR)) (SETQ ES-UNTYI-CHAR NIL))) These two specials used for communication up and down the stack . First says we 're inside the rubout handler , and the second passes ;; options down to the editor function. These specials could be flushed if this ;; state information were kept in the stream, but it would have to be explicitly ;; turned on and off when a specific stack frame was entered and exited. (DO ((RUBOUT-HANDLER T) (TV-MAKE-STREAM-RUBOUT-HANDLER-OPTIONS OPTIONS)) (NIL) ;; Loop until normal (non-throw) exit, which will pass by the CATCH and DO. Each time we enter this loop ( after the first time ) , we are preparing for ;; a re-scan of the input string, so reset the scan pointer. (SETF (SCAN-POINTER) 0) (*CATCH 'RUBOUT-HANDLER (PROGN (ERRSET APPLY is more efficient than - FUNCALL if the read ;; function takes a &rest argument. (MULTIPLE-VALUE-RETURN (APPLY READ-FUNCTION ARGS))) ;; On read error, reprint contents of buffer so user can rub out ok. The ERRSET lets the error message get printed . (IF (MEMQ ':READ-CURSORPOS ES-WHICH-OPERATIONS) (MULTIPLE-VALUE (ES-X-ORIGIN ES-Y-ORIGIN) (FUNCALL ES-CONSOLE-STREAM ':READ-CURSORPOS))) (FUNCALL ES-CONSOLE-STREAM ':STRING-OUT ES-BUFFER) ;; If the user makes an error during read-time, swallow ;; all input until a rubout (or some editing character) ;; is typed. When the edit is complete, we will ;; throw back out of here. This should be changed to stop ;; echoing until the edit is done. (DO () (NIL) (EDITOR-STREAM ':TYI)))) ;; When a rubout or other editing operation is done, throws back to the ;; catch to reread the input. But if the :FULL-RUBOUT option was specified and everything was rubbed out , we return NIL and the specified value . (IF (AND (ZEROP (FILL-POINTER)) (SETQ TEMP (ASSQ ':FULL-RUBOUT OPTIONS))) (RETURN NIL (CADR TEMP))) ))) ;; Returns the "last" element in a circular list, i.e. the cons pointing to the cons we ;; are holding on to. (DEFUN CIRCULAR-LIST-LAST (LIST) (DO ((L (CDR LIST) (CDR L)) (PREV LIST L)) ((EQ LIST L) PREV))) ( DEFUN CIRCULAR - LIST - LENGTH ( LIST ) ;; (IF (NULL LIST) 0 ;; (DO ((L (CDR LIST) (CDR L)) ( I 1 ( 1 + I ) ) ) ;; ((EQ LIST L) I)))) ;; Forward all other operations to the underlying stream rather than ;; STREAM-DEFAULT-HANDLER. Again, we really need a handle on SELF. (DEFUN EDITOR-STREAM-DEFAULT-HANDLER (&REST REST) (LEXPR-FUNCALL ES-CONSOLE-STREAM REST)) Below are two editor functions which form a part of the editor stream . The first is a simple display editor which is a partial emacs , and the second is a printing terminal rubout handler for use via supdup . ;; These functions get called whenever a :TYI message is sent to the stream ;; and we are inside the rubout handler. If the user types a normal ;; character it is echoed, put in the buffer, and returned. If the user ;; types a rubout, or any other editing character, any number of editing commands are processed by modifying the buffer , then , when the first ;; non-editing character is typed, a throw is done back to the top level of ;; the read function and the buffered input will be re-scanned. The ;; character must be typed at the end of the line in order for the throw to ;; take place. This may be a bug. (DEFVAR DISPLAY-EDITOR-COMMAND-ALIST NIL) (DEFUN DISPLAY-EDITOR (STREAM &AUX CH CH-CHAR CH-CONTROL-META COMMAND (OPTIONS TV-MAKE-STREAM-RUBOUT-HANDLER-OPTIONS) (RUBBED-OUT-SOME NIL) (PASS-THROUGH (CDR (ASSQ ':PASS-THROUGH OPTIONS))) (NUMERIC-ARG NIL)) ;; Read characters. If an ordinary character typed and nothing rubbed out, ;; return immediately. Otherwise, let all editing operations complete ;; before returning. ;; This {{#/}} is correct, but is it needed? (SETF (TYPEIN-POINTER) (FILL-POINTER)) (*CATCH 'RETURN-CHARACTER (DO () (NIL) ;; Read a character from the underlying stream. This is a kludge for speed to avoid making two function calls -- one back to the editor ;; stream and then one to the console stream. ;; Really should be: ;; (LET ((RUBOUT-HANDLER NIL)) (FUNCALL STREAM ':TYI)) ;; or better (FUNCALL STREAM ':RAW-TYI) which would bypass the rubout handler. (SETQ CH (FUNCALL ES-CONSOLE-STREAM ':TYI)) (SETQ CH-CHAR (LDB %%KBD-CHAR CH)) (SETQ CH-CONTROL-META (LDB %%KBD-CONTROL-META CH)) (SETQ COMMAND (ASSQ (CHAR-UPCASE CH) DISPLAY-EDITOR-COMMAND-ALIST)) (COND ;; Don't touch this character ((MEMQ CH PASS-THROUGH) (DE-INSERT-CHAR STREAM CH 1 RUBBED-OUT-SOME) (SETQ RUBBED-OUT-SOME T)) A stream editor character of some sort . The RUBBED - OUT - SOME bit can ;; only be cleared by entering this function again. The stream editor ;; editor function is passed the stream and a numeric argument. (COMMAND (SETQ RUBBED-OUT-SOME (OR (FUNCALL (CDR COMMAND) STREAM (OR NUMERIC-ARG 1)) RUBBED-OUT-SOME)) (SETQ NUMERIC-ARG NIL)) ;;Handle control-number, control-u, and control-minus specially. ((AND (NOT (ZEROP CH-CONTROL-META)) ({{#/}} CH-CHAR #/0) ({{#/}} CH-CHAR #/9)) (SETQ CH-CHAR (- CH-CHAR #/0)) (SETQ NUMERIC-ARG (+ (* (OR NUMERIC-ARG 0) 10.) CH-CHAR))) ((= (CHAR-UPCASE CH) #{{#/}}/U) (SETQ NUMERIC-ARG (* (OR NUMERIC-ARG 1) 4))) ;; Some other random control character -- beep and ignore ((NOT (ZEROP CH-CONTROL-META)) (FUNCALL STREAM ':BEEP) (SETQ NUMERIC-ARG NIL)) Self - inserting character . Set RUBBED - OUT - SOME since if we return , ;; we were typing in the middle of the line. Typing at the end of the ;; line throws to RETURN-CHARACTER. (T (DE-INSERT-CHAR STREAM CH (OR NUMERIC-ARG 1) RUBBED-OUT-SOME) (SETQ NUMERIC-ARG NIL) (SETQ RUBBED-OUT-SOME T)))))) ;; A self-inserting character. A character gets here by being non-control-meta ;; and not having an editing command associated with it. Or it can get here ;; via the :PASS-THROUGH option. If a control-meta character gets here, it is ;; echoed as one, but loses its control-meta bits in the buffer. Also, inserting ;; a character with bucky bits on doesn't currently work since TV-CHAR-WIDTH returns ;; 0 as the width, and TV-TYO can't print it. (DEFUN DE-INSERT-CHAR (STREAM CH N RUBBED-OUT-SOME &AUX STRING) (SETQ STRING (MAKE-ARRAY NIL 'ART-16B N)) (DOTIMES (I N) (ASET CH STRING I)) (UNWIND-PROTECT (DE-INSERT-STRING STREAM STRING 0 N RUBBED-OUT-SOME) (RETURN-ARRAY STRING))) ;; Insert a string into the buffer and print it on the screen. The string ;; is inserted at the current cursor position, and the cursor is left after the string. (DEFUN DE-INSERT-STRING (STREAM STRING BEGIN END RUBBED-OUT-SOME &AUX (WIDTH (- END BEGIN)) (TYPEIN-POINTER (TYPEIN-POINTER)) (FILL-POINTER (FILL-POINTER))) Increase the size of of the buffer , if necessary . (IF (= FILL-POINTER (ARRAY-LENGTH ES-BUFFER)) (ADJUST-ARRAY-SIZE ES-BUFFER (+ (* 2 FILL-POINTER) WIDTH))) ;; Make room for the characters to be inserted. Be sure to increment the fill ;; pointer first so that we don't reference outside the active part of the string. (INCREMENT FILL-POINTER WIDTH) (INCREMENT TYPEIN-POINTER WIDTH) (SETF (FILL-POINTER) FILL-POINTER) (SETF (TYPEIN-POINTER) TYPEIN-POINTER) (COPY-VECTOR-SEGMENT (- FILL-POINTER TYPEIN-POINTER) ES-BUFFER (- TYPEIN-POINTER WIDTH) ES-BUFFER TYPEIN-POINTER) ;; Now copy the string in. (COPY-VECTOR-SEGMENT WIDTH STRING BEGIN ES-BUFFER (- TYPEIN-POINTER WIDTH)) ;; Update the screen. (COND ;; If the string is being inserted at the end of the line, then we will return ;; from the rubout handler. If the input buffer has been edited, then we will rescan . If not , we return the first character of the string and leave the scan pointer pointing at the second character , thus avoiding a rescan . ;; Also, updating the display is easier in this case since we don't have to hack insert chars . This is the case for normal -- the scan pointer will keep up with the pointer . ;; I think we need an option so that yanks at the end of the line don't throw ;; but remain in the editor. ((= TYPEIN-POINTER FILL-POINTER) (FUNCALL STREAM ':STRING-OUT STRING BEGIN END) (COND (RUBBED-OUT-SOME (*THROW 'RUBOUT-HANDLER T)) (T (INCREMENT (SCAN-POINTER)) (*THROW 'RETURN-CHARACTER (AREF STRING BEGIN))))) ;; If typing in the middle of the line, we just insert the text and don't bother ;; rescanning. That's only done when text appears at the end of the line to keep ;; the transcript from being confusing. This may be the wrong thing. ;; No need to update the scan pointer in this case since we're going to throw back ;; to the rubout handler. ((MEMQ ':INSERT-STRING ES-WHICH-OPERATIONS) (FUNCALL STREAM ':INSERT-STRING STRING BEGIN END)) If the console ca n't insert chars , simulate it vt52 style . (T (FUNCALL STREAM ':CLEAR-EOL) (FUNCALL STREAM ':STRING-OUT STRING BEGIN END) (FUNCALL STREAM ':STRING-OUT ES-BUFFER TYPEIN-POINTER) (DE-CURSOR-MOTION STREAM TYPEIN-POINTER))) ;; If we didn't throw out, then the input has been modified. Back to the editor. T) ;; Display Editor Commands (DEFMACRO DEF-DE-COMMAND ((NAME . CHARS) ARGS . BODY) `(PROGN 'COMPILE ,@(MAPCAR #'(LAMBDA (CHAR) `(PUSH '(,CHAR . ,NAME) DISPLAY-EDITOR-COMMAND-ALIST)) CHARS) (DEFUN ,NAME ,ARGS . ,BODY))) ;; Moves the cursor to a given position on the screen only. Does no ;; bounds checking. If the index into the buffer corresponding with the ;; screen cursor position is known, and it is before the position we want to ;; go to, then this will run faster. (DEFUN DE-CURSOR-MOTION (STREAM POSITION &OPTIONAL CURRENT-POSITION) (IF (AND CURRENT-POSITION ({{#/}} POSITION CURRENT-POSITION)) (FUNCALL STREAM ':CURSOR-MOTION NIL NIL ES-BUFFER CURRENT-POSITION POSITION) (FUNCALL STREAM ':CURSOR-MOTION ES-X-ORIGIN ES-Y-ORIGIN ES-BUFFER 0 POSITION))) ;; Moves the cursor on the screen and in the buffer. Checks appropriately. (DEFUN DE-SET-POSITION (STREAM POSITION) (SETQ POSITION (MIN (MAX POSITION 0) (FILL-POINTER))) (DE-CURSOR-MOTION STREAM POSITION (TYPEIN-POINTER)) (SETF (TYPEIN-POINTER) POSITION) NIL) ;; Reprinting Input (DEFUN DE-REPRINT-INPUT (STREAM CHAR &AUX PROMPT) (SETQ PROMPT (OR (ASSQ ':REPROMPT TV-MAKE-STREAM-RUBOUT-HANDLER-OPTIONS) (ASSQ ':PROMPT TV-MAKE-STREAM-RUBOUT-HANDLER-OPTIONS))) (IF PROMPT (FUNCALL (CADR PROMPT) STREAM CHAR)) (MULTIPLE-VALUE (ES-X-ORIGIN ES-Y-ORIGIN) (FUNCALL STREAM ':READ-CURSORPOS)) (FUNCALL STREAM ':STRING-OUT ES-BUFFER) (DE-CURSOR-MOTION STREAM (TYPEIN-POINTER)) NIL) FORM clears and redisplays input . Cursor is left where it was before . (DEF-DE-COMMAND (DE-FORM #\FORM #{{#/}}/L) (STREAM &OPTIONAL IGNORE) (FUNCALL STREAM ':CLEAR-SCREEN) (DE-REPRINT-INPUT STREAM #\FORM)) VT reprints input on next line . Cursor is left at the end of the typein line . (DEF-DE-COMMAND (DE-VT #\VT) (STREAM &OPTIONAL IGNORE) (DE-END-OF-BUFFER STREAM) (FUNCALL STREAM ':LINE-OUT "{{#/}}") (DE-REPRINT-INPUT STREAM #\VT)) ;; Moving Around Returns the position of the first newline appearing after POS . (DEFUN DE-SEARCH-FORWARD-NEWLINE (POS) (DO ((FILL-POINTER (FILL-POINTER)) (I POS (1+ I))) ((OR (= I FILL-POINTER) (= (AREF ES-BUFFER I) #\RETURN)) FILL-POINTER))) Returns the position of the first newline appearing before . ;; Returns -1 if reached the beginning of the buffer. (DEFUN DE-SEARCH-BACKWARD-NEWLINE (POS) (DO ((I (1- POS) (1- I))) ((OR (= I -1) (= (AREF ES-BUFFER I) #\RETURN)) I))) (DEF-DE-COMMAND (DE-BEGINNING-OF-LINE #{{#/}}/A) (STREAM &OPTIONAL IGNORE) (DE-SET-POSITION STREAM (1+ (DE-SEARCH-BACKWARD-NEWLINE (TYPEIN-POINTER))))) (DEF-DE-COMMAND (DE-END-OF-LINE #{{#/}}/E) (STREAM &OPTIONAL IGNORE) (DE-SET-POSITION STREAM (DE-SEARCH-FORWARD-NEWLINE (TYPEIN-POINTER)))) (DEF-DE-COMMAND (DE-BEGINNING-OF-BUFFER #{{#/}}/<) (STREAM &OPTIONAL IGNORE) (DE-SET-POSITION STREAM 0)) (DEF-DE-COMMAND (DE-END-OF-BUFFER #{{#/}}/>) (STREAM &OPTIONAL IGNORE) (DE-SET-POSITION STREAM (FILL-POINTER))) (DEF-DE-COMMAND (DE-FORWARD-CHAR #{{#/}}/F) (STREAM &OPTIONAL (N 1)) (DE-SET-POSITION STREAM (+ (TYPEIN-POINTER) N))) (DEF-DE-COMMAND (DE-BACKWARD-CHAR #{{#/}}/B) (STREAM &OPTIONAL (N 1)) (DE-SET-POSITION STREAM (- (TYPEIN-POINTER) N))) (DEF-DE-COMMAND (DE-PREVIOUS-LINE #{{#/}}/P) (STREAM &OPTIONAL (N 1) &AUX LINE-BEGIN INDENT) (SETQ LINE-BEGIN (DE-SEARCH-BACKWARD-NEWLINE (TYPEIN-POINTER))) (SETQ INDENT (- (TYPEIN-POINTER) LINE-BEGIN)) (DOTIMES (I N) (IF (= LINE-BEGIN -1) (RETURN)) (SETQ LINE-BEGIN (DE-SEARCH-BACKWARD-NEWLINE LINE-BEGIN))) ;; When moving up from a long line to a short line, be sure not to go off the end. (DE-SET-POSITION STREAM (+ LINE-BEGIN (MIN INDENT (DE-SEARCH-FORWARD-NEWLINE (1+ LINE-BEGIN)))))) (DEF-DE-COMMAND (DE-NEXT-LINE #{{#/}}/N) (STREAM &OPTIONAL (N 1) &AUX LINE-BEGIN INDENT) (SETQ LINE-BEGIN (DE-SEARCH-BACKWARD-NEWLINE (TYPEIN-POINTER))) (SETQ INDENT (- (TYPEIN-POINTER) LINE-BEGIN)) (DOTIMES (I N) (COND ((= LINE-BEGIN (FILL-POINTER)) (SETQ LINE-BEGIN (DE-SEARCH-BACKWARD-NEWLINE LINE-BEGIN)) (RETURN))) (SETQ LINE-BEGIN (DE-SEARCH-FORWARD-NEWLINE (1+ LINE-BEGIN)))) (DE-SET-POSITION STREAM (+ LINE-BEGIN (MIN INDENT (DE-SEARCH-FORWARD-NEWLINE (1+ LINE-BEGIN)))))) ;; Deleting Things Deletes a buffer interval as marked by two pointers passed in . The pointer ;; is left at the beginning of the interval. (DEFUN DE-DELETE-STRING (STREAM BEGIN END &AUX WIDTH TYPEIN-POINTER (FILL-POINTER (FILL-POINTER))) (SETQ BEGIN (MAX BEGIN 0)) (SETQ END (MIN END FILL-POINTER)) (SETQ WIDTH (- END BEGIN)) (DE-SET-POSITION STREAM BEGIN) ;; Set this after moving the cursor to the beginning of the string. (SETQ TYPEIN-POINTER (TYPEIN-POINTER)) (COND ;; Efficiency hack for clearing to the end of line, as in C-K and CLEAR. ;; Don't need to add up character widths as needed in :DELETE-STRING. ((= END FILL-POINTER) (FUNCALL STREAM ':CLEAR-EOL)) ;; Console can delete characters. Pass in the string to make variable width fonts win. ((MEMQ ':DELETE-STRING ES-WHICH-OPERATIONS) (FUNCALL STREAM ':DELETE-STRING ES-BUFFER BEGIN END)) ;; Console can't delete characters. Be sure to do a clear-eol to flush those ;; characters at the very end. (T (FUNCALL STREAM ':CLEAR-EOL) (FUNCALL STREAM ':STRING-OUT ES-BUFFER END) (DE-CURSOR-MOTION STREAM END))) ;; Now actually delete the characters from the buffer. Do this before decrementing ;; the fill pointer so that we don't attempt to reference outside the string. (COPY-VECTOR-SEGMENT (- FILL-POINTER END) ES-BUFFER (+ TYPEIN-POINTER WIDTH) ES-BUFFER TYPEIN-POINTER) (SETF (FILL-POINTER) (- FILL-POINTER WIDTH)) If all has been deleted and the : FULL - RUBOUT option is ;; active, then throw now. This will throw if the user types rubout ;; immediately after entering the read function. (IF (AND (ZEROP (FILL-POINTER)) (ASSQ ':FULL-RUBOUT TV-MAKE-STREAM-RUBOUT-HANDLER-OPTIONS)) (*THROW 'RUBOUT-HANDLER T)) ;; If it turns out that nothing was deleted, then don't bother rescanning input. ({{#/}} WIDTH 0)) (DEF-DE-COMMAND (DE-DELETE-CHAR #{{#/}}/D) (STREAM &OPTIONAL (N 1)) (DE-DELETE-STRING STREAM (TYPEIN-POINTER) (+ (TYPEIN-POINTER) N))) (DEF-DE-COMMAND (DE-RUBOUT-CHAR #\RUBOUT) (STREAM &OPTIONAL (N 1)) (DE-DELETE-STRING STREAM (- (TYPEIN-POINTER) N) (TYPEIN-POINTER))) ;; CLEAR flushes all buffered input. If the full rubout option is in ;; use, then we will throw out of here. No need to prompt since the prompt still there. (DEF-DE-COMMAND (DE-CLEAR #\CLEAR) (STREAM &OPTIONAL IGNORE) (DE-DELETE-STRING STREAM 0 (FILL-POINTER))) ;; If at the end of the line, change this to kill only the newline. (DEF-DE-COMMAND (DE-CLEAR-EOL #{{#/}}/K) (STREAM &OPTIONAL IGNORE) (DE-DELETE-STRING STREAM (TYPEIN-POINTER) (DE-SEARCH-FORWARD-NEWLINE (TYPEIN-POINTER)))) Word Commands (DEFUN DE-ALPHABETIC? (CHAR) (SETQ CHAR (CHAR-UPCASE CHAR)) (AND ({{#/}} CHAR #/A) ({{#/}} CHAR #/Z))) Returns the position of the first ( non ) alphabetic character ;; in the buffer. If no alphabetic characters between current ;; typein position and end of line, return nil. (DEFUN DE-SEARCH-FORWARD-ALPHABETIC (POS) (DO ((FILL-POINTER (FILL-POINTER)) (I POS (1+ I))) ((= I FILL-POINTER) NIL) (IF (DE-ALPHABETIC? (AREF ES-BUFFER I)) (RETURN I)))) (DEFUN DE-SEARCH-FORWARD-NON-ALPHABETIC (POS) (DO ((FILL-POINTER (FILL-POINTER)) (I POS (1+ I))) ((= I FILL-POINTER) NIL) (IF (NOT (DE-ALPHABETIC? (AREF ES-BUFFER I))) (RETURN I)))) (DEFUN DE-SEARCH-BACKWARD-ALPHABETIC (POS) (DO ((I POS (1- I))) ((= I -1) NIL) (IF (DE-ALPHABETIC? (AREF ES-BUFFER I)) (RETURN I)))) (DEFUN DE-SEARCH-BACKWARD-NON-ALPHABETIC (POS) (DO ((I POS (1- I))) ((= I -1) NIL) (IF (NOT (DE-ALPHABETIC? (AREF ES-BUFFER I))) (RETURN I)))) ;; Search for a point N words away and return that point. If on an alphabetic character , skip to the first non alphabetic one . If on a non - alphabetic , skip over non - alphabetics and then over alphabetics , If no alphabetics follow the non - alphabetics , then do n't move at all . (DEFUN DE-SEARCH-FORWARD-WORD (N &AUX (POS (TYPEIN-POINTER)) SEARCH-POS) (DO ((I 0 (1+ I))) ((= I N) POS) (COND ((DE-ALPHABETIC? (AREF ES-BUFFER POS)) (SETQ POS (DE-SEARCH-FORWARD-NON-ALPHABETIC POS))) (T (SETQ SEARCH-POS (DE-SEARCH-FORWARD-ALPHABETIC POS)) (IF (NOT SEARCH-POS) (RETURN POS)) (SETQ POS (DE-SEARCH-FORWARD-NON-ALPHABETIC SEARCH-POS)))) ;;If within a word and can't find whitespace, leave at right end. (IF (NOT POS) (RETURN (FILL-POINTER))))) ;; Search for a point N words back and return that point. ;; If on an alphabetic character, skip to the character just following the first non - alphabetic one . If on a non - alphabetic , skip over non - alphabetics and then over alphabetics . If no alphabetics after non - alphabetics , then do n't move at all . Treat cursor on first character of a word as a special case . (DEFUN DE-SEARCH-BACKWARD-WORD (N &AUX (POS (TYPEIN-POINTER)) SEARCH-POS) (DO ((I 0 (1+ I))) ((= I N) POS) (COND ;;At beginning of line -- punt ((= POS 0) (RETURN 0)) ;;Inside a word but not at the beginning of a word. ((AND (DE-ALPHABETIC? (AREF ES-BUFFER POS)) (DE-ALPHABETIC? (AREF ES-BUFFER (1- POS)))) (SETQ POS (DE-SEARCH-BACKWARD-NON-ALPHABETIC POS))) ;;Within whitespace or at beginning of a word. (T (SETQ SEARCH-POS (IF (DE-ALPHABETIC? (AREF ES-BUFFER POS)) (1- POS) POS)) (SETQ SEARCH-POS (DE-SEARCH-BACKWARD-ALPHABETIC SEARCH-POS)) (IF (NOT SEARCH-POS) (RETURN POS)) (SETQ POS (DE-SEARCH-BACKWARD-NON-ALPHABETIC SEARCH-POS)))) ;;If within a word and can't find whitespace, leave at left end. (IF (NOT POS) (RETURN 0)) Leave cursor on first character of the word (INCREMENT POS) )) (DEF-DE-COMMAND (DE-FORWARD-WORD #{{#/}}/F) (STREAM &OPTIONAL (N 1)) (DE-SET-POSITION STREAM (DE-SEARCH-FORWARD-WORD N))) (DEF-DE-COMMAND (DE-BACKWARD-WORD #{{#/}}/B) (STREAM &OPTIONAL (N 1)) (DE-SET-POSITION STREAM (DE-SEARCH-BACKWARD-WORD N))) (DEF-DE-COMMAND (DE-DELETE-WORD #{{#/}}/D) (STREAM &OPTIONAL (N 1)) (DE-DELETE-STRING STREAM (TYPEIN-POINTER) (DE-SEARCH-FORWARD-WORD N))) (DEF-DE-COMMAND (DE-RUBOUT-WORD #{{#/}}\RUBOUT) (STREAM &OPTIONAL (N 1)) (DE-DELETE-STRING STREAM (DE-SEARCH-BACKWARD-WORD N) (TYPEIN-POINTER))) (DEF-DE-COMMAND (DE-TWIDDLE-CHARS #{{#/}}/T) (STREAM &OPTIONAL IGNORE &AUX DELETE-POINTER STRING) (SETQ DELETE-POINTER (TYPEIN-POINTER)) At end of line , go back two chars ; in middle of line , one ; at beginning , none . (DECREMENT DELETE-POINTER (COND ((= DELETE-POINTER 0) 0) ((= DELETE-POINTER (FILL-POINTER)) 2) (T 1))) (SETQ STRING (SUBSTRING ES-BUFFER DELETE-POINTER (+ DELETE-POINTER 2))) (DE-DELETE-STRING STREAM DELETE-POINTER (+ DELETE-POINTER 2)) (SETQ STRING (STRING-NREVERSE STRING)) (DE-INSERT-STRING STREAM STRING 0 2 T)) Kill Ring Commands ;; This doesn't really yank things killed, only previous complete lines typed ;; or the current line. C-0 C-Y yanks the current line, C-1 C-Y yanks the previous ;; thing typed. Everything but the last character is brought back, since that ;; is generally the character which triggers the return of the read function. ;; E.g. ) in reading a list, space in reading a symbol, cr in readline, control-c ;; in qsend. This way, we will be asked for more input rather than having ;; the read function return for us. Alternately, we could force the editor ;; to retain control and yank back the complete line. We pass in T for RUBBED - OUT - SOME since it is n't currently given ;; to us. So, we always rescan when yanking at the end of the line. (DEF-DE-COMMAND (DE-YANK #{{#/}}/Y) (STREAM &OPTIONAL (N 1) &AUX (YANKED (NTH N ES-KILL-RING))) (DE-INSERT-STRING STREAM YANKED 0 (MAX 0 (1- (STRING-LENGTH YANKED))) T)) ;; Move the thing at the top of the kill ring to the bottom of the kill ring (DEFUN DE-POP-KILL-RING () (SETF (FIRST ES-KILL-RING) (SECOND ES-KILL-RING)) (SETF (SECOND ES-KILL-RING) ES-BUFFER) (POP ES-KILL-RING)) If previous command was a Yank or a Yank - Pop , then remove what was placed there ;; by the command, yank in the top thing on the ring, and cycle the ring forward. ;; Otherwise, treat the command like an ordinary yank, except pop the ring afterward. (DEF-DE-COMMAND (DE-YANK-POP #{{#/}}/Y) (STREAM &OPTIONAL IGNORE &AUX YANKED YANKED-LENGTH (TYPEIN-POINTER (TYPEIN-POINTER))) (PROG () First see if it was a Yank - Pop . (SETQ YANKED (CAR (CIRCULAR-LIST-LAST ES-KILL-RING))) (SETQ YANKED-LENGTH (1- (STRING-LENGTH YANKED))) (IF (AND ({{#/}} TYPEIN-POINTER YANKED-LENGTH) (STRING-EQUAL ES-BUFFER YANKED (- TYPEIN-POINTER YANKED-LENGTH) 0 TYPEIN-POINTER YANKED-LENGTH)) (RETURN)) ;; Then check for an ordinary yank. If it matches, then pop it off ;; the ring so that we'll get the next thing. (SETQ YANKED (SECOND ES-KILL-RING)) (SETQ YANKED-LENGTH (1- (STRING-LENGTH YANKED))) (COND ((AND ({{#/}} TYPEIN-POINTER YANKED-LENGTH) (STRING-EQUAL ES-BUFFER YANKED (- TYPEIN-POINTER YANKED-LENGTH) 0 TYPEIN-POINTER YANKED-LENGTH)) (DE-POP-KILL-RING) (RETURN))) ;; No match. (SETQ YANKED NIL)) ;; The previous command was a yank of some type. Delete the yanked screen from ;; the screen and the buffer. (IF YANKED (DE-DELETE-STRING STREAM (- TYPEIN-POINTER YANKED-LENGTH) TYPEIN-POINTER)) ;; Yank the thing at the top of the kill ring, and pop the kill ring (DE-YANK STREAM 1) (DE-POP-KILL-RING)) #+DEBUG (DEF-DE-COMMAND (DE-DEBUG #\HELP) (STREAM &OPTIONAL IGNORE) (FORMAT STREAM "~%[Fill pointer = ~D Typein pointer = ~D]~%" (FILL-POINTER) (TYPEIN-POINTER)) (DE-REPRINT-INPUT STREAM #\HELP)) ;; Now a printing (heh, heh) terminal editor. For poor souls coming via supdup ;; and for purposes of comparison. (DEFUN PRINTING-EDITOR (STREAM &AUX CH PROMPT (OPTIONS TV-MAKE-STREAM-RUBOUT-HANDLER-OPTIONS) (RUBBED-OUT-SOME NIL) (DOING-RUBOUT NIL) (PASS-THROUGH (CDR (ASSQ ':PASS-THROUGH OPTIONS)))) (*CATCH 'RETURN-CHARACTER (DO () (NIL) (SETQ CH (FUNCALL ES-CONSOLE-STREAM ':TYI)) (COND ((MEMQ CH PASS-THROUGH) (PRINTING-EDITOR-INSERT-CHAR STREAM CH RUBBED-OUT-SOME DOING-RUBOUT)) Control - D and Control - U kill the current line , ITS and Twenex style . ;; If nothing in the buffer, don't do anything. ((MEMQ CH '(#{{#/}}/d #{{#/}}/D #{{#/}}/u #{{#/}}/U)) (COND ((NOT (ZEROP (FILL-POINTER))) (SETF (FILL-POINTER) 0) (SETQ RUBBED-OUT-SOME T) (COND (DOING-RUBOUT (FUNCALL STREAM ':TYO #/]) (SETQ DOING-RUBOUT NIL))) (FUNCALL STREAM ':LINE-OUT " XXX") (SETQ PROMPT (OR (ASSQ ':REPROMPT OPTIONS) (ASSQ ':PROMPT OPTIONS))) (IF PROMPT (FUNCALL PROMPT STREAM CH)) (IF (ASSQ ':FULL-RUBOUT OPTIONS) (*THROW 'RUBOUT-HANDLER T))))) Control - K or Control - L echo themselves and then reprint the current ;; line, prompting if necessary. ((MEMQ CH '(#\VT #\FORM #{{#/}}/k #{{#/}}/K #{{#/}}/l #{{#/}}/L)) (FUNCALL STREAM ':TYO CH) (FUNCALL STREAM ':FRESH-LINE) (SETQ PROMPT (OR (ASSQ ':REPROMPT OPTIONS) (ASSQ ':PROMPT OPTIONS))) (IF PROMPT (FUNCALL PROMPT STREAM CH)) (FUNCALL STREAM ':STRING-OUT ES-BUFFER)) Echo characters backwards Unix style . ((= CH #\RUBOUT) (MULTIPLE-VALUE (RUBBED-OUT-SOME DOING-RUBOUT) (PRINTING-EDITOR-RUBOUT-CHAR STREAM OPTIONS RUBBED-OUT-SOME DOING-RUBOUT))) Control - W flushes word . ((MEMQ CH '(#{{#/}}/w #{{#/}}/W)) (COND ((NOT (ZEROP (FILL-POINTER))) First flush whitespace . (DO () ((OR (ZEROP (FILL-POINTER)) (DE-ALPHABETIC? (AREF ES-BUFFER (1- (FILL-POINTER)))))) (MULTIPLE-VALUE (RUBBED-OUT-SOME DOING-RUBOUT) (PRINTING-EDITOR-RUBOUT-CHAR STREAM OPTIONS RUBBED-OUT-SOME DOING-RUBOUT))) Then flush alphabetics . (DO () ((OR (ZEROP (FILL-POINTER)) (NOT (DE-ALPHABETIC? (AREF ES-BUFFER (1- (FILL-POINTER))))))) (MULTIPLE-VALUE (RUBBED-OUT-SOME DOING-RUBOUT) (PRINTING-EDITOR-RUBOUT-CHAR STREAM OPTIONS RUBBED-OUT-SOME DOING-RUBOUT)))) (DOING-RUBOUT (FUNCALL STREAM ':LINE-OUT "]") (SETQ DOING-RUBOUT NIL)))) ;; Flush random control characters. ((NOT (ZEROP (LDB %%KBD-CONTROL-META CH))) (FUNCALL STREAM ':BEEP)) (T (PRINTING-EDITOR-INSERT-CHAR STREAM CH RUBBED-OUT-SOME DOING-RUBOUT)))))) (DEFUN PRINTING-EDITOR-RUBOUT-CHAR (STREAM OPTIONS RUBBED-OUT-SOME DOING-RUBOUT &AUX CH) (COND ((NOT (ZEROP (FILL-POINTER))) (SETQ RUBBED-OUT-SOME T) (SETQ CH (ARRAY-POP ES-BUFFER)) ;; If we're already rubbing out, then echo character. ;; If we're not rubbing out and the character is a space, then backspace. If this is our first rubout , print " [ " and echo . (COND (DOING-RUBOUT (FUNCALL STREAM ':TYO CH)) ((= CH #\SPACE) (FUNCALL STREAM ':TYO #\BS)) (T (SETQ DOING-RUBOUT T) (FUNCALL STREAM ':TYO #/[) (FUNCALL STREAM ':TYO CH))) ;; Rubbed out everything, and :FULL-RUBOUT option active, so throw. (IF (AND (ZEROP (FILL-POINTER)) (ASSQ ':FULL-RUBOUT OPTIONS)) (*THROW 'RUBOUT-HANDLER T)) (MVRETURN RUBBED-OUT-SOME DOING-RUBOUT)) ;; Nothing left in the input buffer. If we were rubbing out, close the ;; rubout and go to the next line. (DOING-RUBOUT (FUNCALL STREAM ':LINE-OUT "]") (MVRETURN RUBBED-OUT-SOME NIL)))) ;; This is only called when typing at the end of the line. There is no ;; such thing as typing in the middle of the line here. (DEFUN PRINTING-EDITOR-INSERT-CHAR (STREAM CH RUBBED-OUT-SOME DOING-RUBOUT) (IF DOING-RUBOUT (FUNCALL STREAM ':TYO #/])) (FUNCALL STREAM ':TYO CH) (ARRAY-PUSH-EXTEND ES-BUFFER CH) (INCREMENT (SCAN-POINTER)) (IF RUBBED-OUT-SOME (*THROW 'RUBOUT-HANDLER T) (*THROW 'RETURN-CHARACTER CH))) #+DEBUG (PROGN 'COMPILE ;; These functions for debugging the editor stream. ;; Random "read" functions which test various aspects of the stream. (DEFUN READ-10-CHARS (&OPTIONAL (STREAM STANDARD-INPUT) EOF-OPTION &AUX RESULT) (IF (AND (NOT RUBOUT-HANDLER) (MEMQ ':RUBOUT-HANDLER (FUNCALL STREAM ':WHICH-OPERATIONS))) If the : FULL - RUBOUT option is activated , this will return NIL . ;; Keep looping until a string is returned. (DO () (NIL) (SETQ RESULT (FUNCALL STREAM ':RUBOUT-HANDLER '((:FULL-RUBOUT T) (:PROMPT ES-DEBUG-PROMPT) (:REPROMPT ES-DEBUG-REPROMPT)) #'READ-10-CHARS STREAM EOF-OPTION)) (IF RESULT (RETURN RESULT)) (ES-DEBUG-FULL-RUBOUT STREAM)) (LET ((CHARS (MAKE-ARRAY NIL ART-STRING 10.))) (DOTIMES (I 10.) (ASET (FUNCALL STREAM ':TYI EOF-OPTION) CHARS I)) CHARS))) ;; A study in compensating for missing capabilities -- :INSERT-CHAR [ 1 ] Let the receiving end ( console stream ) worry about it , press file style . ;; It would have to maintain a complete screen image. [ 2 ] The editor stream can handle some cases . This would only work during ;; interactive typein. [ 3 ] Let the toplevel program handle it . It most likely has the screen image ;; buffered in another form. But now, everybody has to worry about the missing ;; capability, although some programs will have better ideas about how to compensate for them . I think having both [ 1 ] and [ 3 ] is the right thing . (DEFUN READ-10-CHARS-FLASH (&OPTIONAL (STREAM TERMINAL-IO) &AUX (W-O (FUNCALL STREAM ':WHICH-OPERATIONS)) CHARS X Y) (SETQ CHARS (READ-10-CHARS STREAM)) (COND ((MEMQ ':READ-CURSORPOS W-O) . Hopefully unnecessary in nws . (SETQ X (SYMEVAL-IN-CLOSURE STREAM 'ES-X-ORIGIN)) (SETQ Y (SYMEVAL-IN-CLOSURE STREAM 'ES-Y-ORIGIN)) (FUNCALL STREAM ':SET-CURSORPOS X Y) (COND ((MEMQ ':INSERT-CHAR W-O) (FUNCALL STREAM ':INSERT-CHAR #/[) (FUNCALL STREAM ':CURSOR-MOTION NIL NIL CHARS)) (T (FUNCALL STREAM ':TYO #/[) (FUNCALL STREAM ':STRING-OUT CHARS))) (FUNCALL STREAM ':TYO #/]))) (IF (MEMQ ':BEEP W-O) (FUNCALL STREAM ':BEEP)) (RETURN-ARRAY CHARS)) ;; Uses the rubout handler to read characters until a Control-C is typed, but ;; does no consing at all. Useful for testing if a rubout handler conses ;; and also tests the :PASS-THROUGH option. (DEFUN CHARACTER-SINK (&OPTIONAL (STOP-CHARS '(#{{#/}}/c #{{#/}}/C)) (STREAM STANDARD-INPUT)) (COND ((AND (NOT RUBOUT-HANDLER) (MEMQ ':RUBOUT-HANDLER (FUNCALL STREAM ':WHICH-OPERATIONS))) (FUNCALL STREAM ':RUBOUT-HANDLER `((:PASS-THROUGH . ,STOP-CHARS) (:PROMPT ES-DEBUG-PROMPT) (:REPROMPT ES-DEBUG-REPROMPT)) #'CHARACTER-SINK STOP-CHARS STREAM)) ;; CHAR-EQUAL throws away bucky bits. (T (DO () ((MEMQ (FUNCALL STREAM ':TYI) STOP-CHARS))) (DOTIMES (I 3) (FUNCALL STREAM ':BEEP))))) (DEFUN ES-DEBUG-PROMPT (STREAM IGNORE) (FORMAT STREAM "~&~11A" "Prompt:")) (DEFUN ES-DEBUG-REPROMPT (STREAM IGNORE) (FORMAT STREAM "~11A" "Reprompt:")) (DEFUN ES-DEBUG-FULL-RUBOUT (STREAM) (FORMAT STREAM "[Full Rubout]~%")) ;; Various testing functions which affect a local lisp listener only. ;; Test display editor, printing editor, multiple font stuff. (DEFUN ES-DEBUG-DISPLAY (&AUX WINDOW STREAM) (SETQ WINDOW (<- SELECTED-WINDOW ':PANE)) (SETQ TERMINAL-IO (MAKE-EDITOR-STREAM (MAKE-TV-STREAM (<- WINDOW ':PC-PPR)) #'DISPLAY-EDITOR)) (<- WINDOW ':STREAM<- TERMINAL-IO)) (DEFUN ES-DEBUG-PRINTING (&AUX WINDOW) (SETQ WINDOW (<- SELECTED-WINDOW ':PANE)) (SETQ TERMINAL-IO (MAKE-EDITOR-STREAM (MAKE-TV-STREAM (<- WINDOW ':PC-PPR)) #'PRINTING-EDITOR)) ;; Make the stream look like a printing console. (SET-IN-CLOSURE TERMINAL-IO 'ES-WHICH-OPERATIONS '(:TYI :TYI-NO-HANG :LISTEN :TYO :STRING-OUT :LINE-OUT :FRESH-LINE :BEEP :UNTYI :RUBOUT-HANDLER :CLEAR-INPUT :LISTEN)) (<- WINDOW ':STREAM<- TERMINAL-IO)) (DEFUN ES-DEBUG-FONT (&OPTIONAL (FONT "TR10B")) (SETQ FONT (STRING-UPCASE FONT)) Ca n't use LOAD - IF - NEEDED since CPTFONT comes from CPTFON > . (IF (NOT (SECOND (MULTIPLE-VALUE-LIST (INTERN FONT "Fonts")))) (LOAD (FORMAT NIL "AI:LMFONT;~A" FONT))) (SETQ FONT (SYMEVAL (INTERN FONT "Fonts"))) (TV-REDEFINE-PC-PPR (FUNCALL TERMINAL-IO ':PC-PPR) ':FONTS (LIST FONT))) (DEFUN ES-DEBUG-OFF (&AUX WINDOW) (SETQ WINDOW (<- SELECTED-WINDOW ':PANE)) (SETQ TERMINAL-IO (TV-MAKE-STREAM (<- WINDOW ':PC-PPR))) (<- WINDOW ':STREAM<- TERMINAL-IO)) ) ;; End of Debug conditionalization (DEFUN DE-TV-MAKE-STREAM (PC-PPR) (MAKE-EDITOR-STREAM (MAKE-TV-STREAM PC-PPR) #'DISPLAY-EDITOR)) ;; This function is for turning the thing on globally. It clobbers ;; TV-MAKE-STREAM and TOP-WINDOW and should only be called from inside ;; the initial lisp listener. (DEFUN DE-GLOBAL-ENABLE () (FSET 'TV-MAKE-STREAM #'DE-TV-MAKE-STREAM) (SETQ TERMINAL-IO (DE-TV-MAKE-STREAM CONSOLE-IO-PC-PPR)) (<- TOP-WINDOW ':STREAM<- TERMINAL-IO)) #-DEBUG (DE-GLOBAL-ENABLE) To do : Modify kill ring representation to not include current buffer . ;; Change font set and default font. ;; Make kill ring stuff work for printing editor. ;; Make printing editor cross out characters with slashes. Be careful ;; about newlines. Write a printing editor ( regular editor plus ? ? command ) {{#/}}{{#/}}
null
https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/gjc/editst.lisp
lisp
-*- Mode: Lisp; Package: System-Internals -*- Lisp Machine Editor Stream The rubout handler implemented here is a crock since it duplicates the functions of ZWEI. However, this editor is implemented in terms of stream operations, and thus can be used from consoles other than the UTILS . There are a couple ideas here: The editor stream itself is separated from the underlying console stream. This is nice since the console stream need know nothing about the rubout handler, and thus rubout handlers can be changed easily without having to duplicate the code for the entire console stream. different console streams. Another thought would be to split the bare console stream into an input stream from a keyboard and an output stream to a window streams together into a single interactive i/o stream. I can't see much use for this, unless somebody wanted a keyboard stream without having a window, or there were multiple keyboard types in use. Terminology: CONSOLE-STREAM -- a bi-directional stream to some console. This stream knows nothing about rubout handling. EDITOR-STREAM -- a bi-directional stream connected to some console stream. It handles both the :RUBOUT-HANDLER and :UNTYI stream operations. case of a console stream. SUPDUP-STREAM -- a bi-directional stream to a console connected via the Chaos net. Special case of a console stream. MAKE-TV-STREAM takes a piece of paper, and returns a it uses the keyboard. For output, it types on the piece of paper. Input operations Clear hardware/firmware buffers Output operations TV-TYO doesn't print "control" characters. If at the beginning of a line, clear it. Otherwise, go If no unit is specified, then the "preferred" unit is used. This is the unit that :SET-CURSORPOS defaults to and that :COMPUTE-MOTION uses. The :CHARACTER unit of these operations is useless with variable width fonts. For compatibility Compute the new cursor position if STRING were output at the specified X-POS and Y-POS are in pixels. Compute the motion for printing a string and then move the cursor there. This eliminates the problem of knowing whether to use the :PIXEL or :CHARACTER unit when calling :SET-CURSORPOS. Since the string is passed in here as an editor stream. This might be better named :MOVE-OVER-STRING. Check for page wrap-around. This assumes that the cursor is positioned before the string to be underlined. The operation should be defined to xor, so that underlining twice erases. Font hackery. FONT-LIST is a list of strings describing fonts, since internal font representations are per-stream. Try to avoid calling The character or string to be inserted is passed along so that variable width fonts can work correctly. Fixed width font console streams can ignore this argument. By default, the characters are printed in the newly created whitespace since this is what happens most of the time. :INSERT-STRING and :DELETE-STRING both assume that the strings contain no newlines. Operations particular to this type of stream Below is the definition of the editor stream. The particular "editor" or rubout handler used is a parameter of the stream. so that console streams don't have to worry about this. Set up the :WHICH-OPERATIONS list ahead of time so as to avoid excessive consing. This operation gets invoked every time READ Be sure to include :CLEAR-INPUT for BREAK. Don't include :TYI and :TYI-NO-HANG since we can't really do them unless the underlying stream can. Make the kill ring into a real ring. FILL-POINTER points to what has been typed so far. SCAN-POINTER points to what has been read so far. TYPEIN-POINTER points to where in the middle of the line we are typing. that we're handling :WHICH-OPERATIONS ourselves. Input Operations Don't need EOF-OPTION for :TYI since this will always be an interactive stream. Accept the option anyway since some functions may work for both interactive and batch streams. Give buffered-back character, if any. Don't bother echoing or putting it in the editor buffer since this has already happened. We are guaranteed that the untyi'ed char is the one just tyi'ed. If not using a rubout processor, go directly to the underlying stream. If using a rubout processor and unread input exists, then return it. Else get more input via the rubout processor. This is kind of a kludge. We really want a handle of SELF. The stream state will be passed along since the specials are still bound. Give buffered-back character, if any. If not using a rubout processor, go directly to the underlying stream. Give buffered input from the rubout processor, if unread input exists. In the case where the rubout handler is on, but no unread input exists, just go to the underlying stream and try to get a character. Don't bother with echoing it or putting it in the character buffer, although this is probably what we should do. Should we check here to see of the console stream really supports :LISTEN? If the rubout handler is on, empty the buffer. Perhaps we should clear the input from the screen in this case as well since the user is still typing. I don't see how this could ever happen. If the handler is off, don't clear the buffer since we want to save the input to be yanked back. Save whatever the previous input was by cycling through the kill ring. If the previous input was the empty string, as in exiting via the :FULL-RUBOUT option, don't bother. Empty the rubout handler buffer of the new buffer. Prompt if desired. Record the position on the screen at which the handler was entered. Absorb and echo the untyi'ed char. We don't need to do this while inside the rubout handler since characters get echoed there. This code runs when READ is called from inside the error handler, for instance. This is kind of a crock since the rubout handler should decide what to do with the character. options down to the editor function. These specials could be flushed if this state information were kept in the stream, but it would have to be explicitly turned on and off when a specific stack frame was entered and exited. Loop until normal (non-throw) exit, which will pass by the CATCH and DO. a re-scan of the input string, so reset the scan pointer. function takes a &rest argument. On read error, reprint contents of buffer so user can rub out ok. If the user makes an error during read-time, swallow all input until a rubout (or some editing character) is typed. When the edit is complete, we will throw back out of here. This should be changed to stop echoing until the edit is done. When a rubout or other editing operation is done, throws back to the catch to reread the input. But if the :FULL-RUBOUT option was specified Returns the "last" element in a circular list, i.e. the cons pointing to the cons we are holding on to. (IF (NULL LIST) 0 (DO ((L (CDR LIST) (CDR L)) ((EQ LIST L) I)))) Forward all other operations to the underlying stream rather than STREAM-DEFAULT-HANDLER. Again, we really need a handle on SELF. These functions get called whenever a :TYI message is sent to the stream and we are inside the rubout handler. If the user types a normal character it is echoed, put in the buffer, and returned. If the user types a rubout, or any other editing character, any number of editing non-editing character is typed, a throw is done back to the top level of the read function and the buffered input will be re-scanned. The character must be typed at the end of the line in order for the throw to take place. This may be a bug. Read characters. If an ordinary character typed and nothing rubbed out, return immediately. Otherwise, let all editing operations complete before returning. This {{#/}} is correct, but is it needed? Read a character from the underlying stream. This is a kludge for stream and then one to the console stream. Really should be: (LET ((RUBOUT-HANDLER NIL)) (FUNCALL STREAM ':TYI)) or better (FUNCALL STREAM ':RAW-TYI) which would bypass the rubout handler. Don't touch this character only be cleared by entering this function again. The stream editor editor function is passed the stream and a numeric argument. Handle control-number, control-u, and control-minus specially. Some other random control character -- beep and ignore we were typing in the middle of the line. Typing at the end of the line throws to RETURN-CHARACTER. A self-inserting character. A character gets here by being non-control-meta and not having an editing command associated with it. Or it can get here via the :PASS-THROUGH option. If a control-meta character gets here, it is echoed as one, but loses its control-meta bits in the buffer. Also, inserting a character with bucky bits on doesn't currently work since TV-CHAR-WIDTH returns 0 as the width, and TV-TYO can't print it. Insert a string into the buffer and print it on the screen. The string is inserted at the current cursor position, and the cursor is left after the string. Make room for the characters to be inserted. Be sure to increment the fill pointer first so that we don't reference outside the active part of the string. Now copy the string in. Update the screen. If the string is being inserted at the end of the line, then we will return from the rubout handler. If the input buffer has been edited, then we will Also, updating the display is easier in this case since we don't have to hack I think we need an option so that yanks at the end of the line don't throw but remain in the editor. If typing in the middle of the line, we just insert the text and don't bother rescanning. That's only done when text appears at the end of the line to keep the transcript from being confusing. This may be the wrong thing. No need to update the scan pointer in this case since we're going to throw back to the rubout handler. If we didn't throw out, then the input has been modified. Back to the editor. Display Editor Commands Moves the cursor to a given position on the screen only. Does no bounds checking. If the index into the buffer corresponding with the screen cursor position is known, and it is before the position we want to go to, then this will run faster. Moves the cursor on the screen and in the buffer. Checks appropriately. Reprinting Input Moving Around Returns -1 if reached the beginning of the buffer. When moving up from a long line to a short line, be sure not to go off the end. Deleting Things is left at the beginning of the interval. Set this after moving the cursor to the beginning of the string. Efficiency hack for clearing to the end of line, as in C-K and CLEAR. Don't need to add up character widths as needed in :DELETE-STRING. Console can delete characters. Pass in the string to make variable width fonts win. Console can't delete characters. Be sure to do a clear-eol to flush those characters at the very end. Now actually delete the characters from the buffer. Do this before decrementing the fill pointer so that we don't attempt to reference outside the string. active, then throw now. This will throw if the user types rubout immediately after entering the read function. If it turns out that nothing was deleted, then don't bother rescanning input. CLEAR flushes all buffered input. If the full rubout option is in use, then we will throw out of here. No need to prompt since the prompt still there. If at the end of the line, change this to kill only the newline. in the buffer. If no alphabetic characters between current typein position and end of line, return nil. Search for a point N words away and return that point. If within a word and can't find whitespace, leave at right end. Search for a point N words back and return that point. If on an alphabetic character, skip to the character just following the At beginning of line -- punt Inside a word but not at the beginning of a word. Within whitespace or at beginning of a word. If within a word and can't find whitespace, leave at left end. in middle of line , one ; at beginning , none . This doesn't really yank things killed, only previous complete lines typed or the current line. C-0 C-Y yanks the current line, C-1 C-Y yanks the previous thing typed. Everything but the last character is brought back, since that is generally the character which triggers the return of the read function. E.g. ) in reading a list, space in reading a symbol, cr in readline, control-c in qsend. This way, we will be asked for more input rather than having the read function return for us. Alternately, we could force the editor to retain control and yank back the complete line. to us. So, we always rescan when yanking at the end of the line. Move the thing at the top of the kill ring to the bottom of the kill ring by the command, yank in the top thing on the ring, and cycle the ring forward. Otherwise, treat the command like an ordinary yank, except pop the ring afterward. Then check for an ordinary yank. If it matches, then pop it off the ring so that we'll get the next thing. No match. The previous command was a yank of some type. Delete the yanked screen from the screen and the buffer. Yank the thing at the top of the kill ring, and pop the kill ring Now a printing (heh, heh) terminal editor. For poor souls coming via supdup and for purposes of comparison. If nothing in the buffer, don't do anything. line, prompting if necessary. Flush random control characters. If we're already rubbing out, then echo character. If we're not rubbing out and the character is a space, then backspace. Rubbed out everything, and :FULL-RUBOUT option active, so throw. Nothing left in the input buffer. If we were rubbing out, close the rubout and go to the next line. This is only called when typing at the end of the line. There is no such thing as typing in the middle of the line here. These functions for debugging the editor stream. Random "read" functions which test various aspects of the stream. Keep looping until a string is returned. A study in compensating for missing capabilities -- :INSERT-CHAR It would have to maintain a complete screen image. interactive typein. buffered in another form. But now, everybody has to worry about the missing capability, although some programs will have better ideas about how to Uses the rubout handler to read characters until a Control-C is typed, but does no consing at all. Useful for testing if a rubout handler conses and also tests the :PASS-THROUGH option. CHAR-EQUAL throws away bucky bits. Various testing functions which affect a local lisp listener only. Test display editor, printing editor, multiple font stuff. Make the stream look like a printing console. End of Debug conditionalization This function is for turning the thing on globally. It clobbers TV-MAKE-STREAM and TOP-WINDOW and should only be called from inside the initial lisp listener. Change font set and default font. Make kill ring stuff work for printing editor. Make printing editor cross out characters with slashes. Be careful about newlines.
local Lisp Machine console . This file makes use of the definitions In addition , it makes it easy to have one editor stream work for on a given monitor . The editor stream would then bind these two TV - STREAM -- a bi - directional stream to the Lisp Machine console . Special stream which talks to the TV terminal of the Lisp Machine . For input , (DECLARE (SPECIAL TV-STREAM-PC-PPR)) (DEFUN MAKE-TV-STREAM (TV-STREAM-PC-PPR) (CLOSURE '(TV-STREAM-PC-PPR) #'TV-STREAM)) (DEFSELECT (TV-STREAM TV-STREAM-DEFAULT-HANDLER) (:TYI () (KBD-TYI)) (:TYI-NO-HANG () (KBD-TYI-NO-HANG)) (:LISTEN () (KBD-CHAR-AVAILABLE)) (:CLEAR-INPUT () (KBD-TYI))) (:TYO (CHAR) (TV-TYO TV-STREAM-PC-PPR CHAR)) (:STRING-OUT (STRING &OPTIONAL (BEGIN 0) END) (TV-STRING-OUT TV-STREAM-PC-PPR STRING BEGIN END)) (:LINE-OUT (STRING &OPTIONAL (BEGIN 0) END) (TV-STRING-OUT TV-STREAM-PC-PPR STRING BEGIN END) (TV-CRLF TV-STREAM-PC-PPR)) to the beginning of the next line and clear it . (:FRESH-LINE () (COND ((= (PC-PPR-CURRENT-X TV-STREAM-PC-PPR) (PC-PPR-LEFT-MARGIN TV-STREAM-PC-PPR)) (TV-CLEAR-EOL TV-STREAM-PC-PPR)) (T (TV-CRLF TV-STREAM-PC-PPR)))) (:TRIGGER-MORE () (OR (ZEROP (PC-PPR-EXCEPTIONS TV-STREAM-PC-PPR)) (TV-EXCEPTION TV-STREAM-PC-PPR))) (:BEEP (&OPTIONAL (WAVELENGTH TV-BEEP-WAVELENGTH) (DURATION TV-BEEP-DURATION)) (%BEEP WAVELENGTH DURATION)) (:READ-CURSORPOS (&OPTIONAL (UNIT ':PIXEL)) (MULTIPLE-VALUE-BIND (X Y) (TV-READ-CURSORPOS TV-STREAM-PC-PPR) (SELECTQ UNIT (:PIXEL) (:CHARACTER (SETQ X (// X (PC-PPR-CHAR-WIDTH TV-STREAM-PC-PPR))) (SETQ Y (// Y (PC-PPR-LINE-HEIGHT TV-STREAM-PC-PPR)))) (:OTHERWISE (FERROR NIL "~S is not a known unit." UNIT))) (MVRETURN X Y))) (:SET-CURSORPOS (X Y &OPTIONAL (UNIT ':PIXEL)) (IF (FIXP UNIT) (PSETQ UNIT X X Y Y UNIT)) (SELECTQ UNIT (:PIXEL) (:CHARACTER (SETQ X (* X (PC-PPR-CHAR-WIDTH TV-STREAM-PC-PPR))) (SETQ Y (* Y (PC-PPR-LINE-HEIGHT TV-STREAM-PC-PPR)))) (:OTHERWISE (FERROR NIL "~S is not a known unit." UNIT))) (TV-SET-CURSORPOS TV-STREAM-PC-PPR X Y)) (:SET-CURSORPOS-RELATIVE (X Y &OPTIONAL (UNIT ':PIXEL)) (SELECTQ UNIT (:PIXEL) (:CHARACTER (SETQ X (* X (PC-PPR-CHAR-WIDTH TV-STREAM-PC-PPR))) (SETQ Y (* Y (PC-PPR-LINE-HEIGHT TV-STREAM-PC-PPR)))) (:OTHERWISE (FERROR NIL "~S is not a known unit." UNIT))) (TV-SET-CURSORPOS-RELATIVE TV-STREAM-PC-PPR X Y)) (:SIZE-IN-CHARACTERS () (MVRETURN (// (- (PC-PPR-RIGHT-MARGIN TV-STREAM-PC-PPR) (PC-PPR-LEFT-MARGIN TV-STREAM-PC-PPR)) (PC-PPR-CHAR-WIDTH TV-STREAM-PC-PPR)) (// (- (PC-PPR-BOTTOM-MARGIN TV-STREAM-PC-PPR) (PC-PPR-TOP-MARGIN TV-STREAM-PC-PPR)) (PC-PPR-LINE-HEIGHT TV-STREAM-PC-PPR)))) point . NIL for X - POS and Y - POS mean use the current cursor position . (:COMPUTE-MOTION (X-POS Y-POS STRING &OPTIONAL (BEGIN 0) (END (STRING-LENGTH STRING))) (TV-COMPUTE-MOTION TV-STREAM-PC-PPR X-POS Y-POS STRING BEGIN END)) argument , this stream need know nothing about the buffer maintained by the (:CURSOR-MOTION (X-POS Y-POS STRING &OPTIONAL (BEGIN 0) (END (STRING-LENGTH STRING))) (MULTIPLE-VALUE-BIND (X Y HOW-FAR) (TV-COMPUTE-MOTION TV-STREAM-PC-PPR X-POS Y-POS STRING BEGIN END) (IF HOW-FAR (MULTIPLE-VALUE (X Y) (TV-COMPUTE-MOTION TV-STREAM-PC-PPR 0 0 STRING HOW-FAR END))) (TV-SET-CURSORPOS TV-STREAM-PC-PPR X Y))) (:UNDERLINE (STRING &OPTIONAL (BEGIN 0) (END (STRING-LENGTH STRING)) &AUX (X1 (PC-PPR-CURRENT-X TV-STREAM-PC-PPR)) (Y1 (+ (PC-PPR-CURRENT-Y TV-STREAM-PC-PPR) (PC-PPR-LINE-HEIGHT TV-STREAM-PC-PPR)))) (MULTIPLE-VALUE-BIND (X2 Y2) (TV-COMPUTE-MOTION TV-STREAM-PC-PPR X1 Y1 STRING BEGIN END) (TV-DRAW-LINE X1 Y1 X2 Y2 TV-ALU-XOR (PC-PPR-SCREEN TV-STREAM-PC-PPR)))) TV - REDEFINE - PC - PPR whenever a font change is made since this reallocates a new font map rather than reusing the old one . If the buffer is to contain font changes , then it should contain 16 - bit characters . (:SET-FONTS (&REST FONT-LIST) (TV-REDEFINE-PC-PPR TV-STREAM-PC-PPR ':FONTS (MAPCAR #'(LAMBDA (FONT) (SETQ FONT (INTERN FONT "FONTS")) (IF (BOUNDP FONT) (SYMEVAL FONT) FONTS:CPTFONT)) FONT-LIST))) (:SET-CURRENT-FONT (N) (TV-TYO TV-STREAM-PC-PPR (+ 240 N))) (:CHAR-WIDTH (&OPTIONAL CHAR FONT) (COND ((NOT CHAR) (PC-PPR-CHAR-WIDTH TV-STREAM-PC-PPR)) (T (SETQ FONT (IF (FIXP FONT) (AREF (PC-PPR-FONT-MAP TV-STREAM-PC-PPR)) (PC-PPR-CURRENT-FONT TV-STREAM-PC-PPR))) (TV-CHAR-WIDTH TV-STREAM-PC-PPR CHAR FONT)))) (:LINE-HEIGHT () (PC-PPR-LINE-HEIGHT TV-STREAM-PC-PPR)) (:STRING-WIDTH (STRING &OPTIONAL (BEGIN 0) (END (STRING-LENGTH STRING))) (TV-STRING-LENGTH TV-STREAM-PC-PPR STRING BEGIN END)) (:DRAW-LINE (X0 Y0 X1 Y1 &OPTIONAL (TV-ALU TV-ALU-IOR)) (LET ((TOP (PC-PPR-TOP TV-STREAM-PC-PPR)) (LEFT (PC-PPR-LEFT TV-STREAM-PC-PPR))) (TV-DRAW-LINE (+ LEFT X0) (+ TOP Y0) (+ LEFT X1) (+ TOP Y1) TV-ALU TV-DEFAULT-SCREEN))) (:INSERT-CHAR (&OPTIONAL (CHAR #\SPACE) (COUNT 1)) (TV-INSERT-WIDTH TV-STREAM-PC-PPR (* COUNT (TV-CHAR-WIDTH TV-STREAM-PC-PPR CHAR (PC-PPR-CURRENT-FONT TV-STREAM-PC-PPR)))) (DOTIMES (I COUNT) (TV-TYO TV-STREAM-PC-PPR CHAR))) (:INSERT-STRING (STRING &OPTIONAL (BEGIN 0) (END (STRING-LENGTH STRING))) (TV-INSERT-WIDTH TV-STREAM-PC-PPR (TV-STRING-LENGTH TV-STREAM-PC-PPR STRING BEGIN END)) (TV-STRING-OUT TV-STREAM-PC-PPR STRING BEGIN END)) (:DELETE-CHAR (&OPTIONAL (CHAR #\SPACE) (COUNT 1)) (TV-DELETE-WIDTH TV-STREAM-PC-PPR (* COUNT (TV-CHAR-WIDTH TV-STREAM-PC-PPR CHAR (PC-PPR-CURRENT-FONT TV-STREAM-PC-PPR))))) (:DELETE-STRING (STRING &OPTIONAL (BEGIN 0) (END (STRING-LENGTH STRING))) (TV-DELETE-WIDTH TV-STREAM-PC-PPR (TV-STRING-LENGTH TV-STREAM-PC-PPR STRING BEGIN END))) (:CLEAR-SCREEN () (TV-CLEAR-PC-PPR TV-STREAM-PC-PPR)) (:CLEAR-EOL () (TV-CLEAR-EOL TV-STREAM-PC-PPR)) (:PC-PPR () TV-STREAM-PC-PPR) (:SET-PC-PPR (PC-PPR) (SETQ TV-STREAM-PC-PPR PC-PPR)) ) (DEFUN TV-STREAM-DEFAULT-HANDLER (OP &OPTIONAL ARG1 &REST REST) (STREAM-DEFAULT-HANDLER #'TV-STREAM OP ARG1 REST)) The stream in AI : also follows this protocol . This stream handles the : and : RUBOUT - HANDLER operations or READLINE is called , for instance . (DECLARE (SPECIAL ES-CONSOLE-STREAM ES-EDITOR ES-UNTYI-CHAR ES-KILL-RING ES-BUFFER ES-WHICH-OPERATIONS ES-X-ORIGIN ES-Y-ORIGIN)) (DEFUN MAKE-EDITOR-STREAM (ES-CONSOLE-STREAM ES-EDITOR &OPTIONAL (KILL-RING-SIZE 20.)) (LET ((ES-UNTYI-CHAR NIL) (ES-KILL-RING NIL) (ES-BUFFER) (ES-X-ORIGIN) (ES-Y-ORIGIN) (ES-WHICH-OPERATIONS (UNION '(:UNTYI :RUBOUT-HANDLER :CLEAR-INPUT :LISTEN) (FUNCALL ES-CONSOLE-STREAM ':WHICH-OPERATIONS)))) (DOTIMES (I KILL-RING-SIZE) (PUSH (MAKE-ARRAY NIL 'ART-8B 400 NIL '(0 0 0)) ES-KILL-RING)) (RPLACD (LAST ES-KILL-RING) ES-KILL-RING) (SETQ ES-BUFFER (CAR ES-KILL-RING)) (CLOSURE '(ES-CONSOLE-STREAM ES-EDITOR ES-UNTYI-CHAR ES-KILL-RING ES-BUFFER ES-WHICH-OPERATIONS) #'EDITOR-STREAM))) (DEFMACRO FILL-POINTER () '(ARRAY-LEADER ES-BUFFER 0)) (DEFMACRO SCAN-POINTER () '(ARRAY-LEADER ES-BUFFER 1)) (DEFMACRO TYPEIN-POINTER () '(ARRAY-LEADER ES-BUFFER 2)) The third argument in the DEFSELECT function specification means May want to flush - CHAR infavor of using the buffer . (DEFSELECT (EDITOR-STREAM EDITOR-STREAM-DEFAULT-HANDLER T) (:WHICH-OPERATIONS () ES-WHICH-OPERATIONS) (:TYI (&OPTIONAL IGNORE &AUX SCAN-POINTER) (COND (ES-UNTYI-CHAR (PROG1 ES-UNTYI-CHAR (SETQ ES-UNTYI-CHAR NIL))) ((NOT RUBOUT-HANDLER) (FUNCALL ES-CONSOLE-STREAM ':TYI)) ((> (FILL-POINTER) (SETQ SCAN-POINTER (SCAN-POINTER))) (SETF (SCAN-POINTER) (1+ SCAN-POINTER)) (AREF ES-BUFFER SCAN-POINTER)) (T (FUNCALL ES-EDITOR #'EDITOR-STREAM)))) (:TYI-NO-HANG (&AUX SCAN-POINTER) (COND (ES-UNTYI-CHAR (PROG1 ES-UNTYI-CHAR (SETQ ES-UNTYI-CHAR NIL))) ((NOT RUBOUT-HANDLER) (FUNCALL ES-CONSOLE-STREAM ':TYI-NO-HANG)) ((> (FILL-POINTER) (SETQ SCAN-POINTER (SCAN-POINTER))) (SETF (SCAN-POINTER) (1+ SCAN-POINTER)) (AREF ES-BUFFER SCAN-POINTER)) (T (FUNCALL ES-CONSOLE-STREAM ':TYI-NO-HANG)))) (:UNTYI (CHAR) (SETQ ES-UNTYI-CHAR CHAR)) (:LISTEN () (COND (ES-UNTYI-CHAR) ((> (FILL-POINTER) (SCAN-POINTER)) (AREF ES-BUFFER (SCAN-POINTER))) (T (FUNCALL ES-CONSOLE-STREAM ':LISTEN)))) (:CLEAR-INPUT () (COND (RUBOUT-HANDLER (SETF (FILL-POINTER) 0) (SETF (SCAN-POINTER) 0) (SETF (TYPEIN-POINTER) 0))) (SETQ ES-UNTYI-CHAR NIL) (FUNCALL ES-CONSOLE-STREAM ':CLEAR-INPUT)) The first argument for this operation is an alist of options or NIL . The options currently supported are : FULL - RUBOUT , : PROMPT , : REPROMPT and : PASS - THROUGH . (:RUBOUT-HANDLER (OPTIONS READ-FUNCTION &REST ARGS TEMP) (COND ((NOT (ZEROP (FILL-POINTER))) (SETQ ES-KILL-RING (CIRCULAR-LIST-LAST ES-KILL-RING)) (SETQ ES-BUFFER (CAR ES-KILL-RING)))) (SETF (FILL-POINTER) 0) (SETF (TYPEIN-POINTER) 0) (SETQ TEMP (ASSQ ':PROMPT OPTIONS)) (IF TEMP (FUNCALL (CADR TEMP) #'EDITOR-STREAM NIL)) (IF (MEMQ ':READ-CURSORPOS ES-WHICH-OPERATIONS) (MULTIPLE-VALUE (ES-X-ORIGIN ES-Y-ORIGIN) (FUNCALL ES-CONSOLE-STREAM ':READ-CURSORPOS))) (COND (ES-UNTYI-CHAR (ARRAY-PUSH ES-BUFFER ES-UNTYI-CHAR) (FUNCALL ES-CONSOLE-STREAM ':TYO (LDB %%KBD-CHAR ES-UNTYI-CHAR)) (SETQ ES-UNTYI-CHAR NIL))) These two specials used for communication up and down the stack . First says we 're inside the rubout handler , and the second passes (DO ((RUBOUT-HANDLER T) (TV-MAKE-STREAM-RUBOUT-HANDLER-OPTIONS OPTIONS)) (NIL) Each time we enter this loop ( after the first time ) , we are preparing for (SETF (SCAN-POINTER) 0) (*CATCH 'RUBOUT-HANDLER (PROGN (ERRSET APPLY is more efficient than - FUNCALL if the read (MULTIPLE-VALUE-RETURN (APPLY READ-FUNCTION ARGS))) The ERRSET lets the error message get printed . (IF (MEMQ ':READ-CURSORPOS ES-WHICH-OPERATIONS) (MULTIPLE-VALUE (ES-X-ORIGIN ES-Y-ORIGIN) (FUNCALL ES-CONSOLE-STREAM ':READ-CURSORPOS))) (FUNCALL ES-CONSOLE-STREAM ':STRING-OUT ES-BUFFER) (DO () (NIL) (EDITOR-STREAM ':TYI)))) and everything was rubbed out , we return NIL and the specified value . (IF (AND (ZEROP (FILL-POINTER)) (SETQ TEMP (ASSQ ':FULL-RUBOUT OPTIONS))) (RETURN NIL (CADR TEMP))) ))) (DEFUN CIRCULAR-LIST-LAST (LIST) (DO ((L (CDR LIST) (CDR L)) (PREV LIST L)) ((EQ LIST L) PREV))) ( DEFUN CIRCULAR - LIST - LENGTH ( LIST ) ( I 1 ( 1 + I ) ) ) (DEFUN EDITOR-STREAM-DEFAULT-HANDLER (&REST REST) (LEXPR-FUNCALL ES-CONSOLE-STREAM REST)) Below are two editor functions which form a part of the editor stream . The first is a simple display editor which is a partial emacs , and the second is a printing terminal rubout handler for use via supdup . commands are processed by modifying the buffer , then , when the first (DEFVAR DISPLAY-EDITOR-COMMAND-ALIST NIL) (DEFUN DISPLAY-EDITOR (STREAM &AUX CH CH-CHAR CH-CONTROL-META COMMAND (OPTIONS TV-MAKE-STREAM-RUBOUT-HANDLER-OPTIONS) (RUBBED-OUT-SOME NIL) (PASS-THROUGH (CDR (ASSQ ':PASS-THROUGH OPTIONS))) (NUMERIC-ARG NIL)) (SETF (TYPEIN-POINTER) (FILL-POINTER)) (*CATCH 'RETURN-CHARACTER (DO () (NIL) speed to avoid making two function calls -- one back to the editor (SETQ CH (FUNCALL ES-CONSOLE-STREAM ':TYI)) (SETQ CH-CHAR (LDB %%KBD-CHAR CH)) (SETQ CH-CONTROL-META (LDB %%KBD-CONTROL-META CH)) (SETQ COMMAND (ASSQ (CHAR-UPCASE CH) DISPLAY-EDITOR-COMMAND-ALIST)) (COND ((MEMQ CH PASS-THROUGH) (DE-INSERT-CHAR STREAM CH 1 RUBBED-OUT-SOME) (SETQ RUBBED-OUT-SOME T)) A stream editor character of some sort . The RUBBED - OUT - SOME bit can (COMMAND (SETQ RUBBED-OUT-SOME (OR (FUNCALL (CDR COMMAND) STREAM (OR NUMERIC-ARG 1)) RUBBED-OUT-SOME)) (SETQ NUMERIC-ARG NIL)) ((AND (NOT (ZEROP CH-CONTROL-META)) ({{#/}} CH-CHAR #/0) ({{#/}} CH-CHAR #/9)) (SETQ CH-CHAR (- CH-CHAR #/0)) (SETQ NUMERIC-ARG (+ (* (OR NUMERIC-ARG 0) 10.) CH-CHAR))) ((= (CHAR-UPCASE CH) #{{#/}}/U) (SETQ NUMERIC-ARG (* (OR NUMERIC-ARG 1) 4))) ((NOT (ZEROP CH-CONTROL-META)) (FUNCALL STREAM ':BEEP) (SETQ NUMERIC-ARG NIL)) Self - inserting character . Set RUBBED - OUT - SOME since if we return , (T (DE-INSERT-CHAR STREAM CH (OR NUMERIC-ARG 1) RUBBED-OUT-SOME) (SETQ NUMERIC-ARG NIL) (SETQ RUBBED-OUT-SOME T)))))) (DEFUN DE-INSERT-CHAR (STREAM CH N RUBBED-OUT-SOME &AUX STRING) (SETQ STRING (MAKE-ARRAY NIL 'ART-16B N)) (DOTIMES (I N) (ASET CH STRING I)) (UNWIND-PROTECT (DE-INSERT-STRING STREAM STRING 0 N RUBBED-OUT-SOME) (RETURN-ARRAY STRING))) (DEFUN DE-INSERT-STRING (STREAM STRING BEGIN END RUBBED-OUT-SOME &AUX (WIDTH (- END BEGIN)) (TYPEIN-POINTER (TYPEIN-POINTER)) (FILL-POINTER (FILL-POINTER))) Increase the size of of the buffer , if necessary . (IF (= FILL-POINTER (ARRAY-LENGTH ES-BUFFER)) (ADJUST-ARRAY-SIZE ES-BUFFER (+ (* 2 FILL-POINTER) WIDTH))) (INCREMENT FILL-POINTER WIDTH) (INCREMENT TYPEIN-POINTER WIDTH) (SETF (FILL-POINTER) FILL-POINTER) (SETF (TYPEIN-POINTER) TYPEIN-POINTER) (COPY-VECTOR-SEGMENT (- FILL-POINTER TYPEIN-POINTER) ES-BUFFER (- TYPEIN-POINTER WIDTH) ES-BUFFER TYPEIN-POINTER) (COPY-VECTOR-SEGMENT WIDTH STRING BEGIN ES-BUFFER (- TYPEIN-POINTER WIDTH)) (COND rescan . If not , we return the first character of the string and leave the scan pointer pointing at the second character , thus avoiding a rescan . insert chars . This is the case for normal -- the scan pointer will keep up with the pointer . ((= TYPEIN-POINTER FILL-POINTER) (FUNCALL STREAM ':STRING-OUT STRING BEGIN END) (COND (RUBBED-OUT-SOME (*THROW 'RUBOUT-HANDLER T)) (T (INCREMENT (SCAN-POINTER)) (*THROW 'RETURN-CHARACTER (AREF STRING BEGIN))))) ((MEMQ ':INSERT-STRING ES-WHICH-OPERATIONS) (FUNCALL STREAM ':INSERT-STRING STRING BEGIN END)) If the console ca n't insert chars , simulate it vt52 style . (T (FUNCALL STREAM ':CLEAR-EOL) (FUNCALL STREAM ':STRING-OUT STRING BEGIN END) (FUNCALL STREAM ':STRING-OUT ES-BUFFER TYPEIN-POINTER) (DE-CURSOR-MOTION STREAM TYPEIN-POINTER))) T) (DEFMACRO DEF-DE-COMMAND ((NAME . CHARS) ARGS . BODY) `(PROGN 'COMPILE ,@(MAPCAR #'(LAMBDA (CHAR) `(PUSH '(,CHAR . ,NAME) DISPLAY-EDITOR-COMMAND-ALIST)) CHARS) (DEFUN ,NAME ,ARGS . ,BODY))) (DEFUN DE-CURSOR-MOTION (STREAM POSITION &OPTIONAL CURRENT-POSITION) (IF (AND CURRENT-POSITION ({{#/}} POSITION CURRENT-POSITION)) (FUNCALL STREAM ':CURSOR-MOTION NIL NIL ES-BUFFER CURRENT-POSITION POSITION) (FUNCALL STREAM ':CURSOR-MOTION ES-X-ORIGIN ES-Y-ORIGIN ES-BUFFER 0 POSITION))) (DEFUN DE-SET-POSITION (STREAM POSITION) (SETQ POSITION (MIN (MAX POSITION 0) (FILL-POINTER))) (DE-CURSOR-MOTION STREAM POSITION (TYPEIN-POINTER)) (SETF (TYPEIN-POINTER) POSITION) NIL) (DEFUN DE-REPRINT-INPUT (STREAM CHAR &AUX PROMPT) (SETQ PROMPT (OR (ASSQ ':REPROMPT TV-MAKE-STREAM-RUBOUT-HANDLER-OPTIONS) (ASSQ ':PROMPT TV-MAKE-STREAM-RUBOUT-HANDLER-OPTIONS))) (IF PROMPT (FUNCALL (CADR PROMPT) STREAM CHAR)) (MULTIPLE-VALUE (ES-X-ORIGIN ES-Y-ORIGIN) (FUNCALL STREAM ':READ-CURSORPOS)) (FUNCALL STREAM ':STRING-OUT ES-BUFFER) (DE-CURSOR-MOTION STREAM (TYPEIN-POINTER)) NIL) FORM clears and redisplays input . Cursor is left where it was before . (DEF-DE-COMMAND (DE-FORM #\FORM #{{#/}}/L) (STREAM &OPTIONAL IGNORE) (FUNCALL STREAM ':CLEAR-SCREEN) (DE-REPRINT-INPUT STREAM #\FORM)) VT reprints input on next line . Cursor is left at the end of the typein line . (DEF-DE-COMMAND (DE-VT #\VT) (STREAM &OPTIONAL IGNORE) (DE-END-OF-BUFFER STREAM) (FUNCALL STREAM ':LINE-OUT "{{#/}}") (DE-REPRINT-INPUT STREAM #\VT)) Returns the position of the first newline appearing after POS . (DEFUN DE-SEARCH-FORWARD-NEWLINE (POS) (DO ((FILL-POINTER (FILL-POINTER)) (I POS (1+ I))) ((OR (= I FILL-POINTER) (= (AREF ES-BUFFER I) #\RETURN)) FILL-POINTER))) Returns the position of the first newline appearing before . (DEFUN DE-SEARCH-BACKWARD-NEWLINE (POS) (DO ((I (1- POS) (1- I))) ((OR (= I -1) (= (AREF ES-BUFFER I) #\RETURN)) I))) (DEF-DE-COMMAND (DE-BEGINNING-OF-LINE #{{#/}}/A) (STREAM &OPTIONAL IGNORE) (DE-SET-POSITION STREAM (1+ (DE-SEARCH-BACKWARD-NEWLINE (TYPEIN-POINTER))))) (DEF-DE-COMMAND (DE-END-OF-LINE #{{#/}}/E) (STREAM &OPTIONAL IGNORE) (DE-SET-POSITION STREAM (DE-SEARCH-FORWARD-NEWLINE (TYPEIN-POINTER)))) (DEF-DE-COMMAND (DE-BEGINNING-OF-BUFFER #{{#/}}/<) (STREAM &OPTIONAL IGNORE) (DE-SET-POSITION STREAM 0)) (DEF-DE-COMMAND (DE-END-OF-BUFFER #{{#/}}/>) (STREAM &OPTIONAL IGNORE) (DE-SET-POSITION STREAM (FILL-POINTER))) (DEF-DE-COMMAND (DE-FORWARD-CHAR #{{#/}}/F) (STREAM &OPTIONAL (N 1)) (DE-SET-POSITION STREAM (+ (TYPEIN-POINTER) N))) (DEF-DE-COMMAND (DE-BACKWARD-CHAR #{{#/}}/B) (STREAM &OPTIONAL (N 1)) (DE-SET-POSITION STREAM (- (TYPEIN-POINTER) N))) (DEF-DE-COMMAND (DE-PREVIOUS-LINE #{{#/}}/P) (STREAM &OPTIONAL (N 1) &AUX LINE-BEGIN INDENT) (SETQ LINE-BEGIN (DE-SEARCH-BACKWARD-NEWLINE (TYPEIN-POINTER))) (SETQ INDENT (- (TYPEIN-POINTER) LINE-BEGIN)) (DOTIMES (I N) (IF (= LINE-BEGIN -1) (RETURN)) (SETQ LINE-BEGIN (DE-SEARCH-BACKWARD-NEWLINE LINE-BEGIN))) (DE-SET-POSITION STREAM (+ LINE-BEGIN (MIN INDENT (DE-SEARCH-FORWARD-NEWLINE (1+ LINE-BEGIN)))))) (DEF-DE-COMMAND (DE-NEXT-LINE #{{#/}}/N) (STREAM &OPTIONAL (N 1) &AUX LINE-BEGIN INDENT) (SETQ LINE-BEGIN (DE-SEARCH-BACKWARD-NEWLINE (TYPEIN-POINTER))) (SETQ INDENT (- (TYPEIN-POINTER) LINE-BEGIN)) (DOTIMES (I N) (COND ((= LINE-BEGIN (FILL-POINTER)) (SETQ LINE-BEGIN (DE-SEARCH-BACKWARD-NEWLINE LINE-BEGIN)) (RETURN))) (SETQ LINE-BEGIN (DE-SEARCH-FORWARD-NEWLINE (1+ LINE-BEGIN)))) (DE-SET-POSITION STREAM (+ LINE-BEGIN (MIN INDENT (DE-SEARCH-FORWARD-NEWLINE (1+ LINE-BEGIN)))))) Deletes a buffer interval as marked by two pointers passed in . The pointer (DEFUN DE-DELETE-STRING (STREAM BEGIN END &AUX WIDTH TYPEIN-POINTER (FILL-POINTER (FILL-POINTER))) (SETQ BEGIN (MAX BEGIN 0)) (SETQ END (MIN END FILL-POINTER)) (SETQ WIDTH (- END BEGIN)) (DE-SET-POSITION STREAM BEGIN) (SETQ TYPEIN-POINTER (TYPEIN-POINTER)) (COND ((= END FILL-POINTER) (FUNCALL STREAM ':CLEAR-EOL)) ((MEMQ ':DELETE-STRING ES-WHICH-OPERATIONS) (FUNCALL STREAM ':DELETE-STRING ES-BUFFER BEGIN END)) (T (FUNCALL STREAM ':CLEAR-EOL) (FUNCALL STREAM ':STRING-OUT ES-BUFFER END) (DE-CURSOR-MOTION STREAM END))) (COPY-VECTOR-SEGMENT (- FILL-POINTER END) ES-BUFFER (+ TYPEIN-POINTER WIDTH) ES-BUFFER TYPEIN-POINTER) (SETF (FILL-POINTER) (- FILL-POINTER WIDTH)) If all has been deleted and the : FULL - RUBOUT option is (IF (AND (ZEROP (FILL-POINTER)) (ASSQ ':FULL-RUBOUT TV-MAKE-STREAM-RUBOUT-HANDLER-OPTIONS)) (*THROW 'RUBOUT-HANDLER T)) ({{#/}} WIDTH 0)) (DEF-DE-COMMAND (DE-DELETE-CHAR #{{#/}}/D) (STREAM &OPTIONAL (N 1)) (DE-DELETE-STRING STREAM (TYPEIN-POINTER) (+ (TYPEIN-POINTER) N))) (DEF-DE-COMMAND (DE-RUBOUT-CHAR #\RUBOUT) (STREAM &OPTIONAL (N 1)) (DE-DELETE-STRING STREAM (- (TYPEIN-POINTER) N) (TYPEIN-POINTER))) (DEF-DE-COMMAND (DE-CLEAR #\CLEAR) (STREAM &OPTIONAL IGNORE) (DE-DELETE-STRING STREAM 0 (FILL-POINTER))) (DEF-DE-COMMAND (DE-CLEAR-EOL #{{#/}}/K) (STREAM &OPTIONAL IGNORE) (DE-DELETE-STRING STREAM (TYPEIN-POINTER) (DE-SEARCH-FORWARD-NEWLINE (TYPEIN-POINTER)))) Word Commands (DEFUN DE-ALPHABETIC? (CHAR) (SETQ CHAR (CHAR-UPCASE CHAR)) (AND ({{#/}} CHAR #/A) ({{#/}} CHAR #/Z))) Returns the position of the first ( non ) alphabetic character (DEFUN DE-SEARCH-FORWARD-ALPHABETIC (POS) (DO ((FILL-POINTER (FILL-POINTER)) (I POS (1+ I))) ((= I FILL-POINTER) NIL) (IF (DE-ALPHABETIC? (AREF ES-BUFFER I)) (RETURN I)))) (DEFUN DE-SEARCH-FORWARD-NON-ALPHABETIC (POS) (DO ((FILL-POINTER (FILL-POINTER)) (I POS (1+ I))) ((= I FILL-POINTER) NIL) (IF (NOT (DE-ALPHABETIC? (AREF ES-BUFFER I))) (RETURN I)))) (DEFUN DE-SEARCH-BACKWARD-ALPHABETIC (POS) (DO ((I POS (1- I))) ((= I -1) NIL) (IF (DE-ALPHABETIC? (AREF ES-BUFFER I)) (RETURN I)))) (DEFUN DE-SEARCH-BACKWARD-NON-ALPHABETIC (POS) (DO ((I POS (1- I))) ((= I -1) NIL) (IF (NOT (DE-ALPHABETIC? (AREF ES-BUFFER I))) (RETURN I)))) If on an alphabetic character , skip to the first non alphabetic one . If on a non - alphabetic , skip over non - alphabetics and then over alphabetics , If no alphabetics follow the non - alphabetics , then do n't move at all . (DEFUN DE-SEARCH-FORWARD-WORD (N &AUX (POS (TYPEIN-POINTER)) SEARCH-POS) (DO ((I 0 (1+ I))) ((= I N) POS) (COND ((DE-ALPHABETIC? (AREF ES-BUFFER POS)) (SETQ POS (DE-SEARCH-FORWARD-NON-ALPHABETIC POS))) (T (SETQ SEARCH-POS (DE-SEARCH-FORWARD-ALPHABETIC POS)) (IF (NOT SEARCH-POS) (RETURN POS)) (SETQ POS (DE-SEARCH-FORWARD-NON-ALPHABETIC SEARCH-POS)))) (IF (NOT POS) (RETURN (FILL-POINTER))))) first non - alphabetic one . If on a non - alphabetic , skip over non - alphabetics and then over alphabetics . If no alphabetics after non - alphabetics , then do n't move at all . Treat cursor on first character of a word as a special case . (DEFUN DE-SEARCH-BACKWARD-WORD (N &AUX (POS (TYPEIN-POINTER)) SEARCH-POS) (DO ((I 0 (1+ I))) ((= I N) POS) (COND ((= POS 0) (RETURN 0)) ((AND (DE-ALPHABETIC? (AREF ES-BUFFER POS)) (DE-ALPHABETIC? (AREF ES-BUFFER (1- POS)))) (SETQ POS (DE-SEARCH-BACKWARD-NON-ALPHABETIC POS))) (T (SETQ SEARCH-POS (IF (DE-ALPHABETIC? (AREF ES-BUFFER POS)) (1- POS) POS)) (SETQ SEARCH-POS (DE-SEARCH-BACKWARD-ALPHABETIC SEARCH-POS)) (IF (NOT SEARCH-POS) (RETURN POS)) (SETQ POS (DE-SEARCH-BACKWARD-NON-ALPHABETIC SEARCH-POS)))) (IF (NOT POS) (RETURN 0)) Leave cursor on first character of the word (INCREMENT POS) )) (DEF-DE-COMMAND (DE-FORWARD-WORD #{{#/}}/F) (STREAM &OPTIONAL (N 1)) (DE-SET-POSITION STREAM (DE-SEARCH-FORWARD-WORD N))) (DEF-DE-COMMAND (DE-BACKWARD-WORD #{{#/}}/B) (STREAM &OPTIONAL (N 1)) (DE-SET-POSITION STREAM (DE-SEARCH-BACKWARD-WORD N))) (DEF-DE-COMMAND (DE-DELETE-WORD #{{#/}}/D) (STREAM &OPTIONAL (N 1)) (DE-DELETE-STRING STREAM (TYPEIN-POINTER) (DE-SEARCH-FORWARD-WORD N))) (DEF-DE-COMMAND (DE-RUBOUT-WORD #{{#/}}\RUBOUT) (STREAM &OPTIONAL (N 1)) (DE-DELETE-STRING STREAM (DE-SEARCH-BACKWARD-WORD N) (TYPEIN-POINTER))) (DEF-DE-COMMAND (DE-TWIDDLE-CHARS #{{#/}}/T) (STREAM &OPTIONAL IGNORE &AUX DELETE-POINTER STRING) (SETQ DELETE-POINTER (TYPEIN-POINTER)) (DECREMENT DELETE-POINTER (COND ((= DELETE-POINTER 0) 0) ((= DELETE-POINTER (FILL-POINTER)) 2) (T 1))) (SETQ STRING (SUBSTRING ES-BUFFER DELETE-POINTER (+ DELETE-POINTER 2))) (DE-DELETE-STRING STREAM DELETE-POINTER (+ DELETE-POINTER 2)) (SETQ STRING (STRING-NREVERSE STRING)) (DE-INSERT-STRING STREAM STRING 0 2 T)) Kill Ring Commands We pass in T for RUBBED - OUT - SOME since it is n't currently given (DEF-DE-COMMAND (DE-YANK #{{#/}}/Y) (STREAM &OPTIONAL (N 1) &AUX (YANKED (NTH N ES-KILL-RING))) (DE-INSERT-STRING STREAM YANKED 0 (MAX 0 (1- (STRING-LENGTH YANKED))) T)) (DEFUN DE-POP-KILL-RING () (SETF (FIRST ES-KILL-RING) (SECOND ES-KILL-RING)) (SETF (SECOND ES-KILL-RING) ES-BUFFER) (POP ES-KILL-RING)) If previous command was a Yank or a Yank - Pop , then remove what was placed there (DEF-DE-COMMAND (DE-YANK-POP #{{#/}}/Y) (STREAM &OPTIONAL IGNORE &AUX YANKED YANKED-LENGTH (TYPEIN-POINTER (TYPEIN-POINTER))) (PROG () First see if it was a Yank - Pop . (SETQ YANKED (CAR (CIRCULAR-LIST-LAST ES-KILL-RING))) (SETQ YANKED-LENGTH (1- (STRING-LENGTH YANKED))) (IF (AND ({{#/}} TYPEIN-POINTER YANKED-LENGTH) (STRING-EQUAL ES-BUFFER YANKED (- TYPEIN-POINTER YANKED-LENGTH) 0 TYPEIN-POINTER YANKED-LENGTH)) (RETURN)) (SETQ YANKED (SECOND ES-KILL-RING)) (SETQ YANKED-LENGTH (1- (STRING-LENGTH YANKED))) (COND ((AND ({{#/}} TYPEIN-POINTER YANKED-LENGTH) (STRING-EQUAL ES-BUFFER YANKED (- TYPEIN-POINTER YANKED-LENGTH) 0 TYPEIN-POINTER YANKED-LENGTH)) (DE-POP-KILL-RING) (RETURN))) (SETQ YANKED NIL)) (IF YANKED (DE-DELETE-STRING STREAM (- TYPEIN-POINTER YANKED-LENGTH) TYPEIN-POINTER)) (DE-YANK STREAM 1) (DE-POP-KILL-RING)) #+DEBUG (DEF-DE-COMMAND (DE-DEBUG #\HELP) (STREAM &OPTIONAL IGNORE) (FORMAT STREAM "~%[Fill pointer = ~D Typein pointer = ~D]~%" (FILL-POINTER) (TYPEIN-POINTER)) (DE-REPRINT-INPUT STREAM #\HELP)) (DEFUN PRINTING-EDITOR (STREAM &AUX CH PROMPT (OPTIONS TV-MAKE-STREAM-RUBOUT-HANDLER-OPTIONS) (RUBBED-OUT-SOME NIL) (DOING-RUBOUT NIL) (PASS-THROUGH (CDR (ASSQ ':PASS-THROUGH OPTIONS)))) (*CATCH 'RETURN-CHARACTER (DO () (NIL) (SETQ CH (FUNCALL ES-CONSOLE-STREAM ':TYI)) (COND ((MEMQ CH PASS-THROUGH) (PRINTING-EDITOR-INSERT-CHAR STREAM CH RUBBED-OUT-SOME DOING-RUBOUT)) Control - D and Control - U kill the current line , ITS and Twenex style . ((MEMQ CH '(#{{#/}}/d #{{#/}}/D #{{#/}}/u #{{#/}}/U)) (COND ((NOT (ZEROP (FILL-POINTER))) (SETF (FILL-POINTER) 0) (SETQ RUBBED-OUT-SOME T) (COND (DOING-RUBOUT (FUNCALL STREAM ':TYO #/]) (SETQ DOING-RUBOUT NIL))) (FUNCALL STREAM ':LINE-OUT " XXX") (SETQ PROMPT (OR (ASSQ ':REPROMPT OPTIONS) (ASSQ ':PROMPT OPTIONS))) (IF PROMPT (FUNCALL PROMPT STREAM CH)) (IF (ASSQ ':FULL-RUBOUT OPTIONS) (*THROW 'RUBOUT-HANDLER T))))) Control - K or Control - L echo themselves and then reprint the current ((MEMQ CH '(#\VT #\FORM #{{#/}}/k #{{#/}}/K #{{#/}}/l #{{#/}}/L)) (FUNCALL STREAM ':TYO CH) (FUNCALL STREAM ':FRESH-LINE) (SETQ PROMPT (OR (ASSQ ':REPROMPT OPTIONS) (ASSQ ':PROMPT OPTIONS))) (IF PROMPT (FUNCALL PROMPT STREAM CH)) (FUNCALL STREAM ':STRING-OUT ES-BUFFER)) Echo characters backwards Unix style . ((= CH #\RUBOUT) (MULTIPLE-VALUE (RUBBED-OUT-SOME DOING-RUBOUT) (PRINTING-EDITOR-RUBOUT-CHAR STREAM OPTIONS RUBBED-OUT-SOME DOING-RUBOUT))) Control - W flushes word . ((MEMQ CH '(#{{#/}}/w #{{#/}}/W)) (COND ((NOT (ZEROP (FILL-POINTER))) First flush whitespace . (DO () ((OR (ZEROP (FILL-POINTER)) (DE-ALPHABETIC? (AREF ES-BUFFER (1- (FILL-POINTER)))))) (MULTIPLE-VALUE (RUBBED-OUT-SOME DOING-RUBOUT) (PRINTING-EDITOR-RUBOUT-CHAR STREAM OPTIONS RUBBED-OUT-SOME DOING-RUBOUT))) Then flush alphabetics . (DO () ((OR (ZEROP (FILL-POINTER)) (NOT (DE-ALPHABETIC? (AREF ES-BUFFER (1- (FILL-POINTER))))))) (MULTIPLE-VALUE (RUBBED-OUT-SOME DOING-RUBOUT) (PRINTING-EDITOR-RUBOUT-CHAR STREAM OPTIONS RUBBED-OUT-SOME DOING-RUBOUT)))) (DOING-RUBOUT (FUNCALL STREAM ':LINE-OUT "]") (SETQ DOING-RUBOUT NIL)))) ((NOT (ZEROP (LDB %%KBD-CONTROL-META CH))) (FUNCALL STREAM ':BEEP)) (T (PRINTING-EDITOR-INSERT-CHAR STREAM CH RUBBED-OUT-SOME DOING-RUBOUT)))))) (DEFUN PRINTING-EDITOR-RUBOUT-CHAR (STREAM OPTIONS RUBBED-OUT-SOME DOING-RUBOUT &AUX CH) (COND ((NOT (ZEROP (FILL-POINTER))) (SETQ RUBBED-OUT-SOME T) (SETQ CH (ARRAY-POP ES-BUFFER)) If this is our first rubout , print " [ " and echo . (COND (DOING-RUBOUT (FUNCALL STREAM ':TYO CH)) ((= CH #\SPACE) (FUNCALL STREAM ':TYO #\BS)) (T (SETQ DOING-RUBOUT T) (FUNCALL STREAM ':TYO #/[) (FUNCALL STREAM ':TYO CH))) (IF (AND (ZEROP (FILL-POINTER)) (ASSQ ':FULL-RUBOUT OPTIONS)) (*THROW 'RUBOUT-HANDLER T)) (MVRETURN RUBBED-OUT-SOME DOING-RUBOUT)) (DOING-RUBOUT (FUNCALL STREAM ':LINE-OUT "]") (MVRETURN RUBBED-OUT-SOME NIL)))) (DEFUN PRINTING-EDITOR-INSERT-CHAR (STREAM CH RUBBED-OUT-SOME DOING-RUBOUT) (IF DOING-RUBOUT (FUNCALL STREAM ':TYO #/])) (FUNCALL STREAM ':TYO CH) (ARRAY-PUSH-EXTEND ES-BUFFER CH) (INCREMENT (SCAN-POINTER)) (IF RUBBED-OUT-SOME (*THROW 'RUBOUT-HANDLER T) (*THROW 'RETURN-CHARACTER CH))) #+DEBUG (PROGN 'COMPILE (DEFUN READ-10-CHARS (&OPTIONAL (STREAM STANDARD-INPUT) EOF-OPTION &AUX RESULT) (IF (AND (NOT RUBOUT-HANDLER) (MEMQ ':RUBOUT-HANDLER (FUNCALL STREAM ':WHICH-OPERATIONS))) If the : FULL - RUBOUT option is activated , this will return NIL . (DO () (NIL) (SETQ RESULT (FUNCALL STREAM ':RUBOUT-HANDLER '((:FULL-RUBOUT T) (:PROMPT ES-DEBUG-PROMPT) (:REPROMPT ES-DEBUG-REPROMPT)) #'READ-10-CHARS STREAM EOF-OPTION)) (IF RESULT (RETURN RESULT)) (ES-DEBUG-FULL-RUBOUT STREAM)) (LET ((CHARS (MAKE-ARRAY NIL ART-STRING 10.))) (DOTIMES (I 10.) (ASET (FUNCALL STREAM ':TYI EOF-OPTION) CHARS I)) CHARS))) [ 1 ] Let the receiving end ( console stream ) worry about it , press file style . [ 2 ] The editor stream can handle some cases . This would only work during [ 3 ] Let the toplevel program handle it . It most likely has the screen image compensate for them . I think having both [ 1 ] and [ 3 ] is the right thing . (DEFUN READ-10-CHARS-FLASH (&OPTIONAL (STREAM TERMINAL-IO) &AUX (W-O (FUNCALL STREAM ':WHICH-OPERATIONS)) CHARS X Y) (SETQ CHARS (READ-10-CHARS STREAM)) (COND ((MEMQ ':READ-CURSORPOS W-O) . Hopefully unnecessary in nws . (SETQ X (SYMEVAL-IN-CLOSURE STREAM 'ES-X-ORIGIN)) (SETQ Y (SYMEVAL-IN-CLOSURE STREAM 'ES-Y-ORIGIN)) (FUNCALL STREAM ':SET-CURSORPOS X Y) (COND ((MEMQ ':INSERT-CHAR W-O) (FUNCALL STREAM ':INSERT-CHAR #/[) (FUNCALL STREAM ':CURSOR-MOTION NIL NIL CHARS)) (T (FUNCALL STREAM ':TYO #/[) (FUNCALL STREAM ':STRING-OUT CHARS))) (FUNCALL STREAM ':TYO #/]))) (IF (MEMQ ':BEEP W-O) (FUNCALL STREAM ':BEEP)) (RETURN-ARRAY CHARS)) (DEFUN CHARACTER-SINK (&OPTIONAL (STOP-CHARS '(#{{#/}}/c #{{#/}}/C)) (STREAM STANDARD-INPUT)) (COND ((AND (NOT RUBOUT-HANDLER) (MEMQ ':RUBOUT-HANDLER (FUNCALL STREAM ':WHICH-OPERATIONS))) (FUNCALL STREAM ':RUBOUT-HANDLER `((:PASS-THROUGH . ,STOP-CHARS) (:PROMPT ES-DEBUG-PROMPT) (:REPROMPT ES-DEBUG-REPROMPT)) #'CHARACTER-SINK STOP-CHARS STREAM)) (T (DO () ((MEMQ (FUNCALL STREAM ':TYI) STOP-CHARS))) (DOTIMES (I 3) (FUNCALL STREAM ':BEEP))))) (DEFUN ES-DEBUG-PROMPT (STREAM IGNORE) (FORMAT STREAM "~&~11A" "Prompt:")) (DEFUN ES-DEBUG-REPROMPT (STREAM IGNORE) (FORMAT STREAM "~11A" "Reprompt:")) (DEFUN ES-DEBUG-FULL-RUBOUT (STREAM) (FORMAT STREAM "[Full Rubout]~%")) (DEFUN ES-DEBUG-DISPLAY (&AUX WINDOW STREAM) (SETQ WINDOW (<- SELECTED-WINDOW ':PANE)) (SETQ TERMINAL-IO (MAKE-EDITOR-STREAM (MAKE-TV-STREAM (<- WINDOW ':PC-PPR)) #'DISPLAY-EDITOR)) (<- WINDOW ':STREAM<- TERMINAL-IO)) (DEFUN ES-DEBUG-PRINTING (&AUX WINDOW) (SETQ WINDOW (<- SELECTED-WINDOW ':PANE)) (SETQ TERMINAL-IO (MAKE-EDITOR-STREAM (MAKE-TV-STREAM (<- WINDOW ':PC-PPR)) #'PRINTING-EDITOR)) (SET-IN-CLOSURE TERMINAL-IO 'ES-WHICH-OPERATIONS '(:TYI :TYI-NO-HANG :LISTEN :TYO :STRING-OUT :LINE-OUT :FRESH-LINE :BEEP :UNTYI :RUBOUT-HANDLER :CLEAR-INPUT :LISTEN)) (<- WINDOW ':STREAM<- TERMINAL-IO)) (DEFUN ES-DEBUG-FONT (&OPTIONAL (FONT "TR10B")) (SETQ FONT (STRING-UPCASE FONT)) Ca n't use LOAD - IF - NEEDED since CPTFONT comes from CPTFON > . (IF (NOT (SECOND (MULTIPLE-VALUE-LIST (INTERN FONT "Fonts")))) (LOAD (FORMAT NIL "AI:LMFONT;~A" FONT))) (SETQ FONT (SYMEVAL (INTERN FONT "Fonts"))) (TV-REDEFINE-PC-PPR (FUNCALL TERMINAL-IO ':PC-PPR) ':FONTS (LIST FONT))) (DEFUN ES-DEBUG-OFF (&AUX WINDOW) (SETQ WINDOW (<- SELECTED-WINDOW ':PANE)) (SETQ TERMINAL-IO (TV-MAKE-STREAM (<- WINDOW ':PC-PPR))) (<- WINDOW ':STREAM<- TERMINAL-IO)) (DEFUN DE-TV-MAKE-STREAM (PC-PPR) (MAKE-EDITOR-STREAM (MAKE-TV-STREAM PC-PPR) #'DISPLAY-EDITOR)) (DEFUN DE-GLOBAL-ENABLE () (FSET 'TV-MAKE-STREAM #'DE-TV-MAKE-STREAM) (SETQ TERMINAL-IO (DE-TV-MAKE-STREAM CONSOLE-IO-PC-PPR)) (<- TOP-WINDOW ':STREAM<- TERMINAL-IO)) #-DEBUG (DE-GLOBAL-ENABLE) To do : Modify kill ring representation to not include current buffer . Write a printing editor ( regular editor plus ? ? command ) {{#/}}{{#/}}
6182ac5f4a7d8cb9a8b8b29fd018426d248d026150046dc411334f2efc6a8ee0
Oblosys/proxima
Ag.hs
module Main where import System (getArgs, getProgName, exitFailure) import System.Console.GetOpt (usageInfo) import List (isSuffixOf) import Monad (zipWithM_) import Data.Maybe import qualified Data.Set as Set import qualified Data.Map as Map import qualified Data.Sequence as Seq ((><)) import Data.Foldable(toList) import Pretty import UU.Parsing (Message(..), Action(..)) import UU.Scanner.Position (Pos, line, file) import UU.Scanner.Token (Token) import qualified Transform as Pass1 (sem_AG , wrap_AG , Syn_AG (..), Inh_AG (..)) import qualified Desugar as Pass1a (sem_Grammar, wrap_Grammar, Syn_Grammar (..), Inh_Grammar (..)) import qualified DefaultRules as Pass2 (sem_Grammar, wrap_Grammar, Syn_Grammar (..), Inh_Grammar (..)) import qualified Order as Pass3 (sem_Grammar, wrap_Grammar, Syn_Grammar (..), Inh_Grammar (..)) import qualified GenerateCode as Pass4 (sem_CGrammar, wrap_CGrammar, Syn_CGrammar(..), Inh_CGrammar(..)) import qualified PrintCode as Pass5 (sem_Program, wrap_Program, Syn_Program (..), Inh_Program (..)) import qualified PrintErrorMessages as PrErr (sem_Errors , wrap_Errors , Syn_Errors (..), Inh_Errors (..), isError) import qualified TfmToVisage as PassV (sem_Grammar, wrap_Grammar, Syn_Grammar (..), Inh_Grammar (..)) import qualified AbstractSyntaxDump as GrammarDump (sem_Grammar, wrap_Grammar, Syn_Grammar (..), Inh_Grammar (..)) import qualified CodeSyntaxDump as CGrammarDump (sem_CGrammar, wrap_CGrammar, Syn_CGrammar (..), Inh_CGrammar (..)) import qualified Visage as VisageDump (sem_VisageGrammar, wrap_VisageGrammar, Syn_VisageGrammar(..), Inh_VisageGrammar(..)) import Options import Version (banner) import Parser (parseAG, depsAG) import ErrorMessages (Error(ParserError), Errors) import CommonTypes import ATermWrite main :: IO () main = do args <- getArgs progName <- getProgName let usageheader = "Usage info:\n " ++ progName ++ " options file ...\n\nList of options:" (flags,files,errs) = getOptions args if showVersion flags then putStrLn banner else if null files || showHelp flags || (not.null) errs then mapM_ putStrLn (usageInfo usageheader options : errs) else if genFileDeps flags then reportDeps flags files else zipWithM_ (compile flags) files (outputFiles flags++repeat "") compile :: Options -> String -> String -> IO () compile flags input output = do (output0,parseErrors) <- parseAG flags (searchPath flags) (inputFile input) irrefutableMap <- readIrrefutableMap flags let output1 = Pass1.wrap_AG (Pass1.sem_AG output0 ) Pass1.Inh_AG {Pass1.options_Inh_AG = flags} flags' = Pass1.pragmas_Syn_AG output1 $ flags grammar1 = Pass1.output_Syn_AG output1 output1a = Pass1a.wrap_Grammar (Pass1a.sem_Grammar grammar1 ) Pass1a.Inh_Grammar {Pass1a.options_Inh_Grammar = flags', Pass1a.forcedIrrefutables_Inh_Grammar = irrefutableMap } grammar1a =Pass1a.output_Syn_Grammar output1a output2 = Pass2.wrap_Grammar (Pass2.sem_Grammar grammar1a ) Pass2.Inh_Grammar {Pass2.options_Inh_Grammar = flags'} grammar2 = Pass2.output_Syn_Grammar output2 outputV = PassV.wrap_Grammar (PassV.sem_Grammar grammar2 ) PassV.Inh_Grammar {} grammarV = PassV.visage_Syn_Grammar outputV output3 = Pass3.wrap_Grammar (Pass3.sem_Grammar grammar2 ) Pass3.Inh_Grammar {Pass3.options_Inh_Grammar = flags'} grammar3 = Pass3.output_Syn_Grammar output3 output4 = Pass4.wrap_CGrammar (Pass4.sem_CGrammar(Pass3.output_Syn_Grammar output3)) Pass4.Inh_CGrammar {Pass4.options_Inh_CGrammar = flags'} output5 = Pass5.wrap_Program (Pass5.sem_Program (Pass4.output_Syn_CGrammar output4)) Pass5.Inh_Program {Pass5.options_Inh_Program = flags', Pass5.pragmaBlocks_Inh_Program = pragmaBlocksTxt, Pass5.importBlocks_Inh_Program = importBlocksTxt, Pass5.textBlocks_Inh_Program = textBlocksDoc, Pass5.textBlockMap_Inh_Program = textBlockMap, Pass5.optionsLine_Inh_Program = optionsLine, Pass5.mainFile_Inh_Program = mainFile, Pass5.moduleHeader_Inh_Program = mkModuleHeader $ Pass1.moduleDecl_Syn_AG output1, Pass5.mainName_Inh_Program = mkMainName mainName $ Pass1.moduleDecl_Syn_AG output1} output6 = PrErr.wrap_Errors (PrErr.sem_Errors errorsToReport) PrErr.Inh_Errors {PrErr.options_Inh_Errors = flags'} dump1 = GrammarDump.wrap_Grammar (GrammarDump.sem_Grammar grammar1 ) GrammarDump.Inh_Grammar dump2 = GrammarDump.wrap_Grammar (GrammarDump.sem_Grammar grammar2 ) GrammarDump.Inh_Grammar dump3 = CGrammarDump.wrap_CGrammar (CGrammarDump.sem_CGrammar grammar3 ) CGrammarDump.Inh_CGrammar outputVisage = VisageDump.wrap_VisageGrammar (VisageDump.sem_VisageGrammar grammarV) VisageDump.Inh_VisageGrammar aterm = VisageDump.aterm_Syn_VisageGrammar outputVisage parseErrorList = map message2error parseErrors errorList = parseErrorList ++ toList ( Pass1.errors_Syn_AG output1 Seq.>< Pass1a.errors_Syn_Grammar output1a Seq.>< Pass2.errors_Syn_Grammar output2 Seq.>< Pass3.errors_Syn_Grammar output3 Seq.>< Pass4.errors_Syn_CGrammar output4 ) fatalErrorList = filter (PrErr.isError flags') errorList allErrors = if null parseErrors then if wignore flags' then fatalErrorList else errorsToFront flags' errorList else take 1 parseErrorList -- the other 1000 or so parse errors are usually not that informative errorsToReport = take (wmaxerrs flags') allErrors errorsToStopOn = if werrors flags' then errorList else fatalErrorList SM ` Map.unionWith ( + + ) ` ( Pass3.blocks_Syn_Grammar output3 ) (pragmaBlocks, blocks2) = Map.partitionWithKey (\(k, at) _->k==BlockPragma && at == Nothing) blocks1 (importBlocks, textBlocks) = Map.partitionWithKey (\(k, at) _->k==BlockImport && at == Nothing) blocks2 importBlocksTxt = vlist_sep "" . map addLocationPragma . concat . Map.elems $ importBlocks textBlocksDoc = vlist_sep "" . map addLocationPragma . Map.findWithDefault [] (BlockOther, Nothing) $ textBlocks pragmaBlocksTxt = unlines . concat . map fst . concat . Map.elems $ pragmaBlocks textBlockMap = Map.map (vlist_sep "" . map addLocationPragma) . Map.filterWithKey (\(_, at) _ -> at /= Nothing) $ textBlocks outputfile = if null output then outputFile input else output addLocationPragma :: ([String], Pos) -> PP_Doc addLocationPragma (strs, p) | genLinePragmas flags' = "{-# LINE" >#< pp (show (line p)) >#< show (file p) >#< "#-}" >-< vlist (map pp strs) >-< "{-# LINE" >#< ppWithLineNr (pp.show.(+1)) >#< show outputfile >#< "#-}" | otherwise = vlist (map pp strs) optionsGHC = option (unbox flags') "-fglasgow-exts" ++ option (bangpats flags') "-fbang-patterns" option True s = [s] option False _ = [] optionsLine | null optionsGHC = "" | otherwise = "{-# OPTIONS_GHC " ++ unwords optionsGHC ++ " #-}" mainName = stripPath $ defaultModuleName input mainFile = defaultModuleName input nrOfErrorsToReport = length $ filter (PrErr.isError flags') errorsToReport nrOfWarningsToReport = length $ filter (not.(PrErr.isError flags')) errorsToReport totalNrOfErrors = length $ filter (PrErr.isError flags') allErrors totalNrOfWarnings = length $ filter (not.(PrErr.isError flags')) allErrors additionalErrors = totalNrOfErrors - nrOfErrorsToReport additionalWarnings = totalNrOfWarnings - nrOfWarningsToReport pluralS n = if n == 1 then "" else "s" putStr . formatErrors $ PrErr.pp_Syn_Errors output6 if additionalErrors > 0 then putStr $ "\nPlus " ++ show additionalErrors ++ " more error" ++ pluralS additionalErrors ++ if additionalWarnings > 0 then " and " ++ show additionalWarnings ++ " more warning" ++ pluralS additionalWarnings ++ ".\n" else ".\n" else if additionalWarnings > 0 then putStr $ "\nPlus " ++ show additionalWarnings ++ " more warning" ++ pluralS additionalWarnings ++ ".\n" else return () if not (null fatalErrorList) then exitFailure else do if genvisage flags' then writeFile (outputfile++".visage") (writeATerm aterm) else return () if genAttributeList flags' then writeAttributeList (outputfile++".attrs") (Pass1a.allAttributes_Syn_Grammar output1a) else return () if sepSemMods flags' then do -- alternative module gen Pass5.genIO_Syn_Program output5 if not (null errorsToStopOn) then exitFailure else return () else do -- conventional module gen let doc = vlist [ pp optionsLine , pp pragmaBlocksTxt , pp $ take 70 ("-- UUAGC " ++ drop 50 banner ++ " (" ++ input) ++ ")" , pp $ if isNothing $ Pass1.moduleDecl_Syn_AG output1 then moduleHeader flags' mainName else mkModuleHeader (Pass1.moduleDecl_Syn_AG output1) mainName "" "" False , pp importBlocksTxt , textBlocksDoc , vlist $ Pass5.output_Syn_Program output5 , if dumpgrammar flags' then vlist [ pp "{- Dump of grammar without default rules" , GrammarDump.pp_Syn_Grammar dump1 , pp "-}" , pp "{- Dump of grammar with default rules" , GrammarDump.pp_Syn_Grammar dump2 , pp "-}" ] else empty , if dumpcgrammar flags' then vlist [ pp "{- Dump of cgrammar" , CGrammarDump.pp_Syn_CGrammar dump3 , pp "-}" ] else empty ] let docTxt = disp doc 50000 "" writeFile outputfile docTxt if not (null errorsToStopOn) then exitFailure else return () formatErrors :: PP_Doc -> String formatErrors pp = disp pp 5000 "" message2error :: Message Token Pos -> Error message2error (Msg expect pos action) = ParserError pos (show expect) actionString where actionString = case action of Insert s -> "inserting: " ++ show s Delete s -> "deleting: " ++ show s Other ms -> ms errorsToFront :: Options -> [Error] -> [Error] errorsToFront flags mesgs = filter (PrErr.isError flags) mesgs ++ filter (not.(PrErr.isError flags)) mesgs moduleHeader :: Options -> String -> String moduleHeader flags input = case moduleName flags of Name nm -> genMod nm Default -> genMod (defaultModuleName input) NoName -> "" where genMod x = "module " ++ x ++ " where" inputFile :: String -> String inputFile name = if ".ag" `isSuffixOf` name || ".lag" `isSuffixOf` name then name else name ++ ".ag" outputFile :: String -> String outputFile name = defaultModuleName name ++ ".hs" defaultModuleName :: String -> String defaultModuleName name = if ".ag" `isSuffixOf` name then take (length name - 3) name else if ".lag" `isSuffixOf` name then take (length name - 4) name else name stripPath :: String -> String stripPath = reverse . takeWhile (\c -> c /= '/' && c /= '\\') . reverse mkMainName :: String -> Maybe (String, String,String) -> String mkMainName defaultName Nothing = defaultName mkMainName _ (Just (name, _, _)) = name mkModuleHeader :: Maybe (String,String,String) -> String -> String -> String -> Bool -> String mkModuleHeader Nothing defaultName _ _ _ = "module " ++ defaultName ++ " where" mkModuleHeader (Just (name, exports, imports)) _ suffix addExports replaceExports = "module " ++ name ++ suffix ++ exp ++ " where\n" ++ imports ++ "\n" where exp = if null exports || (replaceExports && null addExports) then "" else if null addExports then "(" ++ exports ++ ")" else if replaceExports then "(" ++ addExports ++ ")" else "(" ++ exports ++ "," ++ addExports ++ ")" reportDeps :: Options -> [String] -> IO () reportDeps flags files = do results <- mapM (depsAG flags (searchPath flags)) files let (fs, mesgs) = foldr combine ([],[]) results let errs = take (wmaxerrs flags) (map message2error mesgs) let ppErrs = PrErr.wrap_Errors (PrErr.sem_Errors errs) PrErr.Inh_Errors {PrErr.options_Inh_Errors = flags} if null errs then mapM_ putStrLn fs else do putStr . formatErrors $ PrErr.pp_Syn_Errors ppErrs exitFailure where combine :: ([a],[b]) -> ([a], [b]) -> ([a], [b]) combine (fs, mesgs) (fsr, mesgsr) = (fs ++ fsr, mesgs ++ mesgsr) writeAttributeList :: String -> AttrMap -> IO () writeAttributeList file mp = writeFile file s where s = show $ map (\(x,y) -> (show x, y)) $ Map.toList $ Map.map (map (\(x,y) -> (show x, y)) . Map.toList . Map.map (map (\(x,y) -> (show x, show y)) . Set.toList)) $ mp readIrrefutableMap :: Options -> IO AttrMap readIrrefutableMap flags = case forceIrrefutables flags of Just file -> do s <- readFile file seq (length s) (return ()) let lists :: [(String,[(String,[(String, String)])])] lists = read s return $ Map.fromList [ (identifier n, Map.fromList [(identifier c, Set.fromList [ (identifier fld, identifier attr) | (fld,attr) <- ss ]) | (c,ss) <- cs ]) | (n,cs) <- lists ] Nothing -> return Map.empty
null
https://raw.githubusercontent.com/Oblosys/proxima/f154dff2ccb8afe00eeb325d9d06f5e2a5ee7589/uuagc/src/Ag.hs
haskell
the other 1000 or so parse errors are usually not that informative alternative module gen conventional module gen
module Main where import System (getArgs, getProgName, exitFailure) import System.Console.GetOpt (usageInfo) import List (isSuffixOf) import Monad (zipWithM_) import Data.Maybe import qualified Data.Set as Set import qualified Data.Map as Map import qualified Data.Sequence as Seq ((><)) import Data.Foldable(toList) import Pretty import UU.Parsing (Message(..), Action(..)) import UU.Scanner.Position (Pos, line, file) import UU.Scanner.Token (Token) import qualified Transform as Pass1 (sem_AG , wrap_AG , Syn_AG (..), Inh_AG (..)) import qualified Desugar as Pass1a (sem_Grammar, wrap_Grammar, Syn_Grammar (..), Inh_Grammar (..)) import qualified DefaultRules as Pass2 (sem_Grammar, wrap_Grammar, Syn_Grammar (..), Inh_Grammar (..)) import qualified Order as Pass3 (sem_Grammar, wrap_Grammar, Syn_Grammar (..), Inh_Grammar (..)) import qualified GenerateCode as Pass4 (sem_CGrammar, wrap_CGrammar, Syn_CGrammar(..), Inh_CGrammar(..)) import qualified PrintCode as Pass5 (sem_Program, wrap_Program, Syn_Program (..), Inh_Program (..)) import qualified PrintErrorMessages as PrErr (sem_Errors , wrap_Errors , Syn_Errors (..), Inh_Errors (..), isError) import qualified TfmToVisage as PassV (sem_Grammar, wrap_Grammar, Syn_Grammar (..), Inh_Grammar (..)) import qualified AbstractSyntaxDump as GrammarDump (sem_Grammar, wrap_Grammar, Syn_Grammar (..), Inh_Grammar (..)) import qualified CodeSyntaxDump as CGrammarDump (sem_CGrammar, wrap_CGrammar, Syn_CGrammar (..), Inh_CGrammar (..)) import qualified Visage as VisageDump (sem_VisageGrammar, wrap_VisageGrammar, Syn_VisageGrammar(..), Inh_VisageGrammar(..)) import Options import Version (banner) import Parser (parseAG, depsAG) import ErrorMessages (Error(ParserError), Errors) import CommonTypes import ATermWrite main :: IO () main = do args <- getArgs progName <- getProgName let usageheader = "Usage info:\n " ++ progName ++ " options file ...\n\nList of options:" (flags,files,errs) = getOptions args if showVersion flags then putStrLn banner else if null files || showHelp flags || (not.null) errs then mapM_ putStrLn (usageInfo usageheader options : errs) else if genFileDeps flags then reportDeps flags files else zipWithM_ (compile flags) files (outputFiles flags++repeat "") compile :: Options -> String -> String -> IO () compile flags input output = do (output0,parseErrors) <- parseAG flags (searchPath flags) (inputFile input) irrefutableMap <- readIrrefutableMap flags let output1 = Pass1.wrap_AG (Pass1.sem_AG output0 ) Pass1.Inh_AG {Pass1.options_Inh_AG = flags} flags' = Pass1.pragmas_Syn_AG output1 $ flags grammar1 = Pass1.output_Syn_AG output1 output1a = Pass1a.wrap_Grammar (Pass1a.sem_Grammar grammar1 ) Pass1a.Inh_Grammar {Pass1a.options_Inh_Grammar = flags', Pass1a.forcedIrrefutables_Inh_Grammar = irrefutableMap } grammar1a =Pass1a.output_Syn_Grammar output1a output2 = Pass2.wrap_Grammar (Pass2.sem_Grammar grammar1a ) Pass2.Inh_Grammar {Pass2.options_Inh_Grammar = flags'} grammar2 = Pass2.output_Syn_Grammar output2 outputV = PassV.wrap_Grammar (PassV.sem_Grammar grammar2 ) PassV.Inh_Grammar {} grammarV = PassV.visage_Syn_Grammar outputV output3 = Pass3.wrap_Grammar (Pass3.sem_Grammar grammar2 ) Pass3.Inh_Grammar {Pass3.options_Inh_Grammar = flags'} grammar3 = Pass3.output_Syn_Grammar output3 output4 = Pass4.wrap_CGrammar (Pass4.sem_CGrammar(Pass3.output_Syn_Grammar output3)) Pass4.Inh_CGrammar {Pass4.options_Inh_CGrammar = flags'} output5 = Pass5.wrap_Program (Pass5.sem_Program (Pass4.output_Syn_CGrammar output4)) Pass5.Inh_Program {Pass5.options_Inh_Program = flags', Pass5.pragmaBlocks_Inh_Program = pragmaBlocksTxt, Pass5.importBlocks_Inh_Program = importBlocksTxt, Pass5.textBlocks_Inh_Program = textBlocksDoc, Pass5.textBlockMap_Inh_Program = textBlockMap, Pass5.optionsLine_Inh_Program = optionsLine, Pass5.mainFile_Inh_Program = mainFile, Pass5.moduleHeader_Inh_Program = mkModuleHeader $ Pass1.moduleDecl_Syn_AG output1, Pass5.mainName_Inh_Program = mkMainName mainName $ Pass1.moduleDecl_Syn_AG output1} output6 = PrErr.wrap_Errors (PrErr.sem_Errors errorsToReport) PrErr.Inh_Errors {PrErr.options_Inh_Errors = flags'} dump1 = GrammarDump.wrap_Grammar (GrammarDump.sem_Grammar grammar1 ) GrammarDump.Inh_Grammar dump2 = GrammarDump.wrap_Grammar (GrammarDump.sem_Grammar grammar2 ) GrammarDump.Inh_Grammar dump3 = CGrammarDump.wrap_CGrammar (CGrammarDump.sem_CGrammar grammar3 ) CGrammarDump.Inh_CGrammar outputVisage = VisageDump.wrap_VisageGrammar (VisageDump.sem_VisageGrammar grammarV) VisageDump.Inh_VisageGrammar aterm = VisageDump.aterm_Syn_VisageGrammar outputVisage parseErrorList = map message2error parseErrors errorList = parseErrorList ++ toList ( Pass1.errors_Syn_AG output1 Seq.>< Pass1a.errors_Syn_Grammar output1a Seq.>< Pass2.errors_Syn_Grammar output2 Seq.>< Pass3.errors_Syn_Grammar output3 Seq.>< Pass4.errors_Syn_CGrammar output4 ) fatalErrorList = filter (PrErr.isError flags') errorList allErrors = if null parseErrors then if wignore flags' then fatalErrorList else errorsToFront flags' errorList else take 1 parseErrorList errorsToReport = take (wmaxerrs flags') allErrors errorsToStopOn = if werrors flags' then errorList else fatalErrorList SM ` Map.unionWith ( + + ) ` ( Pass3.blocks_Syn_Grammar output3 ) (pragmaBlocks, blocks2) = Map.partitionWithKey (\(k, at) _->k==BlockPragma && at == Nothing) blocks1 (importBlocks, textBlocks) = Map.partitionWithKey (\(k, at) _->k==BlockImport && at == Nothing) blocks2 importBlocksTxt = vlist_sep "" . map addLocationPragma . concat . Map.elems $ importBlocks textBlocksDoc = vlist_sep "" . map addLocationPragma . Map.findWithDefault [] (BlockOther, Nothing) $ textBlocks pragmaBlocksTxt = unlines . concat . map fst . concat . Map.elems $ pragmaBlocks textBlockMap = Map.map (vlist_sep "" . map addLocationPragma) . Map.filterWithKey (\(_, at) _ -> at /= Nothing) $ textBlocks outputfile = if null output then outputFile input else output addLocationPragma :: ([String], Pos) -> PP_Doc addLocationPragma (strs, p) | genLinePragmas flags' = "{-# LINE" >#< pp (show (line p)) >#< show (file p) >#< "#-}" >-< vlist (map pp strs) >-< "{-# LINE" >#< ppWithLineNr (pp.show.(+1)) >#< show outputfile >#< "#-}" | otherwise = vlist (map pp strs) optionsGHC = option (unbox flags') "-fglasgow-exts" ++ option (bangpats flags') "-fbang-patterns" option True s = [s] option False _ = [] optionsLine | null optionsGHC = "" | otherwise = "{-# OPTIONS_GHC " ++ unwords optionsGHC ++ " #-}" mainName = stripPath $ defaultModuleName input mainFile = defaultModuleName input nrOfErrorsToReport = length $ filter (PrErr.isError flags') errorsToReport nrOfWarningsToReport = length $ filter (not.(PrErr.isError flags')) errorsToReport totalNrOfErrors = length $ filter (PrErr.isError flags') allErrors totalNrOfWarnings = length $ filter (not.(PrErr.isError flags')) allErrors additionalErrors = totalNrOfErrors - nrOfErrorsToReport additionalWarnings = totalNrOfWarnings - nrOfWarningsToReport pluralS n = if n == 1 then "" else "s" putStr . formatErrors $ PrErr.pp_Syn_Errors output6 if additionalErrors > 0 then putStr $ "\nPlus " ++ show additionalErrors ++ " more error" ++ pluralS additionalErrors ++ if additionalWarnings > 0 then " and " ++ show additionalWarnings ++ " more warning" ++ pluralS additionalWarnings ++ ".\n" else ".\n" else if additionalWarnings > 0 then putStr $ "\nPlus " ++ show additionalWarnings ++ " more warning" ++ pluralS additionalWarnings ++ ".\n" else return () if not (null fatalErrorList) then exitFailure else do if genvisage flags' then writeFile (outputfile++".visage") (writeATerm aterm) else return () if genAttributeList flags' then writeAttributeList (outputfile++".attrs") (Pass1a.allAttributes_Syn_Grammar output1a) else return () if sepSemMods flags' Pass5.genIO_Syn_Program output5 if not (null errorsToStopOn) then exitFailure else return () let doc = vlist [ pp optionsLine , pp pragmaBlocksTxt , pp $ take 70 ("-- UUAGC " ++ drop 50 banner ++ " (" ++ input) ++ ")" , pp $ if isNothing $ Pass1.moduleDecl_Syn_AG output1 then moduleHeader flags' mainName else mkModuleHeader (Pass1.moduleDecl_Syn_AG output1) mainName "" "" False , pp importBlocksTxt , textBlocksDoc , vlist $ Pass5.output_Syn_Program output5 , if dumpgrammar flags' then vlist [ pp "{- Dump of grammar without default rules" , GrammarDump.pp_Syn_Grammar dump1 , pp "-}" , pp "{- Dump of grammar with default rules" , GrammarDump.pp_Syn_Grammar dump2 , pp "-}" ] else empty , if dumpcgrammar flags' then vlist [ pp "{- Dump of cgrammar" , CGrammarDump.pp_Syn_CGrammar dump3 , pp "-}" ] else empty ] let docTxt = disp doc 50000 "" writeFile outputfile docTxt if not (null errorsToStopOn) then exitFailure else return () formatErrors :: PP_Doc -> String formatErrors pp = disp pp 5000 "" message2error :: Message Token Pos -> Error message2error (Msg expect pos action) = ParserError pos (show expect) actionString where actionString = case action of Insert s -> "inserting: " ++ show s Delete s -> "deleting: " ++ show s Other ms -> ms errorsToFront :: Options -> [Error] -> [Error] errorsToFront flags mesgs = filter (PrErr.isError flags) mesgs ++ filter (not.(PrErr.isError flags)) mesgs moduleHeader :: Options -> String -> String moduleHeader flags input = case moduleName flags of Name nm -> genMod nm Default -> genMod (defaultModuleName input) NoName -> "" where genMod x = "module " ++ x ++ " where" inputFile :: String -> String inputFile name = if ".ag" `isSuffixOf` name || ".lag" `isSuffixOf` name then name else name ++ ".ag" outputFile :: String -> String outputFile name = defaultModuleName name ++ ".hs" defaultModuleName :: String -> String defaultModuleName name = if ".ag" `isSuffixOf` name then take (length name - 3) name else if ".lag" `isSuffixOf` name then take (length name - 4) name else name stripPath :: String -> String stripPath = reverse . takeWhile (\c -> c /= '/' && c /= '\\') . reverse mkMainName :: String -> Maybe (String, String,String) -> String mkMainName defaultName Nothing = defaultName mkMainName _ (Just (name, _, _)) = name mkModuleHeader :: Maybe (String,String,String) -> String -> String -> String -> Bool -> String mkModuleHeader Nothing defaultName _ _ _ = "module " ++ defaultName ++ " where" mkModuleHeader (Just (name, exports, imports)) _ suffix addExports replaceExports = "module " ++ name ++ suffix ++ exp ++ " where\n" ++ imports ++ "\n" where exp = if null exports || (replaceExports && null addExports) then "" else if null addExports then "(" ++ exports ++ ")" else if replaceExports then "(" ++ addExports ++ ")" else "(" ++ exports ++ "," ++ addExports ++ ")" reportDeps :: Options -> [String] -> IO () reportDeps flags files = do results <- mapM (depsAG flags (searchPath flags)) files let (fs, mesgs) = foldr combine ([],[]) results let errs = take (wmaxerrs flags) (map message2error mesgs) let ppErrs = PrErr.wrap_Errors (PrErr.sem_Errors errs) PrErr.Inh_Errors {PrErr.options_Inh_Errors = flags} if null errs then mapM_ putStrLn fs else do putStr . formatErrors $ PrErr.pp_Syn_Errors ppErrs exitFailure where combine :: ([a],[b]) -> ([a], [b]) -> ([a], [b]) combine (fs, mesgs) (fsr, mesgsr) = (fs ++ fsr, mesgs ++ mesgsr) writeAttributeList :: String -> AttrMap -> IO () writeAttributeList file mp = writeFile file s where s = show $ map (\(x,y) -> (show x, y)) $ Map.toList $ Map.map (map (\(x,y) -> (show x, y)) . Map.toList . Map.map (map (\(x,y) -> (show x, show y)) . Set.toList)) $ mp readIrrefutableMap :: Options -> IO AttrMap readIrrefutableMap flags = case forceIrrefutables flags of Just file -> do s <- readFile file seq (length s) (return ()) let lists :: [(String,[(String,[(String, String)])])] lists = read s return $ Map.fromList [ (identifier n, Map.fromList [(identifier c, Set.fromList [ (identifier fld, identifier attr) | (fld,attr) <- ss ]) | (c,ss) <- cs ]) | (n,cs) <- lists ] Nothing -> return Map.empty
689cbbb9e017dfda0865d5bf752a1242ac8c16868aca6e2d7f40973110061986
ghcjs/ghcjs-dom
GlobalCrypto.hs
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} module GHCJS.DOM.JSFFI.Generated.GlobalCrypto (js_getCrypto, getCrypto, GlobalCrypto(..), gTypeGlobalCrypto, IsGlobalCrypto, toGlobalCrypto) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import qualified Prelude (error) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull, jsUndefined) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import Data.Maybe (fromJust) import Data.Traversable (mapM) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"crypto\"]" js_getCrypto :: GlobalCrypto -> IO Crypto | < -US/docs/Web/API/GlobalCrypto.crypto Mozilla GlobalCrypto.crypto documentation > getCrypto :: (MonadIO m, IsGlobalCrypto self) => self -> m Crypto getCrypto self = liftIO (js_getCrypto (toGlobalCrypto self))
null
https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/GlobalCrypto.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # module GHCJS.DOM.JSFFI.Generated.GlobalCrypto (js_getCrypto, getCrypto, GlobalCrypto(..), gTypeGlobalCrypto, IsGlobalCrypto, toGlobalCrypto) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import qualified Prelude (error) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull, jsUndefined) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import Data.Maybe (fromJust) import Data.Traversable (mapM) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"crypto\"]" js_getCrypto :: GlobalCrypto -> IO Crypto | < -US/docs/Web/API/GlobalCrypto.crypto Mozilla GlobalCrypto.crypto documentation > getCrypto :: (MonadIO m, IsGlobalCrypto self) => self -> m Crypto getCrypto self = liftIO (js_getCrypto (toGlobalCrypto self))
0394c35d0ab4bac9630744048172189252471e15e26176885186e09eca87a98d
CryptoKami/cryptokami-core
Instances.hs
# LANGUAGE TypeOperators # -- | Miscellaneous instances, etc. Related to the main blockchain of course. module Pos.Core.Block.Main.Instances ( ) where import Universum import qualified Data.Text.Buildable as Buildable import Formatting (bprint, build, int, stext, (%)) import Serokell.Util (Color (Magenta), colorize, listJson) import Pos.Binary.Class (Bi) import Pos.Binary.Core.Block () import Pos.Core.Block.Blockchain (GenericBlock (..), GenericBlockHeader (..)) import Pos.Core.Block.Main.Chain (Body (..), ConsensusData (..)) import Pos.Core.Block.Main.Lens (mainBlockBlockVersion, mainBlockDifficulty, mainBlockSlot, mainBlockSoftwareVersion, mainHeaderBlockVersion, mainHeaderDifficulty, mainHeaderLeaderKey, mainHeaderSlot, mainHeaderSoftwareVersion, mbTxs, mcdDifficulty, mehBlockVersion, mehSoftwareVersion) import Pos.Core.Block.Main.Types (MainBlock, MainBlockHeader, MainBlockchain, MainExtraHeaderData (..)) import Pos.Core.Block.Union.Types (BlockHeader, blockHeaderHash) import Pos.Core.Class (HasBlockVersion (..), HasDifficulty (..), HasEpochIndex (..), HasEpochOrSlot (..), HasHeaderHash (..), HasSoftwareVersion (..), IsHeader, IsMainHeader (..)) import Pos.Core.Common (HeaderHash) import Pos.Core.Configuration (HasConfiguration) import Pos.Core.Slotting.Types (EpochOrSlot (..), slotIdF) import Pos.Crypto (hashHexF) instance Bi BlockHeader => Buildable MainBlockHeader where build gbh@UnsafeGenericBlockHeader {..} = bprint ("MainBlockHeader:\n"% " hash: "%hashHexF%"\n"% " previous block: "%hashHexF%"\n"% " slot: "%slotIdF%"\n"% " difficulty: "%int%"\n"% " leader: "%build%"\n"% " signature: "%build%"\n"% build ) gbhHeaderHash _gbhPrevBlock _mcdSlot _mcdDifficulty _mcdLeaderKey _mcdSignature _gbhExtra where gbhHeaderHash :: HeaderHash gbhHeaderHash = blockHeaderHash $ Right gbh MainConsensusData {..} = _gbhConsensus instance (HasConfiguration, Bi BlockHeader) => Buildable MainBlock where build UnsafeGenericBlock {..} = bprint (stext%":\n"% " "%build% " transactions ("%int%" items): "%listJson%"\n"% " "%build%"\n"% " "%build%"\n"% " update payload: "%build%"\n"% " "%build ) (colorize Magenta "MainBlock") _gbHeader (length txs) txs _mbDlgPayload _mbSscPayload _mbUpdatePayload _gbExtra where MainBody {..} = _gbBody txs = _gbBody ^. mbTxs instance HasEpochIndex MainBlock where epochIndexL = mainBlockSlot . epochIndexL instance HasEpochIndex MainBlockHeader where epochIndexL = mainHeaderSlot . epochIndexL instance HasEpochOrSlot MainBlockHeader where getEpochOrSlot = EpochOrSlot . Right . view mainHeaderSlot instance HasEpochOrSlot MainBlock where getEpochOrSlot = getEpochOrSlot . _gbHeader NB . it 's not a mistake that these instances require @Bi BlockHeader@ -- instead of @Bi MainBlockHeader@. We compute header's hash by converting it to a BlockHeader first . instance Bi BlockHeader => HasHeaderHash MainBlockHeader where headerHash = blockHeaderHash . Right instance Bi BlockHeader => HasHeaderHash MainBlock where headerHash = blockHeaderHash . Right . _gbHeader instance HasDifficulty (ConsensusData MainBlockchain) where difficultyL = mcdDifficulty instance HasDifficulty MainBlockHeader where difficultyL = mainHeaderDifficulty instance HasDifficulty MainBlock where difficultyL = mainBlockDifficulty instance HasBlockVersion MainExtraHeaderData where blockVersionL = mehBlockVersion instance HasSoftwareVersion MainExtraHeaderData where softwareVersionL = mehSoftwareVersion instance HasBlockVersion MainBlock where blockVersionL = mainBlockBlockVersion instance HasSoftwareVersion MainBlock where softwareVersionL = mainBlockSoftwareVersion instance HasBlockVersion MainBlockHeader where blockVersionL = mainHeaderBlockVersion instance HasSoftwareVersion MainBlockHeader where softwareVersionL = mainHeaderSoftwareVersion instance Bi BlockHeader => IsHeader MainBlockHeader instance Bi BlockHeader => IsMainHeader MainBlockHeader where headerSlotL = mainHeaderSlot headerLeaderKeyL = mainHeaderLeaderKey
null
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/core/Pos/Core/Block/Main/Instances.hs
haskell
| Miscellaneous instances, etc. Related to the main blockchain of course. instead of @Bi MainBlockHeader@. We compute header's hash by
# LANGUAGE TypeOperators # module Pos.Core.Block.Main.Instances ( ) where import Universum import qualified Data.Text.Buildable as Buildable import Formatting (bprint, build, int, stext, (%)) import Serokell.Util (Color (Magenta), colorize, listJson) import Pos.Binary.Class (Bi) import Pos.Binary.Core.Block () import Pos.Core.Block.Blockchain (GenericBlock (..), GenericBlockHeader (..)) import Pos.Core.Block.Main.Chain (Body (..), ConsensusData (..)) import Pos.Core.Block.Main.Lens (mainBlockBlockVersion, mainBlockDifficulty, mainBlockSlot, mainBlockSoftwareVersion, mainHeaderBlockVersion, mainHeaderDifficulty, mainHeaderLeaderKey, mainHeaderSlot, mainHeaderSoftwareVersion, mbTxs, mcdDifficulty, mehBlockVersion, mehSoftwareVersion) import Pos.Core.Block.Main.Types (MainBlock, MainBlockHeader, MainBlockchain, MainExtraHeaderData (..)) import Pos.Core.Block.Union.Types (BlockHeader, blockHeaderHash) import Pos.Core.Class (HasBlockVersion (..), HasDifficulty (..), HasEpochIndex (..), HasEpochOrSlot (..), HasHeaderHash (..), HasSoftwareVersion (..), IsHeader, IsMainHeader (..)) import Pos.Core.Common (HeaderHash) import Pos.Core.Configuration (HasConfiguration) import Pos.Core.Slotting.Types (EpochOrSlot (..), slotIdF) import Pos.Crypto (hashHexF) instance Bi BlockHeader => Buildable MainBlockHeader where build gbh@UnsafeGenericBlockHeader {..} = bprint ("MainBlockHeader:\n"% " hash: "%hashHexF%"\n"% " previous block: "%hashHexF%"\n"% " slot: "%slotIdF%"\n"% " difficulty: "%int%"\n"% " leader: "%build%"\n"% " signature: "%build%"\n"% build ) gbhHeaderHash _gbhPrevBlock _mcdSlot _mcdDifficulty _mcdLeaderKey _mcdSignature _gbhExtra where gbhHeaderHash :: HeaderHash gbhHeaderHash = blockHeaderHash $ Right gbh MainConsensusData {..} = _gbhConsensus instance (HasConfiguration, Bi BlockHeader) => Buildable MainBlock where build UnsafeGenericBlock {..} = bprint (stext%":\n"% " "%build% " transactions ("%int%" items): "%listJson%"\n"% " "%build%"\n"% " "%build%"\n"% " update payload: "%build%"\n"% " "%build ) (colorize Magenta "MainBlock") _gbHeader (length txs) txs _mbDlgPayload _mbSscPayload _mbUpdatePayload _gbExtra where MainBody {..} = _gbBody txs = _gbBody ^. mbTxs instance HasEpochIndex MainBlock where epochIndexL = mainBlockSlot . epochIndexL instance HasEpochIndex MainBlockHeader where epochIndexL = mainHeaderSlot . epochIndexL instance HasEpochOrSlot MainBlockHeader where getEpochOrSlot = EpochOrSlot . Right . view mainHeaderSlot instance HasEpochOrSlot MainBlock where getEpochOrSlot = getEpochOrSlot . _gbHeader NB . it 's not a mistake that these instances require @Bi BlockHeader@ converting it to a BlockHeader first . instance Bi BlockHeader => HasHeaderHash MainBlockHeader where headerHash = blockHeaderHash . Right instance Bi BlockHeader => HasHeaderHash MainBlock where headerHash = blockHeaderHash . Right . _gbHeader instance HasDifficulty (ConsensusData MainBlockchain) where difficultyL = mcdDifficulty instance HasDifficulty MainBlockHeader where difficultyL = mainHeaderDifficulty instance HasDifficulty MainBlock where difficultyL = mainBlockDifficulty instance HasBlockVersion MainExtraHeaderData where blockVersionL = mehBlockVersion instance HasSoftwareVersion MainExtraHeaderData where softwareVersionL = mehSoftwareVersion instance HasBlockVersion MainBlock where blockVersionL = mainBlockBlockVersion instance HasSoftwareVersion MainBlock where softwareVersionL = mainBlockSoftwareVersion instance HasBlockVersion MainBlockHeader where blockVersionL = mainHeaderBlockVersion instance HasSoftwareVersion MainBlockHeader where softwareVersionL = mainHeaderSoftwareVersion instance Bi BlockHeader => IsHeader MainBlockHeader instance Bi BlockHeader => IsMainHeader MainBlockHeader where headerSlotL = mainHeaderSlot headerLeaderKeyL = mainHeaderLeaderKey
24099c02f97af38f611b04921dbd403d430f43767a08112918da9fa4a6e820bf
jeapostrophe/adqc
stx.rkt
#lang racket/base (require (for-syntax racket/base racket/contract/base racket/dict racket/generic racket/list racket/syntax syntax/id-table) racket/contract/base racket/list racket/match racket/require racket/runtime-path racket/string racket/stxparam syntax/parse/define (subtract-in "ast.rkt" "type.rkt") "type.rkt" "util.rkt") ;; XXX This module should use plus not ast (i.e. the thing that does ;; type checking, termination checking, and resource analysis). And ;; plus should have an "any" type that causes inference, and that ;; should be supported here. ;; XXX Should these macros record the src location in the data ;; structure some how? (perhaps plus should do that with meta?) XXX Use remix for # % dot and # % braces (define (keyword->symbol kw) (string->symbol (keyword->string kw))) (define-syntax (define-expanders&macros stx) (syntax-parse stx [(_ S-free-macros define-S-free-syntax S-expander S-expand define-S-expander define-simple-S-expander) #:with expander-struct (generate-temporary #'S-expander) #:with gen-S-expander (format-id #'S-expander "gen:~a" #'S-expander) (syntax/loc stx (begin (begin-for-syntax (define S-free-macros (make-free-id-table)) (define-generics S-expander [S-expand S-expander stx]) (struct expander-struct (impl) #:extra-constructor-name S-expander #:property prop:procedure (struct-field-index impl) #:methods gen-S-expander [(define (S-expand this stx*) (this stx*))])) (define-simple-macro (define-S-free-syntax id impl) (begin-for-syntax (dict-set! S-free-macros #'id impl))) (define-simple-macro (define-S-expander id impl) (define-syntax id (expander-struct impl))) (define-simple-macro (define-simple-S-expander (id . args) body) (define-S-expander id (syntax-parser [(_ . args) (syntax/loc this-syntax body)]))) (provide define-S-free-syntax define-S-expander define-simple-S-expander)))])) (define-expanders&macros T-free-macros define-T-free-syntax T-expander T-expand define-T-expander define-simple-T-expander) (define-syntax (T stx) (with-disappeared-uses (syntax-parse stx #:literals (unsyntax unsyntax-splicing) ;; XXX should array, record, and union be literals? [(_ ((~datum array) dim elem)) (syntax/loc stx (ArrT dim (T elem)))] [(_ ((~datum record) (~or (unsyntax-splicing ps) (~and (~seq (~seq f:id ft) ...) (~bind [ps #'(list (cons 'f (T ft)) ...)]))))) ;; XXX syntax for choosing C stuff ;; XXX smarter defaults (syntax/loc stx (RecT (make-immutable-hasheq ps) (make-immutable-hasheq (for/list ([p (in-list ps)]) (cons (car p) (cify (car p))))) (map car ps)))] [(_ ((~datum union) (~or (unsyntax-splicing ps) (~and (~seq (~seq m:id mt) ...) (~bind [ps #'(list (cons 'm (T mt)) ...)]))))) ;; XXX syntax for choosing C stuff ;; XXX smarter defaults (syntax/loc stx (UniT (make-immutable-hash ps) (make-immutable-hash (for/list ([p (in-list ps)]) (cons (car p) (cify (car p)))))))] [(_ (~and macro-use (~or macro-id:id (macro-id:id . _)))) #:when (dict-has-key? T-free-macros #'macro-id) (record-disappeared-uses #'macro-id) ((dict-ref T-free-macros #'macro-id) #'macro-use)] [(_ (~and macro-use (~or macro-id (macro-id . _)))) #:declare macro-id (static T-expander? "T expander") (record-disappeared-uses #'macro-id) (T-expand (attribute macro-id.value) #'macro-use)] [(_ (unsyntax e)) (record-disappeared-uses #'unsyntax) #'e]))) (define the-void-ref (VoiT)) (define-T-free-syntax void (syntax-parser [_ #'the-void-ref])) (define the-any-ref (AnyT)) (define-T-free-syntax any (syntax-parser [_ #'the-any-ref])) (define-expanders&macros P-free-macros define-P-free-syntax P-expander P-expand define-P-expander define-simple-P-expander) (define-syntax (P stx) (with-disappeared-uses (syntax-parse stx #:literals (unsyntax) [(_ (p ... (~datum @) e)) (syntax/loc stx (Select (P (p ...)) (E e)))] [(_ (p ... (~datum ->) f:id)) (syntax/loc stx (Field (P (p ...)) 'f))] [(_ (p ... (~datum as) m:id)) (syntax/loc stx (Mode (P (p ...)) 'm))] [(_ (unsyntax e)) (record-disappeared-uses #'unsyntax) #'e] [(_ (~and macro-use (~or macro-id:id (macro-id:id . _)))) #:when (dict-has-key? P-free-macros #'macro-id) (record-disappeared-uses #'macro-id) ((dict-ref P-free-macros #'macro-id) #'macro-use)] [(_ (~and macro-use (~or macro-id (macro-id . _)))) #:declare macro-id (static P-expander? "P expander") (record-disappeared-uses #'macro-id) (P-expand (attribute macro-id.value) #'macro-use)] [(_ x:id) #'x] [(_ (x:id)) #'x]))) freenums can be implicitly cast to a larger type by BinOp (struct freenum-tag ()) (define freenum! (freenum-tag)) (define (freenum? e) (match e [(MetaE (== freenum!) _) #t] [(MetaE _ e) (freenum? e)] [(? Expr?) #f])) (define (freenum e) (MetaE freenum! e)) (define (construct-number stx ty n) (define (report fmt . vs) ;; XXX Maybe these are contract or range exceptions, not syntax errors? (raise-syntax-error #f (apply format fmt vs) stx)) (match ty [(IntT signed? bits) (define prefix (if signed? #\S #\U)) (when (< n (if signed? (- (expt 2 (sub1 bits))) 0)) (report "integer value ~a too small for ~a~a" n prefix bits)) (when (> n (sub1 (expt 2 (if signed? (sub1 bits) bits)))) (report "integer value ~a too large for ~a~a" n prefix bits)) (Int signed? bits n)] [(FloT bits) (define val (match bits [32 (real->single-flonum n)] [64 (real->double-flonum n)])) (Flo bits val)] [#f (cond [(single-flonum? n) (freenum (Flo 32 n))] [(double-flonum? n) (freenum (Flo 64 n))] [(exact-integer? n) (define 2^7 (expt 2 7)) (define 2^15 (expt 2 15)) (define 2^31 (expt 2 31)) (define 2^63 (expt 2 63)) (unless (and (< n (expt 2 64)) (>= n (- 2^63))) (report "~a is too large to fit in 64 bits" n)) (define unsigned? (>= n 2^63)) (define bits (cond [(and (< n 2^7) (>= n (- 2^7))) 8] [(and (< n 2^15) (>= n (- 2^15))) 16] [(and (< n 2^31) (>= n (- 2^31))) 32] [else 64])) (freenum (Int (not unsigned?) bits n))])])) (define-syntax-parameter expect-ty #f) (define-syntax (N stx) (syntax-parse stx [(_ n) #:with ty (or (syntax-parameter-value #'expect-ty) #'#f) (syntax/loc stx (N ty n))] [(_ ty n) (quasisyntax/loc stx (construct-number #'#,stx ty n))])) (define-expanders&macros E-free-macros define-E-free-syntax E-expander E-expand define-E-expander define-simple-E-expander) (begin-for-syntax (define-literal-set E-bin-op #:datum-literals ( iadd isub imul isdiv iudiv isrem iurem ishl ilshr iashr ior iand ixor ieq ine iugt isgt iuge isge iult islt iule isle fadd fsub fmul fdiv frem foeq fogt foge folt fole fone fueq fugt fuge fult fule fune ffalse ftrue ford funo) ()) (define E-bin-op? (literal-set->predicate E-bin-op))) (define (Let*E xs tys xes be) (cond [(empty? xs) be] [else (LetE (first xs) (first tys) (first xes) (Let*E (rest xs) (rest tys) (rest xes) be))])) (define (implicit-castable? to from) (match-define (IntT to-signed? to-bits) to) (match-define (IntT from-signed? from-bits) from) (cond [(and from-signed? (not to-signed?)) #f] [else (> to-bits from-bits)])) (define (make-binop op the-lhs the-rhs) (define l-ty (expr-type the-lhs)) (define r-ty (expr-type the-rhs)) ;; XXX Should resulting expression be freenum if both lhs and rhs are freenum ? ( If so , only when return ;; type is integral) ;; XXX This code could examine the actual values of constant ;; expressions so it could be even more permissive, allowing e.g. for ( < ( U32 some - val ) 0 ) , which right now fails ;; because signed values can never be implicitly cast to unsigned. (cond [(and (freenum? the-lhs) (implicit-castable? r-ty l-ty)) (BinOp op (Cast r-ty the-lhs) the-rhs)] [(and (freenum? the-rhs) (implicit-castable? l-ty r-ty)) (BinOp op the-lhs (Cast l-ty the-rhs))] [else (BinOp op the-lhs the-rhs)])) (define-syntax (E stx) (with-disappeared-uses (syntax-parse stx #:literals (if let unsyntax) [(_ (op:id l r)) #:when (E-bin-op? #'op) (syntax/loc stx (make-binop 'op (E l) (E r)))] [(_ (e (~datum :) ty)) (syntax/loc stx (Cast (T ty) (E e)))] [(_ (let ([x (~datum :) xty (~datum :=) xe] ...) be)) #:with (x-id ...) (generate-temporaries #'(x ...)) #:with (the-ty ...) (generate-temporaries #'(xty ...)) (record-disappeared-uses #'let) (syntax/loc stx (let ([x-id 'x-id] ... [the-ty (T xty)] ...) (Let*E (list x-id ...) (list the-ty ...) (list (syntax-parameterize ([expect-ty #'the-ty]) (E xe)) ...) (let ([the-x-ref (Var x-id the-ty)] ...) (let-syntax ([x (P-expander (syntax-parser [_ #'the-x-ref]))] ...) (E be))))))] [(_ (let ([x (~datum :=) xe] ...) be)) #:with (x-id ...) (generate-temporaries #'(x ...)) #:with (the-ty ...) (generate-temporaries #'(x ...)) #:with (the-xe ...) (generate-temporaries #'(xe ...)) (record-disappeared-uses #'let) (syntax/loc stx (let* ([x-id 'x-id] ... [the-xe (E xe)] ... [the-ty (expr-type the-xe)] ...) (Let*E (list x-id ...) (list the-ty ...) (list the-xe ...) (let ([the-x-ref (Var x-id the-ty)] ...) (let-syntax ([x (P-expander (syntax-parser [_ #'the-x-ref]))] ...) (E be))))))] [(_ (if c t f)) (record-disappeared-uses #'if) (syntax/loc stx (IfE (E c) (E t) (E f)))] [(_ (~and macro-use (~or macro-id:id (macro-id:id . _)))) #:when (dict-has-key? E-free-macros #'macro-id) (record-disappeared-uses #'macro-id) ((dict-ref E-free-macros #'macro-id) #'macro-use)] [(_ (~and macro-use (~or macro-id (macro-id . _)))) #:declare macro-id (static E-expander? "E expander") (record-disappeared-uses #'macro-id) (E-expand (attribute macro-id.value) #'macro-use)] [(_ (unsyntax e)) (record-disappeared-uses #'unsyntax) #'e] [(_ n:number) (syntax/loc stx (N n))] [(_ p) (quasisyntax/loc stx (Read #,(syntax/loc #'p (P p))))]))) (define-E-free-syntax cond (syntax-parser #:literals (else) [(_ [else e]) (syntax/loc this-syntax (E e))] [(_ [q a] . more) (syntax/loc this-syntax (E (if q a (cond . more))))])) (define-E-free-syntax and (syntax-parser [(_) (syntax/loc this-syntax (N 1))] [(_ e) (syntax/loc this-syntax (E e))] [(_ e es ...) (syntax/loc this-syntax (let* ([the-e (E e)] [e-ty (expr-type the-e)]) (IfE the-e (syntax-parameterize ([expect-ty #'e-ty]) (E (and es ...))) (N e-ty 0))))])) (define-E-free-syntax or (syntax-parser [(_) (syntax/loc this-syntax (N 0))] [(_ e) (syntax/loc this-syntax (E e))] [(_ e es ...) (syntax/loc this-syntax (let* ([the-e (E e)] [e-ty (expr-type the-e)]) (IfE the-e the-e (syntax-parameterize ([expect-ty #'e-ty]) (E (or es ...))))))])) (define (not* the-e) (define e-ty (expr-type the-e)) (define one (match e-ty [(? IntT?) 1] [(FloT 32) 1.0f0] [(FloT 64) 1.0])) (E (bitwise-xor #,the-e #,(N e-ty one)))) (define-E-free-syntax not (syntax-parser [(_ e) (syntax/loc this-syntax (not* (E e)))])) (define-E-free-syntax let* (syntax-parser [(_ () e) (syntax/loc this-syntax (E e))] [(_ (f r ...) e) (syntax/loc this-syntax (E (let (f) (let* (r ...) e))))])) (define (zero?* the-e) (define e-ty (expr-type the-e)) (define zero (match e-ty [(? IntT?) 0] [(FloT 32) 0.0f0] [(FloT 64) 0.0])) (E (= #,the-e #,(N e-ty zero)))) (define-E-free-syntax zero? (syntax-parser [(_ e) (syntax/loc this-syntax (zero?* (E e)))])) (define-E-free-syntax min (syntax-parser [(_ a b) (syntax/loc this-syntax (E (if (< a b) a b)))])) (define-E-free-syntax max (syntax-parser [(_ a b) (syntax/loc this-syntax (E (if (< a b) b a)))])) (define-syntax (define-E-increment-ops stx) (syntax-parse stx [(_ [name:id op:id] ...+) #:with (name^ ...) (generate-temporaries #'(name ...)) (syntax/loc stx (begin (begin (define (name^ the-e) (define e-ty (expr-type the-e)) (define one (match e-ty [(? IntT?) 1] [(FloT 32) 1.0f0] [(FloT 64) 1.0])) (E (op #,the-e #,(N e-ty one)))) (define-E-free-syntax name (syntax-parser [(_ e) (syntax/loc this-syntax (name^ (E e)))]))) ...))])) (define-E-increment-ops [add1 +] [sub1 -]) (define (subtract the-lhs the-rhs) (match (expr-type the-lhs) [(? IntT?) (E (isub #,the-lhs #,the-rhs))] [(? FloT?) (E (fsub #,the-lhs #,the-rhs))])) (define (negate the-e) (define e-ty (expr-type the-e)) (define zero (match e-ty [(? IntT?) 0] [(FloT 32) 0.0f0] [(FloT 64) 0.0])) (subtract (N e-ty zero) the-e)) (define-E-free-syntax - (syntax-parser [(_ e) (syntax/loc this-syntax (negate (E e)))] [(_ l r) (syntax/loc this-syntax (subtract (E l) (E r)))])) (define-syntax (define-free-binop stx) (syntax-parse stx [(_ name:id [match-clause op:id] ...+) #:with name^ (generate-temporary #'name) (syntax/loc stx (begin (define (name^ the-lhs the-rhs) (match (expr-type the-lhs) [match-clause (E (op #,the-lhs #,the-rhs))] ...)) (define-E-free-syntax name (syntax-parser [(_ l r) (syntax/loc this-syntax (name^ (E l) (E r)))]))))])) (define-free-binop + [(? IntT?) iadd] [(? FloT?) fadd]) (define-free-binop * [(? IntT?) imul] [(? FloT?) fmul]) (define-free-binop / [(IntT #t _) isdiv] [(IntT #f _) iudiv] [(? FloT?) fdiv]) (define-free-binop modulo [(IntT #t _) isrem] [(IntT #f _) iurem] [(? FloT?) frem]) (define-free-binop bitwise-ior [(? IntT?) ior]) (define-free-binop bitwise-and [(? IntT?) iand]) (define-free-binop bitwise-xor [(? IntT?) ixor]) (define-free-binop = [(? IntT?) ieq] [(? FloT?) foeq]) (define-free-binop < [(IntT #t _) islt] [(IntT #f _) iult] [(? FloT?) folt]) (define-free-binop <= [(IntT #t _) isle] [(IntT #f _) iule] [(? FloT?) fole]) (define-free-binop > [(IntT #t _) isgt] [(IntT #f _) iugt] [(? FloT?) fogt]) (define-free-binop >= [(IntT #t _) isge] [(IntT #f _) iuge] [(? FloT?) foge]) (begin-for-syntax (struct T/E-expander (T-impl E-impl) #:property prop:procedure (λ (this stx) (raise-syntax-error #f "Illegal outside T or E" stx)) #:methods gen:T-expander [(define (T-expand this stx) ((T/E-expander-T-impl this) stx))] #:methods gen:E-expander [(define (E-expand this stx) ((T/E-expander-E-impl this) stx))])) (define-simple-macro (define-flo-stx [name:id bits] ...) (begin (define-syntax name (T/E-expander (syntax-parser [_:id (record-disappeared-uses #'name) (syntax/loc this-syntax (FloT bits))]) (syntax-parser [(_ n:expr) (record-disappeared-uses #'name) (quasisyntax/loc this-syntax (construct-number #'#,this-syntax (FloT bits) n))]))) ... (provide name ...))) (define-flo-stx [F32 32] [F64 64]) (define-simple-macro (define-int-stx [name:id signed? bits] ...) (begin (define-syntax name (T/E-expander (syntax-parser [_:id (record-disappeared-uses #'name) (syntax/loc this-syntax (IntT signed? bits))]) (syntax-parser [(_ n:expr) (record-disappeared-uses #'name) (quasisyntax/loc this-syntax (construct-number #'#,this-syntax (IntT signed? bits) n))]))) ... (provide name ...))) (define-int-stx [S8 #t 8] [S16 #t 16] [S32 #t 32] [S64 #t 64] [U8 #f 8] [U16 #f 16] [U32 #f 32] [U64 #f 64]) (define-expanders&macros I-free-macros define-I-free-syntax I-expander I-expand define-I-expander define-simple-I-expander) XXX should undef , zero , array , record , and union be literals ? (define-syntax (I stx) (with-disappeared-uses (syntax-parse stx #:literals (unsyntax unsyntax-splicing) [(_ ((~datum undef) ty)) (syntax/loc stx (UndI (T ty)))] [(_ ((~datum zero) ty)) (syntax/loc stx (ZedI (T ty)))] [(_ ((~datum array) (~or (unsyntax-splicing is) (~and (~seq i ...) (~bind [is #'(list (I i) ...)]))))) (syntax/loc stx (ArrI is))] [(_ ((~datum record) (~or (unsyntax-splicing ps) (~and (~seq (~seq k:id i) ...) (~bind [ps #'(list (cons 'k (I i)) ...)]))))) (syntax/loc stx (RecI (make-immutable-hasheq ps)))] [(_ ((~datum union) (~or (unsyntax m-id) (~and m:id (~bind [m-id #''m]))) i)) (syntax/loc stx (UniI m-id (I i)))] [(_ (~and macro-use (~or macro-id:id (macro-id:id . _)))) #:when (dict-has-key? I-free-macros #'macro-id) (record-disappeared-uses #'macro-id) ((dict-ref I-free-macros #'macro-id) #'macro-use)] [(_ (~and macro-use (~or macro-id (macro-id . _)))) #:declare macro-id (static I-expander? "I expander") (record-disappeared-uses #'macro-id) (I-expand (attribute macro-id.value) #'macro-use)] [(_ (unsyntax e)) (record-disappeared-uses #'unsyntax) #'e] [(_ x) (syntax/loc stx (ConI (E x)))]))) (begin-for-syntax (struct F-expander (impl) #:property prop:procedure (struct-field-index impl))) (define-syntax-parameter current-return #f) (define-syntax-parameter current-return-var #f) (define-syntax-parameter S-in-tail? #f) (define-expanders&macros S-free-macros define-S-free-syntax S-expander S-expand define-S-expander define-simple-S-expander) (define-syntax (S stx) (with-disappeared-uses (syntax-parse stx #:literals (void error begin define set! if let/ec let unsyntax unsyntax-splicing) [(_ (void)) (record-disappeared-uses #'void) (syntax/loc stx (Skip #f))] [(_ (void ~! m)) (record-disappeared-uses #'void) (syntax/loc stx (Skip m))] [(_ (error ~! m)) (record-disappeared-uses #'error) (syntax/loc stx (Fail m))] [(_ (begin)) (record-disappeared-uses #'begin) (syntax/loc stx (S (void)))] [(_ (begin (define . d) . b)) ;; XXX define is not getting bound (record-disappeared-uses (list #'begin #'define)) (syntax/loc stx (S (let (d) . b)))] [(_ (begin s)) (record-disappeared-uses #'begin) (syntax/loc stx (S s))] [(_ (begin ~! a . d)) (record-disappeared-uses #'begin) (syntax/loc stx (Begin (syntax-parameterize ([S-in-tail? #f]) (S a)) (S (begin . d))))] [(_ (set! ~! p e)) (record-disappeared-uses #'set!) (syntax/loc stx (let* ([the-p (P p)] [p-ty (path-type the-p)]) (Assign the-p (syntax-parameterize ([expect-ty #'p-ty]) (E e)))))] [(_ {p (~datum <-) e}) (syntax/loc stx (S (set! p e)))] [(_ (if ~! p t f)) (record-disappeared-uses #'if) (syntax/loc stx (If (E p) (S t) (S f)))] [(_ (let/ec ~! k:id . b)) #:with k-id (generate-temporary #'k) (record-disappeared-uses #'let/ec) (syntax/loc stx (let ([k-id 'k-id]) (Let/ec k-id (let ([the-ret (Jump k-id)]) (let-syntax ([k (S-expander (syntax-parser [(_) #'the-ret]))]) (S (begin . b)))))))] ;; let with T/I expander [(_ (let ([x:id (~datum :=) (~and ctor-use (ctor-id . _))]) . b)) #:declare ctor-id (static (and/c T-expander? I-expander?) "T/I expander") (record-disappeared-uses #'let) (syntax/loc stx (S (let ([x : ctor-id := ctor-use]) . b)))] ;; let with function call from F-expander [(_ (let ([x:id (~optional (~seq (~datum :) ty) #:defaults ([ty #'#f])) (~datum :=) (fun-id . fun-args)]) . b)) #:declare fun-id (static F-expander? "F expander") #:with ty* (if (syntax->datum #'ty) #'(T ty) #'(Fun-ret-ty fun-id)) (record-disappeared-uses (list #'let #'fun-id)) (syntax/loc stx (S (let ([x : #,ty* := fun-id <- . fun-args]) . b)))] let with implicit type from expr initializaiton [(_ (let ([x:id (~datum :=) e]) . b)) #:with x-id (generate-temporary #'x) (record-disappeared-uses #'let) (syntax/loc stx (let* ([x-id 'x-id] [the-e (E e)] [the-ty (expr-type the-e)]) (Let x-id the-ty (ConI the-e) (let ([the-x-ref (Var x-id the-ty)]) (let-syntax ([x (P-expander (syntax-parser [_ #'the-x-ref]))]) (S (begin . b)))))))] ;; let with full type annotation [(_ (let ([x:id (~datum :) ty (~datum :=) xi]) . b)) #:with x-id (generate-temporary #'x) (record-disappeared-uses #'let) (syntax/loc stx (let ([x-id 'x-id] [the-ty (T ty)]) (Let x-id the-ty (syntax-parameterize ([expect-ty #'the-ty]) (I xi)) (let ([the-x-ref (Var x-id the-ty)]) (let-syntax ([x (P-expander (syntax-parser [_ #'the-x-ref]))]) (S (begin . b)))))))] ;; let with uninitialized variable [(_ (let ([x:id (~datum :) ty]) . b)) (record-disappeared-uses #'let) (syntax/loc stx (let ([the-ty (T ty)]) (S (let ([x : #,the-ty := (undef #,the-ty)]) . b))))] ;; let with function call [(_ (let ([x:id (~optional (~seq (~datum :) ty) #:defaults ([ty #'#f])) (~datum :=) f (~datum <-) (~or (unsyntax-splicing as) (~and (~seq a ...) (~bind [as #'(list (E a) ...)])))]) . b)) #:with x-id (generate-temporary #'x) #:with ty* (if (syntax->datum #'ty) #'(T ty) #'(Fun-ret-ty f)) (record-disappeared-uses #'let) (syntax/loc stx (let ([x-id 'x-id] [the-ty ty*]) (Call x-id the-ty f as (let ([the-x-ref (Var x-id the-ty)]) (let-syntax ([x (P-expander (syntax-parser [_ #'the-x-ref]))]) (S (begin . b)))))))] [(_ (~and macro-use (~or macro-id:id (macro-id:id . _)))) #:when (dict-has-key? S-free-macros #'macro-id) (record-disappeared-uses #'macro-id) ((dict-ref S-free-macros #'macro-id) #'macro-use)] [(_ (~and macro-use (~or macro-id (macro-id . _)))) #:declare macro-id (static S-expander? "S expander") (record-disappeared-uses #'macro-id) (S-expand (attribute macro-id.value) #'macro-use)] [(_ (unsyntax ~! e)) (record-disappeared-uses #'unsyntax) #'e] [(_ e ~!) #:fail-unless (syntax-parameter-value #'S-in-tail?) "Cannot end in expression when not in tail position" (syntax/loc stx (S (return e)))]))) (define-S-free-syntax cond (syntax-parser #:literals (else) [(_) (syntax/loc this-syntax (S (void)))] [(_ [else . b]) (syntax/loc this-syntax (S (begin . b)))] [(_ [q . a] . more) (syntax/loc this-syntax (S (if q (begin . a) (cond . more))))])) (define-S-free-syntax when (syntax-parser [(_ p . t) (syntax/loc this-syntax (S (if p (begin . t) (void))))])) (define-S-free-syntax unless (syntax-parser [(_ p . f) (syntax/loc this-syntax (S (if p (void) (begin . f))))])) (define-S-free-syntax let* (syntax-parser #:literals () [(_ () . b) (syntax/loc this-syntax (S (begin . b)))] [(_ (a . d) . b) (syntax/loc this-syntax (S (let (a) (let* d . b))))])) (define-S-expander assert! (syntax-parser [(_ (~optional (~and #:dyn (~bind [must-be-static? #f])) #:defaults ([must-be-static? #t])) (~optional (~seq #:msg p-msg-expr) #:defaults ([p-msg-expr #'#f])) p) #:with p-e (if (attribute must-be-static?) ;; XXX use struct (syntax/loc #'p (MetaE 'must-be-static p)) #'p) (record-disappeared-uses #'assert!) (syntax/loc this-syntax (let ([p-msg (or p-msg-expr (format "~a" 'p))]) (S (if p-e (void (format "Checked: ~a" p-msg)) (error (format "Failed! ~a" p-msg))))))])) (define-S-expander while (syntax-parser [(_ (~optional (~seq #:I I) #:defaults ([I #'(U32 1)])) p . b) (record-disappeared-uses #'while) (syntax/loc this-syntax ;; XXX use struct (MetaS (cons 'while-invariant (E I)) (While (E p) (syntax-parameterize ([S-in-tail? #f]) (S (begin . b))))))])) (define-S-free-syntax for (syntax-parser [(_ ((~optional (~seq #:I I) #:defaults ([I #'(U32 1)])) init pred inc) body ...) (record-disappeared-uses #'for) (syntax/loc this-syntax (S (let (init) (while #:I I pred body ... inc))))])) (define-S-expander return (syntax-parser [(_) #:fail-unless (syntax-parameter-value #'current-return) "Illegal outside of F" (record-disappeared-uses #'return) (syntax/loc this-syntax current-return)] [(_ e) #:fail-unless (and (syntax-parameter-value #'current-return) (syntax-parameter-value #'current-return-var)) "Illegal outside of F" (record-disappeared-uses #'return) (syntax/loc this-syntax (S (begin (set! current-return-var e) (return))))])) (define-expanders&macros A-free-macros define-A-free-syntax A-expander A-expand define-A-expander define-simple-A-expander) (struct anf-nv () #:transparent) (struct anf-void anf-nv (var pre) #:transparent) (struct anf-let/ec (var k b-arg b-nv) #:transparent) (struct anf-let anf-nv (var xe) #:transparent) (struct anf-call anf-nv (x ty f es) #:transparent) (struct anf-if anf-nv (var p-arg t-nv t-arg f-nv f-arg) #:transparent) (struct anf-type anf-nv (var es) #:transparent) (struct anf-union anf-nv (var m e) #:transparent) (define listof-nvs? (listof anf-nv?)) (begin-for-syntax (struct A-esc-k (var id) #:methods gen:A-expander [(define (A-expand this stx) (syntax-parse stx [(_ a) #:with void-id (generate-temporary 'any) #:with k-var (A-esc-k-var this) #:with k-id (A-esc-k-id this) (syntax/loc stx (let* ([void-id 'void-id] [void-ref (Var void-id (T any))]) (define-values (a-nv a-arg) (ANF a)) (define the-stmt (Begin (Assign k-var a-arg) (Jump k-id))) (values (snoc a-nv (anf-void void-ref the-stmt)) (Read void-ref))))]))])) (define-syntax (ANF stx) (with-disappeared-uses (syntax-parse stx #:literals (void error begin define set! if let/ec let unsyntax) [(_ (void ~!)) #:with x-id (generate-temporary 'void) (record-disappeared-uses #'void) (syntax/loc stx (let* ([x-id 'x-id] [the-x-ref (Var x-id (T void))]) (values (list (anf-void the-x-ref #f)) (Read the-x-ref))))] [(_ (error ~! m)) #:with x-id (generate-temporary 'any) (record-disappeared-uses #'error) (syntax/loc stx (let* ([x-id 'x-id] [the-x-ref (Var x-id (T any))]) (values (list (anf-void the-x-ref (Fail m))) (Read the-x-ref))))] [(_ (begin (define . d) . b)) (record-disappeared-uses (list #'begin #'define)) (syntax/loc stx (ANF (let (d) . b)))] [(_ (begin a)) (record-disappeared-uses #'begin) (syntax/loc stx (ANF a))] [(_ (begin ~! a . as)) (record-disappeared-uses #'begin) (syntax/loc stx (let-values ([(a-nv a-arg) (ANF a)] [(as-nv as-arg) (ANF (begin . as))]) (values (append a-nv as-nv) as-arg)))] [(_ (set! ~! p a)) #:with x-id (generate-temporary 'void) (record-disappeared-uses #'set!) (syntax/loc stx (let* ([the-p (P p)] [p-ty (path-type the-p)]) (define-values (a-nv a-arg) (syntax-parameterize ([expect-ty #'p-ty]) (ANF a))) (define x-id 'x-id) (define the-x-ref (Var x-id (T void))) (values (snoc a-nv (anf-void the-x-ref (Assign the-p a-arg))) (Read the-x-ref))))] [(_ (if ~! p t f)) #:with x-id (generate-temporary 'if) (record-disappeared-uses #'if) (syntax/loc stx (let-values ([(p-nv p-arg) (ANF p)] [(t-nv t-arg) (ANF t)] [(f-nv f-arg) (ANF f)]) (define x-id 'x-id) (define x-ty (resolve-type (expr-type t-arg) (expr-type f-arg))) (define the-x-ref (Var x-id x-ty)) (values (snoc p-nv (anf-if the-x-ref p-arg t-nv t-arg f-nv f-arg)) (Read the-x-ref))))] [(_ (let/ec ~! (k:id ty) body ...+)) #:with x-id (generate-temporary 'letec) #:with k-id (generate-temporary #'k) (record-disappeared-uses #'let/ec) (syntax/loc stx (let ([x-id 'x-id] [k-id 'k-id] [the-ty (T ty)]) (define the-x-ref (Var x-id the-ty)) (define-values (body-nv body-arg) (let-syntax ([k (A-esc-k #'the-x-ref #'k-id)]) (ANF (begin body ...)))) (values (list (anf-let/ec the-x-ref k-id body-arg body-nv)) (Read the-x-ref))))] [(_ (let ~! ([x:id xe] ...) body ...+)) #:with (x-id ...) (generate-temporaries #'(x ...)) #:with (xe-ty ...) (generate-temporaries #'(x ...)) #:with (ref-ty? ...) (generate-temporaries #'(x ...)) #:with (the-x-ref ...) (generate-temporaries #'(x ...)) #:with (xe-nv ...) (generate-temporaries #'(x ...)) #:with (xe-arg ...) (generate-temporaries #'(x ...)) (record-disappeared-uses #'let) (quasisyntax/loc stx (let-values ([(xe-nv xe-arg) (ANF xe)] ...) (define x-id 'x-id) ... (define xe-ty (expr-type xe-arg)) ... (for ([ty (in-list (list xe-ty ...))]) (when (VoiT? ty) (raise-syntax-error 'let "new variable cannot be of type void" #'#,stx)) (when (AnyT? ty) (raise-syntax-error 'let "new variable cannot be of type any" #'#,stx))) (define ref-ty? (or (ArrT? xe-ty) (RecT? xe-ty) (UniT? xe-ty))) ... (define the-x-ref (if ref-ty? (Read-p xe-arg) (Var x-id xe-ty))) ... (define-values (body-nv body-arg) (let-syntax ([x (P-expander (syntax-parser [_ #'the-x-ref]))] ...) (ANF (begin body ...)))) (define the-nvs (for/list ([arg (in-list (list xe-arg ...))] [x-ref (in-list (list the-x-ref ...))] [ref? (in-list (list ref-ty? ...))] #:unless ref?) (anf-let x-ref arg))) (values (append xe-nv ... the-nvs body-nv) body-arg)))] [(_ (fn ~! as ...)) #:declare fn (static F-expander? "F expander") #:with x-id (generate-temporary #'fn) #:with (as-nv ...) (generate-temporaries #'(as ...)) #:with (as-arg ...) (generate-temporaries #'(as ...)) (record-disappeared-uses #'fn) (syntax/loc stx (let-values ([(as-nv as-arg) (ANF as)] ...) (define x-id 'x-id) (define x-ty (fun-type fn)) (define the-x-ref (Var x-id x-ty)) (values (snoc (append as-nv ...) (anf-call x-id x-ty fn (list as-arg ...))) (Read the-x-ref))))] [(_ (ty m:keyword ~! a:expr)) #:declare ty (static (and/c T-expander? I-expander?) "T/I expander") #:with x-id (generate-temporary #'ty) (record-disappeared-uses #'ty) (syntax/loc stx (let-values ([(a-nv a-arg) (ANF a)]) (define x-id 'x-id) (define x-ty (T ty)) (define the-x-ref (Var x-id x-ty)) (values (snoc a-nv (anf-union the-x-ref (keyword->symbol 'm) a-arg)) (Read the-x-ref))))] [(_ (ty ~! as ...)) #:declare ty (static (and/c T-expander? I-expander?) "T/I expander") #:with x-id (generate-temporary #'ty) #:with (as-nv ...) (generate-temporaries #'(as ...)) #:with (as-arg ...) (generate-temporaries #'(as ...)) (record-disappeared-uses #'ty) (syntax/loc stx (let-values ([(as-nv as-arg) (ANF as)] ...) (define x-id 'x-id) (define x-ty (T ty)) (define the-x-ref (Var x-id x-ty)) (values (snoc (append as-nv ...) (anf-type the-x-ref (list as-arg ...))) (Read the-x-ref))))] [(_ (~and macro-use (~or macro-id:id (macro-id:id . _)))) #:when (dict-has-key? A-free-macros #'macro-id) (record-disappeared-uses #'macro-id) ((dict-ref A-free-macros #'macro-id) #'macro-use)] [(_ (~and macro-use (~or macro-id (macro-id . _)))) #:declare macro-id (static A-expander? "A expander") (record-disappeared-uses #'macro-id) (A-expand (attribute macro-id.value) #'macro-use)] [(_ (unsyntax ~! nvs/arg)) (record-disappeared-uses #'unsyntax) (quasisyntax/loc stx (let-values ([(nvs arg) nvs/arg]) (unless (Expr? arg) (raise-syntax-error #f "unsyntaxed ANF arg must be Expr" #'#,stx)) (unless (listof-nvs? nvs) (raise-syntax-error #f "unsyntaxed ANF nvs must be list of anf-nv" #'#,stx)) (values nvs arg)))] [(_ e ~!) (syntax/loc stx (values '() (E e)))]))) (define (ANF-compose ret-fn nvs arg) (define (rec nvs arg) (ANF-compose ret-fn nvs arg)) (match nvs ['() (ret-fn arg)] [(cons (anf-void var pre) more) (match-define (Var x ty) (unpack-MetaP var)) (Let x ty (UndI ty) (Begin (or pre (Skip #f)) (rec more arg)))] [(cons (anf-let/ec var k b-arg b-nv) more) (match-define (Var x ty) (unpack-MetaP var)) (define (body-ret arg) (Assign var arg)) (Let x ty (UndI ty) (Begin (Let/ec k (ANF-compose body-ret b-nv b-arg)) (rec more arg)))] [(cons (anf-let var xe) more) (match-define (Var x ty) (unpack-MetaP var)) (Let x ty (UndI ty) (Begin (Assign var xe) (rec more arg)))] [(cons (anf-call x ty f es) more) (Call x ty f es (rec more arg))] [(cons (anf-if var p-arg t-nv t-arg f-nv f-arg) more) (match-define (Var x ty) (unpack-MetaP var)) (define (branch-ret arg) (Assign var arg)) (Let x ty (UndI ty) (Begin (If p-arg (ANF-compose branch-ret t-nv t-arg) (ANF-compose branch-ret f-nv f-arg)) (rec more arg)))] [(cons (anf-type var es) more) (match-define (Var x ty) (unpack-MetaP var)) (define body (match ty [(ArrT dim _) (for/fold ([b (rec more arg)]) ([i (in-list (reverse (range dim)))] [e (in-list (reverse es))]) (Begin (Assign (Select var (N i)) e) b))] [(RecT _ _ c-order) (for/fold ([b (rec more arg)]) ([f (in-list (reverse c-order))] [e (in-list (reverse es))]) (Begin (Assign (Field var f) e) b))])) (Let x ty (UndI ty) body)] [(cons (anf-union var m e) more) (match-define (Var x ty) (unpack-MetaP var)) (Let x ty (UndI ty) (Begin (Assign (Mode var m) e) (rec more arg)))])) (define-simple-macro (S+ e) (let-values ([(nvs arg) (ANF e)]) (define (ret-fn arg) (S (return #,arg))) (ANF-compose ret-fn nvs arg))) (begin-for-syntax (define (make-A-op-parser op-stx) (syntax-parser [(_ as ...) #:with x-id (generate-temporary) #:with (as-nv ...) (generate-temporaries #'(as ...)) #:with (as-arg ...) (generate-temporaries #'(as ...)) #:with op op-stx (syntax/loc this-syntax (let-values ([(as-nv as-arg) (ANF as)] ...) (define x-id 'x-id) (define arg-e (E (op #,as-arg ...))) (define x-ty (expr-type arg-e)) (define the-x-ref (Var x-id x-ty)) (values (snoc (append as-nv ...) (anf-let the-x-ref arg-e)) (Read the-x-ref))))]))) (define-simple-macro (define-A-free-ops op:id ...) (begin (define-A-free-syntax op (make-A-op-parser #'op)) ...)) (define-A-free-ops + - * / modulo bitwise-ior bitwise-and bitwise-xor = < <= > >= not zero? min max) (begin-for-syntax (struct E/A-expander (E-impl A-impl) #:property prop:procedure (λ (this stx) (raise-syntax-error #f "Illegal outside E or S+" stx)) #:methods gen:E-expander [(define (E-expand this stx) ((E/A-expander-E-impl this) stx))] #:methods gen:A-expander [(define (A-expand this stx) ((E/A-expander-A-impl this) stx))])) (define-simple-macro (define-E/A-expander x:id E-impl A-impl) (define-syntax x (E/A-expander E-impl A-impl))) (begin-for-syntax (define (make-E/A-binop-expander op-stx impl-stx) (E/A-expander (syntax-parser [(_ l r) (quasisyntax/loc this-syntax (#,impl-stx (E l) (E r)))]) (make-A-op-parser op-stx)))) (define-syntax (define-E/A-binop stx) (syntax-parse stx [(_ name:id [match-clause op:id] ...+) #:with name^ (generate-temporary #'name) (syntax/loc stx (begin (define (name^ the-lhs the-rhs) (match (expr-type the-lhs) [match-clause (E (op #,the-lhs #,the-rhs))] ...)) (define-syntax name (make-E/A-binop-expander #'name #'name^)) (provide name)))])) (define-E/A-binop << [(? IntT?) ishl]) (define-E/A-binop >> [(IntT #t _) iashr] [(IntT #f _) ilshr]) ;; Note: behavior of C's != operator is unordered for floats (define-E/A-binop != [(? IntT?) ine] [(? FloT?) fune]) (define-simple-macro (define-E/A-aliases [name:id op:id] ...+) (begin (begin (define-E/A-expander name (syntax-parser [(_ . vs) (syntax/loc this-syntax (E (op . vs)))]) (syntax-parser [(_ . as) (syntax/loc this-syntax (ANF (op . as)))])) (provide name)) ...)) (define-E/A-aliases [% modulo] [& bitwise-and] [^ bitwise-xor]) (define-A-free-syntax when (syntax-parser [(_ p . t) (syntax/loc this-syntax (ANF (if p (begin . t) (void))))])) (define-A-free-syntax unless (syntax-parser [(_ p . f) (syntax/loc this-syntax (ANF (if p (void) (begin . f))))])) (define-A-free-syntax let* (syntax-parser [(_ () a) (syntax/loc this-syntax (ANF a))] [(_ (f r ...) a) (syntax/loc this-syntax (ANF (let (f) (let* (r ...) a))))])) (define-A-free-syntax cond (syntax-parser #:literals (else) [(_ [else a]) (syntax/loc this-syntax (ANF a))] [(_ [q a] . more) (syntax/loc this-syntax (ANF (if q a (cond . more))))])) (define-A-free-syntax and (syntax-parser [(_) (syntax/loc this-syntax (ANF #,(values '() (N 1))))] [(_ a) (syntax/loc this-syntax (ANF a))] [(_ a as ...) (syntax/loc this-syntax (let-values ([(a-nv a-arg) (ANF a)]) (define arg-ty (expr-type a-arg)) (define-values (as-nv as-arg) (syntax-parameterize ([expect-ty #'arg-ty]) (ANF (and as ...)))) (ANF (if #,(values a-nv a-arg) #,(values as-nv as-arg) #,(values '() (N arg-ty 0))))))])) (define-A-free-syntax or (syntax-parser [(_) (syntax/loc this-syntax (ANF #,(values '() (N 0))))] [(_ a) (syntax/loc this-syntax (ANF a))] [(_ a as ...) (syntax/loc this-syntax (let-values ([(a-nv a-arg) (ANF a)]) (define arg-ty (expr-type a-arg)) (define-values (as-nv as-arg) (syntax-parameterize ([expect-ty #'arg-ty]) (ANF (or as ...)))) (ANF (let ([tmp #,(values a-nv a-arg)]) (if tmp tmp #,(values as-nv as-arg))))))])) (begin-for-syntax (struct S/A-expander (S-impl A-impl) #:methods gen:S-expander [(define (S-expand this stx) ((S/A-expander-S-impl this) stx))] #:methods gen:A-expander [(define (A-expand this stx) ((S/A-expander-A-impl this) stx))])) (define-simple-macro (define-S/A-expander x:id S-impl A-impl) (define-syntax x (S/A-expander S-impl A-impl))) (define-simple-macro (define-S/A-assign-ops [name:id op:id] ...+) (begin (begin (define-S/A-expander name (syntax-parser [(_ p e) (syntax/loc this-syntax (S (set! p (op p e))))]) (syntax-parser [(_ p a) #:with x-id (generate-temporary 'void) (syntax/loc this-syntax (let-values ([(a-nv a-arg) (ANF a)]) (define x-id 'x-id) (define the-x-ref (Var x-id (T void))) (define the-stmt (S (name p #,a-arg))) (values (snoc a-nv (anf-void the-x-ref the-stmt)) (Read the-x-ref))))])) (provide name)) ...)) (define-S/A-assign-ops [+= +] [-= -] [*= *] [/= /] [%= %] [<<= <<] [>>= >>]) (define-simple-macro (define-S/A-increment-ops [name:id op:id] ...+) (begin (begin (define-S/A-expander name (syntax-parser [(_ p) (syntax/loc this-syntax (S (set! p (op p))))]) (syntax-parser [(_ p) #:with x-id (generate-temporary 'void) (syntax/loc this-syntax (let* ([x-id 'x-id] [the-x-ref (Var x-id (T void))]) (values (list (anf-void the-x-ref (S (name p)))) (Read the-x-ref))))])) (provide name)) ...)) (define-S/A-increment-ops [+=1 add1] [-=1 sub1]) XXX ' assert ! ' , ' let loop ' , ' for ' for ANF . (begin-for-syntax (define-syntax-class Farg #:attributes (x ref var arg) #:description "function argument" [pattern ((~optional (~or (~and #:copy (~bind [mode #''copy])) (~and #:ref (~bind [mode #''ref]))) #:defaults ([mode #''read-only])) ty x:id) #:attr ref (generate-temporary #'x) #:attr var (syntax/loc this-syntax (Var 'ref (T ty))) #:attr arg (syntax/loc this-syntax (Arg (Var-x ref) (Var-ty ref) mode))]) (define-syntax-class Fret #:attributes (x ref var) #:description "function return" [pattern (x:id (~datum :) ty) #:attr ref (generate-temporary #'x) #:attr var (syntax/loc this-syntax (Var 'ref (T ty)))] [pattern ty #:attr x (generate-temporary #'ty) #:attr ref (generate-temporary #'x) #:attr var (syntax/loc this-syntax (Var 'ref (T ty)))])) (define-syntax-parameter F-body-default (make-rename-transformer #'S)) (define-syntax (F stx) (with-disappeared-uses (syntax-parse stx [(_ r:Fret (a:Farg ...) (~optional (~seq #:pre pre) #:defaults ([pre #'(S64 1)])) (~optional (~seq #:post post) #:defaults ([post #'(S64 1)])) (~optional (~seq #:return ret-lab:id) #:defaults ([ret-lab (generate-temporary 'return)])) . bs) #:fail-when (check-duplicates (syntax->list #'(a.x ...)) bound-identifier=?) "All arguments must have unique identifiers" #:with ret-lab-id (generate-temporary #'ret-lab) (syntax/loc stx (let* ([ret-lab-id 'ret-lab-id] [a.ref a.var] ... [r.ref r.var]) (let-syntax ([a.x (P-expander (syntax-parser [_ #'a.ref]))] ...) (let-values ([(the-post the-body) (let-syntax ([r.x (P-expander (syntax-parser [_ #'r.ref]))]) (syntax-parameterize ([current-return-var (make-rename-transformer #'r.x)]) ;; DESIGN: If the return variable is synthesized, ;; then the post condition COULD look at it via ;; current-return-var, which is a really ugly ;; name. Maybe we name it something better? ;; Alternatively, maybe we want it to be illegal ;; for the post condition to refer to the result ;; in this case, so the user has to specify a ;; name? (values (E post) (let ([the-ret (Jump ret-lab-id)]) (let-syntax ([ret-lab (S-expander (syntax-parser [(_) #'the-ret]))]) (syntax-parameterize ([current-return (make-rename-transformer #'the-ret)] [S-in-tail? #t]) XXX Make ANF the default here (F-body-default (begin . bs))))))))]) (MetaFun ;; XXX use struct (vector 'fun-invariants (E pre) the-post) (IntFun (list a.arg ...) (Var-x r.ref) (Var-ty r.ref) ret-lab-id the-body))))))]))) (define-simple-macro (F+ . more) (syntax-parameterize ([F-body-default (make-rename-transformer #'S+)]) (F . more))) (define (apply-union-ctor-init stx ty m i) (unless (UniT? ty) (raise-syntax-error #f "union syntax used for non-union type" stx)) (I (union #,m #,i))) (define (apply-ctor-inits stx ty is) (match ty [(? ArrT?) (I (array #,@is))] [(RecT _ _ c-order) (unless (= (length c-order) (length is)) (raise-syntax-error #f "constructor arity mismatch" stx)) (I (record #,@(map cons c-order is)))] [_ (raise-syntax-error #f "invalid constructor syntax" stx)])) (begin-for-syntax (struct T/I-expander (T-impl I-impl) #:property prop:procedure (struct-field-index T-impl) #:methods gen:T-expander [(define (T-expand this stx) ((T/I-expander-T-impl this) stx))] #:methods gen:I-expander [(define (I-expand this stx) ((T/I-expander-I-impl this) stx))]) (define (make-type-binding ty-stx) (T/I-expander (syntax-parser [_ (quasisyntax/loc this-syntax #,ty-stx)]) (syntax-parser [(_ m:keyword ~! i:expr) (quasisyntax/loc this-syntax (apply-union-ctor-init #'#,this-syntax #,ty-stx (keyword->symbol 'm) (I i)))] [(_ i:expr ...) (quasisyntax/loc this-syntax (apply-ctor-inits #'#,this-syntax #,ty-stx (list (I i) ...)))])))) (define-syntax (define-type stx) (syntax-parse stx [(_ #:public name:id ty) #:fail-unless (syntax-parameter-value #'current-Prog) "Cannot define public type outside of Prog" (syntax/loc stx (begin (define-type name ty) (include-type name)))] [(_ name:id ty) (syntax/loc stx (begin (define the-ty (T ty)) (define-syntax name (make-type-binding #'the-ty))))])) (define-syntax (include-type stx) (with-disappeared-uses (syntax-parse stx [(_ #:maybe n:expr ty:expr) (if (syntax-parameter-value #'current-Prog) (syntax/loc stx (hash-set! (Program-name->ty current-Prog) n ty)) #'(void))] [(_ n:expr ty:expr) #:fail-unless (syntax-parameter-value #'current-Prog) "Cannot include type outside of Prog" (syntax/loc stx (include-type #:maybe n ty))] [(_ x:id) (syntax/loc stx (include-type (symbol->c-name 'x) x))] [(_ #:maybe x:id) (syntax/loc stx (include-type #:maybe (symbol->c-name 'x) x))]))) (define-syntax (define-extern-type stx) (with-disappeared-uses (syntax-parse stx [(_ x:id (~optional (~seq #:name name:expr) #:defaults ([name #'(symbol->c-name 'x)])) (~optional (~seq #:src es:expr) #:defaults ([es #'(ExternSrc '() '())]))) #:with the-ext (generate-temporary #'x) (syntax/loc stx (begin (define the-ext (ExtT es name)) (define-syntax x (T-expander (syntax-parser [_ #'the-ext])))))]))) (define-syntax (include-fun stx) (with-disappeared-uses (syntax-parse stx [(_ #:maybe n:expr f:expr) (if (syntax-parameter-value #'current-Prog) (syntax/loc stx (hash-set! (Program-name->fun current-Prog) n f)) #'(void))] [(_ n:expr f:expr) #:fail-unless (syntax-parameter-value #'current-Prog) "Cannot include function outside of Prog" (syntax/loc stx (include-fun #:maybe n f))] [(_ x:id) (syntax/loc stx (include-fun (symbol->c-name 'x) x))] [(_ #:maybe x:id) (syntax/loc stx (include-fun #:maybe (symbol->c-name 'x) x))]))) (define-syntax (define-fun stx) (with-disappeared-uses (syntax-parse stx [(_ ret-ty x:id #:as n:expr (args ...) . more) (syntax/loc stx (begin (define the-fun (give-name (F ret-ty (args ...) . more) 'x)) (define-syntax x (F-expander (syntax-parser [_ #'the-fun]))) (include-fun #:maybe n x)))] [(_ ret-ty x:id (args ...) . more) (syntax/loc stx (define-fun ret-ty x #:as (symbol->c-name 'x) (args ...) . more))]))) (define-syntax (define-fun+ stx) (with-disappeared-uses (syntax-parse stx [(_ ret-ty x:id #:as n:expr (args ...) . more) (syntax/loc stx (begin (define the-fun (give-name (F+ ret-ty (args ...) . more) 'x)) (define-syntax x (F-expander (syntax-parser [_ #'the-fun]))) (include-fun #:maybe n x)))] [(_ ret-ty x:id (args ...) . more) (syntax/loc stx (define-fun+ ret-ty x #:as (symbol->c-name 'x) (args ...) . more))]))) (define-syntax (define-extern-fun stx) (with-disappeared-uses (syntax-parse stx [(_ ret-ty x:id (~optional (~seq #:name name:expr) #:defaults ([name #'(symbol->c-name 'x)])) (a:Farg ...) #:src es:expr) (syntax/loc stx (begin (define the-fun (ExtFun es (let ([a.ref a.var] ...) (list a.arg ...)) (T ret-ty) name)) (define-syntax x (F-expander (syntax-parser [_ #'the-fun])))))]))) (define-syntax (define-global stx) (with-disappeared-uses (syntax-parse stx #:literals (unsyntax) [(_ #:public name:id . more) #:fail-unless (syntax-parameter-value #'current-Prog) "Cannot define public global outside of Prog" (syntax/loc stx (begin (define-global name . more) (include-global name)))] ;; T/I expander [(_ x:id (~datum :=) (~and ctor-use (ctor-id . _))) #:declare ctor-id (static (and/c T-expander? I-expander?) "T/I expander") (syntax/loc stx (define-global x : ctor-id := ctor-use))] ;; implicit type from expr initialization [(_ x:id (~datum :=) e) (syntax/loc stx (begin (define the-e (E e)) (define e-ty (expr-type the-e)) (define the-glob (give-name (Global e-ty (ConI the-e)) 'x)) (define-syntax x (P-expander (syntax-parser [_ #'the-glob])))))] ;; fully annonated [(_ x:id (~datum :) ty (~datum :=) xi) (syntax/loc stx (begin (define the-ty (T ty)) (define the-init (syntax-parameterize ([expect-ty #'the-ty]) (I xi))) (define the-glob (give-name (Global the-ty the-init) 'x)) (define-syntax x (P-expander (syntax-parser [_ #'the-glob])))))] ;; uninitialied variable [(_ x:id (~datum :) ty) (syntax/loc stx (begin (define the-ty (T ty)) (define-global x : #,the-ty := (undef #,the-ty))))]))) (define-syntax (include-global stx) (with-disappeared-uses (syntax-parse stx [(_ #:maybe n:expr g:expr) (if (syntax-parameter-value #'current-Prog) (syntax/loc stx (hash-set! (Program-name->global current-Prog) n g)) #'(void))] [(_ n:expr g:expr) #:fail-unless (syntax-parameter-value #'current-Prog) "Cannot include global outside of Prog" (syntax/loc stx (include-global #:maybe n g))] [(_ x:id) (syntax/loc stx (include-global (symbol->c-name 'x) x))] [(_ #:maybe x:id) (syntax/loc stx (include-global #:maybe (symbol->c-name 'x) x))]))) (define (symbol->c-name x) (string-replace (symbol->string x) "-" "_")) (define-syntax-parameter current-Prog #f) (define-syntax (Prog stx) (with-disappeared-uses (syntax-parse stx [(_ pf ...) (syntax/loc stx (let ([the-prog (Program (make-hash) (make-hash) (make-hash))]) (syntax-parameterize ([current-Prog (make-rename-transformer #'the-prog)]) pf ... (void)) the-prog))]))) (begin-for-syntax (define-literal-set def-forms #:datum-literals ( define-type define-fun define-fun+ define-global define-extern-fun define-extern-type include-fun include-type include-global) ()) (define def-form? (literal-set->predicate def-forms))) ;; XXX Use let-syntaxes to handle multiple return values ;; from partition, instead of let-values? ;; XXX Should inline function definitions be public? (define-syntax (Prog* stx) (with-disappeared-uses (syntax-parse stx [(_ pf ...) #:with ((def ...) (non ...)) (let-values ([(defs nons) (partition (syntax-parser [(x:id . _) #:when (def-form? #'x) #t] [_ #f]) (syntax->list #'(pf ...)))]) (list defs nons)) (syntax/loc stx (Prog def ... (define-fun S32 main () non ... (return 0))))]))) (define-simple-macro (define-prog name:id pf ...+) (define name (Prog pf ...))) (define-simple-macro (define-prog* name:id pf ...) (define name (Prog* pf ...))) (provide while assert! return F-body-default define-type define-fun define-fun+ define-global define-extern-fun define-extern-type include-fun include-type include-global Prog Prog* define-prog define-prog*) (define-runtime-path util-path "util.h") (define util-h (ExternSrc '() (list (path->string util-path)))) (define-extern-type char*) (define-extern-fun S32 c-print-string #:name "print_string" ([char* str] [S32 n]) #:src util-h) (define (print-string s) (define bs (string->bytes/utf-8 s)) (define init (I (array #,@(for/list ([b (in-bytes bs)]) (I (U8 b)))))) (define len (bytes-length bs)) (S (let* ([str-x : (array len U8) := #,init] [ret-x := (c-print-string (str-x : #,char*) (S32 len))]) (void)))) (define printers (make-weak-hash)) (define array-printers (make-weak-hash)) (define (get-printer ty) (define (new-printer!) (define print-fn (match ty ;; XXX UniT, ExtT (?) [(RecT _ _ c-order) (F S32 ([#,ty rec]) (print "{") #,(let loop ([f (first c-order)] [fs (rest c-order)]) (cond [(empty? fs) (S (print #,(Read (Field (P rec) f))))] [else (S (begin (print #,(Read (Field (P rec) f)) ", ") #,(loop (first fs) (rest fs))))])) (print "}") (return 0))])) (define value (make-ephemeron ty print-fn)) (hash-set! printers ty value) value) (define (new-array-printer!) (define ety (ArrT-ety ty)) (define print-fn (F S32 ([#,ty arr] [U64 count]) (let ([i : U64 := (U64 0)]) (print "[") (while (< i count) (print (arr @ i)) (define next : U64 := (add1 i)) (when (< next count) (print ", ")) (set! i next)) (print "]") (return 0)))) (define value (make-ephemeron ety print-fn)) (hash-set! array-printers ety value) value) (match ty ' ephemeron - value ' may produce # f if the key was GC'd between our call to ' hash - ref ' and ' ephemeron - value ' . In this case , we call ;; 'new-*-printer' directly, and we know that the subsequent call to ' ephemeron - value ' can not produce # f because the key is used ;; within this function (and thus will not be GC'd). [(ArrT _ ety) (or (ephemeron-value (hash-ref array-printers ety new-array-printer!)) (ephemeron-value (new-array-printer!)))] [_ (or (ephemeron-value (hash-ref printers ty new-printer!)) (ephemeron-value (new-printer!)))])) (define (print-expr the-e) (define e-ty (expr-type the-e)) (define printer (cond [(or (IntT? e-ty) (FloT? e-ty)) (define fn-name (match e-ty [(FloT 32) "print_F32"] [(FloT 64) "print_F64"] [(IntT signed? bits) (if signed? (match bits [8 "print_S8"] [16 "print_S16"] [32 "print_S32"] [64 "print_S64"]) (match bits [8 "print_U8"] [16 "print_U16"] [32 "print_U32"] [64 "print_U64"]))])) (ExtFun util-h (list (Arg 'n e-ty 'read-only)) (T S32) fn-name)] [else (get-printer e-ty)])) (match e-ty [(ArrT dim _) (S (let ([ret-x := printer <- #,the-e (U64 dim)]) (void)))] [_ (S (let ([ret-x := printer <- #,the-e]) (void)))])) (define-S-free-syntax print (syntax-parser #:literals (unsyntax) [(_ e es ...+) (syntax/loc this-syntax (S (begin (print e) (print es ...))))] [(_ (unsyntax exp-or-str)) (syntax/loc this-syntax (match exp-or-str [(? string? s) (print-string s)] [(? Expr? the-e) (print-expr the-e)]))] [(_ s:str) (syntax/loc this-syntax (print-string s))] [(_ e) (syntax/loc this-syntax (print-expr (E e)))])) (define-S-free-syntax println (syntax-parser [(_ es ... e:str) (syntax/loc this-syntax (S (print es ... #,(string-append e "\n"))))] [(_ es ...) (syntax/loc this-syntax (S (print es ... "\n")))])) (define-A-free-syntax print (syntax-parser [(_ a as ...+) (syntax/loc this-syntax (ANF (begin (print a) (print as ...))))] [(_ s:str) #:with x-id (generate-temporary 'tmp) (syntax/loc this-syntax (let* ([x-id 'x-id] [the-x-ref (Var x-id (T void))]) (values (list (anf-void the-x-ref (S (print s)))) (Read the-x-ref))))] [(_ a) #:with x-id (generate-temporary 'tmp) (syntax/loc this-syntax (let-values ([(a-nv a-arg) (ANF a)]) (define x-id 'x-id) (define the-x-ref (Var x-id (T void))) (define the-stmt (S (print #,a-arg))) (values (snoc a-nv (anf-void the-x-ref the-stmt)) (Read the-x-ref))))])) (define-A-free-syntax println (syntax-parser [(_ as ...) (syntax/loc this-syntax (ANF (begin (print as ...) (print "\n"))))])) (provide T P N E I F F+ S S+) ;; XXX Array Slice ;; XXX data types XXX try using --
null
https://raw.githubusercontent.com/jeapostrophe/adqc/59030f17f603356786a2cf19b78e54ccb1181848/stx.rkt
racket
XXX This module should use plus not ast (i.e. the thing that does type checking, termination checking, and resource analysis). And plus should have an "any" type that causes inference, and that should be supported here. XXX Should these macros record the src location in the data structure some how? (perhaps plus should do that with meta?) XXX should array, record, and union be literals? XXX syntax for choosing C stuff XXX smarter defaults XXX syntax for choosing C stuff XXX smarter defaults XXX Maybe these are contract or range exceptions, not syntax errors? XXX Should resulting expression be freenum if both type is integral) XXX This code could examine the actual values of constant expressions so it could be even more permissive, allowing because signed values can never be implicitly cast to unsigned. XXX define is not getting bound let with T/I expander let with function call from F-expander let with full type annotation let with uninitialized variable let with function call XXX use struct XXX use struct Note: behavior of C's != operator is unordered for floats DESIGN: If the return variable is synthesized, then the post condition COULD look at it via current-return-var, which is a really ugly name. Maybe we name it something better? Alternatively, maybe we want it to be illegal for the post condition to refer to the result in this case, so the user has to specify a name? XXX use struct T/I expander implicit type from expr initialization fully annonated uninitialied variable XXX Use let-syntaxes to handle multiple return values from partition, instead of let-values? XXX Should inline function definitions be public? XXX UniT, ExtT (?) 'new-*-printer' directly, and we know that the subsequent call within this function (and thus will not be GC'd). XXX Array Slice XXX data types
#lang racket/base (require (for-syntax racket/base racket/contract/base racket/dict racket/generic racket/list racket/syntax syntax/id-table) racket/contract/base racket/list racket/match racket/require racket/runtime-path racket/string racket/stxparam syntax/parse/define (subtract-in "ast.rkt" "type.rkt") "type.rkt" "util.rkt") XXX Use remix for # % dot and # % braces (define (keyword->symbol kw) (string->symbol (keyword->string kw))) (define-syntax (define-expanders&macros stx) (syntax-parse stx [(_ S-free-macros define-S-free-syntax S-expander S-expand define-S-expander define-simple-S-expander) #:with expander-struct (generate-temporary #'S-expander) #:with gen-S-expander (format-id #'S-expander "gen:~a" #'S-expander) (syntax/loc stx (begin (begin-for-syntax (define S-free-macros (make-free-id-table)) (define-generics S-expander [S-expand S-expander stx]) (struct expander-struct (impl) #:extra-constructor-name S-expander #:property prop:procedure (struct-field-index impl) #:methods gen-S-expander [(define (S-expand this stx*) (this stx*))])) (define-simple-macro (define-S-free-syntax id impl) (begin-for-syntax (dict-set! S-free-macros #'id impl))) (define-simple-macro (define-S-expander id impl) (define-syntax id (expander-struct impl))) (define-simple-macro (define-simple-S-expander (id . args) body) (define-S-expander id (syntax-parser [(_ . args) (syntax/loc this-syntax body)]))) (provide define-S-free-syntax define-S-expander define-simple-S-expander)))])) (define-expanders&macros T-free-macros define-T-free-syntax T-expander T-expand define-T-expander define-simple-T-expander) (define-syntax (T stx) (with-disappeared-uses (syntax-parse stx #:literals (unsyntax unsyntax-splicing) [(_ ((~datum array) dim elem)) (syntax/loc stx (ArrT dim (T elem)))] [(_ ((~datum record) (~or (unsyntax-splicing ps) (~and (~seq (~seq f:id ft) ...) (~bind [ps #'(list (cons 'f (T ft)) ...)]))))) (syntax/loc stx (RecT (make-immutable-hasheq ps) (make-immutable-hasheq (for/list ([p (in-list ps)]) (cons (car p) (cify (car p))))) (map car ps)))] [(_ ((~datum union) (~or (unsyntax-splicing ps) (~and (~seq (~seq m:id mt) ...) (~bind [ps #'(list (cons 'm (T mt)) ...)]))))) (syntax/loc stx (UniT (make-immutable-hash ps) (make-immutable-hash (for/list ([p (in-list ps)]) (cons (car p) (cify (car p)))))))] [(_ (~and macro-use (~or macro-id:id (macro-id:id . _)))) #:when (dict-has-key? T-free-macros #'macro-id) (record-disappeared-uses #'macro-id) ((dict-ref T-free-macros #'macro-id) #'macro-use)] [(_ (~and macro-use (~or macro-id (macro-id . _)))) #:declare macro-id (static T-expander? "T expander") (record-disappeared-uses #'macro-id) (T-expand (attribute macro-id.value) #'macro-use)] [(_ (unsyntax e)) (record-disappeared-uses #'unsyntax) #'e]))) (define the-void-ref (VoiT)) (define-T-free-syntax void (syntax-parser [_ #'the-void-ref])) (define the-any-ref (AnyT)) (define-T-free-syntax any (syntax-parser [_ #'the-any-ref])) (define-expanders&macros P-free-macros define-P-free-syntax P-expander P-expand define-P-expander define-simple-P-expander) (define-syntax (P stx) (with-disappeared-uses (syntax-parse stx #:literals (unsyntax) [(_ (p ... (~datum @) e)) (syntax/loc stx (Select (P (p ...)) (E e)))] [(_ (p ... (~datum ->) f:id)) (syntax/loc stx (Field (P (p ...)) 'f))] [(_ (p ... (~datum as) m:id)) (syntax/loc stx (Mode (P (p ...)) 'm))] [(_ (unsyntax e)) (record-disappeared-uses #'unsyntax) #'e] [(_ (~and macro-use (~or macro-id:id (macro-id:id . _)))) #:when (dict-has-key? P-free-macros #'macro-id) (record-disappeared-uses #'macro-id) ((dict-ref P-free-macros #'macro-id) #'macro-use)] [(_ (~and macro-use (~or macro-id (macro-id . _)))) #:declare macro-id (static P-expander? "P expander") (record-disappeared-uses #'macro-id) (P-expand (attribute macro-id.value) #'macro-use)] [(_ x:id) #'x] [(_ (x:id)) #'x]))) freenums can be implicitly cast to a larger type by BinOp (struct freenum-tag ()) (define freenum! (freenum-tag)) (define (freenum? e) (match e [(MetaE (== freenum!) _) #t] [(MetaE _ e) (freenum? e)] [(? Expr?) #f])) (define (freenum e) (MetaE freenum! e)) (define (construct-number stx ty n) (define (report fmt . vs) (raise-syntax-error #f (apply format fmt vs) stx)) (match ty [(IntT signed? bits) (define prefix (if signed? #\S #\U)) (when (< n (if signed? (- (expt 2 (sub1 bits))) 0)) (report "integer value ~a too small for ~a~a" n prefix bits)) (when (> n (sub1 (expt 2 (if signed? (sub1 bits) bits)))) (report "integer value ~a too large for ~a~a" n prefix bits)) (Int signed? bits n)] [(FloT bits) (define val (match bits [32 (real->single-flonum n)] [64 (real->double-flonum n)])) (Flo bits val)] [#f (cond [(single-flonum? n) (freenum (Flo 32 n))] [(double-flonum? n) (freenum (Flo 64 n))] [(exact-integer? n) (define 2^7 (expt 2 7)) (define 2^15 (expt 2 15)) (define 2^31 (expt 2 31)) (define 2^63 (expt 2 63)) (unless (and (< n (expt 2 64)) (>= n (- 2^63))) (report "~a is too large to fit in 64 bits" n)) (define unsigned? (>= n 2^63)) (define bits (cond [(and (< n 2^7) (>= n (- 2^7))) 8] [(and (< n 2^15) (>= n (- 2^15))) 16] [(and (< n 2^31) (>= n (- 2^31))) 32] [else 64])) (freenum (Int (not unsigned?) bits n))])])) (define-syntax-parameter expect-ty #f) (define-syntax (N stx) (syntax-parse stx [(_ n) #:with ty (or (syntax-parameter-value #'expect-ty) #'#f) (syntax/loc stx (N ty n))] [(_ ty n) (quasisyntax/loc stx (construct-number #'#,stx ty n))])) (define-expanders&macros E-free-macros define-E-free-syntax E-expander E-expand define-E-expander define-simple-E-expander) (begin-for-syntax (define-literal-set E-bin-op #:datum-literals ( iadd isub imul isdiv iudiv isrem iurem ishl ilshr iashr ior iand ixor ieq ine iugt isgt iuge isge iult islt iule isle fadd fsub fmul fdiv frem foeq fogt foge folt fole fone fueq fugt fuge fult fule fune ffalse ftrue ford funo) ()) (define E-bin-op? (literal-set->predicate E-bin-op))) (define (Let*E xs tys xes be) (cond [(empty? xs) be] [else (LetE (first xs) (first tys) (first xes) (Let*E (rest xs) (rest tys) (rest xes) be))])) (define (implicit-castable? to from) (match-define (IntT to-signed? to-bits) to) (match-define (IntT from-signed? from-bits) from) (cond [(and from-signed? (not to-signed?)) #f] [else (> to-bits from-bits)])) (define (make-binop op the-lhs the-rhs) (define l-ty (expr-type the-lhs)) (define r-ty (expr-type the-rhs)) lhs and rhs are freenum ? ( If so , only when return e.g. for ( < ( U32 some - val ) 0 ) , which right now fails (cond [(and (freenum? the-lhs) (implicit-castable? r-ty l-ty)) (BinOp op (Cast r-ty the-lhs) the-rhs)] [(and (freenum? the-rhs) (implicit-castable? l-ty r-ty)) (BinOp op the-lhs (Cast l-ty the-rhs))] [else (BinOp op the-lhs the-rhs)])) (define-syntax (E stx) (with-disappeared-uses (syntax-parse stx #:literals (if let unsyntax) [(_ (op:id l r)) #:when (E-bin-op? #'op) (syntax/loc stx (make-binop 'op (E l) (E r)))] [(_ (e (~datum :) ty)) (syntax/loc stx (Cast (T ty) (E e)))] [(_ (let ([x (~datum :) xty (~datum :=) xe] ...) be)) #:with (x-id ...) (generate-temporaries #'(x ...)) #:with (the-ty ...) (generate-temporaries #'(xty ...)) (record-disappeared-uses #'let) (syntax/loc stx (let ([x-id 'x-id] ... [the-ty (T xty)] ...) (Let*E (list x-id ...) (list the-ty ...) (list (syntax-parameterize ([expect-ty #'the-ty]) (E xe)) ...) (let ([the-x-ref (Var x-id the-ty)] ...) (let-syntax ([x (P-expander (syntax-parser [_ #'the-x-ref]))] ...) (E be))))))] [(_ (let ([x (~datum :=) xe] ...) be)) #:with (x-id ...) (generate-temporaries #'(x ...)) #:with (the-ty ...) (generate-temporaries #'(x ...)) #:with (the-xe ...) (generate-temporaries #'(xe ...)) (record-disappeared-uses #'let) (syntax/loc stx (let* ([x-id 'x-id] ... [the-xe (E xe)] ... [the-ty (expr-type the-xe)] ...) (Let*E (list x-id ...) (list the-ty ...) (list the-xe ...) (let ([the-x-ref (Var x-id the-ty)] ...) (let-syntax ([x (P-expander (syntax-parser [_ #'the-x-ref]))] ...) (E be))))))] [(_ (if c t f)) (record-disappeared-uses #'if) (syntax/loc stx (IfE (E c) (E t) (E f)))] [(_ (~and macro-use (~or macro-id:id (macro-id:id . _)))) #:when (dict-has-key? E-free-macros #'macro-id) (record-disappeared-uses #'macro-id) ((dict-ref E-free-macros #'macro-id) #'macro-use)] [(_ (~and macro-use (~or macro-id (macro-id . _)))) #:declare macro-id (static E-expander? "E expander") (record-disappeared-uses #'macro-id) (E-expand (attribute macro-id.value) #'macro-use)] [(_ (unsyntax e)) (record-disappeared-uses #'unsyntax) #'e] [(_ n:number) (syntax/loc stx (N n))] [(_ p) (quasisyntax/loc stx (Read #,(syntax/loc #'p (P p))))]))) (define-E-free-syntax cond (syntax-parser #:literals (else) [(_ [else e]) (syntax/loc this-syntax (E e))] [(_ [q a] . more) (syntax/loc this-syntax (E (if q a (cond . more))))])) (define-E-free-syntax and (syntax-parser [(_) (syntax/loc this-syntax (N 1))] [(_ e) (syntax/loc this-syntax (E e))] [(_ e es ...) (syntax/loc this-syntax (let* ([the-e (E e)] [e-ty (expr-type the-e)]) (IfE the-e (syntax-parameterize ([expect-ty #'e-ty]) (E (and es ...))) (N e-ty 0))))])) (define-E-free-syntax or (syntax-parser [(_) (syntax/loc this-syntax (N 0))] [(_ e) (syntax/loc this-syntax (E e))] [(_ e es ...) (syntax/loc this-syntax (let* ([the-e (E e)] [e-ty (expr-type the-e)]) (IfE the-e the-e (syntax-parameterize ([expect-ty #'e-ty]) (E (or es ...))))))])) (define (not* the-e) (define e-ty (expr-type the-e)) (define one (match e-ty [(? IntT?) 1] [(FloT 32) 1.0f0] [(FloT 64) 1.0])) (E (bitwise-xor #,the-e #,(N e-ty one)))) (define-E-free-syntax not (syntax-parser [(_ e) (syntax/loc this-syntax (not* (E e)))])) (define-E-free-syntax let* (syntax-parser [(_ () e) (syntax/loc this-syntax (E e))] [(_ (f r ...) e) (syntax/loc this-syntax (E (let (f) (let* (r ...) e))))])) (define (zero?* the-e) (define e-ty (expr-type the-e)) (define zero (match e-ty [(? IntT?) 0] [(FloT 32) 0.0f0] [(FloT 64) 0.0])) (E (= #,the-e #,(N e-ty zero)))) (define-E-free-syntax zero? (syntax-parser [(_ e) (syntax/loc this-syntax (zero?* (E e)))])) (define-E-free-syntax min (syntax-parser [(_ a b) (syntax/loc this-syntax (E (if (< a b) a b)))])) (define-E-free-syntax max (syntax-parser [(_ a b) (syntax/loc this-syntax (E (if (< a b) b a)))])) (define-syntax (define-E-increment-ops stx) (syntax-parse stx [(_ [name:id op:id] ...+) #:with (name^ ...) (generate-temporaries #'(name ...)) (syntax/loc stx (begin (begin (define (name^ the-e) (define e-ty (expr-type the-e)) (define one (match e-ty [(? IntT?) 1] [(FloT 32) 1.0f0] [(FloT 64) 1.0])) (E (op #,the-e #,(N e-ty one)))) (define-E-free-syntax name (syntax-parser [(_ e) (syntax/loc this-syntax (name^ (E e)))]))) ...))])) (define-E-increment-ops [add1 +] [sub1 -]) (define (subtract the-lhs the-rhs) (match (expr-type the-lhs) [(? IntT?) (E (isub #,the-lhs #,the-rhs))] [(? FloT?) (E (fsub #,the-lhs #,the-rhs))])) (define (negate the-e) (define e-ty (expr-type the-e)) (define zero (match e-ty [(? IntT?) 0] [(FloT 32) 0.0f0] [(FloT 64) 0.0])) (subtract (N e-ty zero) the-e)) (define-E-free-syntax - (syntax-parser [(_ e) (syntax/loc this-syntax (negate (E e)))] [(_ l r) (syntax/loc this-syntax (subtract (E l) (E r)))])) (define-syntax (define-free-binop stx) (syntax-parse stx [(_ name:id [match-clause op:id] ...+) #:with name^ (generate-temporary #'name) (syntax/loc stx (begin (define (name^ the-lhs the-rhs) (match (expr-type the-lhs) [match-clause (E (op #,the-lhs #,the-rhs))] ...)) (define-E-free-syntax name (syntax-parser [(_ l r) (syntax/loc this-syntax (name^ (E l) (E r)))]))))])) (define-free-binop + [(? IntT?) iadd] [(? FloT?) fadd]) (define-free-binop * [(? IntT?) imul] [(? FloT?) fmul]) (define-free-binop / [(IntT #t _) isdiv] [(IntT #f _) iudiv] [(? FloT?) fdiv]) (define-free-binop modulo [(IntT #t _) isrem] [(IntT #f _) iurem] [(? FloT?) frem]) (define-free-binop bitwise-ior [(? IntT?) ior]) (define-free-binop bitwise-and [(? IntT?) iand]) (define-free-binop bitwise-xor [(? IntT?) ixor]) (define-free-binop = [(? IntT?) ieq] [(? FloT?) foeq]) (define-free-binop < [(IntT #t _) islt] [(IntT #f _) iult] [(? FloT?) folt]) (define-free-binop <= [(IntT #t _) isle] [(IntT #f _) iule] [(? FloT?) fole]) (define-free-binop > [(IntT #t _) isgt] [(IntT #f _) iugt] [(? FloT?) fogt]) (define-free-binop >= [(IntT #t _) isge] [(IntT #f _) iuge] [(? FloT?) foge]) (begin-for-syntax (struct T/E-expander (T-impl E-impl) #:property prop:procedure (λ (this stx) (raise-syntax-error #f "Illegal outside T or E" stx)) #:methods gen:T-expander [(define (T-expand this stx) ((T/E-expander-T-impl this) stx))] #:methods gen:E-expander [(define (E-expand this stx) ((T/E-expander-E-impl this) stx))])) (define-simple-macro (define-flo-stx [name:id bits] ...) (begin (define-syntax name (T/E-expander (syntax-parser [_:id (record-disappeared-uses #'name) (syntax/loc this-syntax (FloT bits))]) (syntax-parser [(_ n:expr) (record-disappeared-uses #'name) (quasisyntax/loc this-syntax (construct-number #'#,this-syntax (FloT bits) n))]))) ... (provide name ...))) (define-flo-stx [F32 32] [F64 64]) (define-simple-macro (define-int-stx [name:id signed? bits] ...) (begin (define-syntax name (T/E-expander (syntax-parser [_:id (record-disappeared-uses #'name) (syntax/loc this-syntax (IntT signed? bits))]) (syntax-parser [(_ n:expr) (record-disappeared-uses #'name) (quasisyntax/loc this-syntax (construct-number #'#,this-syntax (IntT signed? bits) n))]))) ... (provide name ...))) (define-int-stx [S8 #t 8] [S16 #t 16] [S32 #t 32] [S64 #t 64] [U8 #f 8] [U16 #f 16] [U32 #f 32] [U64 #f 64]) (define-expanders&macros I-free-macros define-I-free-syntax I-expander I-expand define-I-expander define-simple-I-expander) XXX should undef , zero , array , record , and union be literals ? (define-syntax (I stx) (with-disappeared-uses (syntax-parse stx #:literals (unsyntax unsyntax-splicing) [(_ ((~datum undef) ty)) (syntax/loc stx (UndI (T ty)))] [(_ ((~datum zero) ty)) (syntax/loc stx (ZedI (T ty)))] [(_ ((~datum array) (~or (unsyntax-splicing is) (~and (~seq i ...) (~bind [is #'(list (I i) ...)]))))) (syntax/loc stx (ArrI is))] [(_ ((~datum record) (~or (unsyntax-splicing ps) (~and (~seq (~seq k:id i) ...) (~bind [ps #'(list (cons 'k (I i)) ...)]))))) (syntax/loc stx (RecI (make-immutable-hasheq ps)))] [(_ ((~datum union) (~or (unsyntax m-id) (~and m:id (~bind [m-id #''m]))) i)) (syntax/loc stx (UniI m-id (I i)))] [(_ (~and macro-use (~or macro-id:id (macro-id:id . _)))) #:when (dict-has-key? I-free-macros #'macro-id) (record-disappeared-uses #'macro-id) ((dict-ref I-free-macros #'macro-id) #'macro-use)] [(_ (~and macro-use (~or macro-id (macro-id . _)))) #:declare macro-id (static I-expander? "I expander") (record-disappeared-uses #'macro-id) (I-expand (attribute macro-id.value) #'macro-use)] [(_ (unsyntax e)) (record-disappeared-uses #'unsyntax) #'e] [(_ x) (syntax/loc stx (ConI (E x)))]))) (begin-for-syntax (struct F-expander (impl) #:property prop:procedure (struct-field-index impl))) (define-syntax-parameter current-return #f) (define-syntax-parameter current-return-var #f) (define-syntax-parameter S-in-tail? #f) (define-expanders&macros S-free-macros define-S-free-syntax S-expander S-expand define-S-expander define-simple-S-expander) (define-syntax (S stx) (with-disappeared-uses (syntax-parse stx #:literals (void error begin define set! if let/ec let unsyntax unsyntax-splicing) [(_ (void)) (record-disappeared-uses #'void) (syntax/loc stx (Skip #f))] [(_ (void ~! m)) (record-disappeared-uses #'void) (syntax/loc stx (Skip m))] [(_ (error ~! m)) (record-disappeared-uses #'error) (syntax/loc stx (Fail m))] [(_ (begin)) (record-disappeared-uses #'begin) (syntax/loc stx (S (void)))] [(_ (begin (define . d) . b)) (record-disappeared-uses (list #'begin #'define)) (syntax/loc stx (S (let (d) . b)))] [(_ (begin s)) (record-disappeared-uses #'begin) (syntax/loc stx (S s))] [(_ (begin ~! a . d)) (record-disappeared-uses #'begin) (syntax/loc stx (Begin (syntax-parameterize ([S-in-tail? #f]) (S a)) (S (begin . d))))] [(_ (set! ~! p e)) (record-disappeared-uses #'set!) (syntax/loc stx (let* ([the-p (P p)] [p-ty (path-type the-p)]) (Assign the-p (syntax-parameterize ([expect-ty #'p-ty]) (E e)))))] [(_ {p (~datum <-) e}) (syntax/loc stx (S (set! p e)))] [(_ (if ~! p t f)) (record-disappeared-uses #'if) (syntax/loc stx (If (E p) (S t) (S f)))] [(_ (let/ec ~! k:id . b)) #:with k-id (generate-temporary #'k) (record-disappeared-uses #'let/ec) (syntax/loc stx (let ([k-id 'k-id]) (Let/ec k-id (let ([the-ret (Jump k-id)]) (let-syntax ([k (S-expander (syntax-parser [(_) #'the-ret]))]) (S (begin . b)))))))] [(_ (let ([x:id (~datum :=) (~and ctor-use (ctor-id . _))]) . b)) #:declare ctor-id (static (and/c T-expander? I-expander?) "T/I expander") (record-disappeared-uses #'let) (syntax/loc stx (S (let ([x : ctor-id := ctor-use]) . b)))] [(_ (let ([x:id (~optional (~seq (~datum :) ty) #:defaults ([ty #'#f])) (~datum :=) (fun-id . fun-args)]) . b)) #:declare fun-id (static F-expander? "F expander") #:with ty* (if (syntax->datum #'ty) #'(T ty) #'(Fun-ret-ty fun-id)) (record-disappeared-uses (list #'let #'fun-id)) (syntax/loc stx (S (let ([x : #,ty* := fun-id <- . fun-args]) . b)))] let with implicit type from expr initializaiton [(_ (let ([x:id (~datum :=) e]) . b)) #:with x-id (generate-temporary #'x) (record-disappeared-uses #'let) (syntax/loc stx (let* ([x-id 'x-id] [the-e (E e)] [the-ty (expr-type the-e)]) (Let x-id the-ty (ConI the-e) (let ([the-x-ref (Var x-id the-ty)]) (let-syntax ([x (P-expander (syntax-parser [_ #'the-x-ref]))]) (S (begin . b)))))))] [(_ (let ([x:id (~datum :) ty (~datum :=) xi]) . b)) #:with x-id (generate-temporary #'x) (record-disappeared-uses #'let) (syntax/loc stx (let ([x-id 'x-id] [the-ty (T ty)]) (Let x-id the-ty (syntax-parameterize ([expect-ty #'the-ty]) (I xi)) (let ([the-x-ref (Var x-id the-ty)]) (let-syntax ([x (P-expander (syntax-parser [_ #'the-x-ref]))]) (S (begin . b)))))))] [(_ (let ([x:id (~datum :) ty]) . b)) (record-disappeared-uses #'let) (syntax/loc stx (let ([the-ty (T ty)]) (S (let ([x : #,the-ty := (undef #,the-ty)]) . b))))] [(_ (let ([x:id (~optional (~seq (~datum :) ty) #:defaults ([ty #'#f])) (~datum :=) f (~datum <-) (~or (unsyntax-splicing as) (~and (~seq a ...) (~bind [as #'(list (E a) ...)])))]) . b)) #:with x-id (generate-temporary #'x) #:with ty* (if (syntax->datum #'ty) #'(T ty) #'(Fun-ret-ty f)) (record-disappeared-uses #'let) (syntax/loc stx (let ([x-id 'x-id] [the-ty ty*]) (Call x-id the-ty f as (let ([the-x-ref (Var x-id the-ty)]) (let-syntax ([x (P-expander (syntax-parser [_ #'the-x-ref]))]) (S (begin . b)))))))] [(_ (~and macro-use (~or macro-id:id (macro-id:id . _)))) #:when (dict-has-key? S-free-macros #'macro-id) (record-disappeared-uses #'macro-id) ((dict-ref S-free-macros #'macro-id) #'macro-use)] [(_ (~and macro-use (~or macro-id (macro-id . _)))) #:declare macro-id (static S-expander? "S expander") (record-disappeared-uses #'macro-id) (S-expand (attribute macro-id.value) #'macro-use)] [(_ (unsyntax ~! e)) (record-disappeared-uses #'unsyntax) #'e] [(_ e ~!) #:fail-unless (syntax-parameter-value #'S-in-tail?) "Cannot end in expression when not in tail position" (syntax/loc stx (S (return e)))]))) (define-S-free-syntax cond (syntax-parser #:literals (else) [(_) (syntax/loc this-syntax (S (void)))] [(_ [else . b]) (syntax/loc this-syntax (S (begin . b)))] [(_ [q . a] . more) (syntax/loc this-syntax (S (if q (begin . a) (cond . more))))])) (define-S-free-syntax when (syntax-parser [(_ p . t) (syntax/loc this-syntax (S (if p (begin . t) (void))))])) (define-S-free-syntax unless (syntax-parser [(_ p . f) (syntax/loc this-syntax (S (if p (void) (begin . f))))])) (define-S-free-syntax let* (syntax-parser #:literals () [(_ () . b) (syntax/loc this-syntax (S (begin . b)))] [(_ (a . d) . b) (syntax/loc this-syntax (S (let (a) (let* d . b))))])) (define-S-expander assert! (syntax-parser [(_ (~optional (~and #:dyn (~bind [must-be-static? #f])) #:defaults ([must-be-static? #t])) (~optional (~seq #:msg p-msg-expr) #:defaults ([p-msg-expr #'#f])) p) #:with p-e (if (attribute must-be-static?) (syntax/loc #'p (MetaE 'must-be-static p)) #'p) (record-disappeared-uses #'assert!) (syntax/loc this-syntax (let ([p-msg (or p-msg-expr (format "~a" 'p))]) (S (if p-e (void (format "Checked: ~a" p-msg)) (error (format "Failed! ~a" p-msg))))))])) (define-S-expander while (syntax-parser [(_ (~optional (~seq #:I I) #:defaults ([I #'(U32 1)])) p . b) (record-disappeared-uses #'while) (syntax/loc this-syntax (MetaS (cons 'while-invariant (E I)) (While (E p) (syntax-parameterize ([S-in-tail? #f]) (S (begin . b))))))])) (define-S-free-syntax for (syntax-parser [(_ ((~optional (~seq #:I I) #:defaults ([I #'(U32 1)])) init pred inc) body ...) (record-disappeared-uses #'for) (syntax/loc this-syntax (S (let (init) (while #:I I pred body ... inc))))])) (define-S-expander return (syntax-parser [(_) #:fail-unless (syntax-parameter-value #'current-return) "Illegal outside of F" (record-disappeared-uses #'return) (syntax/loc this-syntax current-return)] [(_ e) #:fail-unless (and (syntax-parameter-value #'current-return) (syntax-parameter-value #'current-return-var)) "Illegal outside of F" (record-disappeared-uses #'return) (syntax/loc this-syntax (S (begin (set! current-return-var e) (return))))])) (define-expanders&macros A-free-macros define-A-free-syntax A-expander A-expand define-A-expander define-simple-A-expander) (struct anf-nv () #:transparent) (struct anf-void anf-nv (var pre) #:transparent) (struct anf-let/ec (var k b-arg b-nv) #:transparent) (struct anf-let anf-nv (var xe) #:transparent) (struct anf-call anf-nv (x ty f es) #:transparent) (struct anf-if anf-nv (var p-arg t-nv t-arg f-nv f-arg) #:transparent) (struct anf-type anf-nv (var es) #:transparent) (struct anf-union anf-nv (var m e) #:transparent) (define listof-nvs? (listof anf-nv?)) (begin-for-syntax (struct A-esc-k (var id) #:methods gen:A-expander [(define (A-expand this stx) (syntax-parse stx [(_ a) #:with void-id (generate-temporary 'any) #:with k-var (A-esc-k-var this) #:with k-id (A-esc-k-id this) (syntax/loc stx (let* ([void-id 'void-id] [void-ref (Var void-id (T any))]) (define-values (a-nv a-arg) (ANF a)) (define the-stmt (Begin (Assign k-var a-arg) (Jump k-id))) (values (snoc a-nv (anf-void void-ref the-stmt)) (Read void-ref))))]))])) (define-syntax (ANF stx) (with-disappeared-uses (syntax-parse stx #:literals (void error begin define set! if let/ec let unsyntax) [(_ (void ~!)) #:with x-id (generate-temporary 'void) (record-disappeared-uses #'void) (syntax/loc stx (let* ([x-id 'x-id] [the-x-ref (Var x-id (T void))]) (values (list (anf-void the-x-ref #f)) (Read the-x-ref))))] [(_ (error ~! m)) #:with x-id (generate-temporary 'any) (record-disappeared-uses #'error) (syntax/loc stx (let* ([x-id 'x-id] [the-x-ref (Var x-id (T any))]) (values (list (anf-void the-x-ref (Fail m))) (Read the-x-ref))))] [(_ (begin (define . d) . b)) (record-disappeared-uses (list #'begin #'define)) (syntax/loc stx (ANF (let (d) . b)))] [(_ (begin a)) (record-disappeared-uses #'begin) (syntax/loc stx (ANF a))] [(_ (begin ~! a . as)) (record-disappeared-uses #'begin) (syntax/loc stx (let-values ([(a-nv a-arg) (ANF a)] [(as-nv as-arg) (ANF (begin . as))]) (values (append a-nv as-nv) as-arg)))] [(_ (set! ~! p a)) #:with x-id (generate-temporary 'void) (record-disappeared-uses #'set!) (syntax/loc stx (let* ([the-p (P p)] [p-ty (path-type the-p)]) (define-values (a-nv a-arg) (syntax-parameterize ([expect-ty #'p-ty]) (ANF a))) (define x-id 'x-id) (define the-x-ref (Var x-id (T void))) (values (snoc a-nv (anf-void the-x-ref (Assign the-p a-arg))) (Read the-x-ref))))] [(_ (if ~! p t f)) #:with x-id (generate-temporary 'if) (record-disappeared-uses #'if) (syntax/loc stx (let-values ([(p-nv p-arg) (ANF p)] [(t-nv t-arg) (ANF t)] [(f-nv f-arg) (ANF f)]) (define x-id 'x-id) (define x-ty (resolve-type (expr-type t-arg) (expr-type f-arg))) (define the-x-ref (Var x-id x-ty)) (values (snoc p-nv (anf-if the-x-ref p-arg t-nv t-arg f-nv f-arg)) (Read the-x-ref))))] [(_ (let/ec ~! (k:id ty) body ...+)) #:with x-id (generate-temporary 'letec) #:with k-id (generate-temporary #'k) (record-disappeared-uses #'let/ec) (syntax/loc stx (let ([x-id 'x-id] [k-id 'k-id] [the-ty (T ty)]) (define the-x-ref (Var x-id the-ty)) (define-values (body-nv body-arg) (let-syntax ([k (A-esc-k #'the-x-ref #'k-id)]) (ANF (begin body ...)))) (values (list (anf-let/ec the-x-ref k-id body-arg body-nv)) (Read the-x-ref))))] [(_ (let ~! ([x:id xe] ...) body ...+)) #:with (x-id ...) (generate-temporaries #'(x ...)) #:with (xe-ty ...) (generate-temporaries #'(x ...)) #:with (ref-ty? ...) (generate-temporaries #'(x ...)) #:with (the-x-ref ...) (generate-temporaries #'(x ...)) #:with (xe-nv ...) (generate-temporaries #'(x ...)) #:with (xe-arg ...) (generate-temporaries #'(x ...)) (record-disappeared-uses #'let) (quasisyntax/loc stx (let-values ([(xe-nv xe-arg) (ANF xe)] ...) (define x-id 'x-id) ... (define xe-ty (expr-type xe-arg)) ... (for ([ty (in-list (list xe-ty ...))]) (when (VoiT? ty) (raise-syntax-error 'let "new variable cannot be of type void" #'#,stx)) (when (AnyT? ty) (raise-syntax-error 'let "new variable cannot be of type any" #'#,stx))) (define ref-ty? (or (ArrT? xe-ty) (RecT? xe-ty) (UniT? xe-ty))) ... (define the-x-ref (if ref-ty? (Read-p xe-arg) (Var x-id xe-ty))) ... (define-values (body-nv body-arg) (let-syntax ([x (P-expander (syntax-parser [_ #'the-x-ref]))] ...) (ANF (begin body ...)))) (define the-nvs (for/list ([arg (in-list (list xe-arg ...))] [x-ref (in-list (list the-x-ref ...))] [ref? (in-list (list ref-ty? ...))] #:unless ref?) (anf-let x-ref arg))) (values (append xe-nv ... the-nvs body-nv) body-arg)))] [(_ (fn ~! as ...)) #:declare fn (static F-expander? "F expander") #:with x-id (generate-temporary #'fn) #:with (as-nv ...) (generate-temporaries #'(as ...)) #:with (as-arg ...) (generate-temporaries #'(as ...)) (record-disappeared-uses #'fn) (syntax/loc stx (let-values ([(as-nv as-arg) (ANF as)] ...) (define x-id 'x-id) (define x-ty (fun-type fn)) (define the-x-ref (Var x-id x-ty)) (values (snoc (append as-nv ...) (anf-call x-id x-ty fn (list as-arg ...))) (Read the-x-ref))))] [(_ (ty m:keyword ~! a:expr)) #:declare ty (static (and/c T-expander? I-expander?) "T/I expander") #:with x-id (generate-temporary #'ty) (record-disappeared-uses #'ty) (syntax/loc stx (let-values ([(a-nv a-arg) (ANF a)]) (define x-id 'x-id) (define x-ty (T ty)) (define the-x-ref (Var x-id x-ty)) (values (snoc a-nv (anf-union the-x-ref (keyword->symbol 'm) a-arg)) (Read the-x-ref))))] [(_ (ty ~! as ...)) #:declare ty (static (and/c T-expander? I-expander?) "T/I expander") #:with x-id (generate-temporary #'ty) #:with (as-nv ...) (generate-temporaries #'(as ...)) #:with (as-arg ...) (generate-temporaries #'(as ...)) (record-disappeared-uses #'ty) (syntax/loc stx (let-values ([(as-nv as-arg) (ANF as)] ...) (define x-id 'x-id) (define x-ty (T ty)) (define the-x-ref (Var x-id x-ty)) (values (snoc (append as-nv ...) (anf-type the-x-ref (list as-arg ...))) (Read the-x-ref))))] [(_ (~and macro-use (~or macro-id:id (macro-id:id . _)))) #:when (dict-has-key? A-free-macros #'macro-id) (record-disappeared-uses #'macro-id) ((dict-ref A-free-macros #'macro-id) #'macro-use)] [(_ (~and macro-use (~or macro-id (macro-id . _)))) #:declare macro-id (static A-expander? "A expander") (record-disappeared-uses #'macro-id) (A-expand (attribute macro-id.value) #'macro-use)] [(_ (unsyntax ~! nvs/arg)) (record-disappeared-uses #'unsyntax) (quasisyntax/loc stx (let-values ([(nvs arg) nvs/arg]) (unless (Expr? arg) (raise-syntax-error #f "unsyntaxed ANF arg must be Expr" #'#,stx)) (unless (listof-nvs? nvs) (raise-syntax-error #f "unsyntaxed ANF nvs must be list of anf-nv" #'#,stx)) (values nvs arg)))] [(_ e ~!) (syntax/loc stx (values '() (E e)))]))) (define (ANF-compose ret-fn nvs arg) (define (rec nvs arg) (ANF-compose ret-fn nvs arg)) (match nvs ['() (ret-fn arg)] [(cons (anf-void var pre) more) (match-define (Var x ty) (unpack-MetaP var)) (Let x ty (UndI ty) (Begin (or pre (Skip #f)) (rec more arg)))] [(cons (anf-let/ec var k b-arg b-nv) more) (match-define (Var x ty) (unpack-MetaP var)) (define (body-ret arg) (Assign var arg)) (Let x ty (UndI ty) (Begin (Let/ec k (ANF-compose body-ret b-nv b-arg)) (rec more arg)))] [(cons (anf-let var xe) more) (match-define (Var x ty) (unpack-MetaP var)) (Let x ty (UndI ty) (Begin (Assign var xe) (rec more arg)))] [(cons (anf-call x ty f es) more) (Call x ty f es (rec more arg))] [(cons (anf-if var p-arg t-nv t-arg f-nv f-arg) more) (match-define (Var x ty) (unpack-MetaP var)) (define (branch-ret arg) (Assign var arg)) (Let x ty (UndI ty) (Begin (If p-arg (ANF-compose branch-ret t-nv t-arg) (ANF-compose branch-ret f-nv f-arg)) (rec more arg)))] [(cons (anf-type var es) more) (match-define (Var x ty) (unpack-MetaP var)) (define body (match ty [(ArrT dim _) (for/fold ([b (rec more arg)]) ([i (in-list (reverse (range dim)))] [e (in-list (reverse es))]) (Begin (Assign (Select var (N i)) e) b))] [(RecT _ _ c-order) (for/fold ([b (rec more arg)]) ([f (in-list (reverse c-order))] [e (in-list (reverse es))]) (Begin (Assign (Field var f) e) b))])) (Let x ty (UndI ty) body)] [(cons (anf-union var m e) more) (match-define (Var x ty) (unpack-MetaP var)) (Let x ty (UndI ty) (Begin (Assign (Mode var m) e) (rec more arg)))])) (define-simple-macro (S+ e) (let-values ([(nvs arg) (ANF e)]) (define (ret-fn arg) (S (return #,arg))) (ANF-compose ret-fn nvs arg))) (begin-for-syntax (define (make-A-op-parser op-stx) (syntax-parser [(_ as ...) #:with x-id (generate-temporary) #:with (as-nv ...) (generate-temporaries #'(as ...)) #:with (as-arg ...) (generate-temporaries #'(as ...)) #:with op op-stx (syntax/loc this-syntax (let-values ([(as-nv as-arg) (ANF as)] ...) (define x-id 'x-id) (define arg-e (E (op #,as-arg ...))) (define x-ty (expr-type arg-e)) (define the-x-ref (Var x-id x-ty)) (values (snoc (append as-nv ...) (anf-let the-x-ref arg-e)) (Read the-x-ref))))]))) (define-simple-macro (define-A-free-ops op:id ...) (begin (define-A-free-syntax op (make-A-op-parser #'op)) ...)) (define-A-free-ops + - * / modulo bitwise-ior bitwise-and bitwise-xor = < <= > >= not zero? min max) (begin-for-syntax (struct E/A-expander (E-impl A-impl) #:property prop:procedure (λ (this stx) (raise-syntax-error #f "Illegal outside E or S+" stx)) #:methods gen:E-expander [(define (E-expand this stx) ((E/A-expander-E-impl this) stx))] #:methods gen:A-expander [(define (A-expand this stx) ((E/A-expander-A-impl this) stx))])) (define-simple-macro (define-E/A-expander x:id E-impl A-impl) (define-syntax x (E/A-expander E-impl A-impl))) (begin-for-syntax (define (make-E/A-binop-expander op-stx impl-stx) (E/A-expander (syntax-parser [(_ l r) (quasisyntax/loc this-syntax (#,impl-stx (E l) (E r)))]) (make-A-op-parser op-stx)))) (define-syntax (define-E/A-binop stx) (syntax-parse stx [(_ name:id [match-clause op:id] ...+) #:with name^ (generate-temporary #'name) (syntax/loc stx (begin (define (name^ the-lhs the-rhs) (match (expr-type the-lhs) [match-clause (E (op #,the-lhs #,the-rhs))] ...)) (define-syntax name (make-E/A-binop-expander #'name #'name^)) (provide name)))])) (define-E/A-binop << [(? IntT?) ishl]) (define-E/A-binop >> [(IntT #t _) iashr] [(IntT #f _) ilshr]) (define-E/A-binop != [(? IntT?) ine] [(? FloT?) fune]) (define-simple-macro (define-E/A-aliases [name:id op:id] ...+) (begin (begin (define-E/A-expander name (syntax-parser [(_ . vs) (syntax/loc this-syntax (E (op . vs)))]) (syntax-parser [(_ . as) (syntax/loc this-syntax (ANF (op . as)))])) (provide name)) ...)) (define-E/A-aliases [% modulo] [& bitwise-and] [^ bitwise-xor]) (define-A-free-syntax when (syntax-parser [(_ p . t) (syntax/loc this-syntax (ANF (if p (begin . t) (void))))])) (define-A-free-syntax unless (syntax-parser [(_ p . f) (syntax/loc this-syntax (ANF (if p (void) (begin . f))))])) (define-A-free-syntax let* (syntax-parser [(_ () a) (syntax/loc this-syntax (ANF a))] [(_ (f r ...) a) (syntax/loc this-syntax (ANF (let (f) (let* (r ...) a))))])) (define-A-free-syntax cond (syntax-parser #:literals (else) [(_ [else a]) (syntax/loc this-syntax (ANF a))] [(_ [q a] . more) (syntax/loc this-syntax (ANF (if q a (cond . more))))])) (define-A-free-syntax and (syntax-parser [(_) (syntax/loc this-syntax (ANF #,(values '() (N 1))))] [(_ a) (syntax/loc this-syntax (ANF a))] [(_ a as ...) (syntax/loc this-syntax (let-values ([(a-nv a-arg) (ANF a)]) (define arg-ty (expr-type a-arg)) (define-values (as-nv as-arg) (syntax-parameterize ([expect-ty #'arg-ty]) (ANF (and as ...)))) (ANF (if #,(values a-nv a-arg) #,(values as-nv as-arg) #,(values '() (N arg-ty 0))))))])) (define-A-free-syntax or (syntax-parser [(_) (syntax/loc this-syntax (ANF #,(values '() (N 0))))] [(_ a) (syntax/loc this-syntax (ANF a))] [(_ a as ...) (syntax/loc this-syntax (let-values ([(a-nv a-arg) (ANF a)]) (define arg-ty (expr-type a-arg)) (define-values (as-nv as-arg) (syntax-parameterize ([expect-ty #'arg-ty]) (ANF (or as ...)))) (ANF (let ([tmp #,(values a-nv a-arg)]) (if tmp tmp #,(values as-nv as-arg))))))])) (begin-for-syntax (struct S/A-expander (S-impl A-impl) #:methods gen:S-expander [(define (S-expand this stx) ((S/A-expander-S-impl this) stx))] #:methods gen:A-expander [(define (A-expand this stx) ((S/A-expander-A-impl this) stx))])) (define-simple-macro (define-S/A-expander x:id S-impl A-impl) (define-syntax x (S/A-expander S-impl A-impl))) (define-simple-macro (define-S/A-assign-ops [name:id op:id] ...+) (begin (begin (define-S/A-expander name (syntax-parser [(_ p e) (syntax/loc this-syntax (S (set! p (op p e))))]) (syntax-parser [(_ p a) #:with x-id (generate-temporary 'void) (syntax/loc this-syntax (let-values ([(a-nv a-arg) (ANF a)]) (define x-id 'x-id) (define the-x-ref (Var x-id (T void))) (define the-stmt (S (name p #,a-arg))) (values (snoc a-nv (anf-void the-x-ref the-stmt)) (Read the-x-ref))))])) (provide name)) ...)) (define-S/A-assign-ops [+= +] [-= -] [*= *] [/= /] [%= %] [<<= <<] [>>= >>]) (define-simple-macro (define-S/A-increment-ops [name:id op:id] ...+) (begin (begin (define-S/A-expander name (syntax-parser [(_ p) (syntax/loc this-syntax (S (set! p (op p))))]) (syntax-parser [(_ p) #:with x-id (generate-temporary 'void) (syntax/loc this-syntax (let* ([x-id 'x-id] [the-x-ref (Var x-id (T void))]) (values (list (anf-void the-x-ref (S (name p)))) (Read the-x-ref))))])) (provide name)) ...)) (define-S/A-increment-ops [+=1 add1] [-=1 sub1]) XXX ' assert ! ' , ' let loop ' , ' for ' for ANF . (begin-for-syntax (define-syntax-class Farg #:attributes (x ref var arg) #:description "function argument" [pattern ((~optional (~or (~and #:copy (~bind [mode #''copy])) (~and #:ref (~bind [mode #''ref]))) #:defaults ([mode #''read-only])) ty x:id) #:attr ref (generate-temporary #'x) #:attr var (syntax/loc this-syntax (Var 'ref (T ty))) #:attr arg (syntax/loc this-syntax (Arg (Var-x ref) (Var-ty ref) mode))]) (define-syntax-class Fret #:attributes (x ref var) #:description "function return" [pattern (x:id (~datum :) ty) #:attr ref (generate-temporary #'x) #:attr var (syntax/loc this-syntax (Var 'ref (T ty)))] [pattern ty #:attr x (generate-temporary #'ty) #:attr ref (generate-temporary #'x) #:attr var (syntax/loc this-syntax (Var 'ref (T ty)))])) (define-syntax-parameter F-body-default (make-rename-transformer #'S)) (define-syntax (F stx) (with-disappeared-uses (syntax-parse stx [(_ r:Fret (a:Farg ...) (~optional (~seq #:pre pre) #:defaults ([pre #'(S64 1)])) (~optional (~seq #:post post) #:defaults ([post #'(S64 1)])) (~optional (~seq #:return ret-lab:id) #:defaults ([ret-lab (generate-temporary 'return)])) . bs) #:fail-when (check-duplicates (syntax->list #'(a.x ...)) bound-identifier=?) "All arguments must have unique identifiers" #:with ret-lab-id (generate-temporary #'ret-lab) (syntax/loc stx (let* ([ret-lab-id 'ret-lab-id] [a.ref a.var] ... [r.ref r.var]) (let-syntax ([a.x (P-expander (syntax-parser [_ #'a.ref]))] ...) (let-values ([(the-post the-body) (let-syntax ([r.x (P-expander (syntax-parser [_ #'r.ref]))]) (syntax-parameterize ([current-return-var (make-rename-transformer #'r.x)]) (values (E post) (let ([the-ret (Jump ret-lab-id)]) (let-syntax ([ret-lab (S-expander (syntax-parser [(_) #'the-ret]))]) (syntax-parameterize ([current-return (make-rename-transformer #'the-ret)] [S-in-tail? #t]) XXX Make ANF the default here (F-body-default (begin . bs))))))))]) (MetaFun (vector 'fun-invariants (E pre) the-post) (IntFun (list a.arg ...) (Var-x r.ref) (Var-ty r.ref) ret-lab-id the-body))))))]))) (define-simple-macro (F+ . more) (syntax-parameterize ([F-body-default (make-rename-transformer #'S+)]) (F . more))) (define (apply-union-ctor-init stx ty m i) (unless (UniT? ty) (raise-syntax-error #f "union syntax used for non-union type" stx)) (I (union #,m #,i))) (define (apply-ctor-inits stx ty is) (match ty [(? ArrT?) (I (array #,@is))] [(RecT _ _ c-order) (unless (= (length c-order) (length is)) (raise-syntax-error #f "constructor arity mismatch" stx)) (I (record #,@(map cons c-order is)))] [_ (raise-syntax-error #f "invalid constructor syntax" stx)])) (begin-for-syntax (struct T/I-expander (T-impl I-impl) #:property prop:procedure (struct-field-index T-impl) #:methods gen:T-expander [(define (T-expand this stx) ((T/I-expander-T-impl this) stx))] #:methods gen:I-expander [(define (I-expand this stx) ((T/I-expander-I-impl this) stx))]) (define (make-type-binding ty-stx) (T/I-expander (syntax-parser [_ (quasisyntax/loc this-syntax #,ty-stx)]) (syntax-parser [(_ m:keyword ~! i:expr) (quasisyntax/loc this-syntax (apply-union-ctor-init #'#,this-syntax #,ty-stx (keyword->symbol 'm) (I i)))] [(_ i:expr ...) (quasisyntax/loc this-syntax (apply-ctor-inits #'#,this-syntax #,ty-stx (list (I i) ...)))])))) (define-syntax (define-type stx) (syntax-parse stx [(_ #:public name:id ty) #:fail-unless (syntax-parameter-value #'current-Prog) "Cannot define public type outside of Prog" (syntax/loc stx (begin (define-type name ty) (include-type name)))] [(_ name:id ty) (syntax/loc stx (begin (define the-ty (T ty)) (define-syntax name (make-type-binding #'the-ty))))])) (define-syntax (include-type stx) (with-disappeared-uses (syntax-parse stx [(_ #:maybe n:expr ty:expr) (if (syntax-parameter-value #'current-Prog) (syntax/loc stx (hash-set! (Program-name->ty current-Prog) n ty)) #'(void))] [(_ n:expr ty:expr) #:fail-unless (syntax-parameter-value #'current-Prog) "Cannot include type outside of Prog" (syntax/loc stx (include-type #:maybe n ty))] [(_ x:id) (syntax/loc stx (include-type (symbol->c-name 'x) x))] [(_ #:maybe x:id) (syntax/loc stx (include-type #:maybe (symbol->c-name 'x) x))]))) (define-syntax (define-extern-type stx) (with-disappeared-uses (syntax-parse stx [(_ x:id (~optional (~seq #:name name:expr) #:defaults ([name #'(symbol->c-name 'x)])) (~optional (~seq #:src es:expr) #:defaults ([es #'(ExternSrc '() '())]))) #:with the-ext (generate-temporary #'x) (syntax/loc stx (begin (define the-ext (ExtT es name)) (define-syntax x (T-expander (syntax-parser [_ #'the-ext])))))]))) (define-syntax (include-fun stx) (with-disappeared-uses (syntax-parse stx [(_ #:maybe n:expr f:expr) (if (syntax-parameter-value #'current-Prog) (syntax/loc stx (hash-set! (Program-name->fun current-Prog) n f)) #'(void))] [(_ n:expr f:expr) #:fail-unless (syntax-parameter-value #'current-Prog) "Cannot include function outside of Prog" (syntax/loc stx (include-fun #:maybe n f))] [(_ x:id) (syntax/loc stx (include-fun (symbol->c-name 'x) x))] [(_ #:maybe x:id) (syntax/loc stx (include-fun #:maybe (symbol->c-name 'x) x))]))) (define-syntax (define-fun stx) (with-disappeared-uses (syntax-parse stx [(_ ret-ty x:id #:as n:expr (args ...) . more) (syntax/loc stx (begin (define the-fun (give-name (F ret-ty (args ...) . more) 'x)) (define-syntax x (F-expander (syntax-parser [_ #'the-fun]))) (include-fun #:maybe n x)))] [(_ ret-ty x:id (args ...) . more) (syntax/loc stx (define-fun ret-ty x #:as (symbol->c-name 'x) (args ...) . more))]))) (define-syntax (define-fun+ stx) (with-disappeared-uses (syntax-parse stx [(_ ret-ty x:id #:as n:expr (args ...) . more) (syntax/loc stx (begin (define the-fun (give-name (F+ ret-ty (args ...) . more) 'x)) (define-syntax x (F-expander (syntax-parser [_ #'the-fun]))) (include-fun #:maybe n x)))] [(_ ret-ty x:id (args ...) . more) (syntax/loc stx (define-fun+ ret-ty x #:as (symbol->c-name 'x) (args ...) . more))]))) (define-syntax (define-extern-fun stx) (with-disappeared-uses (syntax-parse stx [(_ ret-ty x:id (~optional (~seq #:name name:expr) #:defaults ([name #'(symbol->c-name 'x)])) (a:Farg ...) #:src es:expr) (syntax/loc stx (begin (define the-fun (ExtFun es (let ([a.ref a.var] ...) (list a.arg ...)) (T ret-ty) name)) (define-syntax x (F-expander (syntax-parser [_ #'the-fun])))))]))) (define-syntax (define-global stx) (with-disappeared-uses (syntax-parse stx #:literals (unsyntax) [(_ #:public name:id . more) #:fail-unless (syntax-parameter-value #'current-Prog) "Cannot define public global outside of Prog" (syntax/loc stx (begin (define-global name . more) (include-global name)))] [(_ x:id (~datum :=) (~and ctor-use (ctor-id . _))) #:declare ctor-id (static (and/c T-expander? I-expander?) "T/I expander") (syntax/loc stx (define-global x : ctor-id := ctor-use))] [(_ x:id (~datum :=) e) (syntax/loc stx (begin (define the-e (E e)) (define e-ty (expr-type the-e)) (define the-glob (give-name (Global e-ty (ConI the-e)) 'x)) (define-syntax x (P-expander (syntax-parser [_ #'the-glob])))))] [(_ x:id (~datum :) ty (~datum :=) xi) (syntax/loc stx (begin (define the-ty (T ty)) (define the-init (syntax-parameterize ([expect-ty #'the-ty]) (I xi))) (define the-glob (give-name (Global the-ty the-init) 'x)) (define-syntax x (P-expander (syntax-parser [_ #'the-glob])))))] [(_ x:id (~datum :) ty) (syntax/loc stx (begin (define the-ty (T ty)) (define-global x : #,the-ty := (undef #,the-ty))))]))) (define-syntax (include-global stx) (with-disappeared-uses (syntax-parse stx [(_ #:maybe n:expr g:expr) (if (syntax-parameter-value #'current-Prog) (syntax/loc stx (hash-set! (Program-name->global current-Prog) n g)) #'(void))] [(_ n:expr g:expr) #:fail-unless (syntax-parameter-value #'current-Prog) "Cannot include global outside of Prog" (syntax/loc stx (include-global #:maybe n g))] [(_ x:id) (syntax/loc stx (include-global (symbol->c-name 'x) x))] [(_ #:maybe x:id) (syntax/loc stx (include-global #:maybe (symbol->c-name 'x) x))]))) (define (symbol->c-name x) (string-replace (symbol->string x) "-" "_")) (define-syntax-parameter current-Prog #f) (define-syntax (Prog stx) (with-disappeared-uses (syntax-parse stx [(_ pf ...) (syntax/loc stx (let ([the-prog (Program (make-hash) (make-hash) (make-hash))]) (syntax-parameterize ([current-Prog (make-rename-transformer #'the-prog)]) pf ... (void)) the-prog))]))) (begin-for-syntax (define-literal-set def-forms #:datum-literals ( define-type define-fun define-fun+ define-global define-extern-fun define-extern-type include-fun include-type include-global) ()) (define def-form? (literal-set->predicate def-forms))) (define-syntax (Prog* stx) (with-disappeared-uses (syntax-parse stx [(_ pf ...) #:with ((def ...) (non ...)) (let-values ([(defs nons) (partition (syntax-parser [(x:id . _) #:when (def-form? #'x) #t] [_ #f]) (syntax->list #'(pf ...)))]) (list defs nons)) (syntax/loc stx (Prog def ... (define-fun S32 main () non ... (return 0))))]))) (define-simple-macro (define-prog name:id pf ...+) (define name (Prog pf ...))) (define-simple-macro (define-prog* name:id pf ...) (define name (Prog* pf ...))) (provide while assert! return F-body-default define-type define-fun define-fun+ define-global define-extern-fun define-extern-type include-fun include-type include-global Prog Prog* define-prog define-prog*) (define-runtime-path util-path "util.h") (define util-h (ExternSrc '() (list (path->string util-path)))) (define-extern-type char*) (define-extern-fun S32 c-print-string #:name "print_string" ([char* str] [S32 n]) #:src util-h) (define (print-string s) (define bs (string->bytes/utf-8 s)) (define init (I (array #,@(for/list ([b (in-bytes bs)]) (I (U8 b)))))) (define len (bytes-length bs)) (S (let* ([str-x : (array len U8) := #,init] [ret-x := (c-print-string (str-x : #,char*) (S32 len))]) (void)))) (define printers (make-weak-hash)) (define array-printers (make-weak-hash)) (define (get-printer ty) (define (new-printer!) (define print-fn (match ty [(RecT _ _ c-order) (F S32 ([#,ty rec]) (print "{") #,(let loop ([f (first c-order)] [fs (rest c-order)]) (cond [(empty? fs) (S (print #,(Read (Field (P rec) f))))] [else (S (begin (print #,(Read (Field (P rec) f)) ", ") #,(loop (first fs) (rest fs))))])) (print "}") (return 0))])) (define value (make-ephemeron ty print-fn)) (hash-set! printers ty value) value) (define (new-array-printer!) (define ety (ArrT-ety ty)) (define print-fn (F S32 ([#,ty arr] [U64 count]) (let ([i : U64 := (U64 0)]) (print "[") (while (< i count) (print (arr @ i)) (define next : U64 := (add1 i)) (when (< next count) (print ", ")) (set! i next)) (print "]") (return 0)))) (define value (make-ephemeron ety print-fn)) (hash-set! array-printers ety value) value) (match ty ' ephemeron - value ' may produce # f if the key was GC'd between our call to ' hash - ref ' and ' ephemeron - value ' . In this case , we call to ' ephemeron - value ' can not produce # f because the key is used [(ArrT _ ety) (or (ephemeron-value (hash-ref array-printers ety new-array-printer!)) (ephemeron-value (new-array-printer!)))] [_ (or (ephemeron-value (hash-ref printers ty new-printer!)) (ephemeron-value (new-printer!)))])) (define (print-expr the-e) (define e-ty (expr-type the-e)) (define printer (cond [(or (IntT? e-ty) (FloT? e-ty)) (define fn-name (match e-ty [(FloT 32) "print_F32"] [(FloT 64) "print_F64"] [(IntT signed? bits) (if signed? (match bits [8 "print_S8"] [16 "print_S16"] [32 "print_S32"] [64 "print_S64"]) (match bits [8 "print_U8"] [16 "print_U16"] [32 "print_U32"] [64 "print_U64"]))])) (ExtFun util-h (list (Arg 'n e-ty 'read-only)) (T S32) fn-name)] [else (get-printer e-ty)])) (match e-ty [(ArrT dim _) (S (let ([ret-x := printer <- #,the-e (U64 dim)]) (void)))] [_ (S (let ([ret-x := printer <- #,the-e]) (void)))])) (define-S-free-syntax print (syntax-parser #:literals (unsyntax) [(_ e es ...+) (syntax/loc this-syntax (S (begin (print e) (print es ...))))] [(_ (unsyntax exp-or-str)) (syntax/loc this-syntax (match exp-or-str [(? string? s) (print-string s)] [(? Expr? the-e) (print-expr the-e)]))] [(_ s:str) (syntax/loc this-syntax (print-string s))] [(_ e) (syntax/loc this-syntax (print-expr (E e)))])) (define-S-free-syntax println (syntax-parser [(_ es ... e:str) (syntax/loc this-syntax (S (print es ... #,(string-append e "\n"))))] [(_ es ...) (syntax/loc this-syntax (S (print es ... "\n")))])) (define-A-free-syntax print (syntax-parser [(_ a as ...+) (syntax/loc this-syntax (ANF (begin (print a) (print as ...))))] [(_ s:str) #:with x-id (generate-temporary 'tmp) (syntax/loc this-syntax (let* ([x-id 'x-id] [the-x-ref (Var x-id (T void))]) (values (list (anf-void the-x-ref (S (print s)))) (Read the-x-ref))))] [(_ a) #:with x-id (generate-temporary 'tmp) (syntax/loc this-syntax (let-values ([(a-nv a-arg) (ANF a)]) (define x-id 'x-id) (define the-x-ref (Var x-id (T void))) (define the-stmt (S (print #,a-arg))) (values (snoc a-nv (anf-void the-x-ref the-stmt)) (Read the-x-ref))))])) (define-A-free-syntax println (syntax-parser [(_ as ...) (syntax/loc this-syntax (ANF (begin (print as ...) (print "\n"))))])) (provide T P N E I F F+ S S+) XXX try using --
1657b8ac947d2440d396ecbecf020067872bb2ce00286f84e6aa4c258402bfa6
okuoku/nausicaa
test-msgcat.sps
-*- coding : utf-8 - unix -*- ;;; Part of : / Scheme Contents : tests for msgcat Date : Tue May 18 , 2010 ;;; ;;;Abstract ;;; ;;; ;;; Copyright ( c ) 2010 < > ;;; ;;;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 </>. ;;; #!r6rs (import (nausicaa) (nausicaa msgcat) (nausicaa checks)) (check-set-mode! 'report-failed) (display "*** testing msgcat\n") (parametrise ((check-test-name 'basic)) (define it_IT (load-catalog 'it_IT)) (define en_US (load-catalog 'en_US)) (check (mc "January") => "January") (parametrise ((current-catalog it_IT)) (check (mc "January") => "Gennaio") #f) (parametrise ((current-catalog en_GB)) (check (mc "Yes") => "Yes") #f) (parametrise ((current-catalog en_US)) (check (mc "July") => "July") #f) #t) ;;;; done (check-report) ;;; end of file ;; Local Variables: coding : utf-8 - unix ;; End:
null
https://raw.githubusercontent.com/okuoku/nausicaa/50e7b4d4141ad4d81051588608677223fe9fb715/scheme/tests/test-msgcat.sps
scheme
Abstract 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 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 along with this program. If not, see </>. done end of file Local Variables: End:
-*- coding : utf-8 - unix -*- Part of : / Scheme Contents : tests for msgcat Date : Tue May 18 , 2010 Copyright ( c ) 2010 < > the Free Software Foundation , either version 3 of the License , or ( at General Public License for more details . You should have received a copy of the GNU General Public License #!r6rs (import (nausicaa) (nausicaa msgcat) (nausicaa checks)) (check-set-mode! 'report-failed) (display "*** testing msgcat\n") (parametrise ((check-test-name 'basic)) (define it_IT (load-catalog 'it_IT)) (define en_US (load-catalog 'en_US)) (check (mc "January") => "January") (parametrise ((current-catalog it_IT)) (check (mc "January") => "Gennaio") #f) (parametrise ((current-catalog en_GB)) (check (mc "Yes") => "Yes") #f) (parametrise ((current-catalog en_US)) (check (mc "July") => "July") #f) #t) (check-report) coding : utf-8 - unix
ab81775e3d18a4d90ec8ceebaae3bf9843c5f95954aaadd9953160ebcaab2133
biocad/hasbolt-extras
Converters.hs
# LANGUAGE RecordWildCards # {-# LANGUAGE CPP #-} # LANGUAGE TemplateHaskell # module Database.Bolt.Extras.Template.Internal.Converters ( makeNodeLike , makeNodeLikeWith , makeURelationLike , makeURelationLikeWith ) where import Data.Map.Strict (fromList, member, notMember, (!)) import Data.Text (Text, pack, unpack) import Database.Bolt (Node (..), URelationship (..), Value (..), IsValue(..), RecordValue(..)) import Database.Bolt.Extras (Labels (..), NodeLike (..), Properties (..), URelationLike (..)) import Database.Bolt.Extras.Utils (currentLoc, dummyId) import Instances.TH.Lift () import Language.Haskell.TH import Language.Haskell.TH.Syntax Starting with template - haskell-2.16.0.0 , ' TupE ' constructor accepts @Maybe , to support TupleSections . We use this alias for compatibility with both old and new versions . tupE' :: [Exp] -> Exp #if MIN_VERSION_template_haskell(2, 16, 0) tupE' = TupE . map Just #else tupE' = TupE #endif | Describes a @bijective@ class , i.e. class that has two functions : @phi : : a - > SomeType@ and @phiInv : : SomeType - > a@. -- Requires class name, @SomeType@ name and names of the class functions (@phi@ and @phiInv@). -- data BiClassInfo = BiClassInfo { className :: Name , dataName :: Name , classToFun :: Name , classFromFun :: Name } | Example of @bijective@ class is ' ' . -- Describes conversions into and from 'Node'. That is , this class provides a bridge between Neo4j world and world . -- nodeLikeClass :: BiClassInfo nodeLikeClass = BiClassInfo { className = ''NodeLike , dataName = 'Node , classToFun = 'toNode , classFromFun = 'fromNode } -- | Another example of @bijective@ class is 'URelationLike'. -- Describes conversions into and from 'URelationship'. -- uRelationLikeClass :: BiClassInfo uRelationLikeClass = BiClassInfo { className = ''URelationLike , dataName = 'URelationship , classToFun = 'toURelation , classFromFun = 'fromURelation } | Make an instance of ' ' class . Only data types with one constructor are currently supported . -- Each field is transformed into 'Text' key and its value is transformed into a 'Value'. -- For example, we have a structure and define an instance: -- -- >>> :{ data Foo = Bar -- { baz :: Double , quux : : Text -- , quuz :: Maybe Int -- } deriving (Show) -- makeNodeLike ''Foo -- :} -- -- Then you may create example and convert it to and from Node: -- > > > let foo = Bar 42.0 " ipsum " ( Just 7 ) -- >>> toNode foo Node { nodeIdentity = -1 , labels = [ " " ] , = fromList [ ( " baz",F 42.0),("quux",T " Loren ipsum"),("quuz",I 7 ) ] } > > > fromNode . toNode $ foo : : Bar { baz = 42.0 , quux = " ipsum " , = Just 7 } -- -- 'Maybe' fields are handled correctly: -- -- >>> let bar = Bar 42.0 "Hello world" Nothing -- >>> toNode bar Node { nodeIdentity = -1 , labels = [ " " ] , = fromList [ ( " baz",F 42.0),("quux",T " Hello ( ) ) ] } -- >>> :{ -- let barNode = Node -- { nodeIdentity = -1 -- , labels = ["Foo"] , nodeProps = fromList [ ( " baz " , F 42.0 ) , ( " quux " , T " Hello world " ) ] -- No " quuz " here -- } -- :} -- > > > fromNode barNode : : Bar { baz = 42.0 , quux = " Hello world " , quuz = Nothing } makeNodeLike :: Name -> Q [Dec] makeNodeLike name = makeBiClassInstance nodeLikeClass name id -- | The same as 'makeNodeLike', but applies a function to all field names before storing them in Neo4j , like @aeson@ does . -- This can be used with @fieldLabelModifier@ from ' Data . Aeson . Types . Options ' in @aeson@ : -- > makeNodeLikeWith '' Foo $ fieldLabelModifier $ aesonPrefix camelCase -- makeNodeLikeWith :: Name -> (String -> String) -> Q [Dec] makeNodeLikeWith = makeBiClassInstance nodeLikeClass -- | Make an instance of 'URelationLike' class. Transformations are the same as in ' ' instance declaration with the only one difference : ' URelationship ' holds only one label ( or type ) , but ' ' holds list of labels . -- makeURelationLike :: Name -> Q [Dec] makeURelationLike name = makeBiClassInstance uRelationLikeClass name id -- | As 'makeNodeLikeWith'. makeURelationLikeWith :: Name -> (String -> String) -> Q [Dec] makeURelationLikeWith = makeBiClassInstance uRelationLikeClass | Declare an instance of ` bijective ` class using TemplateHaskell . -- It works as follows: -- Say we have a type with field records, e.g. -- -- > data VariableDomainScoring = VDS { specie :: Text > , : : Double -- > , fr :: Double -- > , sim :: Double -- > , germline :: Text -- > } -- As an example , transformation into Node is described below . -- -- > data Node = Node { nodeIdentity :: Int -- ^Neo4j node identifier -- > , labels :: [Text] -- ^Set of node labels (types) -- > , nodeProps :: Map Text Value -- ^Dict of node properties -- > } -- > deriving (Show, Eq) -- -- @nodeIdentity@ will be set to a dummy value (-1). There is no way of obtaining object ID before uploading it into database. @labels@ will be set to type name , i.e. @VariableDomainScoring@. This is due to our convention : object label into Neo4j is the same as its type name in Haskell . -- @nodeProps@ will be set to a Map: keys are field record names, values are data in the corresponding fields. -- -- Therefore, applying toNode on a @VariableDomainScoring@ will give the following: -- > Node { nodeIdentity = -1 -- > , labels = ["VariableDomainScoring"] > , = fromList [ ( " specie " , T " text value " ) , ( " " , F % float_value ) , ( " fr " , F % float_value ) , ( " sim " , F % float_value ) , ( " germline " , T " text value " ) ] -- > } -- makeBiClassInstance :: BiClassInfo -> Name -> (String -> String) -> Q [Dec] makeBiClassInstance BiClassInfo {..} typeCon fieldLabelModifier = do -- reify function gives Info about Name such as constructor name and its fields. See: -haskell-2.12.0.0/docs/Language-Haskell-TH.html#t:Info TyConI declaration <- reify typeCon -- get type declaration parameters: type name and fields. Supports data and newtype only. These will be used in properties Map formation. let (tyName, constr) = getTypeCons declaration -- nameBase gives object name without package prefix. `label` is the type name here. let label = nameBase tyName -- collects names and types of all fields in the type. let (dataFields, fieldTypes) = unzip $ concatMap (snd . getConsFields) constr -- gets data constructor name let (consName, _) = head $ fmap getConsFields constr -- Just a fresh variable. It will be used in labmda abstractions in makeFromClause function. fresh <- newName "x" constructs ` bijective ` class functions ( phi and phiInv – toClause and fromClause correspondingly here ) . toClause <- makeToClause label dataName consName dataFields fieldLabelModifier fromClause <- makeFromClause label consName fresh dataFields fieldTypes fieldLabelModifier -- function declarations themselves. let bodyDecl = [FunD classToFun [toClause], FunD classFromFun [fromClause]] -- Instance declaration itself. pure [InstanceD Nothing [] (AppT (ConT className) (ConT typeCon)) bodyDecl] -- | Extract information about type: constructor name and field record names with corresponding types. -- getConsFields :: Con -> (Name, [(Name, Type)]) getConsFields (RecC cName decs) = (cName, fmap (\(fname, _, ftype) -> (fname, ftype)) decs) getConsFields (ForallC _ _ cons) = getConsFields cons getConsFields (RecGadtC (cName:_) decs _) = (cName, fmap (\(fname, _, ftype) -> (fname, ftype)) decs) getConsFields (NormalC cName _) = (cName, []) getConsFields _ = error $ $currentLoc ++ "unsupported data declaration." -- | Parse a type declaration and retrieve its name and its constructors. -- getTypeCons :: Dec -> (Name, [Con]) getTypeCons (DataD _ typeName _ _ constructors _) = (typeName, constructors) getTypeCons (NewtypeD _ typeName _ _ constructor _) = (typeName, [constructor]) getTypeCons otherDecl = error $ $currentLoc ++ "unsupported declaration: " ++ show otherDecl ++ "\nShould be either 'data' or 'newtype'." -- | Describes the body of conversion to target type function. -- makeToClause :: String -> Name -> Name -> [Name] -> (String -> String) -> Q Clause makeToClause label dataCons consName dataFields fieldLabelModifier | null dataFields = pure $ Clause [WildP] (NormalB $ result []) [] | otherwise = do fieldVars <- sequenceQ $ newName "_field" <$ dataFields -- var for each field pure $ Clause [recPat fieldVars] (NormalB $ result fieldVars) [] where -- construct record pattern: (Rec {f1 = v1, ... }) recPat :: [Name] -> Pat recPat fieldVars = ParensP $ RecP consName $ zip dataFields $ VarP <$> fieldVars -- List of values which a data holds. The same in terms of : : valuesExp = fmap ( \field - > toValue fieldVar ) valuesExp :: [Name] -> [Exp] valuesExp = fmap (AppE (VarE 'toValue) . VarE) -- Retrieve all field record names from the convertible type. fieldNames :: [String] fieldNames = fmap nameBase dataFields -- List of pairs :: [(key, value)] -- `key` is field record name. -- `value` is the data that corresponding field holds. pairs :: [Name] -> [Exp] pairs = zipWith (\fld val -> tupE' [strToTextE $ fieldLabelModifier fld, val]) fieldNames . valuesExp -- Map representation: -- mapE = fromList pairs in terms of Haskell . mapE :: [Name] -> Exp mapE vars = AppE (VarE 'fromList) (ListE $ pairs vars) -- A bit of crutches. The difference between and is in the number of labels they hold . -- strToTextE returns Text packed in Exp so `id` is applied to it when constructing URelationship. Node takes list of labels so the label must be packed into list using ListE . (: [ ] ) fieldFun :: Exp -> Exp fieldFun | nameBase dataCons == "URelationship" = id | nameBase dataCons == "Node" = ListE . (:[]) | otherwise = error $ $currentLoc ++ "unsupported data type." In terms of : -- dataCons (fromIntegral dummyId) (fieldFun label) mapE Constructs data with three fields . result :: [Name] -> Exp result = AppE (AppE (AppE (ConE dataCons) (LitE . IntegerL . fromIntegral $ dummyId)) (fieldFun $ strToTextE label)) . mapE -- | Describes the body of conversion from target type function. -- makeFromClause :: String -> Name -> Name -> [Name] -> [Type] -> (String -> String) -> Q Clause makeFromClause label conName varName dataFields fieldTypes fieldLabelModifier = do -- Contains 'True' in each position where 'Maybe a' type occured and 'False' everywhere else. let maybeFields = fmap isMaybe fieldTypes -- fieldNames :: [Text] -- field records of the target type. let fieldNames = fmap (pack . fieldLabelModifier . nameBase) dataFields maybeLabels : : [ ( Text , ) ] -- field records of the target type and 'isMaybe' check results. let maybeNames = zip fieldNames maybeFields -- dataLabel :: Text -- Label a.k.a type name let dataLabel = pack label Field record names packed in Exp \x - > [ |x| ] : : a - > Q Exp Therefore , : : [ Exp ] fieldNamesE <- mapM (\x -> [|x|]) fieldNames -- maybeNamesE :: [Exp] Contains Exp representation of ( Text , ) – field name and isMaybe check result on it . let maybeNamesE = zipWith (\n m -> tupE' [n, ConE $ if m then trueName else falseName]) fieldNamesE maybeFields -- varExp :: Q Exp -- Pattern match variable packed in Exp. It will be used in QuasiQuotation below. let varExp = pure (VarE varName) -- Guard checks that all necessary fields are present in the container. guardSuccess <- NormalG <$> [|checkLabels $(varExp) [dataLabel] && checkProps $(varExp) maybeNames|] -- `otherwise` case. guardFail <- NormalG <$> [|otherwise|] Unpack error message . failExp <- [|unpackError $(varExp) (unpack dataLabel)|] Kind of this function realization in terms of : -- fromNode :: Node -> a fromNode varName | checkLabels varName [ dataLabel ] & & checkProps varName fieldNames = ConName ( getProp varName " fieldName1 " ) ( getProp varName " fieldName2 " ) ... | otherwise = unpackError varName ( unpack dataLabel ) let successExp = foldl (\a f -> AppE a $ AppE (AppE (VarE 'getProp) (VarE varName)) f) (ConE conName) maybeNamesE let successCase = (guardSuccess, successExp) let failCase = (guardFail, failExp) pure $ Clause [VarP varName] (GuardedB [successCase, failCase]) [] -- | Check whether given type is 'Maybe _' -- It pattern matches type T applied to any argument and checks if T is ''Maybe isMaybe :: Type -> Bool isMaybe (AppT (ConT t) _) = t == ''Maybe isMaybe _ = False strToTextE :: String -> Exp strToTextE str = AppE (VarE 'pack) (LitE . StringL $ str) checkProps :: Properties t => t -> [(Text, Bool)] -> Bool checkProps container = all (\(fieldName, fieldMaybe) -> fieldMaybe || fieldName `member` getProps container) checkLabels :: Labels t => t -> [Text] -> Bool checkLabels container = all (`elem` getLabels container) getProp :: (Properties t, RecordValue a) => t -> (Text, Bool) -> a getProp container (fieldName, fieldMaybe) | fieldMaybe && fieldName `notMember` getProps container = exactE $ N () | otherwise = exactE (getProps container ! fieldName) where exactE v = case exactEither v of Right res -> res Left err -> error $ show err unpackError :: Show c => c -> String -> a unpackError container label = error $ $currentLoc ++ " could not unpack " ++ label ++ " from " ++ show container {- $setup >>> :set -XTemplateHaskell >>> :set -XOverloadedStrings >>> import Data.Text (Text) -}
null
https://raw.githubusercontent.com/biocad/hasbolt-extras/961726eb1cecfd252952b761317e477ad6bcbc28/src/Database/Bolt/Extras/Template/Internal/Converters.hs
haskell
# LANGUAGE CPP # Requires class name, @SomeType@ name and names of the class functions (@phi@ and @phiInv@). Describes conversions into and from 'Node'. | Another example of @bijective@ class is 'URelationLike'. Describes conversions into and from 'URelationship'. Each field is transformed into 'Text' key and its value is transformed into a 'Value'. For example, we have a structure and define an instance: >>> :{ { baz :: Double , quuz :: Maybe Int } deriving (Show) makeNodeLike ''Foo :} Then you may create example and convert it to and from Node: >>> toNode foo 'Maybe' fields are handled correctly: >>> let bar = Bar 42.0 "Hello world" Nothing >>> toNode bar >>> :{ let barNode = Node { nodeIdentity = -1 , labels = ["Foo"] No " quuz " here } :} | The same as 'makeNodeLike', but applies a function to all field names before storing them | Make an instance of 'URelationLike' class. | As 'makeNodeLikeWith'. It works as follows: Say we have a type with field records, e.g. > data VariableDomainScoring = VDS { specie :: Text > , fr :: Double > , sim :: Double > , germline :: Text > } > data Node = Node { nodeIdentity :: Int -- ^Neo4j node identifier > , labels :: [Text] -- ^Set of node labels (types) > , nodeProps :: Map Text Value -- ^Dict of node properties > } > deriving (Show, Eq) @nodeIdentity@ will be set to a dummy value (-1). There is no way of obtaining object ID before uploading it into database. @nodeProps@ will be set to a Map: keys are field record names, values are data in the corresponding fields. Therefore, applying toNode on a @VariableDomainScoring@ will give the following: > Node { nodeIdentity = -1 > , labels = ["VariableDomainScoring"] > } reify function gives Info about Name such as constructor name and its fields. See: -haskell-2.12.0.0/docs/Language-Haskell-TH.html#t:Info get type declaration parameters: type name and fields. Supports data and newtype only. These will be used in properties Map formation. nameBase gives object name without package prefix. `label` is the type name here. collects names and types of all fields in the type. gets data constructor name Just a fresh variable. It will be used in labmda abstractions in makeFromClause function. function declarations themselves. Instance declaration itself. | Extract information about type: constructor name and field record names with corresponding types. | Parse a type declaration and retrieve its name and its constructors. | Describes the body of conversion to target type function. var for each field construct record pattern: (Rec {f1 = v1, ... }) List of values which a data holds. Retrieve all field record names from the convertible type. List of pairs :: [(key, value)] `key` is field record name. `value` is the data that corresponding field holds. Map representation: mapE = fromList pairs A bit of crutches. strToTextE returns Text packed in Exp so `id` is applied to it when constructing URelationship. dataCons (fromIntegral dummyId) (fieldFun label) mapE | Describes the body of conversion from target type function. Contains 'True' in each position where 'Maybe a' type occured and 'False' everywhere else. fieldNames :: [Text] field records of the target type. field records of the target type and 'isMaybe' check results. dataLabel :: Text Label a.k.a type name maybeNamesE :: [Exp] varExp :: Q Exp Pattern match variable packed in Exp. It will be used in QuasiQuotation below. Guard checks that all necessary fields are present in the container. `otherwise` case. fromNode :: Node -> a | Check whether given type is 'Maybe _' It pattern matches type T applied to any argument and checks if T is ''Maybe $setup >>> :set -XTemplateHaskell >>> :set -XOverloadedStrings >>> import Data.Text (Text)
# LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # module Database.Bolt.Extras.Template.Internal.Converters ( makeNodeLike , makeNodeLikeWith , makeURelationLike , makeURelationLikeWith ) where import Data.Map.Strict (fromList, member, notMember, (!)) import Data.Text (Text, pack, unpack) import Database.Bolt (Node (..), URelationship (..), Value (..), IsValue(..), RecordValue(..)) import Database.Bolt.Extras (Labels (..), NodeLike (..), Properties (..), URelationLike (..)) import Database.Bolt.Extras.Utils (currentLoc, dummyId) import Instances.TH.Lift () import Language.Haskell.TH import Language.Haskell.TH.Syntax Starting with template - haskell-2.16.0.0 , ' TupE ' constructor accepts @Maybe , to support TupleSections . We use this alias for compatibility with both old and new versions . tupE' :: [Exp] -> Exp #if MIN_VERSION_template_haskell(2, 16, 0) tupE' = TupE . map Just #else tupE' = TupE #endif | Describes a @bijective@ class , i.e. class that has two functions : @phi : : a - > SomeType@ and @phiInv : : SomeType - > a@. data BiClassInfo = BiClassInfo { className :: Name , dataName :: Name , classToFun :: Name , classFromFun :: Name } | Example of @bijective@ class is ' ' . That is , this class provides a bridge between Neo4j world and world . nodeLikeClass :: BiClassInfo nodeLikeClass = BiClassInfo { className = ''NodeLike , dataName = 'Node , classToFun = 'toNode , classFromFun = 'fromNode } uRelationLikeClass :: BiClassInfo uRelationLikeClass = BiClassInfo { className = ''URelationLike , dataName = 'URelationship , classToFun = 'toURelation , classFromFun = 'fromURelation } | Make an instance of ' ' class . Only data types with one constructor are currently supported . data Foo = Bar , quux : : Text > > > let foo = Bar 42.0 " ipsum " ( Just 7 ) Node { nodeIdentity = -1 , labels = [ " " ] , = fromList [ ( " baz",F 42.0),("quux",T " Loren ipsum"),("quuz",I 7 ) ] } > > > fromNode . toNode $ foo : : Bar { baz = 42.0 , quux = " ipsum " , = Just 7 } Node { nodeIdentity = -1 , labels = [ " " ] , = fromList [ ( " baz",F 42.0),("quux",T " Hello ( ) ) ] } > > > fromNode barNode : : Bar { baz = 42.0 , quux = " Hello world " , quuz = Nothing } makeNodeLike :: Name -> Q [Dec] makeNodeLike name = makeBiClassInstance nodeLikeClass name id in Neo4j , like @aeson@ does . This can be used with @fieldLabelModifier@ from ' Data . Aeson . Types . Options ' in @aeson@ : > makeNodeLikeWith '' Foo $ fieldLabelModifier $ aesonPrefix camelCase makeNodeLikeWith :: Name -> (String -> String) -> Q [Dec] makeNodeLikeWith = makeBiClassInstance nodeLikeClass Transformations are the same as in ' ' instance declaration with the only one difference : ' URelationship ' holds only one label ( or type ) , but ' ' holds list of labels . makeURelationLike :: Name -> Q [Dec] makeURelationLike name = makeBiClassInstance uRelationLikeClass name id makeURelationLikeWith :: Name -> (String -> String) -> Q [Dec] makeURelationLikeWith = makeBiClassInstance uRelationLikeClass | Declare an instance of ` bijective ` class using TemplateHaskell . > , : : Double As an example , transformation into Node is described below . @labels@ will be set to type name , i.e. @VariableDomainScoring@. This is due to our convention : object label into Neo4j is the same as its type name in Haskell . > , = fromList [ ( " specie " , T " text value " ) , ( " " , F % float_value ) , ( " fr " , F % float_value ) , ( " sim " , F % float_value ) , ( " germline " , T " text value " ) ] makeBiClassInstance :: BiClassInfo -> Name -> (String -> String) -> Q [Dec] makeBiClassInstance BiClassInfo {..} typeCon fieldLabelModifier = do TyConI declaration <- reify typeCon let (tyName, constr) = getTypeCons declaration let label = nameBase tyName let (dataFields, fieldTypes) = unzip $ concatMap (snd . getConsFields) constr let (consName, _) = head $ fmap getConsFields constr fresh <- newName "x" constructs ` bijective ` class functions ( phi and phiInv – toClause and fromClause correspondingly here ) . toClause <- makeToClause label dataName consName dataFields fieldLabelModifier fromClause <- makeFromClause label consName fresh dataFields fieldTypes fieldLabelModifier let bodyDecl = [FunD classToFun [toClause], FunD classFromFun [fromClause]] pure [InstanceD Nothing [] (AppT (ConT className) (ConT typeCon)) bodyDecl] getConsFields :: Con -> (Name, [(Name, Type)]) getConsFields (RecC cName decs) = (cName, fmap (\(fname, _, ftype) -> (fname, ftype)) decs) getConsFields (ForallC _ _ cons) = getConsFields cons getConsFields (RecGadtC (cName:_) decs _) = (cName, fmap (\(fname, _, ftype) -> (fname, ftype)) decs) getConsFields (NormalC cName _) = (cName, []) getConsFields _ = error $ $currentLoc ++ "unsupported data declaration." getTypeCons :: Dec -> (Name, [Con]) getTypeCons (DataD _ typeName _ _ constructors _) = (typeName, constructors) getTypeCons (NewtypeD _ typeName _ _ constructor _) = (typeName, [constructor]) getTypeCons otherDecl = error $ $currentLoc ++ "unsupported declaration: " ++ show otherDecl ++ "\nShould be either 'data' or 'newtype'." makeToClause :: String -> Name -> Name -> [Name] -> (String -> String) -> Q Clause makeToClause label dataCons consName dataFields fieldLabelModifier | null dataFields = pure $ Clause [WildP] (NormalB $ result []) [] | otherwise = do pure $ Clause [recPat fieldVars] (NormalB $ result fieldVars) [] where recPat :: [Name] -> Pat recPat fieldVars = ParensP $ RecP consName $ zip dataFields $ VarP <$> fieldVars The same in terms of : : valuesExp = fmap ( \field - > toValue fieldVar ) valuesExp :: [Name] -> [Exp] valuesExp = fmap (AppE (VarE 'toValue) . VarE) fieldNames :: [String] fieldNames = fmap nameBase dataFields pairs :: [Name] -> [Exp] pairs = zipWith (\fld val -> tupE' [strToTextE $ fieldLabelModifier fld, val]) fieldNames . valuesExp in terms of Haskell . mapE :: [Name] -> Exp mapE vars = AppE (VarE 'fromList) (ListE $ pairs vars) The difference between and is in the number of labels they hold . Node takes list of labels so the label must be packed into list using ListE . (: [ ] ) fieldFun :: Exp -> Exp fieldFun | nameBase dataCons == "URelationship" = id | nameBase dataCons == "Node" = ListE . (:[]) | otherwise = error $ $currentLoc ++ "unsupported data type." In terms of : Constructs data with three fields . result :: [Name] -> Exp result = AppE (AppE (AppE (ConE dataCons) (LitE . IntegerL . fromIntegral $ dummyId)) (fieldFun $ strToTextE label)) . mapE makeFromClause :: String -> Name -> Name -> [Name] -> [Type] -> (String -> String) -> Q Clause makeFromClause label conName varName dataFields fieldTypes fieldLabelModifier = do let maybeFields = fmap isMaybe fieldTypes let fieldNames = fmap (pack . fieldLabelModifier . nameBase) dataFields maybeLabels : : [ ( Text , ) ] let maybeNames = zip fieldNames maybeFields let dataLabel = pack label Field record names packed in Exp \x - > [ |x| ] : : a - > Q Exp Therefore , : : [ Exp ] fieldNamesE <- mapM (\x -> [|x|]) fieldNames Contains Exp representation of ( Text , ) – field name and isMaybe check result on it . let maybeNamesE = zipWith (\n m -> tupE' [n, ConE $ if m then trueName else falseName]) fieldNamesE maybeFields let varExp = pure (VarE varName) guardSuccess <- NormalG <$> [|checkLabels $(varExp) [dataLabel] && checkProps $(varExp) maybeNames|] guardFail <- NormalG <$> [|otherwise|] Unpack error message . failExp <- [|unpackError $(varExp) (unpack dataLabel)|] Kind of this function realization in terms of : fromNode varName | checkLabels varName [ dataLabel ] & & checkProps varName fieldNames = ConName ( getProp varName " fieldName1 " ) ( getProp varName " fieldName2 " ) ... | otherwise = unpackError varName ( unpack dataLabel ) let successExp = foldl (\a f -> AppE a $ AppE (AppE (VarE 'getProp) (VarE varName)) f) (ConE conName) maybeNamesE let successCase = (guardSuccess, successExp) let failCase = (guardFail, failExp) pure $ Clause [VarP varName] (GuardedB [successCase, failCase]) [] isMaybe :: Type -> Bool isMaybe (AppT (ConT t) _) = t == ''Maybe isMaybe _ = False strToTextE :: String -> Exp strToTextE str = AppE (VarE 'pack) (LitE . StringL $ str) checkProps :: Properties t => t -> [(Text, Bool)] -> Bool checkProps container = all (\(fieldName, fieldMaybe) -> fieldMaybe || fieldName `member` getProps container) checkLabels :: Labels t => t -> [Text] -> Bool checkLabels container = all (`elem` getLabels container) getProp :: (Properties t, RecordValue a) => t -> (Text, Bool) -> a getProp container (fieldName, fieldMaybe) | fieldMaybe && fieldName `notMember` getProps container = exactE $ N () | otherwise = exactE (getProps container ! fieldName) where exactE v = case exactEither v of Right res -> res Left err -> error $ show err unpackError :: Show c => c -> String -> a unpackError container label = error $ $currentLoc ++ " could not unpack " ++ label ++ " from " ++ show container